python/ovs/ovsuuid: Fix behavior of UUID.from_json() with no symbol table.
[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 class UUID(uuid.UUID):
22     x = "[0-9a-fA-f]"
23     uuidRE = re.compile("^(%s{8})-(%s{4})-(%s{4})-(%s{4})-(%s{4})(%s{8})$"
24                         % (x, x, x, x, x, x))
25
26     def __init__(self, s):
27         uuid.UUID.__init__(self, hex=s)
28
29     @staticmethod
30     def zero():
31         return UUID('00000000-0000-0000-0000-000000000000')
32
33     def is_zero(self):
34         return self.int == 0
35
36     @staticmethod
37     def is_valid_string(s):
38         return UUID.uuidRE.match(s) != None
39
40     @staticmethod
41     def from_string(s):
42         if not UUID.is_valid_string(s):
43             raise error.Error("%s is not a valid UUID" % s)
44         return UUID(s)
45
46     @staticmethod
47     def from_json(json, symtab=None):
48         try:
49             s = ovs.db.parser.unwrap_json(json, "uuid", unicode)
50             if not UUID.uuidRE.match(s):
51                 raise error.Error("\"%s\" is not a valid UUID" % s, json)
52             return UUID(s)
53         except error.Error, e:
54             if not symtab:
55                 raise e
56             try:
57                 name = ovs.db.parser.unwrap_json(json, "named-uuid", unicode)
58             except error.Error:
59                 raise e
60
61             if name not in symtab:
62                 symtab[name] = uuid4()
63             return symtab[name]
64
65     def to_json(self):
66         return ["uuid", str(self)]
67
68     def cInitUUID(self, var):
69         m = re.match(str(self))
70         return ["%s.parts[0] = 0x%s;" % (var, m.group(1)),
71                 "%s.parts[1] = 0x%s%s;" % (var, m.group(2), m.group(3)),
72                 "%s.parts[2] = 0x%s%s;" % (var, m.group(4), m.group(5)),
73                 "%s.parts[3] = 0x%s;" % (var, m.group(6))]
74