Skip to content

Commit

Permalink
common: handle unordered relationships correctly
Browse files Browse the repository at this point in the history
Continued part of unidoc#198 after @JasonFromSpace pointed out
an error with the original fix.
  • Loading branch information
tbaliance committed Sep 17, 2018
1 parent 0b5e389 commit 70dbd44
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 3 deletions.
12 changes: 9 additions & 3 deletions common/relationships.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,10 +67,16 @@ func (r Relationships) AddRelationship(target, ctype string) Relationship {
}
rel := relationships.NewRelationship()
nextID := len(r.x.Relationship) + 1
used := map[string]struct{}{}

// identify IDs in use
for _, exRel := range r.x.Relationship {
if exRel.IdAttr == fmt.Sprintf("rId%d", nextID) {
nextID++
}
used[exRel.IdAttr] = struct{}{}
}
// find the next ID that is unused
for _, ok := used[fmt.Sprintf("rId%d", nextID)]; ok; _, ok = used[fmt.Sprintf("rId%d", nextID)] {
nextID++

}
rel.IdAttr = fmt.Sprintf("rId%d", nextID)
rel.TargetAttr = target
Expand Down
24 changes: 24 additions & 0 deletions common/relationships_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,3 +65,27 @@ func TestRelationshipsCreation(t *testing.T) {
t.Errorf("expected %s, got %s", exp, rel.ID())
}
}

func TestRelationshipsCreationUnordered(t *testing.T) {
r := common.NewRelationships()
r.AddRelationship("foo", "http://bar").X().IdAttr = "rId1"
r.AddRelationship("foo", "http://bar").X().IdAttr = "rId3"
r.AddRelationship("foo", "http://bar").X().IdAttr = "rId5"
r.AddRelationship("foo", "http://bar").X().IdAttr = "rId7"

// len is 4, but id 5 is used, so we should get 6 next
rel := r.AddRelationship("foo", "http://bar")

exp := "rId6"
if rel.ID() != exp {
t.Errorf("expected %s, got %s", exp, rel.ID())
}

// would get 7, but it's in use so we get 8 now
rel = r.AddRelationship("foo", "http://bar")
exp = "rId8"
if rel.ID() != exp {
t.Errorf("expected %s, got %s", exp, rel.ID())
}

}

0 comments on commit 70dbd44

Please sign in to comment.