summaryrefslogtreecommitdiff
path: root/lib/ovsdb-data.c
blob: 840e18fa18241f303a5380fc69c5a31711c26c72 (plain)
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
/* Copyright (c) 2009, 2010, 2011, 2012, 2014, 2016 Nicira, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at:
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <config.h>

#include "ovsdb-data.h"

#include <ctype.h>
#include <float.h>
#include <inttypes.h>
#include <limits.h>

#include "openvswitch/dynamic-string.h"
#include "hash.h"
#include "ovs-thread.h"
#include "ovsdb-error.h"
#include "ovsdb-parser.h"
#include "openvswitch/json.h"
#include "openvswitch/shash.h"
#include "smap.h"
#include "sort.h"
#include "unicode.h"
#include "util.h"

static struct json *
wrap_json(const char *name, struct json *wrapped)
{
    return json_array_create_2(json_string_create(name), wrapped);
}

/* Initializes 'atom' with the default value of the given 'type'.
 *
 * The default value for an atom is as defined in RFC 7047:
 *
 *      - "integer" or "real": 0
 *
 *      - "boolean": false
 *
 *      - "string": "" (the empty string)
 *
 *      - "uuid": 00000000-0000-0000-0000-000000000000
 *
 * The caller must eventually arrange for 'atom' to be destroyed (with
 * ovsdb_atom_destroy()). */
void
ovsdb_atom_init_default(union ovsdb_atom *atom, enum ovsdb_atomic_type type)
{
    switch (type) {
    case OVSDB_TYPE_VOID:
        OVS_NOT_REACHED();

    case OVSDB_TYPE_INTEGER:
        atom->integer = 0;
        break;

    case OVSDB_TYPE_REAL:
        atom->real = 0.0;
        break;

    case OVSDB_TYPE_BOOLEAN:
        atom->boolean = false;
        break;

    case OVSDB_TYPE_STRING:
        atom->string = xmemdup("", 1);
        break;

    case OVSDB_TYPE_UUID:
        uuid_zero(&atom->uuid);
        break;

    case OVSDB_N_TYPES:
    default:
        OVS_NOT_REACHED();
    }
}

/* Returns a read-only atom of the given 'type' that has the default value for
 * 'type'.  The caller must not modify or free the returned atom.
 *
 * See ovsdb_atom_init_default() for an explanation of the default value of an
 * atom. */
const union ovsdb_atom *
ovsdb_atom_default(enum ovsdb_atomic_type type)
{
    static union ovsdb_atom default_atoms[OVSDB_N_TYPES];
    static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;

    if (ovsthread_once_start(&once)) {
        int i;

        for (i = 0; i < OVSDB_N_TYPES; i++) {
            if (i != OVSDB_TYPE_VOID) {
                ovsdb_atom_init_default(&default_atoms[i], i);
            }
        }
        ovsthread_once_done(&once);
    }

    ovs_assert(ovsdb_atomic_type_is_valid(type));
    return &default_atoms[type];
}

/* Returns true if 'atom', which must have the given 'type', has the default
 * value for that type.
 *
 * See ovsdb_atom_init_default() for an explanation of the default value of an
 * atom. */
bool
ovsdb_atom_is_default(const union ovsdb_atom *atom,
                      enum ovsdb_atomic_type type)
{
    switch (type) {
    case OVSDB_TYPE_VOID:
        OVS_NOT_REACHED();

    case OVSDB_TYPE_INTEGER:
        return atom->integer == 0;

    case OVSDB_TYPE_REAL:
        return atom->real == 0.0;

    case OVSDB_TYPE_BOOLEAN:
        return atom->boolean == false;

    case OVSDB_TYPE_STRING:
        return atom->string[0] == '\0';

    case OVSDB_TYPE_UUID:
        return uuid_is_zero(&atom->uuid);

    case OVSDB_N_TYPES:
    default:
        OVS_NOT_REACHED();
    }
}

/* Initializes 'new' as a copy of 'old', with the given 'type'.
 *
 * The caller must eventually arrange for 'new' to be destroyed (with
 * ovsdb_atom_destroy()). */
void
ovsdb_atom_clone(union ovsdb_atom *new, const union ovsdb_atom *old,
                 enum ovsdb_atomic_type type)
{
    switch (type) {
    case OVSDB_TYPE_VOID:
        OVS_NOT_REACHED();

    case OVSDB_TYPE_INTEGER:
        new->integer = old->integer;
        break;

    case OVSDB_TYPE_REAL:
        new->real = old->real;
        break;

    case OVSDB_TYPE_BOOLEAN:
        new->boolean = old->boolean;
        break;

    case OVSDB_TYPE_STRING:
        new->string = xstrdup(old->string);
        break;

    case OVSDB_TYPE_UUID:
        new->uuid = old->uuid;
        break;

    case OVSDB_N_TYPES:
    default:
        OVS_NOT_REACHED();
    }
}

/* Swaps the contents of 'a' and 'b', which need not have the same type. */
void
ovsdb_atom_swap(union ovsdb_atom *a, union ovsdb_atom *b)
{
    union ovsdb_atom tmp = *a;
    *a = *b;
    *b = tmp;
}

/* Returns a hash value for 'atom', which has the specified 'type', folding
 * 'basis' into the calculation. */
uint32_t
ovsdb_atom_hash(const union ovsdb_atom *atom, enum ovsdb_atomic_type type,
                uint32_t basis)
{
    switch (type) {
    case OVSDB_TYPE_VOID:
        OVS_NOT_REACHED();

    case OVSDB_TYPE_INTEGER:
        return hash_int(atom->integer, basis);

    case OVSDB_TYPE_REAL:
        return hash_double(atom->real, basis);

    case OVSDB_TYPE_BOOLEAN:
        return hash_boolean(atom->boolean, basis);

    case OVSDB_TYPE_STRING:
        return hash_string(atom->string, basis);

    case OVSDB_TYPE_UUID:
        return hash_int(uuid_hash(&atom->uuid), basis);

    case OVSDB_N_TYPES:
    default:
        OVS_NOT_REACHED();
    }
}

/* Compares 'a' and 'b', which both have type 'type', and returns a
 * strcmp()-like result. */
int
ovsdb_atom_compare_3way(const union ovsdb_atom *a,
                        const union ovsdb_atom *b,
                        enum ovsdb_atomic_type type)
{
    switch (type) {
    case OVSDB_TYPE_VOID:
        OVS_NOT_REACHED();

    case OVSDB_TYPE_INTEGER:
        return a->integer < b->integer ? -1 : a->integer > b->integer;

    case OVSDB_TYPE_REAL:
        return a->real < b->real ? -1 : a->real > b->real;

    case OVSDB_TYPE_BOOLEAN:
        return a->boolean - b->boolean;

    case OVSDB_TYPE_STRING:
        return strcmp(a->string, b->string);

    case OVSDB_TYPE_UUID:
        return uuid_compare_3way(&a->uuid, &b->uuid);

    case OVSDB_N_TYPES:
    default:
        OVS_NOT_REACHED();
    }
}

static struct ovsdb_error *
unwrap_json(const struct json *json, const char *name,
            enum json_type value_type, const struct json **value)
{
    if (json->type != JSON_ARRAY
        || json->u.array.n != 2
        || json->u.array.elems[0]->type != JSON_STRING
        || (name && strcmp(json->u.array.elems[0]->u.string, name))
        || json->u.array.elems[1]->type != value_type)
    {
        *value = NULL;
        return ovsdb_syntax_error(json, NULL, "expected [\"%s\", <%s>]", name,
                                  json_type_to_string(value_type));
    }
    *value = json->u.array.elems[1];
    return NULL;
}

static struct ovsdb_error *
parse_json_pair(const struct json *json,
                const struct json **elem0, const struct json **elem1)
{
    if (json->type != JSON_ARRAY || json->u.array.n != 2) {
        return ovsdb_syntax_error(json, NULL, "expected 2-element array");
    }
    *elem0 = json->u.array.elems[0];
    *elem1 = json->u.array.elems[1];
    return NULL;
}

static void
ovsdb_symbol_referenced(struct ovsdb_symbol *symbol,
                        const struct ovsdb_base_type *base)
{
    ovs_assert(base->type == OVSDB_TYPE_UUID);

    if (base->u.uuid.refTableName) {
        switch (base->u.uuid.refType) {
        case OVSDB_REF_STRONG:
            symbol->strong_ref = true;
            break;
        case OVSDB_REF_WEAK:
            symbol->weak_ref = true;
            break;
        }
    }
}

