autosar-data 0.18.0

read, write and modify Autosar arxml data
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
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
use std::cmp::Ordering;
use std::hash::Hash;
use std::str::FromStr;

use super::*;

impl Element {
    /// Get the parent element of the current element
    ///
    /// Returns None if the current element is the root, or if it has been deleted from the element hierarchy
    ///
    /// # Example
    ///
    /// ```
    /// # use autosar_data::*;
    /// # fn main() -> Result<(), AutosarDataError> {
    /// # let model = AutosarModel::new();
    /// # let file = model.create_file("test", AutosarVersion::Autosar_00050).unwrap();
    /// # let element = model.root_element().create_sub_element(ElementName::ArPackages).and_then(|pkgs| pkgs.create_named_sub_element(ElementName::ArPackage, "name")).unwrap();
    /// if let Some(parent) = element.parent()? {
    ///     // ...
    /// }
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    ///  - [`AutosarDataError::ItemDeleted`]: The current element is in the deleted state and will be freed once the last reference is dropped
    pub fn parent(&self) -> Result<Option<Element>, AutosarDataError> {
        self.0.read().parent()
    }

    /// Get the next named parent (or grandparent, etc) of the current element
    ///
    /// This function steps through the hierarchy until an identifiable element is found.
    /// It never returns the current element, even if the current element is identifiable.
    ///
    /// The function returns a suitable element if one is found, or None if the root is reached.
    ///
    /// # Example
    ///
    /// ```
    /// # use autosar_data::*;
    /// # fn main() -> Result<(), AutosarDataError> {
    /// # let model = AutosarModel::new();
    /// # let file = model.create_file("test", AutosarVersion::Autosar_00050)?;
    /// # let el_arpackage = model.root_element().create_sub_element(ElementName::ArPackages)?.create_named_sub_element(ElementName::ArPackage, "Pkg")?;
    /// let el_elements = el_arpackage.create_sub_element(ElementName::Elements)?;
    /// let el_system = el_elements.create_named_sub_element(ElementName::System, "Sys")?;
    /// let named_parent = el_elements.named_parent()?.unwrap();
    /// let named_parent2 = el_system.named_parent()?.unwrap();
    /// assert_eq!(named_parent, el_arpackage);
    /// assert_eq!(named_parent2, el_arpackage);
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    ///  - [`AutosarDataError::ItemDeleted`]: The current element is in the deleted state and will be freed once the last reference is dropped
    pub fn named_parent(&self) -> Result<Option<Element>, AutosarDataError> {
        let mut cur_elem_opt = self.parent()?;
        while let Some(parent) = cur_elem_opt {
            if parent.is_identifiable() {
                return Ok(Some(parent));
            }
            cur_elem_opt = parent.parent()?;
        }

        Ok(None)
    }

    pub(crate) fn set_parent(&self, new_parent: ElementOrModel) {
        self.0.write().set_parent(new_parent);
    }

    /// Get the [`ElementName`] of the element
    ///
    /// # Example
    ///
    /// ```
    /// # use autosar_data::*;
    /// # let model = AutosarModel::new();
    /// # let file = model.create_file("test", AutosarVersion::Autosar_00050).unwrap();
    /// let element = model.root_element();
    /// let element_name = element.element_name();
    /// assert_eq!(element_name, ElementName::Autosar);
    /// ```
    #[must_use]
    pub fn element_name(&self) -> ElementName {
        self.0.read().elemname
    }

    /// Get the [`ElementType`] of the element
    ///
    /// The `ElementType` is needed in order to call methods from the autosar-data-specification crate
    ///
    /// # Example
    ///
    /// ```
    /// # use autosar_data::*;
    /// # let model = AutosarModel::new();
    /// # let file = model.create_file("test", AutosarVersion::Autosar_00050).unwrap();
    /// # let element = model.root_element();
    /// let element_type = element.element_type();
    /// ```
    #[must_use]
    pub fn element_type(&self) -> ElementType {
        self.0.read().elemtype
    }

    /// Get the name of an identifiable element
    ///
    /// An identifiable element has a `<SHORT-NAME>` sub element and can be referenced using an autosar path.
    ///
    /// If the element is not identifiable, this function returns None
    ///
    /// # Example
    ///
    /// ```
    /// # use autosar_data::*;
    /// # let model = AutosarModel::new();
    /// # let file = model.create_file("test", AutosarVersion::Autosar_00050).unwrap();
    /// # let element = model.root_element().create_sub_element(ElementName::ArPackages).and_then(|pkgs| pkgs.create_named_sub_element(ElementName::ArPackage, "name")).unwrap();
    /// if let Some(item_name) = element.item_name() {
    ///     // ...
    /// }
    /// ```
    #[must_use]
    pub fn item_name(&self) -> Option<String> {
        self.0.read().item_name()
    }

    /// Set the item name of this element
    ///
    /// This operation will update all references pointing to the element or its sub-elements so that they remain valid.
    ///
    /// # Example
    ///
    /// ```
    /// # use autosar_data::*;
    /// # let model = AutosarModel::new();
    /// # let file = model.create_file("test", AutosarVersion::Autosar_00050).unwrap();
    /// # let element = model.root_element().create_sub_element(ElementName::ArPackages).and_then(|pkgs| pkgs.create_named_sub_element(ElementName::ArPackage, "name")).unwrap();
    /// element.set_item_name("NewName");
    /// ```
    ///
    /// # Note
    ///
    /// In order to rename an element *without* updating any references, do this instead:
    /// ```
    /// # use autosar_data::*;
    /// # let model = AutosarModel::new();
    /// # let file = model.create_file("test", AutosarVersion::Autosar_00050).unwrap();
    /// # let element = model.root_element().create_sub_element(ElementName::ArPackages).and_then(|pkgs| pkgs.create_named_sub_element(ElementName::ArPackage, "name")).unwrap();
    /// if let Some(short_name) = element.get_sub_element(ElementName::ShortName) {
    ///     short_name.set_character_data("the_new_name");
    /// }
    /// ```
    ///
    /// # Errors
    ///
    ///  - [`AutosarDataError::ItemDeleted`]: The current element is in the deleted state and will be freed once the last reference is dropped
    ///  - [`AutosarDataError::ParentElementLocked`]: a parent element was locked and did not become available after waiting briefly.
    ///    The operation was aborted to avoid a deadlock, but can be retried.
    ///  - [`AutosarDataError::ItemNameRequired`] this function was called for an element which is not identifiable
    ///
    pub fn set_item_name(&self, new_name: &str) -> Result<(), AutosarDataError> {
        // a new name is required
        if new_name.is_empty() {
            return Err(AutosarDataError::ItemNameRequired {
                element: self.element_name(),
            });
        }
        let model = self.model()?;
        let version = self.min_version()?;
        self.0.write().set_item_name(new_name, &model, version)
    }

    /// Returns true if the element is identifiable
    ///
    /// In order to be identifiable, the specification must require a SHORT-NAME
    /// sub-element and the SHORT-NAME must actually be present.
    ///
    /// # Example
    /// ```
    /// # use autosar_data::*;
    /// # let model = AutosarModel::new();
    /// # let file = model.create_file("test", AutosarVersion::Autosar_00050).unwrap();
    /// # let element = model.root_element();
    /// if element.is_identifiable() {
    ///     // ...
    /// }
    /// ```
    #[must_use]
    pub fn is_identifiable(&self) -> bool {
        self.0.read().is_identifiable()
    }

    /// Returns true if the element should contain a reference to another element
    ///
    /// The function does not check if the reference is valid
    ///
    /// # Example
    ///
    /// ```
    /// # use autosar_data::*;
    /// # let model = AutosarModel::new();
    /// # let file = model.create_file("test", AutosarVersion::Autosar_00050).unwrap();
    /// # let element = model.root_element().create_sub_element(ElementName::ArPackages).and_then(|pkgs| pkgs.create_named_sub_element(ElementName::ArPackage, "name")).unwrap();
    /// if element.is_reference() {
    ///     // ex: element.set_reference_target(...)
    /// }
    /// ```
    #[must_use]
    pub fn is_reference(&self) -> bool {
        self.elemtype().is_ref()
    }

    /// Get the Autosar path of an identifiable element
    ///
    /// # Example
    ///
    /// ```
    /// # use autosar_data::*;
    /// # fn main() -> Result<(), AutosarDataError> {
    /// # let model = AutosarModel::new();
    /// # let file = model.create_file("test", AutosarVersion::Autosar_00050).unwrap();
    /// # let element = model.root_element().create_sub_element(ElementName::ArPackages).and_then(|pkgs| pkgs.create_named_sub_element(ElementName::ArPackage, "name")).unwrap();
    /// let path = element.path()?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    ///  - [`AutosarDataError::ItemDeleted`]: Th ecurrent element is in the deleted state and will be freed once the last reference is dropped
    ///  - [`AutosarDataError::ParentElementLocked`]: a parent element was locked and did not become available after waiting briefly.
    ///    The operation was aborted to avoid a deadlock, but can be retried.
    ///  - [`AutosarDataError::ElementNotIdentifiable`]: The current element is not identifiable, so it has no Autosar path
    ///
    pub fn path(&self) -> Result<String, AutosarDataError> {
        self.0.read().path()
    }

    /// Get a reference to the [`AutosarModel`] containing the current element
    ///
    /// # Example
    ///
    /// ```
    /// # use autosar_data::*;
    /// # fn main() -> Result<(), AutosarDataError> {
    /// # let model = AutosarModel::new();
    /// # let file = model.create_file("test", AutosarVersion::Autosar_00050).unwrap();
    /// # let element = model.root_element().create_sub_element(ElementName::ArPackages).and_then(|pkgs| pkgs.create_named_sub_element(ElementName::ArPackage, "name")).unwrap();
    /// let file = element.model()?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    ///  - [`AutosarDataError::ItemDeleted`]: The current element is in the deleted state and will be freed once the last reference is dropped
    ///  - [`AutosarDataError::ParentElementLocked`]: a parent element was locked and did not become available after waiting briefly.
    ///    The operation was aborted to avoid a deadlock, but can be retried.
    ///
    pub fn model(&self) -> Result<AutosarModel, AutosarDataError> {
        let mut cur_elem = self.clone();
        loop {
            let parent = {
                let element = cur_elem
                    .0
                    .try_read_for(std::time::Duration::from_millis(10))
                    .ok_or(AutosarDataError::ParentElementLocked)?;
                match &element.parent {
                    ElementOrModel::Element(weak_parent) => {
                        weak_parent.upgrade().ok_or(AutosarDataError::ItemDeleted)?
                    }
                    ElementOrModel::Model(weak_arxmlfile) => {
                        return weak_arxmlfile.upgrade().ok_or(AutosarDataError::ItemDeleted)
                    }
                    ElementOrModel::None => return Err(AutosarDataError::ItemDeleted),
                }
            };
            cur_elem = parent;
        }
    }

    /// Get the [`ContentType`] of the current element
    ///
    /// # Example
    ///
    /// ```
    /// # use autosar_data::*;
    /// # let model = AutosarModel::new();
    /// # let file = model.create_file("test", AutosarVersion::Autosar_00050).unwrap();
    /// # let element = model.root_element();
    /// if element.content_type() == ContentType::CharacterData {
    ///     // ...
    /// }
    /// ```
    #[must_use]
    pub fn content_type(&self) -> ContentType {
        match self.elemtype().content_mode() {
            ContentMode::Sequence => ContentType::Elements,
            ContentMode::Choice => ContentType::Elements,
            ContentMode::Bag => ContentType::Elements,
            ContentMode::Characters => ContentType::CharacterData,
            ContentMode::Mixed => ContentType::Mixed,
        }
    }

    /// Create a sub element at a suitable insertion position
    ///
    /// The given `ElementName` must be allowed on a sub element in this element, taking into account any sub elements that may already exist.
    /// It is not possible to create named sub elements with this function; use `create_named_sub_element`() for that instead.
    ///
    /// # Example
    ///
    /// ```
    /// # use autosar_data::*;
    /// # fn main() -> Result<(), AutosarDataError> {
    /// # let model = AutosarModel::new();
    /// # let file = model.create_file("test", AutosarVersion::Autosar_00050).unwrap();
    /// let element = model.root_element().create_sub_element(ElementName::ArPackages)?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    ///  - [`AutosarDataError::ItemDeleted`]: The current element is in the deleted state and will be freed once the last reference is dropped
    ///  - [`AutosarDataError::ParentElementLocked`]: a parent element was locked and did not become available after waiting briefly.
    ///    The operation was aborted to avoid a deadlock, but can be retried.
    ///  - [`AutosarDataError::IncorrectContentType`]: A sub element may not be created in an element with content type `CharacterData`.
    ///  - [`AutosarDataError::ElementInsertionConflict`]: The requested sub element cannot be created because it conflicts with an existing sub element.
    ///  - [`AutosarDataError::InvalidSubElement`]: The `ElementName` is not a valid sub element according to the specification.
    ///  - [`AutosarDataError::ItemNameRequired`]: The sub element requires an item name, so you must use `create_named_sub_element`().
    ///  - [`AutosarDataError::NoFilesInModel`]: The operation cannot be completed because the model does not contain any files
    pub fn create_sub_element(&self, element_name: ElementName) -> Result<Element, AutosarDataError> {
        let version = self.min_version()?;
        self.0
            .try_write()
            .ok_or(AutosarDataError::ParentElementLocked)?
            .create_sub_element(self.downgrade(), element_name, version)
    }

    /// Create a sub element at the specified insertion position
    ///
    /// The given `ElementName` must be allowed on a sub element in this element, taking into account any sub elements that may already exist.
    /// It is not possible to create named sub elements with this function; use `create_named_sub_element_at`() for that instead.
    ///
    /// The specified insertion position will be compared to the range of valid insertion positions; if it falls outside that range then the function fails.
    ///
    /// # Example
    ///
    /// ```
    /// # use autosar_data::*;
    /// # fn main() -> Result<(), AutosarDataError> {
    /// # let model = AutosarModel::new();
    /// # let file = model.create_file("test", AutosarVersion::Autosar_00050).unwrap();
    /// let element = model.root_element().create_sub_element_at(ElementName::ArPackages, 0)?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    ///  - [`AutosarDataError::ItemDeleted`]: The current element is in the deleted state and will be freed once the last reference is dropped
    ///  - [`AutosarDataError::ParentElementLocked`]: a parent element was locked and did not become available after waiting briefly.
    ///    The operation was aborted to avoid a deadlock, but can be retried.
    ///  - [`AutosarDataError::IncorrectContentType`]: A sub element may not be created in an element with content type `CharacterData`.
    ///  - [`AutosarDataError::ElementInsertionConflict`]: The requested sub element cannot be created because it conflicts with an existing sub element.
    ///  - [`AutosarDataError::InvalidSubElement`]: The `ElementName` is not a valid sub element according to the specification.
    ///  - [`AutosarDataError::ItemNameRequired`]: The sub element requires an item name, so you must use `create_named_sub_element_at`().
    ///  - [`AutosarDataError::InvalidPosition`]: This sub element cannot be created at the requested position
    ///  - [`AutosarDataError::NoFilesInModel`]: The operation cannot be completed because the model does not contain any files
    pub fn create_sub_element_at(
        &self,
        element_name: ElementName,
        position: usize,
    ) -> Result<Element, AutosarDataError> {
        let version = self.min_version()?;
        self.0
            .write()
            .create_sub_element_at(self.downgrade(), element_name, position, version)
    }

    /// Create a named/identifiable sub element at a suitable insertion position
    ///
    /// The given `ElementName` must be allowed on a sub element in this element, taking into account any sub elements that may already exist.
    ///
    /// This method can only be used to create identifiable sub elements.
    ///
    /// # Example
    ///
    /// ```
    /// # use autosar_data::*;
    /// # fn main() -> Result<(), AutosarDataError> {
    /// # let model = AutosarModel::new();
    /// # let file = model.create_file("test", AutosarVersion::Autosar_00050).unwrap();
    /// let pkgs_element = model.root_element().create_sub_element(ElementName::ArPackages)?;
    /// let element = pkgs_element.create_named_sub_element(ElementName::ArPackage, "Package")?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    ///  - [`AutosarDataError::ItemDeleted`]: The current element is in the deleted state and will be freed once the last reference is dropped
    ///  - [`AutosarDataError::ParentElementLocked`]: a parent element was locked and did not become available after waiting briefly.
    ///    The operation was aborted to avoid a deadlock, but can be retried.
    ///  - [`AutosarDataError::IncorrectContentType`]: A sub element may not be created in an element with content type `CharacterData`.
    ///  - [`AutosarDataError::ElementInsertionConflict`]: The requested sub element cannot be created because it conflicts with an existing sub element.
    ///  - [`AutosarDataError::InvalidSubElement`]: The `ElementName` is not a valid sub element according to the specification.
    ///  - [`AutosarDataError::ElementNotIdentifiable`]: The sub element does not have an item name, so you must use `create_sub_element`() instead.
    ///  - [`AutosarDataError::NoFilesInModel`]: The operation cannot be completed because the model does not contain any files
    pub fn create_named_sub_element(
        &self,
        element_name: ElementName,
        item_name: &str,
    ) -> Result<Element, AutosarDataError> {
        let model = self.model()?;
        let version = self.min_version()?;
        self.0
            .write()
            .create_named_sub_element(self.downgrade(), element_name, item_name, &model, version)
    }

    /// Create a named/identifiable sub element at the specified insertion position
    ///
    /// The given `ElementName` must be allowed on a sub element in this element, taking into account any sub elements that may already exist.
    /// The specified insertion position will be compared to the range of valid insertion positions; if it falls outside that range then the function fails.
    ///
    /// This method can only be used to create identifiable sub elements.
    ///
    /// # Example
    ///
    /// ```
    /// # use autosar_data::*;
    /// # fn main() -> Result<(), AutosarDataError> {
    /// # let model = AutosarModel::new();
    /// # let file = model.create_file("test", AutosarVersion::Autosar_00050).unwrap();
    /// let pkgs_element = model.root_element().create_sub_element(ElementName::ArPackages)?;
    /// let element = pkgs_element.create_named_sub_element_at(ElementName::ArPackage, "Package", 0)?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    ///  - [`AutosarDataError::ItemDeleted`]: The current element is in the deleted state and will be freed once the last reference is dropped
    ///  - [`AutosarDataError::ParentElementLocked`]: a parent element was locked and did not become available after waiting briefly.
    ///    The operation was aborted to avoid a deadlock, but can be retried.
    ///  - [`AutosarDataError::IncorrectContentType`]: A sub element may not be created in an element with content type `CharacterData`.
    ///  - [`AutosarDataError::ElementInsertionConflict`]: The requested sub element cannot be created because it conflicts with an existing sub element.
    ///  - [`AutosarDataError::InvalidSubElement`]: The `ElementName` is not a valid sub element according to the specification.
    ///  - [`AutosarDataError::ElementNotIdentifiable`]: The sub element does not have an item name, so you must use `create_sub_element`() instead.
    ///  - [`AutosarDataError::InvalidPosition`]: This sub element cannot be created at the requested position.
    ///  - [`AutosarDataError::NoFilesInModel`]: The operation cannot be completed because the model does not contain any files
    pub fn create_named_sub_element_at(
        &self,
        element_name: ElementName,
        item_name: &str,
        position: usize,
    ) -> Result<Element, AutosarDataError> {
        let model = self.model()?;
        let version = self.min_version()?;
        self.0
            .write()
            .create_named_sub_element_at(self.downgrade(), element_name, item_name, position, &model, version)
    }

    /// Create a deep copy of the given element and insert it as a sub-element
    ///
    /// The other element must be a permissible sub-element in this element and not conflict with any existing sub element.
    /// The other element can originate from any loaded [`AutosarModel`], it does not have to originate from the same model or file as the current element.
    ///
    /// The [`AutosarVersion`] of the other element might differ from the version of the current file;
    /// in this case a partial copy will be performed that omits all incompatible elements.
    ///
    /// If the copied element is identifiable, then the item name might be extended with a numerical suffix, if one is required in order to make the name unique.
    /// For example: An identifiable element "Foo" already exists at the same path; the copied identifiable element will be renamed to "`Foo_1`".
    ///
    /// If the copied element or the hierarchy of elements under it contain any references, then these will need to be adjusted manually after copying.
    ///
    /// # Example
    ///
    /// ```
    /// # use autosar_data::*;
    /// # fn main() -> Result<(), AutosarDataError> {
    /// # let model = AutosarModel::new();
    /// # let file = model.create_file("test", AutosarVersion::Autosar_00050).unwrap();
    /// # let pkgs_element = model.root_element().create_sub_element(ElementName::ArPackages)?;
    /// # let base = pkgs_element.create_named_sub_element(ElementName::ArPackage, "Package")
    /// #    .and_then(|p| p.create_sub_element(ElementName::Elements))?;
    /// # base.create_named_sub_element(ElementName::System, "Path")?;
    /// let other_element = model.get_element_by_path("/Package/Path").unwrap();
    /// let element = base.create_copied_sub_element(&other_element)?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    ///  - [`AutosarDataError::ItemDeleted`]: The current element is in the deleted state and will be freed once the last reference is dropped
    ///  - [`AutosarDataError::ParentElementLocked`]: a parent element was locked and did not become available after waiting briefly.
    ///    The operation was aborted to avoid a deadlock, but can be retried.
    ///  - [`AutosarDataError::IncorrectContentType`]: A sub element may not be created in an element with content type `CharacterData`.
    ///  - [`AutosarDataError::ElementInsertionConflict`]: The requested sub element cannot be created because it conflicts with an existing sub element.
    ///  - [`AutosarDataError::InvalidSubElement`]: The `ElementName` is not a valid sub element according to the specification.
    ///  - [`AutosarDataError::NoFilesInModel`]: The operation cannot be completed because the model does not contain any files
    pub fn create_copied_sub_element(&self, other: &Element) -> Result<Element, AutosarDataError> {
        if self == other {
            // trying to copy self into self never makes sense, and would deadlock
            return Err(AutosarDataError::InvalidSubElement {
                parent: self.element_name(),
                element: self.element_name(),
            });
        }
        let model = self.model()?;
        let version = self.min_version()?;
        self.0
            .write()
            .create_copied_sub_element(self.downgrade(), other, &model, version)
    }

