Group.swift 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. // Group.swift
  2. // This file is part of KeePassKit.
  3. //
  4. // Copyright © 2019 Maxime Epain. All rights reserved.
  5. //
  6. // KeePassKit 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. // KeePassKit 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 KeePassKit. If not, see <https://www.gnu.org/licenses/>.
  18. import Foundation
  19. import Binary
  20. public final class Group: Row, Streamable {
  21. public static let End = Type.end
  22. public enum `Type`: UInt16, Streamable {
  23. case reserved = 0x0000
  24. case groupID = 0x0001
  25. case name = 0x0002
  26. case creationTime = 0x0003
  27. case lastModifiedTime = 0x0004
  28. case lastAccessTime = 0x0005
  29. case expirationTime = 0x0006
  30. case iconID = 0x0007
  31. case groupLevel = 0x0008
  32. case groupFlags = 0x0009
  33. case end = 0xFFFF
  34. }
  35. var parent: Group?
  36. public var fields: [Field<Type>]
  37. public var childs: [Group]
  38. public var entries: [Entry]
  39. public required init() {
  40. fields = []
  41. childs = []
  42. entries = []
  43. }
  44. }
  45. extension Group {
  46. public func removeFromParent() {
  47. parent?.childs.removeAll(where: { $0 == self })
  48. }
  49. public func add(_ entry: Entry) {
  50. entry.removeFromParent()
  51. entries.append(entry)
  52. entry[.groupID] = self[.groupID]
  53. }
  54. public func add(_ group: Group) {
  55. group.removeFromParent()
  56. childs.append(group)
  57. }
  58. }
  59. extension Group: Hashable {
  60. public static func == (lhs: Group, rhs: Group) -> Bool {
  61. guard let lhs = lhs[.groupLevel], let rhs = rhs[.groupLevel] else { return false }
  62. return lhs == rhs
  63. }
  64. public func hash(into hasher: inout Hasher) {
  65. if let groupLevel = self[.groupLevel] { hasher.combine(groupLevel) }
  66. if let groupFlags = self[.groupFlags] { hasher.combine(groupFlags) }
  67. }
  68. }