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
34fn is_aligned<T>(ptr: *const T, align: usize) -> bool {
35    (ptr as usize) % align == 0
36}
37
38pub fn cast<T, V>(data: &[T]) -> &[V] {
39    let ptr: *const V = data.as_ptr() as *const V;
40    let len: usize = data.len() / std::mem::size_of::<V>();
41    unsafe { std::slice::from_raw_parts(ptr, len) }
42}
43
44pub fn cast_mut<T, V>(data: &[T]) -> &mut [V] {
45    let ptr: *mut V = data.as_ptr() as *mut V;
46    let len: usize = data.len() / std::mem::size_of::<V>();
47    unsafe { std::slice::from_raw_parts_mut(ptr, len) }
48}
49
50use std::alloc::{alloc, Layout};
51
52pub fn alloc_aligned_u8(size: usize, align: usize) -> Vec<u8> {
53    assert_eq!(
54        align & (align - 1),
55        0,
56        "align={} must be a power of two",
57        align
58    );
59    assert_eq!(
60        (size * std::mem::size_of::<u8>()) % align,
61        0,
62        "size={} must be a multiple of align={}",
63        size,
64        align
65    );
66    unsafe {
67        let layout: Layout = Layout::from_size_align(size, align).expect("Invalid alignment");
68        let ptr: *mut u8 = alloc(layout);
69        if ptr.is_null() {
70            panic!("Memory allocation failed");
71        }
72        Vec::from_raw_parts(ptr, size, size)
73    }
74}
75
76pub fn alloc_aligned<T>(size: usize, align: usize) -> Vec<T> {
77    assert_eq!(
78        (size * std::mem::size_of::<T>()) % align,
79        0,
80        "size={} must be a multiple of align={}",
81        size,
82        align
83    );
84    let mut vec_u8: Vec<u8> = alloc_aligned_u8(std::mem::size_of::<T>() * size, align);
85    let ptr: *mut T = vec_u8.as_mut_ptr() as *mut T;
86    let len: usize = vec_u8.len() / std::mem::size_of::<T>();
87    let cap: usize = vec_u8.capacity() / std::mem::size_of::<T>();
88    std::mem::forget(vec_u8);
89    unsafe { Vec::from_raw_parts(ptr, len, cap) }
90}
91
92fn alias_mut_slice_to_vec<T>(slice: &[T]) -> Vec<T> {
93    unsafe {
94        let ptr: *mut T = slice.as_ptr() as *mut T;
95        let len: usize = slice.len();
96        Vec::from_raw_parts(ptr, len, len)
97    }
98}