@zzzeros0/nbsp 0.1.1 → 0.3.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/README.md CHANGED
@@ -27,22 +27,38 @@ interface AckPacket {
27
27
  } // domain AckPacket
28
28
 
29
29
  interface Packet {
30
- header: number;
30
+ header: byte;
31
31
  id: string;
32
32
  method: string;
33
33
  content: string;
34
34
  } // domain Packet
35
35
 
36
- const AckPacketStructure = structure<AckPacket>(
36
+ // Transformers
37
+ // Transforms string <-> number[]
38
+ const stringTransform = {
39
+ input: [(data: string) => toBytes(data)],
40
+ output: [(data: bytes) => toString(data)],
41
+ };
42
+
43
+ // Transforms hex string <-> hex number[]
44
+ const hexStringTransform = {
45
+ input: [(data: string) => toBytes(data, true)],
46
+ output: [(data: bytes) => toString(data, true)],
47
+ };
48
+
49
+ const AckPacketStruct = struct<AckPacket, Transformers<AckPacket>>(
37
50
  {
38
51
  id: charDataType(6),
39
52
  },
40
53
  {
41
54
  packed: true,
55
+ transform: {
56
+ id: hexStringTransform,
57
+ },
42
58
  },
43
- );
59
+ ); // AckPacketStruct Constructor (class)
44
60
 
