malachite_nz/integer_polynomial/conversion/from_unsigned_polynomial.rs
1// Copyright © 2026 Mikhail Hogrefe
2//
3// This file is part of Malachite.
4//
5// Malachite is free software: you can redistribute it and/or modify it under the terms of the GNU
6// Lesser General Public License (LGPL) as published by the Free Software Foundation; either version
7// 3 of the License, or (at your option) any later version. See <https://www.gnu.org/licenses/>.
8
9use crate::integer::Integer;
10use crate::integer_polynomial::IntegerPolynomial;
11use malachite_base::num::basic::unsigneds::PrimitiveUnsigned;
12use malachite_base::polynomial::Polynomial;
13use malachite_base::unsigned_polynomial::UnsignedPolynomial;
14
15impl<T: PrimitiveUnsigned> From<UnsignedPolynomial<T>> for IntegerPolynomial
16where
17 Integer: From<T>,
18{
19 /// Converts a [`UnsignedPolynomial`] to an [`IntegerPolynomial`].
20 ///
21 /// Every unsigned primitive is an [`Integer`], so nothing is lost and nothing can fail. The
22 /// coefficients are converted one by one, and the leading one stays nonzero, so the degree is
23 /// unchanged.
24 ///
25 /// $f(p) = p$, read on the left over the coefficients and on the right over $\Z$.
26 ///
27 /// # Worst-case complexity
28 /// $T(n) = O(n)$
29 ///
30 /// $M(n) = O(n)$
31 ///
32 /// where $T$ is time, $M$ is additional memory, and $n$ is the number of coefficients.
33 ///
34 /// # Examples
35 /// ```
36 /// use core::str::FromStr;
37 /// use malachite_base::unsigned_polynomial::UnsignedPolynomial;
38 /// use malachite_nz::integer_polynomial::IntegerPolynomial;
39 ///
40 /// let p = UnsignedPolynomial::<u64>::from_str("x^2+3*x+2").unwrap();
41 /// assert_eq!(IntegerPolynomial::from(p).to_string(), "x^2+3*x+2");
42 ///
43 /// assert_eq!(
44 /// IntegerPolynomial::from(UnsignedPolynomial::<u64>::default()).to_string(),
45 /// "0"
46 /// );
47 /// ```
48 #[inline]
49 fn from(p: UnsignedPolynomial<T>) -> Self {
50 // The coefficients keep their order and their nonzero leading one, so no trimming is
51 // needed; but going through the constructor costs one comparison and cannot be wrong.
52 Self::from_coefficients_asc(
53 p.into_coefficients_asc()
54 .into_iter()
55 .map(Integer::from)
56 .collect(),
57 )
58 }
59}