WebSequenceNumber.swift 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // _____ _
  2. // |_ _| |_ _ _ ___ ___ _ __ __ _
  3. // | | | ' \| '_/ -_) -_) ' \/ _` |_
  4. // |_| |_||_|_| \___\___|_|_|_\__,_(_)
  5. //
  6. // Threema iOS Client
  7. // Copyright (c) 2018-2020 Threema GmbH
  8. //
  9. // This program is free software: you can redistribute it and/or modify
  10. // it under the terms of the GNU Affero General Public License, version 3,
  11. // as published by the Free Software Foundation.
  12. //
  13. // This program is distributed in the hope that it will be useful,
  14. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. // GNU Affero General Public License for more details.
  17. //
  18. // You should have received a copy of the GNU Affero General Public License
  19. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  20. import Foundation
  21. class WebSequenceNumber: NSObject, NSCoding {
  22. private var minValue: UInt64
  23. private var maxValue: UInt64
  24. private var _value: UInt64
  25. var value: UInt64 {
  26. set {
  27. if isValid(other: UInt64(newValue)) == true {
  28. _value = newValue
  29. }
  30. }
  31. get { return _value }
  32. }
  33. init(initialValue:UInt64 = 0, minValue: UInt64, maxValue: UInt64) {
  34. self.minValue = minValue
  35. self.maxValue = maxValue
  36. self._value = initialValue
  37. }
  38. func isValid(other: UInt64) -> Bool {
  39. if other < minValue {
  40. return false
  41. }
  42. if other > maxValue {
  43. return false
  44. }
  45. return true
  46. }
  47. func increment(by: UInt64 = 1) -> UInt64? {
  48. if by < 0 {
  49. return nil
  50. }
  51. let tmpValue = _value
  52. value = tmpValue + by
  53. return value
  54. }
  55. required init?(coder aDecoder: NSCoder) {
  56. // super.init(coder:) is optional, see notes below
  57. self.minValue = UInt64(aDecoder.decodeInt64(forKey: "minValue"))
  58. self.maxValue = UInt64(aDecoder.decodeInt64(forKey: "maxValue"))
  59. self._value = UInt64(aDecoder.decodeInt64(forKey: "_value"))
  60. }
  61. func encode(with aCoder: NSCoder) {
  62. // super.encodeWithCoder(aCoder) is optional, see notes below
  63. aCoder.encode(Int64(minValue), forKey: "minValue")
  64. aCoder.encode(Int64(maxValue), forKey: "maxValue")
  65. aCoder.encode(Int64(_value), forKey: "_value")
  66. }
  67. }