Skip to content

Instantly share code, notes, and snippets.

@olizilla
Created March 1, 2023 08:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save olizilla/1c931ea44d8a28c6d56089da7e3011a5 to your computer and use it in GitHub Desktop.
Save olizilla/1c931ea44d8a28c6d56089da7e3011a5 to your computer and use it in GitHub Desktop.
CarBufferWriter for synchronous in-memory CAR creation
import fs from 'fs'
import { CarBufferWriter } from '@ipld/car'
import { CID } from 'multiformats/cid'
import * as json from 'multiformats/codecs/json'
import * as raw from 'multiformats/codecs/raw'
import { sha256 } from 'multiformats/hashes/sha2'
/**
* @param {CID} root
* @param {Block[]} blocks
* @returns {Uint8Array} car
*/
function createCARSync (root, blocks) {
const headerSize = CarBufferWriter.headerLength({ roots: [root] })
const bufferSize = blocks.reduce((size, block) => size + CarBufferWriter.blockLength(block), headerSize)
const car = CarBufferWriter.createWriter(new ArrayBuffer(bufferSize), { roots: [root] })
blocks.forEach(b => car.write(b))
blocks.forEach(b => console.log(b.cid.toString()))
return car.close()
}
function createRawBlock (str) {
const bytes = new TextEncoder().encode(str)
const hash = sha256.digest(raw.encode(bytes))
const cid = CID.create(1, raw.code, hash)
return { cid, bytes }
}
function createJsonBlock (obj) {
const bytes = json.encode(obj)
const hash = sha256.digest(bytes)
const cid = CID.create(1, json.code, hash)
return { cid, bytes }
}
function main () {
const blocks = ['a', 'a', 'b', 'c'].map(createRawBlock)
const root = blocks.at(-1).cid
const car = createCARSync(root, blocks)
fs.writeFileSync('dupe.car', car)
}
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment