open62541-sys 0.6.1

Low-level, unsafe bindings for the C11 library open62541, an open source and free implementation of OPC UA (OPC Unified Architecture).
Documentation
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
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 *    Copyright 2020 (c) Fraunhofer IOSB (Author: Andreas Ebner)
 *    Copyright 2014-2017 (c) Fraunhofer IOSB (Author: Julius Pfrommer)
 *    Copyright 2014, 2016-2017 (c) Florian Palm
 *    Copyright 2014-2016 (c) Sten Grüner
 *    Copyright 2014 (c) Leon Urbas
 *    Copyright 2015 (c) Chris Iatrou
 *    Copyright 2015 (c) Markus Graube
 *    Copyright 2015 (c) Reza Ebrahimi
 *    Copyright 2015-2016 (c) Oleksiy Vasylyev
 *    Copyright 2017 (c) Stefan Profanter, fortiss GmbH
 *    Copyright 2016 (c) Lorenz Haas
 */

#include <open62541/types.h>
#include <open62541/types_generated.h>

#include "parse_num.h"
#include "util/ua_util_internal.h"
#include "../deps/itoa.h"
#include "../deps/base64.h"
#include "../deps/libc_time.h"
#include "../deps/mp_printf.h"

#define UA_MAX_ARRAY_DIMS 100 /* Max dimensions of an array */

/* Datatype Handling
 * -----------------
 * This file contains handling functions for the builtin types and functions
 * handling of structured types and arrays. These need type descriptions in a
 * UA_DataType structure. The UA_DataType structures as well as all non-builtin
 * datatypes are autogenerated. */

/* Global definition of NULL type instances. These are always zeroed out, as
 * mandated by the C/C++ standard for global values with no initializer. */
const UA_String UA_STRING_NULL = {0, NULL};
const UA_ByteString UA_BYTESTRING_NULL = {0, NULL};
const UA_Guid UA_GUID_NULL = {0, 0, 0, {0,0,0,0,0,0,0,0}};
const UA_NodeId UA_NODEID_NULL = {0, UA_NODEIDTYPE_NUMERIC, {0}};
const UA_ExpandedNodeId UA_EXPANDEDNODEID_NULL = {{0, UA_NODEIDTYPE_NUMERIC, {0}}, {0, NULL}, 0};

typedef UA_StatusCode
(*UA_copySignature)(const void *src, void *dst, const UA_DataType *type);
extern const UA_copySignature copyJumpTable[UA_DATATYPEKINDS];

typedef void (*UA_clearSignature)(void *p, const UA_DataType *type);
extern const UA_clearSignature clearJumpTable[UA_DATATYPEKINDS];

typedef UA_Order
(*UA_orderSignature)(const void *p1, const void *p2, const UA_DataType *type);
extern const UA_orderSignature orderJumpTable[UA_DATATYPEKINDS];

static UA_Order
nodeIdOrder(const UA_NodeId *p1, const UA_NodeId *p2, const UA_DataType *_);
static UA_Order
expandedNodeIdOrder(const UA_ExpandedNodeId *p1, const UA_ExpandedNodeId *p2,
                    const UA_DataType *_);
static UA_Order
guidOrder(const UA_Guid *p1, const UA_Guid *p2, const UA_DataType *_);

const UA_DataType *
UA_findDataTypeWithCustom(const UA_NodeId *typeId,
                          const UA_DataTypeArray *customTypes) {
    /* Always look in built-in types first (may contain data types from all
     * namespaces).
     *
     * TODO: The standard-defined types are ordered. See if binary search is
     * more efficient. */
    for(size_t i = 0; i < UA_TYPES_COUNT; ++i) {
        if(nodeIdOrder(&UA_TYPES[i].typeId, typeId, NULL) == UA_ORDER_EQ)
            return &UA_TYPES[i];
    }

    /* Search in the customTypes */
    while(customTypes) {
        for(size_t i = 0; i < customTypes->typesSize; ++i) {
            if(nodeIdOrder(&customTypes->types[i].typeId, typeId, NULL) == UA_ORDER_EQ)
                return &customTypes->types[i];
        }
        customTypes = customTypes->next;
    }

    return NULL;
}

const UA_DataType *
UA_findDataType(const UA_NodeId *typeId) {
    return UA_findDataTypeWithCustom(typeId, NULL);
}

#ifdef UA_ENABLE_TYPEDESCRIPTION
const UA_DataType *
UA_findDataTypeByName(const UA_QualifiedName *qn) {
    UA_Byte nameBuf[512];
    UA_String name = {511, nameBuf};
    UA_StatusCode res = UA_QualifiedName_print(qn, &name);
    name.data[name.length] = 0;
    if(res != UA_STATUSCODE_GOOD)
        return NULL;
    for(size_t i = 0; i < UA_TYPES_COUNT; ++i) {
        if(strcmp((char*)nameBuf, UA_TYPES[i].typeName) == 0)
            return &UA_TYPES[i];
    }
    return NULL;
}
#endif

void
UA_DataType_clear(UA_DataType *type) {
#ifdef UA_ENABLE_TYPEDESCRIPTION
    UA_free((void*)(uintptr_t)type->typeName);
    for(size_t j = 0; j < type->membersSize; ++j) {
        UA_DataTypeMember *m = &type->members[j];
        UA_free((void*)(uintptr_t)m->memberName);
    }
#endif
    UA_NodeId_clear(&type->typeId);
    UA_NodeId_clear(&type->binaryEncodingId);
    UA_NodeId_clear(&type->xmlEncodingId);
    UA_free(type->members);
    memset(type, 0, sizeof(UA_DataType));
}

UA_StatusCode
UA_DataType_copy(const UA_DataType *t1, UA_DataType *t2) {
    UA_StatusCode res = UA_STATUSCODE_GOOD;
    memcpy(t2, t1, sizeof(UA_DataType));
    t2->members = NULL;
    t2->membersSize = 0;

    /* Copy the typename */
#ifdef UA_ENABLE_TYPEDESCRIPTION
    size_t nameLen = strlen(t1->typeName) + 1;
    char *t2Name = (char*)UA_malloc(nameLen);
    if(!t2Name) {
        res = UA_STATUSCODE_BADOUTOFMEMORY;
        goto errout;
    }
    memcpy(t2Name, t1->typeName, nameLen);
    *(void**)(uintptr_t)&t2->typeName = t2Name;
#endif


    /* Copy the members */
    if(t1->membersSize > 0) {
        t2->members = (UA_DataTypeMember*)
            UA_calloc(t1->membersSize, sizeof(UA_DataTypeMember));
        if(!t2->members) {
            res = UA_STATUSCODE_BADOUTOFMEMORY;
            goto errout;
        }
        for(size_t i = 0; i < t1->membersSize; i++) {
            const UA_DataTypeMember *m1 = &t1->members[i];
            UA_DataTypeMember *m2 = &t2->members[i];
            memcpy(m2, m1, sizeof(UA_DataTypeMember));
#ifdef UA_ENABLE_TYPEDESCRIPTION
            nameLen = strlen(m1->memberName) + 1;
            char *mName = (char*)UA_malloc(nameLen);
            if(!mName) {
                res = UA_STATUSCODE_BADOUTOFMEMORY;
                goto errout;
            }
            memcpy(mName, m1->memberName, nameLen);
            *(void**)(uintptr_t)&m2->memberName = mName;
#endif
        }
        t2->membersSize = t1->membersSize;
    }

 errout:
    if(res != UA_STATUSCODE_GOOD)
        UA_DataType_clear(t2);
    return res;
}

void
UA_cleanupDataTypeWithCustom(UA_DataTypeArray *customTypes) {
    while(customTypes) {
        UA_DataTypeArray *next = customTypes->next;
        if(customTypes->cleanup) {
            for(size_t i = 0; i < customTypes->typesSize; ++i) {
                UA_DataType *type = &customTypes->types[i];
                UA_DataType_clear(type);
            }
            UA_free(customTypes->types);
            UA_free(customTypes);
        }
        customTypes = next;
    }
}

/*****************/
/* Builtin Types */
/*****************/

UA_Boolean
UA_StatusCode_isBad(UA_StatusCode code) {
    return ((code >> 30) >= 0x02);
}

UA_Boolean
UA_StatusCode_isUncertain(UA_StatusCode code) {
    return ((code >> 30) == 0x01);
}

UA_Boolean
UA_StatusCode_isGood(UA_StatusCode code) {
    return ((code >> 30) == 0x00);
}

UA_Boolean
UA_StatusCode_equalTop(UA_StatusCode s1, UA_StatusCode s2) {
    return ((s1 & 0xFFFF0000) == (s2 & 0xFFFF0000));
}

UA_String
UA_STRING(char *chars) {
    UA_String s = {0, NULL};
    if(!chars)
        return s;
    s.length = strlen(chars);
    s.data = (UA_Byte*)chars;
    return s;
}

UA_String
UA_String_fromChars(const char *src) {
    UA_String s; s.length = 0; s.data = NULL;
    if(!src)
        return s;
    s.length = strlen(src);
    if(s.length > 0) {
        s.data = (u8*)UA_malloc(s.length);
        if(UA_UNLIKELY(!s.data)) {
            s.length = 0;
            return s;
        }
        memcpy(s.data, src, s.length);
    } else {
        s.data = (u8*)UA_EMPTY_ARRAY_SENTINEL;
    }
    return s;
}

UA_Boolean
UA_String_isEmpty(const UA_String *s) {
    return (s->length == 0 || s->data == NULL);
}

static UA_Byte
lowercase(UA_Byte c) {
    if(((int)c) - 'A' < 26) return c | 32;
    return c;
}

static int
casecmp(const UA_Byte *l, const UA_Byte *r, size_t n) {
    if(!n--) return 0;
    for(; *l && *r && n && (*l == *r || lowercase(*l) == lowercase(*r)); l++, r++, n--);
    return lowercase(*l) - lowercase(*r);
}

/* Do not expose UA_String_equal_ignorecase to public API as it currently only handles
 * ASCII strings, and not UTF8! */
UA_Boolean
UA_String_equal_ignorecase(const UA_String *s1, const UA_String *s2) {
    if(s1->length != s2->length)
        return false;
    if(s1->length == 0)
        return true;
    if(s2->data == NULL)
        return false;

    return casecmp(s1->data, s2->data, s1->length) == 0;
}

static UA_StatusCode
String_copy(const void *src, void *dst, const UA_DataType *_) {
    const UA_String *srcS = (const UA_String*)src;
    UA_String *dstS = (UA_String *)dst;
    UA_StatusCode res =
        UA_Array_copy(srcS->data, srcS->length, (void**)&dstS->data,
                      &UA_TYPES[UA_TYPES_BYTE]);
    if(res == UA_STATUSCODE_GOOD)
        dstS->length = srcS->length;
    return res;
}

static void
String_clear(void *p, const UA_DataType *_) {
    UA_String *s = (UA_String*)p;
    UA_Array_delete(s->data, s->length, &UA_TYPES[UA_TYPES_BYTE]);
}

UA_StatusCode
UA_String_append(UA_String *s, const UA_String s2) {
    if(s2.length == 0)
        return UA_STATUSCODE_GOOD;
    UA_Byte *buf = (UA_Byte*)UA_realloc(s->data, s->length + s2.length);
    if(!buf)
        return UA_STATUSCODE_BADOUTOFMEMORY;
    memcpy(buf + s->length, s2.data, s2.length);
    s->data = buf;
    s->length += s2.length;
    return UA_STATUSCODE_GOOD;
}

UA_StatusCode
UA_String_format(UA_String *str, const char *format, ...) {
    va_list args;
    va_start(args, format);
    UA_StatusCode ret = UA_String_vprintf(str, format, args);
    va_end(args);
    return ret;
}

UA_StatusCode
UA_String_vformat(UA_String *str, const char *format, va_list args) {
    /* Store a copy of the arguments for the second pass. va_list cannot be
     * iterated twice. */
    va_list args2;
    va_copy(args2, args);

    /* Encode initially */
    UA_StatusCode res = UA_STATUSCODE_GOOD;
    int out = mp_vsnprintf((char*)str->data, str->length, format, args);
    if(out < 0) {
        res = UA_STATUSCODE_BADENCODINGERROR;
        goto errout;
    }

    /* Output length zero */
    if(out == 0) {
        str->length = 0;
        if(str->data == NULL)
            str->data = (UA_Byte*)UA_EMPTY_ARRAY_SENTINEL;
        goto errout;
    }

    /* Encode into existing buffer. mp_snprintf adds a trailing \0. So out must
     * be truly smaller than str->length for success. */
    if(str->length > 0) {
        if((size_t)out < str->length) {
            str->length = (size_t)out;
        } else {
            res = UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED;
        }
        goto errout;
    }

    /* Allocate and encode again (+1 length for the trailing \0) */
    res = UA_ByteString_allocBuffer(str, (size_t)out + 1);
    if(res != UA_STATUSCODE_GOOD)
        goto errout;
    mp_vsnprintf((char*)str->data, str->length, format, args2);
    str->length--;

 errout:
    va_end(args2);
    return res;
}

/* QualifiedName */
UA_Boolean
UA_QualifiedName_isNull(const UA_QualifiedName *q) {
    return (q->namespaceIndex == 0 && q->name.length == 0);
}

UA_QualifiedName
UA_QUALIFIEDNAME(UA_UInt16 nsIndex, char *chars) {
    UA_QualifiedName qn;
    qn.namespaceIndex = nsIndex;
    qn.name = UA_STRING(chars);
    return qn;
}

UA_QualifiedName
UA_QUALIFIEDNAME_ALLOC(UA_UInt16 nsIndex, const char *chars) {
    UA_QualifiedName qn;
    qn.namespaceIndex = nsIndex;
    qn.name = UA_STRING_ALLOC(chars);
    return qn;
}

static UA_StatusCode
QualifiedName_copy(const void *src, void *dst, const UA_DataType *_) {
    const UA_QualifiedName *srcQ = (const UA_QualifiedName*)src;
    UA_QualifiedName *dstQ = (UA_QualifiedName*)dst;
    dstQ->namespaceIndex = srcQ->namespaceIndex;
    return String_copy(&srcQ->name, &dstQ->name, NULL);
}

static void
QualifiedName_clear(void *p, const UA_DataType *_) {
    UA_QualifiedName *qn = (UA_QualifiedName*)p;
    String_clear(&qn->name, NULL);
}

u32
UA_QualifiedName_hash(const UA_QualifiedName *q) {
    return UA_ByteString_hash(q->namespaceIndex,
                              q->name.data, q->name.length);
}