    /// Create a deep copy of the given element and insert it as a sub-element at the given position
    ///
    /// The other element must be a permissible sub-element in this element and not conflict with any existing sub element.
    /// The other element can originate from any loaded [`AutosarModel`], it does not have to originate from the same model or file as the current element.
    ///
    /// The [`AutosarVersion`] of the other element might differ from the version of the current file;
    /// in this case a partial copy will be performed that omits all incompatible elements.
    ///
    /// If the copied element is identifiable, then the item name might be extended with a numerical suffix, if one is required in order to make the name unique.
    /// For example: An identifiable element "Foo" already exists at the same path; the copied identifiable element will be renamed to "`Foo_1`".
    ///
    /// If the copied element or the hierarchy of elements under it contain any references, then these will need to be adjusted manually after copying.
    ///
    /// # Example
    ///
    /// ```
    /// # use autosar_data::*;
    /// # fn main() -> Result<(), AutosarDataError> {
    /// # let model = AutosarModel::new();
    /// # let file = model.create_file("test", AutosarVersion::Autosar_00050).unwrap();
    /// # let pkgs_element = model.root_element().create_sub_element(ElementName::ArPackages)?;
    /// # let base = pkgs_element.create_named_sub_element(ElementName::ArPackage, "Package")
    /// #    .and_then(|pkg| pkg.create_sub_element(ElementName::Elements))?;
    /// # base.create_named_sub_element(ElementName::System, "Path")?;
    /// let other_element = model.get_element_by_path("/Package/Path").unwrap();
    /// let element = base.create_copied_sub_element_at(&other_element, 0)?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    ///  - [`AutosarDataError::ItemDeleted`]: The current element is in the deleted state and will be freed once the last reference is dropped
    ///  - [`AutosarDataError::ParentElementLocked`]: a parent element was locked and did not become available after waiting briefly.
    ///    The operation was aborted to avoid a deadlock, but can be retried.
    ///  - [`AutosarDataError::IncorrectContentType`]: A sub element may not be created in an element with content type `CharacterData`.
    ///  - [`AutosarDataError::ElementInsertionConflict`]: The requested sub element cannot be created because it conflicts with an existing sub element.
    ///  - [`AutosarDataError::InvalidSubElement`]: The `ElementName` is not a valid sub element according to the specification.
    ///  - [`AutosarDataError::InvalidPosition`]: This sub element cannot be created at the requested position.
    ///  - [`AutosarDataError::NoFilesInModel`]: The operation cannot be completed because the model does not contain any files
    pub fn create_copied_sub_element_at(&self, other: &Element, position: usize) -> Result<Element, AutosarDataError> {
        if self == other {
            // trying to copy self into self never makes sense, and would deadlock
            return Err(AutosarDataError::InvalidSubElement {
                parent: self.element_name(),
                element: self.element_name(),
            });
        }
        let model = self.model()?;
        let version = self.min_version()?;
        self.0
            .write()
            .create_copied_sub_element_at(self.downgrade(), other, position, &model, version)
    }

    /// Take an `element` from it's current location and place it in this element as a sub element
    ///
    /// The moved element can be taken from anywhere - even from a different arxml document that is not part of the same `AutosarModel`
    ///
    /// Restrictions:
    /// 1) The element must have a compatible element type. If it could not have been created here, then it can't be moved either.
    /// 2) The origin document of the element must have exactly the same `AutosarVersion` as the destination.
    ///
    /// # Example
    ///
    /// ```
    /// # use autosar_data::*;
    /// # fn main() -> Result<(), AutosarDataError> {
    /// # let model = AutosarModel::new();
    /// # let file = model.create_file("test", AutosarVersion::Autosar_00050).unwrap();
    /// # let pkgs_element = model.root_element().create_sub_element(ElementName::ArPackages)?;
    /// # let base = pkgs_element.create_named_sub_element(ElementName::ArPackage, "Package")
    /// #    .and_then(|pkg| pkg.create_sub_element(ElementName::Elements))?;
    /// # base.create_named_sub_element(ElementName::System, "Path")?;
    /// let other_element = model.get_element_by_path("/Package/Path").unwrap();
    /// let element = base.move_element_here(&other_element)?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    ///  - [`AutosarDataError::ItemDeleted`]: The current element is in the deleted state and will be freed once the last reference is dropped
    ///  - [`AutosarDataError::ParentElementLocked`]: a parent element was locked and did not become available after waiting briefly.
    ///    The operation was aborted to avoid a deadlock, but can be retried.
    ///  - [`AutosarDataError::IncorrectContentType`]: A sub element may not be created in an element with content type `CharacterData`.
    ///  - [`AutosarDataError::ElementInsertionConflict`]: The requested sub element cannot be created because it conflicts with an existing sub element.
    ///  - [`AutosarDataError::InvalidSubElement`]: The `ElementName` is not a valid sub element according to the specification.
    ///  - [`AutosarDataError::VersionMismatch`]: The Autosar versions of the source and destination are different
    ///  - [`AutosarDataError::ForbiddenMoveToSubElement`]: The destination is a sub element of the source. Moving here is not possible
    ///  - [`AutosarDataError::NoFilesInModel`]: The operation cannot be completed because the model does not contain any files
    pub fn move_element_here(&self, move_element: &Element) -> Result<Element, AutosarDataError> {
        let model_src = move_element.model()?;
        let model = self.model()?;
        let version_src = move_element.min_version()?;
        let version = self.min_version()?;
        if version != version_src {
            return Err(AutosarDataError::VersionMismatch {
                version_cur: version,
                version_new: version_src,
            });
        }
        self.0
            .write()
            .move_element_here(self.downgrade(), move_element, &model, &model_src, version)
    }

    /// Take an `element` from it's current location and place it at the given position in this element as a sub element
    ///
    /// The moved element can be taken from anywhere - even from a different arxml document that is not part of the same `AutosarModel`
    ///
    /// Restrictions:
    /// 1) The element must have a compatible element type. If it could not have been created here, then it can't be moved either.
    /// 2) The origin document of the element must have exactly the same `AutosarVersion` as the destination.
    ///
    /// # Example
    ///
    /// ```
    /// # use autosar_data::*;
    /// # fn main() -> Result<(), AutosarDataError> {
    /// # let model = AutosarModel::new();
    /// # let file = model.create_file("test", AutosarVersion::Autosar_00050).unwrap();
    /// # let pkgs_element = model.root_element().create_sub_element(ElementName::ArPackages)?;
    /// # let base = pkgs_element.create_named_sub_element(ElementName::ArPackage, "Package")
    /// #    .and_then(|p| p.create_sub_element(ElementName::Elements))?;
    /// # base.create_named_sub_element(ElementName::System, "Path")?;
    /// let other_element = model.get_element_by_path("/Package/Path").unwrap();
    /// let element = base.move_element_here_at(&other_element, 0)?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    ///  - [`AutosarDataError::ItemDeleted`]: The current element is in the deleted state and will be freed once the last reference is dropped
    ///  - [`AutosarDataError::ParentElementLocked`]: a parent element was locked and did not become available after waiting briefly.
    ///    The operation was aborted to avoid a deadlock, but can be retried.
    ///  - [`AutosarDataError::IncorrectContentType`]: A sub element may not be created in an element with content type `CharacterData`.
    ///  - [`AutosarDataError::ElementInsertionConflict`]: The requested sub element cannot be created because it conflicts with an existing sub element.
    ///  - [`AutosarDataError::InvalidSubElement`]: The `ElementName` is not a valid sub element according to the specification.
    ///  - [`AutosarDataError::VersionMismatch`]: The Autosar versions of the source and destination are different
    ///  - [`AutosarDataError::ForbiddenMoveToSubElement`]: The destination is a sub element of the source. Moving here is not possible
    ///  - [`AutosarDataError::InvalidPosition`]: This sub element cannot be created at the requested position.
    ///  - [`AutosarDataError::NoFilesInModel`]: The operation cannot be completed because the model does not contain any files
    pub fn move_element_here_at(&self, move_element: &Element, position: usize) -> Result<Element, AutosarDataError> {
        let model_src = move_element.model()?;
        let model = self.model()?;
        let version_src = move_element.min_version()?;
        let version = self.min_version()?;
        if version != version_src {
            return Err(AutosarDataError::VersionMismatch {
                version_cur: version,
                version_new: version_src,
            });
        }
        self.0
            .write()
            .move_element_here_at(self.downgrade(), move_element, position, &model, &model_src, version)
    }

    /// Remove the sub element `sub_element`
    ///
    /// The `sub_element` will be unlinked from the hierarchy of elements.
    /// All of the sub-sub-elements nested under the removed element will also be recusively removed.
    ///
    /// Since all elements are reference counted, they might not be deallocated immediately, however they do become invalid and unusable immediately.
    ///
    /// # Example
    ///
    /// ```
    /// # use autosar_data::*;
    /// # fn main() -> Result<(), AutosarDataError> {
    /// # let model = AutosarModel::new();
    /// # let file = model.create_file("test", AutosarVersion::Autosar_00050).unwrap();
    /// let packages = model.root_element().create_sub_element(ElementName::ArPackages)?;
    /// model.root_element().remove_sub_element(packages)?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    ///  - [`AutosarDataError::ItemDeleted`]: The current element is in the deleted state and will be freed once the last reference is dropped
    ///  - [`AutosarDataError::ParentElementLocked`]: a parent element was locked and did not become available after waiting briefly.
    ///    The operation was aborted to avoid a deadlock, but can be retried.
    ///  - [`AutosarDataError::ElementNotFound`]: The sub element was not found in this element
    ///  - [`AutosarDataError::ShortNameRemovalForbidden`]: It is not permitted to remove the SHORT-NAME of identifiable elements since this would result in invalid data
    pub fn remove_sub_element(&self, sub_element: Element) -> Result<(), AutosarDataError> {
        let model = self.model()?;
        self.0.write().remove_sub_element(sub_element, &model)
    }

    /// Remove a sub element identified by an ElementName
    ///
    /// If multiple sub elements with the same ElementName exist, only the first one will be removed.
    ///
    /// A sub element with the given ElementName will be unlinked from the hierarchy of elements.
    /// All of the sub-sub-elements nested under the removed element will also be recusively removed.
    ///
    /// This is a convenience function that is equivalent to calling `get_sub_element()` followed by `remove_sub_element()`.
    ///
    /// # Example
    ///
    /// ```
    /// # use autosar_data::*;
    /// # fn main() -> Result<(), AutosarDataError> {
    /// # let model = AutosarModel::new();
    /// # let file = model.create_file("test", AutosarVersion::Autosar_00050).unwrap();
    /// let packages = model.root_element().create_sub_element(ElementName::ArPackages)?;
    /// model.root_element().remove_sub_element_kind(ElementName::ArPackages)?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    ///  - [`AutosarDataError::ItemDeleted`]: The current element is in the deleted state and will be freed once the last reference is dropped
    ///  - [`AutosarDataError::ParentElementLocked`]: a parent element was locked and did not become available after waiting briefly.
    ///    The operation was aborted to avoid a deadlock, but can be retried.
    ///  - [`AutosarDataError::ElementNotFound`]: The sub element was not found in this element
    ///  - [`AutosarDataError::ShortNameRemovalForbidden`]: It is not permitted to remove the SHORT-NAME of identifiable elements since this would result in invalid data
    pub fn remove_sub_element_kind(&self, element_name: ElementName) -> Result<(), AutosarDataError> {
        let Some(sub_element) = self.get_sub_element(element_name) else {
            return Err(AutosarDataError::ElementNotFound {
                target: element_name,
                parent: self.element_name(),
            });
        };
        self.remove_sub_element(sub_element)
    }

    /// Set the reference target for the element to target
    ///
    /// When the reference is updated, the DEST attribute is also updated to match the referenced element.
    /// The current element must be a reference element, otherwise the function fails.
    ///
    /// # Example
    ///
    /// ```
    /// # use autosar_data::*;
    /// # fn main() -> Result<(), AutosarDataError> {
    /// # let model = AutosarModel::new();
    /// # let file = model.create_file("test", AutosarVersion::Autosar_00050).unwrap();
    /// # let elements = model.root_element().create_sub_element(ElementName::ArPackages)
    /// #   .and_then(|e| e.create_named_sub_element(ElementName::ArPackage, "Pkg"))
    /// #   .and_then(|e| e.create_sub_element(ElementName::Elements))?;
    /// # let ref_element = elements.create_named_sub_element(ElementName::System, "System")
    /// #   .and_then(|e| e.create_sub_element(ElementName::FibexElements))
    /// #   .and_then(|e| e.create_sub_element(ElementName::FibexElementRefConditional))
    /// #   .and_then(|e| e.create_sub_element(ElementName::FibexElementRef))?;
    /// let cluster_element = elements.create_named_sub_element(ElementName::CanCluster, "Cluster")?;
    /// ref_element.set_reference_target(&cluster_element)?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    ///  - [`AutosarDataError::ItemDeleted`]: The current element is in the deleted state and will be freed once the last reference is dropped
    ///  - [`AutosarDataError::ParentElementLocked`]: a parent element was locked and did not become available after waiting briefly.
    ///    The operation was aborted to avoid a deadlock, but can be retried.
    ///  - [`AutosarDataError::NotReferenceElement`]: The current element is not a reference, so it is not possible to set a reference target
    ///  - [`AutosarDataError::InvalidReference`]: The target element is not a valid reference target for this reference
    ///  - [`AutosarDataError::ElementNotIdentifiable`]: The target element is not identifiable, so it cannot be referenced by an Autosar path
    ///  - [`AutosarDataError::NoFilesInModel`]: The operation cannot be completed because the model does not contain any files
    pub fn set_reference_target(&self, target: &Element) -> Result<(), AutosarDataError> {
        // the current element must be a reference
        if self.is_reference() {
            // the target element must be identifiable, i.e. it has an autosar path
            let new_ref = target.path()?;
            // it must be possible to use the name of the referenced element name as an enum item in the dest attribute of the reference
            if let Some(enum_item) = EnumItem::from_str(target.element_name().to_str())
                .ok()
                .or(self.element_type().reference_dest_value(&target.element_type()))
            {
                let model = self.model()?;
                let version = self.min_version()?;
                let mut element = self.0.write();
                // set the DEST attribute first - this could fail if the target element has the wrong type
                if element
                    .set_attribute_internal(AttributeName::Dest, CharacterData::Enum(enum_item), version)
                    .is_ok()
                {
                    // if this reference previously referenced some other element, update
                    if let Some(CharacterData::String(old_ref)) = element.character_data() {
                        model.fix_reference_origins(&old_ref, &new_ref, self.downgrade());
                    } else {
                        // else initialise the new reference
                        model.add_reference_origin(&new_ref, self.downgrade());
                    }
                    element.set_character_data(CharacterData::String(new_ref), version)?;
                    Ok(())
                } else {
                    Err(AutosarDataError::InvalidReference)
                }
            } else {
                Err(AutosarDataError::InvalidReference)
            }
        } else {
            Err(AutosarDataError::NotReferenceElement)
        }
    }

    /// Get the referenced element
    ///
    /// This function will get the reference string from the character data of the element
    /// as well as the destination type from the DEST attribute. Then a lookup of the Autosar
    /// path is performed, and if an element is found at that path, then the type of the
    /// element is compared to the expected type.
    ///
    /// The element is returned if it exists and its type is correct.
    ///
    /// # Example
    ///
    /// ```
    /// # use autosar_data::*;
    /// # fn main() -> Result<(), AutosarDataError> {
    /// # let model = AutosarModel::new();
    /// # let file = model.create_file("test", AutosarVersion::Autosar_00050).unwrap();
    /// # let elements = model.root_element().create_sub_element(ElementName::ArPackages)
    /// #   .and_then(|e| e.create_named_sub_element(ElementName::ArPackage, "Pkg"))
    /// #   .and_then(|e| e.create_sub_element(ElementName::Elements))?;
    /// # let ref_element = elements.create_named_sub_element(ElementName::System, "System")
    /// #   .and_then(|e| e.create_sub_element(ElementName::FibexElements))
    /// #   .and_then(|e| e.create_sub_element(ElementName::FibexElementRefConditional))
    /// #   .and_then(|e| e.create_sub_element(ElementName::FibexElementRef))?;
    /// let cluster_element = elements.create_named_sub_element(ElementName::CanCluster, "Cluster")?;
    /// ref_element.set_reference_target(&cluster_element)?;
    /// let ref_target = ref_element.get_reference_target()?;
    /// assert_eq!(cluster_element, ref_target);
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    ///  - [`AutosarDataError::ItemDeleted`]: The current element is in the deleted state and will be freed once the last reference is dropped
    ///  - [`AutosarDataError::ParentElementLocked`]: a parent element was locked and did not become available after waiting briefly.
    ///    The operation was aborted to avoid a deadlock, but can be retried.
    ///  - [`AutosarDataError::NotReferenceElement`]: The current element is not a reference, so it is not possible to get the reference target
    ///  - [`AutosarDataError::InvalidReference`]: The reference is invalid; there is no element with the referenced Autosar path
    pub fn get_reference_target(&self) -> Result<Element, AutosarDataError> {
        if self.is_reference() {
            if let Some(CharacterData::String(reference)) = self.character_data() {
                let model = self.model()?;
                let target_elem = model
                    .get_element_by_path(&reference)
                    .ok_or(AutosarDataError::InvalidReference)?;

                let dest_value = self
                    .attribute_value(AttributeName::Dest)
                    .and_then(|cdata| cdata.enum_value())
                    .ok_or(AutosarDataError::InvalidReference)?;
                if target_elem.element_type().verify_reference_dest(dest_value) {
                    Ok(target_elem)
                } else {
                    Err(AutosarDataError::InvalidReference)
                }
            } else {
                Err(AutosarDataError::InvalidReference)
            }
        } else {
            Err(AutosarDataError::NotReferenceElement)
        }
    }

    /// Set the character data of this element
    ///
    /// This method only applies to elements which contain character data, i.e. `element.content_type` == `CharacterData` or Mixed.
    /// On elements with mixed content this function will replace all current content with the single new `CharacterData` item.
    ///
    /// # Example
    ///
    /// ```
    /// # use autosar_data::*;
    /// # fn main() -> Result<(), AutosarDataError> {
    /// # let model = AutosarModel::new();
    /// # let file = model.create_file("test", AutosarVersion::Autosar_00050).unwrap();
    /// # let element = model.root_element().create_sub_element(ElementName::ArPackages)
    /// #   .and_then(|e| e.create_named_sub_element(ElementName::ArPackage, "Pkg"))?
    /// #   .get_sub_element(ElementName::ShortName).unwrap();
    /// element.set_character_data("value")?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    ///  - [`AutosarDataError::ItemDeleted`]: The current element is in the deleted state and will be freed once the last reference is dropped
    ///  - [`AutosarDataError::ParentElementLocked`]: a parent element was locked and did not become available after waiting briefly.
    ///    The operation was aborted to avoid a deadlock, but can be retried.
    ///  - [`AutosarDataError::IncorrectContentType`]: Cannot set character data on an element which does not contain character data
    pub fn set_character_data<T: Into<CharacterData>>(&self, value: T) -> Result<(), AutosarDataError> {
        let chardata: CharacterData = value.into();
        self.set_character_data_internal(chardata)
    }

    // internal function to set the character data - separated out since it doesn't need to be generic
    fn set_character_data_internal(&self, mut chardata: CharacterData) -> Result<(), AutosarDataError> {
        let elemtype = self.elemtype();
        if elemtype.content_mode() == ContentMode::Characters || elemtype.content_mode() == ContentMode::Mixed {
            if let Some(cdata_spec) = elemtype.chardata_spec() {
                let model = self.model()?;
                let version = self.min_version()?;
                let mut compatible_value = CharacterData::check_value(&chardata, cdata_spec, version);
                if !compatible_value
                    && matches!(
                        cdata_spec,
                        CharacterDataSpec::Pattern { .. } | CharacterDataSpec::String { .. }
                    )
                {
                    chardata = CharacterData::String(chardata.to_string());
                    compatible_value = CharacterData::check_value(&chardata, cdata_spec, version);
                }
                if compatible_value {
                    // if this is a SHORT-NAME element a whole lot of handling is needed in order to unbreak all the cross references
                    let mut prev_path = None;
                    if self.element_name() == ElementName::ShortName {
                        // this SHORT-NAME element might be newly created, in which case there is no previous path
                        if self.character_data().is_some() {
                            if let Some(parent) = self.parent()? {
                                prev_path = Some(parent.path()?);
                            }
                        }
                    };

                    // if this is a reference, then some extra effort is needed there too
                    let old_refval = if elemtype.is_ref() {
                        self.character_data().and_then(|cdata| cdata.string_value())
                    } else {
                        None
                    };

                    // update the character data
                    {
                        let mut element = self.0.write();
                        element.content.clear();
                        element.content.push(ElementContent::CharacterData(chardata));
                    }

                    // short-name: make sure the hashmap in the top-level AutosarModel is updated so that this element can still be found
                    if let Some(prev_path) = prev_path {
                        if let Some(parent) = self.parent()? {
                            let new_path = parent.path()?;
                            model.fix_identifiables(&prev_path, &new_path);
                        }
                    }

                    // reference: update the references hashmap in the top-level AutosarModel
                    if elemtype.is_ref() {
                        if let Some(CharacterData::String(refval)) = self.character_data() {
                            if let Some(old_refval) = old_refval {
                                model.fix_reference_origins(&old_refval, &refval, self.downgrade());
                            } else {
                                model.add_reference_origin(&refval, self.downgrade());
                            }
                        }
                    }

                    return Ok(());
                }
            }
        }
        Err(AutosarDataError::IncorrectContentType {
            element: self.element_name(),
        })
    }

