attrs.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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. // Attrs represents attributes for an Edge, Node or Graph.
  19. type Attrs map[Attr]string
  20. // NewAttrs creates an empty Attributes type.
  21. func NewAttrs(m map[string]string) (Attrs, error) {
  22. as := make(Attrs)
  23. for k, v := range m {
  24. if err := as.Add(k, v); err != nil {
  25. return nil, err
  26. }
  27. }
  28. return as, nil
  29. }
  30. // Add adds an attribute name and value.
  31. func (attrs Attrs) Add(field string, value string) error {
  32. a, err := NewAttr(field)
  33. if err != nil {
  34. return err
  35. }
  36. attrs.add(a, value)
  37. return nil
  38. }
  39. func (attrs Attrs) add(field Attr, value string) {
  40. attrs[field] = value
  41. }
  42. // Extend adds the attributes into attrs Attrs type overwriting duplicates.
  43. func (attrs Attrs) Extend(more Attrs) {
  44. for key, value := range more {
  45. attrs.add(key, value)
  46. }
  47. }
  48. // Ammend only adds the missing attributes to attrs Attrs type.
  49. func (attrs Attrs) Ammend(more Attrs) {
  50. for key, value := range more {
  51. if _, ok := attrs[key]; !ok {
  52. attrs.add(key, value)
  53. }
  54. }
  55. }
  56. func (attrs Attrs) toMap() map[string]string {
  57. m := make(map[string]string)
  58. for k, v := range attrs {
  59. m[string(k)] = v
  60. }
  61. return m
  62. }
  63. type attrList []Attr
  64. func (attrs attrList) Len() int { return len(attrs) }
  65. func (attrs attrList) Less(i, j int) bool {
  66. return attrs[i] < attrs[j]
  67. }
  68. func (attrs attrList) Swap(i, j int) {
  69. attrs[i], attrs[j] = attrs[j], attrs[i]
  70. }
  71. func (attrs Attrs) sortedNames() []Attr {
  72. keys := make(attrList, 0)
  73. for key := range attrs {
  74. keys = append(keys, key)
  75. }
  76. sort.Sort(keys)
  77. return []Attr(keys)
  78. }
  79. // Copy returns a copy of the attributes map
  80. func (attrs Attrs) Copy() Attrs {
  81. mm := make(Attrs)
  82. for k, v := range attrs {
  83. mm[k] = v
  84. }
  85. return mm
  86. }