static union ovsdb_atom *
alloc_default_atoms(enum ovsdb_atomic_type type, size_t n)
{
    if (type != OVSDB_TYPE_VOID && n) {
        union ovsdb_atom *atoms;
        unsigned int i;

        atoms = xmalloc(n * sizeof *atoms);
        for (i = 0; i < n; i++) {
            ovsdb_atom_init_default(&atoms[i], type);
        }
        return atoms;
    } else {
        /* Avoid wasting memory in the n == 0 case, because xmalloc(0) is
         * treated as xmalloc(1). */
        return NULL;
    }
}

static struct ovsdb_error * OVS_WARN_UNUSED_RESULT
ovsdb_atom_parse_uuid(struct uuid *uuid, const struct json *json,
                      struct ovsdb_symbol_table *symtab,
                      const struct ovsdb_base_type *base)
{
    struct ovsdb_error *error0;
    const struct json *value;

    error0 = unwrap_json(json, "uuid", JSON_STRING, &value);
    if (!error0) {
        const char *uuid_string = json_string(value);
        if (!uuid_from_string(uuid, uuid_string)) {
            return ovsdb_syntax_error(json, NULL, "\"%s\" is not a valid UUID",
                                      uuid_string);
        }
    } else if (symtab) {
        struct ovsdb_error *error1;

        error1 = unwrap_json(json, "named-uuid", JSON_STRING, &value);
        if (!error1) {
            struct ovsdb_symbol *symbol;

            ovsdb_error_destroy(error0);
            if (!ovsdb_parser_is_id(json_string(value))) {
                return ovsdb_syntax_error(json, NULL, "named-uuid string is "
                                          "not a valid <id>");
            }

            symbol = ovsdb_symbol_table_insert(symtab, json_string(value));
            *uuid = symbol->uuid;
            ovsdb_symbol_referenced(symbol, base);
            return NULL;
        }
        ovsdb_error_destroy(error1);
    }

    return error0;
}

static struct ovsdb_error * OVS_WARN_UNUSED_RESULT
ovsdb_atom_from_json__(union ovsdb_atom *atom,
                       const struct ovsdb_base_type *base,
                       const struct json *json,
                       struct ovsdb_symbol_table *symtab)
{
    enum ovsdb_atomic_type type = base->type;

    switch (type) {
    case OVSDB_TYPE_VOID:
        OVS_NOT_REACHED();

    case OVSDB_TYPE_INTEGER:
        if (json->type == JSON_INTEGER) {
            atom->integer = json->u.integer;
            return NULL;
        }
        break;

    case OVSDB_TYPE_REAL:
        if (json->type == JSON_INTEGER) {
            atom->real = json->u.integer;
            return NULL;
        } else if (json->type == JSON_REAL) {
            atom->real = json->u.real;
            return NULL;
        }
        break;

    case OVSDB_TYPE_BOOLEAN:
        if (json->type == JSON_TRUE) {
            atom->boolean = true;
            return NULL;
        } else if (json->type == JSON_FALSE) {
            atom->boolean = false;
            return NULL;
        }
        break;

    case OVSDB_TYPE_STRING:
        if (json->type == JSON_STRING) {
            atom->string = xstrdup(json->u.string);
            return NULL;
        }
        break;

    case OVSDB_TYPE_UUID:
        return ovsdb_atom_parse_uuid(&atom->uuid, json, symtab, base);

    case OVSDB_N_TYPES:
    default:
        OVS_NOT_REACHED();
    }

    return ovsdb_syntax_error(json, NULL, "expected %s",
                              ovsdb_atomic_type_to_string(type));
}

/* Parses 'json' as an atom of the type described by 'base'.  If successful,
 * returns NULL and initializes 'atom' with the parsed atom.  On failure,
 * returns an error and the contents of 'atom' are indeterminate.  The caller
 * is responsible for freeing the error or the atom that is returned.
 *
 * Violations of constraints expressed by 'base' are treated as errors.
 *
 * If 'symtab' is nonnull, then named UUIDs in 'symtab' are accepted.  Refer to
 * RFC 7047 for information about this, and for the syntax that this function
 * accepts.  If 'base' is a reference and a symbol is parsed, then the symbol's
 * 'strong_ref' or 'weak_ref' member is set to true, as appropriate. */
struct ovsdb_error *
ovsdb_atom_from_json(union ovsdb_atom *atom,
                     const struct ovsdb_base_type *base,
                     const struct json *json,
                     struct ovsdb_symbol_table *symtab)
{
    struct ovsdb_error *error;

    error = ovsdb_atom_from_json__(atom, base, json, symtab);
    if (error) {
        return error;
    }

    error = ovsdb_atom_check_constraints(atom, base);
    if (error) {
        ovsdb_atom_destroy(atom, base->type);
    }
    return error;
}

/* Converts 'atom', of the specified 'type', to JSON format, and returns the
 * JSON.  The caller is responsible for freeing the returned JSON.
 *
 * Refer to RFC 7047 for the format of the JSON that this function produces. */
struct json *
ovsdb_atom_to_json(const union ovsdb_atom *atom, enum ovsdb_atomic_type type)
{
    switch (type) {
    case OVSDB_TYPE_VOID:
        OVS_NOT_REACHED();

    case OVSDB_TYPE_INTEGER:
        return json_integer_create(atom->integer);

    case OVSDB_TYPE_REAL:
        return json_real_create(atom->real);

    case OVSDB_TYPE_BOOLEAN:
        return json_boolean_create(atom->boolean);

    case OVSDB_TYPE_STRING:
        return json_string_create(atom->string);

    case OVSDB_TYPE_UUID:
        return wrap_json("uuid", json_string_create_nocopy(
                             xasprintf(UUID_FMT, UUID_ARGS(&atom->uuid))));

    case OVSDB_N_TYPES:
    default:
        OVS_NOT_REACHED();
    }
}

static char *
ovsdb_atom_from_string__(union ovsdb_atom *atom,
                         union ovsdb_atom **range_end_atom,
                         const struct ovsdb_base_type *base, const char *s,
                         struct ovsdb_symbol_table *symtab)
{
    enum ovsdb_atomic_type type = base->type;

    switch (type) {
    case OVSDB_TYPE_VOID:
        OVS_NOT_REACHED();

    case OVSDB_TYPE_INTEGER: {
        long long int integer, end;
        if (range_end_atom
            && str_to_llong_range(s, 10, &integer, &end)) {
            if (end < integer) {
                return xasprintf("\"%s\" is not a valid range. "
                    "Range end cannot be before start.", s);
            }
            *range_end_atom = alloc_default_atoms(type, 1);
            if (!(*range_end_atom)) {
                return xasprintf("\"%s\" is not a valid range", s);
            }
            (*range_end_atom)->integer = end;
        } else if (!str_to_llong(s, 10, &integer)) {
            return xasprintf("\"%s\" is not a valid integer or range", s);
        }
        atom->integer = integer;
    }
        break;

    case OVSDB_TYPE_REAL:
        if (!str_to_double(s, &atom->real)) {
            return xasprintf("\"%s\" is not a valid real number", s);
        }
        /* Our JSON input routines map negative zero to zero, so do that here
         * too for consistency. */
        if (atom->real == 0.0) {
            atom->real = 0.0;
        }
        break;

    case OVSDB_TYPE_BOOLEAN:
        if (!strcmp(s, "true") || !strcmp(s, "yes") || !strcmp(s, "on")
            || !strcmp(s, "1")) {
            atom->boolean = true;
        } else if (!strcmp(s, "false") || !strcmp(s, "no") || !strcmp(s, "off")
                   || !strcmp(s, "0")) {
            atom->boolean = false;
        } else {
            return xasprintf("\"%s\" is not a valid boolean "
                             "(use \"true\" or \"false\")", s);
        }
        break;

    case OVSDB_TYPE_STRING:
        if (*s == '\0') {
            return xstrdup("An empty string is not valid as input; "
                           "use \"\" to represent the empty string");
        } else if (*s == '"') {
            size_t s_len = strlen(s);

            if (s_len < 2 || s[s_len - 1] != '"') {
                return xasprintf("%s: missing quote at end of "
                                 "quoted string", s);
            } else if (!json_string_unescape(s + 1, s_len - 2,
                                             &atom->string)) {
                char *error = xasprintf("%s: %s", s, atom->string);
                free(atom->string);
                return error;
            }
        } else {
            atom->string = xstrdup(s);
        }
        break;

    case OVSDB_TYPE_UUID:
        if (*s == '@') {
            struct ovsdb_symbol *symbol = ovsdb_symbol_table_insert(symtab, s);
            atom->uuid = symbol->uuid;
            ovsdb_symbol_referenced(symbol, base);
        } else if (!uuid_from_string(&atom->uuid, s)) {
            return xasprintf("\"%s\" is not a valid UUID", s);
        }
        break;

    case OVSDB_N_TYPES:
    default:
        OVS_NOT_REACHED();
    }

