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