-
-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathbyte_str.rs
More file actions
319 lines (279 loc) · 9.84 KB
/
Copy pathbyte_str.rs
File metadata and controls
319 lines (279 loc) · 9.84 KB
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
// Reference rust implementation of AluVM (arithmetic logic unit virtual machine).
// To find more on AluVM please check <https://aluvm.org>
//
// SPDX-License-Identifier: Apache-2.0
//
// Written in 2021-2024 by
// Dr Maxim Orlovsky <orlovsky@ubideco.org>
//
// Copyright (C) 2021-2022 LNP/BP Standards Association. All rights reserved.
// Copyright (C) 2023-2024 UBIDECO Institute. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#[cfg(all(feature = "alloc", not(feature = "std")))]
use alloc::boxed::Box;
#[cfg(all(feature = "alloc", not(feature = "std")))]
use alloc::vec::Vec;
use core::borrow::{Borrow, BorrowMut};
use core::convert::TryFrom;
use core::fmt::{self, Debug, Display, Formatter};
use core::ops::Range;
use amplify::confinement::{SmallBlob, TinyBlob};
use amplify::num::error::OverflowError;
/// Large binary bytestring object.
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ByteStr {
/// Adjusted slice length.
len: u16,
/// Slice bytes
#[doc(hidden)]
pub bytes: Box<[u8; u16::MAX as usize]>,
}
impl Default for ByteStr {
fn default() -> ByteStr { ByteStr { len: 0, bytes: Box::new([0u8; u16::MAX as usize]) } }
}
impl AsRef<[u8]> for ByteStr {
#[inline]
fn as_ref(&self) -> &[u8] { &self.bytes[..self.len as usize] }
}
impl AsMut<[u8]> for ByteStr {
#[inline]
fn as_mut(&mut self) -> &mut [u8] { &mut self.bytes[..self.len as usize] }
}
impl Borrow<[u8]> for ByteStr {
#[inline]
fn borrow(&self) -> &[u8] { &self.bytes[..self.len as usize] }
}
impl BorrowMut<[u8]> for ByteStr {
#[inline]
fn borrow_mut(&mut self) -> &mut [u8] { &mut self.bytes[..self.len as usize] }
}
impl Extend<u8> for ByteStr {
fn extend<T: IntoIterator<Item = u8>>(&mut self, iter: T) {
let mut pos = self.len();
let iter = iter.into_iter();
for byte in iter {
assert!(pos < u16::MAX);
self.bytes[pos as usize] = byte;
pos += 1;
}
self.len = pos;
}
}
impl From<&TinyBlob> for ByteStr {
fn from(blob: &TinyBlob) -> Self {
let len = blob.len_u8() as u16;
let mut bytes = [0u8; u16::MAX as usize];
bytes[0..(len as usize)].copy_from_slice(blob.as_slice());
ByteStr { len, bytes: Box::new(bytes) }
}
}
impl From<&SmallBlob> for ByteStr {
fn from(blob: &SmallBlob) -> Self {
let len = blob.len_u16();
let mut bytes = [0u8; u16::MAX as usize];
bytes[0..(len as usize)].copy_from_slice(blob.as_slice());
ByteStr { len, bytes: Box::new(bytes) }
}
}
impl From<TinyBlob> for ByteStr {
fn from(blob: TinyBlob) -> Self { ByteStr::from(&blob) }
}
impl From<SmallBlob> for ByteStr {
fn from(blob: SmallBlob) -> Self { ByteStr::from(&blob) }
}
impl TryFrom<&[u8]> for ByteStr {
type Error = OverflowError;
fn try_from(slice: &[u8]) -> Result<Self, Self::Error> {
let len = slice.len();
if len > u16::MAX as usize {
return Err(OverflowError { max: u16::MAX as usize + 1, value: len });
}
let mut bytes = [0u8; u16::MAX as usize];
bytes[0..len].copy_from_slice(slice.as_ref());
Ok(ByteStr { len: len as u16, bytes: Box::new(bytes) })
}
}
impl ByteStr {
/// Constructs blob from slice of bytes.
///
/// Panics if the length of the slice is greater than `u16::MAX` bytes.
#[inline]
pub fn with(slice: impl AsRef<[u8]>) -> ByteStr {
ByteStr::try_from(slice.as_ref())
.expect("internal error: ByteStr::with requires slice <= u16::MAX + 1")
}
/// Returns correct length of the string, in range `0 ..= u16::MAX`
#[inline]
pub fn len(&self) -> u16 { self.len }
/// Returns when the string has a zero length
#[inline]
pub fn is_empty(&self) -> bool { self.len == 0 }
/// Adjusts the length of the string
#[inline]
pub fn adjust_len(&mut self, new_len: u16) { self.len = new_len }
/// Extends the length of the string if necessary
#[inline]
pub fn extend_len(&mut self, new_len: u16) { self.len = new_len.max(self.len) }
/// Fills range within a string with the provided byte value, increasing string length if
/// necessary
pub fn fill(&mut self, range: Range<u16>, val: u8) {
let start = range.start;
let end = range.end;
self.extend_len(end);
self.bytes[start as usize..end as usize].fill(val);
}
/// Returns vector representation of the contained bytecode
#[inline]
pub fn to_vec(&self) -> Vec<u8> { self.as_ref().to_vec() }
}
#[cfg(not(feature = "std"))]
impl Debug for ByteStr {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { write!(f, "{:#04X?}", self.as_ref()) }
}
#[cfg(feature = "std")]
impl Debug for ByteStr {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
use amplify::hex::ToHex;
f.debug_tuple("ByteStr").field(&self.as_ref().to_hex()).finish()
}
}
#[cfg(feature = "std")]
impl Display for ByteStr {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
use std::fmt::Write;
use amplify::hex::ToHex;
let vec = Vec::from(&self.bytes[..self.len as usize]);
if f.alternate() {
for (line, slice) in self.as_ref().chunks(16).enumerate() {
write!(f, "\x1B[0;35m{:>1$x}0 | \x1B[0m", line, f.width().unwrap_or(1) - 1)?;
for (pos, byte) in slice.iter().enumerate() {
write!(f, "{:02x} ", byte)?;
if pos == 7 {
f.write_char(' ')?;
}
}
if slice.len() < 8 {
f.write_char(' ')?;
}
write!(
f,
"{:1$}\x1B[0;35m|\x1B[0m ",
' ',
16usize.saturating_sub(slice.len()) * 3 + 1
)?;
for byte in slice {
f.write_str(&if byte.is_ascii_control()
|| byte.is_ascii_whitespace()
|| !byte.is_ascii()
{
s!("\x1B[0;35m·\x1B[0m")
} else {
String::from(char::from(*byte))
})?;
}
f.write_char('\n')?;
}
Ok(())
// write!(f, "{}..{}", self.bytes[..4].to_hex(), self.bytes[(self.len() -
// 4)..].to_hex())
} else if let Ok(s) = String::from_utf8(vec) {
f.write_str("\"")?;
let mut ctl = false;
for c in s.chars() {
let v = c as u32;
if (c.is_control() && v != 0x20) || !(0x20..0x7F).contains(&v) {
if !ctl {
ctl = true;
}
if v <= 0xFF {
write!(f, "{v:02X}")?;
} else if v <= 0xFFFF {
write!(f, "{v:04X}")?;
} else {
write!(f, "{v:08X}")?;
}
} else {
if ctl {
ctl = false;
}
f.write_char(c)?;
}
}
f.write_str("\"")
} else {
f.write_str(&self.as_ref().to_hex())
}
}
}
#[cfg(not(feature = "std"))]
impl Display for ByteStr {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { write!(f, "{:#04X?}", self.as_ref()) }
}
/*
#[cfg(feature = "strict_encoding")]
mod _strict_encoding {
use std::convert::TryFrom;
use std::io::{Read, Write};
use std::ops::Deref;
use strict_encoding::{StrictDecode, StrictEncode};
use super::ByteStr;
impl StrictEncode for ByteStr {
fn strict_encode<E: Write>(&self, e: E) -> Result<usize, strict_encoding::Error> {
self.as_ref().strict_encode(e)
}
}
impl StrictDecode for ByteStr {
fn strict_decode<D: Read>(d: D) -> Result<Self, strict_encoding::Error> {
let data = Vec::<u8>::strict_decode(d)?;
Ok(ByteStr::try_from(data.deref()).expect("strict encoding can't read more than 67 kb"))
}
}
}
*/
#[cfg(feature = "serde")]
mod _serde {
use std::convert::TryFrom;
use std::ops::Deref;
use amplify::hex::{FromHex, ToHex};
use serde_crate::de::Error;
use serde_crate::{Deserialize, Deserializer, Serialize, Serializer};
use super::ByteStr;
impl Serialize for ByteStr {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
if serializer.is_human_readable() {
self.as_ref().to_hex().serialize(serializer)
} else {
self.as_ref().serialize(serializer)
}
}
}
impl<'de> Deserialize<'de> for ByteStr {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let vec = if deserializer.is_human_readable() {
let hex = String::deserialize(deserializer)?;
Vec::<u8>::from_hex(&hex).map_err(D::Error::custom)?
} else {
Vec::<u8>::deserialize(deserializer)?
};
ByteStr::try_from(vec.deref())
.map_err(|_| D::Error::invalid_length(vec.len(), &"max u16::MAX bytes"))
}
}
}