CodeSampleX

Пример

bare-buffer 3.7.0: Buffer.concat

Проверенный пример — npm bare-buffer 3.7.0: Buffer.concat. Контракт выполнен на node 22 · linux alpine/x64 · docker и пройден.

sha256:b55d3007f26b6a359f94cc8b441596a0645b24edf3bcf2290b26adab8bf42ceb

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. MIT-0

Свидетельства выполнения

Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
1
Ключи подписи, собравшие его
1
Заявленная среда node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

Среды запусков проверки

Окружение Контракт Этапы Запуск
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-27

Кейс

HOW
Цель
verify Buffer.concat in pkg:npm/bare-buffer@3.7.0
Пакеты
Символы
  • Buffer.concat
Окружение
node 22.23.2
Создан
2026-08-27T05:17:04Z

Контракт

  1. Buffer.concat combines multiple buffers into a single contiguous buffer
  2. Buffer.concat returns an empty buffer when passed an empty list
  3. Buffer.concat calculates total length automatically when length argument is omitted
  4. Buffer.concat truncates output to specified length when length is less than total buffer bytes
  5. Buffer.concat zero-fills unreached trailing bytes when specified length exceeds total input length
  6. Buffer.concat handles mixed buffer types including Uint8Array and Buffer instances
  7. Buffer.concat returns a single buffer copy when list contains only one element

Файлы

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

Скачать артефакт с исходным кодом (tar.gz)

Исходный код

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: verify Buffer.concat in pkg:npm/bare-buffer@3.7.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/bare-buffer@3.7.0
Demonstrate these symbols/APIs:
  - Buffer.concat

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:b5e7a67f1adcaa34a5995e5d3f72ea6003a76c82022fe69516258a7e62bab6fc","constraints":{"executionContext":"node"},"contract":["Buffer.concat combines multiple buffers into a single contiguous buffer","Buffer.concat returns an empty buffer when passed an empty list","Buffer.concat calculates total length automatically when length argument is omitted","Buffer.concat truncates output to specified length when length is less than total buffer bytes","Buffer.concat zero-fills unreached trailing bytes when specified length exceeds total input length","Buffer.concat handles mixed buffer types including Uint8Array and Buffer instances","Buffer.concat returns a single buffer copy when list contains only one element"],"goal":"verify Buffer.concat in pkg:npm/bare-buffer@3.7.0","kind":"HOW","packages":["pkg:npm/bare-buffer@3.7.0"],"schemaVersion":1,"symbols":["Buffer.concat"]},"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.concat"],"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 concatBuffers(list, totalLength) {
  return Buffer.concat(list, totalLength);
}

export function concatStrings(strings, encoding = 'utf8') {
  const buffers = strings.map(s => Buffer.from(s, encoding));
  return Buffer.concat(buffers);
}

export function concatWithTotalLength(list, totalLength) {
  return Buffer.concat(list, totalLength);
}

export default Buffer;
package-lock.json
{
  "name": "sample-bare-buffer-concat",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-bare-buffer-concat",
      "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-concat",
  "version": "1.0.0",
  "type": "module",
  "private": true,
  "dependencies": {
    "bare-buffer": "3.7.0"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify Buffer.concat in pkg:npm/bare-buffer@3.7.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/bare-buffer@3.7.0"
  ],
  "symbols": [
    "Buffer.concat"
  ]
}
test/contract.mjs
import assert from 'node:assert/strict';
import Buffer, { concatBuffers, concatStrings, concatWithTotalLength } from '../index.js';

// 1. Buffer.concat combines multiple buffers into a single contiguous buffer
const part1 = Buffer.from('Hello, ');
const part2 = Buffer.from('World!');
const combined = concatBuffers([part1, part2]);
assert.strictEqual(combined.length, 13, 'Concatenated length must equal sum of parts');
assert.strictEqual(combined.toString('utf8'), 'Hello, World!', 'Concatenated string content must match parts');
assert.ok(Buffer.isBuffer(combined), 'Result must be a Buffer instance');

// 2. Buffer.concat returns an empty buffer when passed an empty list
const emptyResult = concatBuffers([]);
assert.strictEqual(emptyResult.length, 0, 'Concatenating empty list must return buffer of length 0');
assert.ok(Buffer.isBuffer(emptyResult), 'Empty concatenation result must be a Buffer');

// 3. Buffer.concat calculates total length automatically when length argument is omitted
const chunks = [
  Buffer.from('alpha-'),
  Buffer.from('beta-'),
  Buffer.from('gamma')
];
const autoLengthResult = concatBuffers(chunks);
assert.strictEqual(autoLengthResult.length, 16, 'Auto-calculated length must equal sum of chunk lengths');
assert.strictEqual(autoLengthResult.toString('utf8'), 'alpha-beta-gamma', 'Chunks must concatenate in order');

// 4. Buffer.concat truncates output to specified length when length is less than total buffer bytes
const fullText = [Buffer.from('abcdef'), Buffer.from('123456')];
const truncated = concatWithTotalLength(fullText, 8);
assert.strictEqual(truncated.length, 8, 'Truncated buffer length must equal specified totalLength');
assert.strictEqual(truncated.toString('utf8'), 'abcdef12', 'Truncated buffer content must contain only first 8 bytes');

// 5. Buffer.concat zero-fills unreached trailing bytes when specified length exceeds total input length
const shortList = [Buffer.from([0x01, 0x02]), Buffer.from([0x03, 0x04])];
const extended = concatWithTotalLength(shortList, 8);
assert.strictEqual(extended.length, 8, 'Extended buffer length must equal specified totalLength');
assert.deepStrictEqual(
  Array.from(extended),
  [0x01, 0x02, 0x03, 0x04, 0x00, 0x00, 0x00, 0x00],
  'Trailing unreached bytes must be zero-filled'
);

// 6. Buffer.concat handles mixed buffer types including Uint8Array and Buffer instances
const uint8Arr = new Uint8Array([0x10, 0x20]);
const bareBuf = Buffer.from([0x30, 0x40]);
const mixedResult = concatBuffers([uint8Arr, bareBuf]);
assert.strictEqual(mixedResult.length, 4, 'Mixed array concatenation length must be 4');
assert.deepStrictEqual(
  Array.from(mixedResult),
  [0x10, 0x20, 0x30, 0x40],
  'Bytes from Uint8Array and Buffer must concatenate sequentially'
);

// 7. Buffer.concat returns a single buffer copy when list contains only one element
const single = [Buffer.from('standalone')];
const singleResult = concatBuffers(single);
assert.strictEqual(singleResult.length, 10, 'Single element concatenation length must match element');
assert.strictEqual(singleResult.toString('utf8'), 'standalone', 'Single element content must match');

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

Исходный сидер

аноним