arnaucube
arnaucube/poulpyPublic Self-hosted repository
poulpy/base2k/src/lib.rs
base2k/src/lib.rsRaw
 1pub mod encoding;
 2#[allow(
 3    non_camel_case_types,
 4    non_snake_case,
 5    non_upper_case_globals,
 6    dead_code,
 7    improper_ctypes
 8)]
 9// Other modules and exports
10pub mod ffi;
11pub mod free;
12pub mod infos;
13pub mod module;
14pub mod sampling;
15pub mod svp;
16pub mod vec_znx;
17pub mod vec_znx_big;
18pub mod vec_znx_dft;
19pub mod vmp;
20
21pub use encoding::*;
22pub use free::*;
23pub use infos::*;
24pub use module::*;
25pub use sampling::*;
26pub use svp::*;
27pub use vec_znx::*;
28pub use vec_znx_big::*;
29pub use vec_znx_dft::*;
30pub use vmp::*;
31
32pub const GALOISGENERATOR: u64 = 5;
33
34#[allow(dead_code)]
35fn is_aligned<T>(ptr: *const T, align: usize) -> bool {
36    (ptr as usize) % align == 0
37}
38
39pub fn cast<T, V>(data: &[T]) -> &[V] {
40    let ptr: *const V = data.as_ptr() as *const V;
41    let len: usize = data.len() / std::mem::size_of::<V>();
42    unsafe { std::slice::from_raw_parts(ptr, len) }
43}
44
45pub fn cast_mut<T, V>(data: &[T]) -> &mut [V] {
46    let ptr: *mut V = data.as_ptr() as *mut V;
47    let len: usize = data.len() / std::mem::size_of::<V>();
48    unsafe { std::slice::from_raw_parts_mut(ptr, len) }
49}
50
51use std::alloc::{alloc, Layout};
52
53pub fn alloc_aligned_u8(size: usize, align: usize) -> Vec<u8> {
54    assert_eq!(
55        align & (align - 1),
56        0,
57        "align={} must be a power of two",
58        align
59    );
60    assert_eq!(
61        (size * std::mem::size_of::<u8>()) % align,
62        0,
63        "size={} must be a multiple of align={}",
64        size,
65        align
66    );
67    unsafe {
68        let layout: Layout = Layout::from_size_align(size, align).expect("Invalid alignment");
69        let ptr: *mut u8 = alloc(layout);
70        if ptr.is_null() {
71            panic!("Memory allocation failed");
72        }
73        Vec::from_raw_parts(ptr, size, size)
74    }
75}
76
77pub fn alloc_aligned<T>(size: usize, align: usize) -> Vec<T> {
78    assert_eq!(
79        (size * std::mem::size_of::<T>()) % align,
80        0,
81        "size={} must be a multiple of align={}",
82        size,
83        align
84    );
85    let mut vec_u8: Vec<u8> = alloc_aligned_u8(std::mem::size_of::<T>() * size, align);
86    let ptr: *mut T = vec_u8.as_mut_ptr() as *mut T;
87    let len: usize = vec_u8.len() / std::mem::size_of::<T>();
88    let cap: usize = vec_u8.capacity() / std::mem::size_of::<T>();
89    std::mem::forget(vec_u8);
90    unsafe { Vec::from_raw_parts(ptr, len, cap) }
91}
92
93fn alias_mut_slice_to_vec<T>(slice: &[T]) -> Vec<T> {
94    unsafe {
95        let ptr: *mut T = slice.as_ptr() as *mut T;
96        let len: usize = slice.len();
97        Vec::from_raw_parts(ptr, len, len)
98    }
99}