Skip to main content

neo_types/
bytestring.rs

1// Copyright (c) 2025-2026 R3E Network
2// Licensed under the MIT License
3
4use std::fmt;
5use std::vec::Vec;
6
7#[cfg(feature = "serde")]
8use serde::{Deserialize, Serialize};
9
10/// Neo N3 ByteString type
11#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
12#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
13pub struct NeoByteString {
14    data: Vec<u8>,
15}
16
17impl NeoByteString {
18    pub fn new(data: Vec<u8>) -> Self {
19        Self { data }
20    }
21
22    pub fn from_slice(slice: &[u8]) -> Self {
23        Self {
24            data: slice.to_vec(),
25        }
26    }
27
28    pub fn as_slice(&self) -> &[u8] {
29        &self.data
30    }
31
32    pub fn len(&self) -> usize {
33        self.data.len()
34    }
35
36    pub fn is_empty(&self) -> bool {
37        self.data.is_empty()
38    }
39
40    pub fn push(&mut self, byte: u8) {
41        self.data.push(byte);
42    }
43
44    pub fn extend_from_slice(&mut self, slice: &[u8]) {
45        self.data.extend_from_slice(slice);
46    }
47}
48
49impl fmt::Display for NeoByteString {
50    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
51        for byte in &self.data {
52            write!(f, "{:02x}", byte)?;
53        }
54        Ok(())
55    }
56}
57
58impl From<Vec<u8>> for NeoByteString {
59    fn from(data: Vec<u8>) -> Self {
60        Self { data }
61    }
62}
63
64impl From<&[u8]> for NeoByteString {
65    fn from(slice: &[u8]) -> Self {
66        Self::from_slice(slice)
67    }
68}
69
70impl AsRef<[u8]> for NeoByteString {
71    fn as_ref(&self) -> &[u8] {
72        &self.data
73    }
74}
75
76impl Extend<u8> for NeoByteString {
77    fn extend<I: IntoIterator<Item = u8>>(&mut self, iter: I) {
78        self.data.extend(iter);
79    }
80}
81
82impl FromIterator<u8> for NeoByteString {
83    fn from_iter<I: IntoIterator<Item = u8>>(iter: I) -> Self {
84        Self {
85            data: Vec::from_iter(iter),
86        }
87    }
88}