update validation section

This commit is contained in:
Alfredo Garcia 2021-05-06 12:07:44 -03:00 committed by Deirdre Connolly
parent 2b851e654a
commit 400e6d3d48
1 changed files with 22 additions and 8 deletions

View File

@ -136,7 +136,7 @@ Validation is implemented to each new data type as needed. This will ensure the
```rust ```rust
pub trait Validate { pub trait Validate {
fn validate(&self) -> &Self; fn validate(&self) -> Result<&Self, MsgErr>;
} }
``` ```
@ -144,27 +144,41 @@ And we implement where needed. For example, in the header, sender and receiver c
```rust ```rust
impl Validate for Header { impl Validate for Header {
fn validate(&self) -> &Self { fn validate(&self) -> Result<&Self, MsgErr> {
if self.sender.0 == self.receiver.0 { if self.sender.0 == self.receiver.0 {
panic!("sender and receiver are the same"); return Err(MsgErr::SameSenderAndReceiver);
} }
self Ok(self)
} }
} }
``` ```
Then to create a valid `Header` we call: This will require to have validation error messages as:
```rust
use thiserror::Error;
#[derive(Clone, Error, Debug)]
pub enum MsgErr {
#[error("sender and receiver are the same")]
SameSenderAndReceiver,
}
```
Then to create a valid `Header` in the sender side we call:
```rust ```rust
let header = Validate::validate(&Header { let header = Validate::validate(&Header {
.. ..
}).clone(); }).expect("a valid header");
``` ```
The receiver side will validate the header as: The receiver side will validate the header using the same method. Instead of panicking the error can be ignored to don't crash and keep waiting for other (potentially valid) messages.
```rust ```rust
msg.header.validate(); if let Ok(header) = msg.header.validate() {
..
}
``` ```
## Serialization/Deserialization ## Serialization/Deserialization