Group.swift 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. // Group.swift
  2. // This file is part of KeePass.swift
  3. //
  4. // Copyright © 2021 Maxime Epain. All rights reserved.
  5. //
  6. // KeePass.swift is free software: you can redistribute it and/or modify
  7. // it under the terms of the GNU General Public License as published by
  8. // the Free Software Foundation, either version 3 of the License, or
  9. // (at your option) any later version.
  10. //
  11. // KeePass.swift is distributed in the hope that it will be useful,
  12. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. // GNU General Public License for more details.
  15. //
  16. // You should have received a copy of the GNU General Public License
  17. // along with KeePass.swift. If not, see <https://www.gnu.org/licenses/>.
  18. import Binary
  19. import Foundation
  20. public final class Group: Row, Streamable {
  21. public enum Column: UInt16, Streamable, Endable {
  22. case reserved = 0x0000
  23. case groupID = 0x0001
  24. case name = 0x0002
  25. case creationTime = 0x0003
  26. case lastModifiedTime = 0x0004
  27. case lastAccessTime = 0x0005
  28. case expirationTime = 0x0006
  29. case iconID = 0x0007
  30. case groupLevel = 0x0008
  31. case groupFlags = 0x0009
  32. case end = 0xFFFF
  33. public static var endValue: Self { .end }
  34. }
  35. public internal(set) weak var parent: Group?
  36. public internal(set) var childs: [Group]
  37. public internal(set) var entries: [Entry]
  38. public var properties: [TLV<Column, UInt32>]
  39. public init() {
  40. properties = []
  41. childs = []
  42. entries = []
  43. }
  44. public init(from input: Input) throws {
  45. properties = try input.read()
  46. childs = []
  47. entries = []
  48. }
  49. }
  50. extension Group {
  51. public func removeFromParent() {
  52. parent?.childs.removeAll(where: { $0 == self })
  53. parent = nil
  54. }
  55. public func add(_ entry: Entry) {
  56. entry.removeFromParent()
  57. entries.append(entry)
  58. entry[.groupID] = self[.groupID]
  59. entry.parent = self
  60. }
  61. public func add(_ group: Group) {
  62. group.removeFromParent()
  63. childs.append(group)
  64. group[.groupLevel] = self[.groupLevel] ?? 0 + 1
  65. group.parent = self
  66. }
  67. }
  68. extension Group: Hashable {
  69. public static func == (lhs: Group, rhs: Group) -> Bool {
  70. lhs[.groupID] == rhs[.groupID] &&
  71. lhs[.groupLevel] == rhs[.groupLevel]
  72. }
  73. public func hash(into hasher: inout Hasher) {
  74. hasher.combine(self[.groupID])
  75. hasher.combine(self[.name])
  76. hasher.combine(self[.groupLevel])
  77. }
  78. }