CodeSampleX

샘플

b4a 1.8.1: b4a buffer allocation, encoding conversion, and slicing

검증된 샘플 — npm b4a 1.8.1: b4a buffer allocation, encoding conversion, and slicing. node 22 · linux alpine/x64 · docker에서 contract를 실행해 통과했습니다.

sha256:d2269b48ae6b2b6ed88ad22120992e7dc667b0ce273dd6c53c5b1d0068ad7f16

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. MIT-0

실행 증거

선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.

증거 기준
서명된 컨트랙트 통과
검증 영수증
1
빌드한 서명 키
1
선언된 환경 linux 24 · ubuntu · glibc 2.39 x64 npm

검증 실행 환경

환경 컨트랙트 단계 실행일
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-23

케이스

HOW
목표
b4a buffer allocation, encoding conversion, and slicing
패키지
심벌
  • b4a.alloc
  • b4a.concat
  • b4a.from
  • b4a.toString
생성일
2026-08-23T15:55:56Z

컨트랙트

  1. assert b4a.alloc allocates zero-filled buffer of requested byte length
  2. assert b4a.from creates buffer from string with utf8, hex, and base64 encodings
  3. assert b4a.toString decodes buffer into utf8, hex, and base64 strings
  4. assert b4a.concat joins multiple buffer chunks into a single contiguous buffer

파일

  • 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: b4a buffer allocation, encoding conversion, and slicing
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/b4a@1.8.1
Demonstrate these symbols/APIs:
  - b4a.alloc
  - b4a.concat
  - b4a.from
  - b4a.toString

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:dd4e46ad4a90d7fac24b0987244ca3804caaff9e1f2f2f70b5916425cecdf6f3","contract":["assert b4a.alloc allocates zero-filled buffer of requested byte length","assert b4a.from creates buffer from string with utf8, hex, and base64 encodings","assert b4a.toString decodes buffer into utf8, hex, and base64 strings","assert b4a.concat joins multiple buffer chunks into a single contiguous buffer"],"goal":"b4a buffer allocation, encoding conversion, and slicing","kind":"HOW","packages":["pkg:npm/b4a@1.8.1"],"schemaVersion":1,"symbols":["b4a.alloc","b4a.concat","b4a.from","b4a.toString"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"npm","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/b4a@1.8.1"],"schemaVersion":1,"subject":"pkg:npm/b4a@1.8.1","symbols":["b4a.alloc","b4a.concat","b4a.from","b4a.toString"],"verifierAdapter":"node-typescript@1"}
index.js
const b4a = require('b4a');

/**
 * Allocates a zero-filled buffer of the specified byte size.
 *
 * @param {number} size - Number of bytes to allocate.
 * @returns {Uint8Array} Zero-initialized buffer.
 */
function allocateBuffer(size) {
  return b4a.alloc(size);
}

/**
 * Converts input string or array into a buffer with specified encoding.
 *
 * @param {string|Array<number>|Uint8Array} input - Data to convert.
 * @param {string} [encoding='utf8'] - Encoding name ('utf8', 'hex', 'base64', etc.).
 * @returns {Uint8Array} Created buffer.
 */
function createBuffer(input, encoding) {
  return b4a.from(input, encoding);
}

/**
 * Decodes buffer into a string using specified encoding.
 *
 * @param {Uint8Array} buf - Buffer to convert.
 * @param {string} [encoding='utf8'] - Target string encoding.
 * @returns {string} Decoded string.
 */
function bufferToString(buf, encoding) {
  return b4a.toString(buf, encoding);
}

/**
 * Concatenates multiple buffer chunks into a single buffer.
 *
 * @param {Array<Uint8Array>} chunks - Array of buffer chunks.
 * @param {number} [totalLength] - Total byte length of resulting buffer.
 * @returns {Uint8Array} Concatenated buffer.
 */
function concatBuffers(chunks, totalLength) {
  return b4a.concat(chunks, totalLength);
}

