1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
// Copyright © 2023 Marvin Beckmann
//
// This file is part of qFALL-math.
//
// qFALL-math is free software: you can redistribute it and/or modify it under
// the terms of the Mozilla Public License Version 2.0 as published by the
// Mozilla Foundation. See <https://mozilla.org/en-US/MPL/2.0/>.
//! Implementations to create a [`PolyOverQ`] value from other types.
//!
//! The explicit functions contain the documentation.
use super::PolyOverQ;
use crate::{
error::{MathError, StringConversionError},
integer::PolyOverZ,
macros::for_others::implement_for_owned,
rational::Q,
};
use flint_sys::fmpq_poly::{
fmpq_poly_canonicalise, fmpq_poly_set_fmpq, fmpq_poly_set_fmpz_poly, fmpq_poly_set_str,
};
use std::{ffi::CString, str::FromStr};
impl FromStr for PolyOverQ {
type Err = MathError;
/// Creates a polynomial with arbitrarily many coefficients of type [`Q`].
///
/// Parameters:
/// - `s`: the polynomial of form: "`[#number of coefficients]⌴⌴[0th coefficient]⌴[1st coefficient]⌴...`"
///
/// Note that the `[#number of coefficients]` and `[0th coefficient]`
/// are divided by two spaces and the input string is trimmed, i.e. all whitespaces
/// before and after are ignored.
///
/// Returns a [`PolyOverQ`] or an error if the provided string was not formatted
/// correctly, the number of coefficients was smaller than the number provided at the
/// start of the provided string, or the provided string contains a `Null` Byte.
///
/// # Examples
/// ```
/// use qfall_math::rational::PolyOverQ;
/// use std::str::FromStr;
///
/// let poly = PolyOverQ::from_str("5 0 1/3 2/10 -3/2 1").unwrap();
/// ```
/// # Errors and Failures
/// - Returns a [`MathError`] of type
/// [`StringConversionError`](MathError::StringConversionError)
/// - if the provided string was not formatted correctly,
/// - if the number of coefficients was smaller than the number provided
/// at the start of the provided string,
/// - if the provided value did not contain two whitespaces, or
/// - if the provided string contains a `Null` Byte.
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut res = Self::default();
let c_string = CString::new(s.trim())?;
// `0` is returned if the string is a valid input
// additionally if it was not successfully, test if the provided value 's' actually
// contains two whitespaces, since this might be a common error
match unsafe { fmpq_poly_set_str(&mut res.poly, c_string.as_ptr()) } {
0 => unsafe {
// set_str assumes that all coefficients are reduced as far as possible,
// hence we have to reduce manually
fmpq_poly_canonicalise(&mut res.poly);
Ok(res)
},
_ if !s.contains(" ") => Err(
StringConversionError::InvalidStringToPolyMissingWhitespace(s.to_owned()),
)?,
_ => Err(StringConversionError::InvalidStringToPolyInput(
s.to_owned(),
))?,
}
}
}
impl From<&PolyOverZ> for PolyOverQ {
/// Creates a [`PolyOverQ`] from a [`PolyOverZ`].
///
/// Parameters:
/// - `poly`: the polynomial from which the coefficients are copied
///
/// # Examples
/// ```
/// use qfall_math::integer::PolyOverZ;
/// use qfall_math::rational::PolyOverQ;
/// use std::str::FromStr;
///
/// let poly = PolyOverZ::from_str("4 0 1 102 3").unwrap();
///
/// let poly_q = PolyOverQ::from(&poly);
///
/// # let cmp_poly = PolyOverQ::from_str("4 0 1 102 3").unwrap();
/// # assert_eq!(cmp_poly, poly_q);
/// ```
fn from(poly: &PolyOverZ) -> Self {
let mut out = Self::default();
unsafe { fmpq_poly_set_fmpz_poly(&mut out.poly, &poly.poly) };
out
}
}
implement_for_owned!(PolyOverZ, PolyOverQ, From);
impl<Rational: Into<Q>> From<Rational> for PolyOverQ {
/// Creates a constant [`PolyOverQ`] with a specified rational constant.
///
/// Parameters:
/// - `value`: the constant value the polynomial will have. It has to be a rational
/// number like [`Q`], an integer or a tuple of integers `(numerator, denominator)`.
///
/// Returns a new constant polynomial with the specified value.
///
/// # Examples
/// ```
/// use qfall_math::{rational::*, traits::GetCoefficient};
///
/// let one = PolyOverQ::from(1);
/// let three_quarter = PolyOverQ::from(Q::from((3, 4)));
/// let one_half = PolyOverQ::from((1, 2));
///
/// assert_eq!(one_half.get_coeff(0).unwrap(), Q::from((1, 2)));
/// assert_eq!(one_half.get_degree(), 0);
/// ```
///
/// # Panics ...
/// - if the provided value can not be converted into a [`Q`].
/// For example, because of a division by zero.
fn from(value: Rational) -> Self {
let mut out = PolyOverQ::default();
let value: Q = value.into();
unsafe {
fmpq_poly_set_fmpq(&mut out.poly, &value.value);
}
out
}
}
impl From<&PolyOverQ> for PolyOverQ {
/// Alias for [`PolyOverQ::clone`].
fn from(value: &PolyOverQ) -> Self {
value.clone()
}
}
#[cfg(test)]
mod test_from_str {
use super::PolyOverQ;
use std::str::FromStr;
/// Ensure that zero-coefficients are reduced
#[test]
fn reduce_zero_coeff() {
let one_1 = PolyOverQ::from_str("2 24/42 1").unwrap();
let one_2 = PolyOverQ::from_str("3 24/42 1 0").unwrap();
assert_eq!(one_1, one_2);
}
/// Ensure that coefficients in the string are reduced
#[test]
fn reduce_coeff() {
assert_eq!(
PolyOverQ::from_str("3 4/77 4/14 -28/21").unwrap(),
PolyOverQ::from_str("3 4/77 2/7 -28/21").unwrap()
);
}
/// Tests whether the same string yields the same polynomial
#[test]
fn same_string() {
let str_1 = format!("3 1 2/3 {}/{}", u64::MAX, i64::MIN);
let poly_1 = PolyOverQ::from_str(&str_1).unwrap();
let poly_2 = PolyOverQ::from_str(&str_1).unwrap();
assert_eq!(poly_1, poly_2);
}
/// Tests whether a correctly formatted string outputs an instantiation of a
/// polynomial, i.e. does not return an error
#[test]
fn working_example() {
assert!(PolyOverQ::from_str("3 1 2/5 -3/2").is_ok());
}
/// Tests whether a falsely formatted string (missing double-space) returns
/// an error
#[test]
fn missing_whitespace() {
assert!(PolyOverQ::from_str("3 1 2/5 -3/2").is_err());
assert!(PolyOverQ::from_str("3 12/5 2 -3").is_err());
assert!(PolyOverQ::from_str("2 17 42/4").is_err());
assert!(PolyOverQ::from_str("2 17 42").is_err());
assert!(PolyOverQ::from_str("2 17/1 42").is_err());
assert!(PolyOverQ::from_str("2 17/13 42 ").is_err());
assert!(PolyOverQ::from_str(" 2 17/5 42").is_err());
}
/// Tests whether a falsely formatted string (too many whitespaces) returns
/// an error
#[test]
fn too_many_whitespaces() {
assert!(PolyOverQ::from_str("3 1 2/5 -3/2").is_err());
}
/// Tests whether a falsely formatted string (wrong number of total
/// coefficients) returns an error
#[test]
fn false_number_of_coefficient() {
assert!(PolyOverQ::from_str("4 1 2/5 -3/2").is_err());
}
/// Tests whether a falsely formatted string (too many divisors) returns
/// an error
#[test]
fn too_many_divisors() {
assert!(PolyOverQ::from_str("3 1 2/5 -3/2/3").is_err());
}
/// Ensure that the input works with strings that have to be trimmed
#[test]
fn trim_input() {
let poly = PolyOverQ::from_str(" 4 1/2 2/3 3/4 -4 ");
assert!(poly.is_ok());
assert_eq!(
PolyOverQ::from_str("4 1/2 2/3 3/4 -4").unwrap(),
poly.unwrap()
);
}
}
#[cfg(test)]
mod test_from_poly_over_z {
use crate::{integer::PolyOverZ, rational::PolyOverQ};
use std::str::FromStr;
/// Ensure that the conversion works with negative entries
#[test]
fn small_negative() {
let poly = PolyOverZ::from_str("4 0 1 -102 -3").unwrap();
let poly_q = PolyOverQ::from(&poly);
let cmp_poly = PolyOverQ::from_str("4 0 1 -102 -3").unwrap();
assert_eq!(cmp_poly, poly_q);
}
/// Ensure that the conversion works with negative large entries
#[test]
fn large_negative() {
let poly = PolyOverZ::from_str(&format!("4 0 1 -102 -{}", u64::MAX)).unwrap();
let poly_q = PolyOverQ::from(&poly);
let cmp_poly = PolyOverQ::from_str(&format!("4 0 1 -102 -{}", u64::MAX)).unwrap();
assert_eq!(cmp_poly, poly_q);
}
/// Ensure that the conversion works with positive large entries
#[test]
fn large_positive() {
let poly = PolyOverZ::from_str(&format!("4 0 1 102 {}", u64::MAX)).unwrap();
let poly_q = PolyOverQ::from(&poly);
let cmp_poly = PolyOverQ::from_str(&format!("4 0 1 102 {}", u64::MAX)).unwrap();
assert_eq!(cmp_poly, poly_q);
}
/// Ensure that the conversion works for owned values
#[test]
fn availability() {
let poly = PolyOverZ::from_str("4 0 1 -102 -3").unwrap();
let _ = PolyOverQ::from(poly);
}
}
#[cfg(test)]
mod test_from_rational {
use super::*;
use crate::{integer::Z, traits::GetCoefficient};
/// Ensure that the [`From`] trait works for large
/// borrowed and owned [`Q`],[`Z`] and [`u64`] instances.
#[test]
fn large() {
let value = Q::from(u64::MAX);
let poly = PolyOverQ::from(&value);
let poly_2 = PolyOverQ::from(value.clone());
let poly_3 = PolyOverQ::from(u64::MAX);
let poly_4 = PolyOverQ::from(&u64::MAX);
let poly_5 = PolyOverQ::from(Z::from(u64::MAX));
let poly_6 = PolyOverQ::from(&Z::from(u64::MAX));
assert_eq!(poly.get_coeff(0).unwrap(), value);
assert_eq!(poly.get_degree(), 0);
assert_eq!(poly, poly_2);
assert_eq!(poly, poly_3);
assert_eq!(poly, poly_4);
assert_eq!(poly, poly_5);
assert_eq!(poly, poly_6);
}
/// Ensure that the [`From`] trait works for small
/// borrowed and owned [`Q`] and integer tuples instances.
#[test]
fn small() {
let value = Q::from((1, 2));
let poly = PolyOverQ::from(&value);
let poly_2 = PolyOverQ::from(value.clone());
let poly_3 = PolyOverQ::from((1, 2));
let poly_4 = PolyOverQ::from((&1, &2));
assert_eq!(poly.get_coeff(0).unwrap(), value);
assert_eq!(poly.get_degree(), 0);
assert_eq!(poly, poly_2);
assert_eq!(poly, poly_3);
assert_eq!(poly, poly_4);
}
/// Ensure that a division by zero panics.
#[test]
#[should_panic]
fn divide_by_zero() {
let _ = PolyOverQ::from((1, 0));
}
}