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