• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

tari-project / tari_utilities / 11272197122

10 Oct 2024 10:26AM UTC coverage: 96.047% (-0.1%) from 96.158%
11272197122

push

github

web-flow
chore: update CI and features (#71)

This PR updates CI and relaxes features.

When running CI, a mix of nightly and stable toolchains is used. This PR
moves to the stable toolchain for all jobs except formatting, which
requires nightly. It also updates the CI actions to more updated and
supported versions.

It also relaxes feature gating and simplifies dependencies while
retaining `no_std` compatibility.

729 of 759 relevant lines covered (96.05%)

2420.47 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

98.61
/src/byte_array.rs
1
// Copyright 2019 The Tari Project
2
//
3
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
4
// following conditions are met:
5
//
6
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
7
// disclaimer.
8
//
9
// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
10
// following disclaimer in the documentation and/or other materials provided with the distribution.
11
//
12
// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote
13
// products derived from this software without specific prior written permission.
14
//
15
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
16
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
17
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
18
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
19
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
20
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
21
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
22

23
//! A trait that offers representation of data types as a byte array or hex string.
24

25
use alloc::{string::String, vec::Vec};
26

27
use snafu::prelude::*;
28

29
use crate::hex::{from_hex, to_hex, Hex, HexError};
30

31
/// Errors for [ByteArray] trait.
32
#[derive(Debug, Snafu, PartialEq, Eq)]
×
33
pub enum ByteArrayError {
34
    /// An array can't be parsed.
35
    #[snafu(display("Could not create a ByteArray when converting from a different format: `{reason}'"))]
36
    ConversionError {
37
        /// The reason for the error
38
        reason: String,
39
    },
40
    /// The lenght doesn't fit to the array.
41
    #[snafu(display("The input data was the incorrect length to perform the desired conversion"))]
42
    IncorrectLength {},
43
}
44

45
/// Trait the allows converting to/from [array][[u8]]/[vec][[u8]].
46
#[allow(clippy::ptr_arg)]
47
pub trait ByteArray: Sized {
48
    /// Return the type as a byte vector.
49
    fn to_vec(&self) -> Vec<u8> {
3✔
50
        self.as_bytes().to_vec()
3✔
51
    }
3✔
52

53
    /// Try and convert the given byte vector to the implemented type.
54
    ///
55
    /// # Errors
56
    ///
57
    /// Any failures (incorrect string length, etc) return an [ByteArrayError](enum.ByteArrayError.html) with an
58
    /// explanatory note.
59
    fn from_vec(v: &Vec<u8>) -> Result<Self, ByteArrayError> {
3✔
60
        Self::from_canonical_bytes(v.as_slice())
3✔
61
    }
3✔
62

63
    /// Try and convert the given byte array to the implemented type. Any failures (incorrect array length,
64
    /// implementation-specific checks, etc.) return a [ByteArrayError](enum.ByteArrayError.html) with an explanatory
65
    /// note.
66
    fn from_canonical_bytes(bytes: &[u8]) -> Result<Self, ByteArrayError>;
67

68
    /// Return the type as a byte array.
69
    fn as_bytes(&self) -> &[u8];
70
}
71

72
impl ByteArray for Vec<u8> {
73
    fn to_vec(&self) -> Vec<u8> {
1✔
74
        self.clone()
1✔
75
    }
1✔
76

77
    fn from_vec(v: &Vec<u8>) -> Result<Self, ByteArrayError> {
1✔
78
        Ok(v.clone())
1✔
79
    }
1✔
80

81
    fn from_canonical_bytes(bytes: &[u8]) -> Result<Self, ByteArrayError> {
4✔
82
        Ok(bytes.to_vec())
4✔
83
    }
4✔
84

85
    fn as_bytes(&self) -> &[u8] {
4✔
86
        Vec::as_slice(self)
4✔
87
    }
4✔
88
}
89

90
impl<const I: usize> ByteArray for [u8; I] {
91
    fn from_canonical_bytes(bytes: &[u8]) -> Result<Self, ByteArrayError> {
7✔
92
        if bytes.len() != I {
7✔
93
            return Err(ByteArrayError::IncorrectLength {});
2✔
94
        }
5✔
95
        let mut a = [0u8; I];
5✔
96
        a.copy_from_slice(bytes);
5✔
97
        Ok(a)
5✔
98
    }
7✔
99

100
    fn as_bytes(&self) -> &[u8] {
8✔
101
        self
8✔
102
    }
8✔
103
}
104

105
impl<T: ByteArray> Hex for T {
106
    fn from_hex(hex: &str) -> Result<Self, HexError> {
2✔
107
        let v = from_hex(hex)?;
2✔
108
        Self::from_canonical_bytes(&v).map_err(|_| HexError::HexConversionError {})
2✔
109
    }
2✔
110

111
    fn to_hex(&self) -> String {
4✔
112
        to_hex(self.as_bytes())
4✔
113
    }
4✔
114
}
115

116
#[cfg(test)]
117
mod test {
118
    use super::*;
119

120
    #[test]
121
    fn from_to_vec() {
1✔
122
        let v = vec![0u8, 1, 128, 255];
1✔
123
        let ba = <Vec<u8>>::from_vec(&v).unwrap();
1✔
124
        assert_eq!(ba.to_vec(), v);
1✔
125
    }
1✔
126

127
    #[test]
128
    fn from_to_array() {
1✔
129
        let v = vec![
1✔
130
            0u8, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28,
1✔
131
            29, 30, 31,
1✔
132
        ];
1✔
133
        let ba = <[u8; 32]>::from_vec(&v).unwrap();
1✔
134
        assert_eq!(ba.to_vec(), v);
1✔
135
    }
1✔
136

137
    #[test]
138
    fn from_to_different_sizes() {
1✔
139
        let v4 = vec![0u8, 1, 2, 3];
1✔
140
        let a4 = <[u8; 4]>::from_vec(&v4).unwrap();
1✔
141
        assert_eq!(a4.to_vec(), v4);
1✔
142
        let v10 = vec![0u8, 1, 2, 3, 4, 5, 6, 7, 8, 9];
1✔
143
        let a10 = <[u8; 10]>::from_vec(&v10).unwrap();
1✔
144
        assert_eq!(a10.to_vec(), v10);
1✔
145
        fn check(_: impl ByteArray) {}
3✔
146
        check([0; 32]);
1✔
147
        check([0; 64]);
1✔
148
        check([0; 1000]);
1✔
149
    }
1✔
150

151
    #[test]
152
    fn from_to_hex() {
1✔
153
        let v = <Vec<u8>>::from_hex("deadbeef").unwrap();
1✔
154
        assert_eq!(v.to_hex(), "deadbeef");
1✔
155
    }
1✔
156

157
    #[test]
158
    fn test_error_handling() {
1✔
159
        let err = <[u8; 32]>::from_canonical_bytes(&[1, 2, 3, 4]).unwrap_err();
1✔
160
        assert_eq!(err, ByteArrayError::IncorrectLength {});
1✔
161

162
        let err = <[u8; 32]>::from_hex("abcd").unwrap_err();
1✔
163
        assert!(matches!(err, HexError::HexConversionError {}));
1✔
164
    }
1✔
165
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc