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
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
use std::collections::{Bound, HashMap};
use std::ffi::{c_char, c_void, CStr, CString};
use std::mem::{forget, ManuallyDrop, MaybeUninit};
use std::ops::{Deref, RangeBounds};
use std::ptr::{null, null_mut};
use std::sync::atomic::{AtomicPtr, Ordering};
use std::sync::Arc;
use yrs::block::{ClientID, ItemContent, Prelim, Unused};
use yrs::branch::BranchPtr;
use yrs::encoding::read::Error;
use yrs::types::array::ArrayEvent;
use yrs::types::array::ArrayIter as NativeArrayIter;
use yrs::types::map::MapEvent;
use yrs::types::map::MapIter as NativeMapIter;
use yrs::types::text::{Diff, TextEvent, YChange};
use yrs::types::weak::{LinkSource, Unquote as NativeUnquote, WeakEvent, WeakRef};
use yrs::types::xml::{Attributes as NativeAttributes, XmlNode};
use yrs::types::xml::{TreeWalker as NativeTreeWalker, XmlFragment};
use yrs::types::xml::{XmlEvent, XmlTextEvent};
use yrs::types::{Attrs, Change, Delta, EntryChange, Event, PathSegment, TypeRef, Value};
use yrs::undo::EventKind;
use yrs::updates::decoder::{Decode, DecoderV1};
use yrs::updates::encoder::{Encode, Encoder, EncoderV1, EncoderV2};
use yrs::{
    uuid_v4, Any, Array, ArrayRef, Assoc, BranchID, DeleteSet, GetString, Map, MapRef, Observable,
    OffsetKind, Options, Origin, Quotable, ReadTxn, Snapshot, StateVector, StickyIndex, Store,
    SubdocsEvent, SubdocsEventIter, Text, TextRef, Transact, TransactionCleanupEvent, Update, Xml,
    XmlElementPrelim, XmlElementRef, XmlFragmentRef, XmlTextPrelim, XmlTextRef, ID,
};

/// Flag used by `YInput` and `YOutput` to tag boolean values.
pub const Y_JSON_BOOL: i8 = -8;

/// Flag used by `YInput` and `YOutput` to tag floating point numbers.
pub const Y_JSON_NUM: i8 = -7;

/// Flag used by `YInput` and `YOutput` to tag 64-bit integer numbers.
pub const Y_JSON_INT: i8 = -6;

/// Flag used by `YInput` and `YOutput` to tag strings.
pub const Y_JSON_STR: i8 = -5;

/// Flag used by `YInput` and `YOutput` to tag binary content.
pub const Y_JSON_BUF: i8 = -4;

/// Flag used by `YInput` and `YOutput` to tag embedded JSON-like arrays of values,
/// which themselves are `YInput` and `YOutput` instances respectively.
pub const Y_JSON_ARR: i8 = -3;

/// Flag used by `YInput` and `YOutput` to tag embedded JSON-like maps of key-value pairs,
/// where keys are strings and v
pub const Y_JSON_MAP: i8 = -2;

/// Flag used by `YInput` and `YOutput` to tag JSON-like null values.
pub const Y_JSON_NULL: i8 = -1;

/// Flag used by `YInput` and `YOutput` to tag JSON-like undefined values.
pub const Y_JSON_UNDEF: i8 = 0;

/// Flag used by `YInput` and `YOutput` to tag content, which is an `YArray` shared type.
pub const Y_ARRAY: i8 = 1;

/// Flag used by `YInput` and `YOutput` to tag content, which is an `YMap` shared type.
pub const Y_MAP: i8 = 2;

/// Flag used by `YInput` and `YOutput` to tag content, which is an `YText` shared type.
pub const Y_TEXT: i8 = 3;

/// Flag used by `YInput` and `YOutput` to tag content, which is an `YXmlElement` shared type.
pub const Y_XML_ELEM: i8 = 4;

/// Flag used by `YInput` and `YOutput` to tag content, which is an `YXmlText` shared type.
pub const Y_XML_TEXT: i8 = 5;

/// Flag used by `YInput` and `YOutput` to tag content, which is an `YXmlFragment` shared type.
pub const Y_XML_FRAG: i8 = 6;

/// Flag used by `YInput` and `YOutput` to tag content, which is an `YDoc` shared type.
pub const Y_DOC: i8 = 7;

/// Flag used by `YInput` and `YOutput` to tag content, which is an `YWeakLink` shared type.
pub const Y_WEAK_LINK: i8 = 8;

/// Flag used by `YOutput` to tag content, which is an undefined shared type. This usually happens
/// when it's referencing a root type that has not been initalized localy.
pub const Y_UNDEFINED: i8 = 9;

/// Flag used to mark a truthy boolean numbers.
pub const Y_TRUE: u8 = 1;

/// Flag used to mark a falsy boolean numbers.
pub const Y_FALSE: u8 = 0;

/// Flag used by `YOptions` to determine, that text operations offsets and length will be counted by
/// the byte number of UTF8-encoded string.
pub const Y_OFFSET_BYTES: u8 = 0;

/// Flag used by `YOptions` to determine, that text operations offsets and length will be counted by
/// UTF-16 chars of encoded string.
pub const Y_OFFSET_UTF16: u8 = 1;

/* pub types below are used by cbindgen for c header generation */

/// A Yrs document type. Documents are the most important units of collaborative resources management.
/// All shared collections live within a scope of their corresponding documents. All updates are
/// generated on per-document basis (rather than individual shared type). All operations on shared
/// collections happen via `YTransaction`, which lifetime is also bound to a document.
///
/// Document manages so-called root types, which are top-level shared types definitions (as opposed
/// to recursively nested types).
pub type Doc = yrs::Doc;

/// A common shared data type. All Yrs instances can be refered to using this data type (use
/// `ytype_kind` function if a specific type needs to be determined). Branch pointers are passed
/// over type-specific functions like `ytext_insert`, `yarray_insert` or `ymap_insert` to perform
/// a specific shared type operations.
///
/// Using write methods of different shared types (eg. `ytext_insert` and `yarray_insert`) over
/// the same branch may result in undefined behavior.
pub type Branch = yrs::branch::Branch;

/// Subscription to any kind of observable events, like `ymap_observe`, `ydoc_observe_updates_v1` etc.
/// This subscription can be destroyed by calling `yunobserve` function, which will cause to unsubscribe
/// correlated callback.
pub type Subscription = yrs::Subscription;

