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
use smallvec::smallvec;
use std::{borrow::Cow, str::FromStr, time::Duration};
use crate::iterators::*;
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 project = AutosarProject::new();
/// # let file = project.create_file("test", AutosarVersion::Autosar_00050).unwrap();
/// # let element = file.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(())
/// # }
/// ```
///
/// # Possible 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.lock().parent()
}
pub(crate) fn set_parent(&self, new_parent: ElementOrFile) {
self.0.lock().set_parent(new_parent)
}
/// Get the [ElementName] of the element
///
/// # Example
///
/// ```
/// # use autosar_data::*;
/// # let project = AutosarProject::new();
/// # let file = project.create_file("test", AutosarVersion::Autosar_00050).unwrap();
/// let element = file.root_element();
/// let element_name = element.element_name();
/// assert_eq!(element_name, ElementName::Autosar);
/// ```
pub fn element_name(&self) -> ElementName {
self.0.lock().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 project = AutosarProject::new();
/// # let file = project.create_file("test", AutosarVersion::Autosar_00050).unwrap();
/// # let element = file.root_element();
/// let element_type = element.element_type();
/// ```
pub fn element_type(&self) -> ElementType {
self.0.lock().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 project = AutosarProject::new();
/// # let file = project.create_file("test", AutosarVersion::Autosar_00050).unwrap();
/// # let element = file.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() {
/// // ...
/// }
/// ```
pub fn item_name(&self) -> Option<String> {
self.0.lock().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 project = AutosarProject::new();
/// # let file = project.create_file("test", AutosarVersion::Autosar_00050).unwrap();
/// # let element = file.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 project = AutosarProject::new();
/// # let file = project.create_file("test", AutosarVersion::Autosar_00050).unwrap();
/// # let element = file.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(CharacterData::String("the_new_name".to_string()));
/// }
/// ```
///
/// # Possible 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);
}
let file = self.file()?;
let project = file.project()?;
let version = file.version();
self.0.lock().set_item_name(new_name, &project, 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 project = AutosarProject::new();
/// # let file = project.create_file("test", AutosarVersion::Autosar_00050).unwrap();
/// # let element = file.root_element();
/// if element.is_identifiable() {
/// // ...
/// }
/// ```
pub fn is_identifiable(&self) -> bool {
self.0.lock().is_identifiable()
}
/// Returns true if the element should contain a referenct to another element
///
/// The function does not check if the reference is valid
///
/// # Example
///
/// ```
/// # use autosar_data::*;
/// # let project = AutosarProject::new();
/// # let file = project.create_file("test", AutosarVersion::Autosar_00050).unwrap();
/// # let element = file.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(...)
/// }
/// ```
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 project = AutosarProject::new();
/// # let file = project.create_file("test", AutosarVersion::Autosar_00050).unwrap();
/// # let element = file.root_element().create_sub_element(ElementName::ArPackages).and_then(|pkgs| pkgs.create_named_sub_element(ElementName::ArPackage, "name")).unwrap();
/// let path = element.path()?;
/// # Ok(())
/// # }
/// ```
///
/// # Possible 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.lock().path()
}
/// Get a reference to the [ArxmlFile] containing the current element
///
/// # Example
///
/// ```
/// # use autosar_data::*;
/// # fn main() -> Result<(), AutosarDataError> {
/// # let project = AutosarProject::new();
/// # let file = project.create_file("test", AutosarVersion::Autosar_00050).unwrap();
/// # let element = file.root_element().create_sub_element(ElementName::ArPackages).and_then(|pkgs| pkgs.create_named_sub_element(ElementName::ArPackage, "name")).unwrap();
/// let file = element.file()?;
/// # Ok(())
/// # }
/// ```
///
/// # Possible 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 file(&self) -> Result<ArxmlFile, AutosarDataError> {
let mut cur_elem = self.clone();
loop {
let parent = {
let element = cur_elem
.0
.try_lock_for(std::time::Duration::from_millis(10))
.ok_or_else(|| AutosarDataError::ParentElementLocked)?;
match &element.parent {
ElementOrFile::Element(weak_parent) => {
weak_parent.upgrade().ok_or(AutosarDataError::ItemDeleted)?
}
ElementOrFile::File(weak_arxmlfile) => {
return weak_arxmlfile.upgrade().ok_or(AutosarDataError::ItemDeleted)
}
ElementOrFile::None => return Err(AutosarDataError::ItemDeleted),
}
};
cur_elem = parent;
}
}
/// Get the [ContentType] of the current element
///
/// # Example
///
/// ```
/// # use autosar_data::*;
/// # let project = AutosarProject::new();
/// # let file = project.create_file("test", AutosarVersion::Autosar_00050).unwrap();
/// # let element = file.root_element();
/// if element.content_type() == ContentType::CharacterData {
/// // ...
/// }
/// ```
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 project = AutosarProject::new();
/// # let file = project.create_file("test", AutosarVersion::Autosar_00050).unwrap();
/// let element = file.root_element().create_sub_element(ElementName::ArPackages)?;
/// # Ok(())
/// # }
/// ```
///
/// # Possible 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().
pub fn create_sub_element(&self, element_name: ElementName) -> Result<Element, AutosarDataError> {
let version = self.file().map(|f| f.version())?;
self.0
.lock()
.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 project = AutosarProject::new();
/// # let file = project.create_file("test", AutosarVersion::Autosar_00050).unwrap();
/// let element = file.root_element().create_sub_element_at(ElementName::ArPackages, 0)?;
/// # Ok(())
/// # }
/// ```
///
/// # Possible 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
pub fn create_sub_element_at(
&self,
element_name: ElementName,
position: usize,
) -> Result<Element, AutosarDataError> {
let version = self.file().map(|f| f.version())?;
self.0
.lock()
.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 project = AutosarProject::new();
/// # let file = project.create_file("test", AutosarVersion::Autosar_00050).unwrap();
/// let pkgs_element = file.root_element().create_sub_element(ElementName::ArPackages)?;
/// let element = pkgs_element.create_named_sub_element(ElementName::ArPackage, "Package")?;
/// # Ok(())
/// # }
/// ```
///
/// # Possible 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.
pub fn create_named_sub_element(
&self,
element_name: ElementName,
item_name: &str,
) -> Result<Element, AutosarDataError> {
let file = self.file()?;
let project = file.project()?;
let version = file.version();
self.0
.lock()
.create_named_sub_element(self.downgrade(), element_name, item_name, &project, 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 project = AutosarProject::new();
/// # let file = project.create_file("test", AutosarVersion::Autosar_00050).unwrap();
/// let pkgs_element = file.root_element().create_sub_element(ElementName::ArPackages)?;
/// let element = pkgs_element.create_named_sub_element_at(ElementName::ArPackage, "Package", 0)?;
/// # Ok(())
/// # }
/// ```
///
/// # Possible 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.
pub fn create_named_sub_element_at(
&self,
element_name: ElementName,
item_name: &str,
position: usize,
) -> Result<Element, AutosarDataError> {
let file = self.file()?;
let project = file.project()?;
let version = file.version();
self.0.lock().create_named_sub_element_at(
self.downgrade(),
element_name,
item_name,
position,
&project,
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 [AutosarProject], it does not have to originate from the same project 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 project = AutosarProject::new();
/// # let file = project.create_file("test", AutosarVersion::Autosar_00050).unwrap();
/// # let pkgs_element = file.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 = project.get_element_by_path("/Package/Path").unwrap();
/// let element = base.create_copied_sub_element(&other_element)?;
/// # Ok(())
/// # }
/// ```
///
/// # Possible 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.
pub fn create_copied_sub_element(&self, other: &Element) -> Result<Element, AutosarDataError> {
let file = self.file()?;
let project = file.project()?;
let version = file.version();
self.0
.lock()
.create_copied_sub_element(self.downgrade(), other, &project, 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 [AutosarProject], it does not have to originate from the same project 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 project = AutosarProject::new();
/// # let file = project.create_file("test", AutosarVersion::Autosar_00050).unwrap();
/// # let pkgs_element = file.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 = project.get_element_by_path("/Package/Path").unwrap();
/// let element = base.create_copied_sub_element_at(&other_element, 0)?;
/// # Ok(())
/// # }
/// ```
///
/// # Possible 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.
pub fn create_copied_sub_element_at(&self, other: &Element, position: usize) -> Result<Element, AutosarDataError> {
let file = self.file()?;
let project = file.project()?;
let version = file.version();
self.0
.lock()
.create_copied_sub_element_at(self.downgrade(), other, position, &project, 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 AutosarProject
///
/// 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 project = AutosarProject::new();
/// # let file = project.create_file("test", AutosarVersion::Autosar_00050).unwrap();
/// # let pkgs_element = file.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 = project.get_element_by_path("/Package/Path").unwrap();
/// let element = base.move_element_here(&other_element)?;
/// # Ok(())
/// # }
/// ```
///
/// # Possible 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::VersionIncompatible]: 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
pub fn move_element_here(&self, move_element: &Element) -> Result<Element, AutosarDataError> {
let file_src = move_element.file()?;
let project_src = file_src.project()?;
let version = self.file().map(|f| f.version())?;
let project = self.file().and_then(|f| f.project())?;
let version_src = file_src.version();
if version != version_src {
return Err(AutosarDataError::VersionIncompatible);
}
self.0
.lock()
.move_element_here(self.downgrade(), move_element, &project, &project_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 AutosarProject
///
/// 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 project = AutosarProject::new();
/// # let file = project.create_file("test", AutosarVersion::Autosar_00050).unwrap();
/// # let pkgs_element = file.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 = project.get_element_by_path("/Package/Path").unwrap();
/// let element = base.move_element_here_at(&other_element, 0)?;
/// # Ok(())
/// # }
/// ```
///
/// # Possible 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::VersionIncompatible]: 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.
pub fn move_element_here_at(&self, move_element: &Element, position: usize) -> Result<Element, AutosarDataError> {
let file_src = move_element.file()?;
let project_src = file_src.project()?;
let version = self.file().map(|f| f.version())?;
let project = self.file().and_then(|f| f.project())?;
let version_src = file_src.version();
if version != version_src {
return Err(AutosarDataError::VersionIncompatible);
}
self.0.lock().move_element_here_at(
self.downgrade(),
move_element,
position,
&project,
&project_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 project = AutosarProject::new();
/// # let file = project.create_file("test", AutosarVersion::Autosar_00050).unwrap();
/// let packages = file.root_element().create_sub_element(ElementName::ArPackages)?;
/// file.root_element().remove_sub_element(packages)?;
/// # Ok(())
/// # }
/// ```
///
/// # Possible 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 project = self.file().and_then(|f| f.project())?;
self.0.lock().remove_sub_element(sub_element, &project)
}
/// 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 project = AutosarProject::new();
/// # let file = project.create_file("test", AutosarVersion::Autosar_00050).unwrap();
/// # let elements = file.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(())
/// # }
/// ```
///
/// # Possible 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
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 Ok(enum_item) = EnumItem::from_str(target.element_name().to_str()) {
let file = self.file()?;
let project = file.project()?;
let version = file.version();
let mut element = self.0.lock();
// 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) {
// if this reference previously referenced some other element, update
if let Some(CharacterData::String(old_ref)) = element.character_data() {
project.fix_reference_origins(&old_ref, &new_ref, self.downgrade());
} else {
// else initialise the new reference
project.add_reference_origin(&new_ref, self.downgrade());
}
element.set_character_data(CharacterData::String(new_ref), version)?;
}
Ok(())
} 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 project = AutosarProject::new();
/// # let file = project.create_file("test", AutosarVersion::Autosar_00050).unwrap();
/// # let elements = file.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(())
/// # }
/// ```
///
/// # Possible 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 project = self.file().and_then(|file| file.project())?;
let target_elem = project
.get_element_by_path(&reference)
.ok_or_else(|| AutosarDataError::InvalidReference)?;
let dest = self
.attribute_string(AttributeName::Dest)
.ok_or_else(|| AutosarDataError::InvalidReference)?;
if dest == target_elem.element_name().to_str() {
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
///
/// # Example
///
/// ```
/// # use autosar_data::*;
/// # fn main() -> Result<(), AutosarDataError> {
/// # let project = AutosarProject::new();
/// # let file = project.create_file("test", AutosarVersion::Autosar_00050).unwrap();
/// # let element = file.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(CharacterData::String("value".to_string()))?;
/// # Ok(())
/// # }
/// ```
///
/// # Possible 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 whoch does not contain character data
pub fn set_character_data(&self, chardata: CharacterData) -> Result<(), AutosarDataError> {
let elemtype = self.elemtype();
if elemtype.content_mode() == ContentMode::Characters {
if let Some(cdata_spec) = elemtype.chardata_spec() {
let project = self.file().and_then(|file| file.project())?;
let version = self.file().map(|f| f.version())?;
if CharacterData::check_value(&chardata, cdata_spec, version) {
// 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.lock();
if element.content.is_empty() {
element.content.push(ElementContent::CharacterData(chardata));
} else {
element.content[0] = ElementContent::CharacterData(chardata);
}
}
// short-name: make sure the hashmap in the top-level AutosarProject 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()?;
project.fix_identifiables(&prev_path, &new_path);
}
}
// reference: update the references hashmap in the top-level AutosarProject
if elemtype.is_ref() {
if let Some(CharacterData::String(refval)) = self.character_data() {
if let Some(old_refval) = old_refval {
project.fix_reference_origins(&old_refval, &refval, self.downgrade());
}
}
}
return Ok(());
}
}
}
Err(AutosarDataError::IncorrectContentType)
}
/// 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 project = AutosarProject::new();
/// # let file = project.create_file("test", AutosarVersion::Autosar_00050).unwrap();
/// # let element = file.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(())
/// # }
/// ```
///
/// # Possible 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.lock();
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)
}
}
/// 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 project = AutosarProject::new();
/// # let file = project.create_file("test", AutosarVersion::Autosar_00050).unwrap();
/// # let element = file.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(())
/// # }
/// ```
///
/// # Possible 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.lock();
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)
}
}
/// 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 project = AutosarProject::new();
/// # let file = project.create_file("test", AutosarVersion::Autosar_00050).unwrap();
/// # let element = file.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::Double(dblval)) => {},
/// None => {},
/// }
/// # Ok(())
/// # }
/// ```
pub fn character_data(&self) -> Option<CharacterData> {
self.0.lock().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 project = AutosarProject::new();
/// # let file = project.create_file("test", AutosarVersion::Autosar_00050).unwrap();
/// # let element = file.root_element();
/// for content_item in element.content() {
/// match content_item {
/// ElementContent::CharacterData(data) => {},
/// ElementContent::Element(element) => {},
/// }
/// }
/// ```
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 project = AutosarProject::new();
/// # let file = project.create_file("test", AutosarVersion::Autosar_00050).unwrap();
/// # let element = file.root_element();
/// let weak_element = element.downgrade();
/// ```
pub fn downgrade(&self) -> WeakElement {
WeakElement(Arc::downgrade(&self.0))
}
/// Create an iterator over all sub elements of this element
///
/// # Example
///
/// ```
/// # use autosar_data::*;
/// # let project = AutosarProject::new();
/// # let file = project.create_file("test", AutosarVersion::Autosar_00050).unwrap();
/// # let element = file.root_element();
/// for sub_element in element.sub_elements() {
/// // ...
/// }
/// ```
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 project = AutosarProject::new();
/// # let file = project.create_file("test", AutosarVersion::Autosar_00050).unwrap();
/// # let pkg = file.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(())
/// # }
/// ```
pub fn get_sub_element(&self, name: ElementName) -> Option<Element> {
let locked_elem = self.0.lock();
for item in &locked_elem.content {
if let ElementContent::Element(subelem) = item {
if subelem.element_name() == name {
return Some(subelem.clone());
}
}
}
None
}
/// 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 project = AutosarProject::new();
/// # let file = project.create_file("test", AutosarVersion::Autosar_00050).unwrap();
/// # let element = file.root_element();
/// for (depth, elem) in element.elements_dfs() {
/// // ...
/// }
/// ```
pub fn elements_dfs(&self) -> ElementsDfsIterator {
ElementsDfsIterator::new(self)
}
/// Create an iterator over all the attributes in this element
///
/// # Example
///
/// ```
/// # use autosar_data::*;
/// # let project = AutosarProject::new();
/// # let file = project.create_file("test", AutosarVersion::Autosar_00050).unwrap();
/// # let element = file.root_element();
/// for attribute in element.attributes() {
/// println!("{} = {}", attribute.attrname, attribute.content);
/// }
/// ```
pub fn attributes(&self) -> AttributeIterator {
AttributeIterator {
element: self.clone(),
index: 0,
}
}
/// Get the value of an attribute by name
///
/// # Example
///
/// ```
/// # use autosar_data::*;
/// # let project = AutosarProject::new();
/// # let file = project.create_file("test", AutosarVersion::Autosar_00050).unwrap();
/// let value = file.root_element().attribute_value(AttributeName::xsiSchemalocation);
/// ```
pub fn attribute_value(&self, attrname: AttributeName) -> Option<CharacterData> {
self.0.lock().attribute_value(attrname)
}
/// Get the content of an attribute as a string
///
/// # Example
///
/// ```
/// # use autosar_data::*;
/// # let project = AutosarProject::new();
/// # let file = project.create_file("test", AutosarVersion::Autosar_00050).unwrap();
/// # let element = file.root_element();
/// let value = element.attribute_string(AttributeName::Dest);
/// ```
pub fn attribute_string(&self, attrname: AttributeName) -> Option<String> {
self.0.lock().attribute_string(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 true if the attribute was set.
///
/// ```
/// # use autosar_data::*;
/// # let project = AutosarProject::new();
/// # let file = project.create_file("test", AutosarVersion::Autosar_00050).unwrap();
/// # let element = file.root_element();
/// let result = element.set_attribute(AttributeName::Dest, CharacterData::UnsignedInteger(42));
/// assert_eq!(result, false);
/// ```
pub fn set_attribute(&self, attrname: AttributeName, value: CharacterData) -> bool {
if let Ok(version) = self.file().map(|f| f.version()) {
return self.0.lock().set_attribute_internal(attrname, value, version);
}
false
}
/// 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 true if the attribute was set.
///
/// ```
/// # use autosar_data::*;
/// # let project = AutosarProject::new();
/// # let file = project.create_file("test", AutosarVersion::Autosar_00050).unwrap();
/// # let element = file.root_element();
/// let result = element.set_attribute_string(AttributeName::T, "2022-01-31T13:59:59Z");
/// assert_eq!(result, true);
/// ```
pub fn set_attribute_string(&self, attrname: AttributeName, stringvalue: &str) -> bool {
if let Ok(version) = self.file().map(|f| f.version()) {
let mut locked_elem = self.0.lock();
if let Some((character_data_spec, _, _)) = locked_elem.elemtype.find_attribute_spec(attrname) {
if let Some(value) = CharacterData::parse(stringvalue, character_data_spec, version) {
if let Some(attr) = locked_elem.attributes.iter_mut().find(|attr| attr.attrname == attrname) {
attr.content = value;
} else {
locked_elem.attributes.push(Attribute {
attrname,
content: value,
});
}
return true;
}
}
}
false
}
/// Remove an attribute from the element
///
/// Returns true if the attribute existed and could be removed.
///
/// # Example
///
/// ```
/// # use autosar_data::*;
/// # let project = AutosarProject::new();
/// # let file = project.create_file("test", AutosarVersion::Autosar_00050).unwrap();
/// let result = file.root_element().remove_attribute(AttributeName::xsiSchemalocation);
/// // xsiSchemalocation exists in the AUTOSAR element, but it is mandatory and cannot be removed
/// assert_eq!(result, false);
/// ```
pub fn remove_attribute(&self, attrname: AttributeName) -> bool {
self.0.lock().remove_attribute(attrname)
}
/// 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 project = AutosarProject::new();
/// # let file = project.create_file("test", AutosarVersion::Autosar_00050).unwrap();
/// # let element = file.root_element();
/// let text = element.serialize();
/// ```
pub fn serialize(&self) -> String {
let mut outstring = String::new();
self.serialize_internal(&mut outstring, 0, false);
outstring
}
pub(crate) fn serialize_internal(&self, outstring: &mut String, indent: usize, inline: bool) {
let element_name = self.element_name().to_str();
// write the opening tag on a new line and indent it
if !inline {
self.serialize_newline_indent(outstring, indent);
}
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() {
subelem.serialize_internal(outstring, indent + 1, false);
}
// 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
let element = self.0.lock();
if let Some(content) = element.content.get(0) {
match content {
ElementContent::Element(_) => panic!("Forbidden: Element in CharacterData"),
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('>');
}
ContentType::Mixed => {
for item in self.content() {
match item {
ElementContent::Element(subelem) => {
subelem.serialize_internal(outstring, indent + 1, true);
}
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('>');
}
}
}
fn serialize_newline_indent(&self, 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.lock();
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.lock().elemtype
}
/// check if the sub elements and attributes of this element are compatible with some target_version
pub(crate) fn check_version_compatibility(&self, target_version: AutosarVersion) -> (Vec<CompatibilityError>, u32) {
let mut compat_errors = Vec::new();
let mut overall_version_mask = u32::MAX;
// check the compatibility of all the attributes in this element
{
let element = self.0.lock();
for attribute in &element.attributes {
// find the specification for the current attribute
if let Some((value_spec, _, version_mask)) = element.elemtype.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,
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() {
let (mut sub_element_errors, sub_element_mask) = sub_element.check_version_compatibility(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 project = AutosarProject::new();
/// # let file = project.create_file("test", AutosarVersion::Autosar_00050).unwrap();
/// # let element = file.root_element();
/// for (element_name, is_named, is_allowed) in element.list_valid_sub_elements() {
/// // ...
/// }
/// ```
pub fn list_valid_sub_elements(&self) -> Vec<(ElementName, bool, bool)> {
let etype = self.0.lock().elemtype;
let mut valid_sub_elements = Vec::new();
if let Ok(version) = self.file().map(|f| f.version()) {
for (element_name, _, version_mask, named_mask) in etype.sub_element_spec_iter() {
if version.compatible(version_mask) {
let named = version.compatible(named_mask);
let available = self.0.lock().find_element_insert_pos(element_name, version).is_ok();
valid_sub_elements.push((element_name, named, available));
}
}
}
valid_sub_elements
}
}
/// ElementRaw provides the internal implementation of (almost) all Element operations
///
/// To get an ElementRaw the Element operation must lock the element, so all of these operations run with at least one lock held.
///
/// Note regarding deadlock avoidance:
/// Consider the case where two element operations are started in parallel on different threads.
/// One calls file() or path() and traverses the hierarchy of elements upward
/// root <- element <- element <- current element (locked)
///
/// The other calls e.g. create_copied_sub_element() or remove_sub_element() and wants to lock all of its sub elements
/// root -> current element (locked) -> element -> element
///
/// These two operations could deadlock if they operate on the same tree of elements.
/// To avoid this, parent element locks can only be acquired with try_lock(). If the lock is not acquired within a
/// reasonable time (10ms is used here), then the operation aborts with a ParentElementLocked error.
impl ElementRaw {
/// get the parent element of the current element
pub(crate) fn parent(&self) -> Result<Option<Element>, AutosarDataError> {
match &self.parent {
ElementOrFile::Element(parent) => {
// for items that should have a parent, getting it is not allowed to return None
let parent = parent.upgrade().ok_or(AutosarDataError::ItemDeleted)?;
Ok(Some(parent))
}
ElementOrFile::File(_) => Ok(None),
ElementOrFile::None => Err(AutosarDataError::ItemDeleted),
}
}
pub(crate) fn set_parent(&mut self, new_parent: ElementOrFile) {
self.parent = new_parent;
}
/// get the [ElementName] of the element
pub(crate) fn element_name(&self) -> ElementName {
self.elemname
}
/// get the name of an identifiable element
pub(crate) fn item_name(&self) -> Option<String> {
// is this element named in any autosar version? - If it's not named here then we'll simply fail in the next step
if self.elemtype.is_named() {
// if an item is named, then the SHORT-NAME sub element that contains the name is always the first sub element
if let Some(ElementContent::Element(subelem)) = self.content.get(0) {
// why use try_lock? It is possible that we're calling path() while already holding the lock on subelem.
// In this case path() descends to the parent, then calls item_name() and would deadlock.
// This case happens when subelem is *not* a ShortName but elemtype.is_named() returns true because there
// is a name in some other version, so it is acceptable to return None when locking fails
if let Some(subelem_locked) = subelem.0.try_lock_for(Duration::from_millis(10)) {
if subelem_locked.elemname == ElementName::ShortName {
if let Some(CharacterData::String(name)) = subelem_locked.character_data() {
return Some(name);
}
}
}
}
}
None
}
/// Set the item name of this element
pub(crate) fn set_item_name(
&self,
new_name: &str,
project: &AutosarProject,
version: AutosarVersion,
) -> Result<(), AutosarDataError> {
// a new name is required
if new_name.is_empty() {
return Err(AutosarDataError::ItemNameRequired);
}
if let Some(current_name) = self.item_name() {
// bail out early if the name is actually the same
if current_name == new_name {
return Ok(());
}
let old_path = self.path()?;
let new_path = format!("{}{new_name}", old_path.strip_suffix(¤t_name).unwrap());
if project.get_element_by_path(&new_path).is_some() {
return Err(AutosarDataError::DuplicateItemName);
}
// if an item is named, then the SHORT-NAME sub element that contains the name is always the first sub element
if let Some(ElementContent::Element(subelem_wrapped)) = self.content.get(0) {
let mut subelem = subelem_wrapped.0.lock();
if subelem.element_name() == ElementName::ShortName {
subelem.set_character_data(CharacterData::String(new_name.to_owned()), version)?;
project.fix_identifiables(&old_path, &new_path);
let new_prefix = new_path;
let mut project_locked = project.0.lock();
// check all references and update those that point to this element or its sub elements
let refpaths = project_locked
.reference_origins
.keys()
.cloned()
.collect::<Vec<String>>();
for refpath in refpaths {
// if the existing reference has the old path as a prefix, then it needs to be updated
if let Some(partial_path) = refpath.strip_prefix(&old_path) {
// prevent ref updates from being applied to e.g. /package10 while renaming /package1
if partial_path.is_empty() || partial_path.starts_with('/') {
if let Some(reflist) = project_locked.reference_origins.remove(&refpath) {
let refpath_new = format!("{new_prefix}{partial_path}");
for weak_ref_elem in &reflist {
if let Some(ref_elem) = weak_ref_elem.upgrade() {
let mut ref_elem_locked = ref_elem.0.lock();
// can't use .set_character_data() here, because the project is locked
ref_elem_locked.content[0] = ElementContent::CharacterData(
CharacterData::String(refpath_new.clone()),
);
}
}
project_locked.reference_origins.insert(refpath_new, reflist);
}
}
}
}
}
}
Ok(())
} else {
Err(AutosarDataError::ElementNotIdentifiable)
}
}
/// returns true if the element is identifiable
pub(crate) fn is_identifiable(&self) -> bool {
// is this element named in any autosar version? - If it's not named here then we'll simply fail in the next step
if self.elemtype.is_named() {
// if an item is named, then the SHORT-NAME sub element that contains the name is always the first sub element
if let Some(ElementContent::Element(subelem)) = self.content.get(0) {
if subelem.element_name() == ElementName::ShortName {
return true;
}
}
}
false
}
/// get the Autosar path of an identifiable element
///
/// returns Some(path) if the element is identifiable, None otherwise
pub(crate) fn path(&self) -> Result<String, AutosarDataError> {
if self.is_identifiable() {
self.path_unchecked()
} else {
Err(AutosarDataError::ElementNotIdentifiable)
}
}
fn path_unchecked(&self) -> Result<String, AutosarDataError> {
let mut path_components = vec![];
if let Some(name) = self.item_name() {
path_components.push(name);
}
let mut cur_elem_opt = self.parent()?;
while let Some(cur_elem) = &cur_elem_opt {
if let Some(name) = cur_elem
.0
.try_lock_for(std::time::Duration::from_millis(10))
.ok_or_else(|| AutosarDataError::ParentElementLocked)?
.item_name()
{
path_components.push(name);
}
cur_elem_opt = cur_elem.parent()?;
}
path_components.push(String::new());
path_components.reverse();
let path = path_components.join("/");
Ok(path)
}
/// 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.
pub(crate) fn create_sub_element(
&mut self,
self_weak: WeakElement,
element_name: ElementName,
version: AutosarVersion,
) -> Result<Element, AutosarDataError> {
let (_start_pos, end_pos) = self.find_element_insert_pos(element_name, version)?;
self.create_sub_element_inner(self_weak, element_name, end_pos, 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 ooutside that range then the function fails.
pub(crate) fn create_sub_element_at(
&mut self,
self_weak: WeakElement,
element_name: ElementName,
position: usize,
version: AutosarVersion,
) -> Result<Element, AutosarDataError> {
let (start_pos, end_pos) = self.find_element_insert_pos(element_name, version)?;
if start_pos <= position && position <= end_pos {
self.create_sub_element_inner(self_weak, element_name, position, version)
} else {
Err(AutosarDataError::InvalidPosition)
}
}
/// helper function for create_sub_element and create_sub_element_at
fn create_sub_element_inner(
&mut self,
self_weak: WeakElement,
element_name: ElementName,
position: usize,
version: AutosarVersion,
) -> Result<Element, AutosarDataError> {
let (elemtype, _) = self
.elemtype
.find_sub_element(element_name, version as u32)
.ok_or_else(|| AutosarDataError::InvalidSubElement)?;
if elemtype.is_named_in_version(version) {
Err(AutosarDataError::ItemNameRequired)
} else {
let sub_element = Element(Arc::new(Mutex::new(ElementRaw {
parent: ElementOrFile::Element(self_weak),
elemname: element_name,
elemtype,
content: smallvec![],
attributes: smallvec![],
})));
self.content
.insert(position, ElementContent::Element(sub_element.clone()));
Ok(sub_element)
}
}
/// 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.
pub(crate) fn create_named_sub_element(
&mut self,
self_weak: WeakElement,
element_name: ElementName,
item_name: &str,
project: &AutosarProject,
version: AutosarVersion,
) -> Result<Element, AutosarDataError> {
let (_start_pos, end_pos) = self.find_element_insert_pos(element_name, version)?;
self.create_named_sub_element_inner(self_weak, element_name, item_name, end_pos, project, 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 ooutside that range then the function fails.
/// This method can only be used to create identifiable sub elements.
pub(crate) fn create_named_sub_element_at(
&mut self,
self_weak: WeakElement,
element_name: ElementName,
item_name: &str,
position: usize,
project: &AutosarProject,
version: AutosarVersion,
) -> Result<Element, AutosarDataError> {
let (start_pos, end_pos) = self.find_element_insert_pos(element_name, version)?;
if start_pos <= position && position <= end_pos {
self.create_named_sub_element_inner(self_weak, element_name, item_name, position, project, version)
} else {
Err(AutosarDataError::InvalidPosition)
}
}
/// helper function for create_named_sub_element and create_named_sub_element_at
fn create_named_sub_element_inner(
&mut self,
self_weak: WeakElement,
element_name: ElementName,
item_name: &str,
position: usize,
project: &AutosarProject,
version: AutosarVersion,
) -> Result<Element, AutosarDataError> {
if item_name.is_empty() {
return Err(AutosarDataError::ItemNameRequired);
}
let item_name_cdata = CharacterData::String(item_name.to_owned());
let (elemtype, _) = self
.elemtype
.find_sub_element(element_name, version as u32)
.ok_or_else(|| AutosarDataError::InvalidSubElement)?;
if elemtype.is_named_in_version(version) {
// verify that the given item_name is actually a valid name
if !elemtype
.find_sub_element(ElementName::ShortName, version as u32)
.and_then(|(se_type, _)| se_type.chardata_spec())
.map(|cdata_spec| CharacterData::check_value(&item_name_cdata, cdata_spec, version))
.unwrap_or(false)
{
return Err(AutosarDataError::IncorrectContentType);
}
let parent_path = self.path_unchecked()?;
let path = format!("{parent_path}/{item_name}");
// verify that the name is unique: there must be no existing element that already has this autosar path
if project.get_element_by_path(&path).is_some() {
return Err(AutosarDataError::DuplicateItemName);
}
// create the new element
let sub_element = Element(Arc::new(Mutex::new(ElementRaw {
parent: ElementOrFile::Element(self_weak),
elemname: element_name,
elemtype,
content: smallvec![],
attributes: smallvec![],
})));
self.content
.insert(position, ElementContent::Element(sub_element.clone()));
// create a SHORT-NAME for the sub element
let shortname_element =
sub_element
.0
.lock()
.create_sub_element(sub_element.downgrade(), ElementName::ShortName, version)?;
let _ = shortname_element.0.lock().set_character_data(item_name_cdata, version);
project.add_identifiable(path, sub_element.downgrade());
Ok(sub_element)
} else {
Err(AutosarDataError::ElementNotIdentifiable)
}
}
/// create a deep copy of the given element and insert it as a sub-element
pub(crate) fn create_copied_sub_element(
&mut self,
self_weak: WeakElement,
other: &Element,
project: &AutosarProject,
version: AutosarVersion,
) -> Result<Element, AutosarDataError> {
let other_elemname = {
// need to do this inside its own scope to limit the lifetime of the mutex
let other_element = other.0.lock();
other_element.elemname
};
let (_, end) = self.find_element_insert_pos(other_elemname, version)?;
self.create_copied_sub_element_inner(self_weak, other, end, project, version)
}
/// create a deep copy of the given element and insert it as a sub-element at the given position
pub(crate) fn create_copied_sub_element_at(
&mut self,
self_weak: WeakElement,
other: &Element,
position: usize,
project: &AutosarProject,
version: AutosarVersion,
) -> Result<Element, AutosarDataError> {
let other_elemname = {
// need to do this inside its own scope to limit the lifetime of the mutex
let other_element = other.0.lock();
other_element.elemname
};
let (start_pos, end_pos) = self.find_element_insert_pos(other_elemname, version)?;
if start_pos <= position && position <= end_pos {
self.create_copied_sub_element_inner(self_weak, other, position, project, version)
} else {
Err(AutosarDataError::InvalidPosition)
}
}
fn create_copied_sub_element_inner(
&mut self,
self_weak: WeakElement,
other: &Element,
position: usize,
project: &AutosarProject,
version: AutosarVersion,
) -> Result<Element, AutosarDataError> {
// Arc overrides clone() so that it only manipulates the reference count, so a separate deep_copy operation is needed here.
// Additionally, implementing this manually provides the opportunity to filter out
// elements that ae not compatible with the version of the current file.
let newelem = other.0.lock().deep_copy(version)?;
let path = self.path_unchecked()?;
// set the parent of the newelem - the methods path(), containing_file(), etc become available on newelem
newelem.set_parent(ElementOrFile::Element(self_weak));
if newelem.is_identifiable() {
newelem.0.lock().make_unique_item_name(project, &path)?;
}
let mut path_parts: Vec<Option<String>> = vec![Some(path)];
for (depth, sub_elem) in newelem.elements_dfs() {
while path_parts.len() > depth + 1 {
path_parts.pop();
}
// add each identifiable sub element to the identifiables hashmap
if sub_elem.is_identifiable() {
path_parts.push(sub_elem.item_name());
let sub_elem_path = path_parts
.iter()
.filter_map(|x| x.clone())
.collect::<Vec<String>>()
.join("/");
project.add_identifiable(sub_elem_path, sub_elem.downgrade());
} else {
path_parts.push(None);
}
// add all references to the reference_origins hashmap
if sub_elem.is_reference() {
if let Some(CharacterData::String(reference)) = sub_elem.character_data() {
project.add_reference_origin(&reference, sub_elem.downgrade())
}
}
}
self.content.insert(position, ElementContent::Element(newelem.clone()));
Ok(newelem)
}
/// perform a deep copy of an element, but keep only those sub elements etc, which are compatible with target_version
fn deep_copy(&self, target_version: AutosarVersion) -> Result<Element, AutosarDataError> {
let copy_wrapped = Element(Arc::new(Mutex::new(ElementRaw {
elemname: self.elemname,
elemtype: self.elemtype,
content: SmallVec::with_capacity(self.content.len()),
attributes: SmallVec::with_capacity(self.attributes.len()),
parent: ElementOrFile::None,
})));
{
let mut copy = copy_wrapped.0.lock();
// copy all the attributes
for attribute in &self.attributes {
// get the specification of the attribute
let (cdataspec, required, attr_version_mask) = self
.elemtype
.find_attribute_spec(attribute.attrname)
.ok_or_else(|| AutosarDataError::VersionIncompatible)?;
// check if the attribute is compatible with the target version
if target_version.compatible(attr_version_mask)
&& attribute
.content
.check_version_compatibility(cdataspec, target_version)
.0
{
copy.attributes.push(attribute.clone());
} else if required {
return Err(AutosarDataError::VersionIncompatible);
} else {
// no action, the attribute is not compatible, but it's not required either
}
}
// copy all content: sub elements and text items
for content_item in &self.content {
match content_item {
ElementContent::Element(sub_elem) => {
let sub_elem_name = sub_elem.element_name();
// since find_sub_element already considers the version, finding the element also means it's valid in the target_version
if self
.elemtype
.find_sub_element(sub_elem_name, target_version as u32)
.is_some()
{
if let Ok(copied_sub_elem) = sub_elem.0.lock().deep_copy(target_version) {
copied_sub_elem.0.lock().parent = ElementOrFile::Element(copy_wrapped.downgrade());
copy.content.push(ElementContent::Element(copied_sub_elem));
}
}
}
ElementContent::CharacterData(cdata) => {
copy.content.push(ElementContent::CharacterData(cdata.clone()));
}
}
}
}
Ok(copy_wrapped)
}
/// make_unique_item_name ensures that a copied element has a unique name
fn make_unique_item_name(&self, project: &AutosarProject, parent_path: &str) -> Result<String, AutosarDataError> {
let orig_name = self
.item_name()
.ok_or_else(|| AutosarDataError::ElementNotIdentifiable)?;
let mut name = orig_name.clone();
let mut counter = 1;
let mut path = format!("{parent_path}/{orig_name}");
while project.get_element_by_path(&path).is_some() {
name = format!("{orig_name}_{counter}");
counter += 1;
path = format!("{parent_path}/{name}");
}
if counter > 1 {
// set the name directly by modifying the character content of the short name element
// note: the method set_character_data is not suitable here, because it updates the identifiables hashmap
if let Some(ElementContent::Element(short_name_elem)) = self.content.get(0) {
let mut sn_element = short_name_elem.0.lock();
if sn_element.elemname != ElementName::ShortName {
return Err(AutosarDataError::InvalidSubElement);
}
sn_element.content.clear();
sn_element
.content
.push(ElementContent::CharacterData(CharacterData::String(name.clone())));
}
}
Ok(name)
}
/// 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 AutosarProject
///
/// 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.
pub(crate) fn move_element_here(
&mut self,
self_weak: WeakElement,
move_element: &Element,
project: &AutosarProject,
project_src: &AutosarProject,
version: AutosarVersion,
) -> Result<Element, AutosarDataError> {
let move_element_name = move_element.element_name();
let (_, end_pos) = self.find_element_insert_pos(move_element_name, version)?;
if project == project_src {
let src_parent = move_element
.parent()?
.ok_or_else(|| AutosarDataError::InvalidSubElement)?;
if src_parent.downgrade() == self_weak {
Ok(move_element.clone())
} else {
// move the element within the same project
self.move_element_local(self_weak, move_element, end_pos, project, version)
}
} else {
// move the element between different projects
self.move_element_full(self_weak, move_element, end_pos, project, project_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 AutosarProject
///
/// 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.
pub(crate) fn move_element_here_at(
&mut self,
self_weak: WeakElement,
move_element: &Element,
position: usize,
project: &AutosarProject,
project_src: &AutosarProject,
version: AutosarVersion,
) -> Result<Element, AutosarDataError> {
let move_element_name = move_element.element_name();
let (start_pos, end_pos) = self.find_element_insert_pos(move_element_name, version)?;
if start_pos <= position && position <= end_pos {
if project == project_src {
let src_parent = move_element
.parent()?
.ok_or_else(|| AutosarDataError::InvalidSubElement)?;
if src_parent.downgrade() == self_weak {
// move new_element to a different position within the current element
self.move_element_position(move_element, position)
} else {
// move the element within the same project
self.move_element_local(self_weak, move_element, position, project, version)
}
} else {
// move the element between different projects
self.move_element_full(self_weak, move_element, position, project, project_src, version)
}
} else {
Err(AutosarDataError::InvalidPosition)
}
}
/// move a sub element within the current element to a different position
fn move_element_position(&mut self, move_element: &Element, position: usize) -> Result<Element, AutosarDataError> {
// need to check self.content.len() here, because find_element_insert_pos() will allow values up to len()+1
// that's correct when adding elements to self.content, but not strict enough here
if position < self.content.len() {
let current_position = self
.content
.iter()
.enumerate()
.find(|(_, item)| {
if let ElementContent::Element(elem) = item {
*elem == *move_element
} else {
false
}
})
.map(|(idx, _)| idx)
.unwrap();
if current_position < position {
// the first element in the subslice is moved to the last position by rotate_left
self.content[current_position..=position].rotate_left(1);
} else {
// the last element in the subslice is moved to the first position by rotate_right
self.content[position..=current_position].rotate_right(1);
}
Ok(move_element.clone())
} else {
Err(AutosarDataError::InvalidPosition)
}
}
// remove an element from its current parent and make it a sub element of this element
// the current location must be within the same project
// All references to the moved sub element will be updated to refer to the new path
fn move_element_local(
&mut self,
self_weak: WeakElement,
move_element: &Element,
position: usize,
project: &AutosarProject,
version: AutosarVersion,
) -> Result<Element, AutosarDataError> {
// check if self (target of the move) is a sub element of new_element
// if it is, then the move is not allowed
let mut wrapped_parent = self.parent.clone();
while let ElementOrFile::Element(weak_parent) = wrapped_parent {
let parent = weak_parent.upgrade().ok_or(AutosarDataError::ItemDeleted)?;
if parent == *move_element {
return Err(AutosarDataError::ForbiddenMoveToSubElement);
}
wrapped_parent = parent.0.lock().parent.clone();
}
let src_parent = move_element
.parent()?
.ok_or_else(|| AutosarDataError::InvalidSubElement)?;
if src_parent.downgrade() == self_weak {
return Ok(move_element.clone());
}
// collect the paths of all identifiable elements under new_element before moving it
let original_paths: Vec<String> = move_element.elements_dfs().filter_map(|(_, e)| e.path().ok()).collect();
let src_path_prefix = move_element.0.lock().path_unchecked()?;
let dest_path_prefix = self.path_unchecked()?;
// limit the lifetime of the mutex on src_parent
{
// lock the source parent element and remove the move_element from its content list
let mut src_parent_locked = src_parent
.0
.try_lock_for(Duration::from_millis(10))
.ok_or_else(|| AutosarDataError::ParentElementLocked)?;
let idx = src_parent_locked
.content
.iter()
.enumerate()
.find(|(_, item)| {
if let ElementContent::Element(elem) = item {
*elem == *move_element
} else {
false
}
})
.map(|(idx, _)| idx)
.unwrap();
src_parent_locked.content.remove(idx);
}
// set the parent of the new element to the current element
move_element.0.lock().parent = ElementOrFile::Element(self_weak);
let dest_path = if move_element.is_identifiable() {
let new_name = move_element
.0
.lock()
.make_unique_item_name(project, &dest_path_prefix)?;
format!("{dest_path_prefix}/{new_name}")
} else {
dest_path_prefix
};
// fix the identifiables cache
if move_element.is_identifiable() {
// simple case: the moved element is identifiable; fix_identifiables automatically handles the sub-elements
project.fix_identifiables(&src_path_prefix, &dest_path);
} else {
// the moved element is not identifiable, so its identifiable sub-elements must be fixed individually
for orig_path in &original_paths {
if let Some(suffix) = orig_path.strip_prefix(&src_path_prefix) {
let updated_path = format!("{dest_path}{suffix}");
project.fix_identifiables(orig_path, &updated_path);
}
}
}
// the move_element was moved within this autosar project, so we can update all other references pointing to it
let mut project_locked = project.0.lock();
for orig_ref in &original_paths {
if let Some(suffix) = orig_ref.strip_prefix(&src_path_prefix) {
// e.g. orig_ref = "/Pkg/Foo/Sub/Element" and src_path_prefix = "/Pkg/Foo" then suffix = "/Sub/Element"
// strip prefix can't fail, because all original_paths have the src_path_prefix
if let Some(ref_elements) = project_locked.reference_origins.remove(orig_ref) {
let refstr = format!("{dest_path}{suffix}");
for ref_element_weak in &ref_elements {
if let Some(ref_element) = ref_element_weak.upgrade() {
ref_element
.0
.lock()
.set_character_data(CharacterData::String(refstr.clone()), version)?;
}
}
project_locked.reference_origins.insert(refstr, ref_elements);
}
}
}
// insert move_element
self.content
.insert(position, ElementContent::Element(move_element.clone()));
Ok(move_element.clone())
}
// remove an element from its current parent and make it a sub element of this element
// This is a move between two different projects
// If the moved sub element contains its own tree of sub elements, then references within that tree will be updated
fn move_element_full(
&mut self,
self_weak: WeakElement,
move_element: &Element,
position: usize,
project: &AutosarProject,
project_src: &AutosarProject,
version: AutosarVersion,
) -> Result<Element, AutosarDataError> {
let src_path_prefix = move_element.0.lock().path_unchecked()?;
let dest_path_prefix = self.path_unchecked()?;
let src_parent = move_element
.parent()?
.ok_or_else(|| AutosarDataError::InvalidSubElement)?;
// collect the paths of all identifiable elements under move_element before moving it
let original_paths: FxHashMap<String, Element> = move_element
.elements_dfs()
.filter_map(|(_, e)| e.path().ok().map(|path| (path, e)))
.collect();
// collect all reference targets and referring elements under move_element
let original_refs: Vec<(String, Element)> = move_element
.elements_dfs()
.filter(|(_, e)| e.is_reference())
.filter_map(|(_, e)| e.character_data().map(|data| (data.to_string(), e)))
.collect();
// limit the lifetime of the mutex on src_parent
{
// lock the parent of the new element and remove it from the parent's content list
let mut src_parent_locked = src_parent
.0
.try_lock_for(Duration::from_millis(10))
.ok_or_else(|| AutosarDataError::ParentElementLocked)?;
let idx = src_parent_locked
.content
.iter()
.enumerate()
.find(|(_, item)| {
if let ElementContent::Element(elem) = item {
*elem == *move_element
} else {
false
}
})
.map(|(idx, _)| idx)
.unwrap();
src_parent_locked.content.remove(idx);
}
// remove all cached references for elements under move_element - they all become invalid as a result of moving it
for path in original_paths.keys() {
project_src.remove_identifiable(path);
}
// delete all reference origin info for elements under move_element
for (path, elem) in &original_refs {
project_src.remove_reference_origin(path, elem.downgrade());
}
// set the parent of the new element to the current element
move_element.0.lock().parent = ElementOrFile::Element(self_weak);
let dest_path = if move_element.is_identifiable() {
let new_name = move_element
.0
.lock()
.make_unique_item_name(project, &dest_path_prefix)?;
format!("{dest_path_prefix}/{new_name}")
} else {
dest_path_prefix
};
// cache references to all the identifiable elements in move_element
for (orig_path, identifiable_element) in &original_paths {
if let Some(suffix) = orig_path.strip_prefix(&src_path_prefix) {
let path = format!("{dest_path}{suffix}");
project.add_identifiable(path, identifiable_element.downgrade());
}
}
// cache all newly added reference origins under move_element
for (old_ref, ref_element) in original_refs {
// if the reference points to a known old path, then update it to use the new path instead
if original_paths.contains_key(&old_ref) {
let mut refstr = old_ref.clone();
if let Some(suffix) = old_ref.strip_prefix(&src_path_prefix) {
refstr = format!("{dest_path}{suffix}");
ref_element
.0
.lock()
.set_character_data(CharacterData::String(refstr.clone()), version)?;
}
project.add_reference_origin(&refstr, ref_element.downgrade());
}
}
// insert move_element
self.content
.insert(position, ElementContent::Element(move_element.clone()));
Ok(move_element.clone())
}
/// find the upper and lower bound on the insert position for a sub element
fn find_element_insert_pos(
&self,
element_name: ElementName,
version: AutosarVersion,
) -> Result<(usize, usize), AutosarDataError> {
let elemtype = self.elemtype;
if self.elemtype.content_mode() == ContentMode::Characters {
// cant't insert at all, only character data is permitted
return Err(AutosarDataError::IncorrectContentType);
}
if let Some((_, new_element_indices)) = elemtype.find_sub_element(element_name, version as u32) {
let mut start_pos = 0;
let mut end_pos = 0;
for (idx, content_item) in self.content.iter().enumerate() {
if let ElementContent::Element(subelement) = content_item {
let (_, existing_element_indices) = elemtype
.find_sub_element(subelement.element_name(), version as u32)
.unwrap();
let group_type = elemtype.find_common_group(&new_element_indices, &existing_element_indices);
match group_type.content_mode() {
ContentMode::Sequence => {
// decide where to insert
match new_element_indices.cmp(&existing_element_indices) {
std::cmp::Ordering::Less => {
// new element is smaller than the existing one
// this means that all plausible insert positions have already been seen
break;
}
std::cmp::Ordering::Equal => {
// new element is not smaller than the current one, so set the end position
end_pos = idx + 1;
// are identical elements of this type allowed at all?
if let Some(multiplicity) =
elemtype.get_sub_element_multiplicity(&new_element_indices)
{
if multiplicity != ElementMultiplicity::Any {
// the new element is identical to an existing one, but repetitions are not allowed
return Err(AutosarDataError::ElementInsertionConflict);
}
}
}
std::cmp::Ordering::Greater => {
// new element is greater (i.e. later in the sequence) than the current one
// the erliest possible insert position is aftet the current element
start_pos = idx + 1;
end_pos = idx + 1;
}
}
}
ContentMode::Choice => {
// can insert elements that ar identical to the existing element, if more than one of this element is allowed
// can't insert anything else
if new_element_indices == existing_element_indices {
if let Some(multiplicity) = elemtype.get_sub_element_multiplicity(&new_element_indices)
{
if multiplicity != ElementMultiplicity::Any {
// the new element is identical to an existing one, but repetitions are not allowed
return Err(AutosarDataError::ElementInsertionConflict);
}
} else {
panic!(); // can't happen
}
// the existing element and the new element are equal in positioning
// start_pos remains at its current value (< current position), while
// end_pos is increased to allow inserting before or after this element
end_pos = idx + 1;
} else {
return Err(AutosarDataError::ElementInsertionConflict);
}
}
ContentMode::Bag | ContentMode::Mixed => {
// can insert before or after the current element
end_pos = idx + 1;
}
ContentMode::Characters => {
panic!(); // impossible on sub-groups
}
}
} else if let ElementContent::CharacterData(_) = content_item {
end_pos = idx + 1;
}
}
Ok((start_pos, end_pos))
} else {
Err(AutosarDataError::InvalidSubElement)
}
}
/// 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.
pub(crate) fn remove_sub_element(
&mut self,
sub_element: Element,
project: &AutosarProject,
) -> Result<(), AutosarDataError> {
let path = Cow::from(self.path_unchecked()?);
let mut sub_element_locked = sub_element.0.lock();
// find the position of sub_element in the parent element first to verify that sub_element actuall *is* a sub element
let pos = self
.content
.iter()
.enumerate()
.find(|(_, item)| {
if let ElementContent::Element(elem) = item {
*elem == sub_element
} else {
false
}
})
.map(|(idx, _)| idx)
.ok_or_else(|| AutosarDataError::ElementNotFound)?;
if self.elemtype.is_named() && sub_element_locked.elemname == ElementName::ShortName {
// may not remove the SHORT-NAME, because that would leave the data in an invalid state
return Err(AutosarDataError::ShortNameRemovalForbidden);
}
sub_element_locked.remove_internal(sub_element.downgrade(), project, path);
self.content.remove(pos);
Ok(())
}
// remove all of the content of an element
pub(crate) fn remove_internal(&mut self, self_weak: WeakElement, project: &AutosarProject, mut path: Cow<str>) {
if self.is_identifiable() {
if let Some(name) = self.item_name() {
let mut new_path = String::with_capacity(path.len() + name.len() + 1);
new_path.push_str(&path);
new_path.push('/');
new_path.push_str(&name);
path = Cow::from(new_path.clone());
project.remove_identifiable(&path);
}
}
if self.elemtype.is_ref() {
if let Some(CharacterData::String(reference)) = self.character_data() {
// remove the references-reference (ugh. terminology???)
project.remove_reference_origin(&reference, self_weak);
}
}
for item in &self.content {
if let ElementContent::Element(sub_element) = item {
sub_element
.0
.lock()
.remove_internal(sub_element.downgrade(), project, Cow::from(path.as_ref()));
}
}
self.content.clear();
self.parent = ElementOrFile::None;
}
/// set the character data of this element
///
/// This method only applies to elements which contain character data, i.e. element.content_type == CharacterData
pub(crate) fn set_character_data(
&mut self,
chardata: CharacterData,
version: AutosarVersion,
) -> Result<(), AutosarDataError> {
if self.elemtype.content_mode() == ContentMode::Characters {
if let Some(cdata_spec) = self.elemtype.chardata_spec() {
if CharacterData::check_value(&chardata, cdata_spec, version) {
// update the character data
if self.content.is_empty() {
self.content.push(ElementContent::CharacterData(chardata));
} else {
self.content[0] = ElementContent::CharacterData(chardata);
}
return Ok(());
}
}
}
Err(AutosarDataError::IncorrectContentType)
}
/// get the character content of the element
///
/// This method only applies to elements which contain character data, i.e. element.content_type == CharacterData
pub(crate) fn character_data(&self) -> Option<CharacterData> {
if let ContentMode::Characters = self.elemtype.content_mode() {
if let Some(ElementContent::CharacterData(cdata)) = self.content.get(0) {
return Some(cdata.clone());
}
}
None
}
/// get a single attribute by name
pub(crate) fn attribute_value(&self, attrname: AttributeName) -> Option<CharacterData> {
if let Some(attr) = self.attributes.iter().find(|attr| attr.attrname == attrname) {
return Some(attr.content.clone());
}
None
}
/// get the content of a named attribute as a string
pub(crate) fn attribute_string(&self, attrname: AttributeName) -> Option<String> {
if let Some(chardata) = self.attribute_value(attrname) {
match chardata {
CharacterData::String(stringval) => return Some(stringval),
other => return Some(other.to_string()),
}
}
None
}
pub(crate) fn set_attribute_internal(
&mut self,
attrname: AttributeName,
value: CharacterData,
file_version: AutosarVersion,
) -> bool {
// find the attribute specification in the item type
if let Some((spec, _, _)) = self.elemtype.find_attribute_spec(attrname) {
// find the attribute the element's attribute list
if let Some(attr) = self.attributes.iter_mut().find(|attr| attr.attrname == attrname) {
// the existing attribute gets updated
if CharacterData::check_value(&value, spec, file_version) {
attr.content = value;
return true;
}
} else {
// the attribute didn't exist yet, so it is created here
if CharacterData::check_value(&value, spec, file_version) {
self.attributes.push(Attribute {
attrname,
content: value,
});
return true;
}
}
}
false
}
/// remove an attribute from the element
pub(crate) fn remove_attribute(&mut self, attrname: AttributeName) -> bool {
// find the index of the attribute in the attribute list of the element
for idx in 0..self.attributes.len() {
if self.attributes[idx].attrname == attrname {
// find the definition of this attribute in the specification
if let Some((_, required, _)) = self.elemtype.find_attribute_spec(attrname) {
// the attribute can only be removed if it is optional
if !required {
self.attributes.remove(idx);
return true;
}
}
}
}
false
}
}
impl PartialEq for Element {
fn eq(&self, other: &Self) -> bool {
Arc::as_ptr(&self.0) == Arc::as_ptr(&other.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)
}
}
#[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 project = AutosarProject::new();
project
.load_named_arxml_buffer(BASIC_AUTOSAR_FILE.as_bytes(), &OsString::from("test.arxml"), true)
.unwrap();
let el_ar_package = project.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();
let count = el_elements.sub_elements().count();
assert_eq!(count, 3);
// inserting another COMPU-METHOD into ELEMENTS hould be allowed at any position
let (start_pos, end_pos) = el_elements
.0
.lock()
.find_element_insert_pos(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 = project.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
.0
.lock()
.find_element_insert_pos(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
.0
.lock()
.find_element_insert_pos(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
.0
.lock()
.find_element_insert_pos(ElementName::CompuConst, AutosarVersion::Autosar_00050);
assert!(result.is_err());
}
#[test]
fn element_rename() {
let project = AutosarProject::new();
let file = project
.create_file("test.arxml", AutosarVersion::Autosar_00050)
.unwrap();
let el_autosar = file.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(ElementName::CanCluster, "CanCluster")
.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(ElementName::FrameTriggerings)
.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();
// 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");
// 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");
}
#[test]
fn element_copy() {
let project = AutosarProject::new();
project
.load_named_arxml_buffer(BASIC_AUTOSAR_FILE.as_bytes(), &OsString::from("test.arxml"), true)
.unwrap();
let el_ar_package = project.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, "CompuMethod")
.unwrap();
el_elements
.create_named_sub_element(ElementName::DdsServiceInstanceToMachineMapping, "ApItem")
.unwrap();
let project2 = AutosarProject::new();
let file = project2
.create_file(OsString::from("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 = file.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 = file.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());
}
#[test]
fn element_deletion() {
let project = AutosarProject::new();
project
.load_named_arxml_buffer(BASIC_AUTOSAR_FILE.as_bytes(), &OsString::from("test.arxml"), true)
.unwrap();
let el_ar_package = project.get_element_by_path("/TestPackage").unwrap();
let el_short_name = el_ar_package.get_sub_element(ElementName::ShortName).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_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!(project.0.lock().identifiables.len(), 0);
assert!(result.is_ok());
}
#[test]
fn element_ops() {
let project = AutosarProject::new();
let (file, _) = project
.load_named_arxml_buffer(BASIC_AUTOSAR_FILE.as_bytes(), &OsString::from("test.arxml"), true)
.unwrap();
let el_autosar = file.root_element();
let el_ar_packages = el_autosar.get_sub_element(ElementName::ArPackages).unwrap();
let el_ar_package = el_ar_packages.get_sub_element(ElementName::ArPackage).unwrap();
let el_ar_package2 = project.get_element_by_path("/TestPackage").unwrap();
assert_eq!(el_ar_package, el_ar_package2);
}
#[test]
fn attributes() {
let project = AutosarProject::new();
let (file, _) = project
.load_named_arxml_buffer(BASIC_AUTOSAR_FILE.as_bytes(), &OsString::from("test.arxml"), true)
.unwrap();
let el_autosar = file.root_element();
let count = el_autosar.attributes().count();
assert_eq!(count, 3);
// set the attribute S on the element AUTOSAR
let result = el_autosar.set_attribute(AttributeName::S, CharacterData::String(String::from("something")));
assert_eq!(result, true);
// AUTOSAR has no DEST attribute, so this should fail
let result = el_autosar.set_attribute(AttributeName::Dest, CharacterData::String(String::from("something")));
assert_eq!(result, false);
// The attribute S exists and is optional, so it can be removed
let result = el_autosar.remove_attribute(AttributeName::S);
assert_eq!(result, true);
// the attribute xmlns is required and cannot be removed
let result = el_autosar.remove_attribute(AttributeName::xmlns);
assert_eq!(result, false);
// the attribute ACCESSKEY does not exist in the element AUTOSAR and cannot be removed
let result = el_autosar.remove_attribute(AttributeName::Accesskey);
assert_eq!(result, false);
// the attribute T is permitted on AUTOSAR and the string is a valid value
let result = el_autosar.set_attribute_string(AttributeName::T, "2022-01-31T13:00:59Z");
assert_eq!(result, true);
let xmlns = el_autosar.attribute_string(AttributeName::xmlns).unwrap();
assert_eq!(xmlns, "http://autosar.org/schema/r4.0".to_string());
}
#[test]
fn mixed_content() {
let project = AutosarProject::new();
project
.load_named_arxml_buffer(BASIC_AUTOSAR_FILE.as_bytes(), &OsString::from("test.arxml"), true)
.unwrap();
let el_ar_package = project.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 element_move() {
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>
<SYSTEM><SHORT-NAME>System</SHORT-NAME>
<FIBEX-ELEMENTS>
<FIBEX-ELEMENT-REF-CONDITIONAL>
<FIBEX-ELEMENT-REF DEST="ECU-INSTANCE">/Pkg/EcuInstance</FIBEX-ELEMENT-REF>
</FIBEX-ELEMENT-REF-CONDITIONAL>
<FIBEX-ELEMENT-REF-CONDITIONAL>
<FIBEX-ELEMENT-REF DEST="I-SIGNAL-I-PDU">/Some/Invalid/Path</FIBEX-ELEMENT-REF>
</FIBEX-ELEMENT-REF-CONDITIONAL>
<FIBEX-ELEMENT-REF-CONDITIONAL>
<FIBEX-ELEMENT-REF DEST="I-SIGNAL">/Pkg/System</FIBEX-ELEMENT-REF>
</FIBEX-ELEMENT-REF-CONDITIONAL>
</FIBEX-ELEMENTS>
</SYSTEM>
<ECU-INSTANCE><SHORT-NAME>EcuInstance</SHORT-NAME></ECU-INSTANCE>
</ELEMENTS>
</AR-PACKAGE>
<AR-PACKAGE><SHORT-NAME>Pkg2</SHORT-NAME>
<ELEMENTS>
<ECU-INSTANCE><SHORT-NAME>EcuInstance</SHORT-NAME></ECU-INSTANCE>
</ELEMENTS>
</AR-PACKAGE>
<AR-PACKAGE><SHORT-NAME>Pkg3</SHORT-NAME></AR-PACKAGE>
</AR-PACKAGES></AUTOSAR>"#;
let project = AutosarProject::new();
project
.load_named_arxml_buffer(FILEBUF.as_bytes(), &OsString::from("test"), true)
.unwrap();
// get the existing ECU-INSTANCE EcuInstance
let ecu_instance = project.get_element_by_path("/Pkg/EcuInstance").unwrap();
// get the existing AR-PACKAGE Pkg2
let pkg2 = project.get_element_by_path("/Pkg2").unwrap();
// get the ELEMENTS sub element of Pkg2
let pkg2_elements = pkg2.get_sub_element(ElementName::Elements).unwrap();
// move the EcuInstance into Pkg2
pkg2_elements.move_element_here(&ecu_instance).unwrap();
// assert: pkg2 is now the parent of EcuInstance
assert_eq!(ecu_instance.parent().unwrap().unwrap(), pkg2_elements);
// assert: due to a name conflict, the moved EcuInstance has been renamed to EcuInstance_1
assert_eq!(ecu_instance.item_name().unwrap(), "EcuInstance_1");
// assert: The path of the EcuInstance is now "/Pkg2/EcuInstance" instead of "/Pkg/EcuInstance"
assert_eq!(ecu_instance.path().unwrap(), "/Pkg2/EcuInstance_1");
let system = project.get_element_by_path("/Pkg/System").unwrap();
// get the FIBEX-ELEMENT-REF which has DEST=ECU-INSTANCE
let (_, fibex_elem_ref) = system
.elements_dfs()
.find(|(_, e)| {
e.is_reference()
&& e.attribute_value(AttributeName::Dest)
.map(|val| val == CharacterData::Enum(EnumItem::EcuInstance))
.unwrap()
})
.unwrap();
// assert: The reference has been updated to refer to the new path of the ECU-INSTANCE
assert_eq!(
fibex_elem_ref.character_data().unwrap().to_string(),
"/Pkg2/EcuInstance_1"
);
// move a non-identifiable element
let pkg3 = project.get_element_by_path("/Pkg3").unwrap();
let result = pkg3.move_element_here_at(&pkg2_elements, 0);
assert!(result.is_err()); // bad position, can't move to position 0 in front of the SHORT-NAME
let result = pkg3.move_element_here_at(&pkg2_elements, 1);
assert!(result.is_ok());
// move a tree of elements between two projects
let project2 = AutosarProject::new();
let file = project2.create_file("test2", AutosarVersion::Autosar_00050).unwrap();
let root2 = file.root_element();
let autosar_packages = project
.files()
.next()
.unwrap()
.root_element()
.get_sub_element(ElementName::ArPackages)
.unwrap();
let result = root2.move_element_here(&autosar_packages);
assert!(result.is_ok());
assert!(project2.get_element_by_path("/Pkg/System").is_some());
assert!(project2.get_element_by_path("/Pkg2").is_some());
assert!(project2.get_element_by_path("/Pkg3/EcuInstance").is_some());
assert!(project2.get_element_by_path("/Pkg3/EcuInstance_1").is_some());
// everything has been moved to project2, so the original project is empty now
assert!(project.0.lock().identifiables.is_empty());
assert!(project.0.lock().reference_origins.is_empty());
// move a sub-element to a different position
let ar_packages = pkg3.parent().unwrap().unwrap();
// confirm the current order inside ar_packages:
// 1: AR-PACKAGE ("Pkg"), 2: AR-PACKAGE ("Pkg2"), 3: AR-PACKAGE ("Pkg3")
let mut sub_elem_iter = ar_packages.sub_elements();
assert_eq!(sub_elem_iter.next().unwrap().item_name().unwrap(), "Pkg");
assert_eq!(sub_elem_iter.next().unwrap().item_name().unwrap(), "Pkg2");
assert_eq!(sub_elem_iter.next().unwrap().item_name().unwrap(), "Pkg3");
let result = ar_packages.move_element_here_at(&pkg3, 0);
assert!(result.is_ok());
// now the order is: 1: AR-PACKAGE ("Pkg3"), 2: AR-PACKAGE ("Pkg"), 3: AR-PACKAGE ("Pkg2")
let mut sub_elem_iter = ar_packages.sub_elements();
assert_eq!(sub_elem_iter.next().unwrap().item_name().unwrap(), "Pkg3");
// move to last position, should succeed
let result = ar_packages.move_element_here_at(&pkg3, 2);
assert!(result.is_ok());
// move 1 past the last position, should fail
let result = ar_packages.move_element_here_at(&pkg3, 3);
assert!(result.is_err());
}
}