UA_StatusCode
UA_QualifiedName_printEx(const UA_QualifiedName *qn, UA_String *output,
                         const UA_NamespaceMapping *nsMapping) {
    /* Start tracking the output length */
    size_t len = qn->name.length;

    /* Try to map the NamespaceIndex to the Uri */
    UA_String nsUri = UA_STRING_NULL;
    if(qn->namespaceIndex > 0 && nsMapping) {
        UA_NamespaceMapping_index2Uri(nsMapping, qn->namespaceIndex, &nsUri);
        if(nsUri.length > 0)
            len += nsUri.length + 1;
    }

    /* Print the NamespaceIndex */
    char nsStr[6];
    size_t nsStrSize = 0;
    if(nsUri.length == 0 && qn->namespaceIndex > 0) {
        nsStrSize = itoaUnsigned(qn->namespaceIndex, nsStr, 10);
        len += 1 + nsStrSize;
    }

    /* Allocate memory if required */
    if(output->length == 0) {
        UA_StatusCode res = UA_ByteString_allocBuffer((UA_ByteString*)output, len);
        if(res != UA_STATUSCODE_GOOD)
            return res;
    } else {
        if(output->length < len)
            return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED;
        output->length = len;
    }

    /* Print the namespace */
    u8 *pos = output->data;
    if(nsUri.length > 0) {
        memcpy(pos, nsUri.data, nsUri.length);
        pos += nsUri.length;
        *pos++ = ';';
    } else if(qn->namespaceIndex > 0) {
        memcpy(pos, nsStr, nsStrSize);
        pos += nsStrSize;
        *pos++ = ':';
    }

    /* Print the name */
    if(UA_LIKELY(qn->name.data != NULL))
        memcpy(pos, qn->name.data, qn->name.length);

    UA_assert(output->length == (size_t)((UA_Byte*)pos + qn->name.length - output->data));
    return UA_STATUSCODE_GOOD;
}

UA_StatusCode
UA_QualifiedName_print(const UA_QualifiedName *qn, UA_String *output) {
    return UA_QualifiedName_printEx(qn, output, NULL);
}

/* DateTime */
UA_Int64
UA_DateTime_toUnixTime(UA_DateTime date) {
    return (date - UA_DATETIME_UNIX_EPOCH) / UA_DATETIME_SEC;
}

UA_DateTime
UA_DateTime_fromUnixTime(UA_Int64 unixDate) {
    return (unixDate * UA_DATETIME_SEC) + UA_DATETIME_UNIX_EPOCH;
}

UA_DateTimeStruct
UA_DateTime_toStruct(UA_DateTime t) {
    /* Divide, then subtract -> avoid underflow. Also, negative numbers are
     * rounded up, not down. */
    long long secSinceUnixEpoch = (long long)(t / UA_DATETIME_SEC)
        - (long long)(UA_DATETIME_UNIX_EPOCH / UA_DATETIME_SEC);

    /* Negative fractions of a second? Remove one full second from the epoch
     * distance and allow only a positive fraction. */
    UA_DateTime frac = t % UA_DATETIME_SEC;
    if(frac < 0) {
        secSinceUnixEpoch--;
        frac += UA_DATETIME_SEC;
    }

    struct musl_tm ts;
    memset(&ts, 0, sizeof(struct musl_tm));
    musl_secs_to_tm(secSinceUnixEpoch, &ts);

    UA_DateTimeStruct dateTimeStruct;
    dateTimeStruct.year   = (i16)(ts.tm_year + 1900);
    dateTimeStruct.month  = (u16)(ts.tm_mon + 1);
    dateTimeStruct.day    = (u16)ts.tm_mday;
    dateTimeStruct.hour   = (u16)ts.tm_hour;
    dateTimeStruct.min    = (u16)ts.tm_min;
    dateTimeStruct.sec    = (u16)ts.tm_sec;
    dateTimeStruct.milliSec = (u16)((frac % 10000000) / 10000);
    dateTimeStruct.microSec = (u16)((frac % 10000) / 10);
    dateTimeStruct.nanoSec  = (u16)((frac % 10) * 100);
    return dateTimeStruct;
}

UA_DateTime
UA_DateTime_fromStruct(UA_DateTimeStruct ts) {
    /* Seconds since the Unix epoch */
    struct musl_tm tm;
    memset(&tm, 0, sizeof(struct musl_tm));
    tm.tm_year = ts.year - 1900;
    tm.tm_mon = ts.month - 1;
    tm.tm_mday = ts.day;
    tm.tm_hour = ts.hour;
    tm.tm_min = ts.min;
    tm.tm_sec = ts.sec;
    long long sec_epoch = musl_tm_to_secs(&tm);

    UA_DateTime t = UA_DATETIME_UNIX_EPOCH;
    t += sec_epoch * UA_DATETIME_SEC;
    t += ts.milliSec * UA_DATETIME_MSEC;
    t += ts.microSec * UA_DATETIME_USEC;
    t += ts.nanoSec / 100;
    return t;
}

UA_StatusCode
UA_DateTime_parse(UA_DateTime *dst, const UA_String str) {
    if(str.length == 0)
        return UA_STATUSCODE_BADDECODINGERROR;

    struct musl_tm dts;
    memset(&dts, 0, sizeof(dts));

    /* Parse the year. The ISO standard asks for four digits. But we accept up
     * to five with an optional plus or minus in front due to the range of the
     * DateTime 64bit integer. But in that case we require the year and the
     * month to be separated by a '-'. Otherwise we cannot know where the month
     * starts. */
    size_t pos = 0;
    if(str.data[0] == '-' || str.data[0] == '+')
        pos++;
    UA_Int64 year = 0;
    UA_CHECK(str.length - pos > 5, return UA_STATUSCODE_BADDECODINGERROR);
    size_t len = parseInt64((char*)&str.data[pos], 5, &year);
    pos += len;
    UA_CHECK(len > 0 && pos < str.length, return UA_STATUSCODE_BADDECODINGERROR);
    UA_CHECK(len == 4 || str.data[pos] == '-', return UA_STATUSCODE_BADDECODINGERROR);
    if(str.data[0] == '-')
        year = -year;
    dts.tm_year = (UA_Int16)year - 1900;
    if(str.data[pos] == '-')
        pos++;

    /* Parse the month */
    UA_UInt64 month = 0;
    UA_CHECK(str.length - pos > 2, return UA_STATUSCODE_BADDECODINGERROR);
    len = parseUInt64((char*)&str.data[pos], 2, &month);
    pos += len;
    UA_CHECK(len == 2, return UA_STATUSCODE_BADDECODINGERROR);
    dts.tm_mon = (UA_UInt16)month - 1;
    if(str.data[pos] == '-')
        pos++;

    /* Parse the day and check the T between date and time */
    UA_UInt64 day = 0;
    UA_CHECK(str.length - pos > 2, return UA_STATUSCODE_BADDECODINGERROR);
    len = parseUInt64((char*)&str.data[pos], 2, &day);
    pos += len;
    UA_CHECK(len == 2 || str.data[pos] != 'T',
             return UA_STATUSCODE_BADDECODINGERROR);
    dts.tm_mday = (UA_UInt16)day;
    pos++;

    /* Parse the hour */
    UA_UInt64 hour = 0;
    UA_CHECK(str.length - pos > 2, return UA_STATUSCODE_BADDECODINGERROR);
    len = parseUInt64((char*)&str.data[pos], 2, &hour);
    pos += len;
    UA_CHECK(len == 2, return UA_STATUSCODE_BADDECODINGERROR);
    dts.tm_hour = (UA_UInt16)hour;
    if(str.data[pos] == ':')
        pos++;

    /* Parse the minute */
    UA_UInt64 min = 0;
    UA_CHECK(str.length - pos > 2, return UA_STATUSCODE_BADDECODINGERROR);
    len = parseUInt64((char*)&str.data[pos], 2, &min);
    pos += len;
    UA_CHECK(len == 2, return UA_STATUSCODE_BADDECODINGERROR);
    dts.tm_min = (UA_UInt16)min;
    if(str.data[pos] == ':')
        pos++;

    /* Parse the second */
    UA_UInt64 sec = 0;
    UA_CHECK(str.length - pos >= 2, return UA_STATUSCODE_BADDECODINGERROR);
    len = parseUInt64((char*)&str.data[pos], 2, &sec);
    pos += len;
    UA_CHECK(len == 2, return UA_STATUSCODE_BADDECODINGERROR);
    dts.tm_sec = (UA_UInt16)sec;

    /* Compute the seconds since the Unix epoch */
    long long sinceunix = musl_tm_to_secs(&dts);

    /* Are we within the range that can be represented? */
    long long sinceunix_min =
        (long long)(UA_INT64_MIN / UA_DATETIME_SEC) -
        (long long)(UA_DATETIME_UNIX_EPOCH / UA_DATETIME_SEC) -
        (long long)1; /* manual correction due to rounding */
    long long sinceunix_max = (long long)
        ((UA_INT64_MAX - UA_DATETIME_UNIX_EPOCH) / UA_DATETIME_SEC);
    if(sinceunix < sinceunix_min || sinceunix > sinceunix_max)
        return UA_STATUSCODE_BADDECODINGERROR;

    /* Convert to DateTime. Add or subtract one extra second here to prevent
     * underflow/overflow. This is reverted once the fractional part has been
     * added. */
    sinceunix -= (sinceunix > 0) ? 1 : -1;
    UA_DateTime dt = (UA_DateTime)
        (sinceunix + (UA_DATETIME_UNIX_EPOCH / UA_DATETIME_SEC)) * UA_DATETIME_SEC;

    /* Parse the fraction of the second if defined */
    UA_CHECK(pos < str.length, goto finish);
    if(str.data[pos] == ',' || str.data[pos] == '.') {
        pos++;
        double frac = 0.0;
        double denom = 0.1;
        while(pos < str.length && str.data[pos] >= '0' && str.data[pos] <= '9') {
            frac += denom * (str.data[pos] - '0');
            denom *= 0.1;
            pos++;
        }
        frac += 0.00000005; /* Correct rounding when converting to integer */
        dt += (UA_DateTime)(frac * UA_DATETIME_SEC);
    }

    /* Time zone handling */
    UA_CHECK(pos < str.length, goto finish);
    if(str.data[pos] == 'Z') {
        pos++;
    } else if(str.data[pos] == '+' || str.data[pos] == '-') {
        UA_UInt64 tzHour = 0, tzMin = 0;
        UA_Int64 offsetSeconds = 0;
        UA_Byte tzSign = str.data[pos++];

        UA_CHECK(str.length - pos >= 2, return UA_STATUSCODE_BADDECODINGERROR);
        len = parseUInt64((char*)&str.data[pos], 2, &tzHour);
        pos += len;
        UA_CHECK(len == 2, return UA_STATUSCODE_BADDECODINGERROR);

        UA_CHECK(str.length > pos, goto finish); /* Allow missing tz minutes */
        if(str.data[pos] == ':')
            pos++;

        UA_CHECK(str.length - pos >= 2, return UA_STATUSCODE_BADDECODINGERROR);
        len = parseUInt64((char*)&str.data[pos], 2, &tzMin);
        pos += len;
        UA_CHECK(len == 2, return UA_STATUSCODE_BADDECODINGERROR);

        offsetSeconds = (tzHour * 3600) + (tzMin * 60);
        if(tzSign == '-')
            offsetSeconds = -offsetSeconds;
        dt -= (UA_DateTime)(offsetSeconds * UA_DATETIME_SEC);
    } else {
        return UA_STATUSCODE_BADDECODINGERROR;
    }

 finish:
    /* Remove the underflow/overflow protection (see above) */
    if(sinceunix > 0) {
        if(dt > UA_INT64_MAX - UA_DATETIME_SEC)
            return UA_STATUSCODE_BADDECODINGERROR;
        dt += UA_DATETIME_SEC;
    } else {
        if(dt < UA_INT64_MIN + UA_DATETIME_SEC)
            return UA_STATUSCODE_BADDECODINGERROR;
        dt -= UA_DATETIME_SEC;
    }

    /* We must be at the end of the string */
    if(pos != str.length)
        return UA_STATUSCODE_BADDECODINGERROR;

    *dst = dt;
    return UA_STATUSCODE_GOOD;
}

UA_DateTime
UA_DATETIME(const char *chars) {
    UA_DateTime dst;
    UA_StatusCode res =
        UA_DateTime_parse(&dst, UA_STRING((char*)(uintptr_t)chars));
    if(res != UA_STATUSCODE_GOOD)
        UA_DateTime_init(&dst);
    return dst;
}