/// Iterator structure used by shared array data type.
#[repr(transparent)]
pub struct ArrayIter(NativeArrayIter<&'static Transaction, Transaction>);

/// Iterator structure used by `yweak_iter` function call.
#[repr(transparent)]
pub struct WeakIter(NativeUnquote<'static, Transaction>);

/// Iterator structure used by shared map data type. Map iterators are unordered - there's no
/// specific order in which map entries will be returned during consecutive iterator calls.
#[repr(transparent)]
pub struct MapIter(NativeMapIter<'static, &'static Transaction, Transaction>);

/// Iterator structure used by XML nodes (elements and text) to iterate over node's attributes.
/// Attribute iterators are unordered - there's no specific order in which map entries will be
/// returned during consecutive iterator calls.
#[repr(transparent)]
pub struct Attributes(NativeAttributes<'static, &'static Transaction, Transaction>);

/// Iterator used to traverse over the complex nested tree structure of a XML node. XML node
/// iterator walks only over `YXmlElement` and `YXmlText` nodes. It does so in ordered manner (using
/// the order in which children are ordered within their parent nodes) and using **depth-first**
/// traverse.
#[repr(transparent)]
pub struct TreeWalker(NativeTreeWalker<'static, &'static Transaction, Transaction>);

/// Transaction is one of the core types in Yrs. All operations that need to touch or
/// modify a document's contents (a.k.a. block store), need to be executed in scope of a
/// transaction.
#[repr(transparent)]
pub struct Transaction(TransactionInner);

enum TransactionInner {
    ReadOnly(yrs::Transaction<'static>),
    ReadWrite(yrs::TransactionMut<'static>),
}

impl Transaction {
    fn read_only(txn: yrs::Transaction) -> Self {
        Transaction(TransactionInner::ReadOnly(unsafe {
            std::mem::transmute(txn)
        }))
    }

    fn read_write(txn: yrs::TransactionMut) -> Self {
        Transaction(TransactionInner::ReadWrite(unsafe {
            std::mem::transmute(txn)
        }))
    }

    fn is_writeable(&self) -> bool {
        match &self.0 {
            TransactionInner::ReadOnly(_) => false,
            TransactionInner::ReadWrite(_) => true,
        }
    }

    fn as_mut(&mut self) -> Option<&mut yrs::TransactionMut<'static>> {
        match &mut self.0 {
            TransactionInner::ReadOnly(_) => None,
            TransactionInner::ReadWrite(txn) => Some(txn),
        }
    }
}

impl ReadTxn for Transaction {
    fn store(&self) -> &Store {
        match &self.0 {
            TransactionInner::ReadOnly(txn) => txn.store(),
            TransactionInner::ReadWrite(txn) => txn.store(),
        }
    }
}

/// A structure representing single key-value entry of a map output (used by either
/// embedded JSON-like maps or YMaps).
#[repr(C)]
pub struct YMapEntry {
    /// Null-terminated string representing an entry's key component. Encoded as UTF-8.
    pub key: *const c_char,
    /// A `YOutput` value representing containing variadic content that can be stored withing map's
    /// entry.
    pub value: YOutput,
}

impl YMapEntry {
    fn new(key: &str, value: Value) -> Self {
        let value = YOutput::from(value);
        YMapEntry {
            key: CString::new(key).unwrap().into_raw(),
            value,
        }
    }
}

impl Drop for YMapEntry {
    fn drop(&mut self) {
        unsafe {
            drop(CString::from_raw(self.key as *mut c_char));
            //self.value.drop();
        }
    }
}

/// A structure representing single attribute of an either `YXmlElement` or `YXmlText` instance.
/// It consists of attribute name and string, both of which are null-terminated UTF-8 strings.
#[repr(C)]
pub struct YXmlAttr {
    pub name: *const c_char,
    pub value: *const c_char,
}

impl Drop for YXmlAttr {
    fn drop(&mut self) {
        unsafe {
            drop(CString::from_raw(self.name as *mut _));
            drop(CString::from_raw(self.value as *mut _));
        }
    }
}

/// Configuration object used by `YDoc`.
#[repr(C)]
pub struct YOptions {
    /// Globally unique 53-bit integer assigned to corresponding document replica as its identifier.
    ///
    /// If two clients share the same `id` and will perform any updates, it will result in
    /// unrecoverable document state corruption. The same thing may happen if the client restored
    /// document state from snapshot, that didn't contain all of that clients updates that were sent
    /// to other peers.
    pub id: u64,

    /// A NULL-able globally unique Uuid v4 compatible null-terminated string identifier
    /// of this document. If passed as NULL, a random Uuid will be generated instead.
    pub guid: *const c_char,

    /// A NULL-able, UTF-8 encoded, null-terminated string of a collection that this document
    /// belongs to. It's used only by providers.
    pub collection_id: *const c_char,

    /// Encoding used by text editing operations on this document. It's used to compute
    /// `YText`/`YXmlText` insertion offsets and text lengths. Either:
    ///
    /// - `Y_OFFSET_BYTES`
    /// - `Y_OFFSET_UTF16`
    pub encoding: u8,

    /// Boolean flag used to determine if deleted blocks should be garbage collected or not
    /// during the transaction commits. Setting this value to 0 means GC will be performed.
    pub skip_gc: u8,

    /// Boolean flag used to determine if subdocument should be loaded automatically.
    /// If this is a subdocument, remote peers will load the document as well automatically.
    pub auto_load: u8,

    /// Boolean flag used to determine whether the document should be synced by the provider now.
    pub should_load: u8,
}

impl Into<Options> for YOptions {
    fn into(self) -> Options {
        let encoding = match self.encoding {
            Y_OFFSET_BYTES => OffsetKind::Bytes,
            Y_OFFSET_UTF16 => OffsetKind::Utf16,
            _ => panic!("Unrecognized YOptions.encoding type"),
        };
        let guid = if self.guid.is_null() {
            uuid_v4()
        } else {
            let c_str = unsafe { CStr::from_ptr(self.guid) };
            let str = c_str.to_str().unwrap();
            str.into()
        };
        let collection_id = if self.collection_id.is_null() {
            None
        } else {
            let c_str = unsafe { CStr::from_ptr(self.collection_id) };
            let str = c_str.to_str().unwrap().to_string();
            Some(str)
        };
        Options {
            client_id: self.id as ClientID,
            guid,
            collection_id,
            skip_gc: if self.skip_gc == 0 { false } else { true },
            auto_load: if self.auto_load == 0 { false } else { true },
            should_load: if self.should_load == 0 { false } else { true },
            offset_kind: encoding,
        }
    }
}

impl From<Options> for YOptions {
    fn from(o: Options) -> Self {
        YOptions {
            id: o.client_id,
            guid: CString::new(o.guid.as_ref()).unwrap().into_raw(),
            collection_id: if let Some(collection_id) = o.collection_id {
                CString::new(collection_id).unwrap().into_raw()
            } else {
                null_mut()
            },
            encoding: match o.offset_kind {
                OffsetKind::Bytes => Y_OFFSET_BYTES,
                OffsetKind::Utf16 => Y_OFFSET_UTF16,
            },
            skip_gc: if o.skip_gc { 1 } else { 0 },
            auto_load: if o.auto_load { 1 } else { 0 },
            should_load: if o.should_load { 1 } else { 0 },
        }
    }
}

/// Returns default ceonfiguration for `YOptions`.
#[no_mangle]
pub unsafe extern "C" fn yoptions() -> YOptions {
    Options::default().into()
}

/// Releases all memory-allocated resources bound to given document.
#[no_mangle]
pub unsafe extern "C" fn ydoc_destroy(value: *mut Doc) {
    if !value.is_null() {
        drop(Box::from_raw(value));
    }
}

/// Frees all memory-allocated resources bound to a given [YMapEntry].
#[no_mangle]
pub unsafe extern "C" fn ymap_entry_destroy(value: *mut YMapEntry) {
    if !value.is_null() {
        drop(Box::from_raw(value));
    }
}

/// Frees all memory-allocated resources bound to a given [YXmlAttr].
#[no_mangle]
pub unsafe extern "C" fn yxmlattr_destroy(attr: *mut YXmlAttr) {
    if !attr.is_null() {
        drop(Box::from_raw(attr));
    }
}

/// Frees all memory-allocated resources bound to a given UTF-8 null-terminated string returned from
/// Yrs document API. Yrs strings don't use libc malloc, so calling `free()` on them will fault.
#[no_mangle]
pub unsafe extern "C" fn ystring_destroy(str: *mut c_char) {
    if !str.is_null() {
        drop(CString::from_raw(str));
    }
}

/// Frees all memory-allocated resources bound to a given binary returned from Yrs document API.
/// Unlike strings binaries are not null-terminated and can contain null characters inside,
/// therefore a size of memory to be released must be explicitly provided.
/// Yrs binaries don't use libc malloc, so calling `free()` on them will fault.
#[no_mangle]
pub unsafe extern "C" fn ybinary_destroy(ptr: *mut c_char, len: u32) {
    if !ptr.is_null() {
        drop(Vec::from_raw_parts(ptr, len as usize, len as usize));
    }
}

/// Creates a new [Doc] instance with a randomized unique client identifier.
///
/// Use [ydoc_destroy] in order to release created [Doc] resources.
#[no_mangle]
pub extern "C" fn ydoc_new() -> *mut Doc {
    Box::into_raw(Box::new(Doc::new()))
}

/// Creates a shallow clone of a provided `doc` - it's realized by increasing the ref-count
/// value of the document. In result both input and output documents point to the same instance.
///
/// Documents created this way can be destroyed via [ydoc_destroy] - keep in mind, that the memory
/// will still be persisted until all strong references are dropped.
#[no_mangle]
pub unsafe extern "C" fn ydoc_clone(doc: *mut Doc) -> *mut Doc {
    let doc = doc.as_mut().unwrap();
    Box::into_raw(Box::new(doc.clone()))
}

/// Creates a new [Doc] instance with a specified `options`.
///
/// Use [ydoc_destroy] in order to release created [Doc] resources.
#[no_mangle]
pub extern "C" fn ydoc_new_with_options(options: YOptions) -> *mut Doc {
    Box::into_raw(Box::new(Doc::with_options(options.into())))
}

/// Returns a unique client identifier of this [Doc] instance.
#[no_mangle]
pub unsafe extern "C" fn ydoc_id(doc: *mut Doc) -> u64 {
    let doc = doc.as_ref().unwrap();
    doc.client_id()
}

/// Returns a unique document identifier of this [Doc] instance.
///
/// Generated string resources should be released using [ystring_destroy] function.
#[no_mangle]
pub unsafe extern "C" fn ydoc_guid(doc: *mut Doc) -> *mut c_char {
    let doc = doc.as_ref().unwrap();
    let uid = &doc.options().guid;
    CString::new(uid.as_ref()).unwrap().into_raw()
}

/// Returns a collection identifier of this [Doc] instance.
/// If none was defined, a `NULL` will be returned.
///
/// Generated string resources should be released using [ystring_destroy] function.
#[no_mangle]
pub unsafe extern "C" fn ydoc_collection_id(doc: *mut Doc) -> *mut c_char {
    let doc = doc.as_ref().unwrap();
    if let Some(cid) = doc.options().collection_id.as_ref() {
        CString::new(cid.as_str()).unwrap().into_raw()
    } else {
        null_mut()
    }
}

/// Returns status of should_load flag of this [Doc] instance, informing parent [Doc] if this
/// document instance requested a data load.
#[no_mangle]
pub unsafe extern "C" fn ydoc_should_load(doc: *mut Doc) -> u8 {
    let doc = doc.as_ref().unwrap();
    doc.options().should_load as u8
}

/// Returns status of auto_load flag of this [Doc] instance. Auto loaded sub-documents automatically
/// send a load request to their parent documents.
#[no_mangle]
pub unsafe extern "C" fn ydoc_auto_load(doc: *mut Doc) -> u8 {
    let doc = doc.as_ref().unwrap();
    doc.options().auto_load as u8
}

#[no_mangle]
pub unsafe extern "C" fn ydoc_observe_updates_v1(
    doc: *mut Doc,
    state: *mut c_void,
    cb: extern "C" fn(*mut c_void, u32, *const c_char),
) -> *mut Subscription {
    let doc = doc.as_ref().unwrap();
    let subscription = doc
        .observe_update_v1(move |_, e| {
            let bytes = &e.update;
            let len = bytes.len() as u32;
            cb(state, len, bytes.as_ptr() as *const c_char)
        })
        .unwrap();
    Box::into_raw(Box::new(subscription))
}

#[no_mangle]
pub unsafe extern "C" fn ydoc_observe_updates_v2(
    doc: *mut Doc,
    state: *mut c_void,
    cb: extern "C" fn(*mut c_void, u32, *const c_char),
) -> *mut Subscription {
    let doc = doc.as_ref().unwrap();
    let subscription = doc
        .observe_update_v2(move |_, e| {
            let bytes = &e.update;
            let len = bytes.len() as u32;
            cb(state, len, bytes.as_ptr() as *const c_char)
        })
        .unwrap();
    Box::into_raw(Box::new(subscription))
}

#[no_mangle]
pub unsafe extern "C" fn ydoc_observe_after_transaction(
    doc: *mut Doc,
    state: *mut c_void,
    cb: extern "C" fn(*mut c_void, *mut YAfterTransactionEvent),
) -> *mut Subscription {
    let doc = doc.as_ref().unwrap();
    let subscription = doc
        .observe_transaction_cleanup(move |_, e| {
            let mut event = YAfterTransactionEvent::new(e);
            cb(state, (&mut event) as *mut _);
        })
        .unwrap();
    Box::into_raw(Box::new(subscription))
}

#[no_mangle]
pub unsafe extern "C" fn ydoc_observe_subdocs(
    doc: *mut Doc,
    state: *mut c_void,
    cb: extern "C" fn(*mut c_void, *mut YSubdocsEvent),
) -> *mut Subscription {
    let doc = doc.as_mut().unwrap();
    let subscription = doc
        .observe_subdocs(move |_, e| {
            let mut event = YSubdocsEvent::new(e);
            cb(state, (&mut event) as *mut _);
        })
        .unwrap();
    Box::into_raw(Box::new(subscription))
}

#[no_mangle]
pub unsafe extern "C" fn ydoc_observe_clear(
    doc: *mut Doc,
    state: *mut c_void,
    cb: extern "C" fn(*mut c_void, *mut Doc),
) -> *mut Subscription {
    let doc = doc.as_mut().unwrap();
    let subscription = doc
        .observe_destroy(move |_, e| cb(state, e as *const Doc as *mut _))
        .unwrap();
    Box::into_raw(Box::new(subscription))
}

/// Manually send a load request to a parent document of this subdoc.
#[no_mangle]
pub unsafe extern "C" fn ydoc_load(doc: *mut Doc, parent_txn: *mut Transaction) {
    let doc = doc.as_ref().unwrap();
    let txn = parent_txn.as_mut().unwrap();
    if let Some(txn) = txn.as_mut() {
        doc.load(txn)
    } else {
        panic!("ydoc_load: passed read-only parent transaction, where read-write one was expected")
    }
}

/// Destroys current document, sending a 'destroy' event and clearing up all the event callbacks
/// registered.
#[no_mangle]
pub unsafe extern "C" fn ydoc_clear(doc: *mut Doc, parent_txn: *mut Transaction) {
    let doc = doc.as_mut().unwrap();
    let txn = parent_txn.as_mut().unwrap();
    if let Some(txn) = txn.as_mut() {
        doc.destroy(txn)
    } else {
        panic!("ydoc_clear: passed read-only parent transaction, where read-write one was expected")
    }
}

/// Starts a new read-only transaction on a given document. All other operations happen in context
/// of a transaction. Yrs transactions do not follow ACID rules. Once a set of operations is
/// complete, a transaction can be finished using `ytransaction_commit` function.
///
/// Returns `NULL` if read-only transaction couldn't be created, i.e. when another read-write
/// transaction is already opened.
#[no_mangle]
pub unsafe extern "C" fn ydoc_read_transaction(doc: *mut Doc) -> *mut Transaction {
    assert!(!doc.is_null());

    let doc = doc.as_mut().unwrap();
    if let Ok(txn) = doc.try_transact() {
        Box::into_raw(Box::new(Transaction::read_only(txn)))
    } else {
        null_mut()
    }
}

/// Starts a new read-write transaction on a given document. All other operations happen in context
/// of a transaction. Yrs transactions do not follow ACID rules. Once a set of operations is
/// complete, a transaction can be finished using `ytransaction_commit` function.
///
/// `origin_len` and `origin` are optional parameters to specify a byte sequence used to mark
/// the origin of this transaction (eg. you may decide to give different origins for transaction
/// applying remote updates). These can be used by event handlers or `YUndoManager` to perform
/// specific actions. If origin should not be set, call `ydoc_write_transaction(doc, 0, NULL)`.
///
/// Returns `NULL` if read-write transaction couldn't be created, i.e. when another transaction is
/// already opened.
#[no_mangle]
pub unsafe extern "C" fn ydoc_write_transaction(
    doc: *mut Doc,
    origin_len: u32,
    origin: *const c_char,
) -> *mut Transaction {
    assert!(!doc.is_null());

    let doc = doc.as_mut().unwrap();
    if origin_len == 0 {
        if let Ok(txn) = doc.try_transact_mut() {
            Box::into_raw(Box::new(Transaction::read_write(txn)))
        } else {
            null_mut()
        }
    } else {
        let origin = std::slice::from_raw_parts(origin as *const u8, origin_len as usize);
        if let Ok(txn) = doc.try_transact_mut_with(origin) {
            Box::into_raw(Box::new(Transaction::read_write(txn)))
        } else {
            null_mut()
        }
    }
}

/// Returns a list of subdocs existing within current document.
#[no_mangle]
pub unsafe extern "C" fn ytransaction_subdocs(
    txn: *mut Transaction,
    len: *mut u32,
) -> *mut *mut Doc {
    let txn = txn.as_ref().unwrap();
    let subdocs: Vec<_> = txn
        .subdocs()
        .map(|doc| doc as *const Doc as *mut Doc)
        .collect();
    let out = subdocs.into_boxed_slice();
    *len = out.len() as u32;
    Box::into_raw(out) as *mut _
}

/// Commit and dispose provided read-write transaction. This operation releases allocated resources,
/// triggers update events and performs a storage compression over all operations executed in scope
/// of a current transaction.
#[no_mangle]
pub unsafe extern "C" fn ytransaction_commit(txn: *mut Transaction) {
    assert!(!txn.is_null());
    drop(Box::from_raw(txn)); // transaction is auto-committed when dropped
}

/// Returns `1` if current transaction is of read-write type.
/// Returns `0` if transaction is read-only.
#[no_mangle]
pub unsafe extern "C" fn ytransaction_writeable(txn: *mut Transaction) -> u8 {
    assert!(!txn.is_null());
    if txn.as_ref().unwrap().is_writeable() {
        1
    } else {
        0
    }
}

/// Gets a reference to shared data type instance at the document root-level,
/// identified by its `name`, which must be a null-terminated UTF-8 compatible string.
///
/// Returns `NULL` if no such structure was defined in the document before.
// TODO [LSViana] Rename this to `ytransaction_get_ytype()` (or similar) to match the signature.
#[no_mangle]
pub unsafe extern "C" fn ytype_get(txn: *mut Transaction, name: *const c_char) -> *mut Branch {
    assert!(!txn.is_null());
    assert!(!name.is_null());

    let name = CStr::from_ptr(name).to_str().unwrap();
    //NOTE: we're retrieving this as a text, but ultimatelly it doesn't matter as we don't define
    // nor redefine the underlying branch type
    if let Some(txt) = txn.as_mut().unwrap().get_text(name) {
        txt.into_raw_branch()
    } else {
        null_mut()
    }
}

/// Gets or creates a new shared `YText` data type instance as a root-level type of a given document.
/// This structure can later be accessed using its `name`, which must be a null-terminated UTF-8
/// compatible string.
#[no_mangle]
pub unsafe extern "C" fn ytext(doc: *mut Doc, name: *const c_char) -> *mut Branch {
    assert!(!doc.is_null());
    assert!(!name.is_null());

    let name = CStr::from_ptr(name).to_str().unwrap();
    let txt = doc.as_mut().unwrap().get_or_insert_text(name);
    txt.into_raw_branch()
}

/// Gets or creates a new shared `YArray` data type instance as a root-level type of a given document.
/// This structure can later be accessed using its `name`, which must be a null-terminated UTF-8
/// compatible string.
///
/// Use [yarray_destroy] in order to release pointer returned that way - keep in mind that this will
/// not remove `YArray` instance from the document itself (once created it'll last for the entire
/// lifecycle of a document).
#[no_mangle]
pub unsafe extern "C" fn yarray(doc: *mut Doc, name: *const c_char) -> *mut Branch {
    assert!(!doc.is_null());
    assert!(!name.is_null());

    let name = CStr::from_ptr(name).to_str().unwrap();
    doc.as_mut()
        .unwrap()
        .get_or_insert_array(name)
        .into_raw_branch()
}

/// Gets or creates a new shared `YMap` data type instance as a root-level type of a given document.
/// This structure can later be accessed using its `name`, which must be a null-terminated UTF-8
/// compatible string.
///
/// Use [ymap_destroy] in order to release pointer returned that way - keep in mind that this will
/// not remove `YMap` instance from the document itself (once created it'll last for the entire
/// lifecycle of a document).
#[no_mangle]
pub unsafe extern "C" fn ymap(doc: *mut Doc, name: *const c_char) -> *mut Branch {
    assert!(!doc.is_null());
    assert!(!name.is_null());

    let name = CStr::from_ptr(name).to_str().unwrap();
    doc.as_mut()
        .unwrap()
        .get_or_insert_map(name)
        .into_raw_branch()
}

/// Gets or creates a new shared `YXmlElement` data type instance as a root-level type of a given
/// document. This structure can later be accessed using its `name`, which must be a null-terminated
/// UTF-8 compatible string.
#[no_mangle]
pub unsafe extern "C" fn yxmlfragment(doc: *mut Doc, name: *const c_char) -> *mut Branch {
    assert!(!doc.is_null());
    assert!(!name.is_null());

    let name = CStr::from_ptr(name).to_str().unwrap();
    doc.as_mut()
        .unwrap()
        .get_or_insert_xml_fragment(name)
        .into_raw_branch()
}

/// Returns a state vector of a current transaction's document, serialized using lib0 version 1
/// encoding. Payload created by this function can then be send over the network to a remote peer,
/// where it can be used as a parameter of [ytransaction_state_diff_v1] in order to produce a delta
/// update payload, that can be send back and applied locally in order to efficiently propagate
/// updates from one peer to another.
///
/// The length of a generated binary will be passed within a `len` out parameter.
///
/// Once no longer needed, a returned binary can be disposed using [ybinary_destroy] function.
#[no_mangle]
pub unsafe extern "C" fn ytransaction_state_vector_v1(
    txn: *const Transaction,
    len: *mut u32,
) -> *mut c_char {
    assert!(!txn.is_null());

    let txn = txn.as_ref().unwrap();
    let state_vector = txn.state_vector();
    let binary = state_vector.encode_v1().into_boxed_slice();

    *len = binary.len() as u32;
    Box::into_raw(binary) as *mut c_char
}

/// Returns a delta difference between current state of a transaction's document and a state vector
/// `sv` encoded as a binary payload using lib0 version 1 encoding (which could be generated using
/// [ytransaction_state_vector_v1]). Such delta can be send back to the state vector's sender in
/// order to propagate and apply (using [ytransaction_apply]) all updates known to a current
/// document, which remote peer was not aware of.
///
/// If passed `sv` pointer is null, the generated diff will be a snapshot containing entire state of
/// the document.
///
/// A length of an encoded state vector payload must be passed as `sv_len` parameter.
///
/// A length of generated delta diff binary will be passed within a `len` out parameter.
///
/// Once no longer needed, a returned binary can be disposed using [ybinary_destroy] function.
#[no_mangle]
pub unsafe extern "C" fn ytransaction_state_diff_v1(
    txn: *const Transaction,
    sv: *const c_char,
    sv_len: u32,
    len: *mut u32,
) -> *mut c_char {
    assert!(!txn.is_null());

    let txn = txn.as_ref().unwrap();
    let sv = {
        if sv.is_null() {
            StateVector::default()
        } else {
            let sv_slice = std::slice::from_raw_parts(sv as *const u8, sv_len as usize);
            if let Ok(sv) = StateVector::decode_v1(sv_slice) {
                sv
            } else {
                return null_mut();
            }
        }
    };

    let mut encoder = EncoderV1::new();
    txn.encode_diff(&sv, &mut encoder);
    let binary = encoder.to_vec().into_boxed_slice();
    *len = binary.len() as u32;
    Box::into_raw(binary) as *mut c_char
}

/// Returns a delta difference between current state of a transaction's document and a state vector
/// `sv` encoded as a binary payload using lib0 version 1 encoding (which could be generated using
/// [ytransaction_state_vector_v1]). Such delta can be send back to the state vector's sender in
/// order to propagate and apply (using [ytransaction_apply_v2]) all updates known to a current
/// document, which remote peer was not aware of.
///
/// If passed `sv` pointer is null, the generated diff will be a snapshot containing entire state of
/// the document.
///
/// A length of an encoded state vector payload must be passed as `sv_len` parameter.
///
/// A length of generated delta diff binary will be passed within a `len` out parameter.
///
/// Once no longer needed, a returned binary can be disposed using [ybinary_destroy] function.
#[no_mangle]
pub unsafe extern "C" fn ytransaction_state_diff_v2(
    txn: *const Transaction,
    sv: *const c_char,
    sv_len: u32,
    len: *mut u32,
) -> *mut c_char {
    assert!(!txn.is_null());

    let txn = txn.as_ref().unwrap();
    let sv = {
        if sv.is_null() {
            StateVector::default()
        } else {
            let sv_slice = std::slice::from_raw_parts(sv as *const u8, sv_len as usize);
            if let Ok(sv) = StateVector::decode_v1(sv_slice) {
                sv
            } else {
                return null_mut();
            }
        }
    };

    let mut encoder = EncoderV2::new();
    txn.encode_diff(&sv, &mut encoder);
    let binary = encoder.to_vec().into_boxed_slice();
    *len = binary.len() as u32;
    Box::into_raw(binary) as *mut c_char
}

/// Returns a snapshot descriptor of a current state of the document. This snapshot information
/// can be then used to encode document data at a particular point in time
/// (see: `ytransaction_encode_state_from_snapshot`).
#[no_mangle]
pub unsafe extern "C" fn ytransaction_snapshot(
    txn: *const Transaction,
    len: *mut u32,
) -> *mut c_char {
    assert!(!txn.is_null());
    let txn = txn.as_ref().unwrap();
    let binary = txn.snapshot().encode_v1().into_boxed_slice();

    *len = binary.len() as u32;
    Box::into_raw(binary) as *mut c_char
}

/// Encodes a state of the document at a point in time specified by the provided `snapshot`
/// (generated by: `ytransaction_snapshot`). This is useful to generate a past view of the document.
///
/// The returned update is binary compatible with Yrs update lib0 v1 encoding, and can be processed
/// with functions dedicated to work on it, like `ytransaction_apply`.
///
/// This function requires document with a GC option flag turned off (otherwise "time travel" would
/// not be a safe operation). If this is not a case, the NULL pointer will be returned.
#[no_mangle]
pub unsafe extern "C" fn ytransaction_encode_state_from_snapshot_v1(
    txn: *const Transaction,
    snapshot: *const c_char,
    snapshot_len: u32,
    len: *mut u32,
) -> *mut c_char {
    assert!(!txn.is_null());
    let txn = txn.as_ref().unwrap();
    let snapshot = {
        let len = snapshot_len as usize;
        let data = std::slice::from_raw_parts(snapshot as *mut u8, len);
        Snapshot::decode_v1(&data).unwrap()
    };
    let mut encoder = EncoderV1::new();
    match txn.encode_state_from_snapshot(&snapshot, &mut encoder) {
        Err(_) => null_mut(),
        Ok(_) => {
            let binary = encoder.to_vec().into_boxed_slice();
            *len = binary.len() as u32;
            Box::into_raw(binary) as *mut c_char
        }
    }
}

/// Encodes a state of the document at a point in time specified by the provided `snapshot`
/// (generated by: `ytransaction_snapshot`). This is useful to generate a past view of the document.
///
/// The returned update is binary compatible with Yrs update lib0 v2 encoding, and can be processed
/// with functions dedicated to work on it, like `ytransaction_apply_v2`.
///
/// This function requires document with a GC option flag turned off (otherwise "time travel" would
/// not be a safe operation). If this is not a case, the NULL pointer will be returned.
#[no_mangle]
pub unsafe extern "C" fn ytransaction_encode_state_from_snapshot_v2(
    txn: *const Transaction,
    snapshot: *const c_char,
    snapshot_len: u32,
    len: *mut u32,
) -> *mut c_char {
    assert!(!txn.is_null());
    let txn = txn.as_ref().unwrap();
    let snapshot = {
        let len = snapshot_len as usize;
        let data = std::slice::from_raw_parts(snapshot as *mut u8, len);
        Snapshot::decode_v1(&data).unwrap()
    };
    let mut encoder = EncoderV2::new();
    match txn.encode_state_from_snapshot(&snapshot, &mut encoder) {
        Err(_) => null_mut(),
        Ok(_) => {
            let binary = encoder.to_vec().into_boxed_slice();
            *len = binary.len() as u32;
            Box::into_raw(binary) as *mut c_char
        }
    }
}

/// Returns an unapplied Delete Set for the current document, waiting for missing updates in order
/// to be integrated into document store.
///
/// Return `NULL` if there's no missing delete set and all deletions have been applied.
/// See also: `ytransaction_pending_update`
#[no_mangle]
pub unsafe extern "C" fn ytransaction_pending_ds(txn: *const Transaction) -> *mut YDeleteSet {
    let txn = txn.as_ref().unwrap();
    match txn.store().pending_ds() {
        None => null_mut(),
        Some(ds) => Box::into_raw(Box::new(YDeleteSet::new(ds))),
    }
}

#[no_mangle]
pub unsafe extern "C" fn ydelete_set_destroy(ds: *mut YDeleteSet) {
    if ds.is_null() {
        return;
    }
    drop(Box::from_raw(ds))
}

/// Returns a pending update associated with an underlying `YDoc`. Pending update contains update
/// data waiting for being integrated into main document store. Usually reason for that is that
/// there were missing updates required for integration. In such cases they need to arrive and be
/// integrated first.
///
/// Returns `NULL` if there is not update pending. Returned value can be released by calling
/// `ypending_update_destroy`.
/// See also: `ytransaction_pending_ds`
#[no_mangle]
pub unsafe extern "C" fn ytransaction_pending_update(
    txn: *const Transaction,
) -> *mut YPendingUpdate {
    let txn = txn.as_ref().unwrap();
    match txn.store().pending_update() {
        None => null_mut(),
        Some(u) => {
            let binary = u.update.encode_v1().into_boxed_slice();
            let update_len = binary.len() as u32;
            let missing = YStateVector::new(&u.missing);
            let update = YPendingUpdate {
                missing,
                update_len,
                update_v1: Box::into_raw(binary) as *mut c_char,
            };
            Box::into_raw(Box::new(update))
        }
    }
}

/// Structure containing unapplied update data.
/// Created via `ytransaction_pending_update`.
/// Released via `ypending_update_destroy`.
#[repr(C)]
pub struct YPendingUpdate {
    /// A state vector that informs about minimal client clock values that need to be satisfied
    /// in order to successfully apply current update.
    pub missing: YStateVector,
    /// Update data stored in lib0 v1 format.
    pub update_v1: *mut c_char,
    /// Length of `update_v1` payload.
    pub update_len: u32,
}

#[no_mangle]
pub unsafe extern "C" fn ypending_update_destroy(update: *mut YPendingUpdate) {
    if update.is_null() {
        return;
    }
    let update = Box::from_raw(update);
    drop(update.missing);
    ybinary_destroy(update.update_v1, update.update_len);
}

/// Returns a null-terminated UTF-8 encoded string representation of an `update` binary payload,
/// encoded using lib0 v1 encoding.
/// Returns null if update couldn't be parsed into a lib0 v1 formatting.
#[no_mangle]
pub unsafe extern "C" fn yupdate_debug_v1(update: *const c_char, update_len: u32) -> *mut c_char {
    assert!(!update.is_null());

    let data = std::slice::from_raw_parts(update as *const u8, update_len as usize);
    if let Ok(u) = Update::decode_v1(data) {
        let str = format!("{:#?}", u);
        CString::new(str).unwrap().into_raw()
    } else {
        null_mut()
    }
}

/// Returns a null-terminated UTF-8 encoded string representation of an `update` binary payload,
/// encoded using lib0 v2 encoding.
/// Returns null if update couldn't be parsed into a lib0 v2 formatting.
#[no_mangle]
pub unsafe extern "C" fn yupdate_debug_v2(update: *const c_char, update_len: u32) -> *mut c_char {
    assert!(!update.is_null());

    let data = std::slice::from_raw_parts(update as *const u8, update_len as usize);
    if let Ok(u) = Update::decode_v2(data) {
        let str = format!("{:#?}", u);
        CString::new(str).unwrap().into_raw()
    } else {
        null_mut()
    }
}

/// Applies an diff update (generated by `ytransaction_state_diff_v1`) to a local transaction's
/// document.
///
/// A length of generated `diff` binary must be passed within a `diff_len` out parameter.
///
/// Returns an error code in case if transaction succeeded failed:
/// - **0**: success
/// - `ERR_CODE_IO` (**1**): couldn't read data from input stream.
/// - `ERR_CODE_VAR_INT` (**2**): decoded variable integer outside of the expected integer size bounds.
/// - `ERR_CODE_EOS` (**3**): end of stream found when more data was expected.
/// - `ERR_CODE_UNEXPECTED_VALUE` (**4**): decoded enum tag value was not among known cases.
/// - `ERR_CODE_INVALID_JSON` (**5**): failure when trying to decode JSON content.
/// - `ERR_CODE_OTHER` (**6**): other error type than the one specified.
#[no_mangle]
pub unsafe extern "C" fn ytransaction_apply(
    txn: *mut Transaction,
    diff: *const c_char,
    diff_len: u32,
) -> u8 {
    assert!(!txn.is_null());
    assert!(!diff.is_null());

    let update = std::slice::from_raw_parts(diff as *const u8, diff_len as usize);
    let mut decoder = DecoderV1::from(update);
    match Update::decode(&mut decoder) {
        Ok(update) => {
            let txn = txn.as_mut().unwrap();
            let txn = txn
                .as_mut()
                .expect("provided transaction was not writeable");
            txn.apply_update(update);
            0
        }
        Err(e) => err_code(e),
    }
}

/// Applies an diff update (generated by [ytransaction_state_diff_v2]) to a local transaction's
/// document.
///
/// A length of generated `diff` binary must be passed within a `diff_len` out parameter.
///
/// Returns an error code in case if transaction succeeded failed:
/// - **0**: success
/// - `ERR_CODE_IO` (**1**): couldn't read data from input stream.
/// - `ERR_CODE_VAR_INT` (**2**): decoded variable integer outside of the expected integer size bounds.
/// - `ERR_CODE_EOS` (**3**): end of stream found when more data was expected.
/// - `ERR_CODE_UNEXPECTED_VALUE` (**4**): decoded enum tag value was not among known cases.
/// - `ERR_CODE_INVALID_JSON` (**5**): failure when trying to decode JSON content.
/// - `ERR_CODE_OTHER` (**6**): other error type than the one specified.
#[no_mangle]
pub unsafe extern "C" fn ytransaction_apply_v2(
    txn: *mut Transaction,
    diff: *const c_char,
    diff_len: u32,
) -> u8 {
    assert!(!txn.is_null());
    assert!(!diff.is_null());

    let mut update = std::slice::from_raw_parts(diff as *const u8, diff_len as usize);
    match Update::decode_v2(&mut update) {
        Ok(update) => {
            let txn = txn.as_mut().unwrap();
            let txn = txn
                .as_mut()
                .expect("provided transaction was not writeable");
            txn.apply_update(update);
            0
        }
        Err(e) => err_code(e),
    }
}

/// Error code: couldn't read data from input stream.
pub const ERR_CODE_IO: u8 = 1;

/// Error code: decoded variable integer outside of the expected integer size bounds.
pub const ERR_CODE_VAR_INT: u8 = 2;

/// Error code: end of stream found when more data was expected.
pub const ERR_CODE_EOS: u8 = 3;

/// Error code: decoded enum tag value was not among known cases.
pub const ERR_CODE_UNEXPECTED_VALUE: u8 = 4;

/// Error code: failure when trying to decode JSON content.
pub const ERR_CODE_INVALID_JSON: u8 = 5;

/// Error code: other error type than the one specified.
pub const ERR_CODE_OTHER: u8 = 6;

/// Error code: not enough memory to perform an operation.
pub const ERR_NOT_ENOUGH_MEMORY: u8 = 7;

fn err_code(e: Error) -> u8 {
    match e {
        Error::VarIntSizeExceeded(_) => ERR_CODE_VAR_INT,
        Error::EndOfBuffer(_) => ERR_CODE_EOS,
        Error::UnexpectedValue => ERR_CODE_UNEXPECTED_VALUE,
        Error::InvalidJSON(_) => ERR_CODE_INVALID_JSON,
        Error::NotEnoughMemory(_) => ERR_NOT_ENOUGH_MEMORY,
    }
}

/// Returns the length of the `YText` string content in bytes (without the null terminator character)
#[no_mangle]
pub unsafe extern "C" fn ytext_len(txt: *const Branch, txn: *const Transaction) -> u32 {
    assert!(!txt.is_null());
    let txn = txn.as_ref().unwrap();
    let txt = TextRef::from_raw_branch(txt);
    txt.len(txn)
}

/// Returns a null-terminated UTF-8 encoded string content of a current `YText` shared data type.
///
/// Generated string resources should be released using [ystring_destroy] function.
#[no_mangle]
pub unsafe extern "C" fn ytext_string(txt: *const Branch, txn: *const Transaction) -> *mut c_char {
    assert!(!txt.is_null());

    let txn = txn.as_ref().unwrap();
    let txt = TextRef::from_raw_branch(txt);
    let str = txt.get_string(txn);
    CString::new(str).unwrap().into_raw()
}

/// Inserts a null-terminated UTF-8 encoded string a given `index`. `index` value must be between
/// 0 and a length of a `YText` (inclusive, accordingly to [ytext_len] return value), otherwise this
/// function will panic.
///
/// A `str` parameter must be a null-terminated UTF-8 encoded string. This function doesn't take
/// ownership over a passed value - it will be copied and therefore a string parameter must be
/// released by the caller.
///
/// A nullable pointer with defined `attrs` will be used to wrap provided text with
/// a formatting blocks. `attrs` must be a map-like type.
#[no_mangle]
pub unsafe extern "C" fn ytext_insert(
    txt: *const Branch,
    txn: *mut Transaction,
    index: u32,
    value: *const c_char,
    attrs: *const YInput,
) {
    assert!(!txt.is_null());
    assert!(!txn.is_null());
    assert!(!value.is_null());

    let chunk = CStr::from_ptr(value).to_str().unwrap();
    let txn = txn.as_mut().unwrap();
    let txn = txn
        .as_mut()
        .expect("provided transaction was not writeable");
    let txt = TextRef::from_raw_branch(txt);
    let index = index as u32;
    if attrs.is_null() {
        txt.insert(txn, index, chunk)
    } else {
        if let Some(attrs) = map_attrs(attrs.read().into()) {
            txt.insert_with_attributes(txn, index, chunk, attrs)
        } else {
            panic!("ytext_insert: passed attributes are not of map type")
        }
    }
}

/// Wraps an existing piece of text within a range described by `index`-`len` parameters with
/// formatting blocks containing provided `attrs` metadata. `attrs` must be a map-like type.
#[no_mangle]
pub unsafe extern "C" fn ytext_format(
    txt: *const Branch,
    txn: *mut Transaction,
    index: u32,
    len: u32,
    attrs: *const YInput,
) {
    assert!(!txt.is_null());
    assert!(!txn.is_null());
    assert!(!attrs.is_null());

    if let Some(attrs) = map_attrs(attrs.read().into()) {
        let txt = TextRef::from_raw_branch(txt);
        let txn = txn.as_mut().unwrap();
        let txn = txn
            .as_mut()
            .expect("provided transaction was not writeable");
        let index = index as u32;
        let len = len as u32;
        txt.format(txn, index, len, attrs);
    } else {
        panic!("ytext_format: passed attributes are not of map type")
    }
}

/// Inserts an embed content given `index`. `index` value must be between 0 and a length of a
/// `YText` (inclusive, accordingly to [ytext_len] return value), otherwise this
/// function will panic.
///
/// A `str` parameter must be a null-terminated UTF-8 encoded string. This function doesn't take
/// ownership over a passed value - it will be copied and therefore a string parameter must be
/// released by the caller.
///
/// A nullable pointer with defined `attrs` will be used to wrap provided text with
/// a formatting blocks. `attrs` must be a map-like type.
#[no_mangle]
pub unsafe extern "C" fn ytext_insert_embed(
    txt: *const Branch,
    txn: *mut Transaction,
    index: u32,
    content: *const YInput,
    attrs: *const YInput,
) {
    assert!(!txt.is_null());
    assert!(!txn.is_null());
    assert!(!content.is_null());

    let txn = txn.as_mut().unwrap();
    let txn = txn
        .as_mut()
        .expect("provided transaction was not writeable");
    let txt = TextRef::from_raw_branch(txt);
    let index = index as u32;
    let content: Any = content.read().into();
    if attrs.is_null() {
        txt.insert_embed(txn, index, content);
    } else {
        if let Some(attrs) = map_attrs(attrs.read().into()) {
            txt.insert_embed_with_attributes(txn, index, content, attrs);
        } else {
            panic!("ytext_insert_embed: passed attributes are not of map type")
        }
    }
}

fn map_attrs(attrs: Any) -> Option<Attrs> {
    if let Any::Map(attrs) = attrs {
        let attrs = attrs
            .iter()
            .map(|(k, v)| (k.as_str().into(), v.clone()))
            .collect();
        Some(attrs)
    } else {
        None
    }
}

/// Removes a range of characters, starting a a given `index`. This range must fit within the bounds
/// of a current `YText`, otherwise this function call will fail.
///
/// An `index` value must be between 0 and the length of a `YText` (exclusive, accordingly to
/// [ytext_len] return value).
///
/// A `length` must be lower or equal number of characters (counted as UTF chars depending on the
/// encoding configured by `YDoc`) from `index` position to the end of of the string.
#[no_mangle]
pub unsafe extern "C" fn ytext_remove_range(
    txt: *const Branch,
    txn: *mut Transaction,
    index: u32,
    length: u32,
) {
    assert!(!txt.is_null());
    assert!(!txn.is_null());

    let txn = txn.as_mut().unwrap();
    let txn = txn
        .as_mut()
        .expect("provided transaction was not writeable");
    let txt = TextRef::from_raw_branch(txt);
    txt.remove_range(txn, index as u32, length as u32)
}

/// Returns a number of elements stored within current instance of `YArray`.
#[no_mangle]
pub unsafe extern "C" fn yarray_len(array: *const Branch) -> u32 {
    assert!(!array.is_null());

    let array = array.as_ref().unwrap();
    array.len() as u32
}

/// Returns a pointer to a `YOutput` value stored at a given `index` of a current `YArray`.
/// If `index` is outside of the bounds of an array, a null pointer will be returned.
///
/// A value returned should be eventually released using [youtput_destroy] function.
#[no_mangle]
pub unsafe extern "C" fn yarray_get(
    array: *const Branch,
    txn: *const Transaction,
    index: u32,
) -> *mut YOutput {
    assert!(!array.is_null());

    let array = ArrayRef::from_raw_branch(array);
    let txn = txn.as_ref().unwrap();

    if let Some(val) = array.get(txn, index as u32) {
        Box::into_raw(Box::new(YOutput::from(val)))
    } else {
        std::ptr::null_mut()
    }
}

/// Inserts a range of `items` into current `YArray`, starting at given `index`. An `items_len`
/// parameter is used to determine the size of `items` array - it can also be used to insert
/// a single element given its pointer.
///
/// An `index` value must be between 0 and (inclusive) length of a current array (use [yarray_len]
/// to determine its length), otherwise it will panic at runtime.
///
/// `YArray` doesn't take ownership over the inserted `items` data - their contents are being copied
/// into array structure - therefore caller is responsible for freeing all memory associated with
/// input params.
#[no_mangle]
pub unsafe extern "C" fn yarray_insert_range(
    array: *const Branch,
    txn: *mut Transaction,
    index: u32,
    items: *const YInput,
    items_len: u32,
) {
    assert!(!array.is_null());
    assert!(!txn.is_null());
    assert!(!items.is_null());

    let array = ArrayRef::from_raw_branch(array);
    let txn = txn.as_mut().unwrap();
    let txn = txn
        .as_mut()
        .expect("provided transaction was not writeable");

    let ptr = items;
    let mut i = 0;
    let mut j = index as u32;
    let len = items_len as isize;
    while i < len {
        let mut vec: Vec<Any> = Vec::default();

        // try read as many values a JSON-like primitives and insert them at once
        while i < len {
            let val = ptr.offset(i).read();
            if val.tag <= 0 {
                let any = val.into();
                vec.push(any);
            } else {
                break;
            }
            i += 1;
        }

        if !vec.is_empty() {
            let len = vec.len() as u32;
            array.insert_range(txn, j, vec);
            j += len;
        } else {
            let val = ptr.offset(i).read();
            array.insert(txn, j, val);
            i += 1;
            j += 1;
        }
    }
}

/// Removes a `len` of consecutive range of elements from current `array` instance, starting at
/// a given `index`. Range determined by `index` and `len` must fit into boundaries of an array,
/// otherwise it will panic at runtime.
#[no_mangle]
pub unsafe extern "C" fn yarray_remove_range(
    array: *const Branch,
    txn: *mut Transaction,
    index: u32,
    len: u32,
) {
    assert!(!array.is_null());
    assert!(!txn.is_null());

    let array = ArrayRef::from_raw_branch(array);
    let txn = txn.as_mut().unwrap();
    let txn = txn
        .as_mut()
        .expect("provided transaction was not writeable");

    array.remove_range(txn, index as u32, len as u32)
}

#[no_mangle]
pub unsafe extern "C" fn yarray_move(
    array: *const Branch,
    txn: *mut Transaction,
    source: u32,
    target: u32,
) {
    assert!(!array.is_null());
    assert!(!txn.is_null());

    let array = ArrayRef::from_raw_branch(array);
    let txn = txn.as_mut().unwrap();
    let txn = txn
        .as_mut()
        .expect("provided transaction was not writeable");

    array.move_to(txn, source as u32, target as u32)
}

/// Returns an iterator, which can be used to traverse over all elements of an `array` (`array`'s
/// length can be determined using [yarray_len] function).
///
/// Use [yarray_iter_next] function in order to retrieve a consecutive array elements.
/// Use [yarray_iter_destroy] function in order to close the iterator and release its resources.
#[no_mangle]
pub unsafe extern "C" fn yarray_iter(
    array: *const Branch,
    txn: *mut Transaction,
) -> *mut ArrayIter {
    assert!(!array.is_null());
    assert!(!txn.is_null());

    let txn = txn.as_ref().unwrap();
    let array = &ArrayRef::from_raw_branch(array) as *const ArrayRef;
    Box::into_raw(Box::new(ArrayIter(array.as_ref().unwrap().iter(txn))))
}

/// Releases all of an `YArray` iterator resources created by calling [yarray_iter].
#[no_mangle]
pub unsafe extern "C" fn yarray_iter_destroy(iter: *mut ArrayIter) {
    if !iter.is_null() {
        drop(Box::from_raw(iter))
    }
}

/// Moves current `YArray` iterator over to a next element, returning a pointer to it. If an iterator
/// comes to an end of an array, a null pointer will be returned.
///
/// Returned values should be eventually released using [youtput_destroy] function.
#[no_mangle]
pub unsafe extern "C" fn yarray_iter_next(iterator: *mut ArrayIter) -> *mut YOutput {
    assert!(!iterator.is_null());

    let iter = iterator.as_mut().unwrap();
    if let Some(v) = iter.0.next() {
        let out = YOutput::from(v);
        Box::into_raw(Box::new(out))
    } else {
        std::ptr::null_mut()
    }
}

/// Returns an iterator, which can be used to traverse over all key-value pairs of a `map`.
///
/// Use [ymap_iter_next] function in order to retrieve a consecutive (**unordered**) map entries.
/// Use [ymap_iter_destroy] function in order to close the iterator and release its resources.
#[no_mangle]
pub unsafe extern "C" fn ymap_iter(map: *const Branch, txn: *const Transaction) -> *mut MapIter {
    assert!(!map.is_null());

    let txn = txn.as_ref().unwrap();
    let map = &MapRef::from_raw_branch(map) as *const MapRef;
    Box::into_raw(Box::new(MapIter(map.as_ref().unwrap().iter(txn))))
}

/// Releases all of an `YMap` iterator resources created by calling [ymap_iter].
#[no_mangle]
pub unsafe extern "C" fn ymap_iter_destroy(iter: *mut MapIter) {
    if !iter.is_null() {
        drop(Box::from_raw(iter))
    }
}

/// Moves current `YMap` iterator over to a next entry, returning a pointer to it. If an iterator
/// comes to an end of a map, a null pointer will be returned. Yrs maps are unordered and so are
/// their iterators.
///
/// Returned values should be eventually released using [ymap_entry_destroy] function.
#[no_mangle]
pub unsafe extern "C" fn ymap_iter_next(iter: *mut MapIter) -> *mut YMapEntry {
    assert!(!iter.is_null());

    let iter = iter.as_mut().unwrap();
    if let Some((key, value)) = iter.0.next() {
        Box::into_raw(Box::new(YMapEntry::new(key, value)))
    } else {
        std::ptr::null_mut()
    }
}

/// Returns a number of entries stored within a `map`.
#[no_mangle]
pub unsafe extern "C" fn ymap_len(map: *const Branch, txn: *const Transaction) -> u32 {
    assert!(!map.is_null());

    let txn = txn.as_ref().unwrap();
    let map = MapRef::from_raw_branch(map);

    map.len(txn) as u32
}

/// Inserts a new entry (specified as `key`-`value` pair) into a current `map`. If entry under such
/// given `key` already existed, its corresponding value will be replaced.
///
/// A `key` must be a null-terminated UTF-8 encoded string, which contents will be copied into
/// a `map` (therefore it must be freed by the function caller).
///
/// A `value` content is being copied into a `map`, therefore any of its content must be freed by
/// the function caller.
#[no_mangle]
pub unsafe extern "C" fn ymap_insert(
    map: *const Branch,
    txn: *mut Transaction,
    key: *const c_char,
    value: *const YInput,
) {
    assert!(!map.is_null());
    assert!(!txn.is_null());
    assert!(!key.is_null());
    assert!(!value.is_null());

    let cstr = CStr::from_ptr(key);
    let key = cstr.to_str().unwrap().to_string();

    let map = MapRef::from_raw_branch(map);
    let txn = txn.as_mut().unwrap();
    let txn = txn
        .as_mut()
        .expect("provided transaction was not writeable");

    map.insert(txn, key, value.read());
}

/// Removes a `map` entry, given its `key`. Returns `1` if the corresponding entry was successfully
/// removed or `0` if no entry with a provided `key` has been found inside of a `map`.
///
/// A `key` must be a null-terminated UTF-8 encoded string.
#[no_mangle]
pub unsafe extern "C" fn ymap_remove(
    map: *const Branch,
    txn: *mut Transaction,
    key: *const c_char,
) -> u8 {
    assert!(!map.is_null());
    assert!(!txn.is_null());
    assert!(!key.is_null());

    let key = CStr::from_ptr(key).to_str().unwrap();

    let map = MapRef::from_raw_branch(map);
    let txn = txn.as_mut().unwrap();
    let txn = txn
        .as_mut()
        .expect("provided transaction was not writeable");

    if let Some(_) = map.remove(txn, key) {
        Y_TRUE
    } else {
        Y_FALSE
    }
}

/// Returns a value stored under the provided `key`, or a null pointer if no entry with such `key`
/// has been found in a current `map`. A returned value is allocated by this function and therefore
/// should be eventually released using [youtput_destroy] function.
///
/// A `key` must be a null-terminated UTF-8 encoded string.
#[no_mangle]
pub unsafe extern "C" fn ymap_get(
    map: *const Branch,
    txn: *const Transaction,
    key: *const c_char,
) -> *mut YOutput {
    assert!(!map.is_null());
    assert!(!key.is_null());
    assert!(!txn.is_null());

    let txn = txn.as_ref().unwrap();
    let key = CStr::from_ptr(key).to_str().unwrap();

    let map = MapRef::from_raw_branch(map);

    if let Some(value) = map.get(txn, key) {
        Box::into_raw(Box::new(YOutput::from(value)))
    } else {
        std::ptr::null_mut()
    }
}

/// Removes all entries from a current `map`.
#[no_mangle]
pub unsafe extern "C" fn ymap_remove_all(map: *const Branch, txn: *mut Transaction) {
    assert!(!map.is_null());
    assert!(!txn.is_null());

    let map = MapRef::from_raw_branch(map);
    let txn = txn.as_mut().unwrap();
    let txn = txn
        .as_mut()
        .expect("provided transaction was not writeable");

    map.clear(txn);
}

/// Return a name (or an XML tag) of a current `YXmlElement`. Root-level XML nodes use "UNDEFINED" as
/// their tag names.
///
/// Returned value is a null-terminated UTF-8 string, which must be released using [ystring_destroy]
/// function.
#[no_mangle]
pub unsafe extern "C" fn yxmlelem_tag(xml: *const Branch) -> *mut c_char {
    assert!(!xml.is_null());
    let xml = XmlElementRef::from_raw_branch(xml);
    if let Some(tag) = xml.try_tag() {
        CString::new(tag.deref()).unwrap().into_raw()
    } else {
        null_mut()
    }
}

/// Converts current `YXmlElement` together with its children and attributes into a flat string
/// representation (no padding) eg. `<UNDEFINED><title key="value">sample text</title></UNDEFINED>`.
///
/// Returned value is a null-terminated UTF-8 string, which must be released using [ystring_destroy]
/// function.
#[no_mangle]
pub unsafe extern "C" fn yxmlelem_string(
    xml: *const Branch,
    txn: *const Transaction,
) -> *mut c_char {
    assert!(!xml.is_null());
    assert!(!txn.is_null());

    let txn = txn.as_ref().unwrap();
    let xml = XmlElementRef::from_raw_branch(xml);

    let str = xml.get_string(txn);
    CString::new(str).unwrap().into_raw()
}

/// Inserts an XML attribute described using `attr_name` and `attr_value`. If another attribute with
/// the same name already existed, its value will be replaced with a provided one.
///
/// Both `attr_name` and `attr_value` must be a null-terminated UTF-8 encoded strings. Their
/// contents are being copied, therefore it's up to a function caller to properly release them.
#[no_mangle]
pub unsafe extern "C" fn yxmlelem_insert_attr(
    xml: *const Branch,
    txn: *mut Transaction,
    attr_name: *const c_char,
    attr_value: *const c_char,
) {
    assert!(!xml.is_null());
    assert!(!txn.is_null());
    assert!(!attr_name.is_null());
    assert!(!attr_value.is_null());

    let xml = XmlElementRef::from_raw_branch(xml);
    let txn = txn.as_mut().unwrap();
    let txn = txn
        .as_mut()
        .expect("provided transaction was not writeable");

    let key = CStr::from_ptr(attr_name).to_str().unwrap();
    let value = CStr::from_ptr(attr_value).to_str().unwrap();

    xml.insert_attribute(txn, key, value);
}

/// Removes an attribute from a current `YXmlElement`, given its name.
///
/// An `attr_name`must be a null-terminated UTF-8 encoded string.
#[no_mangle]
pub unsafe extern "C" fn yxmlelem_remove_attr(
    xml: *const Branch,
    txn: *mut Transaction,
    attr_name: *const c_char,
) {
    assert!(!xml.is_null());
    assert!(!txn.is_null());
    assert!(!attr_name.is_null());

    let xml = XmlElementRef::from_raw_branch(xml);
    let txn = txn.as_mut().unwrap();
    let txn = txn
        .as_mut()
        .expect("provided transaction was not writeable");

    let key = CStr::from_ptr(attr_name).to_str().unwrap();
    xml.remove_attribute(txn, &key);
}

/// Returns the value of a current `YXmlElement`, given its name, or a null pointer if not attribute
/// with such name has been found. Returned pointer is a null-terminated UTF-8 encoded string, which
/// should be released using [ystring_destroy] function.
///
/// An `attr_name` must be a null-terminated UTF-8 encoded string.
#[no_mangle]
pub unsafe extern "C" fn yxmlelem_get_attr(
    xml: *const Branch,
    txn: *const Transaction,
    attr_name: *const c_char,
) -> *mut c_char {
    assert!(!xml.is_null());
    assert!(!attr_name.is_null());
    assert!(!txn.is_null());

    let xml = XmlElementRef::from_raw_branch(xml);

    let key = CStr::from_ptr(attr_name).to_str().unwrap();
    let txn = txn.as_ref().unwrap();
    if let Some(value) = xml.get_attribute(txn, key) {
        CString::new(value).unwrap().into_raw()
    } else {
        std::ptr::null_mut()
    }
}

/// Returns an iterator over the `YXmlElement` attributes.
///
/// Use [yxmlattr_iter_next] function in order to retrieve a consecutive (**unordered**) attributes.
/// Use [yxmlattr_iter_destroy] function in order to close the iterator and release its resources.
#[no_mangle]
pub unsafe extern "C" fn yxmlelem_attr_iter(
    xml: *const Branch,
    txn: *const Transaction,
) -> *mut Attributes {
    assert!(!xml.is_null());
    assert!(!txn.is_null());

    let xml = &XmlElementRef::from_raw_branch(xml) as *const XmlElementRef;
    let txn = txn.as_ref().unwrap();
    Box::into_raw(Box::new(Attributes(xml.as_ref().unwrap().attributes(txn))))
}

/// Returns an iterator over the `YXmlText` attributes.
///
/// Use [yxmlattr_iter_next] function in order to retrieve a consecutive (**unordered**) attributes.
/// Use [yxmlattr_iter_destroy] function in order to close the iterator and release its resources.
#[no_mangle]
pub unsafe extern "C" fn yxmltext_attr_iter(
    xml: *const Branch,
    txn: *const Transaction,
) -> *mut Attributes {
    assert!(!xml.is_null());
    assert!(!txn.is_null());

    let xml = &XmlTextRef::from_raw_branch(xml) as *const XmlTextRef;
    let txn = txn.as_ref().unwrap();
    Box::into_raw(Box::new(Attributes(xml.as_ref().unwrap().attributes(txn))))
}

/// Releases all of attributes iterator resources created by calling [yxmlelem_attr_iter]
/// or [yxmltext_attr_iter].
#[no_mangle]
pub unsafe extern "C" fn yxmlattr_iter_destroy(iterator: *mut Attributes) {
    if !iterator.is_null() {
        drop(Box::from_raw(iterator))
    }
}

/// Returns a next XML attribute from an `iterator`. Attributes are returned in an unordered
/// manner. Once `iterator` reaches the end of attributes collection, a null pointer will be
/// returned.
///
/// Returned value should be eventually released using [yxmlattr_destroy].
#[no_mangle]
pub unsafe extern "C" fn yxmlattr_iter_next(iterator: *mut Attributes) -> *mut YXmlAttr {
    assert!(!iterator.is_null());

    let iter = iterator.as_mut().unwrap();

    if let Some((name, value)) = iter.0.next() {
        Box::into_raw(Box::new(YXmlAttr {
            name: CString::new(name).unwrap().into_raw(),
            value: CString::new(value).unwrap().into_raw(),
        }))
    } else {
        std::ptr::null_mut()
    }
}

/// Returns a next sibling of a current XML node, which can be either another `YXmlElement`
/// or a `YXmlText`. Together with [yxmlelem_first_child] it may be used to iterate over the direct
/// children of an XML node (in order to iterate over the nested XML structure use
/// [yxmlelem_tree_walker]).
///
/// If current `YXmlElement` is the last child, this function returns a null pointer.
/// A returned value should be eventually released using [youtput_destroy] function.
#[no_mangle]
pub unsafe extern "C" fn yxml_next_sibling(
    xml: *const Branch,
    txn: *const Transaction,
) -> *mut YOutput {
    assert!(!xml.is_null());
    assert!(!txn.is_null());

    let xml = XmlElementRef::from_raw_branch(xml);
    let txn = txn.as_ref().unwrap();

    let mut siblings = xml.siblings(txn);
    if let Some(next) = siblings.next() {
        match next {
            XmlNode::Element(v) => Box::into_raw(Box::new(YOutput::from(Value::YXmlElement(v)))),
            XmlNode::Text(v) => Box::into_raw(Box::new(YOutput::from(Value::YXmlText(v)))),
            XmlNode::Fragment(v) => Box::into_raw(Box::new(YOutput::from(Value::YXmlFragment(v)))),
        }
    } else {
        null_mut()
    }
}

/// Returns a previous sibling of a current XML node, which can be either another `YXmlElement`
/// or a `YXmlText`.
///
/// If current `YXmlElement` is the first child, this function returns a null pointer.
/// A returned value should be eventually released using [youtput_destroy] function.
#[no_mangle]
pub unsafe extern "C" fn yxml_prev_sibling(
    xml: *const Branch,
    txn: *const Transaction,
) -> *mut YOutput {
    assert!(!xml.is_null());
    assert!(!txn.is_null());

    let xml = XmlElementRef::from_raw_branch(xml);
    let txn = txn.as_ref().unwrap();

    let mut siblings = xml.siblings(txn);
    if let Some(next) = siblings.next_back() {
        match next {
            XmlNode::Element(v) => Box::into_raw(Box::new(YOutput::from(Value::YXmlElement(v)))),
            XmlNode::Text(v) => Box::into_raw(Box::new(YOutput::from(Value::YXmlText(v)))),
            XmlNode::Fragment(v) => Box::into_raw(Box::new(YOutput::from(Value::YXmlFragment(v)))),
        }
    } else {
        null_mut()
    }
}

/// Returns a parent `YXmlElement` of a current node, or null pointer when current `YXmlElement` is
/// a root-level shared data type.
#[no_mangle]
pub unsafe extern "C" fn yxmlelem_parent(xml: *const Branch) -> *mut Branch {
    assert!(!xml.is_null());

    let xml = XmlElementRef::from_raw_branch(xml);

    if let Some(parent) = xml.parent() {
        let branch = parent.as_ptr();
        branch.deref() as *const Branch as *mut Branch
    } else {
        std::ptr::null_mut()
    }
}

/// Returns a number of child nodes (both `YXmlElement` and `YXmlText`) living under a current XML
/// element. This function doesn't count a recursive nodes, only direct children of a current node.
#[no_mangle]
pub unsafe extern "C" fn yxmlelem_child_len(xml: *const Branch, txn: *const Transaction) -> u32 {
    assert!(!xml.is_null());
    assert!(!txn.is_null());

    let txn = txn.as_ref().unwrap();
    let xml = XmlElementRef::from_raw_branch(xml);

    xml.len(txn) as u32
}

/// Returns a first child node of a current `YXmlElement`, or null pointer if current XML node is
/// empty. Returned value could be either another `YXmlElement` or `YXmlText`.
///
/// A returned value should be eventually released using [youtput_destroy] function.
#[no_mangle]
pub unsafe extern "C" fn yxmlelem_first_child(xml: *const Branch) -> *mut YOutput {
    assert!(!xml.is_null());

    let xml = XmlElementRef::from_raw_branch(xml);

    if let Some(value) = xml.first_child() {
        match value {
            XmlNode::Element(v) => Box::into_raw(Box::new(YOutput::from(Value::YXmlElement(v)))),
            XmlNode::Text(v) => Box::into_raw(Box::new(YOutput::from(Value::YXmlText(v)))),
            XmlNode::Fragment(v) => Box::into_raw(Box::new(YOutput::from(Value::YXmlFragment(v)))),
        }
    } else {
        std::ptr::null_mut()
    }
}

/// Returns an iterator over a nested recursive structure of a current `YXmlElement`, starting from
/// first of its children. Returned values can be either `YXmlElement` or `YXmlText` nodes.
///
/// Use [yxmlelem_tree_walker_next] function in order to iterate over to a next node.
/// Use [yxmlelem_tree_walker_destroy] function to release resources used by the iterator.
#[no_mangle]
pub unsafe extern "C" fn yxmlelem_tree_walker(
    xml: *const Branch,
    txn: *const Transaction,
) -> *mut TreeWalker {
    assert!(!xml.is_null());
    assert!(!txn.is_null());

    let txn = txn.as_ref().unwrap();
    let xml = &XmlElementRef::from_raw_branch(xml) as *const XmlElementRef;
    Box::into_raw(Box::new(TreeWalker(xml.as_ref().unwrap().successors(txn))))
}

/// Releases resources associated with a current XML tree walker iterator.
#[no_mangle]
pub unsafe extern "C" fn yxmlelem_tree_walker_destroy(iter: *mut TreeWalker) {
    if !iter.is_null() {
        drop(Box::from_raw(iter))
    }
}

/// Moves current `iterator` to a next value (either `YXmlElement` or `YXmlText`), returning its
/// pointer or a null, if an `iterator` already reached the last successor node.
///
/// Values returned by this function should be eventually released using [youtput_destroy].
#[no_mangle]
pub unsafe extern "C" fn yxmlelem_tree_walker_next(iterator: *mut TreeWalker) -> *mut YOutput {
    assert!(!iterator.is_null());

    let iter = iterator.as_mut().unwrap();

    if let Some(next) = iter.0.next() {
        match next {
            XmlNode::Element(v) => Box::into_raw(Box::new(YOutput::from(Value::YXmlElement(v)))),
            XmlNode::Text(v) => Box::into_raw(Box::new(YOutput::from(Value::YXmlText(v)))),
            XmlNode::Fragment(v) => Box::into_raw(Box::new(YOutput::from(Value::YXmlFragment(v)))),
        }
    } else {
        std::ptr::null_mut()
    }
}

/// Inserts an `YXmlElement` as a child of a current node at the given `index` and returns its
/// pointer. Node created this way will have a given `name` as its tag (eg. `p` for `<p></p>` node).
///
/// An `index` value must be between 0 and (inclusive) length of a current XML element (use
/// [yxmlelem_child_len] function to determine its length).
///
/// A `name` must be a null-terminated UTF-8 encoded string, which will be copied into current
/// document. Therefore `name` should be freed by the function caller.
#[no_mangle]
pub unsafe extern "C" fn yxmlelem_insert_elem(
    xml: *const Branch,
    txn: *mut Transaction,
    index: u32,
    name: *const c_char,
) -> *mut Branch {
    assert!(!xml.is_null());
    assert!(!txn.is_null());
    assert!(!name.is_null());

    let xml = XmlElementRef::from_raw_branch(xml);
    let txn = txn.as_mut().unwrap();
    let txn = txn
        .as_mut()
        .expect("provided transaction was not writeable");

    let name = CStr::from_ptr(name).to_str().unwrap();
    xml.insert(txn, index as u32, XmlElementPrelim::empty(name))
        .into_raw_branch()
}

/// Inserts an `YXmlText` as a child of a current node at the given `index` and returns its
/// pointer.
///
/// An `index` value must be between 0 and (inclusive) length of a current XML element (use
/// [yxmlelem_child_len] function to determine its length).
#[no_mangle]
pub unsafe extern "C" fn yxmlelem_insert_text(
    xml: *const Branch,
    txn: *mut Transaction,
    index: u32,
) -> *mut Branch {
    assert!(!xml.is_null());
    assert!(!txn.is_null());

    let xml = XmlElementRef::from_raw_branch(xml);
    let txn = txn.as_mut().unwrap();
    let txn = txn
        .as_mut()
        .expect("provided transaction was not writeable");
    xml.insert(txn, index as u32, XmlTextPrelim::new(""))
        .into_raw_branch()
}

/// Removes a consecutive range of child elements (of specified length) from the current
/// `YXmlElement`, starting at the given `index`. Specified range must fit into boundaries of current
/// XML node children, otherwise this function will panic at runtime.
#[no_mangle]
pub unsafe extern "C" fn yxmlelem_remove_range(
    xml: *const Branch,
    txn: *mut Transaction,
    index: u32,
    len: u32,
) {
    assert!(!xml.is_null());
    assert!(!txn.is_null());

    let xml = XmlElementRef::from_raw_branch(xml);
    let txn = txn.as_mut().unwrap();
    let txn = txn
        .as_mut()
        .expect("provided transaction was not writeable");

    xml.remove_range(txn, index as u32, len as u32)
}

/// Returns an XML child node (either a `YXmlElement` or `YXmlText`) stored at a given `index` of
/// a current `YXmlElement`. Returns null pointer if `index` was outside of the bound of current XML
/// node children.
///
/// Returned value should be eventually released using [youtput_destroy].
#[no_mangle]
pub unsafe extern "C" fn yxmlelem_get(
    xml: *const Branch,
    txn: *const Transaction,
    index: u32,
) -> *const YOutput {
    assert!(!xml.is_null());
    assert!(!txn.is_null());

    let xml = XmlElementRef::from_raw_branch(xml);
    let txn = txn.as_ref().unwrap();

    if let Some(child) = xml.get(txn, index as u32) {
        match child {
            XmlNode::Element(v) => Box::into_raw(Box::new(YOutput::from(Value::YXmlElement(v)))),
            XmlNode::Text(v) => Box::into_raw(Box::new(YOutput::from(Value::YXmlText(v)))),
            XmlNode::Fragment(v) => Box::into_raw(Box::new(YOutput::from(Value::YXmlFragment(v)))),
        }
    } else {
        std::ptr::null()
    }
}

/// Returns the length of the `YXmlText` string content in bytes (without the null terminator
/// character)
#[no_mangle]
pub unsafe extern "C" fn yxmltext_len(txt: *const Branch, txn: *const Transaction) -> u32 {
    assert!(!txt.is_null());
    assert!(!txn.is_null());

    let txn = txn.as_ref().unwrap();
    let txt = XmlTextRef::from_raw_branch(txt);

    txt.len(txn) as u32
}

/// Returns a null-terminated UTF-8 encoded string content of a current `YXmlText` shared data type.
///
/// Generated string resources should be released using [ystring_destroy] function.
#[no_mangle]
pub unsafe extern "C" fn yxmltext_string(
    txt: *const Branch,
    txn: *const Transaction,
) -> *mut c_char {
    assert!(!txt.is_null());
    assert!(!txn.is_null());

    let txn = txn.as_ref().unwrap();
    let txt = XmlTextRef::from_raw_branch(txt);

    let str = txt.get_string(txn);
    CString::new(str).unwrap().into_raw()
}

/// Inserts a null-terminated UTF-8 encoded string a a given `index`. `index` value must be between
/// 0 and a length of a `YXmlText` (inclusive, accordingly to [yxmltext_len] return value), otherwise
/// this function will panic.
///
/// A `str` parameter must be a null-terminated UTF-8 encoded string. This function doesn't take
/// ownership over a passed value - it will be copied and therefore a string parameter must be
/// released by the caller.
///
/// A nullable pointer with defined `attrs` will be used to wrap provided text with
/// a formatting blocks. `attrs` must be a map-like type.
#[no_mangle]
pub unsafe extern "C" fn yxmltext_insert(
    txt: *const Branch,
    txn: *mut Transaction,
    index: u32,
    str: *const c_char,
    attrs: *const YInput,
) {
    assert!(!txt.is_null());
    assert!(!txn.is_null());
    assert!(!str.is_null());

    let txt = XmlTextRef::from_raw_branch(txt);
    let txn = txn.as_mut().unwrap();
    let txn = txn
        .as_mut()
        .expect("provided transaction was not writeable");
    let chunk = CStr::from_ptr(str).to_str().unwrap();

    if attrs.is_null() {
        txt.insert(txn, index as u32, chunk)
    } else {
        if let Some(attrs) = map_attrs(attrs.read().into()) {
            txt.insert_with_attributes(txn, index as u32, chunk, attrs)
        } else {
            panic!("yxmltext_insert: passed attributes are not of map type")
        }
    }
}

/// Inserts an embed content given `index`. `index` value must be between 0 and a length of a
/// `YXmlText` (inclusive, accordingly to [ytext_len] return value), otherwise this
/// function will panic.
///
/// A `str` parameter must be a null-terminated UTF-8 encoded string. This function doesn't take
/// ownership over a passed value - it will be copied and therefore a string parameter must be
/// released by the caller.
///
/// A nullable pointer with defined `attrs` will be used to wrap provided text with
/// a formatting blocks. `attrs` must be a map-like type.
#[no_mangle]
pub unsafe extern "C" fn yxmltext_insert_embed(
    txt: *const Branch,
    txn: *mut Transaction,
    index: u32,
    content: *const YInput,
    attrs: *const YInput,
) {
    assert!(!txt.is_null());
    assert!(!txn.is_null());
    assert!(!content.is_null());

    let txn = txn.as_mut().unwrap();
    let txn = txn
        .as_mut()
        .expect("provided transaction was not writeable");
    let txt = XmlTextRef::from_raw_branch(txt);
    let index = index as u32;
    let content: Any = content.read().into();
    if attrs.is_null() {
        txt.insert_embed(txn, index, content);
    } else {
        if let Some(attrs) = map_attrs(attrs.read().into()) {
            txt.insert_embed_with_attributes(txn, index, content, attrs);
        } else {
            panic!("yxmltext_insert_embed: passed attributes are not of map type")
        }
    }
}

/// Wraps an existing piece of text within a range described by `index`-`len` parameters with
/// formatting blocks containing provided `attrs` metadata. `attrs` must be a map-like type.
#[no_mangle]
pub unsafe extern "C" fn yxmltext_format(
    txt: *const Branch,
    txn: *mut Transaction,
    index: u32,
    len: u32,
    attrs: *const YInput,
) {
    assert!(!txt.is_null());
    assert!(!txn.is_null());
    assert!(!attrs.is_null());

    if let Some(attrs) = map_attrs(attrs.read().into()) {
        let txt = XmlTextRef::from_raw_branch(txt);
        let txn = txn.as_mut().unwrap();
        let txn = txn
            .as_mut()
            .expect("provided transaction was not writeable");
        let index = index as u32;
        let len = len as u32;
        txt.format(txn, index, len, attrs);
    } else {
        panic!("yxmltext_format: passed attributes are not of map type")
    }
}

/// Removes a range of characters, starting a a given `index`. This range must fit within the bounds
/// of a current `YXmlText`, otherwise this function call will fail.
///
/// An `index` value must be between 0 and the length of a `YXmlText` (exclusive, accordingly to
/// [yxmltext_len] return value).
///
/// A `length` must be lower or equal number of characters (counted as UTF chars depending on the
/// encoding configured by `YDoc`) from `index` position to the end of of the string.
#[no_mangle]
pub unsafe extern "C" fn yxmltext_remove_range(
    txt: *const Branch,
    txn: *mut Transaction,
    idx: u32,
    len: u32,
) {
    assert!(!txt.is_null());
    assert!(!txn.is_null());

    let txt = XmlTextRef::from_raw_branch(txt);
    let txn = txn.as_mut().unwrap();
    let txn = txn
        .as_mut()
        .expect("provided transaction was not writeable");
    txt.remove_range(txn, idx as u32, len as u32)
}

/// Inserts an XML attribute described using `attr_name` and `attr_value`. If another attribute with
/// the same name already existed, its value will be replaced with a provided one.
///
/// Both `attr_name` and `attr_value` must be a null-terminated UTF-8 encoded strings. Their
/// contents are being copied, therefore it's up to a function caller to properly release them.
#[no_mangle]
pub unsafe extern "C" fn yxmltext_insert_attr(
    txt: *const Branch,
    txn: *mut Transaction,
    attr_name: *const c_char,
    attr_value: *const c_char,
) {
    assert!(!txt.is_null());
    assert!(!txn.is_null());
    assert!(!attr_name.is_null());
    assert!(!attr_value.is_null());

    let txt = XmlTextRef::from_raw_branch(txt);
    let txn = txn.as_mut().unwrap();
    let txn = txn
        .as_mut()
        .expect("provided transaction was not writeable");

    let name = CStr::from_ptr(attr_name).to_str().unwrap();
    let value = CStr::from_ptr(attr_value).to_str().unwrap();

    txt.insert_attribute(txn, name, value)
}

/// Removes an attribute from a current `YXmlText`, given its name.
///
/// An `attr_name`must be a null-terminated UTF-8 encoded string.
#[no_mangle]
pub unsafe extern "C" fn yxmltext_remove_attr(
    txt: *const Branch,
    txn: *mut Transaction,
    attr_name: *const c_char,
) {
    assert!(!txt.is_null());
    assert!(!txn.is_null());
    assert!(!attr_name.is_null());

    let txt = XmlTextRef::from_raw_branch(txt);
    let txn = txn.as_mut().unwrap();
    let txn = txn
        .as_mut()
        .expect("provided transaction was not writeable");
    let name = CStr::from_ptr(attr_name).to_str().unwrap();

    txt.remove_attribute(txn, &name)
}

/// Returns the value of a current `YXmlText`, given its name, or a null pointer if not attribute
/// with such name has been found. Returned pointer is a null-terminated UTF-8 encoded string, which
/// should be released using [ystring_destroy] function.
///
/// An `attr_name` must be a null-terminated UTF-8 encoded string.
#[no_mangle]
pub unsafe extern "C" fn yxmltext_get_attr(
    txt: *const Branch,
    txn: *const Transaction,
    attr_name: *const c_char,
) -> *mut c_char {
    assert!(!txt.is_null());
    assert!(!attr_name.is_null());
    assert!(!txn.is_null());

    let txn = txn.as_ref().unwrap();
    let txt = XmlTextRef::from_raw_branch(txt);
    let name = CStr::from_ptr(attr_name).to_str().unwrap();

    if let Some(value) = txt.get_attribute(txn, name) {
        CString::new(value).unwrap().into_raw()
    } else {
        std::ptr::null_mut()
    }
}

/// Returns a collection of chunks representing pieces of `YText` rich text string grouped together
/// by the same formatting rules and type. `chunks_len` is used to inform about a number of chunks
/// generated this way.
///
/// Returned array needs to be eventually deallocated using `ychunks_destroy`.
#[no_mangle]
pub unsafe extern "C" fn ytext_chunks(
    txt: *const Branch,
    txn: *const Transaction,
    chunks_len: *mut u32,
) -> *mut YChunk {
    assert!(!txt.is_null());
    assert!(!txn.is_null());

    let txt = TextRef::from_raw_branch(txt);
    let txn = txn.as_ref().unwrap();

    let diffs = txt.diff(txn, YChange::identity);
    let chunks: Vec<_> = diffs.into_iter().map(YChunk::from).collect();
    let out = chunks.into_boxed_slice();
    *chunks_len = out.len() as u32;
    Box::into_raw(out) as *mut _
}

/// Deallocates result of `ytext_chunks` method.
#[no_mangle]
pub unsafe extern "C" fn ychunks_destroy(chunks: *mut YChunk, len: u32) {
    drop(Vec::from_raw_parts(chunks, len as usize, len as usize));
}

pub const YCHANGE_ADD: i8 = 1;
pub const YCHANGE_RETAIN: i8 = 0;
pub const YCHANGE_REMOVE: i8 = -1;

/// A chunk of text contents formatted with the same set of attributes.
#[repr(C)]
pub struct YChunk {
    /// Piece of YText formatted using the same `fmt` rules. It can be a string, embedded object
    /// or another y-type.
    pub data: YOutput,
    /// Number of formatting attributes attached to current chunk of text.
    pub fmt_len: u32,
    /// The formatting attributes attached to the current chunk of text.
    pub fmt: *mut YMapEntry,
}

impl From<Diff<YChange>> for YChunk {
    fn from(diff: Diff<YChange>) -> Self {
        let data = YOutput::from(diff.insert);
        let mut fmt_len = 0;
        let fmt = if let Some(attrs) = diff.attributes {
            fmt_len = attrs.len() as u32;
            let mut fmt = Vec::with_capacity(attrs.len());
            for (k, v) in attrs.into_iter() {
                let e = YMapEntry::new(k.as_ref(), Value::Any(v));
                fmt.push(e);
            }
            Box::into_raw(fmt.into_boxed_slice()) as *mut _
        } else {
            null_mut()
        };
        YChunk { data, fmt_len, fmt }
    }
}

impl Drop for YChunk {
    fn drop(&mut self) {
        if !self.fmt.is_null() {
            drop(unsafe {
                Vec::from_raw_parts(self.fmt, self.fmt_len as usize, self.fmt_len as usize)
            });
        }
    }
}

/// A data structure that is used to pass input values of various types supported by Yrs into a
/// shared document store.
///
/// `YInput` constructor function don't allocate any resources on their own, neither they take
/// ownership by pointers to memory blocks allocated by user - for this reason once an input cell
/// has been used, its content should be freed by the caller.
#[repr(C)]
pub struct YInput {
    /// Tag describing, which `value` type is being stored by this input cell. Can be one of:
    ///
    /// - [Y_JSON_BOOL] for boolean flags.
    /// - [Y_JSON_NUM] for 64-bit floating point numbers.
    /// - [Y_JSON_INT] for 64-bit signed integers.
    /// - [Y_JSON_STR] for null-terminated UTF-8 encoded strings.
    /// - [Y_JSON_BUF] for embedded binary data.
    /// - [Y_JSON_ARR] for arrays of JSON-like values.
    /// - [Y_JSON_MAP] for JSON-like objects build from key-value pairs.
    /// - [Y_JSON_NULL] for JSON-like null values.
    /// - [Y_JSON_UNDEF] for JSON-like undefined values.
    /// - [Y_ARRAY] for cells which contents should be used to initialize a `YArray` shared type.
    /// - [Y_MAP] for cells which contents should be used to initialize a `YMap` shared type.
    /// - [Y_DOC] for cells which contents should be used to nest a `YDoc` sub-document.
    /// - [Y_WEAK_LINK] for cells which contents should be used to nest a `YWeakLink` sub-document.
    pub tag: i8,

    /// Length of the contents stored by current `YInput` cell.
    ///
    /// For [Y_JSON_NULL] and [Y_JSON_UNDEF] its equal to `0`.
    ///
    /// For [Y_JSON_ARR], [Y_JSON_MAP], [Y_ARRAY] and [Y_MAP] it describes a number of passed
    /// elements.
    ///
    /// For other types it's always equal to `1`.
    pub len: u32,

    /// Union struct which contains a content corresponding to a provided `tag` field.
    value: YInputContent,
}

impl YInput {
    fn into(self) -> Any {
        let tag = self.tag;
        unsafe {
            if tag == Y_JSON_STR {
                let str = CStr::from_ptr(self.value.str).to_str().unwrap().into();
                Any::String(str)
            } else if tag == Y_JSON_ARR {
                let ptr = self.value.values;
                let mut dst: Vec<Any> = Vec::with_capacity(self.len as usize);
                let mut i = 0;
                while i < self.len as isize {
                    let value = ptr.offset(i).read();
                    let any = value.into();
                    dst.push(any);
                    i += 1;
                }
                Any::from(dst)
            } else if tag == Y_JSON_MAP {
                let mut dst = HashMap::with_capacity(self.len as usize);
                let keys = self.value.map.keys;
                let values = self.value.map.values;
                let mut i = 0;
                while i < self.len as isize {
                    let key = CStr::from_ptr(keys.offset(i).read())
                        .to_str()
                        .unwrap()
                        .to_owned();
                    let value = values.offset(i).read().into();
                    dst.insert(key, value);
                    i += 1;
                }
                Any::from(dst)
            } else if tag == Y_JSON_NULL {
                Any::Null
            } else if tag == Y_JSON_UNDEF {
                Any::Undefined
            } else if tag == Y_JSON_INT {
                Any::BigInt(self.value.integer as i64)
            } else if tag == Y_JSON_NUM {
                Any::Number(self.value.num as f64)
            } else if tag == Y_JSON_BOOL {
                Any::Bool(if self.value.flag == 0 { false } else { true })
            } else if tag == Y_JSON_BUF {
                let slice =
                    std::slice::from_raw_parts(self.value.buf as *mut u8, self.len as usize);
                Any::from(slice)
            } else if tag == Y_DOC {
                Any::Undefined
            } else {
                panic!("Unrecognized YVal value tag.")
            }
        }
    }
}

#[repr(C)]
union YInputContent {
    flag: u8,
    num: f64,
    integer: i64,
    str: *mut c_char,
    buf: *mut c_char,
    values: *mut YInput,
    map: ManuallyDrop<YMapInputData>,
    doc: *mut Doc,
    weak: *const Weak,
}

#[repr(C)]
struct YMapInputData {
    keys: *mut *mut c_char,
    values: *mut YInput,
}

impl Drop for YInput {
    fn drop(&mut self) {}
}

impl Prelim for YInput {
    type Return = Unused;

    fn into_content<'doc>(self, _: &mut yrs::TransactionMut<'doc>) -> (ItemContent, Option<Self>) {
        unsafe {
            if self.tag <= 0 {
                let value = self.into();
                (ItemContent::Any(vec![value]), None)
            } else if self.tag == Y_DOC {
                let doc = self.value.doc.as_ref().unwrap();
                (ItemContent::Doc(None, doc.clone()), None)
            } else {
                let type_ref = match self.tag {
                    Y_MAP => TypeRef::Map,
                    Y_ARRAY => TypeRef::Array,
                    Y_TEXT => TypeRef::Text,
                    Y_XML_TEXT => TypeRef::XmlText,
                    Y_XML_ELEM => {
                        let name: Arc<str> =
                            CStr::from_ptr(self.value.str).to_str().unwrap().into();
                        TypeRef::XmlElement(name)
                    }
                    Y_WEAK_LINK => {
                        let source = Arc::from_raw(self.value.weak);
                        TypeRef::WeakLink(source)
                    }
                    Y_XML_FRAG => TypeRef::XmlFragment,
                    other => panic!("unrecognized YInput tag: {}", other),
                };
                let inner = Branch::new(type_ref);
                (ItemContent::Type(inner), Some(self))
            }
        }
    }

    fn integrate(self, txn: &mut yrs::TransactionMut, inner_ref: BranchPtr) {
        unsafe {
            match self.tag {
                Y_MAP => {
                    let map = MapRef::from(inner_ref);
                    let keys = self.value.map.keys;
                    let values = self.value.map.values;
                    let mut i = 0;
                    while i < self.len as isize {
                        let key = CStr::from_ptr(keys.offset(i).read())
                            .to_str()
                            .unwrap()
                            .to_owned();
                        let value = values.offset(i).read().into();
                        map.insert(txn, key, value);
                        i += 1;
                    }
                }
                Y_ARRAY => {
                    let array = ArrayRef::from(inner_ref);
                    let ptr = self.value.values;
                    let len = self.len as isize;
                    let mut i = 0;
                    while i < len {
                        let value = ptr.offset(i).read();
                        array.push_back(txn, value);
                        i += 1;
                    }
                }
                Y_TEXT => {
                    let text = TextRef::from(inner_ref);
                    let init = CStr::from_ptr(self.value.str).to_str().unwrap();
                    text.push(txn, init);
                }
                Y_XML_TEXT => {
                    let text = XmlTextRef::from(inner_ref);
                    let init = CStr::from_ptr(self.value.str).to_str().unwrap();
                    text.push(txn, init);
                }
                _ => { /* do nothing */ }
            }
        }
    }
}

/// An output value cell returned from yrs API methods. It describes a various types of data
/// supported by yrs shared data types.
///
/// Since `YOutput` instances are always created by calling the corresponding yrs API functions,
/// they eventually should be deallocated using [youtput_destroy] function.
#[repr(C)]
pub struct YOutput {
    /// Tag describing, which `value` type is being stored by this input cell. Can be one of:
    ///
    /// - [Y_JSON_BOOL] for boolean flags.
    /// - [Y_JSON_NUM] for 64-bit floating point numbers.
    /// - [Y_JSON_INT] for 64-bit signed integers.
    /// - [Y_JSON_STR] for null-terminated UTF-8 encoded strings.
    /// - [Y_JSON_BUF] for embedded binary data.
    /// - [Y_JSON_ARR] for arrays of JSON-like values.
    /// - [Y_JSON_MAP] for JSON-like objects build from key-value pairs.
    /// - [Y_JSON_NULL] for JSON-like null values.
    /// - [Y_JSON_UNDEF] for JSON-like undefined values.
    /// - [Y_TEXT] for pointers to `YText` data types.
    /// - [Y_ARRAY] for pointers to `YArray` data types.
    /// - [Y_MAP] for pointers to `YMap` data types.
    /// - [Y_XML_ELEM] for pointers to `YXmlElement` data types.
    /// - [Y_XML_TEXT] for pointers to `YXmlText` data types.
    /// - [Y_DOC] for pointers to nested `YDocRef` data types.
    pub tag: i8,

    /// Length of the contents stored by a current `YOutput` cell.
    ///
    /// For [Y_JSON_NULL] and [Y_JSON_UNDEF] its equal to `0`.
    ///
    /// For [Y_JSON_ARR], [Y_JSON_MAP] it describes a number of passed elements.
    ///
    /// For other types it's always equal to `1`.
    pub len: u32,

    /// Union struct which contains a content corresponding to a provided `tag` field.
    value: YOutputContent,
}

impl std::fmt::Display for YOutput {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        let tag = self.tag;
        unsafe {
            if tag == Y_JSON_INT {
                write!(f, "{}", self.value.integer)
            } else if tag == Y_JSON_NUM {
                write!(f, "{}", self.value.num)
            } else if tag == Y_JSON_BOOL {
                write!(
                    f,
                    "{}",
                    if self.value.flag == 0 {
                        "false"
                    } else {
                        "true"
                    }
                )
            } else if tag == Y_JSON_UNDEF {
                write!(f, "undefined")
            } else if tag == Y_JSON_NULL {
                write!(f, "null")
            } else if tag == Y_JSON_STR {
                write!(f, "{}", CString::from_raw(self.value.str).to_str().unwrap())
            } else if tag == Y_MAP {
                write!(f, "YMap")
            } else if tag == Y_ARRAY {
                write!(f, "YArray")
            } else if tag == Y_JSON_ARR {
                write!(f, "[")?;
                let slice = std::slice::from_raw_parts(self.value.array, self.len as usize);
                for o in slice {
                    write!(f, ", {}", o)?;
                }
                write!(f, "]")
            } else if tag == Y_JSON_MAP {
                write!(f, "{{")?;
                let slice = std::slice::from_raw_parts(self.value.map, self.len as usize);
                for e in slice {
                    write!(
                        f,
                        ", '{}' => {}",
                        CStr::from_ptr(e.key).to_str().unwrap(),
                        e.value
                    )?;
                }
                write!(f, "}}")
            } else if tag == Y_TEXT {
                write!(f, "YText")
            } else if tag == Y_XML_TEXT {
                write!(f, "YXmlText")
            } else if tag == Y_XML_ELEM {
                write!(f, "YXmlElement",)
            } else if tag == Y_JSON_BUF {
                write!(f, "YBinary(len: {})", self.len)
            } else {
                Ok(())
            }
        }
    }
}

impl Drop for YOutput {
    fn drop(&mut self) {
        let tag = self.tag;
        unsafe {
            if tag == Y_JSON_STR {
                drop(CString::from_raw(self.value.str));
            } else if tag == Y_JSON_ARR {
                drop(Vec::from_raw_parts(
                    self.value.array,
                    self.len as usize,
                    self.len as usize,
                ));
            } else if tag == Y_JSON_MAP {
                drop(Vec::from_raw_parts(
                    self.value.map,
                    self.len as usize,
                    self.len as usize,
                ));
            } else if tag == Y_JSON_BUF {
                let slice =
                    std::slice::from_raw_parts(self.value.buf as *mut u8, self.len as usize);
                let arc: Arc<[u8]> = Arc::from_raw(slice);
                drop(arc);
            } else if tag == Y_DOC {
                drop(Box::from_raw(self.value.y_doc))
            }
        }
    }
}

impl From<Value> for YOutput {
    fn from(v: Value) -> Self {
        match v {
            Value::Any(v) => Self::from(v),
            Value::YText(v) => Self::from(v),
            Value::YArray(v) => Self::from(v),
            Value::YMap(v) => Self::from(v),
            Value::YXmlElement(v) => Self::from(v),
            Value::YXmlFragment(v) => Self::from(v),
            Value::YXmlText(v) => Self::from(v),
            Value::YDoc(v) => Self::from(v),
            Value::YWeakLink(v) => Self::from(v),
            Value::UndefinedRef(v) => Self::from(v),
        }
    }
}

impl From<Any> for YOutput {
    fn from(v: Any) -> Self {
        unsafe {
            match v {
                Any::Null => YOutput {
                    tag: Y_JSON_NULL,
                    len: 0,
                    value: MaybeUninit::uninit().assume_init(),
                },
                Any::Undefined => YOutput {
                    tag: Y_JSON_UNDEF,
                    len: 0,
                    value: MaybeUninit::uninit().assume_init(),
                },
                Any::Bool(v) => YOutput {
                    tag: Y_JSON_BOOL,
                    len: 1,
                    value: YOutputContent {
                        flag: if v { Y_TRUE } else { Y_FALSE },
                    },
                },
                Any::Number(v) => YOutput {
                    tag: Y_JSON_NUM,
                    len: 1,
                    value: YOutputContent { num: v as _ },
                },
                Any::BigInt(v) => YOutput {
                    tag: Y_JSON_INT,
                    len: 1,
                    value: YOutputContent { integer: v },
                },
                Any::String(v) => YOutput {
                    tag: Y_JSON_STR,
                    len: v.len() as u32,
                    value: YOutputContent {
                        str: CString::new(v.as_ref()).unwrap().into_raw(),
                    },
                },
                Any::Buffer(v) => YOutput {
                    tag: Y_JSON_BUF,
                    len: v.len() as u32,
                    value: YOutputContent {
                        buf: {
                            let ptr: *const [u8] = Arc::into_raw(v);
                            let head: *const u8 = &(*ptr)[0];
                            head as *const _
                        },
                    },
                },
                Any::Array(values) => {
                    let len = values.len() as u32;
                    let mut array = Vec::with_capacity(values.len());
                    for v in values.iter() {
                        array.push(YOutput::from(v.clone()));
                    }
                    let ptr = array.as_mut_ptr();
                    forget(array);
                    YOutput {
                        tag: Y_JSON_ARR,
                        len,
                        value: YOutputContent { array: ptr },
                    }
                }
                Any::Map(v) => {
                    let len = v.len() as u32;
                    let mut array: Vec<_> = v
                        .iter()
                        .map(|(k, v)| YMapEntry::new(k.as_str(), Value::Any(v.clone())))
                        .collect();
                    array.shrink_to_fit();
                    let ptr = array.as_mut_ptr();
                    forget(array);
                    YOutput {
                        tag: Y_JSON_MAP,
                        len,
                        value: YOutputContent { map: ptr },
                    }
                }
            }
        }
    }
}

impl From<TextRef> for YOutput {
    fn from(v: TextRef) -> Self {
        YOutput {
            tag: Y_TEXT,
            len: 1,
            value: YOutputContent {
                y_type: v.into_raw_branch(),
            },
        }
    }
}

impl From<ArrayRef> for YOutput {
    fn from(v: ArrayRef) -> Self {
        YOutput {
            tag: Y_ARRAY,
            len: 1,
            value: YOutputContent {
                y_type: v.into_raw_branch(),
            },
        }
    }
}

impl From<WeakRef<BranchPtr>> for YOutput {
    fn from(v: WeakRef<BranchPtr>) -> Self {
        YOutput {
            tag: Y_WEAK_LINK,
            len: 1,
            value: YOutputContent {
                y_type: v.into_raw_branch(),
            },
        }
    }
}

impl From<MapRef> for YOutput {
    fn from(v: MapRef) -> Self {
        YOutput {
            tag: Y_MAP,
            len: 1,
            value: YOutputContent {
                y_type: v.into_raw_branch(),
            },
        }
    }
}

impl From<BranchPtr> for YOutput {
    fn from(v: BranchPtr) -> Self {
        let branch_ref = v.as_ref();
        YOutput {
            tag: Y_UNDEFINED,
            len: 1,
            value: YOutputContent {
                y_type: branch_ref as *const Branch as *mut Branch,
            },
        }
    }
}

impl From<XmlElementRef> for YOutput {
    fn from(v: XmlElementRef) -> Self {
        YOutput {
            tag: Y_XML_ELEM,
            len: 1,
            value: YOutputContent {
                y_type: v.into_raw_branch(),
            },
        }
    }
}

impl From<XmlTextRef> for YOutput {
    fn from(v: XmlTextRef) -> Self {
        YOutput {
            tag: Y_XML_TEXT,
            len: 1,
            value: YOutputContent {
                y_type: v.into_raw_branch(),
            },
        }
    }
}

impl From<XmlFragmentRef> for YOutput {
    fn from(v: XmlFragmentRef) -> Self {
        YOutput {
            tag: Y_XML_FRAG,
            len: 1,
            value: YOutputContent {
                y_type: v.into_raw_branch(),
            },
        }
    }
}

impl From<Doc> for YOutput {
    fn from(v: Doc) -> Self {
        YOutput {
            tag: Y_DOC,
            len: 1,
            value: YOutputContent {
                y_doc: Box::into_raw(Box::new(v.clone())),
            },
        }
    }
}

#[repr(C)]
union YOutputContent {
    flag: u8,
    num: f64,
    integer: i64,
    str: *mut c_char,
    buf: *const c_char,
    array: *mut YOutput,
    map: *mut YMapEntry,
    y_type: *mut Branch,
    y_doc: *mut Doc,
}

/// Releases all resources related to a corresponding `YOutput` cell.
#[no_mangle]
pub unsafe extern "C" fn youtput_destroy(val: *mut YOutput) {
    if !val.is_null() {
        drop(Box::from_raw(val))
    }
}

/// Function constructor used to create JSON-like NULL `YInput` cell.
/// This function doesn't allocate any heap resources.
#[no_mangle]
pub unsafe extern "C" fn yinput_null() -> YInput {
    YInput {
        tag: Y_JSON_NULL,
        len: 0,
        value: MaybeUninit::uninit().assume_init(),
    }
}

/// Function constructor used to create JSON-like undefined `YInput` cell.
/// This function doesn't allocate any heap resources.
#[no_mangle]
pub unsafe extern "C" fn yinput_undefined() -> YInput {
    YInput {
        tag: Y_JSON_UNDEF,
        len: 0,
        value: MaybeUninit::uninit().assume_init(),
    }
}

/// Function constructor used to create JSON-like boolean `YInput` cell.
/// This function doesn't allocate any heap resources.
#[no_mangle]
pub unsafe extern "C" fn yinput_bool(flag: u8) -> YInput {
    YInput {
        tag: Y_JSON_BOOL,
        len: 1,
        value: YInputContent { flag },
    }
}

/// Function constructor used to create JSON-like 64-bit floating point number `YInput` cell.
/// This function doesn't allocate any heap resources.
#[no_mangle]
pub unsafe extern "C" fn yinput_float(num: f64) -> YInput {
    YInput {
        tag: Y_JSON_NUM,
        len: 1,
        value: YInputContent { num },
    }
}

/// Function constructor used to create JSON-like 64-bit signed integer `YInput` cell.
/// This function doesn't allocate any heap resources.
#[no_mangle]
pub unsafe extern "C" fn yinput_long(integer: i64) -> YInput {
    YInput {
        tag: Y_JSON_INT,
        len: 1,
        value: YInputContent { integer },
    }
}

/// Function constructor used to create a string `YInput` cell. Provided parameter must be
/// a null-terminated UTF-8 encoded string. This function doesn't allocate any heap resources,
/// and doesn't release any on its own, therefore its up to a caller to free resources once
/// a structure is no longer needed.
#[no_mangle]
pub unsafe extern "C" fn yinput_string(str: *const c_char) -> YInput {
    YInput {
        tag: Y_JSON_STR,
        len: 1,
        value: YInputContent {
            str: str as *mut c_char,
        },
    }
}

/// Function constructor used to create a binary `YInput` cell of a specified length.
/// This function doesn't allocate any heap resources and doesn't release any on its own, therefore
/// its up to a caller to free resources once a structure is no longer needed.
#[no_mangle]
pub unsafe extern "C" fn yinput_binary(buf: *const c_char, len: u32) -> YInput {
    YInput {
        tag: Y_JSON_BUF,
        len,
        value: YInputContent {
            buf: buf as *mut c_char,
        },
    }
}

/// Function constructor used to create a JSON-like array `YInput` cell of other JSON-like values of
/// a given length. This function doesn't allocate any heap resources and doesn't release any on its
/// own, therefore its up to a caller to free resources once a structure is no longer needed.
#[no_mangle]
pub unsafe extern "C" fn yinput_json_array(values: *mut YInput, len: u32) -> YInput {
    YInput {
        tag: Y_JSON_ARR,
        len,
        value: YInputContent { values },
    }
}

/// Function constructor used to create a JSON-like map `YInput` cell of other JSON-like key-value
/// pairs. These pairs are build from corresponding indexes of `keys` and `values`, which must have
/// the same specified length.
///
/// This function doesn't allocate any heap resources and doesn't release any on its own, therefore
/// its up to a caller to free resources once a structure is no longer needed.
#[no_mangle]
pub unsafe extern "C" fn yinput_json_map(
    keys: *mut *mut c_char,
    values: *mut YInput,
    len: u32,
) -> YInput {
    YInput {
        tag: Y_JSON_MAP,
        len,
        value: YInputContent {
            map: ManuallyDrop::new(YMapInputData { keys, values }),
        },
    }
}

/// Function constructor used to create a nested `YArray` `YInput` cell prefilled with other
/// values of a given length. This function doesn't allocate any heap resources and doesn't release
/// any on its own, therefore its up to a caller to free resources once a structure is no longer
/// needed.
#[no_mangle]
pub unsafe extern "C" fn yinput_yarray(values: *mut YInput, len: u32) -> YInput {
    YInput {
        tag: Y_ARRAY,
        len,
        value: YInputContent { values },
    }
}

/// Function constructor used to create a nested `YMap` `YInput` cell prefilled with other key-value
/// pairs. These pairs are build from corresponding indexes of `keys` and `values`, which must have
/// the same specified length.
///
/// This function doesn't allocate any heap resources and doesn't release any on its own, therefore
/// its up to a caller to free resources once a structure is no longer needed.
#[no_mangle]
pub unsafe extern "C" fn yinput_ymap(
    keys: *mut *mut c_char,
    values: *mut YInput,
    len: u32,
) -> YInput {
    YInput {
        tag: Y_MAP,
        len,
        value: YInputContent {
            map: ManuallyDrop::new(YMapInputData { keys, values }),
        },
    }
}

/// Function constructor used to create a nested `YText` `YInput` cell prefilled with a specified
/// string, which must be a null-terminated UTF-8 character pointer.
///
/// This function doesn't allocate any heap resources and doesn't release any on its own, therefore
/// its up to a caller to free resources once a structure is no longer needed.
#[no_mangle]
pub unsafe extern "C" fn yinput_ytext(str: *mut c_char) -> YInput {
    YInput {
        tag: Y_TEXT,
        len: 1,
        value: YInputContent { str },
    }
}

/// Function constructor used to create a nested `YXmlElement` `YInput` cell with a specified
/// tag name, which must be a null-terminated UTF-8 character pointer.
///
/// This function doesn't allocate any heap resources and doesn't release any on its own, therefore
/// its up to a caller to free resources once a structure is no longer needed.
#[no_mangle]
pub unsafe extern "C" fn yinput_yxmlelem(name: *mut c_char) -> YInput {
    YInput {
        tag: Y_XML_ELEM,
        len: 1,
        value: YInputContent { str: name },
    }
}

/// Function constructor used to create a nested `YXmlText` `YInput` cell prefilled with a specified
/// string, which must be a null-terminated UTF-8 character pointer.
///
/// This function doesn't allocate any heap resources and doesn't release any on its own, therefore
/// its up to a caller to free resources once a structure is no longer needed.
#[no_mangle]
pub unsafe extern "C" fn yinput_yxmltext(str: *mut c_char) -> YInput {
    YInput {
        tag: Y_XML_TEXT,
        len: 1,
        value: YInputContent { str },
    }
}

/// Function constructor used to create a nested `YDoc` `YInput` cell.
///
/// This function doesn't allocate any heap resources and doesn't release any on its own, therefore
/// its up to a caller to free resources once a structure is no longer needed.
#[no_mangle]
pub unsafe extern "C" fn yinput_ydoc(doc: *mut Doc) -> YInput {
    YInput {
        tag: Y_DOC,
        len: 1,
        value: YInputContent { doc },
    }
}

/// Function constructor used to create a string `YInput` cell with weak reference to another
/// element(s) living inside of the same document.
#[no_mangle]
pub unsafe extern "C" fn yinput_weak(weak: *const Weak) -> YInput {
    YInput {
        tag: Y_WEAK_LINK,
        len: 1,
        value: YInputContent { weak },
    }
}

/// Attempts to read the value for a given `YOutput` pointer as a `YDocRef` reference to a nested
/// document.
#[no_mangle]
pub unsafe extern "C" fn youtput_read_ydoc(val: *const YOutput) -> *mut Doc {
    let v = val.as_ref().unwrap();
    if v.tag == Y_DOC {
        v.value.y_doc
    } else {
        std::ptr::null_mut()
    }
}

/// Attempts to read the value for a given `YOutput` pointer as a boolean flag, which can be either
/// `1` for truthy case and `0` otherwise. Returns a null pointer in case when a value stored under
/// current `YOutput` cell is not of a boolean type.
#[no_mangle]
pub unsafe extern "C" fn youtput_read_bool(val: *const YOutput) -> *const u8 {
    let v = val.as_ref().unwrap();
    if v.tag == Y_JSON_BOOL {
        &v.value.flag
    } else {
        std::ptr::null()
    }
}

/// Attempts to read the value for a given `YOutput` pointer as a 64-bit floating point number.
///
/// Returns a null pointer in case when a value stored under current `YOutput` cell
/// is not a floating point number.
#[no_mangle]
pub unsafe extern "C" fn youtput_read_float(val: *const YOutput) -> *const f64 {
    let v = val.as_ref().unwrap();
    if v.tag == Y_JSON_NUM {
        &v.value.num
    } else {
        std::ptr::null()
    }
}

/// Attempts to read the value for a given `YOutput` pointer as a 64-bit signed integer.
///
/// Returns a null pointer in case when a value stored under current `YOutput` cell
/// is not a signed integer.
#[no_mangle]
pub unsafe extern "C" fn youtput_read_long(val: *const YOutput) -> *const i64 {
    let v = val.as_ref().unwrap();
    if v.tag == Y_JSON_INT {
        &v.value.integer
    } else {
        std::ptr::null()
    }
}

/// Attempts to read the value for a given `YOutput` pointer as a null-terminated UTF-8 encoded
/// string.
///
/// Returns a null pointer in case when a value stored under current `YOutput` cell
/// is not a string. Underlying string is released automatically as part of [youtput_destroy]
/// destructor.
#[no_mangle]
pub unsafe extern "C" fn youtput_read_string(val: *const YOutput) -> *mut c_char {
    let v = val.as_ref().unwrap();
    if v.tag == Y_JSON_STR {
        v.value.str
    } else {
        std::ptr::null_mut()
    }
}

/// Attempts to read the value for a given `YOutput` pointer as a binary payload (which length is
/// stored within `len` filed of a cell itself).
///
/// Returns a null pointer in case when a value stored under current `YOutput` cell
/// is not a binary type. Underlying binary is released automatically as part of [youtput_destroy]
/// destructor.
#[no_mangle]
pub unsafe extern "C" fn youtput_read_binary(val: *const YOutput) -> *const c_char {
    let v = val.as_ref().unwrap();
    if v.tag == Y_JSON_BUF {
        v.value.buf
    } else {
        std::ptr::null()
    }
}

/// Attempts to read the value for a given `YOutput` pointer as a JSON-like array of `YOutput`
/// values (which length is stored within `len` filed of a cell itself).
///
/// Returns a null pointer in case when a value stored under current `YOutput` cell
/// is not a JSON-like array. Underlying heap resources are released automatically as part of
/// [youtput_destroy] destructor.
#[no_mangle]
pub unsafe extern "C" fn youtput_read_json_array(val: *const YOutput) -> *mut YOutput {
    let v = val.as_ref().unwrap();
    if v.tag == Y_JSON_ARR {
        v.value.array
    } else {
        std::ptr::null_mut()
    }
}

/// Attempts to read the value for a given `YOutput` pointer as a JSON-like map of key-value entries
/// (which length is stored within `len` filed of a cell itself).
///
/// Returns a null pointer in case when a value stored under current `YOutput` cell
/// is not a JSON-like map. Underlying heap resources are released automatically as part of
/// [youtput_destroy] destructor.
#[no_mangle]
pub unsafe extern "C" fn youtput_read_json_map(val: *const YOutput) -> *mut YMapEntry {
    let v = val.as_ref().unwrap();
    if v.tag == Y_JSON_MAP {
        v.value.map
    } else {
        std::ptr::null_mut()
    }
}

/// Attempts to read the value for a given `YOutput` pointer as an `YArray`.
///
/// Returns a null pointer in case when a value stored under current `YOutput` cell
/// is not an `YArray`. Underlying heap resources are released automatically as part of
/// [youtput_destroy] destructor.
#[no_mangle]
pub unsafe extern "C" fn youtput_read_yarray(val: *const YOutput) -> *mut Branch {
    let v = val.as_ref().unwrap();
    if v.tag == Y_ARRAY {
        v.value.y_type
    } else {
        std::ptr::null_mut()
    }
}

/// Attempts to read the value for a given `YOutput` pointer as an `YXmlElement`.
///
/// Returns a null pointer in case when a value stored under current `YOutput` cell
/// is not an `YXmlElement`. Underlying heap resources are released automatically as part of
/// [youtput_destroy] destructor.
#[no_mangle]
pub unsafe extern "C" fn youtput_read_yxmlelem(val: *const YOutput) -> *mut Branch {
    let v = val.as_ref().unwrap();
    if v.tag == Y_XML_ELEM {
        v.value.y_type
    } else {
        std::ptr::null_mut()
    }
}

/// Attempts to read the value for a given `YOutput` pointer as an `YMap`.
///
/// Returns a null pointer in case when a value stored under current `YOutput` cell
/// is not an `YMap`. Underlying heap resources are released automatically as part of
/// [youtput_destroy] destructor.
#[no_mangle]
pub unsafe extern "C" fn youtput_read_ymap(val: *const YOutput) -> *mut Branch {
    let v = val.as_ref().unwrap();
    if v.tag == Y_MAP {
        v.value.y_type
    } else {
        std::ptr::null_mut()
    }
}

/// Attempts to read the value for a given `YOutput` pointer as an `YText`.
///
/// Returns a null pointer in case when a value stored under current `YOutput` cell
/// is not an `YText`. Underlying heap resources are released automatically as part of
/// [youtput_destroy] destructor.
#[no_mangle]
pub unsafe extern "C" fn youtput_read_ytext(val: *const YOutput) -> *mut Branch {
    let v = val.as_ref().unwrap();
    if v.tag == Y_TEXT {
        v.value.y_type
    } else {
        std::ptr::null_mut()
    }
}

/// Attempts to read the value for a given `YOutput` pointer as an `YXmlText`.
///
/// Returns a null pointer in case when a value stored under current `YOutput` cell
/// is not an `YXmlText`. Underlying heap resources are released automatically as part of
/// [youtput_destroy] destructor.
#[no_mangle]
pub unsafe extern "C" fn youtput_read_yxmltext(val: *const YOutput) -> *mut Branch {
    let v = val.as_ref().unwrap();
    if v.tag == Y_XML_TEXT {
        v.value.y_type
    } else {
        std::ptr::null_mut()
    }
}

/// Attempts to read the value for a given `YOutput` pointer as an `YWeakRef`.
///
/// Returns a null pointer in case when a value stored under current `YOutput` cell
/// is not an `YWeakRef`. Underlying heap resources are released automatically as part of
/// [youtput_destroy] destructor.
#[no_mangle]
pub unsafe extern "C" fn youtput_read_yweak(val: *const YOutput) -> *mut Branch {
    let v = val.as_ref().unwrap();
    if v.tag == Y_WEAK_LINK {
        v.value.y_type
    } else {
        std::ptr::null_mut()
    }
}

/// Unsubscribe callback from the oberver event it was previously subscribed to.
#[no_mangle]
pub unsafe extern "C" fn yunobserve(subscription: *mut Subscription) {
    drop(unsafe { Box::from_raw(subscription) })
}

/// Subscribes a given callback function `cb` to changes made by this `YText` instance. Callbacks
/// are triggered whenever a `ytransaction_commit` is called.
/// Returns a subscription ID which can be then used to unsubscribe this callback by using
/// `yunobserve` function.
#[no_mangle]
pub unsafe extern "C" fn ytext_observe(
    txt: *const Branch,
    state: *mut c_void,
    cb: extern "C" fn(*mut c_void, *const YTextEvent),
) -> *mut Subscription {
    assert!(!txt.is_null());

    let txt = TextRef::from_raw_branch(txt);
    let subscription = txt.observe(move |txn, e| {
        let e = YTextEvent::new(e, txn);
        cb(state, &e as *const YTextEvent);
    });
    Box::into_raw(Box::new(subscription))
}

/// Subscribes a given callback function `cb` to changes made by this `YMap` instance. Callbacks
/// are triggered whenever a `ytransaction_commit` is called.
/// Returns a subscription ID which can be then used to unsubscribe this callback by using
/// `yunobserve` function.
#[no_mangle]
pub unsafe extern "C" fn ymap_observe(
    map: *const Branch,
    state: *mut c_void,
    cb: extern "C" fn(*mut c_void, *const YMapEvent),
) -> *mut Subscription {
    assert!(!map.is_null());

    let map = MapRef::from_raw_branch(map);
    let subscription = map.observe(move |txn, e| {
        let e = YMapEvent::new(e, txn);
        cb(state, &e as *const YMapEvent);
    });
    Box::into_raw(Box::new(subscription))
}

/// Subscribes a given callback function `cb` to changes made by this `YArray` instance. Callbacks
/// are triggered whenever a `ytransaction_commit` is called.
/// Returns a subscription ID which can be then used to unsubscribe this callback by using
/// `yunobserve` function.
#[no_mangle]
pub unsafe extern "C" fn yarray_observe(
    array: *const Branch,
    state: *mut c_void,
    cb: extern "C" fn(*mut c_void, *const YArrayEvent),
) -> *mut Subscription {
    assert!(!array.is_null());

    let array = ArrayRef::from_raw_branch(array);
    let subscription = array.observe(move |txn, e| {
        let e = YArrayEvent::new(e, txn);
        cb(state, &e as *const YArrayEvent);
    });
    Box::into_raw(Box::new(subscription))
}

/// Subscribes a given callback function `cb` to changes made by this `YXmlElement` instance.
/// Callbacks are triggered whenever a `ytransaction_commit` is called.
/// Returns a subscription ID which can be then used to unsubscribe this callback by using
/// `yunobserve` function.
#[no_mangle]
pub unsafe extern "C" fn yxmlelem_observe(
    xml: *const Branch,
    state: *mut c_void,
    cb: extern "C" fn(*mut c_void, *const YXmlEvent),
) -> *mut Subscription {
    assert!(!xml.is_null());

    let xml = XmlElementRef::from_raw_branch(xml);
    let subscription = xml.observe(move |txn, e| {
        let e = YXmlEvent::new(e, txn);
        cb(state, &e as *const YXmlEvent);
    });
    Box::into_raw(Box::new(subscription))
}

/// Subscribes a given callback function `cb` to changes made by this `YXmlText` instance. Callbacks
/// are triggered whenever a `ytransaction_commit` is called.
/// Returns a subscription ID which can be then used to unsubscribe this callback by using
/// `yunobserve` function.
#[no_mangle]
pub unsafe extern "C" fn yxmltext_observe(
    xml: *const Branch,
    state: *mut c_void,
    cb: extern "C" fn(*mut c_void, *const YXmlTextEvent),
) -> *mut Subscription {
    assert!(!xml.is_null());

    let xml = XmlTextRef::from_raw_branch(xml);
    let subscription = xml.observe(move |txn, e| {
        let e = YXmlTextEvent::new(e, txn);
        cb(state, &e as *const YXmlTextEvent);
    });
    Box::into_raw(Box::new(subscription))
}

/// Subscribes a given callback function `cb` to changes made by this shared type instance as well
/// as all nested shared types living within it. Callbacks are triggered whenever a
/// `ytransaction_commit` is called.
///
/// Returns a subscription ID which can be then used to unsubscribe this callback by using
/// `yunobserve` function.
#[no_mangle]
pub unsafe extern "C" fn yobserve_deep(
    ytype: *mut Branch,
    state: *mut c_void,
    cb: extern "C" fn(*mut c_void, u32, *const YEvent),
) -> *mut Subscription {
    assert!(!ytype.is_null());

    let branch = ytype.as_mut().unwrap();
    let subscription = branch.observe_deep(move |txn, events| {
        let events: Vec<_> = events.iter().map(|e| YEvent::new(txn, e)).collect();
        let len = events.len() as u32;
        cb(state, len, events.as_ptr());
    });
    Box::into_raw(Box::new(subscription))
}

/// Event generated for callbacks subscribed using `ydoc_observe_after_transaction`. It contains
/// snapshot of changes made within any committed transaction.
#[repr(C)]
pub struct YAfterTransactionEvent {
    /// Descriptor of a document state at the moment of creating the transaction.
    pub before_state: YStateVector,
    /// Descriptor of a document state at the moment of committing the transaction.
    pub after_state: YStateVector,
    /// Information about all items deleted within the scope of a transaction.
    pub delete_set: YDeleteSet,
}

impl YAfterTransactionEvent {
    unsafe fn new(e: &TransactionCleanupEvent) -> Self {
        YAfterTransactionEvent {
            before_state: YStateVector::new(&e.before_state),
            after_state: YStateVector::new(&e.after_state),
            delete_set: YDeleteSet::new(&e.delete_set),
        }
    }
}

#[repr(C)]
pub struct YSubdocsEvent {
    added_len: u32,
    removed_len: u32,
    loaded_len: u32,
    added: *mut *mut Doc,
    removed: *mut *mut Doc,
    loaded: *mut *mut Doc,
}

impl YSubdocsEvent {
    unsafe fn new(e: &SubdocsEvent) -> Self {
        fn into_ptr(v: SubdocsEventIter) -> *mut *mut Doc {
            let array: Vec<_> = v.map(|doc| Box::into_raw(Box::new(doc.clone()))).collect();
            let mut boxed = array.into_boxed_slice();
            let ptr = boxed.as_mut_ptr();
            forget(boxed);
            ptr
        }

        let added = e.added();
        let removed = e.removed();
        let loaded = e.loaded();

        YSubdocsEvent {
            added_len: added.len() as u32,
            removed_len: removed.len() as u32,
            loaded_len: loaded.len() as u32,
            added: into_ptr(added),
            removed: into_ptr(removed),
            loaded: into_ptr(loaded),
        }
    }
}

impl Drop for YSubdocsEvent {
    fn drop(&mut self) {
        fn release(len: u32, buf: *mut *mut Doc) {
            unsafe {
                let docs = Vec::from_raw_parts(buf, len as usize, len as usize);
                for d in docs {
                    drop(Box::from_raw(d));
                }
            }
        }

        release(self.added_len, self.added);
        release(self.removed_len, self.removed);
        release(self.loaded_len, self.loaded);
    }
}

/// Struct representing a state of a document. It contains the last seen clocks for blocks submitted
/// per any of the clients collaborating on document updates.
#[repr(C)]
pub struct YStateVector {
    /// Number of clients. It describes a length of both `client_ids` and `clocks` arrays.
    pub entries_count: u32,
    /// Array of unique client identifiers (length is given in `entries_count` field). Each client
    /// ID has corresponding clock attached, which can be found in `clocks` field under the same
    /// index.
    pub client_ids: *mut u64,
    /// Array of clocks (length is given in `entries_count` field) known for each client. Each clock
    /// has a corresponding client identifier attached, which can be found in `client_ids` field
    /// under the same index.
    pub clocks: *mut u32,
}

impl YStateVector {
    unsafe fn new(sv: &StateVector) -> Self {
        let entries_count = sv.len() as u32;
        let mut client_ids = Vec::with_capacity(sv.len());
        let mut clocks = Vec::with_capacity(sv.len());
        for (&client, &clock) in sv.iter() {
            client_ids.push(client as u64);
            clocks.push(clock as u32);
        }

        YStateVector {
            entries_count,
            client_ids: Box::into_raw(client_ids.into_boxed_slice()) as *mut _,
            clocks: Box::into_raw(clocks.into_boxed_slice()) as *mut _,
        }
    }
}

impl Drop for YStateVector {
    fn drop(&mut self) {
        let len = self.entries_count as usize;
        drop(unsafe { Vec::from_raw_parts(self.client_ids, len, len) });
        drop(unsafe { Vec::from_raw_parts(self.clocks, len, len) });
    }
}

/// Delete set is a map of `(ClientID, Range[])` entries. Length of a map is stored in
/// `entries_count` field. ClientIDs reside under `client_ids` and their corresponding range
/// sequences can be found under the same index of `ranges` field.
#[repr(C)]
pub struct YDeleteSet {
    /// Number of client identifier entries.
    pub entries_count: u32,
    /// Array of unique client identifiers (length is given in `entries_count` field). Each client
    /// ID has corresponding sequence of ranges attached, which can be found in `ranges` field under
    /// the same index.
    pub client_ids: *mut u64,
    /// Array of range sequences (length is given in `entries_count` field). Each sequence has
    /// a corresponding client ID attached, which can be found in `client_ids` field under
    /// the same index.
    pub ranges: *mut YIdRangeSeq,
}

impl YDeleteSet {
    unsafe fn new(ds: &DeleteSet) -> Self {
        let len = ds.len();
        let mut client_ids = Vec::with_capacity(len);
        let mut ranges = Vec::with_capacity(len);

        for (&client, range) in ds.iter() {
            client_ids.push(client);
            let seq: Vec<_> = range
                .iter()
                .map(|r| YIdRange {
                    start: r.start as u32,
                    end: r.end as u32,
                })
                .collect();
            ranges.push(YIdRangeSeq {
                len: seq.len() as u32,
                seq: Box::into_raw(seq.into_boxed_slice()) as *mut _,
            })
        }

        YDeleteSet {
            entries_count: len as u32,
            client_ids: Box::into_raw(client_ids.into_boxed_slice()) as *mut _,
            ranges: Box::into_raw(ranges.into_boxed_slice()) as *mut _,
        }
    }
}

impl Drop for YDeleteSet {
    fn drop(&mut self) {
        let len = self.entries_count as usize;
        drop(unsafe { Vec::from_raw_parts(self.client_ids, len, len) });
        drop(unsafe { Vec::from_raw_parts(self.ranges, len, len) });
    }
}

/// Fixed-length sequence of ID ranges. Each range is a pair of [start, end) values, describing the
/// range of items identified by clock values, that this range refers to.
#[repr(C)]
pub struct YIdRangeSeq {
    /// Number of ranges stored in this sequence.
    pub len: u32,
    /// Array (length is stored in `len` field) or ranges. Each range is a pair of [start, end)
    /// values, describing continuous collection of items produced by the same client, identified
    /// by clock values, that this range refers to.
    pub seq: *mut YIdRange,
}

impl Drop for YIdRangeSeq {
    fn drop(&mut self) {
        let len = self.len as usize;
        drop(unsafe { Vec::from_raw_parts(self.seq, len, len) })
    }
}

#[repr(C)]
pub struct YIdRange {
    pub start: u32,
    pub end: u32,
}

#[repr(C)]
pub struct YEvent {
    /// Tag describing, which shared type emitted this event.
    ///
    /// - [Y_TEXT] for pointers to `YText` data types.
    /// - [Y_ARRAY] for pointers to `YArray` data types.
    /// - [Y_MAP] for pointers to `YMap` data types.
    /// - [Y_XML_ELEM] for pointers to `YXmlElement` data types.
    /// - [Y_XML_TEXT] for pointers to `YXmlText` data types.
    pub tag: i8,

    /// A nested event type, specific for a shared data type that triggered it. Type of an
    /// event can be verified using `tag` field.
    pub content: YEventContent,
}

impl YEvent {
    fn new<'doc>(txn: &yrs::TransactionMut<'doc>, e: &Event) -> YEvent {
        match e {
            Event::Text(e) => YEvent {
                tag: Y_TEXT,
                content: YEventContent {
                    text: YTextEvent::new(e, txn),
                },
            },
            Event::Array(e) => YEvent {
                tag: Y_ARRAY,
                content: YEventContent {
                    array: YArrayEvent::new(e, txn),
                },
            },
            Event::Map(e) => YEvent {
                tag: Y_MAP,
                content: YEventContent {
                    map: YMapEvent::new(e, txn),
                },
            },
            Event::XmlFragment(e) => YEvent {
                tag: if let XmlNode::Fragment(_) = e.target() {
                    Y_XML_FRAG
                } else {
                    Y_XML_ELEM
                },
                content: YEventContent {
                    xml_elem: YXmlEvent::new(e, txn),
                },
            },
            Event::XmlText(e) => YEvent {
                tag: Y_XML_TEXT,
                content: YEventContent {
                    xml_text: YXmlTextEvent::new(e, txn),
                },
            },
            Event::Weak(e) => YEvent {
                tag: Y_WEAK_LINK,
                content: YEventContent {
                    weak: YWeakLinkEvent::new(e, txn),
                },
            },
        }
    }
}

