-
-
Notifications
You must be signed in to change notification settings - Fork 13
/
quantity.go
454 lines (380 loc) · 9.53 KB
/
quantity.go
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
444
445
446
447
448
449
450
451
452
453
454
package core
import (
"errors"
"fmt"
"math"
"reflect"
"time"
"github.com/inoxlang/inox/internal/parse"
"github.com/inoxlang/inox/internal/utils"
)
const (
LINE_COUNT_UNIT = "ln"
RUNE_COUNT_UNIT = "rn"
BYTE_COUNT_UNIT = "B"
SIMPLE_RATE_PER_SECOND_SUFFIX = "x/s"
)
var (
ErrUnknownStartQtyRange = errors.New("quantity range has unknown start")
ErrNegFrequency = errors.New("negative frequency")
ErrInfFrequency = errors.New("infinite frequency")
ErrNegByteRate = errors.New("negative byte rate")
ErrQuantityOverflow = errors.New("quantity overflow")
ErrQuantityUnderflow = errors.New("quantity underflow")
)
var (
_ = []Quantity{ByteCount(0), RuneCount(0), LineCount(0)}
_ = []Rate{ByteRate(0), Frequency(0)}
)
type Quantity interface {
Value
// Int64() should return (value, true) if the internal representation of the quantity is an integer (int64, int32, ...),
// (0, false) otherwise. If $hasIntegralRepr is true the implementation should aso implement Integral.
AsInt64() (v int64, hasIntegralRepr bool)
// Int64() should return (value, true) if the internal representation of the quantity is a float (float64, float32, ...),
// (0, false) otherwise.
AsFloat64() (v float64, hasFloatRepr bool)
IsZeroQuantity() bool
}
func HasIntegralRepresentation(q Quantity) bool {
_, hasIntegralRepr := q.AsInt64()
return hasIntegralRepr
}
// ByteCount implements Value.
type ByteCount int64
func (c ByteCount) Int64() int64 {
return int64(c)
}
func (c ByteCount) IsSigned() bool {
return false
}
func (c ByteCount) AsInt64() (int64, bool) {
return int64(c), true
}
func (c ByteCount) AsFloat64() (float64, bool) {
return 0, false
}
func (c ByteCount) IsZeroQuantity() bool {
return c == 0
}
// RuneCount implements Value.
type RuneCount int64
func (c RuneCount) Int64() int64 {
return int64(c)
}
func (c RuneCount) IsSigned() bool {
return false
}
func (c RuneCount) AsInt64() (int64, bool) {
return int64(c), true
}
func (c RuneCount) AsFloat64() (float64, bool) {
return 0, false
}
func (c RuneCount) IsZeroQuantity() bool {
return c == 0
}
// LineCount implements Value.
type LineCount int64
func (c LineCount) Int64() int64 {
return int64(c)
}
func (c LineCount) IsSigned() bool {
return false
}
func (c LineCount) AsInt64() (int64, bool) {
return int64(c), true
}
func (c LineCount) AsFloat64() (float64, bool) {
return 0, false
}
func (c LineCount) IsZeroQuantity() bool {
return c == 0
}
type Rate interface {
Value
QuantityPerSecond() Value
IsZeroRate() bool
}
// A ByteRate represents a number of bytes per second, it implements Value.
type ByteRate int64
func (r ByteRate) QuantityPerSecond() Value {
return ByteCount(r)
}
func (r ByteRate) IsZeroRate() bool {
return r == 0
}
func (r ByteRate) Validate() error {
if r < 0 {
return ErrNegByteRate
}
return nil
}
// A Frequency represents a number of actions per second, it implements Value.
type Frequency float64
func (f Frequency) QuantityPerSecond() Value {
return Float(f)
}
func (f Frequency) IsZeroRate() bool {
return f == 0
}
func (f Frequency) Validate() error {
if f < 0.0 {
return ErrNegFrequency
}
if math.IsInf(float64(f), 1) {
return ErrInfFrequency
}
return nil
}
// QuantityRange implements Value.
type QuantityRange struct {
unknownStart bool
inclusiveEnd bool
start Serializable
end Serializable
}
func (r QuantityRange) KnownStart() Serializable {
if r.unknownStart {
panic(ErrUnknownStartQtyRange)
}
return r.start
}
func (r QuantityRange) InclusiveEnd() Serializable {
if r.inclusiveEnd {
return r.end
}
next := nextInt64Float64(reflect.ValueOf(r.end))
return next.Interface().(Serializable)
}
// evalQuantity computes a quantity value (Duration, ByteCount, ...).
func evalQuantity(values []float64, units []string) (Serializable, error) {
if len(values) != len(units) {
return nil, ErrInvalidQuantity
}
var totalResultF float64
var totalResult Serializable
for partIndex := 0; partIndex < len(units); partIndex++ {
var (
partValue = values[partIndex]
unit = units[partIndex]
i = 0
multiplier = 1.0
partResult float64
isInt bool
)
if partValue < 0 {
return nil, ErrNegQuantityNotSupported
}
switch unit[i] {
case 'k':
multiplier = 1_000.0
i++
case 'M':
multiplier = 1_000_000.0
i++
case 'G':
multiplier = 1_000_000_000.0
i++
case 'T':
multiplier = 1_000_000_000_000.0
i++
}
//multiplier not followed by a unit
if multiplier != 1.0 && len(unit) == 1 {
return nil, fmt.Errorf("unterminated unit '%s'", unit)
}
switch unit[i:] {
case "x":
if totalResult != nil {
return nil, ErrInvalidQuantity
}
partResult = partValue * multiplier
totalResult = Float(partResult)
case "h", "mn", "s", "ms", "us", "ns":
if totalResult == nil {
totalResult = Duration(0)
}
switch unit[i:] {
case "h":
multiplier *= float64(time.Hour)
case "mn":
multiplier *= float64(time.Minute)
case "s":
multiplier *= float64(time.Second)
case "ms":
multiplier *= float64(time.Millisecond)
case "us":
multiplier *= float64(time.Microsecond)
case "ns":
multiplier *= float64(time.Nanosecond)
}
isInt = true
partResult = partValue * multiplier
totalResult = totalResult.(Duration) + Duration(partResult)
case "%":
if multiplier != 1.0 {
return nil, fmt.Errorf("invalid multiplier '%s' for %%", string(unit[0]))
}
partResult = partValue / 100
totalResult = Float(partResult)
case LINE_COUNT_UNIT:
isInt = true
partResult = partValue * multiplier
totalResult = LineCount(partResult)
case RUNE_COUNT_UNIT:
isInt = true
partResult = partValue * multiplier
totalResult = RuneCount(partResult)
case BYTE_COUNT_UNIT:
isInt = true
partResult = partValue * multiplier
totalResult = ByteCount(partResult)
default:
return nil, fmt.Errorf("unsupported unit '%s'", unit[i:])
}
totalResultF += partResult
if isInt && totalResultF >= math.MaxInt64 {
return nil, ErrQuantityLooLarge
}
}
return totalResult, nil
}
func evalRate(q Value, unitName string) (Serializable, error) {
switch qv := q.(type) {
case ByteCount:
if unitName != "s" {
return nil, errors.New("invalid unit " + unitName)
}
return ByteRate(qv), nil
case Float:
if unitName != "s" {
return nil, errors.New("invalid unit " + unitName)
}
return Frequency(qv), nil
}
return nil, fmt.Errorf("invalid quantity type: %T", q)
}
func mustEvalQuantityRange(n *parse.QuantityRangeLiteral) QuantityRange {
lowerBound := utils.Must(evalQuantity(n.LowerBound.Values, n.LowerBound.Units))
var upperBound Serializable
if n.UpperBound != nil {
upperBound = utils.Must(evalQuantity(n.UpperBound.(*parse.QuantityLiteral).Values, n.UpperBound.(*parse.QuantityLiteral).Units))
} else {
upperBound = getQuantityTypeMaxValue(lowerBound)
}
return QuantityRange{
unknownStart: false,
inclusiveEnd: true,
start: lowerBound,
end: upperBound,
}
}
func getQuantityTypeStart(v Serializable) Serializable {
switch v.(type) {
case ByteCount:
return ByteCount(0)
case RuneCount:
return RuneCount(0)
case LineCount:
return LineCount(0)
case Duration:
return Duration(0)
default:
panic(ErrUnreachable)
}
}
func getQuantityTypeMaxValue(v Serializable) Serializable {
switch v.(type) {
case ByteCount:
return ByteCount(math.MaxInt64)
case RuneCount:
return RuneCount(math.MaxInt64)
case LineCount:
return LineCount(math.MaxInt64)
case Duration:
return Duration(math.MaxInt64)
default:
panic(ErrUnreachable)
}
}
func quantityLessThan(a, b reflect.Value) bool {
if a.Type() != b.Type() {
panic(ErrUnreachable)
}
switch a.Kind() {
case reflect.Float64:
return a.Float() < b.Float()
case reflect.Int64:
return a.Int() < b.Int()
default:
panic(ErrUnreachable)
}
}
func quantityLessOrEqual(a, b reflect.Value) bool {
if a.Type() != b.Type() {
panic(ErrUnreachable)
}
switch a.Kind() {
case reflect.Float64:
return a.Float() <= b.Float()
case reflect.Int64:
return a.Int() <= b.Int()
default:
panic(ErrUnreachable)
}
}
func nextInt64Float64(v reflect.Value) reflect.Value {
ptr := reflect.New(v.Type())
ptr.Elem().Set(v)
if v.Kind() == reflect.Float64 {
ptr.Elem().SetFloat(math.Nextafter(v.Float(), math.MaxFloat64))
} else {
ptr.Elem().SetInt(v.Int() + 1)
}
return ptr.Elem()
}
// int64QuantityAdd adds l an r in a safe way:
// - if there is an overflow the returned value is nil and the error is ErrIntOverflow.
// - if there is an underflow the returned value is nil and the error is ErrIntUnderflow.
func int64QuantityAdd[T interface {
Value
~int64
}](l, r T, underflowIfNegative bool) (Value, error) {
if r > 0 {
if l > math.MaxInt64-r {
return nil, ErrQuantityOverflow
}
} else {
if l < math.MinInt64-r {
return nil, ErrQuantityUnderflow
}
}
res := l + r
if res < 0 && underflowIfNegative {
return nil, ErrQuantityUnderflow
}
return res, nil
}
// int64QuantitySub substracts r from l in a safe way:
// - if there is an overflow the returned value is nil and the error is ErrQuantityOverflow.
// - if there is an underflow the returned value is nil and the error is ErrQuantityUnderflow.
func int64QuantitySub[T interface {
Value
~int64
}](l, r T, underflowIfNegative bool) (Value, error) {
if r < 0 {
if l > math.MaxInt64+r {
return nil, ErrQuantityOverflow
}
} else {
if l < math.MinInt64+r {
return nil, ErrQuantityUnderflow
}
}
res := l - r
if res < 0 && underflowIfNegative {
return nil, ErrQuantityUnderflow
}
return res, nil
}