summaryrefslogtreecommitdiff
path: root/taler-swift/Sources/taler-swift/Amount.swift
blob: 25706cfd994d1df65763e4ffc4c47bfce221edcc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
/*
 * This file is part of GNU Taler, ©2022-23 Taler Systems S.A.
 * See LICENSE.md
 */
import Foundation

public func SuperScriptDigit(_ number: UInt32) -> String {
    switch number {
        case 0: return String("\u{2070}")
        case 1: return String("\u{00B9}")
        case 2: return String("\u{00B2}")
        case 3: return String("\u{00B3}")
        case 4: return String("\u{2074}")
        case 5: return String("\u{2075}")
        case 6: return String("\u{2076}")
        case 7: return String("\u{2077}")
        case 8: return String("\u{2078}")
        case 9: return String("\u{2079}")
        default: return ""
    }
}

/// Errors for `Amount`.
enum AmountError: Error {
    /// The string cannot be parsed to create an `Amount`.
    case invalidStringRepresentation
    
    /// Could not compare or operate on two `Amount`s of different currencies.
    case incompatibleCurrency
    
    /// The amount is invalid. The value is either greater than the maximum, or the currency string is not 1-12 characters long.
    case invalidAmount
    
    /// The result of the operation would yield a negative amount.
    case negativeAmount
    
    /// The operation was division by zero.
    case divideByZero
}


/// A value of some currency.
public final class Amount: Codable, Hashable, @unchecked Sendable, CustomStringConvertible {        // TODO: @unchecked
    /// Format that a currency must match.
    private static let currencyRegex = #"^[-_*A-Za-z0-9]{1,12}$"#
    
    /// The largest possible value that can be represented.
    private static let maxValue: UInt64 = 1 << 52
    
    /// The size of `integer` in relation to `fraction`.
    private static let fractionalBase: UInt32 = 100000000
    
    /// The greatest number of fractional digits that can be represented.
    private static let fractionalBaseDigits: UInt = 8
    
    /// The currency of the amount. Cannot be changed later
    private let currency: String

    /// The integer value of the amount (number to the left of the decimal point).
    var integer: UInt64
    
    /// The fractional value of the amount (number to the right of the decimal point).
    var fraction: UInt32

    public func hash(into hasher: inout Hasher) {
        hasher.combine(currency)
        if let normalized = try? normalizedCopy() {
            hasher.combine(normalized.integer)
            hasher.combine(normalized.fraction)
        } else {
            hasher.combine(integer)
            hasher.combine(fraction)
        }
    }

    /// The floating point representation of the integer.
    public var intValue: Double {
        Double(integer)
    }

    /// The floating point representation of the fraction.
    public var fracValue: Double {
        let oneThousand = 1000.0
        let base = Double(Amount.fractionalBase) / oneThousand
        let thousandths = Double(fraction) / base
        return thousandths / oneThousand
    }

    /// The floating point representation of the value.
    /// Be careful, the value might exceed 15 digits which is the limit for Double.
    /// When more significant digits are needed, use valueAsTuple.
    public var value: Double {
        fraction == 0 ? intValue
                      : intValue + fracValue
    }

    /// The tuple representation of the value.
    public var valueAsTuple: (Double, Double) {
        (intValue, fracValue)
    }

    /// The string representation of the value, formatted as "`integer`.`fraction`",
    /// no trailing zeroes, no group separator.
    public var valueStr: String {
        var decimalSeparator = "."
//        if let currencySpecification {      // TODO: use locale
//            decimalSeparator = currencySpecification.decimalSeparator
//        }
        if fraction == 0 {
            return "\(integer)"
        } else {
            var frac = fraction
            var fracStr = ""
            while (frac > 0) {
                fracStr += "\(frac / (Amount.fractionalBase / 10))"
                frac = (frac * 10) % Amount.fractionalBase
            }
            return "\(integer)\(decimalSeparator)\(fracStr)"
        }
    }

    /// read-only getter
    public var currencyStr: String {
        return currency
    }

    /// The string representation of the amount, formatted as "`currency`:`integer`.`fraction`".
    public var description: String {
        return "\(currency):\(valueStr)"
    }
    
