simplicity_sys/c_jets/
c_frame.rs

1// SPDX-License-Identifier: CC0-1.0
2
3//! High level APIs to creating read/write CFrames
4//!
5
6use std::mem;
7
8use super::frame_ffi;
9use super::frame_ffi::CFrameItem;
10use crate::ffi::UWORD;
11
12impl CFrameItem {
13    /// Allocate a new frame item with dummy values
14    unsafe fn new_unchecked() -> Self {
15        Self {
16            edge: std::ptr::null(),
17            len: 0,
18        }
19    }
20
21    /// Initialize a new read frame.
22    /// 'n' is the number of cells for the read frame.
23    /// 'from' is a pointer to the beginning of the new slice for the array of u8 to hold the frame's cells.
24    ///
25    /// Note: The C implementation uses array of UWORD for `from`. UWORD maps to uint_fast16_t which
26    /// maps to usize on both 32-bit and 64-bit platforms.
27    ///
28    /// # Safety
29    ///
30    /// `from` must be a valid pointer to a contiguous allocation of at least `n` usizes.
31    pub unsafe fn new_read(n: usize, from: *const UWORD) -> Self {
32        // Allocate a new vector of required size
33        let mut frame = CFrameItem::new_unchecked();
34        frame_ffi::c_initReadFrame(&mut frame, n, from);
35        frame
36    }
37
38    /// Initialize a new write frame.
39    /// 'n' is the number of cells for the write frame.
40    /// 'from' is a pointer to the one-past-the-end of the new slice for the array of UWORDS to hold the frame's cells.
41    ///
42    /// # Safety
43    ///
44    /// `from` must be a valid pointer **one past the end** of a contiguous allocation
45    /// of at least `n` usizes.
46    pub unsafe fn new_write(n: usize, from: *mut UWORD) -> Self {
47        // Allocate a new vector of required size
48        let mut frame = CFrameItem::new_unchecked();
49        frame_ffi::c_initWriteFrame(&mut frame, n, from);
50        frame
51    }
52}
53
54/// Number of UWORDs required to hold n bits
55pub fn uword_width(n_bits: usize) -> usize {
56    n_bits.div_ceil(8 * mem::size_of::<UWORD>())
57}
58
59/// Number of bytes required to hold n bits
60pub fn byte_width(n_bits: usize) -> usize {
61    uword_width(n_bits) * mem::size_of::<UWORD>()
62}