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