]> git.jsancho.org Git - mojodb.git/blobdiff - objectid.py
Introducing ObjectId
[mojodb.git] / objectid.py
diff --git a/objectid.py b/objectid.py
new file mode 100644 (file)
index 0000000..0bf05c0
--- /dev/null
@@ -0,0 +1,62 @@
+# -*- coding: utf-8 -*-
+##############################################################################
+#
+#    mojo, a Python library for implementing document based databases
+#    Copyright (C) 2013-2014 by Javier Sancho Fernandez <jsf at jsancho dot org>
+#
+#    This program is free software: you can redistribute it and/or modify
+#    it under the terms of the GNU General Public License as published by
+#    the Free Software Foundation, either version 3 of the License, or
+#    (at your option) any later version.
+#
+#    This program is distributed in the hope that it will be useful,
+#    but WITHOUT ANY WARRANTY; without even the implied warranty of
+#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+#    GNU General Public License for more details.
+#
+#    You should have received a copy of the GNU General Public License
+#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+#
+##############################################################################
+
+import binascii
+import hashlib
+import os
+import random
+import socket
+import struct
+import time
+import threading
+
+class ObjectId(object):
+    _inc = random.randint(0, 0xFFFFFF)
+    _inc_lock = threading.Lock()
+
+    __id = ""
+
+    def __init__(self):
+        self.__generate()
+
+    def __generate(self):
+        oid = ""
+        # Secons since the Unix epoch
+        oid += struct.pack(">i", int(time.time()))
+        # Machine Identifier
+        machine_hash = hashlib.md5()
+        machine_hash.update(socket.gethostname())
+        oid += machine_hash.digest()[0:3]
+        # Process Id
+        oid += struct.pack(">H", os.getpid() % 0xFFFF)
+        # Counter
+        ObjectId._inc_lock.acquire()
+        oid += struct.pack(">i", ObjectId._inc)[1:4]
+        ObjectId._inc += 1
+        ObjectId._inc_lock.release()
+
+        self.__id = oid
+
+    def __str__(self):
+        return binascii.hexlify(self.__id)
+
+    def __repr__(self):
+        return "ObjectId('%s')" % (str(self),)