ovsdb: Add simple constraints.
[cascardo/ovs.git] / lib / ovsdb-data.c
1 /* Copyright (c) 2009, 2010 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 "json.h"
30 #include "shash.h"
31 #include "sort.h"
32 #include "unicode.h"
33
34 static struct json *
35 wrap_json(const char *name, struct json *wrapped)
36 {
37     return json_array_create_2(json_string_create(name), wrapped);
38 }
39
40 void
41 ovsdb_atom_init_default(union ovsdb_atom *atom, enum ovsdb_atomic_type type)
42 {
43     switch (type) {
44     case OVSDB_TYPE_VOID:
45         NOT_REACHED();
46
47     case OVSDB_TYPE_INTEGER:
48         atom->integer = 0;
49         break;
50
51     case OVSDB_TYPE_REAL:
52         atom->real = 0.0;
53         break;
54
55     case OVSDB_TYPE_BOOLEAN:
56         atom->boolean = false;
57         break;
58
59     case OVSDB_TYPE_STRING:
60         atom->string = xmemdup("", 1);
61         break;
62
63     case OVSDB_TYPE_UUID:
64         uuid_zero(&atom->uuid);
65         break;
66
67     case OVSDB_N_TYPES:
68     default:
69         NOT_REACHED();
70     }
71 }
72
73 bool
74 ovsdb_atom_is_default(const union ovsdb_atom *atom,
75                       enum ovsdb_atomic_type type)
76 {
77     switch (type) {
78     case OVSDB_TYPE_VOID:
79         NOT_REACHED();
80
81     case OVSDB_TYPE_INTEGER:
82         return atom->integer == 0;
83
84     case OVSDB_TYPE_REAL:
85         return atom->real == 0.0;
86
87     case OVSDB_TYPE_BOOLEAN:
88         return atom->boolean == false;
89
90     case OVSDB_TYPE_STRING:
91         return atom->string[0] == '\0';
92
93     case OVSDB_TYPE_UUID:
94         return uuid_is_zero(&atom->uuid);
95
96     case OVSDB_N_TYPES:
97     default:
98         NOT_REACHED();
99     }
100 }
101
102 void
103 ovsdb_atom_clone(union ovsdb_atom *new, const union ovsdb_atom *old,
104                  enum ovsdb_atomic_type type)
105 {
106     switch (type) {
107     case OVSDB_TYPE_VOID:
108         NOT_REACHED();
109
110     case OVSDB_TYPE_INTEGER:
111         new->integer = old->integer;
112         break;
113
114     case OVSDB_TYPE_REAL:
115         new->real = old->real;
116         break;
117
118     case OVSDB_TYPE_BOOLEAN:
119         new->boolean = old->boolean;
120         break;
121
122     case OVSDB_TYPE_STRING:
123         new->string = xstrdup(old->string);
124         break;
125
126     case OVSDB_TYPE_UUID:
127         new->uuid = old->uuid;
128         break;
129
130     case OVSDB_N_TYPES:
131     default:
132         NOT_REACHED();
133     }
134 }
135
136 void
137 ovsdb_atom_swap(union ovsdb_atom *a, union ovsdb_atom *b)
138 {
139     union ovsdb_atom tmp = *a;
140     *a = *b;
141     *b = tmp;
142 }
143
144 uint32_t
145 ovsdb_atom_hash(const union ovsdb_atom *atom, enum ovsdb_atomic_type type,
146                 uint32_t basis)
147 {
148     switch (type) {
149     case OVSDB_TYPE_VOID:
150         NOT_REACHED();
151
152     case OVSDB_TYPE_INTEGER:
153         return hash_int(atom->integer, basis);
154
155     case OVSDB_TYPE_REAL:
156         return hash_double(atom->real, basis);
157
158     case OVSDB_TYPE_BOOLEAN:
159         return hash_boolean(atom->boolean, basis);
160
161     case OVSDB_TYPE_STRING:
162         return hash_string(atom->string, basis);
163
164     case OVSDB_TYPE_UUID:
165         return hash_int(uuid_hash(&atom->uuid), basis);
166
167     case OVSDB_N_TYPES:
168     default:
169         NOT_REACHED();
170     }
171 }
172
173 int
174 ovsdb_atom_compare_3way(const union ovsdb_atom *a,
175                         const union ovsdb_atom *b,
176                         enum ovsdb_atomic_type type)
177 {
178     switch (type) {
179     case OVSDB_TYPE_VOID:
180         NOT_REACHED();
181
182     case OVSDB_TYPE_INTEGER:
183         return a->integer < b->integer ? -1 : a->integer > b->integer;
184
185     case OVSDB_TYPE_REAL:
186         return a->real < b->real ? -1 : a->real > b->real;
187
188     case OVSDB_TYPE_BOOLEAN:
189         return a->boolean - b->boolean;
190
191     case OVSDB_TYPE_STRING:
192         return strcmp(a->string, b->string);
193
194     case OVSDB_TYPE_UUID:
195         return uuid_compare_3way(&a->uuid, &b->uuid);
196
197     case OVSDB_N_TYPES:
198     default:
199         NOT_REACHED();
200     }
201 }
202
203 static struct ovsdb_error *
204 unwrap_json(const struct json *json, const char *name,
205             enum json_type value_type, const struct json **value)
206 {
207     if (json->type != JSON_ARRAY
208         || json->u.array.n != 2
209         || json->u.array.elems[0]->type != JSON_STRING
210         || (name && strcmp(json->u.array.elems[0]->u.string, name))
211         || json->u.array.elems[1]->type != value_type)
212     {
213         return ovsdb_syntax_error(json, NULL, "expected [\"%s\", <%s>]", name,
214                                   json_type_to_string(value_type));
215     }
216     *value = json->u.array.elems[1];
217     return NULL;
218 }
219
220 static struct ovsdb_error *
221 parse_json_pair(const struct json *json,
222                 const struct json **elem0, const struct json **elem1)
223 {
224     if (json->type != JSON_ARRAY || json->u.array.n != 2) {
225         return ovsdb_syntax_error(json, NULL, "expected 2-element array");
226     }
227     *elem0 = json->u.array.elems[0];
228     *elem1 = json->u.array.elems[1];
229     return NULL;
230 }
231
232 static struct ovsdb_error *
233 ovsdb_atom_parse_uuid(struct uuid *uuid, const struct json *json,
234                       const struct ovsdb_symbol_table *symtab)
235     WARN_UNUSED_RESULT;
236
237 static struct ovsdb_error *
238 ovsdb_atom_parse_uuid(struct uuid *uuid, const struct json *json,
239                       const struct ovsdb_symbol_table *symtab)
240 {
241     struct ovsdb_error *error0;
242     const struct json *value;
243
244     error0 = unwrap_json(json, "uuid", JSON_STRING, &value);
245     if (!error0) {
246         const char *uuid_string = json_string(value);
247         if (!uuid_from_string(uuid, uuid_string)) {
248             return ovsdb_syntax_error(json, NULL, "\"%s\" is not a valid UUID",
249                                       uuid_string);
250         }
251     } else if (symtab) {
252         struct ovsdb_error *error1;
253
254         error1 = unwrap_json(json, "named-uuid", JSON_STRING, &value);
255         if (!error1) {
256             const char *name = json_string(value);
257             const struct ovsdb_symbol *symbol;
258
259             ovsdb_error_destroy(error0);
260
261             symbol = ovsdb_symbol_table_get(symtab, name);
262             if (symbol) {
263                 *uuid = symbol->uuid;
264                 return NULL;
265             } else {
266                 return ovsdb_syntax_error(json, NULL,
267                                           "unknown named-uuid \"%s\"", name);
268             }
269         }
270         ovsdb_error_destroy(error1);
271     }
272
273     return error0;
274 }
275
276 static struct ovsdb_error * WARN_UNUSED_RESULT
277 ovsdb_atom_from_json__(union ovsdb_atom *atom, enum ovsdb_atomic_type type,
278                        const struct json *json,
279                        const struct ovsdb_symbol_table *symtab)
280 {
281     switch (type) {
282     case OVSDB_TYPE_VOID:
283         NOT_REACHED();
284
285     case OVSDB_TYPE_INTEGER:
286         if (json->type == JSON_INTEGER) {
287             atom->integer = json->u.integer;
288             return NULL;
289         }
290         break;
291
292     case OVSDB_TYPE_REAL:
293         if (json->type == JSON_INTEGER) {
294             atom->real = json->u.integer;
295             return NULL;
296         } else if (json->type == JSON_REAL) {
297             atom->real = json->u.real;
298             return NULL;
299         }
300         break;
301
302     case OVSDB_TYPE_BOOLEAN:
303         if (json->type == JSON_TRUE) {
304             atom->boolean = true;
305             return NULL;
306         } else if (json->type == JSON_FALSE) {
307             atom->boolean = false;
308             return NULL;
309         }
310         break;
311
312     case OVSDB_TYPE_STRING:
313         if (json->type == JSON_STRING) {
314             atom->string = xstrdup(json->u.string);
315             return NULL;
316         }
317         break;
318
319     case OVSDB_TYPE_UUID:
320         return ovsdb_atom_parse_uuid(&atom->uuid, json, symtab);
321
322     case OVSDB_N_TYPES:
323     default:
324         NOT_REACHED();
325     }
326
327     return ovsdb_syntax_error(json, NULL, "expected %s",
328                               ovsdb_atomic_type_to_string(type));
329 }
330
331 struct ovsdb_error *
332 ovsdb_atom_from_json(union ovsdb_atom *atom,
333                      const struct ovsdb_base_type *base,
334                      const struct json *json,
335                      const struct ovsdb_symbol_table *symtab)
336 {
337     struct ovsdb_error *error;
338
339     error = ovsdb_atom_from_json__(atom, base->type, json, symtab);
340     if (error) {
341         return error;
342     }
343
344     error = ovsdb_atom_check_constraints(atom, base);
345     if (error) {
346         ovsdb_atom_destroy(atom, base->type);
347     }
348     return error;
349 }
350
351 struct json *
352 ovsdb_atom_to_json(const union ovsdb_atom *atom, enum ovsdb_atomic_type type)
353 {
354     switch (type) {
355     case OVSDB_TYPE_VOID:
356         NOT_REACHED();
357
358     case OVSDB_TYPE_INTEGER:
359         return json_integer_create(atom->integer);
360
361     case OVSDB_TYPE_REAL:
362         return json_real_create(atom->real);
363
364     case OVSDB_TYPE_BOOLEAN:
365         return json_boolean_create(atom->boolean);
366
367     case OVSDB_TYPE_STRING:
368         return json_string_create(atom->string);
369
370     case OVSDB_TYPE_UUID:
371         return wrap_json("uuid", json_string_create_nocopy(
372                              xasprintf(UUID_FMT, UUID_ARGS(&atom->uuid))));
373
374     case OVSDB_N_TYPES:
375     default:
376         NOT_REACHED();
377     }
378 }
379
380 static char *
381 ovsdb_atom_from_string__(union ovsdb_atom *atom, enum ovsdb_atomic_type type,
382                          const char *s)
383 {
384     switch (type) {
385     case OVSDB_TYPE_VOID:
386         NOT_REACHED();
387
388     case OVSDB_TYPE_INTEGER: {
389         long long int integer;
390         if (!str_to_llong(s, 10, &integer)) {
391             return xasprintf("\"%s\" is not a valid integer", s);
392         }
393         atom->integer = integer;
394     }
395         break;
396
397     case OVSDB_TYPE_REAL:
398         if (!str_to_double(s, &atom->real)) {
399             return xasprintf("\"%s\" is not a valid real number", s);
400         }
401         /* Our JSON input routines map negative zero to zero, so do that here
402          * too for consistency. */
403         if (atom->real == 0.0) {
404             atom->real = 0.0;
405         }
406         break;
407
408     case OVSDB_TYPE_BOOLEAN:
409         if (!strcmp(s, "true") || !strcmp(s, "yes") || !strcmp(s, "on")
410             || !strcmp(s, "1")) {
411             atom->boolean = true;
412         } else if (!strcmp(s, "false") || !strcmp(s, "no") || !strcmp(s, "off")
413                    || !strcmp(s, "0")) {
414             atom->boolean = false;
415         } else {
416             return xasprintf("\"%s\" is not a valid boolean "
417                              "(use \"true\" or \"false\")", s);
418         }
419         break;
420
421     case OVSDB_TYPE_STRING:
422         if (*s == '\0') {
423             return xstrdup("An empty string is not valid as input; "
424                            "use \"\" to represent the empty string");
425         } else if (*s == '"') {
426             size_t s_len = strlen(s);
427
428             if (s_len < 2 || s[s_len - 1] != '"') {
429                 return xasprintf("%s: missing quote at end of "
430                                  "quoted string", s);
431             } else if (!json_string_unescape(s + 1, s_len - 2,
432                                              &atom->string)) {
433                 char *error = xasprintf("%s: %s", s, atom->string);
434                 free(atom->string);
435                 return error;
436             }
437         } else {
438             atom->string = xstrdup(s);
439         }
440         break;
441
442     case OVSDB_TYPE_UUID:
443         if (!uuid_from_string(&atom->uuid, s)) {
444             return xasprintf("\"%s\" is not a valid UUID", s);
445         }
446         break;
447
448     case OVSDB_N_TYPES:
449     default:
450         NOT_REACHED();
451     }
452
453     return NULL;
454 }
455
456 /* Initializes 'atom' to a value of type 'base' parsed from 's', which takes
457  * one of the following forms:
458  *
459  *      - OVSDB_TYPE_INTEGER: A decimal integer optionally preceded by a sign.
460  *
461  *      - OVSDB_TYPE_REAL: A floating-point number in the format accepted by
462  *        strtod().
463  *
464  *      - OVSDB_TYPE_BOOLEAN: "true", "yes", "on", "1" for true, or "false",
465  *        "no", "off", or "0" for false.
466  *
467  *      - OVSDB_TYPE_STRING: A JSON string if it begins with a quote, otherwise
468  *        an arbitrary string.
469  *
470  *      - OVSDB_TYPE_UUID: A UUID in RFC 4122 format.
471  *
472  * Returns a null pointer if successful, otherwise an error message describing
473  * the problem.  The caller is responsible for freeing the error.
474  */
475 char *
476 ovsdb_atom_from_string(union ovsdb_atom *atom,
477                        const struct ovsdb_base_type *base, const char *s)
478 {
479     struct ovsdb_error *error;
480     char *msg;
481
482     msg = ovsdb_atom_from_string__(atom, base->type, s);
483     if (msg) {
484         return msg;
485     }
486
487     error = ovsdb_atom_check_constraints(atom, base);
488     if (error) {
489         msg = ovsdb_error_to_string(error);
490         ovsdb_error_destroy(error);
491     }
492     return msg;
493 }
494
495 static bool
496 string_needs_quotes(const char *s)
497 {
498     const char *p = s;
499     unsigned char c;
500
501     c = *p++;
502     if (!isalpha(c) && c != '_') {
503         return true;
504     }
505
506     while ((c = *p++) != '\0') {
507         if (!isalpha(c) && c != '_' && c != '-' && c != '.') {
508             return true;
509         }
510     }
511
512     if (!strcmp(s, "true") || !strcmp(s, "false")) {
513         return true;
514     }
515
516     return false;
517 }
518
519 /* Appends 'atom' (which has the given 'type') to 'out', in a format acceptable
520  * to ovsdb_atom_from_string().  */
521 void
522 ovsdb_atom_to_string(const union ovsdb_atom *atom, enum ovsdb_atomic_type type,
523                      struct ds *out)
524 {
525     switch (type) {
526     case OVSDB_TYPE_VOID:
527         NOT_REACHED();
528
529     case OVSDB_TYPE_INTEGER:
530         ds_put_format(out, "%"PRId64, atom->integer);
531         break;
532
533     case OVSDB_TYPE_REAL:
534         ds_put_format(out, "%.*g", DBL_DIG, atom->real);
535         break;
536
537     case OVSDB_TYPE_BOOLEAN:
538         ds_put_cstr(out, atom->boolean ? "true" : "false");
539         break;
540
541     case OVSDB_TYPE_STRING:
542         if (string_needs_quotes(atom->string)) {
543             struct json json;
544
545             json.type = JSON_STRING;
546             json.u.string = atom->string;
547             json_to_ds(&json, 0, out);
548         } else {
549             ds_put_cstr(out, atom->string);
550         }
551         break;
552
553     case OVSDB_TYPE_UUID:
554         ds_put_format(out, UUID_FMT, UUID_ARGS(&atom->uuid));
555         break;
556
557     case OVSDB_N_TYPES:
558     default:
559         NOT_REACHED();
560     }
561 }
562
563 static struct ovsdb_error *
564 check_string_constraints(const char *s,
565                          const struct ovsdb_string_constraints *c)
566 {
567     size_t n_chars;
568     char *msg;
569
570     msg = utf8_validate(s, &n_chars);
571     if (msg) {
572         struct ovsdb_error *error;
573
574         error = ovsdb_error("constraint violation",
575                             "\"%s\" is not a valid UTF-8 string: %s",
576                             s, msg);
577         free(msg);
578         return error;
579     }
580
581     if (n_chars < c->minLen) {
582         return ovsdb_error(
583             "constraint violation",
584             "\"%s\" length %zu is less than minimum allowed "
585             "length %u", s, n_chars, c->minLen);
586     } else if (n_chars > c->maxLen) {
587         return ovsdb_error(
588             "constraint violation",
589             "\"%s\" length %zu is greater than maximum allowed "
590             "length %u", s, n_chars, c->maxLen);
591     }
592
593 #if HAVE_PCRE
594     if (c->re) {
595         int retval;
596
597         retval = pcre_exec(c->re, NULL, s, strlen(s), 0,
598                            PCRE_ANCHORED | PCRE_NO_UTF8_CHECK, NULL, 0);
599         if (retval == PCRE_ERROR_NOMATCH) {
600             if (c->reComment) {
601                 return ovsdb_error("constraint violation",
602                                    "\"%s\" is not a %s", s, c->reComment);
603             } else {
604                 return ovsdb_error("constraint violation",
605                                    "\"%s\" does not match regular expression "
606                                    "/%s/", s, c->reMatch);
607             }
608         } else if (retval < 0) {
609             /* PCRE doesn't have a function to translate an error code to a
610              * description.  Bizarre.  See pcreapi(3) for error details. */
611             return ovsdb_error("internal error", "PCRE returned error %d",
612                                retval);
613         }
614     }
615 #endif  /* HAVE_PCRE */
616
617     return NULL;
618 }
619
620 /* Checks whether 'atom' meets the constraints (if any) defined in 'base'.
621  * (base->type must specify 'atom''s type.)  Returns a null pointer if the
622  * constraints are met, otherwise an error that explains the violation. */
623 struct ovsdb_error *
624 ovsdb_atom_check_constraints(const union ovsdb_atom *atom,
625                              const struct ovsdb_base_type *base)
626 {
627     switch (base->type) {
628     case OVSDB_TYPE_VOID:
629         NOT_REACHED();
630
631     case OVSDB_TYPE_INTEGER:
632         if (atom->integer >= base->u.integer.min
633             && atom->integer <= base->u.integer.max) {
634             return NULL;
635         } else if (base->u.integer.min != INT64_MIN) {
636             if (base->u.integer.max != INT64_MAX) {
637                 return ovsdb_error("constraint violation",
638                                    "%"PRId64" is not in the valid range "
639                                    "%"PRId64" to %"PRId64" (inclusive)",
640                                    atom->integer,
641                                    base->u.integer.min, base->u.integer.max);
642             } else {
643                 return ovsdb_error("constraint violation",
644                                    "%"PRId64" is less than minimum allowed "
645                                    "value %"PRId64,
646                                    atom->integer, base->u.integer.min);
647             }
648         } else {
649             return ovsdb_error("constraint violation",
650                                "%"PRId64" is greater than maximum allowed "
651                                "value %"PRId64,
652                                atom->integer, base->u.integer.max);
653         }
654         NOT_REACHED();
655
656     case OVSDB_TYPE_REAL:
657         if (atom->real >= base->u.real.min && atom->real <= base->u.real.max) {
658             return NULL;
659         } else if (base->u.real.min != -DBL_MAX) {
660             if (base->u.real.max != DBL_MAX) {
661                 return ovsdb_error("constraint violation",
662                                    "%.*g is not in the valid range "
663                                    "%.*g to %.*g (inclusive)",
664                                    DBL_DIG, atom->real,
665                                    DBL_DIG, base->u.real.min,
666                                    DBL_DIG, base->u.real.max);
667             } else {
668                 return ovsdb_error("constraint violation",
669                                    "%.*g is less than minimum allowed "
670                                    "value %.*g",
671                                    DBL_DIG, atom->real,
672                                    DBL_DIG, base->u.real.min);
673             }
674         } else {
675             return ovsdb_error("constraint violation",
676                                "%.*g is greater than maximum allowed "
677                                "value %.*g",
678                                DBL_DIG, atom->real,
679                                DBL_DIG, base->u.real.max);
680         }
681         NOT_REACHED();
682
683     case OVSDB_TYPE_BOOLEAN:
684         return NULL;
685
686     case OVSDB_TYPE_STRING:
687         return check_string_constraints(atom->string, &base->u.string);
688
689     case OVSDB_TYPE_UUID:
690         return NULL;
691
692     case OVSDB_N_TYPES:
693     default:
694         NOT_REACHED();
695     }
696 }
697 \f
698 static union ovsdb_atom *
699 alloc_default_atoms(enum ovsdb_atomic_type type, size_t n)
700 {
701     if (type != OVSDB_TYPE_VOID && n) {
702         union ovsdb_atom *atoms;
703         unsigned int i;
704
705         atoms = xmalloc(n * sizeof *atoms);
706         for (i = 0; i < n; i++) {
707             ovsdb_atom_init_default(&atoms[i], type);
708         }
709         return atoms;
710     } else {
711         /* Avoid wasting memory in the n == 0 case, because xmalloc(0) is
712          * treated as xmalloc(1). */
713         return NULL;
714     }
715 }
716
717 void
718 ovsdb_datum_init_empty(struct ovsdb_datum *datum)
719 {
720     datum->n = 0;
721     datum->keys = NULL;
722     datum->values = NULL;
723 }
724
725 void
726 ovsdb_datum_init_default(struct ovsdb_datum *datum,
727                          const struct ovsdb_type *type)
728 {
729     datum->n = type->n_min;
730     datum->keys = alloc_default_atoms(type->key.type, datum->n);
731     datum->values = alloc_default_atoms(type->value.type, datum->n);
732 }
733
734 bool
735 ovsdb_datum_is_default(const struct ovsdb_datum *datum,
736                        const struct ovsdb_type *type)
737 {
738     size_t i;
739
740     if (datum->n != type->n_min) {
741         return false;
742     }
743     for (i = 0; i < datum->n; i++) {
744         if (!ovsdb_atom_is_default(&datum->keys[i], type->key.type)) {
745             return false;
746         }
747         if (type->value.type != OVSDB_TYPE_VOID
748             && !ovsdb_atom_is_default(&datum->values[i], type->value.type)) {
749             return false;
750         }
751     }
752
753     return true;
754 }
755
756 static union ovsdb_atom *
757 clone_atoms(const union ovsdb_atom *old, enum ovsdb_atomic_type type, size_t n)
758 {
759     if (type != OVSDB_TYPE_VOID && n) {
760         union ovsdb_atom *new;
761         unsigned int i;
762
763         new = xmalloc(n * sizeof *new);
764         for (i = 0; i < n; i++) {
765             ovsdb_atom_clone(&new[i], &old[i], type);
766         }
767         return new;
768     } else {
769         /* Avoid wasting memory in the n == 0 case, because xmalloc(0) is
770          * treated as xmalloc(1). */
771         return NULL;
772     }
773 }
774
775 void
776 ovsdb_datum_clone(struct ovsdb_datum *new, const struct ovsdb_datum *old,
777                   const struct ovsdb_type *type)
778 {
779     unsigned int n = old->n;
780     new->n = n;
781     new->keys = clone_atoms(old->keys, type->key.type, n);
782     new->values = clone_atoms(old->values, type->value.type, n);
783 }
784
785 static void
786 free_data(enum ovsdb_atomic_type type,
787           union ovsdb_atom *atoms, size_t n_atoms)
788 {
789     if (ovsdb_atom_needs_destruction(type)) {
790         unsigned int i;
791         for (i = 0; i < n_atoms; i++) {
792             ovsdb_atom_destroy(&atoms[i], type);
793         }
794     }
795     free(atoms);
796 }
797
798 void
799 ovsdb_datum_destroy(struct ovsdb_datum *datum, const struct ovsdb_type *type)
800 {
801     free_data(type->key.type, datum->keys, datum->n);
802     free_data(type->value.type, datum->values, datum->n);
803 }
804
805 void
806 ovsdb_datum_swap(struct ovsdb_datum *a, struct ovsdb_datum *b)
807 {
808     struct ovsdb_datum tmp = *a;
809     *a = *b;
810     *b = tmp;
811 }
812
813 struct ovsdb_datum_sort_cbdata {
814     const struct ovsdb_type *type;
815     struct ovsdb_datum *datum;
816 };
817
818 static int
819 ovsdb_datum_sort_compare_cb(size_t a, size_t b, void *cbdata_)
820 {
821     struct ovsdb_datum_sort_cbdata *cbdata = cbdata_;
822
823     return ovsdb_atom_compare_3way(&cbdata->datum->keys[a],
824                                    &cbdata->datum->keys[b],
825                                    cbdata->type->key.type);
826 }
827
828 static void
829 ovsdb_datum_sort_swap_cb(size_t a, size_t b, void *cbdata_)
830 {
831     struct ovsdb_datum_sort_cbdata *cbdata = cbdata_;
832
833     ovsdb_atom_swap(&cbdata->datum->keys[a], &cbdata->datum->keys[b]);
834     if (cbdata->type->value.type != OVSDB_TYPE_VOID) {
835         ovsdb_atom_swap(&cbdata->datum->values[a], &cbdata->datum->values[b]);
836     }
837 }
838
839 struct ovsdb_error *
840 ovsdb_datum_sort(struct ovsdb_datum *datum, const struct ovsdb_type *type)
841 {
842     if (datum->n < 2) {
843         return NULL;
844     } else {
845         struct ovsdb_datum_sort_cbdata cbdata;
846         size_t i;
847
848         cbdata.type = type;
849         cbdata.datum = datum;
850         sort(datum->n, ovsdb_datum_sort_compare_cb, ovsdb_datum_sort_swap_cb,
851              &cbdata);
852
853         for (i = 0; i < datum->n - 1; i++) {
854             if (ovsdb_atom_equals(&datum->keys[i], &datum->keys[i + 1],
855                                   type->key.type)) {
856                 if (ovsdb_type_is_map(type)) {
857                     return ovsdb_error(NULL, "map contains duplicate key");
858                 } else {
859                     return ovsdb_error(NULL, "set contains duplicate");
860                 }
861             }
862         }
863
864         return NULL;
865     }
866 }
867
868 /* Checks that each of the atoms in 'datum' conforms to the constraints
869  * specified by its 'type'.  Returns an error if a constraint is violated,
870  * otherwise a null pointer.
871  *
872  * This function is not commonly useful because the most ordinary way to obtain
873  * a datum is ultimately via ovsdb_atom_from_string() or
874  * ovsdb_atom_from_json(), which check constraints themselves. */
875 struct ovsdb_error *
876 ovsdb_datum_check_constraints(const struct ovsdb_datum *datum,
877                               const struct ovsdb_type *type)
878 {
879     struct ovsdb_error *error;
880     unsigned int i;
881
882     for (i = 0; i < datum->n; i++) {
883         error = ovsdb_atom_check_constraints(&datum->keys[i], &type->key);
884         if (error) {
885             return error;
886         }
887     }
888
889     if (type->value.type != OVSDB_TYPE_VOID) {
890         for (i = 0; i < datum->n; i++) {
891             error = ovsdb_atom_check_constraints(&datum->values[i],
892                                                  &type->value);
893             if (error) {
894                 return error;
895             }
896         }
897     }
898
899     return NULL;
900 }
901
902 struct ovsdb_error *
903 ovsdb_datum_from_json(struct ovsdb_datum *datum,
904                       const struct ovsdb_type *type,
905                       const struct json *json,
906                       const struct ovsdb_symbol_table *symtab)
907 {
908     struct ovsdb_error *error;
909
910     if (ovsdb_type_is_scalar(type)) {
911         datum->n = 1;
912         datum->keys = xmalloc(sizeof *datum->keys);
913         datum->values = NULL;
914
915         error = ovsdb_atom_from_json(&datum->keys[0], &type->key,
916                                      json, symtab);
917         if (error) {
918             free(datum->keys);
919         }
920         return error;
921     } else {
922         bool is_map = ovsdb_type_is_map(type);
923         const char *class = is_map ? "map" : "set";
924         const struct json *inner;
925         unsigned int i;
926         size_t n;
927
928         assert(is_map || ovsdb_type_is_set(type));
929
930         error = unwrap_json(json, class, JSON_ARRAY, &inner);
931         if (error) {
932             return error;
933         }
934
935         n = inner->u.array.n;
936         if (n < type->n_min || n > type->n_max) {
937             return ovsdb_syntax_error(json, NULL, "%s must have %u to "
938                                       "%u members but %zu are present",
939                                       class, type->n_min, type->n_max, n);
940         }
941
942         datum->n = 0;
943         datum->keys = xmalloc(n * sizeof *datum->keys);
944         datum->values = is_map ? xmalloc(n * sizeof *datum->values) : NULL;
945         for (i = 0; i < n; i++) {
946             const struct json *element = inner->u.array.elems[i];
947             const struct json *key = NULL;
948             const struct json *value = NULL;
949
950             if (!is_map) {
951                 key = element;
952             } else {
953                 error = parse_json_pair(element, &key, &value);
954                 if (error) {
955                     goto error;
956                 }
957             }
958
959             error = ovsdb_atom_from_json(&datum->keys[i], &type->key,
960                                          key, symtab);
961             if (error) {
962                 goto error;
963             }
964
965             if (is_map) {
966                 error = ovsdb_atom_from_json(&datum->values[i],
967                                              &type->value, value, symtab);
968                 if (error) {
969                     ovsdb_atom_destroy(&datum->keys[i], type->key.type);
970                     goto error;
971                 }
972             }
973
974             datum->n++;
975         }
976
977         error = ovsdb_datum_sort(datum, type);
978         if (error) {
979             goto error;
980         }
981
982         return NULL;
983
984     error:
985         ovsdb_datum_destroy(datum, type);
986         return error;
987     }
988 }
989
990 struct json *
991 ovsdb_datum_to_json(const struct ovsdb_datum *datum,
992                     const struct ovsdb_type *type)
993 {
994     /* These tests somewhat tolerate a 'datum' that does not exactly match
995      * 'type', in particular a datum with 'n' not in the allowed range. */
996     if (datum->n == 1 && ovsdb_type_is_scalar(type)) {
997         return ovsdb_atom_to_json(&datum->keys[0], type->key.type);
998     } else if (type->value.type == OVSDB_TYPE_VOID) {
999         struct json **elems;
1000         size_t i;
1001
1002         elems = xmalloc(datum->n * sizeof *elems);
1003         for (i = 0; i < datum->n; i++) {
1004             elems[i] = ovsdb_atom_to_json(&datum->keys[i], type->key.type);
1005         }
1006
1007         return wrap_json("set", json_array_create(elems, datum->n));
1008     } else {
1009         struct json **elems;
1010         size_t i;
1011
1012         elems = xmalloc(datum->n * sizeof *elems);
1013         for (i = 0; i < datum->n; i++) {
1014             elems[i] = json_array_create_2(
1015                 ovsdb_atom_to_json(&datum->keys[i], type->key.type),
1016                 ovsdb_atom_to_json(&datum->values[i], type->value.type));
1017         }
1018
1019         return wrap_json("map", json_array_create(elems, datum->n));
1020     }
1021 }
1022
1023 static const char *
1024 skip_spaces(const char *p)
1025 {
1026     while (isspace((unsigned char) *p)) {
1027         p++;
1028     }
1029     return p;
1030 }
1031
1032 static char *
1033 parse_atom_token(const char **s, const struct ovsdb_base_type *base,
1034                  union ovsdb_atom *atom)
1035 {
1036     char *token, *error;
1037
1038     error = ovsdb_token_parse(s, &token);
1039     if (!error) {
1040         error = ovsdb_atom_from_string(atom, base, token);
1041         free(token);
1042     }
1043     return error;
1044 }
1045
1046 static char *
1047 parse_key_value(const char **s, const struct ovsdb_type *type,
1048                 union ovsdb_atom *key, union ovsdb_atom *value)
1049 {
1050     const char *start = *s;
1051     char *error;
1052
1053     error = parse_atom_token(s, &type->key, key);
1054     if (!error && type->value.type != OVSDB_TYPE_VOID) {
1055         *s = skip_spaces(*s);
1056         if (**s == '=') {
1057             (*s)++;
1058             *s = skip_spaces(*s);
1059             error = parse_atom_token(s, &type->value, value);
1060         } else {
1061             error = xasprintf("%s: syntax error at \"%c\" expecting \"=\"",
1062                               start, **s);
1063         }
1064         if (error) {
1065             ovsdb_atom_destroy(key, type->key.type);
1066         }
1067     }
1068     return error;
1069 }
1070
1071 static void
1072 free_key_value(const struct ovsdb_type *type,
1073                union ovsdb_atom *key, union ovsdb_atom *value)
1074 {
1075     ovsdb_atom_destroy(key, type->key.type);
1076     if (type->value.type != OVSDB_TYPE_VOID) {
1077         ovsdb_atom_destroy(value, type->value.type);
1078     }
1079 }
1080
1081 /* Initializes 'datum' as a datum of the given 'type', parsing its contents
1082  * from 's'.  The format of 's' is a series of space or comma separated atoms
1083  * or, for a map, '='-delimited pairs of atoms.  Each atom must in a format
1084  * acceptable to ovsdb_atom_from_string().  Optionally, a set may be enclosed
1085  * in "[]" or a map in "{}"; for an empty set or map these punctuators are
1086  * required. */
1087 char *
1088 ovsdb_datum_from_string(struct ovsdb_datum *datum,
1089                         const struct ovsdb_type *type, const char *s)
1090 {
1091     bool is_map = ovsdb_type_is_map(type);
1092     struct ovsdb_error *dberror;
1093     const char *p;
1094     int end_delim;
1095     char *error;
1096
1097     ovsdb_datum_init_empty(datum);
1098
1099     /* Swallow a leading delimiter if there is one. */
1100     p = skip_spaces(s);
1101     if (*p == (is_map ? '{' : '[')) {
1102         end_delim = is_map ? '}' : ']';
1103         p = skip_spaces(p + 1);
1104     } else if (!*p) {
1105         if (is_map) {
1106             return xstrdup("use \"{}\" to specify the empty map");
1107         } else {
1108             return xstrdup("use \"[]\" to specify the empty set");
1109         }
1110     } else {
1111         end_delim = 0;
1112     }
1113
1114     while (*p && *p != end_delim) {
1115         union ovsdb_atom key, value;
1116
1117         if (ovsdb_token_is_delim(*p)) {
1118             error = xasprintf("%s: unexpected \"%c\" parsing %s",
1119                               s, *p, ovsdb_type_to_english(type));
1120             goto error;
1121         }
1122
1123         /* Add to datum. */
1124         error = parse_key_value(&p, type, &key, &value);
1125         if (error) {
1126             goto error;
1127         }
1128         ovsdb_datum_add_unsafe(datum, &key, &value, type);
1129         free_key_value(type, &key, &value);
1130
1131         /* Skip optional white space and comma. */
1132         p = skip_spaces(p);
1133         if (*p == ',') {
1134             p = skip_spaces(p + 1);
1135         }
1136     }
1137
1138     if (*p != end_delim) {
1139         error = xasprintf("%s: missing \"%c\" at end of data", s, end_delim);
1140         goto error;
1141     }
1142     if (end_delim) {
1143         p = skip_spaces(p + 1);
1144         if (*p) {
1145             error = xasprintf("%s: trailing garbage after \"%c\"",
1146                               s, end_delim);
1147             goto error;
1148         }
1149     }
1150
1151     if (datum->n < type->n_min) {
1152         error = xasprintf("%s: %u %s specified but the minimum number is %u",
1153                           s, datum->n, is_map ? "pair(s)" : "value(s)",
1154                           type->n_min);
1155         goto error;
1156     } else if (datum->n > type->n_max) {
1157         error = xasprintf("%s: %u %s specified but the maximum number is %u",
1158                           s, datum->n, is_map ? "pair(s)" : "value(s)",
1159             type->n_max);
1160         goto error;
1161     }
1162
1163     dberror = ovsdb_datum_sort(datum, type);
1164     if (dberror) {
1165         ovsdb_error_destroy(dberror);
1166         if (ovsdb_type_is_map(type)) {
1167             error = xasprintf("%s: map contains duplicate key", s);
1168         } else {
1169             error = xasprintf("%s: set contains duplicate value", s);
1170         }
1171         goto error;
1172     }
1173
1174     return NULL;
1175
1176 error:
1177     ovsdb_datum_destroy(datum, type);
1178     ovsdb_datum_init_empty(datum);
1179     return error;
1180 }
1181
1182 /* Appends to 'out' the 'datum' (with the given 'type') in a format acceptable
1183  * to ovsdb_datum_from_string(). */
1184 void
1185 ovsdb_datum_to_string(const struct ovsdb_datum *datum,
1186                       const struct ovsdb_type *type, struct ds *out)
1187 {
1188     bool is_map = ovsdb_type_is_map(type);
1189     size_t i;
1190
1191     if (type->n_max > 1 || !datum->n) {
1192         ds_put_char(out, is_map ? '{' : '[');
1193     }
1194     for (i = 0; i < datum->n; i++) {
1195         if (i > 0) {
1196             ds_put_cstr(out, ", ");
1197         }
1198
1199         ovsdb_atom_to_string(&datum->keys[i], type->key.type, out);
1200         if (is_map) {
1201             ds_put_char(out, '=');
1202             ovsdb_atom_to_string(&datum->values[i], type->value.type, out);
1203         }
1204     }
1205     if (type->n_max > 1 || !datum->n) {
1206         ds_put_char(out, is_map ? '}' : ']');
1207     }
1208 }
1209
1210 static uint32_t
1211 hash_atoms(enum ovsdb_atomic_type type, const union ovsdb_atom *atoms,
1212            unsigned int n, uint32_t basis)
1213 {
1214     if (type != OVSDB_TYPE_VOID) {
1215         unsigned int i;
1216
1217         for (i = 0; i < n; i++) {
1218             basis = ovsdb_atom_hash(&atoms[i], type, basis);
1219         }
1220     }
1221     return basis;
1222 }
1223
1224 uint32_t
1225 ovsdb_datum_hash(const struct ovsdb_datum *datum,
1226                  const struct ovsdb_type *type, uint32_t basis)
1227 {
1228     basis = hash_atoms(type->key.type, datum->keys, datum->n, basis);
1229     basis ^= (type->key.type << 24) | (type->value.type << 16) | datum->n;
1230     basis = hash_atoms(type->value.type, datum->values, datum->n, basis);
1231     return basis;
1232 }
1233
1234 static int
1235 atom_arrays_compare_3way(const union ovsdb_atom *a,
1236                          const union ovsdb_atom *b,
1237                          enum ovsdb_atomic_type type,
1238                          size_t n)
1239 {
1240     unsigned int i;
1241
1242     for (i = 0; i < n; i++) {
1243         int cmp = ovsdb_atom_compare_3way(&a[i], &b[i], type);
1244         if (cmp) {
1245             return cmp;
1246         }
1247     }
1248
1249     return 0;
1250 }
1251
1252 bool
1253 ovsdb_datum_equals(const struct ovsdb_datum *a,
1254                    const struct ovsdb_datum *b,
1255                    const struct ovsdb_type *type)
1256 {
1257     return !ovsdb_datum_compare_3way(a, b, type);
1258 }
1259
1260 int
1261 ovsdb_datum_compare_3way(const struct ovsdb_datum *a,
1262                          const struct ovsdb_datum *b,
1263                          const struct ovsdb_type *type)
1264 {
1265     int cmp;
1266
1267     if (a->n != b->n) {
1268         return a->n < b->n ? -1 : 1;
1269     }
1270
1271     cmp = atom_arrays_compare_3way(a->keys, b->keys, type->key.type, a->n);
1272     if (cmp) {
1273         return cmp;
1274     }
1275
1276     return (type->value.type == OVSDB_TYPE_VOID ? 0
1277             : atom_arrays_compare_3way(a->values, b->values, type->value.type,
1278                                        a->n));
1279 }
1280
1281 /* If 'key' is one of the keys in 'datum', returns its index within 'datum',
1282  * otherwise UINT_MAX.  'key.type' must be the type of the atoms stored in the
1283  * 'keys' array in 'datum'.
1284  */
1285 unsigned int
1286 ovsdb_datum_find_key(const struct ovsdb_datum *datum,
1287                      const union ovsdb_atom *key,
1288                      enum ovsdb_atomic_type key_type)
1289 {
1290     unsigned int low = 0;
1291     unsigned int high = datum->n;
1292     while (low < high) {
1293         unsigned int idx = (low + high) / 2;
1294         int cmp = ovsdb_atom_compare_3way(key, &datum->keys[idx], key_type);
1295         if (cmp < 0) {
1296             high = idx;
1297         } else if (cmp > 0) {
1298             low = idx + 1;
1299         } else {
1300             return idx;
1301         }
1302     }
1303     return UINT_MAX;
1304 }
1305
1306 /* If 'key' and 'value' is one of the key-value pairs in 'datum', returns its
1307  * index within 'datum', otherwise UINT_MAX.  'key.type' must be the type of
1308  * the atoms stored in the 'keys' array in 'datum'.  'value_type' may be the
1309  * type of the 'values' atoms or OVSDB_TYPE_VOID to compare only keys.
1310  */
1311 unsigned int
1312 ovsdb_datum_find_key_value(const struct ovsdb_datum *datum,
1313                            const union ovsdb_atom *key,
1314                            enum ovsdb_atomic_type key_type,
1315                            const union ovsdb_atom *value,
1316                            enum ovsdb_atomic_type value_type)
1317 {
1318     unsigned int idx = ovsdb_datum_find_key(datum, key, key_type);
1319     if (idx != UINT_MAX
1320         && value_type != OVSDB_TYPE_VOID
1321         && !ovsdb_atom_equals(&datum->values[idx], value, value_type)) {
1322         idx = UINT_MAX;
1323     }
1324     return idx;
1325 }
1326
1327 /* If atom 'i' in 'a' is also in 'b', returns its index in 'b', otherwise
1328  * UINT_MAX.  'type' must be the type of 'a' and 'b', except that
1329  * type->value.type may be set to OVSDB_TYPE_VOID to compare keys but not
1330  * values. */
1331 static unsigned int
1332 ovsdb_datum_find(const struct ovsdb_datum *a, int i,
1333                  const struct ovsdb_datum *b,
1334                  const struct ovsdb_type *type)
1335 {
1336     return ovsdb_datum_find_key_value(b,
1337                                       &a->keys[i], type->key.type,
1338                                       a->values ? &a->values[i] : NULL,
1339                                       type->value.type);
1340 }
1341
1342 /* Returns true if every element in 'a' is also in 'b', false otherwise. */
1343 bool
1344 ovsdb_datum_includes_all(const struct ovsdb_datum *a,
1345                          const struct ovsdb_datum *b,
1346                          const struct ovsdb_type *type)
1347 {
1348     size_t i;
1349
1350     for (i = 0; i < a->n; i++) {
1351         if (ovsdb_datum_find(a, i, b, type) == UINT_MAX) {
1352             return false;
1353         }
1354     }
1355     return true;
1356 }
1357
1358 /* Returns true if no element in 'a' is also in 'b', false otherwise. */
1359 bool
1360 ovsdb_datum_excludes_all(const struct ovsdb_datum *a,
1361                          const struct ovsdb_datum *b,
1362                          const struct ovsdb_type *type)
1363 {
1364     size_t i;
1365
1366     for (i = 0; i < a->n; i++) {
1367         if (ovsdb_datum_find(a, i, b, type) != UINT_MAX) {
1368             return false;
1369         }
1370     }
1371     return true;
1372 }
1373
1374 static void
1375 ovsdb_datum_reallocate(struct ovsdb_datum *a, const struct ovsdb_type *type,
1376                        unsigned int capacity)
1377 {
1378     a->keys = xrealloc(a->keys, capacity * sizeof *a->keys);
1379     if (type->value.type != OVSDB_TYPE_VOID) {
1380         a->values = xrealloc(a->values, capacity * sizeof *a->values);
1381     }
1382 }
1383
1384 /* Removes the element with index 'idx' from 'datum', which has type 'type'.
1385  * If 'idx' is not the last element in 'datum', then the removed element is
1386  * replaced by the (former) last element.
1387  *
1388  * This function does not maintain ovsdb_datum invariants.  Use
1389  * ovsdb_datum_sort() to check and restore these invariants. */
1390 void
1391 ovsdb_datum_remove_unsafe(struct ovsdb_datum *datum, size_t idx,
1392                           const struct ovsdb_type *type)
1393 {
1394     ovsdb_atom_destroy(&datum->keys[idx], type->key.type);
1395     datum->keys[idx] = datum->keys[datum->n - 1];
1396     if (type->value.type != OVSDB_TYPE_VOID) {
1397         ovsdb_atom_destroy(&datum->values[idx], type->value.type);
1398         datum->values[idx] = datum->values[datum->n - 1];
1399     }
1400     datum->n--;
1401 }
1402
1403 /* Adds the element with the given 'key' and 'value' to 'datum', which must
1404  * have the specified 'type'.
1405  *
1406  * This function always allocates memory, so it is not an efficient way to add
1407  * a number of elements to a datum.
1408  *
1409  * This function does not maintain ovsdb_datum invariants.  Use
1410  * ovsdb_datum_sort() to check and restore these invariants.  (But a datum with
1411  * 0 or 1 elements cannot violate the invariants anyhow.) */
1412 void
1413 ovsdb_datum_add_unsafe(struct ovsdb_datum *datum,
1414                        const union ovsdb_atom *key,
1415                        const union ovsdb_atom *value,
1416                        const struct ovsdb_type *type)
1417 {
1418     size_t idx = datum->n++;
1419     datum->keys = xrealloc(datum->keys, datum->n * sizeof *datum->keys);
1420     ovsdb_atom_clone(&datum->keys[idx], key, type->key.type);
1421     if (type->value.type != OVSDB_TYPE_VOID) {
1422         datum->values = xrealloc(datum->values,
1423                                  datum->n * sizeof *datum->values);
1424         ovsdb_atom_clone(&datum->values[idx], value, type->value.type);
1425     }
1426 }
1427
1428 void
1429 ovsdb_datum_union(struct ovsdb_datum *a, const struct ovsdb_datum *b,
1430                   const struct ovsdb_type *type, bool replace)
1431 {
1432     unsigned int n;
1433     size_t bi;
1434
1435     n = a->n;
1436     for (bi = 0; bi < b->n; bi++) {
1437         unsigned int ai;
1438
1439         ai = ovsdb_datum_find_key(a, &b->keys[bi], type->key.type);
1440         if (ai == UINT_MAX) {
1441             if (n == a->n) {
1442                 ovsdb_datum_reallocate(a, type, a->n + (b->n - bi));
1443             }
1444             ovsdb_atom_clone(&a->keys[n], &b->keys[bi], type->key.type);
1445             if (type->value.type != OVSDB_TYPE_VOID) {
1446                 ovsdb_atom_clone(&a->values[n], &b->values[bi],
1447                                  type->value.type);
1448             }
1449             n++;
1450         } else if (replace && type->value.type != OVSDB_TYPE_VOID) {
1451             ovsdb_atom_destroy(&a->values[ai], type->value.type);
1452             ovsdb_atom_clone(&a->values[ai], &b->values[bi],
1453                              type->value.type);
1454         }
1455     }
1456     if (n != a->n) {
1457         struct ovsdb_error *error;
1458         a->n = n;
1459         error = ovsdb_datum_sort(a, type);
1460         assert(!error);
1461     }
1462 }
1463
1464 void
1465 ovsdb_datum_subtract(struct ovsdb_datum *a, const struct ovsdb_type *a_type,
1466                      const struct ovsdb_datum *b,
1467                      const struct ovsdb_type *b_type)
1468 {
1469     bool changed = false;
1470     size_t i;
1471
1472     assert(a_type->key.type == b_type->key.type);
1473     assert(a_type->value.type == b_type->value.type
1474            || b_type->value.type == OVSDB_TYPE_VOID);
1475
1476     /* XXX The big-O of this could easily be improved. */
1477     for (i = 0; i < a->n; ) {
1478         unsigned int idx = ovsdb_datum_find(a, i, b, b_type);
1479         if (idx != UINT_MAX) {
1480             changed = true;
1481             ovsdb_datum_remove_unsafe(a, i, a_type);
1482         } else {
1483             i++;
1484         }
1485     }
1486     if (changed) {
1487         struct ovsdb_error *error = ovsdb_datum_sort(a, a_type);
1488         assert(!error);
1489     }
1490 }
1491 \f
1492 struct ovsdb_symbol_table {
1493     struct shash sh;
1494 };
1495
1496 struct ovsdb_symbol_table *
1497 ovsdb_symbol_table_create(void)
1498 {
1499     struct ovsdb_symbol_table *symtab = xmalloc(sizeof *symtab);
1500     shash_init(&symtab->sh);
1501     return symtab;
1502 }
1503
1504 void
1505 ovsdb_symbol_table_destroy(struct ovsdb_symbol_table *symtab)
1506 {
1507     if (symtab) {
1508         struct shash_node *node, *next;
1509
1510         SHASH_FOR_EACH_SAFE (node, next, &symtab->sh) {
1511             struct ovsdb_symbol *symbol = node->data;
1512             free(symbol);
1513             shash_delete(&symtab->sh, node);
1514         }
1515         shash_destroy(&symtab->sh);
1516         free(symtab);
1517     }
1518 }
1519
1520 struct ovsdb_symbol *
1521 ovsdb_symbol_table_get(const struct ovsdb_symbol_table *symtab,
1522                        const char *name)
1523 {
1524     return shash_find_data(&symtab->sh, name);
1525 }
1526
1527 void
1528 ovsdb_symbol_table_put(struct ovsdb_symbol_table *symtab, const char *name,
1529                        const struct uuid *uuid, bool used)
1530 {
1531     struct ovsdb_symbol *symbol;
1532
1533     assert(!ovsdb_symbol_table_get(symtab, name));
1534     symbol = xmalloc(sizeof *symbol);
1535     symbol->uuid = *uuid;
1536     symbol->used = used;
1537     shash_add(&symtab->sh, name, symbol);
1538 }
1539 \f
1540 /* Extracts a token from the beginning of 's' and returns a pointer just after
1541  * the token.  Stores the token itself into '*outp', which the caller is
1542  * responsible for freeing (with free()).
1543  *
1544  * If 's[0]' is a delimiter, the returned token is the empty string.
1545  *
1546  * A token extends from 's' to the first delimiter, as defined by
1547  * ovsdb_token_is_delim(), or until the end of the string.  A delimiter can be
1548  * escaped with a backslash, in which case the backslash does not appear in the
1549  * output.  Double quotes also cause delimiters to be ignored, but the double
1550  * quotes are retained in the output.  (Backslashes inside double quotes are
1551  * not removed, either.)
1552  */
1553 char *
1554 ovsdb_token_parse(const char **s, char **outp)
1555 {
1556     const char *p;
1557     struct ds out;
1558     bool in_quotes;
1559     char *error;
1560
1561     ds_init(&out);
1562     in_quotes = false;
1563     for (p = *s; *p != '\0'; ) {
1564         int c = *p++;
1565         if (c == '\\') {
1566             if (in_quotes) {
1567                 ds_put_char(&out, '\\');
1568             }
1569             if (!*p) {
1570                 error = xasprintf("%s: backslash at end of argument", *s);
1571                 goto error;
1572             }
1573             ds_put_char(&out, *p++);
1574         } else if (!in_quotes && ovsdb_token_is_delim(c)) {
1575             p--;
1576             break;
1577         } else {
1578             ds_put_char(&out, c);
1579             if (c == '"') {
1580                 in_quotes = !in_quotes;
1581             }
1582         }
1583     }
1584     if (in_quotes) {
1585         error = xasprintf("%s: quoted string extends past end of argument",
1586                           *s);
1587         goto error;
1588     }
1589     *outp = ds_cstr(&out);
1590     *s = p;
1591     return NULL;
1592
1593 error:
1594     ds_destroy(&out);
1595     *outp = NULL;
1596     return error;
1597 }
1598
1599 /* Returns true if 'c' delimits tokens, or if 'c' is 0, and false otherwise. */
1600 bool
1601 ovsdb_token_is_delim(unsigned char c)
1602 {
1603     return strchr(":=, []{}", c) != NULL;
1604 }