module.exports = {
  allocateBuffer,
  createBuffer,
  bufferToString,
  concatBuffers,
  b4a,
};
package-lock.json
{
  "name": "sample-b4a-buffer-operations",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-b4a-buffer-operations",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "b4a": "1.8.1"
      }
    },
    "node_modules/b4a": {
      "version": "1.8.1",
      "resolved": "https://registry.npmjs.org/b4a/-/b4a-1.8.1.tgz",
      "integrity": "sha512-aiqre1Nr0B/6DgE2N5vwTc+2/oQZ4Wh1t4NznYY4E00y8LCt6NqdRv81so00oo27D8MVKTpUa/MwUUtBLXCoDw==",
      "license": "Apache-2.0",
      "peerDependencies": {
        "react-native-b4a": "*"
      },
      "peerDependenciesMeta": {
        "react-native-b4a": {
          "optional": true
        }
      }
    }
  }
}
package.json
{
  "name": "sample-b4a-buffer-operations",
  "version": "1.0.0",
  "description": "Clean-room sample verifying b4a buffer allocation, encoding conversion, and slicing",
  "main": "index.js",
  "license": "MIT-0",
  "dependencies": {
    "b4a": "1.8.1"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "b4a buffer allocation, encoding conversion, and slicing",
  "kind": "HOW",
  "packages": [
    "pkg:npm/b4a@1.8.1"
  ],
  "symbols": [
    "b4a.alloc",
    "b4a.concat",
    "b4a.from",
    "b4a.toString"
  ]
}
test/contract.mjs
import assert from 'node:assert';
import b4a from 'b4a';
import {
  allocateBuffer,
  createBuffer,
  bufferToString,
  concatBuffers,
} from '../index.js';

// 1. Assert b4a.alloc allocates zero-filled buffer of requested byte length
const zeroBuf = allocateBuffer(8);
assert.strictEqual(zeroBuf.byteLength, 8, 'alloc must return buffer with matching byte length');
assert.strictEqual(b4a.isBuffer(zeroBuf), true, 'alloc must return valid buffer');
for (let i = 0; i < zeroBuf.length; i++) {
  assert.strictEqual(zeroBuf[i], 0, 'alloc buffer elements must be initialized to zero');
}

// 2. Assert b4a.from creates buffer from string with utf8, hex, and base64 encodings
const utf8Buf = createBuffer('Hello b4a', 'utf8');
assert.deepStrictEqual(
  Array.from(utf8Buf),
  [0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x62, 0x34, 0x61],
  'from must parse utf8 string bytes'
);

const hexBuf = createBuffer('68656c6c6f', 'hex');
assert.deepStrictEqual(
  Array.from(hexBuf),
  [0x68, 0x65, 0x6c, 0x6c, 0x6f],
  'from must decode hex string'
);

const base64Buf = createBuffer('aGVsbG8gd29ybGQ=', 'base64');
assert.deepStrictEqual(
  Array.from(base64Buf),
  [0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x77, 0x6f, 0x72, 0x6c, 0x64],
  'from must decode base64 string'
);

// 3. Assert b4a.toString decodes buffer into utf8, hex, and base64 strings
const testBuf = createBuffer('CodeSampleX');
assert.strictEqual(bufferToString(testBuf, 'utf8'), 'CodeSampleX', 'toString utf8 must decode accurately');
assert.strictEqual(bufferToString(testBuf, 'hex'), '436f646553616d706c6558', 'toString hex must decode accurately');
assert.strictEqual(bufferToString(testBuf, 'base64'), 'Q29kZVNhbXBsZVg=', 'toString base64 must decode accurately');

// 4. Assert b4a.concat joins multiple buffer chunks into a single contiguous buffer
const chunk1 = createBuffer('Fast ');
const chunk2 = createBuffer('Universal ');
const chunk3 = createBuffer('Buffer');
const combined = concatBuffers([chunk1, chunk2, chunk3]);
assert.strictEqual(bufferToString(combined, 'utf8'), 'Fast Universal Buffer', 'concat must combine all chunks in order');
assert.strictEqual(combined.byteLength, chunk1.byteLength + chunk2.byteLength + chunk3.byteLength, 'concat byteLength must match sum');

console.log('All b4a contract assertions passed.');

오리진 시더

익명