CodeSampleX

Пример

bare-buffer 3.7.0: Buffer.compare

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

sha256:5c6710c52679d3ed10da3ef7b7ea0c12eb14eeb20fe63a78532a2806d7692c92

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

Кейс

HOW
Цель
verify Buffer.compare in pkg:npm/bare-buffer@3.7.0
Пакеты
Символы
  • Buffer.compare
Создан
2026-08-27T18:47:55Z

Контракт

  1. Buffer.compare returns 0 when two buffers contain identical byte sequences
  2. Buffer.compare returns -1 when first buffer sorts lexicographically before second buffer
  3. Buffer.compare returns 1 when first buffer sorts lexicographically after second buffer
  4. Buffer.compare orders shorter buffers before longer buffers when they share a common prefix
  5. Buffer.compare can be used as a comparator function to sort an array of Buffer instances in lexicographical order
  6. Buffer.prototype.compare compares buffer instances and supports optional target and source slice offsets

Файлы

  • 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.compare 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.compare

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:37cf4042cf9ac45d086c0438b5c5b599c06e3110294f7f24dad620a66419fd35","contract":["Buffer.compare returns 0 when two buffers contain identical byte sequences","Buffer.compare returns -1 when first buffer sorts lexicographically before second buffer","Buffer.compare returns 1 when first buffer sorts lexicographically after second buffer","Buffer.compare orders shorter buffers before longer buffers when they share a common prefix","Buffer.compare can be used as a comparator function to sort an array of Buffer instances in lexicographical order","Buffer.prototype.compare compares buffer instances and supports optional target and source slice offsets"],"goal":"verify Buffer.compare in pkg:npm/bare-buffer@3.7.0","kind":"HOW","packages":["pkg:npm/bare-buffer@3.7.0"],"schemaVersion":1,"symbols":["Buffer.compare"]},"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/bare-buffer@3.7.0"],"schemaVersion":1,"subject":"pkg:npm/bare-buffer@3.7.0","symbols":["Buffer.compare"],"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 compareBuffers(bufA, bufB) {
  return Buffer.compare(bufA, bufB);
}

export function compareSubstrings(bufA, bufB, targetStart, targetEnd, sourceStart, sourceEnd) {
  return bufA.compare(bufB, targetStart, targetEnd, sourceStart, sourceEnd);
}

export function sortBuffers(bufferArray) {
  return [...bufferArray].sort(Buffer.compare);
}

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

// 1. Buffer.compare returns 0 when two buffers contain identical byte sequences
const bufA1 = Buffer.from('hello');
const bufA2 = Buffer.from('hello');
assert.strictEqual(Buffer.compare(bufA1, bufA2), 0, 'Equal buffers must return 0');
assert.strictEqual(compareBuffers(bufA1, bufA2), 0, 'Helper compareBuffers must return 0');

// Also for empty buffers
const empty1 = Buffer.alloc(0);
const empty2 = Buffer.from('');
assert.strictEqual(Buffer.compare(empty1, empty2), 0, 'Two empty buffers must return 0');

// 2. Buffer.compare returns -1 when first buffer sorts lexicographically before second buffer
const bufB1 = Buffer.from('abc');
const bufB2 = Buffer.from('abd');
assert.strictEqual(Buffer.compare(bufB1, bufB2), -1, 'Lexicographically smaller buffer must return -1');
assert.strictEqual(compareBuffers(bufB1, bufB2), -1, 'Helper compareBuffers must return -1');

// 3. Buffer.compare returns 1 when first buffer sorts lexicographically after second buffer
const bufC1 = Buffer.from('xyz');
const bufC2 = Buffer.from('abc');
assert.strictEqual(Buffer.compare(bufC1, bufC2), 1, 'Lexicographically greater buffer must return 1');
assert.strictEqual(compareBuffers(bufC1, bufC2), 1, 'Helper compareBuffers must return 1');

// 4. Buffer.compare orders shorter buffers before longer buffers when they share a common prefix
const shortBuf = Buffer.from('abc');
const longBuf = Buffer.from('abcd');
assert.strictEqual(Buffer.compare(shortBuf, longBuf), -1, 'Shorter prefix buffer must return -1');
assert.strictEqual(Buffer.compare(longBuf, shortBuf), 1, 'Longer prefix buffer must return 1');

// 5. Buffer.compare can be used as a comparator function to sort an array of Buffer instances in lexicographical order
const list = [
  Buffer.from('banana'),
  Buffer.from('apple'),
  Buffer.from('cherry'),
  Buffer.from('apple pie'),
];
const sorted = sortBuffers(list);
assert.deepStrictEqual(
  sorted.map(b => b.toString()),
  ['apple', 'apple pie', 'banana', 'cherry'],
  'Buffers must be sorted lexicographically'
);

// 6. Buffer.prototype.compare compares buffer instances and supports optional target and source slice offsets
const fullBuf1 = Buffer.from('prefix-data-suffix');
const fullBuf2 = Buffer.from('other-data-more');
// fullBuf1 substring 'data' is at sourceStart: 7, sourceEnd: 11
// fullBuf2 substring 'data' is at targetStart: 6, targetEnd: 10
// In bare-buffer: bufA.compare(target, targetStart, targetEnd, sourceStart, sourceEnd)
const sliceCmp = fullBuf1.compare(fullBuf2, 6, 10, 7, 11);
assert.strictEqual(sliceCmp, 0, 'Matching slices must return 0');

const sliceDiff = compareSubstrings(fullBuf1, fullBuf2, 0, 5, 7, 11);
// comparing 'data' (fullBuf1[7..11]) with 'other' (fullBuf2[0..5]) -> 'data' < 'other' => -1
assert.strictEqual(sliceDiff, -1, 'Different slices must return correct ordering');

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

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

аноним