All files / src/chunk cac.ts

90.47% Statements 19/21
71.42% Branches 5/7
100% Functions 2/2
90.47% Lines 19/21

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 7133x 33x 33x 33x   33x 33x   33x                                             33x 16x 6x     16x           16x 16x   16x               33x 3x           3x 3x   3x              
import { Binary } from 'cafe-utility'
import { Bytes } from '../utils/bytes'
import { Reference, Span } from '../utils/typed-bytes'
import { calculateChunkAddress } from './bmt'
 
export const MIN_PAYLOAD_SIZE = 1
export const MAX_PAYLOAD_SIZE = 4096
 
const ENCODER = new TextEncoder()
 
/**
 * General chunk interface for Swarm
 *
 * It stores the serialized data and provides functions to access
 * the fields of a chunk.
 *
 * It also provides an address function to calculate the address of
 * the chunk that is required for the Chunk API.
 */
export interface Chunk {
  readonly data: Uint8Array
  span: Span
  payload: Bytes
  address: Reference
}
 
/**
 * Creates a content addressed chunk and verifies the payload size.
 *
 * @param payloadBytes the data to be stored in the chunk
 */
export function makeContentAddressedChunk(payloadBytes: Uint8Array | string): Chunk {
  if (!(payloadBytes instanceof Uint8Array)) {
    payloadBytes = ENCODER.encode(payloadBytes)
  }
 
  Iif (payloadBytes.length < MIN_PAYLOAD_SIZE || payloadBytes.length > MAX_PAYLOAD_SIZE) {
    throw new RangeError(
      `payload size ${payloadBytes.length} exceeds limits [${MIN_PAYLOAD_SIZE}, ${MAX_PAYLOAD_SIZE}]`,
    )
  }
 
  const span = Span.fromBigInt(BigInt(payloadBytes.length))
  const data = Binary.concatBytes(span.toUint8Array(), payloadBytes)
 
  return {
    data,
    span,
    payload: Bytes.fromSlice(data, Span.LENGTH),
    address: calculateChunkAddress(data),
  }
}
 
export function asContentAddressedChunk(chunkBytes: Uint8Array): Chunk {
  Iif (chunkBytes.length < MIN_PAYLOAD_SIZE + Span.LENGTH || chunkBytes.length > MAX_PAYLOAD_SIZE + Span.LENGTH) {
    throw new RangeError(
      `chunk size ${chunkBytes.length} exceeds limits [${MIN_PAYLOAD_SIZE + Span.LENGTH}, ${Span.LENGTH}]`,
    )
  }
 
  const span = Span.fromSlice(chunkBytes, 0)
  const data = Binary.concatBytes(span.toUint8Array(), chunkBytes.slice(Span.LENGTH))
 
  return {
    data,
    span,
    payload: Bytes.fromSlice(data, Span.LENGTH),
    address: calculateChunkAddress(data),
  }
}