reth_primitives_traits/
encoded.rs

1use alloy_eips::eip2718::Encodable2718;
2use alloy_primitives::Bytes;
3
4/// Generic wrapper with encoded Bytes, such as transaction data.
5#[derive(Debug, Clone, PartialEq, Eq)]
6pub struct WithEncoded<T>(Bytes, pub T);
7
8impl<T> From<(Bytes, T)> for WithEncoded<T> {
9    fn from(value: (Bytes, T)) -> Self {
10        Self(value.0, value.1)
11    }
12}
13
14impl<T> WithEncoded<T> {
15    /// Wraps the value with the bytes.
16    pub const fn new(bytes: Bytes, value: T) -> Self {
17        Self(bytes, value)
18    }
19
20    /// Get the encoded bytes
21    pub const fn encoded_bytes(&self) -> &Bytes {
22        &self.0
23    }
24
25    /// Get the underlying value
26    pub const fn value(&self) -> &T {
27        &self.1
28    }
29
30    /// Returns ownership of the underlying value.
31    pub fn into_value(self) -> T {
32        self.1
33    }
34
35    /// Transform the value
36    pub fn transform<F: From<T>>(self) -> WithEncoded<F> {
37        WithEncoded(self.0, self.1.into())
38    }
39
40    /// Split the wrapper into [`Bytes`] and value tuple
41    pub fn split(self) -> (Bytes, T) {
42        (self.0, self.1)
43    }
44
45    /// Maps the inner value to a new value using the given function.
46    pub fn map<U, F: FnOnce(T) -> U>(self, op: F) -> WithEncoded<U> {
47        WithEncoded(self.0, op(self.1))
48    }
49}
50
51impl<T: Encodable2718> WithEncoded<T> {
52    /// Wraps the value with the [`Encodable2718::encoded_2718`] bytes.
53    pub fn from_2718_encodable(value: T) -> Self {
54        Self(value.encoded_2718().into(), value)
55    }
56}
57
58impl<T> WithEncoded<Option<T>> {
59    /// returns `None` if the inner value is `None`, otherwise returns `Some(WithEncoded<T>)`.
60    pub fn transpose(self) -> Option<WithEncoded<T>> {
61        self.1.map(|v| WithEncoded(self.0, v))
62    }
63}