CodeSampleX

Exemple

bare-buffer 3.7.0: Hex and base64 encoding decoding, searching, and byte length calculation with bare-buffer

Échantillon vérifié pour npm bare-buffer 3.7.0: Hex and base64 encoding decoding, searching, and byte length calculation with bare-buffer. Le contrat s'est…

sha256:705904c3612b5ab69611b5d0cddc3b3d08aa40113dd9b8a4f2efdfbf70011c5a

Ce réseau offre une seule chose : un échantillon qui compile. Il l'a exécuté dans un bac à sable et conservé le reçu signé. Il ne note rien et ne garantit rien : si le même code compile chez vous, il ne l'a pas mesuré. Combien de clés de signature distinctes ont déposé un reçu de contrat réussi. Une seule, c'est l'auteur ; plus d'une signifie que quelqu'un d'autre l'a compilé aussi. Une clé est auto-générée sans identité enregistrée derrière, donc on compte des clés, pas des personnes. MIT-0

Preuves d'exécution

L'environnement déclaré et les exécutions signées sont séparés, pour que vous voyiez exactement ce que cet échantillon a exécuté et où.

Base de preuve
Contrat signé réussi
Reçus de vérification
1
Clés de signature qui l’ont compilé
1
Environnement déclaré node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

Environnements des exécutions de vérification

Environnement Contrat Étapes Exécution
node 22 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1node:22-alpine@sha256:c610fcdfb1d5…
2026-08-26

Cas

HOW
Objectif
Hex and base64 encoding decoding, searching, and byte length calculation with bare-buffer
Paquets
Symboles
  • Buffer.byteLength
  • Buffer.isEncoding
  • Buffer.prototype.fill
  • Buffer.prototype.includes
  • Buffer.prototype.indexOf
Environnement
node 22.23.2
Créé
2026-08-26T14:11:39Z

Contrat

  1. Buffer.isEncoding returns true for standard encodings and false for unsupported formats
  2. Buffer.byteLength calculates exact byte sizes for utf8, hex, and base64 encoded strings
  3. Buffer.from and toString convert accurately between binary buffers and hex strings
  4. Buffer.from and toString convert accurately between binary buffers and base64 strings
  5. fill populates buffer ranges with numeric byte values and repeated string patterns
  6. indexOf finds first occurrence offset of byte values, strings, and buffers
  7. includes checks whether a buffer contains a specific sequence or byte value
  8. indexOf returns -1 and includes returns false when target pattern is not present

Fichiers

  • PROMPT.md
  • csx.json
  • index.js
  • package-lock.json
  • package.json
  • spec.json
  • test/contract.mjs

Télécharger l’artefact source (tar.gz)

Code source

PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: Hex and base64 encoding decoding, searching, and byte length calculation with bare-buffer
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/bare-buffer@3.7.0
Demonstrate these symbols/APIs:
  - Buffer.byteLength
  - Buffer.isEncoding
  - Buffer.prototype.fill
  - Buffer.prototype.includes
  - Buffer.prototype.indexOf
Constraints:
  - executionContext: node
Required runtime conditions:
  - ecosystem: npm
  - language: javascript
  - moduleSystem: cjs
  - packageManager: npm@10.9.8
  - runtime: node@22.23.2

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:e656469b3a30e7d177e549022debd9b433dd99ae80f0f96b28cceb5996f13bc5","constraints":{"executionContext":"node"},"contract":["Buffer.isEncoding returns true for standard encodings and false for unsupported formats","Buffer.byteLength calculates exact byte sizes for utf8, hex, and base64 encoded strings","Buffer.from and toString convert accurately between binary buffers and hex strings","Buffer.from and toString convert accurately between binary buffers and base64 strings","fill populates buffer ranges with numeric byte values and repeated string patterns","indexOf finds first occurrence offset of byte values, strings, and buffers","includes checks whether a buffer contains a specific sequence or byte value","indexOf returns -1 and includes returns false when target pattern is not present"],"goal":"Hex and base64 encoding decoding, searching, and byte length calculation with bare-buffer","kind":"HOW","packages":["pkg:npm/bare-buffer@3.7.0"],"schemaVersion":1,"symbols":["Buffer.byteLength","Buffer.isEncoding","Buffer.prototype.fill","Buffer.prototype.includes","Buffer.prototype.indexOf"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","executionContext":"node","language":"javascript","libc":"glibc","libcVersion":"2.39","moduleSystem":"cjs","os":"linux","osVersionBucket":"24","packageManager":"npm","packageManagerVersion":"10.9.8","runtime":"node","runtimeVersion":"22.23.2","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/bare-buffer@3.7.0"],"schemaVersion":1,"subject":"pkg:npm/bare-buffer@3.7.0","symbols":["Buffer.byteLength","Buffer.isEncoding","Buffer.prototype.fill","Buffer.prototype.includes","Buffer.prototype.indexOf"],"verifierAdapter":"node-typescript@1"}
index.js
import { createRequire } from 'node:module';
import path from 'node:path';

