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