1 /* Copyright (c) 2009, 2010 Nicira Networks
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:
7 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 #include "ovsdb-data.h"
26 #include "dynamic-string.h"
28 #include "ovsdb-error.h"
35 wrap_json(const char *name, struct json *wrapped)
37 return json_array_create_2(json_string_create(name), wrapped);
40 /* Initializes 'atom' with the default value of the given 'type'.
42 * The default value for an atom is as defined in ovsdb/SPECS:
44 * - "integer" or "real": 0
48 * - "string": "" (the empty string)
50 * - "uuid": 00000000-0000-0000-0000-000000000000
52 * The caller must eventually arrange for 'atom' to be destroyed (with
53 * ovsdb_atom_destroy()). */
55 ovsdb_atom_init_default(union ovsdb_atom *atom, enum ovsdb_atomic_type type)
61 case OVSDB_TYPE_INTEGER:
69 case OVSDB_TYPE_BOOLEAN:
70 atom->boolean = false;
73 case OVSDB_TYPE_STRING:
74 atom->string = xmemdup("", 1);
78 uuid_zero(&atom->uuid);
88 /* Returns true if 'atom', which must have the given 'type', has the default
89 * value for that type.
91 * See ovsdb_atom_init_default() for an explanation of the default value of an
94 ovsdb_atom_is_default(const union ovsdb_atom *atom,
95 enum ovsdb_atomic_type type)
101 case OVSDB_TYPE_INTEGER:
102 return atom->integer == 0;
104 case OVSDB_TYPE_REAL:
105 return atom->real == 0.0;
107 case OVSDB_TYPE_BOOLEAN:
108 return atom->boolean == false;
110 case OVSDB_TYPE_STRING:
111 return atom->string[0] == '\0';
113 case OVSDB_TYPE_UUID:
114 return uuid_is_zero(&atom->uuid);
122 /* Initializes 'new' as a copy of 'old', with the given 'type'.
124 * The caller must eventually arrange for 'new' to be destroyed (with
125 * ovsdb_atom_destroy()). */
127 ovsdb_atom_clone(union ovsdb_atom *new, const union ovsdb_atom *old,
128 enum ovsdb_atomic_type type)
131 case OVSDB_TYPE_VOID:
134 case OVSDB_TYPE_INTEGER:
135 new->integer = old->integer;
138 case OVSDB_TYPE_REAL:
139 new->real = old->real;
142 case OVSDB_TYPE_BOOLEAN:
143 new->boolean = old->boolean;
146 case OVSDB_TYPE_STRING:
147 new->string = xstrdup(old->string);
150 case OVSDB_TYPE_UUID:
151 new->uuid = old->uuid;
160 /* Swaps the contents of 'a' and 'b', which need not have the same type. */
162 ovsdb_atom_swap(union ovsdb_atom *a, union ovsdb_atom *b)
164 union ovsdb_atom tmp = *a;
169 /* Returns a hash value for 'atom', which has the specified 'type', folding
170 * 'basis' into the calculation. */
172 ovsdb_atom_hash(const union ovsdb_atom *atom, enum ovsdb_atomic_type type,
176 case OVSDB_TYPE_VOID:
179 case OVSDB_TYPE_INTEGER:
180 return hash_int(atom->integer, basis);
182 case OVSDB_TYPE_REAL:
183 return hash_double(atom->real, basis);
185 case OVSDB_TYPE_BOOLEAN:
186 return hash_boolean(atom->boolean, basis);
188 case OVSDB_TYPE_STRING:
189 return hash_string(atom->string, basis);
191 case OVSDB_TYPE_UUID:
192 return hash_int(uuid_hash(&atom->uuid), basis);
200 /* Compares 'a' and 'b', which both have type 'type', and returns a
201 * strcmp()-like result. */
203 ovsdb_atom_compare_3way(const union ovsdb_atom *a,
204 const union ovsdb_atom *b,
205 enum ovsdb_atomic_type type)
208 case OVSDB_TYPE_VOID:
211 case OVSDB_TYPE_INTEGER:
212 return a->integer < b->integer ? -1 : a->integer > b->integer;
214 case OVSDB_TYPE_REAL:
215 return a->real < b->real ? -1 : a->real > b->real;
217 case OVSDB_TYPE_BOOLEAN:
218 return a->boolean - b->boolean;
220 case OVSDB_TYPE_STRING:
221 return strcmp(a->string, b->string);
223 case OVSDB_TYPE_UUID:
224 return uuid_compare_3way(&a->uuid, &b->uuid);
232 static struct ovsdb_error *
233 unwrap_json(const struct json *json, const char *name,
234 enum json_type value_type, const struct json **value)
236 if (json->type != JSON_ARRAY
237 || json->u.array.n != 2
238 || json->u.array.elems[0]->type != JSON_STRING
239 || (name && strcmp(json->u.array.elems[0]->u.string, name))
240 || json->u.array.elems[1]->type != value_type)
242 return ovsdb_syntax_error(json, NULL, "expected [\"%s\", <%s>]", name,
243 json_type_to_string(value_type));
245 *value = json->u.array.elems[1];
249 static struct ovsdb_error *
250 parse_json_pair(const struct json *json,
251 const struct json **elem0, const struct json **elem1)
253 if (json->type != JSON_ARRAY || json->u.array.n != 2) {
254 return ovsdb_syntax_error(json, NULL, "expected 2-element array");
256 *elem0 = json->u.array.elems[0];
257 *elem1 = json->u.array.elems[1];
261 static struct ovsdb_error * WARN_UNUSED_RESULT
262 ovsdb_atom_parse_uuid(struct uuid *uuid, const struct json *json,
263 struct ovsdb_symbol_table *symtab)
265 struct ovsdb_error *error0;
266 const struct json *value;
268 error0 = unwrap_json(json, "uuid", JSON_STRING, &value);
270 const char *uuid_string = json_string(value);
271 if (!uuid_from_string(uuid, uuid_string)) {
272 return ovsdb_syntax_error(json, NULL, "\"%s\" is not a valid UUID",
276 struct ovsdb_error *error1;
278 error1 = unwrap_json(json, "named-uuid", JSON_STRING, &value);
280 const char *name = json_string(value);
282 ovsdb_error_destroy(error0);
283 *uuid = ovsdb_symbol_table_insert(symtab, name)->uuid;
286 ovsdb_error_destroy(error1);
292 static struct ovsdb_error * WARN_UNUSED_RESULT
293 ovsdb_atom_from_json__(union ovsdb_atom *atom, enum ovsdb_atomic_type type,
294 const struct json *json,
295 struct ovsdb_symbol_table *symtab)
298 case OVSDB_TYPE_VOID:
301 case OVSDB_TYPE_INTEGER:
302 if (json->type == JSON_INTEGER) {
303 atom->integer = json->u.integer;
308 case OVSDB_TYPE_REAL:
309 if (json->type == JSON_INTEGER) {
310 atom->real = json->u.integer;
312 } else if (json->type == JSON_REAL) {
313 atom->real = json->u.real;
318 case OVSDB_TYPE_BOOLEAN:
319 if (json->type == JSON_TRUE) {
320 atom->boolean = true;
322 } else if (json->type == JSON_FALSE) {
323 atom->boolean = false;
328 case OVSDB_TYPE_STRING:
329 if (json->type == JSON_STRING) {
330 atom->string = xstrdup(json->u.string);
335 case OVSDB_TYPE_UUID:
336 return ovsdb_atom_parse_uuid(&atom->uuid, json, symtab);
343 return ovsdb_syntax_error(json, NULL, "expected %s",
344 ovsdb_atomic_type_to_string(type));
347 /* Parses 'json' as an atom of the type described by 'base'. If successful,
348 * returns NULL and initializes 'atom' with the parsed atom. On failure,
349 * returns an error and the contents of 'atom' are indeterminate. The caller
350 * is responsible for freeing the error or the atom that is returned.
352 * If 'symtab' is nonnull, then named UUIDs in 'symtab' are accepted. Refer to
353 * ovsdb/SPECS information about this and other syntactical details. */
355 ovsdb_atom_from_json(union ovsdb_atom *atom,
356 const struct ovsdb_base_type *base,
357 const struct json *json,
358 struct ovsdb_symbol_table *symtab)
360 struct ovsdb_error *error;
362 error = ovsdb_atom_from_json__(atom, base->type, json, symtab);
367 error = ovsdb_atom_check_constraints(atom, base);
369 ovsdb_atom_destroy(atom, base->type);
374 /* Converts 'atom', of the specified 'type', to JSON format, and returns the
375 * JSON. The caller is responsible for freeing the returned JSON. */
377 ovsdb_atom_to_json(const union ovsdb_atom *atom, enum ovsdb_atomic_type type)
380 case OVSDB_TYPE_VOID:
383 case OVSDB_TYPE_INTEGER:
384 return json_integer_create(atom->integer);
386 case OVSDB_TYPE_REAL:
387 return json_real_create(atom->real);
389 case OVSDB_TYPE_BOOLEAN:
390 return json_boolean_create(atom->boolean);
392 case OVSDB_TYPE_STRING:
393 return json_string_create(atom->string);
395 case OVSDB_TYPE_UUID:
396 return wrap_json("uuid", json_string_create_nocopy(
397 xasprintf(UUID_FMT, UUID_ARGS(&atom->uuid))));
406 ovsdb_atom_from_string__(union ovsdb_atom *atom, enum ovsdb_atomic_type type,
407 const char *s, struct ovsdb_symbol_table *symtab)
410 case OVSDB_TYPE_VOID:
413 case OVSDB_TYPE_INTEGER: {
414 long long int integer;
415 if (!str_to_llong(s, 10, &integer)) {
416 return xasprintf("\"%s\" is not a valid integer", s);
418 atom->integer = integer;
422 case OVSDB_TYPE_REAL:
423 if (!str_to_double(s, &atom->real)) {
424 return xasprintf("\"%s\" is not a valid real number", s);
426 /* Our JSON input routines map negative zero to zero, so do that here
427 * too for consistency. */
428 if (atom->real == 0.0) {
433 case OVSDB_TYPE_BOOLEAN:
434 if (!strcmp(s, "true") || !strcmp(s, "yes") || !strcmp(s, "on")
435 || !strcmp(s, "1")) {
436 atom->boolean = true;
437 } else if (!strcmp(s, "false") || !strcmp(s, "no") || !strcmp(s, "off")
438 || !strcmp(s, "0")) {
439 atom->boolean = false;
441 return xasprintf("\"%s\" is not a valid boolean "
442 "(use \"true\" or \"false\")", s);
446 case OVSDB_TYPE_STRING:
448 return xstrdup("An empty string is not valid as input; "
449 "use \"\" to represent the empty string");
450 } else if (*s == '"') {
451 size_t s_len = strlen(s);
453 if (s_len < 2 || s[s_len - 1] != '"') {
454 return xasprintf("%s: missing quote at end of "
456 } else if (!json_string_unescape(s + 1, s_len - 2,
458 char *error = xasprintf("%s: %s", s, atom->string);
463 atom->string = xstrdup(s);
467 case OVSDB_TYPE_UUID:
469 atom->uuid = ovsdb_symbol_table_insert(symtab, s)->uuid;
470 } else if (!uuid_from_string(&atom->uuid, s)) {
471 return xasprintf("\"%s\" is not a valid UUID", s);
483 /* Initializes 'atom' to a value of type 'base' parsed from 's', which takes
484 * one of the following forms:
486 * - OVSDB_TYPE_INTEGER: A decimal integer optionally preceded by a sign.
488 * - OVSDB_TYPE_REAL: A floating-point number in the format accepted by
491 * - OVSDB_TYPE_BOOLEAN: "true", "yes", "on", "1" for true, or "false",
492 * "no", "off", or "0" for false.
494 * - OVSDB_TYPE_STRING: A JSON string if it begins with a quote, otherwise
495 * an arbitrary string.
497 * - OVSDB_TYPE_UUID: A UUID in RFC 4122 format. If 'symtab' is nonnull,
498 * then an identifier beginning with '@' is also acceptable. If the
499 * named identifier is already in 'symtab', then the associated UUID is
500 * used; otherwise, a new, random UUID is used and added to the symbol
503 * Returns a null pointer if successful, otherwise an error message describing
504 * the problem. On failure, the contents of 'atom' are indeterminate. The
505 * caller is responsible for freeing the atom or the error.
508 ovsdb_atom_from_string(union ovsdb_atom *atom,
509 const struct ovsdb_base_type *base, const char *s,
510 struct ovsdb_symbol_table *symtab)
512 struct ovsdb_error *error;
515 msg = ovsdb_atom_from_string__(atom, base->type, s, symtab);
520 error = ovsdb_atom_check_constraints(atom, base);
522 msg = ovsdb_error_to_string(error);
523 ovsdb_error_destroy(error);
529 string_needs_quotes(const char *s)
535 if (!isalpha(c) && c != '_') {
539 while ((c = *p++) != '\0') {
540 if (!isalpha(c) && c != '_' && c != '-' && c != '.') {
545 if (!strcmp(s, "true") || !strcmp(s, "false")) {
552 /* Appends 'atom' (which has the given 'type') to 'out', in a format acceptable
553 * to ovsdb_atom_from_string(). */
555 ovsdb_atom_to_string(const union ovsdb_atom *atom, enum ovsdb_atomic_type type,
559 case OVSDB_TYPE_VOID:
562 case OVSDB_TYPE_INTEGER:
563 ds_put_format(out, "%"PRId64, atom->integer);
566 case OVSDB_TYPE_REAL:
567 ds_put_format(out, "%.*g", DBL_DIG, atom->real);
570 case OVSDB_TYPE_BOOLEAN:
571 ds_put_cstr(out, atom->boolean ? "true" : "false");
574 case OVSDB_TYPE_STRING:
575 if (string_needs_quotes(atom->string)) {
578 json.type = JSON_STRING;
579 json.u.string = atom->string;
580 json_to_ds(&json, 0, out);
582 ds_put_cstr(out, atom->string);
586 case OVSDB_TYPE_UUID:
587 ds_put_format(out, UUID_FMT, UUID_ARGS(&atom->uuid));
596 static struct ovsdb_error *
597 check_string_constraints(const char *s,
598 const struct ovsdb_string_constraints *c)
603 msg = utf8_validate(s, &n_chars);
605 struct ovsdb_error *error;
607 error = ovsdb_error("constraint violation",
608 "\"%s\" is not a valid UTF-8 string: %s",
614 if (n_chars < c->minLen) {
616 "constraint violation",
617 "\"%s\" length %zu is less than minimum allowed "
618 "length %u", s, n_chars, c->minLen);
619 } else if (n_chars > c->maxLen) {
621 "constraint violation",
622 "\"%s\" length %zu is greater than maximum allowed "
623 "length %u", s, n_chars, c->maxLen);
629 /* Checks whether 'atom' meets the constraints (if any) defined in 'base'.
630 * (base->type must specify 'atom''s type.) Returns a null pointer if the
631 * constraints are met, otherwise an error that explains the violation.
633 * Checking UUID constraints is deferred to transaction commit time, so this
634 * function does nothing for UUID constraints. */
636 ovsdb_atom_check_constraints(const union ovsdb_atom *atom,
637 const struct ovsdb_base_type *base)
640 && ovsdb_datum_find_key(base->enum_, atom, base->type) == UINT_MAX) {
641 struct ovsdb_error *error;
642 struct ds actual = DS_EMPTY_INITIALIZER;
643 struct ds valid = DS_EMPTY_INITIALIZER;
645 ovsdb_atom_to_string(atom, base->type, &actual);
646 ovsdb_datum_to_string(base->enum_,
647 ovsdb_base_type_get_enum_type(base->type),
649 error = ovsdb_error("constraint violation",
650 "%s is not one of the allowed values (%s)",
651 ds_cstr(&actual), ds_cstr(&valid));
658 switch (base->type) {
659 case OVSDB_TYPE_VOID:
662 case OVSDB_TYPE_INTEGER:
663 if (atom->integer >= base->u.integer.min
664 && atom->integer <= base->u.integer.max) {
666 } else if (base->u.integer.min != INT64_MIN) {
667 if (base->u.integer.max != INT64_MAX) {
668 return ovsdb_error("constraint violation",
669 "%"PRId64" is not in the valid range "
670 "%"PRId64" to %"PRId64" (inclusive)",
672 base->u.integer.min, base->u.integer.max);
674 return ovsdb_error("constraint violation",
675 "%"PRId64" is less than minimum allowed "
677 atom->integer, base->u.integer.min);
680 return ovsdb_error("constraint violation",
681 "%"PRId64" is greater than maximum allowed "
683 atom->integer, base->u.integer.max);
687 case OVSDB_TYPE_REAL:
688 if (atom->real >= base->u.real.min && atom->real <= base->u.real.max) {
690 } else if (base->u.real.min != -DBL_MAX) {
691 if (base->u.real.max != DBL_MAX) {
692 return ovsdb_error("constraint violation",
693 "%.*g is not in the valid range "
694 "%.*g to %.*g (inclusive)",
696 DBL_DIG, base->u.real.min,
697 DBL_DIG, base->u.real.max);
699 return ovsdb_error("constraint violation",
700 "%.*g is less than minimum allowed "
703 DBL_DIG, base->u.real.min);
706 return ovsdb_error("constraint violation",
707 "%.*g is greater than maximum allowed "
710 DBL_DIG, base->u.real.max);
714 case OVSDB_TYPE_BOOLEAN:
717 case OVSDB_TYPE_STRING:
718 return check_string_constraints(atom->string, &base->u.string);
720 case OVSDB_TYPE_UUID:
729 static union ovsdb_atom *
730 alloc_default_atoms(enum ovsdb_atomic_type type, size_t n)
732 if (type != OVSDB_TYPE_VOID && n) {
733 union ovsdb_atom *atoms;
736 atoms = xmalloc(n * sizeof *atoms);
737 for (i = 0; i < n; i++) {
738 ovsdb_atom_init_default(&atoms[i], type);
742 /* Avoid wasting memory in the n == 0 case, because xmalloc(0) is
743 * treated as xmalloc(1). */
748 /* Initializes 'datum' as an empty datum. (An empty datum can be treated as
751 ovsdb_datum_init_empty(struct ovsdb_datum *datum)
755 datum->values = NULL;
758 /* Initializes 'datum' as a datum that has the default value for 'type'.
760 * The default value for a particular type is as defined in ovsdb/SPECS:
762 * - If n_min is 0, then the default value is the empty set (or map).
764 * - If n_min is 1, the default value is a single value or a single
765 * key-value pair, whose key and value are the defaults for their
766 * atomic types. (See ovsdb_atom_init_default() for details.)
768 * - n_min > 1 is invalid. See ovsdb_type_is_valid().
771 ovsdb_datum_init_default(struct ovsdb_datum *datum,
772 const struct ovsdb_type *type)
774 datum->n = type->n_min;
775 datum->keys = alloc_default_atoms(type->key.type, datum->n);
776 datum->values = alloc_default_atoms(type->value.type, datum->n);
779 /* Returns true if 'datum', which must have the given 'type', has the default
780 * value for that type.
782 * See ovsdb_datum_init_default() for an explanation of the default value of a
785 ovsdb_datum_is_default(const struct ovsdb_datum *datum,
786 const struct ovsdb_type *type)
790 if (datum->n != type->n_min) {
793 for (i = 0; i < datum->n; i++) {
794 if (!ovsdb_atom_is_default(&datum->keys[i], type->key.type)) {
797 if (type->value.type != OVSDB_TYPE_VOID
798 && !ovsdb_atom_is_default(&datum->values[i], type->value.type)) {
806 static union ovsdb_atom *
807 clone_atoms(const union ovsdb_atom *old, enum ovsdb_atomic_type type, size_t n)
809 if (type != OVSDB_TYPE_VOID && n) {
810 union ovsdb_atom *new;
813 new = xmalloc(n * sizeof *new);
814 for (i = 0; i < n; i++) {
815 ovsdb_atom_clone(&new[i], &old[i], type);
819 /* Avoid wasting memory in the n == 0 case, because xmalloc(0) is
820 * treated as xmalloc(1). */
825 /* Initializes 'new' as a copy of 'old', with the given 'type'.
827 * The caller must eventually arrange for 'new' to be destroyed (with
828 * ovsdb_datum_destroy()). */
830 ovsdb_datum_clone(struct ovsdb_datum *new, const struct ovsdb_datum *old,
831 const struct ovsdb_type *type)
833 unsigned int n = old->n;
835 new->keys = clone_atoms(old->keys, type->key.type, n);
836 new->values = clone_atoms(old->values, type->value.type, n);
840 free_data(enum ovsdb_atomic_type type,
841 union ovsdb_atom *atoms, size_t n_atoms)
843 if (ovsdb_atom_needs_destruction(type)) {
845 for (i = 0; i < n_atoms; i++) {
846 ovsdb_atom_destroy(&atoms[i], type);
852 /* Frees the data owned by 'datum', which must have the given 'type'.
854 * This does not actually call free(datum). If necessary, the caller must be
855 * responsible for that. */
857 ovsdb_datum_destroy(struct ovsdb_datum *datum, const struct ovsdb_type *type)
859 free_data(type->key.type, datum->keys, datum->n);
860 free_data(type->value.type, datum->values, datum->n);
863 /* Swaps the contents of 'a' and 'b', which need not have the same type. */
865 ovsdb_datum_swap(struct ovsdb_datum *a, struct ovsdb_datum *b)
867 struct ovsdb_datum tmp = *a;
872 struct ovsdb_datum_sort_cbdata {
873 enum ovsdb_atomic_type key_type;
874 struct ovsdb_datum *datum;
878 ovsdb_datum_sort_compare_cb(size_t a, size_t b, void *cbdata_)
880 struct ovsdb_datum_sort_cbdata *cbdata = cbdata_;
882 return ovsdb_atom_compare_3way(&cbdata->datum->keys[a],
883 &cbdata->datum->keys[b],
888 ovsdb_datum_sort_swap_cb(size_t a, size_t b, void *cbdata_)
890 struct ovsdb_datum_sort_cbdata *cbdata = cbdata_;
892 ovsdb_atom_swap(&cbdata->datum->keys[a], &cbdata->datum->keys[b]);
893 if (cbdata->datum->values) {
894 ovsdb_atom_swap(&cbdata->datum->values[a], &cbdata->datum->values[b]);
898 /* The keys in an ovsdb_datum must be unique and in sorted order. Most
899 * functions that modify an ovsdb_datum maintain these invariants. For those
900 * that don't, this function checks and restores these invariants for 'datum',
901 * whose keys are of type 'key_type'.
903 * This function returns NULL if successful, otherwise an error message. The
904 * caller must free the returned error when it is no longer needed. On error,
905 * 'datum' is sorted but not unique. */
907 ovsdb_datum_sort(struct ovsdb_datum *datum, enum ovsdb_atomic_type key_type)
912 struct ovsdb_datum_sort_cbdata cbdata;
915 cbdata.key_type = key_type;
916 cbdata.datum = datum;
917 sort(datum->n, ovsdb_datum_sort_compare_cb, ovsdb_datum_sort_swap_cb,
920 for (i = 0; i < datum->n - 1; i++) {
921 if (ovsdb_atom_equals(&datum->keys[i], &datum->keys[i + 1],
924 return ovsdb_error(NULL, "map contains duplicate key");
926 return ovsdb_error(NULL, "set contains duplicate");
935 /* This function is the same as ovsdb_datum_sort(), except that the caller
936 * knows that 'datum' is unique. The operation therefore "cannot fail", so
937 * this function assert-fails if it actually does. */
939 ovsdb_datum_sort_assert(struct ovsdb_datum *datum,
940 enum ovsdb_atomic_type key_type)
942 struct ovsdb_error *error = ovsdb_datum_sort(datum, key_type);
948 /* Checks that each of the atoms in 'datum' conforms to the constraints
949 * specified by its 'type'. Returns an error if a constraint is violated,
950 * otherwise a null pointer.
952 * This function is not commonly useful because the most ordinary way to obtain
953 * a datum is ultimately via ovsdb_atom_from_string() or
954 * ovsdb_atom_from_json(), which check constraints themselves. */
956 ovsdb_datum_check_constraints(const struct ovsdb_datum *datum,
957 const struct ovsdb_type *type)
959 struct ovsdb_error *error;
962 for (i = 0; i < datum->n; i++) {
963 error = ovsdb_atom_check_constraints(&datum->keys[i], &type->key);
969 if (type->value.type != OVSDB_TYPE_VOID) {
970 for (i = 0; i < datum->n; i++) {
971 error = ovsdb_atom_check_constraints(&datum->values[i],
983 ovsdb_datum_from_json(struct ovsdb_datum *datum,
984 const struct ovsdb_type *type,
985 const struct json *json,
986 struct ovsdb_symbol_table *symtab)
988 struct ovsdb_error *error;
990 if (ovsdb_type_is_map(type)
991 || (json->type == JSON_ARRAY
992 && json->u.array.n > 0
993 && json->u.array.elems[0]->type == JSON_STRING
994 && !strcmp(json->u.array.elems[0]->u.string, "set"))) {
995 bool is_map = ovsdb_type_is_map(type);
996 const char *class = is_map ? "map" : "set";
997 const struct json *inner;
1001 error = unwrap_json(json, class, JSON_ARRAY, &inner);
1006 n = inner->u.array.n;
1007 if (n < type->n_min || n > type->n_max) {
1008 return ovsdb_syntax_error(json, NULL, "%s must have %u to "
1009 "%u members but %zu are present",
1010 class, type->n_min, type->n_max, n);
1014 datum->keys = xmalloc(n * sizeof *datum->keys);
1015 datum->values = is_map ? xmalloc(n * sizeof *datum->values) : NULL;
1016 for (i = 0; i < n; i++) {
1017 const struct json *element = inner->u.array.elems[i];
1018 const struct json *key = NULL;
1019 const struct json *value = NULL;
1024 error = parse_json_pair(element, &key, &value);
1030 error = ovsdb_atom_from_json(&datum->keys[i], &type->key,
1037 error = ovsdb_atom_from_json(&datum->values[i],
1038 &type->value, value, symtab);
1040 ovsdb_atom_destroy(&datum->keys[i], type->key.type);
1048 error = ovsdb_datum_sort(datum, type->key.type);
1056 ovsdb_datum_destroy(datum, type);
1060 datum->keys = xmalloc(sizeof *datum->keys);
1061 datum->values = NULL;
1063 error = ovsdb_atom_from_json(&datum->keys[0], &type->key,
1073 ovsdb_datum_to_json(const struct ovsdb_datum *datum,
1074 const struct ovsdb_type *type)
1076 /* These tests somewhat tolerate a 'datum' that does not exactly match
1077 * 'type', in particular a datum with 'n' not in the allowed range. */
1078 if (datum->n == 1 && !ovsdb_type_is_map(type)) {
1079 return ovsdb_atom_to_json(&datum->keys[0], type->key.type);
1080 } else if (type->value.type == OVSDB_TYPE_VOID) {
1081 struct json **elems;
1084 elems = xmalloc(datum->n * sizeof *elems);
1085 for (i = 0; i < datum->n; i++) {
1086 elems[i] = ovsdb_atom_to_json(&datum->keys[i], type->key.type);
1089 return wrap_json("set", json_array_create(elems, datum->n));
1091 struct json **elems;
1094 elems = xmalloc(datum->n * sizeof *elems);
1095 for (i = 0; i < datum->n; i++) {
1096 elems[i] = json_array_create_2(
1097 ovsdb_atom_to_json(&datum->keys[i], type->key.type),
1098 ovsdb_atom_to_json(&datum->values[i], type->value.type));
1101 return wrap_json("map", json_array_create(elems, datum->n));
1106 skip_spaces(const char *p)
1108 while (isspace((unsigned char) *p)) {
1115 parse_atom_token(const char **s, const struct ovsdb_base_type *base,
1116 union ovsdb_atom *atom, struct ovsdb_symbol_table *symtab)
1118 char *token, *error;
1120 error = ovsdb_token_parse(s, &token);
1122 error = ovsdb_atom_from_string(atom, base, token, symtab);
1129 parse_key_value(const char **s, const struct ovsdb_type *type,
1130 union ovsdb_atom *key, union ovsdb_atom *value,
1131 struct ovsdb_symbol_table *symtab)
1133 const char *start = *s;
1136 error = parse_atom_token(s, &type->key, key, symtab);
1137 if (!error && type->value.type != OVSDB_TYPE_VOID) {
1138 *s = skip_spaces(*s);
1141 *s = skip_spaces(*s);
1142 error = parse_atom_token(s, &type->value, value, symtab);
1144 error = xasprintf("%s: syntax error at \"%c\" expecting \"=\"",
1148 ovsdb_atom_destroy(key, type->key.type);
1155 free_key_value(const struct ovsdb_type *type,
1156 union ovsdb_atom *key, union ovsdb_atom *value)
1158 ovsdb_atom_destroy(key, type->key.type);
1159 if (type->value.type != OVSDB_TYPE_VOID) {
1160 ovsdb_atom_destroy(value, type->value.type);
1164 /* Initializes 'datum' as a datum of the given 'type', parsing its contents
1165 * from 's'. The format of 's' is a series of space or comma separated atoms
1166 * or, for a map, '='-delimited pairs of atoms. Each atom must in a format
1167 * acceptable to ovsdb_atom_from_string(). Optionally, a set may be enclosed
1168 * in "[]" or a map in "{}"; for an empty set or map these punctuators are
1171 * Optionally, a symbol table may be supplied as 'symtab'. It is passed to
1172 * ovsdb_atom_to_string(). */
1174 ovsdb_datum_from_string(struct ovsdb_datum *datum,
1175 const struct ovsdb_type *type, const char *s,
1176 struct ovsdb_symbol_table *symtab)
1178 bool is_map = ovsdb_type_is_map(type);
1179 struct ovsdb_error *dberror;
1184 ovsdb_datum_init_empty(datum);
1186 /* Swallow a leading delimiter if there is one. */
1188 if (*p == (is_map ? '{' : '[')) {
1189 end_delim = is_map ? '}' : ']';
1190 p = skip_spaces(p + 1);
1193 return xstrdup("use \"{}\" to specify the empty map");
1195 return xstrdup("use \"[]\" to specify the empty set");
1201 while (*p && *p != end_delim) {
1202 union ovsdb_atom key, value;
1204 if (ovsdb_token_is_delim(*p)) {
1205 error = xasprintf("%s: unexpected \"%c\" parsing %s",
1206 s, *p, ovsdb_type_to_english(type));
1211 error = parse_key_value(&p, type, &key, &value, symtab);
1215 ovsdb_datum_add_unsafe(datum, &key, &value, type);
1216 free_key_value(type, &key, &value);
1218 /* Skip optional white space and comma. */
1221 p = skip_spaces(p + 1);
1225 if (*p != end_delim) {
1226 error = xasprintf("%s: missing \"%c\" at end of data", s, end_delim);
1230 p = skip_spaces(p + 1);
1232 error = xasprintf("%s: trailing garbage after \"%c\"",
1238 if (datum->n < type->n_min) {
1239 error = xasprintf("%s: %u %s specified but the minimum number is %u",
1240 s, datum->n, is_map ? "pair(s)" : "value(s)",
1243 } else if (datum->n > type->n_max) {
1244 error = xasprintf("%s: %u %s specified but the maximum number is %u",
1245 s, datum->n, is_map ? "pair(s)" : "value(s)",
1250 dberror = ovsdb_datum_sort(datum, type->key.type);
1252 ovsdb_error_destroy(dberror);
1253 if (ovsdb_type_is_map(type)) {
1254 error = xasprintf("%s: map contains duplicate key", s);
1256 error = xasprintf("%s: set contains duplicate value", s);
1264 ovsdb_datum_destroy(datum, type);
1265 ovsdb_datum_init_empty(datum);
1269 /* Appends to 'out' the 'datum' (with the given 'type') in a format acceptable
1270 * to ovsdb_datum_from_string(). */
1272 ovsdb_datum_to_string(const struct ovsdb_datum *datum,
1273 const struct ovsdb_type *type, struct ds *out)
1275 bool is_map = ovsdb_type_is_map(type);
1278 if (type->n_max > 1 || !datum->n) {
1279 ds_put_char(out, is_map ? '{' : '[');
1281 for (i = 0; i < datum->n; i++) {
1283 ds_put_cstr(out, ", ");
1286 ovsdb_atom_to_string(&datum->keys[i], type->key.type, out);
1288 ds_put_char(out, '=');
1289 ovsdb_atom_to_string(&datum->values[i], type->value.type, out);
1292 if (type->n_max > 1 || !datum->n) {
1293 ds_put_char(out, is_map ? '}' : ']');
1298 hash_atoms(enum ovsdb_atomic_type type, const union ovsdb_atom *atoms,
1299 unsigned int n, uint32_t basis)
1301 if (type != OVSDB_TYPE_VOID) {
1304 for (i = 0; i < n; i++) {
1305 basis = ovsdb_atom_hash(&atoms[i], type, basis);
1312 ovsdb_datum_hash(const struct ovsdb_datum *datum,
1313 const struct ovsdb_type *type, uint32_t basis)
1315 basis = hash_atoms(type->key.type, datum->keys, datum->n, basis);
1316 basis ^= (type->key.type << 24) | (type->value.type << 16) | datum->n;
1317 basis = hash_atoms(type->value.type, datum->values, datum->n, basis);
1322 atom_arrays_compare_3way(const union ovsdb_atom *a,
1323 const union ovsdb_atom *b,
1324 enum ovsdb_atomic_type type,
1329 for (i = 0; i < n; i++) {
1330 int cmp = ovsdb_atom_compare_3way(&a[i], &b[i], type);
1340 ovsdb_datum_equals(const struct ovsdb_datum *a,
1341 const struct ovsdb_datum *b,
1342 const struct ovsdb_type *type)
1344 return !ovsdb_datum_compare_3way(a, b, type);
1348 ovsdb_datum_compare_3way(const struct ovsdb_datum *a,
1349 const struct ovsdb_datum *b,
1350 const struct ovsdb_type *type)
1355 return a->n < b->n ? -1 : 1;
1358 cmp = atom_arrays_compare_3way(a->keys, b->keys, type->key.type, a->n);
1363 return (type->value.type == OVSDB_TYPE_VOID ? 0
1364 : atom_arrays_compare_3way(a->values, b->values, type->value.type,
1368 /* If 'key' is one of the keys in 'datum', returns its index within 'datum',
1369 * otherwise UINT_MAX. 'key.type' must be the type of the atoms stored in the
1370 * 'keys' array in 'datum'.
1373 ovsdb_datum_find_key(const struct ovsdb_datum *datum,
1374 const union ovsdb_atom *key,
1375 enum ovsdb_atomic_type key_type)
1377 unsigned int low = 0;
1378 unsigned int high = datum->n;
1379 while (low < high) {
1380 unsigned int idx = (low + high) / 2;
1381 int cmp = ovsdb_atom_compare_3way(key, &datum->keys[idx], key_type);
1384 } else if (cmp > 0) {
1393 /* If 'key' and 'value' is one of the key-value pairs in 'datum', returns its
1394 * index within 'datum', otherwise UINT_MAX. 'key.type' must be the type of
1395 * the atoms stored in the 'keys' array in 'datum'. 'value_type' may be the
1396 * type of the 'values' atoms or OVSDB_TYPE_VOID to compare only keys.
1399 ovsdb_datum_find_key_value(const struct ovsdb_datum *datum,
1400 const union ovsdb_atom *key,
1401 enum ovsdb_atomic_type key_type,
1402 const union ovsdb_atom *value,
1403 enum ovsdb_atomic_type value_type)
1405 unsigned int idx = ovsdb_datum_find_key(datum, key, key_type);
1407 && value_type != OVSDB_TYPE_VOID
1408 && !ovsdb_atom_equals(&datum->values[idx], value, value_type)) {
1414 /* If atom 'i' in 'a' is also in 'b', returns its index in 'b', otherwise
1415 * UINT_MAX. 'type' must be the type of 'a' and 'b', except that
1416 * type->value.type may be set to OVSDB_TYPE_VOID to compare keys but not
1419 ovsdb_datum_find(const struct ovsdb_datum *a, int i,
1420 const struct ovsdb_datum *b,
1421 const struct ovsdb_type *type)
1423 return ovsdb_datum_find_key_value(b,
1424 &a->keys[i], type->key.type,
1425 a->values ? &a->values[i] : NULL,
1429 /* Returns true if every element in 'a' is also in 'b', false otherwise. */
1431 ovsdb_datum_includes_all(const struct ovsdb_datum *a,
1432 const struct ovsdb_datum *b,
1433 const struct ovsdb_type *type)
1437 for (i = 0; i < a->n; i++) {
1438 if (ovsdb_datum_find(a, i, b, type) == UINT_MAX) {
1445 /* Returns true if no element in 'a' is also in 'b', false otherwise. */
1447 ovsdb_datum_excludes_all(const struct ovsdb_datum *a,
1448 const struct ovsdb_datum *b,
1449 const struct ovsdb_type *type)
1453 for (i = 0; i < a->n; i++) {
1454 if (ovsdb_datum_find(a, i, b, type) != UINT_MAX) {
1462 ovsdb_datum_reallocate(struct ovsdb_datum *a, const struct ovsdb_type *type,
1463 unsigned int capacity)
1465 a->keys = xrealloc(a->keys, capacity * sizeof *a->keys);
1466 if (type->value.type != OVSDB_TYPE_VOID) {
1467 a->values = xrealloc(a->values, capacity * sizeof *a->values);
1471 /* Removes the element with index 'idx' from 'datum', which has type 'type'.
1472 * If 'idx' is not the last element in 'datum', then the removed element is
1473 * replaced by the (former) last element.
1475 * This function does not maintain ovsdb_datum invariants. Use
1476 * ovsdb_datum_sort() to check and restore these invariants. */
1478 ovsdb_datum_remove_unsafe(struct ovsdb_datum *datum, size_t idx,
1479 const struct ovsdb_type *type)
1481 ovsdb_atom_destroy(&datum->keys[idx], type->key.type);
1482 datum->keys[idx] = datum->keys[datum->n - 1];
1483 if (type->value.type != OVSDB_TYPE_VOID) {
1484 ovsdb_atom_destroy(&datum->values[idx], type->value.type);
1485 datum->values[idx] = datum->values[datum->n - 1];
1490 /* Adds the element with the given 'key' and 'value' to 'datum', which must
1491 * have the specified 'type'.
1493 * This function always allocates memory, so it is not an efficient way to add
1494 * a number of elements to a datum.
1496 * This function does not maintain ovsdb_datum invariants. Use
1497 * ovsdb_datum_sort() to check and restore these invariants. (But a datum with
1498 * 0 or 1 elements cannot violate the invariants anyhow.) */
1500 ovsdb_datum_add_unsafe(struct ovsdb_datum *datum,
1501 const union ovsdb_atom *key,
1502 const union ovsdb_atom *value,
1503 const struct ovsdb_type *type)
1505 size_t idx = datum->n++;
1506 datum->keys = xrealloc(datum->keys, datum->n * sizeof *datum->keys);
1507 ovsdb_atom_clone(&datum->keys[idx], key, type->key.type);
1508 if (type->value.type != OVSDB_TYPE_VOID) {
1509 datum->values = xrealloc(datum->values,
1510 datum->n * sizeof *datum->values);
1511 ovsdb_atom_clone(&datum->values[idx], value, type->value.type);
1516 ovsdb_datum_union(struct ovsdb_datum *a, const struct ovsdb_datum *b,
1517 const struct ovsdb_type *type, bool replace)
1523 for (bi = 0; bi < b->n; bi++) {
1526 ai = ovsdb_datum_find_key(a, &b->keys[bi], type->key.type);
1527 if (ai == UINT_MAX) {
1529 ovsdb_datum_reallocate(a, type, a->n + (b->n - bi));
1531 ovsdb_atom_clone(&a->keys[n], &b->keys[bi], type->key.type);
1532 if (type->value.type != OVSDB_TYPE_VOID) {
1533 ovsdb_atom_clone(&a->values[n], &b->values[bi],
1537 } else if (replace && type->value.type != OVSDB_TYPE_VOID) {
1538 ovsdb_atom_destroy(&a->values[ai], type->value.type);
1539 ovsdb_atom_clone(&a->values[ai], &b->values[bi],
1544 struct ovsdb_error *error;
1546 error = ovsdb_datum_sort(a, type->key.type);
1552 ovsdb_datum_subtract(struct ovsdb_datum *a, const struct ovsdb_type *a_type,
1553 const struct ovsdb_datum *b,
1554 const struct ovsdb_type *b_type)
1556 bool changed = false;
1559 assert(a_type->key.type == b_type->key.type);
1560 assert(a_type->value.type == b_type->value.type
1561 || b_type->value.type == OVSDB_TYPE_VOID);
1563 /* XXX The big-O of this could easily be improved. */
1564 for (i = 0; i < a->n; ) {
1565 unsigned int idx = ovsdb_datum_find(a, i, b, b_type);
1566 if (idx != UINT_MAX) {
1568 ovsdb_datum_remove_unsafe(a, i, a_type);
1574 ovsdb_datum_sort_assert(a, a_type->key.type);
1578 struct ovsdb_symbol_table {
1582 struct ovsdb_symbol_table *
1583 ovsdb_symbol_table_create(void)
1585 struct ovsdb_symbol_table *symtab = xmalloc(sizeof *symtab);
1586 shash_init(&symtab->sh);
1591 ovsdb_symbol_table_destroy(struct ovsdb_symbol_table *symtab)
1594 shash_destroy_free_data(&symtab->sh);
1599 struct ovsdb_symbol *
1600 ovsdb_symbol_table_get(const struct ovsdb_symbol_table *symtab,
1603 return shash_find_data(&symtab->sh, name);
1606 struct ovsdb_symbol *
1607 ovsdb_symbol_table_put(struct ovsdb_symbol_table *symtab, const char *name,
1608 const struct uuid *uuid, bool used)
1610 struct ovsdb_symbol *symbol;
1612 assert(!ovsdb_symbol_table_get(symtab, name));
1613 symbol = xmalloc(sizeof *symbol);
1614 symbol->uuid = *uuid;
1615 symbol->used = used;
1616 shash_add(&symtab->sh, name, symbol);
1620 struct ovsdb_symbol *
1621 ovsdb_symbol_table_insert(struct ovsdb_symbol_table *symtab,
1624 struct ovsdb_symbol *symbol;
1626 symbol = ovsdb_symbol_table_get(symtab, name);
1630 uuid_generate(&uuid);
1631 symbol = ovsdb_symbol_table_put(symtab, name, &uuid, false);
1637 ovsdb_symbol_table_find_unused(const struct ovsdb_symbol_table *symtab)
1639 struct shash_node *node;
1641 SHASH_FOR_EACH (node, &symtab->sh) {
1642 struct ovsdb_symbol *symbol = node->data;
1643 if (!symbol->used) {
1651 /* Extracts a token from the beginning of 's' and returns a pointer just after
1652 * the token. Stores the token itself into '*outp', which the caller is
1653 * responsible for freeing (with free()).
1655 * If 's[0]' is a delimiter, the returned token is the empty string.
1657 * A token extends from 's' to the first delimiter, as defined by
1658 * ovsdb_token_is_delim(), or until the end of the string. A delimiter can be
1659 * escaped with a backslash, in which case the backslash does not appear in the
1660 * output. Double quotes also cause delimiters to be ignored, but the double
1661 * quotes are retained in the output. (Backslashes inside double quotes are
1662 * not removed, either.)
1665 ovsdb_token_parse(const char **s, char **outp)
1674 for (p = *s; *p != '\0'; ) {
1678 ds_put_char(&out, '\\');
1681 error = xasprintf("%s: backslash at end of argument", *s);
1684 ds_put_char(&out, *p++);
1685 } else if (!in_quotes && ovsdb_token_is_delim(c)) {
1689 ds_put_char(&out, c);
1691 in_quotes = !in_quotes;
1696 error = xasprintf("%s: quoted string extends past end of argument",
1700 *outp = ds_cstr(&out);
1710 /* Returns true if 'c' delimits tokens, or if 'c' is 0, and false otherwise. */
1712 ovsdb_token_is_delim(unsigned char c)
1714 return strchr(":=, []{}!<>", c) != NULL;