    return NULL;
}

/* Initializes 'atom' and optionally 'range_end_atom' to a value of type 'base'
 * parsed from 's', which takes one of the following forms:
 *
 *      - OVSDB_TYPE_INTEGER: A decimal integer optionally preceded by a sign
 *        or two decimal integers optionally preceded by a sign and separated
 *        by a hyphen, representing inclusive range of integers
 *        ['atom', 'range_end_atom'].
 *
 *      - OVSDB_TYPE_REAL: A floating-point number in the format accepted by
 *        strtod().
 *
 *      - OVSDB_TYPE_BOOLEAN: "true", "yes", "on", "1" for true, or "false",
 *        "no", "off", or "0" for false.
 *
 *      - OVSDB_TYPE_STRING: A JSON string if it begins with a quote, otherwise
 *        an arbitrary string.
 *
 *      - OVSDB_TYPE_UUID: A UUID in RFC 4122 format.  If 'symtab' is nonnull,
 *        then an identifier beginning with '@' is also acceptable.  If the
 *        named identifier is already in 'symtab', then the associated UUID is
 *        used; otherwise, a new, random UUID is used and added to the symbol
 *        table.  If 'base' is a reference and a symbol is parsed, then the
 *        symbol's 'strong_ref' or 'weak_ref' member is set to true, as
 *        appropriate.
 *
 * Returns a null pointer if successful, otherwise an error message describing
 * the problem.  On failure, the contents of 'atom' are indeterminate.  The
 * caller is responsible for freeing the atom or the error.
 *
 * Does not attempt to parse range if 'range_end_atom' is a null pointer.
 * Dynamically allocates ovdsb_atom and stores its address in '*range_end_atom'
 * if successfully parses range. Caller is responsible for deallocating
 * the memory by calling 'ovsdb_atom_destroy' and then 'free' on the address.
 * Does not allocate memory and sets '*range_end_atom' to a null pointer
 * if does not parse a range or fails for any reason.
 */
char *
ovsdb_atom_from_string(union ovsdb_atom *atom,
                       union ovsdb_atom **range_end_atom,
                       const struct ovsdb_base_type *base, const char *s,
                       struct ovsdb_symbol_table *symtab)
{
    struct ovsdb_error *error;
    char *msg;

    if (range_end_atom) {
        *range_end_atom = NULL;
    }

    msg = ovsdb_atom_from_string__(atom, range_end_atom, base, s, symtab);
    if (msg) {
        return msg;
    }

    error = ovsdb_atom_check_constraints(atom, base);

    if (!error && range_end_atom && *range_end_atom) {
        /* Check range constraints */
        int64_t start = atom->integer;
        int64_t end = (*range_end_atom)->integer;
        if (base->enum_) {
            for (int64_t i = start + 1; i <= end; i++) {
                union ovsdb_atom ai = { .integer = i };
                error = ovsdb_atom_check_constraints(&ai, base);
                if (error) {
                    break;
                }
            }
        } else {
            error = ovsdb_atom_check_constraints(*range_end_atom, base);
        }

        if (!error) {
            error = ovsdb_atom_range_check_size(start, end);
        }
    }

    if (error) {
        ovsdb_atom_destroy(atom, base->type);
        if (range_end_atom && *range_end_atom) {
            ovsdb_atom_destroy(*range_end_atom, base->type);
            free(*range_end_atom);
            *range_end_atom = NULL;
        }
        msg = ovsdb_error_to_string(error);
        ovsdb_error_destroy(error);
    }
    return msg;
}

static bool
string_needs_quotes(const char *s)
{
    const char *p = s;
    unsigned char c;

    c = *p++;
    if (!isalpha(c) && c != '_') {
        return true;
    }

    while ((c = *p++) != '\0') {
        if (!isalpha(c) && c != '_' && c != '-' && c != '.') {
            return true;
        }
    }

    if (!strcmp(s, "true") || !strcmp(s, "false")) {
        return true;
    }

    return false;
}

/* Appends 'atom' (which has the given 'type') to 'out', in a format acceptable
 * to ovsdb_atom_from_string().  */
void
ovsdb_atom_to_string(const union ovsdb_atom *atom, enum ovsdb_atomic_type type,
                     struct ds *out)
{
    switch (type) {
    case OVSDB_TYPE_VOID:
        OVS_NOT_REACHED();

    case OVSDB_TYPE_INTEGER:
        ds_put_format(out, "%"PRId64, atom->integer);
        break;

    case OVSDB_TYPE_REAL:
        ds_put_format(out, "%.*g", DBL_DIG, atom->real);
        break;

    case OVSDB_TYPE_BOOLEAN:
        ds_put_cstr(out, atom->boolean ? "true" : "false");
        break;

    case OVSDB_TYPE_STRING:
        if (string_needs_quotes(atom->string)) {
            struct json json;

            json.type = JSON_STRING;
            json.u.string = atom->string;
            json_to_ds(&json, 0, out);
        } else {
            ds_put_cstr(out, atom->string);
        }
        break;

    case OVSDB_TYPE_UUID:
        ds_put_format(out, UUID_FMT, UUID_ARGS(&atom->uuid));
        break;

    case OVSDB_N_TYPES:
    default:
        OVS_NOT_REACHED();
    }
}

/* Appends 'atom' (which has the given 'type') to 'out', in a bare string
 * format that cannot be parsed uniformly back into a datum but is easier for
 * shell scripts, etc., to deal with. */
void
ovsdb_atom_to_bare(const union ovsdb_atom *atom, enum ovsdb_atomic_type type,
                   struct ds *out)
{
    if (type == OVSDB_TYPE_STRING) {
        ds_put_cstr(out, atom->string);
    } else {
        ovsdb_atom_to_string(atom, type, out);
    }
}

static struct ovsdb_error *
check_string_constraints(const char *s,
                         const struct ovsdb_string_constraints *c)
{
    size_t n_chars;
    char *msg;

    msg = utf8_validate(s, &n_chars);
    if (msg) {
        struct ovsdb_error *error;

        error = ovsdb_error("constraint violation",
                            "not a valid UTF-8 string: %s", msg);
        free(msg);
        return error;
    }

    if (n_chars < c->minLen) {
        return ovsdb_error(
            "constraint violation",
            "\"%s\" length %"PRIuSIZE" is less than minimum allowed "
            "length %u", s, n_chars, c->minLen);
    } else if (n_chars > c->maxLen) {
        return ovsdb_error(
            "constraint violation",
            "\"%s\" length %"PRIuSIZE" is greater than maximum allowed "
            "length %u", s, n_chars, c->maxLen);
    }

    return NULL;
}

/* Checks whether 'atom' meets the constraints (if any) defined in 'base'.
 * (base->type must specify 'atom''s type.)  Returns a null pointer if the
 * constraints are met, otherwise an error that explains the violation.
 *
 * Checking UUID constraints is deferred to transaction commit time, so this
 * function does nothing for UUID constraints. */
