@taichunmin/buffer - v0.13.18
    Preparing search index...

    Class Buffer

    The Buffer class is a cross platform alternative of Node buffer base on UInt8Array.

    See the Buffer | Node.js Documentation for more information.

    Hierarchy

    Implements

    Indexable

    • [index: number]: number
    Index
    • Creates a zero-length Buffer.

      Returns Buffer

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf = new Buffer()
      console.log(buf.length) // Prints: 0
      })()
    • Creates a new Buffer with length bytes. The contents are initialized to 0.

      Parameters

      • length: number

        The desired length of the new Buffer.

      Returns Buffer

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf = new Buffer(2)
      console.log(buf.length) // Prints: 2
      })()
    • Creates a new Buffer copied from arrayLike. TypedArray will be treated as an Array.

      Parameters

      • arrayLike:
            | Iterable<number, any, any>
            | ArrayLike<number>
            | ArrayBufferView<ArrayBufferLike>

        An array of bytes in the range 0255. Array entries outside that range will be truncated to fit into it.

      Returns Buffer

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf1 = Buffer.of(21, 31)
      console.log(buf1.toString('hex')) // Prints: 151f

      const buf2 = new Buffer(new Uint16Array([0x1234, 0x5678]))
      console.log(buf2.toString('hex')) // Prints: 3478

      const buf3 = Buffer.from('0102', 'hex')
      const buf4 = new Buffer(buf3)
      buf3[0] = 0x03
      console.log(buf3.toString('hex')) // Prints: 0302
      console.log(buf4.toString('hex')) // Prints: 0102
      })()
    • Creates a view of the arrayBuffer without copying the underlying memory. For example, when passed a reference to the .buffer property of a TypedArray instance, the newly created Buffer will share the same allocated memory as the TypedArray's underlying ArrayBuffer.

      Parameters

      • arrayBuffer: ArrayBufferLike | Buffer

        An ArrayBuffer or SharedArrayBuffer, for example the .buffer property of a TypedArray.

      • OptionalbyteOffset: number

        Index of first byte to expose. Default: 0.

      • Optionallength: number

        Number of bytes to expose. Default: arrayBuffer.byteLength - byteOffset.

      Returns Buffer

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const uint16 = new Uint16Array([5000, 4000])
      const buf = Buffer.from(uint16.buffer) // Shares memory with `uint16`.
      console.log(buf.toString('hex')) // Prints: 8813a00f

      uint16[1] = 6000
      console.log(buf.toString('hex')) // Prints: 88137017
      })()
    of: (...items: any[]) => Buffer

    The static method creates a new Buffer from a variable number of arguments.

    ;(async function () {
    const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

    const buf1 = Buffer.of(1)
    console.log(buf1.toString('hex')) // Prints: 01

    const buf2 = Buffer.of("1", "2", "3")
    console.log(buf2.toString('hex')) // Prints: 010203

    const buf3 = Buffer.of(undefined)
    console.log(buf3.toString('hex')) // Prints: 00
    })()
    • Allocates a new Buffer of size bytes. If fill is undefined, the Buffer will be zero-filled.

      Parameters

      • size: number

        The desired length of the new Buffer.

      • Optionalfill: number | Buffer | Uint8Array<ArrayBufferLike>

        A value to pre-fill the new Buffer with. Default: 0.

      Returns Buffer

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf = Buffer.alloc(5)
      console.log(buf.toString('hex')) // Prints: 0000000000
      })()
    • Allocates a new Buffer of size bytes. If fill is undefined, the Buffer will be zero-filled.

      Parameters

      • size: number

        The desired length of the new Buffer.

      • fill: string

        A value to pre-fill the new Buffer with. Default: 0.

      • Optionalencoding:
            | "base64"
            | "binary"
            | "ucs-2"
            | "utf-16le"
            | "utf-8"
            | "ascii"
            | "base64url"
            | "hex"
            | "latin1"
            | "ucs2"
            | "utf16le"
            | "utf8"

        The encoding of fill. Default: 'utf8'.

      Returns Buffer

      If fill is specified, the allocated Buffer will be initialized by calling buf.fill(fill).

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf = Buffer.alloc(5, 'a')
      console.log(buf.toString('hex')) // Prints: 6161616161
      })()

      If both fill and encoding are specified, the allocated Buffer will be initialized by calling buf.fill(fill, encoding).

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64')
      console.log(buf.toString('hex')) // Prints: 68656c6c6f20776f726c64
      })()
    • Allocates a new Buffer of size bytes. The contents are initialized to 0. This is equivalent to calling new Buffer(size).

      Parameters

      • size: number

        The desired length of the new Buffer.

      Returns Buffer

      This method is different from Node.js's Buffer.allocUnsafe() method.

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf = Buffer.allocUnsafe(10)
      console.log(buf.toString('hex')) // Prints: 00000000000000000000
      })()
    • Allocates a new Buffer of size bytes. The contents are initialized to 0. This is equivalent to calling new Buffer(size).

      Parameters

      • size: number

        The desired length of the new Buffer.

      Returns Buffer

      This method is different from Node.js's Buffer.allocUnsafeSlow() method.

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf = Buffer.allocUnsafeSlow(10)
      console.log(buf.toString('hex')) // Prints: 00000000000000000000
      })()
    • Returns .byteLength if value is a Buffer/DataView/TypedArray/ArrayBuffer/SharedArrayBuffer.

      Parameters

      • value: ArrayBufferLike | ArrayBufferView<ArrayBufferLike>

        A value to calculate the length of bytes.

      Returns number

      The number of bytes contained within value.

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const u8arr = new Uint8Array(5)
      console.log(Buffer.byteLength(u8arr)) // Prints: 5
      })()
    • Returns the byte length of a string when encoded using encoding. This is not the same as String.prototype.length, which does not account for the encoding that is used to convert the string into bytes.

      For 'base64', 'base64url', and 'hex', this method assumes value is valid. For strings that contain non-base64/hex-encoded data (e.g. whitespace), the return value might be greater than the length of a Buffer created from the string.

      Parameters

      • string: string

        A value to calculate the length of bytes.

      • Optionalencoding:
            | "base64"
            | "binary"
            | "ucs-2"
            | "utf-16le"
            | "utf-8"
            | "ascii"
            | "base64url"
            | "hex"
            | "latin1"
            | "ucs2"
            | "utf16le"
            | "utf8"

        The encoding of string. Default: 'utf8'.

      Returns number

      The number of bytes contained within string.

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const str = '\u00bd + \u00bc = \u00be'
      console.log(`${str}: ${str.length} characters, ${Buffer.byteLength(str, 'utf8')} bytes`)
      // Prints: ½ + ¼ = ¾: 9 characters, 12 bytes
      })()
    • Compares buf1 to buf2, typically for the purpose of sorting arrays of Buffer instances. This is equivalent to calling Buffer#compare.

      Parameters

      Returns -1 | 0 | 1

      Either -1, 0, or 1, depending on the result of the comparison. See Buffer#compare for details.

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf1 = Buffer.from('1234')
      const buf2 = Buffer.from('0123')

      console.log([buf1, buf2].sort(Buffer.compare).map(buf => buf.toString('hex')))
      // Prints: ['30313233', '31323334']
      // (This result is equal to: [buf2, buf1].)

      console.log([buf2, buf1].sort(Buffer.compare).map(buf => buf.toString('hex')))
      // Prints: ['30313233', '31323334']
      })()
    • Returns a new Buffer which is the result of concatenating all the Buffer instances in the list together.

      If the list has no items, or if the totalLength is 0, then a new zero-length Buffer is returned.

      If totalLength is not provided, it is calculated from the Buffer instances in list by adding their lengths.

      If totalLength is provided, it is coerced to an unsigned integer. If the combined length of the Buffers in list exceeds totalLength, the result is truncated to totalLength.

      Parameters

      • list: Buffer[]

        List of Buffer or Uint8Array instances to concatenate.

      • OptionaltotalLength: number

        Total length of the Buffer instances in list when concatenated.

      Returns Buffer

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf1 = Buffer.alloc(4)
      const buf2 = Buffer.alloc(5)
      const buf3 = Buffer.alloc(6)
      const totalLength = buf1.length + buf2.length + buf3.length
      console.log(totalLength) // Prints: 15

      const bufA = Buffer.concat([buf1, buf2, buf3], totalLength)
      console.log(bufA.toString('hex'))
      // Prints: 000000000000000000000000000000
      console.log(bufA.length) // Prints: 15
      })()
    • Copies the underlying memory of view into a new Buffer.

      Parameters

      • view: ArrayBufferView

        The TypedArray to copy.

      • offset: number = 0

        The starting offset within view. Default: 0.

      • Optionallength: number

        The number of elements from view to copy. Default: view.length - offset.

      Returns Buffer

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const u16 = new Uint16Array([0, 0xffff])
      const buf = Buffer.copyBytesFrom(u16, 1, 1)
      u16[1] = 0
      console.log(buf.length) // Prints: 2
      console.log(buf.toString('hex')) // Prints: ffff
      })()
    • Parameters

      Returns boolean

      ture if buf1 and buf2 have the same byte length and contents, or false otherwise.

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      console.log(Buffer.equals(Buffer.of(1, 2), Buffer.from('0102', 'hex'))) // true
      console.log(Buffer.equals(Buffer.from(Uint8Array.of(1, 2)), Buffer.from('0102', 'hex'))) // true
      console.log(Buffer.equals(Uint8Array.of(1, 2), Buffer.from('0102', 'hex'))) // false
      console.log(Buffer.equals(1, Uint8Array.of(1, 2))) // false
      console.log(Buffer.equals('', new Buffer(2))) // false
      })()
    • Allocates a new Buffer using an array of bytes in the range 0255. Array entries outside that range will be truncated to fit into it.

      If array is an Array-like object (that is, one with a length property of type number), it is treated as if it is an array, unless it is a Buffer or a Uint8Array. This means all other TypedArray variants get treated as an Array. To create a Buffer from the bytes backing a TypedArray, use Buffer.copyBytesFrom.

      Parameters

      Returns Buffer

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf1 = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72])
      console.log(buf1.toString('hex')) // Prints: 627566666572

      const u16 = new Uint16Array([0x0001, 0x0002])
      const buf2 = Buffer.from(u16)
      console.log(buf2.toString('hex')) // Prints: 0102
      })()
    • This creates a view of the ArrayBuffer without copying the underlying memory. For example, when passed a reference to the .buffer property of a TypedArray instance, the newly created Buffer will share the same allocated memory as the TypedArray's underlying ArrayBuffer.

      The optional byteOffset and length arguments specify a memory range within the arrayBuffer that will be shared by the Buffer.

      It is important to remember that a backing ArrayBuffer can cover a range of memory that extends beyond the bounds of a TypedArray view. A new Buffer created using the buffer property of a TypedArray may extend beyond the range of the TypedArray:

      Parameters

      • arrayBuffer: OrValueOf<ArrayBufferLike>

        An ArrayBuffer, SharedArrayBuffer, for example the .buffer property of a TypedArray.

      • OptionalbyteOffset: number

        Index of first byte to expose. Default: 0.

      • Optionallength: number

        Number of bytes to expose. Default: arrayBuffer.byteLength - byteOffset.

      Returns Buffer

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const arr = new Uint16Array(2)
      arr[0] = 5000
      arr[1] = 4000
      const buf = Buffer.from(arr.buffer) // Shares memory with `arr`
      console.log(buf.toString('hex')) // Prints: 8813a00f

      // Changing the original Uint16Array changes the Buffer also.
      arr[1] = 6000
      console.log(buf.toString('hex')) // Prints: 88137017
      })()
      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const ab = new ArrayBuffer(10)
      const buf = Buffer.from(ab, 0, 2)
      console.log(buf.length) // Prints: 2
      })()
      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const arrA = Uint8Array.from([0x63, 0x64, 0x65, 0x66]) // 4 elements
      const arrB = new Uint8Array(arrA.buffer, 1, 2) // 2 elements
      console.log(arrA.buffer === arrB.buffer) // true

      const buf = Buffer.from(arrB.buffer)
      console.log(buf.toString('hex')) // Prints: 63646566
      })()
    • Copies the passed buffer data onto a new Buffer instance.

      Parameters

      • buffer: OrValueOf<Buffer | Uint8Array<ArrayBufferLike> | Buffer<ArrayBufferLike>>

        An existing Buffer or Uint8Array from which to copy data.

      Returns Buffer

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf1 = Buffer.from('buffer')
      const buf2 = Buffer.from(buf1)
      buf1[0] = 0x61
      console.log(buf1.toString()) // Prints: auffer
      console.log(buf2.toString()) // Prints: buffer
      })()
    • Restore a Buffer in the format returned from Buffer#toJSON.

      Parameters

      • json: { data: number[]; type: "Buffer" }

        A JSON object returned from Buffer#toJSON.

      Returns Buffer

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf1 = Buffer.from('buffer')
      const buf2 = Buffer.from(buf1.toJSON())
      console.log(buf1.equals(buf2)) // Prints: true
      })()
    • Creates a new Buffer containing string. The encoding parameter identifies the character encoding to be used when converting string into bytes.

      Parameters

      • object: OrValueOf<string> | { "[toPrimitive]": (hint?: "string") => string }

        A string to encode.

      • Optionalencoding:
            | "base64"
            | "binary"
            | "ucs-2"
            | "utf-16le"
            | "utf-8"
            | "ascii"
            | "base64url"
            | "hex"
            | "latin1"
            | "ucs2"
            | "utf16le"
            | "utf8"

        The encoding of string. Default: 'utf8'.

      Returns Buffer

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf1 = Buffer.from('this is a tést')
      const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex')

      console.log(buf1.toString()) // Prints: this is a tést
      console.log(buf2.toString()) // Prints: this is a tést
      console.log(buf1.toString('latin1')) // Prints: this is a tést
      })()
      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf = Buffer.from(new String('this is a test'))
      console.log(buf.toString('hex')) // Prints: 7468697320697320612074657374
      })()
      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      class Foo {
      [Symbol.toPrimitive]() {
      return 'this is a test';
      }
      }

      const buf = Buffer.from(new Foo(), 'utf8')
      console.log(buf.toString('hex')) // Prints: 7468697320697320612074657374
      })()
    • Creates a new Buffer that encoded from the provided base64 using Base64 encoding. When creating a Buffer from a string, this encoding will also correctly accept "URL and Filename Safe Alphabet" as specified in RFC 4648, Section 5. Whitespace characters such as spaces, tabs, and new lines contained within the base64-encoded string are ignored.

      Parameters

      • base64: string

        A string to encode.

      Returns Buffer

    • Creates a new Buffer that encoded from the provided base64 using base64url encoding. base64url encoding as specified in RFC 4648, Section 5. When creating a Buffer from a string, this encoding will also correctly accept regular base64-encoded strings.

      Parameters

      • base64: string

        A string to encode.

      Returns Buffer

    • Creates a new Buffer that encoded from the provided hex using hexadecimal encoding. Data truncation may occur when encode strings that do not exclusively consist of an even number of hexadecimal characters.

      Parameters

      • hex: string

        A string to encode.

      Returns Buffer

    • Creates a new Buffer that encoded from the provided latin1 using Latin-1 encoding. Latin-1 stands for ISO-8859-1. This character encoding only supports the Unicode characters from U+0000 to U+00FF. Each character is encoded using a single byte. Characters that do not fit into that range are truncated and will be mapped to characters in that range.

      Parameters

      • latin1: string

        A string to encode.

      Returns Buffer

    • Creates a new Buffer that encoded from the provided string. The encoding parameter identifies the character encoding to be used when converting string into bytes.

      Parameters

      • string: string

        A string to encode.

      • encoding:
            | "base64"
            | "binary"
            | "ucs-2"
            | "utf-16le"
            | "utf-8"
            | "ascii"
            | "base64url"
            | "hex"
            | "latin1"
            | "ucs2"
            | "utf16le"
            | "utf8"

        The encoding of string. Default: 'utf8'.

      Returns Buffer

    • Creates a new Buffer that encoded from the provided ucs2 using UCS-2 encoding. UCS-2 used to refer to a variant of UTF-16 that did not support characters that had code points larger than U+FFFF. In Node.js, these code points are always supported.

      Parameters

      • ucs2: string

        A string to encode.

      Returns Buffer

    • Creates a new Buffer that encoded from the provided utf8 using UTF-8 encoding. Multi-byte encoded Unicode characters. Many web pages and other document formats use UTF-8. This is the default character encoding.

      Parameters

      • utf8: string

        A string to encode.

      Returns Buffer

      This method based on the TextEncoder API.

    • Creates a Buffer from view without copying the underlying memory.

      Parameters

      • view: ArrayBufferView

        The ArrayBufferView to create a Buffer from.

      • Optionaloffset: number

        The starting offset within view. Default: 0.

      • Optionallength: number

        The number of elements from view to copy. Default: view.length - offset.

      Returns Buffer

    • Parameters

      • obj: any

      Returns obj is Buffer

      true if obj is a Buffer, false otherwise.

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      console.log(Buffer.isBuffer(Buffer.alloc(10))) // true
      console.log(Buffer.isBuffer(Buffer.from('foo'))) // true
      console.log(Buffer.isBuffer('a string')) // false
      console.log(Buffer.isBuffer([])) // false
      console.log(Buffer.isBuffer(new Uint8Array(1024))) // false
      })()
    • Parameters

      • encoding: any

        A character encoding name to check.

      Returns encoding is
          | "base64"
          | "binary"
          | "ucs-2"
          | "utf-16le"
          | "utf-8"
          | "ascii"
          | "base64url"
          | "hex"
          | "latin1"
          | "ucs2"
          | "utf16le"
          | "utf8"

      true if encoding is the name of a supported character encoding, or false otherwise.

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      console.log(Buffer.isEncoding('utf8')) // true
      console.log(Buffer.isEncoding('hex')) // true
      console.log(Buffer.isEncoding('utf/8')) // false
      console.log(Buffer.isEncoding('')) // false
      })()
    • Iteratively unpack from the buf according to the format string format. This method returns an iterator which will read equally sized chunks from the buf until remaining contents smaller then the size required by the format, as reflected by Buffer.packCalcSize.

      Type Parameters

      • T extends any[]

      Parameters

      Returns Generator<T>

      A RangeError if the format requires 0 bytes, since such an iterator would never consume the buf. Python raises ValueError: cannot iterate over 0-length struct for the same reason.

      Unlike Python struct, this method does not support native size and alignment (that wouldn't make much sense in a javascript). Instead, specify byte order and emit pad bytes explicitly.

      A trailing partial record is silently dropped, where Python's iter_unpack raises unless the length is an exact multiple: [...Buffer.iterUnpack(Buffer.from('0102030405', 'hex'), '>2b')] is [[1, 2], [3, 4]] and the 5th byte is ignored. A buf too short for even one record still throws a RangeError. As with Buffer.unpack, c / s / p results are views sharing the source's memory.

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf1 = Buffer.from('01fe01fe', 'hex')
      console.log([...Buffer.iterUnpack(buf1, '!BB')]) // Prints: [[1, 254], [1, 254]]
      })()
    • Creates a new Buffer containing the vals packed according to the format string format. The arguments must match the vals required by the format exactly.

      Parameters

      • format: string

        A format string. Please refer to Buffer.packParseFormat for more information.

      • ...vals: any[]

        Values to pack.

      Returns Buffer

      Unlike Python struct, this method does not support native size and alignment (that wouldn't make much sense in a javascript). Instead, specify byte order and emit pad bytes explicitly.

      pack is both struct.pack and struct.pack_into, chosen by whether the first argument is a Buffer or a format string. There is no offset parameter; pack into a subarray() to write at an offset, since it shares memory with the parent.

      Packing values: coercion, not validation

      This is the largest behavioural gap from Python. Producing a value the format cannot hold is not an error; the value is coerced and then truncated.

      Integer formats (b B h H i I l L) run the value through lodash toSafeInteger and then write it with a DataView setter, so it wraps modulo the field width. Nothing throws, where every row below is a struct.error in Python:

      Call Result
      Buffer.pack('>B', 300) 2c (300 mod 256)
      Buffer.pack('>B', -1) ff
      Buffer.pack('>h', 1.9) 0001 (truncated toward zero)
      Buffer.pack('>h', '258') 0102
      Buffer.pack('>h', null) 0000
      Buffer.pack('>h', NaN) 0000
      Buffer.pack('>h', 'abc') 0000
      Buffer.pack('>i', 1e20) ffffffff (clamped to Number.MAX_SAFE_INTEGER, then wrapped)

      Validate ranges yourself before packing anything that comes from user input or the network.

      q / Q always unpack to bigint, never number. When packing, the value goes through BigInt(), which is stricter than the integer path — but the result still wraps. Pass a bigint literal for anything that might exceed 2^53.

      ? uses JavaScript truthiness, which differs from Python's for several common values: [] and {} pack as 01, and any non-empty string including 'false' packs as 01.

      c, s and p pass the value to Buffer.from, so a Buffer, string (UTF-8) or byte array all work, but a number throws TypeError: Invalid type of value: numberBuffer.pack('>c', 65) is an error; use Buffer.pack('>c', 'A') or Buffer.pack('>B', 65). c keeps only the first byte of whatever it is given, and an empty value packs as 00.

      e, f and d always use IEEE 754 binary16 / binary32 / binary64 regardless of the host, rounding half to even. Values too large for the format saturate to ±Infinity rather than raising, which is where e differs most from Python — Buffer.pack('>e', 1e5) is 7c00 (Infinity), while Python's struct.pack('>e', 1e5) raises OverflowError. The largest finite binary16 is 65504, and anything above 65519.996… rounds up to Infinity.

      Argument count

      Too few values throws TypeError: Not enough vals. Too many are silently ignored, where Python raises struct.error in both directions: Buffer.pack('>b', 1, 2, 3) is 01.

      Please refer to Python struct — Interpret bytes as packed binary data for more information.

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      console.log(Buffer.pack('>h', 1023).toString('hex')) // Prints: 03ff
      console.log(Buffer.pack('<h', 1023).toString('hex')) // Prints: ff03
      console.log(Buffer.pack('>bhl', 1, 2, 3).toString('hex')) // Prints: 01000200000003
      })()
    • Pack vals into buf according to the format string format. The arguments must match the vals required by the format exactly. The buf’s size in bytes must larger then the size required by the format, as reflected by Buffer.packCalcSize.

      Parameters

      • buf: Buffer

        A Buffer to pack into. A plain Uint8Array throws TypeError: Invalid type of buf — wrap it first with Buffer.fromView, which shares the same memory, or Buffer.from, which copies.

      • format: string

        A format string. Please refer to Buffer.packParseFormat for more information.

      • ...vals: any[]

        Values to pack.

      Returns Buffer

      A RangeError if buf is shorter than Buffer.packCalcSize.

      Unlike Python struct, this method does not support native size and alignment (that wouldn't make much sense in a javascript). Instead, specify byte order and emit pad bytes explicitly.

      Only the bytes the format covers are written, so a longer buf is fine and its trailing bytes are left as they were: Buffer.alloc(4).fill(0xEE) packed with '>h' becomes 0102eeee. Values are coerced rather than validated — please refer to Buffer.pack for the details.

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf1 = Buffer.alloc(3)
      Buffer.pack(buf1, '>h', 0x0102)
      console.log(buf1.toString('hex')) // Prints: 010200

      const buf2 = Buffer.alloc(3)
      Buffer.pack(buf2.subarray(1), '>h', 0x0102) // struct.pack_into
      console.log(buf2.toString('hex')) // Prints: 000102
      })()
    • Return the required size corresponding to the format string formatOrItems.

      Parameters

      • formatOrItems: string | [number, string][]

        A format string or parsed items return by items of Buffer.packParseFormat.

      Returns number

      Unlike Python struct, this method does not support native size and alignment (that wouldn't make much sense in a javascript). Instead, specify byte order and emit pad bytes explicitly.

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      console.log(Buffer.packCalcSize('>bhl')) // Prints: 7
      console.log(Buffer.packCalcSize('>ci')) // Prints: 5
      console.log(Buffer.packCalcSize('>ic')) // Prints: 5
      console.log(Buffer.packCalcSize('>lhl')) // Prints: 10
      console.log(Buffer.packCalcSize('>llh')) // Prints: 10
      console.log(Buffer.packCalcSize('>llh0l')) // Prints: 10
      console.log(Buffer.packCalcSize('<qh6xq')) // Prints: 24
      console.log(Buffer.packCalcSize('<qqh6x')) // Prints: 24
      })()
    • Parse a format string format. This is a internal method used by Buffer.packCalcSize, Buffer.pack, Buffer.unpack and Buffer.iterUnpack.

      Parameters

      • format: string

        A format string.

        Byte Order, Size, and Alignment

        The first character of the format string can be used to indicate the byte order, size and alignment of the packed data, according to the following table:

        Character Byte order Size Alignment
        @ native standard none
        = native standard none
        < little-endian standard none
        > big-endian standard none
        ! big-endian standard none

        If the first character is not one of these, @ is assumed.

        Format Characters

        Format characters have the following meaning; the conversion between C and Python values should be obvious given their types. The ‘Size’ column refers to the size of the packed value in bytes.

        Format C Type JavaScript Type Size Notes
        x pad byte no value 1 (1)
        c char Buffer of length 1 1
        b signed char number 1
        B unsigned char number 1
        ? _Bool boolean 1 (2)
        h short number 2
        H unsigned short number 2
        i int number 4
        I unsigned int number 4
        l long number 4
        L unsigned long number 4
        q long long BigInt of 64 bits 8
        Q unsigned long long BigInt of 64 bits 8
        e (3) number 2 (4)
        f float number 4 (4)
        d double number 8 (4)
        s char[] Buffer (5)
        p char[] Buffer (6)

        Notes:

        1. When packing, x inserts one NUL byte (0x00).
        2. The ? conversion code corresponds to the _Bool type defined by C standards since C99. It is represented by one byte.
        3. The IEEE 754 binary16 "half precision" type was introduced in the 2008 revision of the IEEE 754 standard. It has a sign bit, a 5-bit exponent and 11-bit precision (with 10 bits explicitly stored), and can represent numbers between approximately 6.1e-05 and 6.5e+04 at full precision. This type is not widely supported by C compilers: on a typical machine, an unsigned short can be used for storage, but not for math operations. See the Wikipedia page on the half-precision floating-point format for more information.
        4. For the f, d and e conversion codes, the packed representation uses the IEEE 754 binary32, binary64 or binary16 format (for f, d or e respectively), regardless of the floating-point format used by the platform.
        5. For the s format character, the count is interpreted as the length of the bytes, not a repeat count like for the other format characters; for example, 10s means a single 10-byte Buffer mapping to or from a single Buffer, while 10c means 10 separate one byte character elements (e.g., cccccccccc) mapping to or from ten different Buffer. (See Examples for a concrete demonstration of the difference.) If a count is not given, it defaults to 1. For packing, the Buffer is truncated or padded with null bytes as appropriate to make it fit. For unpacking, the resulting Buffer always has exactly the specified number of bytes. As a special case, 0s means a single, empty Buffer.
        6. The p format character encodes a "Pascal string", meaning a short variable-length string stored in a fixed number of bytes, given by the count. The first byte stored is the length of the string, or 255, whichever is smaller. The bytes of the string follow. If the string passed in to pack() is too long (longer than the count minus 1), only the leading count-1 bytes of the string are stored. If the string is shorter than count-1, it is padded with null bytes so that exactly count bytes in all are used. Note that for unpack(), the p format character consumes count bytes, but that the string returned can never contain more than 255 bytes.

        A format character may be preceded by an integral repeat count. For example, the format string 4h means exactly the same as hhhh.

        For the ? format character, the return value is either true or false. When packing, the truth value of the argument object is used. Either 0 or 1 in the bool representation will be packed, and any non-zero value will be true when unpacking.

      Returns PackFormat

      { littleEndian, items }, where items is an array of [repeat, type] pairs. Passing that items array back to Buffer.packCalcSize skips re-parsing, which is worth doing in a hot loop.

      Unlike Python struct, this method does not support native size and alignment (that wouldn't make much sense in a javascript). Instead, specify byte order and emit pad bytes explicitly.

      The format syntax is borrowed from Python's struct module, but the runtime behaviour is not — this library validates far less than Python does, and several cases Python rejects loudly are silently accepted here. If you are porting struct code, the four that bite hardest are:

      1. Integers are never range-checked. Buffer.pack('>B', 300) returns 2c, not an error.
      2. Extra values are silently ignored. Buffer.pack('>b', 1, 2, 3) returns 01.
      3. c / s / p unpack to views that share memory with the source buffer, not to copies.
      4. unpack accepts an over-long buffer and ignores the trailing bytes, where Python demands an exact length.

      API Surface

      Every operation has a static form and, except for packCalcSize, an instance form:

      Static Instance Python equivalent
      Buffer.pack(format, ...vals) struct.pack
      Buffer.pack(buf, format, ...vals) buf.pack(format, ...vals) struct.pack_into
      Buffer.unpack(buf, format) buf.unpack(format) struct.unpack
      Buffer.iterUnpack(buf, format) buf.iterUnpack(format) struct.iter_unpack
      Buffer.packCalcSize(formatOrItems) struct.calcsize
      Buffer.packParseFormat(format) (no equivalent)

      Format String Validation

      Only /^([@=<>!]?)((?:\d*[xcbB?hHiIlLqQefdsp])+)$/ is accepted; anything else throws TypeError: Invalid format: …. In particular, and unlike Python:

      • Whitespace is not allowed. '> b h' throws, where Python ignores whitespace between format characters.
      • The empty string is not a valid format. '' throws, where Python's calcsize('') is 0.
      • A byte order prefix is only accepted at position 0, so 'b>h' throws.
      • n, N and P are not supported and throw, since they only exist in Python's native mode.
      • i/I and l/L are identical here — both are 4 bytes, since there is no native size mode.
      • A p count above 255 is clamped to 255, so Buffer.packCalcSize('300p') is 255 where Python gives 300.

      Differences from Python's `struct`

      # Behaviour This library Python
      1 Out-of-range integers coerced and wrapped silently struct.error
      2 Non-numeric values for integer formats coerced ('abc' becomes 0) struct.error
      3 Extra values passed to pack ignored struct.error
      4 unpack buffer length must be at least Buffer.packCalcSize; extra bytes ignored must be exactly calcsize
      5 iter_unpack trailing bytes partial record dropped struct.error
      6 c / s / p unpack results views sharing the source's memory independent bytes copies
      7 Native size and alignment not supported; no padding is ever inserted for any prefix @ inserts C alignment padding
      8 p count above 255 clamped to 255 300
      9 Whitespace in the format string TypeError ignored
      10 Empty format string TypeError valid, calcsize('') is 0
      11 n, N, P formats TypeError supported in native mode
      12 ? truthiness JS rules ([] and {} are true) Python rules ([] and {} are false)
      13 Float overflow saturates to ±Infinity OverflowError for e, f
      14 Error type TypeError / RangeError / SyntaxError struct.error
      15 q / Q results always bigint int

      Rows 7 and 8 are deliberate design choices. The rest follow from this library validating less than Python does, so validate ranges and argument counts yourself at the boundary where untrusted data enters.

      Errors

      Python raises struct.error for everything. This library uses ordinary JS error types, so catch accordingly:

      Error Cause
      TypeError: Invalid format: … format string does not match the grammar
      TypeError: Invalid type of format format is not a string
      TypeError: Invalid type of buf buf is not a Buffer (a plain Uint8Array lands here)
      TypeError: Not enough vals fewer values than the format requires
      TypeError: Invalid type of value: number a number passed to c, s or p
      RangeError: buf.length = N, lenRequired = M buffer shorter than Buffer.packCalcSize
      RangeError: Cannot iterate over 0-length format: … Buffer.iterUnpack with a format of size 0
      RangeError / SyntaxError from BigInt() bad value for q or Q
      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const { items } = Buffer.packParseFormat('<qh6xq')
      console.log(Buffer.packCalcSize(items)) // Prints: 24
      })()
    • Decodes buf to a string according to the Base64 character encoding.

      Parameters

      • buf: Buffer

        The buffer to decode.

      Returns string

    • Decodes buf to a string according to the Base64 URL character encoding.

      Parameters

      • buf: Buffer

        The buffer to decode.

      Returns string

    • Decodes buf to a string according to the hexadecimal character encoding.

      Parameters

      • buf: Buffer

        The buffer to decode.

      Returns string

    • Decodes buf to a string according to the Latin1 character encoding. When decoding a Buffer into a string, using this encoding will additionally unset the highest bit of each byte before decoding as 'latin1'. Generally, there should be no reason to use this encoding, as 'utf8' (or, if the data is known to always be ASCII-only, 'latin1') will be a better choice when encoding or decoding ASCII-only text. It is only provided for legacy compatibility.

      Parameters

      • buf: Buffer

        The buffer to decode.

      Returns string

    • Decodes buf to a string according to the UCS-2 character encoding.

      Parameters

      • buf: Buffer

        The buffer to decode.

      Returns string

    • Decodes buf to a string according to the UTF-8 character encoding.

      Parameters

      • buf: Buffer

        The buffer to decode.

      Returns string

      This method based on the TextDecoder API.

    • Unpack from the buf (presumably packed by pack(format, ...)) according to the format string format. The result is a tuple even if it contains exactly one item. The buf’s size in bytes must larger then the size required by the format, as reflected by Buffer.packCalcSize.

      Type Parameters

      • T extends any[]

      Parameters

      • buf: Buffer

        A Buffer to unpack from. A plain Uint8Array throws TypeError: Invalid type of buf — wrap it first with Buffer.fromView, which shares the same memory, or Buffer.from, which copies.

      • format: string

        A format string. Please refer to Buffer.packParseFormat for more information.

      Returns T

      A RangeError if buf is shorter than Buffer.packCalcSize.

      Unlike Python struct, this method does not support native size and alignment (that wouldn't make much sense in a javascript). Instead, specify byte order and emit pad bytes explicitly.

      An over-long buf is accepted and its trailing bytes are ignored, where Python demands an exact length. The result is always an array, even for a single value: Buffer.unpack(buf, '>b') is [1], not 1.

      Unpacked `c` / `s` / `p` are views, not copies

      For c, s and p the result is a subarray() view into buf, where Python's struct always returns independent bytes. Mutating a result mutates the source, and holding one alive retains the whole underlying ArrayBuffer. Call Buffer.slice (or Buffer.from) when you need to detach the result from the source.

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf1 = Buffer.from('01fe01fe', 'hex')
      console.log(Buffer.unpack(buf1, '!BBbb')) // Prints: [1, 254, 1, -2]

      const buf2 = Buffer.from('0161626300', 'hex')
      const [str] = Buffer.unpack(buf2, '>x4s')
      str[0] = 0x5a
      console.log(buf2.toString('hex')) // Prints: 015a626300, the source changed
      })()
    "[iterator]": () => ArrayIterator<number>

    Implements the iterable protocol and allows Buffer to be consumed by most syntaxes expecting iterables, such as the spread syntax and for...of loops. It returns an array iterator object that yields the value of each index in the Buffer.

    Type Declaration

      • (): ArrayIterator<number>
      • Returns ArrayIterator<number>

        A new iterable iterator object that yields the value of each index in the Buffer.

    ;(async function () {
    const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

    const buf1 = Buffer.of(10, 20, 30, 40, 50)
    for (const n of buf1) console.log(n)

    const values = buf1[Symbol.iterator]()
    console.log(values.next().value) // Expected output: 10
    console.log(values.next().value) // Expected output: 20
    console.log(values.next().value) // Expected output: 30
    console.log(values.next().value) // Expected output: 40
    console.log(values.next().value) // Expected output: 50
    })()
    at: (index: number) => number | undefined

    Takes an integer value and returns the item at that index, allowing for positive and negative integers. Negative integers count back from the last item in the Buffer.

    Type Declaration

      • (index: number): number | undefined
      • Parameters

        • index: number

          Zero-based index of the Buffer element to be returned, converted to an integer. Negative index counts back from the end of the Buffer — if index < 0, index + array.length is accessed.

        Returns number | undefined

        The element in the Buffer matching the given index. Always returns undefined if index < -array.length or index >= array.length without attempting to access the corresponding property.

    ;(async function () {
    const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

    const buf = Buffer.of(1, 2, 4, 7, 11, 18)
    console.log(buf.at(-1)) // Expected output: 18
    console.log(buf[buf.length - 1]) // Expected output: 18
    })()
    copyWithin: (target: number, start: number, end?: number) => this

    The method shallow copies part of this Buffer to another location in the same Buffer and returns this Buffer without modifying its length.

    Type Declaration

      • (target: number, start: number, end?: number): this
      • Parameters

        • target: number

          Zero-based index at which to copy the sequence to. This corresponds to where the element at start will be copied to, and all elements between start and end are copied to succeeding indices.

        • start: number

          Zero-based index at which to start copying elements from.

        • Optionalend: number

          Zero-based index at which to end copying elements from. This method copies up to but not including end.

        Returns this

    ;(async function () {
    const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

    const buf = new Buffer(8)
    buf.set([1, 2, 3])
    console.log(buf.toString('hex')) // Prints: 0102030000000000
    buf.copyWithin(3, 0, 3)
    console.log(buf.toString('hex')) // Prints: 0102030102030000
    })()
    entries: () => ArrayIterator<[number, number]>

    Returns a new array iterator object that contains the key/value pairs for each index in the Buffer.

    Type Declaration

      • (): ArrayIterator<[number, number]>
      • Returns ArrayIterator<[number, number]>

        A new iterable iterator object.

    ;(async function () {
    const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

    const buf = Buffer.of(10, 20, 30, 40, 50)
    for (const entry of buf.entries()) console.log(entry)
    })()
    every: (
        callbackFn: (value: number, index: number, array: this) => unknown,
        thisArg?: any,
    ) => boolean

    Tests whether all elements in the Buffer pass the test implemented by the provided function.

    Type Declaration

      • (
            callbackFn: (value: number, index: number, array: this) => unknown,
            thisArg?: any,
        ): boolean
      • Parameters

        • callbackFn: (value: number, index: number, array: this) => unknown

          A function to execute for each element in the Buffer. It should return a truthy value to indicate the element passes the test, and a falsy value otherwise. The function is called with the following arguments:

          • value: The current element being processed in the Buffer.
          • index: The index of the current element being processed in the Buffer.
          • array: The Buffer every() was called upon.
        • OptionalthisArg: any

          A value to use as this when executing callbackFn.

        Returns boolean

        true unless callbackFn returns a falsy value for a Buffer element, in which case false is immediately returned.

    ;(async function () {
    const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

    console.log(Buffer.of(12, 5, 8, 130, 44).every(v => v >= 10)) // print: false
    console.log(Buffer.of(12, 54, 18, 130, 44).every(v => v >= 10)) // print: true
    })()
    filter: (
        callbackFn: (value: number, index: number, array: this) => any,
        thisArg?: any,
    ) => this

    Creates a copy of a portion of a given Buffer, filtered down to just the elements from the given Buffer that pass the test implemented by the provided function.

    Type Declaration

      • (
            callbackFn: (value: number, index: number, array: this) => any,
            thisArg?: any,
        ): this
      • Parameters

        • callbackFn: (value: number, index: number, array: this) => any

          A function to execute for each element in the Buffer. It should return a truthy value to keep the element in the resulting Buffer, and a falsy value otherwise. The function is called with the following arguments:

          • value: The current element being processed in the Buffer.
          • index: The index of the current element being processed in the Buffer.
          • array: The Buffer filter() was called upon.
        • OptionalthisArg: any

          A value to use as this when executing callbackFn.

        Returns this

        A copy of the given Buffer containing just the elements that pass the test. If no elements pass the test, an empty Buffer is returned.

    ;(async function () {
    const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

    const buf = Buffer.of(12, 5, 8, 130, 44).filter(v => v >= 10)
    console.log(buf.toString('hex')) // Expected output: "0c822c"
    })()
    find: (
        callbackFn: (value: number, index: number, array: this) => any,
        thisArg?: any,
    ) => number | undefined

    Returns the first element in the provided Buffer that satisfies the provided testing function. If no values satisfy the testing function, undefined is returned.

    Type Declaration

      • (
            callbackFn: (value: number, index: number, array: this) => any,
            thisArg?: any,
        ): number | undefined
      • Parameters

        • callbackFn: (value: number, index: number, array: this) => any

          A function to execute for each element in the Buffer. It should return a truthy value to indicate a matching element has been found, and a falsy value otherwise. The function is called with the following arguments:

          • value: The current element being processed in the Buffer.
          • index: The index of the current element being processed in the Buffer.
          • array: The Buffer find() was called upon.
        • OptionalthisArg: any

          A value to use as this when executing callbackFn.

        Returns number | undefined

        The first element in the Buffer that satisfies the provided testing function. Otherwise, undefined is returned.

    ;(async function () {
    const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

    function isPrime(element, index, array) {
    let start = 2;
    while (start <= Math.sqrt(element)) {
    if (element % start++ < 1) {
    return false;
    }
    }
    return element > 1;
    }

    const buf = Buffer.of(4, 5, 8, 12)
    console.log(buf.find(isPrime)) // Expected output: 5
    })()
    findIndex: (
        callbackFn: (value: number, index: number, array: this) => any,
        thisArg?: any,
    ) => number

    Returns the index of the first element in the Buffer that satisfies the provided testing function. If no elements satisfy the testing function, -1 is returned.

    Type Declaration

      • (
            callbackFn: (value: number, index: number, array: this) => any,
            thisArg?: any,
        ): number
      • Parameters

        • callbackFn: (value: number, index: number, array: this) => any

          A function to execute for each element in the Buffer. It should return a truthy value to indicate a matching element has been found, and a falsy value otherwise. The function is called with the following arguments:

          • value: The current element being processed in the Buffer.
          • index: The index of the current element being processed in the Buffer.
          • array: The Buffer findIndex() was called upon.
        • OptionalthisArg: any

          A value to use as this when executing callbackFn.

        Returns number

        The index of the first element in the Buffer that passes the test. Otherwise, -1.

    ;(async function () {
    const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

    function isPrime(element, index, array) {
    let start = 2;
    while (start <= Math.sqrt(element)) {
    if (element % start++ < 1) {
    return false;
    }
    }
    return element > 1;
    }

    console.log(Buffer.of(4, 6, 8, 12).findIndex(isPrime)) // Expected output: -1
    console.log(Buffer.of(4, 6, 7, 12).findIndex(isPrime)) // Expected output: 2
    })()
    findLast: (
        callbackFn: (value: number, index: number, array: this) => any,
        thisArg?: any,
    ) => number | undefined

    Iterates the Buffer in reverse order and returns the value of the first element that satisfies the provided testing function. If no elements satisfy the testing function, undefined is returned.

    Type Declaration

      • (
            callbackFn: (value: number, index: number, array: this) => any,
            thisArg?: any,
        ): number | undefined
      • Parameters

        • callbackFn: (value: number, index: number, array: this) => any

          A function to execute for each element in the Buffer. It should return a truthy value to indicate a matching element has been found, and a falsy value otherwise. The function is called with the following arguments:

          • value: The current element being processed in the Buffer.
          • index: The index of the current element being processed in the Buffer.
          • array: The Buffer find() was called upon.
        • OptionalthisArg: any

          A value to use as this when executing callbackFn.

        Returns number | undefined

        The last (highest-index) element in the Buffer that satisfies the provided testing function; undefined if no matching element is found.

    ;(async function () {
    const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

    function isPrime(element, index, array) {
    let start = 2;
    while (start <= Math.sqrt(element)) {
    if (element % start++ < 1) {
    return false;
    }
    }
    return element > 1;
    }

    const buf1 = Buffer.of(4, 6, 8, 12)
    console.log(buf1.findLast(isPrime)) // Expected output: undefined
    const buf2 = Buffer.of(4, 5, 7, 8, 9, 11, 12)
    console.log(buf2.findLast(isPrime)) // Expected output: 11
    })()
    findLastIndex: (
        callbackFn: (value: number, index: number, array: this) => any,
        thisArg?: any,
    ) => number

    Iterates the Buffer in reverse order and returns the index of the first element that satisfies the provided testing function. If no elements satisfy the testing function, -1 is returned.

    Type Declaration

      • (
            callbackFn: (value: number, index: number, array: this) => any,
            thisArg?: any,
        ): number
      • Parameters

        • callbackFn: (value: number, index: number, array: this) => any

          A function to execute for each element in the Buffer. It should return a truthy value to indicate a matching element has been found, and a falsy value otherwise. The function is called with the following arguments:

          • value: The current element being processed in the Buffer.
          • index: The index of the current element being processed in the Buffer.
          • array: The Buffer findIndex() was called upon.
        • OptionalthisArg: any

          A value to use as this when executing callbackFn.

        Returns number

        The index of the last (highest-index) element in the Buffer that passes the test. Otherwise -1 if no matching element is found.

    ;(async function () {
    const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

    function isPrime(element, index, array) {
    let start = 2;
    while (start <= Math.sqrt(element)) {
    if (element % start++ < 1) {
    return false;
    }
    }
    return element > 1;
    }

    console.log(Buffer.of(4, 6, 8, 12).findLastIndex(isPrime)) // Expected output: -1
    console.log(Buffer.of(4, 5, 7, 8, 9, 11, 12).findLastIndex(isPrime)) // Expected output: 5
    })()
    forEach: (
        callbackfn: (value: number, index: number, array: this) => void,
        thisArg?: any,
    ) => void

    Executes a provided function once for each Buffer element.

    Type Declaration

      • (
            callbackfn: (value: number, index: number, array: this) => void,
            thisArg?: any,
        ): void
      • Parameters

        • callbackfn: (value: number, index: number, array: this) => void

          A function to execute for each element in the Buffer. Its return value is discarded. The function is called with the following arguments:

          • value: The current element being processed in the Buffer.
          • index: The index of the current element being processed in the Buffer.
          • array: The Buffer forEach() was called upon.
        • OptionalthisArg: any

          A value to use as this when executing callbackfn.

        Returns void

    ;(async function () {
    const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

    Buffer.of(0, 1, 2, 3).forEach((element, index, array) => {
    console.log(`a[${index}] = ${element}`)
    })
    // Logs:
    // a[0] = 0
    // a[1] = 1
    // a[2] = 2
    // a[3] = 3
    })()
    join: (separator?: string) => string

    Creates and returns a new string by concatenating all of the elements in this Buffer, separated by commas or a specified separator string. If the Buffer has only one item, then that item will be returned without using the separator.

    Type Declaration

      • (separator?: string): string
      • Parameters

        • Optionalseparator: string

          A string to separate each pair of adjacent elements of the Buffer. If omitted, the Buffer elements are separated with a comma ",".

        Returns string

        A string with all Buffer elements joined. If buf.length is 0, the empty string is returned.

    ;(async function () {
    const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

    const buf = Buffer.of(1, 2, 3)
    console.log(buf.join()) // Expected output: "1,2,3"
    console.log(buf.join(" / ")) // Expected output: "1 / 2 / 3"
    console.log(buf.join('')) // Expected output: "123"
    })()
    keys: () => ArrayIterator<number>

    Returns a new array iterator object that contains the keys for each index in the Buffer.

    Type Declaration

      • (): ArrayIterator<number>
      • Returns ArrayIterator<number>

        A new iterable iterator object.

    ;(async function () {
    const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

    const buf = Buffer.of(10, 20, 30, 40, 50)
    for (const key of buf.keys()) console.log(key)
    })()
    map: (
        callbackfn: (value: number, index: number, array: this) => number,
        thisArg?: any,
    ) => this

    Creates a new Buffer populated with the results of calling a provided function on every element in the calling Buffer.

    Type Declaration

      • (
            callbackfn: (value: number, index: number, array: this) => number,
            thisArg?: any,
        ): this
      • Parameters

        • callbackfn: (value: number, index: number, array: this) => number

          A function to execute for each element in the Buffer. Its return value is added as a single element in the new Buffer. The function is called with the following arguments:

          • value: The current element being processed in the Buffer.
          • index: The index of the current element being processed in the Buffer.
          • array: The Buffer map() was called upon.
        • OptionalthisArg: any

          A value to use as this when executing callbackfn.

        Returns this

        A new Buffer with each element being the result of the callback function.

    ;(async function () {
    const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

    const buf = Buffer.of(1, 4, 9)
    console.log(buf.map(Math.sqrt).toString('hex')) // Expected output: "010203"
    console.log(buf.toString('hex')) // Expected output: "010409"
    })()
    reduce: <T = number>(
        callbackfn: (
            previousValue: T,
            currentValue: number,
            currentIndex: number,
            array: this,
        ) => T,
        initialValue?: T,
    ) => T

    Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.

    Type Declaration

      • <T = number>(
            callbackfn: (
                previousValue: T,
                currentValue: number,
                currentIndex: number,
                array: this,
            ) => T,
            initialValue?: T,
        ): T
      • Type Parameters

        • T = number

        Parameters

        • callbackfn: (previousValue: T, currentValue: number, currentIndex: number, array: this) => T

          A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.

        • OptionalinitialValue: T

          If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.

        Returns T

    ;(async function () {
    const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

    const buf = Buffer.of(0, 1, 2, 3)
    const result = buf.reduce((accumulator, currentValue) => accumulator + currentValue)
    console.log(`result = ${result}`) // result = 6
    })()
    reduceRight: <T = number>(
        callbackfn: (
            previousValue: T,
            currentValue: number,
            currentIndex: number,
            array: this,
        ) => T,
        initialValue?: T,
    ) => T

    Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.

    Type Declaration

      • <T = number>(
            callbackfn: (
                previousValue: T,
                currentValue: number,
                currentIndex: number,
                array: this,
            ) => T,
            initialValue?: T,
        ): T
      • Type Parameters

        • T = number

        Parameters

        • callbackfn: (previousValue: T, currentValue: number, currentIndex: number, array: this) => T

          A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array.

        • OptionalinitialValue: T

          If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.

        Returns T

    ;(async function () {
    const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

    const buf = Buffer.of(10, 20, 30)
    const result = buf.reduceRight((accumulator, currentValue) => `${accumulator}, ${currentValue}`)
    console.log(result) // Expected output: "30, 20, 10"
    })()
    reverse: () => this

    The method reverses a Buffer in place and returns the reference to the same Buffer, the first element now becoming the last, and the last element becoming the first. In other words, elements order in the Buffer will be turned towards the direction opposite to that previously stated.

    ;(async function () {
    const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

    const buf1 = Buffer.from('01020304', 'hex')
    buf1.reverse()
    console.log(buf1.toString('hex')) // Prints: 04030201
    })()
    set: (
        array: Buffer | Uint8Array<ArrayBufferLike> | ArrayLike<number>,
        offset?: number,
    ) => void

    Stores multiple values in the Buffer, reading input values from a specified array.

    Type Declaration

      • (
            array: Buffer | Uint8Array<ArrayBufferLike> | ArrayLike<number>,
            offset?: number,
        ): void
      • Parameters

        • array: Buffer | Uint8Array<ArrayBufferLike> | ArrayLike<number>

          The array from which to copy values. All values from the source array are copied into the Buffer, unless the length of the source array plus the target offset exceeds the length of the Buffer, in which case an exception is thrown. If the source array is a Buffer, the two arrays may share the same underlying ArrayBuffer; the JavaScript engine will intelligently copy the source range of the buffer to the destination range.

        • Optionaloffset: number

          The offset into the Buffer at which to begin writing values from the source array. If this value is omitted, 0 is assumed (that is, the source array will overwrite values in the Buffer starting at index 0).

        Returns void

    ;(async function () {
    const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

    const buf = new Buffer(8)
    buf.set([1, 2, 3], 3)
    console.log(buf.toString('hex')) // Expected output: "0000000102030000"
    })()
    slice: (start?: number, end?: number) => this

    Returns a copy of a portion of a Buffer into a new Buffer object selected from start to end (end not included) where start and end represent the index of items in that buf. The original Buffer will not be modified.

    Type Declaration

      • (start?: number, end?: number): this
      • Parameters

        • Optionalstart: number

          Where the new Buffer will start. Default: 0.

        • Optionalend: number

          Where the new Buffer will end (not inclusive). Default: buf.length.

        Returns this

    This method is different from Node.js's Buffer.slice() method.

    ;(async function () {
    const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

    const buf1 = Buffer.from('1020304050', 'hex')
    const buf2 = buf1.slice(1, 3)
    buf1[1] = 0x60
    console.log(buf1.toString('hex')) // Prints: 1060304050
    console.log(buf2.toString('hex')) // Prints: 2030
    })()
    some: (
        callbackFn: (value: number, index: number, array: this) => any,
        thisArg?: any,
    ) => boolean

    Tests whether at least one element in the Buffer passes the test implemented by the provided function. It returns true if, in the Buffer, it finds an element for which the provided function returns true; otherwise it returns false. It doesn't modify the Buffer.

    Type Declaration

      • (
            callbackFn: (value: number, index: number, array: this) => any,
            thisArg?: any,
        ): boolean
      • Parameters

        • callbackFn: (value: number, index: number, array: this) => any

          A function to execute for each element in the Buffer. It should return a truthy value to indicate the element passes the test, and a falsy value otherwise. The function is called with the following arguments:

          • value: The current element being processed in the Buffer.
          • index: The index of the current element being processed in the Buffer.
          • array: The Buffer some() was called upon.
        • OptionalthisArg: any

          A value to use as this when executing callbackFn.

        Returns boolean

        false unless callbackFn returns a truthy value for a Buffer element, in which case true is immediately returned.

    ;(async function () {
    const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

    const isBiggerThan10 = (value, index, array) => value > 10
    console.log(Buffer.of(2, 5, 8, 1, 4).some(isBiggerThan10)) // Expected output: false
    console.log(Buffer.of(12, 5, 8, 1, 4).some(isBiggerThan10)) // Expected output: true
    })()
    sort: (compareFn?: (a: number, b: number) => any) => this

    The method sorts the elements of a Buffer in place and returns the reference to the same Buffer, now sorted.

    Type Declaration

      • (compareFn?: (a: number, b: number) => any): this
      • Parameters

        • OptionalcompareFn: (a: number, b: number) => any

          A function that determines the order of the elements. The function is called with the following arguments:

          • a: The first element for comparison.
          • b: The second element for comparison. It should return a number where:
          • A negative value indicates that a should come before b.
          • A positive value indicates that a should come after b.
          • Zero or NaN indicates that a and b are considered equal. To memorize this, remember that (a, b) => a - b sorts numbers in ascending order. If omitted, the elements are sorted according to numeric value.

        Returns this

        The reference to the original Buffer, now sorted. Note that the Buffer is sorted in place, and no copy is made.

    ;(async function () {
    const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

    const buf1 = Buffer.from('03010204', 'hex')
    buf1.sort()
    console.log(buf1.toString('hex')) // Prints: 01020304

    buf1.sort((a, b) => b - a)
    console.log(buf1.toString('hex')) // Prints: 04030201
    })()
    subarray: (start?: number, end?: number) => this

    Returns a new Buffer that references the same memory as the original, but offset and cropped by the start and end indexes.

    Specifying end greater than buf.length will return the same result as that of end equal to buf.length.

    Modifying the new Buffer slice will modify the memory in the original Buffer because the allocated memory of the two objects overlap.

    Specifying negative indexes causes the slice to be generated relative to the end of buf rather than the beginning.

    Type Declaration

      • (start?: number, end?: number): this
      • Parameters

        • Optionalstart: number

          Where the new Buffer will start. Default: 0.

        • Optionalend: number

          Where the new Buffer will end (not inclusive). Default: buf.length.

        Returns this

    ;(async function () {
    const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

    const buf1 = Buffer.allocUnsafe(26)
    for (let i = 0; i < 26; i++) buf1[i] = i + 97

    const buf2 = buf1.subarray(0, 3)
    console.log(buf2.toString('ascii', 0, buf2.length)) // Prints: abc

    buf1[0] = 33
    console.log(buf2.toString('ascii', 0, buf2.length)) // Prints: !bc
    })()
    ;(async function () {
    const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

    const buf1 = Buffer.allocUnsafe(26)
    for (let i = 0; i < 26; i++) buf1[i] = i + 97

    const buf2 = buf1.subarray(0, 3)
    console.log(buf2.toString('ascii', 0, buf2.length)) // Prints: abc

    buf1[0] = 33
    console.log(buf2.toString('ascii', 0, buf2.length)) // Prints: !bc
    })()
    toLocaleString: (
        locales?: string | string[],
        options?: NumberFormatOptions,
    ) => string

    Returns a string representing the elements of the Buffer. The elements are converted to strings using their toLocaleString methods and these strings are separated by a locale-specific string (such as a comma ",").

    Type Declaration

      • (locales?: string | string[], options?: NumberFormatOptions): string
      • Parameters

        Returns string

        A string representing the elements of the Buffer.

    ;(async function () {
    const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

    const buf = Buffer.of(200, 50, 81, 12, 42)
    console.log(buf.toLocaleString()) // Expected output: "200,50,81,12,42"
    console.log(buf.toLocaleString('en-US')) // Expected output: "200,50,81,12,42"
    console.log(buf.toLocaleString('ja-JP', { style: 'currency', currency: 'JPY' })) // Expected output: "¥200,¥50,¥81,¥12,¥42"
    })()
    values: () => ArrayIterator<number>

    Returns a new array iterator object that iterates the value of each item in the Buffer.

    Type Declaration

      • (): ArrayIterator<number>
      • Returns ArrayIterator<number>

        A new iterable iterator object.

    ;(async function () {
    const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

    const buf1 = Buffer.of(10, 20, 30, 40, 50)
    for (const n of buf1.values()) console.log(n)

    const values = buf1.values()
    console.log(values.next().value) // Expected output: 10
    console.log(values.next().value) // Expected output: 20
    console.log(values.next().value) // Expected output: 30
    console.log(values.next().value) // Expected output: 40
    console.log(values.next().value) // Expected output: 50
    })()
    • Calculates the Bitwise AND of all bytes in this. If this is empty, returns 0xFF. You can use Buffer#subarray to calculate the Bitwise AND of a subset of this.

      Returns number

      The Bitwise AND of all bytes in buf.

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf = Buffer.from('010203040506070809', 'hex')
      console.log(buf.and()) // Prints: 0
      })()
    • The method Bitwise AND every bytes with other in place and returns this. If length of other is shorter than this, the remaining bytes in this will not be changed. If length of other is longer than this, the remaining bytes in other will be ignored.

      Parameters

      • other: Buffer

        A Buffer to Bitwise AND with.

      Returns this

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf1 = Buffer.from('010203', 'hex')
      const buf2 = Buffer.from('102030', 'hex')
      console.log(buf1.and(buf2).toString('hex')) // Prints: 000000
      console.log(buf1.toString('hex')) // Prints: 000000
      })()
    • Creates an array of chunk Buffers which length is bytesPerChunk. If buf's contents can't be split evenly, the final chunk will be the remaining contents.

      Parameters

      • bytesPerChunk: number

        The length of each chunk

      Returns Buffer[]

      The new array of chunks.

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf = Buffer.from('010203040506070809', 'hex')
      console.log(buf.chunk(4).map(chunk => chunk.toString('hex')))
      // Prints: ['01020304', '05060708', '09']
      })()
    • Compares buf with target and returns a number indicating whether buf comes before, after, or is the same as target in sort order. Comparison is based on the actual sequence of bytes in each Buffer.

      The optional targetStart, targetEnd, sourceStart, and sourceEnd arguments can be used to limit the comparison to specific ranges within target and buf respectively.

      Parameters

      • target: any

        A Buffer or Uint8Array with which to compare buf.

      • targetStart: number = 0

        The offset within target at which to begin comparison. Default: 0.

      • targetEnd: number = target.length

        The offset within target at which to end comparison (not inclusive). Default: target.length.

      • sourceStart: number = 0

        The offset within buf at which to begin comparison. Default: 0.

      • sourceEnd: number = ...

        The offset within buf at which to end comparison (not inclusive). Default: this.length.

      Returns -1 | 0 | 1

      • 0 is returned if target is the same as buf
      • 1 is returned if target should come before buf when sorted.
      • -1 is returned if target should come after buf when sorted.
      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf1 = Buffer.from('ABC')
      const buf2 = Buffer.from('BCD')
      const buf3 = Buffer.from('ABCD')

      console.log(buf1.compare(buf1)) // Prints: 0
      console.log(buf1.compare(buf2)) // Prints: -1
      console.log(buf1.compare(buf3)) // Prints: -1
      console.log(buf2.compare(buf1)) // Prints: 1
      console.log(buf2.compare(buf3)) // Prints: 1

      console.log([buf1, buf2, buf3].sort(Buffer.compare).map(buf => buf.toString()))
      // Prints: ['ABC', 'ABCD', 'BCD']
      })()
      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf1 = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8, 9])
      const buf2 = Buffer.from([5, 6, 7, 8, 9, 1, 2, 3, 4])

      console.log(buf1.compare(buf2, 5, 9, 0, 4)) // Prints: 0
      console.log(buf1.compare(buf2, 0, 6, 4)) // Prints: -1
      console.log(buf1.compare(buf2, 5, 6, 5)) // Prints: 1
      })()
    • Copies data from a region of buf to a region in target, even if the target memory region overlaps with buf.

      TypedArray.prototype.set() performs the same operation, and is available for all TypedArrays, including Node.js Buffers, although it takes different function arguments.

      Parameters

      • target: ArrayBufferView

        A Buffer or Uint8Array to copy into.

      • targetStart: number = 0

        The offset within target at which to begin writing. Default: 0.

      • sourceStart: number = 0

        The offset within buf from which to begin copying. Default: 0.

      • sourceEnd: number = ...

        The offset within buf at which to stop copying (not inclusive). Default: this.length.

      Returns number

      The number of bytes copied.

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf1 = Buffer.allocUnsafe(26)
      const buf2 = Buffer.allocUnsafe(26).fill('!')

      // 97 is the decimal ASCII value for 'a'.
      for (let i = 0; i < 26; i++) buf1[i] = i + 97

      // Copy `buf1` bytes 16 through 19 into `buf2` starting at byte 8 of `buf2`.
      buf1.copy(buf2, 8, 16, 20)
      // This is equivalent to:
      // buf2.set(buf1.subarray(16, 20), 8)

      console.log(buf2.toString('ascii', 0, 25))
      // Prints: !!!!!!!!qrst!!!!!!!!!!!!!
      })()
      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      // Create a `Buffer` and copy data from one region to an overlapping region within the same `Buffer`.
      const buf = Buffer.allocUnsafe(26)

      // 97 is the decimal ASCII value for 'a'.
      for (let i = 0; i < 26; i++) buf[i] = i + 97
      buf.copy(buf, 0, 4, 10)

      console.log(buf.toString())
      // Prints: efghijghijklmnopqrstuvwxyz
      })()
    • Parameters

      • otherBuffer: Buffer | Uint8Array<ArrayBufferLike>

        A Buffer or Uint8Array with which to compare buf.

      Returns boolean

      true if both buf and otherBuffer have exactly the same bytes, false otherwise. Equivalent to buf.compare(otherBuffer) === 0.

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf1 = Buffer.from('ABC')
      const buf2 = Buffer.from('414243', 'hex')
      const buf3 = Buffer.from('ABCD')

      console.log(buf1.equals(buf2)) // Prints: true
      console.log(buf1.equals(buf3)) // Prints: false
      })()
    • Fill the entire buf with the specified value.

      Parameters

      • value: string

        The value with which to fill buf. Empty string is coerced to 0.

      • Optionalencoding:
            | "base64"
            | "binary"
            | "ucs-2"
            | "utf-16le"
            | "utf-8"
            | "ascii"
            | "base64url"
            | "hex"
            | "latin1"
            | "ucs2"
            | "utf16le"
            | "utf8"

        The encoding for value. Default: 'utf8'.

      Returns this

    • Fill the buf with the specified value start from offset.

      Parameters

      • value: string

        The value with which to fill buf. Empty string is coerced to 0.

      • offset: number

        Number of bytes to skip before starting to fill buf. Default: 0.

      • Optionalencoding:
            | "base64"
            | "binary"
            | "ucs-2"
            | "utf-16le"
            | "utf-8"
            | "ascii"
            | "base64url"
            | "hex"
            | "latin1"
            | "ucs2"
            | "utf16le"
            | "utf8"

        The encoding for value. Default: 'utf8'.

      Returns this

    • Fill the buf with the specified value start from offset and stop before end.

      Parameters

      • value: string

        The value with which to fill buf. Empty string is coerced to 0.

      • offset: number

        Number of bytes to skip before starting to fill buf. Default: 0.

      • end: number

        Where to stop filling buf (not inclusive). Default: buf.length.

      • Optionalencoding:
            | "base64"
            | "binary"
            | "ucs-2"
            | "utf-16le"
            | "utf-8"
            | "ascii"
            | "base64url"
            | "hex"
            | "latin1"
            | "ucs2"
            | "utf16le"
            | "utf8"

        The encoding for value. Default: 'utf8'.

      Returns this

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      // Fill a `Buffer` with the ASCII character 'h'.
      const b = Buffer.allocUnsafe(10).fill('h')
      console.log(b.toString()) // Prints: hhhhhhhhhh

      // Fill a buffer with empty string
      const c = Buffer.allocUnsafe(5).fill('')
      console.log(c.toString('hex')) // Prints: 0000000000
      })()

      If the final write of a fill() operation falls on a multi-byte character, then only the bytes of that character that fit into buf are written:

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      // Fill a `Buffer` with character that takes up two bytes in UTF-8.
      const b = Buffer.allocUnsafe(5).fill('\u0222')
      console.log(b.toString('hex')) // Prints: c8a2c8a2c8
      })()

      If value contains invalid characters, it is truncated; if no valid fill data remains, an exception is thrown:

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf = Buffer.allocUnsafe(5)

      console.log(buf.fill('a').toString('hex')) // Prints: 6161616161
      console.log(buf.fill('aazz', 'hex').toString('hex')) // Prints: aaaaaaaaaa
      console.log(buf.fill('zz', 'hex').toString('hex')) // Throws an exception.
      })()
    • Fill buf with the specified value. If the offset and end are not given, the entire buf will be filled.

      Parameters

      • value: number | Buffer | Uint8Array<ArrayBufferLike>

        The value with which to fill buf. Empty value (Uint8Array, Buffer) is coerced to 0. value is coerced to a uint32 value if it is not a string, Buffer, or integer. If the resulting integer is greater than 255 (decimal), buf will be filled with value & 255.

      • Optionaloffset: number

        Number of bytes to skip before starting to fill buf. Default: 0.

      • Optionalend: number

        Where to stop filling buf (not inclusive). Default: buf.length.

      Returns this

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      // Fill a `Buffer` with a Buffer
      const buf1 = Buffer.allocUnsafe(10).fill(Buffer.of(65))
      console.log(buf1.toString()) // Prints: AAAAAAAAAA

      // Fill a `Buffer` with an Uint8Array
      const buf2 = Buffer.allocUnsafe(10).fill(Uint8Array.of(65))
      console.log(buf2.toString()) // Prints: AAAAAAAAAA

      // Fill a `Buffer` with number
      const buf3 = Buffer.allocUnsafe(10).fill(65)
      console.log(buf3.toString()) // Prints: AAAAAAAAAA
      })()
    • Parameters

      • byteOffset: number
      • OptionallittleEndian: boolean

      Returns bigint

    • Parameters

      • byteOffset: number
      • OptionallittleEndian: boolean

      Returns bigint

    • Polyfill of DataView.getFloat16.

      Parameters

      • byteOffset: number
      • littleEndian: boolean = false

      Returns number

    • Parameters

      • byteOffset: number
      • OptionallittleEndian: boolean

      Returns number

    • Parameters

      • byteOffset: number
      • OptionallittleEndian: boolean

      Returns number

    • Parameters

      • byteOffset: number
      • OptionallittleEndian: boolean

      Returns number

    • Parameters

      • byteOffset: number
      • OptionallittleEndian: boolean

      Returns number

    • Parameters

      • byteOffset: number
      • OptionallittleEndian: boolean

      Returns number

    • Parameters

      • byteOffset: number
      • OptionallittleEndian: boolean

      Returns number

    • Equivalent to buf.indexOf() !== -1.

      Parameters

      • value: string

        What to search for.

      • Optionalencoding:
            | "base64"
            | "binary"
            | "ucs-2"
            | "utf-16le"
            | "utf-8"
            | "ascii"
            | "base64url"
            | "hex"
            | "latin1"
            | "ucs2"
            | "utf16le"
            | "utf8"

        The encoding of value. Default: 'utf8'.

      Returns boolean

      true if value was found in buf, false otherwise.

    • Equivalent to buf.indexOf() !== -1.

      Parameters

      • value: string

        What to search for.

      • byteOffset: number

        Where to begin searching in buf. If negative, then offset is calculated from the end of buf. Default: 0.

      • Optionalencoding:
            | "base64"
            | "binary"
            | "ucs-2"
            | "utf-16le"
            | "utf-8"
            | "ascii"
            | "base64url"
            | "hex"
            | "latin1"
            | "ucs2"
            | "utf16le"
            | "utf8"

        The encoding of value. Default: 'utf8'.

      Returns boolean

      true if value was found in buf, false otherwise.

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf = Buffer.from('this is a buffer')
      console.log(buf.includes('this')) // Prints: true
      console.log(buf.includes('is')) // Prints: true
      console.log(buf.includes('this', 4)) // Prints: false
      })()
    • Equivalent to buf.indexOf() !== -1.

      Parameters

      • value: number | Buffer | Uint8Array<ArrayBufferLike>

        What to search for.

      • OptionalbyteOffset: number

        Where to begin searching in buf. If negative, then offset is calculated from the end of buf. Default: 0.

      Returns boolean

      true if value was found in buf, false otherwise.

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf = Buffer.from('this is a buffer')
      console.log(buf.includes(Buffer.from('a buffer'))) // Prints: true
      console.log(buf.includes(97)) // Prints: true (97 is the decimal ASCII value for 'a')
      console.log(buf.includes(Uint8Array.of(97))) // Prints: true (97 is the decimal ASCII value for 'a')
      console.log(buf.includes(Buffer.from('a buffer example'))) // Prints: false
      console.log(buf.includes(Buffer.from('a buffer example').slice(0, 8))) // Prints: true
      })()
    • Parameters

      • value: string

        What to search for.

        • If value is a string, value is interpreted according to the character encoding in encoding.
        • If value is a Buffer or Uint8Array, value will be used in its entirety. To compare a partial Buffer, use Buffer#subarray.
        • If value is a number, it will be coerced to a valid byte value, an integer between 0 and 255.
        • If value is an empty string or empty Buffer and byteOffset is less than buf.length, byteOffset will be returned.
        • If value is empty and byteOffset is at least buf.length, buf.length will be returned.
      • Optionalencoding:
            | "base64"
            | "binary"
            | "ucs-2"
            | "utf-16le"
            | "utf-8"
            | "ascii"
            | "base64url"
            | "hex"
            | "latin1"
            | "ucs2"
            | "utf16le"
            | "utf8"

        The encoding of value. Default: 'utf8'.

      Returns number

      • The index of the first occurrence of value in buf
      • -1 if buf does not contain value.
      • If value is not a string, number, or Buffer, this method will throw a TypeError.
    • Parameters

      • value: string

        What to search for.

        • If value is a string, value is interpreted according to the character encoding in encoding.
        • If value is a Buffer or Uint8Array, value will be used in its entirety. To compare a partial Buffer, use Buffer#subarray.
        • If value is a number, it will be coerced to a valid byte value, an integer between 0 and 255.
        • If value is an empty string or empty Buffer and byteOffset is less than buf.length, byteOffset will be returned.
        • If value is empty and byteOffset is at least buf.length, buf.length will be returned.
      • byteOffset: number

        Where to begin searching in buf. Default: 0.

        • If negative, then offset is calculated from the end of buf.
        • If not a integer, it will be coerced to integer by _.toSafeInteger.
      • Optionalencoding:
            | "base64"
            | "binary"
            | "ucs-2"
            | "utf-16le"
            | "utf-8"
            | "ascii"
            | "base64url"
            | "hex"
            | "latin1"
            | "ucs2"
            | "utf16le"
            | "utf8"

        The encoding of value. Default: 'utf8'.

      Returns number

      • The index of the first occurrence of value in buf
      • -1 if buf does not contain value.
      • If value is not a string, number, or Buffer, this method will throw a TypeError.
      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf = Buffer.from('this is a buffer')
      console.log(buf.indexOf('this')) // Prints: 0
      console.log(buf.indexOf('is')) // Prints: 2

      const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le')
      console.log(utf16Buffer.indexOf('\u03a3', 0, 'utf16le')) // Prints: 4
      console.log(utf16Buffer.indexOf('\u03a3', -4, 'utf16le')) // Prints: 6
      })()
      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const b = Buffer.from('abcdef')

      // Passing a byteOffset that coerces to 0.
      // Prints: 1, searching the whole buffer.
      console.log(b.indexOf('b', undefined))
      console.log(b.indexOf('b', {}))
      console.log(b.indexOf('b', null))
      console.log(b.indexOf('b', []))
      })()
    • Parameters

      • value: number | Buffer | Uint8Array<ArrayBufferLike>

        What to search for.

        • If value is a string, value is interpreted according to the character encoding in encoding.
        • If value is a Buffer or Uint8Array, value will be used in its entirety. To compare a partial Buffer, use Buffer#subarray.
        • If value is a number, it will be coerced to a valid byte value, an integer between 0 and 255.
        • If value is an empty string or empty Buffer and byteOffset is less than buf.length, byteOffset will be returned.
        • If value is empty and byteOffset is at least buf.length, buf.length will be returned.
      • OptionalbyteOffset: number

        Where to begin searching in buf. Default: 0.

        • If negative, then offset is calculated from the end of buf.
        • If not a integer, it will be coerced to integer by _.toSafeInteger.

      Returns number

      • The index of the first occurrence of value in buf
      • -1 if buf does not contain value.
      • If value is not a string, number, or Buffer, this method will throw a TypeError.
      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf = Buffer.from('this is a buffer')
      console.log(buf.indexOf(Buffer.from('a buffer'))) // Prints: 8
      console.log(buf.indexOf(97)) // Prints: 8 (97 is the decimal ASCII value for 'a')
      console.log(buf.indexOf(Buffer.from('a buffer example'))) // Prints: -1
      console.log(buf.indexOf(Buffer.from('a buffer example').slice(0, 8))) // Prints: 8
      })()
      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const b = Buffer.from('abcdef')

      // Passing a value that's a number, but not a valid byte.
      // Prints: 2, equivalent to searching for 99 or 'c'.
      console.log(b.indexOf(99.9))
      console.log(b.indexOf(256 + 99))
      })()
    • Iteratively unpack from the buf according to the format string format. This method returns an iterator which will read equally sized chunks from the buf until remaining contents smaller then the size required by the format, as reflected by Buffer.packCalcSize.

      Type Parameters

      • T extends any[]

      Parameters

      Returns Generator<T>

      A RangeError if the format requires 0 bytes, since such an iterator would never consume the buf.

      Unlike Python struct, this method does not support native size and alignment (that wouldn't make much sense in a javascript). Instead, specify byte order and emit pad bytes explicitly.

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf1 = Buffer.from('01fe01fe', 'hex')
      console.log([...buf1.iterUnpack('!BB')]) // Prints: [[1, 254], [1, 254]]
      })()
    • Identical to Buffer#indexOf, except the last occurrence of value is found rather than the first occurrence.

      Parameters

      • value: string

        What to search for.

        • If value is a string, value is interpreted according to the character encoding in encoding.
        • If value is a Buffer or Uint8Array, value will be used in its entirety. To compare a partial Buffer, use Buffer#subarray.
        • If value is a number, it will be coerced to a valid byte value, an integer between 0 and 255.
        • If value is an empty string or empty Buffer, byteOffset will be returned.
      • Optionalencoding:
            | "base64"
            | "binary"
            | "ucs-2"
            | "utf-16le"
            | "utf-8"
            | "ascii"
            | "base64url"
            | "hex"
            | "latin1"
            | "ucs2"
            | "utf16le"
            | "utf8"

        The encoding of value. Default: 'utf8'.

      Returns number

      • The index of the last occurrence of value in buf
      • -1 if buf does not contain value.
      • If value is not a string, number, or Buffer, this method will throw a TypeError.
    • Identical to Buffer#indexOf, except the last occurrence of value is found rather than the first occurrence.

      Parameters

      • value: string

        What to search for.

        • If value is a string, value is interpreted according to the character encoding in encoding.
        • If value is a Buffer or Uint8Array, value will be used in its entirety. To compare a partial Buffer, use Buffer#subarray.
        • If value is a number, it will be coerced to a valid byte value, an integer between 0 and 255.
        • If value is an empty string or empty Buffer, byteOffset will be returned.
      • byteOffset: number

        Where to begin searching in buf. Default: buf.length - 1.

        • If negative, then offset is calculated from the end of buf.
        • If not a integer, it will be coerced to integer by _.toSafeInteger.
      • Optionalencoding:
            | "base64"
            | "binary"
            | "ucs-2"
            | "utf-16le"
            | "utf-8"
            | "ascii"
            | "base64url"
            | "hex"
            | "latin1"
            | "ucs2"
            | "utf16le"
            | "utf8"

        The encoding of value. Default: 'utf8'.

      Returns number

      • The index of the last occurrence of value in buf
      • -1 if buf does not contain value.
      • If value is not a string, number, or Buffer, this method will throw a TypeError.
      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf = Buffer.from('this buffer is a buffer')

      console.log(buf.lastIndexOf('this')) // Prints: 0
      console.log(buf.lastIndexOf('buffer')) // Prints: 17
      console.log(buf.lastIndexOf('buffer', 5)) // Prints: 5
      console.log(buf.lastIndexOf('buffer', 4)) // Prints: -1

      const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le')
      console.log(utf16Buffer.lastIndexOf('\u03a3', undefined, 'utf16le')) // Prints: 6
      console.log(utf16Buffer.lastIndexOf('\u03a3', -5, 'utf16le')) // Prints: 4
      })()
      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const b = Buffer.from('abcdef')

      // Passing a byteOffset that coerces to NaN.
      // Prints: 1, searching the whole buffer.
      console.log(b.lastIndexOf('b', undefined))
      console.log(b.lastIndexOf('b', {}))

      // Passing a byteOffset that coerces to 0.
      // Prints: -1, equivalent to passing 0.
      console.log(b.lastIndexOf('b', null))
      console.log(b.lastIndexOf('b', []))
      })()
    • Identical to Buffer#indexOf, except the last occurrence of value is found rather than the first occurrence.

      Parameters

      • value: number | Buffer | Uint8Array<ArrayBufferLike>

        What to search for.

        • If value is a number, it will be coerced to a valid byte value, an integer between 0 and 255.
        • If value is an empty string or empty Buffer, byteOffset will be returned.
      • OptionalbyteOffset: number

        Where to begin searching in buf. Default: buf.length - 1.

        • If negative, then offset is calculated from the end of buf.
        • If not a integer, it will be coerced to integer by _.toSafeInteger.

      Returns number

      • The index of the last occurrence of value in buf
      • -1 if buf does not contain value.
      • If value is not a string, number, or Buffer, this method will throw a TypeError.
      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf = Buffer.from('this buffer is a buffer')

      console.log(buf.lastIndexOf(Buffer.from('buffer'))) // Prints: 17
      console.log(buf.lastIndexOf(97)) // Prints: 15 (97 is the decimal ASCII value for 'a')
      console.log(buf.lastIndexOf(Buffer.from('yolo'))) // Prints: -1
      })()
      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const b = Buffer.from('abcdef')

      // Passing a value that's a number, but not a valid byte.
      // Prints: 2, equivalent to searching for 99 or 'c'.
      console.log(b.lastIndexOf(99.9))
      console.log(b.lastIndexOf(256 + 99))
      })()
    • The method Bitwise NOT every bytes in this in place and returns this.

      Returns this

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf = Buffer.from('00010203', 'hex')
      console.log(buf.not().toString('hex')) // Prints: fffefdfc
      console.log(buf.toString('hex')) // Prints: fffefdfc
      })()
    • Calculates the Bitwise OR of all bytes in buf. If buf is empty, returns 0. You can use Buffer#subarray to calculate the Bitwise OR of a subset of buf.

      Returns number

      The Bitwise OR of all bytes in buf.

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf = Buffer.from('010203040506070809', 'hex')
      console.log(buf.or()) // Prints: 15
      })()
    • The method Bitwise OR every bytes with other in place and returns this. If length of other is shorter than this, the remaining bytes in this will not be changed. If length of other is longer than this, the remaining bytes in other will be ignored.

      Parameters

      • other: Buffer

        A Buffer to Bitwise OR with.

      Returns this

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf1 = Buffer.from('010203', 'hex')
      const buf2 = Buffer.from('102030', 'hex')
      console.log(buf1.or(buf2).toString('hex')) // Prints: 112233
      console.log(buf1.toString('hex')) // Prints: 112233
      })()
    • Pack vals into buf according to the format string format. The arguments must match the vals required by the format exactly. The buf’s size in bytes must larger then the size required by the format, as reflected by Buffer.packCalcSize.

      Parameters

      • format: string

        A format string. Please refer to Buffer.packParseFormat for more information.

      • ...vals: any[]

        Values to pack.

      Returns this

      Unlike Python struct, this method does not support native size and alignment (that wouldn't make much sense in a javascript). Instead, specify byte order and emit pad bytes explicitly.

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf1 = Buffer.alloc(3)
      buf1.pack('>h', 0x0102)
      console.log(buf1.toString('hex')) // Prints: 010200

      const buf2 = Buffer.alloc(3)
      buf2.subarray(1).pack('>h', 0x0102) // struct.pack_into
      console.log(buf2.toString('hex')) // Prints: 000102
      })()
    • Reads a signed, big-endian 64-bit integer from buf at the specified offset. Integers read from a Buffer are interpreted as two's complement signed values.

      Parameters

      • offset: number = 0

        Number of bytes to skip before starting to read. Must satisfy: 0 <= offset <= buf.length - 8. Default: 0.

      Returns bigint

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf = Buffer.from('00000000ffffffff', 'hex')
      console.log(buf.readBigInt64BE(0)) // Prints: 4294967295n
      })()
    • Reads a signed, little-endian 64-bit integer from buf at the specified offset. Integers read from a Buffer are interpreted as two's complement signed values.

      Parameters

      • offset: number = 0

        Number of bytes to skip before starting to read. Must satisfy: 0 <= offset <= buf.length - 8. Default: 0.

      Returns bigint

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf = Buffer.from('00000000ffffffff', 'hex')
      console.log(buf.readBigInt64LE(0)) // Prints: -4294967296n
      })()
    • Reads an unsigned, big-endian 64-bit integer from buf at the specified offset.

      Parameters

      • offset: number = 0

        Number of bytes to skip before starting to read. Must satisfy: 0 <= offset <= buf.length - 8. Default: 0.

      Returns bigint

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf = Buffer.from('00000000ffffffff', 'hex')
      console.log(buf.readBigUInt64BE(0)) // Prints: 4294967295n
      })()
    • Reads an unsigned, little-endian 64-bit integer from buf at the specified offset.

      Parameters

      • offset: number = 0

        Number of bytes to skip before starting to read. Must satisfy: 0 <= offset <= buf.length - 8. Default: 0.

      Returns bigint

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf = Buffer.from('00000000ffffffff', 'hex')
      console.log(buf.readBigUInt64LE(0)) // Prints: 18446744069414584320n
      })()
    • Treat the buffer as a least significant bit array and read a bit at the specified bit offset.

      Parameters

      • bitOffset: number

        bit offset to read from.

      Returns number

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf = Buffer.from([0b10010110])
      const bits = new Array(8)
      for (let i = 0; i < 8; i++) bits[i] = buf.readBitLSB(i)
      console.log(bits) // Prints: [0, 1, 1, 0, 1, 0, 0, 1]
      })()
    • Treat buf as a most-significant bit array and read a bit at the specified bit offset.

      Parameters

      • bitOffset: number

        bit offset to read from.

      Returns number

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf = Buffer.from([0b10010110])
      const bits = new Array(8)
      for (let i = 0; i < 8; i++) bits[i] = buf.readBitMSB(i)
      console.log(bits) // Prints: [1, 0, 0, 1, 0, 1, 1, 0]
      })()
    • Reads a 64-bit, big-endian double from buf at the specified offset.

      Parameters

      • offset: number = 0

        Number of bytes to skip before starting to read. Must satisfy 0 <= offset <= buf.length - 8. Default: 0.

      Returns number

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf = Buffer.from('0102030405060708', 'hex')
      console.log(buf.readDoubleBE(0)) // Prints: 8.20788039913184e-304
      })()
    • Reads a 64-bit, little-endian double from buf at the specified offset.

      Parameters

      • offset: number = 0

        Number of bytes to skip before starting to read. Must satisfy 0 <= offset <= buf.length - 8. Default: 0.

      Returns number

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf = Buffer.from('0102030405060708', 'hex')
      console.log(buf.readDoubleLE(0)) // Prints: 5.447603722011605e-270
      })()
    • Reads a 16-bit, big-endian float from buf at the specified offset.

      Parameters

      • offset: number = 0

        Number of bytes to skip before starting to read. Must satisfy 0 <= offset <= buf.length - 2. Default: 0.

      Returns number

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      console.log(Buffer.from('0000', 'hex').readFloat16BE(0)) // Prints: 0
      console.log(Buffer.from('8000', 'hex').readFloat16BE(0)) // Prints: -0
      console.log(Buffer.from('3c00', 'hex').readFloat16BE(0)) // Prints: 1
      console.log(Buffer.from('bc00', 'hex').readFloat16BE(0)) // Prints: -1
      console.log(Buffer.from('7c00', 'hex').readFloat16BE(0)) // Prints: Infinity
      console.log(Buffer.from('fc00', 'hex').readFloat16BE(0)) // Prints: -Infinity
      console.log(Buffer.from('7e00', 'hex').readFloat16BE(0)) // Prints: NaN
      console.log(Buffer.from('fe00', 'hex').readFloat16BE(0)) // Prints: NaN
      })()
    • Reads a 16-bit, little-endian float from buf at the specified offset.

      Parameters

      • offset: number = 0

        Number of bytes to skip before starting to read. Must satisfy 0 <= offset <= buf.length - 2. Default: 0.

      Returns number

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      console.log(Buffer.from('0000', 'hex').readFloat16LE(0)) // Prints: 0
      console.log(Buffer.from('0080', 'hex').readFloat16LE(0)) // Prints: -0
      console.log(Buffer.from('003c', 'hex').readFloat16LE(0)) // Prints: 1
      console.log(Buffer.from('00bc', 'hex').readFloat16LE(0)) // Prints: -1
      console.log(Buffer.from('007c', 'hex').readFloat16LE(0)) // Prints: Infinity
      console.log(Buffer.from('00fc', 'hex').readFloat16LE(0)) // Prints: -Infinity
      console.log(Buffer.from('007e', 'hex').readFloat16LE(0)) // Prints: NaN
      console.log(Buffer.from('00fe', 'hex').readFloat16LE(0)) // Prints: NaN
      })()
    • Reads a 32-bit, big-endian float from buf at the specified offset.

      Parameters

      • offset: number = 0

        Number of bytes to skip before starting to read. Must satisfy 0 <= offset <= buf.length - 4. Default: 0.

      Returns number

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf = Buffer.from('01020304', 'hex')
      console.log(buf.readFloatBE(0)) // Prints: 2.387939260590663e-38
      })()
    • Reads a 32-bit, little-endian float from buf at the specified offset.

      Parameters

      • offset: number = 0

        Number of bytes to skip before starting to read. Must satisfy 0 <= offset <= buf.length - 4. Default: 0.

      Returns number

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf = Buffer.from('01020304', 'hex')
      console.log(buf.readFloatLE(0)) // Prints: 1.539989614439558e-36
      })()
    • Reads a signed, big-endian 16-bit integer from buf at the specified offset. Integers read from a Buffer are interpreted as two's complement signed values.

      Parameters

      • offset: number = 0

        Number of bytes to skip before starting to read. Must satisfy 0 <= offset <= buf.length - 2. Default: 0.

      Returns number

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf = Buffer.from([0, 5])
      console.log(buf.readInt16BE(0)) // Prints: 5
      })()
    • Reads a signed, little-endian 16-bit integer from buf at the specified offset. Integers read from a Buffer are interpreted as two's complement signed values.

      Parameters

      • offset: number = 0

        Number of bytes to skip before starting to read. Must satisfy 0 <= offset <= buf.length - 2. Default: 0.

      Returns number

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf = Buffer.from([0, 5])
      console.log(buf.readInt16LE(0)) // Prints: 1280
      })()
    • Reads a signed, big-endian 32-bit integer from buf at the specified offset. Integers read from a Buffer are interpreted as two's complement signed values.

      Parameters

      • offset: number = 0

        Number of bytes to skip before starting to read. Must satisfy 0 <= offset <= buf.length - 4. Default: 0.

      Returns number

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf = Buffer.from([0, 0, 0, 5])
      console.log(buf.readInt32BE(0)) // Prints: 5
      })()
    • Reads a signed, little-endian 32-bit integer from buf at the specified offset. Integers read from a Buffer are interpreted as two's complement signed values.

      Parameters

      • offset: number = 0

        Number of bytes to skip before starting to read. Must satisfy 0 <= offset <= buf.length - 4. Default: 0.

      Returns number

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf = Buffer.from([0, 0, 0, 5])
      console.log(buf.readInt32LE(0)) // Prints: 83886080
      })()
    • Reads a signed 8-bit integer from buf at the specified offset. Integers read from a Buffer are interpreted as two's complement signed values.

      Parameters

      • offset: number = 0

        Number of bytes to skip before starting to read. Must satisfy 0 <= offset <= buf.length - 1. Default: 0.

      Returns number

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf = Buffer.from([-1, 5])
      console.log(buf.readInt8(0)) // Prints: -1
      console.log(buf.readInt8(1)) // Prints: 5
      })()
    • Reads byteLength number of bytes from buf at the specified offset and interprets the result as a big-endian, two's complement signed value supporting up to 48 bits of accuracy.

      Parameters

      • offset: number = 0

        Number of bytes to skip before starting to read. Must satisfy 0 <= offset <= buf.length - byteLength.

      • byteLength: number = 6

        Number of bytes to read. Must satisfy 1 <= byteLength <= 6.

      Returns number

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab])
      console.log(buf.readIntBE(0, 6).toString(16)) // Prints: 1234567890ab
      })()
    • Reads byteLength number of bytes from buf at the specified offset and interprets the result as a little-endian, two's complement signed value supporting up to 48 bits of accuracy.

      Parameters

      • offset: number = 0

        Number of bytes to skip before starting to read. Must satisfy 0 <= offset <= buf.length - byteLength.

      • byteLength: number = 6

        Number of bytes to read. Must satisfy 1 <= byteLength <= 6.

      Returns number

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab])
      console.log(buf.readIntLE(0, 6).toString(16)) // Prints: -546f87a9cbee
      })()
    • Reads an unsigned, big-endian 16-bit integer from buf at the specified offset.

      Parameters

      • offset: number = 0

        Number of bytes to skip before starting to read. Must satisfy 0 <= offset <= buf.length - 2. Default: 0.

      Returns number

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf = Buffer.from([0x12, 0x34, 0x56])
      console.log(buf.readUInt16BE(0).toString(16)) // Prints: 1234
      console.log(buf.readUInt16BE(1).toString(16)) // Prints: 3456
      })()
    • Reads an unsigned, little-endian 16-bit integer from buf at the specified offset.

      Parameters

      • offset: number = 0

        Number of bytes to skip before starting to read. Must satisfy 0 <= offset <= buf.length - 2. Default: 0.

      Returns number

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf = Buffer.from([0x12, 0x34, 0x56])
      console.log(buf.readUInt16LE(0).toString(16)) // Prints: 3412
      console.log(buf.readUInt16LE(1).toString(16)) // Prints: 5634
      })()
    • Reads an unsigned, big-endian 32-bit integer from buf at the specified offset.

      Parameters

      • offset: number = 0

        Number of bytes to skip before starting to read. Must satisfy 0 <= offset <= buf.length - 4. Default: 0.

      Returns number

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf = Buffer.from([0x12, 0x34, 0x56, 0x78])
      console.log(buf.readUInt32BE(0).toString(16)) // Prints: 12345678
      })()
    • Reads an unsigned, little-endian 32-bit integer from buf at the specified offset.

      Parameters

      • offset: number = 0

        Number of bytes to skip before starting to read. Must satisfy 0 <= offset <= buf.length - 4. Default: 0.

      Returns number

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf = Buffer.from([0x12, 0x34, 0x56, 0x78])
      console.log(buf.readUInt32LE(0).toString(16)) // Prints: 78563412
      })()
    • Reads an unsigned 8-bit integer from buf at the specified offset.

      Parameters

      • offset: number = 0

        Number of bytes to skip before starting to read. Must satisfy 0 <= offset <= buf.length - 1. Default: 0.

      Returns number

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf = Buffer.from([1, -2])
      console.log(buf.readUInt8(0)) // Prints: 1
      console.log(buf.readUInt8(1)) // Prints: 254
      })()
    • Reads byteLength number of bytes from buf at the specified offset and interprets the result as an unsigned big-endian integer supporting up to 48 bits of accuracy.

      Parameters

      • offset: number = 0

        Number of bytes to skip before starting to read. Must satisfy 0 <= offset <= buf.length - byteLength.

      • byteLength: number = 6

        Number of bytes to read. Must satisfy 0 < byteLength <= 6.

      Returns number

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab])
      console.log(buf.readUIntBE(0, 6).toString(16)) // Prints: 1234567890ab
      })()
    • Reads byteLength number of bytes from buf at the specified offset and interprets the result as an unsigned big-endian integer supporting up to 48 bits of accuracy.

      Parameters

      • offset: number = 0

        Number of bytes to skip before starting to read. Must satisfy 0 <= offset <= buf.length - byteLength.

      • byteLength: number = 6

        Number of bytes to read. Must satisfy 0 < byteLength <= 6.

      Returns number

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab])
      console.log(buf.readUIntLE(0, 6).toString(16)) // Prints: ab9078563412
      })()
    • Parameters

      • byteOffset: number
      • value: bigint
      • OptionallittleEndian: boolean

      Returns this

    • Parameters

      • byteOffset: number
      • value: bigint
      • OptionallittleEndian: boolean

      Returns this

    • Polyfill of DataView.setFloat16.

      Parameters

      • byteOffset: number
      • value: number
      • littleEndian: boolean = false

      Returns this

    • Parameters

      • byteOffset: number
      • value: number
      • OptionallittleEndian: boolean

      Returns this

    • Parameters

      • byteOffset: number
      • value: number
      • OptionallittleEndian: boolean

      Returns this

    • Parameters

      • byteOffset: number
      • value: number
      • OptionallittleEndian: boolean

      Returns this

    • Parameters

      • byteOffset: number
      • value: number
      • OptionallittleEndian: boolean

      Returns this

    • Parameters

      • byteOffset: number
      • value: number
      • OptionallittleEndian: boolean

      Returns this

    • Parameters

      • byteOffset: number
      • value: number
      • OptionallittleEndian: boolean

      Returns this

    • Interprets buf as an array of unsigned 16-bit integers and swaps the byte order in-place.

      Returns this

      A reference to buf.

      If buf.length is not a multiple of 2, this method will throw a RangeError.

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf1 = Buffer.from('0102030405060708', 'hex')
      console.log(buf1.toString('hex')) // Prints: 0102030405060708
      buf1.swap16()
      console.log(buf1.toString('hex')) // Prints: 0201040306050807

      const utf16 = Buffer.from('This is little-endian UTF-16', 'utf16le')
      utf16.swap16() // Convert to big-endian UTF-16 text.
      })()
    • Interprets buf as an array of unsigned 32-bit integers and swaps the byte order in-place.

      Returns this

      A reference to buf.

      If buf.length is not a multiple of 4, this method will throw a RangeError.

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf1 = Buffer.from('0102030405060708', 'hex')
      console.log(buf1.toString('hex')) // Prints: 0102030405060708
      buf1.swap32()
      console.log(buf1.toString('hex')) // Prints: 0403020108070605
      })()
    • Interprets buf as an array of unsigned 64-bit integers and swaps the byte order in-place.

      Returns this

      A reference to buf.

      If buf.length is not a multiple of 8, this method will throw a RangeError.

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf1 = Buffer.from('0102030405060708', 'hex')
      console.log(buf1.toString('hex')) // Prints: 0102030405060708
      buf1.swap64()
      console.log(buf1.toString('hex')) // Prints: 0807060504030201
      })()
    • The method returns a new Buffer which is the Bitwise AND of this and other. If length of other is shorter than this, the remaining bytes in this will be copied to the new Buffer. If length of other is longer than this, the remaining bytes in other will be ignored.

      Parameters

      • other: Buffer

        A Buffer to Bitwise AND with.

      Returns this

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf1 = Buffer.from('010203', 'hex')
      const buf2 = Buffer.from('102030', 'hex')
      console.log(buf1.toAnded(buf2).toString('hex')) // Prints: 000000
      console.log(buf1.toString('hex')) // Prints: 010203
      })()
    • JSON.stringify() implicitly calls this method when stringifying a Buffer instance. Buffer.from accepts objects in the format returned from this method. In particular, Buffer.from(buf.toJSON()) works like Buffer.from(buf).

      Returns { data: number[]; type: "Buffer" }

      a JSON representation of buf.

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf = Buffer.from('0102030405', 'hex')
      const json = JSON.stringify(buf)
      console.log(json) // Prints: {"type":"Buffer","data":[1,2,3,4,5]}

      const restored = JSON.parse(json, (key, value) => {
      return value && value.type === 'Buffer' ? Buffer.from(value) : value
      })
      console.log(restored.toString('hex')) // Prints: 0102030405
      })()
    • The method returns a new Buffer which is the Bitwise NOT of this.

      Returns this

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf = Buffer.from('00010203', 'hex')
      console.log(buf.toNoted().toString('hex')) // Prints: fffefdfc
      console.log(buf.toString('hex')) // Prints: 00010203
      })()
    • The method returns a new Buffer which is the Bitwise OR of this and other. If length of other is shorter than this, the remaining bytes in this will be copied to the new Buffer. If length of other is longer than this, the remaining bytes in other will be ignored.

      Parameters

      • other: Buffer

        A Buffer to Bitwise OR with.

      Returns this

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf1 = Buffer.from('010203', 'hex')
      const buf2 = Buffer.from('102030', 'hex')
      console.log(buf1.toOred(buf2).toString('hex')) // Prints: 112233
      console.log(buf1.toString('hex')) // Prints: 010203
      })()
    • The method is the copying counterpart of the reverse() method. It returns a new Buffer with the elements in reversed order.

      Returns this

      A new Buffer containing the elements in reversed order.

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf1 = Buffer.from('01020304', 'hex')
      const buf2 = buf1.reverse()
      console.log(buf1.toString('hex')) // Prints: 01020304
      console.log(buf2.toString('hex')) // Prints: 04030201
      })()
    • The method is the copying version of the sort() method. It returns a new Buffer with the elements sorted in ascending order.

      Parameters

      • OptionalcompareFn: (a: number, b: number) => any

        A function that determines the order of the elements. The function is called with the following arguments:

        • a: The first element for comparison.
        • b: The second element for comparison. It should return a number where:
        • A negative value indicates that a should come before b.
        • A positive value indicates that a should come after b.
        • Zero or NaN indicates that a and b are considered equal. To memorize this, remember that (a, b) => a - b sorts numbers in ascending order. If omitted, the elements are sorted according to numeric value.

      Returns this

      A new Buffer with the elements sorted in ascending order.

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf1 = Buffer.from('03010204', 'hex')
      const buf2 = buf1.toSorted()
      console.log(buf1.toString('hex')) // Prints: 03010204
      console.log(buf2.toString('hex')) // Prints: 01020304
      })()
    • Decodes buf to a string according to the specified character encoding in encoding. start and end may be passed to decode only a subset of buf.

      Parameters

      • encoding:
            | "base64"
            | "binary"
            | "ucs-2"
            | "utf-16le"
            | "utf-8"
            | "ascii"
            | "base64url"
            | "hex"
            | "latin1"
            | "ucs2"
            | "utf16le"
            | "utf8" = 'utf8'

        The character encoding to use. Default: 'utf8'.

      • start: number = 0

        The byte offset to start decoding at. Default: 0.

      • end: number = ...

        The byte offset to stop decoding at (not inclusive). Default: buf.length.

      Returns string

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf1 = Buffer.allocUnsafe(26)
      for (let i = 0; i < 26; i++) buf1[i] = i + 97 // 97 is the decimal ASCII value for 'a'.

      console.log(buf1.toString('utf8')) // Prints: abcdefghijklmnopqrstuvwxyz
      console.log(buf1.toString('utf8', 0, 5)) // Prints: abcde

      const buf2 = Buffer.from('tést')
      console.log(buf2.toString('hex')) // Prints: 74c3a97374
      console.log(buf2.toString('utf8', 0, 3)) // Prints: té
      console.log(buf2.toString(undefined, 0, 3)) // Prints: té
      })()
    • The method returns a new Buffer which is the Bitwise XOR of this and other. If length of other is shorter than this, the remaining bytes in this will be copied to the new Buffer. If length of other is longer than this, the remaining bytes in other will be ignored.

      Parameters

      • other: Buffer

        A Buffer to Bitwise XOR with.

      Returns this

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf1 = Buffer.from('010203', 'hex')
      const buf2 = Buffer.from('102030', 'hex')
      console.log(buf1.toXored(buf2).toString('hex')) // Prints: 112233
      console.log(buf1.toString('hex')) // Prints: 010203
      })()
    • Unpack from the buf (presumably packed by pack(format, ...)) according to the format string format. The result is a tuple even if it contains exactly one item. The buf’s size in bytes must larger then the size required by the format, as reflected by Buffer.packCalcSize.

      Type Parameters

      • T extends any[]

      Parameters

      Returns T

      Unlike Python struct, this method does not support native size and alignment (that wouldn't make much sense in a javascript). Instead, specify byte order and emit pad bytes explicitly.

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf1 = Buffer.from('01fe01fe', 'hex')
      console.log(buf1.unpack('!BBbb')) // Prints: [1, 254, 1, -2]
      })()
    • The method is the copying version of using the bracket notation to change the value of a given index. It returns a new Buffer with the element at the given index replaced with the given value.

      Parameters

      • index: number

        Zero-based index at which to change the Buffer, converted to an integer.

      • value: number

        Any value to be assigned to the given index.

      Returns this

      A new Buffer with the element at index replaced with value.

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf1 = Buffer.from('0102030405', 'hex')
      const buf2 = buf1.with(2, 6)
      console.log(buf1.toString('hex')) // Prints: 0102030405
      console.log(buf2.toString('hex')) // Prints: 0102060405
      })()
    • Writes string to buf at offset according to the character encoding inencoding. The length parameter is the number of bytes to write. If buf did not contain enough space to fit the entire string, only part of string will be written. However, partially encoded characters will not be written.

      import { Buffer } from 'node:buffer';

      const buf = Buffer.alloc(256);

      const len = buf.write('\u00bd + \u00bc = \u00be', 0);

      console.log(`${len} bytes: ${buf.toString('utf8', 0, len)}`);
      // Prints: 12 bytes: ½ + ¼ = ¾

      const buffer = Buffer.alloc(10);

      const length = buffer.write('abcd', 8);

      console.log(`${length} bytes: ${buffer.toString('utf8', 8, 10)}`);
      // Prints: 2 bytes : ab

      Parameters

      • string: string

        String to write to buf.

      • Optionalencoding:
            | "base64"
            | "binary"
            | "ucs-2"
            | "utf-16le"
            | "utf-8"
            | "ascii"
            | "base64url"
            | "hex"
            | "latin1"
            | "ucs2"
            | "utf16le"
            | "utf8"

        The character encoding of string.

      Returns number

      Number of bytes written.

      v0.1.90

    • Parameters

      • string: string
      • offset: number
      • Optionalencoding:
            | "base64"
            | "binary"
            | "ucs-2"
            | "utf-16le"
            | "utf-8"
            | "ascii"
            | "base64url"
            | "hex"
            | "latin1"
            | "ucs2"
            | "utf16le"
            | "utf8"

      Returns number

    • Writes string to buf at offset according to the character encoding in encoding. The length parameter is the number of bytes to write. If buf did not contain enough space to fit the entire string, only part of string will be written. However, partially encoded characters will not be written.

      Parameters

      • string: string

        String to write to buf.

      • offset: number

        Number of bytes to skip before starting to write string. Default: 0.

      • length: number

        Maximum number of bytes to write (written bytes will not exceed buf.length - offset). Default: buf.length - offset.

      • Optionalencoding:
            | "base64"
            | "binary"
            | "ucs-2"
            | "utf-16le"
            | "utf-8"
            | "ascii"
            | "base64url"
            | "hex"
            | "latin1"
            | "ucs2"
            | "utf16le"
            | "utf8"

        The character encoding of string. Default: 'utf8'.

      Returns number

      Number of bytes written.

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf1 = Buffer.alloc(256)
      const len1 = buf1.write('\u00bd + \u00bc = \u00be', 0)
      console.log(`${len1} bytes: ${buf1.toString('utf8', 0, len1)}`)
      // Prints: 12 bytes: ½ + ¼ = ¾

      const buf2 = Buffer.alloc(10)
      const len2 = buf2.write('abcd', 8)
      console.log(`${len2} bytes: ${buf2.toString('utf8', 8, 10)}`)
      // Prints: 2 bytes : ab
      })()
    • Writes value to buf at the specified offset as big-endian. value is interpreted and written as a two's complement signed integer.

      Parameters

      • val: bigint

        Number to be written to buf.

      • offset: number = 0

        Number of bytes to skip before starting to write. Must satisfy: 0 <= offset <= buf.length - 8. Default: 0.

      Returns this

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf = new Buffer(8)
      buf.writeBigInt64BE(0x0102030405060708n, 0)
      console.log(buf.toString('hex')) // Prints: 0102030405060708
      })()
    • Writes value to buf at the specified offset as little-endian. value is interpreted and written as a two's complement signed integer.

      Parameters

      • val: bigint

        Number to be written to buf.

      • offset: number = 0

        Number of bytes to skip before starting to write. Must satisfy: 0 <= offset <= buf.length - 8. Default: 0.

      Returns this

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf = new Buffer(8)
      buf.writeBigInt64LE(0x0102030405060708n, 0)
      console.log(buf.toString('hex')) // Prints: 0807060504030201
      })()
    • Writes value to buf at the specified offset as big-endian.

      Parameters

      • val: bigint

        Number to be written to buf.

      • offset: number = 0

        Number of bytes to skip before starting to write. Must satisfy: 0 <= offset <= buf.length - 8. Default: 0.

      Returns this

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf = new Buffer(8)
      buf.writeBigUInt64BE(0xdecafafecacefaden, 0)
      console.log(buf.toString('hex')) // Prints: decafafecacefade
      })()
    • Writes value to buf at the specified offset as little-endian.

      Parameters

      • val: bigint

        Number to be written to buf.

      • offset: number = 0

        Number of bytes to skip before starting to write. Must satisfy: 0 <= offset <= buf.length - 8. Default: 0.

      Returns this

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf = new Buffer(8)
      buf.writeBigUInt64LE(0xdecafafecacefaden, 0)
      console.log(buf.toString('hex')) // Prints: defacecafefacade
      })()
    • Treats buf as a least significant bit array and write a bit at the specified bit offset.

      Parameters

      • val: number | boolean

        Bit value to write.

      • bitOffset: number

        bit offset to read from.

      Returns this

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf = new Buffer(1)
      const bits = [0, 1, 1, 0, 1, 0, 0, 1]
      for (let i = 0; i < 8; i++) buf.writeBitLSB(bits[i], i)
      console.log(buf[0].toString(2)) // Prints: 10010110
      })()
    • Treats buf as a most-significant bit array and write a bit at the specified bit offset.

      Parameters

      • val: number | boolean

        Bit value to write.

      • bitOffset: number

        bit offset to read from.

      Returns this

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf = new Buffer(1)
      const bits = [1, 0, 0, 1, 0, 1, 1, 0]
      for (let i = 0; i < 8; i++) buf.writeBitMSB(bits[i], i)
      console.log(buf[0].toString(2)) // Prints: 10010110
      })()
    • Writes value to buf at the specified offset as big-endian. The value must be a JavaScript number. Behavior is undefined when value is anything other than a JavaScript number.

      Parameters

      • val: number

        Number to be written to buf.

      • offset: number = 0

        Number of bytes to skip before starting to write. Must satisfy: 0 <= offset <= buf.length - 8. Default: 0.

      Returns this

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf = new Buffer(8)
      buf.writeDoubleBE(123.456, 0)
      console.log(buf.toString('hex')) // Prints: 405edd2f1a9fbe77
      })()
    • Writes value to buf at the specified offset as little-endian. The value must be a JavaScript number. Behavior is undefined when value is anything other than a JavaScript number.

      Parameters

      • val: number

        Number to be written to buf.

      • offset: number = 0

        Number of bytes to skip before starting to write. Must satisfy: 0 <= offset <= buf.length - 8. Default: 0.

      Returns this

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf = new Buffer(8)
      buf.writeDoubleLE(123.456, 0)
      console.log(buf.toString('hex')) // Prints: 77be9f1a2fdd5e40
      })()
    • Writes a 16-bit float value to buf at the specified offset as big-endian. The value must be a JavaScript number. Behavior is undefined when value is anything other than a JavaScript number.

      Parameters

      • val: number

        Number to be written to buf.

      • offset: number = 0

        Number of bytes to skip before starting to write. Must satisfy: 0 <= offset <= buf.length - 2. Default: 0.

      Returns this

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf = new Buffer(2)
      buf.writeFloat16BE(123.456, 0)
      console.log(buf.toString('hex')) // Prints: 57b7
      })()
    • Writes a 16-bit float value to buf at the specified offset as little-endian. The value must be a JavaScript number. Behavior is undefined when value is anything other than a JavaScript number.

      Parameters

      • val: number

        Number to be written to buf.

      • offset: number = 0

        Number of bytes to skip before starting to write. Must satisfy: 0 <= offset <= buf.length - 2. Default: 0.

      Returns this

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf = new Buffer(2)
      buf.writeFloat16LE(123.456, 0)
      console.log(buf.toString('hex')) // Prints: b757
      })()
    • Writes value to buf at the specified offset as big-endian. The value must be a JavaScript number. Behavior is undefined when value is anything other than a JavaScript number.

      Parameters

      • val: number

        Number to be written to buf.

      • offset: number = 0

        Number of bytes to skip before starting to write. Must satisfy: 0 <= offset <= buf.length - 4. Default: 0.

      Returns this

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf = new Buffer(4)
      buf.writeFloatBE(123.456, 0)
      console.log(buf.toString('hex')) // Prints: 42f6e979
      })()
    • Writes value to buf at the specified offset as little-endian. The value must be a JavaScript number. Behavior is undefined when value is anything other than a JavaScript number.

      Parameters

      • val: number

        Number to be written to buf.

      • offset: number = 0

        Number of bytes to skip before starting to write. Must satisfy: 0 <= offset <= buf.length - 4. Default: 0.

      Returns this

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf = new Buffer(4)
      buf.writeFloatLE(123.456, 0)
      console.log(buf.toString('hex')) // Prints: 79e9f642
      })()
    • Writes value to buf at the specified offset as big-endian. The value must be a valid signed 16-bit integer. Behavior is undefined when value is anything other than a signed 16-bit integer. The value is interpreted and written as a two's complement signed integer.

      Parameters

      • val: number

        Number to be written to buf.

      • offset: number = 0

        Number of bytes to skip before starting to write. Must satisfy: 0 <= offset <= buf.length - 2. Default: 0.

      Returns this

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf = new Buffer(2)
      buf.writeInt16BE(0x0102, 0)
      console.log(buf.toString('hex')) // Prints: 0102
      })()
    • Writes value to buf at the specified offset as little-endian. The value must be a valid signed 16-bit integer. Behavior is undefined when value is anything other than a signed 16-bit integer. The value is interpreted and written as a two's complement signed integer.

      Parameters

      • val: number

        Number to be written to buf.

      • offset: number = 0

        Number of bytes to skip before starting to write. Must satisfy: 0 <= offset <= buf.length - 2. Default: 0.

      Returns this

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf = new Buffer(2)
      buf.writeInt16LE(0x0102, 0)
      console.log(buf.toString('hex')) // Prints: 0201
      })()
    • Writes value to buf at the specified offset as big-endian. The value must be a valid signed 32-bit integer. Behavior is undefined when value is anything other than a signed 32-bit integer. The value is interpreted and written as a two's complement signed integer.

      Parameters

      • val: number

        Number to be written to buf.

      • offset: number = 0

        Number of bytes to skip before starting to write. Must satisfy: 0 <= offset <= buf.length - 4. Default: 0.

      Returns this

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf = new Buffer(4)
      buf.writeInt32BE(0x01020304, 0)
      console.log(buf.toString('hex')) // Prints: 01020304
      })()
    • Writes value to buf at the specified offset as little-endian. The value must be a valid signed 32-bit integer. Behavior is undefined when value is anything other than a signed 32-bit integer. The value is interpreted and written as a two's complement signed integer.

      Parameters

      • val: number

        Number to be written to buf.

      • offset: number = 0

        Number of bytes to skip before starting to write. Must satisfy: 0 <= offset <= buf.length - 4. Default: 0.

      Returns this

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf = new Buffer(4)
      buf.writeInt32LE(0x01020304, 0)
      console.log(buf.toString('hex')) // Prints: 04030201
      })()
    • Writes value to buf at the specified offset. value must be a valid signed 8-bit integer. Behavior is undefined when value is anything other than a signed 8-bit integer. value is interpreted and written as a two's complement signed integer.

      Parameters

      • val: number

        Number to be written to buf.

      • offset: number = 0

        Number of bytes to skip before starting to write. Must satisfy: 0 <= offset <= buf.length - 1. Default: 0.

      Returns this

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf = new Buffer(2)
      buf.writeInt8(2, 0)
      buf.writeInt8(-2, 1)
      console.log(buf.toString('hex')) // Prints: 02fe
      })()
    • Writes byteLength bytes of value to buf at the specified offset as big-endian. Supports up to 48 bits of accuracy. Behavior is undefined when value is anything other than a signed integer.

      Parameters

      • val: number

        Number to be written to buf.

      • offset: number = 0

        Number of bytes to skip before starting to write. Must satisfy 0 <= offset <= buf.length - byteLength.

      • byteLength: number = 6

        Number of bytes to write. Must satisfy 1 <= byteLength <= 6.

      Returns this

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf = new Buffer(6)
      buf.writeIntBE(0x1234567890ab, 0, 6)
      console.log(buf.toString('hex')) // Prints: 1234567890ab
      })()
    • Writes byteLength bytes of value to buf at the specified offset as little-endian. Supports up to 48 bits of accuracy. Behavior is undefined when value is anything other than a signed integer.

      Parameters

      • val: number

        Number to be written to buf.

      • offset: number = 0

        Number of bytes to skip before starting to write. Must satisfy 0 <= offset <= buf.length - byteLength.

      • byteLength: number = 6

        Number of bytes to write. Must satisfy 1 <= byteLength <= 6.

      Returns this

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf = new Buffer(6)
      buf.writeIntLE(0x1234567890ab, 0, 6)
      console.log(buf.toString('hex')) // Prints: ab9078563412
      })()
    • Writes value to buf at the specified offset as big-endian. The value must be a valid unsigned 16-bit integer. Behavior is undefined when value is anything other than an unsigned 16-bit integer.

      Parameters

      • val: number

        Number to be written to buf.

      • offset: number = 0

        Number of bytes to skip before starting to write. Must satisfy 0 <= offset <= buf.length - 2. Default: 0.

      Returns this

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf = new Buffer(4)
      buf.writeUInt16BE(0xdead, 0)
      buf.writeUInt16BE(0xbeef, 2)
      console.log(buf.toString('hex')) // Prints: deadbeef
      })()
    • Writes value to buf at the specified offset as little-endian. The value must be a valid unsigned 16-bit integer. Behavior is undefined when value is anything other than an unsigned 16-bit integer.

      Parameters

      • val: number

        Number to be written to buf.

      • offset: number = 0

        Number of bytes to skip before starting to write. Must satisfy 0 <= offset <= buf.length - 2. Default: 0.

      Returns this

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf = new Buffer(4)
      buf.writeUInt16LE(0xdead, 0)
      buf.writeUInt16LE(0xbeef, 2)
      console.log(buf.toString('hex')) // Prints: addeefbe
      })()
    • Writes value to buf at the specified offset as big-endian. The value must be a valid unsigned 32-bit integer. Behavior is undefined when value is anything other than an unsigned 32-bit integer.

      Parameters

      • val: number

        Number to be written to buf.

      • offset: number = 0

        Number of bytes to skip before starting to write. Must satisfy 0 <= offset <= buf.length - 4. Default: 0.

      Returns this

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf = new Buffer(4)
      buf.writeUInt32BE(0xfeedface, 0)
      console.log(buf.toString('hex')) // Prints: feedface
      })()
    • Writes value to buf at the specified offset as little-endian. The value must be a valid unsigned 32-bit integer. Behavior is undefined when value is anything other than an unsigned 32-bit integer.

      Parameters

      • val: number

        Number to be written to buf.

      • offset: number = 0

        Number of bytes to skip before starting to write. Must satisfy 0 <= offset <= buf.length - 4. Default: 0.

      Returns this

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf = new Buffer(4)
      buf.writeUInt32LE(0xfeedface, 0)
      console.log(buf.toString('hex')) // Prints: cefaedfe
      })()
    • Writes value to buf at the specified offset. value must be a valid unsigned 8-bit integer. Behavior is undefined when value is anything other than an unsigned 8-bit integer.

      Parameters

      • val: number

        Number to be written to buf.

      • offset: number = 0

        Number of bytes to skip before starting to write. Must satisfy 0 <= offset <= buf.length - 1. Default: 0.

      Returns this

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf = new Buffer(4)
      buf.writeUInt8(0x3, 0)
      buf.writeUInt8(0x4, 1)
      buf.writeUInt8(0x23, 2)
      buf.writeUInt8(0x42, 3)
      console.log(buf.toString('hex')) // Prints: 03042342
      })()
    • Writes byteLength bytes of value to buf at the specified offset as big-endian. Supports up to 48 bits of accuracy. Behavior is undefined when value is anything other than an unsigned integer.

      Parameters

      • val: number

        Number to be written to buf.

      • offset: number = 0

        Number of bytes to skip before starting to write. Must satisfy 0 <= offset <= buf.length - byteLength.

      • byteLength: number = 6

        Number of bytes to write. Must satisfy 1 <= byteLength <= 6.

      Returns this

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf = new Buffer(6)
      buf.writeUIntBE(0x1234567890ab, 0, 6)
      console.log(buf.toString('hex')) // Prints: 1234567890ab
      })()
    • Writes byteLength bytes of value to buf at the specified offset as little-endian. Supports up to 48 bits of accuracy. Behavior is undefined when value is anything other than an unsigned integer.

      Parameters

      • val: number

        Number to be written to buf.

      • offset: number = 0

        Number of bytes to skip before starting to write. Must satisfy 0 <= offset <= buf.length - byteLength.

      • byteLength: number = 6

        Number of bytes to write. Must satisfy 1 <= byteLength <= 6.

      Returns this

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf = new Buffer(6)
      buf.writeUIntLE(0x1234567890ab, 0, 6)
      console.log(buf.toString('hex')) // Prints: ab9078563412
      })()
    • Calculates the Bitwise XOR of all bytes in buf. If buf is empty, returns 0. You can use Buffer#subarray to calculate the Bitwise XOR of a subset of buf. Xor is usually used to calculate checksums in serial communication.

      Returns number

      The Bitwise XOR of all bytes in buf.

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf = Buffer.from('010203040506070809', 'hex')
      console.log(buf.xor()) // Prints: 1
      })()
    • The method Bitwise XOR every bytes with other in place and returns this. If length of other is shorter than this, the remaining bytes in this will not be changed. If length of other is longer than this, the remaining bytes in other will be ignored.

      Parameters

      • other: Buffer

        A Buffer to Bitwise XOR with.

      Returns this

      ;(async function () {
      const { Buffer } = await import('https://cdn.jsdelivr.net/npm/@taichunmin/buffer@0/+esm')

      const buf1 = Buffer.from('010203', 'hex')
      const buf2 = Buffer.from('102030', 'hex')
      console.log(buf1.xor(buf2).toString('hex')) // Prints: 112233
      console.log(buf1.toString('hex')) // Prints: 112233
      })()