    /// The string representation of the amount, formatted as "`integer`.`fraction` `currency`".
    public var readableDescription: String {
        return "\(valueStr) \(currency)"
    }
    
    /// Whether the value is valid. An amount is valid if and only if the currency is not empty and the value is less than the maximum allowed value.
    var valid: Bool {
        if currency.range(of: Amount.currencyRegex, options: .regularExpression) == nil {
            return false
        }
        return (integer <= Amount.maxValue && currency != "")
    }
    
    /// Whether this amount is zero or not.
    public var isZero: Bool {
        return integer == 0 && fraction == 0
    }
    
    /// Initializes an amount by parsing a string representing the amount. The string should be formatted as "`currency`:`integer`.`fraction`".
    /// - Parameters:
    ///   - fromString: The string to parse.
    /// - Throws:
    ///   - `AmountError.invalidStringRepresentation` if the string cannot be parsed.
    ///   - `AmountError.invalidAmount` if the string can be parsed, but the resulting amount is not valid.
    public init(fromString string: String) throws {
        if let separatorIndex = string.firstIndex(of: ":") {
            self.currency = String(string[..<separatorIndex])
            let amountStr = String(string[string.index(separatorIndex, offsetBy: 1)...])
            if let dotIndex = amountStr.firstIndex(of: ".") {
                let integerStr = String(amountStr[..<dotIndex])
                let fractionStr = String(amountStr[string.index(dotIndex, offsetBy: 1)...])
                if (fractionStr.count > Amount.fractionalBaseDigits) {
                    throw AmountError.invalidStringRepresentation
                }
                guard let intValue = UInt64(integerStr) else { throw AmountError.invalidStringRepresentation }
                self.integer = intValue
                self.fraction = 0
                var digitValue = Amount.fractionalBase / 10
                for char in fractionStr {
                    guard let digit = char.wholeNumberValue else { throw AmountError.invalidStringRepresentation }
                    self.fraction += digitValue * UInt32(digit)
                    digitValue /= 10
                }
            } else {
                guard let intValue = UInt64(amountStr) else { throw AmountError.invalidStringRepresentation }
                self.integer = intValue
                self.fraction = 0
            }
        } else {
            self.currency = string
            self.integer = 0
            self.fraction = 0
        }
        guard self.valid else { throw AmountError.invalidAmount }
    }
    
    /// Initializes an amount with the specified currency, integer, and fraction.
    /// - Parameters:
    ///   - currency: The currency of the amount.
    ///   - integer: The integer value of the amount (number to the left of the decimal point).
    ///   - fraction: The fractional value of the amount (number to the right of the decimal point).
    public init(currency: String, integer: UInt64, fraction: UInt32) {
        self.currency = currency
        self.integer = integer
        self.fraction = fraction
    }
    public init(currency: String, value: UInt64) {
        self.currency = currency
        self.integer = value / 100          // TODO: fractional digits can be 0, 2 or 3
        self.fraction = UInt32(value - (self.integer * 100))
    }

    /// Initializes an amount from a decoder.
    /// - Parameters:
    ///   - from: The decoder to extract the amount from.
    /// - Throws:
    ///   - `AmountError.invalidStringRepresentation` if the string cannot be parsed.
    ///   - `AmountError.invalidAmount` if the string can be parsed, but the resulting amount is not valid.
    required public convenience init(from decoder: Decoder) throws {
        let container = try decoder.singleValueContainer()
        let string = try container.decode(String.self)
        try self.init(fromString: string)
    }
    
    /// Copies an amount.
    /// - Returns: A copy of the amount.
    func copy() -> Amount {
        return Amount(currency: currency, integer: integer, fraction: fraction)
    }
    
    /// Creates a normalized copy of an amount (the fractional part is strictly less than one unit of currency).
    /// - Returns: A copy of the amount that has been normalized
    func normalizedCopy() throws -> Amount {
        let amount = self.copy()
        try amount.normalize()
        return amount
    }
    
    /// Encodes an amount.
    /// - Parameters:
    ///   - to: The encoder to encode the amount with.
    public func encode(to encoder: Encoder) throws {
        var container = encoder.singleValueContainer()
        try container.encode(description)
    }
    
