File: gwyserializable.c

package info (click to toggle)
gwyddion 2.62-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 51,952 kB
  • sloc: ansic: 398,486; python: 7,877; sh: 5,492; makefile: 4,723; xml: 3,883; cpp: 1,969; pascal: 418; perl: 154; ruby: 130
file content (2277 lines) | stat: -rw-r--r-- 73,464 bytes parent folder | download | duplicates (3)
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
/*
 *  $Id: gwyserializable.c 21684 2018-11-26 12:31:34Z yeti-dn $
 *  Copyright (C) 2003-2018 David Necas (Yeti), Petr Klapetek.
 *  E-mail: yeti@gwyddion.net, klapetek@gwyddion.net.
 *
 *  This program 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 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program 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 this program; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor,
 *  Boston, MA 02110-1301, USA.
 */

#include "config.h"
#include <string.h>

#include <libgwyddion/gwymacros.h>
#include <libgwyddion/gwyutils.h>
#include <libgwyddion/gwyserializable.h>

#define GWY_SERIALIZABLE_TYPE_NAME "GwySerializable"

static GByteArray* gwy_serializable_do_serialize   (GObject *serializable,
                                                    GByteArray *buffer);
static void        gwy_serialize_skip_type         (const guchar *buffer,
                                                    gsize size,
                                                    gsize *position,
                                                    guchar ctype);
static void        gwy_serializable_base_init      (gpointer g_class);
static GObject*    gwy_serializable_duplicate_hard_way(GObject *object);

static GByteArray* gwy_serialize_spec              (GByteArray *buffer,
                                                    const GwySerializeSpec *sp);
static gsize       gwy_serialize_spec_get_size     (const GwySerializeSpec *sp);
static gboolean    gwy_deserialize_spec_value      (const guchar *buffer,
                                                    gsize size,
                                                    gsize *position,
                                                    GwySerializeSpec *sp);
static GwySerializeItem* gwy_deserialize_hash_items(const guchar *buffer,
                                                    gsize size,
                                                    gsize *nitems);

static inline gsize ctype_size     (guchar ctype);

GType
gwy_serializable_get_type(void)
{
    /* Threads: type registered from gwy_types_init(). */
    static GType gwy_serializable_type = 0;

    if (!gwy_serializable_type) {
        static const GTypeInfo gwy_serializable_info = {
            sizeof(GwySerializableIface),
            (GBaseInitFunc)gwy_serializable_base_init,
            NULL,
            NULL,
            NULL,
            NULL,
            0,
            0,
            NULL,
            NULL,
        };

        gwy_serializable_type
            = g_type_register_static(G_TYPE_INTERFACE,
                                     GWY_SERIALIZABLE_TYPE_NAME,
                                     &gwy_serializable_info,
                                     0);
        g_type_interface_add_prerequisite(gwy_serializable_type, G_TYPE_OBJECT);
    }

    return gwy_serializable_type;
}

static void
gwy_serializable_base_init(G_GNUC_UNUSED gpointer g_class)
{
    static gboolean initialized = FALSE;

    if (initialized)
        return;
    initialized = TRUE;
}

/**
 * gwy_serializable_serialize:
 * @serializable: A #GObject that implements #GwySerializable interface.
 * @buffer: A buffer to which the serialized object should be appended,
 *          or %NULL to allocate and return a new #GByteArray.
 *
 * Serializes an object to byte buffer.
 *
 * This is a high-level method.  Do not use it for implementation of child
 * object serialization (should you ever need to do it manually), it would
 * lead to repeated required buffer size calculations.
 *
 * Returns: @buffer or a newly allocated #GByteArray with serialized
 *          object appended.
 **/
GByteArray*
gwy_serializable_serialize(GObject *serializable,
                           GByteArray *buffer)
{
    GwySerializeFunc serialize_method;
    gsize expected_size;

    g_return_val_if_fail(serializable, NULL);
    g_return_val_if_fail(GWY_IS_SERIALIZABLE(serializable), NULL);
    gwy_debug("serializing a `%s'",
              G_OBJECT_TYPE_NAME(serializable));

    serialize_method = GWY_SERIALIZABLE_GET_IFACE(serializable)->serialize;
    if (!serialize_method) {
        g_critical("`%s' doesn't implement serialize()",
                   G_OBJECT_TYPE_NAME(serializable));
        return NULL;
    }

    /* Allocate space for all the data in one turn */
    expected_size = gwy_serializable_get_size(serializable);
    if (!buffer)
        buffer = g_byte_array_sized_new(expected_size);
    else {
        /* This trick can make GLib to fill the unused part of array with
         * zeros.  But that's a small price to pay. */
        g_byte_array_set_size(buffer, buffer->len + expected_size);
        g_byte_array_set_size(buffer, buffer->len - expected_size);
    }

    return serialize_method(serializable, buffer);
}

/**
 * gwy_serializable_get_size:
 * @serializable: A #GObject that implements #GwySerializable interface.
 *
 * Calculates the expected size of serialized object.
 *
 * Returns: The expected size of serialized @serializable.
 **/
gsize
gwy_serializable_get_size(GObject *serializable)
{
    gsize (*get_size_method)(GObject*);
    const gchar *type_name;
    gsize size;

    g_return_val_if_fail(serializable, 0);
    g_return_val_if_fail(GWY_IS_SERIALIZABLE(serializable), 0);

    get_size_method = GWY_SERIALIZABLE_GET_IFACE(serializable)->get_size;
    type_name = G_OBJECT_TYPE_NAME(serializable);
    if (!get_size_method) {
        g_warning("`%s' doesn't implement get_size(), assuming empty",
                  type_name);
        return strlen(type_name) + 1 + sizeof(guint32);
    }

    size = get_size_method(serializable);
    gwy_debug("Expected size of `%s' is %" G_GSIZE_FORMAT, type_name, size);
    return size;
}

/**
 * gwy_serializable_deserialize:
 * @buffer: A block of memory of size @size contaning object representation.
 * @size: The size of @buffer.
 * @position: The position of the object in @buffer, it's updated to
 *            point after it.
 *
 * Restores a serialized object from byte buffer.
 *
 * The newly created object has reference count according to its nature, thus
 * a #GtkObject will have a floating reference, a #GObject will have a
 * refcount of 1, etc.
 *
 * Returns: A newly created object.
 **/
GObject*
gwy_serializable_deserialize(const guchar *buffer,
                             gsize size,
                             gsize *position)
{
    static const gchar *generic_skip_msg =
        "Trying to recover by generic object skip. "
        "This can fail if the class uses some very unusual "
        "serialization practices or we've got out of sync.";

    GType type;
    GwyDeserializeFunc deserialize_method;
    GObject *object;
    gsize typenamesize, oldposition;
    gpointer classref;

    g_return_val_if_fail(buffer, NULL);

    /* Get type name */
    typenamesize = gwy_serialize_check_string(buffer, size, *position, NULL);
    if (!typenamesize) {
        g_warning("Memory contents at %p doesn't look as an serialized object. "
                  "Trying to recover by ignoring rest of buffer.", buffer);
        *position = size;
        return NULL;
    }

    /* Get type from name */
    type = g_type_from_name((gchar*)(buffer + *position));
    if (!type) {
        g_warning("Type `%s' is unknown. %s",
                  buffer + *position, generic_skip_msg);
        gwy_serialize_skip_type(buffer, size, position, 'o');
        return NULL;
    }

    /* Get class from type */
    classref = g_type_class_ref(type);
    g_assert(classref);   /* this really should not fail */
    gwy_debug("deserializing a `%s'", g_type_name(type));
    if (!G_TYPE_IS_INSTANTIATABLE(type)) {
        g_warning("Type `%s' is not instantiable. %s",
                  buffer + *position, generic_skip_msg);
        gwy_serialize_skip_type(buffer, size, position, 'o');
        return NULL;
    }
    if (!g_type_is_a(type, GWY_TYPE_SERIALIZABLE)) {
        g_warning("Type `%s' is not serializable. %s",
                  buffer + *position, generic_skip_msg);
        gwy_serialize_skip_type(buffer, size, position, 'o');
        return NULL;
    }

    /* FIXME: this horrible construct gets interface class from a mere GType;
     * deserialize() is a class method, not an object method, there already
     * has to be some macro for it in gobject... */
    deserialize_method
        = ((GwySerializableIface*)
                g_type_interface_peek(g_type_class_peek(type),
                                      GWY_TYPE_SERIALIZABLE))->deserialize;
    if (!deserialize_method) {
        g_critical("Class `%s' doesn't implement deserialize()", buffer);
        gwy_serialize_skip_type(buffer, size, position, 'o');
        return NULL;
    }
    oldposition = *position;
    object = deserialize_method(buffer, size, position);
    if (object)
        g_type_class_unref(G_OBJECT_GET_CLASS(object));
    else {
        /* If deserialize fails, don't trust it and prefer generic object
         * skip. */
        *position = oldposition;
        g_warning("Object `%s' deserialization failed. %s",
                  buffer + *position, generic_skip_msg);
        gwy_serialize_skip_type(buffer, size, position, 'o');
        g_warning("Cannot safely unref class after failed `%s' deserialization",
                  g_type_name(type));
    }
    return object;
}