struct ovsdb_error *
ovsdb_atom_check_constraints(const union ovsdb_atom *atom,
                             const struct ovsdb_base_type *base)
{
    if (base->enum_
        && ovsdb_datum_find_key(base->enum_, atom, base->type) == UINT_MAX) {
        struct ovsdb_error *error;
        struct ds actual = DS_EMPTY_INITIALIZER;
        struct ds valid = DS_EMPTY_INITIALIZER;

        ovsdb_atom_to_string(atom, base->type, &actual);
        ovsdb_datum_to_string(base->enum_,
                              ovsdb_base_type_get_enum_type(base->type),
                              &valid);
        error = ovsdb_error("constraint violation",
                            "%s is not one of the allowed values (%s)",
                            ds_cstr(&actual), ds_cstr(&valid));
        ds_destroy(&actual);
        ds_destroy(&valid);

        return error;
    }

    switch (base->type) {
    case OVSDB_TYPE_VOID:
        OVS_NOT_REACHED();

    case OVSDB_TYPE_INTEGER:
        if (atom->integer >= base->u.integer.min
            && atom->integer <= base->u.integer.max) {
            return NULL;
        } else if (base->u.integer.min != INT64_MIN) {
            if (base->u.integer.max != INT64_MAX) {
                return ovsdb_error("constraint violation",
                                   "%"PRId64" is not in the valid range "
                                   "%"PRId64" to %"PRId64" (inclusive)",
                                   atom->integer,
                                   base->u.integer.min, base->u.integer.max);
            } else {
                return ovsdb_error("constraint violation",
                                   "%"PRId64" is less than minimum allowed "
                                   "value %"PRId64,
                                   atom->integer, base->u.integer.min);
            }
        } else {
            return ovsdb_error("constraint violation",
                               "%"PRId64" is greater than maximum allowed "
                               "value %"PRId64,
                               atom->integer, base->u.integer.max);
        }
        OVS_NOT_REACHED();

    case OVSDB_TYPE_REAL:
        if (atom->real >= base->u.real.min && atom->real <= base->u.real.max) {
            return NULL;
        } else if (base->u.real.min != -DBL_MAX) {
            if (base->u.real.max != DBL_MAX) {
                return ovsdb_error("constraint violation",
                                   "%.*g is not in the valid range "
                                   "%.*g to %.*g (inclusive)",
                                   DBL_DIG, atom->real,
                                   DBL_DIG, base->u.real.min,
                                   DBL_DIG, base->u.real.max);
            } else {
                return ovsdb_error("constraint violation",
                                   "%.*g is less than minimum allowed "
                                   "value %.*g",
                                   DBL_DIG, atom->real,
                                   DBL_DIG, base->u.real.min);
            }
        } else {
            return ovsdb_error("constraint violation",
                               "%.*g is greater than maximum allowed "
                               "value %.*g",
                               DBL_DIG, atom->real,
                               DBL_DIG, base->u.real.max);
        }
        OVS_NOT_REACHED();

    case OVSDB_TYPE_BOOLEAN:
        return NULL;

    case OVSDB_TYPE_STRING:
        return check_string_constraints(atom->string, &base->u.string);

    case OVSDB_TYPE_UUID:
        return NULL;

    case OVSDB_N_TYPES:
    default:
        OVS_NOT_REACHED();
    }
}

/* Initializes 'datum' as an empty datum.  (An empty datum can be treated as
 * any type.) */
void
ovsdb_datum_init_empty(struct ovsdb_datum *datum)
{
    datum->n = 0;
    datum->keys = NULL;
    datum->values = NULL;
}

/* Initializes 'datum' as a datum that has the default value for 'type'.
 *
 * The default value for a particular type is as defined in RFC 7047:
 *
 *    - If n_min is 0, then the default value is the empty set (or map).
 *
 *    - If n_min is 1, the default value is a single value or a single
 *      key-value pair, whose key and value are the defaults for their
 *      atomic types.  (See ovsdb_atom_init_default() for details.)
 *
 *    - n_min > 1 is invalid.  See ovsdb_type_is_valid().
 */
void
ovsdb_datum_init_default(struct ovsdb_datum *datum,
                         const struct ovsdb_type *type)
{
    datum->n = type->n_min;
    datum->keys = alloc_default_atoms(type->key.type, datum->n);
    datum->values = alloc_default_atoms(type->value.type, datum->n);
}

/* Returns a read-only datum of the given 'type' that has the default value for
 * 'type'.  The caller must not modify or free the returned datum.
 *
 * See ovsdb_datum_init_default() for an explanation of the default value of a
 * datum. */
const struct ovsdb_datum *
ovsdb_datum_default(const struct ovsdb_type *type)
{
    if (type->n_min == 0) {
        static const struct ovsdb_datum empty;
        return &empty;
    } else if (type->n_min == 1) {
        static struct ovsdb_datum default_data[OVSDB_N_TYPES][OVSDB_N_TYPES];
        struct ovsdb_datum *d;
        int kt = type->key.type;
        int vt = type->value.type;

        ovs_assert(ovsdb_type_is_valid(type));

        d = &default_data[kt][vt];
        if (!d->n) {
            d->n = 1;
            d->keys = CONST_CAST(union ovsdb_atom *, ovsdb_atom_default(kt));
            if (vt != OVSDB_TYPE_VOID) {
                d->values = CONST_CAST(union ovsdb_atom *,
                                       ovsdb_atom_default(vt));
            }
        }
        return d;
    } else {
        OVS_NOT_REACHED();
    }
}

/* Returns true if 'datum', which must have the given 'type', has the default
 * value for that type.
 *
 * See ovsdb_datum_init_default() for an explanation of the default value of a
 * datum. */
bool
ovsdb_datum_is_default(const struct ovsdb_datum *datum,
                       const struct ovsdb_type *type)
{
    size_t i;

    if (datum->n != type->n_min) {
        return false;
    }
    for (i = 0; i < datum->n; i++) {
        if (!ovsdb_atom_is_default(&datum->keys[i], type->key.type)) {
            return false;
        }
        if (type->value.type != OVSDB_TYPE_VOID
            && !ovsdb_atom_is_default(&datum->values[i], type->value.type)) {
            return false;
        }
    }

    return true;
}

static union ovsdb_atom *
clone_atoms(const union ovsdb_atom *old, enum ovsdb_atomic_type type, size_t n)
{
    if (type != OVSDB_TYPE_VOID && n) {
        union ovsdb_atom *new;
        unsigned int i;

        new = xmalloc(n * sizeof *new);
        for (i = 0; i < n; i++) {
            ovsdb_atom_clone(&new[i], &old[i], type);
        }
        return new;
    } else {
        /* Avoid wasting memory in the n == 0 case, because xmalloc(0) is
         * treated as xmalloc(1). */
        return NULL;
    }
}

/* Initializes 'new' as a copy of 'old', with the given 'type'.
 *
 * The caller must eventually arrange for 'new' to be destroyed (with
 * ovsdb_datum_destroy()). */
void
ovsdb_datum_clone(struct ovsdb_datum *new, const struct ovsdb_datum *old,
                  const struct ovsdb_type *type)
{
    unsigned int n = old->n;
    new->n = n;
    new->keys = clone_atoms(old->keys, type->key.type, n);
    new->values = clone_atoms(old->values, type->value.type, n);
}

static void
free_data(enum ovsdb_atomic_type type,
          union ovsdb_atom *atoms, size_t n_atoms)
{
    if (ovsdb_atom_needs_destruction(type)) {
        unsigned int i;
        for (i = 0; i < n_atoms; i++) {
            ovsdb_atom_destroy(&atoms[i], type);
        }
    }
    free(atoms);
}

/* Frees the data owned by 'datum', which must have the given 'type'.
 *
 * This does not actually call free(datum).  If necessary, the caller must be
 * responsible for that. */
void
ovsdb_datum_destroy(struct ovsdb_datum *datum, const struct ovsdb_type *type)
{
    free_data(type->key.type, datum->keys, datum->n);
    free_data(type->value.type, datum->values, datum->n);
}

/* Swaps the contents of 'a' and 'b', which need not have the same type. */
void
ovsdb_datum_swap(struct ovsdb_datum *a, struct ovsdb_datum *b)
{
    struct ovsdb_datum tmp = *a;
    *a = *b;
    *b = tmp;
}

struct ovsdb_datum_sort_cbdata {
    enum ovsdb_atomic_type key_type;
    enum ovsdb_atomic_type value_type;
    struct ovsdb_datum *datum;
};

static int
ovsdb_datum_sort_compare_cb(size_t a, size_t b, void *cbdata_)
{
    struct ovsdb_datum_sort_cbdata *cbdata = cbdata_;
    int retval;

    retval = ovsdb_atom_compare_3way(&cbdata->datum->keys[a],
                                     &cbdata->datum->keys[b],
                                     cbdata->key_type);
    if (retval || cbdata->value_type == OVSDB_TYPE_VOID) {
        return retval;
    }

    return ovsdb_atom_compare_3way(&cbdata->datum->values[a],
                                   &cbdata->datum->values[b],
                                   cbdata->value_type);
}

static void
ovsdb_datum_sort_swap_cb(size_t a, size_t b, void *cbdata_)
{
    struct ovsdb_datum_sort_cbdata *cbdata = cbdata_;

    ovsdb_atom_swap(&cbdata->datum->keys[a], &cbdata->datum->keys[b]);
    if (cbdata->datum->values) {
        ovsdb_atom_swap(&cbdata->datum->values[a], &cbdata->datum->values[b]);
    }
}

static void
ovsdb_datum_sort__(struct ovsdb_datum *datum, enum ovsdb_atomic_type key_type,
                   enum ovsdb_atomic_type value_type)
{
    struct ovsdb_datum_sort_cbdata cbdata;

    cbdata.key_type = key_type;
    cbdata.value_type = value_type;
    cbdata.datum = datum;
    sort(datum->n, ovsdb_datum_sort_compare_cb, ovsdb_datum_sort_swap_cb,
         &cbdata);
}

