ckb_gen_types/prelude.rs
1//! This module includes several traits.
2//!
3//! Few traits are re-exported from other crates, few are used as aliases and others are syntactic sugar.
4
5pub use molecule::{
6 hex_string,
7 prelude::{Builder, Entity, Reader},
8};
9
10/// An alias of `unwrap()` to mark where we are really have confidence to do unwrap.
11///
12/// We can also customize the panic message or do something else in this alias.
13pub trait ShouldBeOk<T> {
14 /// Unwraps an `Option` or a `Result` with confidence and we assume that it's impossible to fail.
15 fn should_be_ok(self) -> T;
16}
17
18// Use for Option
19impl<T> ShouldBeOk<T> for Option<T> {
20 fn should_be_ok(self) -> T {
21 self.unwrap_or_else(|| panic!("should not be None"))
22 }
23}
24
25// Use for verify
26impl<T> ShouldBeOk<T> for molecule::error::VerificationResult<T> {
27 fn should_be_ok(self) -> T {
28 self.unwrap_or_else(|err| panic!("verify slice should be ok, but {err}"))
29 }
30}
31
32/// An alias of `from_slice(..)` to mark where we are really have confidence to do unwrap on the result of `from_slice(..)`.
33pub trait FromSliceShouldBeOk<'r>: Reader<'r> {
34 /// Unwraps the result of `from_slice(..)` with confidence and we assume that it's impossible to fail.
35 fn from_slice_should_be_ok(slice: &'r [u8]) -> Self;
36
37 /// Unwraps the result of `from_compatible_slice(..)` with confidence and we assume that it's impossible to fail.
38 fn from_compatible_slice_should_be_ok(slice: &'r [u8]) -> Self;
39}
40
41impl<'r, R> FromSliceShouldBeOk<'r> for R
42where
43 R: Reader<'r>,
44{
45 fn from_slice_should_be_ok(slice: &'r [u8]) -> Self {
46 match Self::from_slice(slice) {
47 Ok(ret) => ret,
48 Err(err) => panic!(
49 "failed to convert from slice: reason: {}; data: 0x{}.",
50 err,
51 hex_string(slice)
52 ),
53 }
54 }
55
56 fn from_compatible_slice_should_be_ok(slice: &'r [u8]) -> Self {
57 match Self::from_compatible_slice(slice) {
58 Ok(ret) => ret,
59 Err(err) => panic!(
60 "failed to convert from slice: reason: {}; data: 0x{}.",
61 err,
62 hex_string(slice)
63 ),
64 }
65 }
66}
67
68/// A syntactic sugar to convert binary data into rust types.
69pub trait Unpack<T> {
70 /// Unpack binary data into rust types.
71 fn unpack(&self) -> T;
72}
73
74/// A syntactic sugar to convert a rust type into binary data.
75pub trait Pack<T: Entity> {
76 /// Packs a rust type into binary data.
77 fn pack(&self) -> T;
78}
79
80/// A syntactic sugar to convert a vector of binary data into one binary data.
81pub trait PackVec<T: Entity, I: Entity>: IntoIterator<Item = I> {
82 /// Packs a vector of binary data into one binary data.
83 fn pack(self) -> T;
84}