/**
 * gwy_serializable_duplicate:
 * @object: An object implementing #GwySerializable interface.
 *
 * Creates a copy of an object.
 *
 * If the object doesn't support duplication natively, it's brute-force
 * serialized and then deserialized, this may be quite inefficient,
 * namely for large objects.
 *
 * You can duplicate a %NULL, too, but you are discouraged from doing it.
 *
 * Returns: The newly created object copy.  However if the object is a
 *          singleton, @object itself (with incremented reference count)
 *          can be returned, too.
 **/
GObject*
gwy_serializable_duplicate(GObject *object)
{
    GObject* (*duplicate_method)(GObject*);

    if (!object)
        return NULL;
    g_return_val_if_fail(GWY_IS_SERIALIZABLE(object), NULL);

    duplicate_method = GWY_SERIALIZABLE_GET_IFACE(object)->duplicate;
    if (duplicate_method)
        return duplicate_method(object);

    return gwy_serializable_duplicate_hard_way(object);
}

static GObject*
gwy_serializable_duplicate_hard_way(GObject *object)
{
    GByteArray *buffer = NULL;
    gsize position = 0;
    GObject *duplicate;

    g_warning("`%s' doesn't have its own duplicate() method, "
              "forced to duplicate it the hard way.",
              G_OBJECT_TYPE_NAME(object));

    buffer = gwy_serializable_serialize(object, NULL);
    if (!buffer) {
        g_critical("`%s' serialization failed",
                   G_OBJECT_TYPE_NAME(object));
        return NULL;
    }
    duplicate = gwy_serializable_deserialize(buffer->data, buffer->len,
                                             &position);
    g_byte_array_free(buffer, TRUE);

    return duplicate;
}

static void
gwy_serializable_clone_do(GObject *source,
                          GObject *copy,
                          GType assert_type)
{
    GType source_type, copy_type;
    void (*clone_method)(GObject*, GObject*);

    g_return_if_fail(GWY_IS_SERIALIZABLE(source));
    g_return_if_fail(GWY_IS_SERIALIZABLE(copy));
    if (!assert_type && source == copy)
        return;

    source_type = G_TYPE_FROM_INSTANCE(source);
    copy_type = G_TYPE_FROM_INSTANCE(copy);
    if (assert_type) {
        g_return_if_fail(g_type_is_a(source_type, assert_type));
        g_return_if_fail(g_type_is_a(copy_type, assert_type));
        if (source == copy)
            return;
    }
    g_return_if_fail(g_type_is_a(copy_type, source_type));

    clone_method = GWY_SERIALIZABLE_GET_IFACE(copy)->clone;
    if (!clone_method) {
        g_critical("`%s' doesn't implement clone()",
                   G_OBJECT_TYPE_NAME(copy));
        return;
    }
    clone_method(source, copy);
}

/**
 * gwy_serializable_clone:
 * @source: An object implementing #GwySerializable interface.
 * @copy: An object of the same type as @source to modify after it.
 *
 * Makes an object identical to another object of the same type.
 *
 * More precisely, @source may be subclass of @copy (the extra information
 * is lost then).
 **/
void
gwy_serializable_clone(GObject *source,
                       GObject *copy)
{
    gwy_serializable_clone_do(source, copy, 0);
}

/**
 * gwy_serializable_clone_with_type:
 * @source: An object implementing #GwySerializable interface.
 * @copy: An object of the same type as @source to modify after it.
 * @type: The type the objects are asserted to be.
 *
 * Makes an object identical to another object of the same type, with explicit
 * type checking.
 *
 * This function is the same as gwy_serializable_clone(), except it asserts
 * the object type, which must be @type.
 *
 * Since 2.52
 **/
void
gwy_serializable_clone_with_type(GObject *source,
                                 GObject *copy,
                                 GType type)
{
    gwy_serializable_clone_do(source, copy, type);
}

/**
 * gwy_byteswapped_append:
 * @source: Pointer to memory to copy.
 * @dest: #GByteArray to copy the memory to.
 * @size: Size of one item, must be a power of 2.
 * @len: Number of items to copy.
 * @byteswap: Byte swapping pattern -- if a bit is set, blocks of
 *            corresponding size are swapped.  For byte order reversion,
 *            @byteswap must be equal to 2^@size-1.
 *
 * Appends memory to a byte array, byte swapping meanwhile.
 *
 * This function is not very fast, but neither assumes any memory alignment
 * nor alocates any temporary buffers.
 **/
G_GNUC_UNUSED
static inline void
gwy_byteswapped_append(guint8 *source,
                       GByteArray *dest,
                       gsize size,
                       gsize len,
                       gsize byteswap)
{
    gsize i, k;
    guint8 *buffer;

    if (!byteswap) {
        g_byte_array_append(dest, source, size*len);
        return;
    }

    i = dest->len;
    /* This can cause dest->data to change (bug #73) */
    g_byte_array_set_size(dest, dest->len + size*len);
    buffer = dest->data + i;
    for (i = 0; i < len; i++) {
        guint8 *b = buffer + i*size;

        for (k = 0; k < size; k++)
            b[k ^ byteswap] = *(source++);
    }
}

/**
 * ctype_size:
 * @ctype: Component type, as in gwy_serialize_pack_object_struct().
 *
 * Compute type size based on type letter.
 *
 * Returns: Size in bytes, 0 for arrays and other nonatomic types.
 **/
static inline gsize G_GNUC_CONST
ctype_size(guchar ctype)
{
    switch (ctype) {
        case 'c':
        case 'b':
        return sizeof(guchar);
        break;

        case 'i':
        return sizeof(gint32);
        break;

        case 'q':
        return sizeof(gint64);
        break;

        case 'd':
        return sizeof(gdouble);
        break;

        default:
        return 0;
        break;
    }
}

/****************************************************************************
 *
 * Serialization
 *
 ****************************************************************************/

/**
 * gwy_serializable_do_serialize:
 * @serializable: A #GObject that implements #GwySerializable interface.
 * @buffer: A buffer to which the serialized object should be appended,
 *
 * Performs serialization of an object to byte buffer.
 *
 * This is the low-level method that does not attempt to calculate required
 * buffer size and that should be used for child object serialization.
 *
 * Returns: @buffer or a newly allocated #GByteArray with serialized
 *          object appended.
 **/
static GByteArray*
gwy_serializable_do_serialize(GObject *serializable,
                              GByteArray *buffer)
{
    GwySerializeFunc serialize_method;

    g_return_val_if_fail(serializable, NULL);
    g_return_val_if_fail(GWY_IS_SERIALIZABLE(serializable), NULL);
    gwy_debug("serializing a `%s'",
              G_OBJECT_TYPE_NAME(serializable));

    serialize_method = GWY_SERIALIZABLE_GET_IFACE(serializable)->serialize;
    if (!serialize_method) {
        g_critical("`%s' doesn't implement serialize()",
                   G_OBJECT_TYPE_NAME(serializable));
        return NULL;
    }
    return serialize_method(serializable, buffer);
}

/**
 * gwy_serialize_store_int32:
 * @buffer: A buffer to which the value should be stored.
 * @position: Position in the buffer to store @value to.
 * @value: A 32bit integer.
 *
 * Stores a 32bit integer to a buffer.
 **/
static void
gwy_serialize_store_int32(GByteArray *buffer,
                          gsize position,
                          guint32 value)
{
    value = GINT32_TO_LE(value);
    memcpy(buffer->data + position, &value, sizeof(guint32));
}

/**
 * gwy_serialize_pack_object_header:
 * @buffer: A buffer to which the serialized object header should be appended.
 * @object_name: Object name.
 *
 * Packs object name and size to a byte buffer.
 *
 * As the size is unknown, placeholder value 0 is stored instead.
 * It has to be filled later with gwy_serialize_store_int32().
 *
 * Returns: @buffer or a newly allocated #GByteArray with serialization of
 *          object header appended.
 **/
static GByteArray*
gwy_serialize_pack_object_header(GByteArray *buffer,
                                 const guchar *object_name)
{
    gint32 value = 0;

    if (!buffer)
        buffer = g_byte_array_new();
    g_byte_array_append(buffer, object_name, strlen(object_name) + 1);
    g_byte_array_append(buffer, (guint8*)&value, sizeof(gint32));

    return buffer;
}

