coding.go 1.35 KB
Newer Older
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1 2 3 4 5 6 7 8 9 10 11 12
package merkledag

import (
  "fmt"
  mh "github.com/jbenet/go-multihash"
)

// for now, we use a PBNode intermediate thing.
// because native go objects are nice.

func (n *Node) Unmarshal(encoded []byte) error {
  var pbn PBNode
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
13
  if err := pbn.Unmarshal(encoded); err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
14 15 16
    return fmt.Errorf("Unmarshal failed. %v", err)
  }

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
17
  pbnl := pbn.GetLinks()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
18 19
  n.Links = make([]*Link, len(pbnl))
  for i, l := range(pbnl) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
20 21
    n.Links[i] = &Link{Name: l.GetName(), Size: l.GetTsize()}
    h, err := mh.Cast(l.GetHash())
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
22 23 24
    if err != nil {
      return fmt.Errorf("Link hash is not valid multihash. %v", err)
    }
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
25
    n.Links[i].Hash = h
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
26 27 28 29 30 31 32 33
  }

  n.Data = pbn.GetData()
  return nil
}

func (n *Node) MarshalTo(encoded []byte) error {
  pbn := n.getPBNode()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
34
  if _, err := pbn.MarshalTo(encoded); err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
    return fmt.Errorf("Marshal failed. %v", err)
  }
  return nil
}

func (n *Node) Marshal() ([]byte, error) {
  pbn := n.getPBNode()
  data, err := pbn.Marshal()
  if err != nil {
    return data, fmt.Errorf("Marshal failed. %v", err)
  }
  return data, nil
}

func (n *Node) getPBNode() *PBNode {
  pbn := &PBNode{}
  pbn.Links = make([]*PBLink, len(n.Links))
  for i, l := range(n.Links) {
    pbn.Links[i] = &PBLink{}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
54 55 56
    pbn.Links[i].Name = &l.Name
    pbn.Links[i].Tsize = &l.Size
    pbn.Links[i].Hash = []byte(l.Hash)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
57 58
  }

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
59 60
  pbn.Data = n.Data
  return pbn
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
61 62
}