aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/libs/icu/i18n/messageformat2_function_registry.cpp
blob: 17955760ecfb443b94f34a6b49eb96dc3ff5c280 (plain) (blame)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
// © 2024 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html

#include "unicode/utypes.h"

#if !UCONFIG_NO_FORMATTING

#if !UCONFIG_NO_MF2

#include <math.h>

#include "unicode/dtptngen.h"
#include "unicode/messageformat2_data_model_names.h"
#include "unicode/messageformat2_function_registry.h"
#include "unicode/smpdtfmt.h"
#include "charstr.h"
#include "double-conversion.h"
#include "messageformat2_allocation.h"
#include "messageformat2_function_registry_internal.h"
#include "messageformat2_macros.h"
#include "hash.h"
#include "number_types.h"
#include "uvector.h" // U_ASSERT

// The C99 standard suggested that C++ implementations not define PRId64 etc. constants
// unless this macro is defined.
// See the Notes at https://en.cppreference.com/w/cpp/types/integer .
// Similar to defining __STDC_LIMIT_MACROS in unicode/ptypes.h .
#ifndef __STDC_FORMAT_MACROS
#   define __STDC_FORMAT_MACROS
#endif
#include <inttypes.h>
#include <math.h>

U_NAMESPACE_BEGIN

namespace message2 {

// Function registry implementation

Formatter::~Formatter() {}
Selector::~Selector() {}
FormatterFactory::~FormatterFactory() {}
SelectorFactory::~SelectorFactory() {}

MFFunctionRegistry MFFunctionRegistry::Builder::build() {
    U_ASSERT(formatters != nullptr && selectors != nullptr && formattersByType != nullptr);
    MFFunctionRegistry result = MFFunctionRegistry(formatters, selectors, formattersByType);
    formatters = nullptr;
    selectors = nullptr;
    formattersByType = nullptr;
    return result;
}

MFFunctionRegistry::Builder& MFFunctionRegistry::Builder::adoptSelector(const FunctionName& selectorName, SelectorFactory* selectorFactory, UErrorCode& errorCode) {
    if (U_SUCCESS(errorCode)) {
        U_ASSERT(selectors != nullptr);
        selectors->put(selectorName, selectorFactory, errorCode);
    }
    return *this;
}

MFFunctionRegistry::Builder& MFFunctionRegistry::Builder::adoptFormatter(const FunctionName& formatterName, FormatterFactory* formatterFactory, UErrorCode& errorCode) {
    if (U_SUCCESS(errorCode)) {
        U_ASSERT(formatters != nullptr);
        formatters->put(formatterName, formatterFactory, errorCode);
    }
    return *this;
}

MFFunctionRegistry::Builder& MFFunctionRegistry::Builder::setDefaultFormatterNameByType(const UnicodeString& type, const FunctionName& functionName, UErrorCode& errorCode) {
    if (U_SUCCESS(errorCode)) {
        U_ASSERT(formattersByType != nullptr);
        FunctionName* f = create<FunctionName>(FunctionName(functionName), errorCode);
        formattersByType->put(type, f, errorCode);
    }
    return *this;
}

MFFunctionRegistry::Builder::Builder(UErrorCode& errorCode) {
    CHECK_ERROR(errorCode);

    formatters = new Hashtable();
    selectors = new Hashtable();
    formattersByType = new Hashtable();
    if (!(formatters != nullptr && selectors != nullptr && formattersByType != nullptr)) {
        errorCode = U_MEMORY_ALLOCATION_ERROR;
    }
    formatters->setValueDeleter(uprv_deleteUObject);
    selectors->setValueDeleter(uprv_deleteUObject);
    formattersByType->setValueDeleter(uprv_deleteUObject);
}

MFFunctionRegistry::Builder::~Builder() {
    if (formatters != nullptr) {
        delete formatters;
    }
    if (selectors != nullptr) {
        delete selectors;
    }
    if (formattersByType != nullptr) {
        delete formattersByType;
    }
}

// Returns non-owned pointer. Returns pointer rather than reference because it can fail.
// Returns non-const because FormatterFactory is mutable.
// TODO: This is unsafe because of the cached-formatters map
// (the caller could delete the resulting pointer)
FormatterFactory* MFFunctionRegistry::getFormatter(const FunctionName& formatterName) const {
    U_ASSERT(formatters != nullptr);
    return static_cast<FormatterFactory*>(formatters->get(formatterName));
}

UBool MFFunctionRegistry::getDefaultFormatterNameByType(const UnicodeString& type, FunctionName& name) const {
    U_ASSERT(formatters != nullptr);
    const FunctionName* f = static_cast<FunctionName*>(formattersByType->get(type));
    if (f != nullptr) {
        name = *f;
        return true;
    }
    return false;
}

const SelectorFactory* MFFunctionRegistry::getSelector(const FunctionName& selectorName) const {
    U_ASSERT(selectors != nullptr);
    return static_cast<const SelectorFactory*>(selectors->get(selectorName));
}

bool MFFunctionRegistry::hasFormatter(const FunctionName& f) const {
    return getFormatter(f) != nullptr;
}

bool MFFunctionRegistry::hasSelector(const FunctionName& s) const {
    return getSelector(s) != nullptr;
}

void MFFunctionRegistry::checkFormatter(const char* s) const {
#if U_DEBUG
    U_ASSERT(hasFormatter(FunctionName(UnicodeString(s))));
#else
   (void) s;
#endif
}

void MFFunctionRegistry::checkSelector(const char* s) const {
#if U_DEBUG
    U_ASSERT(hasSelector(FunctionName(UnicodeString(s))));
#else
    (void) s;
#endif
}

// Debugging
void MFFunctionRegistry::checkStandard() const {
    checkFormatter("datetime");
    checkFormatter("date");
    checkFormatter("time");
    checkFormatter("number");
    checkFormatter("integer");
    checkSelector("number");
    checkSelector("integer");
    checkSelector("string");
}

// Formatter/selector helpers

// Converts `s` to a double, indicating failure via `errorCode`
static void strToDouble(const UnicodeString& s, double& result, UErrorCode& errorCode) {
    CHECK_ERROR(errorCode);

    // Using en-US locale because it happens to correspond to the spec:
    // https://github.com/unicode-org/message-format-wg/blob/main/spec/registry.md#number-operands
    // Ideally, this should re-use the code for parsing number literals (Parser::parseUnquotedLiteral())
    // It's hard to reuse the same code because of how parse errors work.
    // TODO: Refactor
    LocalPointer<NumberFormat> numberFormat(NumberFormat::createInstance(Locale("en-US"), errorCode));
    CHECK_ERROR(errorCode);
    icu::Formattable asNumber;
    numberFormat->parse(s, asNumber, errorCode);
    CHECK_ERROR(errorCode);
    result = asNumber.getDouble(errorCode);
}

static double tryStringAsNumber(const Locale& locale, const Formattable& val, UErrorCode& errorCode) {
    // Check for a string option, try to parse it as a number if present
    UnicodeString tempString = val.getString(errorCode);
    LocalPointer<NumberFormat> numberFormat(NumberFormat::createInstance(locale, errorCode));
    if (U_SUCCESS(errorCode)) {
        icu::Formattable asNumber;
        numberFormat->parse(tempString, asNumber, errorCode);
        if (U_SUCCESS(errorCode)) {
            return asNumber.getDouble(errorCode);
        }
    }
    return 0;
}

static int64_t getInt64Value(const Locale& locale, const Formattable& value, UErrorCode& errorCode) {
    if (U_SUCCESS(errorCode)) {
        if (!value.isNumeric()) {
            double doubleResult = tryStringAsNumber(locale, value, errorCode);
            if (U_SUCCESS(errorCode)) {
                return static_cast<int64_t>(doubleResult);
            }
        }
        else {
            int64_t result = value.getInt64(errorCode);
            if (U_SUCCESS(errorCode)) {
                return result;
            }
        }
    }
    // Option was numeric but couldn't be converted to int64_t -- could be overflow
    return 0;
}

// Adopts its arguments
MFFunctionRegistry::MFFunctionRegistry(FormatterMap* f, SelectorMap* s, Hashtable* byType) : formatters(f), selectors(s), formattersByType(byType) {
    U_ASSERT(f != nullptr && s != nullptr && byType != nullptr);
}

MFFunctionRegistry& MFFunctionRegistry::operator=(MFFunctionRegistry&& other) noexcept {
    cleanup();

    formatters = other.formatters;
    selectors = other.selectors;
    formattersByType = other.formattersByType;
    other.formatters = nullptr;
    other.selectors = nullptr;
    other.formattersByType = nullptr;

    return *this;
}

void MFFunctionRegistry::cleanup() noexcept {
    if (formatters != nullptr) {
        delete formatters;
    }
    if (selectors != nullptr) {
        delete selectors;
    }
    if (formattersByType != nullptr) {
        delete formattersByType;
    }
}


MFFunctionRegistry::~MFFunctionRegistry() {
    cleanup();
}

// Specific formatter implementations

// --------- Number

/* static */ number::LocalizedNumberFormatter StandardFunctions::formatterForOptions(const Number& number,
                                                                                     const FunctionOptions& opts,
                                                                                     UErrorCode& status) {
    number::UnlocalizedNumberFormatter nf;

    using namespace number;

    if (U_SUCCESS(status)) {
        Formattable opt;
        nf = NumberFormatter::with();
        bool isInteger = number.isInteger;

        if (isInteger) {
            nf = nf.precision(Precision::integer());
        }

        // Notation options
        if (!isInteger) {
            // These options only apply to `:number`

            // Default notation is simple
            Notation notation = Notation::simple();
            UnicodeString notationOpt = opts.getStringFunctionOption(UnicodeString("notation"));
            if (notationOpt == UnicodeString("scientific")) {
                notation = Notation::scientific();
            } else if (notationOpt == UnicodeString("engineering")) {
                notation = Notation::engineering();
            } else if (notationOpt == UnicodeString("compact")) {
                UnicodeString displayOpt = opts.getStringFunctionOption(UnicodeString("compactDisplay"));
                if (displayOpt == UnicodeString("long")) {
                    notation = Notation::compactLong();
                } else {
                    // Default is short
                    notation = Notation::compactShort();
                }
            } else {
                // Already set to default
            }
            nf = nf.notation(notation);
        }

        // Style options -- specific to `:number`
        if (!isInteger) {
            if (number.usePercent(opts)) {
                nf = nf.unit(NoUnit::percent()).scale(Scale::powerOfTen(2));
            }
        }

        int32_t maxSignificantDigits = number.maximumSignificantDigits(opts);
        if (!isInteger) {
            int32_t minFractionDigits = number.minimumFractionDigits(opts);
            int32_t maxFractionDigits = number.maximumFractionDigits(opts);
            int32_t minSignificantDigits = number.minimumSignificantDigits(opts);
            Precision p = Precision::unlimited();
            bool precisionOptions = false;

            // Returning -1 means the option wasn't provided
            if (maxFractionDigits != -1 && minFractionDigits != -1) {
                precisionOptions = true;
                p = Precision::minMaxFraction(minFractionDigits, maxFractionDigits);
            } else if (minFractionDigits != -1) {
                precisionOptions = true;
                p = Precision::minFraction(minFractionDigits);
            } else if (maxFractionDigits != -1) {
                precisionOptions = true;
                p = Precision::maxFraction(maxFractionDigits);
            }

            if (minSignificantDigits != -1) {
                precisionOptions = true;
                p = p.minSignificantDigits(minSignificantDigits);
            }
            if (maxSignificantDigits != -1) {
                precisionOptions = true;
                p = p.maxSignificantDigits(maxSignificantDigits);
            }
            if (precisionOptions) {
                nf = nf.precision(p);
            }
        } else {
            // maxSignificantDigits applies to `:integer`, but the other precision options don't
            Precision p = Precision::integer();
            if (maxSignificantDigits != -1) {
                p = p.maxSignificantDigits(maxSignificantDigits);
            }
            nf = nf.precision(p);
        }

        // All other options apply to both `:number` and `:integer`
        int32_t minIntegerDigits = number.minimumIntegerDigits(opts);
        nf = nf.integerWidth(IntegerWidth::zeroFillTo(minIntegerDigits));

        // signDisplay
        UnicodeString sd = opts.getStringFunctionOption(UnicodeString("signDisplay"));
        UNumberSignDisplay signDisplay;
        if (sd == UnicodeString("always")) {
            signDisplay = UNumberSignDisplay::UNUM_SIGN_ALWAYS;
        } else if (sd == UnicodeString("exceptZero")) {
            signDisplay = UNumberSignDisplay::UNUM_SIGN_EXCEPT_ZERO;
        } else if (sd == UnicodeString("negative")) {
            signDisplay = UNumberSignDisplay::UNUM_SIGN_NEGATIVE;
        } else if (sd == UnicodeString("never")) {
            signDisplay = UNumberSignDisplay::UNUM_SIGN_NEVER;
        } else {
            signDisplay = UNumberSignDisplay::UNUM_SIGN_AUTO;
        }
        nf = nf.sign(signDisplay);

        // useGrouping
        UnicodeString ug = opts.getStringFunctionOption(UnicodeString("useGrouping"));
        UNumberGroupingStrategy grp;
        if (ug == UnicodeString("always")) {
            grp = UNumberGroupingStrategy::UNUM_GROUPING_ON_ALIGNED;
        } else if (ug == UnicodeString("never")) {
            grp = UNumberGroupingStrategy::UNUM_GROUPING_OFF;
        } else if (ug == UnicodeString("min2")) {
            grp = UNumberGroupingStrategy::UNUM_GROUPING_MIN2;
        } else {
            // Default is "auto"
            grp = UNumberGroupingStrategy::UNUM_GROUPING_AUTO;
        }
        nf = nf.grouping(grp);

        // numberingSystem
        UnicodeString ns = opts.getStringFunctionOption(UnicodeString("numberingSystem"));
        if (ns.length() > 0) {
            ns = ns.toLower(Locale("en-US"));
            CharString buffer;
            // Ignore bad option values, so use a local status
            UErrorCode localStatus = U_ZERO_ERROR;
            // Copied from number_skeletons.cpp (helpers::parseNumberingSystemOption)
            buffer.appendInvariantChars({false, ns.getBuffer(), ns.length()}, localStatus);
            if (U_SUCCESS(localStatus)) {
                LocalPointer<NumberingSystem> symbols
                    (NumberingSystem::createInstanceByName(buffer.data(), localStatus));
                if (U_SUCCESS(localStatus)) {
                    nf = nf.adoptSymbols(symbols.orphan());
                }
            }
        }
    }
    return nf.locale(number.locale);
}

Formatter* StandardFunctions::NumberFactory::createFormatter(const Locale& locale, UErrorCode& errorCode) {
    NULL_ON_ERROR(errorCode);

    Formatter* result = new Number(locale);
    if (result == nullptr) {
        errorCode = U_MEMORY_ALLOCATION_ERROR;
    }
    return result;
}

Formatter* StandardFunctions::IntegerFactory::createFormatter(const Locale& locale, UErrorCode& errorCode) {
    NULL_ON_ERROR(errorCode);

    Formatter* result = new Number(Number::integer(locale));
    if (result == nullptr) {
        errorCode = U_MEMORY_ALLOCATION_ERROR;
    }
    return result;
}

StandardFunctions::IntegerFactory::~IntegerFactory() {}

static FormattedPlaceholder notANumber(const FormattedPlaceholder& input) {
    return FormattedPlaceholder(input, FormattedValue(UnicodeString("NaN")));
}

static double parseNumberLiteral(const FormattedPlaceholder& input, UErrorCode& errorCode) {
    if (U_FAILURE(errorCode)) {
        return {};
    }

    // Copying string to avoid GCC dangling-reference warning
    // (although the reference is safe)
    UnicodeString inputStr = input.asFormattable().getString(errorCode);
    // Precondition: `input`'s source Formattable has type string
    if (U_FAILURE(errorCode)) {
        return {};
    }

    // Hack: Check for cases that are forbidden by the MF2 grammar
    // but allowed by StringToDouble
    int32_t len = inputStr.length();

    if (len > 0 && ((inputStr[0] == '+')
                    || (inputStr[0] == '0' && len > 1 && inputStr[1] != '.')
                    || (inputStr[len - 1] == '.')
                    || (inputStr[0] == '.'))) {
        errorCode = U_MF_OPERAND_MISMATCH_ERROR;
        return 0;
    }

    // Otherwise, convert to double using double_conversion::StringToDoubleConverter
    using namespace double_conversion;
    int processedCharactersCount = 0;
    StringToDoubleConverter converter(0, 0, 0, "", "");
    double result =
        converter.StringToDouble(reinterpret_cast<const uint16_t*>(inputStr.getBuffer()),
                                 len,
                                 &processedCharactersCount);
    if (processedCharactersCount != len) {
        errorCode = U_MF_OPERAND_MISMATCH_ERROR;
    }
    return result;
}

static FormattedPlaceholder tryParsingNumberLiteral(const number::LocalizedNumberFormatter& nf, const FormattedPlaceholder& input, UErrorCode& errorCode) {
    double numberValue = parseNumberLiteral(input, errorCode);
    if (U_FAILURE(errorCode)) {
        return notANumber(input);
    }

    UErrorCode savedStatus = errorCode;
    number::FormattedNumber result = nf.formatDouble(numberValue, errorCode);
    // Ignore U_USING_DEFAULT_WARNING
    if (errorCode == U_USING_DEFAULT_WARNING) {
        errorCode = savedStatus;
    }
    return FormattedPlaceholder(input, FormattedValue(std::move(result)));
}

int32_t StandardFunctions::Number::maximumFractionDigits(const FunctionOptions& opts) const {
    Formattable opt;

    if (isInteger) {
        return 0;
    }

    if (opts.getFunctionOption(UnicodeString("maximumFractionDigits"), opt)) {
        UErrorCode localErrorCode = U_ZERO_ERROR;
        int64_t val = getInt64Value(locale, opt, localErrorCode);
        if (U_SUCCESS(localErrorCode)) {
            return static_cast<int32_t>(val);
        }
    }
    // Returning -1 indicates that the option wasn't provided or was a non-integer.
    // The caller needs to check for that case, since passing -1 to Precision::maxFraction()
    // is an error.
    return -1;
}

int32_t StandardFunctions::Number::minimumFractionDigits(const FunctionOptions& opts) const {
    Formattable opt;

    if (!isInteger) {
        if (opts.getFunctionOption(UnicodeString("minimumFractionDigits"), opt)) {
            UErrorCode localErrorCode = U_ZERO_ERROR;
            int64_t val = getInt64Value(locale, opt, localErrorCode);
            if (U_SUCCESS(localErrorCode)) {
                return static_cast<int32_t>(val);
            }
        }
    }
    // Returning -1 indicates that the option wasn't provided or was a non-integer.
    // The caller needs to check for that case, since passing -1 to Precision::minFraction()
    // is an error.
    return -1;
}

int32_t StandardFunctions::Number::minimumIntegerDigits(const FunctionOptions& opts) const {
    Formattable opt;

    if (opts.getFunctionOption(UnicodeString("minimumIntegerDigits"), opt)) {
        UErrorCode localErrorCode = U_ZERO_ERROR;
        int64_t val = getInt64Value(locale, opt, localErrorCode);
        if (U_SUCCESS(localErrorCode)) {
            return static_cast<int32_t>(val);
        }
    }
    return 0;
}

int32_t StandardFunctions::Number::minimumSignificantDigits(const FunctionOptions& opts) const {
    Formattable opt;

    if (!isInteger) {
        if (opts.getFunctionOption(UnicodeString("minimumSignificantDigits"), opt)) {
            UErrorCode localErrorCode = U_ZERO_ERROR;
            int64_t val = getInt64Value(locale, opt, localErrorCode);
            if (U_SUCCESS(localErrorCode)) {
                return static_cast<int32_t>(val);
            }
        }
    }
    // Returning -1 indicates that the option wasn't provided or was a non-integer.
    // The caller needs to check for that case, since passing -1 to Precision::minSignificantDigits()
    // is an error.
    return -1;
}

int32_t StandardFunctions::Number::maximumSignificantDigits(const FunctionOptions& opts) const {
    Formattable opt;

    if (opts.getFunctionOption(UnicodeString("maximumSignificantDigits"), opt)) {
        UErrorCode localErrorCode = U_ZERO_ERROR;
        int64_t val = getInt64Value(locale, opt, localErrorCode);
        if (U_SUCCESS(localErrorCode)) {
            return static_cast<int32_t>(val);
        }
    }
    // Returning -1 indicates that the option wasn't provided or was a non-integer.
    // The caller needs to check for that case, since passing -1 to Precision::maxSignificantDigits()
    // is an error.
    return -1; // Not a valid value for Precision; has to be checked
}

bool StandardFunctions::Number::usePercent(const FunctionOptions& opts) const {
    Formattable opt;
    if (isInteger
        || !opts.getFunctionOption(UnicodeString("style"), opt)
        || opt.getType() != UFMT_STRING) {
        return false;
    }
    UErrorCode localErrorCode = U_ZERO_ERROR;
    const UnicodeString& style = opt.getString(localErrorCode);
    U_ASSERT(U_SUCCESS(localErrorCode));
    return (style == UnicodeString("percent"));
}

/* static */ StandardFunctions::Number StandardFunctions::Number::integer(const Locale& loc) {
    return StandardFunctions::Number(loc, true);
}

FormattedPlaceholder StandardFunctions::Number::format(FormattedPlaceholder&& arg, FunctionOptions&& opts, UErrorCode& errorCode) const {
    if (U_FAILURE(errorCode)) {
        return {};
    }

    // No argument => return "NaN"
    if (!arg.canFormat()) {
        errorCode = U_MF_OPERAND_MISMATCH_ERROR;
        return notANumber(arg);
    }

    number::LocalizedNumberFormatter realFormatter;
    realFormatter = formatterForOptions(*this, opts, errorCode);

    number::FormattedNumber numberResult;
    if (U_SUCCESS(errorCode)) {
        // Already checked that contents can be formatted
        const Formattable& toFormat = arg.asFormattable();
        switch (toFormat.getType()) {
        case UFMT_DOUBLE: {
            double d = toFormat.getDouble(errorCode);
            U_ASSERT(U_SUCCESS(errorCode));
            numberResult = realFormatter.formatDouble(d, errorCode);
            break;
        }
        case UFMT_LONG: {
            int32_t l = toFormat.getLong(errorCode);
            U_ASSERT(U_SUCCESS(errorCode));
            numberResult = realFormatter.formatInt(l, errorCode);
            break;
        }
        case UFMT_INT64: {
            int64_t i = toFormat.getInt64(errorCode);
            U_ASSERT(U_SUCCESS(errorCode));
            numberResult = realFormatter.formatInt(i, errorCode);
            break;
        }
        case UFMT_STRING: {
            // Try to parse the string as a number
            return tryParsingNumberLiteral(realFormatter, arg, errorCode);
        }
        default: {
            // Other types can't be parsed as a number
            errorCode = U_MF_OPERAND_MISMATCH_ERROR;
            return notANumber(arg);
        }
        }
    }

    return FormattedPlaceholder(arg, FormattedValue(std::move(numberResult)));
}

StandardFunctions::Number::~Number() {}
StandardFunctions::NumberFactory::~NumberFactory() {}

// --------- PluralFactory


StandardFunctions::Plural::PluralType StandardFunctions::Plural::pluralType(const FunctionOptions& opts) const {
    Formattable opt;

    if (opts.getFunctionOption(UnicodeString("select"), opt)) {
        UErrorCode localErrorCode = U_ZERO_ERROR;
        UnicodeString val = opt.getString(localErrorCode);
        if (U_SUCCESS(localErrorCode)) {
            if (val == UnicodeString("ordinal")) {
                return PluralType::PLURAL_ORDINAL;
            }
            if (val == UnicodeString("exact")) {
                return PluralType::PLURAL_EXACT;
            }
        }
    }
    return PluralType::PLURAL_CARDINAL;
}

Selector* StandardFunctions::PluralFactory::createSelector(const Locale& locale, UErrorCode& errorCode) const {
    NULL_ON_ERROR(errorCode);

    Selector* result;
    if (isInteger) {
        result = new Plural(Plural::integer(locale, errorCode));
    } else {
        result = new Plural(locale, errorCode);
    }
    NULL_ON_ERROR(errorCode);
    if (result == nullptr) {
        errorCode = U_MEMORY_ALLOCATION_ERROR;
    }
    return result;
}

void StandardFunctions::Plural::selectKey(FormattedPlaceholder&& toFormat,
                                          FunctionOptions&& opts,
                                          const UnicodeString* keys,
                                          int32_t keysLen,
                                          UnicodeString* prefs,
                                          int32_t& prefsLen,
					  UErrorCode& errorCode) const {
    CHECK_ERROR(errorCode);

    // No argument => return "NaN"
    if (!toFormat.canFormat()) {
        errorCode = U_MF_SELECTOR_ERROR;
        return;
    }

    // Handle any formatting options
    PluralType type = pluralType(opts);
    FormattedPlaceholder resolvedSelector = numberFormatter->format(std::move(toFormat),
                                                                    std::move(opts),
                                                                    errorCode);
    CHECK_ERROR(errorCode);

    U_ASSERT(resolvedSelector.isEvaluated() && resolvedSelector.output().isNumber());

    // See  https://github.com/unicode-org/message-format-wg/blob/main/spec/registry.md#number-selection
    // 1. Let exact be the JSON string representation of the numeric value of resolvedSelector
    const number::FormattedNumber& formattedNumber = resolvedSelector.output().getNumber();
    UnicodeString exact = formattedNumber.toString(errorCode);

    if (U_FAILURE(errorCode)) {
        // Non-number => selector error
        errorCode = U_MF_SELECTOR_ERROR;
        return;
    }

    // Step 2. Let keyword be a string which is the result of rule selection on resolvedSelector.
    // If the option select is set to exact, rule-based selection is not used. Return the empty string.
    UnicodeString keyword;
    if (type != PluralType::PLURAL_EXACT) {
        UPluralType t = type == PluralType::PLURAL_ORDINAL ? UPLURAL_TYPE_ORDINAL : UPLURAL_TYPE_CARDINAL;
        // Look up plural rules by locale and type
        LocalPointer<PluralRules> rules(PluralRules::forLocale(locale, t, errorCode));
        CHECK_ERROR(errorCode);

        keyword = rules->select(formattedNumber, errorCode);
    }

    // Steps 3-4 elided:
    // 3. Let resultExact be a new empty list of strings.
    // 4. Let resultKeyword be a new empty list of strings.
    // Instead, we use `prefs` the concatenation of `resultExact`
    // and `resultKeyword`.

    prefsLen = 0;

    // 5. For each string key in keys:
    double keyAsDouble = 0;
    for (int32_t i = 0; i < keysLen; i++) {
        // Try parsing the key as a double
        UErrorCode localErrorCode = U_ZERO_ERROR;
        strToDouble(keys[i], keyAsDouble, localErrorCode);
        // 5i. If the value of key matches the production number-literal, then
        if (U_SUCCESS(localErrorCode)) {
            // 5i(a). If key and exact consist of the same sequence of Unicode code points, then
            if (exact == keys[i]) {
                // 5i(a)(a) Append key as the last element of the list resultExact.
		prefs[prefsLen] = keys[i];
                prefsLen++;
                break;
            }
        }
    }

    // Return immediately if exact matching was requested
    if (prefsLen == keysLen || type == PluralType::PLURAL_EXACT) {
        return;
    }


    for (int32_t i = 0; i < keysLen; i ++) {
        if (prefsLen >= keysLen) {
            break;
        }
        // 5ii. Else if key is one of the keywords zero, one, two, few, many, or other, then
        // 5ii(a). If key and keyword consist of the same sequence of Unicode code points, then
        if (keyword == keys[i]) {
            // 5ii(a)(a) Append key as the last element of the list resultKeyword.
            prefs[prefsLen] = keys[i];
            prefsLen++;
        }
    }

    // Note: Step 5(iii) "Else, emit a Selection Error" is omitted in both loops

    // 6. Return a new list whose elements are the concatenation of the elements
    // (in order) of resultExact followed by the elements (in order) of resultKeyword.
    // (Implicit, since `prefs` is an out-parameter)
}

StandardFunctions::Plural::Plural(const Locale& loc, UErrorCode& status) : locale(loc) {
    CHECK_ERROR(status);

    numberFormatter.adoptInstead(new StandardFunctions::Number(loc));
    if (!numberFormatter.isValid()) {
        status = U_MEMORY_ALLOCATION_ERROR;
    }
}

StandardFunctions::Plural::Plural(const Locale& loc, bool isInt, UErrorCode& status) : locale(loc), isInteger(isInt) {
    CHECK_ERROR(status);

    if (isInteger) {
        numberFormatter.adoptInstead(new StandardFunctions::Number(loc, true));
    } else {
        numberFormatter.adoptInstead(new StandardFunctions::Number(loc));
    }

    if (!numberFormatter.isValid()) {
        status = U_MEMORY_ALLOCATION_ERROR;
    }
}

StandardFunctions::Plural::~Plural() {}

StandardFunctions::PluralFactory::~PluralFactory() {}

// --------- DateTimeFactory

/* static */ UnicodeString StandardFunctions::getStringOption(const FunctionOptions& opts,
                                                              const UnicodeString& optionName,
                                                              UErrorCode& errorCode) {
    if (U_SUCCESS(errorCode)) {
        Formattable opt;
        if (opts.getFunctionOption(optionName, opt)) {
            return opt.getString(errorCode); // In case it's not a string, error code will be set
        } else {
            errorCode = U_ILLEGAL_ARGUMENT_ERROR;
        }
    }
    // Default is empty string
    return {};
}

// Date/time options only
static UnicodeString defaultForOption(const UnicodeString& optionName) {
    if (optionName == UnicodeString("dateStyle")
        || optionName == UnicodeString("timeStyle")
        || optionName == UnicodeString("style")) {
        return UnicodeString("short");
    }
    return {}; // Empty string is default
}

// TODO
// Only DateTime currently uses the function options stored in the placeholder.
// It also doesn't use them very consistently (it looks at the previous set of options,
// and others aren't preserved). This needs to be generalized,
// but that depends on https://github.com/unicode-org/message-format-wg/issues/515
// Finally, the option value is assumed to be a string,
// which works for datetime options but not necessarily in general.
UnicodeString StandardFunctions::DateTime::getFunctionOption(const FormattedPlaceholder& toFormat,
                                                             const FunctionOptions& opts,
                                                             const UnicodeString& optionName) const {
    // Options passed to the current function invocation take priority
    Formattable opt;
    UnicodeString s;
    UErrorCode localErrorCode = U_ZERO_ERROR;
    s = getStringOption(opts, optionName, localErrorCode);
    if (U_SUCCESS(localErrorCode)) {
        return s;
    }
    // Next try the set of options used to construct `toFormat`
    localErrorCode = U_ZERO_ERROR;
    s = getStringOption(toFormat.options(), optionName, localErrorCode);
    if (U_SUCCESS(localErrorCode)) {
        return s;
    }
    // Finally, use default
    return defaultForOption(optionName);
}

// Used for options that don't have defaults
UnicodeString StandardFunctions::DateTime::getFunctionOption(const FormattedPlaceholder& toFormat,
                                                             const FunctionOptions& opts,
                                                             const UnicodeString& optionName,
                                                             UErrorCode& errorCode) const {
    if (U_SUCCESS(errorCode)) {
        // Options passed to the current function invocation take priority
        Formattable opt;
        UnicodeString s;
        UErrorCode localErrorCode = U_ZERO_ERROR;
        s = getStringOption(opts, optionName, localErrorCode);
        if (U_SUCCESS(localErrorCode)) {
            return s;
        }
        // Next try the set of options used to construct `toFormat`
        localErrorCode = U_ZERO_ERROR;
        s = getStringOption(toFormat.options(), optionName, localErrorCode);
        if (U_SUCCESS(localErrorCode)) {
            return s;
        }
        errorCode = U_ILLEGAL_ARGUMENT_ERROR;
    }
    return {};
}

static DateFormat::EStyle stringToStyle(UnicodeString option, UErrorCode& errorCode) {
    if (U_SUCCESS(errorCode)) {
        UnicodeString upper = option.toUpper();
        if (upper == UnicodeString("FULL")) {
            return DateFormat::EStyle::kFull;
        }
        if (upper == UnicodeString("LONG")) {
            return DateFormat::EStyle::kLong;
        }
        if (upper == UnicodeString("MEDIUM")) {
            return DateFormat::EStyle::kMedium;
        }
        if (upper == UnicodeString("SHORT")) {
            return DateFormat::EStyle::kShort;
        }
        if (upper.isEmpty() || upper == UnicodeString("DEFAULT")) {
            return DateFormat::EStyle::kDefault;
        }
        errorCode = U_ILLEGAL_ARGUMENT_ERROR;
    }
    return DateFormat::EStyle::kNone;
}

/* static */ StandardFunctions::DateTimeFactory* StandardFunctions::DateTimeFactory::dateTime(UErrorCode& errorCode) {
    NULL_ON_ERROR(errorCode);

    DateTimeFactory* result = new StandardFunctions::DateTimeFactory(DateTimeType::DateTime);
    if (result == nullptr) {
        errorCode = U_MEMORY_ALLOCATION_ERROR;
    }
    return result;
}

/* static */ StandardFunctions::DateTimeFactory* StandardFunctions::DateTimeFactory::date(UErrorCode& errorCode) {
    NULL_ON_ERROR(errorCode);

    DateTimeFactory* result = new DateTimeFactory(DateTimeType::Date);
    if (result == nullptr) {
        errorCode = U_MEMORY_ALLOCATION_ERROR;
    }
    return result;
}

/* static */ StandardFunctions::DateTimeFactory* StandardFunctions::DateTimeFactory::time(UErrorCode& errorCode) {
    NULL_ON_ERROR(errorCode);

    DateTimeFactory* result = new DateTimeFactory(DateTimeType::Time);
    if (result == nullptr) {
        errorCode = U_MEMORY_ALLOCATION_ERROR;
    }
    return result;
}

Formatter* StandardFunctions::DateTimeFactory::createFormatter(const Locale& locale, UErrorCode& errorCode) {
    NULL_ON_ERROR(errorCode);

    Formatter* result = new StandardFunctions::DateTime(locale, type);
    if (result == nullptr) {
        errorCode = U_MEMORY_ALLOCATION_ERROR;
    }
    return result;
}

FormattedPlaceholder StandardFunctions::DateTime::format(FormattedPlaceholder&& toFormat,
                                                   FunctionOptions&& opts,
                                                   UErrorCode& errorCode) const {
    if (U_FAILURE(errorCode)) {
        return {};
    }

    // Argument must be present
    if (!toFormat.canFormat()) {
        errorCode = U_MF_OPERAND_MISMATCH_ERROR;
        return std::move(toFormat);
    }

    LocalPointer<DateFormat> df;
    Formattable opt;

    DateFormat::EStyle dateStyle = DateFormat::kShort;
    DateFormat::EStyle timeStyle = DateFormat::kShort;

    UnicodeString dateStyleName("dateStyle");
    UnicodeString timeStyleName("timeStyle");
    UnicodeString styleName("style");

    bool hasDateStyleOption = opts.getFunctionOption(dateStyleName, opt);
    bool hasTimeStyleOption = opts.getFunctionOption(timeStyleName, opt);
    bool noOptions = opts.optionsCount() == 0;

    bool useStyle = (type == DateTimeFactory::DateTimeType::DateTime
                     && (hasDateStyleOption || hasTimeStyleOption
                         || noOptions))
        || (type != DateTimeFactory::DateTimeType::DateTime);

    bool useDate = type == DateTimeFactory::DateTimeType::Date
        || (type == DateTimeFactory::DateTimeType::DateTime
            && hasDateStyleOption);
    bool useTime = type == DateTimeFactory::DateTimeType::Time
        || (type == DateTimeFactory::DateTimeType::DateTime
            && hasTimeStyleOption);

    if (useStyle) {
        // Extract style options
        if (type == DateTimeFactory::DateTimeType::DateTime) {
            // Note that the options-getting has to be repeated across the three cases,
            // since `:datetime` uses "dateStyle"/"timeStyle" and `:date` and `:time`
            // use "style"
            dateStyle = stringToStyle(getFunctionOption(toFormat, opts, dateStyleName), errorCode);
            timeStyle = stringToStyle(getFunctionOption(toFormat, opts, timeStyleName), errorCode);

            if (useDate && !useTime) {
                df.adoptInstead(DateFormat::createDateInstance(dateStyle, locale));
            } else if (useTime && !useDate) {
                df.adoptInstead(DateFormat::createTimeInstance(timeStyle, locale));
            } else {
                df.adoptInstead(DateFormat::createDateTimeInstance(dateStyle, timeStyle, locale));
            }
        } else if (type == DateTimeFactory::DateTimeType::Date) {
            dateStyle = stringToStyle(getFunctionOption(toFormat, opts, styleName), errorCode);
            df.adoptInstead(DateFormat::createDateInstance(dateStyle, locale));
        } else {
            // :time
            timeStyle = stringToStyle(getFunctionOption(toFormat, opts, styleName), errorCode);
            df.adoptInstead(DateFormat::createTimeInstance(timeStyle, locale));
        }
    } else {
        // Build up a skeleton based on the field options, then use that to
        // create the date formatter

        UnicodeString skeleton;
        #define ADD_PATTERN(s) skeleton += UnicodeString(s)
        if (U_SUCCESS(errorCode)) {
            // Year
            UnicodeString year = getFunctionOption(toFormat, opts, UnicodeString("year"), errorCode);
            if (U_FAILURE(errorCode)) {
                errorCode = U_ZERO_ERROR;
            } else {
                useDate = true;
                if (year == UnicodeString("2-digit")) {
                    ADD_PATTERN("YY");
                } else if (year == UnicodeString("numeric")) {
                    ADD_PATTERN("YYYY");
                }
            }
            // Month
            UnicodeString month = getFunctionOption(toFormat, opts, UnicodeString("month"), errorCode);
            if (U_FAILURE(errorCode)) {
                errorCode = U_ZERO_ERROR;
            } else {
                useDate = true;
                /* numeric, 2-digit, long, short, narrow */
                if (month == UnicodeString("long")) {
                    ADD_PATTERN("MMMM");
                } else if (month == UnicodeString("short")) {
                    ADD_PATTERN("MMM");
                } else if (month == UnicodeString("narrow")) {
                    ADD_PATTERN("MMMMM");
                } else if (month == UnicodeString("numeric")) {
                    ADD_PATTERN("M");
                } else if (month == UnicodeString("2-digit")) {
                    ADD_PATTERN("MM");
                }
            }
            // Weekday
            UnicodeString weekday = getFunctionOption(toFormat, opts, UnicodeString("weekday"), errorCode);
            if (U_FAILURE(errorCode)) {
                errorCode = U_ZERO_ERROR;
            } else {
                useDate = true;
                if (weekday == UnicodeString("long")) {
                    ADD_PATTERN("EEEE");
                } else if (weekday == UnicodeString("short")) {
                    ADD_PATTERN("EEEEE");
                } else if (weekday == UnicodeString("narrow")) {
                    ADD_PATTERN("EEEEE");
                }
            }
            // Day
            UnicodeString day = getFunctionOption(toFormat, opts, UnicodeString("day"), errorCode);
            if (U_FAILURE(errorCode)) {
                errorCode = U_ZERO_ERROR;
            } else {
                useDate = true;
                if (day == UnicodeString("numeric")) {
                    ADD_PATTERN("d");
                } else if (day == UnicodeString("2-digit")) {
                    ADD_PATTERN("dd");
                }
            }
            // Hour
            UnicodeString hour = getFunctionOption(toFormat, opts, UnicodeString("hour"), errorCode);
            if (U_FAILURE(errorCode)) {
                errorCode = U_ZERO_ERROR;
            } else {
                useTime = true;
                if (hour == UnicodeString("numeric")) {
                    ADD_PATTERN("h");
                } else if (hour == UnicodeString("2-digit")) {
                    ADD_PATTERN("hh");
                }
            }
            // Minute
            UnicodeString minute = getFunctionOption(toFormat, opts, UnicodeString("minute"), errorCode);
            if (U_FAILURE(errorCode)) {
                errorCode = U_ZERO_ERROR;
            } else {
                useTime = true;
                if (minute == UnicodeString("numeric")) {
                    ADD_PATTERN("m");
                } else if (minute == UnicodeString("2-digit")) {
                    ADD_PATTERN("mm");
                }
            }
            // Second
            UnicodeString second = getFunctionOption(toFormat, opts, UnicodeString("second"), errorCode);
            if (U_FAILURE(errorCode)) {
                errorCode = U_ZERO_ERROR;
            } else {
                useTime = true;
                if (second == UnicodeString("numeric")) {
                    ADD_PATTERN("s");
                } else if (second == UnicodeString("2-digit")) {
                    ADD_PATTERN("ss");
                }
            }
        }
        /*
          TODO
          fractionalSecondDigits
          hourCycle
          timeZoneName
          era
         */
        df.adoptInstead(DateFormat::createInstanceForSkeleton(skeleton, errorCode));
    }

    if (U_FAILURE(errorCode)) {
        return {};
    }
    if (!df.isValid()) {
        errorCode = U_MEMORY_ALLOCATION_ERROR;
        return {};
    }

    UnicodeString result;
    const Formattable& source = toFormat.asFormattable();
    switch (source.getType()) {
    case UFMT_STRING: {
        const UnicodeString& sourceStr = source.getString(errorCode);
        U_ASSERT(U_SUCCESS(errorCode));
        // Pattern for ISO 8601 format - datetime
        UnicodeString pattern("YYYY-MM-dd'T'HH:mm:ss");
        LocalPointer<DateFormat> dateParser(new SimpleDateFormat(pattern, errorCode));
        if (U_FAILURE(errorCode)) {
            errorCode = U_MF_FORMATTING_ERROR;
        } else {
            // Parse the date
            UDate d = dateParser->parse(sourceStr, errorCode);
            if (U_FAILURE(errorCode)) {
                // Pattern for ISO 8601 format - date
                UnicodeString pattern("YYYY-MM-dd");
                errorCode = U_ZERO_ERROR;
                dateParser.adoptInstead(new SimpleDateFormat(pattern, errorCode));
                if (U_FAILURE(errorCode)) {
                    errorCode = U_MF_FORMATTING_ERROR;
                } else {
                    d = dateParser->parse(sourceStr, errorCode);
                    if (U_FAILURE(errorCode)) {
                        errorCode = U_MF_OPERAND_MISMATCH_ERROR;
                    }
                }
            }
            // Use the parsed date as the source value
            // in the returned FormattedPlaceholder; this is necessary
            // so the date can be re-formatted
            toFormat = FormattedPlaceholder(message2::Formattable::forDate(d),
                                            toFormat.getFallback());
            df->format(d, result, 0, errorCode);
        }
        break;
    }
    case UFMT_DATE: {
        df->format(source.asICUFormattable(errorCode), result, 0, errorCode);
        if (U_FAILURE(errorCode)) {
            if (errorCode == U_ILLEGAL_ARGUMENT_ERROR) {
                errorCode = U_MF_OPERAND_MISMATCH_ERROR;
            }
        }
        break;
    }
    // Any other cases are an error
    default: {
        errorCode = U_MF_OPERAND_MISMATCH_ERROR;
        break;
    }
    }
    if (U_FAILURE(errorCode)) {
        return {};
    }
    return FormattedPlaceholder(toFormat, std::move(opts), FormattedValue(std::move(result)));
}

StandardFunctions::DateTimeFactory::~DateTimeFactory() {}
StandardFunctions::DateTime::~DateTime() {}

// --------- TextFactory

Selector* StandardFunctions::TextFactory::createSelector(const Locale& locale, UErrorCode& errorCode) const {
    Selector* result = new TextSelector(locale);
    if (result == nullptr) {
        errorCode = U_MEMORY_ALLOCATION_ERROR;
        return nullptr;
    }
    return result;
}

void StandardFunctions::TextSelector::selectKey(FormattedPlaceholder&& toFormat,
                                                FunctionOptions&& opts,
                                                const UnicodeString* keys,
                                                int32_t keysLen,
                                                UnicodeString* prefs,
                                                int32_t& prefsLen,
						UErrorCode& errorCode) const {
    // No options
    (void) opts;

    CHECK_ERROR(errorCode);

    // Just compares the key and value as strings

    // Argument must be present
    if (!toFormat.canFormat()) {
        errorCode = U_MF_SELECTOR_ERROR;
        return;
    }

    prefsLen = 0;

    // Convert to string
    const UnicodeString& formattedValue = toFormat.formatToString(locale, errorCode);
    if (U_FAILURE(errorCode)) {
        return;
    }

    for (int32_t i = 0; i < keysLen; i++) {
        if (keys[i] == formattedValue) {
	    prefs[0] = keys[i];
            prefsLen = 1;
            break;
        }
    }
}

StandardFunctions::TextFactory::~TextFactory() {}
StandardFunctions::TextSelector::~TextSelector() {}

} // namespace message2
U_NAMESPACE_END

#endif /* #if !UCONFIG_NO_MF2 */

#endif /* #if !UCONFIG_NO_FORMATTING */