/**
 * gwy_serialize_pack_object_struct:
 * @buffer: A buffer to which the serialized components should be appended.
 * @object_name: The type name of the object.
 * @nspec: The number of items in @spec.
 * @spec: The components to serialize.
 *
 * Appends serialization of object with g_type_name() @object_name and
 * components described by @spec to @buffer in gwy-file format.
 *
 * Here's how a serialization method of a simple object whose state is
 * described by a single real number foo could look (without error checking):
 * <informalexample><programlisting>
 * static guchar*
 * my_object_serialize(GObject *obj,
 *                     guchar *buffer,
 *                     gsize *size)
 * {
 *     MyObject *my_object = MY_OBJECT(obj);
 *     GwySerializeSpec spec[] = {
 *         { 'd', "foo", &my_object->foo, NULL, },
 *     };
 *
 *     return gwy_serialize_pack_object_struct(buffer, size,
 *                                             "MyObject",
 *                                             G_N_ELEMENTS(spec), spec);
 * }
 * </programlisting></informalexample>
 *
 * Returns: The buffer with serialization of @spec components appended.
 **/
GByteArray*
gwy_serialize_pack_object_struct(GByteArray *buffer,
                                 const guchar *object_name,
                                 gsize nspec,
                                 const GwySerializeSpec *spec)
{
    gsize before_obj, i;

    g_return_val_if_fail(spec || !nspec, buffer);
    g_return_val_if_fail(object_name && *object_name, buffer);
    gwy_debug("init size: %u, buffer = %p", buffer ? buffer->len : 0, buffer);

    buffer = gwy_serialize_pack_object_header(buffer, object_name);
    before_obj = buffer->len;
    gwy_debug("+head size: %u", buffer->len);
    for (i = 0; i < nspec; i++) {
        if (!spec[i].value) {
            gwy_debug("ignoring item `%s' with NULL value", spec[i].name);
            continue;
        }
        if (spec[i].ctype == 'o') {
            GObject **p = spec[i].value;
            if (!*p) {
                gwy_debug("ignoring NULL object item `%s'", spec[i].name);
                continue;
            }
        }
        gwy_serialize_spec(buffer, spec + i);
    }
    gwy_debug("+body size: %u", buffer->len);
    gwy_serialize_store_int32(buffer, before_obj - sizeof(guint32),
                              buffer->len - before_obj);
    return buffer;
}

/**
 * gwy_serialize_object_items:
 * @buffer: A buffer to which the serialized components should be appended,
 *          or %NULL.
 * @object_name: The type of the object.
 * @nitems: The number of @items items.
 * @items: The components to serialize.
 *
 * Serializes an object to buffer in gwy-file format.
 *
 * More precisely, it appends serialization of object with g_type_name()
 * @object_name with components described by @items to @buffer.
 *
 * Returns: @buffer or a newly allocated #GByteArray with serialization of
 *          @items components appended.
 **/
GByteArray*
gwy_serialize_object_items(GByteArray *buffer,
                           const guchar *object_name,
                           gsize nitems,
                           const GwySerializeItem *items)
{
    GwySerializeSpec sp;
    gsize before_obj, i;

    g_return_val_if_fail(items || !nitems, buffer);
    g_return_val_if_fail(object_name && *object_name, buffer);
    gwy_debug("init size: %u, buffer = %p", buffer ? buffer->len : 0, buffer);

    buffer = gwy_serialize_pack_object_header(buffer, object_name);
    before_obj = buffer->len;
    gwy_debug("+head size: %u", buffer->len);

    for (i = 0; i < nitems; i++) {
        sp.ctype = items[i].ctype;
        sp.name = items[i].name;
        sp.value = (const gpointer)&items[i].value;
        sp.array_size = (guint32*)&items[i].array_size;
        if (sp.ctype == 'o' && !items[i].value.v_object) {
            gwy_debug("ignoring NULL object item `%s'", sp.name);
            continue;
        }
        gwy_serialize_spec(buffer, &sp);
    }

    gwy_debug("+body size: %u", buffer->len);
    gwy_serialize_store_int32(buffer, before_obj - sizeof(guint32),
                              buffer->len - before_obj);

    return buffer;
}

static GByteArray*
gwy_serialize_spec(GByteArray *buffer,
                   const GwySerializeSpec *sp)
{
    guint32 asize = 0, leasize;
    gsize j;
    guint8 *arr = NULL;

    g_assert(sp->value);
    if (g_ascii_isupper(sp->ctype)) {
        g_assert(sp->array_size);
        g_assert(*(gpointer*)sp->value);
        asize = *sp->array_size;
        leasize = GINT32_TO_LE(asize);
        arr = *(guint8**)sp->value;
        if (!asize) {
            g_warning("Ignoring zero-length array <%s>", sp->name);
            return buffer;
        }
    }

    g_byte_array_append(buffer, sp->name, strlen(sp->name) + 1);
    g_byte_array_append(buffer, &sp->ctype, 1);
    gwy_debug("<%s> <%c> %u", sp->name, sp->ctype, buffer->len);
    switch (sp->ctype) {
        case 'b': {
            /* store it as char */
            char value = *(gboolean*)sp->value;

            value = !!value;
            g_byte_array_append(buffer, &value, 1);
        }
        break;

        case 'c': {
            g_byte_array_append(buffer, sp->value, 1);
        }
        break;

        case 'C': {
            g_byte_array_append(buffer, (guint8*)&leasize, sizeof(gint32));
            g_byte_array_append(buffer, arr, asize*sizeof(char));
        }
        break;

        case 'i': {
            gint32 value = *(gint32*)sp->value;

            value = GINT32_TO_LE(value);
            g_byte_array_append(buffer, (guint8*)&value, sizeof(gint32));
        }
        break;

        case 'I': {
            g_byte_array_append(buffer, (guint8*)&leasize, sizeof(gint32));
#if (G_BYTE_ORDER == G_LITTLE_ENDIAN)
            g_byte_array_append(buffer, arr, asize*sizeof(gint32));
#else
             gwy_byteswapped_append(arr, buffer, sizeof(gint32), asize,
                                    sizeof(gint32) - 1);
#endif
        }
        break;

        case 'q': {
            gint64 value = *(gint64*)sp->value;

            value = GINT64_TO_LE(value);
            g_byte_array_append(buffer, (guint8*)&value, sizeof(gint64));
        }
        break;

        case 'Q': {
            g_byte_array_append(buffer, (guint8*)&leasize, sizeof(gint32));
#if (G_BYTE_ORDER == G_LITTLE_ENDIAN)
            g_byte_array_append(buffer, arr, asize*sizeof(gint64));
#else
            gwy_byteswapped_append(arr, buffer, sizeof(gint64), asize,
                                   sizeof(gint64) - 1);
#endif
        }
        break;

        case 'd': {
#if (G_BYTE_ORDER == G_LITTLE_ENDIAN)
            g_byte_array_append(buffer, sp->value, sizeof(gdouble));
#else
            gwy_byteswapped_append(sp->value, buffer, sizeof(gdouble), 1,
                                   sizeof(gdouble) - 1);
#endif
        }
        break;

        case 'D': {
            g_byte_array_append(buffer, (guint8*)&leasize, sizeof(gint32));
#if (G_BYTE_ORDER == G_LITTLE_ENDIAN)
            g_byte_array_append(buffer, arr, asize*sizeof(gdouble));
#else
            gwy_byteswapped_append(arr, buffer, sizeof(gdouble), asize,
                                   sizeof(gdouble) - 1);
#endif
        }
        break;

        case 's': {
            guchar *value = *(guchar**)sp->value;

            if (!value) {
                g_warning("representing NULL as an empty string");
                g_byte_array_append(buffer, "", 1);
            }
            else
                g_byte_array_append(buffer, value, strlen(value) + 1);
        }
        break;

        case 'S': {
            g_byte_array_append(buffer, (guint8*)&leasize, sizeof(gint32));
            for (j = 0; j < asize; j++) {
                guchar *value = ((guchar**)arr)[j];

                if (!value) {
                    g_warning("representing NULL as an empty string");
                    g_byte_array_append(buffer, "", 1);
                }
                else
                    g_byte_array_append(buffer, value, strlen(value) + 1);
            }
        }
        break;

        case 'o': {
            GObject *value = *(GObject**)sp->value;

            if (G_UNLIKELY(!value))
                g_critical("Object cannot be NULL");
            else if (G_UNLIKELY(!GWY_IS_SERIALIZABLE(value)))
                g_critical("Object must be serializable");
            else
                gwy_serializable_do_serialize(value, buffer);
        }
        break;

        case 'O': {
            g_byte_array_append(buffer, (guint8*)&leasize, sizeof(gint32));
            for (j = 0; j < asize; j++) {
                GObject *value = ((GObject**)arr)[j];

                if (G_UNLIKELY(!value))
                    g_critical("Object cannot be NULL");
                else if (G_UNLIKELY(!GWY_IS_SERIALIZABLE(value)))
                    g_critical("Object must be serializable");
                else
                    gwy_serializable_do_serialize(value, buffer);
            }
        }
        break;

        default:
        g_critical("wrong spec <%c>", sp->ctype);
        break;
    }

    gwy_debug("after: %u", buffer->len);
    return buffer;
}