/* Guid */
static const u8 hexmapLower[16] =
    {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
static const u8 hexmapUpper[16] =
    {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

void
UA_Guid_to_hex(const UA_Guid *guid, u8* out, UA_Boolean lower) {
    const u8 *hexmap = (lower) ? hexmapLower : hexmapUpper;
    size_t i = 0, j = 28;
    for(; i<8;i++,j-=4)         /* pos 0-7, 4byte, (a) */
        out[i] = hexmap[(guid->data1 >> j) & 0x0Fu];
    out[i++] = '-';             /* pos 8 */
    for(j=12; i<13;i++,j-=4)    /* pos 9-12, 2byte, (b) */
        out[i] = hexmap[(uint16_t)(guid->data2 >> j) & 0x0Fu];
    out[i++] = '-';             /* pos 13 */
    for(j=12; i<18;i++,j-=4)    /* pos 14-17, 2byte (c) */
        out[i] = hexmap[(uint16_t)(guid->data3 >> j) & 0x0Fu];
    out[i++] = '-';              /* pos 18 */
    for(j=0;i<23;i+=2,j++) {     /* pos 19-22, 2byte (d) */
        out[i] = hexmap[(guid->data4[j] & 0xF0u) >> 4u];
        out[i+1] = hexmap[guid->data4[j] & 0x0Fu];
    }
    out[i++] = '-';              /* pos 23 */
    for(j=2; i<36;i+=2,j++) {    /* pos 24-35, 6byte (e) */
        out[i] = hexmap[(guid->data4[j] & 0xF0u) >> 4u];
        out[i+1] = hexmap[guid->data4[j] & 0x0Fu];
    }
}

UA_StatusCode
UA_Guid_print(const UA_Guid *guid, UA_String *output) {
    if(output->length == 0) {
        UA_StatusCode res =
            UA_ByteString_allocBuffer((UA_ByteString*)output, 36);
        if(res != UA_STATUSCODE_GOOD)
            return res;
    } else {
        if(output->length < 36)
            return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED;
        output->length = 36;
    }
    UA_Guid_to_hex(guid, output->data, true);
    return UA_STATUSCODE_GOOD;
}

UA_Guid
UA_GUID(const char *chars) {
    UA_Guid guid;
    UA_Guid_parse(&guid, UA_STRING((char*)(uintptr_t)chars));
    return guid;
}

/* ByteString */
UA_StatusCode
UA_ByteString_allocBuffer(UA_ByteString *bs, size_t length) {
    UA_ByteString_init(bs);
    if(length == 0) {
        bs->data = (u8*)UA_EMPTY_ARRAY_SENTINEL;
        return UA_STATUSCODE_GOOD;
    }
    bs->data = (u8*)UA_calloc(1,length);
    if(UA_UNLIKELY(!bs->data))
        return UA_STATUSCODE_BADOUTOFMEMORY;
    bs->length = length;
    return UA_STATUSCODE_GOOD;
}

/* NodeId */
static void
NodeId_clear(void *p, const UA_DataType *_) {
    UA_NodeId *id = (UA_NodeId*)p;
    switch(id->identifierType) {
    case UA_NODEIDTYPE_STRING:
    case UA_NODEIDTYPE_BYTESTRING:
        String_clear(&id->identifier.string, NULL);
        break;
    default: break;
    }
}

static UA_StatusCode
NodeId_copy(const void *src, void *dst, const UA_DataType *_) {
    const UA_NodeId *srcN = (const UA_NodeId*)src;
    UA_NodeId *dstN = (UA_NodeId *)dst;
    UA_StatusCode retval = UA_STATUSCODE_GOOD;
    switch(srcN->identifierType) {
    case UA_NODEIDTYPE_NUMERIC:
        *dstN = *srcN;
        return UA_STATUSCODE_GOOD;
    case UA_NODEIDTYPE_STRING:
    case UA_NODEIDTYPE_BYTESTRING:
        retval |= String_copy(&srcN->identifier.string,
                              &dstN->identifier.string, NULL);
        break;
    case UA_NODEIDTYPE_GUID:
        dstN->identifier.guid = srcN->identifier.guid;
        break;
    default:
        return UA_STATUSCODE_BADINTERNALERROR;
    }
    dstN->namespaceIndex = srcN->namespaceIndex;
    dstN->identifierType = srcN->identifierType;
    return retval;
}

UA_Boolean
UA_NodeId_isNull(const UA_NodeId *p) {
    if(p->namespaceIndex != 0)
        return false;
    switch (p->identifierType) {
    case UA_NODEIDTYPE_NUMERIC:
        return (p->identifier.numeric == 0);
    case UA_NODEIDTYPE_STRING:
    case UA_NODEIDTYPE_BYTESTRING:
        return (p->identifier.string.length == 0); /* Null and empty string */
    case UA_NODEIDTYPE_GUID:
        return (guidOrder(&p->identifier.guid, &UA_GUID_NULL, NULL) == UA_ORDER_EQ);
    }
    return false;
}

UA_Order
UA_NodeId_order(const UA_NodeId *n1, const UA_NodeId *n2) {
    return nodeIdOrder(n1, n2, NULL);
}

UA_NodeId
UA_NODEID_NUMERIC(UA_UInt16 nsIndex, UA_UInt32 identifier) {
    UA_NodeId id;
    memset(&id, 0, sizeof(UA_NodeId));
    id.namespaceIndex = nsIndex;
    id.identifierType = UA_NODEIDTYPE_NUMERIC;
    id.identifier.numeric = identifier;
    return id;
}

UA_NodeId
UA_NODEID_STRING(UA_UInt16 nsIndex, char *chars) {
    UA_NodeId id;
    memset(&id, 0, sizeof(UA_NodeId));
    id.namespaceIndex = nsIndex;
    id.identifierType = UA_NODEIDTYPE_STRING;
    id.identifier.string = UA_STRING(chars);
    return id;
}

UA_NodeId
UA_NODEID_STRING_ALLOC(UA_UInt16 nsIndex,
                       const char *chars) {
    UA_NodeId id;
    memset(&id, 0, sizeof(UA_NodeId));
    id.namespaceIndex = nsIndex;
    id.identifierType = UA_NODEIDTYPE_STRING;
    id.identifier.string = UA_STRING_ALLOC(chars);
    return id;
}

UA_NodeId
UA_NODEID_GUID(UA_UInt16 nsIndex, UA_Guid guid) {
    UA_NodeId id;
    memset(&id, 0, sizeof(UA_NodeId));
    id.namespaceIndex = nsIndex;
    id.identifierType = UA_NODEIDTYPE_GUID;
    id.identifier.guid = guid;
    return id;
}

UA_NodeId
UA_NODEID_BYTESTRING(UA_UInt16 nsIndex, char *chars) {
    UA_NodeId id;
    memset(&id, 0, sizeof(UA_NodeId));
    id.namespaceIndex = nsIndex;
    id.identifierType = UA_NODEIDTYPE_BYTESTRING;
    id.identifier.byteString = UA_BYTESTRING(chars);
    return id;
}

UA_NodeId
UA_NODEID_BYTESTRING_ALLOC(UA_UInt16 nsIndex,
                           const char *chars) {
    UA_NodeId id;
    memset(&id, 0, sizeof(UA_NodeId));
    id.namespaceIndex = nsIndex;
    id.identifierType = UA_NODEIDTYPE_BYTESTRING;
    id.identifier.byteString = UA_BYTESTRING_ALLOC(chars);
    return id;
}

/* sdbm-hash (http://www.cse.yorku.ca/~oz/hash.html) */
u32
UA_ByteString_hash(u32 initialHashValue,
                   const u8 *data, size_t size) {
    u32 h = initialHashValue;
    for(size_t i = 0; i < size; i++)
        h = data[i] + (h << 6) + (h << 16) - h;
    return h;
}

u32
UA_NodeId_hash(const UA_NodeId *n) {
    switch(n->identifierType) {
    case UA_NODEIDTYPE_NUMERIC:
    default:
        return UA_ByteString_hash(n->namespaceIndex, (const u8*)&n->identifier.numeric,
                                  sizeof(UA_UInt32));
    case UA_NODEIDTYPE_STRING:
    case UA_NODEIDTYPE_BYTESTRING:
        return UA_ByteString_hash(n->namespaceIndex, n->identifier.string.data,
                                  n->identifier.string.length);
    case UA_NODEIDTYPE_GUID:
        return UA_ByteString_hash(n->namespaceIndex, (const u8*)&n->identifier.guid,
                                  sizeof(UA_Guid));
    }
}

/* Computes length for the encoding size and pre-encodes the numeric values.
 * This can be larger than the actual size due to the removed base64 padding
 * (for the percent-escaping). */
static size_t
nodeIdSize(const UA_NodeId *id, u8 *nsStr, u8 *numIdStr, UA_String nsUri,
           UA_Escaping idEsc) {
    /* Namespace length */
    size_t len = 0;
    if(nsUri.data != NULL) {
        len += 5; /* nsu=; */
        len += UA_String_escapedSize(nsUri, UA_ESCAPING_PERCENT);
    } else if(id->namespaceIndex > 0) {
        len += 4; /* ns=; */
        size_t nsStrSize = itoaUnsigned(id->namespaceIndex, (char*)nsStr, 10);
        nsStr[nsStrSize] = 0;
        len += nsStrSize;
    }

    len += 2; /* ?= */

    switch (id->identifierType) {
    case UA_NODEIDTYPE_NUMERIC: {
        size_t numIdStrSize = itoaUnsigned(id->identifier.numeric, (char*)numIdStr, 10);
        numIdStr[numIdStrSize] = 0;
        len += numIdStrSize;
        break;
    }
    case UA_NODEIDTYPE_STRING:
        len += UA_String_escapedSize(id->identifier.string, idEsc);
        break;
    case UA_NODEIDTYPE_GUID:
        len += 36;
        break;
    case UA_NODEIDTYPE_BYTESTRING:
        len += 4 * ((id->identifier.byteString.length + 2) / 3);
        break;
    default:
        len = 0;
    }
    return len;
}

static u8 *
printNodeIdBody(const UA_NodeId *id, UA_String nsUri, u8* nsStr, u8* numIdStr, u8 *pos,
                const UA_NamespaceMapping *nsMapping, UA_Escaping idEsc) {
    size_t len;

    /* Encode the namespace */
    if(nsUri.data != NULL) {
        memcpy(pos, "nsu=", 4);
        pos += 4;
        pos += UA_String_escapeInsert(pos, nsUri, UA_ESCAPING_PERCENT);
        *pos++ = ';';
    } else if(id->namespaceIndex > 0) {
        memcpy(pos, "ns=", 3);
        pos += 3;
        len = strlen((char*)nsStr);
        memcpy(pos, nsStr, len);
        pos += len;
        *pos++ = ';';
    }

    /* Encode the identifier */
    switch(id->identifierType) {
    case UA_NODEIDTYPE_NUMERIC:
        memcpy(pos, "i=", 2);
        pos += 2;
        len = strlen((char*)numIdStr);
        memcpy(pos, numIdStr, len);
        pos += len;
        break;
    case UA_NODEIDTYPE_STRING:
        memcpy(pos, "s=", 2);
        pos += 2;
        pos += UA_String_escapeInsert(pos, id->identifier.string, idEsc);
        break;
    case UA_NODEIDTYPE_GUID:
        memcpy(pos, "g=", 2);
        pos += 2;
        UA_Guid_to_hex(&id->identifier.guid, pos, true);
        pos += 36;
        break;
    case UA_NODEIDTYPE_BYTESTRING:
        memcpy(pos, "b=", 2);
        pos += 2;
        /* Use base64url encoding for percent-escaping.
         * Replace +/ with -_ and remove the padding. */
        u8 *bpos = pos;
        pos += UA_base64_buf(id->identifier.byteString.data,
                             id->identifier.byteString.length, pos);
        if(idEsc == UA_ESCAPING_PERCENT ||
           idEsc == UA_ESCAPING_PERCENT_EXTENDED) {
            while(pos > bpos && pos[-1] == '=')
                pos--;
            for(; bpos < pos; bpos++) {
                if(*bpos == '+') *bpos = '-';
                else if(*bpos == '/') *bpos = '_';
            }
        }
        break;
    }
    return pos;
}

UA_StatusCode
nodeId_printEscape(const UA_NodeId *id, UA_String *output,
                   const UA_NamespaceMapping *nsMapping, UA_Escaping idEsc) {
    /* Try to map the NamespaceIndex to the Uri */
    UA_String nsUri = UA_STRING_NULL;
    if(id->namespaceIndex > 0 && nsMapping)
        UA_NamespaceMapping_index2Uri(nsMapping, id->namespaceIndex, &nsUri);

    /* Compute the string length and print numerical identifiers. */
    u8 nsStr[7];
    u8 numIdStr[12];
    size_t idLen = nodeIdSize(id, nsStr, numIdStr, nsUri, idEsc);
    if(idLen == 0)
        return UA_STATUSCODE_BADINTERNALERROR;

    /* Allocate memory if required */
    if(output->length == 0) {
        UA_StatusCode res = UA_ByteString_allocBuffer((UA_ByteString*)output, idLen);
        if(res != UA_STATUSCODE_GOOD)
            return res;
    } else {
        if(output->length < idLen)
            return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED;
        output->length = idLen;
    }

    /* Print the NodeId */
    u8 *pos = printNodeIdBody(id, nsUri, nsStr, numIdStr, output->data, nsMapping, idEsc);
    output->length = (size_t)(pos - output->data);
    return UA_STATUSCODE_GOOD;
}

UA_StatusCode
UA_NodeId_printEx(const UA_NodeId *id, UA_String *output,
                  const UA_NamespaceMapping *nsMapping) {
    return nodeId_printEscape(id, output, nsMapping, UA_ESCAPING_NONE);
}

UA_StatusCode
UA_NodeId_print(const UA_NodeId *id, UA_String *output) {
    return UA_NodeId_printEx(id, output, NULL);
}

UA_NodeId UA_NODEID(const char *chars) {
    UA_NodeId id;
    UA_NodeId_parse(&id, UA_STRING((char*)(uintptr_t)chars));
    return id;
}

/* ExpandedNodeId */
static void
ExpandedNodeId_clear(void *p, const UA_DataType *_) {
    UA_ExpandedNodeId *id = (UA_ExpandedNodeId*)p;
    NodeId_clear(&id->nodeId, NULL);
    String_clear(&id->namespaceUri, NULL);
}

static UA_StatusCode
ExpandedNodeId_copy(const void *src, void *dst, const UA_DataType *_) {
    const UA_ExpandedNodeId *srcE = (const UA_ExpandedNodeId *)src;
    UA_ExpandedNodeId *dstE = (UA_ExpandedNodeId*)dst;
    UA_StatusCode retval = NodeId_copy(&srcE->nodeId, &dstE->nodeId, NULL);
    retval |= String_copy(&srcE->namespaceUri, &dstE->namespaceUri, NULL);
    dstE->serverIndex = srcE->serverIndex;
    return retval;
}

UA_ExpandedNodeId
UA_EXPANDEDNODEID_NUMERIC(UA_UInt16 nsIndex, UA_UInt32 identifier) {
    UA_ExpandedNodeId id;
    memset(&id, 0, sizeof(UA_ExpandedNodeId));
    id.nodeId = UA_NODEID_NUMERIC(nsIndex, identifier);
    return id;
}

UA_ExpandedNodeId
UA_EXPANDEDNODEID_STRING(UA_UInt16 nsIndex, char *chars) {
    UA_ExpandedNodeId id;
    memset(&id, 0, sizeof(UA_ExpandedNodeId));
    id.nodeId = UA_NODEID_STRING(nsIndex, chars);
    return id;
}

UA_ExpandedNodeId
UA_EXPANDEDNODEID_STRING_ALLOC(UA_UInt16 nsIndex, const char *chars) {
    UA_ExpandedNodeId id;
    memset(&id, 0, sizeof(UA_ExpandedNodeId));
    id.nodeId = UA_NODEID_STRING_ALLOC(nsIndex, chars);
    return id;
}

UA_ExpandedNodeId
UA_EXPANDEDNODEID_STRING_GUID(UA_UInt16 nsIndex, UA_Guid guid) {
    UA_ExpandedNodeId id;
    memset(&id, 0, sizeof(UA_ExpandedNodeId));
    id.nodeId = UA_NODEID_GUID(nsIndex, guid);
    return id;
}

UA_ExpandedNodeId
UA_EXPANDEDNODEID_BYTESTRING(UA_UInt16 nsIndex, char *chars) {
    UA_ExpandedNodeId id;
    memset(&id, 0, sizeof(UA_ExpandedNodeId));
    id.nodeId = UA_NODEID_BYTESTRING(nsIndex, chars);
    return id;
}

UA_ExpandedNodeId
UA_EXPANDEDNODEID_BYTESTRING_ALLOC(UA_UInt16 nsIndex, const char *chars) {
    UA_ExpandedNodeId id;
    memset(&id, 0, sizeof(UA_ExpandedNodeId));
    id.nodeId = UA_NODEID_BYTESTRING_ALLOC(nsIndex, chars);
    return id;
}

UA_ExpandedNodeId
UA_EXPANDEDNODEID_NODEID(UA_NodeId nodeId) {
    UA_ExpandedNodeId id;
    memset(&id, 0, sizeof(UA_ExpandedNodeId));
    id.nodeId = nodeId;
    return id;
}

UA_ExpandedNodeId
UA_EXPANDEDNODEID(const char *chars) {
    UA_ExpandedNodeId id;
    UA_ExpandedNodeId_parse(&id, UA_STRING((char*)(uintptr_t)chars));
    return id;
}

UA_Boolean
UA_ExpandedNodeId_isLocal(const UA_ExpandedNodeId *n) {
    return (n->namespaceUri.length == 0 && n->serverIndex == 0);
}

UA_Order
UA_ExpandedNodeId_order(const UA_ExpandedNodeId *n1,
                        const UA_ExpandedNodeId *n2) {
    return expandedNodeIdOrder(n1, n2, NULL);
}

u32
UA_ExpandedNodeId_hash(const UA_ExpandedNodeId *n) {
    u32 h = UA_NodeId_hash(&n->nodeId);
    if(n->serverIndex != 0)
        h = UA_ByteString_hash(h, (const UA_Byte*)&n->serverIndex, 4);
    if(n->namespaceUri.length != 0)
        h = UA_ByteString_hash(h, n->namespaceUri.data, n->namespaceUri.length);
    return h;
}

UA_StatusCode
UA_ExpandedNodeId_printEx(const UA_ExpandedNodeId *eid, UA_String *output,
                          const UA_NamespaceMapping *nsMapping,
                          size_t serverUrisSize, const UA_String *serverUris) {
    /* Try to map the NamespaceIndex to the Uri */
    UA_String nsUri = eid->namespaceUri;
    if(nsUri.data == NULL && eid->nodeId.namespaceIndex > 0 && nsMapping)
        UA_NamespaceMapping_index2Uri(nsMapping, eid->nodeId.namespaceIndex, &nsUri);

    /* Try to map the ServerIndex to a Uri */
    UA_String srvUri = UA_STRING_NULL;
    if(eid->serverIndex > 0 && eid->serverIndex < serverUrisSize)
        srvUri = serverUris[eid->serverIndex];

    /* No special escaping for ExpandedNodeIds */
    UA_Escaping idEsc = UA_ESCAPING_NONE;

    /* Compute the NodeId string length */
    u8 nsStr[7];
    u8 numIdStr[12];
    char srvIdxStr[11];
    size_t srvIdxSize = 0;
    size_t idLen = nodeIdSize(&eid->nodeId, nsStr, numIdStr, nsUri, idEsc);
    if(idLen == 0)
        return UA_STATUSCODE_BADINTERNALERROR;
    if(srvUri.length  > 0) {
        idLen += 5; /* svu=; */
        idLen += UA_String_escapedSize(srvUri, UA_ESCAPING_PERCENT);
    } else if(eid->serverIndex > 0) {
        idLen += 5; /* svr=; */
        srvIdxSize = itoaUnsigned(eid->serverIndex, srvIdxStr, 10);
        idLen += srvIdxSize;
    }

    /* Allocate memory if required */
    if(output->length == 0) {
        UA_StatusCode res = UA_ByteString_allocBuffer((UA_ByteString*)output, idLen);
        if(res != UA_STATUSCODE_GOOD)
            return res;
    } else {
        if(output->length < idLen)
            return UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED;
        output->length = idLen;
    }

    /* Encode the ServerIndex or ServerUrl */
    u8 *pos = output->data;
    if(srvUri.length  > 0) {
        memcpy(pos, "svu=", 4);
        pos += 4;
        pos += UA_String_escapeInsert(pos, srvUri, UA_ESCAPING_PERCENT);
        *pos++ = ';';
    } else if(eid->serverIndex > 0) {
        memcpy(pos, "svr=", 4);
        pos += 4;
        memcpy(pos, srvIdxStr, srvIdxSize);
        pos += srvIdxSize;
        *pos++ = ';';
    }

    /* Print the NodeId */
    pos = printNodeIdBody(&eid->nodeId, nsUri, nsStr, numIdStr, pos, nsMapping, idEsc);
    output->length = (size_t)(pos - output->data);
    return UA_STATUSCODE_GOOD;
}

UA_StatusCode
UA_ExpandedNodeId_print(const UA_ExpandedNodeId *eid, UA_String *output) {
    return UA_ExpandedNodeId_printEx(eid, output, NULL, 0, NULL);
}

/* ExtensionObject */
static void
ExtensionObject_clear(void *p, const UA_DataType *_) {
    UA_ExtensionObject *eo = (UA_ExtensionObject *)p;
    switch(eo->encoding) {
    case UA_EXTENSIONOBJECT_ENCODED_NOBODY:
    case UA_EXTENSIONOBJECT_ENCODED_BYTESTRING:
    case UA_EXTENSIONOBJECT_ENCODED_XML:
        NodeId_clear(&eo->content.encoded.typeId, NULL);
        String_clear(&eo->content.encoded.body, NULL);
        break;
    case UA_EXTENSIONOBJECT_DECODED:
        if(eo->content.decoded.data)
            UA_delete(eo->content.decoded.data, eo->content.decoded.type);
        break;
    default:
        break;
    }
}

static UA_StatusCode
ExtensionObject_copy(const void *src, void *dst, const UA_DataType *_) {
    const UA_ExtensionObject *srcE = (const UA_ExtensionObject *)src;
    UA_ExtensionObject *dstE = (UA_ExtensionObject *)dst;
    UA_StatusCode retval = UA_STATUSCODE_GOOD;
    switch(srcE->encoding) {
    case UA_EXTENSIONOBJECT_ENCODED_NOBODY:
    case UA_EXTENSIONOBJECT_ENCODED_BYTESTRING:
    case UA_EXTENSIONOBJECT_ENCODED_XML:
        dstE->encoding = srcE->encoding;
        retval = NodeId_copy(&srcE->content.encoded.typeId,
                             &dstE->content.encoded.typeId, NULL);
        /* ByteString -> copy as string */
        retval |= String_copy(&srcE->content.encoded.body,
                              &dstE->content.encoded.body, NULL);
        break;
    case UA_EXTENSIONOBJECT_DECODED:
    case UA_EXTENSIONOBJECT_DECODED_NODELETE:
        if(!srcE->content.decoded.type || !srcE->content.decoded.data)
            return UA_STATUSCODE_BADINTERNALERROR;
        dstE->encoding = UA_EXTENSIONOBJECT_DECODED;
        dstE->content.decoded.type = srcE->content.decoded.type;
        retval = UA_Array_copy(srcE->content.decoded.data, 1,
                               &dstE->content.decoded.data,
                               srcE->content.decoded.type);
        break;
    default:
        break;
    }
    return retval;
}

void
UA_ExtensionObject_setValue(UA_ExtensionObject *eo,
                            void * UA_RESTRICT p,
                            const UA_DataType *type) {
    UA_ExtensionObject_init(eo);
    eo->content.decoded.data = p;
    eo->content.decoded.type = type;
    eo->encoding = UA_EXTENSIONOBJECT_DECODED;
}

void
UA_ExtensionObject_setValueNoDelete(UA_ExtensionObject *eo,
                                    void * UA_RESTRICT p,
                                    const UA_DataType *type) {
    UA_ExtensionObject_init(eo);
    eo->content.decoded.data = p;
    eo->content.decoded.type = type;
    eo->encoding = UA_EXTENSIONOBJECT_DECODED_NODELETE;
}

UA_StatusCode
UA_ExtensionObject_setValueCopy(UA_ExtensionObject *eo,
                                void * UA_RESTRICT p,
                                const UA_DataType *type) {
    UA_ExtensionObject_init(eo);

    /* Make a copy of the value */
    void *val = UA_malloc(type->memSize);
    if(UA_UNLIKELY(!val))
        return UA_STATUSCODE_BADOUTOFMEMORY;
    UA_StatusCode res = UA_copy(p, val, type);
    if(UA_UNLIKELY(res != UA_STATUSCODE_GOOD)) {
        UA_free(val);
        return res;
    }

    /* Set the ExtensionObject */
    eo->content.decoded.data = val;
    eo->content.decoded.type = type;
    eo->encoding = UA_EXTENSIONOBJECT_DECODED;
    return UA_STATUSCODE_GOOD;
}

UA_Boolean
UA_ExtensionObject_hasDecodedType(const UA_ExtensionObject *eo,
                                  const UA_DataType *type) {
    if(eo->encoding != UA_EXTENSIONOBJECT_DECODED &&
       eo->encoding != UA_EXTENSIONOBJECT_DECODED_NODELETE)
        return false;
    return (eo->content.decoded.data != NULL &&
            eo->content.decoded.type == type);
}

/* Variant */
UA_Boolean
UA_Variant_isEmpty(const UA_Variant *v) {
    return v->type == NULL;
}

UA_Boolean
UA_Variant_isScalar(const UA_Variant *v) {
    return (v->type != NULL && v->arrayLength == 0 &&
            v->data > UA_EMPTY_ARRAY_SENTINEL);
}

UA_Boolean
UA_Variant_hasScalarType(const UA_Variant *v, const UA_DataType *type) {
    return UA_Variant_isScalar(v) && type == v->type;
}

UA_Boolean
UA_Variant_isArray(const UA_Variant *v) {
    return (v->type != NULL && !UA_Variant_isScalar(v));
}

UA_Boolean
UA_Variant_hasArrayType(const UA_Variant *v, const UA_DataType *type) {
    return (!UA_Variant_isScalar(v)) && type == v->type;
}

static void
Variant_clear(void *p, const UA_DataType *_) {
    UA_Variant *v = (UA_Variant *)p;

    /* The content is "borrowed" */
    if(v->storageType == UA_VARIANT_DATA_NODELETE)
        return;

    /* Delete the value */
    if(v->type && v->data > UA_EMPTY_ARRAY_SENTINEL) {
        if(v->arrayLength == 0)
            v->arrayLength = 1;
        UA_Array_delete(v->data, v->arrayLength, v->type);
        v->data = NULL;
    }

    /* Delete the array dimensions */
    if((void*)v->arrayDimensions > UA_EMPTY_ARRAY_SENTINEL)
        UA_free(v->arrayDimensions);
}

static UA_StatusCode
Variant_copy(const void *src, void *dst, const UA_DataType *_) {
    const UA_Variant *srcV = (const UA_Variant *)src;
    UA_Variant *dstV = (UA_Variant *)dst;
    size_t length = srcV->arrayLength;
    if(UA_Variant_isScalar(srcV))
        length = 1;
    UA_StatusCode retval = UA_Array_copy(srcV->data, length,
                                         &dstV->data, srcV->type);
    if(retval != UA_STATUSCODE_GOOD)
        return retval;
    dstV->arrayLength = srcV->arrayLength;
    dstV->type = srcV->type;
    if(srcV->arrayDimensions) {
        retval = UA_Array_copy(srcV->arrayDimensions, srcV->arrayDimensionsSize,
            (void**)&dstV->arrayDimensions, &UA_TYPES[UA_TYPES_INT32]);
        if(retval != UA_STATUSCODE_GOOD)
            return retval;
        dstV->arrayDimensionsSize = srcV->arrayDimensionsSize;
    }
    return UA_STATUSCODE_GOOD;
}

void
UA_Variant_setScalar(UA_Variant *v, void * UA_RESTRICT p,
                     const UA_DataType *type) {
    UA_Variant_init(v);
    v->type = type;
    v->arrayLength = 0;
    v->data = p;
}

UA_StatusCode
UA_Variant_setScalarCopy(UA_Variant *v, const void * UA_RESTRICT p,
                         const UA_DataType *type) {
    void *n = UA_malloc(type->memSize);
    if(UA_UNLIKELY(!n))
        return UA_STATUSCODE_BADOUTOFMEMORY;
    UA_StatusCode retval = UA_copy(p, n, type);
    if(UA_UNLIKELY(retval != UA_STATUSCODE_GOOD)) {
        UA_free(n);
        //cppcheck-suppress memleak
        return retval;
    }
    UA_Variant_setScalar(v, n, type);
    //cppcheck-suppress memleak
    return UA_STATUSCODE_GOOD;
}

void UA_Variant_setArray(UA_Variant *v, void * UA_RESTRICT array,
                         size_t arraySize, const UA_DataType *type) {
    UA_Variant_init(v);
    v->data = array;
    v->arrayLength = arraySize;
    v->type = type;
}

UA_StatusCode
UA_Variant_setArrayCopy(UA_Variant *v, const void * UA_RESTRICT array,
                        size_t arraySize, const UA_DataType *type) {
    UA_Variant_init(v);
    UA_StatusCode retval = UA_Array_copy(array, arraySize, &v->data, type);
    if(retval != UA_STATUSCODE_GOOD)
        return retval;
    v->arrayLength = arraySize;
    v->type = type;
    return UA_STATUSCODE_GOOD;
}

/* Test if a range is compatible with a variant. This may adjust the upper bound
 * (max) in order to fit the variant. */
static UA_StatusCode
checkAdjustRange(const UA_Variant *v, UA_NumericRange *range) {
    /* Test for max array size (64bit only) */
#if (SIZE_MAX > 0xffffffff)
    if(v->arrayLength > UA_UINT32_MAX)
        return UA_STATUSCODE_BADINTERNALERROR;
#endif
    u32 arrayLength = (u32)v->arrayLength;

    /* Assume one array dimension if none defined */
    const u32 *dims = v->arrayDimensions;
    size_t dims_count = v->arrayDimensionsSize;
    if(v->arrayDimensionsSize == 0) {
        dims_count = 1;
        dims = &arrayLength;
    }

    /* Does the range match the dimension of the variant? */
    if(range->dimensionsSize != dims_count)
        return UA_STATUSCODE_BADINDEXRANGENODATA;

    /* Check that the number of elements in the variant matches the array
     * dimensions */
    size_t elements = 1;
    for(size_t i = 0; i < dims_count; ++i) {
        if(dims[i] != 0 && elements > SIZE_MAX / dims[i])
            return UA_STATUSCODE_BADINTERNALERROR;
        elements *= dims[i];
    }
    if(elements != v->arrayLength)
        return UA_STATUSCODE_BADINTERNALERROR;

    /* Test the integrity of the range and compute the max index used for every
     * dimension. The standard says in Part 4, Section 7.22:
     *
     * When reading a value, the indexes may not specify a range that is within
     * the bounds of the array. The Server shall return a partial result if some
     * elements exist within the range. */
    for(size_t i = 0; i < dims_count; ++i) {
        if(range->dimensions[i].min > range->dimensions[i].max)
            return UA_STATUSCODE_BADINDEXRANGEINVALID;
        if(range->dimensions[i].min >= dims[i])
            return UA_STATUSCODE_BADINDEXRANGENODATA;

        /* Reduce the max to fit the variant */
        if(range->dimensions[i].max >= dims[i])
            range->dimensions[i].max = dims[i] - 1;
    }

    return UA_STATUSCODE_GOOD;
}

/* Computes the stride for copying the range elements.
 * - total: how many elements are in the range
 * - block: how big is each contiguous block of elements in the variant that
 *   maps into the range
 * - stride: how many elements are between the blocks (beginning to beginning)
 * - first: where does the first block begin */
static void
computeStrides(const UA_Variant *v, const UA_NumericRange range,
               size_t *total, size_t *block, size_t *stride, size_t *first) {
    /* Number of total elements to be copied */
    size_t count = 1;
    for(size_t i = 0; i < range.dimensionsSize; ++i)
        count *= (range.dimensions[i].max - range.dimensions[i].min) + 1;
    *total = count;

    /* Assume one array dimension if none defined */
    u32 arrayLength = (u32)v->arrayLength;
    const u32 *dims = v->arrayDimensions;
    size_t dims_count = v->arrayDimensionsSize;
    if(v->arrayDimensionsSize == 0) {
        dims_count = 1;
        dims = &arrayLength;
    }

    /* Compute the stride length and the position of the first element */
    *block = count;           /* Assume the range describes the entire array. */
    *stride = v->arrayLength; /* So it can be copied as a contiguous block.   */
    *first = 0;
    size_t running_dimssize = 1;
    UA_Boolean found_contiguous = false;
    for(size_t k = dims_count; k > 0;) {
        --k;
        size_t dimrange = 1 + range.dimensions[k].max - range.dimensions[k].min;
        if(!found_contiguous && dimrange != dims[k]) {
            /* Found the maximum block that can be copied contiguously */
            found_contiguous = true;
            *block = running_dimssize * dimrange;
            *stride = running_dimssize * dims[k];
        }
        /* Overflow in running_dimssize is only possible when the Variant has
         * passed a corrupted state through checkAdjustRange. Guard here as a
         * defence-in-depth measure. */
        if(running_dimssize != 0 && dims[k] > SIZE_MAX / running_dimssize)
            break;
        *first += running_dimssize * range.dimensions[k].min;
        running_dimssize *= dims[k];
    }
}

/* Is the type string-like? */
static UA_Boolean
isStringLike(const UA_DataType *type) {
    if(type == &UA_TYPES[UA_TYPES_STRING] ||
       type == &UA_TYPES[UA_TYPES_BYTESTRING] ||
       type == &UA_TYPES[UA_TYPES_XMLELEMENT])
        return true;
    return false;
}

/* Returns the part of the string that lies within the rangedimension */
static UA_StatusCode
copySubString(const UA_String *src, UA_String *dst,
              const UA_NumericRangeDimension *dim) {
    if(dim->min > dim->max)
        return UA_STATUSCODE_BADINDEXRANGEINVALID;
    if(dim->min >= src->length)
        return UA_STATUSCODE_BADINDEXRANGENODATA;

    size_t length;
    if(dim->max < src->length)
       length = dim->max - dim->min + 1;
    else
        length = src->length - dim->min;

    UA_StatusCode retval = UA_ByteString_allocBuffer(dst, length);
    if(retval != UA_STATUSCODE_GOOD)
        return retval;

    memcpy(dst->data, &src->data[dim->min], length);
    return UA_STATUSCODE_GOOD;
}

UA_StatusCode
UA_Variant_copyRange(const UA_Variant *src, UA_Variant * UA_RESTRICT dst,
                     const UA_NumericRange range) {
    if(!src->type)
        return UA_STATUSCODE_BADINVALIDARGUMENT;

    UA_Boolean isScalar = UA_Variant_isScalar(src);
    UA_Boolean stringLike = isStringLike(src->type);

    /* Upper bound of the dimensions for stack-allocation */
    if(range.dimensionsSize > UA_MAX_ARRAY_DIMS)
        return UA_STATUSCODE_BADINTERNALERROR;

    /* Copy the const range to a mutable stack location */
    UA_NumericRangeDimension thisrangedims[UA_MAX_ARRAY_DIMS];
    memcpy(thisrangedims, range.dimensions, sizeof(UA_NumericRangeDimension) * range.dimensionsSize);
    UA_NumericRange thisrange = {range.dimensionsSize, thisrangedims};

    UA_NumericRangeDimension scalarThisDimension = {0,0}; /* a single entry */
    UA_NumericRange nextrange = {0, NULL};

    /* Extract the range for copying at this level. The remaining range is dealt
     * with in the "scalar" type that may define an array by itself (string,
     * variant, ...). */
    UA_Variant arraySrc;
    if(isScalar) {
        /* Replace scalar src with array of length 1 */
        arraySrc = *src;
        arraySrc.arrayLength = 1;
        src = &arraySrc;
        /* Deal with all range dimensions within the scalar */
        thisrange.dimensions = &scalarThisDimension;
        thisrange.dimensionsSize = 1;
        nextrange = range;
    } else {
        /* Deal with as many range dimensions as possible right now */
        size_t dims = src->arrayDimensionsSize;
        if(dims == 0)
            dims = 1;
        if(dims > range.dimensionsSize)
            return UA_STATUSCODE_BADINDEXRANGEINVALID;
       thisrange.dimensionsSize = dims;
       nextrange.dimensions = &range.dimensions[dims];
       nextrange.dimensionsSize = range.dimensionsSize - dims;
    }

    UA_StatusCode retval = checkAdjustRange(src, &thisrange);
    if(retval != UA_STATUSCODE_GOOD)
        return retval;

    /* Compute the strides */
    size_t count, block, stride, first;
    computeStrides(src, thisrange, &count, &block, &stride, &first);
    UA_assert(block > 0);

    /* Allocate the array */
    UA_Variant_init(dst);
    dst->data = UA_Array_new(count, src->type);
    if(!dst->data)
        return UA_STATUSCODE_BADOUTOFMEMORY;

    /* Copy the range */
    size_t block_count = count / block;
    size_t elem_size = src->type->memSize;
    uintptr_t nextdst = (uintptr_t)dst->data;
    uintptr_t nextsrc = (uintptr_t)src->data + (elem_size * first);
    if(nextrange.dimensionsSize == 0) {
        /* no nextrange */
        if(src->type->pointerFree) {
            for(size_t i = 0; i < block_count; ++i) {
                memcpy((void*)nextdst, (void*)nextsrc, elem_size * block);
                nextdst += block * elem_size;
                nextsrc += stride * elem_size;
            }
        } else {
            for(size_t i = 0; i < block_count; ++i) {
                for(size_t j = 0; j < block; ++j) {
                    retval = UA_copy((const void*)nextsrc,
                                     (void*)nextdst, src->type);
                    nextdst += elem_size;
                    nextsrc += elem_size;
                }
                nextsrc += (stride - block) * elem_size;
            }
        }
    } else {
        /* nextrange can only be used for variants and stringlike with remaining
         * range of dimension 1 */
        if(src->type != &UA_TYPES[UA_TYPES_VARIANT]) {
            if(!stringLike)
                retval = UA_STATUSCODE_BADINDEXRANGENODATA;
            if(nextrange.dimensionsSize != 1)
                retval = UA_STATUSCODE_BADINDEXRANGENODATA;
        }

        /* Copy the content */
        for(size_t i = 0; i < block_count; ++i) {
            for(size_t j = 0; j < block && retval == UA_STATUSCODE_GOOD; ++j) {
                if(stringLike)
                    retval = copySubString((const UA_String*)nextsrc,
                                           (UA_String*)nextdst,
                                           nextrange.dimensions);
                else
                    retval = UA_Variant_copyRange((const UA_Variant*)nextsrc,
                                                  (UA_Variant*)nextdst,
                                                  nextrange);
                nextdst += elem_size;
                nextsrc += elem_size;
            }
            nextsrc += (stride - block) * elem_size;
        }
    }

    /* Clean up if copying failed */
    if(retval != UA_STATUSCODE_GOOD) {
        UA_Array_delete(dst->data, count, src->type);
        dst->data = NULL;
        return retval;
    }

    /* Done if scalar */
    dst->type = src->type;
    if(isScalar)
        return retval;

    /* Copy array dimensions */
    dst->arrayLength = count;
    if(src->arrayDimensionsSize > 0) {
        dst->arrayDimensions =
            (u32*)UA_Array_new(thisrange.dimensionsSize, &UA_TYPES[UA_TYPES_UINT32]);
        if(!dst->arrayDimensions) {
            Variant_clear(dst, NULL);
            return UA_STATUSCODE_BADOUTOFMEMORY;
        }
        dst->arrayDimensionsSize = thisrange.dimensionsSize;
        for(size_t k = 0; k < thisrange.dimensionsSize; ++k)
            dst->arrayDimensions[k] =
                thisrange.dimensions[k].max - thisrange.dimensions[k].min + 1;
    }
    return UA_STATUSCODE_GOOD;
}

/* TODO: Allow ranges to reach inside a scalars that are array-like, e.g.
 * variant and strings. This is already possible for reading... */
static UA_StatusCode
Variant_setRange(UA_Variant *v, void *array, size_t arraySize,
                 const UA_NumericRange range, UA_Boolean copy) {
    if(!v->type)
        return UA_STATUSCODE_BADINVALIDARGUMENT;

    /* Upper bound of the dimensions for stack-allocation */
    if(range.dimensionsSize > UA_MAX_ARRAY_DIMS)
        return UA_STATUSCODE_BADINTERNALERROR;

    /* Copy the const range to a mutable stack location */
    UA_NumericRangeDimension thisrangedims[UA_MAX_ARRAY_DIMS];
    memcpy(thisrangedims, range.dimensions, sizeof(UA_NumericRangeDimension) * range.dimensionsSize);
    UA_NumericRange thisrange = {range.dimensionsSize, thisrangedims};

    UA_StatusCode retval = checkAdjustRange(v, &thisrange);
    if(retval != UA_STATUSCODE_GOOD)
        return retval;

    /* Compute the strides */
    size_t count, block, stride, first;
    computeStrides(v, range, &count, &block, &stride, &first);
    if(count != arraySize)
        return UA_STATUSCODE_BADINDEXRANGEINVALID;

    /* Move/copy the elements */
    size_t block_count = count / block;
    size_t elem_size = v->type->memSize;
    uintptr_t nextdst = (uintptr_t)v->data + (first * elem_size);
    uintptr_t nextsrc = (uintptr_t)array;
    if(v->type->pointerFree || !copy) {
        for(size_t i = 0; i < block_count; ++i) {
            memcpy((void*)nextdst, (void*)nextsrc, elem_size * block);
            nextsrc += block * elem_size;
            nextdst += stride * elem_size;
        }
    } else {
        for(size_t i = 0; i < block_count; ++i) {
            for(size_t j = 0; j < block; ++j) {
                clearJumpTable[v->type->typeKind]((void*)nextdst, v->type);
                retval |= UA_copy((void*)nextsrc, (void*)nextdst, v->type);
                nextdst += elem_size;
                nextsrc += elem_size;
            }
            nextdst += (stride - block) * elem_size;
        }
    }

    /* If members were moved, initialize original array to prevent reuse */
    if(!copy && !v->type->pointerFree)
        memset(array, 0, elem_size*arraySize);

    return retval;
}

UA_StatusCode
UA_Variant_setRange(UA_Variant *v, void * UA_RESTRICT array,
                    size_t arraySize, const UA_NumericRange range) {
    return Variant_setRange(v, array, arraySize, range, false);
}

UA_StatusCode
UA_Variant_setRangeCopy(UA_Variant *v, const void * UA_RESTRICT array,
                        size_t arraySize, const UA_NumericRange range) {
    return Variant_setRange(v, (void*)(uintptr_t)array,
                            arraySize, range, true);
}

/* LocalizedText */
UA_LocalizedText
UA_LOCALIZEDTEXT(char *locale, char *text) {
    UA_LocalizedText lt;
    lt.locale = UA_STRING(locale);
    lt.text = UA_STRING(text);
    return lt;
}

UA_LocalizedText
UA_LOCALIZEDTEXT_ALLOC(const char *locale, const char *text) {
    UA_LocalizedText lt;
    lt.locale = UA_STRING_ALLOC(locale);
    lt.text = UA_STRING_ALLOC(text);
    return lt;
}

static void
LocalizedText_clear(void *p, const UA_DataType *_) {
    UA_LocalizedText *lt = (UA_LocalizedText *)p;
    String_clear(&lt->locale, NULL);
    String_clear(&lt->text, NULL);
}

static UA_StatusCode
LocalizedText_copy(const void *src, void *dst, const UA_DataType *_) {
    const UA_LocalizedText *srcL = (const UA_LocalizedText *)src;
    UA_LocalizedText *dstL = (UA_LocalizedText *)dst;
    UA_StatusCode retval = String_copy(&srcL->locale, &dstL->locale, NULL);
    retval |= String_copy(&srcL->text, &dstL->text, NULL);
    return retval;
}

/* DataValue */
static void
DataValue_clear(void *p, const UA_DataType *_) {
    UA_DataValue *dv = (UA_DataValue *)p;
    Variant_clear(&dv->value, NULL);
}

static UA_StatusCode
DataValue_copy(const void *src, void *dst, const UA_DataType *_) {
    const UA_DataValue *srcD = (const UA_DataValue*)src;
    UA_DataValue *dstD = (UA_DataValue *)dst;
    memcpy(dstD, srcD, sizeof(UA_DataValue));
    UA_Variant_init(&dstD->value);
    UA_StatusCode retval = Variant_copy(&srcD->value, &dstD->value, NULL);
    if(retval != UA_STATUSCODE_GOOD)
        DataValue_clear(dstD, NULL);
    return retval;
}

UA_StatusCode
UA_DataValue_copyRange(const UA_DataValue *src, UA_DataValue * UA_RESTRICT dst,
                       const UA_NumericRange range) {
    memcpy(dst, src, sizeof(UA_DataValue));
    UA_Variant_init(&dst->value);
    UA_StatusCode retval = UA_Variant_copyRange(&src->value, &dst->value, range);
    if(retval != UA_STATUSCODE_GOOD)
        DataValue_clear(dst, NULL);
    return retval;
}

/* DiagnosticInfo */
static void
DiagnosticInfo_clear(void *p, const UA_DataType *_) {
    UA_DiagnosticInfo *di = (UA_DiagnosticInfo *)p;

    String_clear(&di->additionalInfo, NULL);
    if(di->hasInnerDiagnosticInfo && di->innerDiagnosticInfo) {
        DiagnosticInfo_clear(di->innerDiagnosticInfo, NULL);
        UA_free(di->innerDiagnosticInfo);
    }
}

static UA_StatusCode
DiagnosticInfo_copy(const void *src, void *dst, const UA_DataType *_) {
    const UA_DiagnosticInfo *srcD = (const UA_DiagnosticInfo *)src;
    UA_DiagnosticInfo *dstD = (UA_DiagnosticInfo *)dst;
    memcpy(dstD, srcD, sizeof(UA_DiagnosticInfo));
    UA_String_init(&dstD->additionalInfo);
    dstD->innerDiagnosticInfo = NULL;
    UA_StatusCode retval = UA_STATUSCODE_GOOD;
    if(srcD->hasAdditionalInfo)
        retval = String_copy(&srcD->additionalInfo, &dstD->additionalInfo, NULL);
    if(srcD->hasInnerDiagnosticInfo && srcD->innerDiagnosticInfo) {
        dstD->innerDiagnosticInfo = (UA_DiagnosticInfo*)
            UA_malloc(sizeof(UA_DiagnosticInfo));
        if(UA_LIKELY(dstD->innerDiagnosticInfo != NULL)) {
            retval |= DiagnosticInfo_copy(srcD->innerDiagnosticInfo,
                                          dstD->innerDiagnosticInfo, NULL);
            dstD->hasInnerDiagnosticInfo = true;
        } else {
            dstD->hasInnerDiagnosticInfo = false;
            retval |= UA_STATUSCODE_BADOUTOFMEMORY;
        }
    }
    return retval;
}

/********************/
/* Structured Types */
/********************/

void *
UA_new(const UA_DataType *type) {
    void *p = UA_calloc(1, type->memSize);
    return p;
}

void UA_init(void *p, const UA_DataType *type) {
    memset(p, 0, type->memSize);
}

static UA_StatusCode
copyByte(const void *src, void *dst, const UA_DataType *_) {
    const u8 *src8 = (const u8 *)src;
    u8 *dst8 = (u8 *)dst;
    *dst8 = *src8;
    return UA_STATUSCODE_GOOD;
}

static UA_StatusCode
copy2Byte(const void *src, void *dst, const UA_DataType *_) {
    const u16 *src16 = (const u16 *)src;
    u16 *dst16 = (u16 *)dst;
    *dst16 = *src16;
    return UA_STATUSCODE_GOOD;
}

static UA_StatusCode
copy4Byte(const void *src, void *dst, const UA_DataType *_) {
    const u32 *src32 = (const u32 *)src;
    u32 *dst32 = (u32 *)dst;
    *dst32 = *src32;
    return UA_STATUSCODE_GOOD;
}

static UA_StatusCode
copy8Byte(const void *src, void *dst, const UA_DataType *_) {
    const u64 *src64 = (const u64 *)src;
    u64 *dst64 = (u64 *)dst;
    *dst64 = *src64;
    return UA_STATUSCODE_GOOD;
}

static UA_StatusCode
copyGuid(const void *src, void *dst, const UA_DataType *_) {
    const UA_Guid *srcG = (const UA_Guid*)src;
    UA_Guid *dstG = (UA_Guid*)dst;
    *dstG = *srcG;
    return UA_STATUSCODE_GOOD;
}

static UA_StatusCode
copyStructure(const void *src, void *dst, const UA_DataType *type) {
    UA_StatusCode retval = UA_STATUSCODE_GOOD;
    uintptr_t ptrs = (uintptr_t)src;
    uintptr_t ptrd = (uintptr_t)dst;
    for(size_t i = 0; i < type->membersSize; ++i) {
        const UA_DataTypeMember *m = &type->members[i];
        const UA_DataType *mt = m->memberType;
        ptrs += m->padding;
        ptrd += m->padding;
        if(!m->isOptional) {
            if(!m->isArray) {
                retval |= copyJumpTable[mt->typeKind]((const void *)ptrs, (void *)ptrd, mt);
                ptrs += mt->memSize;
                ptrd += mt->memSize;
            } else {
                size_t *dst_size = (size_t*)ptrd;
                const size_t size = *((const size_t*)ptrs);
                ptrs += sizeof(size_t);
                ptrd += sizeof(size_t);
                retval |= UA_Array_copy(*(void* const*)ptrs, size, (void**)ptrd, mt);
                if(retval == UA_STATUSCODE_GOOD)
                    *dst_size = size;
                else
                    *dst_size = 0;
                ptrs += sizeof(void*);
                ptrd += sizeof(void*);
            }
        } else {
            if(!m->isArray) {
                if(*(void* const*)ptrs != NULL)
                    retval |= UA_Array_copy(*(void* const*)ptrs, 1, (void**)ptrd, mt);
            } else {
                if(*(void* const*)(ptrs+sizeof(size_t)) != NULL) {
                    size_t *dst_size = (size_t*)ptrd;
                    const size_t size = *((const size_t*)ptrs);
                    ptrs += sizeof(size_t);
                    ptrd += sizeof(size_t);
                    retval |= UA_Array_copy(*(void* const*)ptrs, size, (void**)ptrd, mt);
                    if(retval == UA_STATUSCODE_GOOD)
                        *dst_size = size;
                    else
                        *dst_size = 0;
                } else {
                    ptrs += sizeof(size_t);
                    ptrd += sizeof(size_t);
                }
            }
            ptrs += sizeof(void*);
            ptrd += sizeof(void*);
        }
    }
    return retval;
}

static UA_StatusCode
copyUnion(const void *src, void *dst, const UA_DataType *type) {
    uintptr_t ptrs = (uintptr_t) src;
    uintptr_t ptrd = (uintptr_t) dst;
    UA_UInt32 selection = *(UA_UInt32 *)ptrs;
    UA_copy((const UA_UInt32 *) ptrs, (UA_UInt32 *) ptrd, &UA_TYPES[UA_TYPES_UINT32]);
    if(selection == 0)
        return UA_STATUSCODE_GOOD;
    const UA_DataTypeMember *m = &type->members[selection-1];
    const UA_DataType *mt = m->memberType;
    ptrs += m->padding;
    ptrd += m->padding;

    UA_StatusCode retval = UA_STATUSCODE_GOOD;

    if (m->isArray) {
        size_t *dst_size = (size_t*)ptrd;
        const size_t size = *((const size_t*)ptrs);
        ptrs += sizeof(size_t);
        ptrd += sizeof(size_t);
        retval = UA_Array_copy(*(void* const*)ptrs, size, (void**)ptrd, mt);
        if(retval == UA_STATUSCODE_GOOD)
            *dst_size = size;
        else
            *dst_size = 0;
    } else {
        retval = copyJumpTable[mt->typeKind]((const void *)ptrs, (void *)ptrd, mt);
    }

    return retval;
}

static UA_StatusCode
copyNotImplemented(const void *src, void *dst, const UA_DataType *type) {
    return UA_STATUSCODE_BADNOTIMPLEMENTED;
}

const UA_copySignature copyJumpTable[UA_DATATYPEKINDS] = {
    copyByte, /* Boolean */
    copyByte, /* SByte */
    copyByte, /* Byte */
    copy2Byte, /* Int16 */
    copy2Byte, /* UInt16 */
    copy4Byte, /* Int32 */
    copy4Byte, /* UInt32 */
    copy8Byte, /* Int64 */
    copy8Byte, /* UInt64 */
    copy4Byte, /* Float */
    copy8Byte, /* Double */
    String_copy,
    copy8Byte, /* DateTime */
    copyGuid, /* Guid */
    String_copy, /* ByteString */
    String_copy, /* XmlElement */
    NodeId_copy,
    ExpandedNodeId_copy,
    copy4Byte, /* StatusCode */
    QualifiedName_copy,
    LocalizedText_copy,
    ExtensionObject_copy,
    DataValue_copy,
    Variant_copy,
    DiagnosticInfo_copy,
    copyNotImplemented, /* Decimal */
    copy4Byte, /* Enumeration */
    copyStructure,
    copyStructure, /* Structure with Optional Fields */
    copyUnion, /* Union */
    copyNotImplemented /* BitfieldCluster*/
};

UA_StatusCode
UA_copy(const void *src, void *dst, const UA_DataType *type) {
    memset(dst, 0, type->memSize); /* init */
    UA_StatusCode retval = copyJumpTable[type->typeKind](src, dst, type);
    if(retval != UA_STATUSCODE_GOOD)
        UA_clear(dst, type);
    return retval;
}

static void
clearStructure(void *p, const UA_DataType *type) {
    uintptr_t ptr = (uintptr_t)p;
    for(size_t i = 0; i < type->membersSize; ++i) {
        const UA_DataTypeMember *m = &type->members[i];
        const UA_DataType *mt = m->memberType;
        ptr += m->padding;
        if(!m->isOptional) {
            if(!m->isArray) {
                clearJumpTable[mt->typeKind]((void*)ptr, mt);
                ptr += mt->memSize;
            } else {
                size_t length = *(size_t*)ptr;
                ptr += sizeof(size_t);
                UA_Array_delete(*(void**)ptr, length, mt);
                ptr += sizeof(void*);
            }
        } else { /* field is optional */
            if(!m->isArray) {
                /* optional scalar field is contained */
                if((*(void *const *)ptr != NULL))
                    UA_Array_delete(*(void **)ptr, 1, mt);
                ptr += sizeof(void *);
            } else {
                /* optional array field is contained */
                if((*(void *const *)(ptr + sizeof(size_t)) != NULL)) {
                    size_t length = *(size_t *)ptr;
                    ptr += sizeof(size_t);
                    UA_Array_delete(*(void **)ptr, length, mt);
                    ptr += sizeof(void *);
                } else { /* optional array field not contained */
                    ptr += sizeof(size_t);
                    ptr += sizeof(void *);
                }
            }
        }
    }
}

static void
clearUnion(void *p, const UA_DataType *type) {
    uintptr_t ptr = (uintptr_t) p;
    UA_UInt32 selection = *(UA_UInt32 *)ptr;
    if(selection == 0)
        return;
    const UA_DataTypeMember *m = &type->members[selection-1];
    const UA_DataType *mt = m->memberType;
    ptr += m->padding;
    if (m->isArray) {
        size_t length = *(size_t *)ptr;
        ptr += sizeof(size_t);
        UA_Array_delete(*(void **)ptr, length, mt);
    } else {
        UA_clear((void *) ptr, mt);
    }
}

static void nopClear(void *p, const UA_DataType *type) { }

const
UA_clearSignature clearJumpTable[UA_DATATYPEKINDS] = {
    nopClear, /* Boolean */
    nopClear, /* SByte */
    nopClear, /* Byte */
    nopClear, /* Int16 */
    nopClear, /* UInt16 */
    nopClear, /* Int32 */
    nopClear, /* UInt32 */
    nopClear, /* Int64 */
    nopClear, /* UInt64 */
    nopClear, /* Float */
    nopClear, /* Double */
    String_clear, /* String */
    nopClear, /* DateTime */
    nopClear, /* Guid */
    String_clear, /* ByteString */
    String_clear, /* XmlElement */
    NodeId_clear,
    ExpandedNodeId_clear,
    nopClear, /* StatusCode */
    QualifiedName_clear,
    LocalizedText_clear,
    ExtensionObject_clear,
    DataValue_clear,
    Variant_clear,
    DiagnosticInfo_clear,
    nopClear, /* Decimal, not implemented */
    nopClear, /* Enumeration */
    clearStructure,
    clearStructure, /* Struct with Optional Fields*/
    clearUnion, /* Union*/
    nopClear /* BitfieldCluster, not implemented*/
};

void
UA_clear(void *p, const UA_DataType *type) {
    clearJumpTable[type->typeKind](p, type);
    memset(p, 0, type->memSize); /* init */
}

void
UA_delete(void *p, const UA_DataType *type) {
    clearJumpTable[type->typeKind](p, type);
    UA_free(p);
}

/******************/
/* Value Ordering */
/******************/

#define UA_NUMERICORDER(NAME, TYPE)                                 \
    static UA_Order                                                 \
    NAME(const TYPE *p1, const TYPE *p2, const UA_DataType *type) { \
        if(*p1 != *p2)                                              \
            return (*p1 < *p2) ? UA_ORDER_LESS : UA_ORDER_MORE;     \
        return UA_ORDER_EQ;                                         \
    }

UA_NUMERICORDER(booleanOrder, UA_Boolean)
UA_NUMERICORDER(sByteOrder, UA_SByte)
UA_NUMERICORDER(byteOrder, UA_Byte)
UA_NUMERICORDER(int16Order, UA_Int16)
UA_NUMERICORDER(uInt16Order, UA_UInt16)
UA_NUMERICORDER(int32Order, UA_Int32)
UA_NUMERICORDER(uInt32Order, UA_UInt32)
UA_NUMERICORDER(int64Order, UA_Int64)
UA_NUMERICORDER(uInt64Order, UA_UInt64)

#define UA_FLOATORDER(NAME, TYPE)                                   \
    static UA_Order                                                 \
    NAME(const TYPE *p1, const TYPE *p2, const UA_DataType *type) { \
        if(*p1 != *p2) {                                            \
            /* p1 is NaN */                                         \
            if(*p1 != *p1) {                                        \
                if(*p2 != *p2)                                      \
                    return UA_ORDER_EQ;                             \
                return UA_ORDER_LESS;                               \
            }                                                       \
            /* p2 is NaN */                                         \
            if(*p2 != *p2)                                          \
                return UA_ORDER_MORE;                               \
            return (*p1 < *p2) ? UA_ORDER_LESS : UA_ORDER_MORE;     \
        }                                                           \
        return UA_ORDER_EQ;                                         \
    }

UA_FLOATORDER(floatOrder, UA_Float)
UA_FLOATORDER(doubleOrder, UA_Double)

static UA_Order
guidOrder(const UA_Guid *p1, const UA_Guid *p2, const UA_DataType *type) {
    if(p1->data1 != p2->data1)
        return (p1->data1 < p2->data1) ? UA_ORDER_LESS : UA_ORDER_MORE;
    if(p1->data2 != p2->data2)
        return (p1->data2 < p2->data2) ? UA_ORDER_LESS : UA_ORDER_MORE;
    if(p1->data3 != p2->data3)
        return (p1->data3 < p2->data3) ? UA_ORDER_LESS : UA_ORDER_MORE;
    int cmp = memcmp(p1->data4, p2->data4, 8);
    if(cmp != 0)
        return (cmp < 0) ? UA_ORDER_LESS : UA_ORDER_MORE;
    return UA_ORDER_EQ;
}

static UA_Order
stringOrder(const UA_String *p1, const UA_String *p2, const UA_DataType *type) {
    if(p1->length != p2->length)
        return (p1->length < p2->length) ? UA_ORDER_LESS : UA_ORDER_MORE;
    /* For zero-length arrays, every pointer not NULL is considered a
     * UA_EMPTY_ARRAY_SENTINEL. */
    if(p1->data == p2->data) return UA_ORDER_EQ;
    if(p1->data == NULL) return UA_ORDER_LESS;
    if(p2->data == NULL) return UA_ORDER_MORE;
    int cmp = memcmp((const char*)p1->data, (const char*)p2->data, p1->length);
    if(cmp != 0)
        return (cmp < 0) ? UA_ORDER_LESS : UA_ORDER_MORE;
    return UA_ORDER_EQ;
}

static UA_Order
nodeIdOrder(const UA_NodeId *p1, const UA_NodeId *p2, const UA_DataType *_) {
    /* Compare namespaceIndex */
    if(p1->namespaceIndex != p2->namespaceIndex)
        return (p1->namespaceIndex < p2->namespaceIndex) ? UA_ORDER_LESS : UA_ORDER_MORE;

    /* Compare identifierType */
    if(p1->identifierType != p2->identifierType)
        return (p1->identifierType < p2->identifierType) ? UA_ORDER_LESS : UA_ORDER_MORE;

    /* Compare the identifier */
    switch(p1->identifierType) {
    case UA_NODEIDTYPE_NUMERIC:
    default:
        if(p1->identifier.numeric != p2->identifier.numeric)
            return (p1->identifier.numeric < p2->identifier.numeric) ?
                UA_ORDER_LESS : UA_ORDER_MORE;
        return UA_ORDER_EQ;
    case UA_NODEIDTYPE_GUID:
        return guidOrder(&p1->identifier.guid, &p2->identifier.guid, NULL);
    case UA_NODEIDTYPE_STRING:
    case UA_NODEIDTYPE_BYTESTRING:
        return stringOrder(&p1->identifier.string, &p2->identifier.string, NULL);
    }
}

static UA_Order
expandedNodeIdOrder(const UA_ExpandedNodeId *p1, const UA_ExpandedNodeId *p2,
                    const UA_DataType *_) {
    if(p1->serverIndex != p2->serverIndex)
        return (p1->serverIndex < p2->serverIndex) ? UA_ORDER_LESS : UA_ORDER_MORE;
    UA_Order o = stringOrder(&p1->namespaceUri, &p2->namespaceUri, NULL);
    if(o != UA_ORDER_EQ)
        return o;
    return nodeIdOrder(&p1->nodeId, &p2->nodeId, NULL);
}

static UA_Order
qualifiedNameOrder(const UA_QualifiedName *p1, const UA_QualifiedName *p2,
                   const UA_DataType *_) {
    if(p1->namespaceIndex != p2->namespaceIndex)
        return (p1->namespaceIndex < p2->namespaceIndex) ? UA_ORDER_LESS : UA_ORDER_MORE;
    return stringOrder(&p1->name, &p2->name, NULL);
}

static UA_Order
localizedTextOrder(const UA_LocalizedText *p1, const UA_LocalizedText *p2,
                   const UA_DataType *_) {
    UA_Order o = stringOrder(&p1->locale, &p2->locale, NULL);
    if(o != UA_ORDER_EQ)
        return o;
    return stringOrder(&p1->text, &p2->text, NULL);
}

static UA_Order
extensionObjectOrder(const UA_ExtensionObject *p1, const UA_ExtensionObject *p2,
                     const UA_DataType *_) {
    UA_ExtensionObjectEncoding enc1 = p1->encoding;
    UA_ExtensionObjectEncoding enc2 = p2->encoding;
    if(enc1 > UA_EXTENSIONOBJECT_DECODED)
        enc1 = UA_EXTENSIONOBJECT_DECODED;
    if(enc2 > UA_EXTENSIONOBJECT_DECODED)
        enc2 = UA_EXTENSIONOBJECT_DECODED;
    if(enc1 != enc2)
        return (enc1 < enc2) ? UA_ORDER_LESS : UA_ORDER_MORE;

    switch(enc1) {
    case UA_EXTENSIONOBJECT_ENCODED_NOBODY:
        return UA_ORDER_EQ;

    case UA_EXTENSIONOBJECT_ENCODED_BYTESTRING:
    case UA_EXTENSIONOBJECT_ENCODED_XML: {
            UA_Order o = nodeIdOrder(&p1->content.encoded.typeId,
                                     &p2->content.encoded.typeId, NULL);
            if(o != UA_ORDER_EQ)
                return o;
            return stringOrder((const UA_String*)&p1->content.encoded.body,
                               (const UA_String*)&p2->content.encoded.body, NULL);
        }

    case UA_EXTENSIONOBJECT_DECODED:
    default: {
            const UA_DataType *type1 = p1->content.decoded.type;
            const UA_DataType *type2 = p2->content.decoded.type;
            if(type1 != type2)
                return ((uintptr_t)type1 < (uintptr_t)type2) ? UA_ORDER_LESS : UA_ORDER_MORE;
            if(!type1)
                return UA_ORDER_EQ;
            return orderJumpTable[type1->typeKind]
                (p1->content.decoded.data, p2->content.decoded.data, type1);
        }
    }
}

/* Part 4: When testing for equality, a Server shall treat null and empty arrays
 * as equal.
 *
 * Don't compare overlayable types as "binary blobs". We have specific order
 * rules also for some overlayable types. For example how NaN floats are
 * compared. */
static UA_Order
arrayOrder(const void *p1, size_t p1Length,
           const void *p2, size_t p2Length,
           const UA_DataType *type) {
    if(p1Length != p2Length)
        return (p1Length < p2Length) ? UA_ORDER_LESS : UA_ORDER_MORE;
    uintptr_t u1 = (uintptr_t)p1;
    uintptr_t u2 = (uintptr_t)p2;
    for(size_t i = 0; i < p1Length; i++) {
        UA_Order o = orderJumpTable[type->typeKind]((const void*)u1, (const void*)u2, type);
        if(o != UA_ORDER_EQ)
            return o;
        u1 += type->memSize;
        u2 += type->memSize;
    }
    return UA_ORDER_EQ;
}

static UA_Order
variantOrder(const UA_Variant *p1, const UA_Variant *p2, const UA_DataType *_) {
    if(p1->type != p2->type)
        return ((uintptr_t)p1->type < (uintptr_t)p2->type) ? UA_ORDER_LESS : UA_ORDER_MORE;

    UA_Order o;
    if(p1->type != NULL) {
        /* Check if both variants are scalars or arrays */
        UA_Boolean s1 = UA_Variant_isScalar(p1);
        UA_Boolean s2 = UA_Variant_isScalar(p2);
        if(s1 != s2)
            return s1 ? UA_ORDER_LESS : UA_ORDER_MORE;
        if(s1) {
            o = orderJumpTable[p1->type->typeKind](p1->data, p2->data, p1->type);
        } else {
            /* Mismatching array length? */
            if(p1->arrayLength != p2->arrayLength)
                return (p1->arrayLength < p2->arrayLength) ? UA_ORDER_LESS : UA_ORDER_MORE;
            o = arrayOrder(p1->data, p1->arrayLength, p2->data, p2->arrayLength, p1->type);
        }
        if(o != UA_ORDER_EQ)
            return o;
    }

    if(p1->arrayDimensionsSize != p2->arrayDimensionsSize)
        return (p1->arrayDimensionsSize < p2->arrayDimensionsSize) ?
            UA_ORDER_LESS : UA_ORDER_MORE;
    o = UA_ORDER_EQ;
    if(p1->arrayDimensionsSize > 0)
        o = arrayOrder(p1->arrayDimensions, p1->arrayDimensionsSize,
                       p2->arrayDimensions, p2->arrayDimensionsSize,
                       &UA_TYPES[UA_TYPES_UINT32]);
    return o;
}

static UA_Order
dataValueOrder(const UA_DataValue *p1, const UA_DataValue *p2, const UA_DataType *_) {
    /* Value */
    if(p1->hasValue != p2->hasValue)
        return (!p1->hasValue) ? UA_ORDER_LESS : UA_ORDER_MORE;
    if(p1->hasValue) {
        UA_Order o = variantOrder(&p1->value, &p2->value, NULL);
        if(o != UA_ORDER_EQ)
            return o;
    }

    /* Status */
    if(p1->hasStatus != p2->hasStatus)
        return (!p1->hasStatus) ? UA_ORDER_LESS : UA_ORDER_MORE;
    if(p1->hasStatus && p1->status != p2->status)
        return (p1->status < p2->status) ? UA_ORDER_LESS : UA_ORDER_MORE;

    /* SourceTimestamp */
    if(p1->hasSourceTimestamp != p2->hasSourceTimestamp)
        return (!p1->hasSourceTimestamp) ? UA_ORDER_LESS : UA_ORDER_MORE;
    if(p1->hasSourceTimestamp && p1->sourceTimestamp != p2->sourceTimestamp)
        return (p1->sourceTimestamp < p2->sourceTimestamp) ? UA_ORDER_LESS : UA_ORDER_MORE;

    /* ServerTimestamp */
    if(p1->hasServerTimestamp != p2->hasServerTimestamp)
        return (!p1->hasServerTimestamp) ? UA_ORDER_LESS : UA_ORDER_MORE;
    if(p1->hasServerTimestamp && p1->serverTimestamp != p2->serverTimestamp)
        return (p1->serverTimestamp < p2->serverTimestamp) ? UA_ORDER_LESS : UA_ORDER_MORE;

    /* SourcePicoseconds */
    if(p1->hasSourcePicoseconds != p2->hasSourcePicoseconds)
        return (!p1->hasSourcePicoseconds) ? UA_ORDER_LESS : UA_ORDER_MORE;
    if(p1->hasSourcePicoseconds && p1->sourcePicoseconds != p2->sourcePicoseconds)
        return (p1->sourcePicoseconds < p2->sourcePicoseconds) ?
            UA_ORDER_LESS : UA_ORDER_MORE;

    /* ServerPicoseconds */
    if(p1->hasServerPicoseconds != p2->hasServerPicoseconds)
        return (!p1->hasServerPicoseconds) ? UA_ORDER_LESS : UA_ORDER_MORE;
    if(p1->hasServerPicoseconds && p1->serverPicoseconds != p2->serverPicoseconds)
        return (p1->serverPicoseconds < p2->serverPicoseconds) ?
            UA_ORDER_LESS : UA_ORDER_MORE;

    return UA_ORDER_EQ;
}

static UA_Order
diagnosticInfoOrder(const UA_DiagnosticInfo *p1, const UA_DiagnosticInfo *p2,
                    const UA_DataType *_) {
    /* SymbolicId */
    if(p1->hasSymbolicId != p2->hasSymbolicId)
        return (!p1->hasSymbolicId) ? UA_ORDER_LESS : UA_ORDER_MORE;
    if(p1->hasSymbolicId && p1->symbolicId != p2->symbolicId)
        return (p1->symbolicId < p2->symbolicId) ? UA_ORDER_LESS : UA_ORDER_MORE;

    /* NamespaceUri */
    if(p1->hasNamespaceUri != p2->hasNamespaceUri)
        return (!p1->hasNamespaceUri) ? UA_ORDER_LESS : UA_ORDER_MORE;
    if(p1->hasNamespaceUri && p1->namespaceUri != p2->namespaceUri)
        return (p1->namespaceUri < p2->namespaceUri) ? UA_ORDER_LESS : UA_ORDER_MORE;

    /* LocalizedText */
    if(p1->hasLocalizedText != p2->hasLocalizedText)
        return (!p1->hasLocalizedText) ? UA_ORDER_LESS : UA_ORDER_MORE;
    if(p1->hasLocalizedText && p1->localizedText != p2->localizedText)
        return (p1->localizedText < p2->localizedText) ? UA_ORDER_LESS : UA_ORDER_MORE;

    /* Locale */
    if(p1->hasLocale != p2->hasLocale)
        return (!p1->hasLocale) ? UA_ORDER_LESS : UA_ORDER_MORE;
    if(p1->hasLocale && p1->locale != p2->locale)
        return (p1->locale < p2->locale) ? UA_ORDER_LESS : UA_ORDER_MORE;

    /* AdditionalInfo */
    if(p1->hasAdditionalInfo != p2->hasAdditionalInfo)
        return (!p1->hasAdditionalInfo) ? UA_ORDER_LESS : UA_ORDER_MORE;
    if(p1->hasAdditionalInfo) {
        UA_Order o = stringOrder(&p1->additionalInfo, &p2->additionalInfo, NULL);
        if(o != UA_ORDER_EQ)
            return o;
    }

    /* InnerStatusCode */
    if(p1->hasInnerStatusCode != p2->hasInnerStatusCode)
        return (!p1->hasInnerStatusCode) ? UA_ORDER_LESS : UA_ORDER_MORE;
    if(p1->hasInnerStatusCode && p1->innerStatusCode != p2->innerStatusCode)
        return (p1->innerStatusCode < p2->innerStatusCode) ? UA_ORDER_LESS : UA_ORDER_MORE;

    /* InnerDiagnosticInfo */
    if(p1->hasInnerDiagnosticInfo != p2->hasInnerDiagnosticInfo)
        return (!p1->hasInnerDiagnosticInfo) ? UA_ORDER_LESS : UA_ORDER_MORE;
    if(p1->innerDiagnosticInfo == p2->innerDiagnosticInfo)
        return UA_ORDER_EQ;
    if(!p1->innerDiagnosticInfo || !p2->innerDiagnosticInfo)
        return (!p1->innerDiagnosticInfo) ? UA_ORDER_LESS : UA_ORDER_MORE;
    return diagnosticInfoOrder(p1->innerDiagnosticInfo, p2->innerDiagnosticInfo, NULL);
}

static UA_Order
structureOrder(const void *p1, const void *p2, const UA_DataType *type) {
    uintptr_t u1 = (uintptr_t)p1;
    uintptr_t u2 = (uintptr_t)p2;
    UA_Order o = UA_ORDER_EQ;
    for(size_t i = 0; i < type->membersSize; ++i) {
        const UA_DataTypeMember *m = &type->members[i];
        const UA_DataType *mt = m->memberType;
        u1 += m->padding;
        u2 += m->padding;
        if(!m->isOptional) {
            if(!m->isArray) {
                o = orderJumpTable[mt->typeKind]((const void *)u1, (const void *)u2, mt);
                u1 += mt->memSize;
                u2 += mt->memSize;
            } else {
                size_t size1 = *(size_t*)u1;
                size_t size2 = *(size_t*)u2;
                u1 += sizeof(size_t);
                u2 += sizeof(size_t);
                o = arrayOrder(*(void* const*)u1, size1, *(void* const*)u2, size2, mt);
                u1 += sizeof(void*);
                u2 += sizeof(void*);
            }
        } else {
            if(!m->isArray) {
                const void *pp1 = *(void* const*)u1;
                const void *pp2 = *(void* const*)u2;
                if(pp1 == pp2) {
                    o = UA_ORDER_EQ;
                } else if(pp1 == NULL) {
                    o = UA_ORDER_LESS;
                } else if(pp2 == NULL) {
                    o = UA_ORDER_MORE;
                } else {
                    o = orderJumpTable[mt->typeKind](pp1, pp2, mt);
                }
            } else {
                size_t sa1 = *(size_t*)u1;
                size_t sa2 = *(size_t*)u2;
                u1 += sizeof(size_t);
                u2 += sizeof(size_t);
                o = arrayOrder(*(void* const*)u1, sa1, *(void* const*)u2, sa2, mt);
            }
            u1 += sizeof(void*);
            u2 += sizeof(void*);
        }

        if(o != UA_ORDER_EQ)
            break;
    }
    return o;
}

static UA_Order
unionOrder(const void *p1, const void *p2, const UA_DataType *type) {
    UA_UInt32 sel1 = *(const UA_UInt32 *)p1;
    UA_UInt32 sel2 = *(const UA_UInt32 *)p2;
    if(sel1 != sel2)
        return (sel1 < sel2) ? UA_ORDER_LESS : UA_ORDER_MORE;

    if(sel1 == 0) {
        return UA_ORDER_EQ;
    }

    const UA_DataTypeMember *m = &type->members[sel1-1];
    const UA_DataType *mt = m->memberType;

    uintptr_t u1 = ((uintptr_t)p1) + m->padding; /* includes switchfield length */
    uintptr_t u2 = ((uintptr_t)p2) + m->padding;
    if(m->isArray) {
        size_t sa1 = *(size_t*)u1;
        size_t sa2 = *(size_t*)u2;
        u1 += sizeof(size_t);
        u2 += sizeof(size_t);
        return arrayOrder(*(void* const*)u1, sa1, *(void* const*)u2, sa2, mt);
    }
    return orderJumpTable[mt->typeKind]((const void*)u1, (const void*)u2, mt);
}

static UA_Order
notImplementedOrder(const void *p1, const void *p2, const UA_DataType *type) {
    return UA_ORDER_EQ;
}

const
UA_orderSignature orderJumpTable[UA_DATATYPEKINDS] = {
    (UA_orderSignature)booleanOrder,
    (UA_orderSignature)sByteOrder,
    (UA_orderSignature)byteOrder,
    (UA_orderSignature)int16Order,
    (UA_orderSignature)uInt16Order,
    (UA_orderSignature)int32Order,
    (UA_orderSignature)uInt32Order,
    (UA_orderSignature)int64Order,
    (UA_orderSignature)uInt64Order,
    (UA_orderSignature)floatOrder,
    (UA_orderSignature)doubleOrder,
    (UA_orderSignature)stringOrder,
    (UA_orderSignature)int64Order,  /* DateTime */
    (UA_orderSignature)guidOrder,
    (UA_orderSignature)stringOrder, /* ByteString */
    (UA_orderSignature)stringOrder, /* XmlElement */
    (UA_orderSignature)nodeIdOrder,
    (UA_orderSignature)expandedNodeIdOrder,
    (UA_orderSignature)uInt32Order, /* StatusCode */
    (UA_orderSignature)qualifiedNameOrder,
    (UA_orderSignature)localizedTextOrder,
    (UA_orderSignature)extensionObjectOrder,
    (UA_orderSignature)dataValueOrder,
    (UA_orderSignature)variantOrder,
    (UA_orderSignature)diagnosticInfoOrder,
    notImplementedOrder, /* Decimal, not implemented */
    (UA_orderSignature)uInt32Order, /* Enumeration */
    (UA_orderSignature)structureOrder,
    (UA_orderSignature)structureOrder, /* Struct with Optional Fields*/
    (UA_orderSignature)unionOrder, /* Union*/
    notImplementedOrder /* BitfieldCluster, not implemented */
};

UA_Order UA_order(const void *p1, const void *p2, const UA_DataType *type) {
    return orderJumpTable[type->typeKind](p1, p2, type);
}

UA_Boolean
UA_equal(const void *p1, const void *p2, const UA_DataType *type) {
    return (UA_order(p1, p2, type) == UA_ORDER_EQ);
}

/******************/
/* Array Handling */
/******************/

void *
UA_Array_new(size_t size, const UA_DataType *type) {
    if(size > UA_INT32_MAX)
        return NULL;
    if(size == 0)
        return UA_EMPTY_ARRAY_SENTINEL;
    return UA_calloc(size, type->memSize);
}

UA_StatusCode
UA_Array_copy(const void *src, size_t size,
              void **dst, const UA_DataType *type) {
    if(size == 0) {
        if(src == NULL)
            *dst = NULL;
        else
            *dst= UA_EMPTY_ARRAY_SENTINEL;
        return UA_STATUSCODE_GOOD;
    }

    /* Check the array consistency -- defensive programming in case the user
     * manually created an inconsistent array */
    if(UA_UNLIKELY(!type || !src))
        return UA_STATUSCODE_BADINTERNALERROR;

    /* calloc, so we don't have to check retval in every iteration of copying */
    *dst = UA_calloc(size, type->memSize);
    if(!*dst)
        return UA_STATUSCODE_BADOUTOFMEMORY;

    if(type->pointerFree) {
        memcpy(*dst, src, type->memSize * size);
        return UA_STATUSCODE_GOOD;
    }

    uintptr_t ptrs = (uintptr_t)src;
    uintptr_t ptrd = (uintptr_t)*dst;
    UA_StatusCode retval = UA_STATUSCODE_GOOD;
    for(size_t i = 0; i < size; ++i) {
        retval |= UA_copy((void*)ptrs, (void*)ptrd, type);
        ptrs += type->memSize;
        ptrd += type->memSize;
    }
    if(retval != UA_STATUSCODE_GOOD) {
        UA_Array_delete(*dst, size, type);
        *dst = NULL;
    }
    return retval;
}

UA_StatusCode
UA_Array_resize(void **p, size_t *size, size_t newSize,
                const UA_DataType *type) {
    if(*size == newSize)
        return UA_STATUSCODE_GOOD;

    /* Empty array? */
    if(newSize == 0) {
        UA_Array_delete(*p, *size, type);
        *p = UA_EMPTY_ARRAY_SENTINEL;
        *size = 0;
        return UA_STATUSCODE_GOOD;
    }

    /* Make a copy of the members that shall be removed. Realloc can fail during
     * trimming. So we cannot clear the members already here. */
    void *deleteMembers = NULL;
    if(newSize < *size && !type->pointerFree) {
        size_t deleteSize = *size - newSize;
        deleteMembers = UA_malloc(deleteSize * type->memSize);
        if(!deleteMembers)
            return UA_STATUSCODE_BADOUTOFMEMORY;
        memcpy(deleteMembers, (void*)((uintptr_t)*p + (newSize * type->memSize)),
               deleteSize * type->memSize); /* shallow copy */
    }

    void *oldP = *p;
    if(oldP == UA_EMPTY_ARRAY_SENTINEL)
        oldP = NULL;

    /* Realloc */
    void *newP = UA_realloc(oldP, newSize * type->memSize);
    if(!newP) {
        if(deleteMembers)
            UA_free(deleteMembers);
        return UA_STATUSCODE_BADOUTOFMEMORY;
    }

    /* Clear removed members or initialize the new ones. Note that deleteMembers
     * depends on type->pointerFree. */
    if(newSize > *size) {
        memset((void*)((uintptr_t)newP + (*size * type->memSize)), 0,
               (newSize - *size) * type->memSize);
    } else if(deleteMembers) {
        UA_Array_delete(deleteMembers, *size - newSize, type);
    }

    /* Set the new array */
    *p = newP;
    *size = newSize;
    return UA_STATUSCODE_GOOD;
}

UA_StatusCode
UA_Array_append(void **p, size_t *size, void *newElem,
                const UA_DataType *type) {
    /* Resize the array */
    size_t oldSize = *size;
    UA_StatusCode res = UA_Array_resize(p, size, oldSize+1, type);
    if(res != UA_STATUSCODE_GOOD)
        return res;

    /* Move the value */
    memcpy((void*)((uintptr_t)*p + (oldSize * type->memSize)),
           newElem, type->memSize);
    UA_init(newElem, type);
    return UA_STATUSCODE_GOOD;
}

UA_StatusCode
UA_Array_appendCopy(void **p, size_t *size, const void *newElem,
                    const UA_DataType *type) {
    char scratch[512];
    if(type->memSize > 512)
        return UA_STATUSCODE_BADINTERNALERROR;

    /* Copy the value */
    UA_StatusCode res = UA_copy(newElem, (void*)scratch, type);
    if(res != UA_STATUSCODE_GOOD)
        return res;

    /* Append */
    res = UA_Array_append(p, size, (void*)scratch, type);
    if(res != UA_STATUSCODE_GOOD)
        UA_clear((void*)scratch, type);
    return res;
}

void
UA_Array_delete(void *p, size_t size, const UA_DataType *type) {
    if(!type->pointerFree) {
        uintptr_t ptr = (uintptr_t)p;
        for(size_t i = 0; i < size; ++i) {
            UA_clear((void*)ptr, type);
            ptr += type->memSize;
        }
    }
    UA_free((void*)((uintptr_t)p & ~(uintptr_t)UA_EMPTY_ARRAY_SENTINEL));
}

#ifdef UA_ENABLE_TYPEDESCRIPTION
UA_Boolean
UA_DataType_getStructMember(const UA_DataType *type, const char *memberName,
                            size_t *outOffset, const UA_DataType **outMemberType,
                            UA_Boolean *outIsArray) {
    if(type->typeKind != UA_DATATYPEKIND_STRUCTURE &&
       type->typeKind != UA_DATATYPEKIND_OPTSTRUCT)
        return false;

    size_t offset = 0;
    for(size_t i = 0; i < type->membersSize; ++i) {
        const UA_DataTypeMember *m = &type->members[i];
        const UA_DataType *mt = m->memberType;
        offset += m->padding;

        if(strcmp(memberName, m->memberName) == 0) {
            *outOffset = offset;
            *outMemberType = mt;
            *outIsArray = m->isArray;
            return true;
        }

        if(!m->isOptional) {
            if(!m->isArray) {
                offset += mt->memSize;
            } else {
                offset += sizeof(size_t);
                offset += sizeof(void*);
            }
        } else { /* field is optional */
            if(!m->isArray) {
                offset += sizeof(void *);
            } else {
                offset += sizeof(size_t);
                offset += sizeof(void *);
            }
        }
    }

    return false;
}
#endif

UA_Boolean
UA_DataType_isNumeric(const UA_DataType *type) {
    switch(type->typeKind) {
    case UA_DATATYPEKIND_SBYTE:
    case UA_DATATYPEKIND_BYTE:
    case UA_DATATYPEKIND_INT16:
    case UA_DATATYPEKIND_UINT16:
    case UA_DATATYPEKIND_INT32:
    case UA_DATATYPEKIND_UINT32:
    case UA_DATATYPEKIND_INT64:
    case UA_DATATYPEKIND_UINT64:
    case UA_DATATYPEKIND_FLOAT:
    case UA_DATATYPEKIND_DOUBLE:
    /* not implemented: UA_DATATYPEKIND_DECIMAL */
        return true;
    default:
        return false;
    }
}

/**********************/
/* Parse NumericRange */
/**********************/

static size_t
readDimension(UA_Byte *buf, size_t buflen, UA_NumericRangeDimension *dim) {
    size_t progress = UA_readNumber(buf, buflen, &dim->min);
    if(progress == 0)
        return 0;
    if(buflen <= progress + 1 || buf[progress] != ':') {
        dim->max = dim->min;
        return progress;
    }

    ++progress;
    size_t progress2 = UA_readNumber(&buf[progress], buflen - progress, &dim->max);
    if(progress2 == 0)
        return 0;

    /* invalid range */
    if(dim->min >= dim->max)
        return 0;

    return progress + progress2;
}

UA_StatusCode
UA_NumericRange_parse(UA_NumericRange *range, const UA_String str) {
    size_t idx = 0;
    size_t dimensionsMax = 0;
    UA_NumericRangeDimension *dimensions = NULL;
    UA_StatusCode retval = UA_STATUSCODE_GOOD;
    size_t offset = 0;
    while(true) {
        /* alloc dimensions */
        if(idx >= dimensionsMax) {
            UA_NumericRangeDimension *newds;
            size_t newdssize = sizeof(UA_NumericRangeDimension) * (dimensionsMax + 2);
            newds = (UA_NumericRangeDimension*)UA_realloc(dimensions, newdssize);
            if(!newds) {
                retval = UA_STATUSCODE_BADOUTOFMEMORY;
                break;
            }
            dimensions = newds;
            dimensionsMax = dimensionsMax + 2;
        }

        /* read the dimension */
        size_t progress = readDimension(&str.data[offset], str.length - offset,
                                        &dimensions[idx]);
        if(progress == 0) {
            retval = UA_STATUSCODE_BADINDEXRANGEINVALID;
            break;
        }
        offset += progress;
        ++idx;

        /* loop into the next dimension */
        if(offset >= str.length)
            break;

        if(str.data[offset] != ',') {
            retval = UA_STATUSCODE_BADINDEXRANGEINVALID;
            break;
        }
        ++offset;
    }

    if(retval == UA_STATUSCODE_GOOD && idx > 0) {
        range->dimensions = dimensions;
        range->dimensionsSize = idx;
    } else {
        UA_free(dimensions);
    }

    return retval;
}

UA_NumericRange
UA_NUMERICRANGE(const char *s) {
    UA_NumericRange nr;
    memset(&nr, 0, sizeof(nr));
    UA_NumericRange_parse(&nr, UA_STRING((char*)(uintptr_t)s));
    return nr;
}

/*********************/
/* Namespace Mapping */
/*********************/

UA_UInt16
UA_NamespaceMapping_local2Remote(const UA_NamespaceMapping *nm,
                                 UA_UInt16 localIndex) {
    if(localIndex >= nm->local2remoteSize)
        return UA_UINT16_MAX - localIndex;
    return nm->local2remote[localIndex];
}

UA_UInt16
UA_NamespaceMapping_remote2Local(const UA_NamespaceMapping *nm,
                                 UA_UInt16 remoteIndex) {
    if(remoteIndex >= nm->remote2localSize)
        return UA_UINT16_MAX - remoteIndex;
    return nm->remote2local[remoteIndex];
}

/* Returns an error if the uri was not found.
 * The pointer to the index argument needs to be non-NULL. */
UA_StatusCode
UA_NamespaceMapping_uri2Index(const UA_NamespaceMapping *nm,
                              UA_String uri, UA_UInt16 *index) {
    for(size_t i = 0; i < nm->namespaceUrisSize; i++) {
        if(UA_String_equal(&uri, &nm->namespaceUris[i])) {
            *index = (UA_UInt16)i;
            return UA_STATUSCODE_GOOD;
        }
    }
    return UA_STATUSCODE_BADNOTFOUND;
}

UA_StatusCode
UA_NamespaceMapping_index2Uri(const UA_NamespaceMapping *nm,
                              UA_UInt16 index, UA_String *uri) {
    if(nm->namespaceUrisSize <= index)
        return UA_STATUSCODE_BADNOTFOUND;
    *uri = nm->namespaceUris[index];
    return UA_STATUSCODE_GOOD;
}

void
UA_NamespaceMapping_clear(UA_NamespaceMapping *nm) {
    if(!nm)
        return;
    UA_Array_delete(nm->namespaceUris, nm->namespaceUrisSize, &UA_TYPES[UA_TYPES_STRING]);
    UA_Array_delete(nm->local2remote, nm->local2remoteSize, &UA_TYPES[UA_TYPES_UINT16]);
    UA_Array_delete(nm->remote2local, nm->remote2localSize, &UA_TYPES[UA_TYPES_UINT16]);
    nm->namespaceUris = NULL;
    nm->local2remote = NULL;
    nm->remote2local = NULL;
    nm->namespaceUrisSize = 0;
    nm->local2remoteSize = 0;
    nm->remote2localSize = 0;
}

void
UA_NamespaceMapping_delete(UA_NamespaceMapping *nm) {
    UA_NamespaceMapping_clear(nm);
    UA_free(nm);
}