#[repr(C)]
pub union YEventContent {
    pub text: YTextEvent,
    pub map: YMapEvent,
    pub array: YArrayEvent,
    pub xml_elem: YXmlEvent,
    pub xml_text: YXmlTextEvent,
    pub weak: YWeakLinkEvent,
}

/// Event pushed into callbacks registered with `ytext_observe` function. It contains delta of all
/// text changes made within a scope of corresponding transaction (see: `ytext_event_delta`) as
/// well as navigation data used to identify a `YText` instance which triggered this event.
#[repr(C)]
#[derive(Copy, Clone)]
pub struct YTextEvent {
    inner: *const c_void,
    txn: *const yrs::TransactionMut<'static>,
}

impl YTextEvent {
    fn new<'dev>(inner: &TextEvent, txn: &yrs::TransactionMut<'dev>) -> Self {
        let inner = inner as *const TextEvent as *const _;
        let txn: &yrs::TransactionMut<'static> = unsafe { std::mem::transmute(txn) };
        let txn = txn as *const _;
        YTextEvent { inner, txn }
    }

    fn txn(&self) -> &yrs::TransactionMut {
        unsafe { self.txn.as_ref().unwrap() }
    }
}

impl Deref for YTextEvent {
    type Target = TextEvent;

    fn deref(&self) -> &Self::Target {
        unsafe { (self.inner as *const TextEvent).as_ref().unwrap() }
    }
}