    /// Normalizes an amount by reducing `fraction` until it is less than `Amount.fractionalBase`, increasing `integer` appropriately.
    /// - Throws:
    ///   - `AmountError.invalidAmount` if the amount is invalid either before or after normalization.
    func normalize() throws {
        if !valid {
            throw AmountError.invalidAmount
        }
        integer += UInt64(fraction / Amount.fractionalBase)
        fraction = fraction % Amount.fractionalBase
        if !valid {
            throw AmountError.invalidAmount
        }
    }
    
    /// Adds two amounts together.
    /// - Parameters:
    ///   - left: The amount on the left.
    ///   - right: The amount on the right.
    /// - Throws:
    ///   - `AmountError.incompatibleCurrency` if `left` and `right` do not share the same currency.
    /// - Returns: The sum of `left` and `right`, normalized.
    public static func + (left: Amount, right: Amount) throws -> Amount {
        if left.currency != right.currency {
            throw AmountError.incompatibleCurrency
        }
        let leftNormalized = try left.normalizedCopy()
        let rightNormalized = try right.normalizedCopy()
        let result: Amount = leftNormalized
        result.integer += rightNormalized.integer
        result.fraction += rightNormalized.fraction
        try result.normalize()
        return result
    }
    
    /// Subtracts one amount from another.
    /// - Parameters:
    ///   - left: The amount on the left.
    ///   - right: The amount on the right.
    /// - Throws:
    ///   - `AmountError.incompatibleCurrency` if `left` and `right` do not share the same currency.
    /// - Returns: The difference of `left` and `right`, normalized.
    public static func - (left: Amount, right: Amount) throws -> Amount {
        if left.currency != right.currency {
            throw AmountError.incompatibleCurrency
        }
        let leftNormalized = try left.normalizedCopy()
        let rightNormalized = try right.normalizedCopy()
        if (leftNormalized.fraction < rightNormalized.fraction) {
            guard leftNormalized.integer != 0 else { throw AmountError.negativeAmount }
            leftNormalized.integer -= 1
            leftNormalized.fraction += Amount.fractionalBase
        }
        guard leftNormalized.integer >= rightNormalized.integer else { throw AmountError.negativeAmount }
        let diff = Amount.zero(currency: left.currency)
        diff.integer = leftNormalized.integer - rightNormalized.integer
        diff.fraction = leftNormalized.fraction - rightNormalized.fraction
        try diff.normalize()
        return diff
    }

    public static func diff (_ left: Amount, _ right: Amount) throws -> Amount {
        return try left > right ? left - right
                                : right - left
    }

    /// Divides an amount by a scalar, possibly introducing rounding error.
    /// - Parameters:
    ///   - dividend: The amount to divide.
    ///   - divisor: The scalar dividing `dividend`.
    /// - Returns: The quotient of `dividend` and `divisor`, normalized.
    public static func / (dividend: Amount, divisor: UInt32) throws -> Amount {
        guard divisor != 0 else { throw AmountError.divideByZero }
        let result = try dividend.normalizedCopy()
        if (divisor == 1) {
            return result
        }
        var remainder = result.integer % UInt64(divisor)
        result.integer = result.integer / UInt64(divisor)

        let fractionalBase = UInt64(Amount.fractionalBase)
        remainder = (remainder * fractionalBase) + UInt64(result.fraction)
        result.fraction = UInt32(remainder / UInt64(divisor))
        try result.normalize()
        return result
    }
    
    /// Multiply an amount by a scalar.
    /// - Parameters:
    ///   - amount: The amount to multiply.
    ///   - factor: The scalar multiplying `amount`.
    /// - Returns: The product of `amount` and `factor`, normalized.
    public static func * (amount: Amount, factor: UInt32) throws -> Amount {
        let result = try amount.normalizedCopy()
        result.integer = result.integer * UInt64(factor)
        let fraction_tmp = UInt64(result.fraction) * UInt64(factor)
        result.integer += fraction_tmp / UInt64(Amount.fractionalBase)
        result.fraction = UInt32(fraction_tmp % UInt64(Amount.fractionalBase))
        return result
    }
    
