New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

@yume-chan/struct

Package Overview
Dependencies
Maintainers
1
Versions
27
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@yume-chan/struct - npm Package Compare versions

Comparing version 0.0.9 to 0.0.10

CHANGELOG.json

28

dts/basic/context.d.ts

@@ -1,26 +0,18 @@

import type { ValueOrPromise } from '../utils';
/**
* Context with enough methods to serialize a struct
*/
export interface StructSerializationContext {
export interface StructDeserializeStream {
/**
* Encode the specified string into an ArrayBuffer using UTF-8 encoding
* Read data from the underlying data source.
*
* Stream must return exactly `length` bytes or data. If that's not possible
* (due to end of file or other error condition), it must throw an error.
*/
encodeUtf8(input: string): ArrayBuffer;
read(length: number): ArrayBuffer;
}
/**
* Context with enough methods to deserialize a struct
*/
export interface StructDeserializationContext extends StructSerializationContext {
export interface StructAsyncDeserializeStream {
/**
* Decode the specified `ArrayBuffer` using UTF-8 encoding
*/
decodeUtf8(buffer: ArrayBuffer): string;
/**
* Read data from the underlying data source.
*
* Context should return exactly `length` bytes or data. If that's not possible
* (due to end of file or other error condition), it should throw an error.
* Context must return exactly `length` bytes or data. If that's not possible
* (due to end of file or other error condition), it must throw an error.
*/
read(length: number): ValueOrPromise<ArrayBuffer>;
read(length: number): Promise<ArrayBuffer>;
}

@@ -27,0 +19,0 @@ export interface StructOptions {

@@ -1,3 +0,2 @@

import type { ValueOrPromise } from '../utils';
import type { StructDeserializationContext, StructOptions, StructSerializationContext } from './context';
import type { StructAsyncDeserializeStream, StructDeserializeStream, StructOptions } from './context';
import type { StructFieldValue } from './field-value';

@@ -42,8 +41,9 @@ import type { StructValue } from './struct-value';

*/
abstract create(options: Readonly<StructOptions>, context: StructSerializationContext, struct: StructValue, value: TValue): StructFieldValue<this>;
abstract create(options: Readonly<StructOptions>, struct: StructValue, value: TValue): StructFieldValue<this>;
/**
* When implemented in derived classes, creates a `StructFieldValue` by parsing `context`.
*/
abstract deserialize(options: Readonly<StructOptions>, context: StructDeserializationContext, struct: StructValue): ValueOrPromise<StructFieldValue<this>>;
abstract deserialize(options: Readonly<StructOptions>, stream: StructDeserializeStream, struct: StructValue): StructFieldValue<this>;
abstract deserialize(options: Readonly<StructOptions>, stream: StructAsyncDeserializeStream, struct: StructValue): Promise<StructFieldValue<this>>;
}
//# sourceMappingURL=definition.d.ts.map

@@ -1,2 +0,2 @@

import type { StructOptions, StructSerializationContext } from './context';
import type { StructOptions } from './context';
import type { StructFieldDefinition } from './definition';

@@ -15,8 +15,6 @@ import type { StructValue } from './struct-value';

readonly options: Readonly<StructOptions>;
/** Gets the serialization context of the associated `Struct` instance */
readonly context: StructSerializationContext;
/** Gets the associated `Struct` instance */
readonly struct: StructValue;
protected value: TDefinition['TValue'];
constructor(definition: TDefinition, options: Readonly<StructOptions>, context: StructSerializationContext, struct: StructValue, value: TDefinition['TValue']);
constructor(definition: TDefinition, options: Readonly<StructOptions>, struct: StructValue, value: TDefinition['TValue']);
/**

@@ -39,4 +37,4 @@ * Gets size of this field. By default, it returns its `definition`'s size.

*/
abstract serialize(dataView: DataView, offset: number, context: StructSerializationContext): void;
abstract serialize(dataView: DataView, offset: number): void;
}
//# sourceMappingURL=field-value.d.ts.map

@@ -1,21 +0,19 @@

import { StructDeserializationContext, StructFieldDefinition, StructOptions, StructSerializationContext } from './basic';
import type { StructAsyncDeserializeStream, StructDeserializeStream, StructFieldDefinition, StructOptions } from './basic';
import { ArrayBufferFieldType, ArrayBufferLikeFieldType, FixedLengthArrayBufferLikeFieldDefinition, FixedLengthArrayBufferLikeFieldOptions, LengthField, NumberFieldType, StringFieldType, Uint8ClampedArrayFieldType, VariableLengthArrayBufferLikeFieldDefinition, VariableLengthArrayBufferLikeFieldOptions } from './types';
import { Awaited, Evaluate, Identity, Overwrite } from './utils';
import { Evaluate, Identity, Overwrite } from "./utils";
export interface StructLike<TValue> {
deserialize(context: StructDeserializationContext): Promise<TValue>;
deserialize(stream: StructDeserializeStream | StructAsyncDeserializeStream): Promise<TValue>;
}
/**
* Extract the value type of the specified `Struct`
*
* The lack of generic constraint is on purpose to allow `StructLike` types
*/
export declare type StructValueType<T extends StructLike<any>> = Awaited<ReturnType<T['deserialize']>>;
/**
* Create a new `Struct` type with `TDescriptor` appended
* Create a new `Struct` type with `TDefinition` appended
*/
declare type AddFieldDescriptor<TFields extends object, TOmitInitKey extends PropertyKey, TExtra extends object, TPostDeserialized, TFieldName extends PropertyKey, TDefinition extends StructFieldDefinition<any, any, any>> = Identity<Struct<Evaluate<TFields & Record<TFieldName, TDefinition['TValue']>>, TOmitInitKey | TDefinition['TOmitInitKey'], TExtra, TPostDeserialized>>;
/**
* Similar to `ArrayBufferLikeFieldCreator`, but bind to a `ArrayBufferLikeFieldType`
* Similar to `ArrayBufferLikeFieldCreator`, but bind to `TType`
*/
interface ArrayBufferTypeFieldDefinitionCreator<TFields extends object, TOmitInitKey extends PropertyKey, TExtra extends object, TPostDeserialized, TType extends ArrayBufferLikeFieldType> {
interface BindedArrayBufferLikeFieldDefinitionCreator<TFields extends object, TOmitInitKey extends PropertyKey, TExtra extends object, TPostDeserialized, TType extends ArrayBufferLikeFieldType<any, any>> {
<TName extends PropertyKey, TTypeScriptType = TType['TTypeScriptType']>(name: TName, options: FixedLengthArrayBufferLikeFieldOptions, typescriptType?: TTypeScriptType): AddFieldDescriptor<TFields, TOmitInitKey, TExtra, TPostDeserialized, TName, FixedLengthArrayBufferLikeFieldDefinition<TType, FixedLengthArrayBufferLikeFieldOptions>>;

@@ -88,14 +86,14 @@ <TName extends PropertyKey, TLengthField extends LengthField<TFields>, TOptions extends VariableLengthArrayBufferLikeFieldOptions<TFields, TLengthField>, TTypeScriptType = TType['TTypeScriptType']>(name: TName, options: TOptions, typescriptType?: TTypeScriptType): AddFieldDescriptor<TFields, TOmitInitKey, TExtra, TPostDeserialized, TName, VariableLengthArrayBufferLikeFieldDefinition<TType, TOptions>>;

private arrayBufferLike;
arrayBuffer: ArrayBufferTypeFieldDefinitionCreator<TFields, TOmitInitKey, TExtra, TPostDeserialized, ArrayBufferFieldType>;
uint8ClampedArray: ArrayBufferTypeFieldDefinitionCreator<TFields, TOmitInitKey, TExtra, TPostDeserialized, Uint8ClampedArrayFieldType>;
string: ArrayBufferTypeFieldDefinitionCreator<TFields, TOmitInitKey, TExtra, TPostDeserialized, StringFieldType>;
arrayBuffer: BindedArrayBufferLikeFieldDefinitionCreator<TFields, TOmitInitKey, TExtra, TPostDeserialized, ArrayBufferFieldType>;
uint8ClampedArray: BindedArrayBufferLikeFieldDefinitionCreator<TFields, TOmitInitKey, TExtra, TPostDeserialized, Uint8ClampedArrayFieldType>;
string: BindedArrayBufferLikeFieldDefinitionCreator<TFields, TOmitInitKey, TExtra, TPostDeserialized, StringFieldType>;
/**
* Adds some extra fields into every Struct value.
* Adds some extra properties into every `Struct` value.
*
* Extra fields will not affect serialize or deserialize process.
* Extra properties will not affect serialize or deserialize process.
*
* Multiple calls to `extra` will merge all values together.
* Multiple calls to `extra` will merge all properties together.
*
* @param value
* An object containing anything you want to add to the result object. Accessors and methods are also allowed.
* An object containing properties to be added to the result value. Accessors and methods are also allowed.
*/

@@ -124,6 +122,7 @@ extra<T extends Record<Exclude<keyof T, Exclude<keyof T, keyof TFields>>, never>>(value: T & ThisType<Overwrite<Overwrite<TExtra, T>, TFields>>): Struct<TFields, TOmitInitKey, Overwrite<TExtra, T>, TPostDeserialized>;

postDeserialize<TPostSerialize>(callback?: StructPostDeserialized<TFields, TPostSerialize>): Struct<TFields, TOmitInitKey, TExtra, TPostSerialize>;
deserialize(context: StructDeserializationContext): Promise<StructDeserializedResult<TFields, TExtra, TPostDeserialized>>;
serialize(init: Evaluate<Omit<TFields, TOmitInitKey>>, context: StructSerializationContext): ArrayBuffer;
deserialize(stream: StructDeserializeStream): StructDeserializedResult<TFields, TExtra, TPostDeserialized>;
deserialize(stream: StructAsyncDeserializeStream): Promise<StructDeserializedResult<TFields, TExtra, TPostDeserialized>>;
serialize(init: Evaluate<Omit<TFields, TOmitInitKey>>): ArrayBuffer;
}
export {};
//# sourceMappingURL=struct.d.ts.map

@@ -1,2 +0,2 @@

import { StructDeserializationContext, StructFieldDefinition, StructFieldValue, StructOptions, StructSerializationContext, StructValue } from '../basic';
import { StructAsyncDeserializeStream, StructDeserializeStream, StructFieldDefinition, StructFieldValue, StructOptions, StructValue } from '../basic';
/**

@@ -19,5 +19,5 @@ * Base class for all types that

*/
abstract toArrayBuffer(value: TValue, context: StructSerializationContext): ArrayBuffer;
abstract toArrayBuffer(value: TValue): ArrayBuffer;
/** When implemented in derived classes, converts the `ArrayBuffer` to a type-specific value */
abstract fromArrayBuffer(arrayBuffer: ArrayBuffer, context: StructDeserializationContext): TValue;
abstract fromArrayBuffer(arrayBuffer: ArrayBuffer): TValue;
/**

@@ -48,10 +48,10 @@ * When implemented in derived classes, gets the size in byte of the type-specific `value`.

}
/** Am ArrayBufferLike type that converts between `ArrayBuffer` and `string` */
/** An ArrayBufferLike type that converts between `ArrayBuffer` and `string` */
export declare class StringFieldType<TTypeScriptType = string> extends ArrayBufferLikeFieldType<string, TTypeScriptType> {
static readonly instance: StringFieldType<string>;
toArrayBuffer(value: string, context: StructSerializationContext): ArrayBuffer;
fromArrayBuffer(arrayBuffer: ArrayBuffer, context: StructDeserializationContext): string;
toArrayBuffer(value: string): ArrayBuffer;
fromArrayBuffer(arrayBuffer: ArrayBuffer): string;
getSize(): number;
}
export declare abstract class ArrayBufferLikeFieldDefinition<TType extends ArrayBufferLikeFieldType = ArrayBufferLikeFieldType, TOptions = void, TOmitInitKey extends PropertyKey = never> extends StructFieldDefinition<TOptions, TType['TTypeScriptType'], TOmitInitKey> {
export declare abstract class ArrayBufferLikeFieldDefinition<TType extends ArrayBufferLikeFieldType<any, any> = ArrayBufferLikeFieldType<unknown, unknown>, TOptions = void, TOmitInitKey extends PropertyKey = never> extends StructFieldDefinition<TOptions, TType['TTypeScriptType'], TOmitInitKey> {
readonly type: TType;

@@ -63,11 +63,12 @@ constructor(type: TType, options: TOptions);

*/
create(options: Readonly<StructOptions>, context: StructSerializationContext, struct: StructValue, value: TType['TTypeScriptType'], arrayBuffer?: ArrayBuffer): ArrayBufferLikeFieldValue<this>;
deserialize(options: Readonly<StructOptions>, context: StructDeserializationContext, struct: StructValue): Promise<ArrayBufferLikeFieldValue<this>>;
create(options: Readonly<StructOptions>, struct: StructValue, value: TType['TTypeScriptType'], arrayBuffer?: ArrayBuffer): ArrayBufferLikeFieldValue<this>;
deserialize(options: Readonly<StructOptions>, stream: StructDeserializeStream, struct: StructValue): ArrayBufferLikeFieldValue<this>;
deserialize(options: Readonly<StructOptions>, stream: StructAsyncDeserializeStream, struct: StructValue): Promise<ArrayBufferLikeFieldValue<this>>;
}
export declare class ArrayBufferLikeFieldValue<TDefinition extends ArrayBufferLikeFieldDefinition<ArrayBufferLikeFieldType, any, any>> extends StructFieldValue<TDefinition> {
export declare class ArrayBufferLikeFieldValue<TDefinition extends ArrayBufferLikeFieldDefinition<ArrayBufferLikeFieldType<unknown, unknown>, any, any>> extends StructFieldValue<TDefinition> {
protected arrayBuffer: ArrayBuffer | undefined;
constructor(definition: TDefinition, options: Readonly<StructOptions>, context: StructSerializationContext, struct: StructValue, value: TDefinition['TValue'], arrayBuffer?: ArrayBuffer);
constructor(definition: TDefinition, options: Readonly<StructOptions>, struct: StructValue, value: TDefinition['TValue'], arrayBuffer?: ArrayBuffer);
set(value: TDefinition['TValue']): void;
serialize(dataView: DataView, offset: number, context: StructSerializationContext): void;
serialize(dataView: DataView, offset: number): void;
}
//# sourceMappingURL=array-buffer.d.ts.map

@@ -1,2 +0,2 @@

import { StructDeserializationContext, StructFieldDefinition, StructFieldValue, StructOptions, StructSerializationContext, StructValue } from '../basic';
import { StructAsyncDeserializeStream, StructDeserializeStream, StructFieldDefinition, StructFieldValue, StructOptions, StructValue } from '../basic';
export declare type DataViewGetters = {

@@ -27,4 +27,5 @@ [TKey in keyof DataView]: TKey extends `get${string}` ? TKey : never;

getSize(): number;
create(options: Readonly<StructOptions>, context: StructSerializationContext, struct: StructValue, value: TTypeScriptType): NumberFieldValue<this>;
deserialize(options: Readonly<StructOptions>, context: StructDeserializationContext, struct: StructValue): Promise<NumberFieldValue<this>>;
create(options: Readonly<StructOptions>, struct: StructValue, value: TTypeScriptType): NumberFieldValue<this>;
deserialize(options: Readonly<StructOptions>, stream: StructDeserializeStream, struct: StructValue): NumberFieldValue<this>;
deserialize(options: Readonly<StructOptions>, stream: StructAsyncDeserializeStream, struct: StructValue): Promise<NumberFieldValue<this>>;
}

@@ -31,0 +32,0 @@ export declare class NumberFieldValue<TDefinition extends NumberFieldDefinition<NumberFieldType, any>> extends StructFieldValue<TDefinition> {

@@ -1,2 +0,2 @@

import { StructFieldDefinition, StructFieldValue, StructOptions, StructSerializationContext, StructValue } from '../basic';
import { StructFieldDefinition, StructFieldValue, StructOptions, StructValue } from '../basic';
import type { KeysOfType } from '../utils';

@@ -12,3 +12,3 @@ import { ArrayBufferLikeFieldDefinition, ArrayBufferLikeFieldType, ArrayBufferLikeFieldValue } from './array-buffer';

protected getDeserializeSize(struct: StructValue): number;
create(options: Readonly<StructOptions>, context: StructSerializationContext, struct: StructValue, value: TType['TTypeScriptType'], arrayBuffer?: ArrayBuffer): VariableLengthArrayBufferLikeStructFieldValue<this>;
create(options: Readonly<StructOptions>, struct: StructValue, value: TType['TTypeScriptType'], arrayBuffer?: ArrayBuffer): VariableLengthArrayBufferLikeStructFieldValue<this>;
}

@@ -18,3 +18,3 @@ export declare class VariableLengthArrayBufferLikeStructFieldValue<TDefinition extends VariableLengthArrayBufferLikeFieldDefinition = VariableLengthArrayBufferLikeFieldDefinition> extends ArrayBufferLikeFieldValue<TDefinition> {

protected lengthFieldValue: VariableLengthArrayBufferLikeFieldLengthValue;
constructor(definition: TDefinition, options: Readonly<StructOptions>, context: StructSerializationContext, struct: StructValue, value: TDefinition['TValue'], arrayBuffer?: ArrayBuffer);
constructor(definition: TDefinition, options: Readonly<StructOptions>, struct: StructValue, value: TDefinition['TValue'], arrayBuffer?: ArrayBuffer);
getSize(): number;

@@ -31,5 +31,5 @@ set(value: unknown): void;

set(): void;
serialize(dataView: DataView, offset: number, context: StructSerializationContext): void;
serialize(dataView: DataView, offset: number): void;
}
export {};
//# sourceMappingURL=variable-length-array-buffer.d.ts.map

@@ -41,4 +41,3 @@ /**

}[keyof T];
export declare type ValueOrPromise<T> = T | Promise<T>;
export declare type Awaited<T> = T extends Promise<infer R> ? Awaited<R> : T;
export declare type ValueOrPromise<T> = T | PromiseLike<T>;
/**

@@ -48,2 +47,4 @@ * Returns a (fake) value of the given type.

export declare function placeholder<T>(): T;
export declare function encodeUtf8(input: string): ArrayBuffer;
export declare function decodeUtf8(buffer: ArrayBuffer): string;
//# sourceMappingURL=utils.d.ts.map

@@ -8,6 +8,5 @@ /**

export class StructFieldValue {
constructor(definition, options, context, struct, value) {
constructor(definition, options, struct, value) {
this.definition = definition;
this.options = options;
this.context = context;
this.struct = struct;

@@ -14,0 +13,0 @@ this.value = value;

@@ -19,5 +19,2 @@ /**

set(key, value) {
// TODO: TypeScript 4.2 will allow this behavior
// https://github.com/microsoft/TypeScript/pull/26797
// @ts-expect-error Type 'symbol' cannot be used as an index type. ts(2538)
this.fieldValues[key] = value;

@@ -37,5 +34,2 @@ Object.defineProperty(this.value, key, {

get(key) {
// TODO: TypeScript 4.2 will allow this behavior
// https://github.com/microsoft/TypeScript/pull/26797
// @ts-expect-error Type 'symbol' cannot be used as an index type. ts(2538)
return this.fieldValues[key];

@@ -42,0 +36,0 @@ }

@@ -1,3 +0,3 @@

import { __awaiter } from "tslib";
import { StructDefaultOptions, StructValue } from './basic';
import { Syncbird } from "./syncbird";
import { ArrayBufferFieldType, FixedLengthArrayBufferLikeFieldDefinition, NumberFieldDefinition, NumberFieldType, StringFieldType, Uint8ClampedArrayFieldType, VariableLengthArrayBufferLikeFieldDefinition } from './types';

@@ -114,10 +114,10 @@ export class Struct {

/**
* Adds some extra fields into every Struct value.
* Adds some extra properties into every `Struct` value.
*
* Extra fields will not affect serialize or deserialize process.
* Extra properties will not affect serialize or deserialize process.
*
* Multiple calls to `extra` will merge all values together.
* Multiple calls to `extra` will merge all properties together.
*
* @param value
* An object containing anything you want to add to the result object. Accessors and methods are also allowed.
* An object containing properties to be added to the result value. Accessors and methods are also allowed.
*/

@@ -132,10 +132,20 @@ extra(value) {

}
deserialize(context) {
return __awaiter(this, void 0, void 0, function* () {
const value = new StructValue();
Object.defineProperties(value.value, this._extra);
for (const [name, definition] of this._fields) {
const fieldValue = yield definition.deserialize(this.options, context, value);
value.set(name, fieldValue);
}
deserialize(stream) {
const value = new StructValue();
Object.defineProperties(value.value, this._extra);
return Syncbird.try(() => {
const iterator = this._fields[Symbol.iterator]();
const iterate = () => {
const result = iterator.next();
if (result.done) {
return value;
}
const [name, definition] = result.value;
return Syncbird.resolve(definition.deserialize(this.options, stream, value)).then(fieldValue => {
value.set(name, fieldValue);
return iterate();
});
};
return iterate();
}).then(value => {
if (this._postDeserialized) {

@@ -149,8 +159,8 @@ const object = value.value;

return value.value;
});
}).valueOrPromise();
}
serialize(init, context) {
serialize(init) {
const value = new StructValue();
for (const [name, definition] of this._fields) {
const fieldValue = definition.create(this.options, context, value, init[name]);
const fieldValue = definition.create(this.options, value, init[name]);
value.set(name, fieldValue);

@@ -170,3 +180,3 @@ }

for (const { fieldValue, size } of fieldsInfo) {
fieldValue.serialize(dataView, offset, context);
fieldValue.serialize(dataView, offset);
offset += size;

@@ -173,0 +183,0 @@ }

@@ -1,3 +0,4 @@

import { __awaiter } from "tslib";
import { StructFieldDefinition, StructFieldValue } from '../basic';
import { Syncbird } from "../syncbird";
import { decodeUtf8, encodeUtf8 } from "../utils";
/**

@@ -46,9 +47,9 @@ * Base class for all types that

Uint8ClampedArrayFieldType.instance = new Uint8ClampedArrayFieldType();
/** Am ArrayBufferLike type that converts between `ArrayBuffer` and `string` */
/** An ArrayBufferLike type that converts between `ArrayBuffer` and `string` */
export class StringFieldType extends ArrayBufferLikeFieldType {
toArrayBuffer(value, context) {
return context.encodeUtf8(value);
toArrayBuffer(value) {
return encodeUtf8(value);
}
fromArrayBuffer(arrayBuffer, context) {
return context.decodeUtf8(arrayBuffer);
fromArrayBuffer(arrayBuffer) {
return decodeUtf8(arrayBuffer);
}

@@ -75,23 +76,23 @@ getSize() {

*/
create(options, context, struct, value, arrayBuffer) {
return new ArrayBufferLikeFieldValue(this, options, context, struct, value, arrayBuffer);
create(options, struct, value, arrayBuffer) {
return new ArrayBufferLikeFieldValue(this, options, struct, value, arrayBuffer);
}
deserialize(options, context, struct) {
return __awaiter(this, void 0, void 0, function* () {
deserialize(options, stream, struct) {
return Syncbird.try(() => {
const size = this.getDeserializeSize(struct);
let arrayBuffer;
if (size === 0) {
arrayBuffer = EmptyArrayBuffer;
return EmptyArrayBuffer;
}
else {
arrayBuffer = yield context.read(size);
return stream.read(size);
}
const value = this.type.fromArrayBuffer(arrayBuffer, context);
return this.create(options, context, struct, value, arrayBuffer);
});
}).then(arrayBuffer => {
const value = this.type.fromArrayBuffer(arrayBuffer);
return this.create(options, struct, value, arrayBuffer);
}).valueOrPromise();
}
}
export class ArrayBufferLikeFieldValue extends StructFieldValue {
constructor(definition, options, context, struct, value, arrayBuffer) {
super(definition, options, context, struct, value);
constructor(definition, options, struct, value, arrayBuffer) {
super(definition, options, struct, value);
this.arrayBuffer = arrayBuffer;

@@ -103,5 +104,5 @@ }

}
serialize(dataView, offset, context) {
serialize(dataView, offset) {
if (!this.arrayBuffer) {
this.arrayBuffer = this.definition.type.toArrayBuffer(this.value, context);
this.arrayBuffer = this.definition.type.toArrayBuffer(this.value);
}

@@ -108,0 +109,0 @@ new Uint8Array(dataView.buffer)

@@ -1,3 +0,3 @@

import { __awaiter } from "tslib";
import { StructFieldDefinition, StructFieldValue } from '../basic';
import { Syncbird } from "../syncbird";
export class NumberFieldType {

@@ -26,12 +26,13 @@ constructor(size, dataViewGetter, dataViewSetter) {

}
create(options, context, struct, value) {
return new NumberFieldValue(this, options, context, struct, value);
create(options, struct, value) {
return new NumberFieldValue(this, options, struct, value);
}
deserialize(options, context, struct) {
return __awaiter(this, void 0, void 0, function* () {
const buffer = yield context.read(this.getSize());
deserialize(options, stream, struct) {
return Syncbird.try(() => {
return stream.read(this.getSize());
}).then(buffer => {
const view = new DataView(buffer);
const value = view[this.type.dataViewGetter](0, options.littleEndian);
return this.create(options, context, struct, value);
});
return this.create(options, struct, value);
}).valueOrPromise();
}

@@ -38,0 +39,0 @@ }

@@ -15,9 +15,9 @@ import { StructFieldValue } from '../basic';

}
create(options, context, struct, value, arrayBuffer) {
return new VariableLengthArrayBufferLikeStructFieldValue(this, options, context, struct, value, arrayBuffer);
create(options, struct, value, arrayBuffer) {
return new VariableLengthArrayBufferLikeStructFieldValue(this, options, struct, value, arrayBuffer);
}
}
export class VariableLengthArrayBufferLikeStructFieldValue extends ArrayBufferLikeFieldValue {
constructor(definition, options, context, struct, value, arrayBuffer) {
super(definition, options, context, struct, value, arrayBuffer);
constructor(definition, options, struct, value, arrayBuffer) {
super(definition, options, struct, value, arrayBuffer);
if (arrayBuffer) {

@@ -36,3 +36,3 @@ this.length = arrayBuffer.byteLength;

if (this.length === -1) {
this.arrayBuffer = this.definition.type.toArrayBuffer(this.value, this.context);
this.arrayBuffer = this.definition.type.toArrayBuffer(this.value);
this.length = this.arrayBuffer.byteLength;

@@ -51,3 +51,3 @@ }

constructor(originalField, arrayBufferField) {
super(originalField.definition, originalField.options, originalField.context, originalField.struct, 0);
super(originalField.definition, originalField.options, originalField.struct, 0);
this.originalField = originalField;

@@ -69,7 +69,7 @@ this.arrayBufferField = arrayBufferField;

set() { }
serialize(dataView, offset, context) {
serialize(dataView, offset) {
this.originalField.set(this.get());
this.originalField.serialize(dataView, offset, context);
this.originalField.serialize(dataView, offset);
}
}
//# sourceMappingURL=variable-length-array-buffer.js.map

@@ -7,2 +7,12 @@ /**

}
// @ts-expect-error @types/node missing `TextEncoder`
const Utf8Encoder = new TextEncoder();
// @ts-expect-error @types/node missing `TextDecoder`
const Utf8Decoder = new TextDecoder();
export function encodeUtf8(input) {
return Utf8Encoder.encode(input).buffer;
}
export function decodeUtf8(buffer) {
return Utf8Decoder.decode(buffer);
}
//# sourceMappingURL=utils.js.map
{
"name": "@yume-chan/struct",
"version": "0.0.9",
"version": "0.0.10",
"description": "C-style structure serializer and deserializer.",

@@ -26,26 +26,23 @@ "keywords": [

},
"main": "cjs/index.js",
"type": "module",
"module": "esm/index.js",
"types": "dts/index.d.ts",
"scripts": {
"build": "rimraf {cjs,esm,dts,*.tsbuildinfo} && tsc -b tsconfig.esm.json tsconfig.cjs.json",
"build:watch": "tsc -b -w tsconfig.esm.json tsconfig.cjs.json",
"test": "jest",
"coverage": "jest --coverage",
"build": "build-ts-package",
"build:watch": "build-ts-package --incremental",
"test": "jest --coverage",
"prepublishOnly": "npm run build"
},
"dependencies": {
"tslib": "2.1.0"
"bluebird": "^3.7.2",
"tslib": "^2.3.1"
},
"devDependencies": {
"@types/jest": "26.0.19",
"jest": "26.6.3",
"rimraf": "3.0.2",
"ts-jest": "26.4.4",
"typescript": "4.2.3"
},
"publishConfig": {
"access": "public"
},
"gitHead": "09c9764aa84fe0098342283a61758354ba2613b6"
"jest": "^26.6.3",
"typescript": "^4.5.4",
"@yume-chan/ts-package-builder": "^1.0.0",
"@types/jest": "^27.4.0",
"@types/node": "^16.11.19",
"@types/bluebird": "^3.5.36"
}
}

@@ -11,2 +11,4 @@ # @yume-chan/struct

**WARNING:** The public API is UNSTABLE. If you have any questions, please open an issue.
## Installation

@@ -218,5 +220,5 @@

struct.serialize({ }, context) // error: 'foo' is required
struct.serialize({ foo: 'bar' }, context) // error: 'foo' must be a number
struct.serialize({ foo: 42 }, context) // ok
struct.serialize({ }) // error: 'foo' is required
struct.serialize({ foo: 'bar' }) // error: 'foo' must be a number
struct.serialize({ foo: 42 }) // ok
```

@@ -240,5 +242,5 @@

struct.serialize({ foo: 42, bar: MyEnum.a }, context); // error: 'foo' must be of type `MyEnum`
struct.serialize({ foo: MyEnum.a, bar: MyEnum.b }, context); // error: 'bar' must be of type `MyEnum.a`
struct.serialize({ foo: MyEnum.a, bar: MyEnum.b }, context); // ok
struct.serialize({ foo: 42, bar: MyEnum.a }); // error: 'foo' must be of type `MyEnum`
struct.serialize({ foo: MyEnum.a, bar: MyEnum.b }); // error: 'bar' must be of type `MyEnum.a`
struct.serialize({ foo: MyEnum.a, bar: MyEnum.b }); // ok
```

@@ -340,3 +342,3 @@

const structV2 = await MyStructV2.deserialize(context);
const structV2 = await MyStructV2.deserialize(stream);
structV2.field1; // number

@@ -359,3 +361,3 @@ structV2.field2; // number

const structV2 = await MyStructV2.deserialize(context);
const structV2 = await MyStructV2.deserialize(stream);
structV2.field1; // number

@@ -417,4 +419,4 @@ structV2.field2; // number

struct.serialize({ foo: 42 }, context); // ok
struct.serialize({ foo: 42, bar: 'hello' }, context); // error: 'bar' is redundant
struct.serialize({ foo: 42 }); // ok
struct.serialize({ foo: 42, bar: 'hello' }); // error: 'bar' is redundant
```

@@ -529,10 +531,20 @@

```ts
interface StructDeserializationContext {
decodeUtf8(buffer: ArrayBuffer): string;
read(length: number): ArrayBuffer | Promise<ArrayBuffer>;
interface StructDeserializeStream {
/**
* Read data from the underlying data source.
*
* Stream must return exactly `length` bytes or data. If that's not possible
* (due to end of file or other error condition), it must throw an error.
*/
read(length: number): ArrayBuffer;
}
deserialize(
context: StructDeserializationContext
stream: StructDeserializeStream,
): TPostDeserialized extends undefined
? Overwrite<TExtra, TValue>
: TPostDeserialized
>;
deserialize(
stream: StructAsyncDeserializeStream,
): Promise<

@@ -542,10 +554,11 @@ TPostDeserialized extends undefined

: TPostDeserialized
>;
>
>;
```
Deserialize a Struct value from `context`.
Deserialize a Struct value from `stream`.
As the signature shows, if the `postDeserialize` callback returns any value, `deserialize` will return that value instead.
The `read` method of `context`, when being called, should returns exactly `length` bytes of data (or throw an `Error` if it can't).
The `read` method of `stream`, when being called, should returns exactly `length` bytes of data (or throw an `Error` if it can't).

@@ -555,9 +568,4 @@ #### `serialize`

```ts
interface StructSerializationContext {
encodeUtf8(input: string): ArrayBuffer;
}
serialize(
init: Omit<TFields, TOmitInitKey>,
context: StructSerializationContext
init: Omit<TFields, TOmitInitKey>
): ArrayBuffer;

@@ -646,3 +654,2 @@ ```

options: Readonly<StructOptions>,
context: StructSerializationContext,
struct: StructValue,

@@ -662,12 +669,17 @@ value: TValue,

options: Readonly<StructOptions>,
context: StructDeserializationContext,
stream: StructDeserializeStream,
struct: StructValue,
): ValueOrPromise<StructFieldValue<this>>;
): StructFieldValue<this>;
abstract deserialize(
options: Readonly<StructOptions>,
stream: StructAsyncDeserializeStream,
struct: StructValue,
): Promise<StructFieldValue<this>>;
```
Derived classes must implement this method to define how to deserialize a value from `context`. Can also return a `Promise`.
Derived classes must implement this method to define how to deserialize a value from `stream`. Can also return a `Promise`.
Usually implementations should be:
1. Somehow parse the value from `context`
1. Somehow parse the value from `stream`
2. Pass the value into its `create` method

@@ -715,4 +727,3 @@

dataView: DataView,
offset: number,
context: StructSerializationContext
offset: number
): void;

@@ -719,0 +730,0 @@ ```

@@ -1,29 +0,19 @@

import type { ValueOrPromise } from '../utils';
/**
* Context with enough methods to serialize a struct
*/
export interface StructSerializationContext {
export interface StructDeserializeStream {
/**
* Encode the specified string into an ArrayBuffer using UTF-8 encoding
* Read data from the underlying data source.
*
* Stream must return exactly `length` bytes or data. If that's not possible
* (due to end of file or other error condition), it must throw an error.
*/
encodeUtf8(input: string): ArrayBuffer;
read(length: number): ArrayBuffer;
}
/**
* Context with enough methods to deserialize a struct
*/
export interface StructDeserializationContext extends StructSerializationContext {
export interface StructAsyncDeserializeStream {
/**
* Decode the specified `ArrayBuffer` using UTF-8 encoding
*/
decodeUtf8(buffer: ArrayBuffer): string;
/**
* Read data from the underlying data source.
*
* Context should return exactly `length` bytes or data. If that's not possible
* (due to end of file or other error condition), it should throw an error.
* Context must return exactly `length` bytes or data. If that's not possible
* (due to end of file or other error condition), it must throw an error.
*/
read(length: number): ValueOrPromise<ArrayBuffer>;
read(length: number): Promise<ArrayBuffer>;
}

@@ -30,0 +20,0 @@

@@ -1,3 +0,2 @@

import type { ValueOrPromise } from '../utils';
import type { StructDeserializationContext, StructOptions, StructSerializationContext } from './context';
import type { StructAsyncDeserializeStream, StructDeserializeStream, StructOptions } from './context';
import type { StructFieldValue } from './field-value';

@@ -56,3 +55,2 @@ import type { StructValue } from './struct-value';

options: Readonly<StructOptions>,
context: StructSerializationContext,
struct: StructValue,

@@ -67,5 +65,10 @@ value: TValue,

options: Readonly<StructOptions>,
context: StructDeserializationContext,
stream: StructDeserializeStream,
struct: StructValue,
): ValueOrPromise<StructFieldValue<this>>;
): StructFieldValue<this>;
public abstract deserialize(
options: Readonly<StructOptions>,
stream: StructAsyncDeserializeStream,
struct: StructValue,
): Promise<StructFieldValue<this>>;
}

@@ -1,2 +0,2 @@

import type { StructOptions, StructSerializationContext } from './context';
import type { StructOptions } from './context';
import type { StructFieldDefinition } from './definition';

@@ -20,5 +20,2 @@ import type { StructValue } from './struct-value';

/** Gets the serialization context of the associated `Struct` instance */
public readonly context: StructSerializationContext;
/** Gets the associated `Struct` instance */

@@ -32,3 +29,2 @@ public readonly struct: StructValue;

options: Readonly<StructOptions>,
context: StructSerializationContext,
struct: StructValue,

@@ -39,3 +35,2 @@ value: TDefinition['TValue'],

this.options = options;
this.context = context;
this.struct = struct;

@@ -74,4 +69,3 @@ this.value = value;

offset: number,
context: StructSerializationContext
): void;
}

@@ -0,0 +0,0 @@ export * from './context';

@@ -21,5 +21,2 @@ import type { StructFieldValue } from './field-value';

public set(key: PropertyKey, value: StructFieldValue): void {
// TODO: TypeScript 4.2 will allow this behavior
// https://github.com/microsoft/TypeScript/pull/26797
// @ts-expect-error Type 'symbol' cannot be used as an index type. ts(2538)
this.fieldValues[key] = value;

@@ -41,7 +38,4 @@

public get(key: PropertyKey): StructFieldValue {
// TODO: TypeScript 4.2 will allow this behavior
// https://github.com/microsoft/TypeScript/pull/26797
// @ts-expect-error Type 'symbol' cannot be used as an index type. ts(2538)
return this.fieldValues[key];
}
}

@@ -0,0 +0,0 @@ export * from './basic';

@@ -1,7 +0,9 @@

import { StructDefaultOptions, StructDeserializationContext, StructFieldDefinition, StructFieldValue, StructOptions, StructSerializationContext, StructValue } from './basic';
import type { StructAsyncDeserializeStream, StructDeserializeStream, StructFieldDefinition, StructFieldValue, StructOptions } from './basic';
import { StructDefaultOptions, StructValue } from './basic';
import { Syncbird } from "./syncbird";
import { ArrayBufferFieldType, ArrayBufferLikeFieldType, FixedLengthArrayBufferLikeFieldDefinition, FixedLengthArrayBufferLikeFieldOptions, LengthField, NumberFieldDefinition, NumberFieldType, StringFieldType, Uint8ClampedArrayFieldType, VariableLengthArrayBufferLikeFieldDefinition, VariableLengthArrayBufferLikeFieldOptions } from './types';
import { Awaited, Evaluate, Identity, Overwrite } from './utils';
import { Evaluate, Identity, Overwrite, ValueOrPromise } from "./utils";
export interface StructLike<TValue> {
deserialize(context: StructDeserializationContext): Promise<TValue>;
deserialize(stream: StructDeserializeStream | StructAsyncDeserializeStream): Promise<TValue>;
}

@@ -11,4 +13,2 @@

* Extract the value type of the specified `Struct`
*
* The lack of generic constraint is on purpose to allow `StructLike` types
*/

@@ -19,3 +19,3 @@ export type StructValueType<T extends StructLike<any>> =

/**
* Create a new `Struct` type with `TDescriptor` appended
* Create a new `Struct` type with `TDefinition` appended
*/

@@ -50,3 +50,3 @@ type AddFieldDescriptor<

/**
* Append a fixed-length array to the `Struct`
* Append a fixed-length array buffer like field to the `Struct`
*

@@ -61,3 +61,3 @@ * @param name Name of the field

TName extends PropertyKey,
TType extends ArrayBufferLikeFieldType,
TType extends ArrayBufferLikeFieldType<any, any>,
TTypeScriptType = TType['TTypeScriptType'],

@@ -82,7 +82,7 @@ >(

/**
* Append a variable-length array to the `Struct`
* Append a variable-length array buffer like field to the `Struct`
*/
<
TName extends PropertyKey,
TType extends ArrayBufferLikeFieldType,
TType extends ArrayBufferLikeFieldType<any, any>,
TOptions extends VariableLengthArrayBufferLikeFieldOptions<TFields>,

@@ -109,5 +109,5 @@ TTypeScriptType = TType['TTypeScriptType'],

/**
* Similar to `ArrayBufferLikeFieldCreator`, but bind to a `ArrayBufferLikeFieldType`
* Similar to `ArrayBufferLikeFieldCreator`, but bind to `TType`
*/
interface ArrayBufferTypeFieldDefinitionCreator<
interface BindedArrayBufferLikeFieldDefinitionCreator<
TFields extends object,

@@ -117,3 +117,3 @@ TOmitInitKey extends PropertyKey,

TPostDeserialized,
TType extends ArrayBufferLikeFieldType
TType extends ArrayBufferLikeFieldType<any, any>
> {

@@ -430,3 +430,3 @@ <

public arrayBuffer: ArrayBufferTypeFieldDefinitionCreator<
public arrayBuffer: BindedArrayBufferLikeFieldDefinitionCreator<
TFields,

@@ -444,3 +444,3 @@ TOmitInitKey,

public uint8ClampedArray: ArrayBufferTypeFieldDefinitionCreator<
public uint8ClampedArray: BindedArrayBufferLikeFieldDefinitionCreator<
TFields,

@@ -458,3 +458,3 @@ TOmitInitKey,

public string: ArrayBufferTypeFieldDefinitionCreator<
public string: BindedArrayBufferLikeFieldDefinitionCreator<
TFields,

@@ -473,10 +473,10 @@ TOmitInitKey,

/**
* Adds some extra fields into every Struct value.
* Adds some extra properties into every `Struct` value.
*
* Extra fields will not affect serialize or deserialize process.
* Extra properties will not affect serialize or deserialize process.
*
* Multiple calls to `extra` will merge all values together.
* Multiple calls to `extra` will merge all properties together.
*
* @param value
* An object containing anything you want to add to the result object. Accessors and methods are also allowed.
* An object containing properties to be added to the result value. Accessors and methods are also allowed.
*/

@@ -536,29 +536,49 @@ public extra<T extends Record<

public async deserialize(
context: StructDeserializationContext
): Promise<StructDeserializedResult<TFields, TExtra, TPostDeserialized>> {
public deserialize(
stream: StructDeserializeStream,
): StructDeserializedResult<TFields, TExtra, TPostDeserialized>;
public deserialize(
stream: StructAsyncDeserializeStream,
): Promise<StructDeserializedResult<TFields, TExtra, TPostDeserialized>>;
public deserialize(
stream: StructDeserializeStream | StructAsyncDeserializeStream,
): ValueOrPromise<StructDeserializedResult<TFields, TExtra, TPostDeserialized>> {
const value = new StructValue();
Object.defineProperties(value.value, this._extra);
for (const [name, definition] of this._fields) {
const fieldValue = await definition.deserialize(this.options, context, value);
value.set(name, fieldValue);
}
return Syncbird.try(() => {
const iterator = this._fields[Symbol.iterator]();
const iterate: () => StructValue | Syncbird<StructValue> = () => {
const result = iterator.next();
if (result.done) {
return value;
}
if (this._postDeserialized) {
const object = value.value as TFields;
const result = this._postDeserialized.call(object, object);
if (result) {
return result;
const [name, definition] = result.value;
return Syncbird.resolve(
definition.deserialize(this.options, stream as any, value)
).then(fieldValue => {
value.set(name, fieldValue);
return iterate();
});
};
return iterate();
}).then(value => {
if (this._postDeserialized) {
const object = value.value as TFields;
const result = this._postDeserialized.call(object, object);
if (result) {
return result;
}
}
}
return value.value as any;
return value.value;
}).valueOrPromise();
}
public serialize(init: Evaluate<Omit<TFields, TOmitInitKey>>, context: StructSerializationContext): ArrayBuffer {
public serialize(init: Evaluate<Omit<TFields, TOmitInitKey>>): ArrayBuffer {
const value = new StructValue();
for (const [name, definition] of this._fields) {
const fieldValue = definition.create(this.options, context, value, (init as any)[name]);
const fieldValue = definition.create(this.options, value, (init as any)[name]);
value.set(name, fieldValue);

@@ -581,3 +601,3 @@ }

for (const { fieldValue, size } of fieldsInfo) {
fieldValue.serialize(dataView, offset, context);
fieldValue.serialize(dataView, offset);
offset += size;

@@ -584,0 +604,0 @@ }

@@ -1,2 +0,4 @@

import { StructDeserializationContext, StructFieldDefinition, StructFieldValue, StructOptions, StructSerializationContext, StructValue } from '../basic';
import { StructAsyncDeserializeStream, StructDeserializeStream, StructFieldDefinition, StructFieldValue, StructOptions, StructValue } from '../basic';
import { Syncbird } from "../syncbird";
import { decodeUtf8, encodeUtf8, ValueOrPromise } from "../utils";

@@ -21,6 +23,6 @@ /**

*/
public abstract toArrayBuffer(value: TValue, context: StructSerializationContext): ArrayBuffer;
public abstract toArrayBuffer(value: TValue): ArrayBuffer;
/** When implemented in derived classes, converts the `ArrayBuffer` to a type-specific value */
public abstract fromArrayBuffer(arrayBuffer: ArrayBuffer, context: StructDeserializationContext): TValue;
public abstract fromArrayBuffer(arrayBuffer: ArrayBuffer): TValue;

@@ -80,3 +82,3 @@ /**

/** Am ArrayBufferLike type that converts between `ArrayBuffer` and `string` */
/** An ArrayBufferLike type that converts between `ArrayBuffer` and `string` */
export class StringFieldType<TTypeScriptType = string>

@@ -86,8 +88,8 @@ extends ArrayBufferLikeFieldType<string, TTypeScriptType> {

public toArrayBuffer(value: string, context: StructSerializationContext): ArrayBuffer {
return context.encodeUtf8(value);
public toArrayBuffer(value: string): ArrayBuffer {
return encodeUtf8(value);
}
public fromArrayBuffer(arrayBuffer: ArrayBuffer, context: StructDeserializationContext): string {
return context.decodeUtf8(arrayBuffer);
public fromArrayBuffer(arrayBuffer: ArrayBuffer): string {
return decodeUtf8(arrayBuffer);
}

@@ -106,3 +108,3 @@

export abstract class ArrayBufferLikeFieldDefinition<
TType extends ArrayBufferLikeFieldType = ArrayBufferLikeFieldType,
TType extends ArrayBufferLikeFieldType<any, any> = ArrayBufferLikeFieldType<unknown, unknown>,
TOptions = void,

@@ -131,3 +133,2 @@ TOmitInitKey extends PropertyKey = never,

options: Readonly<StructOptions>,
context: StructSerializationContext,
struct: StructValue,

@@ -137,21 +138,31 @@ value: TType['TTypeScriptType'],

): ArrayBufferLikeFieldValue<this> {
return new ArrayBufferLikeFieldValue(this, options, context, struct, value, arrayBuffer);
return new ArrayBufferLikeFieldValue(this, options, struct, value, arrayBuffer);
}
public async deserialize(
public override deserialize(
options: Readonly<StructOptions>,
context: StructDeserializationContext,
stream: StructDeserializeStream,
struct: StructValue,
): Promise<ArrayBufferLikeFieldValue<this>> {
const size = this.getDeserializeSize(struct);
let arrayBuffer: ArrayBuffer;
if (size === 0) {
arrayBuffer = EmptyArrayBuffer;
} else {
arrayBuffer = await context.read(size);
}
const value = this.type.fromArrayBuffer(arrayBuffer, context);
return this.create(options, context, struct, value, arrayBuffer);
): ArrayBufferLikeFieldValue<this>;
public override deserialize(
options: Readonly<StructOptions>,
stream: StructAsyncDeserializeStream,
struct: StructValue,
): Promise<ArrayBufferLikeFieldValue<this>>;
public override deserialize(
options: Readonly<StructOptions>,
stream: StructDeserializeStream | StructAsyncDeserializeStream,
struct: StructValue,
): ValueOrPromise<ArrayBufferLikeFieldValue<this>> {
return Syncbird.try(() => {
const size = this.getDeserializeSize(struct);
if (size === 0) {
return EmptyArrayBuffer;
} else {
return stream.read(size);
}
}).then(arrayBuffer => {
const value = this.type.fromArrayBuffer(arrayBuffer);
return this.create(options, struct, value, arrayBuffer);
}).valueOrPromise();
}

@@ -161,3 +172,3 @@ }

export class ArrayBufferLikeFieldValue<
TDefinition extends ArrayBufferLikeFieldDefinition<ArrayBufferLikeFieldType, any, any>,
TDefinition extends ArrayBufferLikeFieldDefinition<ArrayBufferLikeFieldType<unknown, unknown>, any, any>,
> extends StructFieldValue<TDefinition> {

@@ -169,3 +180,2 @@ protected arrayBuffer: ArrayBuffer | undefined;

options: Readonly<StructOptions>,
context: StructSerializationContext,
struct: StructValue,

@@ -175,7 +185,7 @@ value: TDefinition['TValue'],

) {
super(definition, options, context, struct, value);
super(definition, options, struct, value);
this.arrayBuffer = arrayBuffer;
}
public set(value: TDefinition['TValue']): void {
public override set(value: TDefinition['TValue']): void {
super.set(value);

@@ -185,5 +195,5 @@ this.arrayBuffer = undefined;

public serialize(dataView: DataView, offset: number, context: StructSerializationContext): void {
public serialize(dataView: DataView, offset: number): void {
if (!this.arrayBuffer) {
this.arrayBuffer = this.definition.type.toArrayBuffer(this.value, context);
this.arrayBuffer = this.definition.type.toArrayBuffer(this.value);
}

@@ -190,0 +200,0 @@

@@ -0,0 +0,0 @@ import { ArrayBufferLikeFieldDefinition, ArrayBufferLikeFieldType } from './array-buffer';

@@ -0,0 +0,0 @@ export * from './array-buffer';

@@ -1,2 +0,4 @@

import { StructDeserializationContext, StructFieldDefinition, StructFieldValue, StructOptions, StructSerializationContext, StructValue } from '../basic';
import { StructAsyncDeserializeStream, StructDeserializeStream, StructFieldDefinition, StructFieldValue, StructOptions, StructValue } from '../basic';
import { Syncbird } from "../syncbird";
import { ValueOrPromise } from "../utils";

@@ -65,21 +67,33 @@ export type DataViewGetters =

options: Readonly<StructOptions>,
context: StructSerializationContext,
struct: StructValue,
value: TTypeScriptType,
): NumberFieldValue<this> {
return new NumberFieldValue(this, options, context, struct, value);
return new NumberFieldValue(this, options, struct, value);
}
public async deserialize(
public override deserialize(
options: Readonly<StructOptions>,
context: StructDeserializationContext,
stream: StructDeserializeStream,
struct: StructValue,
): Promise<NumberFieldValue<this>> {
const buffer = await context.read(this.getSize());
const view = new DataView(buffer);
const value = view[this.type.dataViewGetter](
0,
options.littleEndian
) as any;
return this.create(options, context, struct, value);
): NumberFieldValue<this>;
public override deserialize(
options: Readonly<StructOptions>,
stream: StructAsyncDeserializeStream,
struct: StructValue,
): Promise<NumberFieldValue<this>>;
public override deserialize(
options: Readonly<StructOptions>,
stream: StructDeserializeStream | StructAsyncDeserializeStream,
struct: StructValue,
): ValueOrPromise<NumberFieldValue<this>> {
return Syncbird.try(() => {
return stream.read(this.getSize());
}).then(buffer => {
const view = new DataView(buffer);
const value = view[this.type.dataViewGetter](
0,
options.littleEndian
) as any;
return this.create(options, struct, value);
}).valueOrPromise();
}

@@ -86,0 +100,0 @@ }

@@ -1,2 +0,2 @@

import { StructFieldDefinition, StructFieldValue, StructOptions, StructSerializationContext, StructValue } from '../basic';
import { StructFieldDefinition, StructFieldValue, StructOptions, StructValue } from '../basic';
import type { KeysOfType } from '../utils';

@@ -28,3 +28,3 @@ import { ArrayBufferLikeFieldDefinition, ArrayBufferLikeFieldType, ArrayBufferLikeFieldValue } from './array-buffer';

protected getDeserializeSize(struct: StructValue) {
protected override getDeserializeSize(struct: StructValue) {
let value = struct.value[this.options.lengthField] as number | string;

@@ -37,5 +37,4 @@ if (typeof value === 'string') {

public create(
public override create(
options: Readonly<StructOptions>,
context: StructSerializationContext,
struct: StructValue,

@@ -48,3 +47,2 @@ value: TType['TTypeScriptType'],

options,
context,
struct,

@@ -67,3 +65,2 @@ value,

options: Readonly<StructOptions>,
context: StructSerializationContext,
struct: StructValue,

@@ -73,3 +70,3 @@ value: TDefinition['TValue'],

) {
super(definition, options, context, struct, value, arrayBuffer);
super(definition, options, struct, value, arrayBuffer);

@@ -91,7 +88,7 @@ if (arrayBuffer) {

public getSize() {
public override getSize() {
if (this.length === undefined) {
this.length = this.definition.type.getSize(this.value);
if (this.length === -1) {
this.arrayBuffer = this.definition.type.toArrayBuffer(this.value, this.context);
this.arrayBuffer = this.definition.type.toArrayBuffer(this.value);
this.length = this.arrayBuffer.byteLength;

@@ -104,3 +101,3 @@ }

public set(value: unknown) {
public override set(value: unknown) {
super.set(value);

@@ -126,3 +123,3 @@ this.arrayBuffer = undefined;

) {
super(originalField.definition, originalField.options, originalField.context, originalField.struct, 0);
super(originalField.definition, originalField.options, originalField.struct, 0);
this.originalField = originalField;

@@ -132,7 +129,7 @@ this.arrayBufferField = arrayBufferField;

public getSize() {
public override getSize() {
return this.originalField.getSize();
}
get() {
public override get() {
let value: string | number = this.arrayBufferField.getSize();

@@ -148,8 +145,8 @@

set() { }
public override set() { }
serialize(dataView: DataView, offset: number, context: StructSerializationContext) {
serialize(dataView: DataView, offset: number) {
this.originalField.set(this.get());
this.originalField.serialize(dataView, offset, context);
this.originalField.serialize(dataView, offset);
}
}

@@ -42,6 +42,4 @@ /**

export type ValueOrPromise<T> = T | Promise<T>;
export type ValueOrPromise<T> = T | PromiseLike<T>;
export type Awaited<T> = T extends Promise<infer R> ? Awaited<R> : T;
/**

@@ -53,1 +51,14 @@ * Returns a (fake) value of the given type.

}
// @ts-expect-error @types/node missing `TextEncoder`
const Utf8Encoder = new TextEncoder();
// @ts-expect-error @types/node missing `TextDecoder`
const Utf8Decoder = new TextDecoder();
export function encodeUtf8(input: string): ArrayBuffer {
return Utf8Encoder.encode(input).buffer;
}
export function decodeUtf8(buffer: ArrayBuffer): string {
return Utf8Decoder.decode(buffer);
}

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc