2017-11-21 15:09:26 +00:00
|
|
|
import * as validator from 'validator';
|
2017-11-24 17:45:34 +00:00
|
|
|
const uuid = require('uuid');
|
2017-11-21 15:09:26 +00:00
|
|
|
|
|
|
|
|
export class UUID
|
|
|
|
|
{
|
|
|
|
|
private mUUID = '00000000-0000-0000-0000-000000000000';
|
|
|
|
|
|
|
|
|
|
static zero(): UUID
|
|
|
|
|
{
|
|
|
|
|
return new UUID();
|
|
|
|
|
}
|
2017-12-14 18:22:41 +00:00
|
|
|
static random(): UUID
|
|
|
|
|
{
|
|
|
|
|
const newUUID = uuid.v4();
|
|
|
|
|
return new UUID(newUUID);
|
|
|
|
|
}
|
2017-11-21 15:09:26 +00:00
|
|
|
|
2017-11-24 17:45:34 +00:00
|
|
|
constructor(buf?: Buffer | string, pos?: number)
|
2017-11-21 15:09:26 +00:00
|
|
|
{
|
2017-11-24 17:45:34 +00:00
|
|
|
if (buf !== undefined)
|
2017-11-21 15:09:26 +00:00
|
|
|
{
|
2017-11-24 17:45:34 +00:00
|
|
|
if (typeof buf === 'string')
|
|
|
|
|
{
|
|
|
|
|
this.setUUID(buf);
|
|
|
|
|
}
|
|
|
|
|
else if (pos !== undefined)
|
|
|
|
|
{
|
2017-11-26 01:14:02 +00:00
|
|
|
const uuidBuf: Buffer = buf.slice(pos, pos + 16);
|
|
|
|
|
const hexString = uuidBuf.toString('hex');
|
|
|
|
|
this.setUUID(hexString.substr(0, 8) + '-'
|
|
|
|
|
+ hexString.substr(8, 4) + '-'
|
|
|
|
|
+ hexString.substr(12, 4) + '-'
|
|
|
|
|
+ hexString.substr(16, 4) + '-'
|
|
|
|
|
+ hexString.substr(20, 12));
|
2017-11-24 17:45:34 +00:00
|
|
|
}
|
2017-11-30 04:11:59 +00:00
|
|
|
else
|
|
|
|
|
{
|
|
|
|
|
console.error('Can\'t accept UUIDs of type ' + typeof buf);
|
2017-12-14 18:22:41 +00:00
|
|
|
console.trace();
|
2017-11-30 04:11:59 +00:00
|
|
|
}
|
2017-11-21 15:09:26 +00:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public setUUID(val: string): boolean
|
|
|
|
|
{
|
2017-11-30 04:11:59 +00:00
|
|
|
const test = val.trim();
|
|
|
|
|
if (validator.isUUID(test))
|
2017-11-21 15:09:26 +00:00
|
|
|
{
|
2017-11-30 04:11:59 +00:00
|
|
|
this.mUUID = test;
|
2017-11-21 15:09:26 +00:00
|
|
|
return true;
|
|
|
|
|
}
|
2017-11-30 04:11:59 +00:00
|
|
|
else
|
|
|
|
|
{
|
|
|
|
|
console.log('Invalid UUID: ' + test + ' (length ' + val.length + ')');
|
|
|
|
|
}
|
2017-11-21 15:09:26 +00:00
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public toString = (): string =>
|
|
|
|
|
{
|
|
|
|
|
return this.mUUID;
|
2017-11-24 17:45:34 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
|
|
writeToBuffer(buf: Buffer, pos: number)
|
|
|
|
|
{
|
2017-11-26 01:14:02 +00:00
|
|
|
const shortened = this.mUUID.substr(0, 8) + this.mUUID.substr(9, 4) + this.mUUID.substr(14, 4) + this.mUUID.substr(19, 4) + this.mUUID.substr(24, 12);
|
|
|
|
|
const binary = Buffer.from(shortened, 'hex');
|
|
|
|
|
binary.copy(buf, pos, 0);
|
2017-11-21 15:09:26 +00:00
|
|
|
}
|
|
|
|
|
}
|