    /// Remove the character data of this element
    ///
    /// This method only applies to elements which contain character data, i.e. `element.content_type` == `CharacterData`
    ///
    /// # Example
    ///
    /// ```
    /// # use autosar_data::*;
    /// # fn main() -> Result<(), AutosarDataError> {
    /// # let model = AutosarModel::new();
    /// # let file = model.create_file("test", AutosarVersion::Autosar_00050).unwrap();
    /// # let element = model.root_element().create_sub_element(ElementName::ArPackages)
    /// #   .and_then(|e| e.create_named_sub_element(ElementName::ArPackage, "Pkg"))
    /// #   .and_then(|e| e.create_sub_element(ElementName::Elements))
    /// #   .and_then(|e| e.create_named_sub_element(ElementName::System, "System"))
    /// #   .and_then(|e| e. create_sub_element(ElementName::PncVectorLength))
    /// #   .unwrap();
    /// element.remove_character_data()?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    ///  - [`AutosarDataError::ItemDeleted`]: The current element is in the deleted state and will be freed once the last reference is dropped
    ///  - [`AutosarDataError::ParentElementLocked`]: a parent element was locked and did not become available after waiting briefly.
    ///    The operation was aborted to avoid a deadlock, but can be retried. Only relevant when removing references.
    ///  - [`AutosarDataError::ShortNameRemovalForbidden`]: Removing the character content of a SHORT-NAME is forbidden
    ///  - [`AutosarDataError::IncorrectContentType`]: Cannot set character data on an element whoch does not contain character data
    pub fn remove_character_data(&self) -> Result<(), AutosarDataError> {
        let elemtype = self.elemtype();
        if elemtype.content_mode() == ContentMode::Characters {
            if self.element_name() == ElementName::ShortName {
                Err(AutosarDataError::ShortNameRemovalForbidden)
            } else {
                if self.character_data().is_some() {
                    if self.is_reference() {
                        let model = self.model()?;
                        if let Some(CharacterData::String(reference)) = self.character_data() {
                            model.remove_reference_origin(&reference, self.downgrade());
                        }
                    }
                    self.0.write().content.clear();
                }
                Ok(())
            }
        } else {
            Err(AutosarDataError::IncorrectContentType {
                element: self.element_name(),
            })
        }
    }

    /// Insert a character data item into the content of this element
    ///
    /// This method only applies to elements which contain mixed data, i.e. `element.content_type`() == Mixed.
    /// Use `create_sub_element_at` to add an element instead of a character data item
    ///
    /// # Example
    ///
    /// ```
    /// # use autosar_data::*;
    /// # fn main() -> Result<(), AutosarDataError> {
    /// # let model = AutosarModel::new();
    /// # let file = model.create_file("test", AutosarVersion::Autosar_00050).unwrap();
    /// # let element = model.root_element().create_sub_element(ElementName::ArPackages)
    /// #   .and_then(|e| e.create_named_sub_element(ElementName::ArPackage, "Pkg"))?;
    /// // mixed content elements are primarily used for documentation and description
    /// let desc = element.create_sub_element(ElementName::Desc)?;
    /// let l2 = desc.create_sub_element(ElementName::L2)?;
    /// l2.insert_character_content_item("descriptive text", 0)?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    ///  - [`AutosarDataError::IncorrectContentType`] the element `content_type` is not Mixed
    ///  - [`AutosarDataError::InvalidPosition`] the position is not valid
    pub fn insert_character_content_item(&self, chardata: &str, position: usize) -> Result<(), AutosarDataError> {
        let mut element = self.0.write();
        if let ContentMode::Mixed = element.elemtype.content_mode() {
            if position <= element.content.len() {
                element.content.insert(
                    position,
                    ElementContent::CharacterData(CharacterData::String(chardata.to_owned())),
                );
                Ok(())
            } else {
                Err(AutosarDataError::InvalidPosition)
            }
        } else {
            Err(AutosarDataError::IncorrectContentType {
                element: element.element_name(),
            })
        }
    }

    /// Remove a character data item from the content of this element
    ///
    /// This method only applies to elements which contain mixed data, i.e. `element.content_type` == Mixed
    ///
    /// # Example
    ///
    /// ```
    /// # use autosar_data::*;
    /// # fn main() -> Result<(), AutosarDataError> {
    /// # let model = AutosarModel::new();
    /// # let file = model.create_file("test", AutosarVersion::Autosar_00050).unwrap();
    /// # let element = model.root_element().create_sub_element(ElementName::ArPackages)
    /// #   .and_then(|e| e.create_named_sub_element(ElementName::ArPackage, "Pkg"))
    /// #   .and_then(|e| e.create_sub_element(ElementName::Desc))
    /// #   .and_then(|e| e.create_sub_element(ElementName::L2))?;
    /// element.insert_character_content_item("descriptive text", 0)?;
    /// element.remove_character_content_item(0)?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    ///  - [`AutosarDataError::IncorrectContentType`] the element `content_type` is not Mixed
    ///  - [`AutosarDataError::InvalidPosition`] the position is not valid
    pub fn remove_character_content_item(&self, position: usize) -> Result<(), AutosarDataError> {
        let mut element = self.0.write();
        if let ContentMode::Mixed = element.elemtype.content_mode() {
            if position < element.content.len() {
                if let ElementContent::CharacterData(_) = element.content[position] {
                    element.content.remove(position);
                    return Ok(());
                }
            }
            Err(AutosarDataError::InvalidPosition)
        } else {
            Err(AutosarDataError::IncorrectContentType {
                element: element.element_name(),
            })
        }
    }

    /// returns the number of content items in this element
    /// ```
    /// # use autosar_data::*;
    /// # fn main() -> Result<(), AutosarDataError> {
    /// # let model = AutosarModel::new();
    /// # let file = model.create_file("test", AutosarVersion::Autosar_00050).unwrap();
    /// # let pkg = model.root_element().create_sub_element(ElementName::ArPackages)
    /// #   .and_then(|e| e.create_named_sub_element(ElementName::ArPackage, "Pkg"))?;
    /// assert_eq!(pkg.content_item_count(), 1);
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn content_item_count(&self) -> usize {
        self.0.read().content.len()
    }

    /// Get the character content of the element
    ///
    /// This method only applies to elements which contain character data, i.e. `element.content_type`() == `CharacterData`
    ///
    /// # Example
    ///
    /// ```
    /// # use autosar_data::*;
    /// # fn main() -> Result<(), AutosarDataError> {
    /// # let model = AutosarModel::new();
    /// # let file = model.create_file("test", AutosarVersion::Autosar_00050).unwrap();
    /// # let element = model.root_element().create_sub_element(ElementName::ArPackages)
    /// #   .and_then(|e| e.create_named_sub_element(ElementName::ArPackage, "Pkg"))?
    /// #   .get_sub_element(ElementName::ShortName).unwrap();
    /// match element.character_data() {
    ///     Some(CharacterData::String(stringval)) => {},
    ///     Some(CharacterData::Enum(enumval)) => {},
    ///     Some(CharacterData::UnsignedInteger(intval)) => {},
    ///     Some(CharacterData::Float(floatval)) => {},
    ///     None => {},
    /// }
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn character_data(&self) -> Option<CharacterData> {
        self.0.read().character_data()
    }

    /// Create an iterator over all of the content of this element
    ///
    /// The iterator can return both sub elements and character data, wrapped as `ElementContent::Element` and `ElementContent::CharacterData`
    ///
    /// This method is intended to be used with elements that contain mixed content.
    ///
    /// # Example
    ///
    /// ```
    /// # use autosar_data::*;
    /// # let model = AutosarModel::new();
    /// # let file = model.create_file("test", AutosarVersion::Autosar_00050).unwrap();
    /// # let element = model.root_element();
    /// for content_item in element.content() {
    ///     match content_item {
    ///         ElementContent::CharacterData(data) => {},
    ///         ElementContent::Element(element) => {},
    ///     }
    /// }
    /// ```
    #[must_use]
    pub fn content(&self) -> ElementContentIterator {
        ElementContentIterator::new(self)
    }

    /// Create a weak reference to this element
    ///
    /// A weak reference can be stored without preventing the element from being deallocated.
    /// The weak reference has to be upgraded in order to be used, which can fail if the element no longer exists.
    ///
    /// See the documentation for [Arc]
    ///
    /// # Example
    ///
    /// ```
    /// # use autosar_data::*;
    /// # let model = AutosarModel::new();
    /// # let file = model.create_file("test", AutosarVersion::Autosar_00050).unwrap();
    /// # let element = model.root_element();
    /// let weak_element = element.downgrade();
    /// ```
    #[must_use]
    pub fn downgrade(&self) -> WeakElement {
        WeakElement(Arc::downgrade(&self.0))
    }

    /// return the position of this element within the parent element
    ///
    /// None may be returned if the element has been deleted, or for the root element (AUTOSAR) which has no parent.
    /// The returned position can be used with `get_sub_element_at()`.
    ///
    /// # Example
    ///
    /// ```
    /// # use autosar_data::*;
    /// # let model = AutosarModel::new();
    /// # let file = model.create_file("test", AutosarVersion::Autosar_00050).unwrap();
    /// # let el_ar_packages = model.root_element().create_sub_element(ElementName::ArPackages).unwrap();
    /// let el_pkg1 = el_ar_packages.create_named_sub_element(ElementName::ArPackage, "Pkg1").unwrap();
    /// let el_pkg2 = el_ar_packages.create_named_sub_element(ElementName::ArPackage, "Pkg2").unwrap();
    /// let el_pkg3 = el_ar_packages.create_named_sub_element(ElementName::ArPackage, "Pkg3").unwrap();
    /// let position = el_pkg2.position().unwrap();
    /// assert_eq!(position, 1);
    /// assert_eq!(el_pkg2, el_ar_packages.get_sub_element_at(position).unwrap());
    /// ```
    #[must_use]
    pub fn position(&self) -> Option<usize> {
        if let Ok(Some(parent)) = self.parent() {
            parent
                .0
                .read()
                .content
                .iter()
                .position(|ec| matches!(ec, ElementContent::Element(elem) if elem == self))
        } else {
            None
        }
    }

    /// Create an iterator over all sub elements of this element
    ///
    /// # Example
    ///
    /// ```
    /// # use autosar_data::*;
    /// # let model = AutosarModel::new();
    /// # let file = model.create_file("test", AutosarVersion::Autosar_00050).unwrap();
    /// # let element = model.root_element();
    /// for sub_element in element.sub_elements() {
    ///     // ...
    /// }
    /// ```
    #[must_use]
    pub fn sub_elements(&self) -> ElementsIterator {
        ElementsIterator::new(self.clone())
    }

    /// Get the sub element with the given element name
    ///
    /// Returns None if no such element exists. if there are multiple sub elements with the requested name, then only the first is returned
    ///
    /// # Example
    ///
    /// ```
    /// # use autosar_data::*;
    /// # fn main() -> Result<(), AutosarDataError> {
    /// # let model = AutosarModel::new();
    /// # let file = model.create_file("test", AutosarVersion::Autosar_00050).unwrap();
    /// # let pkg = model.root_element().create_sub_element(ElementName::ArPackages)
    /// #   .and_then(|e| e.create_named_sub_element(ElementName::ArPackage, "Pkg"))?;
    /// let element = pkg.get_sub_element(ElementName::ShortName).unwrap();
    /// assert_eq!(element.element_name(), ElementName::ShortName);
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn get_sub_element(&self, name: ElementName) -> Option<Element> {
        let locked_elem = self.0.read();
        for item in &locked_elem.content {
            if let ElementContent::Element(subelem) = item {
                if subelem.element_name() == name {
                    return Some(subelem.clone());
                }
            }
        }
        None
    }

    /// Get the sub element at the given position.
    ///
    /// Returns None if no such element exists.
    ///
    /// # Example
    ///
    /// ```
    /// # use autosar_data::*;
    /// # fn main() -> Result<(), AutosarDataError> {
    /// # let model = AutosarModel::new();
    /// # let file = model.create_file("test", AutosarVersion::Autosar_00050).unwrap();
    /// # let pkg = model.root_element().create_sub_element(ElementName::ArPackages)
    /// #   .and_then(|e| e.create_named_sub_element(ElementName::ArPackage, "Pkg"))?;
    /// let element = pkg.get_sub_element_at(0).unwrap();
    /// assert_eq!(element.element_name(), ElementName::ShortName);
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn get_sub_element_at(&self, position: usize) -> Option<Element> {
        let locked_elem = self.0.read();
        if let Some(ElementContent::Element(subelem)) = locked_elem.content.get(position) {
            return Some(subelem.clone());
        }
        None
    }

    /// Get or create a sub element
    ///
    /// This is a shorthand for `get_sub_element` followed by `create_cub_element` if getting an existing element fails.
    ///
    /// # Example
    ///
    /// ```
    /// # use autosar_data::*;
    /// # fn main() -> Result<(), AutosarDataError> {
    /// # let model = AutosarModel::new();
    /// # let file = model.create_file("test", AutosarVersion::Autosar_00050).unwrap();
    /// let element = model.root_element().get_or_create_sub_element(ElementName::ArPackages)?;
    /// let element2 = model.root_element().get_or_create_sub_element(ElementName::ArPackages)?;
    /// assert_eq!(element, element2);
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    ///  - [`AutosarDataError::ItemDeleted`]: The current element is in the deleted state and will be freed once the last reference is dropped
    ///  - [`AutosarDataError::ParentElementLocked`]: a parent element was locked and did not become available after waiting briefly.
    ///    The operation was aborted to avoid a deadlock, but can be retried.
    ///  - [`AutosarDataError::IncorrectContentType`]: A sub element may not be created in an element with content type `CharacterData`.
    ///  - [`AutosarDataError::ElementInsertionConflict`]: The requested sub element cannot be created because it conflicts with an existing sub element.
    ///  - [`AutosarDataError::InvalidSubElement`]: The `ElementName` is not a valid sub element according to the specification.
    ///  - [`AutosarDataError::ItemNameRequired`]: The sub element requires an item name, so you must use `create_named_sub_element`().
    ///  - [`AutosarDataError::NoFilesInModel`]: The operation cannot be completed because the model does not contain any files
    pub fn get_or_create_sub_element(&self, name: ElementName) -> Result<Element, AutosarDataError> {
        let version = self.min_version()?;
        let mut locked_elem = self.0.try_write().ok_or(AutosarDataError::ParentElementLocked)?;
        for item in &locked_elem.content {
            if let ElementContent::Element(subelem) = item {
                if subelem.element_name() == name {
                    return Ok(subelem.clone());
                }
            }
        }
        locked_elem.create_sub_element(self.downgrade(), name, version)
    }
    /// Get or create a named sub element
    ///
    /// Checks if a matching subelement exists, and returns it if it does.
    /// If no matching subelement exists, tries to create one.
    ///
    /// # Example
    ///
    /// ```
    /// # use autosar_data::*;
    /// # fn main() -> Result<(), AutosarDataError> {
    /// # let model = AutosarModel::new();
    /// # let file = model.create_file("test", AutosarVersion::Autosar_00050).unwrap();
    /// let ar_packages = model.root_element().get_or_create_sub_element(ElementName::ArPackages)?;
    /// let pkg = ar_packages.get_or_create_named_sub_element(ElementName::ArPackage, "Pkg")?;
    /// let pkg_2 = ar_packages.get_or_create_named_sub_element(ElementName::ArPackage, "Pkg")?;
    /// assert_eq!(pkg, pkg_2);
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    ///  - [`AutosarDataError::ItemDeleted`]: The current element is in the deleted state and will be freed once the last reference is dropped
    ///  - [`AutosarDataError::ParentElementLocked`]: a parent element was locked and did not become available after waiting briefly.
    ///    The operation was aborted to avoid a deadlock, but can be retried.
    ///  - [`AutosarDataError::IncorrectContentType`]: A sub element may not be created in an element with content type `CharacterData`.
    ///  - [`AutosarDataError::ElementInsertionConflict`]: The requested sub element cannot be created because it conflicts with an existing sub element.
    ///  - [`AutosarDataError::InvalidSubElement`]: The `ElementName` is not a valid sub element according to the specification.
    ///  - [`AutosarDataError::ItemNameRequired`]: The sub element requires an item name, so you must use `create_named_sub_element`().
    ///  - [`AutosarDataError::NoFilesInModel`]: The operation cannot be completed because the model does not contain any files
    pub fn get_or_create_named_sub_element(
        &self,
        element_name: ElementName,
        item_name: &str,
    ) -> Result<Element, AutosarDataError> {
        let model = self.model()?;
        let version = self.min_version()?;
        let mut locked_elem = self.0.try_write().ok_or(AutosarDataError::ParentElementLocked)?;
        for item in &locked_elem.content {
            if let ElementContent::Element(subelem) = item {
                if subelem.element_name() == element_name && subelem.item_name().as_deref().unwrap_or("") == item_name {
                    return Ok(subelem.clone());
                }
            }
        }
        locked_elem.create_named_sub_element(self.downgrade(), element_name, item_name, &model, version)
    }

    /// Create a depth first iterator over this element and all of its sub elements
    ///
    /// Each step in the iteration returns the depth and an element. Due to the nature of a depth first search,
    /// the returned depth can remain the same, increase by one, or decrease by an arbitrary number in each step.
    ///
    /// The dfs iterator will always return this element as the first item.
    ///
    /// # Example
    ///
    /// ```
    /// # use autosar_data::*;
    /// # let model = AutosarModel::new();
    /// # let file = model.create_file("test", AutosarVersion::Autosar_00050).unwrap();
    /// # let element = model.root_element();
    /// for (depth, elem) in element.elements_dfs() {
    ///     // ...
    /// }
    /// ```
    #[must_use]
    pub fn elements_dfs(&self) -> ElementsDfsIterator {
        ElementsDfsIterator::new(self, 0)
    }

    /// Create a depth first iterator over this element and all of its sub elements up to a maximum depth
    ///
    /// Each step in the iteration returns the depth and an element. Due to the nature of a depth first search,
    /// the returned depth can remain the same, increase by one, or decrease by an arbitrary number in each step.
    ///
    /// The dfs iterator will always return this element as the first item. A `max_depth` of `0` returns all
    /// child elements, regardless of depth (like `elements_dfs` does).
    ///
    /// # Example
    ///
    /// ```
    /// # use autosar_data::*;
    /// # let model = AutosarModel::new();
    /// # let file = model.create_file("test", AutosarVersion::Autosar_00050).unwrap();
    /// # let element = model.root_element();
    /// # element.create_sub_element(ElementName::ArPackages).unwrap();
    /// # let sub_elem = element.get_sub_element(ElementName::ArPackages).unwrap();
    /// # sub_elem.create_named_sub_element(ElementName::ArPackage, "test2").unwrap();
    /// for (depth, elem) in element.elements_dfs_with_max_depth(1) {
    ///     assert!(depth <= 1);
    ///     // ...
    /// }
    /// ```
    #[must_use]
    pub fn elements_dfs_with_max_depth(&self, max_depth: usize) -> ElementsDfsIterator {
        ElementsDfsIterator::new(self, max_depth)
    }

    /// Create an iterator over all the attributes in this element
    ///
    /// # Example
    ///
    /// ```
    /// # use autosar_data::*;
    /// # let model = AutosarModel::new();
    /// # let file = model.create_file("test", AutosarVersion::Autosar_00050).unwrap();
    /// # let element = model.root_element();
    /// for attribute in element.attributes() {
    ///     println!("{} = {}", attribute.attrname, attribute.content);
    /// }
    /// ```
    #[must_use]
    pub fn attributes(&self) -> AttributeIterator {
        AttributeIterator {
            element: self.clone(),
            index: 0,
        }
    }

    /// Get the value of an attribute by name
    ///
    /// # Example
    ///
    /// ```
    /// # use autosar_data::*;
    /// # let model = AutosarModel::new();
    /// # let file = model.create_file("test", AutosarVersion::Autosar_00050).unwrap();
    /// let value = model.root_element().attribute_value(AttributeName::xsiSchemalocation);
    /// ```
    #[must_use]
    pub fn attribute_value(&self, attrname: AttributeName) -> Option<CharacterData> {
        self.0.read().attribute_value(attrname)
    }

    /// Set the value of a named attribute
    ///
    /// If no attribute by that name exists, and the attribute is a valid attribute of the element, then the attribute will be created.
    ///
    /// Returns Ok(()) if the attribute was set, otherwise the Err indicates why setting the attribute failed.
    ///
    /// ```
    /// # use autosar_data::*;
    /// # let model = AutosarModel::new();
    /// # let file = model.create_file("test", AutosarVersion::Autosar_00050).unwrap();
    /// # let element = model.root_element();
    /// let result = element.set_attribute(AttributeName::S, CharacterData::String("1234-5678".to_string()));
    /// # assert!(result.is_ok());
    /// ```
    ///
    /// # Errors
    ///
    ///  - [`AutosarDataError::ItemDeleted`]: The current element is in the deleted state and will be freed once the last reference is dropped
    ///  - [`AutosarDataError::InvalidAttribute`]: The `AttributeName` is not valid for this element
    ///  - [`AutosarDataError::InvalidAttributeValue`]: The value is not valid for this attribute in this element
    ///  - [`AutosarDataError::NoFilesInModel`]: The operation cannot be completed because the model does not contain any files
    pub fn set_attribute<T: Into<CharacterData>>(
        &self,
        attrname: AttributeName,
        value: T,
    ) -> Result<(), AutosarDataError> {
        let version = self.min_version()?;
        self.0.write().set_attribute_internal(attrname, value.into(), version)
    }