/****************************************************************************
 *
 * Size calculation
 *
 ****************************************************************************/

/**
 * gwy_serialize_get_struct_size:
 * @object_name: The type name of the object.
 * @nspec: The number of items in @spec.
 * @spec: The components to serialize.
 *
 * Calculates serialized object size for struct-like objects.
 *
 * The component specification is the same as in
 * gwy_serialize_pack_object_struct().
 *
 * Returns: Serialized object size, it included space for object name and size.
 *          The value is exact unless some components are objects that do not
 *          return exact size estimate themselves.
 **/
gsize
gwy_serialize_get_struct_size(const guchar *object_name,
                              gsize nspec,
                              const GwySerializeSpec *spec)
{
    gsize i, size;

    g_return_val_if_fail(spec || !nspec, 0);
    g_return_val_if_fail(object_name && *object_name, 0);

    size = strlen(object_name) + 1 + sizeof(guint32);
    for (i = 0; i < nspec; i++) {
        if (!spec[i].value) {
            gwy_debug("ignoring item `%s' with NULL value", spec[i].name);
            continue;
        }
        if (spec[i].ctype == 'o') {
            GObject **p = spec[i].value;
            if (!*p) {
                gwy_debug("ignoring NULL object item `%s'", spec[i].name);
                continue;
            }
        }
        size += gwy_serialize_spec_get_size(spec + i);
    }

    return size;
}

/**
 * gwy_serialize_get_items_size:
 * @object_name: The type name of the object.
 * @nitems: The number of @items items.
 * @items: The components to serialize.
 *
 * Calculates serialized object size for hash-like objects.
 *
 * The component specification is the same as in
 * gwy_serialize_object_items().
 *
 * Returns: Serialized object size, it included space for object name and size.
 *          The value is exact unless some components are objects that do not
 *          return exact size estimate themselves.
 **/
gsize
gwy_serialize_get_items_size(const guchar *object_name,
                             gsize nitems,
                             const GwySerializeItem *items)
{
    GwySerializeSpec sp;
    gsize size, i;

    g_return_val_if_fail(items || !nitems, 0);
    g_return_val_if_fail(object_name && *object_name, 0);

    size = strlen(object_name) + 1 + sizeof(guint32);
    for (i = 0; i < nitems; i++) {
        sp.ctype = items[i].ctype;
        sp.name = items[i].name;
        sp.value = (const gpointer)&items[i].value;
        sp.array_size = (guint32*)&items[i].array_size;
        if (sp.ctype == 'o' && !items[i].value.v_object) {
            gwy_debug("ignoring NULL object item `%s'", sp.name);
            continue;
        }
        size += gwy_serialize_spec_get_size(&sp);
    }

    return size;
}

static gsize
gwy_serialize_spec_get_size(const GwySerializeSpec *sp)
{
    guint32 asize = 0;
    gsize size, j, s;
    guint8 *arr = NULL;

    g_assert(sp->value);
    if (g_ascii_isupper(sp->ctype)) {
        g_assert(sp->array_size);
        g_assert(*(gpointer*)sp->value);
        asize = *sp->array_size;
        if (!asize) {
            g_warning("Ignoring zero-length array <%s>", sp->name);
            return 0;
        }
        arr = *(guint8**)sp->value;
    }

    size = strlen(sp->name) + 1;
    size++;
    if ((s = ctype_size(sp->ctype)))
        return size + s;
    else if ((s = ctype_size(g_ascii_tolower(sp->ctype))))
        return size + s*asize;

    switch (sp->ctype) {
        case 's': {
            guchar *value = *(guchar**)sp->value;

            size++;
            if (value)
                size += strlen(value);
        }
        break;

        case 'S': {
            size += sizeof(guint32);
            for (j = 0; j < asize; j++) {
                guchar *value = ((guchar**)arr)[j];

                if (value)
                    size += strlen(value);
            }
            size += asize;
        }
        break;

        case 'o': {
            GObject *value = *(GObject**)sp->value;

            if (G_UNLIKELY(!value))
                g_critical("Object cannot be NULL");
            else if (G_UNLIKELY(!GWY_IS_SERIALIZABLE(value)))
                g_critical("Object must be serializable");
            else
                size += gwy_serializable_get_size(value);
        }
        break;

        case 'O': {
            size += sizeof(guint32);
            for (j = 0; j < asize; j++) {
                GObject *value = ((GObject**)arr)[j];

                if (G_UNLIKELY(!value))
                    g_critical("Object cannot be NULL");
                else if (G_UNLIKELY(!GWY_IS_SERIALIZABLE(value)))
                    g_critical("Object must be serializable");
                else
                    size += gwy_serializable_get_size(value);
            }
        }
        break;

        default:
        g_critical("wrong spec <%c>", sp->ctype);
        break;
    }

    return size;
}

/****************************************************************************
 *
 * Deserialization
 *
 ****************************************************************************/

/**
 * gwy_deserialize_int32:
 * @buffer: A memory location containing a serialized 32bit integer at position
 *          @position.
 * @size: The size of @buffer.
 * @position: The position of the integer in @buffer, it's updated to
 *            point after it.
 *
 * Deserializes a one 32bit integer.
 *
 * Returns: The integer as gint32.
 **/
static inline gint32
gwy_deserialize_int32(const guchar *buffer,
                      gsize size,
                      gsize *position)
{
    gint32 value;

    gwy_debug("buf = %p, size = %" G_GSIZE_FORMAT ", pos = %" G_GSIZE_FORMAT,
              buffer, size, *position);
    g_assert(buffer);
    g_assert(position);
    g_return_val_if_fail(*position + sizeof(gint32) <= size, 0);
    memcpy(&value, buffer + *position, sizeof(gint32));
    value = GINT32_FROM_LE(value);
    *position += sizeof(gint32);

    gwy_debug("value = <%d>", value);
    return value;
}

/**
 * gwy_deserialize_char:
 * @buffer: A memory location containing a serialized character at position
 *          @position.
 * @size: The size of @buffer.
 * @position: The position of the character in @buffer, it's updated to
 *            point after it.
 *
 * Deserializes a one character.
 *
 * Returns: The character as guchar.
 **/
static inline guchar
gwy_deserialize_char(const guchar *buffer,
                     gsize size,
                     gsize *position)
{
    guchar value;

    gwy_debug("buf = %p, size = %" G_GSIZE_FORMAT ", pos = %" G_GSIZE_FORMAT,
              buffer, size, *position);
    g_assert(buffer);
    g_assert(position);
    g_return_val_if_fail(*position + sizeof(guchar) <= size, '\0');
    value = buffer[*position];
    *position += sizeof(guchar);

    gwy_debug("value = <%c>", value);
    return value;
}

/**
 * gwy_serialize_skip_type:
 * @buffer: Serialized data.
 * @size: Size of @buffer.
 * @position: Current position in buffer, will be updated after type end.
 * @ctype: Type to skip.
 *
 * Skips a serialized item of given type in buffer.
 *
 * On failure, skips to the end of buffer.
 **/
