Skip to content

Commit

Permalink
zcash_protocol: Add TryFrom<&MemoBytes> for Memo
Browse files Browse the repository at this point in the history
  • Loading branch information
nuttycom committed Mar 8, 2024
1 parent d48e45e commit 2c6055a
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
4 changes: 4 additions & 0 deletions components/zcash_protocol/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ and this library adheres to Rust's notion of

## [Unreleased]

### Added
- `zcash_protocol::memo`:
- `impl TryFrom<&MemoBytes> for Memo`

## [0.1.0] - 2024-03-06
The entries below are relative to the `zcash_primitives` crate as of the tag
`zcash_primitives-0.14.0`.
Expand Down
14 changes: 13 additions & 1 deletion components/zcash_protocol/src/memo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -197,13 +197,25 @@ impl TryFrom<MemoBytes> for Memo {
/// Returns an error if the provided slice does not represent a valid `Memo` (for
/// example, if the slice is not 512 bytes, or the encoded `Memo` is non-canonical).
fn try_from(bytes: MemoBytes) -> Result<Self, Self::Error> {
Self::try_from(&bytes)
}
}

impl TryFrom<&MemoBytes> for Memo {
type Error = Error;

/// Parses a `Memo` from its ZIP 302 serialization.
///
/// Returns an error if the provided slice does not represent a valid `Memo` (for
/// example, if the slice is not 512 bytes, or the encoded `Memo` is non-canonical).
fn try_from(bytes: &MemoBytes) -> Result<Self, Self::Error> {
match bytes.0[0] {
0xF6 if bytes.0.iter().skip(1).all(|&b| b == 0) => Ok(Memo::Empty),
0xFF => Ok(Memo::Arbitrary(Box::new(bytes.0[1..].try_into().unwrap()))),
b if b <= 0xF4 => str::from_utf8(bytes.as_slice())
.map(|r| Memo::Text(TextMemo(r.to_owned())))
.map_err(Error::InvalidUtf8),
_ => Ok(Memo::Future(bytes)),
_ => Ok(Memo::Future(bytes.clone())),
}
}
}
Expand Down

0 comments on commit 2c6055a

Please sign in to comment.