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
|
////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 1996-2021 The Octave Project Developers
//
// See the file COPYRIGHT.md in the top-level directory of this
// distribution or <https://octave.org/copyright/>.
//
// This file is part of Octave.
//
// Octave is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Octave is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Octave; see the file COPYING. If not, see
// <https://www.gnu.org/licenses/>.
//
////////////////////////////////////////////////////////////////////////
#if defined (HAVE_CONFIG_H)
# include "config.h"
#endif
#include <istream>
#include <ostream>
#include "Cell.h"
#include "builtin-defun-decls.h"
#include "defun.h"
#include "error.h"
#include "errwarn.h"
#include "mxarray.h"
#include "oct-lvalue.h"
#include "oct-hdf5.h"
#include "ov-struct.h"
#include "unwind-prot.h"
#include "utils.h"
#include "variables.h"
#include "Array-util.h"
#include "oct-locbuf.h"
#include "byte-swap.h"
#include "ls-oct-text.h"
#include "ls-oct-binary.h"
#include "ls-hdf5.h"
#include "ls-utils.h"
#include "pr-output.h"
DEFINE_OV_TYPEID_FUNCTIONS_AND_DATA(octave_struct, "struct", "struct");
// How many levels of structure elements should we print?
static int Vstruct_levels_to_print = 2;
// TRUE means print struct array contents, up to the number of levels
// specified by struct_levels_to_print.
static bool Vprint_struct_array_contents = false;
octave_base_value *
octave_struct::try_narrowing_conversion (void)
{
octave_base_value *retval = nullptr;
if (numel () == 1)
retval = new octave_scalar_struct (map.checkelem (0));
return retval;
}
Cell
octave_struct::dotref (const octave_value_list& idx, bool auto_add)
{
Cell retval;
assert (idx.length () == 1);
std::string nm = idx(0).string_value ();
octave_map::const_iterator p = map.seek (nm);
if (p != map.end ())
retval = map.contents (p);
else if (auto_add)
retval = (isempty ()) ? Cell (dim_vector (1, 1)) : Cell (dims ());
else
error_with_id ("Octave:invalid-indexing",
"structure has no member '%s'", nm.c_str ());
return retval;
}
static void
err_invalid_index_for_assignment (void)
{
error ("invalid index for structure array assignment");
}
static void
err_invalid_index_type (const std::string& nm, char t)
{
error ("%s cannot be indexed with %c", nm.c_str (), t);
}
static void
maybe_warn_invalid_field_name (const std::string& key, const char *who)
{
if (! octave::valid_identifier (key))
{
if (who)
warning_with_id ("Octave:language-extension",
"%s: invalid structure field name '%s'",
who, key.c_str ());
else
warning_with_id ("Octave:language-extension",
"invalid structure field name '%s'",
key.c_str ());
}
}
octave_value_list
octave_struct::subsref (const std::string& type,
const std::list<octave_value_list>& idx,
int nargout)
{
octave_value_list retval;
int skip = 1;
switch (type[0])
{
case '(':
{
if (type.length () > 1 && type[1] == '.')
{
auto p = idx.begin ();
octave_value_list key_idx = *++p;
const Cell tmp = dotref (key_idx);
const Cell t = tmp.index (idx.front ());
// Avoid creating a comma-separated list if the result is a
// single element.
retval(0) = (t.numel () == 1) ? t(0) : octave_value (t, true);
// We handled two index elements, so tell
// next_subsref to skip both of them.
skip++;
}
else
retval(0) = do_index_op (idx.front ());
}
break;
case '.':
{
const Cell t = dotref (idx.front ());
// Avoid creating a comma-separated list if the result is a
// single element.
retval(0) = (t.numel () == 1) ? t(0) : octave_value (t, true);
}
break;
case '{':
err_invalid_index_type (type_name (), type[0]);
break;
default:
panic_impossible ();
}
// FIXME: perhaps there should be an
// octave_value_list::next_subsref member function? See also
// octave_user_function::subsref.
if (idx.size () > 1)
retval = retval(0).next_subsref (nargout, type, idx, skip);
return retval;
}
octave_value
octave_struct::subsref (const std::string& type,
const std::list<octave_value_list>& idx,
bool auto_add)
{
octave_value retval;
int skip = 1;
switch (type[0])
{
case '(':
{
if (type.length () > 1 && type[1] == '.')
{
auto p = idx.begin ();
octave_value_list key_idx = *++p;
const Cell tmp = dotref (key_idx, auto_add);
const Cell t = tmp.index (idx.front (), auto_add);
// Avoid creating a comma-separated list if the result is a
// single element.
retval = (t.numel () == 1) ? t(0) : octave_value (t, true);
// We handled two index elements, so tell
// next_subsref to skip both of them.
skip++;
}
else
retval = do_index_op (idx.front (), auto_add);
}
break;
case '.':
{
if (map.numel () > 0)
{
const Cell t = dotref (idx.front (), auto_add);
// Avoid creating a comma-separated list if the result is a
// single element.
retval = (t.numel () == 1) ? t(0) : octave_value (t, true);
}
}
break;
case '{':
err_invalid_index_type (type_name (), type[0]);
break;
default:
panic_impossible ();
}
// FIXME: perhaps there should be an
// octave_value_list::next_subsref member function? See also
// octave_user_function::subsref.
if (idx.size () > 1)
retval = retval.next_subsref (auto_add, type, idx, skip);
return retval;
}
/*
%!test
%! x(1).a.a = 1;
%! x(2).a.a = 2;
%! assert (size (x), [1, 2]);
%! assert (x(1).a.a, 1);
%! assert (x(2).a.a, 2);
*/
octave_value
octave_struct::numeric_conv (const octave_value& val,
const std::string& type)
{
octave_value retval;
if (type.length () > 0 && type[0] == '.' && ! val.isstruct ())
retval = octave_map ();
else
retval = val;
return retval;
}
octave_value
octave_struct::subsasgn (const std::string& type,
const std::list<octave_value_list>& idx,
const octave_value& rhs)
{
octave_value retval;
int n = type.length ();
octave_value t_rhs = rhs;
if (idx.front ().empty ())
error ("missing index in indexed assignment");
if (n > 1 && ! (type.length () == 2 && type[0] == '(' && type[1] == '.'))
{
switch (type[0])
{
case '(':
{
if (type.length () > 1 && type[1] == '.')
{
auto p = idx.begin ();
octave_value_list t_idx = *p;
octave_value_list key_idx = *++p;
assert (key_idx.length () == 1);
std::string key = key_idx(0).string_value ();
maybe_warn_invalid_field_name (key, "subsasgn");
std::list<octave_value_list> next_idx (idx);
// We handled two index elements, so subsasgn to
// needs to skip both of them.
next_idx.erase (next_idx.begin ());
next_idx.erase (next_idx.begin ());
std::string next_type = type.substr (2);
Cell tmpc (1, 1);
auto pkey = map.seek (key);
if (pkey != map.end ())
{
map.contents (pkey).make_unique ();
tmpc = map.contents (pkey).index (idx.front (), true);
}
// FIXME: better code reuse?
// cf. octave_cell::subsasgn and the case below.
if (tmpc.numel () != 1)
err_indexed_cs_list ();
octave_value& tmp = tmpc(0);
bool orig_undefined = tmp.is_undefined ();
if (orig_undefined || tmp.is_zero_by_zero ())
{
tmp = octave_value::empty_conv (next_type, rhs);
tmp.make_unique (); // probably a no-op.
}
else
// optimization: ignore the copy
// still stored inside our map.
tmp.make_unique (1);
t_rhs =(orig_undefined
? tmp.undef_subsasgn (next_type, next_idx, rhs)
: tmp.subsasgn (next_type, next_idx, rhs));
}
else
err_invalid_index_for_assignment ();
}
break;
case '.':
{
octave_value_list key_idx = idx.front ();
assert (key_idx.length () == 1);
std::string key = key_idx(0).string_value ();
maybe_warn_invalid_field_name (key, "subsasgn");
std::list<octave_value_list> next_idx (idx);
next_idx.erase (next_idx.begin ());
std::string next_type = type.substr (1);
Cell tmpc (1, 1);
auto pkey = map.seek (key);
if (pkey != map.end ())
{
map.contents (pkey).make_unique ();
tmpc = map.contents (pkey);
}
// FIXME: better code reuse?
if (tmpc.numel () == 1)
{
octave_value& tmp = tmpc(0);
bool orig_undefined = tmp.is_undefined ();
if (orig_undefined || tmp.is_zero_by_zero ())
{
tmp = octave_value::empty_conv (next_type, rhs);
tmp.make_unique (); // probably a no-op.
}
else
// optimization: ignore the copy
// still stored inside our map.
tmp.make_unique (1);
t_rhs = (orig_undefined
? tmp.undef_subsasgn (next_type, next_idx, rhs)
: tmp.subsasgn (next_type, next_idx, rhs));
}
else
err_indexed_cs_list ();
}
break;
case '{':
err_invalid_index_type (type_name (), type[0]);
break;
default:
panic_impossible ();
}
}
switch (type[0])
{
case '(':
{
if (n > 1 && type[1] == '.')
{
auto p = idx.begin ();
octave_value_list key_idx = *++p;
octave_value_list idxf = idx.front ();
assert (key_idx.length () == 1);
std::string key = key_idx(0).string_value ();
maybe_warn_invalid_field_name (key, "subsasgn");
if (t_rhs.is_cs_list ())
{
Cell tmp_cell = Cell (t_rhs.list_value ());
// Inquire the proper shape of the RHS.
dim_vector didx = dims ().redim (idxf.length ());
for (octave_idx_type k = 0; k < idxf.length (); k++)
if (! idxf(k).is_magic_colon ())
didx(k) = idxf(k).numel ();
if (didx.numel () == tmp_cell.numel ())
tmp_cell = tmp_cell.reshape (didx);
map.assign (idxf, key, tmp_cell);
count++;
retval = octave_value (this);
}
else
{
const octave_map& cmap = const_cast<const octave_map &> (map);
// cast to const reference, avoid forced key insertion.
if (idxf.all_scalars ()
|| cmap.contents (key).index (idxf, true).numel () == 1)
{
map.assign (idxf,
key, Cell (t_rhs.storable_value ()));
count++;
retval = octave_value (this);
}
else
err_nonbraced_cs_list_assignment ();
}
}
else
{
if (t_rhs.isstruct () || t_rhs.isobject ())
{
octave_map rhs_map = t_rhs.xmap_value ("invalid structure assignment");
map.assign (idx.front (), rhs_map);
count++;
retval = octave_value (this);
}
else
{
if (! t_rhs.isnull ())
error ("invalid structure assignment");
map.delete_elements (idx.front ());
count++;
retval = octave_value (this);
}
}
}
break;
case '.':
{
octave_value_list key_idx = idx.front ();
assert (key_idx.length () == 1);
std::string key = key_idx(0).string_value ();
maybe_warn_invalid_field_name (key, "subsasgn");
if (t_rhs.is_cs_list ())
{
Cell tmp_cell = Cell (t_rhs.list_value ());
// The shape of the RHS is irrelevant, we just want
// the number of elements to agree and to preserve the
// shape of the left hand side of the assignment.
if (numel () == tmp_cell.numel ())
tmp_cell = tmp_cell.reshape (dims ());
map.setfield (key, tmp_cell);
}
else
{
Cell tmp_cell(1, 1);
tmp_cell(0) = t_rhs.storable_value ();
map.setfield (key, tmp_cell);
}
count++;
retval = octave_value (this);
}
break;
case '{':
err_invalid_index_type (type_name (), type[0]);
break;
default:
panic_impossible ();
}
retval.maybe_mutate ();
return retval;
}
octave_value
octave_struct::do_index_op (const octave_value_list& idx, bool resize_ok)
{
if (idx.length () == 0)
{
warn_empty_index (type_name ());
return map;
}
else // octave_map handles indexing itself.
return map.index (idx, resize_ok);
}
size_t
octave_struct::byte_size (void) const
{
// Neglect the size of the fieldnames.
size_t retval = 0;
for (auto p = map.cbegin (); p != map.cend (); p++)
{
std::string key = map.key (p);
octave_value val = octave_value (map.contents (p));
retval += val.byte_size ();
}
return retval;
}
void
octave_struct::print (std::ostream& os, bool)
{
print_raw (os);
}
void
octave_struct::print_raw (std::ostream& os, bool) const
{
octave::unwind_protect frame;
frame.protect_var (Vstruct_levels_to_print);
if (Vstruct_levels_to_print >= 0)
{
bool max_depth_reached = Vstruct_levels_to_print-- == 0;
bool print_fieldnames_only
= (max_depth_reached || ! Vprint_struct_array_contents);
increment_indent_level ();
indent (os);
dim_vector dv = dims ();
os << dv.str () << " struct array containing the fields:";
newline (os);
increment_indent_level ();
string_vector key_list = map.fieldnames ();
for (octave_idx_type i = 0; i < key_list.numel (); i++)
{
std::string key = key_list[i];
Cell val = map.contents (key);
if (i > 0 || ! Vcompact_format)
newline (os);
if (print_fieldnames_only)
{
indent (os);
os << key;
}
else
{
octave_value tmp (val);
tmp.print_with_name (os, key);
}
}
if (print_fieldnames_only)
newline (os);
decrement_indent_level ();
decrement_indent_level ();
}
else
{
indent (os);
os << "<structure>";
newline (os);
}
}
bool
octave_struct::print_name_tag (std::ostream& os, const std::string& name) const
{
bool retval = false;
indent (os);
if (Vstruct_levels_to_print < 0)
os << name << " = ";
else
{
os << name << " =";
newline (os);
if (! Vcompact_format)
newline (os);
retval = true;
}
return retval;
}
static bool
scalar (const dim_vector& dims)
{
return dims.ndims () == 2 && dims(0) == 1 && dims(1) == 1;
}
std::string
octave_struct::edit_display (const float_display_format&,
octave_idx_type r, octave_idx_type c) const
{
octave_value val;
if (map.rows () == 1 || map.columns () == 1)
{
// Vector struct. Columns are fields, rows are values.
Cell cval = map.contents (c);
val = cval(r);
}
else
{
// 2-d struct array. Rows and columns index individual
// scalar structs.
val = map(r,c);
}
std::string tname = val.type_name ();
dim_vector dv = val.dims ();
std::string dimstr = dv.str ();
return "[" + dimstr + " " + tname + "]";
}
bool
octave_struct::save_ascii (std::ostream& os)
{
octave_map m = map_value ();
octave_idx_type nf = m.nfields ();
const dim_vector dv = dims ();
os << "# ndims: " << dv.ndims () << "\n";
for (int i = 0; i < dv.ndims (); i++)
os << ' ' << dv(i);
os << "\n";
os << "# length: " << nf << "\n";
// Iterating over the list of keys will preserve the order of the
// fields.
string_vector keys = m.fieldnames ();
for (octave_idx_type i = 0; i < nf; i++)
{
std::string key = keys(i);
octave_value val = map.contents (key);
bool b = save_text_data (os, val, key, false, 0);
if (! b)
return ! os.fail ();
}
return true;
}
bool
octave_struct::load_ascii (std::istream& is)
{
octave_idx_type len = 0;
dim_vector dv (1, 1);
bool success = true;
// KLUGE: earlier Octave versions did not save extra dimensions with struct,
// and as a result did not preserve dimensions for empty structs.
// The default dimensions were 1x1, which we want to preserve.
string_vector keywords(2);
keywords[0] = "ndims";
keywords[1] = "length";
std::string kw;
if (extract_keyword (is, keywords, kw, len, true))
{
if (kw == keywords[0])
{
int mdims = std::max (static_cast<int> (len), 2);
dv.resize (mdims);
for (int i = 0; i < mdims; i++)
is >> dv(i);
success = extract_keyword (is, keywords[1], len);
}
}
else
success = false;
if (! success || len < 0)
error ("load: failed to extract number of elements in structure");
if (len > 0)
{
octave_map m (dv);
for (octave_idx_type j = 0; j < len; j++)
{
octave_value t2;
bool dummy;
// recurse to read cell elements
std::string nm = read_text_data (is, "", dummy, t2, j, false);
if (! is)
break;
Cell tcell = (t2.iscell () ? t2.xcell_value ("load: internal error loading struct elements") : Cell (t2));
m.setfield (nm, tcell);
}
if (! is)
error ("load: failed to load structure");
map = m;
}
else if (len == 0)
map = octave_map (dv);
else
panic_impossible ();
return success;
}
bool
octave_struct::save_binary (std::ostream& os, bool save_as_floats)
{
octave_map m = map_value ();
octave_idx_type nf = m.nfields ();
dim_vector dv = dims ();
if (dv.ndims () < 1)
return false;
// Use negative value for ndims
int32_t di = - dv.ndims ();
os.write (reinterpret_cast<char *> (&di), 4);
for (int i = 0; i < dv.ndims (); i++)
{
di = dv(i);
os.write (reinterpret_cast<char *> (&di), 4);
}
int32_t len = nf;
os.write (reinterpret_cast<char *> (&len), 4);
// Iterating over the list of keys will preserve the order of the
// fields.
string_vector keys = m.fieldnames ();
for (octave_idx_type i = 0; i < nf; i++)
{
std::string key = keys(i);
octave_value val = map.contents (key);
bool b = save_binary_data (os, val, key, "", 0, save_as_floats);
if (! b)
return ! os.fail ();
}
return true;
}
bool
octave_struct::load_binary (std::istream& is, bool swap,
octave::mach_info::float_format fmt)
{
bool success = true;
int32_t len;
if (! is.read (reinterpret_cast<char *> (&len), 4))
return false;
if (swap)
swap_bytes<4> (&len);
dim_vector dv (1, 1);
if (len < 0)
{
// We have explicit dimensions.
int mdims = -len;
int32_t di;
dv.resize (mdims);
for (int i = 0; i < mdims; i++)
{
if (! is.read (reinterpret_cast<char *> (&di), 4))
return false;
if (swap)
swap_bytes<4> (&di);
dv(i) = di;
}
if (! is.read (reinterpret_cast<char *> (&len), 4))
return false;
if (swap)
swap_bytes<4> (&len);
}
if (len > 0)
{
octave_map m (dv);
for (octave_idx_type j = 0; j < len; j++)
{
octave_value t2;
bool dummy;
std::string doc;
// recurse to read cell elements
std::string nm = read_binary_data (is, swap, fmt, "",
dummy, t2, doc);
if (! is)
break;
Cell tcell = (t2.iscell () ? t2.xcell_value ("load: internal error loading struct elements") : Cell (t2));
m.setfield (nm, tcell);
}
if (! is)
error ("load: failed to load structure");
map = m;
}
else if (len == 0)
map = octave_map (dv);
else
success = false;
return success;
}
bool
octave_struct::save_hdf5 (octave_hdf5_id loc_id, const char *name,
bool save_as_floats)
{
#if defined (HAVE_HDF5)
hid_t data_hid = -1;
#if defined (HAVE_HDF5_18)
data_hid = H5Gcreate (loc_id, name, octave_H5P_DEFAULT, octave_H5P_DEFAULT,
octave_H5P_DEFAULT);
#else
data_hid = H5Gcreate (loc_id, name, 0);
#endif
if (data_hid < 0) return false;
// recursively add each element of the structure to this group
octave_map m = map_value ();
octave_idx_type nf = m.nfields ();
// Iterating over the list of keys will preserve the order of the
// fields.
string_vector keys = m.fieldnames ();
for (octave_idx_type i = 0; i < nf; i++)
{
std::string key = keys(i);
octave_value val = map.contents (key);
bool retval2 = add_hdf5_data (data_hid, val, key, "", false,
save_as_floats);
if (! retval2)
break;
}
H5Gclose (data_hid);
return true;
#else
octave_unused_parameter (loc_id);
octave_unused_parameter (name);
octave_unused_parameter (save_as_floats);
warn_save ("hdf5");
return false;
#endif
}
bool
octave_struct::load_hdf5 (octave_hdf5_id loc_id, const char *name)
{
bool retval = false;
#if defined (HAVE_HDF5)
hdf5_callback_data dsub;
herr_t retval2 = 0;
octave_map m (dim_vector (1, 1));
int current_item = 0;
hsize_t num_obj = 0;
#if defined (HAVE_HDF5_18)
hid_t group_id = H5Gopen (loc_id, name, octave_H5P_DEFAULT);
#else
hid_t group_id = H5Gopen (loc_id, name);
#endif
H5Gget_num_objs (group_id, &num_obj);
H5Gclose (group_id);
// FIXME: fields appear to be sorted alphabetically on loading.
// Why is that happening?
while (current_item < static_cast<int> (num_obj)
&& (retval2 = hdf5_h5g_iterate (loc_id, name, ¤t_item,
&dsub)) > 0)
{
octave_value t2 = dsub.tc;
Cell tcell = (t2.iscell () ? t2.xcell_value ("load: internal error loading struct elements") : Cell (t2));
m.setfield (dsub.name, tcell);
}
if (retval2 >= 0)
{
map = m;
retval = true;
}
#else
octave_unused_parameter (loc_id);
octave_unused_parameter (name);
warn_load ("hdf5");
#endif
return retval;
}
mxArray *
octave_struct::as_mxArray (void) const
{
int nf = nfields ();
string_vector kv = map_keys ();
OCTAVE_LOCAL_BUFFER (const char *, f, nf);
for (int i = 0; i < nf; i++)
f[i] = kv[i].c_str ();
mxArray *retval = new mxArray (dims (), nf, f);
mxArray **elts = static_cast<mxArray **> (retval->get_data ());
mwSize nel = numel ();
mwSize ntot = nf * nel;
for (int i = 0; i < nf; i++)
{
Cell c = map.contents (kv[i]);
const octave_value *p = c.data ();
mwIndex k = 0;
for (mwIndex j = i; j < ntot; j += nf)
elts[j] = new mxArray (p[k++]);
}
return retval;
}
octave_value
octave_struct::fast_elem_extract (octave_idx_type n) const
{
if (n < map.numel ())
return map.checkelem (n);
else
return octave_value ();
}
bool
octave_struct::fast_elem_insert (octave_idx_type n,
const octave_value& x)
{
bool retval = false;
if (n < map.numel ())
{
// To avoid copying the scalar struct, it just stores a pointer to
// itself.
const octave_scalar_map *sm_ptr;
void *here = reinterpret_cast<void *>(&sm_ptr);
return (x.get_rep ().fast_elem_insert_self (here, btyp_struct)
&& map.fast_elem_insert (n, *sm_ptr));
}
return retval;
}
DEFINE_OV_TYPEID_FUNCTIONS_AND_DATA(octave_scalar_struct, "scalar struct",
"struct");
octave_value
octave_scalar_struct::dotref (const octave_value_list& idx, bool auto_add)
{
octave_value retval;
assert (idx.length () == 1);
std::string nm = idx(0).string_value ();
maybe_warn_invalid_field_name (nm, "subsref");
retval = map.getfield (nm);
if (! auto_add && retval.is_undefined ())
error_with_id ("Octave:invalid-indexing",
"structure has no member '%s'", nm.c_str ());
return retval;
}
octave_value
octave_scalar_struct::subsref (const std::string& type,
const std::list<octave_value_list>& idx)
{
octave_value retval;
if (type[0] == '.')
{
int skip = 1;
retval = dotref (idx.front ());
if (idx.size () > 1)
retval = retval.next_subsref (type, idx, skip);
}
else
retval = to_array ().subsref (type, idx);
return retval;
}
octave_value_list
octave_scalar_struct::subsref (const std::string& type,
const std::list<octave_value_list>& idx,
int nargout)
{
octave_value_list retval;
if (type[0] == '.')
{
int skip = 1;
retval(0) = dotref (idx.front ());
if (idx.size () > 1)
retval = retval(0).next_subsref (nargout, type, idx, skip);
}
else
retval = to_array ().subsref (type, idx, nargout);
return retval;
}
octave_value
octave_scalar_struct::subsref (const std::string& type,
const std::list<octave_value_list>& idx,
bool auto_add)
{
octave_value retval;
if (type[0] == '.')
{
int skip = 1;
retval = dotref (idx.front (), auto_add);
if (idx.size () > 1)
retval = retval.next_subsref (auto_add, type, idx, skip);
}
else
retval = to_array ().subsref (type, idx, auto_add);
return retval;
}
/*
%!test
%! x(1).a.a = 1;
%! x(2).a.a = 2;
%! assert (size (x), [1, 2]);
%! assert (x(1).a.a, 1);
%! assert (x(2).a.a, 2);
*/
octave_value
octave_scalar_struct::numeric_conv (const octave_value& val,
const std::string& type)
{
octave_value retval;
if (type.length () > 0 && type[0] == '.' && ! val.isstruct ())
retval = octave_map ();
else
retval = val;
return retval;
}
octave_value
octave_scalar_struct::subsasgn (const std::string& type,
const std::list<octave_value_list>& idx,
const octave_value& rhs)
{
octave_value retval;
if (idx.front ().empty ())
error ("missing index in indexed assignment");
if (type[0] == '.')
{
int n = type.length ();
octave_value t_rhs = rhs;
octave_value_list key_idx = idx.front ();
assert (key_idx.length () == 1);
std::string key = key_idx(0).string_value ();
maybe_warn_invalid_field_name (key, "subsasgn");
if (n > 1)
{
std::list<octave_value_list> next_idx (idx);
next_idx.erase (next_idx.begin ());
std::string next_type = type.substr (1);
octave_value tmp;
auto pkey = map.seek (key);
if (pkey != map.end ())
{
map.contents (pkey).make_unique ();
tmp = map.contents (pkey);
}
bool orig_undefined = tmp.is_undefined ();
if (orig_undefined || tmp.is_zero_by_zero ())
{
tmp = octave_value::empty_conv (next_type, rhs);
tmp.make_unique (); // probably a no-op.
}
else
// optimization: ignore the copy still stored inside our map.
tmp.make_unique (1);
t_rhs = (orig_undefined
? tmp.undef_subsasgn (next_type, next_idx, rhs)
: tmp.subsasgn (next_type, next_idx, rhs));
}
map.setfield (key, t_rhs.storable_value ());
count++;
retval = this;
}
else
{
// Forward this case to octave_struct.
octave_value tmp (new octave_struct (octave_map (map)));
retval = tmp.subsasgn (type, idx, rhs);
}
return retval;
}
octave_value
octave_scalar_struct::do_index_op (const octave_value_list& idx, bool resize_ok)
{
// octave_map handles indexing itself.
return octave_map (map).index (idx, resize_ok);
}
size_t
octave_scalar_struct::byte_size (void) const
{
// Neglect the size of the fieldnames.
size_t retval = 0;
for (auto p = map.cbegin (); p != map.cend (); p++)
{
std::string key = map.key (p);
octave_value val = octave_value (map.contents (p));
retval += val.byte_size ();
}
return retval;
}
void
octave_scalar_struct::print (std::ostream& os, bool)
{
print_raw (os);
}
void
octave_scalar_struct::print_raw (std::ostream& os, bool) const
{
octave::unwind_protect frame;
frame.protect_var (Vstruct_levels_to_print);
if (Vstruct_levels_to_print >= 0)
{
bool max_depth_reached = Vstruct_levels_to_print-- == 0;
bool print_fieldnames_only = max_depth_reached;
increment_indent_level ();
indent (os);
os << "scalar structure containing the fields:";
newline (os);
if (! Vcompact_format)
newline (os);
increment_indent_level ();
string_vector key_list = map.fieldnames ();
for (octave_idx_type i = 0; i < key_list.numel (); i++)
{
std::string key = key_list[i];
octave_value val = map.contents (key);
if (print_fieldnames_only)
{
indent (os);
os << key;
dim_vector dv = val.dims ();
os << ": " << dv.str () << ' ' << val.type_name ();
newline (os);
}
else
val.print_with_name (os, key);
}
decrement_indent_level ();
decrement_indent_level ();
}
else
{
indent (os);
os << "<structure>";
newline (os);
}
}
bool
octave_scalar_struct::print_name_tag (std::ostream& os,
const std::string& name) const
{
bool retval = false;
indent (os);
if (Vstruct_levels_to_print < 0)
os << name << " = ";
else
{
os << name << " =";
newline (os);
if (! Vcompact_format)
newline (os);
retval = true;
}
return retval;
}
std::string
octave_scalar_struct::edit_display (const float_display_format&,
octave_idx_type r, octave_idx_type) const
{
// Scalar struct. Rows are fields, single column for values.
octave_value val = map.contents (r);
std::string tname = val.type_name ();
dim_vector dv = val.dims ();
std::string dimstr = dv.str ();
return "[" + dimstr + " " + tname + "]";
}
bool
octave_scalar_struct::save_ascii (std::ostream& os)
{
octave_map m = map_value ();
octave_idx_type nf = m.nfields ();
const dim_vector dv = dims ();
os << "# ndims: " << dv.ndims () << "\n";
for (int i = 0; i < dv.ndims (); i++)
os << ' ' << dv(i);
os << "\n";
os << "# length: " << nf << "\n";
// Iterating over the list of keys will preserve the order of the
// fields.
string_vector keys = m.fieldnames ();
for (octave_idx_type i = 0; i < nf; i++)
{
std::string key = keys(i);
octave_value val = map.contents (key);
bool b = save_text_data (os, val, key, false, 0);
if (! b)
return ! os.fail ();
}
return true;
}
bool
octave_scalar_struct::load_ascii (std::istream& is)
{
octave_idx_type len = 0;
if (! extract_keyword (is, "length", len) || len < 0)
error ("load: failed to extract number of elements in structure");
if (len > 0)
{
octave_scalar_map m;
for (octave_idx_type j = 0; j < len; j++)
{
octave_value t2;
bool dummy;
// recurse to read cell elements
std::string nm
= read_text_data (is, "", dummy, t2, j, false);
if (! is)
break;
m.setfield (nm, t2);
}
if (! is)
error ("load: failed to load structure");
map = m;
}
else if (len == 0)
map = octave_scalar_map ();
else
panic_impossible ();
return true;
}
bool
octave_scalar_struct::save_binary (std::ostream& os, bool save_as_floats)
{
octave_map m = map_value ();
octave_idx_type nf = m.nfields ();
int32_t len = nf;
os.write (reinterpret_cast<char *> (&len), 4);
// Iterating over the list of keys will preserve the order of the
// fields.
string_vector keys = m.fieldnames ();
for (octave_idx_type i = 0; i < nf; i++)
{
std::string key = keys(i);
octave_value val = map.contents (key);
bool b = save_binary_data (os, val, key, "", 0, save_as_floats);
if (! b)
return ! os.fail ();
}
return true;
}
bool
octave_scalar_struct::load_binary (std::istream& is, bool swap,
octave::mach_info::float_format fmt)
{
bool success = true;
int32_t len;
if (! is.read (reinterpret_cast<char *> (&len), 4))
return false;
if (swap)
swap_bytes<4> (&len);
if (len > 0)
{
octave_scalar_map m;
for (octave_idx_type j = 0; j < len; j++)
{
octave_value t2;
bool dummy;
std::string doc;
// recurse to read cell elements
std::string nm = read_binary_data (is, swap, fmt, "",
dummy, t2, doc);
if (! is)
break;
m.setfield (nm, t2);
}
if (! is)
error ("load: failed to load structure");
map = m;
}
else if (len == 0)
map = octave_scalar_map ();
else
success = false;
return success;
}
bool
octave_scalar_struct::save_hdf5 (octave_hdf5_id loc_id, const char *name,
bool save_as_floats)
{
#if defined (HAVE_HDF5)
hid_t data_hid = -1;
#if defined (HAVE_HDF5_18)
data_hid = H5Gcreate (loc_id, name, octave_H5P_DEFAULT, octave_H5P_DEFAULT,
octave_H5P_DEFAULT);
#else
data_hid = H5Gcreate (loc_id, name, 0);
#endif
if (data_hid < 0) return false;
// recursively add each element of the structure to this group
octave_scalar_map m = scalar_map_value ();
octave_idx_type nf = m.nfields ();
// Iterating over the list of keys will preserve the order of the
// fields.
string_vector keys = m.fieldnames ();
for (octave_idx_type i = 0; i < nf; i++)
{
std::string key = keys(i);
octave_value val = map.contents (key);
bool retval2 = add_hdf5_data (data_hid, val, key, "", false,
save_as_floats);
if (! retval2)
break;
}
H5Gclose (data_hid);
return true;
#else
octave_unused_parameter (loc_id);
octave_unused_parameter (name);
octave_unused_parameter (save_as_floats);
warn_save ("hdf5");
return false;
#endif
}
bool
octave_scalar_struct::load_hdf5 (octave_hdf5_id loc_id, const char *name)
{
bool retval = false;
#if defined (HAVE_HDF5)
hdf5_callback_data dsub;
herr_t retval2 = 0;
octave_scalar_map m;
int current_item = 0;
hsize_t num_obj = 0;
#if defined (HAVE_HDF5_18)
hid_t group_id = H5Gopen (loc_id, name, octave_H5P_DEFAULT);
#else
hid_t group_id = H5Gopen (loc_id, name);
#endif
H5Gget_num_objs (group_id, &num_obj);
H5Gclose (group_id);
// FIXME: fields appear to be sorted alphabetically on loading.
// Why is that happening?
while (current_item < static_cast<int> (num_obj)
&& (retval2 = hdf5_h5g_iterate (loc_id, name, ¤t_item,
&dsub)) > 0)
{
octave_value t2 = dsub.tc;
m.setfield (dsub.name, t2);
}
if (retval2 >= 0)
{
map = m;
retval = true;
}
#else
octave_unused_parameter (loc_id);
octave_unused_parameter (name);
warn_load ("hdf5");
#endif
return retval;
}
mxArray *
octave_scalar_struct::as_mxArray (void) const
{
int nf = nfields ();
string_vector kv = map_keys ();
OCTAVE_LOCAL_BUFFER (const char *, f, nf);
for (int i = 0; i < nf; i++)
f[i] = kv[i].c_str ();
mxArray *retval = new mxArray (dims (), nf, f);
mxArray **elts = static_cast<mxArray **> (retval->get_data ());
mwSize nel = numel ();
mwSize ntot = nf * nel;
for (int i = 0; i < nf; i++)
{
Cell c = map.contents (kv[i]);
const octave_value *p = c.data ();
mwIndex k = 0;
for (mwIndex j = i; j < ntot; j += nf)
elts[j] = new mxArray (p[k++]);
}
return retval;
}
octave_value
octave_scalar_struct::to_array (void)
{
return new octave_struct (octave_map (map));
}
bool
octave_scalar_struct::fast_elem_insert_self (void *where,
builtin_type_t btyp) const
{
if (btyp == btyp_struct)
{
*(reinterpret_cast<const octave_scalar_map **>(where)) = ↦
return true;
}
else
return false;
}
DEFUN (struct, args, ,
doc: /* -*- texinfo -*-
@deftypefn {} {@var{s} =} struct ()
@deftypefnx {} {@var{s} =} struct (@var{field1}, @var{value1}, @var{field2}, @var{value2}, @dots{})
@deftypefnx {} {@var{s} =} struct (@var{obj})
Create a scalar or array structure and initialize its values.
The @var{field1}, @var{field2}, @dots{} variables are strings specifying the
names of the fields and the @var{value1}, @var{value2}, @dots{} variables
can be of any type.
If the values are cell arrays, create a structure array and initialize its
values. The dimensions of each cell array of values must match. Singleton
cells and non-cell values are repeated so that they fill the entire array.
If the cells are empty, create an empty structure array with the specified
field names.
If the argument is an object, return the underlying struct.
Observe that the syntax is optimized for struct @strong{arrays}. Consider
the following examples:
@example
@group
struct ("foo", 1)
@result{} scalar structure containing the fields:
foo = 1
struct ("foo", @{@})
@result{} 0x0 struct array containing the fields:
foo
struct ("foo", @{ @{@} @})
@result{} scalar structure containing the fields:
foo = @{@}(0x0)
struct ("foo", @{1, 2, 3@})
@result{} 1x3 struct array containing the fields:
foo
@end group
@end example
@noindent
The first case is an ordinary scalar struct---one field, one value. The
second produces an empty struct array with one field and no values, since
being passed an empty cell array of struct array values. When the value is
a cell array containing a single entry, this becomes a scalar struct with
that single entry as the value of the field. That single entry happens
to be an empty cell array.
Finally, if the value is a non-scalar cell array, then @code{struct}
produces a struct @strong{array}.
@seealso{cell2struct, fieldnames, getfield, setfield, rmfield, isfield, orderfields, isstruct, structfun}
@end deftypefn */)
{
int nargin = args.length ();
// struct ([]) returns an empty struct.
// struct (empty_matrix) returns an empty struct with the same
// dimensions as the empty matrix.
// Note that struct () creates a 1x1 struct with no fields for
// compatibility with Matlab.
if (nargin == 1 && args(0).isstruct ())
return ovl (args(0));
if (nargin == 1 && args(0).isobject ())
return ovl (args(0).map_value ());
if ((nargin == 1 || nargin == 2)
&& args(0).isempty () && args(0).is_real_matrix ())
{
if (nargin == 2)
{
Array<std::string> cstr = args(1).xcellstr_value ("struct: second argument should be a cell array of field names");
return ovl (octave_map (args(0).dims (), cstr));
}
else
return ovl (octave_map (args(0).dims ()));
}
// Check for "field", VALUE pairs.
for (int i = 0; i < nargin; i += 2)
{
if (! args(i).is_string () || i + 1 >= nargin)
error (R"(struct: additional arguments must occur as "field", VALUE pairs)");
}
// Check that the dimensions of the values correspond.
dim_vector dims (1, 1);
int first_dimensioned_value = 0;
for (int i = 1; i < nargin; i += 2)
{
if (args(i).iscell ())
{
dim_vector argdims (args(i).dims ());
if (! scalar (argdims))
{
if (! first_dimensioned_value)
{
dims = argdims;
first_dimensioned_value = i + 1;
}
else if (dims != argdims)
{
error ("struct: dimensions of parameter %d "
"do not match those of parameter %d",
first_dimensioned_value, i+1);
}
}
}
}
// Create the return value.
octave_map map (dims);
for (int i = 0; i < nargin; i+= 2)
{
// Get key.
std::string key (args(i).string_value ());
maybe_warn_invalid_field_name (key, "struct");
// Value may be v, { v }, or { v1, v2, ... }
// In the first two cases, we need to create a cell array of
// the appropriate dimensions filled with v. In the last case,
// the cell array has already been determined to be of the
// correct dimensions.
if (args(i+1).iscell ())
{
const Cell c (args(i+1).cell_value ());
if (scalar (c.dims ()))
map.setfield (key, Cell (dims, c(0)));
else
map.setfield (key, c);
}
else
map.setfield (key, Cell (dims, args(i+1)));
}
return ovl (map);
}
/*
%!shared x
%! x(1).a=1; x(2).a=2; x(1).b=3; x(2).b=3;
%!assert (struct ("a",1, "b",3), x(1))
%!assert (isempty (x([])))
%!assert (isempty (struct ("a",{}, "b",{})))
%!assert (struct ("a",{1,2}, "b",{3,3}), x)
%!assert (struct ("a",{1,2}, "b",3), x)
%!assert (struct ("a",{1,2}, "b",{3}), x)
%!assert (struct ("b",3, "a",{1,2}), x)
%!assert (struct ("b",{3}, "a",{1,2}), x)
%!test x = struct ([]);
%!assert (size (x), [0,0])
%!assert (isstruct (x))
%!assert (isempty (fieldnames (x)))
%!fail ('struct ("a",{1,2},"b",{1,2,3})', 'dimensions of parameter 2 do not match those of parameter 4')
%!error <arguments must occur as "field", VALUE pairs> struct (1,2,3,4)
%!fail ('struct ("1",2,"3")', 'struct: additional arguments must occur as "field", VALUE pairs')
*/
DEFUN (isstruct, args, ,
doc: /* -*- texinfo -*-
@deftypefn {} {} isstruct (@var{x})
Return true if @var{x} is a structure or a structure array.
@seealso{ismatrix, iscell, isa}
@end deftypefn */)
{
if (args.length () != 1)
print_usage ();
return ovl (args(0).isstruct ());
}
DEFUN (__fieldnames__, args, ,
doc: /* -*- texinfo -*-
@deftypefn {} {} __fieldnames__ (@var{struct})
@deftypefnx {} {} __fieldnames__ (@var{obj})
Internal function.
Implements @code{fieldnames()} for structures and Octave objects.
@seealso{fieldnames}
@end deftypefn */)
{
octave_value retval;
// Input validation has already been done in fieldnames.m.
octave_value arg = args(0);
octave_map m = arg.map_value ();
string_vector keys = m.fieldnames ();
if (keys.isempty ())
retval = Cell (0, 1);
else
retval = Cell (keys);
return retval;
}
DEFUN (isfield, args, ,
doc: /* -*- texinfo -*-
@deftypefn {} {} isfield (@var{x}, "@var{name}")
@deftypefnx {} {} isfield (@var{x}, @var{name})
Return true if the @var{x} is a structure and it includes an element named
@var{name}.
If @var{name} is a cell array of strings then a logical array of equal
dimension is returned.
@seealso{fieldnames}
@end deftypefn */)
{
if (args.length () != 2)
print_usage ();
octave_value retval = false;
if (args(0).isstruct ())
{
octave_map m = args(0).map_value ();
// FIXME: should this work for all types that can do
// structure reference operations?
if (args(1).is_string ())
{
std::string key = args(1).string_value ();
retval = m.isfield (key);
}
else if (args(1).iscell ())
{
Cell c = args(1).cell_value ();
boolNDArray bm (c.dims ());
octave_idx_type n = bm.numel ();
for (octave_idx_type i = 0; i < n; i++)
{
if (c(i).is_string ())
{
std::string key = c(i).string_value ();
bm(i) = m.isfield (key);
}
else
bm(i) = false;
}
retval = bm;
}
}
return retval;
}
DEFUN (numfields, args, ,
doc: /* -*- texinfo -*-
@deftypefn {} {} numfields (@var{s})
Return the number of fields of the structure @var{s}.
@seealso{fieldnames}
@end deftypefn */)
{
if (args.length () != 1)
print_usage ();
if (! args(0).isstruct ())
error ("numfields: argument must be a struct");
return ovl (static_cast<double> (args(0).nfields ()));
}
/*
## test isfield
%!test
%! x(3).d=1; x(2).a=2; x(1).b=3; x(2).c=3;
%! assert (isfield (x, "b"));
%!assert (isfield (struct ("a", "1"), "a"))
%!assert (isfield ({1}, "c"), false)
%!assert (isfield (struct ("a", "1"), 10), false)
%!assert (isfield (struct ("a", "b"), "a "), false)
%!assert (isfield (struct ("a", 1, "b", 2), {"a", "c"}), [true, false])
*/
DEFUN (cell2struct, args, ,
doc: /* -*- texinfo -*-
@deftypefn {} {} cell2struct (@var{cell}, @var{fields})
@deftypefnx {} {} cell2struct (@var{cell}, @var{fields}, @var{dim})
Convert @var{cell} to a structure.
The number of fields in @var{fields} must match the number of elements in
@var{cell} along dimension @var{dim}, that is
@code{numel (@var{fields}) == size (@var{cell}, @var{dim})}. If @var{dim}
is omitted, a value of 1 is assumed.
@example
@group
A = cell2struct (@{"Peter", "Hannah", "Robert";
185, 170, 168@},
@{"Name","Height"@}, 1);
A(1)
@result{}
@{
Name = Peter
Height = 185
@}
@end group
@end example
@seealso{struct2cell, cell2mat, struct}
@end deftypefn */)
{
int nargin = args.length ();
if (nargin < 2 || nargin > 3)
print_usage ();
if (! args(0).iscell ())
error ("cell2struct: argument CELL must be of type cell");
if (! (args(1).iscellstr () || args(1).is_char_matrix ()))
error ("cell2struct: FIELDS must be a cell array of strings or a character matrix");
int dim = 0;
if (nargin == 3)
{
if (! args(2).is_real_scalar ())
error ("cell2struct: DIM must be a real scalar");
dim = args(2).int_value () - 1;
}
if (dim < 0)
error ("cell2struct: DIM must be a valid dimension");
const Cell vals = args(0).cell_value ();
const Array<std::string> fields = args(1).cellstr_value ();
octave_idx_type ext = (vals.ndims () > dim ? vals.dims ()(dim) : 1);
if (ext != fields.numel ())
error ("cell2struct: number of FIELDS does not match dimension");
int nd = std::max (dim+1, vals.ndims ());
// result dimensions.
dim_vector rdv = vals.dims ().redim (nd);
assert (ext == rdv(dim));
if (nd == 2)
{
rdv(0) = rdv(1-dim);
rdv(1) = 1;
}
else
{
for (int i = dim + 1; i < nd; i++)
rdv(i-1) = rdv(i);
rdv.resize (nd-1);
}
octave_map map (rdv);
Array<idx_vector> ia (dim_vector (nd, 1), idx_vector::colon);
for (octave_idx_type i = 0; i < ext; i++)
{
ia(dim) = i;
map.setfield (fields(i), vals.index (ia).reshape (rdv));
}
return ovl (map);
}
/*
## test cell2struct versus struct2cell
%!test
%! keys = cellstr (char (floor (rand (100,10)*24+65)))';
%! vals = mat2cell (rand (100,1), ones (100,1), 1)';
%! s = struct ([keys; vals]{:});
%! t = cell2struct (vals, keys, 2);
%! assert (s, t);
%! assert (struct2cell (s), vals');
%! assert (fieldnames (s), keys');
%!assert (cell2struct ({1; 2}, {"a"; "b"}), struct ("a", 1, "b", 2))
%!assert (cell2struct ({}, {"f"}, 3), struct ("f", {}))
*/
DEFUN (rmfield, args, ,
doc: /* -*- texinfo -*-
@deftypefn {} {@var{sout} =} rmfield (@var{s}, "@var{f}")
@deftypefnx {} {@var{sout} =} rmfield (@var{s}, @var{f})
Return a @emph{copy} of the structure (array) @var{s} with the field @var{f}
removed.
If @var{f} is a cell array of strings or a character array, remove each of
the named fields.
@seealso{orderfields, fieldnames, isfield}
@end deftypefn */)
{
if (args.length () != 2)
print_usage ();
octave_map m = args(0).xmap_value ("rmfield: first argument must be a struct");
octave_value_list fval = Fcellstr (args(1), 1);
Cell fcell = fval(0).cell_value ();
for (int i = 0; i < fcell.numel (); i++)
{
std::string key = fcell(i).string_value ();
if (! m.isfield (key))
error ("rmfield: structure does not contain field %s", key.c_str ());
m.rmfield (key);
}
return ovl (m);
}
/*
## test rmfield
%!shared x
%! x(3).d=1; x(2).a=2; x(1).b=3; x(2).c=3; x(6).f="abc123";
%!
%!test
%! y = rmfield (x, "c");
%! assert (fieldnames (y), {"d"; "a"; "b"; "f"});
%! assert (size (y), [1, 6]);
%!test
%! y = rmfield (x, {"a", "f"});
%! assert (fieldnames (y), {"d"; "b"; "c"});
%! assert (size (y), [1, 6]);
*/
DEFUN (struct_levels_to_print, args, nargout,
doc: /* -*- texinfo -*-
@deftypefn {} {@var{val} =} struct_levels_to_print ()
@deftypefnx {} {@var{old_val} =} struct_levels_to_print (@var{new_val})
@deftypefnx {} {} struct_levels_to_print (@var{new_val}, "local")
Query or set the internal variable that specifies the number of
structure levels to display.
When called from inside a function with the @qcode{"local"} option, the
variable is changed locally for the function and any subroutines it calls.
The original variable value is restored when exiting the function.
@seealso{print_struct_array_contents}
@end deftypefn */)
{
return SET_INTERNAL_VARIABLE_WITH_LIMITS (struct_levels_to_print, -1,
std::numeric_limits<int>::max ());
}
DEFUN (print_struct_array_contents, args, nargout,
doc: /* -*- texinfo -*-
@deftypefn {} {@var{val} =} print_struct_array_contents ()
@deftypefnx {} {@var{old_val} =} print_struct_array_contents (@var{new_val})
@deftypefnx {} {} print_struct_array_contents (@var{new_val}, "local")
Query or set the internal variable that specifies whether to print struct
array contents.
If true, values of struct array elements are printed. This variable does
not affect scalar structures whose elements are always printed. In both
cases, however, printing will be limited to the number of levels specified
by @var{struct_levels_to_print}.
When called from inside a function with the @qcode{"local"} option, the
variable is changed locally for the function and any subroutines it calls.
The original variable value is restored when exiting the function.
@seealso{struct_levels_to_print}
@end deftypefn */)
{
return SET_INTERNAL_VARIABLE (print_struct_array_contents);
}
|