/* The keys in an ovsdb_datum must be unique and in sorted order.  Most
 * functions that modify an ovsdb_datum maintain these invariants.  For those
 * that don't, this function checks and restores these invariants for 'datum',
 * whose keys are of type 'key_type'.
 *
 * This function returns NULL if successful, otherwise an error message.  The
 * caller must free the returned error when it is no longer needed.  On error,
 * 'datum' is sorted but not unique. */
struct ovsdb_error *
ovsdb_datum_sort(struct ovsdb_datum *datum, enum ovsdb_atomic_type key_type)
{
    size_t i;

    if (datum->n < 2) {
        return NULL;
    }

    ovsdb_datum_sort__(datum, key_type, OVSDB_TYPE_VOID);

    for (i = 0; i < datum->n - 1; i++) {
        if (ovsdb_atom_equals(&datum->keys[i], &datum->keys[i + 1],
                              key_type)) {
            if (datum->values) {
                return ovsdb_error(NULL, "map contains duplicate key");
            } else {
                return ovsdb_error(NULL, "set contains duplicate");
            }
        }
    }
    return NULL;
}

/* This function is the same as ovsdb_datum_sort(), except that the caller
 * knows that 'datum' is unique.  The operation therefore "cannot fail", so
 * this function assert-fails if it actually does. */
void
ovsdb_datum_sort_assert(struct ovsdb_datum *datum,
                        enum ovsdb_atomic_type key_type)
{
    struct ovsdb_error *error = ovsdb_datum_sort(datum, key_type);
    if (error) {
        OVS_NOT_REACHED();
    }
}

/* This is similar to ovsdb_datum_sort(), except that it drops duplicate keys
 * instead of reporting an error.  In a map type, the smallest value among a
 * group of duplicate pairs is retained and the others are dropped.
 *
 * Returns the number of keys (or pairs) that were dropped. */
size_t
ovsdb_datum_sort_unique(struct ovsdb_datum *datum,
                        enum ovsdb_atomic_type key_type,
                        enum ovsdb_atomic_type value_type)
{
    size_t src, dst;

    if (datum->n < 2) {
        return 0;
    }

    ovsdb_datum_sort__(datum, key_type, value_type);

    dst = 1;
    for (src = 1; src < datum->n; src++) {
        if (ovsdb_atom_equals(&datum->keys[src], &datum->keys[dst - 1],
                              key_type)) {
            ovsdb_atom_destroy(&datum->keys[src], key_type);
            if (value_type != OVSDB_TYPE_VOID) {
                ovsdb_atom_destroy(&datum->values[src], value_type);
            }
        } else {
            if (src != dst) {
                datum->keys[dst] = datum->keys[src];
                if (value_type != OVSDB_TYPE_VOID) {
                    datum->values[dst] = datum->values[src];
                }
            }
            dst++;
        }
    }
    datum->n = dst;
    return datum->n - src;
}

/* Checks that each of the atoms in 'datum' conforms to the constraints
 * specified by its 'type'.  Returns an error if a constraint is violated,
 * otherwise a null pointer.
 *
 * This function is not commonly useful because the most ordinary way to obtain
 * a datum is ultimately via ovsdb_atom_from_string() or
 * ovsdb_atom_from_json(), which check constraints themselves. */
struct ovsdb_error *
ovsdb_datum_check_constraints(const struct ovsdb_datum *datum,
                              const struct ovsdb_type *type)
{
    struct ovsdb_error *error;
    unsigned int i;

    for (i = 0; i < datum->n; i++) {
        error = ovsdb_atom_check_constraints(&datum->keys[i], &type->key);
        if (error) {
            return error;
        }
    }

    if (type->value.type != OVSDB_TYPE_VOID) {
        for (i = 0; i < datum->n; i++) {
            error = ovsdb_atom_check_constraints(&datum->values[i],
                                                 &type->value);
            if (error) {
                return error;
            }
        }
    }

    return NULL;
}

static struct ovsdb_error *
ovsdb_datum_from_json__(struct ovsdb_datum *datum,
                        const struct ovsdb_type *type,
                        const struct json *json,
                        struct ovsdb_symbol_table *symtab)
{
    struct ovsdb_error *error;

    if (ovsdb_type_is_map(type)
        || (json->type == JSON_ARRAY
            && json->u.array.n > 0
            && json->u.array.elems[0]->type == JSON_STRING
            && !strcmp(json->u.array.elems[0]->u.string, "set"))) {
        bool is_map = ovsdb_type_is_map(type);
        const char *class = is_map ? "map" : "set";
        const struct json *inner;
        unsigned int i;
        size_t n;

        error = unwrap_json(json, class, JSON_ARRAY, &inner);
        if (error) {
            return error;
        }

        n = inner->u.array.n;
        if (n < type->n_min || n > type->n_max) {
            return ovsdb_syntax_error(json, NULL, "%s must have %u to "
                                      "%u members but %"PRIuSIZE" are present",
                                      class, type->n_min, type->n_max, n);
        }

        datum->n = 0;
        datum->keys = xmalloc(n * sizeof *datum->keys);
        datum->values = is_map ? xmalloc(n * sizeof *datum->values) : NULL;
        for (i = 0; i < n; i++) {
            const struct json *element = inner->u.array.elems[i];
            const struct json *key = NULL;
            const struct json *value = NULL;

            if (!is_map) {
                key = element;
            } else {
                error = parse_json_pair(element, &key, &value);
                if (error) {
                    goto error;
                }
            }

            error = ovsdb_atom_from_json(&datum->keys[i], &type->key,
                                         key, symtab);
            if (error) {
                goto error;
            }

            if (is_map) {
                error = ovsdb_atom_from_json(&datum->values[i],
                                             &type->value, value, symtab);
                if (error) {
                    ovsdb_atom_destroy(&datum->keys[i], type->key.type);
                    goto error;
                }
            }

            datum->n++;
        }
        return NULL;

    error:
        ovsdb_datum_destroy(datum, type);
        return error;
    } else {
        datum->n = 1;
        datum->keys = xmalloc(sizeof *datum->keys);
        datum->values = NULL;

        error = ovsdb_atom_from_json(&datum->keys[0], &type->key,
                                     json, symtab);
        if (error) {
            free(datum->keys);
        }
        return error;
    }
}

/* Parses 'json' as a datum of the type described by 'type'.  If successful,
 * returns NULL and initializes 'datum' with the parsed datum.  On failure,
 * returns an error and the contents of 'datum' are indeterminate.  The caller
 * is responsible for freeing the error or the datum that is returned.
 *
 * Violations of constraints expressed by 'type' are treated as errors.
 *
 * If 'symtab' is nonnull, then named UUIDs in 'symtab' are accepted.  Refer to
 * RFC 7047 for information about this, and for the syntax that this function
 * accepts. */
struct ovsdb_error *
ovsdb_datum_from_json(struct ovsdb_datum *datum,
                      const struct ovsdb_type *type,
                      const struct json *json,
                      struct ovsdb_symbol_table *symtab)
{
    struct ovsdb_error *error;

    error = ovsdb_datum_from_json__(datum, type, json, symtab);
    if (error) {
        return error;
    }

    error = ovsdb_datum_sort(datum, type->key.type);
    if (error) {
        ovsdb_datum_destroy(datum, type);
    }
    return error;
}

/* Parses 'json' as a datum of the type described by 'type' for internal
 * use. This function is similar to 'ovsdb_datum_from_json', except the
 * member size of set or map is not checked.
 *
 * The datum generated should be used then discard. It is not suitable
 * for storing into IDL because of the possible member size violation.  */
struct ovsdb_error *
ovsdb_transient_datum_from_json(struct ovsdb_datum *datum,
                                const struct ovsdb_type *type,
                                const struct json *json)
{
    struct ovsdb_type relaxed_type = *type;

    relaxed_type.n_min = 0;
    relaxed_type.n_max = UINT_MAX;

    return ovsdb_datum_from_json(datum, &relaxed_type, json, NULL);
}

/* Converts 'datum', of the specified 'type', to JSON format, and returns the
 * JSON.  The caller is responsible for freeing the returned JSON.
 *
 * 'type' constraints on datum->n are ignored.
 *
 * Refer to RFC 7047 for the format of the JSON that this function produces. */