/// Event pushed into callbacks registered with `yarray_observe` function. It contains delta of all
/// content changes made within a scope of corresponding transaction (see: `yarray_event_delta`) as
/// well as navigation data used to identify a `YArray` instance which triggered this event.
#[repr(C)]
#[derive(Copy, Clone)]
pub struct YArrayEvent {
    inner: *const c_void,
    txn: *const yrs::TransactionMut<'static>,
}

impl YArrayEvent {
    fn new<'doc>(inner: &ArrayEvent, txn: &yrs::TransactionMut<'doc>) -> Self {
        let inner = inner as *const ArrayEvent as *const _;
        let txn: &yrs::TransactionMut<'static> = unsafe { std::mem::transmute(txn) };
        let txn = txn as *const _;
        YArrayEvent { inner, txn }
    }

    fn txn(&self) -> &yrs::TransactionMut {
        unsafe { self.txn.as_ref().unwrap() }
    }
}

impl Deref for YArrayEvent {
    type Target = ArrayEvent;

    fn deref(&self) -> &Self::Target {
        unsafe { (self.inner as *const ArrayEvent).as_ref().unwrap() }
    }
}

/// Event pushed into callbacks registered with `ymap_observe` function. It contains all
/// key-value changes made within a scope of corresponding transaction (see: `ymap_event_keys`) as
/// well as navigation data used to identify a `YMap` instance which triggered this event.
#[repr(C)]
#[derive(Copy, Clone)]
pub struct YMapEvent {
    inner: *const c_void,
    txn: *const yrs::TransactionMut<'static>,
}

