|
1 | 1 | use core::fmt;
|
| 2 | +use core::ops::Deref; |
2 | 3 |
|
3 | 4 | use schemars::JsonSchema;
|
4 | 5 | use serde::{de, ser, Deserialize, Deserializer, Serialize};
|
@@ -52,6 +53,25 @@ impl From<[u8; 32]> for Checksum {
|
52 | 53 | }
|
53 | 54 | }
|
54 | 55 |
|
| 56 | +/// Just like Vec<u8>, Checksum is a smart pointer to [u8]. |
| 57 | +/// This implements `*data` for us and allows us to |
| 58 | +/// do `&*data`, returning a `&[u8]` from a `&Checksum`. |
| 59 | +/// With [deref coercions](https://doc.rust-lang.org/1.22.1/book/first-edition/deref-coercions.html#deref-coercions), |
| 60 | +/// this allows us to use `&data` whenever a `&[u8]` is required. |
| 61 | +impl Deref for Checksum { |
| 62 | + type Target = [u8; 32]; |
| 63 | + |
| 64 | + fn deref(&self) -> &Self::Target { |
| 65 | + self.as_ref() |
| 66 | + } |
| 67 | +} |
| 68 | + |
| 69 | +impl AsRef<[u8; 32]> for Checksum { |
| 70 | + fn as_ref(&self) -> &[u8; 32] { |
| 71 | + &self.0 |
| 72 | + } |
| 73 | +} |
| 74 | + |
55 | 75 | /// Serializes as a hex string
|
56 | 76 | impl Serialize for Checksum {
|
57 | 77 | fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
@@ -184,4 +204,18 @@ mod tests {
|
184 | 204 | let as_vec: Vec<u8> = checksum.into();
|
185 | 205 | assert_eq!(as_vec, checksum.0);
|
186 | 206 | }
|
| 207 | + |
| 208 | + #[test] |
| 209 | + fn ref_conversions_work() { |
| 210 | + let checksum = Checksum::generate(&[12u8; 17]); |
| 211 | + // deref |
| 212 | + let _: &[u8; 32] = &checksum; |
| 213 | + let _: &[u8] = &*checksum; |
| 214 | + // as_ref |
| 215 | + let _: &[u8; 32] = checksum.as_ref(); |
| 216 | + let _: &[u8] = checksum.as_ref(); |
| 217 | + // as_slice |
| 218 | + let _: &[u8; 32] = checksum.as_ref(); |
| 219 | + let _: &[u8] = checksum.as_ref(); |
| 220 | + } |
187 | 221 | }
|
0 commit comments