This repository has been archived by the owner on Sep 20, 2023. It is now read-only.
/
units.go
2313 lines (2141 loc) · 59.8 KB
/
units.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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2018 The Periph Authors. All rights reserved.
// Use of this source code is governed under the Apache License, Version 2.0
// that can be found in the LICENSE file.
package physic
import (
"errors"
"strconv"
"strings"
"time"
"unicode/utf8"
)
// Angle is the measurement of the difference in orientation between two vectors
// stored as an int64 nano radian.
//
// A negative angle is valid.
//
// The highest representable value is a bit over 9.223GRad or 500,000,000,000°.
type Angle int64
// String returns the angle formatted as a string in degree.
func (a Angle) String() string {
// Angle is not a S.I. unit, so it must not be prefixed by S.I. prefixes.
if a == 0 {
return "0°"
}
// Round.
prefix := ""
if a < 0 {
a = -a
prefix = "-"
}
switch {
case a < Degree:
v := ((a * 1000) + Degree/2) / Degree
return prefix + "0." + prefixZeros(3, int(v)) + "°"
case a < 10*Degree:
v := ((a * 1000) + Degree/2) / Degree
i := v / 1000
v = v - i*1000
return prefix + strconv.FormatInt(int64(i), 10) + "." + prefixZeros(3, int(v)) + "°"
case a < 100*Degree:
v := ((a * 1000) + Degree/2) / Degree
i := v / 1000
v = v - i*1000
return prefix + strconv.FormatInt(int64(i), 10) + "." + prefixZeros(2, int(v)) + "°"
case a < 1000*Degree:
v := ((a * 1000) + Degree/2) / Degree
i := v / 1000
v = v - i*1000
return prefix + strconv.FormatInt(int64(i), 10) + "." + prefixZeros(1, int(v)) + "°"
case a > maxAngle-Degree:
u := (uint64(a) + uint64(Degree)/2) / uint64(Degree)
v := int64(u)
return prefix + strconv.FormatInt(int64(v), 10) + "°"
default:
v := (a + Degree/2) / Degree
return prefix + strconv.FormatInt(int64(v), 10) + "°"
}
}
// Set sets the Angle to the value represented by s. Units are to be provided in
// "rad", "deg" or "°" with an optional SI prefix: "p", "n", "u", "µ", "m", "k",
// "M", "G" or "T".
func (a *Angle) Set(s string) error {
d, n, err := atod(s)
if err != nil {
if e, ok := err.(*parseError); ok {
switch e.error {
case errNotANumber:
if found := hasSuffixes(s[n:], "Rad", "rad", "Deg", "deg", "°"); found != "" {
return err
}
return notNumberUnitErr("Rad, Deg or °")
case errOverflowsInt64:
// TODO(maruel): Look for suffix, and reuse it.
return maxValueErr(maxAngle.String())
case errOverflowsInt64Negative:
// TODO(maruel): Look for suffix, and reuse it.
return minValueErr(minAngle.String())
}
}
return err
}
var si prefix
if n != len(s) {
r, rsize := utf8.DecodeRuneInString(s[n:])
if r <= 1 || rsize == 0 {
return errors.New("unexpected end of string")
}
var siSize int
si, siSize = parseSIPrefix(r)
n += siSize
}
switch s[n:] {
case "Deg", "deg", "°":
degreePerRadian := decimal{
base: 17453293,
exp: 0,
neg: false,
}
deg, _ := decimalMul(d, degreePerRadian)
// Impossible for precision loss to exceed 9 since the number of
// significant figures in degrees per radian is only 8.
v, overflow := dtoi(deg, int(si))
if overflow {
if deg.neg {
return minValueErr(minAngle.String())
}
return maxValueErr(maxAngle.String())
}
*a = (Angle)(v)
case "Rad", "rad":
v, overflow := dtoi(d, int(si-nano))
if overflow {
if d.neg {
return minValueErr("-9.223G" + s[n:])
}
return maxValueErr("9.223G" + s[n:])
}
*a = (Angle)(v)
case "":
return noUnitErr("Rad, Deg or °")
default:
if found := hasSuffixes(s[n:], "Rad", "rad", "Deg", "deg", "°"); found != "" {
return unknownUnitPrefixErr(found, "p,n,u,µ,m,k,M,G or T")
}
return incorrectUnitErr("Rad, Deg or °")
}
return nil
}
// Well known Angle constants.
const (
NanoRadian Angle = 1
MicroRadian Angle = 1000 * NanoRadian
MilliRadian Angle = 1000 * MicroRadian
Radian Angle = 1000 * MilliRadian
// Theta is 2π. This is equivalent to 360°.
Theta Angle = 6283185307 * NanoRadian
Pi Angle = 3141592653 * NanoRadian
Degree Angle = 17453293 * NanoRadian
maxAngle Angle = 9223372036854775807
minAngle Angle = -9223372036854775807
)
// Distance is a measurement of length stored as an int64 nano metre.
//
// This is one of the base unit in the International System of Units.
//
// The highest representable value is 9.2Gm.
type Distance int64
// String returns the distance formatted as a string in metre.
func (d Distance) String() string {
return nanoAsString(int64(d)) + "m"
}
// Set sets the Distance to the value represented by s. Units are to
// be provided in "m", "Mile", "Yard", "in", or "ft" with an optional SI
// prefix: "p", "n", "u", "µ", "m", "k", "M", "G" or "T".
func (d *Distance) Set(s string) error {
dc, n, err := atod(s)
if err != nil {
if e, ok := err.(*parseError); ok {
switch e.error {
case errNotANumber:
if found := hasSuffixes(s[n:], "in", "ft", "Yard", "yard", "Mile", "mile", "m"); found != "" {
return err
}
return notNumberUnitErr("m, Mile, in, ft or Yard")
case errOverflowsInt64:
// TODO(maruel): Look for suffix, and reuse it.
return maxValueErr(maxDistance.String())
case errOverflowsInt64Negative:
// TODO(maruel): Look for suffix, and reuse it.
return minValueErr(minDistance.String())
}
}
return err
}
si := prefix(unit)
if n != len(s) {
r, rsize := utf8.DecodeRuneInString(s[n:])
if r <= 1 || rsize == 0 {
return errors.New("unexpected end of string")
}
var siSize int
si, siSize = parseSIPrefix(r)
if si == milli || si == mega {
switch s[n:] {
case "m", "Mile", "mile":
si = unit
}
}
if si != unit {
n += siSize
}
}
v, overflow := dtoi(dc, int(si-nano))
if overflow {
if dc.neg {
return minValueErr(minDistance.String())
}
return maxValueErr(maxDistance.String())
}
switch s[n:] {
case "m":
*d = (Distance)(v)
case "Mile", "mile":
switch {
case v > maxMiles:
return maxValueErr("5731Mile")
case v < minMiles:
return minValueErr("-5731Mile")
case v >= 0:
*d = (Distance)((v*1609344 + 500) / 1000)
default:
*d = (Distance)((v*1609344 - 500) / 1000)
}
case "Yard", "yard":
switch {
case v > maxYards:
return maxValueErr("1 Million Yard")
case v < minYards:
return minValueErr("-1 Million Yard")
case v >= 0:
*d = (Distance)((v*9144 + 5000) / 10000)
default:
*d = (Distance)((v*9144 - 5000) / 10000)
}
case "ft":
switch {
case v > maxFeet:
return maxValueErr("3 Million ft")
case v < minFeet:
return minValueErr("-3 Million ft")
case v >= 0:
*d = (Distance)((v*3048 + 5000) / 10000)
default:
*d = (Distance)((v*3048 - 5000) / 10000)
}
case "in":
switch {
case v > maxInches:
return maxValueErr("36 Million inch")
case v < minInches:
return minValueErr("-36 Million inch")
case v >= 0:
*d = (Distance)((v*254 + 5000) / 10000)
default:
*d = (Distance)((v*254 - 5000) / 10000)
}
case "":
return noUnitErr("m, Mile, in, ft or Yard")
default:
if found := hasSuffixes(s[n:], "in", "ft", "Yard", "Mile", "m"); found != "" {
return unknownUnitPrefixErr(found, "p,n,u,µ,m,k,M,G or T")
}
return incorrectUnitErr("m, Mile, in, ft or Yard")
}
return nil
}
// Well known Distance constants.
const (
NanoMetre Distance = 1
MicroMetre Distance = 1000 * NanoMetre
MilliMetre Distance = 1000 * MicroMetre
Metre Distance = 1000 * MilliMetre
KiloMetre Distance = 1000 * Metre
MegaMetre Distance = 1000 * KiloMetre
GigaMetre Distance = 1000 * MegaMetre
// Conversion between Metre and imperial units.
Thou Distance = 25400 * NanoMetre
Inch Distance = 1000 * Thou
Foot Distance = 12 * Inch
Yard Distance = 3 * Foot
Mile Distance = 1760 * Yard
maxDistance = 9223372036854775807 * NanoMetre
minDistance = -9223372036854775807 * NanoMetre
maxMiles int64 = (int64(maxDistance) - 500) / int64((Mile)/1000000) // ~Max/1609344
minMiles int64 = (int64(minDistance) + 500) / int64((Mile)/1000000) // ~Min/1609344
maxYards int64 = (int64(maxDistance) - 5000) / int64((Yard)/100000) // ~Max/9144
minYards int64 = (int64(minDistance) + 5000) / int64((Yard)/100000) // ~Min/9144
maxFeet int64 = (int64(maxDistance) - 5000) / int64((Foot)/100000) // ~Max/3048
minFeet int64 = (int64(minDistance) + 5000) / int64((Foot)/100000) // ~Min/3048
maxInches int64 = (int64(maxDistance) - 5000) / int64((Inch)/100000) // ~Max/254
minInches int64 = (int64(minDistance) + 5000) / int64((Inch)/100000) // ~Min/254
)
// ElectricCurrent is a measurement of a flow of electric charge stored as an
// int64 nano Ampere.
//
// This is one of the base unit in the International System of Units.
//
// The highest representable value is 9.2GA.
type ElectricCurrent int64
// String returns the current formatted as a string in Ampere.
func (c ElectricCurrent) String() string {
return nanoAsString(int64(c)) + "A"
}
// Set sets the ElectricCurrent to the value represented by s. Units are to
// be provided in "A" with an optional SI prefix: "p", "n", "u", "µ", "m", "k",
// "M", "G" or "T".
func (c *ElectricCurrent) Set(s string) error {
v, n, err := valueOfUnitString(s, nano)
if err != nil {
if e, ok := err.(*parseError); ok {
switch e.error {
case errNotANumber:
if found := hasSuffixes(s, "A", "a"); found != "" {
return err
}
return notNumberUnitErr("A")
case errOverflowsInt64:
return maxValueErr(maxElectricCurrent.String())
case errOverflowsInt64Negative:
return minValueErr(minElectricCurrent.String())
}
}
return err
}
switch s[n:] {
case "A", "a":
*c = (ElectricCurrent)(v)
case "":
return noUnitErr("A")
default:
if found := hasSuffixes(s[n:], "A"); found != "" {
return unknownUnitPrefixErr(found, "p,n,u,µ,m,k,M,G or T")
}
return incorrectUnitErr("A")
}
return nil
}
// Well known ElectricCurrent constants.
const (
NanoAmpere ElectricCurrent = 1
MicroAmpere ElectricCurrent = 1000 * NanoAmpere
MilliAmpere ElectricCurrent = 1000 * MicroAmpere
Ampere ElectricCurrent = 1000 * MilliAmpere
KiloAmpere ElectricCurrent = 1000 * Ampere
MegaAmpere ElectricCurrent = 1000 * KiloAmpere
GigaAmpere ElectricCurrent = 1000 * MegaAmpere
maxElectricCurrent = 9223372036854775807 * NanoAmpere
minElectricCurrent = -9223372036854775807 * NanoAmpere
)
// ElectricPotential is a measurement of electric potential stored as an int64
// nano Volt.
//
// The highest representable value is 9.2GV.
type ElectricPotential int64
// String returns the tension formatted as a string in Volt.
func (p ElectricPotential) String() string {
return nanoAsString(int64(p)) + "V"
}
// Set sets the ElectricPotential to the value represented by s. Units are to
// be provided in "V" with an optional SI prefix: "p", "n", "u", "µ", "m", "k",
// "M", "G" or "T".
func (p *ElectricPotential) Set(s string) error {
v, n, err := valueOfUnitString(s, nano)
if err != nil {
if e, ok := err.(*parseError); ok {
switch e.error {
case errNotANumber:
if found := hasSuffixes(s, "V", "v"); found != "" {
return err
}
return notNumberUnitErr("V")
case errOverflowsInt64:
return maxValueErr(maxElectricPotential.String())
case errOverflowsInt64Negative:
return minValueErr(minElectricPotential.String())
}
}
return err
}
switch s[n:] {
case "V", "v":
*p = (ElectricPotential)(v)
case "":
return noUnitErr("V")
default:
if found := hasSuffixes(s[n:], "V", "v"); found != "" {
return unknownUnitPrefixErr(found, "p,n,u,µ,m,k,M,G or T")
}
return incorrectUnitErr("V")
}
return nil
}
// Well known ElectricPotential constants.
const (
// Volt is W/A, kg⋅m²/s³/A.
NanoVolt ElectricPotential = 1
MicroVolt ElectricPotential = 1000 * NanoVolt
MilliVolt ElectricPotential = 1000 * MicroVolt
Volt ElectricPotential = 1000 * MilliVolt
KiloVolt ElectricPotential = 1000 * Volt
MegaVolt ElectricPotential = 1000 * KiloVolt
GigaVolt ElectricPotential = 1000 * MegaVolt
maxElectricPotential = 9223372036854775807 * NanoVolt
minElectricPotential = -9223372036854775807 * NanoVolt
)
// ElectricResistance is a measurement of the difficulty to pass an electric
// current through a conductor stored as an int64 nano Ohm.
//
// The highest representable value is 9.2GΩ.
type ElectricResistance int64
// String returns the resistance formatted as a string in Ohm.
func (r ElectricResistance) String() string {
return nanoAsString(int64(r)) + "Ω"
}
// Set sets the ElectricResistance to the value represented by s. Units are to
// be provided in "Ohm", or "Ω" with an optional SI prefix: "p", "n", "u", "µ",
// "m", "k", "M", "G" or "T".
func (r *ElectricResistance) Set(s string) error {
v, n, err := valueOfUnitString(s, nano)
if err != nil {
if e, ok := err.(*parseError); ok {
switch e.error {
case errNotANumber:
if found := hasSuffixes(s, "Ohm", "ohm", "Ω"); found != "" {
return err
}
return notNumberUnitErr("Ohm or Ω")
case errOverflowsInt64:
return maxValueErr(maxElectricResistance.String())
case errOverflowsInt64Negative:
return minValueErr(minElectricResistance.String())
}
}
return err
}
switch s[n:] {
case "Ohm", "ohm", "Ω":
*r = (ElectricResistance)(v)
case "":
return noUnitErr("Ohm or Ω")
default:
if found := hasSuffixes(s[n:], "Ohm", "ohm", "Ω"); found != "" {
return unknownUnitPrefixErr(found, "p,n,u,µ,m,k,M,G or T")
}
return incorrectUnitErr("Ohm or Ω")
}
return nil
}
// Well known ElectricResistance constants.
const (
// Ohm is V/A, kg⋅m²/s³/A².
NanoOhm ElectricResistance = 1
MicroOhm ElectricResistance = 1000 * NanoOhm
MilliOhm ElectricResistance = 1000 * MicroOhm
Ohm ElectricResistance = 1000 * MilliOhm
KiloOhm ElectricResistance = 1000 * Ohm
MegaOhm ElectricResistance = 1000 * KiloOhm
GigaOhm ElectricResistance = 1000 * MegaOhm
maxElectricResistance = 9223372036854775807 * NanoOhm
minElectricResistance = -9223372036854775807 * NanoOhm
)
// Force is a measurement of interaction that will change the motion of an
// object stored as an int64 nano Newton.
//
// A measurement of Force is a vector and has a direction but this unit only
// represents the magnitude. The orientation needs to be stored as a Quaternion
// independently.
//
// The highest representable value is 9.2TN.
type Force int64
// String returns the force formatted as a string in Newton.
func (f Force) String() string {
return nanoAsString(int64(f)) + "N"
}
// Set sets the Force to the value represented by s. Units are to
// be provided in "N", or "lbf" (Pound force) with an optional SI prefix: "p",
// "n", "u", "µ", "m", "k", "M", "G" or "T".
func (f *Force) Set(s string) error {
d, n, err := atod(s)
if err != nil {
if e, ok := err.(*parseError); ok {
switch e.error {
case errNotANumber:
if found := hasSuffixes(s[n:], "N", "lbf"); found != "" {
return err
}
return notNumberUnitErr("N or lbf")
case errOverflowsInt64:
// TODO(maruel): Look for suffix, and reuse it.
return maxValueErr(maxForce.String())
case errOverflowsInt64Negative:
// TODO(maruel): Look for suffix, and reuse it.
return minValueErr(minForce.String())
}
}
return err
}
var si prefix
if n != len(s) {
r, rsize := utf8.DecodeRuneInString(s[n:])
if r <= 1 || rsize == 0 {
return errors.New("unexpected end of string")
}
var siSize int
si, siSize = parseSIPrefix(r)
n += siSize
}
switch s[n:] {
case "lbf":
poundForce := decimal{
base: 4448221615261,
exp: -3,
neg: false,
}
lbf, loss := decimalMul(d, poundForce)
if loss > 9 {
return errors.New("converting to nano Newtons would overflow, consider using nN for maximum precision")
}
v, overflow := dtoi(lbf, int(si))
if overflow {
if lbf.neg {
return minValueErr("-2.073496519Glbf")
}
return maxValueErr("2.073496519Glbf")
}
*f = (Force)(v)
case "N":
v, overflow := dtoi(d, int(si-nano))
if overflow {
if d.neg {
return minValueErr(minForce.String())
}
return maxValueErr(maxForce.String())
}
*f = (Force)(v)
case "":
return noUnitErr("N or lbf")
default:
if found := hasSuffixes(s[n:], "N", "lbf"); found != "" {
return unknownUnitPrefixErr(found, "p,n,u,µ,m,k,M,G or T")
}
return incorrectUnitErr("N or lbf")
}
return nil
}
// Well known Force constants.
const (
// Newton is kg⋅m/s².
NanoNewton Force = 1
MicroNewton Force = 1000 * NanoNewton
MilliNewton Force = 1000 * MicroNewton
Newton Force = 1000 * MilliNewton
KiloNewton Force = 1000 * Newton
MegaNewton Force = 1000 * KiloNewton
GigaNewton Force = 1000 * MegaNewton
EarthGravity Force = 9806650 * MicroNewton
// Conversion between Newton and imperial units.
// Pound is both a unit of mass and weight (force). The suffix Force is added
// to disambiguate the measurement it represents.
PoundForce Force = 4448221615 * NanoNewton
maxForce Force = (1 << 63) - 1
minForce Force = -((1 << 63) - 1)
)
// Frequency is a measurement of cycle per second, stored as an int64 micro
// Hertz.
//
// The highest representable value is 9.2THz.
type Frequency int64
// String returns the frequency formatted as a string in Hertz.
func (f Frequency) String() string {
return microAsString(int64(f)) + "Hz"
}
// Set sets the Frequency to the value represented by s. Units are to
// be provided in "Hz" or "rpm" with an optional SI prefix: "p", "n", "u", "µ",
// "m", "k", "M", "G" or "T".
//
// Unlike most Set() functions, "Hz" is assumed by default.
func (f *Frequency) Set(s string) error {
v, n, err := valueOfUnitString(s, micro)
if err != nil {
if e, ok := err.(*parseError); ok {
switch e.error {
case errNotANumber:
if found := hasSuffixes(s, "Hz", "hz"); found != "" {
return err
}
return notNumberUnitErr("Hz")
case errOverflowsInt64:
return maxValueErr(maxFrequency.String())
case errOverflowsInt64Negative:
return minValueErr(minFrequency.String())
}
}
return err
}
switch s[n:] {
case "Hz", "hz", "":
*f = (Frequency)(v)
default:
if found := hasSuffixes(s[n:], "Hz", "hz"); found != "" {
return unknownUnitPrefixErr(found, "p,n,u,µ,m,k,M,G or T")
}
return incorrectUnitErr("Hz")
}
return nil
}
// Period returns the duration of one cycle at this frequency.
//
// Frequency above GigaHertz cannot be represented as Duration.
//
// A 0Hz frequency returns a 0s period.
func (f Frequency) Period() time.Duration {
if f == 0 {
return 0
}
if f < 0 {
return (time.Second*time.Duration(Hertz) - time.Duration(f/2)) / time.Duration(f)
}
return (time.Second*time.Duration(Hertz) + time.Duration(f/2)) / time.Duration(f)
}
// Duration returns the duration of one cycle at this frequency.
//
// Deprecated: This method is removed in v4.0.0. Use Period() instead.
func (f Frequency) Duration() time.Duration {
return f.Period()
}
// PeriodToFrequency returns the frequency for a period of this interval.
//
// A 0s period returns a 0Hz frequency.
func PeriodToFrequency(p time.Duration) Frequency {
if p == 0 {
return 0
}
if p < 0 {
return (Frequency(time.Second)*Hertz - Frequency(p/2)) / Frequency(p)
}
return (Frequency(time.Second)*Hertz + Frequency(p/2)) / Frequency(p)
}
// Well known Frequency constants.
const (
// Hertz is 1/s.
MicroHertz Frequency = 1
MilliHertz Frequency = 1000 * MicroHertz
Hertz Frequency = 1000 * MilliHertz
KiloHertz Frequency = 1000 * Hertz
MegaHertz Frequency = 1000 * KiloHertz
GigaHertz Frequency = 1000 * MegaHertz
TeraHertz Frequency = 1000 * GigaHertz
// RPM is revolutions per minute. It is used to quantify angular frequency.
RPM Frequency = 16667 * MicroHertz
maxFrequency = 9223372036854775807 * MicroHertz
minFrequency = -9223372036854775807 * MicroHertz
)
// Mass is a measurement of mass stored as an int64 nano gram.
//
// This is one of the base unit in the International System of Units.
//
// The highest representable value is 9.2Gg.
type Mass int64
// String returns the mass formatted as a string in gram.
func (m Mass) String() string {
return nanoAsString(int64(m)) + "g"
}
// Set sets the Mass to the value represented by s. Units are to be provided in
// "g", "lb" or "oz" with an optional SI prefix: "p", "n", "u", "µ", "m", "k",
// "M", "G" or "T".
func (m *Mass) Set(s string) error {
d, n, err := atod(s)
if err != nil {
if e, ok := err.(*parseError); ok {
switch e.error {
case errNotANumber:
if found := hasSuffixes(s[n:], "g", "lb", "oz"); found != "" {
return err
}
return notNumberUnitErr("g, lb or oz")
case errOverflowsInt64:
// TODO(maruel): Look for suffix, and reuse it.
return maxValueErr(maxMass.String())
case errOverflowsInt64Negative:
// TODO(maruel): Look for suffix, and reuse it.
return minValueErr(minMass.String())
}
}
return err
}
var si prefix
if n != len(s) {
r, rsize := utf8.DecodeRuneInString(s[n:])
if r <= 1 || rsize == 0 {
return errors.New("unexpected end of string")
}
var siSize int
si, siSize = parseSIPrefix(r)
n += siSize
}
switch s[n:] {
case "g":
v, overflow := dtoi(d, int(si-nano))
if overflow {
if d.neg {
return minValueErr(minMass.String())
}
return maxValueErr(maxMass.String())
}
*m = (Mass)(v)
case "lb":
gramsPerlb := decimal{
base: uint64(PoundMass),
exp: 0,
neg: false,
}
lbs, _ := decimalMul(d, gramsPerlb)
v, overflow := dtoi(lbs, int(si))
if overflow {
if lbs.neg {
return minValueErr(strconv.FormatInt(int64(minPoundMass), 10) + "lb")
}
return maxValueErr(strconv.FormatInt(int64(maxPoundMass), 10) + "lb")
}
*m = (Mass)(v)
case "oz":
gramsPerOz := decimal{
base: uint64(OunceMass),
exp: 0,
neg: false,
}
oz, _ := decimalMul(d, gramsPerOz)
v, overflow := dtoi(oz, int(si))
if overflow {
if oz.neg {
return minValueErr(strconv.FormatInt(int64(minOunceMass), 10) + "oz")
}
return maxValueErr(strconv.FormatInt(int64(maxOunceMass), 10) + "oz")
}
*m = (Mass)(v)
case "":
return noUnitErr("g, lb or oz")
default:
if found := hasSuffixes(s[n:], "g", "lb", "oz"); found != "" {
return unknownUnitPrefixErr(found, "p,n,u,µ,m,k,M,G or T")
}
return incorrectUnitErr("g, lb or oz")
}
return nil
}
// Well known Mass constants.
const (
NanoGram Mass = 1
MicroGram Mass = 1000 * NanoGram
MilliGram Mass = 1000 * MicroGram
Gram Mass = 1000 * MilliGram
KiloGram Mass = 1000 * Gram
MegaGram Mass = 1000 * KiloGram
GigaGram Mass = 1000 * MegaGram
Tonne Mass = MegaGram
// Conversion between Gram and imperial units.
// Ounce is both a unit of mass, weight (force) or volume depending on
// context. The suffix Mass is added to disambiguate the measurement it
// represents.
OunceMass Mass = 28349523125 * NanoGram
// Pound is both a unit of mass and weight (force). The suffix Mass is added
// to disambiguate the measurement it represents.
PoundMass Mass = 16 * OunceMass
Slug Mass = 14593903 * MilliGram
maxMass Mass = (1 << 63) - 1
minMass Mass = -((1 << 63) - 1)
// min and max Pound mass are in lb.
minPoundMass Mass = -20334054
maxPoundMass Mass = 20334054
// min and max Ounce mass are in oz.
minOunceMass Mass = -325344874
maxOunceMass Mass = 325344874
)
// Pressure is a measurement of force applied to a surface per unit
// area (stress) stored as an int64 nano Pascal.
//
// The highest representable value is 9.2GPa.
type Pressure int64
// String returns the pressure formatted as a string in Pascal.
func (p Pressure) String() string {
return nanoAsString(int64(p)) + "Pa"
}
// Set sets the Pressure to the value represented by s. Units are to
// be provided in "Pa" with an optional SI prefix: "p", "n", "u", "µ", "m", "k",
// "M", "G" or "T".
func (p *Pressure) Set(s string) error {
v, n, err := valueOfUnitString(s, nano)
if err != nil {
if e, ok := err.(*parseError); ok {
switch e.error {
case errNotANumber:
if found := hasSuffixes(s, "Pa"); found != "" {
return err
}
return notNumberUnitErr("Pa")
case errOverflowsInt64:
return maxValueErr(maxPressure.String())
case errOverflowsInt64Negative:
return minValueErr(minPressure.String())
}
}
return err
}
switch s[n:] {
case "Pa":
*p = (Pressure)(v)
case "":
return noUnitErr("Pa")
default:
if found := hasSuffixes(s[n:], "Pa"); found != "" {
return unknownUnitPrefixErr(found, "p,n,u,µ,m,k,M,G or T")
}
return incorrectUnitErr("Pa")
}
return nil
}
// Well known Pressure constants.
const (
// Pascal is N/m², kg/m/s².
NanoPascal Pressure = 1
MicroPascal Pressure = 1000 * NanoPascal
MilliPascal Pressure = 1000 * MicroPascal
Pascal Pressure = 1000 * MilliPascal
KiloPascal Pressure = 1000 * Pascal
MegaPascal Pressure = 1000 * KiloPascal
GigaPascal Pressure = 1000 * MegaPascal
maxPressure = 9223372036854775807 * NanoPascal
minPressure = -9223372036854775807 * NanoPascal
)
// RelativeHumidity is a humidity level measurement stored as an int32 fixed
// point integer at a precision of 0.00001%rH.
//
// Valid values are between 0% and 100%.
type RelativeHumidity int32
// String returns the humidity formatted as a string.
func (r RelativeHumidity) String() string {
r /= MilliRH
frac := int(r % 10)
if frac == 0 {
return strconv.Itoa(int(r)/10) + "%rH"
}
if frac < 0 {
frac = -frac
}
return strconv.Itoa(int(r)/10) + "." + strconv.Itoa(frac) + "%rH"
}
// Set sets the RelativeHumidity to the value represented by s. Units are to
// be provided in "%rH" or "%" with an optional SI prefix: "p", "n", "u", "µ",
// "m", "k", "M", "G" or "T".
func (r *RelativeHumidity) Set(s string) error {
// PercentRH is micro + deca.
v, n, err := valueOfUnitString(s, micro+deca)
if err != nil {
if e, ok := err.(*parseError); ok {
switch e.error {
case errNotANumber:
if found := hasSuffixes(s[n:], "%rH", "%"); found != "" {
return err
}
return notNumberUnitErr("%rH or %")
case errOverflowsInt64:
return maxValueErr(maxRelativeHumidity.String())
case errOverflowsInt64Negative:
return minValueErr(minRelativeHumidity.String())
}
}
return err
}
switch s[n:] {
case "%rH", "%":
// We need an extra check here to make sure that v will fit inside a
// int32.
switch {
case v > int64(maxRelativeHumidity):
return maxValueErr(maxRelativeHumidity.String())
case v < int64(minRelativeHumidity):
return minValueErr(minRelativeHumidity.String())
}
*r = (RelativeHumidity)(v)
case "":
return noUnitErr("%rH or %")
default:
if found := hasSuffixes(s[n:], "%rH", "%"); found != "" {
return unknownUnitPrefixErr(found, "p,n,u,µ,m,k,M,G or T")
}
return incorrectUnitErr("%rH or %")
}
return nil
}
// Well known RelativeHumidity constants.
const (
TenthMicroRH RelativeHumidity = 1 // 0.00001%rH
MicroRH RelativeHumidity = 10 * TenthMicroRH // 0.0001%rH
MilliRH RelativeHumidity = 1000 * MicroRH // 0.1%rH
PercentRH RelativeHumidity = 10 * MilliRH // 1%rH
maxRelativeHumidity RelativeHumidity = 100 * PercentRH
minRelativeHumidity RelativeHumidity = 0
)
// Speed is a measurement of magnitude of velocity stored as an int64 nano
// Metre per Second.
//
// The highest representable value is 9.2Gm/s.
type Speed int64
// String returns the speed formatted as a string in m/s.
func (sp Speed) String() string {
return nanoAsString(int64(sp)) + "m/s"
}
// Set sets the Speed to the value represented by s. Units are to be provided in
// "mps"(meters per second), "m/s", "kph", "fps", or "mph" with an optional SI
// prefix: "p", "n", "u", "µ", "m", "k", "M", "G" or "T".
func (sp *Speed) Set(s string) error {
d, n, err := atod(s)
if err != nil {
if e, ok := err.(*parseError); ok {
switch e.error {
case errNotANumber:
if found := hasSuffixes(s[n:], "m/s", "mps", "kph", "fps", "mph"); found != "" {
return err
}
return notNumberUnitErr("m/s, mps, kph, fps or mph")
case errOverflowsInt64:
// TODO(maruel): Look for suffix, and reuse it.
return maxValueErr(maxSpeed.String())
case errOverflowsInt64Negative:
// TODO(maruel): Look for suffix, and reuse it.
return minValueErr(minSpeed.String())
}
}