static void
gwy_serialize_skip_type(const guchar *buffer,
                        gsize size,
                        gsize *position,
                        guchar ctype)
{
/* XXX: Must use #defines that have no scope and are not visible in debugger
 * instead of const char buffers because Mandriva's idiotic enforcement of
 * -Werror=format-security. */
#define too_short_msg \
        "Truncated or corrupted buffer, need %" G_GSIZE_FORMAT " bytes " \
        "to skip <%c>, but only %" G_GSIZE_FORMAT " bytes remain."
#define no_string_msg \
        "Expected a string, trying to skip to end of [sub]buffer."

    gsize tsize, alen;

    if (*position >= size) {
        g_critical("Trying to skip <%c> after end of buffer?!", ctype);
        return;
    }

    /* simple types */
    tsize = ctype_size(ctype);
    if (tsize) {
        if (*position + tsize > size) {
            g_warning(too_short_msg, tsize, ctype, size - *position);
            *position = size;
            return;
        }
        *position += tsize;
        return;
    }

    /* strings */
    if (ctype == 's') {
        tsize = gwy_serialize_check_string(buffer, size, *position, NULL);
        if (!tsize) {
            g_warning(no_string_msg);
            *position = size;
            return;
        }
        *position += tsize;
        return;
    }

    /* objects */
    if (ctype == 'o') {
        /* an object consists of its name... */
        tsize = gwy_serialize_check_string(buffer, size, *position, NULL);
        if (!tsize) {
            g_warning(no_string_msg);
            *position = size;
            return;
        }
        *position += tsize;
        /* ...and length of data... */
        if (*position + ctype_size('i') > size) {
            g_warning(too_short_msg, ctype_size('i'), 'i', size - *position);
            *position = size;
            return;
        }
        tsize = gwy_deserialize_int32(buffer, size, position);
        /* ...and the data */
        if (*position + tsize > size) {
            g_warning(too_short_msg, tsize, ctype, size - *position);
            *position = size;
            return;
        }
        *position += tsize;
        return;
    }

    /* string arrays */
    if (ctype == 'S') {
        if (*position + ctype_size('i') > size) {
            g_warning(too_short_msg, ctype_size('i'), 'i', size - *position);
            *position = size;
            return;
        }
        alen = gwy_deserialize_int32(buffer, size, position);
        while (alen) {
            tsize = gwy_serialize_check_string(buffer, size, *position, NULL);
            if (!tsize) {
                g_warning(no_string_msg);
                *position = size;
                return;
            }
            *position += tsize;
            alen--;
        }
        return;
    }

    /* object arrays */
    if (ctype == 'O') {
        if (*position + ctype_size('i') > size) {
            g_warning(too_short_msg, ctype_size('i'), 'i', size - *position);
            *position = size;
            return;
        }
        alen = gwy_deserialize_int32(buffer, size, position);
        while (alen) {
            /* an object consists of its name... */
            tsize = gwy_serialize_check_string(buffer, size, *position, NULL);
            if (!tsize) {
                g_warning(no_string_msg);
                *position = size;
                return;
            }
            *position += tsize;
            /* ...and length of data... */
            if (*position + ctype_size('i') > size) {
                g_warning(too_short_msg,
                          ctype_size('i'), 'i', size - *position);
                *position = size;
                return;
            }
            tsize = gwy_deserialize_int32(buffer, size, position);
            /* ...and the data */
            if (*position + tsize > size) {
                g_warning(too_short_msg, tsize, ctype, size - *position);
                *position = size;
                return;
            }
            *position += tsize;
            alen--;
        }
        return;
    }

    /* arrays of simple types */
    if (g_ascii_isupper(ctype)) {
        ctype = g_ascii_tolower(ctype);
        tsize = ctype_size(ctype);
        if (*position + ctype_size('i') > size) {
            g_warning(too_short_msg, ctype_size('i'), 'i', size - *position);
            *position = size;
            return;
        }
        alen = gwy_deserialize_int32(buffer, size, position);
        if (*position + alen*tsize > size) {
            g_warning(too_short_msg, alen*tsize, ctype, size - *position);
            *position = size;
            return;
        }
        *position += alen*tsize;
        return;
    }

    g_critical("Trying to skip unknown type `%c'", ctype);
    *position = size;
}

/* FIXME: Merge into gwy_serialize_unpack_object_struct()? */
static gboolean
gwy_serialize_unpack_struct(const guchar *buffer,
                            gsize size,
                            gsize nspec,
                            GwySerializeSpec *spec)
{
    gsize nlen, position;
    const GwySerializeSpec *sp;
    const guchar *name;
    guchar ctype;

    position = 0;
    while (position < size) {
        nlen = gwy_serialize_check_string(buffer, size, position, NULL);
        if (!nlen) {
            g_warning("Expected a component name to deserialize, got garbage");
            return FALSE;
        }

        for (sp = spec; (gsize)(sp - spec) < nspec; sp++) {
            if (gwy_strequal(sp->name, buffer + position))
                break;
        }
        name = buffer + position;
        position += nlen;
        if (position >= size) {
            g_warning("Got past the end of truncated or corrupted buffer");
            return FALSE;
        }
        ctype = gwy_deserialize_char(buffer, size, &position);
        if ((gsize)(sp - spec) == nspec) {
            g_warning("Extra component `%s' of type `%c'", name, ctype);
            gwy_serialize_skip_type(buffer, size, &position, ctype);
            continue;
        }
        if (!sp->value) {
            gwy_debug("ignoring item `%s' with NULL value", sp->name);
            gwy_serialize_skip_type(buffer, size, &position, ctype);
            continue;
        }

        if (ctype != sp->ctype) {
            g_warning("Bad or unknown type `%c' of `%s' (expected `%c')",
                      ctype, name, sp->ctype);
            return FALSE;
        }

        if (position + ctype_size(ctype) > size) {
            g_warning("Got past the end of truncated or corrupted buffer");
            return FALSE;
        }

        if (!gwy_deserialize_spec_value(buffer, size, &position,
                                        (GwySerializeSpec*)sp))
            return FALSE;
    }
    return TRUE;
}

/**
 * gwy_serialize_unpack_object_struct:
 * @buffer: A memory location containing a serialized object at position
 *          @position.
 * @size: Current size of @buffer, new size is returned here.
 * @position: The position of the object in @buffer, it's updated to point
 *            after it.
 * @object_name: The type name of the object.
 * @nspec: The number of items in @spec.
 * @spec: The components to deserialize.
 *
 * Deserializes an object with named components packed into gwy-file format by
 * gwy_serialize_pack_object_struct().
 *
 * Extra components are ignored (but cause a warning), components of different
 * type than expected cause failure, missing components are not detected.
 *
 * It is safe to pass pointers to existing non-atomic objects (strings, arrays,
 * objects) in @spec values, they will be dereferenced and freed as necessary
 * when an unpacked value is about to replace them.
 * For the same reason it is an error to pass pointers to unintialized memory
 * there, always initialize non-atomic @spec values to %NULL pointers, at
 * least.
 *
 * Caller is responsible for use/clean-up of these values if deserialization
 * succeeds or not.
 *
 * Here's how a deserialization method of a simple object whose state is
 * described by a single real number @foo could look (without error checking):
 * <informalexample><programlisting>
 * static GObject*
 * my_object_deserialize(const guchar *buffer,
 *                       gsize size,
 *                       gsize *position)
 * {
 *     double foo = 1.0;
 *     GwySerializeSpec spec[] = {
 *         { 'd', "foo", &foo, NULL, },
 *     };
 *     MyObject *my_object;
 *
 *     gwy_serialize_unpack_object_struct(buffer, size, position,
 *                                        "MyObject",
 *                                        G_N_ELEMENTS(spec), spec);
 *     return my_object_new(foo);
 * }
 * </programlisting></informalexample>
 *
 * Returns: Whether the unpacking succeeded
 *          (see description body for definition of success and failure).
 **/
gboolean
gwy_serialize_unpack_object_struct(const guchar *buffer,
                                   gsize size,
                                   gsize *position,
                                   const guchar *object_name,
                                   gsize nspec,
                                   GwySerializeSpec *spec)
{
    gsize mysize;
    gboolean ok;

    mysize = gwy_serialize_check_string(buffer, size, *position, object_name);
    g_return_val_if_fail(mysize, FALSE);
    *position += mysize;

    mysize = gwy_deserialize_int32(buffer, size, position);
    g_return_val_if_fail(mysize <= size - *position, FALSE);
    ok = gwy_serialize_unpack_struct(buffer + *position, mysize, nspec, spec);
    *position += mysize;

    return ok;
}

/**
 * gwy_deserialize_object_hash:
 * @buffer: A block of memory of size @size contaning object representation.
 * @size: The size of @buffer.
 * @position: Current position in buffer, will be updated to point after
 *            object.
 * @object_name: The type name of the object.
 * @nitems: Where the number of deserialized components should be stored.
 *
 * Deserializes an object with arbitrary components from gwy-file format.
 *
 * This function works like gwy_serialize_unpack_object_struct(), except that
 * it does not use any a priori knowledge of what the object contains.  So
 * instead of filling values in supplied #GwySerializeSpec's, it constructs
 * #GwySerializeItem's completely from what is found in @buffer.  It does
 * considerably less sanity checks and even allows several components of the
 * same name.
 *
 * Returns: A newly allocated array of deserialized components.  Note the
 *          @name fields of #GwySerializeSpec's point to @buffer and thus are
 *          valid only as long as @buffer is; any arrays or strings are newly
 *          allocated and must be reused or freed by caller.
 **/
GwySerializeItem*
gwy_deserialize_object_hash(const guchar *buffer,
                            gsize size,
                            gsize *position,
                            const guchar *object_name,
                            gsize *nitems)
{
    gsize mysize;
    GwySerializeItem *items;

    mysize = gwy_serialize_check_string(buffer, size, *position, object_name);
    g_return_val_if_fail(mysize, NULL);
    *position += mysize;

    mysize = (guint32)gwy_deserialize_int32(buffer, size, position);
    g_return_val_if_fail(mysize <= size - *position, NULL);
    items = gwy_deserialize_hash_items(buffer + *position, mysize, nitems);
    *position += mysize;

    return items;
}

