util.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. /*
  2. * EliasDB
  3. *
  4. * Copyright 2016 Matthias Ladkau. All rights reserved.
  5. *
  6. * This Source Code Form is subject to the terms of the Mozilla Public
  7. * License, v. 2.0. If a copy of the MPL was not distributed with this
  8. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  9. */
  10. package data
  11. import (
  12. "sort"
  13. "devt.de/krotik/common/datautil"
  14. )
  15. /*
  16. NodeCompare compares node attributes.
  17. */
  18. func NodeCompare(node1 Node, node2 Node, attrs []string) bool {
  19. if attrs == nil {
  20. if len(node1.Data()) != len(node2.Data()) {
  21. return false
  22. }
  23. attrs = make([]string, 0, len(node1.Data()))
  24. for attr := range node1.Data() {
  25. attrs = append(attrs, attr)
  26. }
  27. }
  28. for _, attr := range attrs {
  29. if node1.Attr(attr) != node2.Attr(attr) {
  30. return false
  31. }
  32. }
  33. return true
  34. }
  35. /*
  36. NodeClone clones a node.
  37. */
  38. func NodeClone(node Node) Node {
  39. var data map[string]interface{}
  40. datautil.CopyObject(node.Data(), &data)
  41. return &graphNode{data}
  42. }
  43. /*
  44. NodeMerge merges two nodes together in a third node. The node values are copied
  45. by reference.
  46. */
  47. func NodeMerge(node1 Node, node2 Node) Node {
  48. data := make(map[string]interface{})
  49. for k, v := range node1.Data() {
  50. data[k] = v
  51. }
  52. for k, v := range node2.Data() {
  53. data[k] = v
  54. }
  55. return &graphNode{data}
  56. }
  57. /*
  58. NodeSort sorts a list of nodes.
  59. */
  60. func NodeSort(list []Node) {
  61. sort.Sort(NodeSlice(list))
  62. }
  63. /*
  64. NodeSlice attaches the methods of sort.Interface to []Node, sorting in
  65. increasing order by key and kind.
  66. */
  67. type NodeSlice []Node
  68. /*
  69. Len belongs to the sort.Interface.
  70. */
  71. func (p NodeSlice) Len() int { return len(p) }
  72. /*
  73. Less belongs to the sort.Interface.
  74. */
  75. func (p NodeSlice) Less(i, j int) bool {
  76. in := p[i]
  77. jn := p[j]
  78. if in.Kind() != jn.Kind() {
  79. return in.Kind() < jn.Kind()
  80. }
  81. return in.Key() < jn.Key()
  82. }
  83. /*
  84. Swap belongs to the sort.Interface.
  85. */
  86. func (p NodeSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }