LLZK 3.0.0
An open-source IR for Zero Knowledge (ZK) circuits
Loading...
Searching...
No Matches
BinaryBuffer.h
Go to the documentation of this file.
1//===-- BinaryBuffer.h - Little-endian binary buffer ------------*- C++ -*-===//
2//
3// Part of the LLZK Project, under the Apache License v2.0.
4// See LICENSE.txt for license information.
5// Copyright 2026 Project LLZK
6// SPDX-License-Identifier: Apache-2.0
7//
8//===----------------------------------------------------------------------===//
9
10#pragma once
11
13
14#include <llvm/ADT/ArrayRef.h>
15#include <llvm/ADT/SmallVector.h>
16#include <llvm/Support/Endian.h>
17
18#include <climits>
19#include <cstdint>
20#include <limits>
21
22namespace llzk {
23
26public:
27 void writeU32(uint32_t value) { writeInteger(value); }
28 void writeU64(uint64_t value) { writeInteger(value); }
29
30 void writeBytes(llvm::ArrayRef<char> bytes) { buffer_.append(bytes.begin(), bytes.end()); }
31
34 llvm::Error writeFieldElement(uint32_t size, const llvm::DynamicAPInt &value) {
35 if (size == 0 || size > std::numeric_limits<unsigned>::max() / CHAR_BIT) {
36 return llvm::createStringError(llvm::inconvertibleErrorCode(), "invalid field encoding size");
37 }
38 auto exact = checkedToAPInt(value, size * CHAR_BIT, false);
39 if (!exact) {
40 return exact.takeError();
41 }
42 for (uint32_t i = 0; i < size; ++i) {
43 buffer_.push_back(static_cast<char>(exact->extractBitsAsZExtValue(8, i * 8)));
44 }
45 return llvm::Error::success();
46 }
47
48 uint64_t size() const { return static_cast<uint64_t>(buffer_.size()); }
49 llvm::ArrayRef<char> bytes() const { return buffer_; }
50
51private:
52 template <typename T> void writeInteger(T value) {
53 char bytes[sizeof(T)];
54 llvm::support::endian::write<T, llvm::endianness::little>(bytes, value);
56 }
57
58 llvm::SmallVector<char> buffer_;
59};
60
61} // namespace llzk
This file implements helpers for DynamicAPInt operations and conversions that LLVM does not provide.
Accumulate fixed-width integers and field elements in little-endian order.
void writeBytes(llvm::ArrayRef< char > bytes)
uint64_t size() const
llvm::Error writeFieldElement(uint32_t size, const llvm::DynamicAPInt &value)
Append an unsigned fixed-width field encoding, rejecting overflow and negatives.
llvm::ArrayRef< char > bytes() const
void writeU64(uint64_t value)
void writeU32(uint32_t value)
Expected< APInt > checkedToAPInt(const DynamicAPInt &value, unsigned bitWidth, bool isSigned)