    /// Set the value of a named attribute from a string
    ///
    /// The function tries to convert the string to the correct data type for the attribute
    ///
    /// Returns Ok(()) if the attribute was set, otherwise the Err indicates why setting the attribute failed.
    ///
    /// ```
    /// # use autosar_data::*;
    /// # let model = AutosarModel::new();
    /// # let file = model.create_file("test", AutosarVersion::Autosar_00050).unwrap();
    /// # let element = model.root_element();
    /// let result = element.set_attribute_string(AttributeName::T, "2022-01-31T13:59:59Z");
    /// # assert!(result.is_ok());
    /// ```
    ///
    /// # Errors
    ///
    ///  - [`AutosarDataError::ItemDeleted`]: The current element is in the deleted state and will be freed once the last reference is dropped
    ///  - [`AutosarDataError::InvalidAttribute`]: The `AttributeName` is not valid for this element
    ///  - [`AutosarDataError::InvalidAttributeValue`]: The value is not valid for this attribute in this element
    ///  - [`AutosarDataError::NoFilesInModel`]: The operation cannot be completed because the model does not contain any files
    pub fn set_attribute_string(&self, attrname: AttributeName, stringvalue: &str) -> Result<(), AutosarDataError> {
        let version = self.min_version()?;
        self.0.write().set_attribute_string(attrname, stringvalue, version)
    }

    /// Remove an attribute from the element
    ///
    /// Returns true if the attribute existed and could be removed.
    ///
    /// # Example
    ///
    /// ```
    /// # use autosar_data::*;
    /// # let model = AutosarModel::new();
    /// # let file = model.create_file("test", AutosarVersion::Autosar_00050).unwrap();
    /// let result = model.root_element().remove_attribute(AttributeName::xsiSchemalocation);
    /// // xsiSchemalocation exists in the AUTOSAR element, but it is mandatory and cannot be removed
    /// assert_eq!(result, false);
    /// ```
    #[must_use]
    pub fn remove_attribute(&self, attrname: AttributeName) -> bool {
        self.0.write().remove_attribute(attrname)
    }

    /// Recursively sort all sub-elements of this element
    ///
    /// All sub elements of the current element are sorted alphabetically.
    /// If the sub-elements are named, then the sorting is performed according to the item names,
    /// otherwise the serialized form of the sub-elements is used for sorting.
    /// Element attributes are not taken into account while sorting.
    /// The elements are sorted in place, and sorting cannot fail, so there is no return value.
    ///
    /// # Example
    /// ```
    /// # use autosar_data::*;
    /// # let model = AutosarModel::new();
    /// # let file = model.create_file("test", AutosarVersion::Autosar_00050).unwrap();
    /// # let element = model.root_element();
    /// element.sort();
    /// ```
    pub fn sort(&self) {
        self.0.write().sort();
    }

    /// Serialize the element and all of its content to a string
    ///
    /// The serialized text generated for elements below the root element cannot be loaded, but it may be useful for display.
    ///
    /// # Example
    ///
    /// ```
    /// # use autosar_data::*;
    /// # let model = AutosarModel::new();
    /// # let file = model.create_file("test", AutosarVersion::Autosar_00050).unwrap();
    /// # let element = model.root_element();
    /// let text = element.serialize();
    /// ```
    #[must_use]
    pub fn serialize(&self) -> String {
        let mut outstring = String::new();

        self.serialize_internal(&mut outstring, 0, false, &None);

        outstring
    }

    pub(crate) fn serialize_internal(
        &self,
        outstring: &mut String,
        indent: usize,
        inline: bool,
        for_file: &Option<WeakArxmlFile>,
    ) {
        let element = self.0.read();
        let element_name = element.elemname.to_str();

        if let Some(comment) = &self.0.read().comment {
            // put the comment on a separate line
            if !inline {
                Self::serialize_newline_indent(outstring, indent);
            }
            outstring.push_str("<!--");
            outstring.push_str(comment);
            outstring.push_str("-->");
        }

        // write the opening tag on a new line and indent it
        if !inline {
            Self::serialize_newline_indent(outstring, indent);
        }

        if !element.content.is_empty() {
            outstring.push('<');
            outstring.push_str(element_name);
            self.serialize_attributes(outstring);
            outstring.push('>');

            match self.content_type() {
                ContentType::Elements => {
                    // serialize each sub-element
                    for subelem in self.sub_elements() {
                        if for_file.is_none()
                            || subelem.0.read().file_membership.is_empty()
                            || subelem.0.read().file_membership.contains(for_file.as_ref().unwrap())
                        {
                            subelem.serialize_internal(outstring, indent + 1, false, for_file);
                        }
                    }
                    // put the closing tag on a new line and indent it
                    Self::serialize_newline_indent(outstring, indent);
                    outstring.push_str("</");
                    outstring.push_str(element_name);
                    outstring.push('>');
                }
                ContentType::CharacterData => {
                    // write the character data on the same line as the opening tag
                    if let Some(ElementContent::CharacterData(chardata)) = element.content.first() {
                        chardata.serialize_internal(outstring);
                    }

                    // write the closing tag on the same line
                    outstring.push_str("</");
                    outstring.push_str(element_name);
                    outstring.push('>');
                }
                ContentType::Mixed => {
                    for item in self.content() {
                        match item {
                            ElementContent::Element(subelem) => {
                                if for_file.is_none()
                                    || subelem.0.read().file_membership.is_empty()
                                    || subelem.0.read().file_membership.contains(for_file.as_ref().unwrap())
                                {
                                    subelem.serialize_internal(outstring, indent + 1, true, for_file);
                                }
                            }
                            ElementContent::CharacterData(chardata) => {
                                chardata.serialize_internal(outstring);
                            }
                        }
                    }
                    // write the closing tag on the same line
                    outstring.push_str("</");
                    outstring.push_str(element_name);
                    outstring.push('>');
                }
            }
        } else {
            outstring.push('<');
            outstring.push_str(element_name);
            self.serialize_attributes(outstring);
            outstring.push('/');
            outstring.push('>');
        }
    }

    fn serialize_newline_indent(outstring: &mut String, indent: usize) {
        outstring.push('\n');
        for _ in 0..indent {
            outstring.push_str("  ");
        }
    }

    fn serialize_attributes(&self, outstring: &mut String) {
        let element = self.0.read();
        if !element.attributes.is_empty() {
            for attribute in &element.attributes {
                outstring.push(' ');
                outstring.push_str(attribute.attrname.to_str());
                outstring.push_str("=\"");
                attribute.content.serialize_internal(outstring);
                outstring.push('"');
            }
        }
    }

    pub(crate) fn elemtype(&self) -> ElementType {
        self.0.read().elemtype
    }

    // an element might have a diffeent element type depending on the version - as a result of a
    // changed datatype of the CharacterData, or because the element ordering was changed
    fn recalc_element_type(&self, target_version: AutosarVersion) -> ElementType {
        if let Ok(Some(parent)) = self.parent() {
            if let Some((etype, ..)) = parent
                .element_type()
                .find_sub_element(self.element_name(), target_version as u32)
            {
                return etype;
            }
        }

        self.element_type()
    }

    /// check if the sub elements and attributes of this element are compatible with some `target_version`
    pub(crate) fn check_version_compatibility(
        &self,
        file: &WeakArxmlFile,
        target_version: AutosarVersion,
    ) -> (Vec<CompatibilityError>, u32) {
        let mut compat_errors = Vec::new();
        let mut overall_version_mask = u32::MAX;

        // make sure compatibility checks are performed with the element type used in the target version
        let elemtype_new = self.recalc_element_type(target_version);

        // check the compatibility of all the attributes in this element
        {
            let element = self.0.read();
            for attribute in &element.attributes {
                // find the specification for the current attribute
                if let Some(AttributeSpec {
                    spec: value_spec,
                    version: version_mask,
                    ..
                }) = elemtype_new.find_attribute_spec(attribute.attrname)
                {
                    overall_version_mask &= version_mask;
                    // check if the attribute is allowed at all
                    if !target_version.compatible(version_mask) {
                        compat_errors.push(CompatibilityError::IncompatibleAttribute {
                            element: self.clone(),
                            attribute: attribute.attrname,
                            version_mask,
                        });
                    } else {
                        let (is_compatible, value_version_mask) = attribute
                            .content
                            .check_version_compatibility(value_spec, target_version);
                        if !is_compatible {
                            compat_errors.push(CompatibilityError::IncompatibleAttributeValue {
                                element: self.clone(),
                                attribute: attribute.attrname,
                                attribute_value: attribute.content.to_string(),
                                version_mask: value_version_mask,
                            });
                        }
                        overall_version_mask &= value_version_mask;
                    }
                }
            }
        }

        // check the compatibility of all sub-elements
        for sub_element in self.sub_elements() {
            if sub_element.0.read().file_membership.is_empty() || sub_element.0.read().file_membership.contains(file) {
                if let Some((_, indices)) = elemtype_new
                    .find_sub_element(sub_element.element_name(), target_version as u32)
                    .or(elemtype_new.find_sub_element(sub_element.element_name(), u32::MAX))
                {
                    let version_mask = self.element_type().get_sub_element_version_mask(&indices).unwrap();
                    overall_version_mask &= version_mask;
                    if !target_version.compatible(version_mask) {
                        compat_errors.push(CompatibilityError::IncompatibleElement {
                            element: sub_element.clone(),
                            version_mask,
                        });
                    } else {
                        let (mut sub_element_errors, sub_element_mask) =
                            sub_element.check_version_compatibility(file, target_version);
                        compat_errors.append(&mut sub_element_errors);
                        overall_version_mask &= sub_element_mask;
                    }
                }
            }
        }

        (compat_errors, overall_version_mask)
    }

    /// List all `sub_elements` that are valid in the current element
    ///
    /// The target use case is direct interaction with a user, e.g. through a selection dialog
    ///
    /// # Return Value
    ///
    /// A list of tuples consisting of
    ///     `ElementName` of the potential sub element
    ///     bool: is the sub element named
    ///     bool: can this sub element be inserted considering the current content of the element
    ///
    /// # Example
    ///
    /// ```
    /// # use autosar_data::*;
    /// # let model = AutosarModel::new();
    /// # let file = model.create_file("test", AutosarVersion::Autosar_00050).unwrap();
    /// # let element = model.root_element();
    /// for ValidSubElementInfo{element_name, is_named, is_allowed} in element.list_valid_sub_elements() {
    ///     // ...
    /// }
    /// ```
    #[must_use]
    pub fn list_valid_sub_elements(&self) -> Vec<ValidSubElementInfo> {
        let etype = self.0.read().elemtype;
        let mut valid_sub_elements = Vec::new();

        if let Ok(version) = self.min_version() {
            for (element_name, _, version_mask, named_mask) in etype.sub_element_spec_iter() {
                if version.compatible(version_mask) {
                    let is_named = version.compatible(named_mask);
                    let is_allowed = self.0.read().calc_element_insert_range(element_name, version).is_ok();
                    valid_sub_elements.push(ValidSubElementInfo {
                        element_name,
                        is_named,
                        is_allowed,
                    });
                }
            }
        }

        valid_sub_elements
    }

    /// Return the set of files in which the current element is present
    ///
    /// # Return Value
    ///
    /// A tuple (bool, `HashSet`); if the bool value is true, then the file set is stored in this element, otherwise it is inherited from a parent element.
    ///
    /// # Example
    ///
    /// ```
    /// # use autosar_data::*;
    /// # fn main() -> Result<(), AutosarDataError> {
    /// # let model = AutosarModel::new();
    /// # let file = model.create_file("test", AutosarVersion::Autosar_00050).unwrap();
    /// # let element = model.root_element();
    /// let (inherited, file_membership) = element.file_membership()?;
    /// # Ok(())
    /// # }
    /// ```
    /// # Errors
    ///
    ///  - [`AutosarDataError::ItemDeleted`]: The current element is in the deleted state and will be freed once the last reference is dropped
    ///  - [`AutosarDataError::ParentElementLocked`]: a parent element was locked and did not become available after waiting briefly.
    ///    The operation was aborted to avoid a deadlock, but can be retried.
    ///  - [`AutosarDataError::NoFilesInModel`]: The operation cannot be completed because the model does not contain any files
    pub fn file_membership(&self) -> Result<(bool, HashSet<WeakArxmlFile>), AutosarDataError> {
        let mut cur_elem_opt = Some(self.clone());
        while let Some(cur_elem) = &cur_elem_opt {
            let locked_cur_elem = cur_elem
                .0
                .try_read_for(std::time::Duration::from_millis(10))
                .ok_or(AutosarDataError::ParentElementLocked)?;
            if !locked_cur_elem.file_membership.is_empty() {
                return Ok((cur_elem == self, locked_cur_elem.file_membership.clone()));
            }
            drop(locked_cur_elem);

            cur_elem_opt = cur_elem.parent()?;
        }

        // no file membership info found at any level - this only happens if the model does not contain any files
        Err(AutosarDataError::NoFilesInModel)
    }

    /// return the file membership of this element without trying to get an inherited value
    pub(crate) fn file_membership_local(&self) -> HashSet<WeakArxmlFile> {
        self.0.read().file_membership.clone()
    }

    /// set the file membership of an element
    ///
    /// The passed set acts as a restriction of the file membership of the parent element.
    /// This means that the set of a child cannot be greater than that of the parent.
    ///
    /// Setting an empty set has a special meaning: it reverts the membership to default,
    /// i.e. inherited from the parent with no additional restriction
    pub(crate) fn set_file_membership(&self, file_membership: HashSet<WeakArxmlFile>) {
        // find out if the parent is splittable. If the parent is unavaliable, assume
        // that the caller knows what they're doing and assume it is splittable
        let parent_splittable = self
            .parent()
            .ok()
            .flatten()
            .map_or(u32::MAX, |p| p.element_type().splittable());
        // can always reset the membership to empty = inherited; otherwise the parent must be splittable
        if file_membership.is_empty() || parent_splittable != 0 {
            self.0.write().file_membership = file_membership;
        }
    }

    /// add the current element to the given file
    ///
    /// In order to successfully cause the element to appear in the serialized file data, all parent elements
    /// of the current element will also be added if required.
    ///
    /// If the model only has a single file then this function does nothing.
    ///
    /// # Example
    /// ```
    /// # use autosar_data::*;
    /// # use std::collections::HashSet;
    /// # let model = AutosarModel::new();
    /// let file = model.create_file("test", AutosarVersion::Autosar_00050).unwrap();
    /// # let element = model.root_element();
    /// element.add_to_file(&file);
    /// ```
    ///
    /// # Errors
    ///
    ///  - [`AutosarDataError::ItemDeleted`]: The current element is in the deleted state and will be freed once the last reference is dropped
    ///  - [`AutosarDataError::ParentElementLocked`]: a parent element was locked and did not become available after waiting briefly.
    ///    The operation was aborted to avoid a deadlock, but can be retried.
    ///
    pub fn add_to_file(&self, file: &ArxmlFile) -> Result<(), AutosarDataError> {
        let parent_splittable = self.parent()?.map_or(true, |p| p.element_type().splittable() != 0);
        if parent_splittable {
            if file.model()? == self.model()? {
                let weak_file = file.downgrade();
                // current_fileset is the set of files which contain the current element
                let (_, current_fileset) = self.file_membership()?;
                // if the model only has a single file or if the element is already in the set then there is nothing to do
                if !current_fileset.contains(&weak_file) {
                    let mut updated_fileset = current_fileset;
                    updated_fileset.insert(weak_file);
                    self.0.write().file_membership = updated_fileset;

                    // recursively continue with the parent
                    if let Some(parent) = self.parent()? {
                        parent.add_to_file_restricted(file)?;
                    }
                }
                Ok(())
            } else {
                // adding a file from a different model is not permitted
                Err(AutosarDataError::InvalidFile)
            }
        } else {
            Err(AutosarDataError::FilesetModificationForbidden)
        }
    }

    /// add only this element and its direct parents to a file, but not its children
    pub(crate) fn add_to_file_restricted(&self, file: &ArxmlFile) -> Result<(), AutosarDataError> {
        let weak_file = file.downgrade();
        let (local, current_fileset) = self.file_membership().unwrap_or((true, HashSet::new()));

        if !current_fileset.contains(&weak_file) {
            // if the current element is splittable, then all of its subelements are allowed to have their own filesets
            // unless something else is already set, they should get the current unmodified file membership of this element
            // which does not include the new file
            if self.element_type().splittable() != 0 {
                for se in self.sub_elements() {
                    if let Some(mut subelem) = se.0.try_write() {
                        if subelem.file_membership.is_empty() {
                            subelem.file_membership.clone_from(&current_fileset);
                        }
                    }
                }
            }

            let mut extended_fileset = current_fileset;
            extended_fileset.insert(weak_file);
            // if the parent is splittable, or if the current element already has a fileset, then that fileset should be updated
            let parent_splittable = self.parent()?.map_or(true, |p| p.element_type().splittable() != 0);
            if parent_splittable || local {
                self.0.write().file_membership = extended_fileset;
            }

            // recursively continue with the parent
            if let Some(parent) = self.parent()? {
                parent.add_to_file_restricted(file)?;
            }
        }

        Ok(())
    }

    /// remove this element from a file
    ///
    /// If the model consists of multiple files, then the set of files in
    /// which this element appears will be restricted.
    /// It may be required to also omit its parent(s), up to the next splittable point.
    ///
    /// If the element is only present in single file then an attempt to delete it will be made instead.
    /// Deleting the element fails if the element is the root AUTOSAR element, or if it is a SHORT-NAME.
    ///
    /// # Example
    /// ```
    /// # use autosar_data::*;
    /// # use std::collections::HashSet;
    /// # let model = AutosarModel::new();
    /// # let file = model.create_file("test", AutosarVersion::Autosar_00050).unwrap();
    /// # let file2 = model.create_file("test2", AutosarVersion::Autosar_00050).unwrap();
    /// # let element = model.root_element();
    /// assert!(model.files().count() > 1);
    /// element.remove_from_file(&file);
    /// ```
    ///
    /// # Errors
    ///
    ///  - [`AutosarDataError::ItemDeleted`]: The current element is in the deleted state and will be freed once the last reference is dropped
    ///  - [`AutosarDataError::ParentElementLocked`]: a parent element was locked and did not become available after waiting briefly.
    ///    The operation was aborted to avoid a deadlock, but can be retried.
    ///
    pub fn remove_from_file(&self, file: &ArxmlFile) -> Result<(), AutosarDataError> {
        let parent_splittable = self.parent()?.map_or(true, |p| p.element_type().splittable() != 0);
        if parent_splittable {
            if file.model()? == self.model()? {
                let weak_file = file.downgrade();

                // current_fileset is the set of files which contain the current element
                let (_, current_fileset) = self.file_membership()?;
                let mut restricted_fileset = current_fileset;
                restricted_fileset.remove(&weak_file);
                if restricted_fileset.is_empty() {
                    // the element will no longer be part of any file, so try to delete it
                    if let Some(parent) = self.parent()? {
                        let _ = parent.remove_sub_element(self.to_owned());
                    }
                }
                // this works even if the element was just removed
                self.0.write().file_membership = restricted_fileset;

                // update all sub elements with non-default file_membership
                let mut to_delete = Vec::new();
                for (_, subelem) in self.elements_dfs() {
                    // only need to care about those where file_membership is not empty. All other inherit from their parent
                    if !subelem.0.read().file_membership.is_empty() {
                        subelem.0.write().file_membership.remove(&weak_file);
                        // if the file_membership just went to empty, then subelem should be deleted
                        if subelem.0.read().file_membership.is_empty() {
                            to_delete.push(subelem);
                        }
                    }
                }
                // delete elements that are no longer in any file
                for delete_elem in to_delete {
                    if let Ok(Some(parent)) = delete_elem.parent() {
                        let _ = parent.remove_sub_element(delete_elem);
                    }
                }

                Ok(())
            } else {
                // adding a file from a different model is not permitted
                Err(AutosarDataError::InvalidFile)
            }
        } else {
            Err(AutosarDataError::FilesetModificationForbidden)
        }
    }

    /// Return a path that includes non-identifiable elements by their xml names
    ///
    /// This function cannot fail completely, it will always collect as much information as possible.
    /// It is intended for display in error messages.
    #[must_use]
    pub fn xml_path(&self) -> String {
        self.0.read().xml_path()
    }

    /// Find the upper and lower bound on the insert position for a new sub element
    ///
    /// If the sub element is allowed for this element given its current content, this function
    /// returns the lower and upper bound on the position the new sub element could have.
    /// If the sub element is not allowed, then an Err is returned instead.
    ///
    /// The lower and upper bounds are inclusive: lower <= (element insert pos) <= upper.
    /// In many situations lower == upper, this means there is only a single valid position.
    ///
    /// # Example
    /// ```
    /// # use autosar_data::*;
    /// # fn main() -> Result<(), AutosarDataError> {
    /// # use std::collections::HashSet;
    /// # let model = AutosarModel::new();
    /// # model.create_file("test", AutosarVersion::LATEST).unwrap();
    /// let (lbound, ubound) = model.root_element()
    ///     .calc_element_insert_range(ElementName::ArPackages, AutosarVersion::LATEST)?;
    /// model.root_element().create_sub_element_at(ElementName::ArPackages, lbound)?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// - [`AutosarDataError::ElementInsertionConflict`]: The sub element conflicts with an existing sub element
    /// - [`AutosarDataError::InvalidSubElement`]: The sub element is not valid inside this element
    pub fn calc_element_insert_range(
        &self,
        element_name: ElementName,
        version: AutosarVersion,
    ) -> Result<(usize, usize), AutosarDataError> {
        self.0.read().calc_element_insert_range(element_name, version)
    }

