bun-memory 1.1.24 → 1.1.26

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.
@@ -1,747 +1,178 @@
1
- /**
2
- * Global type augmentations for ArrayBuffer-like views with native pointer access.
3
- *
4
- * This ambient declaration module augments common Buffer and TypedArray types with a
5
- * read-only `ptr` property that returns a native pointer usable by `bun:ffi`. This
6
- * provides TypeScript type safety and IntelliSense support for the pointer properties
7
- * that are added at runtime by the corresponding implementation in `extensions.ts`.
8
- *
9
- * The `ptr` property enables direct memory access for FFI (Foreign Function Interface)
10
- * operations, allowing JavaScript code to pass buffer addresses to native functions
11
- * without additional marshaling overhead.
12
- *
13
- * @remarks
14
- * - These are ambient type declarations only - runtime implementation is in `extensions.ts`
15
- * - The property is defined as a non-enumerable getter at runtime
16
- * - Pointers are only valid for the lifetime of the buffer and should not be cached long-term
17
- * - It is safe to take the pointer immediately before an FFI call; do not store
18
- * it long-term across reallocations or garbage collection cycles
19
- * - Requires Bun runtime environment for the underlying `bun:ffi` functionality
20
- *
21
- * @example
22
- * ```typescript
23
- * // TypeScript will recognize .ptr property on these types
24
- * declare function nativeFunction(data: Pointer, size: number): boolean;
25
- *
26
- * const buffer = new Uint8Array([1, 2, 3, 4]);
27
- * const success = nativeFunction(buffer.ptr, buffer.length); // Type-safe!
28
- * ```
29
- *
30
- * @example
31
- * ```typescript
32
- * // Useful for Win32 API calls
33
- * import { dlopen, FFIType } from 'bun:ffi';
34
- *
35
- * const { symbols } = dlopen('kernel32.dll', {
36
- * WriteFile: {
37
- * args: [FFIType.u64, FFIType.ptr, FFIType.u32, FFIType.ptr, FFIType.ptr],
38
- * returns: FFIType.bool
39
- * }
40
- * });
41
- *
42
- * const data = Buffer.from('Hello, World!', 'utf8');
43
- * const bytesWritten = new Uint32Array(1);
44
- *
45
- * // TypeScript knows about .ptr properties
46
- * const result = symbols.WriteFile(
47
- * fileHandle,
48
- * data.ptr, // Buffer pointer
49
- * data.length,
50
- * bytesWritten.ptr, // Uint32Array pointer
51
- * 0n
52
- * );
53
- * ```
54
- *
55
- * @see {@link ../extensions.ts} for the runtime implementation
56
- */
57
-
58
1
  import { type Pointer, ptr } from 'bun:ffi';
59
2
 