static GwySerializeItem*
gwy_deserialize_hash_items(const guchar *buffer,
                           gsize size,
                           gsize *nitems)
{
    gsize nlen, position;
    GArray *items;
    GwySerializeItem it, *pit;
    GwySerializeSpec sp;

    if (!size) {
        *nitems = 0;
        /* Return something non-NULL since we didn't fail. */
        return g_new(GwySerializeItem, 1);
    }

    items = g_array_new(FALSE, FALSE, sizeof(GwySerializeItem));
    position = 0;
    sp.array_size = &it.array_size;
    sp.value = &it.value;
    while (position < size) {
        gwy_clear(&it, 1);
        nlen = gwy_serialize_check_string(buffer, size, position, NULL);
        if (!nlen) {
            g_warning("Expected a component name to deserialize, got garbage");
            break;
        }
        it.name = buffer + position;
        position += nlen;
        if (position >= size) {
            g_warning("Got past the end of truncated or corrupted buffer");
            break;
        }
        it.ctype = gwy_deserialize_char(buffer, size, &position);
        if (position + ctype_size(it.ctype) > size) {
            g_warning("Got past the end of truncated or corrupted buffer");
            break;
        }
        sp.name = it.name;
        sp.ctype = it.ctype;
        if (!gwy_deserialize_spec_value(buffer, size, &position, &sp))
            break;
        g_array_append_val(items, it);
        gwy_debug("appended value #%u: <%s> of <%c>",
                  items->len - 1, sp.name, sp.ctype);
    }

    *nitems = items->len;
    pit = (GwySerializeItem*)items->data;
    g_array_free(items, FALSE);

    return pit;
}

/**
 * gwy_deserialize_boolean:
 * @buffer: A memory location containing a serialized boolean at position
 *          @position.
 * @size: The size of @buffer.
 * @position: The position of the character in @buffer, it's updated to
 *            point after it.
 *
 * Deserializes a one boolean.
 *
 * Returns: The boolean as gboolean.
 **/
static inline gboolean
gwy_deserialize_boolean(const guchar *buffer,
                        gsize size,
                        gsize *position)
{
    gboolean value;

    gwy_debug("buf = %p, size = %" G_GSIZE_FORMAT ", pos = %" G_GSIZE_FORMAT,
              buffer, size, *position);
    g_assert(buffer);
    g_assert(position);
    g_return_val_if_fail(*position + sizeof(guchar) <= size, FALSE);
    value = !!buffer[*position];
    *position += sizeof(guchar);

    gwy_debug("value = <%s>", value ? "TRUE" : "FALSE");
    return value;
}

/**
 * gwy_deserialize_char_array:
 * @buffer: A memory location containing a serialized character array at
 *          position @position.
 * @size: The size of @buffer.
 * @position: The position of the array in @buffer, it's updated to
 *            point after it.
 * @asize: Where the size of the array is to be returned on success.
 *
 * Deserializes a character array.
 *
 * Returns: The unpacked character array (newly allocated).
 **/
static inline guchar*
gwy_deserialize_char_array(const guchar *buffer,
                           gsize size,
                           gsize *position,
                           gsize *asize)
{
    guchar *value;
    gsize newasize;

    gwy_debug("buf = %p, size = %" G_GSIZE_FORMAT ", pos = %" G_GSIZE_FORMAT,
              buffer, size, *position);

    if (*position + sizeof(gint32) > size)
        return NULL;
    if (!(newasize = gwy_deserialize_int32(buffer, size, position)))
        return NULL;
    if (newasize > (size - *position))
        return NULL;
    g_return_val_if_fail(*position + newasize*sizeof(guchar) <= size, NULL);
    value = g_memdup(buffer + *position, newasize*sizeof(guchar));
    *position += newasize*sizeof(guchar);
    *asize = newasize;

    gwy_debug("|value| = %" G_GSIZE_FORMAT, newasize);
    return value;
}

/**
 * gwy_deserialize_int32_array:
 * @buffer: A memory location containing a serialized int32 array at
 *          position @position.
 * @size: The size of @buffer.
 * @position: The position of the array in @buffer, it's updated to
 *            point after it.
 * @asize: Where the size of the array is to be returned on success.
 *
 * Deserializes an int32 array.
 *
 * Returns: The unpacked 32bit integer array (newly allocated).
 **/
static inline gint32*
gwy_deserialize_int32_array(const guchar *buffer,
                            gsize size,
                            gsize *position,
                            gsize *asize)
{
    gint32 *value;
    gsize newasize;

    gwy_debug("buf = %p, size = %" G_GSIZE_FORMAT ", pos = %" G_GSIZE_FORMAT,
              buffer, size, *position);

    if (*position + sizeof(gint32) > size)
        return NULL;
    if (!(newasize = gwy_deserialize_int32(buffer, size, position)))
        return NULL;
    if (newasize > (size - *position)/sizeof(gint32))
        return NULL;
#if (G_BYTE_ORDER == G_LITTLE_ENDIAN)
    value = g_memdup(buffer + *position, newasize*sizeof(gint32));
#else
    value = g_new(gint32, newasize*sizeof(gint32));
    gwy_memcpy_byte_swap(buffer + *position, (guint8*)value,
                         sizeof(gint32), newasize, sizeof(gint32) - 1);
#endif
    *position += newasize*sizeof(gint32);
    *asize = newasize;

    gwy_debug("|value| = %" G_GSIZE_FORMAT, newasize);
    return value;
}

/**
 * gwy_deserialize_int64:
 * @buffer: A memory location containing a serialized 64bit integer at position
 *          @position.
 * @size: The size of @buffer.
 * @position: The position of the integer in @buffer, it's updated to
 *            point after it.
 *
 * Deserializes a one 64bit integer.
 *
 * Returns: The integer as gint64.
 **/
static inline gint64
gwy_deserialize_int64(const guchar *buffer,
                      gsize size,
                      gsize *position)
{
    gint64 value;

    gwy_debug("buf = %p, size = %" G_GSIZE_FORMAT ", pos = %" G_GSIZE_FORMAT,
              buffer, size, *position);
    g_assert(buffer);
    g_assert(position);
    g_return_val_if_fail(*position + sizeof(gint64) <= size, 0);
    memcpy(&value, buffer + *position, sizeof(gint64));
    value = GINT64_FROM_LE(value);
    *position += sizeof(gint64);

    gwy_debug("value = <%lld>", value);
    return value;
}

/**
 * gwy_deserialize_int64_array:
 * @buffer: A memory location containing a serialized int64 array at
 *          position @position.
 * @size: The size of @buffer.
 * @position: The position of the array in @buffer, it's updated to
 *            point after it.
 * @asize: Where the size of the array is to be returned on success.
 *
 * Deserializes an int64 array.
 *
 * Returns: The unpacked 64bit integer array (newly allocated).
 **/
static inline gint64*
gwy_deserialize_int64_array(const guchar *buffer,
                            gsize size,
                            gsize *position,
                            gsize *asize)
{
    gint64 *value;
    gsize newasize;

    gwy_debug("buf = %p, size = %" G_GSIZE_FORMAT ", pos = %" G_GSIZE_FORMAT,
              buffer, size, *position);

    if (*position + sizeof(gint32) > size)
        return NULL;
    if (!(newasize = gwy_deserialize_int32(buffer, size, position)))
        return NULL;
    if (newasize > (size - *position)/sizeof(gint64))
        return NULL;
#if (G_BYTE_ORDER == G_LITTLE_ENDIAN)
    value = g_memdup(buffer + *position, newasize*sizeof(gint64));
#else
    value = g_new(gint64, newasize*sizeof(gint64));
    gwy_memcpy_byte_swap(buffer + *position, (guint8*)value,
                         sizeof(gint64), newasize, sizeof(gint64) - 1);
#endif
    *position += newasize*sizeof(gint64);
    *asize = newasize;

    gwy_debug("|value| = %" G_GSIZE_FORMAT, newasize);
    return value;
}

/**
 * gwy_deserialize_double:
 * @buffer: A memory location containing a serialized gdouble at position
 *          @position.
 * @size: The size of @buffer.
 * @position: The position of the integer in @buffer, it's updated to
 *            point after it.
 *
 * Deserializes a one gdouble.
 *
 * Returns: The integer as gdouble.
 **/
static inline gdouble
gwy_deserialize_double(const guchar *buffer,
                       gsize size,
                       gsize *position)
{
    gdouble value;

    gwy_debug("buf = %p, size = %" G_GSIZE_FORMAT ", pos = %" G_GSIZE_FORMAT,
              buffer, size, *position);
    g_assert(buffer);
    g_assert(position);
    g_return_val_if_fail(*position + sizeof(gdouble) <= size, 0.0);
#if (G_BYTE_ORDER == G_LITTLE_ENDIAN)
    memcpy(&value, buffer + *position, sizeof(gdouble));
#else
    gwy_memcpy_byte_swap(buffer + *position, (guint8*)&value,
                         sizeof(gdouble), 1, sizeof(gdouble) - 1);
#endif
    *position += sizeof(gdouble);

    gwy_debug("value = <%g>", value);
    return value;
}

