diff --git a/merkledag/utils/diffenum.go b/merkledag/utils/diffenum.go index 7e3a763566d..c2904cbc05e 100644 --- a/merkledag/utils/diffenum.go +++ b/merkledag/utils/diffenum.go @@ -65,27 +65,35 @@ type diffpair struct { // getLinkDiff returns a changeset between nodes 'a' and 'b'. Currently does // not log deletions as our usecase doesnt call for this. func getLinkDiff(a, b node.Node) []diffpair { - have := make(map[string]*node.Link) - names := make(map[string]*node.Link) + ina := make(map[string]*node.Link) + inb := make(map[string]*node.Link) + var aonly []*cid.Cid + for _, l := range b.Links() { + inb[l.Cid.KeyString()] = l + } for _, l := range a.Links() { - have[l.Cid.KeyString()] = l - names[l.Name] = l + var key = l.Cid.KeyString() + ina[key] = l + if inb[key] == nil { + aonly = append(aonly, l.Cid) + } } var out []diffpair + var aindex int for _, l := range b.Links() { - if have[l.Cid.KeyString()] != nil { + if ina[l.Cid.KeyString()] != nil { continue } - match, ok := names[l.Name] - if !ok { + if aindex < len(aonly) { + out = append(out, diffpair{bef: aonly[aindex], aft: l.Cid}) + aindex++ + } else { out = append(out, diffpair{aft: l.Cid}) continue } - - out = append(out, diffpair{bef: match.Cid, aft: l.Cid}) } return out } diff --git a/merkledag/utils/diffenum_test.go b/merkledag/utils/diffenum_test.go index ed5e0db36ef..bf7d38d425d 100644 --- a/merkledag/utils/diffenum_test.go +++ b/merkledag/utils/diffenum_test.go @@ -84,6 +84,49 @@ var tg3 = map[string]ndesc{ "d": ndesc{}, } +var tg4 = map[string]ndesc{ + "a1": ndesc{ + "key1": "b", + "key2": "c", + }, + "a2": ndesc{ + "key1": "b", + "key2": "d", + }, +} + +var tg5 = map[string]ndesc{ + "a1": ndesc{ + "key1": "a", + "key2": "b", + }, + "a2": ndesc{ + "key1": "c", + "key2": "d", + }, +} + +func TestNameMatching(t *testing.T) { + nds := mkGraph(tg4) + + diff := getLinkDiff(nds["a1"], nds["a2"]) + if len(diff) != 1 { + t.Fatal(fmt.Errorf("node diff didn't match by name")) + } +} + +func TestNameMatching2(t *testing.T) { + nds := mkGraph(tg5) + + diff := getLinkDiff(nds["a1"], nds["a2"]) + if len(diff) != 2 { + t.Fatal(fmt.Errorf("incorrect number of link diff elements")) + } + if !(diff[0].bef.Equals(nds["a1"].Links()[0].Cid) && diff[0].aft.Equals(nds["a2"].Links()[0].Cid)) { + t.Fatal(fmt.Errorf("node diff didn't match by name")) + } +} + func TestDiffEnumBasic(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel()