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
/*
* BSD 3-Clause License
*
* Copyright (c) 2020, InterlockLedger Network
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
//! This module contains the implementation of the **IL2 ILInt** standard
//! as defined in [ILInt Specification](https://github.com/interlockledger/specification/tree/master/ILInt)
//!
//! This code is based on the **IL2 ILInt** implementation for Rust found at
//! [InterlockLedger ILInt for Rust](https://github.com/interlockledger/rust-il2-ilint).
//! This version does not share the same interface of the original library and thus
//! is not compatible with it.
#[cfg(test)]
mod tests;
use super::io::{Reader, Writer};
/// Error codes generated by this module.
#[derive(Debug)]
pub enum ErrorKind {
/// The encoded value is larger than 2^64 - 1.
ValueOverflow,
/// In case of an invalid format.
InvalidFormat,
/// I/O error.
IOError(crate::io::ErrorKind),
}
/// A specialized [`std::result::Result`] generated by functions and methods from this package.
pub type Result<T> = std::result::Result<T, ErrorKind>;
/// LInt base value. All values smaller than this value are encoded as
/// a single byte.
pub const ILINT_BASE: u8 = 0xF8;
/// Value of ILINT_BASE as U64.
pub const ILINT_BASE_U64: u64 = ILINT_BASE as u64;
/// Returns the size of the given value encoded as an ILInt.
///
/// Arguments:
/// * `value` : The value to be encoded.
///
/// Returns:
/// * The number of bytes required to encode the value.
pub fn encoded_size(value: u64) -> usize {
match value {
value if value < ILINT_BASE_U64 => 1,
value if value <= (0xFF + ILINT_BASE_U64) => 2,
value if value <= (0xFFFF + ILINT_BASE_U64) => 3,
value if value <= (0x00FF_FFFF + ILINT_BASE_U64) => 4,
value if value <= (0xFFFF_FFFF + ILINT_BASE_U64) => 5,
value if value <= (0x00FF_FFFF_FFFF + ILINT_BASE_U64) => 6,
value if value <= (0xFFFF_FFFF_FFFF + ILINT_BASE_U64) => 7,
value if value <= (0x00FF_FFFF_FFFF_FFFF + ILINT_BASE_U64) => 8,
_ => 9,
}
}
/// Encodes the given value into a **ILInt** value.
///
/// Arguments:
/// * `value`: The value to be encoded;
/// * `writer`: The writer that will receive the encoded value;
///
/// Returns:
/// * `Ok(())`: In case of success.
/// * `Err(ErrorKind)`: In case of an I/O error.
pub fn encode(value: u64, writer: &mut dyn Writer) -> Result<()> {
let size = encoded_size(value);
if size == 1 {
match writer.write(value as u8) {
Ok(()) => (),
Err(e) => return Err(ErrorKind::IOError(e)),
}
} else {
// Header
match writer.write((ILINT_BASE + ((size - 2) as u8)) as u8) {
Ok(()) => (),
Err(e) => return Err(ErrorKind::IOError(e)),
}
let v = value - ILINT_BASE_U64;
let mut shift = 8 * (size - 1);
for _i in 1..size {
shift -= 8;
match writer.write(((v >> shift) & 0xFF) as u8) {
Ok(()) => (),
Err(e) => return Err(ErrorKind::IOError(e)),
}
}
}
Ok(())
}
/// Determines the size of the **ILInt** based on its header (the
/// first byte).
///
/// Arguments:
/// * `header`: The header of the **ILInt**. It is always the first byte of
/// the **ILInt** value;
///
/// Returns:
/// * The size of the **ILInt** in bytes, including the header.
pub fn decoded_size(header: u8) -> usize {
if header < ILINT_BASE {
1
} else {
(header - ILINT_BASE + 2) as usize
}
}
/// Decodes the body of a multi-byte **ILInt**. This function
/// is usefull if the header was already used to determine the
/// size of the body.
///
/// Arguments:
/// * `body`: The multibyte **ILInt** value.
///
/// Returns:
/// * `Ok(u64)`: The value of the ILInt.
/// * `Err(ErrorKind)`: In case of error.
pub fn decode_body(body: &[u8]) -> Result<u64> {
let mut v: u64 = 0;
if body.is_empty() || body.len() > 8 {
Err(ErrorKind::InvalidFormat)
} else {
for x in body {
v = (v << 8) + (*x as u64);
}
if v > 0xFFFF_FFFF_FFFF_FF07 {
Err(ErrorKind::ValueOverflow)
} else {
Ok(v + ILINT_BASE_U64)
}
}
}
/// Decodes an **ILInt** from a byte slice.
///
/// Arguments:
/// * `value`: The **ILInt** value.
///
/// Returns:
/// * `Ok((u64,usize))`: The value of the **ILInt** and the number of bytes used.
/// * `Err(ErrorKind)`: In case of error.
pub fn decode_from_bytes(value: &[u8]) -> Result<(u64, usize)> {
if value.is_empty() {
Err(ErrorKind::InvalidFormat)
} else {
let size = decoded_size(value[0]);
if size == 1 {
Ok((value[0] as u64, size))
} else if value.len() < size {
Err(ErrorKind::InvalidFormat)
} else {
match decode_body(&value[1..size]) {
Ok(v) => Ok((v, size)),
Err(x) => Err(x),
}
}
}
}
/// Decodes an **ILInt** value.
///
/// Arguments:
/// * `reader`: The reader that contains the encoded
/// value;
///
/// Returns:
/// * `Ok(u64)`: On success, returns the value read.
/// * `Err(ErrorKind)`: In case of error.
pub fn decode(reader: &mut dyn Reader) -> Result<u64> {
let header = match reader.read() {
Ok(v) => v,
Err(e) => return Err(ErrorKind::IOError(e)),
};
let size = decoded_size(header);
if size == 1 {
Ok(header as u64)
} else {
let mut tmp: [u8; 8] = [0; 8];
match reader.read_all(&mut tmp[0..size - 1]) {
Ok(()) => (),
Err(e) => return Err(ErrorKind::IOError(e)),
}
decode_body(&tmp[0..size - 1])
}
}
/// Encodes a signed value into an unsiged value suitable
/// to be encoded as **ILInt**.
///
/// This transformation is designed to minimize the encoding
/// of both negative and positive values with small modules
/// using the **ILInt** enconding rules. See
/// [ILInt Specification](https://github.com/interlockledger/specification/tree/master/ILInt).
/// for further information about how this encoding works.
///
/// This operation can be undone by [`decode_sign()`].
///
/// Arguments:
/// - `v`: The value to be encoded;
///
/// Returns the signed value ready to be encoded as an **ILInt**.
///
/// New since 1.3.0.
pub fn encode_sign(v: i64) -> u64 {
let tmp = v as u64;
if tmp & 0x8000_0000_0000_0000 == 0 {
tmp << 1
} else {
!(tmp << 1)
}
}
/// Decodes an unsigned value into a signed value.
///
/// This operation can be undone by [`encode_sign()`].
///
/// Arguments:
/// - `v`: The value to be decoded;
///
/// Returns the decoded signed value.
///
/// New since 1.3.0.
pub fn decode_sign(v: u64) -> i64 {
if v & 0x1 == 0 {
(v >> 1) as i64
} else {
(!(v >> 1)) as i64
}
}
/// Returns the size of the given signed value encoded as an ILInt.
///
/// Arguments:
/// * `value` : The value to be encoded.
///
/// Returns:
/// * The number of bytes required to encode the value.
///
/// New since 1.3.0.
pub fn signed_encoded_size(value: i64) -> usize {
encoded_size(encode_sign(value))
}
/// Encodes the given signed value into a **ILInt** value.
///
/// Arguments:
/// * `value`: The value to be encoded;
/// * `writer`: The writer that will receive the encoded value;
///
/// Returns:
/// * `Ok(())`: In case of success.
/// * `Err(ErrorKind)`: In case of an I/O error.
///
/// New since 1.3.0.
pub fn signed_encode(value: i64, writer: &mut dyn Writer) -> Result<()> {
encode(encode_sign(value), writer)
}
/// Decodes a signed **ILInt** value.
///
/// Arguments:
/// * `reader`: The reader that contains the encoded
/// value;
///
/// Returns:
/// * `Ok(i64)`: On success, returns the value read.
/// * `Err(ErrorKind)`: In case of error.
///
/// New since 1.3.0.
pub fn signed_decode(reader: &mut dyn Reader) -> Result<i64> {
let tmp = decode(reader)?;
Ok(decode_sign(tmp))
}