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
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
// This file is part of Frontier.
//
// Copyright (c) 2019-2022 Moonsong Labs.
// Copyright (c) 2023 Parity Technologies (UK) Ltd.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.

use super::*;
use alloc::borrow::ToOwned;
use sp_core::{ConstU32, Get};

type ConstU32Max = ConstU32<{ u32::MAX }>;

pub type UnboundedBytes = BoundedBytesString<BytesKind, ConstU32Max>;
pub type BoundedBytes<S> = BoundedBytesString<BytesKind, S>;

pub type UnboundedString = BoundedBytesString<StringKind, ConstU32Max>;
pub type BoundedString<S> = BoundedBytesString<StringKind, S>;

trait Kind {
	fn signature() -> String;
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct BytesKind;

impl Kind for BytesKind {
	fn signature() -> String {
		String::from("bytes")
	}
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct StringKind;

impl Kind for StringKind {
	fn signature() -> String {
		String::from("string")
	}
}

/// The `bytes/string` type of Solidity.
/// It is different from `Vec<u8>` which will be serialized with padding for each `u8` element
/// of the array, while `Bytes` is tightly packed.
#[derive(Debug, Eq, PartialEq)]
pub struct BoundedBytesString<K, S> {
	data: Vec<u8>,
	_phantom: PhantomData<(K, S)>,
}

impl<K: Kind, S: Get<u32>> Clone for BoundedBytesString<K, S> {
	fn clone(&self) -> Self {
		Self {
			data: self.data.clone(),
			_phantom: PhantomData,
		}
	}
}

impl<K, S: Get<u32>> BoundedBytesString<K, S> {
	pub fn as_bytes(&self) -> &[u8] {
		&self.data
	}

	pub fn as_str(&self) -> Result<&str, sp_std::str::Utf8Error> {
		sp_std::str::from_utf8(&self.data)
	}
}

impl<K: Kind, S: Get<u32>> Codec for BoundedBytesString<K, S> {
	fn read(reader: &mut Reader) -> MayRevert<Self> {
		let mut inner_reader = reader.read_pointer()?;

		// Read bytes/string size.
		let array_size: usize = inner_reader
			.read::<U256>()
			.map_err(|_| RevertReason::read_out_of_bounds("length"))?
			.try_into()
			.map_err(|_| RevertReason::value_is_too_large("length"))?;

		if array_size > S::get() as usize {
			return Err(RevertReason::value_is_too_large("length").into());
		}

		// Get valid range over the bytes data.
		let range = inner_reader.move_cursor(array_size)?;

		let data = inner_reader
			.input
			.get(range)
			.ok_or_else(|| RevertReason::read_out_of_bounds(K::signature()))?;

		let bytes = Self {
			data: data.to_owned(),
			_phantom: PhantomData,
		};

		Ok(bytes)
	}

	fn write(writer: &mut Writer, value: Self) {
		let value: Vec<_> = value.into();
		let length = value.len();

		// Pad the data.
		// Leave it as is if a multiple of 32, otherwise pad to next
		// multiple or 32.
		let chunks = length / 32;
		let padded_size = match length % 32 {
			0 => chunks * 32,
			_ => (chunks + 1) * 32,
		};

		let mut value = value.to_vec();
		value.resize(padded_size, 0);

		writer.write_pointer(
			Writer::new()
				.write(U256::from(length))
				.write_raw_bytes(&value)
				.build(),
		);
	}

	fn has_static_size() -> bool {
		false
	}

	fn signature() -> String {
		K::signature()
	}
}

// BytesString <=> Vec/&[u8]

impl<K, S> From<BoundedBytesString<K, S>> for Vec<u8> {
	fn from(value: BoundedBytesString<K, S>) -> Self {
		value.data
	}
}

impl<K, S> From<Vec<u8>> for BoundedBytesString<K, S> {
	fn from(value: Vec<u8>) -> Self {
		Self {
			data: value,
			_phantom: PhantomData,
		}
	}
}

impl<K, S> From<&[u8]> for BoundedBytesString<K, S> {
	fn from(value: &[u8]) -> Self {
		Self {
			data: value.to_vec(),
			_phantom: PhantomData,
		}
	}
}

impl<K, S, const N: usize> From<[u8; N]> for BoundedBytesString<K, S> {
	fn from(value: [u8; N]) -> Self {
		Self {
			data: value.to_vec(),
			_phantom: PhantomData,
		}
	}
}

impl<K, S, const N: usize> From<&[u8; N]> for BoundedBytesString<K, S> {
	fn from(value: &[u8; N]) -> Self {
		Self {
			data: value.to_vec(),
			_phantom: PhantomData,
		}
	}
}

// BytesString <=> String/str

impl<K, S> TryFrom<BoundedBytesString<K, S>> for String {
	type Error = alloc::string::FromUtf8Error;

	fn try_from(value: BoundedBytesString<K, S>) -> Result<Self, Self::Error> {
		alloc::string::String::from_utf8(value.data)
	}
}

impl<K, S> From<&str> for BoundedBytesString<K, S> {
	fn from(value: &str) -> Self {
		Self {
			data: value.as_bytes().into(),
			_phantom: PhantomData,
		}
	}
}

impl<K, S> From<String> for BoundedBytesString<K, S> {
	fn from(value: String) -> Self {
		Self {
			data: value.as_bytes().into(),
			_phantom: PhantomData,
		}
	}
}