impl YMapEvent {
    fn new<'doc>(inner: &MapEvent, txn: &yrs::TransactionMut<'doc>) -> Self {
        let inner = inner as *const MapEvent as *const _;
        let txn: &yrs::TransactionMut<'static> = unsafe { std::mem::transmute(txn) };
        let txn = txn as *const _;
        YMapEvent { inner, txn }
    }

    fn txn(&self) -> &yrs::TransactionMut<'static> {
        unsafe { self.txn.as_ref().unwrap() }
    }
}

impl Deref for YMapEvent {
    type Target = MapEvent;

    fn deref(&self) -> &Self::Target {
        unsafe { (self.inner as *const MapEvent).as_ref().unwrap() }
    }
}

/// Event pushed into callbacks registered with `yxmlelem_observe` function. It contains
/// all attribute changes made within a scope of corresponding transaction
/// (see: `yxmlelem_event_keys`) as well as child XML nodes changes (see: `yxmlelem_event_delta`)
/// and navigation data used to identify a `YXmlElement` instance which triggered this event.
#[repr(C)]
#[derive(Copy, Clone)]
pub struct YXmlEvent {
    inner: *const c_void,
    txn: *const yrs::TransactionMut<'static>,
}

impl YXmlEvent {
    fn new<'doc>(inner: &XmlEvent, txn: &yrs::TransactionMut<'doc>) -> Self {
        let inner = inner as *const XmlEvent as *const _;
        let txn: &yrs::TransactionMut<'static> = unsafe { std::mem::transmute(txn) };
        let txn = txn as *const _;
        YXmlEvent { inner, txn }
    }

    fn txn(&self) -> &yrs::TransactionMut<'static> {
        unsafe { self.txn.as_ref().unwrap() }
    }
}

