-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathunit.ex
More file actions
2570 lines (1869 loc) · 78.3 KB
/
Copy pathunit.ex
File metadata and controls
2570 lines (1869 loc) · 78.3 KB
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
defmodule Localize.Unit do
@moduledoc """
Represents and formats CLDR units of measure.
A `Localize.Unit` struct holds the original unit name string,
its parsed AST representation, and an optional numeric value.
Units can be created with `new/3` and formatted with
`to_string/2`.
## Unit names
Unit names follow the CLDR identifier syntax defined in
[TR35](https://www.unicode.org/reports/tr35/tr35-general.html#unit-syntax).
Examples: `"meter"`, `"kilogram"`, `"meter-per-second"`,
`"square-kilometer"`, `"liter-per-100-kilometer"`.
## Formatting
`to_string/2` produces locale-aware output with plural-sensitive
patterns (e.g., `"1 kilometer"` vs `"3 kilometers"`) and supports
`:long`, `:short`, and `:narrow` format styles.
## Usage preferences
CLDR defines measurement usage preferences by territory and
category (e.g., road distances in the US use miles). The
`:usage` field on the struct and the `:usage` option on
`to_string/2` support automatic unit selection based on locale.
"""
defstruct name: nil,
parsed: nil,
value: nil,
usage: nil,
format_options: []
@type value :: number() | Decimal.t() | [number()] | nil
@type t :: %__MODULE__{
name: String.t(),
parsed: tuple(),
value: value(),
usage: String.t() | nil,
format_options: Keyword.t()
}
defp valid_usages do
cached(:valid_usages, fn ->
Localize.Unit.Data.unit_preferences()
|> Enum.map(& &1.usage)
|> Enum.uniq()
|> Enum.sort()
end)
end
@compile {:inline, cached: 2}
defp cached(key, build_fn) do
pt_key = {__MODULE__, key}
case :persistent_term.get(pt_key, :__not_loaded__) do
:__not_loaded__ ->
value = build_fn.()
:persistent_term.put(pt_key, value)
value
value ->
value
end
end
@doc """
Creates a new unit with a value and a CLDR unit identifier string.
### Arguments
* `amount` is the numeric value (integer, float, or Decimal).
* `unit` is a unit identifier string such as `"meter-per-second"`.
* `options` is an optional keyword list.
### Options
* `:usage` is a string specifying the intended usage context for
the unit. Valid values include `"default"`, `"person"`,
`"person-height"`, `"road"`, `"food"`, `"vehicle-fuel"`,
and others defined in the CLDR unit preference data. The usage
affects which target unit is selected when calling
`convert_measurement_system/2`.
### Returns
* `{:ok, unit}` where `unit` is a `%Localize.Unit{}` struct, or
* `{:error, reason}` if the value is not a valid number, the
identifier cannot be parsed, or the usage is invalid.
### Examples
iex> {:ok, unit} = Localize.Unit.new(100, "meter")
iex> unit.value
100
iex> unit.name
"meter"
iex> {:ok, unit} = Localize.Unit.new(Decimal.new("3.14"), "kilogram")
iex> unit.value
Decimal.new("3.14")
iex> {:ok, unit} = Localize.Unit.new(180, "centimeter", usage: "person-height")
iex> unit.usage
"person-height"
"""
@spec new(number() | Decimal.t(), String.t(), keyword()) ::
{:ok, t()} | {:error, Exception.t()}
def new(amount, unit, options \\ []) when is_binary(unit) do
with {:ok, _} <- validate_value(amount),
{:ok, parsed} <- Localize.Unit.Parser.parse(unit),
:ok <- validate_currency_codes(parsed),
:ok <- validate_base_names(parsed),
{:ok, usage} <- validate_usage(Keyword.get(options, :usage)) do
{canonical_name, normalised_ast} = Localize.Unit.Canonical.canonicalize(parsed)
{:ok,
%__MODULE__{
name: canonical_name,
parsed: normalised_ast,
value: amount,
usage: usage
}}
end
end
@doc """
Creates a new unit from a CLDR unit identifier string without a value.
### Arguments
* `name` is a unit identifier string such as `"meter-per-second"`.
### Returns
* `{:ok, unit}` where `unit` is a `%Localize.Unit{}` struct, or
* `{:error, reason}` if the identifier cannot be parsed.
### Examples
iex> {:ok, unit} = Localize.Unit.new("meter")
iex> unit.name
"meter"
"""
@spec new(String.t()) :: {:ok, t()} | {:error, Exception.t()}
@dialyzer {:nowarn_function, new: 1}
def new(name) when is_binary(name) do
with {:ok, parsed} <- Localize.Unit.Parser.parse(name),
:ok <- validate_currency_codes(parsed),
:ok <- validate_base_names(parsed) do
{canonical_name, normalised_ast} = Localize.Unit.Canonical.canonicalize(parsed)
{:ok, %__MODULE__{name: canonical_name, parsed: normalised_ast}}
end
end
@doc """
Creates a new unit with a value and a CLDR unit identifier string,
raising on error.
Same as `new/2` but returns the struct directly or raises
`ArgumentError`.
### Arguments
* `amount` is the numeric value (integer, float, or Decimal).
* `unit` is a unit identifier string.
* `options` is a keyword list of options.
### Options
See `new/3` for the supported options.
### Returns
* A `%Localize.Unit{}` struct.
### Examples
iex> unit = Localize.Unit.new!(42, "kilogram")
iex> unit.value
42
"""
@spec new!(number() | Decimal.t(), String.t(), keyword()) :: t() | no_return()
@dialyzer {:nowarn_function, new!: 3}
def new!(amount, unit, options \\ []) when is_binary(unit) do
case new(amount, unit, options) do
{:ok, result} -> result
{:error, exception} -> raise exception
end
end
@doc """
Creates a new unit from a CLDR unit identifier string, raising on error.
Same as `new/1` but returns the struct directly or raises
`ArgumentError`.
### Arguments
* `name` is a unit identifier string.
### Returns
* A `%Localize.Unit{}` struct.
### Examples
iex> unit = Localize.Unit.new!("meter")
iex> unit.name
"meter"
"""
@spec new!(String.t()) :: t() | no_return()
@dialyzer {:nowarn_function, new!: 1}
def new!(name) when is_binary(name) do
case new(name) do
{:ok, unit} -> unit
{:error, exception} -> raise exception
end
end
@doc """
Parses a string containing a number and a unit name into a unit.
The number is parsed with the locale's number symbols and the unit name is matched against the locale's unit names — display names and the text of the long, short and narrow patterns — as well as the canonical CLDR identifiers and any units registered with `define_unit/2`. Matching is case-insensitive; when a name is ambiguous ("2 w" matches both watt and week via their narrow forms) the candidates are filtered by the `:only`/`:except` options and the first remaining unit in alphabetical order is chosen.
### Arguments
* `unit_string` is a string containing a number and a unit name, in either order (e.g., `"1kg"`, `"1 kilogram"`, `"2,5 kg"` in a locale with comma decimals).
* `options` is a keyword list of options.
### Options
* `:locale` is a locale identifier atom, string, or a `t:Localize.LanguageTag.t/0`. The default is `Localize.get_locale()`. Both the number symbols and the unit names follow this locale.
* `:only` is a category, a unit name, or a list of either (atoms or strings). Only matching candidates are considered: `only: :duration` resolves `"2w"` to weeks rather than watts.
* `:except` is the complement of `:only`: matching candidates are excluded.
### Returns
* `{:ok, unit}` where `unit` is a `t:t/0` with the parsed value.
* `{:error, exception}` if no number is found, the unit name is unknown, or the filters exclude every candidate.
### Examples
iex> Localize.Unit.parse("1kg")
Localize.Unit.new(1, "kilogram")
iex> Localize.Unit.parse("1 kilogram")
Localize.Unit.new(1, "kilogram")
iex> Localize.Unit.parse("2w", only: :duration)
Localize.Unit.new(2, "week")
iex> Localize.Unit.parse("2 Tage", locale: :de)
Localize.Unit.new(2, "day")
iex> {:error, %Localize.UnknownUnitError{}} = Localize.Unit.parse("1 blorb")
"""
@spec parse(String.t(), Keyword.t()) :: {:ok, t()} | {:error, Exception.t()}
def parse(unit_string, options \\ []) when is_binary(unit_string) and is_list(options) do
locale = Keyword.get(options, :locale, Localize.get_locale())
with {:ok, language_tag} <- Localize.validate_locale(locale),
{:ok, value, name_token} <- split_value_and_name(unit_string, language_tag),
{:ok, unit_name} <- resolve_unit_name(name_token, language_tag, options) do
new(value, unit_name)
end
end
@doc """
Same as `parse/2` but raises on error.
### Arguments
* `unit_string` is a string containing a number and a unit name.
* `options` is a keyword list of options. See `parse/2`.
### Returns
* A `t:t/0` with the parsed value.
### Raises
* Raises an exception if the string cannot be parsed.
### Examples
iex> Localize.Unit.parse!("1kg").name
"kilogram"
"""
@spec parse!(String.t(), Keyword.t()) :: t() | no_return()
def parse!(unit_string, options \\ []) do
case parse(unit_string, options) do
{:ok, unit} -> unit
{:error, exception} -> raise exception
end
end
@doc """
Parses a unit name string into its canonical unit identifier.
Like `parse/2` but for a bare unit name with no numeric value: `"kg"` resolves to `"kilogram"`. The same locale-aware matching and `:only`/`:except` disambiguation apply.
### Arguments
* `unit_name_string` is a unit name string (e.g., `"kg"`, `"kilograms"`, `"Tage"`).
* `options` is a keyword list of options. See `parse/2`.
### Returns
* `{:ok, unit_name}` where `unit_name` is the canonical unit identifier string.
* `{:error, exception}` if the name is unknown or the filters exclude every candidate.
### Examples
iex> Localize.Unit.parse_unit_name("kg")
{:ok, "kilogram"}
iex> Localize.Unit.parse_unit_name("w", only: :duration)
{:ok, "week"}
iex> Localize.Unit.parse_unit_name("Tage", locale: :de)
{:ok, "day"}
"""
@spec parse_unit_name(String.t(), Keyword.t()) ::
{:ok, String.t()} | {:error, Exception.t()}
def parse_unit_name(unit_name_string, options \\ [])
when is_binary(unit_name_string) and is_list(options) do
locale = Keyword.get(options, :locale, Localize.get_locale())
with {:ok, language_tag} <- Localize.validate_locale(locale) do
resolve_unit_name(unit_name_string, language_tag, options)
end
end
@doc """
Same as `parse_unit_name/2` but raises on error.
### Arguments
* `unit_name_string` is a unit name string.
* `options` is a keyword list of options. See `parse_unit_name/2`.
### Returns
* The canonical unit identifier string.
### Raises
* Raises an exception if the name cannot be resolved.
### Examples
iex> Localize.Unit.parse_unit_name!("kg")
"kilogram"
"""
@spec parse_unit_name!(String.t(), Keyword.t()) :: String.t() | no_return()
def parse_unit_name!(unit_name_string, options \\ []) do
case parse_unit_name(unit_name_string, options) do
{:ok, unit_name} -> unit_name
{:error, exception} -> raise exception
end
end
# The scan yields interleaved text and number tokens; a parseable
# unit string has exactly one number and one non-empty text token,
# in either order ("1kg", "kg 1").
defp split_value_and_name(unit_string, language_tag) do
tokens = Localize.Number.Parser.scan(unit_string, locale: language_tag)
numbers = Enum.filter(tokens, &is_number/1)
texts =
tokens |> Enum.filter(&is_binary/1) |> Enum.map(&String.trim/1) |> Enum.reject(&(&1 == ""))
case {numbers, texts} do
{[value], [name]} ->
{:ok, value, name}
_other ->
{:error,
Localize.InvalidValueError.exception(
value: unit_string,
expected: "a string containing one number and one unit name"
)}
end
end
defp resolve_unit_name(name_token, language_tag, options) do
with {:ok, locale_id} <- Localize.Locale.cldr_locale_id_from(language_tag) do
only = List.wrap(Keyword.get(options, :only, [])) |> Enum.map(&Kernel.to_string/1)
except = List.wrap(Keyword.get(options, :except, [])) |> Enum.map(&Kernel.to_string/1)
candidates =
name_token
|> Localize.Unit.NameIndex.candidates(locale_id)
|> apply_unit_filter(only, except)
case candidates do
[%{unit: unit} | _rest] ->
{:ok, unit}
[] ->
canonical_fallback(name_token, only, except)
end
end
end
defp apply_unit_filter(candidates, only, except) do
candidates
|> Enum.filter(fn candidate ->
only == [] or candidate.unit in only or candidate.category in only
end)
|> Enum.reject(fn candidate ->
candidate.unit in except or candidate.category in except
end)
end
# Compound identifiers such as "kilometer-per-hour" have no single
# display name; when the index misses, the canonical unit grammar
# is the fallback. The filters still apply — by name only, since a
# compound has no single category.
defp canonical_fallback(name_token, only, except) do
trimmed = String.trim(name_token)
case new(trimmed) do
{:ok, %__MODULE__{name: name}} ->
cond do
name in except ->
{:error, Localize.UnknownUnitError.exception(unit: trimmed)}
only != [] and name not in only ->
{:error, Localize.UnknownUnitError.exception(unit: trimmed)}
true ->
{:ok, name}
end
{:error, _} ->
{:error, Localize.UnknownUnitError.exception(unit: trimmed)}
end
end
@doc """
Converts a unit to a different target unit.
The source and target units must be convertible (same dimensional
base unit). Returns a new unit struct with the converted value and
the target unit type.
### Arguments
* `unit` is a `%Localize.Unit{}` struct with a value.
* `target` is the target unit identifier string (e.g., `"foot"`).
### Returns
* `{:ok, unit}` where `unit` is a new `%Localize.Unit{}` with
the converted value and target unit type, or
* `{:error, reason}` if the unit has no value, the target cannot
be parsed, or the units are not convertible.
### Value type
The converted value is a `Decimal` when the source value is a `Decimal`
(results stay exact) and a float otherwise. Integer and float values
both yield a float, because unit conversion is real-valued — an integer
input cannot represent a converted quantity such as `1` mile in
kilometers, so promoting to float is preferred over integer arithmetic,
which would silently lose precision. Pass a `Decimal` value when you
need an exact result.
### Examples
iex> {:ok, meters} = Localize.Unit.new(1, "kilometer")
iex> {:ok, result} = Localize.Unit.convert(meters, "meter")
iex> result.value
1000.0
iex> result.name
"meter"
iex> {:ok, tonnes} = Localize.Unit.new(Decimal.new(1), "tonne")
iex> {:ok, result} = Localize.Unit.convert(tonnes, "kilogram")
iex> match?(%Decimal{}, result.value)
true
"""
@spec convert(t(), String.t()) :: {:ok, t()} | {:error, Exception.t()}
def convert(%__MODULE__{value: nil}, _target) do
{:error, Localize.UnitNoValueError.exception(operation: :convert)}
end
def convert(%__MODULE__{} = source, target) when is_binary(target) do
with {:ok, target_parsed} <- Localize.Unit.Parser.parse(target) do
convert_parsed(source, target, target_parsed)
end
end
defp convert_parsed(source, target, {:mixed_unit, _units} = target_parsed) do
convert_to_mixed(source, target, target_parsed)
end
defp convert_parsed(%__MODULE__{value: value, name: from_name} = source, target, _target_parsed) do
{source_value, effective_from} = effective_source(value, from_name, source.parsed)
with {:ok, converted} <-
Localize.Unit.Conversion.convert(source_value, effective_from, target) do
new(converted, target)
end
end
# For mixed units, sum all component values into the primary (first) unit.
# For regular units, pass through unchanged.
defp effective_source(values, _name, {:mixed_unit, units}) when is_list(values) do
{:single_unit, first_opts} = hd(units)
first_name = format_single_unit_name(first_opts)
{mixed_to_scalar(values, first_name, {:mixed_unit, units}), first_name}
end
defp effective_source(value, name, _parsed), do: {value, name}
# The unit name conversions should be performed in: the first (primary)
# component for a mixed unit, otherwise the unit's own name. The scalar
# produced by `mixed_to_scalar/3` for a mixed unit is denominated in
# this first component, so conversions must use it rather than the
# mixed name (which `Conversion.convert/3` rejects with :mixed_units).
defp effective_source_name(_name, {:mixed_unit, units}) do
{:single_unit, first_opts} = hd(units)
format_single_unit_name(first_opts)
end
defp effective_source_name(name, _parsed), do: name
# Convert a scalar value from a source unit to a mixed target unit.
# For example, 180 centimeter → foot-and-inch = [5, 11.024...]
# Each component gets the integer part except the last which gets the remainder.
defp convert_to_mixed(source, _target_name, {:mixed_unit, target_units}) do
source_value = mixed_to_scalar(source.value, source.name, source.parsed)
effective_from = effective_source_name(source.name, source.parsed)
# Get the first target component name to check convertibility
{:single_unit, first_opts} = hd(target_units)
first_name = format_single_unit_name(first_opts)
with {:ok, full_in_first} <-
Localize.Unit.Conversion.convert(source_value, effective_from, first_name) do
values = distribute_mixed_values(full_in_first, target_units)
{canonical_name, canonical_ast} =
Localize.Unit.Canonical.canonicalize({:mixed_unit, target_units})
{:ok,
%__MODULE__{
name: canonical_name,
parsed: canonical_ast,
value: values
}}
end
end
# Distribute a value across mixed unit components.
# Each component except the last gets the integer (floor) part,
# and the remainder is converted to the next component.
defp distribute_mixed_values(value, [_last_unit]) do
[value]
end
defp distribute_mixed_values(value, [current_unit | rest]) do
integer_part = trunc(value)
remainder = value - integer_part
# Convert the remainder from the current unit to the next unit
{:single_unit, current_opts} = current_unit
{:single_unit, next_opts} = hd(rest)
current_name = format_single_unit_name(current_opts)
next_name = format_single_unit_name(next_opts)
case Localize.Unit.Conversion.convert(remainder, current_name, next_name) do
{:ok, remainder_in_next} ->
[integer_part | distribute_mixed_values(remainder_in_next, rest)]
{:error, _} ->
# If conversion fails, put the remainder in the current unit
[value]
end
end
# Convert a mixed unit value (list of values) to a single scalar
# in the unit's primary (first) component, for use as input to conversions.
defp mixed_to_scalar(values, _name, {:mixed_unit, units}) when is_list(values) do
{:single_unit, first_opts} = hd(units)
first_name = format_single_unit_name(first_opts)
values
|> Enum.zip(units)
|> Enum.reduce(0.0, fn {val, {:single_unit, opts}}, acc ->
component_name = format_single_unit_name(opts)
case Localize.Unit.Conversion.convert(val * 1.0, component_name, first_name) do
{:ok, converted} -> acc + converted
{:error, _} -> acc
end
end)
end
defp mixed_to_scalar(value, _name, _parsed) when is_number(value), do: value * 1.0
defp mixed_to_scalar(%Decimal{} = value, _name, _parsed), do: Decimal.to_float(value)
defp format_single_unit_name(opts) do
prefix = Keyword.get(opts, :prefix)
base = Keyword.get(opts, :base)
prefix_str = if prefix, do: Atom.to_string(prefix), else: ""
"#{prefix_str}#{base}"
end
@doc """
Converts a unit to a different target unit, raising on error.
Same as `convert/2` but returns the unit struct directly or raises
`ArgumentError`.
### Arguments
* `unit` is a `%Localize.Unit{}` struct with a value.
* `target` is the target unit identifier string.
### Returns
* A `%Localize.Unit{}` struct with the converted value.
### Examples
iex> unit = Localize.Unit.new!(1000, "meter")
iex> result = Localize.Unit.convert!(unit, "kilometer")
iex> result.value
1.0
"""
@spec convert!(t(), String.t()) :: t() | no_return()
@dialyzer {:nowarn_function, convert!: 2}
def convert!(%__MODULE__{} = unit, target) when is_binary(target) do
case convert(unit, target) do
{:ok, result} -> result
{:error, exception} -> raise exception
end
end
@doc """
Converts a unit to the preferred unit for a given measurement system.
Looks up the CLDR unit preference data for the unit's quantity
category and the specified measurement system, then converts to
the first preferred unit for the "default" usage.
### Arguments
* `unit` is a `%Localize.Unit{}` struct with a value.
* `system` is the target measurement system: `:metric`, `:us`, or `:uk`.
### Returns
* `{:ok, unit}` where `unit` is a new `%Localize.Unit{}` with the
converted value and the preferred unit for that system, or
* `{:error, reason}` if the unit has no value, the measurement
system is invalid, or no preference is found.
### Examples
iex> {:ok, meters} = Localize.Unit.new(100, "meter")
iex> {:ok, result} = Localize.Unit.convert_measurement_system(meters, :us)
iex> result.name
"mile"
"""
@spec convert_measurement_system(t(), :metric | :us | :uk) ::
{:ok, t()} | {:error, String.t()}
def convert_measurement_system(%__MODULE__{value: nil}, _system) do
{:error, Localize.UnitNoValueError.exception(operation: :convert)}
end
def convert_measurement_system(%__MODULE__{} = unit, system)
when system in [:metric, :us, :uk] do
usage = unit.usage || "default"
with {:ok, target_unit} <- preferred_unit(unit.name, system, usage) do
convert(unit, target_unit)
end
end
def convert_measurement_system(%__MODULE__{}, system) do
{:error,
Localize.InvalidValueError.exception(
value: system,
expected: ":metric, :us, or :uk",
context: "measurement system"
)}
end
# Measurement system to CLDR region code mapping.
@system_regions %{metric: "001", us: "US", uk: "GB"}
# Quantity names that differ between unitQuantity and unitPreferences.
@quantity_to_preference_category %{
"length" => "length",
"mass" => "mass",
"area" => "area",
"volume" => "volume",
"speed" => "speed",
"temperature" => "temperature",
"pressure" => "pressure",
"energy" => "energy",
"power" => "power",
"duration" => "duration",
"acceleration" => "acceleration",
"force" => "force",
"consumption" => "consumption",
"mass-density" => "mass-density",
"concentration" => "concentration",
"year-duration" => "year-duration"
}
defp preferred_unit(unit_name, system, usage) do
region = Map.fetch!(@system_regions, system)
with {:ok, base_unit} <- Localize.Unit.BaseUnit.base_unit(unit_name),
{:ok, quantity} <- lookup_quantity(base_unit),
{:ok, category} <- lookup_category(quantity) do
find_preference(category, region, usage)
end
end
defp lookup_quantity(base_unit) do
case Map.get(Localize.Unit.Data.base_unit_to_quantity(), base_unit) do
nil ->
{:error,
Localize.UnitPreferenceError.exception(
reason: :unknown_quantity,
unit: base_unit
)}
quantity ->
{:ok, quantity}
end
end
defp lookup_category(quantity) do
case Map.get(@quantity_to_preference_category, quantity) do
nil ->
{:error,
Localize.UnitPreferenceError.exception(
reason: :unknown_category,
quantity: quantity
)}
category ->
{:ok, category}
end
end
defp find_preference(category, region, usage) do
# Try the requested usage first, then fall back to "default"
case find_preference_for_usage(category, region, usage) do
{:ok, _} = result ->
result
{:error, _} when usage != "default" ->
find_preference_for_usage(category, region, "default")
error ->
error
end
end
defp find_preference_for_usage(category, region, usage) do
case Enum.find(
Localize.Unit.Data.unit_preferences(),
&(&1.category == category and &1.usage == usage)
) do
nil ->
{:error,
Localize.UnitPreferenceError.exception(
reason: :no_preference_for_usage,
category: category,
usage: usage
)}
%{preferences: preferences} ->
find_preference_for_region(preferences, category, region)
end
end
defp find_preference_for_region(preferences, category, region) do
case Enum.find(preferences, fn pref -> region in String.split(pref.regions) end) do
nil ->
{:error,
Localize.UnitPreferenceError.exception(
reason: :no_preference_for_region,
category: category,
region: region
)}
%{unit: unit} ->
{:ok, unit}
end
end
# Base units humanize/2 scales through the prefix ladder: the
# locale-invariant SI-prefixed quantities that CLDR's unit
# preference data does not cover. IEC binary prefixes are
# meaningful only for the digital bases.
@si_humanize_bases ~w(bit byte hertz watt)
@iec_humanize_bases ~w(bit byte)
# Prefix ladders for humanize/2, largest factor first so the first
# match is the prefix that scales the value into [1, 1000) or [1, 1024).
@si_humanize_prefixes ~w(kilo mega giga tera peta exa zetta yotta)
@iec_humanize_prefixes ~w(kibi mebi gibi tebi pebi exbi zebi yobi)
@si_humanize_ladder @si_humanize_prefixes
|> Enum.with_index(1)
|> Enum.map(fn {prefix, index} -> {prefix, Integer.pow(1000, index)} end)
|> Enum.reverse()
@iec_humanize_ladder @iec_humanize_prefixes
|> Enum.with_index(1)
|> Enum.map(fn {prefix, index} -> {prefix, Integer.pow(1024, index)} end)
|> Enum.reverse()
@doc """
Converts a bit-, byte-, hertz- or watt-based unit to the prefixed
unit that best fits its magnitude — human-readable file sizes,
frequencies and power figures.
Selects the largest SI prefix (kilobyte, megahertz, gigawatt, ...)
or, for bits and bytes, IEC binary prefix (kibibyte, mebibyte, ...)
such that the converted value is at least `1`. Values smaller than
one kilo-unit (or kibi-unit) are returned unchanged.
These bases are the locale-invariant SI-prefixed quantities that
CLDR's unit preference data does not cover. For physical
quantities such as length or mass, use the `:usage` option on
`to_string/2` instead — CLDR preferences pick the display unit by
territory and magnitude.
### Arguments
* `unit` is a `%Localize.Unit{}` struct with a value, based on
`"bit"`, `"byte"`, `"hertz"` or `"watt"` (a bare or
already-prefixed unit such as `"byte"`, `"kilobyte"` or
`"megahertz"`).
* `options` is a keyword list of options.
### Options
* `:system` is the prefix system to scale with: `:si` (powers of
1000, the default) or `:iec` (powers of 1024, bit- and
byte-based units only). Note that CLDR provides compact display
patterns (like `"MB"`) only for SI-prefixed units; IEC units
format with their full names in all format widths.
### Returns
* `{:ok, unit}` where `unit` is a new `%Localize.Unit{}` with the
scaled value and prefixed unit name, or
* `{:error, reason}` if the unit has no value, has an unsupported
base unit, or the prefix system is invalid or does not apply to
the base unit.
### Examples
iex> {:ok, unit} = Localize.Unit.new(1_500_000, "byte")
iex> {:ok, humanized} = Localize.Unit.humanize(unit)
iex> {humanized.name, humanized.value}
{"megabyte", 1.5}
iex> Localize.Unit.to_string(humanized, format: :narrow, locale: :en)
{:ok, "1.5MB"}
iex> {:ok, unit} = Localize.Unit.new(2_500_000_000, "hertz")
iex> {:ok, humanized} = Localize.Unit.humanize(unit)
iex> {humanized.name, humanized.value}
{"gigahertz", 2.5}
iex> {:ok, unit} = Localize.Unit.new(1_048_576, "byte")
iex> {:ok, humanized} = Localize.Unit.humanize(unit, system: :iec)
iex> {humanized.name, humanized.value}
{"mebibyte", 1.0}
"""
@spec humanize(t(), Keyword.t()) :: {:ok, t()} | {:error, Exception.t()}
def humanize(unit, options \\ [])
def humanize(%__MODULE__{value: nil}, _options) do
{:error, Localize.UnitNoValueError.exception(operation: :humanize)}
end
def humanize(%__MODULE__{} = unit, options) do
system = Keyword.get(options, :system, :si)
with :ok <- validate_prefix_system(system),
{:ok, base_name} <- humanizable_base_unit(unit),
:ok <- validate_system_for_base(system, base_name),
{:ok, base_unit} <- convert_unless_same(unit, base_name) do
target_name = humanized_unit_name(base_unit.value, system, base_name)
convert_unless_same(base_unit, target_name)
end
end
@doc """
Converts a bit-, byte-, hertz- or watt-based unit to the prefixed
unit that best fits its magnitude, raising on error.
See `humanize/2` for details.
### Arguments
* `unit` is a `%Localize.Unit{}` struct with a value, based on
`"bit"`, `"byte"`, `"hertz"` or `"watt"`.
* `options` is a keyword list of options. See `humanize/2`.
### Returns
* A new `%Localize.Unit{}` with the scaled value and prefixed
unit name, or
* raises an exception if the unit has no value, has an unsupported
base unit, or the prefix system is invalid.
### Examples
iex> Localize.Unit.new!(2_750_000_000, "byte")
...> |> Localize.Unit.humanize!()
...> |> Localize.Unit.to_string!(format: :narrow, fractional_digits: 1, locale: :en)
"2.8GB"
"""
@spec humanize!(t(), Keyword.t()) :: t() | no_return()
def humanize!(%__MODULE__{} = unit, options \\ []) do
case humanize(unit, options) do
{:ok, result} -> result
{:error, exception} -> raise exception
end
end
defp validate_prefix_system(system) when system in [:si, :iec], do: :ok
defp validate_prefix_system(system) do
{:error,
Localize.InvalidValueError.exception(
value: system,
expected: ":si or :iec",
context: "prefix system"
)}
end
defp validate_system_for_base(:iec, base_name) when base_name not in @iec_humanize_bases do
{:error,
Localize.InvalidValueError.exception(
value: base_name,
expected: "a bit- or byte-based unit when system: :iec"
)}
end