    /// Return the comment attachd to the element (if any)
    ///
    /// A comment directly preceding the opening tag is considered to be atached and is returned here.
    ///
    /// In the arxml text:
    /// ```xml
    ///     <!--element comment-->
    ///     <ELEMENT> ...
    /// ```
    ///
    /// # Example
    ///
    /// ```
    /// # use autosar_data::*;
    /// # use std::collections::HashSet;
    /// # let model = AutosarModel::new();
    /// # let file = model.create_file("test", AutosarVersion::LATEST).unwrap();
    /// # let element = model.root_element();
    /// let opt_comment = element.comment();
    /// ```
    #[must_use]
    pub fn comment(&self) -> Option<String> {
        self.0.read().comment.clone()
    }

    /// Set or delete the comment attached to the element
    ///
    /// Set None to remove the comment.
    ///
    /// If the new comment value contains "--", then this is replaced with "__", because "--" is forbidden inside XML comments.
    ///
    /// # Example
    ///
    /// ```
    /// # use autosar_data::*;
    /// # use std::collections::HashSet;
    /// # let model = AutosarModel::new();
    /// # let file = model.create_file("test", AutosarVersion::LATEST).unwrap();
    /// # let element = model.root_element();
    /// # let string = "".to_string();
    /// element.set_comment(Some(string));
    /// ```
    pub fn set_comment(&self, mut opt_comment: Option<String>) {
        if let Some(comment) = &mut opt_comment {
            // make sure the comment we store never contains "--" as this is forbidden by the w3 xml specification
            if comment.contains("--") {
                *comment = comment.replace("--", "__");
            }
        }
        self.0.write().comment = opt_comment;
    }

    /// find the minumum version of all arxml files which contain this element
    ///
    /// Typically this reduces to finding out which single file contains the element and returning this version.
    ///
    /// # Example
    ///
    /// ```
    /// # use autosar_data::*;
    /// # use std::collections::HashSet;
    /// # let model = AutosarModel::new();
    /// let file1 = model.create_file("file1", AutosarVersion::LATEST).unwrap();
    /// let file2 = model.create_file("file2", AutosarVersion::Autosar_4_3_0).unwrap();
    /// let version = model.root_element().min_version().unwrap();
    /// assert_eq!(version, AutosarVersion::Autosar_4_3_0);
    /// ```
    ///
    /// # Errors
    ///
    ///  - [`AutosarDataError::ItemDeleted`]: The current element is in the deleted state and will be freed once the last reference is dropped
    ///  - [`AutosarDataError::ParentElementLocked`]: a parent element was locked and did not become available after waiting briefly.
    ///    The operation was aborted to avoid a deadlock, but can be retried.
    ///  - [`AutosarDataError::NoFilesInModel`]: The operation cannot be completed because the model does not contain any files
    pub fn min_version(&self) -> Result<AutosarVersion, AutosarDataError> {
        let (_, files) = self.file_membership()?;
        let mut ver = AutosarVersion::LATEST;
        for f in files.iter().filter_map(WeakArxmlFile::upgrade) {
            if f.version() < ver {
                ver = f.version();
            }
        }
        Ok(ver)
    }
}

impl Ord for Element {
    /// compare the content of two elements
    ///
    /// This function compares the content of two elements, returning a cmp::Ordering value.
    /// The purpose of this function is to allow sorting of elements based on their content.
    ///
    /// The comparison is performed in the following order:
    /// 1. Element name
    /// 2. Index (if present)
    /// 3. Item name (if present)
    /// 4. Definition reference (if present)
    /// 5. DEST attribute (if present)
    /// 6. Content of the element
    /// 7. Attributes of the element
    ///
    /// If the comparison returns `Ordering::Equal`, then the two elements are identical, but this does not imply that they are the same object.
    ///
    /// # Example
    /// ```
    /// # use autosar_data::*;
    /// # let model = AutosarModel::new();
    /// # let file = model.create_file("test", AutosarVersion::LATEST).unwrap();
    /// # let element1 = model.root_element();
    /// # let element2 = model.root_element();
    /// let ordering = element1.cmp(&element2);
    /// ```
    fn cmp(&self, other: &Element) -> std::cmp::Ordering {
        // Sort by the element name first. This test prevents the other comparisons from being performed when they don't make sense.
        match self.element_name().to_str().cmp(other.element_name().to_str()) {
            Ordering::Equal => {}
            other => return other,
        }

        // if both elements have an index, then compare the index; if only one has an index, then it comes first
        // if neither has an index, then continue and compare other criteria
        let index1 = self
            .get_sub_element(ElementName::Index)
            .and_then(|indexelem| indexelem.character_data())
            .and_then(|cdata| cdata.parse_integer::<u64>());
        let index2 = other
            .get_sub_element(ElementName::Index)
            .and_then(|indexelem| indexelem.character_data())
            .and_then(|cdata| cdata.parse_integer::<u64>());
        match (index1, index2) {
            (Some(idx1), Some(idx2)) => {
                let result = idx1.cmp(&idx2);
                if result != Ordering::Equal {
                    return result;
                }
            }
            (Some(_), None) => return std::cmp::Ordering::Less,
            (None, Some(_)) => return std::cmp::Ordering::Greater,
            (None, None) => {}
        }

        // sort by item name if present
        if let (Some(name1), Some(name2)) = (self.item_name(), other.item_name()) {
            // both items have a name - try to decompose the name into a base and an index
            // this allows for a more natural sorting of indexed items (e.g. "item2" < "item10")
            if let (Some((base1, idx1)), Some((base2, idx2))) =
                (decompose_item_name(&name1), decompose_item_name(&name2))
            {
                if base1 == base2 {
                    let result = idx1.cmp(&idx2);
                    if result != Ordering::Equal {
                        return result;
                    }
                }
            }
            // if the decomposition fails, then just compare the full item names
            let result = name1.cmp(&name2);
            if result != Ordering::Equal {
                return result;
            }
        }

        // for BSW values: compare the definition references
        let definition1 = self
            .get_sub_element(ElementName::DefinitionRef)
            .and_then(|defref| defref.character_data())
            .and_then(|cdata| cdata.string_value());
        let definition2 = other
            .get_sub_element(ElementName::DefinitionRef)
            .and_then(|defref| defref.character_data())
            .and_then(|cdata| cdata.string_value());
        if let (Some(def1), Some(def2)) = (definition1, definition2) {
            let result = def1.cmp(&def2);
            if result != Ordering::Equal {
                return result;
            }
        }

        // for references: compare the DEST attribute
        let dest1 = self
            .attribute_value(AttributeName::Dest)
            .and_then(|cdata| cdata.enum_value());
        let dest2 = other
            .attribute_value(AttributeName::Dest)
            .and_then(|cdata| cdata.enum_value());
        match (dest1, dest2) {
            (Some(dest1), Some(dest2)) => {
                let result = dest1.to_str().cmp(dest2.to_str());
                if result != Ordering::Equal {
                    return result;
                }
            }
            (Some(_), None) => return std::cmp::Ordering::Less,
            (None, Some(_)) => return std::cmp::Ordering::Greater,
            (None, None) => {}
        }

        // if all else fails, compare the content of the elements
        let locked_self = self.0.read();
        let locked_other = other.0.read();
        locked_self
            .content
            .cmp(&locked_other.content)
            .then(locked_self.attributes.cmp(&locked_other.attributes))
    }
}

impl PartialOrd for Element {
    fn partial_cmp(&self, other: &Element) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

/// decompose an item name into a base name and an index
/// The index is expected to be a decimal number at the end of the string
///
/// E.g. "item123" -> ("item", 123)
fn decompose_item_name(name: &str) -> Option<(String, u64)> {
    let bytestr = name.as_bytes();
    let mut pos = bytestr.len();
    while pos > 0 && bytestr[pos - 1].is_ascii_digit() {
        pos -= 1;
    }
    if let Ok(index) = name[pos..].parse() {
        Some((name[0..pos].to_owned(), index))
    } else {
        None
    }
}

// a helper that provides compact debug output for the content of an element
struct ElementContentFormatter<'a>(&'a SmallVec<[ElementContent; 4]>);
impl std::fmt::Debug for ElementContentFormatter<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut list_fmt = f.debug_list();
        for item in self.0.iter() {
            match item {
                ElementContent::Element(elem) => list_fmt.entry(&elem.element_name()),
                ElementContent::CharacterData(cdata) => list_fmt.entry(&cdata),
            };
        }
        list_fmt.finish()
    }
}

// A custom type is needed in order to print a custom value in the Debug implementation without double quoting
struct DebugDisplay<'a>(&'a str);
impl std::fmt::Debug for DebugDisplay<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.0)
    }
}

// custom debug implementation: print the content instead of only showing the pointer of the Arc
impl std::fmt::Debug for Element {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let elem = self.0.read();
        let mut dbgstruct = f.debug_struct("Element");
        if let Some(name) = elem.item_name() {
            dbgstruct.field("name", &name);
        }
        dbgstruct.field("elemname", &elem.elemname);
        dbgstruct.field("elemtype", &elem.elemtype);
        dbgstruct.field("parent", &elem.parent);
        dbgstruct.field("content", &ElementContentFormatter(&elem.content));
        dbgstruct.field("attributes", &elem.attributes);
        // only print the file membership if the element is splittable
        // elements that are not splittable may not modify their file membership
        if elem.elemtype.splittable() != 0 {
            if elem.file_membership.is_empty() {
                dbgstruct.field("file_membership", &DebugDisplay("(inherited)"));
            } else {
                dbgstruct.field("file_membership", &elem.file_membership);
            }
        }
        dbgstruct.finish()
    }
}

impl PartialEq for Element {
    fn eq(&self, other: &Self) -> bool {
        Arc::as_ptr(&self.0) == Arc::as_ptr(&other.0)
    }
}

impl Eq for Element {}

impl Hash for Element {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        state.write_usize(Arc::as_ptr(&self.0) as usize);
    }
}

impl std::fmt::Debug for WeakElement {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if let Some(elem) = self.upgrade() {
            // write!(f, "Element:WeakRef {:p}", Arc::as_ptr(&elem.0));
            f.write_fmt(format_args!("Element:WeakRef ({})", elem.element_name()))
        } else {
            f.write_fmt(format_args!("Element:WeakRef {:p} (invalid)", Weak::as_ptr(&self.0)))
        }
    }
}

impl WeakElement {
    /// try to get a strong reference to the [Element]
    pub fn upgrade(&self) -> Option<Element> {
        Weak::upgrade(&self.0).map(Element)
    }
}

impl PartialEq for WeakElement {
    fn eq(&self, other: &Self) -> bool {
        Weak::as_ptr(&self.0) == Weak::as_ptr(&other.0)
    }
}

impl Eq for WeakElement {}

impl Hash for WeakElement {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        state.write_usize(Weak::as_ptr(&self.0) as usize);
    }
}

impl ElementContent {
    /// returns the element contained inside this `ElementContent`, or None if the content is `CharacterData`
    #[must_use]
    pub fn unwrap_element(&self) -> Option<Element> {
        if let ElementContent::Element(element) = self {
            Some(element.clone())
        } else {
            None
        }
    }

    /// returns the `CharacterData` inside this `ElementContent`, or None if the content is an Element
    #[must_use]
    pub fn unwrap_cdata(&self) -> Option<CharacterData> {
        if let ElementContent::CharacterData(cdata) = self {
            Some(cdata.clone())
        } else {
            None
        }
    }
}

// custom debug implementation: skip printing any content, since the content is only "WeakRef(0x...)"
impl std::fmt::Debug for ElementOrModel {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ElementOrModel::Element(_) => f.write_str("Element"),
            ElementOrModel::Model(_) => f.write_str("Model"),
            ElementOrModel::None => f.write_str("None/Invalid"),
        }
    }
}

// custom debug implementation: skip printing the name of the wrapper-enum and directly show the content
impl std::fmt::Debug for ElementContent {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ElementContent::Element(elem) => elem.fmt(f),
            ElementContent::CharacterData(cdata) => cdata.fmt(f),
        }
    }
}

#[cfg(test)]
mod test {
    use crate::*;
    use std::ffi::OsString;

    const BASIC_AUTOSAR_FILE: &str = r#"<?xml version="1.0" encoding="utf-8"?>
    <AUTOSAR xsi:schemaLocation="http://autosar.org/schema/r4.0 AUTOSAR_00050.xsd" xmlns="http://autosar.org/schema/r4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
        <AR-PACKAGES>
            <AR-PACKAGE>
                <SHORT-NAME>TestPackage</SHORT-NAME>
            </AR-PACKAGE>
        </AR-PACKAGES>
    </AUTOSAR>"#;

    #[test]
    fn element_creation() {
        let model = AutosarModel::new();
        model
            .load_buffer(BASIC_AUTOSAR_FILE.as_bytes(), OsString::from("test.arxml"), true)
            .unwrap();
        let el_autosar = model.root_element();
        let el_ar_package = model.get_element_by_path("/TestPackage").unwrap();

        let el_elements = el_ar_package.create_sub_element(ElementName::Elements).unwrap();
        let el_compu_method = el_elements
            .create_named_sub_element(ElementName::CompuMethod, "TestCompuMethod")
            .unwrap();
        el_elements
            .create_named_sub_element(ElementName::CompuMethod, "TestCompuMethod2")
            .unwrap();
        el_elements
            .create_named_sub_element(ElementName::CompuMethod, "TestCompuMethod3")
            .unwrap();
        // elements with duplicate names are not allowed
        assert!(el_elements
            .create_named_sub_element(ElementName::CompuMethod, "TestCompuMethod3")
            .is_err());

        let count = el_elements.sub_elements().count();
        assert_eq!(count, 3);
        assert_eq!(count, el_elements.content_item_count());

        // inserting another COMPU-METHOD into ELEMENTS hould be allowed at any position
        let (start_pos, end_pos) = el_elements
            .0
            .read()
            .calc_element_insert_range(ElementName::CompuMethod, AutosarVersion::Autosar_00050)
            .unwrap();
        assert_eq!(start_pos, 0);
        assert_eq!(end_pos, 3); // upper limit is 3 since there are currently 3 elements

        // check if create_named_sub_element correctly registered the element in the hashmap so that it can be found
        let el_compu_method_test = model.get_element_by_path("/TestPackage/TestCompuMethod").unwrap();
        assert_eq!(el_compu_method, el_compu_method_test);

        // create more hierarchy
        let el_compu_internal_to_phys = el_compu_method
            .create_sub_element(ElementName::CompuInternalToPhys)
            .unwrap();
        let el_compu_scales = el_compu_internal_to_phys
            .create_sub_element(ElementName::CompuScales)
            .unwrap();
        let el_compu_scale = el_compu_scales.create_sub_element(ElementName::CompuScale).unwrap();
        el_compu_scale.create_sub_element(ElementName::Desc).unwrap();

        // SHORT-LABEL should only be allowed before DESC inside COMPU-SCALE
        let (start_pos, end_pos) = el_compu_scale
            .calc_element_insert_range(ElementName::ShortLabel, AutosarVersion::Autosar_00050)
            .unwrap();
        assert_eq!(start_pos, 0);
        assert_eq!(end_pos, 0);

        // COMPU-CONST should only be allowed after DESC inside COMPU-SCALE
        let (start_pos, end_pos) = el_compu_scale
            .calc_element_insert_range(ElementName::CompuConst, AutosarVersion::Autosar_00050)
            .unwrap();
        assert_eq!(start_pos, 1);
        assert_eq!(end_pos, 1);

        // create COMPU-RATIONAL-COEFFS in COMPU-SCALE. It's presence excludes COMPU-CONST from being inserted
        el_compu_scale
            .create_sub_element(ElementName::CompuRationalCoeffs)
            .unwrap();
        // try to insert COMPU-CONST anyway
        let result = el_compu_scale.calc_element_insert_range(ElementName::CompuConst, AutosarVersion::Autosar_00050);
        assert!(result.is_err());
        // it is also not possible to create a second COMPU-RATIONAL-COEFFS
        let result =
            el_compu_scale.calc_element_insert_range(ElementName::CompuRationalCoeffs, AutosarVersion::Autosar_00050);
        assert!(result.is_err());

        // creating a sub element at an invalid position fails
        assert!(el_elements
            .create_named_sub_element_at(ElementName::System, "System", 99)
            .is_err());
        assert!(el_autosar.create_sub_element_at(ElementName::AdminData, 99).is_err());

        // an identifiable element cannot be created without a name
        assert!(el_elements.create_sub_element(ElementName::System).is_err());
        // the name for an identifiable element must be valid according to the rules
        assert!(el_elements.create_named_sub_element(ElementName::System, "").is_err());
        assert!(el_elements
            .create_named_sub_element(ElementName::System, "abc def")
            .is_err());

        // a non-identifiable element cannot be created with a name
        assert!(el_autosar
            .create_named_sub_element(ElementName::AdminData, "AdminData")
            .is_err());

        // only valid sub-elements can be created
        assert!(el_autosar
            .create_named_sub_element(ElementName::Autosar, "Autosar")
            .is_err());
        assert!(el_autosar
            .create_named_sub_element_at(ElementName::Autosar, "Autosar", 0)
            .is_err());
        assert!(el_autosar.create_sub_element(ElementName::Autosar).is_err());
        assert!(el_autosar.create_sub_element_at(ElementName::Autosar, 0).is_err());

        // creating a sub element fails when any parent element in the hierarchy is locked for writing
        let el_autosar_locked = el_autosar.0.write();
        assert!(el_elements
            .create_named_sub_element(ElementName::System, "System")
            .is_err());
        assert!(el_elements
            .create_named_sub_element_at(ElementName::System, "System", 0)
            .is_err());
        assert!(el_autosar.create_sub_element(ElementName::AdminData).is_err());
        assert!(el_autosar.create_sub_element_at(ElementName::AdminData, 0).is_err());
        drop(el_autosar_locked);
    }

    #[test]
    fn parent() {
        let model = AutosarModel::new();
        model.create_file("test.arxml", AutosarVersion::Autosar_00050).unwrap();
        let el_autosar = model.root_element();
        let el_ar_packages = el_autosar.create_sub_element(ElementName::ArPackages).unwrap();
        let el_ar_package = el_ar_packages
            .create_named_sub_element(ElementName::ArPackage, "Package")
            .unwrap();
        let el_elements = el_ar_package.create_sub_element(ElementName::Elements).unwrap();
        let el_system = el_elements
            .create_named_sub_element(ElementName::System, "Sys")
            .unwrap();
        let el_fibex = el_system.create_sub_element(ElementName::FibexElements).unwrap();
        let el_fibex_cond = el_fibex
            .create_sub_element(ElementName::FibexElementRefConditional)
            .unwrap();

        let parent = el_fibex_cond.parent().unwrap().unwrap();
        assert_eq!(parent, el_fibex);
        let named_parent = el_fibex_cond.named_parent().unwrap().unwrap();
        assert_eq!(named_parent, el_system);

        let named_parent = el_system.named_parent().unwrap().unwrap();
        assert_eq!(named_parent, el_ar_package);

        let named_parent = el_autosar.named_parent().unwrap();
        assert!(named_parent.is_none());

        // trying to get the named parent of a removed element should fail
        el_autosar.remove_sub_element(el_ar_packages).unwrap();
        assert!(el_ar_package.named_parent().is_err());
    }

    #[test]
    fn element_rename() {
        let model = AutosarModel::new();
        model.create_file("test.arxml", AutosarVersion::Autosar_00050).unwrap();
        let el_autosar = model.root_element();
        let el_ar_packages = el_autosar.create_sub_element(ElementName::ArPackages).unwrap();
        let el_ar_package = el_ar_packages
            .create_named_sub_element(ElementName::ArPackage, "Package")
            .unwrap();
        let el_elements = el_ar_package.create_sub_element(ElementName::Elements).unwrap();
        let el_can_cluster = el_elements
            .create_named_sub_element_at(ElementName::CanCluster, "CanCluster", 0)
            .unwrap();
        let el_can_physical_channel = el_can_cluster
            .create_sub_element(ElementName::CanClusterVariants)
            .and_then(|ccv| ccv.create_sub_element(ElementName::CanClusterConditional))
            .and_then(|ccc| ccc.create_sub_element(ElementName::PhysicalChannels))
            .and_then(|pc| pc.create_named_sub_element(ElementName::CanPhysicalChannel, "CanPhysicalChannel"))
            .unwrap();

        let el_can_frame_triggering = el_can_physical_channel
            .create_sub_element_at(ElementName::FrameTriggerings, 1)
            .and_then(|ft| ft.create_named_sub_element(ElementName::CanFrameTriggering, "CanFrameTriggering"))
            .unwrap();

        let el_ar_package2 = el_ar_packages
            .create_named_sub_element(ElementName::ArPackage, "Package2")
            .unwrap();
        let el_can_frame = el_ar_package2
            .create_sub_element(ElementName::Elements)
            .and_then(|e| e.create_named_sub_element(ElementName::CanFrame, "CanFrame"))
            .unwrap();
        let el_frame_ref = el_can_frame_triggering
            .create_sub_element(ElementName::FrameRef)
            .unwrap();
        let _ = el_frame_ref.set_reference_target(&el_can_frame);

        // initial value of the reference
        let refstr = el_frame_ref.character_data().unwrap().string_value().unwrap();
        assert_eq!(refstr, "/Package2/CanFrame");

        // empty name, renaming should fail
        let result = el_ar_package.set_item_name("");
        assert!(result.is_err());

        // rename 1. package
        el_ar_package.set_item_name("NewPackage").unwrap();
        // setting the current name again - should be a no-op
        el_ar_package.set_item_name("NewPackage").unwrap();

        // duplicate name for Package2, renaming should fail
        let result = el_ar_package2.set_item_name("NewPackage");
        assert!(result.is_err());

        // rename package 2 with a valid name
        el_ar_package2.set_item_name("OtherPackage").unwrap();
        let refstr = el_frame_ref.character_data().unwrap().string_value().unwrap();
        assert_eq!(refstr, "/OtherPackage/CanFrame");

        // make sure get_reference_target still works after renaming
        let el_can_frame2 = el_frame_ref.get_reference_target().unwrap();
        assert_eq!(el_can_frame, el_can_frame2);

        // rename the CanFrame as well
        el_can_frame.set_item_name("CanFrame_renamed").unwrap();
        let refstr = el_frame_ref.character_data().unwrap().string_value().unwrap();
        assert_eq!(refstr, "/OtherPackage/CanFrame_renamed");

        // invalid element
        assert!(el_autosar.set_item_name("Autosar").is_err());

        // invalid preconditions
        let el_autosar_locked = el_autosar.0.write();
        // fails because a parent element is locked
        assert!(el_ar_package.set_item_name("TestPackage_renamed").is_err());
        drop(el_autosar_locked);
        drop(model);
        // the reference count of model is now zero, so set_item_name can't get a new reference to it
        assert!(el_ar_package.set_item_name("TestPackage_renamed").is_err());
    }

