@guarani/primitives 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License Copyright (c) 2021 Eduardo Ribeiro Rezende
2
+
3
+ Permission is hereby granted,
4
+ free of charge, to any person obtaining a copy of this software and associated
5
+ documentation files (the "Software"), to deal in the Software without
6
+ restriction, including without limitation the rights to use, copy, modify, merge,
7
+ publish, distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to the
9
+ following conditions:
10
+
11
+ The above copyright notice and this permission notice
12
+ (including the next paragraph) shall be included in all copies or substantial
13
+ portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
16
+ ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
18
+ EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
19
+ OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1 @@
1
+ # `@guarani/primitives`
@@ -0,0 +1,49 @@
1
+ /// <reference types="node" />
2
+ import { Optional } from '@guarani/types';
3
+ export declare type Endianness = 'be' | 'le';
4
+ /**
5
+ * Pads the provided bitstring until its length is a multiple of 8.
6
+ *
7
+ * @param bits Bitstring to be padded.
8
+ * @param endianness Defines if the padding will be added at the beginning or at the end of the bitstring.
9
+ * @returns Padded bitstring.
10
+ */
11
+ export declare function padBits(bits: string, endianness: Endianness): string;
12
+ /**
13
+ * Returns the Binary String representation of the provided Buffer.
14
+ *
15
+ * @param buffer Buffer to be encoded.
16
+ * @param endianness Defines if the padding will be added at the beginning or at the end of the bitstring.
17
+ * @returns Binary String representation of the provided Buffer.
18
+ */
19
+ export declare function bufferToBinary(buffer: Buffer, endianness?: Optional<Endianness>): string;
20
+ /**
21
+ * Returns the Buffer representation of the provided Binary String.
22
+ *
23
+ * @param bits Binary String to be decoded.
24
+ * @param endianness Defines if the padding will be added at the beginning or at the end of the bitstring.
25
+ * @returns Buffer representation of the provided Binary String.
26
+ */
27
+ export declare function binaryToBuffer(bits: string, endianness?: Optional<Endianness>): Buffer;
28
+ /**
29
+ * Performs a bitwise NOT operation on the provided Buffer.
30
+ *
31
+ * @param buffer Buffer to be transformed.
32
+ * @returns Buffer that contains the flipped bits.
33
+ */
34
+ export declare function flipBufferBits(buffer: Buffer): Buffer;
35
+ /**
36
+ * Returns the Unsigned Integer value of the provided Buffer.
37
+ *
38
+ * @param buffer Buffer to be transformed.
39
+ * @returns Unsigned Integer based on the provided Buffer.
40
+ */
41
+ export declare function bufferToUnsignedInteger(buffer: Buffer): bigint;
42
+ /**
43
+ * Returns the Integer value of the provided Buffer.
44
+ *
45
+ * @param buffer Buffer to be transformed.
46
+ * @param asTwosComplement The provided Buffer is in Two's Complement format.
47
+ * @returns Integer based on the provided Buffer.
48
+ */
49
+ export declare function bufferToInteger(buffer: Buffer, asTwosComplement?: Optional<true>): bigint;
package/dist/buffer.js ADDED
@@ -0,0 +1,114 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.bufferToInteger = exports.bufferToUnsignedInteger = exports.flipBufferBits = exports.binaryToBuffer = exports.bufferToBinary = exports.padBits = void 0;
4
+ const integer_1 = require("./integer");
5
+ /**
6
+ * Pads the provided bitstring until its length is a multiple of 8.
7
+ *
8
+ * @param bits Bitstring to be padded.
9
+ * @param endianness Defines if the padding will be added at the beginning or at the end of the bitstring.
10
+ * @returns Padded bitstring.
11
+ */
12
+ function padBits(bits, endianness) {
13
+ const modulo = bits.length % 8;
14
+ const unusedBits = modulo === 0 ? 0 : 8 - (bits.length % 8);
15
+ let paddedBits = bits;
16
+ if (unusedBits !== 0) {
17
+ const padding = '0'.repeat(unusedBits);
18
+ paddedBits = endianness === 'be' ? `${padding}${paddedBits}` : `${paddedBits}${padding}`;
19
+ }
20
+ return paddedBits;
21
+ }
22
+ exports.padBits = padBits;
23
+ /**
24
+ * Returns the Binary String representation of the provided Buffer.
25
+ *
26
+ * @param buffer Buffer to be encoded.
27
+ * @param endianness Defines if the padding will be added at the beginning or at the end of the bitstring.
28
+ * @returns Binary String representation of the provided Buffer.
29
+ */
30
+ function bufferToBinary(buffer, endianness = 'be') {
31
+ if (!Buffer.isBuffer(buffer)) {
32
+ throw new TypeError('Invalid parameter "buffer".');
33
+ }
34
+ return buffer.reduce((bits, byte) => (bits += padBits(byte.toString(2), endianness)), '');
35
+ }
36
+ exports.bufferToBinary = bufferToBinary;
37
+ /**
38
+ * Returns the Buffer representation of the provided Binary String.
39
+ *
40
+ * @param bits Binary String to be decoded.
41
+ * @param endianness Defines if the padding will be added at the beginning or at the end of the bitstring.
42
+ * @returns Buffer representation of the provided Binary String.
43
+ */
44
+ function binaryToBuffer(bits, endianness = 'be') {
45
+ const paddedBits = padBits(bits, endianness);
46
+ const binaryBytes = paddedBits.match(/.{8}/g) ?? [];
47
+ const bytes = binaryBytes.map((byte) => Number.parseInt(byte, 2));
48
+ return Buffer.from(bytes);
49
+ }
50
+ exports.binaryToBuffer = binaryToBuffer;
51
+ /**
52
+ * Performs a bitwise NOT operation on the provided Buffer.
53
+ *
54
+ * @param buffer Buffer to be transformed.
55
+ * @returns Buffer that contains the flipped bits.
56
+ */
57
+ function flipBufferBits(buffer) {
58
+ if (buffer.length === 0) {
59
+ throw new Error('The provided buffer must not be empty.');
60
+ }
61
+ // buffer.toString("binary") returns latin1 characteres.
62
+ const bits = bufferToBinary(buffer);
63
+ const flippedBits = bits
64
+ .split('')
65
+ .map((bit) => (bit === '0' ? '1' : '0'))
66
+ .join('');
67
+ return binaryToBuffer(flippedBits);
68
+ }
69
+ exports.flipBufferBits = flipBufferBits;
70
+ /**
71
+ * Returns the Unsigned Integer value of the provided Buffer.
72
+ *
73
+ * @param buffer Buffer to be transformed.
74
+ * @returns Unsigned Integer based on the provided Buffer.
75
+ */
76
+ function bufferToUnsignedInteger(buffer) {
77
+ if (buffer.length === 0) {
78
+ throw new Error('The provided buffer must not be empty.');
79
+ }
80
+ return buffer.reduce((result, byte) => (result << 8n) | BigInt(byte), 0n);
81
+ }
82
+ exports.bufferToUnsignedInteger = bufferToUnsignedInteger;
83
+ /**
84
+ * Returns the original unsigned Buffer from the provided
85
+ * Two's Complemented Buffer.
86
+ *
87
+ * @param buffer Buffer to be transformed.
88
+ * @returns Original unsigned Buffer.
89
+ */
90
+ function fromTwosComplement(buffer) {
91
+ if (buffer.length === 0) {
92
+ throw new Error('The provided buffer must not be empty.');
93
+ }
94
+ const complemented = bufferToUnsignedInteger(buffer);
95
+ const reciprocal = (0, integer_1.integerToBuffer)(complemented - 1n);
96
+ const original = flipBufferBits(reciprocal);
97
+ return original[0] === 0x00 ? original.subarray(1) : original;
98
+ }
99
+ /**
100
+ * Returns the Integer value of the provided Buffer.
101
+ *
102
+ * @param buffer Buffer to be transformed.
103
+ * @param asTwosComplement The provided Buffer is in Two's Complement format.
104
+ * @returns Integer based on the provided Buffer.
105
+ */
106
+ function bufferToInteger(buffer, asTwosComplement) {
107
+ if (buffer.length === 0) {
108
+ throw new Error('The provided buffer must not be empty.');
109
+ }
110
+ const complemented = asTwosComplement === true && (buffer[0] & 0x80) !== 0x00 ? fromTwosComplement(buffer) : buffer;
111
+ const integer = bufferToUnsignedInteger(complemented);
112
+ return asTwosComplement === true && (buffer[0] & 0x80) !== 0x00 ? -integer : integer;
113
+ }
114
+ exports.bufferToInteger = bufferToInteger;
@@ -0,0 +1,37 @@
1
+ import { Nullable, Optional } from '@guarani/types';
2
+ /**
3
+ * Exception class that keeps the Stack Trace of rethrown Errors.
4
+ */
5
+ export declare class Exception extends Error {
6
+ /**
7
+ * Previous Error of the Chain.
8
+ */
9
+ readonly originalError?: Optional<Error>;
10
+ /**
11
+ * Instantiates an empty Exception.
12
+ */
13
+ constructor();
14
+ /**
15
+ * Instantiates a new Exception based on the provide message.
16
+ *
17
+ * @param message Message of the Exception.
18
+ */
19
+ constructor(message: string);
20
+ /**
21
+ * Instantiates a new Exception by rethrowing the provided Error.
22
+ *
23
+ * @param originalError Rethrown Error.
24
+ */
25
+ constructor(originalError: Error);
26
+ /**
27
+ * Instantiates a new Exception with the provided message and chaining the provided Error's Stack Trace.
28
+ *
29
+ * @param message Message of the Exception.
30
+ * @param originalError Rethrown Error.
31
+ */
32
+ constructor(message: Nullable<string>, originalError: Error);
33
+ /**
34
+ * Returns the default Exception Message.
35
+ */
36
+ protected getDefaultMessage(): string;
37
+ }
@@ -0,0 +1,39 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Exception = void 0;
4
+ /**
5
+ * Exception class that keeps the Stack Trace of rethrown Errors.
6
+ */
7
+ class Exception extends Error {
8
+ /**
9
+ * Instantiates a new Exception based on the provided parameters.
10
+ *
11
+ * @param messageOrBaseError Message of the Exception or rethrown Error.
12
+ * @param originalError Rethrown Error.
13
+ */
14
+ constructor(messageOrBaseError, originalError) {
15
+ originalError = messageOrBaseError instanceof Error ? messageOrBaseError : originalError;
16
+ super(messageOrBaseError === null
17
+ ? undefined
18
+ : typeof messageOrBaseError === 'string'
19
+ ? messageOrBaseError
20
+ : originalError?.message);
21
+ this.name = this.constructor.name;
22
+ Object.defineProperty(this, 'originalError', { enumerable: false, value: originalError, writable: true });
23
+ if (this.message === '') {
24
+ this.message = this.getDefaultMessage();
25
+ }
26
+ // TODO: Check if this does not cause a memory leak.
27
+ const thisStack = this.stack ?? '';
28
+ const originalStack = (this.originalError?.stack ?? '').split('\n').slice(0, Error.stackTraceLimit).join('\n');
29
+ this.stack =
30
+ this.originalError === undefined ? `${thisStack}\n${originalStack}` : `${thisStack}\nFrom ${originalStack}`;
31
+ }
32
+ /**
33
+ * Returns the default Exception Message.
34
+ */
35
+ getDefaultMessage() {
36
+ return '';
37
+ }
38
+ }
39
+ exports.Exception = Exception;
@@ -0,0 +1,3 @@
1
+ export { Endianness, binaryToBuffer, bufferToBinary, bufferToInteger, bufferToUnsignedInteger, flipBufferBits, padBits, } from './buffer';
2
+ export { Exception } from './exception';
3
+ export { integerToBuffer } from './integer';
package/dist/index.js ADDED
@@ -0,0 +1,14 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.integerToBuffer = exports.Exception = exports.padBits = exports.flipBufferBits = exports.bufferToUnsignedInteger = exports.bufferToInteger = exports.bufferToBinary = exports.binaryToBuffer = void 0;
4
+ var buffer_1 = require("./buffer");
5
+ Object.defineProperty(exports, "binaryToBuffer", { enumerable: true, get: function () { return buffer_1.binaryToBuffer; } });
6
+ Object.defineProperty(exports, "bufferToBinary", { enumerable: true, get: function () { return buffer_1.bufferToBinary; } });
7
+ Object.defineProperty(exports, "bufferToInteger", { enumerable: true, get: function () { return buffer_1.bufferToInteger; } });
8
+ Object.defineProperty(exports, "bufferToUnsignedInteger", { enumerable: true, get: function () { return buffer_1.bufferToUnsignedInteger; } });
9
+ Object.defineProperty(exports, "flipBufferBits", { enumerable: true, get: function () { return buffer_1.flipBufferBits; } });
10
+ Object.defineProperty(exports, "padBits", { enumerable: true, get: function () { return buffer_1.padBits; } });
11
+ var exception_1 = require("./exception");
12
+ Object.defineProperty(exports, "Exception", { enumerable: true, get: function () { return exception_1.Exception; } });
13
+ var integer_1 = require("./integer");
14
+ Object.defineProperty(exports, "integerToBuffer", { enumerable: true, get: function () { return integer_1.integerToBuffer; } });
@@ -0,0 +1,11 @@
1
+ /// <reference types="node" />
2
+ import { Optional } from '@guarani/types';
3
+ /**
4
+ * Encodes the provided Integer into a Buffer.
5
+ *
6
+ * @param integer Integer to be encoded.
7
+ * @param asTwosComplement Represents Natural Number Buffers starting in
8
+ * **0b1xxxxxxx** as positive by appending a **0x00** byte at the beginning.
9
+ * @returns Encoded Buffer.
10
+ */
11
+ export declare function integerToBuffer(integer: number | bigint, asTwosComplement?: Optional<true>): Buffer;
@@ -0,0 +1,53 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.integerToBuffer = void 0;
4
+ const buffer_1 = require("./buffer");
5
+ /**
6
+ * Encodes the provided unsigned Integer into a Buffer.
7
+ *
8
+ * @param integer Unsigned Integer to be encoded.
9
+ * @returns Encoded Buffer.
10
+ */
11
+ function unsignedIntegerToBuffer(integer) {
12
+ let hex = integer.toString(16);
13
+ if (hex.length % 2 !== 0) {
14
+ hex = `0${hex}`;
15
+ }
16
+ const bytes = hex.match(/.{2}/g).map((byte) => Number.parseInt(byte, 16));
17
+ return Buffer.from(bytes);
18
+ }
19
+ /**
20
+ * Encodes the provided Integer into a Buffer.
21
+ *
22
+ * @param integer Integer to be encoded.
23
+ * @param asTwosComplement Represents Natural Number Buffers starting in
24
+ * **0b1xxxxxxx** as positive by appending a **0x00** byte at the beginning.
25
+ * @returns Encoded Buffer.
26
+ */
27
+ function integerToBuffer(integer, asTwosComplement) {
28
+ if (typeof integer !== 'bigint' && typeof integer !== 'number') {
29
+ throw new TypeError('Invalid parameter "integer".');
30
+ }
31
+ if (typeof integer === 'number' && !Number.isInteger(integer)) {
32
+ throw new TypeError('Invalid parameter "integer".');
33
+ }
34
+ const data = BigInt(integer);
35
+ const unsignedInteger = data < 0n ? data * -1n : data;
36
+ let unsignedBuffer = unsignedIntegerToBuffer(unsignedInteger);
37
+ if (data >= 0n) {
38
+ return asTwosComplement === true && (unsignedBuffer[0] & 0x80) !== 0x00
39
+ ? Buffer.from([0x00, ...unsignedBuffer])
40
+ : unsignedBuffer;
41
+ }
42
+ if (data > 0 && (unsignedBuffer[0] & 0x80) !== 0x00) {
43
+ unsignedBuffer = Buffer.from([0x00, ...unsignedBuffer]);
44
+ }
45
+ const reciprocal = (0, buffer_1.flipBufferBits)(unsignedBuffer);
46
+ const complementedInteger = (0, buffer_1.bufferToUnsignedInteger)(reciprocal) + 1n;
47
+ let complemented = unsignedIntegerToBuffer(complementedInteger);
48
+ if ((complemented[0] & 0x80) === 0x00) {
49
+ complemented = Buffer.from([0xff, ...complemented]);
50
+ }
51
+ return complemented;
52
+ }
53
+ exports.integerToBuffer = integerToBuffer;
package/package.json ADDED
@@ -0,0 +1,40 @@
1
+ {
2
+ "name": "@guarani/primitives",
3
+ "version": "0.7.0",
4
+ "description": "Utilities for manipulating NodeJS' Primitives.",
5
+ "license": "MIT",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "homepage": "https://github.com/guaranijs/guarani/tree/master/packages/primitives#readme",
9
+ "bugs": "https://github.com/guaranijs/guarani/issues",
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "git@github.com/guaranijs/guarani.git",
13
+ "directory": "packages/primitives"
14
+ },
15
+ "author": {
16
+ "name": "Eduardo Ribeiro Rezende",
17
+ "email": "eduardorbr7@gmail.com",
18
+ "url": "https://github.com/revensky"
19
+ },
20
+ "directories": {
21
+ "lib": "lib",
22
+ "test": "tests"
23
+ },
24
+ "files": [
25
+ "dist"
26
+ ],
27
+ "scripts": {
28
+ "prebuild": "rimraf dist",
29
+ "build": "tsc -p tsconfig.build.json",
30
+ "test": "jest"
31
+ },
32
+ "publishConfig": {
33
+ "access": "public",
34
+ "registry": "https://registry.npmjs.org/"
35
+ },
36
+ "devDependencies": {
37
+ "@guarani/types": "0.7.0"
38
+ },
39
+ "gitHead": "bb8bf8ce17ca2d5821bd2be09c67cf93a18340eb"
40
+ }