Skip to main content

OptionalSpec

Struct OptionalSpec 

Source
pub struct OptionalSpec {
    pub of: Box<Field>,
    pub prob: f64,
}
Expand description

Specification for conditional field generation based on probability.

OptionalSpec wraps any field type and generates its value conditionally based on a probability threshold. This enables modeling of optional or sparse data patterns commonly found in real-world JSON datasets.

§Fields

  • of: The wrapped field specification that will be generated when the probability condition is met
  • prob: Probability value (0.0 to 1.0) determining how often the field is generated

§Probability Behavior

  • 0.0: Field is never generated (always null)
  • 0.5: Field is generated 50% of the time (default)
  • 1.0: Field is always generated (never null)
  • Other values: Proportional probability of generation

§JGD Schema Examples

§Basic Optional String

{
  "bio": {
    "optional": {
      "of": "${lorem.paragraph}",
      "prob": 0.7
    }
  }
}

§Optional Nested Object

{
  "profile": {
    "optional": {
      "prob": 0.8,
      "of": {
        "fields": {
          "avatar": "${internet.avatar}",
          "social": {
            "fields": {
              "twitter": "${internet.userName}",
              "github": "${internet.userName}"
            }
          }
        }
      }
    }
  }
}

§Optional Array

{
  "tags": {
    "optional": {
      "prob": 0.6,
      "of": {
        "array": {
          "count": [1, 5],
          "of": "${lorem.word}"
        }
      }
    }
  }
}

§Default Probability

When prob is not specified in the JSON schema, it defaults to 0.5 (50% probability). This provides balanced optional field generation for realistic data patterns.

§Deserialization

The struct uses Serde’s #[serde(default)] attribute with a custom default function to provide the 0.5 probability when not explicitly specified in the input JSON.

Fields§

§of: Box<Field>

The field specification to generate when the probability condition is met.

This boxed field can be any valid Field type, including primitives, complex objects, arrays, or even nested optional specifications for multi-level conditional generation.

§prob: f64

Probability threshold for field generation (0.0 to 1.0).

  • Values closer to 0.0 make the field less likely to be generated
  • Values closer to 1.0 make the field more likely to be generated
  • Defaults to 0.5 when not specified in the JSON schema

§Valid Range

While the type allows any f64 value, probabilities should typically be between 0.0 and 1.0 for meaningful probability behavior.

Trait Implementations§

Source§

impl Clone for OptionalSpec

Source§

fn clone(&self) -> OptionalSpec

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for OptionalSpec

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<'de> Deserialize<'de> for OptionalSpec

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl JsonGenerator for OptionalSpec

Source§

fn generate( &self, config: &mut GeneratorConfig, local_config: Option<&mut LocalConfig>, ) -> Result<Value, JgdGeneratorError>

Generates a JSON value conditionally based on the configured probability.

This method implements the core probability-based generation logic for optional fields. It uses the random number generator from the configuration to determine whether to generate the wrapped field or return null.

§Parameters
  • config: Mutable reference to generator configuration containing the RNG state
§Returns
  • Value: Either the generated field value or Value::Null based on probability
§Algorithm
  1. Generate a random floating-point number between 0.0 and 1.0
  2. Compare it against the configured probability threshold
  3. If random value < probability: generate the wrapped field
  4. Otherwise: return Value::Null
§Probability Distribution

The method uses uniform random distribution, ensuring that over many generations, the actual presence rate will converge to the specified probability value.

§Examples
use jgd_rs::{OptionalSpec, Field, GeneratorConfig};

// 80% chance of generating a string
let optional_field = OptionalSpec {
    of: Box::new(Field::Str("Hello World".to_string())),
    prob: 0.8,
};

let mut config = GeneratorConfig::new("EN", Some(42));
let result = optional_field.generate(&mut config);
// Result: ~80% chance of Value::String("Hello World"), ~20% chance of Value::Null
§Deterministic Behavior

When using a seeded random number generator, the probability outcomes become deterministic and reproducible, which is useful for testing and consistent data generation across runs.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> Fake for T

Source§

fn fake<U>(&self) -> U
where Self: FakeBase<U>,

Source§

fn fake_with_rng<U, R>(&self, rng: &mut R) -> U
where R: Rng + ?Sized, Self: FakeBase<U>,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,