impl Deref for YXmlEvent {
    type Target = XmlEvent;

    fn deref(&self) -> &Self::Target {
        unsafe { (self.inner as *const XmlEvent).as_ref().unwrap() }
    }
}

/// Event pushed into callbacks registered with `yxmltext_observe` function. It contains
/// all attribute changes made within a scope of corresponding transaction
/// (see: `yxmltext_event_keys`) as well as text edits (see: `yxmltext_event_delta`)
/// and navigation data used to identify a `YXmlText` instance which triggered this event.
#[repr(C)]
#[derive(Copy, Clone)]
pub struct YXmlTextEvent {
    inner: *const c_void,
    txn: *const yrs::TransactionMut<'static>,
}

impl YXmlTextEvent {
    fn new<'doc>(inner: &XmlTextEvent, txn: &yrs::TransactionMut<'doc>) -> Self {
        let inner = inner as *const XmlTextEvent as *const _;
        let txn: &yrs::TransactionMut<'static> = unsafe { std::mem::transmute(txn) };
        let txn = txn as *const _;
        YXmlTextEvent { inner, txn }
    }

    fn txn(&self) -> &yrs::TransactionMut<'static> {
        unsafe { self.txn.as_ref().unwrap() }
    }
}

impl Deref for YXmlTextEvent {
    type Target = XmlTextEvent;

    fn deref(&self) -> &Self::Target {
        unsafe { (self.inner as *const XmlTextEvent).as_ref().unwrap() }
    }
}

/// Event pushed into callbacks registered with `yweak_observe` function. It contains
/// all an event changes of the underlying transaction.
#[repr(C)]
#[derive(Copy, Clone)]
pub struct YWeakLinkEvent {
    inner: *const c_void,
    txn: *const yrs::TransactionMut<'static>,
}

impl YWeakLinkEvent {
    fn new<'doc>(inner: &WeakEvent, txn: &yrs::TransactionMut<'doc>) -> Self {
        let inner = inner as *const WeakEvent as *const _;
        let txn: &yrs::TransactionMut<'static> = unsafe { std::mem::transmute(txn) };
        let txn = txn as *const _;
        YWeakLinkEvent { inner, txn }
    }
}

impl Deref for YWeakLinkEvent {
    type Target = WeakEvent;

    fn deref(&self) -> &Self::Target {
        unsafe { (self.inner as *const WeakEvent).as_ref().unwrap() }
    }
}

/// Returns a pointer to a shared collection, which triggered passed event `e`.
#[no_mangle]
pub unsafe extern "C" fn ytext_event_target(e: *const YTextEvent) -> *mut Branch {
    assert!(!e.is_null());
    let out = (&*e).target().clone();
    out.into_raw_branch()
}

/// Returns a pointer to a shared collection, which triggered passed event `e`.
#[no_mangle]
pub unsafe extern "C" fn yarray_event_target(e: *const YArrayEvent) -> *mut Branch {
    assert!(!e.is_null());
    let out = (&*e).target().clone();
    out.into_raw_branch()
}

/// Returns a pointer to a shared collection, which triggered passed event `e`.
#[no_mangle]
pub unsafe extern "C" fn ymap_event_target(e: *const YMapEvent) -> *mut Branch {
    assert!(!e.is_null());
    let out = (&*e).target().clone();
    out.into_raw_branch()
}

/// Returns a pointer to a shared collection, which triggered passed event `e`.
#[no_mangle]
pub unsafe extern "C" fn yxmlelem_event_target(e: *const YXmlEvent) -> *mut Branch {
    assert!(!e.is_null());
    let out = (&*e).target().clone();
    match out {
        XmlNode::Element(e) => e.into_raw_branch(),
        XmlNode::Fragment(e) => e.into_raw_branch(),
        XmlNode::Text(e) => e.into_raw_branch(),
    }
}

/// Returns a pointer to a shared collection, which triggered passed event `e`.
#[no_mangle]
pub unsafe extern "C" fn yxmltext_event_target(e: *const YXmlTextEvent) -> *mut Branch {
    assert!(!e.is_null());
    let out = (&*e).target().clone();
    out.into_raw_branch()
}

/// Returns a path from a root type down to a current shared collection (which can be obtained using
/// `ytext_event_target` function). It can consist of either integer indexes (used by sequence
/// components) of *char keys (used by map components). `len` output parameter is used to provide
/// information about length of the path.
///
/// Path returned this way should be eventually released using `ypath_destroy`.
#[no_mangle]
pub unsafe extern "C" fn ytext_event_path(
    e: *const YTextEvent,
    len: *mut u32,
) -> *mut YPathSegment {
    assert!(!e.is_null());
    let e = &*e;
    let path: Vec<_> = e.path().into_iter().map(YPathSegment::from).collect();
    let out = path.into_boxed_slice();
    *len = out.len() as u32;
    Box::into_raw(out) as *mut _
}

