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 rand::rngs::StdRng;
23//! use 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::{Dummy, Fake, Faker};
133/// use rand::Rng;
134/// use rand::seq::IndexedRandom;
135///
136/// struct Name; // does not handle locale, see locales module for more
137///
138/// impl Dummy<Name> for &'static str {
139///     fn dummy_with_rng<R: Rng + ?Sized>(_: &Name, rng: &mut R) -> &'static str {
140///         const NAMES: &[&str] = &["John Doe", "Jane Doe"];
141///         NAMES.choose(rng).unwrap()
142///     }
143/// }
144///
145/// let name: &str = Name.fake();
146/// assert!(name == "John Doe" || name == "Jane Doe");
147/// ```
148///
149/// # Derivable
150///
151/// The trait can be used with `#[derive]` if all the type's fields
152/// implement [`Fake`]. See [`Dummy`][macro@Dummy] for more.
153pub trait Dummy<T>: Sized {
154    /// Generate a dummy value for a type.
155    ///
156    /// This can be left as a blanket implemented most of the time since it
157    /// uses [`Dummy::dummy_with_rng`] under the hood.
158    fn dummy(config: &T) -> Self {
159        let mut r = rand::rng();
160        Dummy::<T>::dummy_with_rng(config, &mut r)
161    }
162
163    /// Generate a dummy value for a given type using a random number
164    /// generator.
165    fn dummy_with_rng<R: Rng + ?Sized>(config: &T, rng: &mut R) -> Self;
166}
167
168mod private {
169    pub trait FakeBase<T>: Sized {
170        fn _fake(&self) -> T;
171        fn _fake_with_rng<R: rand::Rng + ?Sized>(&self, rng: &mut R) -> T;
172    }
173
174    impl<T, U> FakeBase<U> for T
175    where
176        U: crate::Dummy<T>,
177    {
178        fn _fake(&self) -> U {
179            U::dummy(self)
180        }
181
182        fn _fake_with_rng<R: rand::Rng + ?Sized>(&self, rng: &mut R) -> U {
183            U::dummy_with_rng(self, rng)
184        }
185    }
186}
187
188/// Generate fake values given a type that implements [`Dummy`].
189/// The opposite of [`Dummy`].
190///
191/// Generate default fake values with [`Faker`].
192/// Generate specific fake values with helpers in [`faker`].
193///
194/// This trait is implemented for any type that implements [`Dummy`]:
195/// [`Dummy`] should be implemented instead, and you get the [`Fake`]
196/// implementation for free.
197///
198/// [`Dummy`] is similar to [`From`] trait, while [`Fake`] is similar to
199/// [`Into`] trait. Except in this case [`Fake`] cannot be implemented.
200///
201/// # Examples
202///
203/// ```
204/// use fake::Fake;
205///
206/// assert_eq!(10.fake::<String>().len(), 10);
207/// let a: [[u8; 2]; 3] = (1..10).fake();
208/// let b: Option<Option<usize>> = (1..10).fake();
209/// ```
210pub trait Fake: Sized {
211    #[inline]
212    fn fake<U>(&self) -> U
213    where
214        Self: private::FakeBase<U>,
215    {
216        self._fake()
217    }
218
219    #[inline]
220    fn fake_with_rng<U, R: Rng + ?Sized>(&self, rng: &mut R) -> U
221    where
222        Self: private::FakeBase<U>,
223    {
224        self._fake_with_rng(rng)
225    }
226}
227impl<T> Fake for T {}
228
229#[cfg(feature = "geo")]
230#[cfg_attr(docsrs, doc(cfg(feature = "geo")))]
231fn unique<U: Dummy<Faker> + PartialEq, R: Rng + ?Sized>(rng: &mut R, len: usize) -> Vec<U> {
232    let mut set = Vec::<U>::new();
233    unique_append(&mut set, rng, len);
234    set
235}
236
237#[cfg(feature = "geo")]
238#[cfg_attr(docsrs, doc(cfg(feature = "geo")))]
239fn unique_append<U: Dummy<Faker> + PartialEq, R: Rng + ?Sized>(
240    set: &mut Vec<U>,
241    rng: &mut R,
242    len: usize,
243) {
244    while set.len() != len {
245        let new_item: U = Faker.fake_with_rng(rng);
246        let mut found = false;
247        for item in &mut *set {
248            if *item == new_item {
249                found = true;
250                break;
251            }
252        }
253        if !found {
254            set.push(new_item);
255        }
256    }
257}
258#[macro_use]
259mod impls;
260pub use impls::std::option::{Opt, Optional};
261pub use impls::std::path::PathFaker;
262pub use impls::std::result::ResultFaker;
263pub use impls::std::string::StringFaker;
264
265#[cfg(feature = "geo")]
266#[cfg_attr(docsrs, doc(cfg(feature = "geo")))]
267pub use impls::geo;
268
269#[cfg(feature = "ulid")]
270#[cfg_attr(docsrs, doc(cfg(feature = "ulid")))]
271pub use impls::ulid;
272
273#[cfg(feature = "uuid")]
274#[cfg_attr(docsrs, doc(cfg(feature = "uuid")))]
275pub use impls::uuid;
276
277#[cfg(feature = "rust_decimal")]
278#[cfg_attr(docsrs, doc(cfg(feature = "rust_decimal")))]
279pub use impls::decimal;
280
281#[cfg(any(feature = "bigdecimal", feature = "bigdecimal-rs"))]
282#[cfg_attr(
283    docsrs,
284    doc(cfg(any(feature = "bigdecimal", feature = "bigdecimal-rs")))
285)]
286pub use impls::bigdecimal;
287
288#[cfg(feature = "serde_json")]
289#[cfg_attr(docsrs, doc(cfg(feature = "serde_json")))]
290pub use impls::serde_json;
291
292#[cfg(feature = "time")]
293#[cfg_attr(docsrs, doc(cfg(feature = "time")))]
294pub use impls::time;
295
296#[cfg(feature = "chrono")]
297#[cfg_attr(docsrs, doc(cfg(feature = "chrono")))]
298pub use impls::chrono;
299
300#[cfg(feature = "bson_oid")]
301#[cfg_attr(docsrs, doc(cfg(feature = "bson_oid")))]
302pub use impls::bson_oid;
303
304#[cfg(feature = "base64")]
305#[cfg_attr(docsrs, doc(cfg(feature = "base64")))]
306pub use impls::base64;
307
308/// Fake value generation for specific formats.
309///
310/// It is structured in a way such that the modules here describes the custom
311/// group for structs implementing [`Dummy`] to generate custom fake formats.
312///
313/// Within the module, there is multiple modules. With `raw` module providing
314/// a generic faker requiring a locale ([`faker::lorem::raw::Paragraph<L>`])
315/// and the rest of the modules providing a localized faker
316/// ([`faker::lorem::en::Paragraph`]) as convenient functions.
317///
318/// # Examples
319///
320/// ```
321/// use fake::Fake;
322/// use fake::faker::lorem::en::*;
323///
324/// let words: Vec<String> = Words(3..5).fake();
325/// ```
326pub mod faker;
327/// Localized data for [`faker`]. May be incomplete.
328///
329/// Locales used for custom [`Dummy`] implementations within [`faker`] module.
330pub mod locales;
331
332/// Derive macro generating an impl of the trait [`Dummy`]. This works for both structs and enums.
333///
334/// # Attributes
335///
336/// For any fields in the type there are a number of keys that can be used to control the code generation.
337/// All of these go within the dummy attribute.
338///
339/// 1. `faker` key can be used to provide a specific faker for a field provided it implements [`Fake`].
340/// 2. `expr` key can be used to provide a rust expression as a fixed value.
341/// 3. `default` key sets the value to the types [`Default`] implementation.
342///
343/// # Examples
344///
345/// A simple example for deriving [`Dummy`] on a struct:
346///
347/// ```
348/// use fake::{Dummy, Fake, Faker};
349/// use fake::faker::name::en::Name;
350///
351/// #[derive(Dummy)]
352/// pub struct Foo {
353///     #[dummy(faker = "1000..2000")]
354///     order_id: usize,
355///     #[dummy(faker = "Name()")]
356///     customer: String,
357///     paid: bool,
358///     #[dummy(expr = "\"Fixed\".into()")]
359///     fixed_value: String,
360///     #[dummy(default)]
361///     other: String,
362/// }
363///
364/// let f: Foo = Faker.fake();
365/// ```
366///
367/// This would generate code roughly equivalent to:
368///
369/// ```
370/// use fake::{Dummy, Fake, Faker};
371/// use fake::faker::name::en::Name;
372/// use rand::Rng;
373///
374/// pub struct Foo {
375///     order_id: usize,
376///     customer: String,
377///     paid: bool,
378///     fixed_value: String,
379///     other: String,
380/// }
381///
382/// impl Dummy<Faker> for Foo {
383///     fn dummy_with_rng<R: Rng + ?Sized>(_: &Faker, rng: &mut R) -> Self {
384///         let order_id = Fake::fake_with_rng::<usize, _>(&(1000..2000), rng);
385///         let customer = Fake::fake_with_rng::<String, _>(&(Name()), rng);
386///         let paid = Fake::fake_with_rng::<bool, _>(&Faker, rng);
387///         let fixed_value = "Fixed".into();
388///         let other = Default::default();
389///         Self {
390///             order_id,
391///             customer,
392///             paid,
393///             fixed_value,
394///             other,
395///         }
396///     }
397/// }
398///
399/// let f: Foo = Faker.fake();
400/// ```
401///
402/// A simple example for deriving [`Dummy`] on an enum. For enum tuple variants the faker attribute
403/// is applied directly to the types in the tuple, for struct variants it is applied on each struct
404/// field.
405///
406/// ```
407/// use fake::{Dummy, Fake, Faker};
408/// use fake::faker::name::en::Name;
409///
410/// #[derive(Dummy)]
411/// pub enum Bar {
412///     Simple,
413///     Tuple(#[dummy(faker="0..5")] i32),
414///     Structure {
415///         #[dummy(faker = "1000..2000")]
416///         i: usize,
417///         j: String,
418///     }
419/// }
420///
421/// let b: Bar = Faker.fake();
422/// ```
423///
424/// This will generate code roughly equivalent to:
425///
426/// ```
427/// use fake::{Dummy, Fake, Faker};
428/// use fake::faker::name::en::Name;
429/// use rand::Rng;
430///
431/// pub enum Bar {
432///     Simple,
433///     Tuple(i32),
434///     Structure {
435///         i: usize,
436///         j: String,
437///     }
438/// }
439///
440/// impl Dummy<Faker> for Bar {
441///     fn dummy_with_rng<R: Rng + ?Sized>(_: &Faker, rng: &mut R) -> Self {
442///         match rng.random_range(0..3usize) {
443///             0 => Self::Simple,
444///             1 => Self::Tuple(Fake::fake_with_rng::<i32, _>(&(0..5), rng)),
445///             2 => {
446///                 let i = Fake::fake_with_rng::<usize, _>(&(1000..2000), rng);
447///                 let j = Fake::fake_with_rng::<String, _>(&Faker, rng);
448///                 Self::Structure { i, j }
449///             },
450///             _ => unreachable!(),
451///         }
452///     }
453/// }
454///
455/// let b: Bar = Faker.fake();
456/// ```
457#[cfg(feature = "derive")]
458#[cfg_attr(docsrs, doc(cfg(feature = "derive")))]
459pub use dummy::Dummy;
460
461pub mod utils;