    #[test]
    fn element_copy() {
        let model = AutosarModel::new();
        model
            .load_buffer(BASIC_AUTOSAR_FILE.as_bytes(), OsString::from("test.arxml"), true)
            .unwrap();
        model.create_file("test", AutosarVersion::LATEST).unwrap();
        let el_ar_package = model.get_element_by_path("/TestPackage").unwrap();
        el_ar_package
            .set_attribute(AttributeName::Uuid, CharacterData::String("0123456".to_string()))
            .unwrap();
        let el_elements = el_ar_package.create_sub_element(ElementName::Elements).unwrap();
        let el_compu_method = el_elements
            .create_named_sub_element(ElementName::CompuMethod, "CompuMethod")
            .unwrap();
        el_elements
            .create_named_sub_element(ElementName::DdsServiceInstanceToMachineMapping, "ApItem")
            .unwrap();
        el_elements
            .create_named_sub_element(ElementName::AclObjectSet, "AclObjectSet")
            .and_then(|el| el.create_sub_element(ElementName::DerivedFromBlueprintRefs))
            .and_then(|el| el.create_sub_element(ElementName::DerivedFromBlueprintRef))
            .and_then(|el| {
                el.set_attribute(
                    AttributeName::Dest,
                    CharacterData::Enum(EnumItem::AbstractImplementationDataType),
                )
            })
            .unwrap();
        el_elements
            .create_named_sub_element(ElementName::System, "System")
            .and_then(|el| el.create_sub_element(ElementName::FibexElements))
            .and_then(|el| el.create_sub_element(ElementName::FibexElementRefConditional))
            .and_then(|el| el.create_sub_element(ElementName::FibexElementRef))
            .and_then(|el| el.set_character_data("/invalid"))
            .unwrap();

        let project2 = AutosarModel::new();
        project2
            .create_file("test.arxml", AutosarVersion::Autosar_00044)
            .unwrap();

        // it should not be possible to create an AR-PACKAGE element directly in the AUTOSAR element by copying data
        let result = project2.root_element().create_copied_sub_element(&el_ar_package);
        assert!(result.is_err());

        // create an AR-PACKAGES element and copy the data there. This should succeed.
        // the copied data shoud contain the COMPU-METHOD, but not the DDS-SERVICE-INSTANCE-TO-MACHINE-MAPPING
        // because the latter was specified in Adaptive 18-03 (Autosar_00045) and is not valid in Autosar_00044
        let el_ar_packages2 = project2
            .root_element()
            .create_sub_element(ElementName::ArPackages)
            .unwrap();
        el_ar_packages2.create_copied_sub_element(&el_ar_package).unwrap();

        // it should be possible to look up the copied compu-method by its path
        let el_compu_method_2 = project2.get_element_by_path("/TestPackage/CompuMethod").unwrap();

        // the copy should not refer to the same memory as the original
        assert_ne!(el_compu_method, el_compu_method_2);
        // the copy should serialize to exactly the same string as the original
        assert_eq!(el_compu_method.serialize(), el_compu_method_2.serialize());

        // verify that the DDS-SERVICE-INSTANCE-TO-MACHINE-MAPPING element was not copied
        let result = project2.get_element_by_path("/TestPackage/ApItem");
        assert!(result.is_none());

        // make sure the element ordering constraints are considered when copying with the _at() variant
        let el_ar_package2 = el_ar_packages2
            .create_named_sub_element(ElementName::ArPackage, "Package2")
            .unwrap();
        let result = el_ar_package2.create_copied_sub_element_at(&el_elements, 0);
        assert!(result.is_err()); // position 0 is already used by the SHORT-NAME
        let el_elements2 = el_ar_package2.create_sub_element(ElementName::Elements).unwrap();
        let result = el_elements2.create_copied_sub_element_at(&el_compu_method, 99);
        assert!(result.is_err()); // position 99 is not valid
        let result = el_elements2.create_copied_sub_element_at(&el_compu_method, 0);
        assert!(result.is_ok()); // position 0 is valid

        // can't copy an element that is not a valid sub element here
        let result = el_ar_package2.create_copied_sub_element_at(&el_compu_method, 0);
        assert!(result.is_err()); // COMPU-METHOS id not a valid sub-element of AR-PACKAGE
    }

    #[test]
    fn element_copy_loop() {
        let model = AutosarModel::new();
        model.create_file("test.arxml", AutosarVersion::Autosar_00050).unwrap();
        let el_autosar = model.root_element();
        let el_ar_packages = el_autosar.create_sub_element(ElementName::ArPackages).unwrap();
        let el_ar_package = el_ar_packages
            .create_named_sub_element(ElementName::ArPackage, "Pkg")
            .unwrap();

        let result = el_ar_package.create_copied_sub_element(&el_ar_packages);
        assert!(result.is_err());

        // copying an element into itself should return an error and should not deadlock
        let result = el_ar_package.create_copied_sub_element(&el_ar_package);
        assert!(result.is_err());
        let result = el_ar_package.create_copied_sub_element_at(&el_ar_package, 0);
        assert!(result.is_err());
    }

    #[test]
    fn element_deletion() {
        let model = AutosarModel::new();
        model
            .load_buffer(BASIC_AUTOSAR_FILE.as_bytes(), OsString::from("test.arxml"), true)
            .unwrap();
        let el_ar_package = model.get_element_by_path("/TestPackage").unwrap();
        let el_short_name = el_ar_package.get_sub_element(ElementName::ShortName).unwrap();
        el_ar_package
            .create_sub_element(ElementName::Elements)
            .and_then(|el| el.create_named_sub_element(ElementName::System, "System"))
            .and_then(|el| el.create_sub_element(ElementName::FibexElements))
            .and_then(|el| el.create_sub_element(ElementName::FibexElementRefConditional))
            .and_then(|el| el.create_sub_element(ElementName::FibexElementRef))
            .and_then(|el| el.set_character_data("/invalid"))
            .unwrap();

        // removing the SHORT-NAME of an identifiable element is forbidden
        let result = el_ar_package.remove_sub_element(el_short_name);
        if let Err(AutosarDataError::ShortNameRemovalForbidden) = result {
            // correct
        } else {
            panic!("Removing the SHORT-NAME was not prohibited");
        }
        let el_ar_package_clone = el_ar_package.clone();
        let el_ar_packages = el_ar_package.parent().unwrap().unwrap();
        let result = el_ar_packages.remove_sub_element(el_ar_package);
        // deleting identifiable elements should also cause the cached references to them to be removed
        assert_eq!(model.0.read().identifiables.len(), 0);
        assert!(result.is_ok());

        // alternative: remove_sub_element_kind
        el_ar_packages
            .create_named_sub_element(ElementName::ArPackage, "SecondPackage")
            .unwrap();
        assert_eq!(el_ar_packages.content_item_count(), 1);
        let result = el_ar_packages.remove_sub_element_kind(ElementName::ArPackage);
        assert!(result.is_ok());
        assert_eq!(el_ar_packages.content_item_count(), 0);
        let result = el_ar_packages.remove_sub_element_kind(ElementName::ArPackage);
        assert!(result.is_err());

        // the removed element may still exist if there were other references to it, but it is no longer usable
        let result = el_ar_package_clone.parent();
        assert!(matches!(result, Err(AutosarDataError::ItemDeleted)));
        let result = el_ar_package_clone.model();
        assert!(matches!(result, Err(AutosarDataError::ItemDeleted)));
        assert_eq!(el_ar_package_clone.position(), None);
    }

    #[test]
    fn element_position() {
        let model = AutosarModel::new();
        model.create_file("test.arxml", AutosarVersion::Autosar_00050).unwrap();
        let el_autosar = model.root_element();
        let el_ar_packages = el_autosar.create_sub_element(ElementName::ArPackages).unwrap();
        let el_ar_package1 = el_ar_packages
            .create_named_sub_element(ElementName::ArPackage, "Pkg1")
            .unwrap();
        let el_ar_package2 = el_ar_packages
            .create_named_sub_element(ElementName::ArPackage, "Pkg2")
            .unwrap();
        let el_ar_package3 = el_ar_packages
            .create_named_sub_element(ElementName::ArPackage, "Pkg3")
            .unwrap();

        assert_eq!(el_ar_packages.content_item_count(), 3);
        assert_eq!(el_ar_package2.position().unwrap(), 1);
        assert_eq!(el_ar_packages.get_sub_element_at(1).unwrap(), el_ar_package2);
        assert_eq!(el_ar_package3.position().unwrap(), 2);
        assert_eq!(el_ar_packages.get_sub_element_at(2).unwrap(), el_ar_package3);

        // there is no subelement at position 1
        let nonexistent = el_ar_package1.get_sub_element_at(1);
        assert_eq!(nonexistent, None);
    }

    #[test]
    fn element_type() {
        let model = AutosarModel::new();
        model.create_file("test.arxml", AutosarVersion::Autosar_00050).unwrap();
        let el_autosar = model.root_element();

        assert_eq!(el_autosar.element_type(), ElementType::ROOT);
    }

    #[test]
    fn content_type() {
        let model = AutosarModel::new();
        model.create_file("test.arxml", AutosarVersion::Autosar_00050).unwrap();
        let el_autosar = model.root_element();
        let el_ar_package = el_autosar
            .create_sub_element(ElementName::ArPackages)
            .and_then(|ar_pkgs| ar_pkgs.create_named_sub_element(ElementName::ArPackage, "Package"))
            .unwrap();
        let el_short_name = el_ar_package.get_sub_element(ElementName::ShortName).unwrap();

        let el_l4 = el_ar_package
            .create_sub_element(ElementName::LongName)
            .and_then(|ln| ln.create_sub_element(ElementName::L4))
            .unwrap();

        let el_elements = el_ar_package.create_sub_element(ElementName::Elements).unwrap();
        let el_debounce_algo = el_elements
            .create_named_sub_element(ElementName::DiagnosticContributionSet, "DCS")
            .and_then(|dcs| dcs.create_sub_element(ElementName::CommonProperties))
            .and_then(|cp| cp.create_sub_element(ElementName::DiagnosticCommonPropsVariants))
            .and_then(|dcpv| dcpv.create_sub_element(ElementName::DiagnosticCommonPropsConditional))
            .and_then(|dcpc| dcpc.create_sub_element(ElementName::DebounceAlgorithmPropss))
            .and_then(|dap| dap.create_named_sub_element(ElementName::DiagnosticDebounceAlgorithmProps, "ddap"))
            .and_then(|ddap| ddap.create_sub_element(ElementName::DebounceAlgorithm))
            .unwrap();

        assert_eq!(el_autosar.element_type().content_mode(), ContentMode::Sequence);
        assert_eq!(el_autosar.content_type(), ContentType::Elements);
        assert_eq!(el_elements.element_type().content_mode(), ContentMode::Bag);
        assert_eq!(el_elements.content_type(), ContentType::Elements);
        assert_eq!(el_debounce_algo.element_type().content_mode(), ContentMode::Choice);
        assert_eq!(el_debounce_algo.content_type(), ContentType::Elements);
        assert_eq!(el_short_name.element_type().content_mode(), ContentMode::Characters);
        assert_eq!(el_short_name.content_type(), ContentType::CharacterData);
        assert_eq!(el_l4.element_type().content_mode(), ContentMode::Mixed);
        assert_eq!(el_l4.content_type(), ContentType::Mixed);
    }

    #[test]
    fn attributes() {
        let model = AutosarModel::new();
        model
            .load_buffer(BASIC_AUTOSAR_FILE.as_bytes(), OsString::from("test.arxml"), true)
            .unwrap();
        model.create_file("test", AutosarVersion::LATEST).unwrap();
        let el_autosar = model.root_element();
        let el_ar_packages = el_autosar.get_sub_element(ElementName::ArPackages).unwrap();

        let count = el_autosar.attributes().count();
        assert_eq!(count, 3);

        // set the attribute S on the element AUTOSAR
        el_autosar
            .set_attribute(AttributeName::S, CharacterData::String(String::from("something")))
            .unwrap();

        // AUTOSAR has no DEST attribute, so this should fail
        assert!(el_autosar
            .set_attribute(AttributeName::Dest, CharacterData::String(String::from("something")))
            .is_err());

        // The attribute S exists and is optional, so it can be removed
        let result = el_autosar.remove_attribute(AttributeName::S);
        assert!(result);

        // the attribute xmlns is required and cannot be removed
        let result = el_autosar.remove_attribute(AttributeName::xmlns);
        assert!(!result);

        // the attribute ACCESSKEY does not exist in the element AUTOSAR and cannot be removed
        let result = el_autosar.remove_attribute(AttributeName::Accesskey);
        assert!(!result);

        // the attribute T is permitted on AUTOSAR and the string is a valid value
        el_autosar
            .set_attribute_string(AttributeName::T, "2022-01-31T13:00:59Z")
            .unwrap();

        // update an existing attribute
        el_autosar
            .set_attribute_string(AttributeName::T, "2022-01-31T14:00:59Z")
            .unwrap();

        // fail set an attribute due to data validation
        assert!(el_autosar.set_attribute_string(AttributeName::T, "abc").is_err());

        // can't set unknown attributes with set_attribute_string
        assert!(el_ar_packages
            .set_attribute_string(AttributeName::xmlns, "abc")
            .is_err());

        // directly return an attribute as a string
        let xmlns = el_autosar
            .attribute_value(AttributeName::xmlns)
            .map(|cdata| cdata.to_string())
            .unwrap();
        assert_eq!(xmlns, "http://autosar.org/schema/r4.0".to_string());

        // attribute operation fails when a parent element is locked for writing
        let lock = el_autosar.0.write();
        assert!(el_ar_packages
            .set_attribute(AttributeName::Uuid, CharacterData::String(String::from("1234")))
            .is_err());
        assert!(el_ar_packages
            .set_attribute_string(AttributeName::Uuid, "1234")
            .is_err());
        drop(lock);
    }

    #[test]
    fn mixed_content() {
        let model = AutosarModel::new();
        model
            .load_buffer(BASIC_AUTOSAR_FILE.as_bytes(), OsString::from("test.arxml"), true)
            .unwrap();
        let el_ar_package = model.get_element_by_path("/TestPackage").unwrap();
        let el_long_name = el_ar_package.create_sub_element(ElementName::LongName).unwrap();
        assert_eq!(el_long_name.content_type(), ContentType::Elements);
        let el_l_4 = el_long_name.create_sub_element(ElementName::L4).unwrap();
        assert_eq!(el_l_4.content_type(), ContentType::Mixed);

        el_l_4.create_sub_element(ElementName::E).unwrap();
        el_l_4.insert_character_content_item("foo", 1).unwrap();
        el_l_4.create_sub_element(ElementName::Sup).unwrap();
        el_l_4.insert_character_content_item("bar", 0).unwrap();
        assert_eq!(el_l_4.content().count(), 4);

        // character data item "foo" is now in position 2 and gets removed
        assert!(el_l_4.remove_character_content_item(2).is_ok());
        assert_eq!(el_l_4.content().count(), 3);
        // character data item "bar" should be in postion 0
        let item = el_l_4.content().next().unwrap();
        if let ElementContent::CharacterData(CharacterData::String(content)) = item {
            assert_eq!(content, "bar");
        } else {
            panic!("unexpected content in <L-4>: {item:?}");
        }
    }

    #[test]
    fn move_element_position() {
        // move an element to a different position within its parent
        let model = AutosarModel::new();
        model.create_file("test.arxml", AutosarVersion::Autosar_00050).unwrap();
        let el_autosar = model.root_element();
        let el_ar_packages = el_autosar.create_sub_element(ElementName::ArPackages).unwrap();
        let pkg1 = el_ar_packages
            .create_named_sub_element(ElementName::ArPackage, "Pkg1")
            .unwrap();
        let pkg2 = el_ar_packages
            .create_named_sub_element(ElementName::ArPackage, "Pkg2")
            .unwrap();
        let pkg3 = el_ar_packages
            .create_named_sub_element(ElementName::ArPackage, "Pkg3")
            .unwrap();

        // "moving" an element inside its parent without actually giving a position is a no-op
        el_ar_packages.move_element_here(&pkg3).unwrap();

        // moving to an invalid position fails
        assert!(el_ar_packages.move_element_here_at(&pkg1, 99).is_err());
        assert!(el_ar_packages.move_element_here_at(&pkg1, 3).is_err()); // special boundary case

        // move an element forward
        el_ar_packages.move_element_here_at(&pkg2, 0).unwrap();
        // move an element backward
        el_ar_packages.move_element_here_at(&pkg1, 2).unwrap();
        // check the new ordering
        let mut packages_iter = el_ar_packages.sub_elements();
        assert_eq!(packages_iter.next().unwrap(), pkg2);
        assert_eq!(packages_iter.next().unwrap(), pkg3);
        assert_eq!(packages_iter.next().unwrap(), pkg1);

        // moving elements should also work with mixed content
        let el_l_4 = pkg1
            .create_sub_element(ElementName::LongName)
            .and_then(|el| el.create_sub_element(ElementName::L4))
            .unwrap();
        el_l_4.create_sub_element(ElementName::E).unwrap();
        el_l_4.insert_character_content_item("foo", 1).unwrap();
        let el_sup = el_l_4.create_sub_element(ElementName::Sup).unwrap();
        el_l_4.insert_character_content_item("bar", 0).unwrap();
        el_l_4.move_element_here_at(&el_sup, 0).unwrap();
        let mut iter = el_l_4.sub_elements();
        assert_eq!(iter.next().unwrap(), el_sup);
    }

    #[test]
    fn move_element_local() {
        // move an element within the same model
        let model = AutosarModel::new();
        model.create_file("test.arxml", AutosarVersion::Autosar_00050).unwrap();
        let el_autosar = model.root_element();
        let el_ar_packages = el_autosar.create_sub_element(ElementName::ArPackages).unwrap();
        let el_pkg1 = el_ar_packages
            .create_named_sub_element(ElementName::ArPackage, "Pkg1")
            .unwrap();
        let el_elements1 = el_pkg1.create_sub_element(ElementName::Elements).unwrap();
        let el_ecu_instance = el_elements1
            .create_named_sub_element(ElementName::EcuInstance, "EcuInstance")
            .unwrap();
        let el_pkg2 = el_ar_packages
            .create_named_sub_element(ElementName::ArPackage, "Pkg2")
            .unwrap();
        let el_pkg3 = el_ar_packages
            .create_named_sub_element(ElementName::ArPackage, "Pkg3")
            .unwrap();
        let el_fibex_element_ref = el_pkg3
            .create_sub_element(ElementName::Elements)
            .and_then(|el| el.create_named_sub_element(ElementName::System, "System"))
            .and_then(|el| el.create_sub_element(ElementName::FibexElements))
            .and_then(|el| el.create_sub_element(ElementName::FibexElementRefConditional))
            .and_then(|el| el.create_sub_element(ElementName::FibexElementRef))
            .unwrap();
        el_fibex_element_ref.set_reference_target(&el_ecu_instance).unwrap();

        // can't move an element of the wrong type
        assert!(el_ar_packages.move_element_here(&el_autosar).is_err());
        assert!(el_ar_packages.move_element_here_at(&el_autosar, 0).is_err());

        // moving an element into its own sub element (creating a loop) is forbidden
        assert!(el_pkg1.move_element_here(&el_ar_packages).is_err());
        assert!(el_pkg1.move_element_here_at(&el_ar_packages, 1).is_err());

        // move an unnamed element
        assert!(model.get_element_by_path("/Pkg1/EcuInstance").is_some());
        el_pkg2.move_element_here(&el_elements1).unwrap();
        assert_eq!(el_elements1.parent().unwrap().unwrap(), el_pkg2);
        assert!(model.get_element_by_path("/Pkg2/EcuInstance").is_some());
        assert_eq!(el_fibex_element_ref.get_reference_target().unwrap(), el_ecu_instance);

        // move the unnamed element back using the _at variant
        el_pkg1.move_element_here_at(&el_elements1, 1).unwrap();
        assert_eq!(el_elements1.parent().unwrap().unwrap(), el_pkg1);
        assert!(model.get_element_by_path("/Pkg1/EcuInstance").is_some());
        assert_eq!(el_fibex_element_ref.get_reference_target().unwrap(), el_ecu_instance);

        // move a named element
        let el_elements2 = el_pkg2.create_sub_element(ElementName::Elements).unwrap();
        el_elements2.move_element_here(&el_ecu_instance).unwrap();
        assert_eq!(el_ecu_instance.parent().unwrap().unwrap(), el_elements2);
        assert!(model.get_element_by_path("/Pkg2/EcuInstance").is_some());
        assert_eq!(el_fibex_element_ref.get_reference_target().unwrap(), el_ecu_instance);

        // moving an element should automatically resolve name conflicts
        el_elements1
            .create_named_sub_element(ElementName::EcuInstance, "EcuInstance")
            .unwrap();
        el_elements1.move_element_here_at(&el_ecu_instance, 0).unwrap();
        assert_eq!(el_ecu_instance.parent().unwrap().unwrap(), el_elements1);
        assert!(model.get_element_by_path("/Pkg1/EcuInstance_1").is_some());
        assert_eq!(el_fibex_element_ref.get_reference_target().unwrap(), el_ecu_instance);
    }

