### Quickstart Examples Source: https://github.com/cksac/fake-rs/blob/master/_autodocs/MANIFEST.txt A collection of 16 runnable practical examples demonstrating various aspects of fake-rs, from simple type generation to complex nested structures and derive macro usage. ```APIDOC ## Quickstart Examples ### Description This section provides a set of practical, runnable examples designed to help users quickly understand and utilize the capabilities of the fake-rs library. These examples cover a range of common use cases and advanced features. ### Example Scenarios 1. **Simple Type Generation**: Demonstrates basic data generation for primitive types. 2. **Generation with Ranges**: Shows how to generate data within specified numerical or date ranges. 3. **Using Faker Modules**: Illustrates the usage of specific faker modules like `Name` or `Internet`. 4. **Struct with Derive Macro**: Example of generating data for a custom struct using `#[derive(Dummy)]`. 5. **Nested Structures**: Demonstrates generating data for structs containing other structs or collections. 6. **Locale-Specific Data**: Shows how to generate data using different locales. 7. **Feature Integration Usage**: Examples of generating data for types from integrated crates (e.g., `chrono`, `uuid`). 8. **Custom Faker Implementation**: Illustrates how to define and use custom faker logic. 9. **Enum Generation**: Examples of generating data for enum types. 10. **Wrapper Type Generation**: Demonstrates generating data for wrapped values. 11. **Conditional Generation**: Using `EitherFaker` for generating data based on conditions. 12. **Macro Usage**: Examples of using utility macros like `vec!`. 13. **RNG Integration**: Demonstrates using custom random number generators. 14. **Error Handling Examples**: Shows common errors and their solutions. 15. **Complex Data Structures**: Generating data for deeply nested or complex types. 16. **Real-world Scenarios**: Practical examples simulating common application needs. ### Usage Each example is self-contained and includes the necessary code to compile and run, allowing users to experiment directly with fake-rs functionality. ``` -------------------------------- ### Quickstart Example: Simple Type Generation Source: https://github.com/cksac/fake-rs/blob/master/_autodocs/MANIFEST.txt A basic example demonstrating the generation of a single primitive data type. ```Rust use fake::{Fake, Faker}; let random_number: u32 = Faker.fake(); println!("Random number: {}", random_number); ``` -------------------------------- ### Quickstart Example: Generation with Ranges Source: https://github.com/cksac/fake-rs/blob/master/_autodocs/MANIFEST.txt Shows how to generate data within a specified numerical range. ```Rust use fake::{Fake, Faker}; use std::ops::RangeInclusive; let number_in_range: u32 = Faker.fake(RangeInclusive::new(10, 100)); println!("Number in range [10, 100]: {}", number_in_range); ``` -------------------------------- ### Quickstart Example: Nested Structures Source: https://github.com/cksac/fake-rs/blob/master/_autodocs/MANIFEST.txt Shows how to generate instances of structs that contain other structs or collections. ```Rust use fake::{Fake, Faker, Dummy}; #[derive(Dummy, Debug)] struct Address { street: String, city: String, } #[derive(Dummy, Debug)] struct Profile { user_id: u64, address: Address, tags: Vec, } let profile: Profile = Faker.fake(); println!("Generated profile: {:?}", profile); ``` -------------------------------- ### Quickstart Example: Using Faker Modules Source: https://github.com/cksac/fake-rs/blob/master/_autodocs/MANIFEST.txt Demonstrates generating data using specific faker modules like Name or Internet. ```Rust use fake::{Fake, Faker}; use fake::providers::internet::en::Name; let name: String = Faker.fake::(); println!("Generated name: {}", name); ``` -------------------------------- ### Start Local HTTP Server (Node.js) Source: https://github.com/cksac/fake-rs/blob/master/docs/MAINTENANCE.md Use `http-server` package with npx to serve your documentation locally. Ensure Node.js is installed. ```bash # Node.js npx http-server ``` -------------------------------- ### Quickstart Example: Struct with Derive Macro Source: https://github.com/cksac/fake-rs/blob/master/_autodocs/MANIFEST.txt Illustrates generating an instance of a struct that uses the `#[derive(Dummy)]` macro. ```Rust use fake::{Fake, Faker, Dummy}; #[derive(Dummy, Debug)] struct User { id: u32, username: String, } let user: User = Faker.fake(); println!("Generated user: {:?}", user); ``` -------------------------------- ### Start Local HTTP Server (PHP) Source: https://github.com/cksac/fake-rs/blob/master/docs/MAINTENANCE.md Use PHP's built-in web server to test documentation changes locally. Ensure PHP is installed. ```bash # PHP php -S localhost:8000 ``` -------------------------------- ### Minimal Dependencies Source: https://github.com/cksac/fake-rs/blob/master/_autodocs/00-index.md Example `Cargo.toml` dependencies for a minimal setup using `fake-rs` with only the `derive` feature enabled. ```toml [dependencies] fake = { version = "5", features = ["derive"] } ``` -------------------------------- ### Add New Example Configuration Source: https://github.com/cksac/fake-rs/blob/master/docs/README.md To add a new code example to the documentation, update the `data/examples.js` file by adding an object with a title, language, and the code itself. ```javascript { title: "Title", language: "rust", code: `...` } ``` -------------------------------- ### Log Examples Data Source: https://github.com/cksac/fake-rs/blob/master/docs/MAINTENANCE.md Ensure that the examples data is loaded correctly by logging it to the console. This is helpful for debugging scenarios where examples are not visible. ```javascript console.log(examplesData); // Should show array ``` -------------------------------- ### Add New Example to Data Source: https://github.com/cksac/fake-rs/blob/master/docs/MAINTENANCE.md Edit `docs/data/examples.js` to add a new example. Specify the title, language, code, and an optional note. ```javascript { title: "Example Title", language: "rust", // or "bash", "toml", etc. code: `your code here`, note: "⚠️ Optional note" // Optional } ``` -------------------------------- ### Examples.js Data Structure Source: https://github.com/cksac/fake-rs/blob/master/docs/MAINTENANCE.md Defines the structure for the examples data file, including example title, language, code content, and an optional note. Used for providing code examples. ```javascript const examplesData = [ { title: string, // Example title language: string, // "rust", "bash", "toml" code: string, // Code content note: string | undefined // Optional note } ]; ``` -------------------------------- ### Install fake-rs CLI Source: https://github.com/cksac/fake-rs/blob/master/README.md Install the fake-rs command-line interface using cargo. This command enables the 'cli' feature for installation. ```shell cargo install --features=cli --git https://github.com/cksac/fake-rs.git ``` -------------------------------- ### Feature Integration Example (Chrono) Source: https://github.com/cksac/fake-rs/blob/master/_autodocs/MANIFEST.txt Shows how to integrate fake-rs with external crates like `chrono` for generating DateTime types. ```Rust // Example usage with chrono integration // use chrono::NaiveDateTime; // let dt: NaiveDateTime = Faker.fake(); ``` -------------------------------- ### Install fake-rs CLI Tool Source: https://github.com/cksac/fake-rs/blob/master/docs/index.html Install the fake-rs command-line interface using cargo. Ensure to include the 'cli' feature and specify the Git repository. ```bash cargo install --features=cli --git https://github.com/cksac/fake-rs.git ``` -------------------------------- ### Feature Integration Example (UUID) Source: https://github.com/cksac/fake-rs/blob/master/_autodocs/MANIFEST.txt Demonstrates integrating fake-rs with the `uuid` crate to generate various versions of UUIDs. ```Rust // Example usage with uuid integration // use uuid::Uuid; // let uuid_v4: Uuid = Faker.fake(); ``` -------------------------------- ### Macro Expansion Example for Derive Macro Source: https://github.com/cksac/fake-rs/blob/master/_autodocs/05-derive-macro.md Provides an example of the generated `Dummy` trait implementation by the derive macro, showing how it translates attributes into actual code. ```rust use fake::{Dummy, RngExt, Fake, Faker}; use fake::faker::name::en::Name; // Original #[derive(Dummy)] struct Person { #[dummy(faker = "Name()")] name: String, #[dummy(faker = "18..65")] age: u8, } // Expands to approximately: impl Dummy for Person { fn dummy_with_rng(_: &Faker, rng: &mut R) -> Self { let name = >>::dummy_with_rng( &Name(fake::locales::EN), rng, ); let age = >>::dummy_with_rng( &(18..65), rng, ); Person { name, age } } } ``` -------------------------------- ### Local Development Server using PHP Source: https://github.com/cksac/fake-rs/blob/master/docs/README.md Start a local HTTP server using PHP to test the documentation site. Access the site via `http://localhost:8000`. ```bash php -S localhost:8000 ``` -------------------------------- ### Install fake-rs CLI with cli Feature Source: https://github.com/cksac/fake-rs/blob/master/_autodocs/04-feature-integrations.md Install the fake-rs command-line tool by enabling the 'cli' feature. This allows generating fake data directly from the terminal. ```toml [dependencies] fake = { version = "5", features = ["cli"] } ``` -------------------------------- ### Start Local HTTP Server (Python) Source: https://github.com/cksac/fake-rs/blob/master/docs/MAINTENANCE.md Use Python's built-in HTTP server to test documentation changes locally. Run this command in your project directory. ```bash # Python python -m http.server 8000 ``` -------------------------------- ### Faker Module Example Source: https://github.com/cksac/fake-rs/blob/master/_autodocs/MANIFEST.txt Illustrates how to use faker modules for generating specific types of data, such as addresses, names, or internet-related information. ```Rust // Example usage of faker modules (specific module not shown in source) // let address: Address = Faker.fake(); // let name: Name = Faker.fake(); // let internet: Internet = Faker.fake(); ``` -------------------------------- ### Local Development Server using Python Source: https://github.com/cksac/fake-rs/blob/master/docs/README.md Start a local HTTP server using Python's built-in module to test the documentation site. Access the site via `http://localhost:8000`. ```bash python -m http.server 8000 ``` -------------------------------- ### Rust Code Examples for Fake Data Generation Source: https://github.com/cksac/fake-rs/blob/master/fake/README.md Examples demonstrating how to use the 'fake' crate in Rust for generating various types of fake data, including custom structs, collections, and locale-specific data. ```APIDOC ## Rust Fake Data Generation Examples This section provides examples of using the `fake` crate in Rust to generate various types of fake data. ### Basic Usage Generate a custom struct `Foo`: ```rust use fake::{Dummy, Fake, Faker}; #[derive(Debug, Dummy)] pub struct Foo { #[dummy(faker = "1000..2000")] order_id: usize, customer: String, paid: bool, } let f: Foo = Faker.fake(); println!("{:?}", f); ``` Generate a generic struct `Bar` containing `Foo`: ```rust use fake::{Dummy, Fake, Faker}; #[derive(Debug, Dummy)] struct Bar { field: Vec, } let b: Bar = Faker.fake(); println!("{:?}", b); ``` Generate a tuple: ```rust let tuple = Faker.fake::<(u8, u32, f32)>(); println!("tuple {:?}", tuple); ``` Generate a `String`: ```rust println!("String {:?}", Faker.fake::()); ``` Generate data using a range: ```rust println!("String {:?}", (8..20).fake::()); println!("u32 {:?}", (8..20).fake::()); ``` ### Locale-Specific Data Generate a name using the English locale: ```rust use fake::faker::name::raw::*; use fake::locales::EN; let name: String = Name(EN).fake(); println!("name {:?}", name); ``` Generate a name using the Traditional Chinese locale: ```rust use fake::faker::name::raw::*; use fake::locales::ZH_TW; let name: String = Name(ZH_TW).fake(); println!("name {:?}", name); ``` Generate words using a convenient function (defaults to English): ```rust use fake::faker::lorem::en::*; let words: Vec = Words(3..5).fake(); println!("words {:?}", words); ``` ### Nested Collections Generate a nested vector of names: ```rust let name_vec = fake::vec![String as Name(EN); 4, 3..5, 2]; println!("random nested vec {:?}", name_vec); ``` ### Using a Fixed Seed RNG Generate values using a specific random number generator seed: ```rust use fake::rand::rngs::StdRng; use fake::rand::SeedableRng; use fake::{Dummy, Fake, Faker}; let seed = [ 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, 0, 0, 0, 0, ]; let mut r = StdRng::from_seed(seed); for _ in 0..5 { let v: usize = Faker.fake_with_rng(r); println!("value from fixed seed {}", v); } ``` ``` -------------------------------- ### Local Development Server using Node.js http-server Source: https://github.com/cksac/fake-rs/blob/master/docs/README.md Start a local HTTP server using the `http-server` package via npx to test the documentation site. Access the site via `http://localhost:8000`. ```bash npx http-server ``` -------------------------------- ### Database Testing Dependencies Source: https://github.com/cksac/fake-rs/blob/master/_autodocs/00-index.md Example `Cargo.toml` dependencies for database testing using `fake-rs` with features for `derive`, `chrono`, and `serde_json`. ```toml [dependencies] fake = { version = "5", features = ["derive", "chrono", "serde_json"] } ``` -------------------------------- ### Barcode Generation Examples Source: https://github.com/cksac/fake-rs/blob/master/_autodocs/02-faker-modules.md Generates different formats of ISBN barcodes (ISBN, ISBN-10, ISBN-13) using the English locale. ```rust use fake::Fake; use fake::faker::barcode::en::*; let isbn = Isbn().fake::(); let isbn10 = Isbn10().fake::(); let isbn13 = Isbn13().fake::(); ``` -------------------------------- ### Address Generation Examples Source: https://github.com/cksac/fake-rs/blob/master/_autodocs/02-faker-modules.md Generates various address components like city names, zip codes, latitude, and geohashes using the English locale. ```rust use fake::Fake; use fake::faker::address::en::*; let city = CityName().fake::(); let zip = ZipCode().fake::(); let lat: f64 = Latitude().fake(); let hash = Geohash(8).fake::(); ``` -------------------------------- ### Implementing Custom Locales Source: https://github.com/cksac/fake-rs/blob/master/_autodocs/03-locales.md Provides an example of how to implement custom locales by creating a struct and implementing the `Data` trait. All required constants for the desired categories must be defined. ```rust use fake::locales::Data; pub struct MY_CUSTOM; impl Data for MY_CUSTOM { const ADDRESS_CITY_PREFIX: &'static [&'static str] = &["North", "South"]; const ADDRESS_CITY_SUFFIX: &'static [&'static str] = &["ville", "burg"]; // ... implement all required constants } ``` -------------------------------- ### Generate Markdown Elements Source: https://github.com/cksac/fake-rs/blob/master/README.md Provides examples for generating various markdown elements like italics, bold text, links, lists, and blockquotes. ```rust ItalicWord(); BoldWord(); Link(); BulletPoints(); ListItems(); BlockQuoteSingleLine(); BlockQuoteMultiLine(); Code(); ``` -------------------------------- ### Command Line Interface for Fake Data Generation Source: https://github.com/cksac/fake-rs/blob/master/fake/README.md Examples of using the `fake` command-line tool to generate fake data for various types, with options for count, locale, and specific generator arguments. ```APIDOC ## Command Line Usage The `fake` command-line tool allows generating fake data directly from the terminal. ### Generating Random Names Generate a single random name (defaults to English locale): ```shell ❯ ./fake Name Generating 1 fakes for EN locale Theresa Walker ``` Generate 5 Chinese random names: ```shell ❯ ./fake -r5 -lzh_cn Name Generating 5 fakes for ZH_CN locale 何丹华 尹雅瑾 于金福 郭雨珍 龙菲霞 ``` ### Generating Passwords with Options Generate 5 random passwords with a minimum length of 10 characters: ```shell ❯ ./fake -r5 Password --min 10 Generating 5 fakes for EN locale Q6eeXHfC3uzSRqtZwB 6fDHAOh3I7Ah77duLL R8ygoTLmd4i1z1Z 5Uxj3RdEK5O4Af3ow 2XWsGT0lUaDnMZTb7 ``` ### Viewing Generator Help View available options for a specific generator, like `Password`: ```shell ❯ ./fake Password --help Usage: fake Password [OPTIONS] Options: --max [default: 20] --min [default: 10] -h, --help Print help ``` ``` -------------------------------- ### Feature Integrations Source: https://github.com/cksac/fake-rs/blob/master/_autodocs/MANIFEST.txt Details on integrating fake-rs with 18+ external crates, including support for chrono, uuid, rust_decimal, and more, with usage examples for each integration. ```APIDOC ## Feature Integrations ### Description This section covers the extensive integrations fake-rs offers with various popular Rust crates, enhancing its data generation capabilities. It details the supported types and provides practical usage examples for each integration. ### Supported Integrations - **chrono**: DateTime types - **uuid**: UUID v1-v8 - **ulid**: ULID - **ferroid**: Distributed IDs - **rust_decimal**: Decimal - **bigdecimal**: BigDecimal - **chrono-tz**: Timezone-aware types - **http**: HTTP types (e.g., StatusCode, Method) - **semver**: Semantic versioning - **serde_json**: JSON types - **time**: Time crate types - **geo**: Geographic types - **glam**: Math vectors and matrices - **url**: URL types - **either**: Either - **bson_oid**: MongoDB ObjectId - **indexmap**: IndexMap and IndexSet - **email_address**: Email validation types - **base64**: Base64 encoded strings - **random_color**: Color types ### Usage Each integration is documented with the specific types it supports and includes code examples demonstrating how to generate data for those types using fake-rs. ``` -------------------------------- ### Full Stack Dependencies Source: https://github.com/cksac/fake-rs/blob/master/_autodocs/00-index.md Example `Cargo.toml` dependencies for full-stack development using `fake-rs` with a comprehensive set of features including `derive`, `chrono`, `uuid`, `ulid`, `rust_decimal`, `bigdecimal`, `http`, `semver`, `url`, and `geo`. ```toml [dependencies] fake = { version = "5", features = [ "derive", "chrono", "uuid", "ulid", "rust_decimal", "bigdecimal", "http", "semver", "url", "geo" ] } ``` -------------------------------- ### Web API Testing Dependencies Source: https://github.com/cksac/fake-rs/blob/master/_autodocs/00-index.md Example `Cargo.toml` dependencies for web API testing using `fake-rs` with features for `derive`, `chrono`, `uuid`, and `http`. ```toml [dependencies] fake = { version = "5", features = ["derive", "chrono", "uuid", "http"] } ``` -------------------------------- ### Generate Fake Data with fake-rs CLI Source: https://github.com/cksac/fake-rs/blob/master/_autodocs/04-feature-integrations.md Examples of using the fake-rs CLI to generate various types of fake data, including names, phone numbers, and passwords with specific constraints. ```bash cargo install fake --features cli fake Name # Generate a name fake -r 5 -l zh_cn Name # Generate 5 Chinese names fake -r 10 Password --min 12 # 10 passwords minimum 12 chars ``` -------------------------------- ### Generate Fake Data in Rust Source: https://github.com/cksac/fake-rs/blob/master/README.md Demonstrates how to generate various types of fake data using the fake-rs library, including custom structs, tuples, strings, and locale-specific data. Includes examples for using fixed seed RNG. ```rust use fake::{Dummy, Fake, Faker}; use fake::rand::rngs::StdRng; use fake::rand::SeedableRng; #[derive(Debug, Dummy)] pub struct Foo { #[dummy(faker = "1000..2000")] order_id: usize, customer: String, paid: bool, } #[derive(Debug, Dummy)] struct Bar { field: Vec, } fn main() { // type derived Dummy let f: Foo = Faker.fake(); println!("{:?}", f); let b: Bar = Faker.fake(); println!("{:?}", b); // using `Faker` to generate default fake value of given type let tuple = Faker.fake::<(u8, u32, f32)>(); println!("tuple {:?}", tuple); println!("String {:?}", Faker.fake::()); // types U can used to generate fake value T, if `T: Dummy` println!("String {:?}", (8..20).fake::()); println!("u32 {:?}", (8..20).fake::()); // using `faker` module with locales use fake::faker::name::raw::*; use fake::locales::*; let name: String = Name(EN).fake(); println!("name {:?}", name); let name: String = Name(ZH_TW).fake(); println!("name {:?}", name); // using convenient function without providing locale use fake::faker::lorem::en::*; let words: Vec = Words(3..5).fake(); println!("words {:?}", words); // using macro to generate nested collection let name_vec = fake::vec![String as Name(EN); 4, 3..5, 2]; println!("random nested vec {:?}", name_vec); // fixed seed rng let seed = [ 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, 0, 0, 0, 0, ]; let ref mut r = StdRng::from_seed(seed); for _ in 0..5 { let v: usize = Faker.fake_with_rng(r); println!("value from fixed seed {}", v); } } ``` -------------------------------- ### IntoInner Trait Implementation Example Source: https://github.com/cksac/fake-rs/blob/master/_autodocs/07-utilities-and-macros.md Example implementation of the IntoInner trait for a custom Wrapper struct. ```rust use fake::utils::IntoInner; struct Wrapper(T); impl IntoInner for Wrapper { type Target = T; fn into_inner(self) -> T { self.0 } } let wrapped = Wrapper(42); let inner: i32 = wrapped.into_inner(); assert_eq!(inner, 42); ``` -------------------------------- ### Display Help for Password Generator Command Line Source: https://github.com/cksac/fake-rs/blob/master/fake/README.md Shows how to display the help message for a specific fake generator, such as `Password`, to see available options and their defaults. ```shell ./fake Password --help ``` -------------------------------- ### Fake CLI Help Source: https://github.com/cksac/fake-rs/blob/master/fake/README.md Display the help information for the fake CLI tool, listing all available commands and options. ```shell ❯ fake An easy to use library and command line for generating fake data like name, number, address, lorem, dates, etc. Usage: fake [OPTIONS] [COMMAND] Commands: CityPrefix CitySuffix CityName CountryName CountryCode StreetSuffix StreetName TimeZone StateName StateAbbr SecondaryAddressType SecondaryAddress ZipCode PostCode BuildingNumber Latitude Longitude Geohash Isbn Isbn10 Isbn13 CreditCardNumber CompanySuffix CompanyName Buzzword BuzzwordMiddle BuzzwordTail CatchPhrase BsVerb BsAdj BsNoun Bs Profession Industry FreeEmailProvider DomainSuffix FreeEmail SafeEmail Username Password IPv4 IPv6 IP MACAddress UserAgent Seniority Field Position Word Words Sentence Sentences Paragraph Paragraphs FirstName LastName Title Suffix Name NameWithTitle PhoneNumber CellNumber FilePath FileName FileExtension DirPath MimeType Semver SemverStable SemverUnstable CurrencyCode CurrencyName CurrencySymbol Bic Isin HexColor RgbColor RgbaColor HslColor HslaColor Color Time Date DateTime RfcStatusCode ValidStatusCode help Print this message or the help of the given subcommand(s) Options: -r, --repeat [default: 1] -l, --locale [default: EN] -h, --help Print help -V, --version Print version ``` -------------------------------- ### Complex Nested Collections Generation Source: https://github.com/cksac/fake-rs/blob/master/_autodocs/07-utilities-and-macros.md Example of generating a 3D nested vector using the vec! macro, with assertions to verify the dimensions. ```rust use fake::Faker; use fake::faker::name::en::Name; let data = fake::vec![String as Name(); 3, 4, 5]; // 3 outer × 4 middle × 5 inner = 60 names total assert_eq!(data.len(), 3); assert_eq!(data[0].len(), 4); assert_eq!(data[0][0].len(), 5); ``` -------------------------------- ### GitHub Actions Workflow for Deploying GitHub Pages Source: https://github.com/cksac/fake-rs/blob/master/docs/README.md This YAML workflow automates the deployment of the documentation site to GitHub Pages upon pushes to the main branch or manual triggers. It requires specific permissions for contents, pages, and ID tokens. ```yaml name: Deploy GitHub Pages on: push: branches: [ main ] workflow_dispatch: permissions: contents: read pages: write id-token: write jobs: deploy: environment: name: github-pages url: ${{ steps.deployment.outputs.page_url }} runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v3 - name: Setup Pages uses: actions/configure-pages@v3 - name: Upload artifact uses: actions/upload-pages-artifact@v2 with: path: './docs' - name: Deploy to GitHub Pages id: deployment uses: actions/deploy-pages@v2 ``` -------------------------------- ### Basic Derive Macro Usage Source: https://github.com/cksac/fake-rs/blob/master/_autodocs/05-derive-macro.md Demonstrates the basic usage of the `#[derive(Dummy)]` macro with different field configurations including custom fakers, ranges, expressions, and default options. ```rust use fake::{Dummy, Faker, Fake}; use fake::faker::name::en::Name; #[derive(Dummy)] struct Person { #[dummy(faker = "Name()")gra] name: String, #[dummy(faker = "18..65")] age: u8, #[dummy(expr = "\"default@example.com\".into()")gra] email: String, #[dummy(default)] phone: Option, } let person: Person = Faker.fake(); println!("{:?}", person); ``` -------------------------------- ### Using either() for Random Email Type Generation Source: https://github.com/cksac/fake-rs/blob/master/_autodocs/07-utilities-and-macros.md Example demonstrating the use of the either() function with WrappedVal to generate either a FreeEmail or a SafeEmail for an Account struct. ```rust use fake::{Dummy, Faker, Fake}; use fake::faker::internet::en::{FreeEmail, SafeEmail}; use fake::utils::{either, WrappedVal}; #[derive(Dummy)] struct Account { #[dummy(faker = "either(FreeEmail(), SafeEmail())", wrapper = "WrappedVal")] email: String, } let account: Account = Faker.fake(); // Email is either from a free provider or a safe email ``` -------------------------------- ### fake-rs CLI Help Source: https://github.com/cksac/fake-rs/blob/master/README.md Display the help message for the fake-rs CLI tool, listing all available commands for generating fake data. ```shell ❯ fake An easy to use library and command line for generating fake data like name, number, address, lorem, dates, etc. Usage: fake [OPTIONS] [COMMAND] Commands: CityPrefix CitySuffix CityName CountryName CountryCode StreetSuffix StreetName TimeZone StateName StateAbbr SecondaryAddressType SecondaryAddress ZipCode PostCode BuildingNumber Latitude Longitude Geohash Isbn Isbn10 Isbn13 CreditCardNumber CompanySuffix CompanyName Buzzword BuzzwordMiddle BuzzwordTail CatchPhrase BsVerb BsAdj BsNoun Bs Profession Industry FreeEmailProvider DomainSuffix FreeEmail SafeEmail Username Password IPv4 IPv6 IP MACAddress UserAgent Seniority Field Position Word Words Sentence Sentences Paragraph Paragraphs ItalicWord BoldWord Link BulletPoints ListItems BlockQuoteSingleLine BlockQuoteMultiLine Code FirstName LastName Title Suffix Name NameWithTitle PhoneNumber CellNumber FilePath FileName FileExtension DirPath MimeType Semver SemverStable SemverUnstable CurrencyCode CurrencyName CurrencySymbol Bic Isin HexColor RgbColor RgbaColor HslColor HslaColor Color Time Date DateTime RfcStatusCode ValidStatusCode CommerceColor CommerceDepartment CommerceProductAdjective CommerceProductMaterial CommerceProductType CommerceProduct CommerceProductPrice CommercePromotionCode CommerceProductDescription CommerceUPC help Print this message or the help of the given subcommand(s) Options: -r, --repeat [default: 1] -l, --locale [default: EN] -h, --help Print help -V, --version Print version ``` -------------------------------- ### Adjust CSS Grid Layouts Source: https://github.com/cksac/fake-rs/blob/master/docs/MAINTENANCE.md Modify CSS properties in `styles.css` to adjust layout elements like grids. For example, change `grid-template-columns` for responsive grids. ```css .faker-grid { grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); } ``` -------------------------------- ### Generate HTTP Method and Status Code with Fake Source: https://github.com/cksac/fake-rs/blob/master/_autodocs/04-feature-integrations.md Demonstrates generating http::Method and http::StatusCode using the Dummy derive macro and Faker. Requires the 'http' feature. ```rust use fake::{Dummy, Faker, Fake}; use http::{Method, StatusCode}; #[derive(Dummy)] struct HttpRequest { method: Method, #[dummy(faker = "\"http://example.com\".into()")] url: String, } let request: HttpRequest = Faker.fake(); let status: StatusCode = Faker.fake(); ``` -------------------------------- ### Generate a localized faker value in Rust Source: https://github.com/cksac/fake-rs/blob/master/docs/index.html Generate a fake data value using a specific faker and locale. This example demonstrates generating a name in the Chinese locale. ```rust Name(ZH_CN).fake() ``` -------------------------------- ### View Password Generator Help Source: https://github.com/cksac/fake-rs/blob/master/README.md Displays the help message for the Password generator, showing available options like --max and --min for controlling password length. This is useful for understanding generator capabilities. ```shell ./fake Password --help ``` -------------------------------- ### Using either() for Random Number Range Generation Source: https://github.com/cksac/fake-rs/blob/master/_autodocs/07-utilities-and-macros.md Example showing the use of the either() function with WrappedVal to generate a u32 value within one of two specified ranges. ```rust use fake::{Dummy, Faker, Fake}; use fake::utils::{either, WrappedVal}; #[derive(Dummy)] struct Data { #[dummy(faker = "either(1..100, 1000..2000)", wrapper = "WrappedVal")] value: u32, } let data: Data = Faker.fake(); // Value is either 1-99 or 1000-1999 ``` -------------------------------- ### Generate a default String value in Rust Source: https://github.com/cksac/fake-rs/blob/master/docs/index.html Generate a default String value using the Faker struct. This is a simple way to get a fake string for testing or placeholder purposes. ```rust let s: String = Faker.fake(); ``` -------------------------------- ### Generate Glam Vec3 with Fake Source: https://github.com/cksac/fake-rs/blob/master/_autodocs/04-feature-integrations.md Demonstrates generating a glam::Vec3 using the Dummy derive macro and Faker. Requires the 'glam' feature. ```rust use fake::{Dummy, Faker, Fake}; use glam::Vec3; #[derive(Dummy)] struct Position { coords: Vec3, } let position: Position = Faker.fake(); ``` -------------------------------- ### Generate Semver Version with Fake Source: https://github.com/cksac/fake-rs/blob/master/_autodocs/04-feature-integrations.md Demonstrates generating semver::Version using the Dummy derive macro and Faker. Requires the 'semver' feature. ```rust use fake::{Dummy, Faker, Fake}; use semver::Version; #[derive(Dummy)] struct Package { name: String, version: Version, } let package: Package = Faker.fake(); ``` -------------------------------- ### Derive Dummy for Enums Source: https://github.com/cksac/fake-rs/blob/master/_autodocs/08-quickstart-examples.md This example demonstrates how to derive the `Dummy` trait for enum types, allowing `Faker` to generate random variants of the enums. It covers both unit-like enums and enums with associated data. ```rust use fake::{Dummy, Faker, Fake}; #[derive(Dummy, Debug)] enum Status { Active, Inactive, Pending, } #[derive(Dummy, Debug)] enum Message { Text(String), Number(u32), Empty, } fn main() { let status: Status = Faker.fake(); println!("Status: {:?}", status); let msg: Message = Faker.fake(); println!("Message: {:?}", msg); } ``` -------------------------------- ### Generate Optional and Result Values Source: https://github.com/cksac/fake-rs/blob/master/_autodocs/08-quickstart-examples.md Demonstrates how to generate `Option` and `Result` types with a 50/50 chance of `Some`/`Ok` or `None`/`Err`. Also shows how to use a custom RNG to always generate `Some` values. ```rust use fake::Fake; use fake::Faker; fn main() { // Optional values (50/50 Some/None) let opt: Option = Faker.fake(); println!("Optional: {:?}", opt); // Result values (50/50 Ok/Err) let res: Result = Faker.fake(); println!("Result: {:?}", res); // Guarded some values use fake::utils::AlwaysTrueRng; let mut rng = AlwaysTrueRng::default(); let always_some: Option = Faker.fake_with_rng(&mut rng); println!("Always Some: {:?}", always_some); } ``` -------------------------------- ### BigDecimal Operations in Rust Source: https://github.com/cksac/fake-rs/blob/master/fake/README.md Demonstrates various BigDecimal operations. Ensure BigDecimal is correctly imported and used. ```rust BigDecimal(); PositiveBigDecimal(); NegativeBigDecimal(); NoBigDecimalPoints(); ``` -------------------------------- ### Generate Default Fake Values with Faker Source: https://github.com/cksac/fake-rs/blob/master/_autodocs/01-core-traits.md Use the Faker struct with the .fake() method to generate default fake values for various types. This example also shows generating values with a custom seeded RNG. ```rust use fake::{Fake, Faker}; // Generate default fake values let s: String = Faker.fake(); let num: u32 = Faker.fake(); let tuple: (u8, u32, f32) = Faker.fake(); // With custom RNG use fake::rand::rngs::StdRng; use fake::rand::SeedableRng; let mut rng = StdRng::seed_from_u64(42); let s: String = Faker.fake_with_rng(&mut rng); ``` -------------------------------- ### Utilities and Macros Source: https://github.com/cksac/fake-rs/blob/master/_autodocs/MANIFEST.txt Documentation for utility traits and macros provided by fake-rs, such as `IntoInner`, `WrappedVal`, `EitherFaker`, and the `vec!` macro. ```APIDOC ## Utilities and Macros ### Description This section covers the various utility traits and macros offered by fake-rs to enhance data generation workflows and provide convenient abstractions. ### Utilities - **`IntoInner` trait**: Facilitates unwrapping values from wrapper types. - **`WrappedVal`**: A general-purpose wrapper type for custom data structures. - **`EitherFaker`**: Enables conditional generation between two faker types. - **`either()` function**: A helper function for creating `EitherFaker` instances. - **`AlwaysTrueRng`**: A special random number generator that always produces `true` for boolean checks, useful for guaranteeing `Some` or `Ok` values. ### Macros - **`vec!` macro**: A convenient macro for creating nested collection types, particularly `Vec`. - **`rand` crate re-export**: Provides direct access to re-exported functionalities from the `rand` crate. ### Usage These utilities and macros are designed to streamline common data generation tasks, offering flexibility and ease of use in various scenarios. Code examples are provided for all utilities to illustrate their practical application. ``` -------------------------------- ### Generate UUIDs Source: https://github.com/cksac/fake-rs/blob/master/README.md Shows how to generate various versions of UUIDs. ```rust UUIDv1(); UUIDv3(); UUIDv4(); UUIDv5(); ``` -------------------------------- ### Generate Random Passwords with Minimum Length from Command Line Source: https://github.com/cksac/fake-rs/blob/master/fake/README.md Command-line usage for generating random passwords with a specified minimum length. ```shell ./fake -r5 Password --min 10 ``` -------------------------------- ### Built-in Types Support Source: https://github.com/cksac/fake-rs/blob/master/_autodocs/MANIFEST.txt Comprehensive documentation on fake-rs' support for generating data for all standard library types, including primitives, collections, smart pointers, and more. ```APIDOC ## Built-in Types Support ### Description This section details the extensive support within fake-rs for generating data for a wide array of standard Rust types. It covers primitives, collections, smart pointers, strings, options, results, and more. ### Supported Types - **Primitives**: `u8` to `u128`, `i8` to `i128`, `f32`, `f64`, `bool`, `char` - **Collections**: `Vec`, `HashMap`, `HashSet`, `BTreeMap`, `BTreeSet`, `VecDeque`, `LinkedList`, `BinaryHeap` - **Smart Pointers**: `Box`, `Arc`, `Rc`, `Cell`, `RefCell`, `Mutex`, `RwLock`, `Pin` - **Strings and Paths**: `String`, `&str`, `Path`, `PathBuf` - **Arrays and Tuples**: Fixed-size arrays and tuple types. - **Options and Results**: `Option`, `Result` - **Ranges**: Inclusive, exclusive, and full ranges. - **Wrapping Types**: Types like `NonZeroU8`, etc. ### Features - **Type Conversion Patterns**: Guidance on converting between related types. - **Nested Generics Handling**: Robust support for complex nested generic types. ### Usage Developers can directly generate data for these built-in types using the `Dummy` or `Fake` traits, or via the `#[derive(Dummy)]` macro. ``` -------------------------------- ### Generate Localized Names Source: https://github.com/cksac/fake-rs/blob/master/_autodocs/08-quickstart-examples.md Shows how to generate names in different locales (English, French, Chinese) using the `fake` crate. ```rust use fake::Fake; use fake::faker::name::raw::Name; use fake::locales::{EN, FR_FR, ZH_CN}; fn main() { let english_name: String = Name(EN).fake(); println!("English: {}", english_name); let french_name: String = Name(FR_FR).fake(); println!("French: {}", french_name); let chinese_name: String = Name(ZH_CN).fake(); println!("Chinese: {}", chinese_name); } ``` -------------------------------- ### Generating Locale-Specific State Abbreviations Source: https://github.com/cksac/fake-rs/blob/master/_autodocs/03-locales.md Demonstrates generating state abbreviations for different countries using their respective locale providers. Note the use of `as` to alias providers when names conflict. ```rust use fake::Fake; use fake::faker::address::en::StateAbbr; use fake::faker::address::de_de::StateAbbr as DeStateAbbr; let us_state: &str = StateAbbr().fake(); // "CA" let de_state: &str = DeStateAbbr().fake(); // "Bayern" ``` -------------------------------- ### Generate Ferroid IDs Source: https://github.com/cksac/fake-rs/blob/master/README.md Demonstrates the generation of different Ferroid-based IDs. ```rust FerroidULID(); FerroidTwitterId(); FerroidInstagramId(); FerroidMastodonId(); FerroidDiscordId(); ``` -------------------------------- ### Using Faker with Locales in Rust Source: https://github.com/cksac/fake-rs/blob/master/fake/README.md Illustrates how to generate fake data using specific locales for names. This allows for culturally relevant data generation. ```rust use fake::faker::name::raw::*; use fake::locales::*; let name: String = Name(EN).fake(); println!("name {:?}", name); let name: String = Name(ZH_TW).fake(); println!("name {:?}", name); ``` -------------------------------- ### Built-in Type Generation (Options and Results) Source: https://github.com/cksac/fake-rs/blob/master/_autodocs/MANIFEST.txt Demonstrates generating values for Option and Result types, including handling of None and Err variants. ```Rust // Example generation for Option and Result // let maybe_value: Option = Faker.fake(); // let outcome: Result = Faker.fake(); ``` -------------------------------- ### Generating Locale-Specific Names Source: https://github.com/cksac/fake-rs/blob/master/_autodocs/03-locales.md Illustrates generating first names using different locale providers. Ensure the correct faker provider for the desired locale is imported. ```rust use fake::Fake; use fake::faker::name::en::FirstName as EnFirstName; use fake::faker::name::zh_cn::FirstName as CnFirstName; let en_name: String = EnFirstName().fake(); // "John" let cn_name: String = CnFirstName().fake(); // "王" ``` -------------------------------- ### Generating Locale-Specific Postal Codes Source: https://github.com/cksac/fake-rs/blob/master/_autodocs/03-locales.md Illustrates generating postal codes, which vary in format by country. Use the appropriate faker provider for the target locale. ```rust use fake::Fake; use fake::faker::address::en::ZipCode; use fake::faker::address::de_de::PostCode; let us_zip: String = ZipCode().fake(); // "12345" let de_post: String = PostCode().fake(); // "12345" ``` -------------------------------- ### Mixing Locales in a Program Source: https://github.com/cksac/fake-rs/blob/master/_autodocs/03-locales.md Illustrates how to use multiple locales (EN, FR_FR, ZH_CN) within the same program to generate fake data in different languages. ```rust use fake::Fake; use fake::faker::name::raw::Name; use fake::locales::{EN, FR_FR, ZH_CN}; let english_name: String = Name(EN).fake(); let french_name: String = Name(FR_FR).fake(); let chinese_name: String = Name(ZH_CN).fake(); ``` -------------------------------- ### Minimal Import and Usage Source: https://github.com/cksac/fake-rs/blob/master/_autodocs/08-quickstart-examples.md Import Faker and the Fake trait to generate a default String value. ```rust use fake::{Fake, Faker}; fn main() { let name: String = Faker.fake(); println!("Generated name: {}", name); } ``` -------------------------------- ### Using AlwaysTrueRng for Guaranteed Some/Ok Values Source: https://github.com/cksac/fake-rs/blob/master/_autodocs/07-utilities-and-macros.md Demonstrates how to use AlwaysTrueRng to ensure that Option fields are always Some and Result fields are always Ok when generating data. ```rust use fake::{Dummy, Faker, Fake}; use fake::utils::AlwaysTrueRng; #[derive(Dummy)] struct Data { optional: Option, result: Result, } let mut rng = AlwaysTrueRng::default(); let data: Data = Faker.fake_with_rng(&mut rng); // Both fields will always have Some/Ok values assert!(data.optional.is_some()); assert!(data.result.is_ok()); ``` -------------------------------- ### Lorem Ipsum Text Generators Source: https://github.com/cksac/fake-rs/blob/master/_autodocs/02-faker-modules.md Generates various forms of Lorem Ipsum text, including words, sentences, and paragraphs. The `lorem` module must be imported. ```Rust use fake::Fake; use fake::faker::lorem::en::*; let word = Word().fake::(); let words: Vec = Words(5..10).fake(); let sentence = Sentence(3..8).fake::(); ``` -------------------------------- ### Add Dummy Crate Dependency Source: https://github.com/cksac/fake-rs/blob/master/dummy_derive/README.md Add the fake crate with the 'derive' feature enabled to your Cargo.toml file to use the derive(Dummy) macros. ```toml [dependencies] fake = { version = "4", features=["derive"] } ``` -------------------------------- ### Built-in Type Generation (Collections) Source: https://github.com/cksac/fake-rs/blob/master/_autodocs/MANIFEST.txt Shows how to generate common collection types such as Vec, HashMap, and HashSet. ```Rust // Example generation of collections // let vec: Vec = Faker.fake(); // let map: std::collections::HashMap = Faker.fake(); ``` -------------------------------- ### Seeding a Random Number Generator Source: https://github.com/cksac/fake-rs/blob/master/_autodocs/07-utilities-and-macros.md Demonstrates seeding a StdRng from the 'rand' crate with a byte array to generate reproducible random values. ```rust use fake::rand::rngs::StdRng; use fake::rand::SeedableRng; let seed = [1, 0, 0, 0, /* ... */]; let mut rng = StdRng::from_seed(seed); let value: u32 = Faker.fake_with_rng(&mut rng); ``` -------------------------------- ### Generate Time-Aware Appointment with Fake Source: https://github.com/cksac/fake-rs/blob/master/_autodocs/04-feature-integrations.md Demonstrates generating time-related types like Date, Time, and OffsetDateTime for an Appointment struct using the Dummy derive macro and Faker. Requires the 'time' feature. ```rust use fake::{Dummy, Faker, Fake}; use time::{Date, Time, OffsetDateTime}; #[derive(Dummy)] struct Appointment { date: Date, time: Time, created: OffsetDateTime, } let appointment: Appointment = Faker.fake(); ``` -------------------------------- ### Dummy Trait Methods Source: https://github.com/cksac/fake-rs/blob/master/_autodocs/MANIFEST.txt Demonstrates the core generation traits `Dummy` and `Fake`, including their `dummy()` and `fake()` methods, and integration with Random Number Generators (RNGs). ```Rust trait Dummy { fn dummy() -> Self; fn dummy_with_rng(_: &mut R) -> Self; } trait Fake: Dummy { fn fake() -> Self; fn fake_with_rng(_: &mut R) -> Self; } ``` -------------------------------- ### Generate Localized Structs Source: https://github.com/cksac/fake-rs/blob/master/_autodocs/08-quickstart-examples.md Demonstrates generating a struct with fields localized to a specific locale (French in this case), using the `Dummy` derive macro. ```rust use fake::{Dummy, Faker, Fake}; use fake::faker::name::raw::Name; use fake::locales::FR_FR; #[derive(Dummy, Debug)] struct PersonFrench { #[dummy(faker = "Name(FR_FR)")] nom: String, #[dummy(faker = "18..65")] age: u8, } fn main() { let person: PersonFrench = Faker.fake(); println!("{:#?}", person); } ``` -------------------------------- ### Generate Decimal Numbers Source: https://github.com/cksac/fake-rs/blob/master/README.md Illustrates the creation of decimal numbers with different properties. ```rust Decimal(); PositiveDecimal(); NegativeDecimal(); NoDecimalPoints(); ```