nimble_participant/lib.rs
1/*
2 * Copyright (c) Peter Bjorklund. All rights reserved. https://github.com/nimble-rust/nimble
3 * Licensed under the MIT License. See LICENSE in the project root for license information.
4 */
5
6/*!
7# nimble-participant
8
9`nimble-participant` is a crate for managing participants in a deterministic simulation.
10
11## Features ✨
12- **`ParticipantId`**: Provides a unique identifier for participants using a simple wrapper around `u8`.
13- **Serialization/Deserialization**: Supports binary serialization and deserialization through the `flood_rs` crate.
14- **Display Formatting**: Offers a formatted, human-readable display for logging or printing participant identifiers.
15
16## Usage 🚀
17
18 Add the following to your `Cargo.toml`:
19
20```toml
21[dependencies]
22nimble-participant = "0.1"
23```
24
25## Example:
26
27```rust
28use nimble_participant::ParticipantId;
29
30let participant = ParticipantId(42);
31println!("{}", participant); // Outputs: Participant(42)
32```
33*/
34
35use flood_rs::{Deserialize, ReadOctetStream, Serialize, WriteOctetStream};
36use std::fmt::Display;
37
38/// Represents a unique participant in a simulation.
39///
40/// The `ParticipantId` wraps a `u8` and provides serialization,
41/// deserialization, and display capabilities.
42#[derive(PartialEq, Eq, Copy, Ord, Hash, Clone, Debug, PartialOrd)]
43pub struct ParticipantId(pub u8);
44
45impl Serialize for ParticipantId {
46 /// Serializes the `ParticipantId` into the given stream.
47 ///
48 /// # Arguments
49 ///
50 /// * `stream` - A mutable reference to an object that implements `WriteOctetStream`.
51 ///
52 /// # Errors
53 ///
54 /// Returns an `std::io::Error` if writing to the stream fails.
55 fn serialize(&self, stream: &mut impl WriteOctetStream) -> std::io::Result<()> {
56 stream.write_u8(self.0)
57 }
58}
59
60impl Deserialize for ParticipantId {
61 /// Deserializes a `ParticipantId` from the given stream.
62 ///
63 /// # Arguments
64 ///
65 /// * `stream` - A mutable reference to an object that implements `ReadOctetStream`.
66 ///
67 /// # Errors
68 ///
69 /// Returns an `std::io::Error` if reading from the stream fails.
70 fn deserialize(stream: &mut impl ReadOctetStream) -> std::io::Result<Self> {
71 Ok(Self(stream.read_u8()?))
72 }
73}
74
75impl Display for ParticipantId {
76 /// Formats the `ParticipantId` for display.
77 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
78 write!(f, "Participant({})", self.0)
79 }
80}