    #[test]
    fn move_element_full() {
        // move an element between two projects
        let model1 = AutosarModel::new();
        model1
            .create_file("test1.arxml", AutosarVersion::Autosar_00050)
            .unwrap();
        let el_autosar = model1.root_element();
        let el_ar_packages1 = el_autosar.create_sub_element(ElementName::ArPackages).unwrap();
        let el_pkg1 = el_ar_packages1
            .create_named_sub_element(ElementName::ArPackage, "Pkg1")
            .unwrap();
        let el_elements1 = el_pkg1.create_sub_element(ElementName::Elements).unwrap();
        let el_ecu_instance = el_elements1
            .create_named_sub_element(ElementName::EcuInstance, "EcuInstance")
            .unwrap();
        let el_pkg2 = el_ar_packages1
            .create_named_sub_element(ElementName::ArPackage, "Pkg2")
            .unwrap();
        let el_fibex_element_ref = el_pkg2
            .create_sub_element(ElementName::Elements)
            .and_then(|el| el.create_named_sub_element(ElementName::System, "System"))
            .and_then(|el| el.create_sub_element(ElementName::FibexElements))
            .and_then(|el| el.create_sub_element(ElementName::FibexElementRefConditional))
            .and_then(|el| el.create_sub_element(ElementName::FibexElementRef))
            .unwrap();
        el_fibex_element_ref.set_reference_target(&el_ecu_instance).unwrap();

        let model2 = AutosarModel::new();
        model2
            .create_file("test2.arxml", AutosarVersion::Autosar_00050)
            .unwrap();
        let el_autosar2 = model2.root_element();
        let el_ar_packages2 = el_autosar2.create_sub_element(ElementName::ArPackages).unwrap();

        // move a named element
        el_ar_packages2.move_element_here(&el_pkg1).unwrap();
        assert!(model1.get_element_by_path("/Pkg1").is_none());
        assert!(model2.get_element_by_path("/Pkg1").is_some());
        el_ar_packages2.move_element_here_at(&el_pkg2, 1).unwrap();
        assert!(model1.get_element_by_path("/Pkg2").is_none());
        assert!(model2.get_element_by_path("/Pkg2").is_some());

        // move an unnamed element
        el_autosar.remove_sub_element(el_ar_packages1).unwrap();
        el_autosar.move_element_here(&el_ar_packages2).unwrap();
        assert!(model1.get_element_by_path("/Pkg1/EcuInstance").is_some());
        assert!(model1.get_element_by_path("/Pkg2/System").is_some());
        assert_eq!(el_fibex_element_ref.get_reference_target().unwrap(), el_ecu_instance);

        // can't move an element when one of the projects is deleted
        drop(model2);
        assert!(el_autosar2.move_element_here(&el_ar_packages2).is_err());
        assert!(el_autosar2.move_element_here_at(&el_ar_packages2, 0).is_err());

        // can't move between files with different versions
        let project3 = AutosarModel::new();
        project3
            .create_file("test2.arxml", AutosarVersion::Autosar_4_3_0)
            .unwrap();
        let el_autosar3 = project3.root_element();
        assert!(el_autosar3.move_element_here(&el_ar_packages2).is_err());
        assert!(el_autosar3.move_element_here_at(&el_ar_packages2, 0).is_err());
    }

    #[test]
    fn get_set_reference_target() {
        let model = AutosarModel::new();
        model.create_file("text.arxml", AutosarVersion::Autosar_00050).unwrap();
        let el_autosar = model.root_element();
        let el_ar_package = el_autosar
            .create_sub_element(ElementName::ArPackages)
            .and_then(|arpkgs| arpkgs.create_named_sub_element(ElementName::ArPackage, "Package"))
            .unwrap();
        let el_elements = el_ar_package.create_sub_element(ElementName::Elements).unwrap();
        let el_ecu_instance1 = el_elements
            .create_named_sub_element(ElementName::EcuInstance, "EcuInstance1")
            .unwrap();
        let el_ecu_instance2 = el_elements
            .create_named_sub_element(ElementName::EcuInstance, "EcuInstance2")
            .unwrap();
        let el_req_result = el_elements
            .create_named_sub_element(ElementName::DiagnosticRoutine, "DiagRoutine")
            .and_then(|dr| dr.create_named_sub_element(ElementName::RequestResult, "RequestResult"))
            .unwrap();
        let el_fibex_element_ref = el_elements
            .create_named_sub_element(ElementName::System, "System")
            .and_then(|sys| sys.create_sub_element(ElementName::FibexElements))
            .and_then(|fe| fe.create_sub_element(ElementName::FibexElementRefConditional))
            .and_then(|ferc| ferc.create_sub_element(ElementName::FibexElementRef))
            .unwrap();
        let el_physical_request_ref = el_elements
            .create_named_sub_element(ElementName::DiagnosticConnection, "DiagnosticConnection")
            .and_then(|dc| dc.create_sub_element(ElementName::PhysicalRequestRef))
            .unwrap();
        let el_connection_ident = el_elements
            .create_named_sub_element(ElementName::CanTpConfig, "CanTpConfig")
            .and_then(|ctc| ctc.create_sub_element(ElementName::TpConnections))
            .and_then(|tc: Element| tc.create_sub_element(ElementName::CanTpConnection))
            .and_then(|ctc: Element| ctc.create_named_sub_element(ElementName::Ident, "ConnectionIdent"))
            .unwrap();

        // set_reference_target does not work for elements which are not references
        assert!(el_elements.set_reference_target(&el_ar_package).is_err());
        // element AUTOSAR is not identifiable, and a reference to it cannot be set
        assert!(el_fibex_element_ref.set_reference_target(&el_autosar).is_err());
        // element AR-PACKAGE is identifiable, but not a valid reference target for a FIBEX-ELEMENT-REF
        assert!(el_fibex_element_ref.set_reference_target(&el_ar_package).is_err());
        // element REQUEST-RESULT is identifiable, but cannot be referenced by any other element as here is no valid DEST enum entry for it
        assert!(el_fibex_element_ref.set_reference_target(&el_req_result).is_err());

        // set a valid reference and verify that the reference can be used
        el_fibex_element_ref.set_reference_target(&el_ecu_instance1).unwrap();
        assert_eq!(el_fibex_element_ref.get_reference_target().unwrap(), el_ecu_instance1);
        // update with a different valid reference and verify that the reference can be used
        el_fibex_element_ref.set_reference_target(&el_ecu_instance2).unwrap();
        assert_eq!(el_fibex_element_ref.get_reference_target().unwrap(), el_ecu_instance2);

        // set a valid reference to <CAN-TP-CONNECTION><IDENT>.
        // This is a complex case, as the correct DEST attribute must be looked up in the specification
        el_physical_request_ref
            .set_reference_target(&el_connection_ident)
            .unwrap();
        assert_eq!(
            el_physical_request_ref.get_reference_target().unwrap(),
            el_connection_ident
        );

        // invalid reference: bad DEST attribute
        el_fibex_element_ref
            .set_attribute(AttributeName::Dest, CharacterData::Enum(EnumItem::ISignal))
            .unwrap();
        assert!(el_fibex_element_ref.get_reference_target().is_err());
        // invalid reference: no DEST attribute
        el_fibex_element_ref.0.write().attributes.clear(); // remove the DEST attribute
        assert!(el_fibex_element_ref.get_reference_target().is_err());
        el_fibex_element_ref.set_reference_target(&el_ecu_instance2).unwrap();
        // invalid reference: bad reference string
        el_fibex_element_ref
            .set_attribute(AttributeName::Dest, CharacterData::Enum(EnumItem::EcuInstance))
            .unwrap();
        el_fibex_element_ref.set_character_data("/does/not/exist").unwrap();
        assert!(el_fibex_element_ref.get_reference_target().is_err());
        // invalid reference: refers to the wrong type of element
        el_fibex_element_ref.set_character_data("/Package").unwrap();
        assert!(el_fibex_element_ref.get_reference_target().is_err());
        // invalid reference: no reference string
        el_fibex_element_ref.remove_character_data().unwrap();
        assert!(el_fibex_element_ref.get_reference_target().is_err());
        el_fibex_element_ref.set_reference_target(&el_ecu_instance2).unwrap();
        // not a reference
        assert!(el_elements.get_reference_target().is_err());
        // model is deleted
        drop(model);
        assert!(el_fibex_element_ref.get_reference_target().is_err());
    }

    #[test]
    fn modify_character_data() {
        let model = AutosarModel::new();
        model.create_file("text.arxml", AutosarVersion::Autosar_00050).unwrap();
        let el_autosar = model.root_element();
        let el_ar_package = el_autosar
            .create_sub_element(ElementName::ArPackages)
            .and_then(|arpkgs| arpkgs.create_named_sub_element(ElementName::ArPackage, "Package"))
            .unwrap();
        let el_short_name = el_ar_package.get_sub_element(ElementName::ShortName).unwrap();
        let el_elements = el_ar_package.create_sub_element(ElementName::Elements).unwrap();
        let el_system = el_elements
            .create_named_sub_element(ElementName::System, "System")
            .unwrap();
        let el_fibex_element_ref = el_system
            .create_sub_element(ElementName::FibexElements)
            .and_then(|fe| fe.create_sub_element(ElementName::FibexElementRefConditional))
            .and_then(|ferc| ferc.create_sub_element(ElementName::FibexElementRef))
            .unwrap();
        let el_pnc_vector_length = el_system.create_sub_element(ElementName::PncVectorLength).unwrap();

        // set character data on an "ordinary" element that has no special handling
        assert!(el_pnc_vector_length
            .set_character_data(CharacterData::String("2".to_string()))
            .is_ok()); // "native" type is String, without automatic wrapping
        assert!(el_pnc_vector_length.set_character_data("2".to_string()).is_ok()); // "native" type is String
        assert!(el_pnc_vector_length.set_character_data("2").is_ok()); // automatic conversion: &str -> String
        assert!(el_pnc_vector_length.set_character_data(2).is_ok()); // automatic conversion: u64 -> String

        // set a new SHORT-NAME, this also updates path cache
        assert!(el_short_name
            .set_character_data(CharacterData::String("PackageRenamed".to_string()))
            .is_ok());
        assert_eq!(
            el_short_name.character_data().unwrap().string_value().unwrap(),
            "PackageRenamed"
        );
        model.get_element_by_path("/PackageRenamed").unwrap();

        // set a new reference target, which creates an entry in the reference origin cache
        assert!(el_fibex_element_ref
            .set_character_data("/PackageRenamed/EcuInstance1")
            .is_ok());
        model
            .0
            .read()
            .reference_origins
            .get("/PackageRenamed/EcuInstance1")
            .unwrap();

        // modify the reference target, which updates the entry in the reference origin cache
        assert!(el_fibex_element_ref
            .set_character_data("/PackageRenamed/EcuInstance2")
            .is_ok());
        model
            .0
            .read()
            .reference_origins
            .get("/PackageRenamed/EcuInstance2")
            .unwrap();
        assert!(!model
            .0
            .read()
            .reference_origins
            .contains_key("/PackageRenamed/EcuInstance1"));

        // can only set character data that are specified with ContentMode::Characters
        assert!(el_autosar.set_character_data("text").is_err());

        // can't set a value that doesn't match the target spec
        assert!(el_short_name.set_character_data(0).is_err());
        assert!(el_short_name.set_character_data("").is_err());

        // remove character data
        assert!(el_pnc_vector_length.remove_character_data().is_ok());

        // remove the character data of a reference
        assert!(el_fibex_element_ref.remove_character_data().is_ok());
        assert!(!model
            .0
            .read()
            .reference_origins
            .contains_key("/PackageRenamed/EcuInstance2"));

        // remove on an element whose character data has already been removed is not an error
        assert!(el_fibex_element_ref.remove_character_data().is_ok());

        // can't remove SHORT-NAME
        assert!(el_short_name.remove_character_data().is_err());

        // can't remove from elements which do not contain character data
        assert!(el_autosar.remove_character_data().is_err());

        // slightly different behavior for the internal version that is used for locked elements
        assert!(el_autosar
            .0
            .write()
            .set_character_data(0, AutosarVersion::Autosar_00050)
            .is_err());
        assert!(el_fibex_element_ref
            .0
            .write()
            .set_character_data(0, AutosarVersion::Autosar_00050)
            .is_err());

        // operation fails if the model is needed (e.g. reference or short name update), but the model has been deleted
        el_fibex_element_ref
            .set_character_data("/PackageRenamed/EcuInstance2")
            .unwrap();
        drop(model);
        assert!(el_fibex_element_ref
            .set_character_data("/PackageRenamed/EcuInstance1")
            .is_err());
        assert!(el_fibex_element_ref.remove_character_data().is_err());
    }

    #[test]
    fn mixed_character_content() {
        let model = AutosarModel::new();
        model.create_file("test", AutosarVersion::Autosar_00050).unwrap();
        let el_ar_package = model
            .root_element()
            .create_sub_element(ElementName::ArPackages)
            .and_then(|e| e.create_named_sub_element(ElementName::ArPackage, "Pkg"))
            .unwrap();
        let el_desc = el_ar_package.create_sub_element(ElementName::Desc).unwrap();
        let el_l2 = el_desc.create_sub_element(ElementName::L2).unwrap();

        // ok: add a character content item to a vaild element at a valid position
        el_l2.insert_character_content_item("descriptive text", 0).unwrap();

        // ok: add an element to the mixed item as well
        el_l2.create_sub_element(ElementName::Br).unwrap();

        // not ok: add a character content item to a valid element at an invalid position
        assert!(el_l2.insert_character_content_item("more text", 99).is_err());

        // not ok: add a character content item to an invalid element
        assert!(el_desc.insert_character_content_item("text", 0).is_err());

        // not ok: remove character content from an invalid position
        assert!(el_l2.remove_character_content_item(99).is_err());

        // not ok: remove character content from an invalid element
        assert!(el_desc.remove_character_content_item(0).is_err());

        // not ok: remove a sub-element
        assert!(el_l2.remove_character_content_item(1).is_err());

        // ok: remove character content from a valid element at a valid position
        el_l2.remove_character_content_item(0).unwrap();
    }

    #[test]
    fn get_sub_element() {
        let model = AutosarModel::new();
        model.create_file("test", AutosarVersion::Autosar_00050).unwrap();
        let el_autosar = model.root_element();
        let el_ar_packages = el_autosar.create_sub_element(ElementName::ArPackages).unwrap();
        let el_ar_package = el_ar_packages
            .create_named_sub_element(ElementName::ArPackage, "Package")
            .unwrap();
        let el_desc = el_ar_package.create_sub_element(ElementName::Desc).unwrap();
        let el_l2 = el_desc.create_sub_element(ElementName::L2).unwrap();

        el_l2.insert_character_content_item("descriptive text", 0).unwrap();
        el_l2.create_sub_element(ElementName::Br).unwrap();

        assert_eq!(
            el_autosar.get_sub_element(ElementName::ArPackages).unwrap(),
            el_ar_packages
        );
        assert!(el_autosar.get_sub_element(ElementName::Abs).is_none());
        assert!(el_l2.get_sub_element(ElementName::Br).is_some());
    }

    #[test]
    fn get_or_create() {
        let model = AutosarModel::new();
        model.create_file("test", AutosarVersion::Autosar_00050).unwrap();
        let el_autosar = model.root_element();

        assert_eq!(el_autosar.sub_elements().count(), 0);
        let el_admin_data = el_autosar.get_or_create_sub_element(ElementName::AdminData).unwrap();
        let el_ar_packages = el_autosar.get_or_create_sub_element(ElementName::ArPackages).unwrap();
        let el_ar_packages2 = el_autosar.get_or_create_sub_element(ElementName::ArPackages).unwrap();
        assert_ne!(el_admin_data, el_ar_packages);
        assert_eq!(el_ar_packages, el_ar_packages2);

        let el_ar_package = el_ar_packages
            .get_or_create_named_sub_element(ElementName::ArPackage, "Pkg")
            .unwrap();
        let el_ar_package2 = el_ar_packages
            .get_or_create_named_sub_element(ElementName::ArPackage, "Pkg2")
            .unwrap();
        let el_ar_package3 = el_ar_packages
            .get_or_create_named_sub_element(ElementName::ArPackage, "Pkg2")
            .unwrap();
        assert_ne!(el_ar_package, el_ar_package2);
        assert_eq!(el_ar_package2, el_ar_package3);
    }

