0
# Advanced Classes
1
2
Configurable class instances providing advanced MessagePack features like record structures, structured cloning, custom extensions, and performance optimizations.
3
4
## Capabilities
5
6
### Packr Class
7
8
Main packing class that extends Unpackr to provide both packing and unpacking capabilities with shared configuration.
9
10
```javascript { .api }
11
/**
12
* Advanced MessagePack encoder/decoder with configurable options
13
*/
14
class Packr extends Unpackr {
15
constructor(options?: Options);
16
17
// Buffer management properties
18
offset: number;
19
position: number;
20
21
// Packing methods
22
pack(value: any, encodeOptions?: number): Buffer;
23
encode(value: any, encodeOptions?: number): Buffer;
24
25
// Buffer management methods
26
useBuffer(buffer: Buffer | Uint8Array): void;
27
clearSharedData(): void;
28
}
29
```
30
31
**Usage Examples:**
32
33
```javascript
34
import { Packr } from "msgpackr";
35
36
// Basic usage with default options
37
const packr = new Packr();
38
const packed = packr.pack({ name: "Alice", age: 25 });
39
const unpacked = packr.unpack(packed);
40
41
// With record structures for optimal performance
42
const optimizedPackr = new Packr({
43
useRecords: true,
44
structures: []
45
});
46
47
// Reuse structures across multiple objects
48
const data = [
49
{ name: "Alice", age: 25, active: true },
50
{ name: "Bob", age: 30, active: false },
51
{ name: "Charlie", age: 35, active: true }
52
];
53
54
data.forEach(item => {
55
const packed = optimizedPackr.pack(item); // Reuses structure definitions
56
});
57
58
// Custom buffer management
59
const packr2 = new Packr();
60
const customBuffer = new Uint8Array(1024);
61
packr2.useBuffer(customBuffer);
62
const result = packr2.pack(someData);
63
```
64
65
### Unpackr Class
66
67
Main unpacking class providing configurable MessagePack decoding with advanced options.
68
69
```javascript { .api }
70
/**
71
* Advanced MessagePack decoder with configurable options
72
*/
73
class Unpackr {
74
constructor(options?: Options);
75
76
// Unpacking methods
77
unpack(messagePack: Buffer | Uint8Array, options?: UnpackOptions): any;
78
decode(messagePack: Buffer | Uint8Array, options?: UnpackOptions): any;
79
unpackMultiple(messagePack: Buffer | Uint8Array): any[];
80
unpackMultiple(
81
messagePack: Buffer | Uint8Array,
82
forEach: (value: any, start?: number, end?: number) => any
83
): void;
84
}
85
```
86
87
**Usage Examples:**
88
89
```javascript
90
import { Unpackr } from "msgpackr";
91
92
// With structured cloning support
93
const unpackr = new Unpackr({
94
structuredClone: true,
95
mapsAsObjects: true
96
});
97
98
// Handle cyclical references
99
const packedWithCycles = /* buffer with cyclical object */;
100
const restored = unpackr.unpack(packedWithCycles);
101
// Object identity and cycles are preserved
102
103
// With custom type handling
104
const typedUnpackr = new Unpackr({
105
moreTypes: true,
106
int64AsType: 'bigint',
107
useTimestamp32: true
108
});
109
110
const result = typedUnpackr.unpack(someTypedData);
111
```
112
113
### Encoder and Decoder Classes
114
115
Alias classes for Packr and Unpackr respectively, providing alternative naming conventions.
116
117
```javascript { .api }
118
/**
119
* Alias for Packr class
120
*/
121
class Encoder extends Packr {}
122
123
/**
124
* Alias for Unpackr class
125
*/
126
class Decoder extends Unpackr {}
127
```
128
129
## Configuration Options
130
131
### Options Interface
132
133
Comprehensive configuration interface for customizing MessagePack behavior.
134
135
```javascript { .api }
136
interface Options {
137
// Float handling
138
useFloat32?: FLOAT32_OPTIONS;
139
140
// Record structure optimization
141
useRecords?: boolean | ((value: any) => boolean);
142
structures?: {}[];
143
maxSharedStructures?: number;
144
maxOwnStructures?: number;
145
shouldShareStructure?: (keys: string[]) => boolean;
146
getStructures?(): {}[];
147
saveStructures?(structures: {}[]): boolean | void;
148
149
// Type handling
150
moreTypes?: boolean;
151
int64AsNumber?: boolean; // deprecated
152
int64AsType?: 'bigint' | 'number' | 'string';
153
largeBigIntToFloat?: boolean;
154
largeBigIntToString?: boolean;
155
useBigIntExtension?: boolean;
156
useTimestamp32?: boolean;
157
158
// Object mapping
159
mapsAsObjects?: boolean;
160
mapAsEmptyObject?: boolean;
161
setAsEmptyObject?: boolean;
162
variableMapSize?: boolean;
163
allowArraysInMapKeys?: boolean;
164
coercibleKeyAsNumber?: boolean;
165
166
// Advanced features
167
structuredClone?: boolean;
168
sequential?: boolean;
169
copyBuffers?: boolean;
170
bundleStrings?: boolean;
171
encodeUndefinedAsNil?: boolean;
172
173
// Custom handlers
174
writeFunction?: () => any;
175
onInvalidDate?: () => any;
176
}
177
```
178
179
**Configuration Examples:**
180
181
```javascript
182
import { Packr, FLOAT32_OPTIONS } from "msgpackr";
183
184
// Performance-optimized configuration
185
const fastPackr = new Packr({
186
useRecords: true,
187
useFloat32: FLOAT32_OPTIONS.DECIMAL_FIT,
188
sequential: true,
189
bundleStrings: true
190
});
191
192
// Structured cloning configuration
193
const cloningPackr = new Packr({
194
structuredClone: true,
195
moreTypes: true,
196
copyBuffers: true
197
});
198
199
// Custom type handling
200
const customPackr = new Packr({
201
int64AsType: 'string',
202
largeBigIntToString: true,
203
useTimestamp32: true,
204
onInvalidDate: () => null
205
});
206
207
// Record structure with custom sharing logic
208
const smartPackr = new Packr({
209
useRecords: (value) => {
210
// Only use records for objects with 3+ properties
211
return typeof value === 'object' &&
212
value !== null &&
213
Object.keys(value).length >= 3;
214
},
215
shouldShareStructure: (keys) => {
216
// Share structures for common patterns
217
return keys.includes('id') && keys.includes('name');
218
}
219
});
220
```
221
222
### Buffer Management
223
224
Advanced buffer management for high-performance scenarios.
225
226
```javascript { .api }
227
/**
228
* Use a specific buffer for packing operations
229
* @param buffer - Buffer or Uint8Array to use for packing
230
*/
231
useBuffer(buffer: Buffer | Uint8Array): void;
232
233
/**
234
* Clear shared structure and buffer data
235
*/
236
clearSharedData(): void;
237
```
238
239
**Usage Examples:**
240
241
```javascript
242
import { Packr } from "msgpackr";
243
244
const packr = new Packr({ useRecords: true });
245
246
// Pre-allocate buffer for better performance
247
const buffer = new Uint8Array(4096);
248
packr.useBuffer(buffer);
249
250
// Pack multiple items using the same buffer
251
const results = [];
252
for (const item of largeDataset) {
253
results.push(packr.pack(item));
254
}
255
256
// Clear shared data when switching contexts
257
packr.clearSharedData();
258
```
259
260
## Performance Considerations
261
262
- **Record Structures**: Enable `useRecords: true` for repeated object structures
263
- **Buffer Reuse**: Use `useBuffer()` for high-frequency packing operations
264
- **Float32 Options**: Choose appropriate `FLOAT32_OPTIONS` for your data
265
- **Sequential Mode**: Enable `sequential: true` for streaming scenarios
266
- **String Bundling**: Use `bundleStrings: true` for repeated string values
267
268
```javascript
269
// High-performance configuration example
270
const highPerformancePackr = new Packr({
271
useRecords: true,
272
useFloat32: FLOAT32_OPTIONS.DECIMAL_FIT,
273
sequential: true,
274
bundleStrings: true,
275
maxSharedStructures: 32
276
});
277
```