@cryptotaxi247 / kubo / commits / cd65ec614

merkledag: keep links sorted by name

May not be necessary to sort when adding each link-- doing so would be unnecessarily expensive O(n^2) when constructing nodes -- though n wont be big.

Juan Batiz-Benet committed Jan 6, 2015 at 13:07 UTC cd65ec614b5506013c86e02236ce6267d22fc77e
2 files changed +11
merkledag/coding.go
+5
@@ -2,6 +2,7 @@ package merkledag
2
3 import (
4 "fmt"
5 + "sort"
6
7 mh "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-multihash"
8
@@ -30,6 +31,7 @@ func (n *Node) Unmarshal(encoded []byte) error {
31 }
32 n.Links[i].Hash = h
33 }
34 + sort.Stable(LinkSlice(n.Links)) // keep links sorted
35
36 n.Data = pbn.GetData()
37 return nil
@@ -59,6 +61,8 @@ func (n *Node) Marshal() ([]byte, error) {
61 func (n *Node) getPBNode() *pb.PBNode {
62 pbn := &pb.PBNode{}
63 pbn.Links = make([]*pb.PBLink, len(n.Links))
64 +
65 + sort.Stable(LinkSlice(n.Links)) // keep links sorted
66 for i, l := range n.Links {
67 pbn.Links[i] = &pb.PBLink{}
68 pbn.Links[i].Name = &l.Name
@@ -73,6 +77,7 @@ func (n *Node) getPBNode() *pb.PBNode {
77 // Encoded returns the encoded raw data version of a Node instance.
78 // It may use a cached encoded version, unless the force flag is given.
79 func (n *Node) Encoded(force bool) ([]byte, error) {
80 + sort.Stable(LinkSlice(n.Links)) // keep links sorted
81 if n.encoded == nil || force {
82 var err error
83 n.encoded, err = n.Marshal()
merkledag/merkledag.go
+6
@@ -66,6 +66,12 @@ type Link struct {
66 Node *Node
67 }
68
69 +type LinkSlice []*Link
70 +
71 +func (ls LinkSlice) Len() int { return len(ls) }
72 +func (ls LinkSlice) Swap(a, b int) { ls[a], ls[b] = ls[b], ls[a] }
73 +func (ls LinkSlice) Less(a, b int) bool { return ls[a].Name < ls[b].Name }
74 +
75 // MakeLink creates a link to the given node
76 func MakeLink(n *Node) (*Link, error) {
77 s, err := n.Size()