python: Accept multiple forms of strings and lists when parsing JSON.
[sliver-openvswitch.git] / python / ovs / ovsuuid.py
1 # Copyright (c) 2009, 2010, 2011 Nicira Networks
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at:
6 #
7 #     http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 import re
16 import uuid
17
18 from ovs.db import error
19 import ovs.db.parser
20
21 uuidRE = re.compile("^xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx$"
22                     .replace('x', '[0-9a-fA-F]'))
23
24 def zero():
25     return uuid.UUID(int=0)
26
27
28 def is_valid_string(s):
29     return uuidRE.match(s) is not None
30
31
32 def from_string(s):
33     if not is_valid_string(s):
34         raise error.Error("%s is not a valid UUID" % s)
35     return uuid.UUID(s)
36
37
38 def from_json(json, symtab=None):
39     try:
40         s = ovs.db.parser.unwrap_json(json, "uuid", [str, unicode], "string")
41         if not uuidRE.match(s):
42             raise error.Error("\"%s\" is not a valid UUID" % s, json)
43         return uuid.UUID(s)
44     except error.Error, e:
45         if not symtab:
46             raise e
47         try:
48             name = ovs.db.parser.unwrap_json(json, "named-uuid",
49                                              [str, unicode], "string")
50         except error.Error:
51             raise e
52
53         if name not in symtab:
54             symtab[name] = uuid4()
55         return symtab[name]
56
57
58 def to_json(uuid_):
59     return ["uuid", str(uuid_)]
60
61
62 def to_c_assignment(uuid_, var):
63     """Returns an array of strings, each of which contain a C statement.  The
64     statements assign 'uuid_' to a "struct uuid" as defined in Open vSwitch
65     lib/uuid.h."""
66
67     hex_string = uuid_.hex
68     return ["%s.parts[%d] = 0x%s;" % (var, x, hex_string[x * 8:(x + 1) * 8])
69             for x in range(4)]