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

@yume-chan/struct

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.16 to 0.0.17

@@ -5,2 +5,8 @@ {

{
"version": "0.0.17",
"tag": "@yume-chan/struct_v0.0.17",
"date": "Tue, 18 Oct 2022 09:32:30 GMT",
"comments": {}
},
{
"version": "0.0.16",

@@ -7,0 +13,0 @@ "tag": "@yume-chan/struct_v0.0.16",

# Change Log - @yume-chan/struct
This log was last generated on Sat, 28 May 2022 03:56:37 GMT and should not be manually modified.
This log was last generated on Tue, 18 Oct 2022 09:32:30 GMT and should not be manually modified.
## 0.0.17
Tue, 18 Oct 2022 09:32:30 GMT
_Version update only_
## 0.0.16

@@ -6,0 +11,0 @@ Sat, 28 May 2022 03:56:37 GMT

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

import { STRUCT_VALUE_SYMBOL } from './basic/index.js';
import { StructDefaultOptions, StructValue } from './basic/index.js';
import { StructDefaultOptions, StructValue, STRUCT_VALUE_SYMBOL } from './basic/index.js';
import { SyncPromise } from "./sync-promise.js";

@@ -157,3 +156,3 @@ import { BigIntFieldDefinition, BigIntFieldType, FixedLengthBufferLikeFieldDefinition, NumberFieldDefinition, NumberFieldType, StringBufferFieldSubType, Uint8ArrayBufferFieldSubType, VariableLengthBufferLikeFieldDefinition } from './types/index.js';

// Otherwise it only inspects/mutates the object in place.
if (override) {
if (override !== undefined) {
return override;

@@ -160,0 +159,0 @@ }

{
"name": "@yume-chan/struct",
"version": "0.0.16",
"version": "0.0.17",
"description": "C-style structure serializer and deserializer.",

@@ -17,3 +17,3 @@ "keywords": [

},
"homepage": "https://github.com/yume-chan/ya-webadb/tree/master/packages/struct#readme",
"homepage": "https://github.com/yume-chan/ya-webadb/tree/main/packages/struct#readme",
"repository": {

@@ -31,12 +31,12 @@ "type": "git",

"dependencies": {
"@yume-chan/dataview-bigint-polyfill": "^0.0.16",
"tslib": "^2.3.1"
"@yume-chan/dataview-bigint-polyfill": "^0.0.17",
"tslib": "^2.4.0"
},
"devDependencies": {
"@jest/globals": "^28.1.0",
"@jest/globals": "^28.1.2",
"@yume-chan/ts-package-builder": "^1.0.0",
"cross-env": "^7.0.3",
"jest": "^28.1.0",
"ts-jest": "^28.0.2",
"typescript": "4.7.2"
"jest": "^28.1.2",
"ts-jest": "^28.0.5",
"typescript": "^4.7.4"
},

@@ -47,4 +47,3 @@ "scripts": {

"test": "cross-env NODE_OPTIONS=--experimental-vm-modules jest --coverage"
},
"readme": "# @yume-chan/struct\n\n<!--\ncspell: ignore Codecov\ncspell: ignore uint8arraystring\n-->\n\n![license](https://img.shields.io/npm/l/@yume-chan/struct)\n![npm type definitions](https://img.shields.io/npm/types/@yume-chan/struct)\n[![npm version](https://img.shields.io/npm/v/@yume-chan/struct)](https://www.npmjs.com/package/@yume-chan/struct)\n![npm bundle size](https://img.shields.io/bundlephobia/min/@yume-chan/struct)\n![Codecov](https://img.shields.io/codecov/c/github/yume-chan/ya-webadb?flag=struct&token=2fU3Cx2Edq)\n\nA C-style structure serializer and deserializer. Written in TypeScript and highly takes advantage of its type system.\n\n**WARNING:** The public API is UNSTABLE. If you have any questions, please open an issue.\n\n## Installation\n\n```sh\n$ npm i @yume-chan/struct\n```\n\n## Quick Start\n\n```ts\nimport Struct from '@yume-chan/struct';\n\nconst MyStruct =\n new Struct({ littleEndian: true })\n .int8('foo')\n .int64('bar')\n .int32('bazLength')\n .string('baz', { lengthField: 'bazLength' });\n\nconst value = await MyStruct.deserialize(stream);\nvalue.foo // number\nvalue.bar // bigint\nvalue.bazLength // number\nvalue.baz // string\n\nconst buffer = MyStruct.serialize({\n foo: 42,\n bar: 42n,\n // `bazLength` automatically set to `baz`'s byte length\n baz: 'Hello, World!',\n});\n```\n\n<!-- cspell: disable -->\n\n- [Installation](#installation)\n- [Quick Start](#quick-start)\n- [Compatibility](#compatibility)\n - [Basic usage](#basic-usage)\n - [`int64`/`uint64`](#int64uint64)\n - [`string`](#string)\n- [API](#api)\n - [`placeholder`](#placeholder)\n - [`Struct`](#struct)\n - [`int8`/`uint8`/`int16`/`uint16`/`int32`/`uint32`](#int8uint8int16uint16int32uint32)\n - [`int64`/`uint64`](#int64uint64-1)\n - [`uint8Array`/`string`](#uint8arraystring)\n - [`fields`](#fields)\n - [`extra`](#extra)\n - [`postDeserialize`](#postdeserialize)\n - [`deserialize`](#deserialize)\n - [`serialize`](#serialize)\n- [Custom field type](#custom-field-type)\n - [`Struct#field`](#structfield)\n - [Relationship between types](#relationship-between-types)\n - [`StructFieldDefinition`](#structfielddefinition)\n - [`TValue`/`TOmitInitKey`](#tvaluetomitinitkey)\n - [`getSize`](#getsize)\n - [`create`](#create)\n - [`deserialize`](#deserialize-1)\n - [`StructFieldValue`](#structfieldvalue)\n - [`getSize`](#getsize-1)\n - [`get`/`set`](#getset)\n - [`serialize`](#serialize-1)\n\n<!-- cspell: enable -->\n\n## Compatibility\n\nHere is a list of features, their used APIs, and their compatibilities. If an optional feature is not actually used, its requirements can be ignored.\n\nSome features can be polyfilled to support older runtimes, but this library doesn't ship with any polyfills.\n\n### Basic usage\n\n| API | Chrome | Edge | Firefox | Internet Explorer | Safari | Node.js |\n| -------------------------------- | ------ | ---- | ------- | ----------------- | ------ | ------- |\n| [`Promise`][MDN_Promise] | 32 | 12 | 29 | No | 8 | 0.12 |\n| [`ArrayBuffer`][MDN_ArrayBuffer] | 7 | 12 | 4 | 10 | 5.1 | 0.10 |\n| [`Uint8Array`][MDN_Uint8Array] | 7 | 12 | 4 | 10 | 5.1 | 0.10 |\n| [`DataView`][MDN_DataView] | 9 | 12 | 15 | 10 | 5.1 | 0.10 |\n| *Overall* | 32 | 12 | 29 | No | 8 | 0.12 |\n\n### [`int64`/`uint64`](#int64uint64-1)\n\n| API | Chrome | Edge | Firefox | Internet Explorer | Safari | Node.js |\n| ---------------------------------- | ------ | ---- | ------- | ----------------- | ------ | ------- |\n| [`BigInt`][MDN_BigInt]<sup>1</sup> | 67 | 79 | 68 | No | 14 | 10.4 |\n\n<sup>1</sup> Can't be polyfilled\n\n### [`string`](#uint8arraystring)\n\n| API | Chrome | Edge | Firefox | Internet Explorer | Safari | Node.js |\n| -------------------------------- | ------ | ---- | ------- | ----------------- | ------ | ------------------- |\n| [`TextEncoder`][MDN_TextEncoder] | 38 | 79 | 19 | No | 10.1 | 8.3<sup>1</sup>, 11 |\n\n<sup>1</sup> `TextEncoder` and `TextDecoder` are only available in `util` module. Need to be assigned to `globalThis`.\n\n[MDN_Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise\n[MDN_ArrayBuffer]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer\n[MDN_Uint8Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array\n[MDN_DataView]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView\n[MDN_BigInt]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt\n[MDN_DataView]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView\n[MDN_TextEncoder]: https://developer.mozilla.org/en-US/docs/Web/API/TextEncoder\n\n## API\n\n### `placeholder`\n\n```ts\nfunction placeholder<T>(): T {\n return undefined as unknown as T;\n}\n```\n\nReturns a (fake) value of the given type. It's only useful in TypeScript, if you are using JavaScript, you shouldn't care about it.\n\nMany methods in this library have multiple generic parameters, but TypeScript only allows users to specify none (let TypeScript inference all of them from arguments), or all generic arguments. ([Microsoft/TypeScript#26242](https://github.com/microsoft/TypeScript/issues/26242))\n\n<details>\n<summary>Detail explanation (click to expand)</summary>\n\nWhen you have a generic method, where half generic parameters can be inferred.\n\n```ts\ndeclare function fn<A, B>(a: A): [A, B];\nfn(42); // Expected 2 type arguments, but got 1. ts(2558)\n```\n\nRather than force users repeat the type `A`, I declare a parameter for `B`.\n\n```ts\ndeclare function fn2<A, B>(a: A, b: B): [A, B];\n```\n\nI don't really need a value of type `B`, I only require its type information\n\n```ts\nfn2(42, placeholder<boolean>()) // fn2<number, boolean>\n```\n</details>\n\nTo workaround this issue, these methods have an extra `_typescriptType` parameter, to let you specify a generic parameter, without passing all other generic arguments manually. The actual value of `_typescriptType` argument is never used, so you can pass any value, as long as it has the correct type, including values produced by this `placeholder` method.\n\n**With that said, I don't expect you to specify any generic arguments manually when using this library.**\n\n### `Struct`\n\n```ts\nclass Struct<\n TFields extends object = {},\n TOmitInitKey extends string | number | symbol = never,\n TExtra extends object = {},\n TPostDeserialized = undefined\n> {\n public constructor(options: Partial<StructOptions> = StructDefaultOptions);\n}\n```\n\nCreates a new structure definition.\n\n<details>\n<summary>Generic parameters (click to expand)</summary>\n\nThis information was added to help you understand how does it work. These are considered as \"internal state\" so don't specify them manually.\n\n1. `TFields`: Type of the Struct value. Modified when new fields are added.\n2. `TOmitInitKey`: When serializing a structure containing variable length buffers, the length field can be calculate from the buffer field, so they doesn't need to be provided explicitly.\n3. `TExtra`: Type of extra fields. Modified when `extra` is called.\n4. `TPostDeserialized`: State of the `postDeserialize` function. Modified when `postDeserialize` is called. Affects return type of `deserialize`\n</details>\n\n**Parameters**\n\n1. `options`:\n * `littleEndian:boolean = false`: Whether all multi-byte fields in this struct are [little-endian encoded][Wikipeida_Endianess].\n\n[Wikipeida_Endianess]: https://en.wikipedia.org/wiki/Endianness\n\n#### `int8`/`uint8`/`int16`/`uint16`/`int32`/`uint32`\n\n```ts\nint32<\n TName extends string | number | symbol,\n TTypeScriptType = number\n>(\n name: TName,\n _typescriptType?: TTypeScriptType\n): Struct<\n TFields & Record<TName, TTypeScriptType>,\n TOmitInitKey,\n TExtra,\n TPostDeserialized\n>;\n```\n\nAppends an `int8`/`uint8`/`int16`/`uint16`/`int32`/`uint32` field to the `Struct`.\n\n<details>\n<summary>Generic parameters (click to expand)</summary>\n\n1. `TName`: Literal type of the field's name.\n2. `TTypeScriptType = number`: Type of the field in the result object. For example you can declare it as a number literal type, or some enum type.\n</details>\n\n**Parameters**\n\n1. `name`: (Required) Field name. Must be a string literal.\n2. `_typescriptType`: Set field's type. See examples below.\n\n**Note**\n\nThere is no generic constraints on the `TTypeScriptType`, because TypeScript doesn't allow casting enum types to `number`.\n\nSo it's technically possible to pass in an incompatible type (e.g. `string`). But obviously, it's a bad idea.\n\n**Examples**\n\n1. Append an `int32` field named `foo`\n\n ```ts\n const struct = new Struct()\n .int32('foo');\n\n const value = await struct.deserialize(stream);\n value.foo; // number\n\n struct.serialize({ }) // error: 'foo' is required\n struct.serialize({ foo: 'bar' }) // error: 'foo' must be a number\n struct.serialize({ foo: 42 }) // ok\n ```\n\n2. Set fields' type (can be used with [`placeholder` method](#placeholder))\n\n ```ts\n enum MyEnum {\n a,\n b,\n }\n\n const struct = new Struct()\n .int32('foo', placeholder<MyEnum>())\n .int32('bar', MyEnum.a as const);\n\n const value = await struct.deserialize(stream);\n value.foo; // MyEnum\n value.bar; // MyEnum.a\n\n struct.serialize({ foo: 42, bar: MyEnum.a }); // error: 'foo' must be of type `MyEnum`\n struct.serialize({ foo: MyEnum.a, bar: MyEnum.b }); // error: 'bar' must be of type `MyEnum.a`\n struct.serialize({ foo: MyEnum.a, bar: MyEnum.b }); // ok\n ```\n\n#### `int64`/`uint64`\n\n```ts\nint64<\n TName extends string | number | symbol,\n TTypeScriptType = bigint\n>(\n name: TName,\n _typescriptType?: TTypeScriptType\n): Struct<\n TFields & Record<TName, TTypeScriptType>,\n TOmitInitKey,\n TExtra,\n TPostDeserialized\n>;\n```\n\nAppends an `int64`/`uint64` field to the `Struct`. The usage is same as `uint32`/`uint32`.\n\nRequires native support for `BigInt`. Check [compatibility table](#compatibility) for more information.\n\n#### `uint8Array`/`string`\n\n```ts\nuint8Array<\n TName extends string | number | symbol,\n TTypeScriptType = ArrayBuffer\n>(\n name: TName,\n options: FixedLengthBufferLikeFieldOptions,\n _typescriptType?: TTypeScriptType,\n): Struct<\n TFields & Record<TName, TTypeScriptType>,\n TOmitInitKey,\n TExtra,\n TPostDeserialized\n>;\n\nuint8Array<\n TName extends string | number | symbol,\n TLengthField extends LengthField<TFields>,\n TOptions extends VariableLengthBufferLikeFieldOptions<TFields, TLengthField>,\n TTypeScriptType = ArrayBuffer,\n>(\n name: TName,\n options: TOptions,\n _typescriptType?: TTypeScriptType,\n): Struct<\n TFields & Record<TName, TTypeScriptType>,\n TOmitInitKey | TLengthField,\n TExtra,\n TPostDeserialized\n>;\n```\n\nAppends an `uint8Array`/`string` field to the `Struct`.\n\nThe `options` parameter defines its length, it can be in two formats:\n\n* `{ length: number }`: Presence of the `length` option indicates that it's a fixed length array.\n* `{ lengthField: string; lengthFieldRadix?: number }`: Presence of the `lengthField` option indicates it's a variable length array. The `lengthField` options must refers to a `number` or `string` (can't be `bigint`) typed field that's already defined in this `Struct`. If the length field is a `string`, the optional `lengthFieldRadix` option (defaults to `10`) defines the radix when converting the string to a number. When deserializing, it will use that field's value as its length. When serializing, it will write its length to that field.\n\n#### `fields`\n\n```ts\nfields<\n TOther extends Struct<any, any, any, any>\n>(\n other: TOther\n): Struct<\n TFields & TOther['fieldsType'],\n TOmitInitKey | TOther['omitInitType'],\n TExtra & TOther['extraType'],\n TPostDeserialized\n>;\n```\n\nMerges (flats) another `Struct`'s fields and extra fields into the current one.\n\n**Examples**\n\n1. Extending another `Struct`\n\n ```ts\n const MyStructV1 =\n new Struct()\n .int32('field1');\n\n const MyStructV2 =\n new Struct()\n .fields(MyStructV1)\n .int32('field2');\n\n const structV2 = await MyStructV2.deserialize(stream);\n structV2.field1; // number\n structV2.field2; // number\n // Fields are flatten\n ```\n\n2. Also possible in any order\n\n ```ts\n const MyStructV1 =\n new Struct()\n .int32('field1');\n\n const MyStructV2 =\n new Struct()\n .int32('field2')\n .fields(MyStructV1);\n\n const structV2 = await MyStructV2.deserialize(stream);\n structV2.field1; // number\n structV2.field2; // number\n // Same result as above, but serialize/deserialize order is reversed\n ```\n\n#### `extra`\n\n```ts\nextra<\n T extends Record<\n Exclude<\n keyof T,\n Exclude<\n keyof T,\n keyof TFields\n >\n >,\n never\n >\n>(\n value: T & ThisType<Overwrite<Overwrite<TExtra, T>, TFields>>\n): Struct<\n TFields,\n TInit,\n Overwrite<TExtra, T>,\n TPostDeserialized\n>;\n```\n\nAdds extra fields into the `Struct`. Extra fields will be defined on prototype of each Struct values, so they don't affect serialize and deserialize process, and deserialized fields will overwrite extra fields.\n\nMultiple calls merge all extra fields together.\n\n**Generic Parameters**\n\n1. `T`: Type of the extra fields. The scary looking generic constraint is used to forbid overwriting any already existed fields.\n\n**Parameters**\n\n1. `value`: An object containing anything you want to add to Struct values. Accessors and methods are also allowed.\n\n**Examples**\n\n1. Add an extra field\n\n ```ts\n const struct = new Struct()\n .int32('foo')\n .extra({\n bar: 'hello',\n });\n\n const value = await struct.deserialize(stream);\n value.foo; // number\n value.bar; // 'hello'\n\n struct.serialize({ foo: 42 }); // ok\n struct.serialize({ foo: 42, bar: 'hello' }); // error: 'bar' is redundant\n ```\n\n2. Add getters and methods. `this` in functions refers to the result object.\n\n ```ts\n const struct = new Struct()\n .int32('foo')\n .extra({\n get bar() {\n // `this` is the result Struct value\n return this.foo + 1;\n },\n logBar() {\n // `this` also contains other extra fields\n console.log(this.bar);\n },\n });\n\n const value = await struct.deserialize(stream);\n value.foo; // number\n value.bar; // number\n value.logBar();\n ```\n\n#### `postDeserialize`\n\n```ts\npostDeserialize(): Struct<TFields, TOmitInitKey, TExtra, undefined>;\n```\n\nRemove any registered post-deserialization callback.\n\n```ts\npostDeserialize(\n callback: (this: TFields, object: TFields) => never\n): Struct<TFields, TOmitInitKey, TExtra, never>;\npostDeserialize(\n callback: (this: TFields, object: TFields) => void\n): Struct<TFields, TOmitInitKey, TExtra, undefined>;\n```\n\nRegisters (or replaces) a custom callback to be run after deserialized.\n\n`this` in `callback`, along with the first parameter `object` will both be the deserialized Struct value.\n\nA callback returning `never` (always throws errors) will change the return type of `deserialize` to `never`.\n\nA callback returning `void` means it modify the result object in-place (or doesn't modify it at all), so `deserialize` will still return the result object.\n\n```ts\npostDeserialize<TPostSerialize>(\n callback: (this: TFields, object: TFields) => TPostSerialize\n): Struct<TFields, TOmitInitKey, TExtra, TPostSerialize>;\n```\n\nRegisters (or replaces) a custom callback to be run after deserialized.\n\nA callback returning anything other than `undefined` will cause `deserialize` to return that value instead.\n\n**Generic Parameters**\n\n1. `TPostSerialize`: Type of the new result.\n\n**Parameters**\n\n1. `callback`: An function contains the custom logic to be run, optionally returns a new result. Or `undefined`, to remove any previously set `postDeserialize` callback.\n\n**Examples**\n\n1. Handle an \"error\" packet\n\n ```ts\n // Say your protocol have an error packet,\n // You want to throw a JavaScript Error when received such a packet,\n // But you don't want to modify all receiving path\n\n const struct = new Struct()\n .int32('messageLength')\n .string('message', { lengthField: 'messageLength' })\n .postDeserialize(value => {\n throw new Error(value.message);\n });\n ```\n\n2. Do anything you want\n\n ```ts\n // I think this one doesn't need any code example\n ```\n\n3. Replace result object\n\n ```ts\n const struct1 = new Struct()\n .int32('foo')\n .postDeserialize(value => {\n return {\n bar: value.foo,\n };\n });\n\n const value = await struct.deserialize(stream);\n value.foo // error: not exist\n value.bar; // number\n ```\n\n#### `deserialize`\n\n```ts\ninterface StructDeserializeStream {\n /**\n * Read data from the underlying data source.\n *\n * The stream must return exactly `length` bytes or data. If that's not possible\n * (due to end of file or other error condition), it must throw an error.\n */\n read(length: number): Uint8Array;\n}\n\ninterface StructAsyncDeserializeStream {\n /**\n * Read data from the underlying data source.\n *\n * The stream must return exactly `length` bytes or data. If that's not possible\n * (due to end of file or other error condition), it must throw an error.\n */\n read(length: number): Promise<Uint8Array>;\n}\n\ndeserialize(\n stream: StructDeserializeStream,\n): TPostDeserialized extends undefined\n ? Overwrite<TExtra, TValue>\n : TPostDeserialized\n>;\ndeserialize(\n stream: StructAsyncDeserializeStream,\n): Promise<\n TPostDeserialized extends undefined\n ? Overwrite<TExtra, TValue>\n : TPostDeserialized\n >\n>;\n```\n\nDeserialize a struct value from `stream`.\n\nIt will be synchronous (returns a value) or asynchronous (returns a `Promise`) depending on the type of `stream`.\n\nAs the signature shows, if the `postDeserialize` callback returns any value, `deserialize` will return that value instead.\n\nThe `read` method of `stream`, when being called, should returns exactly `length` bytes of data (or throw an `Error` if it can't).\n\n#### `serialize`\n\n```ts\nserialize(init: Evaluate<Omit<TFields, TOmitInitKey>>): Uint8Array;\nserialize(init: Evaluate<Omit<TFields, TOmitInitKey>>, output: Uint8Array): number;\n```\n\nSerialize a struct value into an `Uint8Array`.\n\nIf an `output` is given, it will serialize the struct into it, and returns the number of bytes written.\n\n## Custom field type\n\nIt's also possible to create your own field types.\n\n### `Struct#field`\n\n```ts\nfield<\n TName extends string | number | symbol,\n TDefinition extends StructFieldDefinition<any, any, any>\n>(\n name: TName,\n definition: TDefinition\n): Struct<\n TFields & Record<TName, TDefinition['TValue']>,\n TOmitInitKey | TDefinition['TOmitInitKey'],\n TExtra,\n TPostDeserialized\n>;\n```\n\nAppends a `StructFieldDefinition` to the `Struct`.\n\nAll built-in field type methods are actually aliases to it. For example, calling\n\n```ts\nstruct.int8('foo')\n```\n\nis same as\n\n```ts\nstruct.field(\n 'foo',\n new NumberFieldDefinition(\n NumberFieldType.Int8\n )\n)\n```\n\n### Relationship between types\n\n* `StructFieldValue`: Contains value of a field, with optional metadata and accessor methods.\n* `StructFieldDefinition`: Definition of a field, can deserialize `StructFieldValue`s from a stream or create them from exist values.\n* `StructValue`: A map between field names and `StructFieldValue`s.\n* `Struct`: Definiton of a struct, a map between field names and `StructFieldDefintion`s. May contain extra metadata.\n* Result of `Struct#deserialize()`: A map between field names and results of `StructFieldValue#get()`.\n\n### `StructFieldDefinition`\n\n```ts\nabstract class StructFieldDefinition<\n TOptions = void,\n TValue = unknown,\n TOmitInitKey extends PropertyKey = never,\n> {\n public readonly options: TOptions;\n\n public constructor(options: TOptions);\n}\n```\n\nA field definition defines how to deserialize a field.\n\nIt's an `abstract` class, means it can't be constructed (`new`ed) directly. It's only used as a base class for other field types.\n\n#### `TValue`/`TOmitInitKey`\n\nThese two fields provide type information to TypeScript compiler. Their values will always be `undefined`, but having correct types is enough. You don't need to touch them.\n\n#### `getSize`\n\n```ts\nabstract getSize(): number;\n```\n\nDerived classes must implement this method to return size (or minimal size if it's dynamic) of this field.\n\nActual size should be returned from `StructFieldValue#getSize`\n\n#### `create`\n\n```ts\nabstract create(\n options: Readonly<StructOptions>,\n struct: StructValue,\n value: TValue,\n): StructFieldValue<this>;\n```\n\nDerived classes must implement this method to create its own field value instance for the current definition.\n\n`Struct#serialize` will call this method, then call `StructFieldValue#serialize` to serialize one field value.\n\n#### `deserialize`\n\n```ts\nabstract deserialize(\n options: Readonly<StructOptions>,\n stream: StructDeserializeStream,\n struct: StructValue,\n): StructFieldValue<this>;\nabstract deserialize(\n options: Readonly<StructOptions>,\n stream: StructAsyncDeserializeStream,\n struct: StructValue,\n): Promise<StructFieldValue<this>>;\n```\n\nDerived classes must implement this method to define how to deserialize a value from `stream`.\n\nIt must be synchronous (returns a value) or asynchronous (returns a `Promise`) depending on the type of `stream`.\n\nUsually implementations should be:\n\n1. Read required bytes from `stream`\n2. Parse it to your type\n3. Pass the value into your own `create` method\n\nSometimes, extra metadata is present when deserializing, but need to be calculated when serializing, for example a UTF-8 encoded string may have different length between itself (character count) and serialized form (byte length). So `deserialize` can save those metadata on the `StructFieldValue` instance for later use.\n\n### `StructFieldValue`\n\n```ts\nabstract class StructFieldValue<\n TDefinition extends StructFieldDefinition<any, any, any>\n>\n```\n\nA field value defines how to serialize a field.\n\n#### `getSize`\n\n```ts\ngetSize(): number;\n```\n\nGets size of this field. By default, it returns its `definition`'s size.\n\nIf this field's size can change based on some criteria, one must override `getSize` to return its actual size.\n\n#### `get`/`set`\n\n```ts\nget(): TDefinition['TValue'];\nset(value: TDefinition['TValue']): void;\n```\n\nDefines how to get or set this field's value. By default, it reads/writes its `value` field.\n\nIf one needs to manipulate other states when getting/setting values, they can override these methods.\n\n#### `serialize`\n\n```ts\nabstract serialize(\n dataView: DataView,\n offset: number\n): void;\n```\n\nDerived classes must implement this method to serialize current value into `dataView`, from `offset`. It must not write more bytes than what its `getSize` returned.\n"
}
}
import type { ValueOrPromise } from "../utils.js";
// TODO: allow over reading (returning a `Uint8Array`, an `offset` and a `length`) to avoid copying
export interface StructDeserializeStream {

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

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

import { StructAsyncDeserializeStream, StructDeserializeStream, StructFieldDefinition, StructFieldValue, StructOptions, STRUCT_VALUE_SYMBOL } from './basic/index.js';
import { StructDefaultOptions, StructValue } from './basic/index.js';
import { StructAsyncDeserializeStream, StructDefaultOptions, StructDeserializeStream, StructFieldDefinition, StructFieldValue, StructOptions, StructValue, STRUCT_VALUE_SYMBOL } from './basic/index.js';
import { SyncPromise } from "./sync-promise.js";

@@ -569,3 +568,3 @@ import { BigIntFieldDefinition, BigIntFieldType, BufferFieldSubType, FixedLengthBufferLikeFieldDefinition, NumberFieldDefinition, NumberFieldType, StringBufferFieldSubType, Uint8ArrayBufferFieldSubType, VariableLengthBufferLikeFieldDefinition, type FixedLengthBufferLikeFieldOptions, type LengthField, type VariableLengthBufferLikeFieldOptions } from './types/index.js';

// Otherwise it only inspects/mutates the object in place.
if (override) {
if (override !== undefined) {
return override;

@@ -572,0 +571,0 @@ }

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