Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(NODE-4506): Make UUID a subclass of binary #512

Merged
merged 11 commits into from
Aug 11, 2022
206 changes: 204 additions & 2 deletions src/binary.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { Buffer } from 'buffer';
import { ensureBuffer } from './ensure_buffer';
import { uuidHexStringToBuffer } from './uuid_utils';
import { UUID, UUIDExtended } from './uuid';
import { bufferToUuidHexString, uuidHexStringToBuffer, uuidValidateString } from './uuid_utils';
import { isUint8Array, randomBytes } from './parser/utils';
import type { EJSONOptions } from './extended_json';
import { BSONError, BSONTypeError } from './error';
import { BSON_BINARY_SUBTYPE_UUID_NEW } from './constants';

/** @public */
export type BinarySequence = Uint8Array | Buffer | number[];
Expand Down Expand Up @@ -292,3 +293,204 @@ export class Binary {
}

Object.defineProperty(Binary.prototype, '_bsontype', { value: 'Binary' });

/** @public */
export type UUIDExtended = {
$uuid: string;
};
const BYTE_LENGTH = 16;
nbbeeken marked this conversation as resolved.
Show resolved Hide resolved

const kId = Symbol('id');

/**
* A class representation of the BSON UUID type.
* @public
*/
export class UUID extends Binary {
static cacheHexString: boolean;

/** UUID Bytes @internal */
private [kId]!: Buffer;
addaleax marked this conversation as resolved.
Show resolved Hide resolved
/** UUID hexString cache @internal */
private __id?: string;

/**
* Create an UUID type
*
* @param input - Can be a 32 or 36 character hex string (dashes excluded/included) or a 16 byte binary Buffer.
*/
constructor(input?: string | Buffer | UUID) {
let bytes;
let hexStr;
if (input == null) {
bytes = UUID.generate();
} else if (input instanceof UUID) {
bytes = Buffer.from(input[kId]);
hexStr = input.__id;
} else if (ArrayBuffer.isView(input) && input.byteLength === BYTE_LENGTH) {
bytes = ensureBuffer(input);
} else if (typeof input === 'string') {
bytes = uuidHexStringToBuffer(input);
} else {
throw new BSONTypeError(
'Argument passed in UUID constructor must be a UUID, a 16 byte Buffer or a 32/36 character hex string (dashes excluded/included, format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).'
);
}
super(bytes, BSON_BINARY_SUBTYPE_UUID_NEW);
this[kId] = bytes;
this.__id = hexStr;
}

/**
* The UUID bytes
* @readonly
*/
get id(): Buffer {
return this[kId];
}

set id(value: Buffer) {
this[kId] = value;

if (UUID.cacheHexString) {
this.__id = bufferToUuidHexString(value);
}
}

/**
* Generate a 16 byte uuid v4 buffer used in UUIDs
*/

addaleax marked this conversation as resolved.
Show resolved Hide resolved
/**
* Returns the UUID id as a 32 or 36 character hex string representation, excluding/including dashes (defaults to 36 character dash separated)
* @param includeDashes - should the string exclude dash-separators.
* */
toHexString(includeDashes = true): string {
if (UUID.cacheHexString && this.__id) {
return this.__id;
}

const uuidHexString = bufferToUuidHexString(this.id, includeDashes);

if (UUID.cacheHexString) {
this.__id = uuidHexString;
}

return uuidHexString;
}

/**
* Converts the id into a 36 character (dashes included) hex string, unless a encoding is specified.
*/
toString(encoding?: string): string {
return encoding ? this.id.toString(encoding) : this.toHexString();
}

/**
* Converts the id into its JSON string representation.
* A 36 character (dashes included) hex string in the format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
*/
toJSON(): string {
return this.toHexString();
}

/**
* Compares the equality of this UUID with `otherID`.
*
* @param otherId - UUID instance to compare against.
*/
equals(otherId: string | Buffer | UUID): boolean {
if (!otherId) {
return false;
}

if (otherId instanceof UUID) {
return otherId.id.equals(this.id);
}

try {
return new UUID(otherId).id.equals(this.id);
} catch {
return false;
}
}

/**
* Creates a Binary instance from the current UUID.
*/
toBinary(): Binary {
return new Binary(this.id, Binary.SUBTYPE_UUID);
}

/**
* Generates a populated buffer containing a v4 uuid
*/
static generate(): Buffer {
const bytes = randomBytes(BYTE_LENGTH);

// Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
// Kindly borrowed from https://github.com/uuidjs/uuid/blob/master/src/v4.js
bytes[6] = (bytes[6] & 0x0f) | 0x40;
bytes[8] = (bytes[8] & 0x3f) | 0x80;

return Buffer.from(bytes);
}

/**
* Checks if a value is a valid bson UUID
* @param input - UUID, string or Buffer to validate.
*/
static isValid(input: string | Buffer | UUID): boolean {
if (!input) {
return false;
}

if (input instanceof UUID) {
return true;
}

if (typeof input === 'string') {
return uuidValidateString(input);
}

if (isUint8Array(input)) {
// check for length & uuid version (https://tools.ietf.org/html/rfc4122#section-4.1.3)
if (input.length !== BYTE_LENGTH) {
return false;
}

try {
// get this byte as hex: xxxxxxxx-xxxx-XXxx-xxxx-xxxxxxxxxxxx
// check first part as uuid version: xxxxxxxx-xxxx-Xxxx-xxxx-xxxxxxxxxxxx
return parseInt(input[6].toString(16)[0], 10) === Binary.SUBTYPE_UUID;
} catch {
return false;
}
addaleax marked this conversation as resolved.
Show resolved Hide resolved
}

return false;
}

/**
* Creates an UUID from a hex string representation of an UUID.
* @param hexString - 32 or 36 character hex string (dashes excluded/included).
*/
static createFromHexString(hexString: string): UUID {
const buffer = uuidHexStringToBuffer(hexString);
return new UUID(buffer);
}

/**
* Converts to a string representation of this Id.
*
* @returns return the 36 character hex string representation.
* @internal
*/
[Symbol.for('nodejs.util.inspect.custom')](): string {
return this.inspect();
}

inspect(): string {
return `new UUID("${this.toHexString()}")`;
}
}
6 changes: 2 additions & 4 deletions src/bson.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Buffer } from 'buffer';
import { Binary } from './binary';
import { Binary, UUID } from './binary';
import { Code } from './code';
import { DBRef } from './db_ref';
import { Decimal128 } from './decimal128';
Expand All @@ -20,8 +20,7 @@ import { serializeInto as internalSerialize, SerializeOptions } from './parser/s
import { BSONRegExp } from './regexp';
import { BSONSymbol } from './symbol';
import { Timestamp } from './timestamp';
import { UUID } from './uuid';
export type { BinaryExtended, BinaryExtendedLegacy, BinarySequence } from './binary';
export type { UUIDExtended, BinaryExtended, BinaryExtendedLegacy, BinarySequence } from './binary';
export type { CodeExtended } from './code';
export {
BSON_BINARY_SUBTYPE_BYTE_ARRAY,
Expand Down Expand Up @@ -73,7 +72,6 @@ export type { BSONRegExpExtended, BSONRegExpExtendedLegacy } from './regexp';
export type { BSONSymbolExtended } from './symbol';
export type { LongWithoutOverrides, TimestampExtended, TimestampOverrides } from './timestamp';
export { LongWithoutOverridesClass } from './timestamp';
export type { UUIDExtended } from './uuid';
export type { SerializeOptions, DeserializeOptions };
export {
Code,
Expand Down
6 changes: 0 additions & 6 deletions src/parser/serializer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -837,8 +837,6 @@ export function serializeInto(
);
} else if (value['_bsontype'] === 'Binary') {
index = serializeBinary(buffer, key, value, index, true);
} else if (value['_bsontype'] === 'UUID') {
index = serializeBinary(buffer, key, value.toBinary(), index);
} else if (value['_bsontype'] === 'Symbol') {
index = serializeSymbol(buffer, key, value, index, true);
} else if (value['_bsontype'] === 'DBRef') {
Expand Down Expand Up @@ -940,8 +938,6 @@ export function serializeInto(
index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions);
} else if (value['_bsontype'] === 'Binary') {
index = serializeBinary(buffer, key, value, index);
} else if (value['_bsontype'] === 'UUID') {
index = serializeBinary(buffer, key, value.toBinary(), index);
} else if (value['_bsontype'] === 'Symbol') {
index = serializeSymbol(buffer, key, value, index);
} else if (value['_bsontype'] === 'DBRef') {
Expand Down Expand Up @@ -1047,8 +1043,6 @@ export function serializeInto(
index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions);
} else if (value['_bsontype'] === 'Binary') {
index = serializeBinary(buffer, key, value, index);
} else if (value['_bsontype'] === 'UUID') {
index = serializeBinary(buffer, key, value.toBinary(), index);
addaleax marked this conversation as resolved.
Show resolved Hide resolved
} else if (value['_bsontype'] === 'Symbol') {
index = serializeSymbol(buffer, key, value, index);
} else if (value['_bsontype'] === 'DBRef') {
Expand Down
Loading