@ethersphere/bee-js
Version:
Javascript client for Bee
77 lines (76 loc) • 2.43 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.Bytes = void 0;
const cafe_utility_1 = require("cafe-utility");
const DECODER = new TextDecoder();
const ENCODER = new TextEncoder();
class Bytes {
constructor(bytes, byteLength) {
if (bytes instanceof Bytes) {
this.bytes = bytes.bytes;
}
else if (typeof bytes === 'string') {
this.bytes = cafe_utility_1.Binary.hexToUint8Array(cafe_utility_1.Types.asHexString(bytes, { name: 'Bytes#constructor(bytes)' }));
}
else if (bytes instanceof ArrayBuffer) {
this.bytes = new Uint8Array(bytes);
}
else {
this.bytes = bytes;
}
this.length = this.bytes.length;
if (byteLength) {
if (Array.isArray(byteLength)) {
if (!byteLength.includes(this.length)) {
throw new Error(`Bytes#checkByteLength: bytes length is ${this.length} but expected ${byteLength.join(' or ')}`);
}
}
else if (this.length !== byteLength) {
throw new Error(`Bytes#checkByteLength: bytes length is ${this.length} but expected ${byteLength}`);
}
}
}
static keccak256(bytes) {
return new Bytes(cafe_utility_1.Binary.keccak256(new Bytes(bytes).toUint8Array()));
}
static fromUtf8(utf8) {
return new Bytes(ENCODER.encode(utf8));
}
static fromSlice(bytes, start, length) {
if (length === undefined) {
return new Bytes(bytes.slice(start));
}
return new Bytes(bytes.slice(start, start + length));
}
offset(index) {
return new Uint8Array(this.bytes.slice(index));
}
toUint8Array() {
return new Uint8Array(this.bytes);
}
toHex() {
return cafe_utility_1.Binary.uint8ArrayToHex(this.bytes);
}
toBase64() {
return cafe_utility_1.Binary.uint8ArrayToBase64(this.bytes);
}
toBase32() {
return cafe_utility_1.Binary.uint8ArrayToBase32(this.bytes);
}
toString() {
return this.toHex();
}
toUtf8() {
return DECODER.decode(this.bytes);
}
toJSON() {
return JSON.parse(this.toUtf8());
}
equals(other) {
return this.toHex() === new Bytes(other).toHex();
}
represent() {
return this.toHex();
}
}
exports.Bytes = Bytes;