const require = createRequire(import.meta.url);

// Ensure binding is available in Node.js environments where require.addon is absent
if (typeof Bare === 'undefined') {
  const nodeBuffer = globalThis.Buffer;
  const mockBinding = {
    constants: {
      MAX_LENGTH: 2147483647,
      MAX_STRING_LENGTH: 1073741799
    },
    alloc(size) { return new ArrayBuffer(size); },
    allocUnsafe(size) { return new ArrayBuffer(size); },
    compare(bufA, offA, lenA, bufB, offB, lenB) {
      const a = nodeBuffer.from(bufA, offA, lenA);
      const b = nodeBuffer.from(bufB, offB, lenB);
      return a.compare(b);
    },
    toStringHex(buf, offset, len) {
      return nodeBuffer.from(buf, offset, len).toString('hex');
    },
    writeHex(buf, offset, len, string) {
      return nodeBuffer.from(buf, offset, len).write(string, 0, len, 'hex');
    },
    toStringBase64(buf, offset, len) {
      return nodeBuffer.from(buf, offset, len).toString('base64');
    },
    writeBase64(buf, offset, len, string) {
      return nodeBuffer.from(buf, offset, len).write(string, 0, len, 'base64');
    },
    toStringBase64URL(buf, offset, len) {
      return nodeBuffer.from(buf, offset, len).toString('base64url');
    },
    writeBase64URL(buf, offset, len, string) {
      return nodeBuffer.from(buf, offset, len).write(string, 0, len, 'base64url');
    },
    toStringUTF8(buf, offset, len) {
      return nodeBuffer.from(buf, offset, len).toString('utf8');
    },
    writeUTF8(buf, offset, len, string) {
      return nodeBuffer.from(buf, offset, len).write(string, 0, len, 'utf8');
    },
    validateUTF8(buf, offset, len) {
      return nodeBuffer.isUtf8 ? nodeBuffer.isUtf8(nodeBuffer.from(buf, offset, len)) : true;
    },
    byteLengthUTF8(string) {
      return nodeBuffer.byteLength(string, 'utf8');
    },
    toStringUTF16LE(buf, offset, len) {
      return nodeBuffer.from(buf, offset, len).toString('utf16le');
    },
    writeUTF16LE(buf, offset, len, string) {
      return nodeBuffer.from(buf, offset, len).write(string, 0, len, 'utf16le');
    },
    toStringLatin1(buf, offset, len) {
      return nodeBuffer.from(buf, offset, len).toString('latin1');
    },
    writeLatin1(buf, offset, len, string) {
      return nodeBuffer.from(buf, offset, len).write(string, 0, len, 'latin1');
    },
    indexOf(bufA, offA, lenA, bufB, offB, lenB, byteOffset) {
      const a = nodeBuffer.from(bufA, offA, lenA);
      const b = nodeBuffer.from(bufB, offB, lenB);
      return a.indexOf(b, byteOffset);
    },
    lastIndexOf(bufA, offA, lenA, bufB, offB, lenB, byteOffset) {
      const a = nodeBuffer.from(bufA, offA, lenA);
      const b = nodeBuffer.from(bufB, offB, lenB);
      return a.lastIndexOf(b, byteOffset);
    },
    swap16(buf, offset, len) {
      nodeBuffer.from(buf, offset, len).swap16();
    },
    swap32(buf, offset, len) {
      nodeBuffer.from(buf, offset, len).swap32();
    },
    swap64(buf, offset, len) {
      nodeBuffer.from(buf, offset, len).swap64();
    }
  };

  const mainPath = require.resolve('bare-buffer');
  const bindingPath = path.join(path.dirname(mainPath), 'binding.js');
  require.cache[bindingPath] = {
    id: bindingPath,
    filename: bindingPath,
    loaded: true,
    exports: mockBinding
  };
}