60
3
  declare global {
61
4
  /**
62
- * Augmentation for ArrayBuffer with native pointer access.
5
+ * Adds a native pointer property to all ArrayBuffer, Buffer, DataView, and TypedArray types.
63
6
  *
64
- * ArrayBuffer represents a raw binary data buffer of a fixed length.
65
- * The `ptr` property provides access to the underlying memory address
66
- * for direct FFI operations.
7
+ * The `ptr` property returns a native pointer usable with Bun FFI.
67
8
  *
68
9
  * @example
69
- * ```typescript
70
- * const buffer = new ArrayBuffer(1024);
71
- * const view = new DataView(buffer);
72
- *
73
- * // Both buffer and view provide access to the same memory
74
- * console.log(buffer.ptr === view.ptr); // Should be true
75
- *
76
- * // Use in FFI calls
77
- * nativeMemcpy(destPtr, buffer.ptr, buffer.byteLength);
78
- * ```
79
- *
80
- * @example
81
- * ```typescript
82
- * // Allocate buffer for native function output
83
- * const outputBuffer = new ArrayBuffer(512);
84
- * const success = nativeFunction(inputData, outputBuffer.ptr, outputBuffer.byteLength);
85
- *
86
- * if (success) {
87
- * // Process the data written by native function
88
- * const view = new Uint8Array(outputBuffer);
89
- * processResults(view);
90
- * }
10
+ * ```ts
11
+ * const arr = new Uint8Array([1, 2, 3]);
12
+ * nativeFunction(arr.ptr, arr.length);
91
13
  * ```
92
14
  */
93
15
  interface ArrayBuffer {
94
16
  /**
95
- * Native pointer to the backing memory for Bun FFI operations.
96
- *
97
- * This property returns a Pointer object that can be passed directly to
98
- * native functions via Bun's FFI system. The pointer represents the start
99
- * address of the ArrayBuffer's data.
100
- *
101
- * @readonly
17
+ * Native pointer to ArrayBuffer memory for Bun FFI.
102
18
  * @example
103
- * ```typescript
104
- * const buffer = new ArrayBuffer(256);
105
- * const memPtr = buffer.ptr;
106
- *
107
- * // Pass to native memory operation
108
- * memset(memPtr, 0, buffer.byteLength);
19
+ * ```ts
20
+ * const buf = new ArrayBuffer(8);
21
+ * nativeFunction(buf.ptr, buf.byteLength);
109
22
  * ```
110
23
  */
111
24
  readonly ptr: Pointer;
112
25
  }
113
-
114
- /**
115
- * Augmentation for BigInt64Array with native pointer access.
116
- *
117
- * BigInt64Array represents an array of 64-bit signed integers using BigInt.
118
- * Used for very large integer values, timestamps, file sizes, and memory addresses.
119
- *
120
- * @example
121
- * ```typescript
122
- * const timestamps = new BigInt64Array([
123
- * 1640995200000n, // Unix timestamp in milliseconds
124
- * 1641081600000n,
125
- * 1641168000000n
126
- * ]);
127
- *
128
- * // Process timestamps with native date/time library
129
- * const formatted = nativeFormatTimestamps(timestamps.ptr, timestamps.length);
130
- * ```
131
- *
132
- * @example
133
- * ```typescript
134
- * // Large file sizes or memory addresses
135
- * const fileSizes = new BigInt64Array([
136
- * 1099511627776n, // 1TB
137
- * 2199023255552n, // 2TB
138
- * 4398046511104n // 4TB
139
- * ]);
140
- *
141
- * // Analyze storage with native file system utilities
142
- * const analysis = nativeAnalyzeStorage(fileSizes.ptr, fileSizes.length);
143
- * ```
144
- */
145
26
  interface BigInt64Array {
146
27
  /**
147
- * Native pointer to the underlying buffer for Bun FFI operations.
148
- *
149
- * @readonly
28
+ * Native pointer to BigInt64Array memory for Bun FFI.
150
29
  * @example
151
- * ```typescript
152
- * const bigInts = new BigInt64Array([-9223372036854775808n, 0n, 9223372036854775807n]);
153
- * const result = nativeProcessBigInt64(bigInts.ptr, bigInts.length);
30
+ * ```ts
31
+ * const arr = new BigInt64Array([1n, 2n]);
32
+ * nativeFunction(arr.ptr, arr.length);
154
33
  * ```
155
34
  */
156
35
  readonly ptr: Pointer;
157
36
  }
158
-
159
- /**
160
- * Augmentation for BigUint64Array with native pointer access.
161
- *
162
- * BigUint64Array represents an array of 64-bit unsigned integers using BigInt.
163
- * Used for very large positive values, memory addresses (on 64-bit systems),
164
- * and cryptographic operations.
165
- *
166
- * @example
167
- * ```typescript
168
- * const memoryAddresses = new BigUint64Array([
169
- * 0x7fff00000000n,
170
- * 0x7fff12345678n,
171
- * 0x7fffabcdef00n
172
- * ]);
173
- *
174
- * // Process memory addresses with native memory manager
175
- * const valid = nativeValidateAddresses(memoryAddresses.ptr, memoryAddresses.length);
176
- * ```
177
- *
178
- * @example
179
- * ```typescript
180
- * // Cryptographic key material
181
- * const keyMaterial = new BigUint64Array([
182
- * 0x123456789ABCDEF0n,
183
- * 0xFEDCBA9876543210n,
184
- * 0x0F0F0F0F0F0F0F0Fn
185
- * ]);
186
- *
187
- * // Generate cryptographic keys with native crypto library
188
- * const keys = nativeGenerateKeys(keyMaterial.ptr, keyMaterial.length);
189
- * ```
190
- */
191
37
  interface BigUint64Array {
192
38
  /**
193
- * Native pointer to the underlying buffer for Bun FFI operations.
194
- *
195
- * @readonly
39
+ * Native pointer to BigUint64Array memory for Bun FFI.
196
40
  * @example
197
- * ```typescript
198
- * const bigUints = new BigUint64Array([0n, 1n, 18446744073709551615n]);
199
- * const hash = nativeHashBigUint64(bigUints.ptr, bigUints.length);
41
+ * ```ts
42
+ * const arr = new BigUint64Array([1n, 2n]);
43
+ * nativeFunction(arr.ptr, arr.length);
200
44
  * ```
201
45
  */
202
46
  readonly ptr: Pointer;
203
47
  }
204
-
205
48
  interface Buffer {
206
49
  /**
207
- * Native pointer to the underlying buffer for Bun FFI operations.
208
- *
209
- * This property provides direct access to the memory address of the Buffer's
210
- * data, enabling efficient data exchange with native functions without copying.
211
- * The pointer is compatible with all FFI operations and can be passed directly
212
- * to native functions expecting raw memory addresses.
213
- *
214
- * @readonly
215
- * @example
216
- * ```typescript
217
- * const data = Buffer.from([0x41, 0x42, 0x43, 0x44]); // "ABCD"
218
- *
219
- * // Pass buffer directly to native function
220
- * const checksum = nativeCalculateChecksum(data.ptr, data.length);
221
- *
222
- * // Use for memory operations
223
- * const copied = Buffer.alloc(data.length);
224
- * nativeMemcpy(copied.ptr, data.ptr, data.length);
225
- * ```
226
- *
50
+ * Native pointer to Buffer memory for Bun FFI.
227
51
  * @example
228
- * ```typescript
229
- * // Efficient string processing with native functions
230
- * const text = Buffer.from('Process this text', 'utf8');
231
- * const result = Buffer.alloc(text.length * 2); // Assume processing might expand
232
- *
233
- * const newLength = nativeProcessText(
234
- * text.ptr, // Input buffer
235
- * text.length, // Input length
236
- * result.ptr, // Output buffer
237
- * result.length // Output capacity
238
- * );
239
- *
240
- * if (newLength > 0) {
241
- * const processedText = result.subarray(0, newLength).toString('utf8');
242
- * console.log('Processed:', processedText);
243
- * }
52
+ * ```ts
53
+ * const buf = Buffer.from([1, 2, 3]);
54
+ * nativeFunction(buf.ptr, buf.length);
244
55
  * ```
245
56
  */
246
57
  readonly ptr: Pointer;
247
58
  }
248
-
249
- /**
250
- * Augmentation for DataView with native pointer access.
251
- *
252
- * DataView provides a low-level interface for reading and writing multiple
253
- * data types in an ArrayBuffer. The `ptr` property provides access to the
254
- * underlying buffer's memory address.
255
- *
256
- * @example
257
- * ```typescript
258
- * const buffer = new ArrayBuffer(64);
259
- * const view = new DataView(buffer, 16, 32); // Offset 16, length 32
260
- *
261
- * // DataView ptr points to the underlying ArrayBuffer start, not the view offset
262
- * console.log(buffer.ptr === view.ptr); // Should be true
263
- *
264
- * // For native functions, you may need to account for the offset
265
- * const offsetPtr = view.ptr + view.byteOffset;
266
- * nativeFunction(offsetPtr, view.byteLength);
267
- * ```
268
- *
269
- * @example
270
- * ```typescript
271
- * // Read structured data from native function
272
- * const resultBuffer = new ArrayBuffer(128);
273
- * const view = new DataView(resultBuffer);
274
- *
275
- * if (nativeGetStructData(view.ptr, view.byteLength)) {
276
- * const id = view.getUint32(0, true); // Little endian uint32
277
- * const value = view.getFloat64(4, true); // Little endian float64
278
- * const flags = view.getUint16(12, true); // Little endian uint16
279
- * }
280
- * ```
281
- */
282
59
  interface DataView {
283
60
  /**
284
- * Native pointer to the underlying buffer for Bun FFI operations.
285
- *
286
- * Note that this points to the start of the underlying ArrayBuffer,
287
- * not accounting for any byteOffset of the DataView. If you need to
288
- * pass the exact view location to native code, add byteOffset to the pointer.
289
- *
290
- * @readonly
61
+ * Native pointer to DataView memory for Bun FFI.
291
62
  * @example
292
- * ```typescript
293
- * const buffer = new ArrayBuffer(1024);
294
- * const view = new DataView(buffer, 100, 200);
295
- *
296
- * // Points to buffer start
297
- * const bufferPtr = view.ptr;
298
- *
299
- * // Points to view start (buffer + offset)
300
- * const viewPtr = view.ptr + view.byteOffset;
63
+ * ```ts
64
+ * const view = new DataView(new ArrayBuffer(4));
65
+ * nativeFunction(view.ptr, view.byteLength);
301
66
  * ```
302
67
  */
303
68
  readonly ptr: Pointer;
304
69
  }
305
-
306
- /**
307
- * Augmentation for Float32Array with native pointer access.
308
- *
309
- * Float32Array represents an array of 32-bit floating-point numbers.
310
- * Commonly used for 3D graphics, audio processing, scientific computing,
311
- * and any application requiring single-precision floating-point data.
312
- *
313
- * @example
314
- * ```typescript
315
- * const vertices = new Float32Array([
316
- * -1.0, -1.0, 0.0, // Vertex 1: x, y, z
317
- * 1.0, -1.0, 0.0, // Vertex 2: x, y, z
318
- * 0.0, 1.0, 0.0 // Vertex 3: x, y, z
319
- * ]);
320
- *
321
- * // Render triangle with native graphics API
322
- * nativeRenderTriangle(vertices.ptr, vertices.length / 3);
323
- * ```
324
- *
325
- * @example
326
- * ```typescript
327
- * // Audio signal processing
328
- * const audioBuffer = new Float32Array(1024); // Audio samples
329
- *
330
- * // Apply native audio filter
331
- * nativeApplyFilter(audioBuffer.ptr, audioBuffer.length, filterCoeffs);
332
- *
333
- * // Output processed audio
334
- * outputAudio(audioBuffer);
335
- * ```
336
- *
337
- * @example
338
- * ```typescript
339
- * // Matrix operations for 3D transformations
340
- * const matrix4x4 = new Float32Array(16); // 4x4 transformation matrix
341
- *
342
- * // Calculate view-projection matrix with native math library
343
- * nativeCalculateMatrix(matrix4x4.ptr, viewMatrix, projectionMatrix);
344
- * ```
345
- */
346
70
  interface Float32Array {
347
71
  /**
348
- * Native pointer to the underlying buffer for Bun FFI operations.
349
- *
350
- * @readonly
72
+ * Native pointer to Float32Array memory for Bun FFI.
351
73
  * @example
352
- * ```typescript
353
- * const floats = new Float32Array([3.14159, 2.71828, 1.41421]);
354
- * const result = nativeMathOperation(floats.ptr, floats.length);
74
+ * ```ts
75
+ * const arr = new Float32Array([1, 2, 3]);
76
+ * nativeFunction(arr.ptr, arr.length);
355
77
  * ```
356
78
  */
357
79
  readonly ptr: Pointer;
358
80
  }
359
-
360
- /**
361
- * Augmentation for Float64Array with native pointer access.
362
- *
363
- * Float64Array represents an array of 64-bit floating-point numbers (double precision).
364
- * Used for high-precision mathematical calculations, scientific computing,
365
- * financial calculations, and applications requiring maximum floating-point accuracy.
366
- *
367
- * @example
368
- * ```typescript
369
- * const scientificData = new Float64Array([
370
- * 6.62607015e-34, // Planck constant
371
- * 1.602176634e-19, // Elementary charge
372
- * 9.1093837015e-31 // Electron mass
373
- * ]);
374
- *
375
- * // Perform high-precision physics calculations
376
- * const results = nativePhysicsCalculation(scientificData.ptr, scientificData.length);
377
- * ```
378
- *
379
- * @example
380
- * ```typescript
381
- * // Financial calculations requiring high precision
382
- * const prices = new Float64Array([1234.56789012345, 9876.54321098765]);
383
- *
384
- * // Calculate precise financial metrics
385
- * const metrics = nativeFinancialAnalysis(prices.ptr, prices.length);
386
- * ```
387
- *
388
- * @example
389
- * ```typescript
390
- * // Numerical analysis and statistics
391
- * const dataset = new Float64Array(10000);
392
- *
393
- * // Fill with measurement data
394
- * nativePopulateDataset(dataset.ptr, dataset.length, measurementParams);
395
- *
396
- * // Perform statistical analysis
397
- * const statistics = nativeStatisticalAnalysis(dataset.ptr, dataset.length);
398
- * ```
399
- */
400
81
  interface Float64Array {
401
82
  /**
402
- * Native pointer to the underlying buffer for Bun FFI operations.
403
- *
404
- * @readonly
83
+ * Native pointer to Float64Array memory for Bun FFI.
405
84
  * @example
406
- * ```typescript
407
- * const doubles = new Float64Array([Math.PI, Math.E, Math.SQRT2]);
408
- * const precise = nativePrecisionMath(doubles.ptr, doubles.length);
85
+ * ```ts
86
+ * const arr = new Float64Array([1, 2, 3]);
87
+ * nativeFunction(arr.ptr, arr.length);
409
88
  * ```
410
89
  */
411
90
  readonly ptr: Pointer;
412
91
  }
413
-
414
- /**
415
- * Augmentation for Int8Array with native pointer access.
416
- *
417
- * Int8Array represents an array of 8-bit signed integers. The `ptr` property
418
- * provides access to the underlying memory address for FFI operations.
419
- *
420
- * @example
421
- * ```typescript
422
- * const signedBytes = new Int8Array([-128, -1, 0, 1, 127]);
423
- *
424
- * // Pass to native function expecting signed byte array
425
- * const result = nativeProcessSignedBytes(signedBytes.ptr, signedBytes.length);
426
- * ```
427
- *
428
- * @example
429
- * ```typescript
430
- * // Audio processing with signed 8-bit samples
431
- * const audioSamples = new Int8Array(44100); // 1 second at 44.1kHz
432
- *
433
- * if (nativeGenerateAudio(audioSamples.ptr, audioSamples.length)) {
434
- * // Process the generated audio data
435
- * playAudio(audioSamples);
436
- * }
437
- * ```
438
- */
439
- interface Int8Array {
92
+ interface Int16Array {
440
93
  /**
441
- * Native pointer to the underlying buffer for Bun FFI operations.
442
- *
443
- * @readonly
94
+ * Native pointer to Int16Array memory for Bun FFI.
444
95
  * @example
445
- * ```typescript
446
- * const data = new Int8Array([1, -2, 3, -4]);
447
- * nativeFunction(data.ptr, data.length);
96
+ * ```ts
97
+ * const arr = new Int16Array([1, 2, 3]);
98
+ * nativeFunction(arr.ptr, arr.length);
448
99
  * ```
449
100
  */
450
101
  readonly ptr: Pointer;
451
102
  }
452
-
453
- /**
454
- * Augmentation for SharedArrayBuffer with native pointer access.
455
- *
456
- * SharedArrayBuffer represents raw binary data that can be shared between
457
- * multiple JavaScript contexts (workers). The `ptr` property provides access
458
- * to the underlying shared memory address for FFI operations.
459
- *
460
- * @example
461
- * ```typescript
462
- * const sharedBuffer = new SharedArrayBuffer(1024);
463
- * const worker1View = new Int32Array(sharedBuffer);
464
- * const worker2View = new Int32Array(sharedBuffer);
465
- *
466
- * // All views share the same underlying memory pointer
467
- * console.log(sharedBuffer.ptr === worker1View.ptr); // Should be true
468
- *
469
- * // Native function can operate on shared memory
470
- * nativeProcessData(sharedBuffer.ptr, sharedBuffer.byteLength);
471
- * ```
472
- *
473
- * @example
474
- * ```typescript
475
- * // Inter-worker communication through shared memory
476
- * const sharedData = new SharedArrayBuffer(4096);
477
- *
478
- * // Worker can pass shared memory to native code
479
- * if (nativeInitializeBuffer(sharedData.ptr, sharedData.byteLength)) {
480
- * // Share the buffer with other workers
481
- * worker.postMessage({ sharedBuffer: sharedData });
482
- * }
483
- * ```
484
- */
485
- interface SharedArrayBuffer {
103
+ interface Int32Array {
486
104
  /**
487
- * Native pointer to the backing shared memory for Bun FFI operations.
488
- *
489
- * This property returns a Pointer object representing the start address of
490
- * the SharedArrayBuffer's data. The pointer can be used across multiple
491
- * workers that share the same buffer.
492
- *
493
- * @readonly
105
+ * Native pointer to Int32Array memory for Bun FFI.
494
106
  * @example
495
- * ```typescript
496
- * const shared = new SharedArrayBuffer(512);
497
- *
498
- * // Initialize shared memory with native function
499
- * nativeMemoryInit(shared.ptr, shared.byteLength);
500
- *
501
- * // Multiple workers can access the same memory via the pointer
107
+ * ```ts
108
+ * const arr = new Int32Array([1, 2, 3]);
109
+ * nativeFunction(arr.ptr, arr.length);
502
110
  * ```
503
111
  */
504
112
  readonly ptr: Pointer;
505
113
  }
506
-
507
- /**
508
- * Augmentation for Uint8Array with native pointer access.
509
- *
510
- * Uint8Array represents an array of 8-bit unsigned integers. This is one of
511
- * the most commonly used types for binary data and raw memory operations.
512
- *
513
- * @example
514
- * ```typescript
515
- * const imageData = new Uint8Array(width * height * 4); // RGBA pixels
516
- *
517
- * // Load image data from native library
518
- * if (nativeLoadImage(filename, imageData.ptr, imageData.length)) {
519
- * // Process loaded pixel data
520
- * displayImage(imageData, width, height);
521
- * }
522
- * ```
523
- *
524
- * @example
525
- * ```typescript
526
- * // Network packet processing
527
- * const packet = new Uint8Array(1500); // Maximum Ethernet frame
528
- * const bytesReceived = nativeReceivePacket(socket, packet.ptr, packet.length);
529
- *
530
- * if (bytesReceived > 0) {
531
- * const actualPacket = packet.subarray(0, bytesReceived);
532
- * processNetworkPacket(actualPacket);
533
- * }
534
- * ```
535
- */
536
- interface Uint8Array {
114
+ interface Int8Array {
537
115
  /**
538
- * Native pointer to the underlying buffer for Bun FFI operations.
539
- *
540
- * @readonly
116
+ * Native pointer to Int8Array memory for Bun FFI.
541
117
  * @example
542
- * ```typescript
543
- * const bytes = new Uint8Array([0xFF, 0xAB, 0x12, 0x00]);
544
- * const checksum = nativeCalculateChecksum(bytes.ptr, bytes.length);
118
+ * ```ts
119
+ * const arr = new Int8Array([1, 2, 3]);
120
+ * nativeFunction(arr.ptr, arr.length);
545
121
  * ```
546
122
  */
547
123
  readonly ptr: Pointer;
548
124
  }
549
-
550
- /**
551
- * Augmentation for Uint8ClampedArray with native pointer access.
552
- *
553
- * Uint8ClampedArray represents an array of 8-bit unsigned integers clamped
554
- * to 0-255 range. Commonly used for canvas image data.
555
- *
556
- * @example
557
- * ```typescript
558
- * const canvas = document.createElement('canvas');
559
- * const ctx = canvas.getContext('2d');
560
- * const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
561
- *
562
- * // Apply native image filter
563
- * nativeImageFilter(imageData.data.ptr, imageData.data.length, filterType);
564
- *
565
- * // Put processed data back to canvas
566
- * ctx.putImageData(imageData, 0, 0);
567
- * ```
568
- *
569
- * @example
570
- * ```typescript
571
- * // Create clamped pixel data
572
- * const pixels = new Uint8ClampedArray(256 * 256 * 4);
573
- *
574
- * // Generate procedural texture with native code
575
- * nativeGenerateTexture(pixels.ptr, 256, 256, textureParams);
576
- * ```
577
- */
578
- interface Uint8ClampedArray {
125
+ interface SharedArrayBuffer {
579
126
  /**
580
- * Native pointer to the underlying buffer for Bun FFI operations.
581
- *
582
- * @readonly
127
+ * Native pointer to SharedArrayBuffer memory for Bun FFI.
583
128
  * @example
584
- * ```typescript
585
- * const clampedData = new Uint8ClampedArray([300, -10, 128, 255]);
586
- * // Values are clamped: [255, 0, 128, 255]
587
- * nativeProcessClamped(clampedData.ptr, clampedData.length);
129
+ * ```ts
130
+ * const buf = new SharedArrayBuffer(8);
131
+ * nativeFunction(buf.ptr, buf.byteLength);
588
132
  * ```
589
133
  */
590
134
  readonly ptr: Pointer;
591
135
  }
592
-
593
- /**
594
- * Augmentation for Int16Array with native pointer access.
595
- *
596
- * Int16Array represents an array of 16-bit signed integers. Commonly used
597
- * for audio samples, coordinate data, and other medium-range integer values.
598
- *
599
- * @example
600
- * ```typescript
601
- * const audioSamples = new Int16Array(44100 * 2); // Stereo, 1 second
602
- *
603
- * // Generate audio with native synthesizer
604
- * nativeGenerateWaveform(audioSamples.ptr, audioSamples.length, frequency);
605
- *
606
- * // Play the generated audio
607
- * playAudioSamples(audioSamples);
608
- * ```
609
- *
610
- * @example
611
- * ```typescript
612
- * // 2D coordinate data
613
- * const coordinates = new Int16Array([-1000, 500, 0, -250, 750, 1000]);
614
- *
615
- * // Transform coordinates with native math library
616
- * nativeTransformPoints(coordinates.ptr, coordinates.length / 2, transformMatrix);
617
- * ```
618
- */
619
- interface Int16Array {
136
+ interface Uint16Array {
620
137
  /**
621
- * Native pointer to the underlying buffer for Bun FFI operations.
622
- *
623
- * @readonly
138
+ * Native pointer to Uint16Array memory for Bun FFI.
624
139
  * @example
625
- * ```typescript
626
- * const samples = new Int16Array([-32768, -1, 0, 1, 32767]);
627
- * const rms = nativeCalculateRMS(samples.ptr, samples.length);
140
+ * ```ts
141
+ * const arr = new Uint16Array([1, 2, 3]);
142
+ * nativeFunction(arr.ptr, arr.length);
628
143
  * ```
629
144
  */
630
145
  readonly ptr: Pointer;
631
146
  }
632
-
633
- /**
634
- * Augmentation for Int32Array with native pointer access.
635
- *
636
- * Int32Array represents an array of 32-bit signed integers. Commonly used
637
- * for large integer values, IDs, timestamps, and general numeric data.
638
- *
639
- * @example
640
- * ```typescript
641
- * const playerScores = new Int32Array([150000, -50, 999999, 0, 42]);
642
- *
643
- * // Process game scores with native leaderboard system
644
- * const rankings = nativeCalculateRankings(playerScores.ptr, playerScores.length);
645
- * ```
646
- *
647
- * @example
648
- * ```typescript
649
- * // Large dataset processing
650
- * const dataset = new Int32Array(1000000);
651
- *
652
- * // Populate with native data generator
653
- * nativeGenerateDataset(dataset.ptr, dataset.length, seed);
654
- *
655
- * // Analyze with native statistics
656
- * const stats = nativeAnalyzeInt32(dataset.ptr, dataset.length);
657
- * ```
658
- */
659
- interface Int32Array {
147
+ interface Uint32Array {
660
148
  /**
661
- * Native pointer to the underlying buffer for Bun FFI operations.
662
- *
663
- * @readonly
149
+ * Native pointer to Uint32Array memory for Bun FFI.
664
150
  * @example
665
- * ```typescript
666
- * const integers = new Int32Array([-2147483648, -1, 0, 1, 2147483647]);
667
- * const result = nativeProcessInt32(integers.ptr, integers.length);
151
+ * ```ts
152
+ * const arr = new Uint32Array([1, 2, 3]);
153
+ * nativeFunction(arr.ptr, arr.length);
668
154
  * ```
669
155
  */
670
156
  readonly ptr: Pointer;
671
157
  }
672
-
673
- /**
674
- * Augmentation for Uint16Array with native pointer access.
675
- *
676
- * Uint16Array represents an array of 16-bit unsigned integers. Commonly used
677
- * for Unicode character codes, port numbers, and other unsigned 16-bit data.
678
- *
679
- * @example
680
- * ```typescript
681
- * const unicodeText = new Uint16Array([0x48, 0x65, 0x6C, 0x6C, 0x6F]); // "Hello"
682
- *
683
- * // Process Unicode string with native text processor
684
- * const processed = nativeProcessUnicode(unicodeText.ptr, unicodeText.length);
685
- * ```
686
- *
687
- * @example
688
- * ```typescript
689
- * // Network port configuration
690
- * const ports = new Uint16Array([80, 443, 8080, 3000, 5432]);
691
- *
692
- * // Configure network services with native code
693
- * nativeConfigurePorts(ports.ptr, ports.length);
694
- * ```
695
- */
696
- interface Uint16Array {
158
+ interface Uint8Array {
697
159
  /**
698
- * Native pointer to the underlying buffer for Bun FFI operations.
699
- *
700
- * @readonly
160
+ * Native pointer to Uint8Array memory for Bun FFI.
701
161
  * @example
702
- * ```typescript
703
- * const values = new Uint16Array([0, 1, 65535]);
704
- * const sum = nativeSum16(values.ptr, values.length);
162
+ * ```ts
163
+ * const arr = new Uint8Array([1, 2, 3]);
164
+ * nativeFunction(arr.ptr, arr.length);
705
165
  * ```
706
166
  */
707
167
  readonly ptr: Pointer;
708
168
  }
709
-
710
- /**
711
- * Augmentation for Uint32Array with native pointer access.
712
- *
713
- * Uint32Array represents an array of 32-bit unsigned integers. Commonly used
714
- * for large positive values, memory addresses (on 32-bit systems), and counts.
715
- *
716
- * @example
717
- * ```typescript
718
- * const pixelColors = new Uint32Array(width * height); // ARGB pixels
719
- *
720
- * // Render with native graphics engine
721
- * nativeRenderScene(pixelColors.ptr, width, height, sceneData);
722
- *
723
- * // Display rendered pixels
724
- * displayPixelBuffer(pixelColors, width, height);
725
- * ```
726
- *
727
- * @example
728
- * ```typescript
729
- * // Hash table or ID mapping
730
- * const hashValues = new Uint32Array([0x12345678, 0xABCDEF00, 0xFF00FF00]);
731
- *
732
- * // Process hashes with native cryptographic function
733
- * const verified = nativeVerifyHashes(hashValues.ptr, hashValues.length);
734
- * ```
735
- */
736
- interface Uint32Array {
169
+ interface Uint8ClampedArray {
737
170
  /**
738
- * Native pointer to the underlying buffer for Bun FFI operations.
739
- *
740
- * @readonly
171
+ * Native pointer to Uint8ClampedArray memory for Bun FFI.
741
172
  * @example
742
- * ```typescript
743
- * const counts = new Uint32Array([0, 1, 4294967295]);
744
- * const total = nativeSum32(counts.ptr, counts.length);
173
+ * ```ts
174
+ * const arr = new Uint8ClampedArray([1, 2, 3]);
175
+ * nativeFunction(arr.ptr, arr.length);
745
176
  * ```
746
177
  */
747
178
  readonly ptr: Pointer;
@@ -749,240 +180,31 @@ declare global {
749
180
  }
750
181
 
751
182
  /**
752
- * Runtime definition of a non-enumerable `ptr` getter on Buffer and TypedArray
753
- * prototypes, returning a native pointer compatible with Bun's FFI layer.
754
- *
755
- * This module extends common JavaScript binary view objects (Buffer, TypedArrays, etc.)
756
- * with a `.ptr` property that provides direct access to the underlying memory address.
757
- * This pairs with the ambient declarations in `global.d.ts` so that common
758
- * JavaScript binary views expose a strongly-typed `.ptr` for direct FFI calls.
759
- *
760
- * The `ptr` property enables seamless integration between JavaScript memory views
761
- * and native code through Bun's Foreign Function Interface, allowing efficient
762
- * data exchange without additional copying or marshaling overhead.
763
- *
764
- * @remarks
765
- * - The property is added lazily only if not already present, avoiding conflicts
766
- * - The getter calls `bun:ffi.ptr(this)` each time it is accessed; avoid calling
767
- * it in tight loops when the value can be reused for performance
768
- * - The property is **non-enumerable** and **configurable**, minimizing surface
769
- * area and allowing controlled redefinition in tests if necessary
770
- * - Requires Bun runtime environment (uses `bun:ffi`)
771
- * - Properties are installed on prototype objects, affecting all instances
772
- *
773
- * @example
774
- * ```typescript
775
- * import './extensions'; // Import to install ptr getters
776
- *
777
- * // Create various binary views
778
- * const buffer = Buffer.from([1, 2, 3, 4]);
779
- * const floats = new Float32Array([1.0, 2.0, 3.0]);
780
- * const ints = new Int32Array([100, 200, 300]);
781
- *
782
- * // Access native pointers for FFI calls
783
- * console.log('Buffer pointer:', buffer.ptr);
784
- * console.log('Float array pointer:', floats.ptr);
785
- * console.log('Int array pointer:', ints.ptr);
786
- *
787
- * // Use in FFI function calls
788
- * const success = someNativeFunction(buffer.ptr, buffer.length);
789
- * ```
790
- *
791
- * @example
792
- * ```typescript
793
- * import './extensions';
794
- * import { dlopen, FFIType } from 'bun:ffi';
795
- *
796
- * const { symbols } = dlopen('user32.dll', {
797
- * MessageBoxA: {
798
- * args: [FFIType.ptr, FFIType.cstring, FFIType.cstring, FFIType.u32],
799
- * returns: FFIType.i32
800
- * }
801
- * });
802
- *
803
- * // Create message text in a buffer
804
- * const messageText = Buffer.from('Hello from FFI!\0', 'utf8');
805
- * const titleText = Buffer.from('Notification\0', 'utf8');
806
- *
807
- * // Use .ptr property to pass buffer addresses to native function
808
- * symbols.MessageBoxA(0n, messageText.ptr, titleText.ptr, 0);
809
- * ```
810
- *
811
- * @example
812
- * ```typescript
813
- * import './extensions';
814
- *
815
- * function processAudioData(samples: Float32Array) {
816
- * // Cache the pointer for multiple uses in tight loop
817
- * const samplePtr = samples.ptr;
818
- *
819
- * for (let i = 0; i < 100; i++) {
820
- * // Use cached pointer instead of accessing .ptr repeatedly
821
- * processAudioBuffer(samplePtr, samples.length);
822
- * }
823
- * }
824
- * ```
825
- */
826
-
827
- /**
828
- * List of binary view constructor functions whose prototypes will be extended
829
- * with the `ptr` getter property.
830
- *
831
- * This array contains all the standard JavaScript binary data types that can
832
- * hold raw memory data. Each type is extended with a `ptr` getter that returns
833
- * a native pointer compatible with Bun's FFI system.
183
+ * Installs the `ptr` property on all supported binary view prototypes.
834
184
  *
835
- * Supported types:
836
- * - **ArrayBuffer**: Raw binary data buffer
837
- * - **SharedArrayBuffer**: Shared memory buffer for worker threads
838
- * - **Buffer**: Node.js/Bun Buffer object (subclass of Uint8Array)
839
- * - **DataView**: View for reading/writing various data types from ArrayBuffer
840
- * - **Typed Arrays**: All standard typed array types for specific numeric types
841
- * - Int8Array, Uint8Array, Uint8ClampedArray (8-bit integers)
842
- * - Int16Array, Uint16Array (16-bit integers)
843
- * - Int32Array, Uint32Array (32-bit integers)
844
- * - BigInt64Array, BigUint64Array (64-bit integers)
845
- * - Float32Array, Float64Array (floating-point numbers)
846
- *
847
- * @example
848
- * ```typescript
849
- * // All these types will have .ptr available after importing extensions
850
- * const arrayBuffer = new ArrayBuffer(1024);
851
- * const sharedBuffer = new SharedArrayBuffer(512);
852
- * const nodeBuffer = Buffer.allocUnsafe(256);
853
- * const dataView = new DataView(arrayBuffer);
854
- * const int32View = new Int32Array(arrayBuffer);
855
- * const float64View = new Float64Array(8);
856
- *
857
- * // Each can provide its native pointer
858
- * console.log(arrayBuffer.ptr, sharedBuffer.ptr, nodeBuffer.ptr);
859
- * console.log(dataView.ptr, int32View.ptr, float64View.ptr);
860
- * ```
185
+ * The property is non-enumerable and configurable. The getter calls `ptr(this)`.
861
186
  */
862
- const constructors = [
863
- ArrayBuffer, //
864
- BigInt64Array,
865
- BigUint64Array,
866
- Buffer,
867
- DataView,
868
- Float32Array,
869
- Float64Array,
870
- Int16Array,
871
- Int32Array,
872
- Int8Array,
873
- SharedArrayBuffer,
874
- Uint16Array,
875
- Uint8Array,
876
- Uint8ClampedArray,
877
- Uint32Array,
878
- ] as const;
187
+ const constructors = [ArrayBuffer, BigInt64Array, BigUint64Array, Buffer, DataView, Float32Array, Float64Array, Int16Array, Int32Array, Int8Array, SharedArrayBuffer, Uint16Array, Uint32Array, Uint8Array, Uint8ClampedArray] as const;
879
188
 
880
- /**
881
- * Install the `ptr` getter on common binary view prototypes if not already present.
882
- *
883
- * This code iterates through all supported binary view types and adds a non-enumerable
884
- * `ptr` getter property to each prototype. The getter calls `bun:ffi.ptr()` to obtain
885
- * the native memory address of the underlying buffer.
886
- *
887
- * The property is only added if it doesn't already exist, preventing conflicts with
888
- * existing implementations or multiple imports of this module.
889
- *
890
- * Property characteristics:
891
- * - **configurable: true** - Can be reconfigured or deleted if needed
892
- * - **enumerable: false** - Won't appear in Object.keys() or for...in loops
893
- * - **get function** - Computed property that calls bun:ffi.ptr() on each access
894
- *
895
- * @example
896
- * ```typescript
897
- * // Before importing extensions
898
- * const buffer = Buffer.from([1, 2, 3]);
899
- * console.log(buffer.ptr); // undefined or TypeError
900
- *
901
- * // After importing extensions
902
- * import './extensions';
903
- * console.log(buffer.ptr); // Pointer { [native pointer address] }
904
- * ```
905
- *
906
- * @example
907
- * ```typescript
908
- * // Property is non-enumerable
909
- * const array = new Uint8Array([1, 2, 3]);
910
- * console.log(Object.keys(array)); // ['0', '1', '2'] - ptr not included
911
- * console.log(array.ptr); // Pointer { [native pointer address] } - but still accessible
912
- * ```
913
- *
914
- * @example
915
- * ```typescript
916
- * // Property can be reconfigured if needed (for testing, etc.)
917
- * const mockPtr = { mockPointer: true };
918
- * Object.defineProperty(Uint8Array.prototype, 'ptr', {
919
- * configurable: true,
920
- * enumerable: false,
921
- * value: mockPtr
922
- * });
923
- *
924
- * const testArray = new Uint8Array([1, 2, 3]);
925
- * console.log(testArray.ptr); // { mockPointer: true }
926
- * ```
927
- */
928
- constructors.forEach(({ prototype }) => {
929
- if (!Object.getOwnPropertyDescriptor(prototype, 'ptr')) {
189
+ constructors.forEach(
190
+ ({ prototype }) =>
191
+ !Object.getOwnPropertyDescriptor(prototype, 'ptr') &&
930
192
  Object.defineProperty(prototype, 'ptr', {
931
- configurable: true,
193
+ configurable: false,
932
194
  enumerable: false,
933
195
  /**
934
- * Getter function that returns a native pointer to the underlying memory.
935
- *
936
- * This getter calls `bun:ffi.ptr()` each time the property is accessed to
937
- * obtain the current memory address of the buffer. The pointer is computed
938
- * on-demand to ensure it reflects the current state of the buffer.
939
- *
940
- * **Important Performance Note**: The pointer is computed on every access.
941
- * In performance-critical code with repeated FFI calls, cache the pointer
942
- * value in a local variable rather than accessing this property repeatedly.
943
- *
944
- * **Memory Safety**: The returned pointer is only valid as long as the
945
- * buffer exists and hasn't been reallocated. Do not store pointers long-term
946
- * across garbage collection cycles or buffer resizing operations.
947
- *
948
- * @returns Native pointer compatible with Bun FFI system
949
- *
196
+ * Returns a native pointer to the underlying memory.
197
+ * @returns Native pointer for Bun FFI.
950
198
  * @example
951
- * ```typescript
952
- * const data = new Float32Array([1.0, 2.0, 3.0, 4.0]);
953
- *
954
- * // Inefficient: ptr computed on each call
955
- * for (let i = 0; i < 1000; i++) {
956
- * processData(data.ptr, data.length); // ptr computed 1000 times!
957
- * }
958
- *
959
- * // Efficient: cache the pointer
960
- * const dataPtr = data.ptr; // Computed once
961
- * for (let i = 0; i < 1000; i++) {
962
- * processData(dataPtr, data.length); // Reuse cached pointer
963
- * }
964
- * ```
965
- *
966
- * @example
967
- * ```typescript
968
- * // Pointer reflects current buffer state
969
- * const buffer = Buffer.alloc(10);
970
- * const ptr1 = buffer.ptr;
971
- *
972
- * // Buffer might be reallocated internally
973
- * buffer.write('Hello World', 0); // May cause reallocation
974
- * const ptr2 = buffer.ptr;
975
- *
976
- * // ptr1 and ptr2 might be different if reallocation occurred
977
- * console.log('Same pointer?', ptr1 === ptr2);
199
+ * ```ts
200
+ * const arr = new Uint8Array([1, 2, 3]);
201
+ * nativeFunction(arr.ptr, arr.length);
978
202
  * ```
979
203
  */
980
204
  get(this): Pointer {
981
- // The pointer is computed on demand; do not cache across GC or growth.
982
205
  return ptr(this);
983
206
  },
984
- });
985
- }
986
- });
207
+ })
208
+ );
987
209
 
988
210
  export {};