fake/
lib.rs

1//! A library for generating fake data.
2//!
3//! # Feature flags
4//!
5//! - `derive`: Enable `#[derive(Dummy)]` macro
6//! - `bigdecimal`: [bigdecimal](https://docs.rs/bigdecimal) integration
7//! - `bson_oid`: [bson](https://docs.rs/bson) integration
8//! - `chrono`: [chrono](https://docs.rs/chrono) integration
9//! - `chrono-tz`: [chrono-tz](https://docs.rs/chrono-tz) integration
10//! - `geo`: [geo-types](https://docs.rs/geo-types) integration
11//! - `glam`: [glam](https://docs.rs/glam) integration
12//! - `http`: [http](https://docs.rs/http) integration
13//! - `rust-decimal`: [rust_decimal](https://docs.rs/rust_decimal) integration
14//! - `time`: [time](https://docs.rs/time) integration
15//! - `ulid`: [ulid](https://docs.rs/ulid) integration
16//! - `uuid`: [uuid](https://docs.rs/uuid) integration
17//!
18//! # Usage
19//!
20//! ```
21//! use fake::{Dummy, Fake, Faker};
22//! use fake::rand::rngs::StdRng;
23//! use fake::rand::SeedableRng;
24//!
25//! #[derive(Debug, Dummy)]
26//! pub struct Foo {
27//!     #[dummy(faker = "1000..2000")]
28//!     order_id: usize,
29//!     customer: String,
30//!     paid: bool,
31//! }
32//!
33//! // type derived Dummy
34//! let f: Foo = Faker.fake();
35//! println!("{:?}", f);
36//!
37//! // using `Faker` to generate default fake value of given type
38//! let tuple = Faker.fake::<(u8, u32, f32)>();
39//! println!("tuple {:?}", tuple);
40//! println!("String {:?}", Faker.fake::<String>());
41//!
42//! // types U can `be used to generate fake value T, if `T: Dummy<U>`
43//! println!("String {:?}", (8..20).fake::<String>());
44//! println!("u32 {:?}", (8..20).fake::<u32>());
45//!
46//! // using `faker` module with locales
47//! use fake::faker::name::raw::*;
48//! use fake::locales::*;
49//!
50//! let name: String = Name(EN).fake();
51//! println!("name {:?}", name);
52//!
53//! let name: String = Name(ZH_TW).fake();
54//! println!("name {:?}", name);
55//!
56//! // using convenient function without providing locale
57//! use fake::faker::lorem::en::*;
58//! let words: Vec<String> = Words(3..5).fake();
59//! println!("words {:?}", words);
60//!
61//! // Using a tuple config list to generate a vector with a length range and a specific faker for the element
62//! let name_vec: Vec<String> = (Name(EN), 3..5).fake();
63//!
64//! // Using a macro as an alternative method for the tuple config list
65//! let name_vec = fake::vec![String as Name(EN); 3..5];
66//!
67//! // using macro to generate nested collection
68//! let name_vec = fake::vec![String as Name(EN); 4, 3..5, 2];
69//! println!("random nested vec {:?}", name_vec);
70//!
71//! // fixed seed rng
72//! let seed = [
73//!     1, 0, 0, 0, 23, 0, 0, 0, 200, 1, 0, 0, 210, 30, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
74//!     0, 0, 0, 0,
75//! ];
76//! let ref mut r = StdRng::from_seed(seed);
77//! for _ in 0..5 {
78//!     let v: usize = Faker.fake_with_rng(r);
79//!     println!("value from fixed seed {}", v);
80//! }
81//!
82//! # #[cfg(feature = "always-true-rng")] {
83//! // Use an always true RNG so that optional types are always `Some` values. (Requires
84//! // always-true-rng feature).
85//! use fake::utils::AlwaysTrueRng;
86//! let mut rng = AlwaysTrueRng::default();
87//! let result: Option<i64> = Faker.fake_with_rng(&mut rng);
88//! println!("Always Some: {}", result.unwrap());
89//! # }
90//! ```
91
92// Enable `doc_cfg` feature for `docs.rs`
93#![cfg_attr(docsrs, feature(doc_cfg))]
94
95pub use rand;
96pub use rand::Rng;
97
98/// Generate default fake value for given type using [`Fake`].
99///
100/// # Examples
101///
102/// ```
103/// use fake::{Fake, Faker};
104///
105/// let a: Option<usize> = Faker.fake();
106/// // or use turbofish syntax
107/// let b = Faker.fake::<Result<u32, u8>>();
108/// let c: (u8, u32, f32) = Faker.fake();
109/// // can also be combined with other values that implements Fake
110/// let d: (u8, u32, f32) = (1..10, Faker, 2.5..5.5).fake();
111/// let e: [u8; 3] = Faker.fake();
112/// let f: String = Faker.fake();
113/// // it also works for smart pointers and wrappers
114/// let g: std::pin::Pin<String> = Faker.fake();
115/// let h: Box<std::rc::Rc<u8>> = Faker.fake();
116/// let i: std::path::PathBuf = Faker.fake();
117/// ```
118pub struct Faker;
119
120/// Provide data structure a way to generate fake values.
121/// The opposite of [`Fake`].
122///
123/// [`Faker`] can be used as a generic `T` for `Dummy<T>` to generate a
124/// default fake value.
125///
126/// [`Dummy`] is similar to [`From`] trait, while [`Fake`] is similar to
127/// [`Into`] trait. Except in this case [`Fake`] cannot be implemented.
128///
129/// # Examples
130///
131/// ```
132/// use fake::rand::prelude::IndexedRandom;
133/// use fake::{Dummy, Fake, Faker, Rng};
134///
135/// struct Name; // does not handle locale, see locales module for more
136///
137/// impl Dummy<Name> for &'static str {
138///     fn dummy_with_rng<R: Rng + ?Sized>(_: &Name, rng: &mut R) -> &'static str {
139///         const NAMES: &[&str] = &["John Doe", "Jane Doe"];
140///         NAMES.choose(rng).unwrap()
141///     }
142/// }
143///
144/// let name: &str = Name.fake();
145/// assert!(name == "John Doe" || name == "Jane Doe");
146/// ```
147///
148/// # Derivable
149///
150/// The trait can be used with `#[derive]` if all the type's fields
151/// implement [`Fake`]. See [`Dummy`][macro@Dummy] for more.
152pub trait Dummy<T>: Sized {
153    /// Generate a dummy value for a type.
154    ///
155    /// This can be left as a blanket implemented most of the time since it
156    /// uses [`Dummy::dummy_with_rng`] under the hood.
157    fn dummy(config: &T) -> Self {
158        let mut r = rand::rng();
159        Dummy::<T>::dummy_with_rng(config, &mut r)
160    }
161
162    /// Generate a dummy value for a given type using a random number
163    /// generator.
164    fn dummy_with_rng<R: Rng + ?Sized>(config: &T, rng: &mut R) -> Self;
165}
166
167mod private {
168    pub trait FakeBase<T>: Sized {
169        fn _fake(&self) -> T;
170        fn _fake_with_rng<R: rand::Rng + ?Sized>(&self, rng: &mut R) -> T;
171    }
172
173    impl<T, U> FakeBase<U> for T
174    where
175        U: crate::Dummy<T>,
176    {
177        fn _fake(&self) -> U {
178            U::dummy(self)
179        }
180
181        fn _fake_with_rng<R: rand::Rng + ?Sized>(&self, rng: &mut R) -> U {
182            U::dummy_with_rng(self, rng)
183        }
184    }
185}
186
187/// Generate fake values given a type that implements [`Dummy`].
188/// The opposite of [`Dummy`].
189///
190/// Generate default fake values with [`Faker`].
191/// Generate specific fake values with helpers in [`faker`].
192///
193/// This trait is implemented for any type that implements [`Dummy`]:
194/// [`Dummy`] should be implemented instead, and you get the [`Fake`]
195/// implementation for free.
196///
197/// [`Dummy`] is similar to [`From`] trait, while [`Fake`] is similar to
198/// [`Into`] trait. Except in this case [`Fake`] cannot be implemented.
199///
200/// # Examples
201///
202/// ```
203/// use fake::Fake;
204///
205/// assert_eq!(10.fake::<String>().len(), 10);
206/// let a: [[u8; 2]; 3] = (1..10).fake();
207/// let b: Option<Option<usize>> = (1..10).fake();
208/// ```
209pub trait Fake: Sized {
210    #[inline]
211    fn fake<U>(&self) -> U
212    where
213        Self: private::FakeBase<U>,
214    {
215        self._fake()
216    }
217
218    #[inline]
219    fn fake_with_rng<U, R: Rng + ?Sized>(&self, rng: &mut R) -> U
220    where
221        Self: private::FakeBase<U>,
222    {
223        self._fake_with_rng(rng)
224    }
225}
226impl<T> Fake for T {}
227
228#[cfg(feature = "geo")]
229#[cfg_attr(docsrs, doc(cfg(feature = "geo")))]
230fn unique<U: Dummy<Faker> + PartialEq, R: Rng + ?Sized>(rng: &mut R, len: usize) -> Vec<U> {
231    let mut set = Vec::<U>::new();
232    unique_append(&mut set, rng, len);
233    set
234}
235
236#[cfg(feature = "geo")]
237#[cfg_attr(docsrs, doc(cfg(feature = "geo")))]
238fn unique_append<U: Dummy<Faker> + PartialEq, R: Rng + ?Sized>(
239    set: &mut Vec<U>,
240    rng: &mut R,
241    len: usize,
242) {
243    while set.len() != len {
244        let new_item: U = Faker.fake_with_rng(rng);
245        let mut found = false;
246        for item in &mut *set {
247            if *item == new_item {
248                found = true;
249                break;
250            }
251        }
252        if !found {
253            set.push(new_item);
254        }
255    }
256}
257#[macro_use]
258mod impls;
259pub use impls::std::option::{Opt, Optional};
260pub use impls::std::path::PathFaker;
261pub use impls::std::result::ResultFaker;
262pub use impls::std::string::StringFaker;
263
264#[cfg(feature = "geo")]
265#[cfg_attr(docsrs, doc(cfg(feature = "geo")))]
266pub use impls::geo;
267
268#[cfg(feature = "ulid")]
269#[cfg_attr(docsrs, doc(cfg(feature = "ulid")))]
270pub use impls::ulid;
271
272#[cfg(feature = "uuid")]
273#[cfg_attr(docsrs, doc(cfg(feature = "uuid")))]
274pub use impls::uuid;
275
276#[cfg(feature = "rust_decimal")]
277#[cfg_attr(docsrs, doc(cfg(feature = "rust_decimal")))]
278pub use impls::decimal;
279
280#[cfg(any(feature = "bigdecimal", feature = "bigdecimal-rs"))]
281#[cfg_attr(
282    docsrs,
283    doc(cfg(any(feature = "bigdecimal", feature = "bigdecimal-rs")))
284)]
285pub use impls::bigdecimal;
286
287#[cfg(feature = "serde_json")]
288#[cfg_attr(docsrs, doc(cfg(feature = "serde_json")))]
289pub use impls::serde_json;
290
291#[cfg(feature = "time")]
292#[cfg_attr(docsrs, doc(cfg(feature = "time")))]
293pub use impls::time;
294
295#[cfg(feature = "chrono")]
296#[cfg_attr(docsrs, doc(cfg(feature = "chrono")))]
297pub use impls::chrono;
298
299#[cfg(feature = "bson_oid")]
300#[cfg_attr(docsrs, doc(cfg(feature = "bson_oid")))]
301pub use impls::bson_oid;
302
303#[cfg(feature = "base64")]
304#[cfg_attr(docsrs, doc(cfg(feature = "base64")))]
305pub use impls::base64;
306
307/// Fake value generation for specific formats.
308///
309/// It is structured in a way such that the modules here describes the custom
310/// group for structs implementing [`Dummy`] to generate custom fake formats.
311///
312/// Within the module, there is multiple modules. With `raw` module providing
313/// a generic faker requiring a locale ([`faker::lorem::raw::Paragraph<L>`])
314/// and the rest of the modules providing a localized faker
315/// ([`faker::lorem::en::Paragraph`]) as convenient functions.
316///
317/// # Examples
318///
319/// ```
320/// use fake::Fake;
321/// use fake::faker::lorem::en::*;
322///
323/// let words: Vec<String> = Words(3..5).fake();
324/// ```
325pub mod faker;
326/// Localized data for [`faker`]. May be incomplete.
327///
328/// Locales used for custom [`Dummy`] implementations within [`faker`] module.
329pub mod locales;
330
331/// Derive macro generating an impl of the trait [`Dummy`]. This works for both structs and enums.
332///
333/// # Attributes
334///
335/// For any fields in the type there are a number of keys that can be used to control the code generation.
336/// All of these go within the dummy attribute.
337///
338/// 1. `faker` key can be used to provide a specific faker for a field provided it implements [`Fake`].
339/// 2. `expr` key can be used to provide a rust expression as a fixed value.
340/// 3. `default` key sets the value to the types [`Default`] implementation.
341///
342/// # Examples
343///
344/// A simple example for deriving [`Dummy`] on a struct:
345///
346/// ```
347/// use fake::{Dummy, Fake, Faker};
348/// use fake::faker::name::en::Name;
349///
350/// #[derive(Dummy)]
351/// pub struct Foo {
352///     #[dummy(faker = "1000..2000")]
353///     order_id: usize,
354///     #[dummy(faker = "Name()")]
355///     customer: String,
356///     paid: bool,
357///     #[dummy(expr = "\"Fixed\".into()")]
358///     fixed_value: String,
359///     #[dummy(default)]
360///     other: String,
361/// }
362///
363/// let f: Foo = Faker.fake();
364/// ```
365///
366/// This would generate code roughly equivalent to:
367///
368/// ```
369/// use fake::{Dummy, Fake, Faker, Rng};
370/// use fake::faker::name::en::Name;
371///
372/// pub struct Foo {
373///     order_id: usize,
374///     customer: String,
375///     paid: bool,
376///     fixed_value: String,
377///     other: String,
378/// }
379///
380/// impl Dummy<Faker> for Foo {
381///     fn dummy_with_rng<R: Rng + ?Sized>(_: &Faker, rng: &mut R) -> Self {
382///         let order_id = Fake::fake_with_rng::<usize, _>(&(1000..2000), rng);
383///         let customer = Fake::fake_with_rng::<String, _>(&(Name()), rng);
384///         let paid = Fake::fake_with_rng::<bool, _>(&Faker, rng);
385///         let fixed_value = "Fixed".into();
386///         let other = Default::default();
387///         Self {
388///             order_id,
389///             customer,
390///             paid,
391///             fixed_value,
392///             other,
393///         }
394///     }
395/// }
396///
397/// let f: Foo = Faker.fake();
398/// ```
399///
400/// A simple example for deriving [`Dummy`] on an enum. For enum tuple variants the faker attribute
401/// is applied directly to the types in the tuple, for struct variants it is applied on each struct
402/// field.
403///
404/// ```
405/// use fake::{Dummy, Fake, Faker};
406/// use fake::faker::name::en::Name;
407///
408/// #[derive(Dummy)]
409/// pub enum Bar {
410///     Simple,
411///     Tuple(#[dummy(faker="0..5")] i32),
412///     Structure {
413///         #[dummy(faker = "1000..2000")]
414///         i: usize,
415///         j: String,
416///     }
417/// }
418///
419/// let b: Bar = Faker.fake();
420/// ```
421///
422/// This will generate code roughly equivalent to:
423///
424/// ```
425/// use fake::{Dummy, Fake, Faker, Rng};
426/// use fake::faker::name::en::Name;
427///
428/// pub enum Bar {
429///     Simple,
430///     Tuple(i32),
431///     Structure {
432///         i: usize,
433///         j: String,
434///     }
435/// }
436///
437/// impl Dummy<Faker> for Bar {
438///     fn dummy_with_rng<R: Rng + ?Sized>(_: &Faker, rng: &mut R) -> Self {
439///         match rng.random_range(0..3usize) {
440///             0 => Self::Simple,
441///             1 => Self::Tuple(Fake::fake_with_rng::<i32, _>(&(0..5), rng)),
442///             2 => {
443///                 let i = Fake::fake_with_rng::<usize, _>(&(1000..2000), rng);
444///                 let j = Fake::fake_with_rng::<String, _>(&Faker, rng);
445///                 Self::Structure { i, j }
446///             },
447///             _ => unreachable!(),
448///         }
449///     }
450/// }
451///
452/// let b: Bar = Faker.fake();
453/// ```
454#[cfg(feature = "derive")]
455#[cfg_attr(docsrs, doc(cfg(feature = "derive")))]
456pub use dummy::Dummy;
457
458pub mod utils;