UNPKG

1.38 kBJavaScriptView Raw
1function UUID(uuid) {
2 this._str;
3 this._buf;
4
5 if (typeof uuid === "string") {
6 uuid = uuid.replace('-','');
7 this._str = uuid;
8 this._buf = UUID.strToBuf(this._str);
9 }
10 else if (Buffer.isBuffer(uuid)) {
11 this._buf = uuid;
12 this._str = UUID.bufToStr(this._buf);
13 }
14 else {
15 throw new Error("UUID intializer must be string or buffer.");
16 }
17}
18
19UUID.prototype.toString = function() {
20 return this._str;
21}
22
23UUID.prototype.toBuffer = function() {
24 return this._buf;
25}
26
27UUID.strToBuf = function(uuidStr) {
28 // Every two hex values is a byte
29 var numBytes = uuidStr.length/2;
30
31 // Create the return buf
32 var buf = new Buffer(numBytes);
33
34 // If it's just an odd number, return nothing
35 if (numBytes % 2) {
36 throw new Error("Invalid UUID" + uuidStr + ".");
37 }
38
39 for (var i = 0; i < numBytes; i++) {
40 // The "0x" is a hack until beta/#206 is fixed
41 buf.writeUInt8(parseInt("0x" + uuidStr.substr((i*2), 2), 16), numBytes-i-1);
42 }
43
44 return buf;
45}
46
47UUID.bufToStr = function(uuidBuf) {
48 var str = "";
49 var length = uuidBuf.length;
50 var elem;
51
52 for (var i = 0; i < length; i++) {
53 elem = uuidBuf.readUInt8(length-1-i).toString(16);
54 if (elem.length === 1) {
55 elem = "0" + elem;
56 }
57 str += elem;
58
59 }
60 return str
61}
62
63module.exports = UUID;
64module.exports.bufToStr = UUID.bufToStr;
65module.exports.strToBuf = UUID.strToBuf;