struct json *
ovsdb_datum_to_json(const struct ovsdb_datum *datum,
                    const struct ovsdb_type *type)
{
    if (ovsdb_type_is_map(type)) {
        struct json **elems;
        size_t i;

        elems = xmalloc(datum->n * sizeof *elems);
        for (i = 0; i < datum->n; i++) {
            elems[i] = json_array_create_2(
                ovsdb_atom_to_json(&datum->keys[i], type->key.type),
                ovsdb_atom_to_json(&datum->values[i], type->value.type));
        }

        return wrap_json("map", json_array_create(elems, datum->n));
    } else if (datum->n == 1) {
        return ovsdb_atom_to_json(&datum->keys[0], type->key.type);
    } else {
        struct json **elems;
        size_t i;

        elems = xmalloc(datum->n * sizeof *elems);
        for (i = 0; i < datum->n; i++) {
            elems[i] = ovsdb_atom_to_json(&datum->keys[i], type->key.type);
        }

        return wrap_json("set", json_array_create(elems, datum->n));
    }
}

static const char *
skip_spaces(const char *p)
{
    while (isspace((unsigned char) *p)) {
        p++;
    }
    return p;
}

static char *
parse_atom_token(const char **s, const struct ovsdb_base_type *base,
                 union ovsdb_atom *atom, union ovsdb_atom **range_end_atom,
                 struct ovsdb_symbol_table *symtab)
{
    char *token, *error;

    error = ovsdb_token_parse(s, &token);
    if (!error) {
        error = ovsdb_atom_from_string(atom, range_end_atom,
                                       base, token, symtab);
        free(token);
    }
    return error;
}

static char *
parse_key_value(const char **s, const struct ovsdb_type *type,
                union ovsdb_atom *key, union ovsdb_atom *value,
                struct ovsdb_symbol_table *symtab,
                union ovsdb_atom **range_end_key)
{
    const char *start = *s;
    char *error;

    error = parse_atom_token(s, &type->key, key, range_end_key, symtab);

    if (!error && type->value.type != OVSDB_TYPE_VOID) {
        *s = skip_spaces(*s);
        if (**s == '=') {
            (*s)++;
            *s = skip_spaces(*s);
            error = parse_atom_token(s, &type->value, value, NULL, symtab);
        } else {
            error = xasprintf("%s: syntax error at \"%c\" expecting \"=\"",
                              start, **s);
        }
        if (error) {
            ovsdb_atom_destroy(key, type->key.type);
            if (range_end_key && *range_end_key) {
                ovsdb_atom_destroy(*range_end_key, type->key.type);
                free(*range_end_key);
                *range_end_key = NULL;
            }
        }
    }
    return error;
}

static void
free_key_value_range(const struct ovsdb_type *type,
                     union ovsdb_atom *key, union ovsdb_atom *value,
                     union ovsdb_atom **range_end_atom)
{
    ovsdb_atom_destroy(key, type->key.type);
    if (type->value.type != OVSDB_TYPE_VOID) {
        ovsdb_atom_destroy(value, type->value.type);
    }
    if (range_end_atom && *range_end_atom) {
        ovsdb_atom_destroy(*range_end_atom, type->key.type);
        free(*range_end_atom);
        *range_end_atom = NULL;
    }
}

/* Initializes 'datum' as a datum of the given 'type', parsing its contents
 * from 's'.  The format of 's' is a series of space or comma separated atoms
 * or, for a map, '='-delimited pairs of atoms.  Each atom must in a format
 * acceptable to ovsdb_atom_from_string().  Optionally, a set may be enclosed
 * in "[]" or a map in "{}"; for an empty set or map these punctuators are
 * required.
 *
 * Optionally, a symbol table may be supplied as 'symtab'.  It is passed to
 * ovsdb_atom_to_string(). */
char *
ovsdb_datum_from_string(struct ovsdb_datum *datum,
                        const struct ovsdb_type *type, const char *s,
                        struct ovsdb_symbol_table *symtab)
{
    bool is_map = ovsdb_type_is_map(type);
    struct ovsdb_error *dberror;
    const char *p;
    int end_delim;
    char *error;

    ovsdb_datum_init_empty(datum);

    /* Swallow a leading delimiter if there is one. */
    p = skip_spaces(s);
    if (*p == (is_map ? '{' : '[')) {
        end_delim = is_map ? '}' : ']';
        p = skip_spaces(p + 1);
    } else if (!*p) {
        if (is_map) {
            return xstrdup("use \"{}\" to specify the empty map");
        } else {
            return xstrdup("use \"[]\" to specify the empty set");
        }
    } else {
        end_delim = 0;
    }

    while (*p && *p != end_delim) {
        union ovsdb_atom key, value;
        union ovsdb_atom *range_end_key = NULL;

        if (ovsdb_token_is_delim(*p)) {
            char *type_str = ovsdb_type_to_english(type);
            error = xasprintf("%s: unexpected \"%c\" parsing %s",
                              s, *p, type_str);
            free(type_str);
            goto error;
        }

        /* Add to datum. */
        error = parse_key_value(&p, type, &key, &value,
                                symtab, &range_end_key);
        if (error) {
            goto error;
        }
        ovsdb_datum_add_unsafe(datum, &key, &value, type, range_end_key);
        free_key_value_range(type, &key, &value, &range_end_key);

        /* Skip optional white space and comma. */
        p = skip_spaces(p);
        if (*p == ',') {
            p = skip_spaces(p + 1);
        }
    }

    if (*p != end_delim) {
        error = xasprintf("%s: missing \"%c\" at end of data", s, end_delim);
        goto error;
    }
    if (end_delim) {
        p = skip_spaces(p + 1);
        if (*p) {
            error = xasprintf("%s: trailing garbage after \"%c\"",
                              s, end_delim);
            goto error;
        }
    }

    if (datum->n < type->n_min) {
        error = xasprintf("%s: %u %s specified but the minimum number is %u",
                          s, datum->n, is_map ? "pair(s)" : "value(s)",
                          type->n_min);
        goto error;
    } else if (datum->n > type->n_max) {
        error = xasprintf("%s: %u %s specified but the maximum number is %u",
                          s, datum->n, is_map ? "pair(s)" : "value(s)",
            type->n_max);
        goto error;
    }

    dberror = ovsdb_datum_sort(datum, type->key.type);
    if (dberror) {
        ovsdb_error_destroy(dberror);
        if (ovsdb_type_is_map(type)) {
            error = xasprintf("%s: map contains duplicate key", s);
        } else {
            error = xasprintf("%s: set contains duplicate value", s);
        }
        goto error;
    }

    return NULL;

error:
    ovsdb_datum_destroy(datum, type);
    ovsdb_datum_init_empty(datum);
    return error;
}

/* Appends to 'out' the 'datum' (with the given 'type') in a format acceptable
 * to ovsdb_datum_from_string(). */
void
ovsdb_datum_to_string(const struct ovsdb_datum *datum,
                      const struct ovsdb_type *type, struct ds *out)
{
    bool is_map = ovsdb_type_is_map(type);
    size_t i;

    if (type->n_max > 1 || !datum->n) {
        ds_put_char(out, is_map ? '{' : '[');
    }
    for (i = 0; i < datum->n; i++) {
        if (i > 0) {
            ds_put_cstr(out, ", ");
        }

        ovsdb_atom_to_string(&datum->keys[i], type->key.type, out);
        if (is_map) {
            ds_put_char(out, '=');
            ovsdb_atom_to_string(&datum->values[i], type->value.type, out);
        }
    }
    if (type->n_max > 1 || !datum->n) {
        ds_put_char(out, is_map ? '}' : ']');
    }
}

/* Appends to 'out' the 'datum' (with the given 'type') in a bare string format
 * that cannot be parsed uniformly back into a datum but is easier for shell
 * scripts, etc., to deal with. */
void
ovsdb_datum_to_bare(const struct ovsdb_datum *datum,
                    const struct ovsdb_type *type, struct ds *out)
{
    bool is_map = ovsdb_type_is_map(type);
    size_t i;

    for (i = 0; i < datum->n; i++) {
        if (i > 0) {
            ds_put_cstr(out, " ");
        }

        ovsdb_atom_to_bare(&datum->keys[i], type->key.type, out);
        if (is_map) {
            ds_put_char(out, '=');
            ovsdb_atom_to_bare(&datum->values[i], type->value.type, out);
        }
    }
}

/* Initializes 'datum' as a string-to-string map whose contents are copied from
 * 'smap', which is not modified. */
void
ovsdb_datum_from_smap(struct ovsdb_datum *datum, const struct smap *smap)
{
    datum->n = smap_count(smap);
    datum->keys = xmalloc(datum->n * sizeof *datum->keys);
    datum->values = xmalloc(datum->n * sizeof *datum->values);

    struct smap_node *node;
    size_t i = 0;
    SMAP_FOR_EACH (node, smap) {
        datum->keys[i].string = xstrdup(node->key);
        datum->values[i].string = xstrdup(node->value);
        i++;
    }
    ovs_assert(i == datum->n);

    ovsdb_datum_sort_unique(datum, OVSDB_TYPE_STRING, OVSDB_TYPE_STRING);
}

