relations.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. //Copyright 2013 GoGraphviz Authors
  2. //
  3. //Licensed under the Apache License, Version 2.0 (the "License");
  4. //you may not use this file except in compliance with the License.
  5. //You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. //Unless required by applicable law or agreed to in writing, software
  10. //distributed under the License is distributed on an "AS IS" BASIS,
  11. //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. //See the License for the specific language governing permissions and
  13. //limitations under the License.
  14. package gographviz
  15. import (
  16. "sort"
  17. )
  18. // Relations represents the relations between graphs and nodes.
  19. // Each node belongs the main graph or a subgraph.
  20. type Relations struct {
  21. ParentToChildren map[string]map[string]bool
  22. ChildToParents map[string]map[string]bool
  23. }
  24. // NewRelations creates an empty set of relations.
  25. func NewRelations() *Relations {
  26. return &Relations{make(map[string]map[string]bool), make(map[string]map[string]bool)}
  27. }
  28. // Add adds a node to a parent graph.
  29. func (relations *Relations) Add(parent string, child string) {
  30. if _, ok := relations.ParentToChildren[parent]; !ok {
  31. relations.ParentToChildren[parent] = make(map[string]bool)
  32. }
  33. relations.ParentToChildren[parent][child] = true
  34. if _, ok := relations.ChildToParents[child]; !ok {
  35. relations.ChildToParents[child] = make(map[string]bool)
  36. }
  37. relations.ChildToParents[child][parent] = true
  38. }
  39. // Remove removes relation
  40. func (relations *Relations) Remove(parent string, child string) {
  41. if _, ok := relations.ParentToChildren[parent]; ok {
  42. delete(relations.ParentToChildren[parent], child)
  43. }
  44. if _, ok := relations.ChildToParents[child]; ok {
  45. delete(relations.ChildToParents[child], parent)
  46. }
  47. }
  48. // SortedChildren returns a list of sorted children of the given parent graph.
  49. func (relations *Relations) SortedChildren(parent string) []string {
  50. keys := make([]string, 0)
  51. for key := range relations.ParentToChildren[parent] {
  52. keys = append(keys, key)
  53. }
  54. sort.Strings(keys)
  55. return keys
  56. }