    #[test]
    fn serialize() {
        const FILEBUF: &str = r#"<?xml version="1.0" encoding="utf-8"?>
<!--comment-->
<AUTOSAR xsi:schemaLocation="http://autosar.org/schema/r4.0 AUTOSAR_00050.xsd" xmlns="http://autosar.org/schema/r4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <AR-PACKAGES>
    <AR-PACKAGE>
      <SHORT-NAME>Pkg</SHORT-NAME>
      <DESC>
        <L-2 L="EN">Description<BR/>Description</L-2>
      </DESC>
    </AR-PACKAGE>
  </AR-PACKAGES>
</AUTOSAR>"#;
        let model = AutosarModel::new();
        model
            .load_buffer(FILEBUF.as_bytes(), OsString::from("test"), true)
            .unwrap();
        model.files().next().unwrap();
        let el_autosar = model.root_element();
        el_autosar.set_comment(Some("comment".to_string()));

        let mut outstring = String::from(r#"<?xml version="1.0" encoding="utf-8"?>"#);
        el_autosar.serialize_internal(&mut outstring, 0, false, &None);

        assert_eq!(FILEBUF, outstring);
    }

    #[test]
    fn list_valid_sub_elements() {
        let model = AutosarModel::new();
        model.create_file("test.arxml", AutosarVersion::Autosar_4_3_0).unwrap();
        let el_autosar = model.root_element();
        let el_elements = el_autosar
            .create_sub_element(ElementName::ArPackages)
            .and_then(|el| el.create_named_sub_element(ElementName::ArPackage, "Package"))
            .and_then(|el| el.create_sub_element(ElementName::Elements))
            .unwrap();
        let result = el_elements.list_valid_sub_elements();
        assert!(!result.is_empty());
    }

    #[test]
    fn check_version_compatibility() {
        const FILEBUF: &str = r#"<?xml version="1.0" encoding="utf-8"?>
<AUTOSAR xsi:schemaLocation="http://autosar.org/schema/r4.0 AUTOSAR_00050.xsd" xmlns="http://autosar.org/schema/r4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <AR-PACKAGES>
    <AR-PACKAGE>
      <SHORT-NAME>Pkg</SHORT-NAME>
      <ELEMENTS>
        <ACL-OBJECT-SET UUID="012345">
          <SHORT-NAME BLUEPRINT-VALUE="xyz">AclObjectSet</SHORT-NAME>
          <DERIVED-FROM-BLUEPRINT-REFS>
            <DERIVED-FROM-BLUEPRINT-REF DEST="ABSTRACT-IMPLEMENTATION-DATA-TYPE">/invalid</DERIVED-FROM-BLUEPRINT-REF>
          </DERIVED-FROM-BLUEPRINT-REFS>
        </ACL-OBJECT-SET>
        <ADAPTIVE-APPLICATION-SW-COMPONENT-TYPE>
          <SHORT-NAME>AdaptiveApplicationSwComponentType</SHORT-NAME>
        </ADAPTIVE-APPLICATION-SW-COMPONENT-TYPE>
      </ELEMENTS>
    </AR-PACKAGE>
  </AR-PACKAGES>
</AUTOSAR>"#;
        let model = AutosarModel::new();
        let (file, _) = model
            .load_buffer(FILEBUF.as_bytes(), OsString::from("test"), true)
            .unwrap();
        model.files().next().unwrap();
        let el_autosar = model.root_element();

        let (compat_errors, _) =
            el_autosar.check_version_compatibility(&file.downgrade(), AutosarVersion::Autosar_4_3_0);
        assert_eq!(compat_errors.len(), 3);

        for ce in compat_errors {
            match ce {
                CompatibilityError::IncompatibleElement { element, .. } => {
                    assert_eq!(element.element_name(), ElementName::AdaptiveApplicationSwComponentType);
                }
                CompatibilityError::IncompatibleAttribute { element, attribute, .. } => {
                    assert_eq!(element.element_name(), ElementName::ShortName);
                    assert_eq!(attribute, AttributeName::BlueprintValue);
                }
                CompatibilityError::IncompatibleAttributeValue { element, attribute, .. } => {
                    assert_eq!(element.element_name(), ElementName::DerivedFromBlueprintRef);
                    assert_eq!(attribute, AttributeName::Dest);
                }
            }
        }

        // regression test - CompuScales in CompuInternalToPhys was falsely detected as incompatible
        let model = AutosarModel::new();
        let file = model.create_file("filename", AutosarVersion::Autosar_00046).unwrap();
        model
            .root_element()
            .create_sub_element(ElementName::ArPackages)
            .and_then(|e| e.create_named_sub_element(ElementName::ArPackage, "Pkg"))
            .and_then(|e| e.create_sub_element(ElementName::Elements))
            .and_then(|e| e.create_named_sub_element(ElementName::CompuMethod, "CompuMethod"))
            .and_then(|e| e.create_sub_element(ElementName::CompuInternalToPhys))
            .and_then(|e| e.create_sub_element(ElementName::CompuScales))
            .and_then(|e| e.create_sub_element(ElementName::CompuScale))
            .unwrap();
        let (compat_errors, _) = file.check_version_compatibility(AutosarVersion::Autosar_4_3_0);
        assert!(compat_errors.is_empty());
    }

    #[test]
    fn find_element_insert_pos() {
        let model = AutosarModel::new();
        model.create_file("test", AutosarVersion::Autosar_00050).unwrap();
        let el_autosar = model.root_element();
        let el_ar_packages = el_autosar.create_sub_element(ElementName::ArPackages).unwrap();
        let el_ar_package = el_ar_packages
            .create_named_sub_element(ElementName::ArPackage, "Pkg")
            .unwrap();
        let el_short_name = el_ar_package.get_sub_element(ElementName::ShortName).unwrap();

        // find_element_insert_pos does not operat on CharacterData elements, e.g. SHORT-NAME
        assert!(el_short_name
            .0
            .read()
            .calc_element_insert_range(ElementName::Desc, AutosarVersion::Autosar_00050)
            .is_err());

        // find_element_insert_pos fails to find a place for a sequence element with multiplicity 0-1
        assert!(el_autosar
            .0
            .read()
            .calc_element_insert_range(ElementName::ArPackages, AutosarVersion::Autosar_00050)
            .is_err());
    }

    #[test]
    fn sort() {
        let model = AutosarModel::new();
        model.create_file("test", AutosarVersion::Autosar_00050).unwrap();
        let el_autosar = model.root_element();
        let el_ar_packages = el_autosar.create_sub_element(ElementName::ArPackages).unwrap();
        let el_ar_package1 = el_ar_packages
            .create_named_sub_element(ElementName::ArPackage, "Z")
            .unwrap();
        let el_ar_package2 = el_ar_packages
            .create_named_sub_element(ElementName::ArPackage, "A")
            .unwrap();
        let el_elements = el_ar_package1.create_sub_element(ElementName::Elements).unwrap();
        el_ar_package1.create_sub_element(ElementName::AdminData).unwrap();
        // create some bsw values to sort inside el_ar_package1 "Z"
        let el_emcv = el_elements
            .create_named_sub_element(ElementName::EcucModuleConfigurationValues, "Config")
            .unwrap();
        let el_containers = el_emcv.create_sub_element(ElementName::Containers).unwrap();
        let el_ecv = el_containers
            .create_named_sub_element(ElementName::EcucContainerValue, "ConfigValues")
            .unwrap();
        let el_paramvalues = el_ecv.create_sub_element(ElementName::ParameterValues).unwrap();
        // first bsw value
        let el_value1 = el_paramvalues
            .create_sub_element(ElementName::EcucNumericalParamValue)
            .unwrap();
        let el_defref1 = el_value1.create_sub_element(ElementName::DefinitionRef).unwrap();
        el_defref1
            .set_attribute(AttributeName::Dest, CharacterData::Enum(EnumItem::EcucBooleanParamDef))
            .unwrap();
        el_defref1.set_character_data("/DefRef_999").unwrap();
        // second bsw value
        let el_value2 = el_paramvalues
            .create_sub_element(ElementName::EcucNumericalParamValue)
            .unwrap();
        let el_defref2 = el_value2.create_sub_element(ElementName::DefinitionRef).unwrap();
        el_defref2
            .set_attribute(AttributeName::Dest, CharacterData::Enum(EnumItem::EcucBooleanParamDef))
            .unwrap();
        el_defref2.set_character_data("/DefRef_111").unwrap();
        // Create some misc value sto sort inside el_ar_package2 "A"
        let el_elements2 = el_ar_package2.create_sub_element(ElementName::Elements).unwrap();
        let el_system = el_elements2
            .create_named_sub_element(ElementName::System, "System")
            .unwrap();
        let el_fibex_elements = el_system.create_sub_element(ElementName::FibexElements).unwrap();
        let el_fibex_element1 = el_fibex_elements
            .create_sub_element(ElementName::FibexElementRefConditional)
            .unwrap();
        let el_fibex_element_ref1 = el_fibex_element1
            .create_sub_element(ElementName::FibexElementRef)
            .unwrap();
        el_fibex_element_ref1
            .set_attribute(AttributeName::Dest, CharacterData::Enum(EnumItem::ISignal))
            .unwrap();
        el_fibex_element_ref1.set_character_data("/ZZZZZ").unwrap();
        let el_fibex_element2 = el_fibex_elements
            .create_sub_element(ElementName::FibexElementRefConditional)
            .unwrap();
        let el_fibex_element_ref2 = el_fibex_element2
            .create_sub_element(ElementName::FibexElementRef)
            .unwrap();
        el_fibex_element_ref2
            .set_attribute(AttributeName::Dest, CharacterData::Enum(EnumItem::ISignal))
            .unwrap();
        el_fibex_element_ref2.set_character_data("/AAAAA").unwrap();

        model.sort();
        // validate that identifiable elements have been sorted
        let mut iter = el_ar_packages.sub_elements();
        let item1 = iter.next().unwrap();
        let item2 = iter.next().unwrap();
        assert_eq!(item1.item_name().unwrap(), "A");
        assert_eq!(item2.item_name().unwrap(), "Z");

        // validate that BSW parameter values have been sorted
        let mut iter = el_paramvalues.sub_elements();
        let item1 = iter.next().unwrap();
        let item2 = iter.next().unwrap();
        assert_eq!(item1, el_value2);
        assert_eq!(item2, el_value1);

        // validate that the misc elements (FIBEX-ELEMENT-REF-CONDITIONAL) have been sorted
        let mut iter = el_fibex_elements.sub_elements();
        let item1 = iter.next().unwrap();
        let item2 = iter.next().unwrap();
        assert_eq!(item1, el_fibex_element2);
        assert_eq!(item2, el_fibex_element1);
    }

    fn helper_create_bsw_subelem(
        el_subcontainers: &Element,
        short_name: &str,
        defref: &str,
    ) -> Result<Element, AutosarDataError> {
        let e = el_subcontainers.create_named_sub_element(ElementName::EcucContainerValue, short_name)?;
        let defrefelem = e.create_sub_element(ElementName::DefinitionRef)?;
        defrefelem.set_character_data(defref)?;
        Ok(e)
    }

    fn helper_create_indexed_bsw_subelem(
        el_subcontainers: &Element,
        short_name: &str,
        indexstr: &str,
        defref: &str,
    ) -> Result<Element, AutosarDataError> {
        let e = helper_create_bsw_subelem(el_subcontainers, short_name, defref)?;
        let indexelem = e.create_sub_element(ElementName::Index)?;
        indexelem.set_character_data(indexstr)?;
        Ok(e)
    }

    #[test]
    fn sort_bsw_elements() {
        let model = AutosarModel::new();
        model.create_file("test", AutosarVersion::LATEST).unwrap();
        let el_subcontainers = model
            .root_element()
            .create_sub_element(ElementName::ArPackages)
            .and_then(|ap| ap.create_named_sub_element(ElementName::ArPackage, "Pkg"))
            .and_then(|ap| ap.create_sub_element(ElementName::Elements))
            .and_then(|elems| elems.create_named_sub_element(ElementName::EcucModuleConfigurationValues, "Config"))
            .and_then(|emcv| emcv.create_sub_element(ElementName::Containers))
            .and_then(|c| c.create_named_sub_element(ElementName::EcucContainerValue, "ConfigValues"))
            .and_then(|ecv| ecv.create_sub_element(ElementName::SubContainers))
            .unwrap();
        let elem1 =
            helper_create_indexed_bsw_subelem(&el_subcontainers, "Aaa", "06", "/Defref/Container/Value").unwrap(); // idx 6
        let elem2 =
            helper_create_indexed_bsw_subelem(&el_subcontainers, "Bbb", "5", "/Defref/Container/Value").unwrap(); // idx 5
        let elem3 =
            helper_create_indexed_bsw_subelem(&el_subcontainers, "Bbb2", "5", "/Defref/Container/Value").unwrap(); // idx 5 duplicate
        let elem4 =
            helper_create_indexed_bsw_subelem(&el_subcontainers, "Ccc", "0X4", "/Defref/Container/Value").unwrap(); // idx 4
        let elem5 = helper_create_bsw_subelem(&el_subcontainers, "Zzz", "/Defref/Container/Value").unwrap();
        let elem6 =
            helper_create_indexed_bsw_subelem(&el_subcontainers, "Ddd", "0b1", "/Defref/Container/Value").unwrap(); // idx 1
        let elem7 =
            helper_create_indexed_bsw_subelem(&el_subcontainers, "Eee", "0x3", "/Defref/Container/Value").unwrap(); // idx 3
        let elem8 =
            helper_create_indexed_bsw_subelem(&el_subcontainers, "Fff", "0B10", "/Defref/Container/Value").unwrap(); // idx 2
        let elem9 =
            helper_create_indexed_bsw_subelem(&el_subcontainers, "Ggg", "0", "/Defref/Container/Value").unwrap(); // idx 0

        let elem10 = helper_create_bsw_subelem(&el_subcontainers, "Mmm_0", "/Defref/Container/Value").unwrap();
        let elem11 = helper_create_bsw_subelem(&el_subcontainers, "Mmm_5", "/Defref/Container/Value").unwrap();
        let elem12 = helper_create_bsw_subelem(&el_subcontainers, "Mmm_10", "/Defref/Container/Value").unwrap();
        let elem13 = helper_create_bsw_subelem(&el_subcontainers, "Mmm_9", "/Defref/Container/Value").unwrap();

        el_subcontainers.sort();
        assert_eq!(elem1.position().unwrap(), 7);
        assert_eq!(elem2.position().unwrap(), 5);
        assert_eq!(elem3.position().unwrap(), 6);
        assert_eq!(elem4.position().unwrap(), 4);
        assert_eq!(elem6.position().unwrap(), 1);
        assert_eq!(elem7.position().unwrap(), 3);
        assert_eq!(elem8.position().unwrap(), 2);
        assert_eq!(elem9.position().unwrap(), 0);
        // elements without indices are sorted behind the indexed elements
        assert_eq!(elem10.position().unwrap(), 8);
        assert_eq!(elem11.position().unwrap(), 9);
        assert_eq!(elem13.position().unwrap(), 10);
        assert_eq!(elem12.position().unwrap(), 11);
        assert_eq!(elem5.position().unwrap(), 12);
    }

    #[test]
    fn file_membership() {
        let model = AutosarModel::new();
        let file1 = model.create_file("test_1", AutosarVersion::Autosar_00050).unwrap();
        let file2 = model.create_file("test_2", AutosarVersion::Autosar_00050).unwrap();
        let el_autosar = model.root_element();
        let el_ar_packages = el_autosar.create_sub_element(ElementName::ArPackages).unwrap();
        let el_ar_package = el_ar_packages
            .create_named_sub_element(ElementName::ArPackage, "Pkg")
            .unwrap();
        el_ar_package.create_sub_element(ElementName::Elements).unwrap();

        let fm: HashSet<WeakArxmlFile> = [file1.downgrade()].iter().cloned().collect();
        // setting the file membership of el_ar_packages should fail
        // its parent is not splittable, so this is not allowed
        el_ar_packages.set_file_membership(fm.clone());
        let (local, _) = el_ar_package.file_membership().unwrap();
        assert!(!local);

        // setting the file membership of el_ar_package should succeed
        // this element is only part of file1, and is only serialized with file1
        el_ar_package.set_file_membership(fm.clone());
        let (local, fm2) = el_ar_package.file_membership().unwrap();
        assert!(local);
        assert_eq!(fm, fm2);
        let filetxt1 = file1.serialize().unwrap();
        let filetxt2 = file2.serialize().unwrap();
        assert_ne!(filetxt1, filetxt2);

        // can't use a file from a different model in add_to_file / remove_from_file
        let model2 = AutosarModel::new();
        let model2_file = model2.create_file("file", AutosarVersion::LATEST).unwrap();
        assert!(el_ar_package.add_to_file(&model2_file).is_err());
        assert!(el_ar_package.remove_from_file(&model2_file).is_err());

        // adding el_ar_package to file1 does nothing, since it is already present in this file
        el_ar_package.add_to_file(&file1).unwrap();
        let (local, fm3) = el_ar_package.file_membership().unwrap();
        assert!(local);
        assert_eq!(fm3.len(), 1);

        // removing el_ar_package from file2 does nothing, it is not present in this file
        el_ar_package.remove_from_file(&file2).unwrap();
        let (local, fm3) = el_ar_package.file_membership().unwrap();
        assert!(local);
        assert_eq!(fm3.len(), 1);

        // adding el_ar_package to file2 succeeds
        el_ar_package.add_to_file(&file2).unwrap();
        let (local, fm3) = el_ar_package.file_membership().unwrap();
        assert!(local);
        assert_eq!(fm3.len(), 2);

        // removing el_ar_package from file1 and file2 causes it to be deleted
        assert!(el_ar_package.get_sub_element(ElementName::Elements).is_some());
        el_ar_package.remove_from_file(&file1).unwrap();
        el_ar_package.remove_from_file(&file2).unwrap();
        assert!(el_ar_package.get_sub_element(ElementName::Elements).is_none());
        assert!(el_ar_package.remove_from_file(&file2).is_err());
    }

    #[test]
    fn comment() {
        let model = AutosarModel::new();
        model.create_file("test", AutosarVersion::LATEST).unwrap();
        let el_autosar = model.root_element();

        // initially there is no comment
        assert!(el_autosar.comment().is_none());

        // set and get a comment
        el_autosar.set_comment(Some("comment".to_string()));
        assert_eq!(el_autosar.comment().unwrap(), "comment");

        // set a new comment containing "--" which is a forbidden sequence in XML comments
        el_autosar.set_comment(Some("comment--".to_string()));
        assert_eq!(el_autosar.comment().unwrap(), "comment__");

        // remove the comment
        el_autosar.set_comment(None);
        assert!(el_autosar.comment().is_none());
    }

    #[test]
    fn min_version() {
        let model = AutosarModel::new();
        let result = model.root_element().min_version();
        assert!(result.is_err());

        model.create_file("test", AutosarVersion::LATEST).unwrap();
        let min_ver = model.root_element().min_version().unwrap();
        assert_eq!(min_ver, AutosarVersion::LATEST);

        model.create_file("test2", AutosarVersion::Autosar_00042).unwrap();
        let min_ver = model.root_element().min_version().unwrap();
        assert_eq!(min_ver, AutosarVersion::Autosar_00042);
    }

    #[test]
    fn traits() {
        let model = AutosarModel::new();
        model.create_file("test", AutosarVersion::LATEST).unwrap();

        // traits of elements
        let el_autosar = model.root_element();
        let el_ar_packages = el_autosar.create_sub_element(ElementName::ArPackages).unwrap();

        let el_autosar_second_ref = el_autosar.clone();
        assert_eq!(el_autosar, el_autosar_second_ref);
        assert_eq!(format!("{el_autosar:?}"), format!("{el_autosar_second_ref:?}"));
        assert_ne!(el_autosar, el_ar_packages);

        let weak1 = el_autosar.downgrade();
        let weak2 = el_autosar_second_ref.downgrade();
        assert_eq!(weak1, weak2);
        assert_eq!(format!("{weak1:?}"), format!("{weak2:?}"));

        let mut hs = HashSet::new();
        hs.insert(el_autosar);
        hs.insert(el_ar_packages);
        // can't insert el_autosar_second_ref, it is already in the set
        assert!(!hs.insert(el_autosar_second_ref));
        assert_eq!(hs.len(), 2);

        let mut hs2 = HashSet::new();
        hs2.insert(weak1);
        assert!(!hs2.insert(weak2));
        assert_eq!(hs2.len(), 1);

        // traits of elementcontent
        let ec_elem = ElementContent::Element(model.root_element());
        assert_eq!(format!("{:?}", model.root_element()), format!("{ec_elem:?}"));
        assert_eq!(ec_elem.unwrap_element(), Some(model.root_element()));
        assert!(ec_elem.unwrap_cdata().is_none());
        let cdata = CharacterData::String("test".to_string());
        let ec_chars = ElementContent::CharacterData(cdata.clone());
        assert_eq!(format!("{cdata:?}"), format!("{ec_chars:?}"));
        assert_eq!(ec_chars.unwrap_cdata(), Some(cdata));
        assert!(ec_chars.unwrap_element().is_none());
    }

    #[test]
    fn element_order() {
        let model = AutosarModel::new();
        let _file = model.create_file("test", AutosarVersion::LATEST).unwrap();
        let el_autosar = model.root_element();
        let el_elements = el_autosar
            .create_sub_element(ElementName::ArPackages)
            .unwrap()
            .create_named_sub_element(ElementName::ArPackage, "pkg")
            .unwrap()
            .create_sub_element(ElementName::Elements)
            .unwrap();
        let el_system = el_elements
            .create_named_sub_element(ElementName::System, "sys")
            .unwrap();
        let fibex_elements = el_system.create_sub_element(ElementName::FibexElements).unwrap();

        let item1 = el_elements
            .create_named_sub_element(ElementName::ApplicationPrimitiveDataType, "adt_2")
            .unwrap();
        let item2 = el_elements
            .create_named_sub_element(ElementName::ApplicationPrimitiveDataType, "adt_10")
            .unwrap();
        let item3 = el_elements
            .create_named_sub_element(ElementName::ApplicationArrayDataType, "adt_12")
            .unwrap();
        // items 1 and 2 are sorted after separating the index from the name, so 10 comes after 2
        assert!(item1 < item2);
        // items 2 and 3 are sorted by the element type, so in this case the index does not matter
        assert!(item3 < item1);

        let item4 = fibex_elements
            .create_sub_element(ElementName::FibexElementRefConditional)
            .unwrap();
        let item4_ref = item4.create_sub_element(ElementName::FibexElementRef).unwrap();
        item4_ref
            .set_attribute(AttributeName::Dest, CharacterData::Enum(EnumItem::ISignal))
            .unwrap();
        item4_ref.set_character_data("/aaa").unwrap();

        let item5 = fibex_elements
            .create_sub_element(ElementName::FibexElementRefConditional)
            .unwrap();
        let item5_ref = item5.create_sub_element(ElementName::FibexElementRef).unwrap();
        item5_ref
            .set_attribute(AttributeName::Dest, CharacterData::Enum(EnumItem::ISignal))
            .unwrap();
        item5_ref.set_character_data("/bbb").unwrap();

        // items 4 and 5 are sorted by the character data of the reference
        assert!(item4 < item5);

        let item6 = fibex_elements
            .create_sub_element(ElementName::FibexElementRefConditional)
            .unwrap();
        let item6_ref = item6.create_sub_element(ElementName::FibexElementRef).unwrap();
        item6_ref
            .set_attribute(AttributeName::Dest, CharacterData::Enum(EnumItem::EcuInstance))
            .unwrap();

        // items 4 and 6 are sorted by the DEST attribute of the reference
        assert!(item6 < item4);

        let item7 = fibex_elements
            .create_sub_element(ElementName::FibexElementRefConditional)
            .unwrap();
        item7.create_sub_element(ElementName::FibexElementRef).unwrap();

        // item7 is incomplete, lacking the DEST attribute so it is sorted last
        assert!(item7 > item6);
        assert!(item6 < item7);
    }

    #[test]
    fn elements_dfs_with_max_depth() {
        const FILEBUF: &[u8] = r#"<?xml version="1.0" encoding="utf-8"?>
        <AUTOSAR xsi:schemaLocation="http://autosar.org/schema/r4.0 AUTOSAR_00050.xsd" xmlns="http://autosar.org/schema/r4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
        <AR-PACKAGES>
          <AR-PACKAGE><SHORT-NAME>Pkg_A</SHORT-NAME><ELEMENTS>
            <ECUC-MODULE-CONFIGURATION-VALUES><SHORT-NAME>BswModule</SHORT-NAME><CONTAINERS><ECUC-CONTAINER-VALUE>
              <SHORT-NAME>BswModuleValues</SHORT-NAME>
              <PARAMETER-VALUES>
                <ECUC-NUMERICAL-PARAM-VALUE>
                  <DEFINITION-REF DEST="ECUC-BOOLEAN-PARAM-DEF">/REF_A</DEFINITION-REF>
                </ECUC-NUMERICAL-PARAM-VALUE>
                <ECUC-NUMERICAL-PARAM-VALUE>
                  <DEFINITION-REF DEST="ECUC-BOOLEAN-PARAM-DEF">/REF_B</DEFINITION-REF>
                </ECUC-NUMERICAL-PARAM-VALUE>
                <ECUC-NUMERICAL-PARAM-VALUE>
                  <DEFINITION-REF DEST="ECUC-BOOLEAN-PARAM-DEF">/REF_C</DEFINITION-REF>
                </ECUC-NUMERICAL-PARAM-VALUE>
              </PARAMETER-VALUES>
            </ECUC-CONTAINER-VALUE></CONTAINERS></ECUC-MODULE-CONFIGURATION-VALUES>
          </ELEMENTS></AR-PACKAGE>
          <AR-PACKAGE><SHORT-NAME>Pkg_B</SHORT-NAME></AR-PACKAGE>
          <AR-PACKAGE><SHORT-NAME>Pkg_C</SHORT-NAME></AR-PACKAGE>
        </AR-PACKAGES></AUTOSAR>"#.as_bytes();
        let model = AutosarModel::new();
        let (_, _) = model.load_buffer(FILEBUF, "test1", true).unwrap();
        let root_elem = model.root_element();
        let ar_packages_elem = root_elem.get_sub_element(ElementName::ArPackages).unwrap();
        let root_all_count = root_elem.elements_dfs().count();
        let ar_packages_all_count = ar_packages_elem.elements_dfs().count();
        assert_eq!(root_all_count, ar_packages_all_count + 1);

        let root_lvl3_count = root_elem.elements_dfs_with_max_depth(3).count();
        let ar_packages_lvl2_count = ar_packages_elem.elements_dfs_with_max_depth(2).count();
        assert_eq!(root_lvl3_count, ar_packages_lvl2_count + 1);

        root_elem
            .elements_dfs_with_max_depth(3)
            .skip(1)
            .zip(ar_packages_elem.elements_dfs_with_max_depth(2))
            .for_each(|((_, x), (_, y))| assert_eq!(x, y));

        for elem in ar_packages_elem.elements_dfs_with_max_depth(2) {
            assert!(elem.0 <= 2);
        }
    }
}