/// Returns a path from a root type down to a current shared collection (which can be obtained using
/// `ymap_event_target` function). It can consist of either integer indexes (used by sequence
/// components) of *char keys (used by map components). `len` output parameter is used to provide
/// information about length of the path.
///
/// Path returned this way should be eventually released using `ypath_destroy`.
#[no_mangle]
pub unsafe extern "C" fn ymap_event_path(e: *const YMapEvent, len: *mut u32) -> *mut YPathSegment {
    assert!(!e.is_null());
    let e = &*e;
    let path: Vec<_> = e.path().into_iter().map(YPathSegment::from).collect();
    let out = path.into_boxed_slice();
    *len = out.len() as u32;
    Box::into_raw(out) as *mut _
}

/// Returns a path from a root type down to a current shared collection (which can be obtained using
/// `yxmlelem_event_path` function). It can consist of either integer indexes (used by sequence
/// components) of *char keys (used by map components). `len` output parameter is used to provide
/// information about length of the path.
///
/// Path returned this way should be eventually released using `ypath_destroy`.
#[no_mangle]
pub unsafe extern "C" fn yxmlelem_event_path(
    e: *const YXmlEvent,
    len: *mut u32,
) -> *mut YPathSegment {
    assert!(!e.is_null());
    let e = &*e;
    let path: Vec<_> = e.path().into_iter().map(YPathSegment::from).collect();
    let out = path.into_boxed_slice();
    *len = out.len() as u32;
    Box::into_raw(out) as *mut _
}

/// Returns a path from a root type down to a current shared collection (which can be obtained using
/// `yxmltext_event_path` function). It can consist of either integer indexes (used by sequence
/// components) of *char keys (used by map components). `len` output parameter is used to provide
/// information about length of the path.
///
/// Path returned this way should be eventually released using `ypath_destroy`.
#[no_mangle]
pub unsafe extern "C" fn yxmltext_event_path(
    e: *const YXmlTextEvent,
    len: *mut u32,
) -> *mut YPathSegment {
    assert!(!e.is_null());
    let e = &*e;
    let path: Vec<_> = e.path().into_iter().map(YPathSegment::from).collect();
    let out = path.into_boxed_slice();
    *len = out.len() as u32;
    Box::into_raw(out) as *mut _
}

/// Returns a path from a root type down to a current shared collection (which can be obtained using
/// `yarray_event_target` function). It can consist of either integer indexes (used by sequence
/// components) of *char keys (used by map components). `len` output parameter is used to provide
/// information about length of the path.
///
/// Path returned this way should be eventually released using `ypath_destroy`.
#[no_mangle]
pub unsafe extern "C" fn yarray_event_path(
    e: *const YArrayEvent,
    len: *mut u32,
) -> *mut YPathSegment {
    assert!(!e.is_null());
    let e = &*e;
    let path: Vec<_> = e.path().into_iter().map(YPathSegment::from).collect();
    let out = path.into_boxed_slice();
    *len = out.len() as u32;
    Box::into_raw(out) as *mut _
}

/// Releases allocated memory used by objects returned from path accessor functions of shared type
/// events.
#[no_mangle]
pub unsafe extern "C" fn ypath_destroy(path: *mut YPathSegment, len: u32) {
    if !path.is_null() {
        drop(Vec::from_raw_parts(path, len as usize, len as usize));
    }
}

/// Returns a sequence of changes produced by sequence component of shared collections (such as
/// `YText`, `YXmlText` and XML nodes added to `YXmlElement`). `len` output parameter is used to
/// provide information about number of changes produced.
///
/// Delta returned from this function should eventually be released using `yevent_delta_destroy`
/// function.
#[no_mangle]
pub unsafe extern "C" fn ytext_event_delta(e: *const YTextEvent, len: *mut u32) -> *mut YDelta {
    assert!(!e.is_null());
    let e = &*e;
    let delta: Vec<_> = e.delta(e.txn()).into_iter().map(YDelta::from).collect();

    let out = delta.into_boxed_slice();
    *len = out.len() as u32;
    Box::into_raw(out) as *mut _
}

/// Returns a sequence of changes produced by sequence component of shared collections (such as
/// `YText`, `YXmlText` and XML nodes added to `YXmlElement`). `len` output parameter is used to
/// provide information about number of changes produced.
///
/// Delta returned from this function should eventually be released using `yevent_delta_destroy`
/// function.
#[no_mangle]
pub unsafe extern "C" fn yxmltext_event_delta(
    e: *const YXmlTextEvent,
    len: *mut u32,
) -> *mut YDelta {
    assert!(!e.is_null());
    let e = &*e;
    let delta: Vec<_> = e.delta(e.txn()).into_iter().map(YDelta::from).collect();

    let out = delta.into_boxed_slice();
    *len = out.len() as u32;
    Box::into_raw(out) as *mut _
}

/// Returns a sequence of changes produced by sequence component of shared collections (such as
/// `YText`, `YXmlText` and XML nodes added to `YXmlElement`). `len` output parameter is used to
/// provide information about number of changes produced.
///
/// Delta returned from this function should eventually be released using `yevent_delta_destroy`
/// function.
#[no_mangle]
pub unsafe extern "C" fn yarray_event_delta(
    e: *const YArrayEvent,
    len: *mut u32,
) -> *mut YEventChange {
    assert!(!e.is_null());
    let e = &*e;
    let delta: Vec<_> = e
        .delta(e.txn())
        .into_iter()
        .map(YEventChange::from)
        .collect();

    let out = delta.into_boxed_slice();
    *len = out.len() as u32;
    Box::into_raw(out) as *mut _
}

/// Returns a sequence of changes produced by sequence component of shared collections (such as
/// `YText`, `YXmlText` and XML nodes added to `YXmlElement`). `len` output parameter is used to
/// provide information about number of changes produced.
///
/// Delta returned from this function should eventually be released using `yevent_delta_destroy`
/// function.
#[no_mangle]
pub unsafe extern "C" fn yxmlelem_event_delta(
    e: *const YXmlEvent,
    len: *mut u32,
) -> *mut YEventChange {
    assert!(!e.is_null());
    let e = &*e;
    let delta: Vec<_> = e
        .delta(e.txn())
        .into_iter()
        .map(YEventChange::from)
        .collect();

    let out = delta.into_boxed_slice();
    *len = out.len() as u32;
    Box::into_raw(out) as *mut _
}

/// Releases memory allocated by the object returned from `yevent_delta` function.
#[no_mangle]
pub unsafe extern "C" fn ytext_delta_destroy(delta: *mut YDelta, len: u32) {
    if !delta.is_null() {
        let delta = Vec::from_raw_parts(delta, len as usize, len as usize);
        drop(delta);
    }
}

/// Releases memory allocated by the object returned from `yevent_delta` function.
#[no_mangle]
pub unsafe extern "C" fn yevent_delta_destroy(delta: *mut YEventChange, len: u32) {
    if !delta.is_null() {
        let delta = Vec::from_raw_parts(delta, len as usize, len as usize);
        drop(delta);
    }
}

/// Returns a sequence of changes produced by map component of shared collections (such as
/// `YMap` and `YXmlText`/`YXmlElement` attribute changes). `len` output parameter is used to
/// provide information about number of changes produced.
///
/// Delta returned from this function should eventually be released using `yevent_keys_destroy`
/// function.
#[no_mangle]
pub unsafe extern "C" fn ymap_event_keys(
    e: *const YMapEvent,
    len: *mut u32,
) -> *mut YEventKeyChange {
    assert!(!e.is_null());
    let e = &*e;
    let delta: Vec<_> = e
        .keys(e.txn())
        .into_iter()
        .map(|(k, v)| YEventKeyChange::new(k.as_ref(), v))
        .collect();

    let out = delta.into_boxed_slice();
    *len = out.len() as u32;
    Box::into_raw(out) as *mut _
}

/// Returns a sequence of changes produced by map component of shared collections.
/// `len` output parameter is used to provide information about number of changes produced.
///
/// Delta returned from this function should eventually be released using `yevent_keys_destroy`
/// function.
#[no_mangle]
pub unsafe extern "C" fn yxmlelem_event_keys(
    e: *const YXmlEvent,
    len: *mut u32,
) -> *mut YEventKeyChange {
    assert!(!e.is_null());
    let e = &*e;
    let delta: Vec<_> = e
        .keys(e.txn())
        .into_iter()
        .map(|(k, v)| YEventKeyChange::new(k.as_ref(), v))
        .collect();

    let out = delta.into_boxed_slice();
    *len = out.len() as u32;
    Box::into_raw(out) as *mut _
}

/// Returns a sequence of changes produced by map component of shared collections.
/// `len` output parameter is used to provide information about number of changes produced.
///
/// Delta returned from this function should eventually be released using `yevent_keys_destroy`
/// function.
#[no_mangle]
pub unsafe extern "C" fn yxmltext_event_keys(
    e: *const YXmlTextEvent,
    len: *mut u32,
) -> *mut YEventKeyChange {
    assert!(!e.is_null());
    let e = &*e;
    let delta: Vec<_> = e
        .keys(e.txn())
        .into_iter()
        .map(|(k, v)| YEventKeyChange::new(k.as_ref(), v))
        .collect();

    let out = delta.into_boxed_slice();
    *len = out.len() as u32;
    Box::into_raw(out) as *mut _
}

/// Releases memory allocated by the object returned from `yxml_event_keys` and `ymap_event_keys`
/// functions.
#[no_mangle]
pub unsafe extern "C" fn yevent_keys_destroy(keys: *mut YEventKeyChange, len: u32) {
    if !keys.is_null() {
        drop(Vec::from_raw_parts(keys, len as usize, len as usize));
    }
}

pub type YUndoManager = yrs::undo::UndoManager<AtomicPtr<c_void>>;

#[repr(C)]
pub struct YUndoManagerOptions {
    pub capture_timeout_millis: i32,
}

// TODO [LSViana] Maybe rename this to `yundo_manager_new_with_options` to match `ydoc_new_with_options`?
#[no_mangle]
pub unsafe extern "C" fn yundo_manager(
    doc: *const Doc,
    ytype: *const Branch,
    options: *const YUndoManagerOptions,
) -> *mut YUndoManager {
    let doc = doc.as_ref().unwrap();
    let branch = ytype.as_ref().unwrap();

    let mut o = yrs::undo::Options::default();
    if let Some(options) = options.as_ref() {
        if options.capture_timeout_millis >= 0 {
            o.capture_timeout_millis = options.capture_timeout_millis as u64;
        }
    };
    let boxed = Box::new(yrs::undo::UndoManager::with_options(
        doc,
        &BranchPtr::from(branch),
        o,
    ));
    Box::into_raw(boxed)
}

#[no_mangle]
pub unsafe extern "C" fn yundo_manager_destroy(mgr: *mut YUndoManager) {
    drop(Box::from_raw(mgr));
}

#[no_mangle]
pub unsafe extern "C" fn yundo_manager_add_origin(
    mgr: *mut YUndoManager,
    origin_len: u32,
    origin: *const c_char,
) {
    let mgr = mgr.as_mut().unwrap();
    let bytes = std::slice::from_raw_parts(origin as *const u8, origin_len as usize);
    mgr.include_origin(Origin::from(bytes));
}

#[no_mangle]
pub unsafe extern "C" fn yundo_manager_remove_origin(
    mgr: *mut YUndoManager,
    origin_len: u32,
    origin: *const c_char,
) {
    let mgr = mgr.as_mut().unwrap();
    let bytes = std::slice::from_raw_parts(origin as *const u8, origin_len as usize);
    mgr.exclude_origin(Origin::from(bytes));
}

#[no_mangle]
pub unsafe extern "C" fn yundo_manager_add_scope(mgr: *mut YUndoManager, ytype: *const Branch) {
    let mgr = mgr.as_mut().unwrap();
    let branch = ytype.as_ref().unwrap();
    mgr.expand_scope(&BranchPtr::from(branch));
}

#[no_mangle]
pub unsafe extern "C" fn yundo_manager_clear(mgr: *mut YUndoManager) -> u8 {
    let mgr = mgr.as_mut().unwrap();
    match mgr.clear() {
        Ok(_) => Y_TRUE,
        Err(_) => Y_FALSE,
    }
}

#[no_mangle]
pub unsafe extern "C" fn yundo_manager_stop(mgr: *mut YUndoManager) {
    let mgr = mgr.as_mut().unwrap();
    mgr.reset();
}

#[no_mangle]
pub unsafe extern "C" fn yundo_manager_undo(mgr: *mut YUndoManager) -> u8 {
    let mgr = mgr.as_mut().unwrap();

    match mgr.undo() {
        Ok(true) => Y_TRUE,
        Ok(false) => Y_FALSE,
        Err(_) => Y_FALSE,
    }
}

#[no_mangle]
pub unsafe extern "C" fn yundo_manager_redo(mgr: *mut YUndoManager) -> u8 {
    let mgr = mgr.as_mut().unwrap();
    match mgr.redo() {
        Ok(true) => Y_TRUE,
        Ok(false) => Y_FALSE,
        Err(_) => Y_FALSE,
    }
}

#[no_mangle]
pub unsafe extern "C" fn yundo_manager_can_undo(mgr: *mut YUndoManager) -> u8 {
    let mgr = mgr.as_mut().unwrap();
    if mgr.can_undo() {
        Y_TRUE
    } else {
        Y_FALSE
    }
}

#[no_mangle]
pub unsafe extern "C" fn yundo_manager_can_redo(mgr: *mut YUndoManager) -> u8 {
    let mgr = mgr.as_mut().unwrap();
    if mgr.can_redo() {
        Y_TRUE
    } else {
        Y_FALSE
    }
}

#[no_mangle]
pub unsafe extern "C" fn yundo_manager_observe_added(
    mgr: *mut YUndoManager,
    state: *mut c_void,
    cb: extern "C" fn(*mut c_void, *const YUndoEvent),
) -> *mut Subscription {
    let mgr = mgr.as_mut().unwrap();
    let subscription = mgr.observe_item_added(move |_, e| {
        let meta_ptr = {
            let event = YUndoEvent::new(e);
            cb(state, &event as *const YUndoEvent);
            event.meta
        };
        e.meta().store(meta_ptr, Ordering::Release);
    });
    Box::into_raw(Box::new(subscription))
}

#[no_mangle]
pub unsafe extern "C" fn yundo_manager_observe_popped(
    mgr: *mut YUndoManager,
    state: *mut c_void,
    cb: extern "C" fn(*mut c_void, *const YUndoEvent),
) -> *mut Subscription {
    let mgr = mgr.as_mut().unwrap();
    let subscription = mgr
        .observe_item_popped(move |_, e| {
            let meta_ptr = {
                let event = YUndoEvent::new(e);
                cb(state, &event as *const YUndoEvent);
                event.meta
            };
            e.meta().store(meta_ptr, Ordering::Release);
        })
        .into();
    Box::into_raw(Box::new(subscription))
}

pub const Y_KIND_UNDO: c_char = 0;
pub const Y_KIND_REDO: c_char = 1;

/// Event type related to `UndoManager` observer operations, such as `yundo_manager_observe_popped`
/// and `yundo_manager_observe_added`. It contains various informations about the context in which
/// undo/redo operations are executed.
#[repr(C)]
pub struct YUndoEvent {
    /// Informs if current event is related to executed undo (`Y_KIND_UNDO`) or redo (`Y_KIND_REDO`)
    /// operation.
    pub kind: c_char,
    /// Origin assigned to a transaction, in context of which this event is being executed.
    /// Transaction origin is specified via `ydoc_write_transaction(doc, origin_len, origin)`.
    pub origin: *const c_char,
    /// Length of an `origin` field assigned to a transaction, in context of which this event is
    /// being executed.
    /// Transaction origin is specified via `ydoc_write_transaction(doc, origin_len, origin)`.
    pub origin_len: u32,
    /// Pointer to a custom metadata object that can be passed between
    /// `yundo_manager_observe_popped` and `yundo_manager_observe_added`. It's useful for passing
    /// around custom user data ie. cursor position, that needs to be remembered and restored as
    /// part of undo/redo operations.
    ///
    /// This field always starts with no value (`NULL`) assigned to it and can be set/unset in
    /// corresponding callback calls. In such cases it's up to a programmer to handle allocation
    /// and deallocation of memory that this pointer will point to. Not releasing it properly may
    /// lead to memory leaks.
    pub meta: *mut c_void,
}

impl YUndoEvent {
    unsafe fn new(e: &yrs::undo::Event<AtomicPtr<c_void>>) -> Self {
        let (origin, origin_len) = if let Some(origin) = e.origin() {
            let bytes = origin.as_ref();
            let origin_len = bytes.len() as u32;
            let origin = bytes.as_ptr() as *const c_char;
            (origin, origin_len)
        } else {
            (null(), 0)
        };
        YUndoEvent {
            kind: match e.kind() {
                EventKind::Undo => Y_KIND_UNDO,
                EventKind::Redo => Y_KIND_REDO,
            },
            origin,
            origin_len,
            meta: e.meta().load(Ordering::Acquire),
        }
    }
}

/// Returns a value informing what kind of Yrs shared collection given `branch` represents.
/// Returns either 0 when `branch` is null or one of values: `Y_ARRAY`, `Y_TEXT`, `Y_MAP`,
/// `Y_XML_ELEM`, `Y_XML_TEXT`.
#[no_mangle]
pub unsafe extern "C" fn ytype_kind(branch: *const Branch) -> i8 {
    if let Some(branch) = branch.as_ref() {
        match branch.type_ref() {
            TypeRef::Array => Y_ARRAY,
            TypeRef::Map => Y_MAP,
            TypeRef::Text => Y_TEXT,
            TypeRef::XmlElement(_) => Y_XML_ELEM,
            TypeRef::XmlText => Y_XML_TEXT,
            TypeRef::XmlFragment => Y_XML_FRAG,
            TypeRef::SubDoc => Y_DOC,
            TypeRef::WeakLink(_) => Y_WEAK_LINK,
            TypeRef::XmlHook => 0,
            TypeRef::Undefined => 0,
        }
    } else {
        0
    }
}

/// Tag used to identify `YPathSegment` storing a *char parameter.
pub const Y_EVENT_PATH_KEY: c_char = 1;

/// Tag used to identify `YPathSegment` storing an int parameter.
pub const Y_EVENT_PATH_INDEX: c_char = 2;

/// A single segment of a path returned from `yevent_path` function. It can be one of two cases,
/// recognized by it's `tag` field:
///
/// 1. `Y_EVENT_PATH_KEY` means that segment value can be accessed by `segment.value.key` and is
/// referring to a string key used by map component (eg. `YMap` entry).
/// 2. `Y_EVENT_PATH_INDEX` means that segment value can be accessed by `segment.value.index` and is
/// referring to an int index used by sequence component (eg. `YArray` item or `YXmlElement` child).
#[repr(C)]
pub struct YPathSegment {
    /// Tag used to identify which case current segment is referring to:
    ///
    /// 1. `Y_EVENT_PATH_KEY` means that segment value can be accessed by `segment.value.key` and is
    /// referring to a string key used by map component (eg. `YMap` entry).
    /// 2. `Y_EVENT_PATH_INDEX` means that segment value can be accessed by `segment.value.index`
    /// and is referring to an int index used by sequence component (eg. `YArray` item or
    /// `YXmlElement` child).
    pub tag: c_char,

    /// Union field containing either `key` or `index`. A particular case can be recognized by using
    /// segment's `tag` field.
    pub value: YPathSegmentCase,
}

impl From<PathSegment> for YPathSegment {
    fn from(ps: PathSegment) -> Self {
        match ps {
            PathSegment::Key(key) => {
                let key = CString::new(key.as_ref()).unwrap().into_raw() as *const _;
                YPathSegment {
                    tag: Y_EVENT_PATH_KEY,
                    value: YPathSegmentCase { key },
                }
            }
            PathSegment::Index(index) => YPathSegment {
                tag: Y_EVENT_PATH_INDEX,
                value: YPathSegmentCase {
                    index: index as u32,
                },
            },
        }
    }
}

impl Drop for YPathSegment {
    fn drop(&mut self) {
        if self.tag == Y_EVENT_PATH_KEY {
            unsafe {
                ystring_destroy(self.value.key as *mut _);
            }
        }
    }
}

#[repr(C)]
pub union YPathSegmentCase {
    pub key: *const c_char,
    pub index: u32,
}

/// Tag used to identify `YEventChange` (see: `yevent_delta` function) case, when a new element
/// has been added to an observed collection.
pub const Y_EVENT_CHANGE_ADD: c_char = 1;

/// Tag used to identify `YEventChange` (see: `yevent_delta` function) case, when an existing
/// element has been removed from an observed collection.
pub const Y_EVENT_CHANGE_DELETE: c_char = 2;

/// Tag used to identify `YEventChange` (see: `yevent_delta` function) case, when no changes have
/// been detected for a particular range of observed collection.
pub const Y_EVENT_CHANGE_RETAIN: c_char = 3;

/// A data type representing a single change detected over an observed shared collection. A type
/// of change can be detected using a `tag` field:
///
/// 1. `Y_EVENT_CHANGE_ADD` marks a new elements added to a collection. In this case `values` field
/// contains a pointer to a list of newly inserted values, while `len` field informs about their
/// count.
/// 2. `Y_EVENT_CHANGE_DELETE` marks an existing elements removed from the collection. In this case
/// `len` field informs about number of removed elements.
/// 3. `Y_EVENT_CHANGE_RETAIN` marks a number of elements that have not been changed, counted from
/// the previous element. `len` field informs about number of retained elements.
///
/// A list of changes returned by `yarray_event_delta`/`yxml_event_delta` enables to locate a
/// position of all changes within an observed collection by using a combination of added/deleted
/// change structs separated by retained changes (marking eg. number of elements that can be safely
/// skipped, since they remained unchanged).
#[repr(C)]
pub struct YEventChange {
    /// Tag field used to identify particular type of change made:
    ///
    /// 1. `Y_EVENT_CHANGE_ADD` marks a new elements added to a collection. In this case `values`
    /// field contains a pointer to a list of newly inserted values, while `len` field informs about
    /// their count.
    /// 2. `Y_EVENT_CHANGE_DELETE` marks an existing elements removed from the collection. In this
    /// case `len` field informs about number of removed elements.
    /// 3. `Y_EVENT_CHANGE_RETAIN` marks a number of elements that have not been changed, counted
    /// from the previous element. `len` field informs about number of retained elements.
    pub tag: c_char,

    /// Number of element affected by current type of a change. It can refer to a number of
    /// inserted `values`, number of deleted element or a number of retained (unchanged) values.  
    pub len: u32,

    /// Used in case when current change is of `Y_EVENT_CHANGE_ADD` type. Contains a list (of
    /// length stored in `len` field) of newly inserted values.
    pub values: *const YOutput,
}

impl<'a> From<&'a Change> for YEventChange {
    fn from(change: &'a Change) -> Self {
        match change {
            Change::Added(values) => {
                let out: Vec<_> = values
                    .into_iter()
                    .map(|v| YOutput::from(v.clone()))
                    .collect();
                let len = out.len() as u32;
                let out = out.into_boxed_slice();
                let values = Box::into_raw(out) as *mut _;

                YEventChange {
                    tag: Y_EVENT_CHANGE_ADD,
                    len,
                    values,
                }
            }
            Change::Removed(len) => YEventChange {
                tag: Y_EVENT_CHANGE_DELETE,
                len: *len as u32,
                values: null(),
            },
            Change::Retain(len) => YEventChange {
                tag: Y_EVENT_CHANGE_RETAIN,
                len: *len as u32,
                values: null(),
            },
        }
    }
}

