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#![warn(
80 clippy::cast_lossless,
81 clippy::explicit_into_iter_loop,
82 clippy::explicit_iter_loop,
83 clippy::filter_map_next,
84 clippy::large_digit_groups,
85 clippy::manual_filter_map,
86 clippy::manual_find_map,
87 clippy::map_flatten,
88 clippy::map_unwrap_or,
89 clippy::match_same_arms,
90 clippy::missing_const_for_fn,
91 clippy::mut_mut,
92 clippy::needless_borrow,
93 clippy::needless_continue,
94 clippy::needless_pass_by_value,
95 clippy::print_stdout,
96 clippy::redundant_closure_for_method_calls,
97 clippy::single_match_else,
98 clippy::trait_duplication_in_bounds,
99 clippy::type_repetition_in_bounds,
100 clippy::uninlined_format_args,
101 clippy::unused_self,
102 clippy::if_not_else,
103 clippy::manual_assert,
104 clippy::range_plus_one,
105 clippy::redundant_else,
106 clippy::semicolon_if_nothing_returned,
107 clippy::cloned_instead_of_copied,
108 clippy::flat_map_option,
109 clippy::unnecessary_wraps,
110 clippy::unnested_or_patterns,
111 clippy::trivially_copy_pass_by_ref
112)]
113#![allow(
114 clippy::cognitive_complexity,
115 clippy::float_cmp,
116 clippy::many_single_char_names,
117 clippy::too_many_arguments,
118 clippy::type_complexity,
119 clippy::upper_case_acronyms,
120 unstable_name_collisions
121)]
122#![cfg_attr(not(any(feature = "test_build", feature = "random")), no_std)]
123
124#[macro_use]
125extern crate alloc;
126
127#[cfg(feature = "test_build")]
128#[doc(hidden)]
129#[inline]
130pub fn fail_on_untested_path(message: &str) {
131 panic!("Untested path. {message}");
132}
133
134#[cfg(not(feature = "test_build"))]
135#[doc(hidden)]
136#[inline]
137pub const fn fail_on_untested_path(_message: &str) {}
138
139// TODO links for malachite-nz and malachite-q
140
141/// The [`Named`](named::Named) trait, for getting a type's name.
142#[macro_use]
143pub mod named;
144
145#[doc(hidden)]
146#[macro_use]
147pub mod macros;
148
149/// Functions for working with [`bool`]s.
150#[macro_use]
151pub mod bools;
152/// Functions for working with [`char`]s.
153#[macro_use]
154pub mod chars;
155/// Macros and traits related to comparing values.
156pub mod comparison;
157/// Functions and adaptors for iterators.
158pub mod iterators;
159/// [`Never`](nevers::Never), a type that cannot be instantiated.
160pub mod nevers;
161/// Functions for working with primitive integers and floats.
162#[macro_use]
163pub mod num;
164/// Functions for working with [`Ordering`](std::cmp::Ordering)s.
165pub mod options;
166/// Functions for working with [`Option`]s.
167pub mod orderings;
168#[cfg(feature = "random")]
169/// Functions for generating random values.
170pub mod random;
171/// [`RationalSequence`](rational_sequences::RationalSequence), a type representing a sequence that
172/// is finite or eventually repeating, just like the digits of a rational number.
173pub mod rational_sequences;
174/// [`RoundingMode`](rounding_modes::RoundingMode), an enum used to specify rounding behavior.
175pub mod rounding_modes;
176/// Functions for working with [`HashSet`](std::collections::HashSet)s and
177/// [`BTreeSet`](std::collections::BTreeSet)s.
178pub mod sets;
179/// Functions for working with slices.
180#[macro_use]
181pub mod slices;
182/// Functions for working with [`String`]s.
183pub mod strings;
184/// Functions for working with tuples.
185pub mod tuples;
186/// Unions (sum types). These are essentially generic enums.
187///
188/// # unwrap
189/// ```
190/// use malachite_base::union_struct;
191/// use malachite_base::unions::UnionFromStrError;
192/// use std::fmt::{self, Display, Formatter};
193/// use std::str::FromStr;
194///
195/// union_struct!(
196/// (pub(crate)),
197/// Union3,
198/// Union3<T, T, T>,
199/// [A, A, 'A', a],
200/// [B, B, 'B', b],
201/// [C, C, 'C', c]
202/// );
203///
204/// let mut u: Union3<char, char, char>;
205///
206/// u = Union3::A('a');
207/// assert_eq!(u.unwrap(), 'a');
208///
209/// u = Union3::B('b');
210/// assert_eq!(u.unwrap(), 'b');
211///
212/// u = Union3::C('c');
213/// assert_eq!(u.unwrap(), 'c');
214/// ```
215///
216/// # fmt
217/// ```
218/// use malachite_base::union_struct;
219/// use malachite_base::unions::UnionFromStrError;
220/// use std::fmt::{self, Display, Formatter};
221/// use std::str::FromStr;
222///
223/// union_struct!(
224/// (pub(crate)),
225/// Union3,
226/// Union3<T, T, T>,
227/// [A, A, 'A', a],
228/// [B, B, 'B', b],
229/// [C, C, 'C', c]
230/// );
231///
232/// let mut u: Union3<char, u32, bool>;
233///
234/// u = Union3::A('a');
235/// assert_eq!(u.to_string(), "A(a)");
236///
237/// u = Union3::B(5);
238/// assert_eq!(u.to_string(), "B(5)");
239///
240/// u = Union3::C(false);
241/// assert_eq!(u.to_string(), "C(false)");
242/// ```
243///
244/// # from_str
245/// ```
246/// use malachite_base::union_struct;
247/// use malachite_base::unions::UnionFromStrError;
248/// use std::fmt::{self, Display, Formatter};
249/// use std::str::FromStr;
250///
251/// union_struct!(
252/// (pub(crate)),
253/// Union3,
254/// Union3<T, T, T>,
255/// [A, A, 'A', a],
256/// [B, B, 'B', b],
257/// [C, C, 'C', c]
258/// );
259///
260/// let u3: Union3<bool, u32, char> = Union3::from_str("B(5)").unwrap();
261/// assert_eq!(u3, Union3::B(5));
262///
263/// let result: Result<Union3<char, u32, bool>, _> = Union3::from_str("xyz");
264/// assert_eq!(result, Err(UnionFromStrError::Generic("xyz".to_string())));
265///
266/// let result: Result<Union3<char, u32, bool>, _> = Union3::from_str("A(ab)");
267/// if let Err(UnionFromStrError::Specific(Union3::A(_e))) = result {
268/// } else {
269/// panic!("wrong error variant")
270/// }
271/// ```
272pub mod unions;
273/// Functions for working with [`Vec`]s.
274pub mod vecs;
275
276#[cfg(feature = "test_build")]
277pub mod test_util;