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