malachite_base/unsigned_polynomial/conversion/from_unsigned.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::num::basic::traits::Zero;
10use crate::num::basic::unsigneds::PrimitiveUnsigned;
11use crate::polynomial::Polynomial;
12use crate::unsigned_polynomial::UnsignedPolynomial;
13use alloc::vec;
14
15impl<T: PrimitiveUnsigned> From<T> for UnsignedPolynomial<T> {
16 /// Converts a value to a constant [`UnsignedPolynomial`].
17 ///
18 /// This works for anything a [`u64`] can be converted from, and for a [`u64`] itself. The
19 /// polynomial is the constant one, whose only coefficient is the value; zero becomes the zero
20 /// polynomial, which has no coefficients at all.
21 ///
22 /// $f(x) = x$, read on the left as a number and on the right as a polynomial.
23 ///
24 /// # Worst-case complexity
25 /// Constant time and additional memory.
26 ///
27 /// # Examples
28 /// ```
29 /// use malachite_base::unsigned_polynomial::UnsignedPolynomial;
30 ///
31 /// assert_eq!(UnsignedPolynomial::<u64>::from(123u64).to_string(), "123");
32 /// assert_eq!(UnsignedPolynomial::<u64>::from(123u64).to_string(), "123");
33 /// assert_eq!(UnsignedPolynomial::<u64>::from(true).to_string(), "1");
34 ///
35 /// // Zero is the zero polynomial, which has no coefficients.
36 /// assert_eq!(
37 /// UnsignedPolynomial::<u64>::from(0u64),
38 /// UnsignedPolynomial::<u64>::default()
39 /// );
40 /// ```
41 #[inline]
42 fn from(x: T) -> Self {
43 Self::from_coefficients_asc(vec![x])
44 }
45}
46
47impl<T: PrimitiveUnsigned> From<bool> for UnsignedPolynomial<T> {
48 /// Converts a [`bool`] to an [`UnsignedPolynomial`]: the constant polynomial 0 or 1.
49 ///
50 /// # Worst-case complexity
51 /// Constant time and additional memory.
52 ///
53 /// # Examples
54 /// ```
55 /// use malachite_base::unsigned_polynomial::UnsignedPolynomial;
56 ///
57 /// assert_eq!(UnsignedPolynomial::<u64>::from(false).to_string(), "0");
58 /// assert_eq!(UnsignedPolynomial::<u64>::from(true).to_string(), "1");
59 /// ```
60 #[inline]
61 fn from(b: bool) -> Self {
62 if b { Self::one() } else { Self::ZERO }
63 }
64}