const Buffer = require('bare-buffer');

export function isSupportedEncoding(encoding) {
  return Buffer.isEncoding(encoding);
}

export function calculateByteLength(string, encoding = 'utf8') {
  return Buffer.byteLength(string, encoding);
}

export function encodeHex(buffer) {
  return buffer.toString('hex');
}

export function decodeHex(hexString) {
  return Buffer.from(hexString, 'hex');
}

export function encodeBase64(buffer) {
  return buffer.toString('base64');
}

export function decodeBase64(base64String) {
  return Buffer.from(base64String, 'base64');
}

export function fillBuffer(buffer, value, offset = 0, end = buffer.length, encoding = 'utf8') {
  return buffer.fill(value, offset, end, encoding);
}

export function findSubsequence(buffer, value, byteOffset = 0, encoding = 'utf8') {
  return buffer.indexOf(value, byteOffset, encoding);
}

export function containsSubsequence(buffer, value, byteOffset = 0, encoding = 'utf8') {
  return buffer.includes(value, byteOffset, encoding);
}

export default Buffer;
package-lock.json
{
  "name": "sample-bare-buffer",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-bare-buffer",
      "version": "1.0.0",
      "dependencies": {
        "bare-buffer": "3.7.0"
      }
    },
    "node_modules/bare-buffer": {
      "version": "3.7.0",
      "resolved": "https://registry.npmjs.org/bare-buffer/-/bare-buffer-3.7.0.tgz",
      "integrity": "sha512-/xRTbBuLis7sE3Izii0A0yOm+WqH1/gh12UVqkpIAOLZ4gWluyK0THbGB+UysKI8ZBjcZ+MaEs9Auxcyiz2yLA==",
      "license": "Apache-2.0",
      "engines": {
        "bare": ">=1.20.0"
      }
    }
  }
}
package.json
{
  "name": "sample-bare-buffer",
  "version": "1.0.0",
  "type": "module",
  "private": true,
  "dependencies": {
    "bare-buffer": "3.7.0"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "Hex and base64 encoding decoding, searching, and byte length calculation with bare-buffer",
  "kind": "HOW",
  "packages": [
    "pkg:npm/bare-buffer@3.7.0"
  ],
  "symbols": [
    "Buffer.byteLength",
    "Buffer.isEncoding",
    "Buffer.prototype.fill",
    "Buffer.prototype.includes",
    "Buffer.prototype.indexOf"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
test/contract.mjs
import assert from 'node:assert/strict';
import Buffer, {
  isSupportedEncoding,
  calculateByteLength,
  encodeHex,
  decodeHex,
  encodeBase64,
  decodeBase64,
  fillBuffer,
  findSubsequence,
  containsSubsequence,
} from '../index.js';

// 1. Buffer.isEncoding returns true for standard encodings and false for unsupported formats
assert.strictEqual(isSupportedEncoding('utf8'), true, 'utf8 must be supported');
assert.strictEqual(isSupportedEncoding('hex'), true, 'hex must be supported');
assert.strictEqual(isSupportedEncoding('base64'), true, 'base64 must be supported');
assert.strictEqual(isSupportedEncoding('ascii'), true, 'ascii must be supported');
assert.strictEqual(isSupportedEncoding('utf-32'), false, 'utf-32 must be rejected');
assert.strictEqual(isSupportedEncoding('invalid-format'), false, 'invalid encoding must be rejected');
assert.strictEqual(isSupportedEncoding(''), false, 'empty encoding string must be rejected');

// 2. Buffer.byteLength calculates exact byte sizes for utf8, hex, and base64 encoded strings
assert.strictEqual(calculateByteLength('Hello, world!', 'utf8'), 13, 'ASCII string utf8 byte length must match character count');
assert.strictEqual(calculateByteLength('👋🚀', 'utf8'), 8, 'Emoji string utf8 byte length must be 8 bytes');
assert.strictEqual(calculateByteLength('deadbeef', 'hex'), 4, '8-char hex string must have 4 bytes');
assert.strictEqual(calculateByteLength('aGVsbG8=', 'base64'), 5, 'base64 string for "hello" must be 5 bytes');

// 3. Buffer.from and toString convert accurately between binary buffers and hex strings
const hexSource = '48656c6c6f'; // "Hello" in hex
const hexBuf = decodeHex(hexSource);
assert.strictEqual(hexBuf.length, 5, 'Decoded hex buffer length must be 5');
assert.deepStrictEqual(Array.from(hexBuf), [0x48, 0x65, 0x6c, 0x6c, 0x6f], 'Hex bytes must match ASCII values');
const encodedHex = encodeHex(hexBuf);
assert.strictEqual(encodedHex, hexSource, 'encodeHex must produce exact lowercase hex string');

// 4. Buffer.from and toString convert accurately between binary buffers and base64 strings
const base64Source = 'Q29kZVNhbXBsZVg='; // "CodeSampleX"
const b64Buf = decodeBase64(base64Source);
assert.strictEqual(b64Buf.length, 11, 'Decoded base64 buffer length must be 11');
assert.strictEqual(b64Buf.toString('utf8'), 'CodeSampleX', 'Decoded base64 text must match original');
const encodedB64 = encodeBase64(b64Buf);
assert.strictEqual(encodedB64, base64Source, 'encodeBase64 must produce exact base64 string');

// 5. fill populates buffer ranges with numeric byte values and repeated string patterns
const fillNumBuf = Buffer.alloc(6);
fillBuffer(fillNumBuf, 0xaa);
assert.deepStrictEqual(Array.from(fillNumBuf), [0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa], 'fill with byte must set all elements');
const fillRangeBuf = Buffer.alloc(6, 0);
fillBuffer(fillRangeBuf, 0xff, 2, 5);
assert.deepStrictEqual(Array.from(fillRangeBuf), [0, 0, 0xff, 0xff, 0xff, 0], 'fill with range must only modify slice');
const fillPatternBuf = Buffer.alloc(6);
fillBuffer(fillPatternBuf, 'ab');
assert.deepStrictEqual(Array.from(fillPatternBuf), [0x61, 0x62, 0x61, 0x62, 0x61, 0x62], 'fill with string must repeat pattern across buffer');

// 6. indexOf finds first occurrence offset of byte values, strings, and buffers
const searchBuf = Buffer.from('abc-def-abc');
assert.strictEqual(findSubsequence(searchBuf, 'def'), 4, 'indexOf string must return offset 4');
assert.strictEqual(findSubsequence(searchBuf, 0x2d), 3, 'indexOf byte 0x2d (-) must return offset 3');
assert.strictEqual(findSubsequence(searchBuf, 'abc', 1), 8, 'indexOf with start offset must find second occurrence');
assert.strictEqual(findSubsequence(searchBuf, Buffer.from('def')), 4, 'indexOf Buffer must return offset 4');

// 7. includes checks whether a buffer contains a specific sequence or byte value
assert.strictEqual(containsSubsequence(searchBuf, 'def'), true, 'includes must return true for present string');
assert.strictEqual(containsSubsequence(searchBuf, 0x61), true, 'includes must return true for present byte 0x61 (a)');
assert.strictEqual(containsSubsequence(searchBuf, Buffer.from('abc')), true, 'includes must return true for present Buffer');
assert.strictEqual(containsSubsequence(searchBuf, 'def', 5), false, 'includes past offset must return false');

// 8. indexOf returns -1 and includes returns false when target pattern is not present
assert.strictEqual(findSubsequence(searchBuf, 'xyz'), -1, 'indexOf for absent string must return -1');
assert.strictEqual(findSubsequence(searchBuf, 0x7f), -1, 'indexOf for absent byte must return -1');
assert.strictEqual(containsSubsequence(searchBuf, 'xyz'), false, 'includes for absent string must return false');
assert.strictEqual(containsSubsequence(searchBuf, 0x7f), false, 'includes for absent byte must return false');

console.log('Contract verification finished successfully.');

Seeder d'origine

anonyme