static uint32_t
hash_atoms(enum ovsdb_atomic_type type, const union ovsdb_atom *atoms,
           unsigned int n, uint32_t basis)
{
    if (type != OVSDB_TYPE_VOID) {
        unsigned int i;

        for (i = 0; i < n; i++) {
            basis = ovsdb_atom_hash(&atoms[i], type, basis);
        }
    }
    return basis;
}

uint32_t
ovsdb_datum_hash(const struct ovsdb_datum *datum,
                 const struct ovsdb_type *type, uint32_t basis)
{
    basis = hash_atoms(type->key.type, datum->keys, datum->n, basis);
    basis ^= (type->key.type << 24) | (type->value.type << 16) | datum->n;
    basis = hash_atoms(type->value.type, datum->values, datum->n, basis);
    return basis;
}

static int
atom_arrays_compare_3way(const union ovsdb_atom *a,
                         const union ovsdb_atom *b,
                         enum ovsdb_atomic_type type,
                         size_t n)
{
    unsigned int i;

    for (i = 0; i < n; i++) {
        int cmp = ovsdb_atom_compare_3way(&a[i], &b[i], type);
        if (cmp) {
            return cmp;
        }
    }

    return 0;
}

bool
ovsdb_datum_equals(const struct ovsdb_datum *a,
                   const struct ovsdb_datum *b,
                   const struct ovsdb_type *type)
{
    return !ovsdb_datum_compare_3way(a, b, type);
}

int
ovsdb_datum_compare_3way(const struct ovsdb_datum *a,
                         const struct ovsdb_datum *b,
                         const struct ovsdb_type *type)
{
    int cmp;

    if (a->n != b->n) {
        return a->n < b->n ? -1 : 1;
    }

    cmp = atom_arrays_compare_3way(a->keys, b->keys, type->key.type, a->n);
    if (cmp) {
        return cmp;
    }

    return (type->value.type == OVSDB_TYPE_VOID ? 0
            : atom_arrays_compare_3way(a->values, b->values, type->value.type,
                                       a->n));
}

/* If 'key' is one of the keys in 'datum', returns its index within 'datum',
 * otherwise UINT_MAX.  'key.type' must be the type of the atoms stored in the
 * 'keys' array in 'datum'.
 */
unsigned int
ovsdb_datum_find_key(const struct ovsdb_datum *datum,
                     const union ovsdb_atom *key,
                     enum ovsdb_atomic_type key_type)
{
    unsigned int low = 0;
    unsigned int high = datum->n;
    while (low < high) {
        unsigned int idx = (low + high) / 2;
        int cmp = ovsdb_atom_compare_3way(key, &datum->keys[idx], key_type);
        if (cmp < 0) {
            high = idx;
        } else if (cmp > 0) {
            low = idx + 1;
        } else {
            return idx;
        }
    }
    return UINT_MAX;
}

/* If 'key' and 'value' is one of the key-value pairs in 'datum', returns its
 * index within 'datum', otherwise UINT_MAX.  'key.type' must be the type of
 * the atoms stored in the 'keys' array in 'datum'.  'value_type' may be the
 * type of the 'values' atoms or OVSDB_TYPE_VOID to compare only keys.
 */
unsigned int
ovsdb_datum_find_key_value(const struct ovsdb_datum *datum,
                           const union ovsdb_atom *key,
                           enum ovsdb_atomic_type key_type,
                           const union ovsdb_atom *value,
                           enum ovsdb_atomic_type value_type)
{
    unsigned int idx = ovsdb_datum_find_key(datum, key, key_type);
    if (idx != UINT_MAX
        && value_type != OVSDB_TYPE_VOID
        && !ovsdb_atom_equals(&datum->values[idx], value, value_type)) {
        idx = UINT_MAX;
    }
    return idx;
}

/* If atom 'i' in 'a' is also in 'b', returns its index in 'b', otherwise
 * UINT_MAX.  'type' must be the type of 'a' and 'b', except that
 * type->value.type may be set to OVSDB_TYPE_VOID to compare keys but not
 * values. */
static unsigned int
ovsdb_datum_find(const struct ovsdb_datum *a, int i,
                 const struct ovsdb_datum *b,
                 const struct ovsdb_type *type)
{
    return ovsdb_datum_find_key_value(b,
                                      &a->keys[i], type->key.type,
                                      a->values ? &a->values[i] : NULL,
                                      type->value.type);
}

/* Returns true if every element in 'a' is also in 'b', false otherwise. */
bool
ovsdb_datum_includes_all(const struct ovsdb_datum *a,
                         const struct ovsdb_datum *b,
                         const struct ovsdb_type *type)
{
    size_t i;

    if (a->n > b->n) {
        return false;
    }
    for (i = 0; i < a->n; i++) {
        if (ovsdb_datum_find(a, i, b, type) == UINT_MAX) {
            return false;
        }
    }
    return true;
}

/* Returns true if no element in 'a' is also in 'b', false otherwise. */
bool
ovsdb_datum_excludes_all(const struct ovsdb_datum *a,
                         const struct ovsdb_datum *b,
                         const struct ovsdb_type *type)
{
    size_t i;

    for (i = 0; i < a->n; i++) {
        if (ovsdb_datum_find(a, i, b, type) != UINT_MAX) {
            return false;
        }
    }
    return true;
}

static void
ovsdb_datum_reallocate(struct ovsdb_datum *a, const struct ovsdb_type *type,
                       unsigned int capacity)
{
    a->keys = xrealloc(a->keys, capacity * sizeof *a->keys);
    if (type->value.type != OVSDB_TYPE_VOID) {
        a->values = xrealloc(a->values, capacity * sizeof *a->values);
    }
}

/* Removes the element with index 'idx' from 'datum', which has type 'type'.
 * If 'idx' is not the last element in 'datum', then the removed element is
 * replaced by the (former) last element.
 *
 * This function does not maintain ovsdb_datum invariants.  Use
 * ovsdb_datum_sort() to check and restore these invariants. */
void
ovsdb_datum_remove_unsafe(struct ovsdb_datum *datum, size_t idx,
                          const struct ovsdb_type *type)
{
    ovsdb_atom_destroy(&datum->keys[idx], type->key.type);
    datum->keys[idx] = datum->keys[datum->n - 1];
    if (type->value.type != OVSDB_TYPE_VOID) {
        ovsdb_atom_destroy(&datum->values[idx], type->value.type);
        datum->values[idx] = datum->values[datum->n - 1];
    }
    datum->n--;
}

/* Adds the element with the given 'key' and 'value' to 'datum', which must
 * have the specified 'type'. Optionally if 'range_end_atom' is not
 * a null pointer, adds a set of integers to 'datum' from inclusive
 * range ['key', 'range_end_atom'].
 *
 * This function always allocates memory, so it is not an efficient way to add
 * a number of elements to a datum.
 *
 * When adding a range of integers, this function allocates the memory once
 * for the whole range.
 *
 * This function does not maintain ovsdb_datum invariants.  Use
 * ovsdb_datum_sort() to check and restore these invariants.  (But a datum with
 * 0 or 1 elements cannot violate the invariants anyhow.) */
void
ovsdb_datum_add_unsafe(struct ovsdb_datum *datum,
                       const union ovsdb_atom *key,
                       const union ovsdb_atom *value,
                       const struct ovsdb_type *type,
                       const union ovsdb_atom *range_end_atom)
{
    size_t idx = datum->n;
    datum->n += range_end_atom ?
                (range_end_atom->integer - key->integer + 1) : 1;
    datum->keys = xrealloc(datum->keys, datum->n * sizeof *datum->keys);
    if (range_end_atom && key->integer <= range_end_atom->integer) {
        for (int64_t i = key->integer; i <= range_end_atom->integer; i++) {
            datum->keys[idx++].integer = i;
        }
    } else {
        ovsdb_atom_clone(&datum->keys[idx], key, type->key.type);
        if (type->value.type != OVSDB_TYPE_VOID) {
            datum->values = xrealloc(datum->values,
                                     datum->n * sizeof *datum->values);
            ovsdb_atom_clone(&datum->values[idx], value, type->value.type);
        }
    }
}