impl Drop for YEventChange {
    fn drop(&mut self) {
        if self.tag == Y_EVENT_CHANGE_ADD {
            unsafe {
                let len = self.len as usize;
                let values = Vec::from_raw_parts(self.values as *mut YOutput, len, len);
                drop(values);
            }
        }
    }
}

/// A data type representing a single change detected over an observed `YText`/`YXmlText`. A type
/// of change can be detected using a `tag` field:
///
/// 1. `Y_EVENT_CHANGE_ADD` marks a new characters added to a collection. In this case `insert`
/// field contains a pointer to a list of newly inserted values, while `len` field informs about
/// their count. Additionally `attributes_len` nad `attributes` carry information about optional
/// formatting attributes applied to edited blocks.
/// 2. `Y_EVENT_CHANGE_DELETE` marks an existing elements removed from the collection. In this case
/// `len` field informs about number of removed elements.
/// 3. `Y_EVENT_CHANGE_RETAIN` marks a number of characters that have not been changed, counted from
/// the previous element. `len` field informs about number of retained elements. Additionally
/// `attributes_len` nad `attributes` carry information about optional formatting attributes applied
/// to edited blocks.
///
/// A list of changes returned by `ytext_event_delta`/`yxmltext_event_delta` enables to locate
/// a position of all changes within an observed collection by using a combination of added/deleted
/// change structs separated by retained changes (marking eg. number of elements that can be safely
/// skipped, since they remained unchanged).
#[repr(C)]
pub struct YDelta {
    /// Tag field used to identify particular type of change made:
    ///
    /// 1. `Y_EVENT_CHANGE_ADD` marks a new elements added to a collection. In this case `values`
    /// field contains a pointer to a list of newly inserted values, while `len` field informs about
    /// their count.
    /// 2. `Y_EVENT_CHANGE_DELETE` marks an existing elements removed from the collection. In this
    /// case `len` field informs about number of removed elements.
    /// 3. `Y_EVENT_CHANGE_RETAIN` marks a number of elements that have not been changed, counted
    /// from the previous element. `len` field informs about number of retained elements.
    pub tag: c_char,

    /// Number of element affected by current type of a change. It can refer to a number of
    /// inserted `values`, number of deleted element or a number of retained (unchanged) values.  
    pub len: u32,

    /// Used in case when current change is of `Y_EVENT_CHANGE_ADD` type. Contains a list (of
    /// length stored in `len` field) of newly inserted values.
    pub insert: *mut YOutput,

    /// A number of formatting attributes assigned to an edited area represented by this delta.
    pub attributes_len: u32,

    /// A nullable pointer to a list of formatting attributes assigned to an edited area represented
    /// by this delta.
    pub attributes: *mut YDeltaAttr,
}

impl YDelta {
    fn insert(value: &Value, attrs: &Option<Box<Attrs>>) -> Self {
        let insert = Box::into_raw(Box::new(YOutput::from(value.clone())));
        let (attributes_len, attributes) = if let Some(attrs) = attrs {
            let len = attrs.len() as u32;
            let attrs: Vec<_> = attrs.iter().map(|(k, v)| YDeltaAttr::new(k, v)).collect();
            let attrs = Box::into_raw(attrs.into_boxed_slice()) as *mut _;
            (len, attrs)
        } else {
            (0, null_mut())
        };

        YDelta {
            tag: Y_EVENT_CHANGE_ADD,
            len: 1,
            insert,
            attributes_len,
            attributes,
        }
    }

    fn retain(len: u32, attrs: &Option<Box<Attrs>>) -> Self {
        let (attributes_len, attributes) = if let Some(attrs) = attrs {
            let len = attrs.len() as u32;
            let attrs: Vec<_> = attrs.iter().map(|(k, v)| YDeltaAttr::new(k, v)).collect();
            let attrs = Box::into_raw(attrs.into_boxed_slice()) as *mut _;
            (len, attrs)
        } else {
            (0, null_mut())
        };
        YDelta {
            tag: Y_EVENT_CHANGE_RETAIN,
            len: len as u32,
            insert: null_mut(),
            attributes_len,
            attributes,
        }
    }

    fn delete(len: u32) -> Self {
        YDelta {
            tag: Y_EVENT_CHANGE_DELETE,
            len: len as u32,
            insert: null_mut(),
            attributes_len: 0,
            attributes: null_mut(),
        }
    }
}

impl<'a> From<&'a Delta> for YDelta {
    fn from(d: &Delta) -> Self {
        match d {
            Delta::Inserted(value, attrs) => YDelta::insert(value, attrs),
            Delta::Retain(len, attrs) => YDelta::retain(*len, attrs),
            Delta::Deleted(len) => YDelta::delete(*len),
        }
    }
}

impl Drop for YDelta {
    fn drop(&mut self) {
        unsafe {
            if !self.attributes.is_null() {
                let len = self.attributes_len as usize;
                drop(Vec::from_raw_parts(self.attributes, len, len));
            }
            if !self.insert.is_null() {
                drop(Box::from_raw(self.insert));
            }
        }
    }
}

/// A single instance of formatting attribute stored as part of `YDelta` instance.
#[repr(C)]
pub struct YDeltaAttr {
    /// A null-terminated UTF-8 encoded string containing a unique formatting attribute name.
    pub key: *const c_char,
    /// A value assigned to a formatting attribute.
    pub value: YOutput,
}

impl YDeltaAttr {
    fn new(k: &Arc<str>, v: &Any) -> Self {
        let key = CString::new(k.as_ref()).unwrap().into_raw() as *const _;
        let value = YOutput::from(v.clone());
        YDeltaAttr { key, value }
    }
}

impl Drop for YDeltaAttr {
    fn drop(&mut self) {
        unsafe { ystring_destroy(self.key as *mut _) }
    }
}

/// Tag used to identify `YEventKeyChange` (see: `yevent_keys` function) case, when a new entry has
/// been inserted into a map component of shared collection.
pub const Y_EVENT_KEY_CHANGE_ADD: c_char = 4;

/// Tag used to identify `YEventKeyChange` (see: `yevent_keys` function) case, when an existing
/// entry has been removed from a map component of shared collection.
pub const Y_EVENT_KEY_CHANGE_DELETE: c_char = 5;

/// Tag used to identify `YEventKeyChange` (see: `yevent_keys` function) case, when an existing
/// entry has been overridden with a new value within a map component of shared collection.
pub const Y_EVENT_KEY_CHANGE_UPDATE: c_char = 6;

/// A data type representing a single change made over a map component of shared collection types,
/// such as `YMap` entries or `YXmlText`/`YXmlElement` attributes. A `key` field provides a
/// corresponding unique key string of a changed entry, while `tag` field informs about specific
/// type of change being done:
///
/// 1. `Y_EVENT_KEY_CHANGE_ADD` used to identify a newly added entry. In this case an `old_value`
/// field is NULL, while `new_value` field contains an inserted value.
/// 1. `Y_EVENT_KEY_CHANGE_DELETE` used to identify an existing entry being removed. In this case
/// an `old_value` field contains the removed value.
/// 1. `Y_EVENT_KEY_CHANGE_UPDATE` used to identify an existing entry, which value has been changed.
/// In this case `old_value` field contains replaced value, while `new_value` contains a newly
/// inserted one.
#[repr(C)]
pub struct YEventKeyChange {
    /// A UTF8-encoded null-terminated string containing a key of a changed entry.
    pub key: *const c_char,
    /// Tag field informing about type of change current struct refers to:
    ///
    /// 1. `Y_EVENT_KEY_CHANGE_ADD` used to identify a newly added entry. In this case an
    /// `old_value` field is NULL, while `new_value` field contains an inserted value.
    /// 1. `Y_EVENT_KEY_CHANGE_DELETE` used to identify an existing entry being removed. In this
    /// case an `old_value` field contains the removed value.
    /// 1. `Y_EVENT_KEY_CHANGE_UPDATE` used to identify an existing entry, which value has been
    /// changed. In this case `old_value` field contains replaced value, while `new_value` contains
    /// a newly inserted one.
    pub tag: c_char,

    /// Contains a removed entry's value or replaced value of an updated entry.
    pub old_value: *const YOutput,

    /// Contains a value of newly inserted entry or an updated entry's new value.
    pub new_value: *const YOutput,
}

impl YEventKeyChange {
    fn new(key: &str, change: &EntryChange) -> Self {
        let key = CString::new(key).unwrap().into_raw() as *const _;
        match change {
            EntryChange::Inserted(new) => YEventKeyChange {
                key,
                tag: Y_EVENT_KEY_CHANGE_ADD,
                old_value: null(),
                new_value: Box::into_raw(Box::new(YOutput::from(new.clone()))),
            },
            EntryChange::Updated(old, new) => YEventKeyChange {
                key,
                tag: Y_EVENT_KEY_CHANGE_UPDATE,
                old_value: Box::into_raw(Box::new(YOutput::from(old.clone()))),
                new_value: Box::into_raw(Box::new(YOutput::from(new.clone()))),
            },
            EntryChange::Removed(old) => YEventKeyChange {
                key,
                tag: Y_EVENT_KEY_CHANGE_DELETE,
                old_value: Box::into_raw(Box::new(YOutput::from(old.clone()))),
                new_value: null(),
            },
        }
    }
}

impl Drop for YEventKeyChange {
    fn drop(&mut self) {
        unsafe {
            ystring_destroy(self.key as *mut _);
            youtput_destroy(self.old_value as *mut _);
            youtput_destroy(self.new_value as *mut _);
        }
    }
}

trait BranchPointable {
    fn into_raw_branch(self) -> *mut Branch;
    fn from_raw_branch(branch: *const Branch) -> Self;
}

impl<T> BranchPointable for T
where
    T: AsRef<Branch> + From<BranchPtr>,
{
    fn into_raw_branch(self) -> *mut Branch {
        let branch_ref = self.as_ref();
        branch_ref as *const Branch as *mut Branch
    }

    fn from_raw_branch(branch: *const Branch) -> Self {
        let b = unsafe { branch.as_ref().unwrap() };
        let branch_ref = BranchPtr::from(b);
        T::from(branch_ref)
    }
}

/// A sticky index is based on the Yjs model and is not affected by document changes.
/// E.g. If you place a sticky index before a certain character, it will always point to this character.
/// If you place a sticky index at the end of a type, it will always point to the end of the type.
///
/// A numeric position is often unsuited for user selections, because it does not change when content is inserted
/// before or after.
///
/// ```Insert(0, 'x')('a.bc') = 'xa.bc'``` Where `.` is the sticky index position.
///
/// Instances of `YStickyIndex` can be freed using `ysticky_index_destroy`.
#[repr(transparent)]
pub struct YStickyIndex(StickyIndex);

impl From<StickyIndex> for YStickyIndex {
    #[inline(always)]
    fn from(value: StickyIndex) -> Self {
        YStickyIndex(value)
    }
}

/// Releases resources allocated by `YStickyIndex` pointers.
#[no_mangle]
pub unsafe extern "C" fn ysticky_index_destroy(pos: *mut YStickyIndex) {
    drop(Box::from_raw(pos))
}

/// Returns association of current `YStickyIndex`.
/// If association is **after** the referenced inserted character, returned number will be >= 0.
/// If association is **before** the referenced inserted character, returned number will be < 0.
#[no_mangle]
pub unsafe extern "C" fn ysticky_index_assoc(pos: *const YStickyIndex) -> i8 {
    let pos = pos.as_ref().unwrap();
    match pos.0.assoc {
        Assoc::After => 0,
        Assoc::Before => -1,
    }
}

/// Retrieves a `YStickyIndex` corresponding to a given human-readable `index` pointing into
/// the shared y-type `branch`. Unlike standard indexes sticky one enables to track
/// the location inside of a shared y-types, even in the face of concurrent updates.
///
/// If association is >= 0, the resulting position will point to location **after** the referenced index.
/// If association is < 0, the resulting position will point to location **before** the referenced index.
#[no_mangle]
pub unsafe extern "C" fn ysticky_index_from_index(
    branch: *const Branch,
    txn: *mut Transaction,
    index: u32,
    assoc: i8,
) -> *mut YStickyIndex {
    assert!(!branch.is_null());
    assert!(!txn.is_null());

    let branch = BranchPtr::from_raw_branch(branch);
    let txn = txn.as_mut().unwrap();
    let index = index as u32;
    let assoc = if assoc >= 0 {
        Assoc::After
    } else {
        Assoc::Before
    };

    if let Some(txn) = txn.as_mut() {
        if let Some(pos) = StickyIndex::at(txn, branch, index, assoc) {
            Box::into_raw(Box::new(YStickyIndex(pos)))
        } else {
            null_mut()
        }
    } else {
        panic!("ysticky_index_from_index requires a read-write transaction");
    }
}

/// Serializes `YStickyIndex` into binary representation. `len` parameter is updated with byte
/// length of the generated binary. Returned binary can be free'd using `ybinary_destroy`.  
#[no_mangle]
pub unsafe extern "C" fn ysticky_index_encode(
    pos: *const YStickyIndex,
    len: *mut u32,
) -> *mut c_char {
    let pos = pos.as_ref().unwrap();
    let binary = pos.0.encode_v1().into_boxed_slice();
    *len = binary.len() as u32;
    Box::into_raw(binary) as *mut c_char
}

/// Deserializes `YStickyIndex` from the payload previously serialized using `ysticky_index_encode`.
#[no_mangle]
pub unsafe extern "C" fn ysticky_index_decode(
    binary: *const c_char,
    len: u32,
) -> *mut YStickyIndex {
    let slice = std::slice::from_raw_parts(binary as *const u8, len as usize);
    if let Ok(pos) = StickyIndex::decode_v1(slice) {
        Box::into_raw(Box::new(YStickyIndex(pos)))
    } else {
        null_mut()
    }
}

/// Given `YStickyIndex` and transaction reference, if computes a human-readable index in a
/// context of the referenced shared y-type.
///
/// `out_branch` is getting assigned with a corresponding shared y-type reference.
/// `out_index` will be used to store computed human-readable index.
#[no_mangle]
pub unsafe extern "C" fn ysticky_index_read(
    pos: *const YStickyIndex,
    txn: *const Transaction,
    out_branch: *mut *mut Branch,
    out_index: *mut u32,
) {
    let pos = pos.as_ref().unwrap();
    let txn = txn.as_ref().unwrap();

    if let Some(abs) = pos.0.get_offset(txn) {
        *out_branch = abs.branch.as_ref() as *const Branch as *mut Branch;
        *out_index = abs.index as u32;
    }
}

pub type Weak = LinkSource;

#[no_mangle]
pub unsafe extern "C" fn yweak_destroy(weak: *const Weak) {
    drop(Arc::from_raw(weak));
}

#[no_mangle]
pub unsafe extern "C" fn yweak_deref(
    map_link: *const Branch,
    txn: *const Transaction,
) -> *mut YOutput {
    assert!(!map_link.is_null());
    assert!(!txn.is_null());

    let txn = txn.as_ref().unwrap();
    let weak: WeakRef<MapRef> = WeakRef::from_raw_branch(map_link);
    if let Some(value) = weak.try_deref_value(txn) {
        Box::into_raw(Box::new(YOutput::from(value)))
    } else {
        null_mut()
    }
}

#[no_mangle]
pub unsafe extern "C" fn yweak_iter(
    array_link: *const Branch,
    txn: *const Transaction,
) -> *mut WeakIter {
    assert!(!array_link.is_null());
    assert!(!txn.is_null());

    let txn = txn.as_ref().unwrap();
    let weak: WeakRef<ArrayRef> = WeakRef::from_raw_branch(array_link);
    let iter: NativeUnquote<'static, Transaction> = std::mem::transmute(weak.unquote(txn));

    Box::into_raw(Box::new(WeakIter(iter)))
}

#[no_mangle]
pub unsafe extern "C" fn yweak_iter_destroy(iter: *mut WeakIter) {
    drop(Box::from_raw(iter))
}

#[no_mangle]
pub unsafe extern "C" fn yweak_iter_next(iter: *mut WeakIter) -> *mut YOutput {
    assert!(!iter.is_null());
    let iter = iter.as_mut().unwrap();

    if let Some(value) = iter.0.next() {
        Box::into_raw(Box::new(YOutput::from(value)))
    } else {
        null_mut()
    }
}

#[no_mangle]
pub unsafe extern "C" fn yweak_string(
    text_link: *const Branch,
    txn: *const Transaction,
) -> *mut c_char {
    assert!(!text_link.is_null());
    assert!(!txn.is_null());

    let txn = txn.as_ref().unwrap();
    let weak: WeakRef<TextRef> = WeakRef::from_raw_branch(text_link);

    let str = weak.get_string(txn);
    CString::new(str).unwrap().into_raw()
}

#[no_mangle]
pub unsafe extern "C" fn yweak_xml_string(
    xml_text_link: *const Branch,
    txn: *const Transaction,
) -> *mut c_char {
    assert!(!xml_text_link.is_null());
    assert!(!txn.is_null());

    let txn = txn.as_ref().unwrap();
    let weak: WeakRef<XmlTextRef> = WeakRef::from_raw_branch(xml_text_link);

    let str = weak.get_string(txn);
    CString::new(str).unwrap().into_raw()
}

/// Subscribes a given callback function `cb` to changes made by this `YText` instance. Callbacks
/// are triggered whenever a `ytransaction_commit` is called.
/// Returns a subscription ID which can be then used to unsubscribe this callback by using
/// `yunobserve` function.
#[no_mangle]
pub unsafe extern "C" fn yweak_observe(
    weak: *const Branch,
    state: *mut c_void,
    cb: extern "C" fn(*mut c_void, *const YWeakLinkEvent),
) -> *mut Subscription {
    assert!(!weak.is_null());

    let txt: WeakRef<BranchPtr> = WeakRef::from_raw_branch(weak);
    let subscription = txt.observe(move |txn, e| {
        let e = YWeakLinkEvent::new(e, txn);
        cb(state, &e as *const YWeakLinkEvent);
    });
    Box::into_raw(Box::new(subscription))
}

#[no_mangle]
pub unsafe extern "C" fn ymap_link(
    map: *const Branch,
    txn: *const Transaction,
    key: *const c_char,
) -> *const Weak {
    assert!(!map.is_null());
    assert!(!txn.is_null());

    let txn = txn.as_ref().unwrap();
    let map = MapRef::from_raw_branch(map);
    let key = CStr::from_ptr(key).to_str().unwrap();
    if let Some(weak) = map.link(txn, key) {
        let source = weak.source();
        Arc::into_raw(source.clone())
    } else {
        null()
    }
}

#[no_mangle]
pub unsafe extern "C" fn ytext_quote(
    text: *const Branch,
    txn: *mut Transaction,
    start_index: u32,
    end_index: u32,
    start_exclusive: i8,
    end_exclusive: i8,
) -> *const Weak {
    assert!(!text.is_null());
    assert!(!txn.is_null());

    let text = TextRef::from_raw_branch(text);
    let txn = txn.as_mut().unwrap();
    let txn = txn
        .as_mut()
        .expect("provided transaction was not writeable");

    let range = ExplicitRange {
        start_index,
        end_index,
        start_exclusive,
        end_exclusive,
    };
    if let Ok(weak) = text.quote(txn, range) {
        let source = weak.source();
        Arc::into_raw(source.clone())
    } else {
        null()
    }
}

#[no_mangle]
pub unsafe extern "C" fn yarray_quote(
    array: *const Branch,
    txn: *mut Transaction,
    start_index: u32,
    end_index: u32,
    start_exclusive: i8,
    end_exclusive: i8,
) -> *const Weak {
    assert!(!array.is_null());
    assert!(!txn.is_null());

    let array = ArrayRef::from_raw_branch(array);
    let txn = txn.as_mut().unwrap();
    let txn = txn
        .as_mut()
        .expect("provided transaction was not writeable");

    let range = ExplicitRange {
        start_index,
        end_index,
        start_exclusive,
        end_exclusive,
    };
    if let Ok(weak) = array.quote(txn, range) {
        let source = weak.source();
        Arc::into_raw(source.clone())
    } else {
        null()
    }
}

struct ExplicitRange {
    start_index: u32,
    end_index: u32,
    start_exclusive: i8,
    end_exclusive: i8,
}

impl RangeBounds<u32> for ExplicitRange {
    fn start_bound(&self) -> Bound<&u32> {
        if self.start_exclusive == 0 {
            Bound::Included(&self.start_index)
        } else {
            Bound::Excluded(&self.start_index)
        }
    }

    fn end_bound(&self) -> Bound<&u32> {
        if self.end_exclusive == 0 {
            Bound::Included(&self.end_index)
        } else {
            Bound::Excluded(&self.end_index)
        }
    }
}

/// A structure representing logical identifier of a specific shared collection.
/// Can be obtained by `ybranch_id` executed over alive `Branch`.
///
/// Use `ybranch_get` to resolve a `Branch` pointer from this branch ID.
///
/// This structure doesn't need to be destroyed. It's internal pointer reference is valid through
/// a lifetime of a document, which collection this branch ID has been created from.
#[repr(C)]
pub struct YBranchId {
    /// If positive: Client ID of a creator of a nested shared type, this identifier points to.
    /// If negative: a negated Length of a root-level shared collection name.
    pub client_or_len: i64,
    pub variant: YBranchIdVariant,
}

#[repr(C)]
pub union YBranchIdVariant {
    /// Clock number timestamp when the creator of a nested shared type created it.
    pub clock: u32,
    /// Pointer to UTF-8 encoded string representing root-level type name. This pointer is valid
    /// as long as document - in which scope it was created in - was not destroyed. As usually
    /// root-level type names are statically allocated strings, it can also be supplied manually
    /// from the outside.
    pub name: *const u8,
}

/// Returns a logical identifier for a given shared collection. That collection must be alive at
/// the moment of function call.
#[no_mangle]
pub unsafe extern "C" fn ybranch_id(branch: *const Branch) -> YBranchId {
    let branch = branch.as_ref().unwrap();
    match branch.id() {
        BranchID::Nested(id) => YBranchId {
            client_or_len: id.client as i64,
            variant: YBranchIdVariant { clock: id.clock },
        },
        BranchID::Root(name) => {
            let len = -(name.len() as i64);
            YBranchId {
                client_or_len: len,
                variant: YBranchIdVariant {
                    name: name.as_ptr(),
                },
            }
        }
    }
}

/// Given a logical identifier, returns a physical pointer to a shared collection.
/// Returns null if collection was not found - either because it was not defined or not synchronized
/// yet.
/// Returned pointer may still point to deleted collection. In such case a subsequent `ybranch_alive`
/// function call is required.
#[no_mangle]
pub unsafe extern "C" fn ybranch_get(
    branch_id: *const YBranchId,
    txn: *mut Transaction,
) -> *mut Branch {
    let txn = txn.as_ref().unwrap();
    let branch_id = branch_id.as_ref().unwrap();
    let client_or_len = branch_id.client_or_len;
    let ptr = if client_or_len >= 0 {
        BranchID::get_nested(txn, &ID::new(client_or_len as u64, branch_id.variant.clock))
    } else {
        let name = std::slice::from_raw_parts(branch_id.variant.name, (-client_or_len) as usize);
        BranchID::get_root(txn, std::str::from_utf8_unchecked(name))
    };

    match ptr {
        None => null_mut(),
        Some(branch_ptr) => branch_ptr.into_raw_branch(),
    }
}

/// Check if current branch is still alive (returns `Y_TRUE`, otherwise `Y_FALSE`).
/// If it was deleted, this branch pointer is no longer a valid pointer and cannot be used to
/// execute any functions using it.
#[no_mangle]
pub unsafe extern "C" fn ybranch_alive(branch: *mut Branch) -> u8 {
    if branch.is_null() {
        Y_FALSE
    } else {
        let branch = BranchPtr::from_raw_branch(branch);
        if branch.is_deleted() {
            Y_FALSE
        } else {
            Y_TRUE
        }
    }
}