/**
 * gwy_deserialize_double_array:
 * @buffer: A memory location containing a serialized gdouble array at
 *          position @position.
 * @size: The size of @buffer.
 * @position: The position of the array in @buffer, it's updated to
 *            point after it.
 * @asize: Where the size of the array is to be returned on success.
 *
 * Deserializes a gdouble array.
 *
 * Returns: The unpacked gdouble array (newly allocated).
 **/
static inline gdouble*
gwy_deserialize_double_array(const guchar *buffer,
                             gsize size,
                             gsize *position,
                             gsize *asize)
{
    gdouble *value;
    gsize newasize;

    gwy_debug("buf = %p, size = %" G_GSIZE_FORMAT ", pos = %" G_GSIZE_FORMAT,
              buffer, size, *position);

    if (*position + sizeof(gint32) > size)
        return NULL;
    if (!(newasize = gwy_deserialize_int32(buffer, size, position)))
        return NULL;
    if (newasize > (size - *position)/sizeof(gdouble))
        return NULL;
#if (G_BYTE_ORDER == G_LITTLE_ENDIAN)
    value = g_memdup(buffer + *position, newasize*sizeof(gdouble));
#else
    value = g_new(gdouble, newasize*sizeof(gdouble));
    gwy_memcpy_byte_swap(buffer + *position, (guint8*)value,
                         sizeof(gdouble), newasize, sizeof(gdouble) - 1);
#endif
    *position += newasize*sizeof(gdouble);
    *asize = newasize;

    gwy_debug("|value| = %" G_GSIZE_FORMAT, newasize);
    return value;
}

/**
 * gwy_deserialize_string:
 * @buffer: A memory location containing a serialized NUL-terminated string at
 *          position @position.
 * @size: The size of @buffer.
 * @position: The position of the string in @buffer, it's updated to
 *            point after it.
 *
 * Deserializes a one NUL-terminated string.
 *
 * Returns: A newly allocated, NUL-terminated string.
 **/
static inline guchar*
gwy_deserialize_string(const guchar *buffer,
                       gsize size,
                       gsize *position)
{
    guchar *value;
    const guchar *p;

    gwy_debug("buf = %p, size = %" G_GSIZE_FORMAT ", pos = %" G_GSIZE_FORMAT,
              buffer, size, *position);
    g_assert(buffer);
    g_assert(position);
    g_return_val_if_fail(*position < size, NULL);
    p = memchr(buffer + *position, 0, size - *position);
    g_return_val_if_fail(p, NULL);
    value = g_strdup(buffer + *position);
    *position += (p - buffer) - *position + 1;

    gwy_debug("value = <%s>", value);
    return value;
}

/**
 * gwy_deserialize_string_array:
 * @buffer: A memory location containing an array of serialized NUL-terminated
 *          string at position @position.
 * @size: The size of @buffer.
 * @position: The position of the string array in @buffer, it's updated to
 *            after it.
 * @asize: Where the size of the array is to be returned on success.
 *
 * Deserializes a string array.
 *
 * Returns: A newly allocated array of NUL-terminated strings.
 **/
static inline guchar**
gwy_deserialize_string_array(const guchar *buffer,
                             gsize size,
                             gsize *position,
                             gsize *asize)
{
    guchar **value;
    gsize newasize, j;

    gwy_debug("buf = %p, size = %" G_GSIZE_FORMAT ", pos = %" G_GSIZE_FORMAT,
              buffer, size, *position);

    if (*position + sizeof(gint32) > size)
        return NULL;
    if (!(newasize = gwy_deserialize_int32(buffer, size, position)))
        return NULL;
    /* Minimum string size is 1 byte */
    if (newasize > (size - *position))
        return NULL;
    value = g_new(guchar*, newasize);
    for (j = 0; j < newasize; j++) {
        value[j] = gwy_deserialize_string(buffer, size, position);
        if (!value[j]) {
            while (j) {
                j--;
                g_free(value[j]);
            }
            g_free(value);
            return NULL;
        }
    }
    *asize = newasize;

    gwy_debug("|value| = %" G_GSIZE_FORMAT, newasize);
    return value;
}

/**
 * gwy_deserialize_object_array:
 * @buffer: A memory location containing an array of serialized object at
 *          position @position.
 * @size: The size of @buffer.
 * @position: The position of the object array in @buffer, it's updated to
 *            after it.
 * @asize: Where the size of the array is to be returned on success.
 *
 * Deserializes an object array.
 *
 * Returns: A newly allocated array of objects.
 **/
static inline GObject**
gwy_deserialize_object_array(const guchar *buffer,
                             gsize size,
                             gsize *position,
                             gsize *asize)
{
    GObject **value;
    gsize j, newasize, minsize;

    gwy_debug("buf = %p, size = %" G_GSIZE_FORMAT ", pos = %" G_GSIZE_FORMAT,
              buffer, size, *position);

    if (*position + sizeof(gint32) > size)
        return NULL;
    minsize = 2*sizeof(guchar) + sizeof(gint32);  /* Size of empty object */
    if (!(newasize = gwy_deserialize_int32(buffer, size, position)))
        return NULL;
    if (newasize > (size - *position)/minsize)
        return NULL;
    value = g_new(GObject*, newasize);
    for (j = 0; j < newasize; j++) {
        value[j] = gwy_serializable_deserialize(buffer, size, position);
        if (!value[j]) {
            while (j) {
                j--;
                g_object_unref(value[j]);
            }
            g_free(value);
            return NULL;
        }
    }
    *asize = newasize;

    gwy_debug("|value| = %" G_GSIZE_FORMAT, newasize);
    return value;
}

/**
 * gwy_deserialize_spec_value:
 * @buffer: A memory location containing a serialized item value.
 * @size: The size of @buffer.
 * @position: Current position in buffer, will be updated to point after item.
 * @sp: A single serialize spec with @ctype and @name already deserialized,
 *      its @value and @array_size will be filled.
 *
 * Unpacks one serialized item value.
 *
 * Returns: %TRUE on success, %FALSE on failure.
 **/
static gboolean
gwy_deserialize_spec_value(const guchar *buffer,
                           gsize size,
                           gsize *position,
                           GwySerializeSpec *sp)
{
    gpointer p;
    guint32 *a;

    p = sp->value;
    a = sp->array_size;

    switch (sp->ctype) {
        case 'o': {
            GObject *val, *old = *(GObject**)p;

            val = gwy_serializable_deserialize(buffer, size, position);
            if (val) {
                *(GObject**)p = val;
                GWY_OBJECT_UNREF(old);
            }
            else
                return FALSE;
        }
        break;

        case 'b':
        *(gboolean*)p = gwy_deserialize_boolean(buffer, size, position);
        break;

        case 'c':
        *(guchar*)p = gwy_deserialize_char(buffer, size, position);
        break;

        case 'i':
        *(gint32*)p = gwy_deserialize_int32(buffer, size, position);
        break;

        case 'q':
        *(gint64*)p = gwy_deserialize_int64(buffer, size, position);
        break;

        case 'd':
        *(gdouble*)p = gwy_deserialize_double(buffer, size, position);
        break;

        case 's': {
            guchar *val, *old = *(guchar**)p;

            val = gwy_deserialize_string(buffer, size, position);
            if (val) {
                *(guchar**)p = val;
                g_free(old);
            }
            else if (!*(guchar**)p)
                return FALSE;
        }
        break;

        case 'C': {
            guchar *val, *old = *(guchar**)p;
            gsize len;

            val = gwy_deserialize_char_array(buffer, size, position, &len);
            if (val) {
                *a = len;
                *(guchar**)p = val;
                g_free(old);
            }
            else if (!*(guchar**)p)
                return FALSE;
        }
        break;

        case 'I': {
            guint32 *val, *old = *(guint32**)p;
            gsize len;

            val = gwy_deserialize_int32_array(buffer, size, position, &len);
            if (val) {
                *a = len;
                *(guint32**)p = val;
                g_free(old);
            }
            else if (!*(guint32**)p)
                return FALSE;
        }
        break;

        case 'Q': {
            guint64 *val, *old = *(guint64**)p;
            gsize len;

            val = gwy_deserialize_int64_array(buffer, size, position, &len);
            if (val) {
                *a = len;
                *(guint64**)p = val;
                g_free(old);
            }
            else if (!*(guint64**)p)
                return FALSE;
        }
        break;

        case 'D': {
            gdouble *val, *old = *(gdouble**)p;
            gsize len;

            val = gwy_deserialize_double_array(buffer, size, position, &len);
            if (val) {
                *a = len;
                *(gdouble**)p = val;
                g_free(old);
            }
            else if (!*(double**)p)
                return FALSE;
        }
        break;

        case 'S': {
            guchar **val, **old = *(guchar***)p;
            gsize len, j, oldlen = *a;

            val = gwy_deserialize_string_array(buffer, size, position, &len);
            if (val) {
                *a = len;
                *(guchar***)p = val;
                if (old) {
                    for (j = 0; j < oldlen; j++)
                        g_free(old[j]);
                    g_free(old);
                }
            }
            else if (!*(guchar***)p)
                return FALSE;
        }
        break;

        case 'O': {
            GObject **val, **old = *(GObject***)p;
            gsize len, j, oldlen = *a;

            val = gwy_deserialize_object_array(buffer, size, position, &len);
            if (val) {
                *a = len;
                *(GObject***)p = val;
                if (old) {
                    for (j = 0; j < oldlen; j++)
                        GWY_OBJECT_UNREF(old[j]);
                    g_free(old);
                }
            }
            else if (!*(GObject***)p)
                return FALSE;
        }
        break;

        default:
        g_critical("Type <%c> of <%s> is unknown (though known to caller?!)",
                   sp->ctype, sp->name);
        return FALSE;
        break;
    }

    return TRUE;
}