void
ovsdb_datum_union(struct ovsdb_datum *a, const struct ovsdb_datum *b,
                  const struct ovsdb_type *type, bool replace)
{
    unsigned int n;
    size_t bi;

    n = a->n;
    for (bi = 0; bi < b->n; bi++) {
        unsigned int ai;

        ai = ovsdb_datum_find_key(a, &b->keys[bi], type->key.type);
        if (ai == UINT_MAX) {
            if (n == a->n) {
                ovsdb_datum_reallocate(a, type, a->n + (b->n - bi));
            }
            ovsdb_atom_clone(&a->keys[n], &b->keys[bi], type->key.type);
            if (type->value.type != OVSDB_TYPE_VOID) {
                ovsdb_atom_clone(&a->values[n], &b->values[bi],
                                 type->value.type);
            }
            n++;
        } else if (replace && type->value.type != OVSDB_TYPE_VOID) {
            ovsdb_atom_destroy(&a->values[ai], type->value.type);
            ovsdb_atom_clone(&a->values[ai], &b->values[bi],
                             type->value.type);
        }
    }
    if (n != a->n) {
        struct ovsdb_error *error;
        a->n = n;
        error = ovsdb_datum_sort(a, type->key.type);
        ovs_assert(!error);
    }
}

void
ovsdb_datum_subtract(struct ovsdb_datum *a, const struct ovsdb_type *a_type,
                     const struct ovsdb_datum *b,
                     const struct ovsdb_type *b_type)
{
    bool changed = false;
    size_t i;

    ovs_assert(a_type->key.type == b_type->key.type);
    ovs_assert(a_type->value.type == b_type->value.type
               || b_type->value.type == OVSDB_TYPE_VOID);

    /* XXX The big-O of this could easily be improved. */
    for (i = 0; i < a->n; ) {
        unsigned int idx = ovsdb_datum_find(a, i, b, b_type);
        if (idx != UINT_MAX) {
            changed = true;
            ovsdb_datum_remove_unsafe(a, i, a_type);
        } else {
            i++;
        }
    }
    if (changed) {
        ovsdb_datum_sort_assert(a, a_type->key.type);
    }
}

struct ovsdb_symbol_table *
ovsdb_symbol_table_create(void)
{
    struct ovsdb_symbol_table *symtab = xmalloc(sizeof *symtab);
    shash_init(&symtab->sh);
    return symtab;
}

void
ovsdb_symbol_table_destroy(struct ovsdb_symbol_table *symtab)
{
    if (symtab) {
        shash_destroy_free_data(&symtab->sh);
        free(symtab);
    }
}

struct ovsdb_symbol *
ovsdb_symbol_table_get(const struct ovsdb_symbol_table *symtab,
                       const char *name)
{
    return shash_find_data(&symtab->sh, name);
}

struct ovsdb_symbol *
ovsdb_symbol_table_put(struct ovsdb_symbol_table *symtab, const char *name,
                       const struct uuid *uuid, bool created)
{
    struct ovsdb_symbol *symbol;

    ovs_assert(!ovsdb_symbol_table_get(symtab, name));
    symbol = xmalloc(sizeof *symbol);
    symbol->uuid = *uuid;
    symbol->created = created;
    symbol->strong_ref = false;
    symbol->weak_ref = false;
    shash_add(&symtab->sh, name, symbol);
    return symbol;
}

struct ovsdb_symbol *
ovsdb_symbol_table_insert(struct ovsdb_symbol_table *symtab,
                          const char *name)
{
    struct ovsdb_symbol *symbol;

    symbol = ovsdb_symbol_table_get(symtab, name);
    if (!symbol) {
        struct uuid uuid;

        uuid_generate(&uuid);
        symbol = ovsdb_symbol_table_put(symtab, name, &uuid, false);
    }
    return symbol;
}

/* APIs for Generating and apply diffs.  */

/* Generate a difference ovsdb_dataum between 'old' and 'new'.
 * 'new' can be regenerated by applying the difference to the 'old'.
 *
 * The diff operation is reversible. Given 'old',
 * 'new' can be recreated by applying diff to 'old'.
 *
 * Thus
 *     Let  d = 'old' diff 'new'
 *     then 'new' = 'old' diff d
 *
 * The 'diff' datum is always safe; the orders of keys are maintained
 * since they are added in order.   */
void
ovsdb_datum_diff(struct ovsdb_datum *diff,
                 const struct ovsdb_datum *old,
                 const struct ovsdb_datum *new,
                 const struct ovsdb_type *type)
{
    size_t oi, ni;

    ovsdb_datum_init_empty(diff);
    if (!ovsdb_type_is_composite(type)) {
        ovsdb_datum_clone(diff, new, type);
        return;
    }

    /* Generate the diff in O(n) time. */
    for (oi = ni = 0; oi < old->n && ni < new->n; ) {
        int c = ovsdb_atom_compare_3way(&old->keys[oi], &new->keys[ni],
                                        type->key.type);
        if (c < 0) {
            ovsdb_datum_add_unsafe(diff, &old->keys[oi], &old->values[oi],
                                   type, NULL);
            oi++;
        } else if (c > 0) {
            ovsdb_datum_add_unsafe(diff, &new->keys[ni], &new->values[ni],
                                   type, NULL);
            ni++;
        } else {
            if (type->value.type != OVSDB_TYPE_VOID &&
                ovsdb_atom_compare_3way(&old->values[oi], &new->values[ni],
                                        type->value.type)) {
                ovsdb_datum_add_unsafe(diff, &new->keys[ni], &new->values[ni],
                                       type, NULL);
            }
            oi++; ni++;
        }
    }

    for (; oi < old->n; oi++) {
        ovsdb_datum_add_unsafe(diff, &old->keys[oi], &old->values[oi],
                               type, NULL);
    }

    for (; ni < new->n; ni++) {
        ovsdb_datum_add_unsafe(diff, &new->keys[ni], &new->values[ni],
                               type, NULL);
    }
}

/* Apply 'diff' to 'old' to regenerate 'new'.
 *
 * Return NULL if the 'new' is successfully generated, otherwise, return
 * ovsdb_error and the stat of 'new' is indeterministic. */
struct ovsdb_error *
ovsdb_datum_apply_diff(struct ovsdb_datum *new,
                       const struct ovsdb_datum *old,
                       const struct ovsdb_datum *diff,
                       const struct ovsdb_type *type)
{
    ovsdb_datum_init_empty(new);
    ovsdb_datum_diff(new, old, diff, type);

    /* Make sure member size of 'new' conforms to type. */
    if (new->n < type->n_min || new->n > type->n_max) {
        ovsdb_datum_destroy(new, type);
        return ovsdb_error(NULL, "Datum crated by diff has size error");
    }

    return NULL;
}


/* Extracts a token from the beginning of 's' and returns a pointer just after
 * the token.  Stores the token itself into '*outp', which the caller is
 * responsible for freeing (with free()).
 *
 * If 's[0]' is a delimiter, the returned token is the empty string.
 *
 * A token extends from 's' to the first delimiter, as defined by
 * ovsdb_token_is_delim(), or until the end of the string.  A delimiter can be
 * escaped with a backslash, in which case the backslash does not appear in the
 * output.  Double quotes also cause delimiters to be ignored, but the double
 * quotes are retained in the output.  (Backslashes inside double quotes are
 * not removed, either.)
 */
char *
ovsdb_token_parse(const char **s, char **outp)
{
    const char *p;
    struct ds out;
    bool in_quotes;
    char *error;

    ds_init(&out);
    in_quotes = false;
    for (p = *s; *p != '\0'; ) {
        int c = *p++;
        if (c == '\\') {
            if (in_quotes) {
                ds_put_char(&out, '\\');
            }
            if (!*p) {
                error = xasprintf("%s: backslash at end of argument", *s);
                goto error;
            }
            ds_put_char(&out, *p++);
        } else if (!in_quotes && ovsdb_token_is_delim(c)) {
            p--;
            break;
        } else {
            ds_put_char(&out, c);
            if (c == '"') {
                in_quotes = !in_quotes;
            }
        }
    }
    if (in_quotes) {
        error = xasprintf("%s: quoted string extends past end of argument",
                          *s);
        goto error;
    }
    *outp = ds_cstr(&out);
    *s = p;
    return NULL;

error:
    ds_destroy(&out);
    *outp = NULL;
    return error;
}

/* Returns true if 'c' delimits tokens, or if 'c' is 0, and false otherwise. */
bool
ovsdb_token_is_delim(unsigned char c)
{
    return strchr(":=, []{}!<>", c) != NULL;
}

struct ovsdb_error *
ovsdb_atom_range_check_size(int64_t range_start, int64_t range_end)
{
    if ((uint64_t) range_end - (uint64_t) range_start
        >= MAX_OVSDB_ATOM_RANGE_SIZE) {
        return ovsdb_error("constraint violation",
                           "Range \"%"PRId64"-%"PRId64"\" is too big. "
                           "Maximum allowed size is %d.",
                           range_start, range_end, MAX_OVSDB_ATOM_RANGE_SIZE);
    }
    return NULL;
}