Global replace of Nicira Networks.
[sliver-openvswitch.git] / lib / ovsdb-data.c
1 /* Copyright (c) 2009, 2010, 2011, 2012 Nicira, Inc.
2  *
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at:
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15
16 #include <config.h>
17
18 #include "ovsdb-data.h"
19
20 #include <assert.h>
21 #include <ctype.h>
22 #include <float.h>
23 #include <inttypes.h>
24 #include <limits.h>
25
26 #include "dynamic-string.h"
27 #include "hash.h"
28 #include "ovsdb-error.h"
29 #include "ovsdb-parser.h"
30 #include "json.h"
31 #include "shash.h"
32 #include "sort.h"
33 #include "unicode.h"
34
35 static struct json *
36 wrap_json(const char *name, struct json *wrapped)
37 {
38     return json_array_create_2(json_string_create(name), wrapped);
39 }
40
41 /* Initializes 'atom' with the default value of the given 'type'.
42  *
43  * The default value for an atom is as defined in ovsdb/SPECS:
44  *
45  *      - "integer" or "real": 0
46  *
47  *      - "boolean": false
48  *
49  *      - "string": "" (the empty string)
50  *
51  *      - "uuid": 00000000-0000-0000-0000-000000000000
52  *
53  * The caller must eventually arrange for 'atom' to be destroyed (with
54  * ovsdb_atom_destroy()). */
55 void
56 ovsdb_atom_init_default(union ovsdb_atom *atom, enum ovsdb_atomic_type type)
57 {
58     switch (type) {
59     case OVSDB_TYPE_VOID:
60         NOT_REACHED();
61
62     case OVSDB_TYPE_INTEGER:
63         atom->integer = 0;
64         break;
65
66     case OVSDB_TYPE_REAL:
67         atom->real = 0.0;
68         break;
69
70     case OVSDB_TYPE_BOOLEAN:
71         atom->boolean = false;
72         break;
73
74     case OVSDB_TYPE_STRING:
75         atom->string = xmemdup("", 1);
76         break;
77
78     case OVSDB_TYPE_UUID:
79         uuid_zero(&atom->uuid);
80         break;
81
82     case OVSDB_N_TYPES:
83     default:
84         NOT_REACHED();
85     }
86 }
87
88 /* Returns a read-only atom of the given 'type' that has the default value for
89  * 'type'.  The caller must not modify or free the returned atom.
90  *
91  * See ovsdb_atom_init_default() for an explanation of the default value of an
92  * atom. */
93 const union ovsdb_atom *
94 ovsdb_atom_default(enum ovsdb_atomic_type type)
95 {
96     static union ovsdb_atom default_atoms[OVSDB_N_TYPES];
97     static bool inited;
98
99     if (!inited) {
100         int i;
101
102         for (i = 0; i < OVSDB_N_TYPES; i++) {
103             if (i != OVSDB_TYPE_VOID) {
104                 ovsdb_atom_init_default(&default_atoms[i], i);
105             }
106         }
107         inited = true;
108     }
109
110     assert(ovsdb_atomic_type_is_valid(type));
111     return &default_atoms[type];
112 }
113
114 /* Returns true if 'atom', which must have the given 'type', has the default
115  * value for that type.
116  *
117  * See ovsdb_atom_init_default() for an explanation of the default value of an
118  * atom. */
119 bool
120 ovsdb_atom_is_default(const union ovsdb_atom *atom,
121                       enum ovsdb_atomic_type type)
122 {
123     switch (type) {
124     case OVSDB_TYPE_VOID:
125         NOT_REACHED();
126
127     case OVSDB_TYPE_INTEGER:
128         return atom->integer == 0;
129
130     case OVSDB_TYPE_REAL:
131         return atom->real == 0.0;
132
133     case OVSDB_TYPE_BOOLEAN:
134         return atom->boolean == false;
135
136     case OVSDB_TYPE_STRING:
137         return atom->string[0] == '\0';
138
139     case OVSDB_TYPE_UUID:
140         return uuid_is_zero(&atom->uuid);
141
142     case OVSDB_N_TYPES:
143     default:
144         NOT_REACHED();
145     }
146 }
147
148 /* Initializes 'new' as a copy of 'old', with the given 'type'.
149  *
150  * The caller must eventually arrange for 'new' to be destroyed (with
151  * ovsdb_atom_destroy()). */
152 void
153 ovsdb_atom_clone(union ovsdb_atom *new, const union ovsdb_atom *old,
154                  enum ovsdb_atomic_type type)
155 {
156     switch (type) {
157     case OVSDB_TYPE_VOID:
158         NOT_REACHED();
159
160     case OVSDB_TYPE_INTEGER:
161         new->integer = old->integer;
162         break;
163
164     case OVSDB_TYPE_REAL:
165         new->real = old->real;
166         break;
167
168     case OVSDB_TYPE_BOOLEAN:
169         new->boolean = old->boolean;
170         break;
171
172     case OVSDB_TYPE_STRING:
173         new->string = xstrdup(old->string);
174         break;
175
176     case OVSDB_TYPE_UUID:
177         new->uuid = old->uuid;
178         break;
179
180     case OVSDB_N_TYPES:
181     default:
182         NOT_REACHED();
183     }
184 }
185
186 /* Swaps the contents of 'a' and 'b', which need not have the same type. */
187 void
188 ovsdb_atom_swap(union ovsdb_atom *a, union ovsdb_atom *b)
189 {
190     union ovsdb_atom tmp = *a;
191     *a = *b;
192     *b = tmp;
193 }
194
195 /* Returns a hash value for 'atom', which has the specified 'type', folding
196  * 'basis' into the calculation. */
197 uint32_t
198 ovsdb_atom_hash(const union ovsdb_atom *atom, enum ovsdb_atomic_type type,
199                 uint32_t basis)
200 {
201     switch (type) {
202     case OVSDB_TYPE_VOID:
203         NOT_REACHED();
204
205     case OVSDB_TYPE_INTEGER:
206         return hash_int(atom->integer, basis);
207
208     case OVSDB_TYPE_REAL:
209         return hash_double(atom->real, basis);
210
211     case OVSDB_TYPE_BOOLEAN:
212         return hash_boolean(atom->boolean, basis);
213
214     case OVSDB_TYPE_STRING:
215         return hash_string(atom->string, basis);
216
217     case OVSDB_TYPE_UUID:
218         return hash_int(uuid_hash(&atom->uuid), basis);
219
220     case OVSDB_N_TYPES:
221     default:
222         NOT_REACHED();
223     }
224 }
225
226 /* Compares 'a' and 'b', which both have type 'type', and returns a
227  * strcmp()-like result. */
228 int
229 ovsdb_atom_compare_3way(const union ovsdb_atom *a,
230                         const union ovsdb_atom *b,
231                         enum ovsdb_atomic_type type)
232 {
233     switch (type) {
234     case OVSDB_TYPE_VOID:
235         NOT_REACHED();
236
237     case OVSDB_TYPE_INTEGER:
238         return a->integer < b->integer ? -1 : a->integer > b->integer;
239
240     case OVSDB_TYPE_REAL:
241         return a->real < b->real ? -1 : a->real > b->real;
242
243     case OVSDB_TYPE_BOOLEAN:
244         return a->boolean - b->boolean;
245
246     case OVSDB_TYPE_STRING:
247         return strcmp(a->string, b->string);
248
249     case OVSDB_TYPE_UUID:
250         return uuid_compare_3way(&a->uuid, &b->uuid);
251
252     case OVSDB_N_TYPES:
253     default:
254         NOT_REACHED();
255     }
256 }
257
258 static struct ovsdb_error *
259 unwrap_json(const struct json *json, const char *name,
260             enum json_type value_type, const struct json **value)
261 {
262     if (json->type != JSON_ARRAY
263         || json->u.array.n != 2
264         || json->u.array.elems[0]->type != JSON_STRING
265         || (name && strcmp(json->u.array.elems[0]->u.string, name))
266         || json->u.array.elems[1]->type != value_type)
267     {
268         *value = NULL;
269         return ovsdb_syntax_error(json, NULL, "expected [\"%s\", <%s>]", name,
270                                   json_type_to_string(value_type));
271     }
272     *value = json->u.array.elems[1];
273     return NULL;
274 }
275
276 static struct ovsdb_error *
277 parse_json_pair(const struct json *json,
278                 const struct json **elem0, const struct json **elem1)
279 {
280     if (json->type != JSON_ARRAY || json->u.array.n != 2) {
281         return ovsdb_syntax_error(json, NULL, "expected 2-element array");
282     }
283     *elem0 = json->u.array.elems[0];
284     *elem1 = json->u.array.elems[1];
285     return NULL;
286 }
287
288 static void
289 ovsdb_symbol_referenced(struct ovsdb_symbol *symbol,
290                         const struct ovsdb_base_type *base)
291 {
292     assert(base->type == OVSDB_TYPE_UUID);
293
294     if (base->u.uuid.refTableName) {
295         switch (base->u.uuid.refType) {
296         case OVSDB_REF_STRONG:
297             symbol->strong_ref = true;
298             break;
299         case OVSDB_REF_WEAK:
300             symbol->weak_ref = true;
301             break;
302         }
303     }
304 }
305
306 static struct ovsdb_error * WARN_UNUSED_RESULT
307 ovsdb_atom_parse_uuid(struct uuid *uuid, const struct json *json,
308                       struct ovsdb_symbol_table *symtab,
309                       const struct ovsdb_base_type *base)
310 {
311     struct ovsdb_error *error0;
312     const struct json *value;
313
314     error0 = unwrap_json(json, "uuid", JSON_STRING, &value);
315     if (!error0) {
316         const char *uuid_string = json_string(value);
317         if (!uuid_from_string(uuid, uuid_string)) {
318             return ovsdb_syntax_error(json, NULL, "\"%s\" is not a valid UUID",
319                                       uuid_string);
320         }
321     } else if (symtab) {
322         struct ovsdb_error *error1;
323
324         error1 = unwrap_json(json, "named-uuid", JSON_STRING, &value);
325         if (!error1) {
326             struct ovsdb_symbol *symbol;
327
328             ovsdb_error_destroy(error0);
329             if (!ovsdb_parser_is_id(json_string(value))) {
330                 return ovsdb_syntax_error(json, NULL, "named-uuid string is "
331                                           "not a valid <id>");
332             }
333
334             symbol = ovsdb_symbol_table_insert(symtab, json_string(value));
335             *uuid = symbol->uuid;
336             ovsdb_symbol_referenced(symbol, base);
337             return NULL;
338         }
339         ovsdb_error_destroy(error1);
340     }
341
342     return error0;
343 }
344
345 static struct ovsdb_error * WARN_UNUSED_RESULT
346 ovsdb_atom_from_json__(union ovsdb_atom *atom,
347                        const struct ovsdb_base_type *base,
348                        const struct json *json,
349                        struct ovsdb_symbol_table *symtab)
350 {
351     enum ovsdb_atomic_type type = base->type;
352
353     switch (type) {
354     case OVSDB_TYPE_VOID:
355         NOT_REACHED();
356
357     case OVSDB_TYPE_INTEGER:
358         if (json->type == JSON_INTEGER) {
359             atom->integer = json->u.integer;
360             return NULL;
361         }
362         break;
363
364     case OVSDB_TYPE_REAL:
365         if (json->type == JSON_INTEGER) {
366             atom->real = json->u.integer;
367             return NULL;
368         } else if (json->type == JSON_REAL) {
369             atom->real = json->u.real;
370             return NULL;
371         }
372         break;
373
374     case OVSDB_TYPE_BOOLEAN:
375         if (json->type == JSON_TRUE) {
376             atom->boolean = true;
377             return NULL;
378         } else if (json->type == JSON_FALSE) {
379             atom->boolean = false;
380             return NULL;
381         }
382         break;
383
384     case OVSDB_TYPE_STRING:
385         if (json->type == JSON_STRING) {
386             atom->string = xstrdup(json->u.string);
387             return NULL;
388         }
389         break;
390
391     case OVSDB_TYPE_UUID:
392         return ovsdb_atom_parse_uuid(&atom->uuid, json, symtab, base);
393
394     case OVSDB_N_TYPES:
395     default:
396         NOT_REACHED();
397     }
398
399     return ovsdb_syntax_error(json, NULL, "expected %s",
400                               ovsdb_atomic_type_to_string(type));
401 }
402
403 /* Parses 'json' as an atom of the type described by 'base'.  If successful,
404  * returns NULL and initializes 'atom' with the parsed atom.  On failure,
405  * returns an error and the contents of 'atom' are indeterminate.  The caller
406  * is responsible for freeing the error or the atom that is returned.
407  *
408  * Violations of constraints expressed by 'base' are treated as errors.
409  *
410  * If 'symtab' is nonnull, then named UUIDs in 'symtab' are accepted.  Refer to
411  * ovsdb/SPECS for information about this, and for the syntax that this
412  * function accepts.  If 'base' is a reference and a symbol is parsed, then the
413  * symbol's 'strong_ref' or 'weak_ref' member is set to true, as
414  * appropriate. */
415 struct ovsdb_error *
416 ovsdb_atom_from_json(union ovsdb_atom *atom,
417                      const struct ovsdb_base_type *base,
418                      const struct json *json,
419                      struct ovsdb_symbol_table *symtab)
420 {
421     struct ovsdb_error *error;
422
423     error = ovsdb_atom_from_json__(atom, base, json, symtab);
424     if (error) {
425         return error;
426     }
427
428     error = ovsdb_atom_check_constraints(atom, base);
429     if (error) {
430         ovsdb_atom_destroy(atom, base->type);
431     }
432     return error;
433 }
434
435 /* Converts 'atom', of the specified 'type', to JSON format, and returns the
436  * JSON.  The caller is responsible for freeing the returned JSON.
437  *
438  * Refer to ovsdb/SPECS for the format of the JSON that this function
439  * produces. */
440 struct json *
441 ovsdb_atom_to_json(const union ovsdb_atom *atom, enum ovsdb_atomic_type type)
442 {
443     switch (type) {
444     case OVSDB_TYPE_VOID:
445         NOT_REACHED();
446
447     case OVSDB_TYPE_INTEGER:
448         return json_integer_create(atom->integer);
449
450     case OVSDB_TYPE_REAL:
451         return json_real_create(atom->real);
452
453     case OVSDB_TYPE_BOOLEAN:
454         return json_boolean_create(atom->boolean);
455
456     case OVSDB_TYPE_STRING:
457         return json_string_create(atom->string);
458
459     case OVSDB_TYPE_UUID:
460         return wrap_json("uuid", json_string_create_nocopy(
461                              xasprintf(UUID_FMT, UUID_ARGS(&atom->uuid))));
462
463     case OVSDB_N_TYPES:
464     default:
465         NOT_REACHED();
466     }
467 }
468
469 static char *
470 ovsdb_atom_from_string__(union ovsdb_atom *atom,
471                          const struct ovsdb_base_type *base, const char *s,
472                          struct ovsdb_symbol_table *symtab)
473 {
474     enum ovsdb_atomic_type type = base->type;
475
476     switch (type) {
477     case OVSDB_TYPE_VOID:
478         NOT_REACHED();
479
480     case OVSDB_TYPE_INTEGER: {
481         long long int integer;
482         if (!str_to_llong(s, 10, &integer)) {
483             return xasprintf("\"%s\" is not a valid integer", s);
484         }
485         atom->integer = integer;
486     }
487         break;
488
489     case OVSDB_TYPE_REAL:
490         if (!str_to_double(s, &atom->real)) {
491             return xasprintf("\"%s\" is not a valid real number", s);
492         }
493         /* Our JSON input routines map negative zero to zero, so do that here
494          * too for consistency. */
495         if (atom->real == 0.0) {
496             atom->real = 0.0;
497         }
498         break;
499
500     case OVSDB_TYPE_BOOLEAN:
501         if (!strcmp(s, "true") || !strcmp(s, "yes") || !strcmp(s, "on")
502             || !strcmp(s, "1")) {
503             atom->boolean = true;
504         } else if (!strcmp(s, "false") || !strcmp(s, "no") || !strcmp(s, "off")
505                    || !strcmp(s, "0")) {
506             atom->boolean = false;
507         } else {
508             return xasprintf("\"%s\" is not a valid boolean "
509                              "(use \"true\" or \"false\")", s);
510         }
511         break;
512
513     case OVSDB_TYPE_STRING:
514         if (*s == '\0') {
515             return xstrdup("An empty string is not valid as input; "
516                            "use \"\" to represent the empty string");
517         } else if (*s == '"') {
518             size_t s_len = strlen(s);
519
520             if (s_len < 2 || s[s_len - 1] != '"') {
521                 return xasprintf("%s: missing quote at end of "
522                                  "quoted string", s);
523             } else if (!json_string_unescape(s + 1, s_len - 2,
524                                              &atom->string)) {
525                 char *error = xasprintf("%s: %s", s, atom->string);
526                 free(atom->string);
527                 return error;
528             }
529         } else {
530             atom->string = xstrdup(s);
531         }
532         break;
533
534     case OVSDB_TYPE_UUID:
535         if (*s == '@') {
536             struct ovsdb_symbol *symbol = ovsdb_symbol_table_insert(symtab, s);
537             atom->uuid = symbol->uuid;
538             ovsdb_symbol_referenced(symbol, base);
539         } else if (!uuid_from_string(&atom->uuid, s)) {
540             return xasprintf("\"%s\" is not a valid UUID", s);
541         }
542         break;
543
544     case OVSDB_N_TYPES:
545     default:
546         NOT_REACHED();
547     }
548
549     return NULL;
550 }
551
552 /* Initializes 'atom' to a value of type 'base' parsed from 's', which takes
553  * one of the following forms:
554  *
555  *      - OVSDB_TYPE_INTEGER: A decimal integer optionally preceded by a sign.
556  *
557  *      - OVSDB_TYPE_REAL: A floating-point number in the format accepted by
558  *        strtod().
559  *
560  *      - OVSDB_TYPE_BOOLEAN: "true", "yes", "on", "1" for true, or "false",
561  *        "no", "off", or "0" for false.
562  *
563  *      - OVSDB_TYPE_STRING: A JSON string if it begins with a quote, otherwise
564  *        an arbitrary string.
565  *
566  *      - OVSDB_TYPE_UUID: A UUID in RFC 4122 format.  If 'symtab' is nonnull,
567  *        then an identifier beginning with '@' is also acceptable.  If the
568  *        named identifier is already in 'symtab', then the associated UUID is
569  *        used; otherwise, a new, random UUID is used and added to the symbol
570  *        table.  If 'base' is a reference and a symbol is parsed, then the
571  *        symbol's 'strong_ref' or 'weak_ref' member is set to true, as
572  *        appropriate.
573  *
574  * Returns a null pointer if successful, otherwise an error message describing
575  * the problem.  On failure, the contents of 'atom' are indeterminate.  The
576  * caller is responsible for freeing the atom or the error.
577  */
578 char *
579 ovsdb_atom_from_string(union ovsdb_atom *atom,
580                        const struct ovsdb_base_type *base, const char *s,
581                        struct ovsdb_symbol_table *symtab)
582 {
583     struct ovsdb_error *error;
584     char *msg;
585
586     msg = ovsdb_atom_from_string__(atom, base, s, symtab);
587     if (msg) {
588         return msg;
589     }
590
591     error = ovsdb_atom_check_constraints(atom, base);
592     if (error) {
593         ovsdb_atom_destroy(atom, base->type);
594         msg = ovsdb_error_to_string(error);
595         ovsdb_error_destroy(error);
596     }
597     return msg;
598 }
599
600 static bool
601 string_needs_quotes(const char *s)
602 {
603     const char *p = s;
604     unsigned char c;
605
606     c = *p++;
607     if (!isalpha(c) && c != '_') {
608         return true;
609     }
610
611     while ((c = *p++) != '\0') {
612         if (!isalpha(c) && c != '_' && c != '-' && c != '.') {
613             return true;
614         }
615     }
616
617     if (!strcmp(s, "true") || !strcmp(s, "false")) {
618         return true;
619     }
620
621     return false;
622 }
623
624 /* Appends 'atom' (which has the given 'type') to 'out', in a format acceptable
625  * to ovsdb_atom_from_string().  */
626 void
627 ovsdb_atom_to_string(const union ovsdb_atom *atom, enum ovsdb_atomic_type type,
628                      struct ds *out)
629 {
630     switch (type) {
631     case OVSDB_TYPE_VOID:
632         NOT_REACHED();
633
634     case OVSDB_TYPE_INTEGER:
635         ds_put_format(out, "%"PRId64, atom->integer);
636         break;
637
638     case OVSDB_TYPE_REAL:
639         ds_put_format(out, "%.*g", DBL_DIG, atom->real);
640         break;
641
642     case OVSDB_TYPE_BOOLEAN:
643         ds_put_cstr(out, atom->boolean ? "true" : "false");
644         break;
645
646     case OVSDB_TYPE_STRING:
647         if (string_needs_quotes(atom->string)) {
648             struct json json;
649
650             json.type = JSON_STRING;
651             json.u.string = atom->string;
652             json_to_ds(&json, 0, out);
653         } else {
654             ds_put_cstr(out, atom->string);
655         }
656         break;
657
658     case OVSDB_TYPE_UUID:
659         ds_put_format(out, UUID_FMT, UUID_ARGS(&atom->uuid));
660         break;
661
662     case OVSDB_N_TYPES:
663     default:
664         NOT_REACHED();
665     }
666 }
667
668 /* Appends 'atom' (which has the given 'type') to 'out', in a bare string
669  * format that cannot be parsed uniformly back into a datum but is easier for
670  * shell scripts, etc., to deal with. */
671 void
672 ovsdb_atom_to_bare(const union ovsdb_atom *atom, enum ovsdb_atomic_type type,
673                    struct ds *out)
674 {
675     if (type == OVSDB_TYPE_STRING) {
676         ds_put_cstr(out, atom->string);
677     } else {
678         ovsdb_atom_to_string(atom, type, out);
679     }
680 }
681
682 static struct ovsdb_error *
683 check_string_constraints(const char *s,
684                          const struct ovsdb_string_constraints *c)
685 {
686     size_t n_chars;
687     char *msg;
688
689     msg = utf8_validate(s, &n_chars);
690     if (msg) {
691         struct ovsdb_error *error;
692
693         error = ovsdb_error("constraint violation",
694                             "not a valid UTF-8 string: %s", msg);
695         free(msg);
696         return error;
697     }
698
699     if (n_chars < c->minLen) {
700         return ovsdb_error(
701             "constraint violation",
702             "\"%s\" length %zu is less than minimum allowed "
703             "length %u", s, n_chars, c->minLen);
704     } else if (n_chars > c->maxLen) {
705         return ovsdb_error(
706             "constraint violation",
707             "\"%s\" length %zu is greater than maximum allowed "
708             "length %u", s, n_chars, c->maxLen);
709     }
710
711     return NULL;
712 }
713
714 /* Checks whether 'atom' meets the constraints (if any) defined in 'base'.
715  * (base->type must specify 'atom''s type.)  Returns a null pointer if the
716  * constraints are met, otherwise an error that explains the violation.
717  *
718  * Checking UUID constraints is deferred to transaction commit time, so this
719  * function does nothing for UUID constraints. */
720 struct ovsdb_error *
721 ovsdb_atom_check_constraints(const union ovsdb_atom *atom,
722                              const struct ovsdb_base_type *base)
723 {
724     if (base->enum_
725         && ovsdb_datum_find_key(base->enum_, atom, base->type) == UINT_MAX) {
726         struct ovsdb_error *error;
727         struct ds actual = DS_EMPTY_INITIALIZER;
728         struct ds valid = DS_EMPTY_INITIALIZER;
729
730         ovsdb_atom_to_string(atom, base->type, &actual);
731         ovsdb_datum_to_string(base->enum_,
732                               ovsdb_base_type_get_enum_type(base->type),
733                               &valid);
734         error = ovsdb_error("constraint violation",
735                             "%s is not one of the allowed values (%s)",
736                             ds_cstr(&actual), ds_cstr(&valid));
737         ds_destroy(&actual);
738         ds_destroy(&valid);
739
740         return error;
741     }
742
743     switch (base->type) {
744     case OVSDB_TYPE_VOID:
745         NOT_REACHED();
746
747     case OVSDB_TYPE_INTEGER:
748         if (atom->integer >= base->u.integer.min
749             && atom->integer <= base->u.integer.max) {
750             return NULL;
751         } else if (base->u.integer.min != INT64_MIN) {
752             if (base->u.integer.max != INT64_MAX) {
753                 return ovsdb_error("constraint violation",
754                                    "%"PRId64" is not in the valid range "
755                                    "%"PRId64" to %"PRId64" (inclusive)",
756                                    atom->integer,
757                                    base->u.integer.min, base->u.integer.max);
758             } else {
759                 return ovsdb_error("constraint violation",
760                                    "%"PRId64" is less than minimum allowed "
761                                    "value %"PRId64,
762                                    atom->integer, base->u.integer.min);
763             }
764         } else {
765             return ovsdb_error("constraint violation",
766                                "%"PRId64" is greater than maximum allowed "
767                                "value %"PRId64,
768                                atom->integer, base->u.integer.max);
769         }
770         NOT_REACHED();
771
772     case OVSDB_TYPE_REAL:
773         if (atom->real >= base->u.real.min && atom->real <= base->u.real.max) {
774             return NULL;
775         } else if (base->u.real.min != -DBL_MAX) {
776             if (base->u.real.max != DBL_MAX) {
777                 return ovsdb_error("constraint violation",
778                                    "%.*g is not in the valid range "
779                                    "%.*g to %.*g (inclusive)",
780                                    DBL_DIG, atom->real,
781                                    DBL_DIG, base->u.real.min,
782                                    DBL_DIG, base->u.real.max);
783             } else {
784                 return ovsdb_error("constraint violation",
785                                    "%.*g is less than minimum allowed "
786                                    "value %.*g",
787                                    DBL_DIG, atom->real,
788                                    DBL_DIG, base->u.real.min);
789             }
790         } else {
791             return ovsdb_error("constraint violation",
792                                "%.*g is greater than maximum allowed "
793                                "value %.*g",
794                                DBL_DIG, atom->real,
795                                DBL_DIG, base->u.real.max);
796         }
797         NOT_REACHED();
798
799     case OVSDB_TYPE_BOOLEAN:
800         return NULL;
801
802     case OVSDB_TYPE_STRING:
803         return check_string_constraints(atom->string, &base->u.string);
804
805     case OVSDB_TYPE_UUID:
806         return NULL;
807
808     case OVSDB_N_TYPES:
809     default:
810         NOT_REACHED();
811     }
812 }
813 \f
814 static union ovsdb_atom *
815 alloc_default_atoms(enum ovsdb_atomic_type type, size_t n)
816 {
817     if (type != OVSDB_TYPE_VOID && n) {
818         union ovsdb_atom *atoms;
819         unsigned int i;
820
821         atoms = xmalloc(n * sizeof *atoms);
822         for (i = 0; i < n; i++) {
823             ovsdb_atom_init_default(&atoms[i], type);
824         }
825         return atoms;
826     } else {
827         /* Avoid wasting memory in the n == 0 case, because xmalloc(0) is
828          * treated as xmalloc(1). */
829         return NULL;
830     }
831 }
832
833 /* Initializes 'datum' as an empty datum.  (An empty datum can be treated as
834  * any type.) */
835 void
836 ovsdb_datum_init_empty(struct ovsdb_datum *datum)
837 {
838     datum->n = 0;
839     datum->keys = NULL;
840     datum->values = NULL;
841 }
842
843 /* Initializes 'datum' as a datum that has the default value for 'type'.
844  *
845  * The default value for a particular type is as defined in ovsdb/SPECS:
846  *
847  *    - If n_min is 0, then the default value is the empty set (or map).
848  *
849  *    - If n_min is 1, the default value is a single value or a single
850  *      key-value pair, whose key and value are the defaults for their
851  *      atomic types.  (See ovsdb_atom_init_default() for details.)
852  *
853  *    - n_min > 1 is invalid.  See ovsdb_type_is_valid().
854  */
855 void
856 ovsdb_datum_init_default(struct ovsdb_datum *datum,
857                          const struct ovsdb_type *type)
858 {
859     datum->n = type->n_min;
860     datum->keys = alloc_default_atoms(type->key.type, datum->n);
861     datum->values = alloc_default_atoms(type->value.type, datum->n);
862 }
863
864 /* Returns a read-only datum of the given 'type' that has the default value for
865  * 'type'.  The caller must not modify or free the returned datum.
866  *
867  * See ovsdb_datum_init_default() for an explanation of the default value of a
868  * datum. */
869 const struct ovsdb_datum *
870 ovsdb_datum_default(const struct ovsdb_type *type)
871 {
872     if (type->n_min == 0) {
873         static const struct ovsdb_datum empty;
874         return &empty;
875     } else if (type->n_min == 1) {
876         static struct ovsdb_datum default_data[OVSDB_N_TYPES][OVSDB_N_TYPES];
877         struct ovsdb_datum *d;
878         int kt = type->key.type;
879         int vt = type->value.type;
880
881         assert(ovsdb_type_is_valid(type));
882
883         d = &default_data[kt][vt];
884         if (!d->n) {
885             d->n = 1;
886             d->keys = (union ovsdb_atom *) ovsdb_atom_default(kt);
887             if (vt != OVSDB_TYPE_VOID) {
888                 d->values = (union ovsdb_atom *) ovsdb_atom_default(vt);
889             }
890         }
891         return d;
892     } else {
893         NOT_REACHED();
894     }
895 }
896
897 /* Returns true if 'datum', which must have the given 'type', has the default
898  * value for that type.
899  *
900  * See ovsdb_datum_init_default() for an explanation of the default value of a
901  * datum. */
902 bool
903 ovsdb_datum_is_default(const struct ovsdb_datum *datum,
904                        const struct ovsdb_type *type)
905 {
906     size_t i;
907
908     if (datum->n != type->n_min) {
909         return false;
910     }
911     for (i = 0; i < datum->n; i++) {
912         if (!ovsdb_atom_is_default(&datum->keys[i], type->key.type)) {
913             return false;
914         }
915         if (type->value.type != OVSDB_TYPE_VOID
916             && !ovsdb_atom_is_default(&datum->values[i], type->value.type)) {
917             return false;
918         }
919     }
920
921     return true;
922 }
923
924 static union ovsdb_atom *
925 clone_atoms(const union ovsdb_atom *old, enum ovsdb_atomic_type type, size_t n)
926 {
927     if (type != OVSDB_TYPE_VOID && n) {
928         union ovsdb_atom *new;
929         unsigned int i;
930
931         new = xmalloc(n * sizeof *new);
932         for (i = 0; i < n; i++) {
933             ovsdb_atom_clone(&new[i], &old[i], type);
934         }
935         return new;
936     } else {
937         /* Avoid wasting memory in the n == 0 case, because xmalloc(0) is
938          * treated as xmalloc(1). */
939         return NULL;
940     }
941 }
942
943 /* Initializes 'new' as a copy of 'old', with the given 'type'.
944  *
945  * The caller must eventually arrange for 'new' to be destroyed (with
946  * ovsdb_datum_destroy()). */
947 void
948 ovsdb_datum_clone(struct ovsdb_datum *new, const struct ovsdb_datum *old,
949                   const struct ovsdb_type *type)
950 {
951     unsigned int n = old->n;
952     new->n = n;
953     new->keys = clone_atoms(old->keys, type->key.type, n);
954     new->values = clone_atoms(old->values, type->value.type, n);
955 }
956
957 static void
958 free_data(enum ovsdb_atomic_type type,
959           union ovsdb_atom *atoms, size_t n_atoms)
960 {
961     if (ovsdb_atom_needs_destruction(type)) {
962         unsigned int i;
963         for (i = 0; i < n_atoms; i++) {
964             ovsdb_atom_destroy(&atoms[i], type);
965         }
966     }
967     free(atoms);
968 }
969
970 /* Frees the data owned by 'datum', which must have the given 'type'.
971  *
972  * This does not actually call free(datum).  If necessary, the caller must be
973  * responsible for that. */
974 void
975 ovsdb_datum_destroy(struct ovsdb_datum *datum, const struct ovsdb_type *type)
976 {
977     free_data(type->key.type, datum->keys, datum->n);
978     free_data(type->value.type, datum->values, datum->n);
979 }
980
981 /* Swaps the contents of 'a' and 'b', which need not have the same type. */
982 void
983 ovsdb_datum_swap(struct ovsdb_datum *a, struct ovsdb_datum *b)
984 {
985     struct ovsdb_datum tmp = *a;
986     *a = *b;
987     *b = tmp;
988 }
989
990 struct ovsdb_datum_sort_cbdata {
991     enum ovsdb_atomic_type key_type;
992     enum ovsdb_atomic_type value_type;
993     struct ovsdb_datum *datum;
994 };
995
996 static int
997 ovsdb_datum_sort_compare_cb(size_t a, size_t b, void *cbdata_)
998 {
999     struct ovsdb_datum_sort_cbdata *cbdata = cbdata_;
1000     int retval;
1001
1002     retval = ovsdb_atom_compare_3way(&cbdata->datum->keys[a],
1003                                      &cbdata->datum->keys[b],
1004                                      cbdata->key_type);
1005     if (retval || cbdata->value_type == OVSDB_TYPE_VOID) {
1006         return retval;
1007     }
1008
1009     return ovsdb_atom_compare_3way(&cbdata->datum->values[a],
1010                                    &cbdata->datum->values[b],
1011                                    cbdata->value_type);
1012 }
1013
1014 static void
1015 ovsdb_datum_sort_swap_cb(size_t a, size_t b, void *cbdata_)
1016 {
1017     struct ovsdb_datum_sort_cbdata *cbdata = cbdata_;
1018
1019     ovsdb_atom_swap(&cbdata->datum->keys[a], &cbdata->datum->keys[b]);
1020     if (cbdata->datum->values) {
1021         ovsdb_atom_swap(&cbdata->datum->values[a], &cbdata->datum->values[b]);
1022     }
1023 }
1024
1025 static void
1026 ovsdb_datum_sort__(struct ovsdb_datum *datum, enum ovsdb_atomic_type key_type,
1027                    enum ovsdb_atomic_type value_type)
1028 {
1029     struct ovsdb_datum_sort_cbdata cbdata;
1030
1031     cbdata.key_type = key_type;
1032     cbdata.value_type = value_type;
1033     cbdata.datum = datum;
1034     sort(datum->n, ovsdb_datum_sort_compare_cb, ovsdb_datum_sort_swap_cb,
1035          &cbdata);
1036 }
1037
1038 /* The keys in an ovsdb_datum must be unique and in sorted order.  Most
1039  * functions that modify an ovsdb_datum maintain these invariants.  For those
1040  * that don't, this function checks and restores these invariants for 'datum',
1041  * whose keys are of type 'key_type'.
1042  *
1043  * This function returns NULL if successful, otherwise an error message.  The
1044  * caller must free the returned error when it is no longer needed.  On error,
1045  * 'datum' is sorted but not unique. */
1046 struct ovsdb_error *
1047 ovsdb_datum_sort(struct ovsdb_datum *datum, enum ovsdb_atomic_type key_type)
1048 {
1049     size_t i;
1050
1051     if (datum->n < 2) {
1052         return NULL;
1053     }
1054
1055     ovsdb_datum_sort__(datum, key_type, OVSDB_TYPE_VOID);
1056
1057     for (i = 0; i < datum->n - 1; i++) {
1058         if (ovsdb_atom_equals(&datum->keys[i], &datum->keys[i + 1],
1059                               key_type)) {
1060             if (datum->values) {
1061                 return ovsdb_error(NULL, "map contains duplicate key");
1062             } else {
1063                 return ovsdb_error(NULL, "set contains duplicate");
1064             }
1065         }
1066     }
1067     return NULL;
1068 }
1069
1070 /* This function is the same as ovsdb_datum_sort(), except that the caller
1071  * knows that 'datum' is unique.  The operation therefore "cannot fail", so
1072  * this function assert-fails if it actually does. */
1073 void
1074 ovsdb_datum_sort_assert(struct ovsdb_datum *datum,
1075                         enum ovsdb_atomic_type key_type)
1076 {
1077     struct ovsdb_error *error = ovsdb_datum_sort(datum, key_type);
1078     if (error) {
1079         NOT_REACHED();
1080     }
1081 }
1082
1083 /* This is similar to ovsdb_datum_sort(), except that it drops duplicate keys
1084  * instead of reporting an error.  In a map type, the smallest value among a
1085  * group of duplicate pairs is retained and the others are dropped.
1086  *
1087  * Returns the number of keys (or pairs) that were dropped. */
1088 size_t
1089 ovsdb_datum_sort_unique(struct ovsdb_datum *datum,
1090                         enum ovsdb_atomic_type key_type,
1091                         enum ovsdb_atomic_type value_type)
1092 {
1093     size_t src, dst;
1094
1095     if (datum->n < 2) {
1096         return 0;
1097     }
1098
1099     ovsdb_datum_sort__(datum, key_type, value_type);
1100
1101     dst = 1;
1102     for (src = 1; src < datum->n; src++) {
1103         if (ovsdb_atom_equals(&datum->keys[src], &datum->keys[dst - 1],
1104                               key_type)) {
1105             ovsdb_atom_destroy(&datum->keys[src], key_type);
1106             if (value_type != OVSDB_TYPE_VOID) {
1107                 ovsdb_atom_destroy(&datum->values[src], value_type);
1108             }
1109         } else {
1110             if (src != dst) {
1111                 datum->keys[dst] = datum->keys[src];
1112                 if (value_type != OVSDB_TYPE_VOID) {
1113                     datum->values[dst] = datum->values[src];
1114                 }
1115             }
1116             dst++;
1117         }
1118     }
1119     datum->n = dst;
1120     return datum->n - src;
1121 }
1122
1123 /* Checks that each of the atoms in 'datum' conforms to the constraints
1124  * specified by its 'type'.  Returns an error if a constraint is violated,
1125  * otherwise a null pointer.
1126  *
1127  * This function is not commonly useful because the most ordinary way to obtain
1128  * a datum is ultimately via ovsdb_atom_from_string() or
1129  * ovsdb_atom_from_json(), which check constraints themselves. */
1130 struct ovsdb_error *
1131 ovsdb_datum_check_constraints(const struct ovsdb_datum *datum,
1132                               const struct ovsdb_type *type)
1133 {
1134     struct ovsdb_error *error;
1135     unsigned int i;
1136
1137     for (i = 0; i < datum->n; i++) {
1138         error = ovsdb_atom_check_constraints(&datum->keys[i], &type->key);
1139         if (error) {
1140             return error;
1141         }
1142     }
1143
1144     if (type->value.type != OVSDB_TYPE_VOID) {
1145         for (i = 0; i < datum->n; i++) {
1146             error = ovsdb_atom_check_constraints(&datum->values[i],
1147                                                  &type->value);
1148             if (error) {
1149                 return error;
1150             }
1151         }
1152     }
1153
1154     return NULL;
1155 }
1156
1157 static struct ovsdb_error *
1158 ovsdb_datum_from_json__(struct ovsdb_datum *datum,
1159                         const struct ovsdb_type *type,
1160                         const struct json *json,
1161                         struct ovsdb_symbol_table *symtab)
1162 {
1163     struct ovsdb_error *error;
1164
1165     if (ovsdb_type_is_map(type)
1166         || (json->type == JSON_ARRAY
1167             && json->u.array.n > 0
1168             && json->u.array.elems[0]->type == JSON_STRING
1169             && !strcmp(json->u.array.elems[0]->u.string, "set"))) {
1170         bool is_map = ovsdb_type_is_map(type);
1171         const char *class = is_map ? "map" : "set";
1172         const struct json *inner;
1173         unsigned int i;
1174         size_t n;
1175
1176         error = unwrap_json(json, class, JSON_ARRAY, &inner);
1177         if (error) {
1178             return error;
1179         }
1180
1181         n = inner->u.array.n;
1182         if (n < type->n_min || n > type->n_max) {
1183             return ovsdb_syntax_error(json, NULL, "%s must have %u to "
1184                                       "%u members but %zu are present",
1185                                       class, type->n_min, type->n_max, n);
1186         }
1187
1188         datum->n = 0;
1189         datum->keys = xmalloc(n * sizeof *datum->keys);
1190         datum->values = is_map ? xmalloc(n * sizeof *datum->values) : NULL;
1191         for (i = 0; i < n; i++) {
1192             const struct json *element = inner->u.array.elems[i];
1193             const struct json *key = NULL;
1194             const struct json *value = NULL;
1195
1196             if (!is_map) {
1197                 key = element;
1198             } else {
1199                 error = parse_json_pair(element, &key, &value);
1200                 if (error) {
1201                     goto error;
1202                 }
1203             }
1204
1205             error = ovsdb_atom_from_json(&datum->keys[i], &type->key,
1206                                          key, symtab);
1207             if (error) {
1208                 goto error;
1209             }
1210
1211             if (is_map) {
1212                 error = ovsdb_atom_from_json(&datum->values[i],
1213                                              &type->value, value, symtab);
1214                 if (error) {
1215                     ovsdb_atom_destroy(&datum->keys[i], type->key.type);
1216                     goto error;
1217                 }
1218             }
1219
1220             datum->n++;
1221         }
1222         return NULL;
1223
1224     error:
1225         ovsdb_datum_destroy(datum, type);
1226         return error;
1227     } else {
1228         datum->n = 1;
1229         datum->keys = xmalloc(sizeof *datum->keys);
1230         datum->values = NULL;
1231
1232         error = ovsdb_atom_from_json(&datum->keys[0], &type->key,
1233                                      json, symtab);
1234         if (error) {
1235             free(datum->keys);
1236         }
1237         return error;
1238     }
1239 }
1240
1241 /* Parses 'json' as a datum of the type described by 'type'.  If successful,
1242  * returns NULL and initializes 'datum' with the parsed datum.  On failure,
1243  * returns an error and the contents of 'datum' are indeterminate.  The caller
1244  * is responsible for freeing the error or the datum that is returned.
1245  *
1246  * Violations of constraints expressed by 'type' are treated as errors.
1247  *
1248  * If 'symtab' is nonnull, then named UUIDs in 'symtab' are accepted.  Refer to
1249  * ovsdb/SPECS for information about this, and for the syntax that this
1250  * function accepts. */
1251 struct ovsdb_error *
1252 ovsdb_datum_from_json(struct ovsdb_datum *datum,
1253                       const struct ovsdb_type *type,
1254                       const struct json *json,
1255                       struct ovsdb_symbol_table *symtab)
1256 {
1257     struct ovsdb_error *error;
1258
1259     error = ovsdb_datum_from_json__(datum, type, json, symtab);
1260     if (error) {
1261         return error;
1262     }
1263
1264     error = ovsdb_datum_sort(datum, type->key.type);
1265     if (error) {
1266         ovsdb_datum_destroy(datum, type);
1267     }
1268     return error;
1269 }
1270
1271 /* Converts 'datum', of the specified 'type', to JSON format, and returns the
1272  * JSON.  The caller is responsible for freeing the returned JSON.
1273  *
1274  * 'type' constraints on datum->n are ignored.
1275  *
1276  * Refer to ovsdb/SPECS for the format of the JSON that this function
1277  * produces. */
1278 struct json *
1279 ovsdb_datum_to_json(const struct ovsdb_datum *datum,
1280                     const struct ovsdb_type *type)
1281 {
1282     if (ovsdb_type_is_map(type)) {
1283         struct json **elems;
1284         size_t i;
1285
1286         elems = xmalloc(datum->n * sizeof *elems);
1287         for (i = 0; i < datum->n; i++) {
1288             elems[i] = json_array_create_2(
1289                 ovsdb_atom_to_json(&datum->keys[i], type->key.type),
1290                 ovsdb_atom_to_json(&datum->values[i], type->value.type));
1291         }
1292
1293         return wrap_json("map", json_array_create(elems, datum->n));
1294     } else if (datum->n == 1) {
1295         return ovsdb_atom_to_json(&datum->keys[0], type->key.type);
1296     } else {
1297         struct json **elems;
1298         size_t i;
1299
1300         elems = xmalloc(datum->n * sizeof *elems);
1301         for (i = 0; i < datum->n; i++) {
1302             elems[i] = ovsdb_atom_to_json(&datum->keys[i], type->key.type);
1303         }
1304
1305         return wrap_json("set", json_array_create(elems, datum->n));
1306     }
1307 }
1308
1309 static const char *
1310 skip_spaces(const char *p)
1311 {
1312     while (isspace((unsigned char) *p)) {
1313         p++;
1314     }
1315     return p;
1316 }
1317
1318 static char *
1319 parse_atom_token(const char **s, const struct ovsdb_base_type *base,
1320                  union ovsdb_atom *atom, struct ovsdb_symbol_table *symtab)
1321 {
1322     char *token, *error;
1323
1324     error = ovsdb_token_parse(s, &token);
1325     if (!error) {
1326         error = ovsdb_atom_from_string(atom, base, token, symtab);
1327         free(token);
1328     }
1329     return error;
1330 }
1331
1332 static char *
1333 parse_key_value(const char **s, const struct ovsdb_type *type,
1334                 union ovsdb_atom *key, union ovsdb_atom *value,
1335                 struct ovsdb_symbol_table *symtab)
1336 {
1337     const char *start = *s;
1338     char *error;
1339
1340     error = parse_atom_token(s, &type->key, key, symtab);
1341     if (!error && type->value.type != OVSDB_TYPE_VOID) {
1342         *s = skip_spaces(*s);
1343         if (**s == '=') {
1344             (*s)++;
1345             *s = skip_spaces(*s);
1346             error = parse_atom_token(s, &type->value, value, symtab);
1347         } else {
1348             error = xasprintf("%s: syntax error at \"%c\" expecting \"=\"",
1349                               start, **s);
1350         }
1351         if (error) {
1352             ovsdb_atom_destroy(key, type->key.type);
1353         }
1354     }
1355     return error;
1356 }
1357
1358 static void
1359 free_key_value(const struct ovsdb_type *type,
1360                union ovsdb_atom *key, union ovsdb_atom *value)
1361 {
1362     ovsdb_atom_destroy(key, type->key.type);
1363     if (type->value.type != OVSDB_TYPE_VOID) {
1364         ovsdb_atom_destroy(value, type->value.type);
1365     }
1366 }
1367
1368 /* Initializes 'datum' as a datum of the given 'type', parsing its contents
1369  * from 's'.  The format of 's' is a series of space or comma separated atoms
1370  * or, for a map, '='-delimited pairs of atoms.  Each atom must in a format
1371  * acceptable to ovsdb_atom_from_string().  Optionally, a set may be enclosed
1372  * in "[]" or a map in "{}"; for an empty set or map these punctuators are
1373  * required.
1374  *
1375  * Optionally, a symbol table may be supplied as 'symtab'.  It is passed to
1376  * ovsdb_atom_to_string(). */
1377 char *
1378 ovsdb_datum_from_string(struct ovsdb_datum *datum,
1379                         const struct ovsdb_type *type, const char *s,
1380                         struct ovsdb_symbol_table *symtab)
1381 {
1382     bool is_map = ovsdb_type_is_map(type);
1383     struct ovsdb_error *dberror;
1384     const char *p;
1385     int end_delim;
1386     char *error;
1387
1388     ovsdb_datum_init_empty(datum);
1389
1390     /* Swallow a leading delimiter if there is one. */
1391     p = skip_spaces(s);
1392     if (*p == (is_map ? '{' : '[')) {
1393         end_delim = is_map ? '}' : ']';
1394         p = skip_spaces(p + 1);
1395     } else if (!*p) {
1396         if (is_map) {
1397             return xstrdup("use \"{}\" to specify the empty map");
1398         } else {
1399             return xstrdup("use \"[]\" to specify the empty set");
1400         }
1401     } else {
1402         end_delim = 0;
1403     }
1404
1405     while (*p && *p != end_delim) {
1406         union ovsdb_atom key, value;
1407
1408         if (ovsdb_token_is_delim(*p)) {
1409             char *type_str = ovsdb_type_to_english(type);
1410             error = xasprintf("%s: unexpected \"%c\" parsing %s",
1411                               s, *p, type_str);
1412             free(type_str);
1413             goto error;
1414         }
1415
1416         /* Add to datum. */
1417         error = parse_key_value(&p, type, &key, &value, symtab);
1418         if (error) {
1419             goto error;
1420         }
1421         ovsdb_datum_add_unsafe(datum, &key, &value, type);
1422         free_key_value(type, &key, &value);
1423
1424         /* Skip optional white space and comma. */
1425         p = skip_spaces(p);
1426         if (*p == ',') {
1427             p = skip_spaces(p + 1);
1428         }
1429     }
1430
1431     if (*p != end_delim) {
1432         error = xasprintf("%s: missing \"%c\" at end of data", s, end_delim);
1433         goto error;
1434     }
1435     if (end_delim) {
1436         p = skip_spaces(p + 1);
1437         if (*p) {
1438             error = xasprintf("%s: trailing garbage after \"%c\"",
1439                               s, end_delim);
1440             goto error;
1441         }
1442     }
1443
1444     if (datum->n < type->n_min) {
1445         error = xasprintf("%s: %u %s specified but the minimum number is %u",
1446                           s, datum->n, is_map ? "pair(s)" : "value(s)",
1447                           type->n_min);
1448         goto error;
1449     } else if (datum->n > type->n_max) {
1450         error = xasprintf("%s: %u %s specified but the maximum number is %u",
1451                           s, datum->n, is_map ? "pair(s)" : "value(s)",
1452             type->n_max);
1453         goto error;
1454     }
1455
1456     dberror = ovsdb_datum_sort(datum, type->key.type);
1457     if (dberror) {
1458         ovsdb_error_destroy(dberror);
1459         if (ovsdb_type_is_map(type)) {
1460             error = xasprintf("%s: map contains duplicate key", s);
1461         } else {
1462             error = xasprintf("%s: set contains duplicate value", s);
1463         }
1464         goto error;
1465     }
1466
1467     return NULL;
1468
1469 error:
1470     ovsdb_datum_destroy(datum, type);
1471     ovsdb_datum_init_empty(datum);
1472     return error;
1473 }
1474
1475 /* Appends to 'out' the 'datum' (with the given 'type') in a format acceptable
1476  * to ovsdb_datum_from_string(). */
1477 void
1478 ovsdb_datum_to_string(const struct ovsdb_datum *datum,
1479                       const struct ovsdb_type *type, struct ds *out)
1480 {
1481     bool is_map = ovsdb_type_is_map(type);
1482     size_t i;
1483
1484     if (type->n_max > 1 || !datum->n) {
1485         ds_put_char(out, is_map ? '{' : '[');
1486     }
1487     for (i = 0; i < datum->n; i++) {
1488         if (i > 0) {
1489             ds_put_cstr(out, ", ");
1490         }
1491
1492         ovsdb_atom_to_string(&datum->keys[i], type->key.type, out);
1493         if (is_map) {
1494             ds_put_char(out, '=');
1495             ovsdb_atom_to_string(&datum->values[i], type->value.type, out);
1496         }
1497     }
1498     if (type->n_max > 1 || !datum->n) {
1499         ds_put_char(out, is_map ? '}' : ']');
1500     }
1501 }
1502
1503 /* Appends to 'out' the 'datum' (with the given 'type') in a bare string format
1504  * that cannot be parsed uniformly back into a datum but is easier for shell
1505  * scripts, etc., to deal with. */
1506 void
1507 ovsdb_datum_to_bare(const struct ovsdb_datum *datum,
1508                     const struct ovsdb_type *type, struct ds *out)
1509 {
1510     bool is_map = ovsdb_type_is_map(type);
1511     size_t i;
1512
1513     for (i = 0; i < datum->n; i++) {
1514         if (i > 0) {
1515             ds_put_cstr(out, " ");
1516         }
1517
1518         ovsdb_atom_to_bare(&datum->keys[i], type->key.type, out);
1519         if (is_map) {
1520             ds_put_char(out, '=');
1521             ovsdb_atom_to_bare(&datum->values[i], type->value.type, out);
1522         }
1523     }
1524 }
1525
1526 /* Initializes 'datum' as a string-to-string map whose contents are taken from
1527  * 'sh'.  Destroys 'sh'. */
1528 void
1529 ovsdb_datum_from_shash(struct ovsdb_datum *datum, struct shash *sh)
1530 {
1531     struct shash_node *node, *next;
1532     size_t i;
1533
1534     datum->n = shash_count(sh);
1535     datum->keys = xmalloc(datum->n * sizeof *datum->keys);
1536     datum->values = xmalloc(datum->n * sizeof *datum->values);
1537
1538     i = 0;
1539     SHASH_FOR_EACH_SAFE (node, next, sh) {
1540         datum->keys[i].string = node->name;
1541         datum->values[i].string = node->data;
1542         shash_steal(sh, node);
1543         i++;
1544     }
1545     assert(i == datum->n);
1546
1547     shash_destroy(sh);
1548     ovsdb_datum_sort_unique(datum, OVSDB_TYPE_STRING, OVSDB_TYPE_STRING);
1549 }
1550
1551 static uint32_t
1552 hash_atoms(enum ovsdb_atomic_type type, const union ovsdb_atom *atoms,
1553            unsigned int n, uint32_t basis)
1554 {
1555     if (type != OVSDB_TYPE_VOID) {
1556         unsigned int i;
1557
1558         for (i = 0; i < n; i++) {
1559             basis = ovsdb_atom_hash(&atoms[i], type, basis);
1560         }
1561     }
1562     return basis;
1563 }
1564
1565 uint32_t
1566 ovsdb_datum_hash(const struct ovsdb_datum *datum,
1567                  const struct ovsdb_type *type, uint32_t basis)
1568 {
1569     basis = hash_atoms(type->key.type, datum->keys, datum->n, basis);
1570     basis ^= (type->key.type << 24) | (type->value.type << 16) | datum->n;
1571     basis = hash_atoms(type->value.type, datum->values, datum->n, basis);
1572     return basis;
1573 }
1574
1575 static int
1576 atom_arrays_compare_3way(const union ovsdb_atom *a,
1577                          const union ovsdb_atom *b,
1578                          enum ovsdb_atomic_type type,
1579                          size_t n)
1580 {
1581     unsigned int i;
1582
1583     for (i = 0; i < n; i++) {
1584         int cmp = ovsdb_atom_compare_3way(&a[i], &b[i], type);
1585         if (cmp) {
1586             return cmp;
1587         }
1588     }
1589
1590     return 0;
1591 }
1592
1593 bool
1594 ovsdb_datum_equals(const struct ovsdb_datum *a,
1595                    const struct ovsdb_datum *b,
1596                    const struct ovsdb_type *type)
1597 {
1598     return !ovsdb_datum_compare_3way(a, b, type);
1599 }
1600
1601 int
1602 ovsdb_datum_compare_3way(const struct ovsdb_datum *a,
1603                          const struct ovsdb_datum *b,
1604                          const struct ovsdb_type *type)
1605 {
1606     int cmp;
1607
1608     if (a->n != b->n) {
1609         return a->n < b->n ? -1 : 1;
1610     }
1611
1612     cmp = atom_arrays_compare_3way(a->keys, b->keys, type->key.type, a->n);
1613     if (cmp) {
1614         return cmp;
1615     }
1616
1617     return (type->value.type == OVSDB_TYPE_VOID ? 0
1618             : atom_arrays_compare_3way(a->values, b->values, type->value.type,
1619                                        a->n));
1620 }
1621
1622 /* If 'key' is one of the keys in 'datum', returns its index within 'datum',
1623  * otherwise UINT_MAX.  'key.type' must be the type of the atoms stored in the
1624  * 'keys' array in 'datum'.
1625  */
1626 unsigned int
1627 ovsdb_datum_find_key(const struct ovsdb_datum *datum,
1628                      const union ovsdb_atom *key,
1629                      enum ovsdb_atomic_type key_type)
1630 {
1631     unsigned int low = 0;
1632     unsigned int high = datum->n;
1633     while (low < high) {
1634         unsigned int idx = (low + high) / 2;
1635         int cmp = ovsdb_atom_compare_3way(key, &datum->keys[idx], key_type);
1636         if (cmp < 0) {
1637             high = idx;
1638         } else if (cmp > 0) {
1639             low = idx + 1;
1640         } else {
1641             return idx;
1642         }
1643     }
1644     return UINT_MAX;
1645 }
1646
1647 /* If 'key' and 'value' is one of the key-value pairs in 'datum', returns its
1648  * index within 'datum', otherwise UINT_MAX.  'key.type' must be the type of
1649  * the atoms stored in the 'keys' array in 'datum'.  'value_type' may be the
1650  * type of the 'values' atoms or OVSDB_TYPE_VOID to compare only keys.
1651  */
1652 unsigned int
1653 ovsdb_datum_find_key_value(const struct ovsdb_datum *datum,
1654                            const union ovsdb_atom *key,
1655                            enum ovsdb_atomic_type key_type,
1656                            const union ovsdb_atom *value,
1657                            enum ovsdb_atomic_type value_type)
1658 {
1659     unsigned int idx = ovsdb_datum_find_key(datum, key, key_type);
1660     if (idx != UINT_MAX
1661         && value_type != OVSDB_TYPE_VOID
1662         && !ovsdb_atom_equals(&datum->values[idx], value, value_type)) {
1663         idx = UINT_MAX;
1664     }
1665     return idx;
1666 }
1667
1668 /* If atom 'i' in 'a' is also in 'b', returns its index in 'b', otherwise
1669  * UINT_MAX.  'type' must be the type of 'a' and 'b', except that
1670  * type->value.type may be set to OVSDB_TYPE_VOID to compare keys but not
1671  * values. */
1672 static unsigned int
1673 ovsdb_datum_find(const struct ovsdb_datum *a, int i,
1674                  const struct ovsdb_datum *b,
1675                  const struct ovsdb_type *type)
1676 {
1677     return ovsdb_datum_find_key_value(b,
1678                                       &a->keys[i], type->key.type,
1679                                       a->values ? &a->values[i] : NULL,
1680                                       type->value.type);
1681 }
1682
1683 /* Returns true if every element in 'a' is also in 'b', false otherwise. */
1684 bool
1685 ovsdb_datum_includes_all(const struct ovsdb_datum *a,
1686                          const struct ovsdb_datum *b,
1687                          const struct ovsdb_type *type)
1688 {
1689     size_t i;
1690
1691     if (a->n > b->n) {
1692         return false;
1693     }
1694     for (i = 0; i < a->n; i++) {
1695         if (ovsdb_datum_find(a, i, b, type) == UINT_MAX) {
1696             return false;
1697         }
1698     }
1699     return true;
1700 }
1701
1702 /* Returns true if no element in 'a' is also in 'b', false otherwise. */
1703 bool
1704 ovsdb_datum_excludes_all(const struct ovsdb_datum *a,
1705                          const struct ovsdb_datum *b,
1706                          const struct ovsdb_type *type)
1707 {
1708     size_t i;
1709
1710     for (i = 0; i < a->n; i++) {
1711         if (ovsdb_datum_find(a, i, b, type) != UINT_MAX) {
1712             return false;
1713         }
1714     }
1715     return true;
1716 }
1717
1718 static void
1719 ovsdb_datum_reallocate(struct ovsdb_datum *a, const struct ovsdb_type *type,
1720                        unsigned int capacity)
1721 {
1722     a->keys = xrealloc(a->keys, capacity * sizeof *a->keys);
1723     if (type->value.type != OVSDB_TYPE_VOID) {
1724         a->values = xrealloc(a->values, capacity * sizeof *a->values);
1725     }
1726 }
1727
1728 /* Removes the element with index 'idx' from 'datum', which has type 'type'.
1729  * If 'idx' is not the last element in 'datum', then the removed element is
1730  * replaced by the (former) last element.
1731  *
1732  * This function does not maintain ovsdb_datum invariants.  Use
1733  * ovsdb_datum_sort() to check and restore these invariants. */
1734 void
1735 ovsdb_datum_remove_unsafe(struct ovsdb_datum *datum, size_t idx,
1736                           const struct ovsdb_type *type)
1737 {
1738     ovsdb_atom_destroy(&datum->keys[idx], type->key.type);
1739     datum->keys[idx] = datum->keys[datum->n - 1];
1740     if (type->value.type != OVSDB_TYPE_VOID) {
1741         ovsdb_atom_destroy(&datum->values[idx], type->value.type);
1742         datum->values[idx] = datum->values[datum->n - 1];
1743     }
1744     datum->n--;
1745 }
1746
1747 /* Adds the element with the given 'key' and 'value' to 'datum', which must
1748  * have the specified 'type'.
1749  *
1750  * This function always allocates memory, so it is not an efficient way to add
1751  * a number of elements to a datum.
1752  *
1753  * This function does not maintain ovsdb_datum invariants.  Use
1754  * ovsdb_datum_sort() to check and restore these invariants.  (But a datum with
1755  * 0 or 1 elements cannot violate the invariants anyhow.) */
1756 void
1757 ovsdb_datum_add_unsafe(struct ovsdb_datum *datum,
1758                        const union ovsdb_atom *key,
1759                        const union ovsdb_atom *value,
1760                        const struct ovsdb_type *type)
1761 {
1762     size_t idx = datum->n++;
1763     datum->keys = xrealloc(datum->keys, datum->n * sizeof *datum->keys);
1764     ovsdb_atom_clone(&datum->keys[idx], key, type->key.type);
1765     if (type->value.type != OVSDB_TYPE_VOID) {
1766         datum->values = xrealloc(datum->values,
1767                                  datum->n * sizeof *datum->values);
1768         ovsdb_atom_clone(&datum->values[idx], value, type->value.type);
1769     }
1770 }
1771
1772 void
1773 ovsdb_datum_union(struct ovsdb_datum *a, const struct ovsdb_datum *b,
1774                   const struct ovsdb_type *type, bool replace)
1775 {
1776     unsigned int n;
1777     size_t bi;
1778
1779     n = a->n;
1780     for (bi = 0; bi < b->n; bi++) {
1781         unsigned int ai;
1782
1783         ai = ovsdb_datum_find_key(a, &b->keys[bi], type->key.type);
1784         if (ai == UINT_MAX) {
1785             if (n == a->n) {
1786                 ovsdb_datum_reallocate(a, type, a->n + (b->n - bi));
1787             }
1788             ovsdb_atom_clone(&a->keys[n], &b->keys[bi], type->key.type);
1789             if (type->value.type != OVSDB_TYPE_VOID) {
1790                 ovsdb_atom_clone(&a->values[n], &b->values[bi],
1791                                  type->value.type);
1792             }
1793             n++;
1794         } else if (replace && type->value.type != OVSDB_TYPE_VOID) {
1795             ovsdb_atom_destroy(&a->values[ai], type->value.type);
1796             ovsdb_atom_clone(&a->values[ai], &b->values[bi],
1797                              type->value.type);
1798         }
1799     }
1800     if (n != a->n) {
1801         struct ovsdb_error *error;
1802         a->n = n;
1803         error = ovsdb_datum_sort(a, type->key.type);
1804         assert(!error);
1805     }
1806 }
1807
1808 void
1809 ovsdb_datum_subtract(struct ovsdb_datum *a, const struct ovsdb_type *a_type,
1810                      const struct ovsdb_datum *b,
1811                      const struct ovsdb_type *b_type)
1812 {
1813     bool changed = false;
1814     size_t i;
1815
1816     assert(a_type->key.type == b_type->key.type);
1817     assert(a_type->value.type == b_type->value.type
1818            || b_type->value.type == OVSDB_TYPE_VOID);
1819
1820     /* XXX The big-O of this could easily be improved. */
1821     for (i = 0; i < a->n; ) {
1822         unsigned int idx = ovsdb_datum_find(a, i, b, b_type);
1823         if (idx != UINT_MAX) {
1824             changed = true;
1825             ovsdb_datum_remove_unsafe(a, i, a_type);
1826         } else {
1827             i++;
1828         }
1829     }
1830     if (changed) {
1831         ovsdb_datum_sort_assert(a, a_type->key.type);
1832     }
1833 }
1834 \f
1835 struct ovsdb_symbol_table *
1836 ovsdb_symbol_table_create(void)
1837 {
1838     struct ovsdb_symbol_table *symtab = xmalloc(sizeof *symtab);
1839     shash_init(&symtab->sh);
1840     return symtab;
1841 }
1842
1843 void
1844 ovsdb_symbol_table_destroy(struct ovsdb_symbol_table *symtab)
1845 {
1846     if (symtab) {
1847         shash_destroy_free_data(&symtab->sh);
1848         free(symtab);
1849     }
1850 }
1851
1852 struct ovsdb_symbol *
1853 ovsdb_symbol_table_get(const struct ovsdb_symbol_table *symtab,
1854                        const char *name)
1855 {
1856     return shash_find_data(&symtab->sh, name);
1857 }
1858
1859 struct ovsdb_symbol *
1860 ovsdb_symbol_table_put(struct ovsdb_symbol_table *symtab, const char *name,
1861                        const struct uuid *uuid, bool created)
1862 {
1863     struct ovsdb_symbol *symbol;
1864
1865     assert(!ovsdb_symbol_table_get(symtab, name));
1866     symbol = xmalloc(sizeof *symbol);
1867     symbol->uuid = *uuid;
1868     symbol->created = created;
1869     symbol->strong_ref = false;
1870     symbol->weak_ref = false;
1871     shash_add(&symtab->sh, name, symbol);
1872     return symbol;
1873 }
1874
1875 struct ovsdb_symbol *
1876 ovsdb_symbol_table_insert(struct ovsdb_symbol_table *symtab,
1877                           const char *name)
1878 {
1879     struct ovsdb_symbol *symbol;
1880
1881     symbol = ovsdb_symbol_table_get(symtab, name);
1882     if (!symbol) {
1883         struct uuid uuid;
1884
1885         uuid_generate(&uuid);
1886         symbol = ovsdb_symbol_table_put(symtab, name, &uuid, false);
1887     }
1888     return symbol;
1889 }
1890 \f
1891 /* Extracts a token from the beginning of 's' and returns a pointer just after
1892  * the token.  Stores the token itself into '*outp', which the caller is
1893  * responsible for freeing (with free()).
1894  *
1895  * If 's[0]' is a delimiter, the returned token is the empty string.
1896  *
1897  * A token extends from 's' to the first delimiter, as defined by
1898  * ovsdb_token_is_delim(), or until the end of the string.  A delimiter can be
1899  * escaped with a backslash, in which case the backslash does not appear in the
1900  * output.  Double quotes also cause delimiters to be ignored, but the double
1901  * quotes are retained in the output.  (Backslashes inside double quotes are
1902  * not removed, either.)
1903  */
1904 char *
1905 ovsdb_token_parse(const char **s, char **outp)
1906 {
1907     const char *p;
1908     struct ds out;
1909     bool in_quotes;
1910     char *error;
1911
1912     ds_init(&out);
1913     in_quotes = false;
1914     for (p = *s; *p != '\0'; ) {
1915         int c = *p++;
1916         if (c == '\\') {
1917             if (in_quotes) {
1918                 ds_put_char(&out, '\\');
1919             }
1920             if (!*p) {
1921                 error = xasprintf("%s: backslash at end of argument", *s);
1922                 goto error;
1923             }
1924             ds_put_char(&out, *p++);
1925         } else if (!in_quotes && ovsdb_token_is_delim(c)) {
1926             p--;
1927             break;
1928         } else {
1929             ds_put_char(&out, c);
1930             if (c == '"') {
1931                 in_quotes = !in_quotes;
1932             }
1933         }
1934     }
1935     if (in_quotes) {
1936         error = xasprintf("%s: quoted string extends past end of argument",
1937                           *s);
1938         goto error;
1939     }
1940     *outp = ds_cstr(&out);
1941     *s = p;
1942     return NULL;
1943
1944 error:
1945     ds_destroy(&out);
1946     *outp = NULL;
1947     return error;
1948 }
1949
1950 /* Returns true if 'c' delimits tokens, or if 'c' is 0, and false otherwise. */
1951 bool
1952 ovsdb_token_is_delim(unsigned char c)
1953 {
1954     return strchr(":=, []{}!<>", c) != NULL;
1955 }