/**
 * gwy_serialize_check_string:
 * @buffer: A memory location containing a NUL-terminated string at position
 *          @position.
 * @size: The size of @buffer.
 * @position: The position of the string in @buffer.
 * @compare_to: String to compare @buffer to, or %NULL.
 *
 * Check whether @size bytes of memory in @buffer can be interpreted as a
 * NUL-terminated string, and eventually whether it's equal to @compare_to.
 *
 * When @compare_to is %NULL, the comparsion is not performed.
 *
 * Returns: The length of the NUL-terminated string including the NUL
 * character; zero otherwise.
 **/
gsize
gwy_serialize_check_string(const guchar *buffer,
                           gsize size,
                           gsize position,
                           const guchar *compare_to)
{
    const guchar *p;

    gwy_debug("<%s> buf = %p, size = %" G_GSIZE_FORMAT ", pos = %"
              G_GSIZE_FORMAT,
              compare_to ? compare_to : (const guchar*)"(null)",
              buffer, size, position);
    g_assert(buffer);
    g_assert(size > 0);
    g_return_val_if_fail(position < size, 0);
    p = (guchar*)memchr(buffer + position, 0, size - position);
    if (!p || (compare_to && !gwy_strequal(buffer + position, compare_to)))
        return 0;

    return (p - buffer) + 1 - position;
}

/************************** Documentation ****************************/

/**
 * SECTION:gwyserializable
 * @title: GwySerializable
 * @short_description: Abstract interface for serializable objects
 *
 * GwySerializable is an abstract interface for data-like object that can be
 * serialized and deserialized.  You can serialize any object implementing this
 * interface with gwy_serializable_serialize() and the restore (deserialize) it
 * with gwy_serializable_deserialize(). It is also posible it duplicate any
 * such object with gwy_serializable_duplicate() and transform one object to
 * copy of another with gwy_serializable_clone().
 *
 * Note all #GwySerializable methods work with object `value', whatever it means
 * for a particular type.  Beside that, objects also have their identity which
 * is unique and can't be subject of cloning.  It consists of properties like
 * memory address or references held by object users.  Two important properties
 * related to identity (and thus NOT retained) are: signals connected to
 * a particular object and user data set with g_object_set_data() or
 * g_object_set_qdata().
 *
 * You can implement serialization and deserialization in your classes with
 * gwy_serialize_pack_object_struct() and gwy_serialize_unpack_object_struct()
 * or with gwy_serialize_object_items() and gwy_deserialize_object_hash().
 * The former two are useful for struct-like objects (most objects are of this
 * kind), the latter two for hash-like objects, i.e., objects that can contain
 * components of arbitrary name and type.  Serialized size calculations can be
 * in most cases performed by gwy_serialize_get_struct_size() and
 * gwy_serialize_get_items_size() helper functions.
 **/

/**
 * GwySerializeFunc:
 * @serializable: An object to serialize.
 * @buffer: A buffer to append the representation to, may be %NULL indicating
 *          a new one should be allocated.
 *
 * The type of serialization method, see gwy_serializable_serialize() for
 * description.
 *
 * Returns: @buffer with serialized object appended.
 */

/**
 * GwyDeserializeFunc:
 * @buffer: A buffer containing a serialized object.
 * @size: The size of @buffer.
 * @position: The current position in @buffer.
 *
 * The type of deserialization method, see gwy_serializable_deserialize() for
 * description.
 *
 * Returns: A newly created (restored) object.
 */

/**
 * GwySerializeSpec:
 * @ctype: Component type, see description body for possible values.
 * @name: Component name as a NUL-terminated string.
 * @value: Pointer to component (always add one level of indirection; for
 *         an object, a #GObject** pointer should be stored).  If it is
 *         %NULL, the component is ignored.  For serialization it means it
 *         is not serialized, for deserialization it means its existence
 *         is acknowledged (no unknown component warning) but it's skipped
 *         instead of unpacking.
 * @array_size: Pointer to array size if component is an array, %NULL
 *              otherwise.
 *
 * A structure containing information for one object/struct component
 * serialization or deserialization.
 *
 * This component information is used in gwy_serialize_pack_object_struct()
 * and gwy_serialize_unpack_object_struct() suitable for (de)serialization
 * of struct-like objects.
 *
 * Following atomic component types (@ctype's) exist:
 * <literal>'b'</literal> for a boolean,
 * <literal>'c'</literal> for a character,
 * <literal>'i'</literal> for a 32bit integer,
 * <literal>'q'</literal> for a 64bit integer,
 * <literal>'d'</literal> for a gdouble,
 * <literal>'s'</literal> for a NUL-terminated string,
 * <literal>'o'</literal> for a serializable object.
 *
 * And array component types:
 * <literal>'C'</literal> for a character array,
 * <literal>'I'</literal> for a 32bit integer array,
 * <literal>'Q'</literal> for a 64bit integer array,
 * <literal>'D'</literal> for a gdouble array,
 * <literal>'S'</literal> for an array of NUL-terminated strings,
 * <literal>'O'</literal> for an array of objects.
 **/

/**
 * GwySerializeItem:
 * @ctype: Component type, see #GwySerializeSpec for details.
 * @name: Component name as a NUL-terminated string.
 * @value: Component value.
 * @array_size: Array size if component is an array, unused otherwise.
 *
 * A structure containing information for one object/struct component
 * serialization or deserialization.
 *
 * This component information is used in gwy_serialize_object_items() and
 * gwy_deserialize_object_hash() suitable for (de)serialization of hash-like
 * objects.
 **/

/**
 * GwySerializableIface:
 * @serialize: Serialization method (obligatory), see #GwySerializeFunc for
 *             description.
 * @deserialize: Restore method (obligatory), see #GwyDeserializeFunc for
 *               description.
 * @clone: Clone method (obligatory).  Copies complete object `value' to an
 *         existing object of the same type.  This method is called from
 *         copy's class if source and copy classes differ.
 * @duplicate: Duplication method (optional).  Creates a duplicate of an
 *             object.  When it is absent, duplication is performed by
 *             a rather inefficient serialize-and-deserialize fallback.
 * @get_size: Serialized size calculation method (optional).
 *            Calculates expected serialized object size (including object
 *            name and size header).
 *            Its purpose is to avoid frequent memory reallocations during
 *            serialization of large objects.
 *            The returned value may be inexact, a reasonable upper bound is
 *            sufficient.  When it is absent, serialization is less efficient.
 *
 * The methods a serializable objects has to implement.
 **/

/**
 * GWY_IMPLEMENT_SERIALIZABLE:
 * @iface_init: The interface init function.
 *
 * Specialization of G_IMPLEMENT_INTERFACE() for #GwySerializableIface.
 *
 * To be used in last G_DEFINE_TYPE_EXTENDED() argument:
 * <informalexample><programlisting>
 * G_DEFINE_TYPE_EXTENDED
 *    (GwyFoo, gwy_foo, G_TYPE_OBJECT, 0,
 *     GWY_IMPLEMENT_SERIALIZABLE(gwy_foo_serializable_init))
 * </programlisting></informalexample>
 **/

/**
 * GwySerializeValue:
 * @v_boolean: Boolean.
 * @v_char: Character.
 * @v_int32: 32bit integer.
 * @v_int64: 64bit integer.
 * @v_double: Double-precision float.
 * @v_string: NUL-terminated string.
 * @v_object: Object (serializable).
 * @v_boolean_array: Array of booleans.  Not to be used.
 * @v_char_array: Array of characters.
 * @v_int32_array: Array of 32bit integers.
 * @v_int64_array: Array of 64bit integers.
 * @v_double_array: Array of double-precision floats.
 * @v_string_array: Array of NUL-terminated strings.
 * @v_object_array: Array of objects (serializable).
 *
 * Helper serialization type that can hold any atomic value or pointer to
 * non-atomic value.
 **/

/* vim: set cin et ts=4 sw=4 cino=>1s,e0,n0,f0,{0,}0,^0,\:1s,=0,g1s,h0,t0,+1s,c3,(0,u0 : */