malachite_base/
lib.rs

1// Copyright © 2025 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
9//! This crate contains many utilities that are used by the
10//! [`malachite-nz`](https://docs.rs/malachite-nz/latest/malachite_nz/) and
11//! [`malachite-q`]((https://docs.rs/malachite-q/latest/malachite_q/)) crates. These utilities
12//! include
13//! - Traits that wrap functions from the standard library, like
14//!   [`CheckedAdd`](num::arithmetic::traits::CheckedAdd).
15//! - Traits that give extra functionality to primitive types, like
16//!   [`Gcd`](num::arithmetic::traits::Gcd), [`FloorSqrt`](num::arithmetic::traits::FloorSqrt), and
17//!   [`BitAccess`](num::logic::traits::BitAccess).
18//! - Iterator-producing functions that let you generate values for testing. Here's an example of
19//!   an iterator that produces all pairs of [`u32`]s:
20//!   ```
21//!   use malachite_base::num::exhaustive::exhaustive_unsigneds;
22//!   use malachite_base::tuples::exhaustive::exhaustive_pairs_from_single;
23//!
24//!   let mut pairs = exhaustive_pairs_from_single(exhaustive_unsigneds::<u32>());
25//!   assert_eq!(
26//!       pairs.take(20).collect::<Vec<_>>(),
27//!       &[
28//!           (0, 0), (0, 1), (1, 0), (1, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 0), (2, 1),
29//!           (3, 0), (3, 1), (2, 2), (2, 3), (3, 2), (3, 3), (0, 4), (0, 5), (1, 4), (1, 5)
30//!       ]
31//!   );
32//!   ```
33//! - The [`RoundingMode`](rounding_modes::RoundingMode) enum, which allows you to specify the
34//!   rounding behavior of various functions.
35//! - The [`NiceFloat`](num::float::NiceFloat) wrapper, which provides alternative implementations
36//!   of [`Eq`], [`Ord`], and [`Display`](std::fmt::Display) for floating-point values which are in
37//!   some ways nicer than the defaults.
38//!
39//! # Demos and benchmarks
40//! This crate comes with a `bin` target that can be used for running demos and benchmarks.
41//! - Almost all of the public functions in this crate have an associated demo. Running a demo
42//!   shows you a function's behavior on a large number of inputs. For example, to demo the
43//!   [`mod_pow`](num::arithmetic::traits::ModPow::mod_pow) function on [`u32`]s, you can use the
44//!   following command:
45//!   ```text
46//!   cargo run --features bin_build --release -- -l 10000 -m exhaustive -d demo_mod_pow_u32
47//!   ```
48//!   This command uses the `exhaustive` mode, which generates every possible input, generally
49//!   starting with the simplest input and progressing to more complex ones. Another mode is
50//!   `random`. The `-l` flag specifies how many inputs should be generated.
51//! - You can use a similar command to run benchmarks. The following command benchmarks various
52//!   GCD algorithms for [`u64`]s:
53//!   ```text
54//!   cargo run --features bin_build --release -- -l 1000000 -m random -b \
55//!       benchmark_gcd_algorithms_u64 -o gcd-bench.gp
56//!   ```
57//!   This creates a file called gcd-bench.gp. You can use gnuplot to create an SVG from it like
58//!   so:
59//!   ```text
60//!   gnuplot -e "set terminal svg; l \"gcd-bench.gp\"" > gcd-bench.svg
61//!   ```
62//!
63//! The list of available demos and benchmarks is not documented anywhere; you must find them by
64//! browsing through
65//! [`bin_util/demo_and_bench`](https://github.com/mhogrefe/malachite/tree/master/malachite-base/src/bin_util/demo_and_bench).
66//!
67//! # Features
68//! - `test_build`: A large proportion of the code in this crate is only used for testing. For a
69//!   typical user, building this code would result in an unnecessarily long compilation time and
70//!   an unnecessarily large binary. Much of it is also used for testing
71//!   [`malachite-nz`](https://docs.rs/malachite-nz/latest/malachite_nz/) and
72//!   [`malachite-q`](https://docs.rs/malachite-q/latest/malachite_q/), so it can't just be
73//!   confined to the `tests` directory. My solution is to only build this code when the
74//!   `test_build` feature is enabled. If you want to run unit tests, you must enable `test_build`.
75//!   However, doctests don't require it, since they only test the public interface.
76//! - `bin_build`: This feature is used to build the code for demos and benchmarks, which also
77//!   takes a long time to build. Enabling this feature also enables `test_build`.
78
79#![allow(
80    unstable_name_collisions,
81    clippy::assertions_on_constants,
82    clippy::cognitive_complexity,
83    clippy::many_single_char_names,
84    clippy::range_plus_one,
85    clippy::suspicious_arithmetic_impl,
86    clippy::suspicious_op_assign_impl,
87    clippy::too_many_arguments,
88    clippy::type_complexity,
89    clippy::upper_case_acronyms,
90    clippy::multiple_bound_locations
91)]
92#![warn(
93    clippy::cast_lossless,
94    clippy::explicit_into_iter_loop,
95    clippy::explicit_iter_loop,
96    clippy::filter_map_next,
97    clippy::large_digit_groups,
98    clippy::manual_filter_map,
99    clippy::manual_find_map,
100    clippy::map_flatten,
101    clippy::map_unwrap_or,
102    clippy::match_same_arms,
103    clippy::missing_const_for_fn,
104    clippy::mut_mut,
105    clippy::needless_borrow,
106    clippy::needless_continue,
107    clippy::needless_pass_by_value,
108    clippy::print_stdout,
109    clippy::redundant_closure_for_method_calls,
110    clippy::single_match_else,
111    clippy::trait_duplication_in_bounds,
112    clippy::type_repetition_in_bounds,
113    clippy::uninlined_format_args,
114    clippy::unused_self,
115    clippy::if_not_else,
116    clippy::manual_assert,
117    clippy::range_plus_one,
118    clippy::redundant_else,
119    clippy::semicolon_if_nothing_returned,
120    clippy::cloned_instead_of_copied,
121    clippy::flat_map_option,
122    clippy::unnecessary_wraps,
123    clippy::unnested_or_patterns,
124    clippy::use_self,
125    clippy::trivially_copy_pass_by_ref
126)]
127#![cfg_attr(
128    not(any(feature = "test_build", feature = "random", feature = "std")),
129    no_std
130)]
131
132#[macro_use]
133extern crate alloc;
134
135#[cfg(feature = "test_build")]
136#[doc(hidden)]
137#[inline]
138pub fn fail_on_untested_path(message: &str) {
139    panic!("Untested path. {message}");
140}
141
142#[cfg(not(feature = "test_build"))]
143#[doc(hidden)]
144#[inline]
145pub const fn fail_on_untested_path(_message: &str) {}
146
147// TODO links for malachite-nz and malachite-q
148
149/// The [`Named`](named::Named) trait, for getting a type's name.
150#[macro_use]
151pub mod named;
152
153#[doc(hidden)]
154#[macro_use]
155pub mod macros;
156
157/// Functions for working with [`bool`]s.
158#[macro_use]
159pub mod bools;
160/// Functions for working with [`char`]s.
161#[macro_use]
162pub mod chars;
163/// Macros and traits related to comparing values.
164pub mod comparison;
165/// Functions and adaptors for iterators.
166pub mod iterators;
167/// [`Never`](nevers::Never), a type that cannot be instantiated.
168pub mod nevers;
169/// Functions for working with primitive integers and floats.
170#[macro_use]
171pub mod num;
172/// Functions for working with [`Ordering`](std::cmp::Ordering)s.
173pub mod options;
174/// Functions for working with [`Option`]s.
175pub mod orderings;
176#[cfg(feature = "random")]
177/// Functions for generating random values.
178pub mod random;
179/// [`RationalSequence`](rational_sequences::RationalSequence), a type representing a sequence that
180/// is finite or eventually repeating, just like the digits of a rational number.
181pub mod rational_sequences;
182/// [`RoundingMode`](rounding_modes::RoundingMode), an enum used to specify rounding behavior.
183pub mod rounding_modes;
184/// Functions for working with [`HashSet`](std::collections::HashSet)s and
185/// [`BTreeSet`](std::collections::BTreeSet)s.
186pub mod sets;
187/// Functions for working with slices.
188#[macro_use]
189pub mod slices;
190/// Functions for working with [`String`]s.
191pub mod strings;
192/// Functions for working with tuples.
193pub mod tuples;
194/// Unions (sum types). These are essentially generic enums.
195///
196/// # unwrap
197/// ```
198/// use malachite_base::union_struct;
199/// use malachite_base::unions::UnionFromStrError;
200/// use std::fmt::{self, Display, Formatter};
201/// use std::str::FromStr;
202///
203/// union_struct!(
204///     (pub(crate)),
205///     Union3,
206///     Union3<T, T, T>,
207///     [A, A, 'A', a],
208///     [B, B, 'B', b],
209///     [C, C, 'C', c]
210/// );
211///
212/// let mut u: Union3<char, char, char>;
213///
214/// u = Union3::A('a');
215/// assert_eq!(u.unwrap(), 'a');
216///
217/// u = Union3::B('b');
218/// assert_eq!(u.unwrap(), 'b');
219///
220/// u = Union3::C('c');
221/// assert_eq!(u.unwrap(), 'c');
222/// ```
223///
224/// # fmt
225/// ```
226/// use malachite_base::union_struct;
227/// use malachite_base::unions::UnionFromStrError;
228/// use std::fmt::{self, Display, Formatter};
229/// use std::str::FromStr;
230///
231/// union_struct!(
232///     (pub(crate)),
233///     Union3,
234///     Union3<T, T, T>,
235///     [A, A, 'A', a],
236///     [B, B, 'B', b],
237///     [C, C, 'C', c]
238/// );
239///
240/// let mut u: Union3<char, u32, bool>;
241///
242/// u = Union3::A('a');
243/// assert_eq!(u.to_string(), "A(a)");
244///
245/// u = Union3::B(5);
246/// assert_eq!(u.to_string(), "B(5)");
247///
248/// u = Union3::C(false);
249/// assert_eq!(u.to_string(), "C(false)");
250/// ```
251///
252/// # from_str
253/// ```
254/// use malachite_base::union_struct;
255/// use malachite_base::unions::UnionFromStrError;
256/// use std::fmt::{self, Display, Formatter};
257/// use std::str::FromStr;
258///
259/// union_struct!(
260///     (pub(crate)),
261///     Union3,
262///     Union3<T, T, T>,
263///     [A, A, 'A', a],
264///     [B, B, 'B', b],
265///     [C, C, 'C', c]
266/// );
267///
268/// let u3: Union3<bool, u32, char> = Union3::from_str("B(5)").unwrap();
269/// assert_eq!(u3, Union3::B(5));
270///
271/// let result: Result<Union3<char, u32, bool>, _> = Union3::from_str("xyz");
272/// assert_eq!(result, Err(UnionFromStrError::Generic("xyz".to_string())));
273///
274/// let result: Result<Union3<char, u32, bool>, _> = Union3::from_str("A(ab)");
275/// if let Err(UnionFromStrError::Specific(Union3::A(_e))) = result {
276/// } else {
277///     panic!("wrong error variant")
278/// }
279/// ```
280pub mod unions;
281/// Functions for working with [`Vec`]s.
282pub mod vecs;
283
284#[cfg(feature = "test_build")]
285pub mod test_util;
286
287pub mod platform;