mpir/
prim.rs

1//! prim
2//!
3
4pub mod typ;
5pub mod mpz;
6pub mod mpf;
7pub mod mpq;
8pub mod randstate;
9pub mod gmp;
10
11use crate::prim::{typ::*, gmp::*}; // mpz::*, mpf::*, mpq::*, randstate::*
12
13/// trait SNew
14pub trait SNew {
15  /// new
16  fn new() -> Self;
17  /// as_ptr
18  fn as_ptr(&mut self) -> mp_t { self as *mut Self as mp_t }
19}
20
21/// to_u8z (&str)
22#[macro_export]
23macro_rules! to_u8z {
24  ($s:expr) => { (String::from($s)+"\0").as_bytes() }
25}
26pub use to_u8z;
27
28/// term_z ([u8])
29#[macro_export]
30macro_rules! term_z {
31  ($u:expr) => { (String::from_utf8($u.to_vec()).unwrap()+"\0").as_bytes() }
32}
33pub use term_z;
34
35/// get length from u8z buffer pointer (terminated 0)
36pub fn u8zlen(p: *mut u8) -> usize {
37  let mut l = 0usize;
38unsafe {
39  loop { // infinit
40    if std::slice::from_raw_parts_mut(p, l + 1)[l] == 0u8 { break; }
41    l += 1;
42  }
43}
44  l
45}
46
47/// get Option vec u8 from u8z buffer pointer (ff: true to free)
48pub fn u8zvec(p: *mut u8, ff: bool) -> Option<Vec<u8>> {
49unsafe {
50  if p == 0 as *mut u8 { None }
51  else {
52    let l = u8zlen(p);
53    let r = std::slice::from_raw_parts_mut(p, l).to_vec();
54    if ff {
55      let mut mp_free: FnPtrFree = __gmp_free_func; // dummy
56      __gmp_get_memory_functions(
57        0 as *mut FnPtrAllocate, 0 as *mut FnPtrReallocate, &mut mp_free);
58      mp_free(p, l + 1);
59    }
60    Some(r)
61  }
62}
63}
64
65/// gmp_printf
66pub fn gmp_printf<'a, T: SNew>(f: &str, a: &'a mut T) -> () {
67  gmp_printf_u8z(to_u8z!(f), a)
68}
69
70/// gmp_printf_u8z
71pub fn gmp_printf_u8z<'a, T: SNew>(f: &[u8], a: &'a mut T) -> () {
72  unsafe {
73    __gmp_printf(f as *const [u8] as *const u8,
74      a.as_ptr(), 0 as mp_t, 0 as mp_t, 0 as mp_t)
75  }
76}
77
78/// gmp_printf_1f
79pub fn gmp_printf_1f<'a, T: SNew>(f: &str,
80  p: int_t, a: &'a mut T) -> () {
81  gmp_printf_u8z_1f(to_u8z!(f), p, a)
82}
83
84/// gmp_printf_u8z_1f
85pub fn gmp_printf_u8z_1f<'a, T: SNew>(f: &[u8],
86  p: int_t, a: &'a mut T) -> () {
87  unsafe {
88    __gmp_printf(f as *const [u8] as *const u8,
89      p as mp_t, a.as_ptr(), 0 as mp_t, 0 as mp_t)
90  }
91}
92
93/// gmp_printf_2f
94pub fn gmp_printf_2f<'a, T: SNew>(f: &str,
95  p: int_t, a: &'a mut T, q: int_t, b: &'a mut T) -> () {
96  gmp_printf_u8z_2f(to_u8z!(f), p, a, q, b)
97}
98
99/// gmp_printf_u8z_2f
100pub fn gmp_printf_u8z_2f<'a, T: SNew>(f: &[u8],
101  p: int_t, a: &'a mut T, q: int_t, b: &'a mut T) -> () {
102  unsafe {
103    __gmp_printf(f as *const [u8] as *const u8,
104      p as mp_t, a.as_ptr(), q as mp_t, b.as_ptr())
105  }
106}
107
108/// mp_get_memory_functions
109pub fn mp_get_memory_functions(
110  alloc: &mut FnPtrAllocate,
111  realloc: &mut FnPtrReallocate,
112  free: &mut FnPtrFree) -> () {
113  unsafe { __gmp_get_memory_functions(alloc, realloc, free) }
114}