assert_none.rs

Overview

This file defines a Rust struct named StripAssertNoneStruct that leverages the derive_setters crate to automatically generate setter methods with special behaviors. The struct contains optional and non-optional fields, where setters enforce an invariant: attempting to set a field more than once triggers a runtime panic. This is achieved through the assert_none attribute combined with strip_option behavior.

The file also includes three unit tests that verify the correct behavior of the setters, specifically testing the enforcement of the "set only once" rule.

Struct: StripAssertNoneStruct

Purpose

StripAssertNoneStruct is designed to demonstrate and test the interaction of two derive_setters attributes:

Definition

#[derive(Default, Setters, Debug, PartialEq, Eq)]
#[setters(strip_option, assert_none)]
struct StripAssertNoneStruct {
    a: Option<u32>,
    #[setters(strip_option = false)]
    c: std::option::Option<u32>,
    d: u32,
}

Attributes and Effects

Generated Setter Methods

Usage Example

let s = StripAssertNoneStruct::default()
    .a(3)               // sets a = Some(3)
    .c(Some(42))        // sets c = Some(42)
    .d(7);              // sets d = 7

Attempting to call .a(3) or .c(Some(3)) again on the same instance will panic, enforcing the "set once" rule.

Unit Tests

assert_none_must_not_panic_for_the_first_set

assert_none_panic_if_value_was_set

assert_none_panic_if_value_was_set_for_stripped_option

Interaction with Other Parts of the System

Implementation Details

Mermaid Diagram

flowchart TD
A[StripAssertNoneStruct]
A -->|has| a[Option<u32> a]
A -->|has| c[Option<u32> c]
A -->|has| d[u32 d]
subgraph Setters
Sa["a(value: u32)"]
Sc["c(value: Option<u32>)"]
Sd["d(value: u32)"]
end
A --> Setters
Sa -->|assert_none + strip_option| A.a
Sc -->|assert_none only| A.c
Sd -->|no assert_none| A.d
subgraph Tests
T1[assert_none_must_not_panic_for_the_first_set]
T2[assert_none_panic_if_value_was_set]
T3[assert_none_panic_if_value_was_set_for_stripped_option]
end
Tests -->|test| Sa
Tests -->|test| Sc

This diagram illustrates the struct's fields and their corresponding setters, highlighting the application of assert_none and strip_option attributes, as well as the unit tests exercising these behaviors.