From 8464d20e48292a369bc43ece52e7a996dd895008 Mon Sep 17 00:00:00 2001 From: "Rafael H. Schloming" Date: Tue, 29 Apr 2008 20:24:48 +0000 Subject: QPID-979: added backwards compatible uuid to qpid.datatypes git-svn-id: https://svn.apache.org/repos/asf/incubator/qpid/trunk@652086 13f79535-47bb-0310-9956-ffa450edef68 --- qpid/python/qpid/datatypes.py | 39 ++++++++++++++++++++++++++++++++++++++- qpid/python/tests/datatypes.py | 9 +++++++++ 2 files changed, 47 insertions(+), 1 deletion(-) (limited to 'qpid/python') diff --git a/qpid/python/qpid/datatypes.py b/qpid/python/qpid/datatypes.py index 0893269174..36b290700b 100644 --- a/qpid/python/qpid/datatypes.py +++ b/qpid/python/qpid/datatypes.py @@ -17,7 +17,7 @@ # under the License. # -import threading +import threading, struct class Struct: @@ -172,3 +172,40 @@ class Future: def is_set(self): return self._set.isSet() + +try: + import uuid + def random_uuid(): + return uuid.uuid4().get_bytes() +except ImportError: + import random + def random_uuid(): + bytes = [random.randint(0, 255) for i in xrange(16)] + + # From RFC4122, the version bits are set to 0100 + bytes[7] &= 0x0F + bytes[7] |= 0x40 + + # From RFC4122, the top two bits of byte 8 get set to 01 + bytes[8] &= 0x3F + bytes[8] |= 0x80 + return "".join(map(chr, bytes)) + +def uuid4(): + return UUID(random_uuid()) + +class UUID: + + def __init__(self, bytes): + self.bytes = bytes + + def __cmp__(self, other): + if isinstance(other, UUID): + return cmp(self.bytes, other.bytes) + raise NotImplemented() + + def __str__(self): + return "%08x-%04x-%04x-%04x-%04x%08x" % struct.unpack("!LHHHHL", self.bytes) + + def __repr__(self): + return "UUID(%r)" % str(self) diff --git a/qpid/python/tests/datatypes.py b/qpid/python/tests/datatypes.py index 7844cf4d10..e4d6723d95 100644 --- a/qpid/python/tests/datatypes.py +++ b/qpid/python/tests/datatypes.py @@ -100,3 +100,12 @@ class RangedSetTest(TestCase): range = a.ranges[0] assert range.lower == 0 assert range.upper == 8 + +class UUIDTest(TestCase): + + def test(self): + # this test is kind of lame, but it does excercise the basic + # functionality of the class + u = uuid4() + for i in xrange(1024): + assert u != uuid4() -- cgit v1.2.1