45
- const PacketStructure = structure<Packet>(
61
+ const PacketStruct = struct<Packet, Transformers<Packet>>(
46
62
  {
47
63
  header: DataType.UINT32LE,
48
64
  id: charDataType(6),
@@ -51,170 +67,142 @@ const PacketStructure = structure<Packet>(
51
67
  },
52
68
  {
53
69
  packed: true,
70
+ transform: {
71
+ id: hexStringTransform,
72
+ method: stringTransform,
73
+ content: stringTransform,
74
+ },
54
75
  },
55
- );
76
+ ); // PacketStruct Constructor (class)
56
77
 
57
- console.log(AckPacketStructure.size); // 6 (Unpacked: 10)
58
- console.log(PacketStructure.size); // 78 (Unpacked: 128)
78
+ console.log(AckPacketStruct.size); // 6 (Unpacked: 10)
79
+ console.log(PacketStruct.size); // 78 (Unpacked: 128)
59
80
 
60
81
  mqttClient.on("message", (topic, msg) => {
61
- const packet = PacketStructure.from(msg);
62
-
63
- processMessage(
64
- topic,
65
- toString(packet.id),
66
- toString(packet.method),
67
- toString(packet.content),
68
- ).then(() => {
69
- const ackMessage = new AckPacketStructure({
70
- id: packet.id,
71
- });
82
+ const packet = PacketStruct.from(msg);
83
+
84
+ processMessage(topic, packet.id, packet.method, packet.content).then(() => {
85
+ const ackMessage = AckPacketStruct.from(msg, sizeof(DataType.UINT32LE)); // Offset the 'header' property
72
86
 
73
87
  mqttClient.publish("ack", ackMessage.data());
74
88
  });
75
89
  });
76
90
  ```
77
91
 
78
- ## Usage
92
+ ### Struct Constructor methods
93
+
94
+ | Method | Description | Arguments | Returned type |
95
+ | ------ | ----------------------------------------------------------------- | -------------------------------------------- | ------------- |
96
+ | from | Creates a new instance and copies the buffer content from target. | `(target: Buffer \| Struct, byte: byte = 0)` | `Struct<T>` |
97
+ | toJson | Creates a plain object, resolving with the data of the buffer. | `(target: Buffer, offset: byte = 0)` | T |
98
+
99
+ ### Struct methods
100
+
101
+ | Method | Description | Arguments | Returned type |
102
+ | ------ | -------------------------------------- | ---------------------------------------------- | ------------- |
103
+ | data | Returns the internal buffer (no copy). | | `Buffer` |
104
+ | reset | Zero the internal buffer content. | | `void` |
105
+ | toJson | Returns a plain object. | | `T` |
106
+ | copy | Copies the buffer content from target. | `(target: Buffer \| Struct, offset: byte = 0)` | `void` |
79
107
 
80
- 1. Create a domain interface.
108
+ ### Struct Options
81
109
 
82
- - This will represent your data.
110
+ Options argument for the `struct` function.
111
+
112
+ | Property | Description | Type | Default |
113
+ | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------- | ------- |
114
+ | packed | When false, fields of the `struct` are aligned or padded. This is really important especially for binary communications, improving performance and usage. | `boolean` | `false` |
115
+ | transform | An object that contains keys from the domain object. Transforms the data obtained/retrieved from the buffer data. | `Transformers<T>` | `{}` |
116
+
117
+ ## Usage
118
+
119
+ 1. Create a domain interface. This will represent your data.
83
120
 
84
121
  ```ts
85
122
  interface Person {
86
- age: number;
123
+ age: byte;
87
124
  name: string;
88
125
  } // domain Person
89
126
  ```
90
127
 
91
- 2. Create a Structure for your domain interface. Calling `structure` will return a new class; it is not intended to be extended.
128
+ 2. Create a Struct for your domain interface. Calling `struct` will return a new class; it is not intended to be extended.
92
129
 
93
130
  ```ts
94
- const PersonStructure = structure<Person>({
131
+ const PersonStruct = struct<Person>({
95
132
  age: DataType.UINT8,
96
133
  name: charDataType(4), // strings are arrays of UINT8. charDataType(n) is equivalent to [DataType.UINT8, n]
97
134
  });
98
135
  ```
99
136
 
100
- 3. Now, you can instantiate the structure by using `new` or the `StructureConstructor`'s static method `from`. Instance exposes getters and setters to update and retrieve data directly from the fields of the structure in the buffer as well as some other methods to manage it:
137
+ 3. Now, you can instantiate the struct by using `new` or the `StructConstructor`'s static method `from`. Instance exposes getters and setters to update and retrieve data directly from the fields of the struct in the buffer as well as some other methods to manage it:
101
138
 
102
139
  ```ts
103
- const person1 = new PersonStructure({
140
+ const person1 = new PersonStruct({
104
141
  age: 24,
105
- name: toUint8Array("Dave"), // Transform the string to UTF-8 UINT8 array
142
+ name: toBytes("Dave"), // Transform the string to UTF-8 UINT8 array
106
143
  });
107
144
  console.log("Name: %s, age: %d", toString(person1.name), person1.age); // Name: Dave, age: 24
108
145
 
109
- const person2 = PersonStructure.from(Buffer.from("526f73655a000000", "hex"));
110
-
111
- console.log("Name: %s, age: %d", toString(person2.name), person2.age); // Name: Rose, age: 90
146
+ const person2 = PersonStruct.from(Buffer.from("63000000526f7365", "hex"));
112
147
 
113
- console.log(person2.data()); // <Buffer 52 6f 73 65 5a 00 00 00>
114
- ```
148
+ console.log("Name: %s, age: %d", toString(person2.name), person2.age); // Name: Rose, age: 99
115
149
 
116
- 4. You can create a plain object using `toJson` instance or static methods:
150
+ console.log(person2.data()); // <Buffer 63 00 00 00 52 6f 73 65>
117
151
 
118
- ```ts
119
- console.log(person2.toJson()); // { name: [ 82, 111, 115, 101 ], age: 90 }
152
+ console.log(person2.toJson()); // { age: 99, name: [ 82, 111, 115, 101 ] }
120
153
 
121
- const person3 = PersonStructure.toJson(Buffer.from("4a616b655a000000", "hex"));
154
+ const person3 = PersonStruct.toJson(Buffer.from("5a0000004a616b65", "hex"));
122
155
 
123
156
  console.log("Name: %s, age: %d", toString(person3.name), person3.age); // Name: Jake, age: 90
124
157
  ```
125
158
 
126
- ### Packing
127
-
128
- When creating a `Structure`, you can provide the argument `packed` (default is `false`):
159
+ Transformers help to transform data.
160
+ When a property has transformers, its exposed TypeScript type becomes the transformed type instead of the raw BindedType<T>.
161
+ You can have multiple transforms in input/output; each one will receive the last transformed value.
129
162
 
130
163
  ```ts
131
- const PacketStructure = structure<Packet>(
164
+ const PersonStruct = struct<Person, { name: PropertyTransform }>(
132
165
  {
133
- header: DataType.UINT32LE,
134
- id: charDataType(6),
135
- content: charDataType(64),
166
+ age: DataType.UINT8,
167
+ name: charDataType(4),
136
168
  },
137
169
  {
138
- packed: true,
170
+ transform: {
171
+ name: {
172
+ // Executed when data is written to the buffer
173
+ input: [(data: string) => toBytes(data)],
174
+ // Executed when data is retrieved from the buffer
175
+ output: [(data: bytes) => toString(data)],
176
+ },
177
+ },
139
178
  },
140
179
  );
141
- ```
142
-
143
- When `packed` is `true`, no padding or alignment will be applied to the fields. This is really important especially for binary communications, improving performance and usage.
144
-
145
- ```ts
146
- console.log(PersonStructure.size); // Unpacked: 8 bytes
147
- console.log(PersonStructure.size); // Packed: 5 bytes
148
- ```
149
-
150
- ### Strings
151
-
152
- NBSP does not store strings dynamically.
153
- Strings are represented as fixed-length arrays of `UINT8`. You can use `charDataType` as a shorthand:
154
-
155
- ```ts
156
- charDataType(6); // returns [DataType.UINT8, 6]
157
- ```
158
-
159
- This is intentional and ensures:
160
-
161
- - Deterministic payload size
162
- - Protocol compatibility
163
- - Zero dynamic allocation
164
-
165
- ### Working with hex
166
-
167
- You can serialize/retrieve hex data:
168
-
169
- ```ts
170
- interface User {
171
- id: string;
172
- role: number;
173
- } // domain Person
174
-
175
- const UserStructure = structure<User>({
176
- id: charDataType(4),
177
- role: DataType.UINT8,
178
- });
179
-
180
- const instance = new UserStructure({
181
- id: toUint8Array("1a2b4c6d", true), // Transform to hex array
182
- role: 2,
180
+ const person = new PersonStruct({
181
+ age: 24,
182
+ name: "Dave", // Input transformer
183
183
  });
184
- // HEX string length 8 -> HEX array length 4
185
-
186
- console.log(instance.name); // Prints [ 26, 43, 76, 109 ]
187
- console.log(toString(instance.name, true)); // "1a2b4c6d"
184
+ person.name = "Jack"; // Input transformer
185
+ console.log(person.name); // "Jack", output transformer
188
186
  ```
189
187
 
190
- ### Arrays
188
+ ### Arrays & Nesting
191
189
 
192
- `Arrays` are defined with a `type` and a fixed `length` of items:
190
+ `Array` types are defined with a `type` and a fixed `length` of items:
193
191
 
194
192
  ```ts
195
- interface Person {
196
- name: string;
197
- } // domain Person
198
-
199
- const PersonStructure = structure<Person>({
200
- name: charDataType(4), // [ DataType.UINT8, 4 ]
201
- });
202
-
203
- const person = new PersonStructure({
204
- name: toUint8Array("Jake"),
193
+ const PersonStruct = struct<Person>({
194
+ name: [DataType.UINT8, 4], // or charDataType(4)
205
195
  });
206
196
  ```
207
197
 
208
- This specifies that there will be `4` items in this field, each of them of type `DataType.UINT8` (strings will always be stored as arrays of `DataType.UINT8`).
209
-
210
- ### Nested Structures
198
+ > Strings are represented as a fixed array of `UINT8` if no transformer was applied for that property. Use the shorthand `charDataType`.
211
199
 
212
- You can nest `Structures`:
200
+ You can nest `Structs`:
213
201
 
214
202
  ```ts
215
203
  interface DeviceConfig {
216
- mode: number;
217
- factor: number;
204
+ mode: byte;
205
+ factor: byte;
218
206
  } // domain DeviceConfig
219
207
 
220
208
  interface Device {
@@ -222,54 +210,54 @@ interface Device {
222
210
  config: DeviceConfig; // Provide the domain type
223
211
  } // domain Device
224
212
 
225
- const DeviceConfigStructure = structure<DeviceConfig>({
213
+ const DeviceConfigStruct = struct<DeviceConfig>({
226
214
  mode: DataType.UINT8,
227
215
  factor: DataType.UINT8,
228
216
  });
229
217
 
230
- const DeviceStructure = structure<Device>({
218
+ const DeviceStruct = struct<Device>({
231
219
  id: charDataType(6),
232
- config: DeviceConfigStructure, // Provide the structure as type
220
+ config: DeviceConfigStruct, // Provide the struct as type
233
221
  });
234
222
 
235
- const instance = new DeviceStructure({
223
+ const instance = new DeviceStruct({
236
224
  id: Array.from(randomBytes(6)),
237
225
  config: {
238
226
  // Create a plain object
239
- // DO NOT use DeviceConfigStructure constructor
227
+ // DO NOT use DeviceConfigStruct constructor
240
228
  // it will cause unnecessary allocations
241
229
  mode: 4,
242
230
  factor: 8,
243
231
  },
244
232
  });
245
233
 
246
- console.log(instance.config.factor); // Prints '8'
234
+ console.log(instance.config.factor); // 8
247
235
  ```
248
236
 
249
- You can also store `Structures` or `Arrays` inside of `Arrays`:
237
+ You can also store `Structs` or `Arrays` inside of `Arrays`:
250
238
 
251
239
  ```ts
252
240
  interface Group {
253
241
  people: Person[];
254
242
  } // domain Group
255
243
 
256
- const GroupStructure = structure<Group>({
257
- people: [PersonStructure, 100],
244
+ const GroupStruct = struct<Group>({
245
+ people: [PersonStruct, 100],
258
246
  });
259
247
 
260
- const groupInstance = new GroupStructure({
248
+ const groupInstance = new GroupStruct({
261
249
  people: [
262
250
  // Create a plain object
263
- // DO NOT use PersonStructure constructor
251
+ // DO NOT use PersonStruct constructor
264
252
  // it will cause unnecessary allocations
265
253
  {
266
- name: toUint8Array("Jack"),
254
+ name: "Jack",
267
255
  },
268
256
  {
269
- name: toUint8Array("Rose"),
257
+ name: "Rose",
270
258
  },
271
259
  {
272
- name: toUint8Array("Dave"),
260
+ name: "Dave",
273
261
  },
274
262
  ...
275
263
  ],
@@ -280,43 +268,11 @@ console.log(groupInstance.people); // Array<100> [ { name: [Getter/Setter] }, ..
280
268
 
281
269
  > **Important**
282
270
  >
283
- > Structures must be instantiated with plain objects when are nested, `do not` use the `Structure's constructor`; doing so will make unnecessary allocations.
284
-
285
- ### Buffer and copying
286
-
287
- You can access the `buffer` of the `instance` with `data` method:
288
-
289
- ```ts
290
- instance.data(); // Returns the internal Buffer (no copy)
291
- ```
292
-
293
- You can reset the `buffer` of the `instance` with `reset` method:
294
-
295
- ```ts
296
- instance.reset(); // Resets the internal Buffer (0)
297
- ```
298
-
299
- You can `copy` the data from other `instance` or `buffer`:
300
-
301
- ```ts
302
- instance.copy(instanceOrBuffer);
303
- ```
304
-
305
- You can create a `new instance` of the `Structure`, copying the data `from` other `buffer` or `instance`:
306
-
307
- ```ts
308
- const copiedInstance = PersonStructure.from(instanceOrBuffer);
309
- ```
310
-
311
- > **Important**
312
- >
313
- > Buffers must be the same size when copying.
314
- >
315
- > Each instance has its own buffer.
271
+ > Structs must be instantiated with plain objects when are nested, `do not` use the `Struct's constructor`; doing so will make unnecessary allocations.
316
272
 
317
273
  ### JSON
318
274
 
319
- Instances can be converted to plain JavaScript object with all the resolved properties and nested attributes of your structure using `toJson` method:
275
+ Instances can be converted to plain JavaScript object with all the resolved properties and nested attributes of your struct using `toJson` method:
320
276
 
321
277
  ```ts
322
278
  personInstance.toJson(); // { name: [ 68, 97, 118, 101 ], age: 24 }
@@ -325,16 +281,24 @@ personInstance.toJson(); // { name: [ 68, 97, 118, 101 ], age: 24 }
325
281
  You can serialize directly to a plain JavaScript object from a buffer by using the static method `toJson`:
326
282
 
327
283
  ```ts
328
- PersonStructure.toJson(Buffer.from("4a616b655a000000", "hex")); // { name: [ 68, 97, 118, 101 ], age: 24 }
284
+ PersonStruct.toJson(Buffer.from("4a616b655a000000", "hex")); // { name: [ 68, 97, 118, 101 ], age: 24 }
329
285
  ```
330
286
 
331
287
  > **Important**
332
288
  >
333
- > Strings are still represented as numeric arrays in JSON output.
289
+ > Transformers will also run when serializing JSON.
290
+
291
+ > Prefer the static `toJson` method when working with raw buffers; there's no point on doing this:
292
+ >
293
+ > ```ts
294
+ > PersonStruct.toJson(personInstance.data());
295
+ > // Instead
296
+ > personInstance.toJson();
297
+ > ```
334
298
 
335
299
  ### Endianness
336
300
 
337
- `DataType` difference between `LE` and `BE` types:
301
+ Data types defined in the enum `DataType` difference between `LE` and `BE` types:
338
302
 
339
303
  ```ts
340
304
  structure({
@@ -343,6 +307,16 @@ structure({
343
307
  });
344
308
  ```
345
309
 
310
+ > **Note**
311
+ >
312
+ > You can get the `size` of data types with `sizeof`:
313
+ >
314
+ > ```ts
315
+ > console.log(sizeof(DataType.INT16LE)); // 2
316
+ > console.log(sizeof(charDataType(6))); // 6
317
+ > console.log(sizeof(Structure)); // Or Structure.size
318
+ > ```
319
+
346
320
  ### Floating point (FLOAT32) precision
347
321
 
348
322
  NBSP uses IEEE-754 floating point representations for FLOAT32 and FLOAT64, exactly like C, C++, Rust, Java, etc.
@@ -352,7 +326,7 @@ This means that some decimal values cannot be represented exactly in binary.
352
326
 
353
327
  FLOAT32 is a 32-bit single-precision IEEE-754 float.
354
328
 
355
- The decimal number 0.4 cannot be represented exactly using a finite binary fraction, so the closest representable value is stored instead.
329
+ Some decimal numbers, like 0.4, cannot be represented exactly using a finite binary fraction, so the closest representable value is stored instead.
356
330
 
357
331
  Example:
358
332
 
@@ -381,7 +355,9 @@ NBSP intentionally exposes the real binary value, without rounding or post-proce
381
355
 
382
356
  If you need to compare floating point values, never use strict equality:
383
357
 
384
- a === b // ❌ unsafe for floats
358
+ ```ts
359
+ a === b; // ❌ unsafe for floats
360
+ ```
385
361
 
386
362
  Instead, compare with a tolerance:
387
363
 
package/dist/index.d.ts CHANGED
@@ -1,4 +1,5 @@
1
- export { toString, toUint8Array } from "./memory.js";
2
- export { structure, type Structure, type StructureConstructor, type StructureFields, type StructureMethods, } from "./structure.js";
3
- export { charDataType, DataType, type BindedType, type DomainObject, type ArrayDataType, type BigIntDataType, type Type, type NumericArrayDataType, type StructureArrayDataType, type StructureDefinitionDataType, type DataVale, } from "./type.js";
1
+ export { toString, toBytes, sizeof } from "./memory.js";
2
+ export { struct, type Struct, type StructConstructor, type StructFields, type StructMethods, type StructReturn, } from "./structure.js";
3
+ export { charDataType, DataType, type ArrayDataType, type BigIntDataType, type BindedType, type DataValue, type DomainObject, type NumericArrayDataType, type StructArrayDataType, type StructDefinitionDataType, type Type, type byte, type bytes, } from "./type.js";
4
+ export { type Transformer, type Transformers, type ApplyTransformers, type PropertyTransformer, } from "./transformer.js";
4
5
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AACrD,OAAO,EACL,SAAS,EACT,KAAK,SAAS,EACd,KAAK,oBAAoB,EACzB,KAAK,eAAe,EACpB,KAAK,gBAAgB,GACtB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EACL,YAAY,EACZ,QAAQ,EACR,KAAK,UAAU,EACf,KAAK,YAAY,EACjB,KAAK,aAAa,EAClB,KAAK,cAAc,EACnB,KAAK,IAAI,EACT,KAAK,oBAAoB,EACzB,KAAK,sBAAsB,EAC3B,KAAK,2BAA2B,EAChC,KAAK,QAAQ,GACd,MAAM,WAAW,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AACxD,OAAO,EACL,MAAM,EACN,KAAK,MAAM,EACX,KAAK,iBAAiB,EACtB,KAAK,YAAY,EACjB,KAAK,aAAa,EAClB,KAAK,YAAY,GAClB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EACL,YAAY,EACZ,QAAQ,EACR,KAAK,aAAa,EAClB,KAAK,cAAc,EACnB,KAAK,UAAU,EACf,KAAK,SAAS,EACd,KAAK,YAAY,EACjB,KAAK,oBAAoB,EACzB,KAAK,mBAAmB,EACxB,KAAK,wBAAwB,EAC7B,KAAK,IAAI,EACT,KAAK,IAAI,EACT,KAAK,KAAK,GACX,MAAM,WAAW,CAAC;AACnB,OAAO,EACL,KAAK,WAAW,EAChB,KAAK,YAAY,EACjB,KAAK,iBAAiB,EACtB,KAAK,mBAAmB,GACzB,MAAM,kBAAkB,CAAC"}
package/dist/index.js CHANGED
@@ -1,4 +1,5 @@
1
- export { toString, toUint8Array } from "./memory.js";
2
- export { structure, } from "./structure.js";
1
+ export { toString, toBytes, sizeof } from "./memory.js";
2
+ export { struct, } from "./structure.js";
3
3
  export { charDataType, DataType, } from "./type.js";
4
+ export {} from "./transformer.js";
4
5
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AACrD,OAAO,EACL,SAAS,GAKV,MAAM,gBAAgB,CAAC;AACxB,OAAO,EACL,YAAY,EACZ,QAAQ,GAUT,MAAM,WAAW,CAAC"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AACxD,OAAO,EACL,MAAM,GAMP,MAAM,gBAAgB,CAAC;AACxB,OAAO,EACL,YAAY,EACZ,QAAQ,GAYT,MAAM,WAAW,CAAC;AACnB,OAAO,EAKN,MAAM,kBAAkB,CAAC"}
package/dist/memory.d.ts CHANGED
@@ -1,7 +1,8 @@
1
- import { type AlignedData } from "./type.js";
2
- export declare function alloc(s: number): Buffer<ArrayBuffer>;
3
- export declare function read(data: AlignedData, buffer: Buffer, offset: number): number | bigint;
4
- export declare function write(data: AlignedData, buffer: Buffer, value: number, offset: number): void;
5
- export declare function toUint8Array(s: string, hex?: boolean): number[];
6
- export declare function toString(n: number[], hex?: boolean): string;
1
+ import { type AlignedData, type byte, type bytes, type Type } from "./type.js";
2
+ export declare function alloc(s: byte): Buffer<ArrayBuffer>;
3
+ export declare function read(data: AlignedData, buffer: Buffer, offset: byte): number | bigint;
4
+ export declare function write(data: AlignedData, buffer: Buffer, value: byte, offset: byte): void;
5
+ export declare function sizeof(type: Type): byte;
6
+ export declare function toBytes(s: string, hex?: boolean): bytes;
7
+ export declare function toString(n: bytes, hex?: boolean): string;
7
8
  //# sourceMappingURL=memory.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"memory.d.ts","sourceRoot":"","sources":["../src/memory.ts"],"names":[],"mappings":"AAAA,OAAO,EAAY,KAAK,WAAW,EAAE,MAAM,WAAW,CAAC;AA4BvD,wBAAgB,KAAK,CAAC,CAAC,EAAE,MAAM,uBAG9B;AAED,wBAAgB,IAAI,CAAC,IAAI,EAAE,WAAW,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,mBA2CrE;AAED,wBAAgB,KAAK,CACnB,IAAI,EAAE,WAAW,EACjB,MAAM,EAAE,MAAM,EACd,KAAK,EAAE,MAAM,EACb,MAAM,EAAE,MAAM,QA0Ff;AAyBD,wBAAgB,YAAY,CAAC,CAAC,EAAE,MAAM,EAAE,GAAG,GAAE,OAAe,GAAG,MAAM,EAAE,CAMtE;AACD,wBAAgB,QAAQ,CAAC,CAAC,EAAE,MAAM,EAAE,EAAE,GAAG,GAAE,OAAe,GAAG,MAAM,CAKlE"}
1
+ {"version":3,"file":"memory.d.ts","sourceRoot":"","sources":["../src/memory.ts"],"names":[],"mappings":"AACA,OAAO,EAEL,KAAK,WAAW,EAEhB,KAAK,IAAI,EACT,KAAK,KAAK,EACV,KAAK,IAAI,EACV,MAAM,WAAW,CAAC;AA8BnB,wBAAgB,KAAK,CAAC,CAAC,EAAE,IAAI,uBAE5B;AAED,wBAAgB,IAAI,CAAC,IAAI,EAAE,WAAW,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,mBAyCnE;AAED,wBAAgB,KAAK,CACnB,IAAI,EAAE,WAAW,EACjB,MAAM,EAAE,MAAM,EACd,KAAK,EAAE,IAAI,EACX,MAAM,EAAE,IAAI,GACX,IAAI,CAqFN;AAsCD,wBAAgB,MAAM,CAAC,IAAI,EAAE,IAAI,GAAG,IAAI,CAQvC;AAsBD,wBAAgB,OAAO,CAAC,CAAC,EAAE,MAAM,EAAE,GAAG,GAAE,OAAe,GAAG,KAAK,CAI9D;AACD,wBAAgB,QAAQ,CAAC,CAAC,EAAE,KAAK,EAAE,GAAG,GAAE,OAAe,GAAG,MAAM,CAK/D"}
package/dist/memory.js CHANGED
@@ -1,4 +1,5 @@
1
- import { DataType } from "./type.js";
1
+ import { DataType, } from "./type.js";
2
+ let encoder, decoder;
2
3
  function assertInteger(value, min, max, type) {
3
4
  if (!Number.isInteger(value)) {
4
5
  throw new Error(`${type}: value is not an integer`);
@@ -18,12 +19,9 @@ function assertBigIntRange(value, min, max, type) {
18
19
  }
19
20
  }
20
21
  export function alloc(s) {
21
- // console.log("Alloc", s);
22
22
  return Buffer.alloc(s);
23
23
  }
24
24
  export function read(data, buffer, offset) {
25
- // console.log("read", data, offset + data.offset);
26
- // if (typeof data.type === "number") {
27
25
  switch (data.type) {
28
26
  case DataType.INT8:
29
27
  return buffer.readInt8(offset + data.offset);
@@ -66,10 +64,6 @@ export function read(data, buffer, offset) {
66
64
  }
67
65
  }
68
66
  export function write(data, buffer, value, offset) {
69
- // console.log("Write", data.offset + offset, value);
70
- // if (typeof data.type === "number") {
71
- // if (Array.isArray(value) || typeof value !== "number")
72
- // throw new Error("Invalid value");
73
67
  switch (data.type) {
74
68
  case DataType.INT8:
75
69
  assertInteger(value, -128, 127, "INT8");
@@ -155,7 +149,49 @@ export function write(data, buffer, value, offset) {
155
149
  throw new Error("Invalid type");
156
150
  }
157
151
  }
158
- let encoder, decoder;
152
+ function getDataTypeSize(type) {
153
+ switch (type) {
154
+ case DataType.INT8:
155
+ case DataType.UINT8:
156
+ return 1;
157
+ case DataType.INT16LE:
158
+ case DataType.INT16BE:
159
+ case DataType.UINT16LE:
160
+ case DataType.UINT16BE:
161
+ return 2;
162
+ case DataType.INT32BE:
163
+ case DataType.INT32LE:
164
+ case DataType.UINT32LE:
165
+ case DataType.UINT32BE:
166
+ return 4;
167
+ case DataType.INT64LE:
168
+ case DataType.INT64BE:
169
+ case DataType.UINT64LE:
170
+ case DataType.UINT64BE:
171
+ return 8;
172
+ case DataType.FLOAT32LE:
173
+ case DataType.FLOAT32BE:
174
+ return 4;
175
+ case DataType.FLOAT64LE:
176
+ case DataType.FLOAT64BE:
177
+ return 8;
178
+ }
179
+ }
180
+ function getStructureDataSize(structure) {
181
+ return structure.size;
182
+ }
183
+ function getArrrayDataSize(type) {
184
+ return sizeof(type[0]) * type[1];
185
+ }
186
+ export function sizeof(type) {
187
+ return typeof type === "number"
188
+ ? getDataTypeSize(type)
189
+ : typeof type === "string"
190
+ ? 0
191
+ : Array.isArray(type)
192
+ ? getArrrayDataSize(type)
193
+ : getStructureDataSize(type);
194
+ }
159
195
  function hexToBytes(hex) {
160
196
  let bytes = [];
161
197
  for (let c = 0; c < hex.length; c += 2)
@@ -164,7 +200,7 @@ function hexToBytes(hex) {
164
200
  return bytes;
165
201
  }
166
202
  function bytesToHex(bytes) {
167
- let hex = [];
203
+ const hex = [];
168
204
  for (let i = 0; i < bytes.length; i++) {
169
205
  const byte = bytes[i];
170
206
  if (byte == undefined)
@@ -175,14 +211,12 @@ function bytesToHex(bytes) {
175
211
  }
176
212
  return hex.join("");
177
213
  }
178
- export function toUint8Array(s, hex = false) {
214
+ export function toBytes(s, hex = false) {
179
215
  if (hex)
180
216
  return hexToBytes(s);
181
217
  if (!encoder)
182
218
  encoder = new TextEncoder(); // UTF-8 por defecto
183
- const bytes = encoder.encode(s);
184
- // console.log("Raw", bytes);
185
- return Array.from(bytes);
219
+ return Array.from(encoder.encode(s));
186
220
  }
187
221
  export function toString(n, hex = false) {
188
222
  // console.log("String", n);