github.com/dahs81/otto@v0.2.1-0.20160126165905-6400716cf085/appfile/compile_json.go (about)

     1  package appfile
     2  
     3  import (
     4  	"encoding/json"
     5  	"strconv"
     6  
     7  	"github.com/hashicorp/terraform/dag"
     8  )
     9  
    10  // This file contains the MarshalJSON and UnmarshalJSON functions so that
    11  // the Compiled struct can be safely encoded/decoded on disk. We put this
    12  // in a separate file since it requires a bunch of auxilliary structs that
    13  // we didn't want to confuse compile.go with.
    14  
    15  func (c *Compiled) MarshalJSON() ([]byte, error) {
    16  	raw := &compiledJSON{
    17  		File:  c.File,
    18  		Edges: make([]map[string]string, 0, len(c.Graph.Edges())),
    19  	}
    20  
    21  	// Compile the list of vertices, keeping track of their position
    22  	set := make(map[dag.Vertex]string)
    23  	for i, rawV := range c.Graph.Vertices() {
    24  		v := rawV.(*CompiledGraphVertex)
    25  		raw.Vertices = append(raw.Vertices, v)
    26  		set[v] = strconv.FormatInt(int64(i), 10)
    27  	}
    28  
    29  	// Map the edges by position
    30  	for _, e := range c.Graph.Edges() {
    31  		raw.Edges = append(raw.Edges,
    32  			map[string]string{
    33  				set[e.Source()]: set[e.Target()],
    34  			})
    35  	}
    36  
    37  	return json.Marshal(raw)
    38  }
    39  
    40  func (c *Compiled) UnmarshalJSON(data []byte) error {
    41  	var raw compiledJSON
    42  	if err := json.Unmarshal(data, &raw); err != nil {
    43  		return err
    44  	}
    45  
    46  	c.File = raw.File
    47  	c.Graph = new(dag.AcyclicGraph)
    48  	for _, v := range raw.Vertices {
    49  		c.Graph.Add(v)
    50  	}
    51  	for _, e := range raw.Edges {
    52  		for a, b := range e {
    53  			ai, err := strconv.ParseInt(a, 0, 0)
    54  			if err != nil {
    55  				return err
    56  			}
    57  
    58  			bi, err := strconv.ParseInt(b, 0, 0)
    59  			if err != nil {
    60  				return err
    61  			}
    62  
    63  			c.Graph.Connect(dag.BasicEdge(raw.Vertices[ai], raw.Vertices[bi]))
    64  		}
    65  	}
    66  
    67  	return nil
    68  }
    69  
    70  type compiledJSON struct {
    71  	File     *File
    72  	Vertices []*CompiledGraphVertex
    73  	Edges    []map[string]string
    74  }