    /// Compares two amounts.
    /// - Parameters:
    ///   - left: The first amount.
    ///   - right: The second amount.
    /// - Throws:
    ///   - `AmountError.incompatibleCurrency` if `left` and `right` do not share the same currency.
    /// - Returns: `true` if and only if the amounts have the same `integer` and `fraction` after normalization, `false` otherwise.
//    public static func == (left: Amount, right: Amount) throws -> Bool {
//        if left.currency != right.currency {
//            throw AmountError.incompatibleCurrency
//        }
//        let leftNormalized = try left.normalizedCopy()
//        let rightNormalized = try right.normalizedCopy()
//        return (leftNormalized.integer == rightNormalized.integer && leftNormalized.fraction == rightNormalized.fraction)
//    }
    
    public static func == (left: Amount, right: Amount) -> Bool {
        do {
            if left.currency != right.currency {
                throw AmountError.incompatibleCurrency
            }
            let leftNormalized = try left.normalizedCopy()
            let rightNormalized = try right.normalizedCopy()
            return (leftNormalized.integer == rightNormalized.integer && leftNormalized.fraction == rightNormalized.fraction)
        }
        catch {
            return false
        }
    }

    /// Compares two amounts.
    /// - Parameters:
    ///   - left: The amount on the left.
    ///   - right: The amount on the right.
    /// - Throws:
    ///   - `AmountError.incompatibleCurrency` if `left` and `right` do not share the same currency.
    /// - Returns: `true` if and only if `left` is lesser than `right` after normalization, `false` otherwise.
    public static func < (left: Amount, right: Amount) throws -> Bool {
        if left.currency != right.currency {
            throw AmountError.incompatibleCurrency
        }
        let leftNormalized = try left.normalizedCopy()
        let rightNormalized = try right.normalizedCopy()
        if (leftNormalized.integer == rightNormalized.integer) {
            return (leftNormalized.fraction < rightNormalized.fraction)
        } else {
            return (leftNormalized.integer < rightNormalized.integer)
        }
    }
    
    /// Compares two amounts.
    /// - Parameters:
    ///   - left: The amount on the left.
    ///   - right: The amount on the right.
    /// - Throws:
    ///   - `AmountError.incompatibleCurrency` if `left` and `right` do not share the same currency.
    /// - Returns: `true` if and only if `left` is lesser than or equal to `right` after normalization, `false` otherwise.
    public static func <= (left: Amount, right: Amount) throws -> Bool {
        return try left < right || left == right
    }
    
    /// Compares two amounts.
    /// - Parameters:
    ///   - left: The amount on the left.
    ///   - right: The amount on the right.
    /// - Throws:
    ///   - `AmountError.incompatibleCurrency` if `left` and `right` do not share the same currency.
    /// - Returns: `true` if and only if `left` is greater than `right` after normalization, `false` otherwise.
    public static func > (left: Amount, right: Amount) throws -> Bool {
        return try right < left
    }
    
    /// Compares two amounts.
    /// - Parameters:
    ///   - left: The amount on the left.
    ///   - right: The amount on the right.
    /// - Throws:
    ///   - `AmountError.incompatibleCurrency` if `left` and `right` do not share the same currency.
    /// - Returns: `true` if and only if `left` is greater than or equal `right` after normalization, `false` otherwise.
    public static func >= (left: Amount, right: Amount) throws -> Bool {
        return try left > right || left == right
    }
    
    /// Creates the amount representing zero in a given currency.
    /// - Parameters:
    ///   - currency: The currency to use.
    /// - Returns: The zero amount for `currency`.
    public static func zero(currency: String) -> Amount {
        return Amount(currency: currency, integer: 0, fraction: 0)
    }

    public static func amountFromCents(_ currency: String, _ cents: UInt64) -> Amount {
        let amount100 = Amount(currency: currency, integer: cents, fraction: 0)
        do {
            let amount = try amount100 / 100
            return amount
        } catch {       // shouldn't happen, but if it does then truncate
            return Amount(currency: currency, integer: cents / 100, fraction: 0)
        }
    }
}
// MARK: -
extension Amount: Identifiable {
    // needed to be passed as value for .sheet
    public var id: Amount {self}
}