use molecule::prelude::*;
#[derive(Clone)]
pub struct Secp256k1(molecule::bytes::Bytes);
impl ::core::fmt::LowerHex for Secp256k1 {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
use molecule::hex_string;
if f.alternate() {
write!(f, "0x")?;
}
write!(f, "{}", hex_string(self.as_slice()))
}
}
impl ::core::fmt::Debug for Secp256k1 {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{}({:#x})", Self::NAME, self)
}
}
impl ::core::fmt::Display for Secp256k1 {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
use molecule::hex_string;
let raw_data = hex_string(&self.raw_data());
write!(f, "{}(0x{})", Self::NAME, raw_data)
}
}
impl ::core::default::Default for Secp256k1 {
fn default() -> Self {
let v: Vec<u8> = vec![0, 0, 0, 0];
Secp256k1::new_unchecked(v.into())
}
}
impl Secp256k1 {
pub const ITEM_SIZE: usize = 1;
pub fn total_size(&self) -> usize {
molecule::NUMBER_SIZE * (self.item_count() + 1)
}
pub fn item_count(&self) -> usize {
molecule::unpack_number(self.as_slice()) as usize
}
pub fn len(&self) -> usize {
self.item_count()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn get(&self, idx: usize) -> Option<Byte> {
if idx >= self.len() {
None
} else {
Some(self.get_unchecked(idx))
}
}
pub fn get_unchecked(&self, idx: usize) -> Byte {
let start = molecule::NUMBER_SIZE + Self::ITEM_SIZE * idx;
let end = start + Self::ITEM_SIZE;
Byte::new_unchecked(self.0.slice(start..end))
}
pub fn raw_data(&self) -> molecule::bytes::Bytes {
self.0.slice(molecule::NUMBER_SIZE..)
}
pub fn as_reader<'r>(&'r self) -> Secp256k1Reader<'r> {
Secp256k1Reader::new_unchecked(self.as_slice())
}
}
impl molecule::prelude::Entity for Secp256k1 {
type Builder = Secp256k1Builder;
const NAME: &'static str = "Secp256k1";
fn new_unchecked(data: molecule::bytes::Bytes) -> Self {
Secp256k1(data)
}
fn as_bytes(&self) -> molecule::bytes::Bytes {
self.0.clone()
}
fn as_slice(&self) -> &[u8] {
&self.0[..]
}
fn from_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> {
Secp256k1Reader::from_slice(slice).map(|reader| reader.to_entity())
}
fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> {
Secp256k1Reader::from_compatible_slice(slice).map(|reader| reader.to_entity())
}
fn new_builder() -> Self::Builder {
::core::default::Default::default()
}
fn as_builder(self) -> Self::Builder {
Self::new_builder().extend(self.into_iter())
}
}
#[derive(Clone, Copy)]
pub struct Secp256k1Reader<'r>(&'r [u8]);
impl<'r> ::core::fmt::LowerHex for Secp256k1Reader<'r> {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
use molecule::hex_string;
if f.alternate() {
write!(f, "0x")?;
}
write!(f, "{}", hex_string(self.as_slice()))
}
}
impl<'r> ::core::fmt::Debug for Secp256k1Reader<'r> {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{}({:#x})", Self::NAME, self)
}
}
impl<'r> ::core::fmt::Display for Secp256k1Reader<'r> {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
use molecule::hex_string;
let raw_data = hex_string(&self.raw_data());
write!(f, "{}(0x{})", Self::NAME, raw_data)
}
}
impl<'r> Secp256k1Reader<'r> {
pub const ITEM_SIZE: usize = 1;
pub fn total_size(&self) -> usize {
molecule::NUMBER_SIZE * (self.item_count() + 1)
}
pub fn item_count(&self) -> usize {
molecule::unpack_number(self.as_slice()) as usize
}
pub fn len(&self) -> usize {
self.item_count()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn get(&self, idx: usize) -> Option<ByteReader<'r>> {
if idx >= self.len() {
None
} else {
Some(self.get_unchecked(idx))
}
}
pub fn get_unchecked(&self, idx: usize) -> ByteReader<'r> {
let start = molecule::NUMBER_SIZE + Self::ITEM_SIZE * idx;
let end = start + Self::ITEM_SIZE;
ByteReader::new_unchecked(&self.as_slice()[start..end])
}
pub fn raw_data(&self) -> &'r [u8] {
&self.as_slice()[molecule::NUMBER_SIZE..]
}
}
impl<'r> molecule::prelude::Reader<'r> for Secp256k1Reader<'r> {
type Entity = Secp256k1;
const NAME: &'static str = "Secp256k1Reader";
fn to_entity(&self) -> Self::Entity {
Self::Entity::new_unchecked(self.as_slice().to_owned().into())
}
fn new_unchecked(slice: &'r [u8]) -> Self {
Secp256k1Reader(slice)
}
fn as_slice(&self) -> &'r [u8] {
self.0
}
fn verify(slice: &[u8], _compatible: bool) -> molecule::error::VerificationResult<()> {
use molecule::verification_error as ve;
let slice_len = slice.len();
if slice_len < molecule::NUMBER_SIZE {
return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE, slice_len);
}
let item_count = molecule::unpack_number(slice) as usize;
if item_count == 0 {
if slice_len != molecule::NUMBER_SIZE {
return ve!(Self, TotalSizeNotMatch, molecule::NUMBER_SIZE, slice_len);
}
return Ok(());
}
let total_size = molecule::NUMBER_SIZE + Self::ITEM_SIZE * item_count;
if slice_len != total_size {
return ve!(Self, TotalSizeNotMatch, total_size, slice_len);
}
Ok(())
}
}
#[derive(Debug, Default)]
pub struct Secp256k1Builder(pub(crate) Vec<Byte>);
impl Secp256k1Builder {
pub const ITEM_SIZE: usize = 1;
pub fn set(mut self, v: Vec<Byte>) -> Self {
self.0 = v;
self
}
pub fn push(mut self, v: Byte) -> Self {
self.0.push(v);
self
}
pub fn extend<T: ::core::iter::IntoIterator<Item = Byte>>(mut self, iter: T) -> Self {
for elem in iter {
self.0.push(elem);
}
self
}
}
impl molecule::prelude::Builder for Secp256k1Builder {
type Entity = Secp256k1;
const NAME: &'static str = "Secp256k1Builder";
fn expected_length(&self) -> usize {
molecule::NUMBER_SIZE + Self::ITEM_SIZE * self.0.len()
}
fn write<W: ::molecule::io::Write>(&self, writer: &mut W) -> ::molecule::io::Result<()> {
writer.write_all(&molecule::pack_number(self.0.len() as molecule::Number))?;
for inner in &self.0[..] {
writer.write_all(inner.as_slice())?;
}
Ok(())
}
fn build(&self) -> Self::Entity {
let mut inner = Vec::with_capacity(self.expected_length());
self.write(&mut inner)
.unwrap_or_else(|_| panic!("{} build should be ok", Self::NAME));
Secp256k1::new_unchecked(inner.into())
}
}
pub struct Secp256k1Iterator(Secp256k1, usize, usize);
impl ::core::iter::Iterator for Secp256k1Iterator {
type Item = Byte;
fn next(&mut self) -> Option<Self::Item> {
if self.1 >= self.2 {
None
} else {
let ret = self.0.get_unchecked(self.1);
self.1 += 1;
Some(ret)
}
}
}
impl ::core::iter::ExactSizeIterator for Secp256k1Iterator {
fn len(&self) -> usize {
self.2 - self.1
}
}
impl ::core::iter::IntoIterator for Secp256k1 {
type Item = Byte;
type IntoIter = Secp256k1Iterator;
fn into_iter(self) -> Self::IntoIter {
let len = self.len();
Secp256k1Iterator(self, 0, len)
}
}
#[derive(Clone)]
pub struct Bytes(molecule::bytes::Bytes);
impl ::core::fmt::LowerHex for Bytes {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
use molecule::hex_string;
if f.alternate() {
write!(f, "0x")?;
}
write!(f, "{}", hex_string(self.as_slice()))
}
}
impl ::core::fmt::Debug for Bytes {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{}({:#x})", Self::NAME, self)
}
}
impl ::core::fmt::Display for Bytes {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
use molecule::hex_string;
let raw_data = hex_string(&self.raw_data());
write!(f, "{}(0x{})", Self::NAME, raw_data)
}
}
impl ::core::default::Default for Bytes {
fn default() -> Self {
let v: Vec<u8> = vec![0, 0, 0, 0];
Bytes::new_unchecked(v.into())
}
}
impl Bytes {
pub const ITEM_SIZE: usize = 1;
pub fn total_size(&self) -> usize {
molecule::NUMBER_SIZE * (self.item_count() + 1)
}
pub fn item_count(&self) -> usize {
molecule::unpack_number(self.as_slice()) as usize
}
pub fn len(&self) -> usize {
self.item_count()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn get(&self, idx: usize) -> Option<Byte> {
if idx >= self.len() {
None
} else {
Some(self.get_unchecked(idx))
}
}
pub fn get_unchecked(&self, idx: usize) -> Byte {
let start = molecule::NUMBER_SIZE + Self::ITEM_SIZE * idx;
let end = start + Self::ITEM_SIZE;
Byte::new_unchecked(self.0.slice(start..end))
}
pub fn raw_data(&self) -> molecule::bytes::Bytes {
self.0.slice(molecule::NUMBER_SIZE..)
}
pub fn as_reader<'r>(&'r self) -> BytesReader<'r> {
BytesReader::new_unchecked(self.as_slice())
}
}
impl molecule::prelude::Entity for Bytes {
type Builder = BytesBuilder;
const NAME: &'static str = "Bytes";
fn new_unchecked(data: molecule::bytes::Bytes) -> Self {
Bytes(data)
}
fn as_bytes(&self) -> molecule::bytes::Bytes {
self.0.clone()
}
fn as_slice(&self) -> &[u8] {
&self.0[..]
}
fn from_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> {
BytesReader::from_slice(slice).map(|reader| reader.to_entity())
}
fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> {
BytesReader::from_compatible_slice(slice).map(|reader| reader.to_entity())
}
fn new_builder() -> Self::Builder {
::core::default::Default::default()
}
fn as_builder(self) -> Self::Builder {
Self::new_builder().extend(self.into_iter())
}
}
#[derive(Clone, Copy)]
pub struct BytesReader<'r>(&'r [u8]);
impl<'r> ::core::fmt::LowerHex for BytesReader<'r> {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
use molecule::hex_string;
if f.alternate() {
write!(f, "0x")?;
}
write!(f, "{}", hex_string(self.as_slice()))
}
}
impl<'r> ::core::fmt::Debug for BytesReader<'r> {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{}({:#x})", Self::NAME, self)
}
}
impl<'r> ::core::fmt::Display for BytesReader<'r> {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
use molecule::hex_string;
let raw_data = hex_string(&self.raw_data());
write!(f, "{}(0x{})", Self::NAME, raw_data)
}
}
impl<'r> BytesReader<'r> {
pub const ITEM_SIZE: usize = 1;
pub fn total_size(&self) -> usize {
molecule::NUMBER_SIZE * (self.item_count() + 1)
}
pub fn item_count(&self) -> usize {
molecule::unpack_number(self.as_slice()) as usize
}
pub fn len(&self) -> usize {
self.item_count()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn get(&self, idx: usize) -> Option<ByteReader<'r>> {
if idx >= self.len() {
None
} else {
Some(self.get_unchecked(idx))
}
}
pub fn get_unchecked(&self, idx: usize) -> ByteReader<'r> {
let start = molecule::NUMBER_SIZE + Self::ITEM_SIZE * idx;
let end = start + Self::ITEM_SIZE;
ByteReader::new_unchecked(&self.as_slice()[start..end])
}
pub fn raw_data(&self) -> &'r [u8] {
&self.as_slice()[molecule::NUMBER_SIZE..]
}
}
impl<'r> molecule::prelude::Reader<'r> for BytesReader<'r> {
type Entity = Bytes;
const NAME: &'static str = "BytesReader";
fn to_entity(&self) -> Self::Entity {
Self::Entity::new_unchecked(self.as_slice().to_owned().into())
}
fn new_unchecked(slice: &'r [u8]) -> Self {
BytesReader(slice)
}
fn as_slice(&self) -> &'r [u8] {
self.0
}
fn verify(slice: &[u8], _compatible: bool) -> molecule::error::VerificationResult<()> {
use molecule::verification_error as ve;
let slice_len = slice.len();
if slice_len < molecule::NUMBER_SIZE {
return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE, slice_len);
}
let item_count = molecule::unpack_number(slice) as usize;
if item_count == 0 {
if slice_len != molecule::NUMBER_SIZE {
return ve!(Self, TotalSizeNotMatch, molecule::NUMBER_SIZE, slice_len);
}
return Ok(());
}
let total_size = molecule::NUMBER_SIZE + Self::ITEM_SIZE * item_count;
if slice_len != total_size {
return ve!(Self, TotalSizeNotMatch, total_size, slice_len);
}
Ok(())
}
}
#[derive(Debug, Default)]
pub struct BytesBuilder(pub(crate) Vec<Byte>);
impl BytesBuilder {
pub const ITEM_SIZE: usize = 1;
pub fn set(mut self, v: Vec<Byte>) -> Self {
self.0 = v;
self
}
pub fn push(mut self, v: Byte) -> Self {
self.0.push(v);
self
}
pub fn extend<T: ::core::iter::IntoIterator<Item = Byte>>(mut self, iter: T) -> Self {
for elem in iter {
self.0.push(elem);
}
self
}
}
impl molecule::prelude::Builder for BytesBuilder {
type Entity = Bytes;
const NAME: &'static str = "BytesBuilder";
fn expected_length(&self) -> usize {
molecule::NUMBER_SIZE + Self::ITEM_SIZE * self.0.len()
}
fn write<W: ::molecule::io::Write>(&self, writer: &mut W) -> ::molecule::io::Result<()> {
writer.write_all(&molecule::pack_number(self.0.len() as molecule::Number))?;
for inner in &self.0[..] {
writer.write_all(inner.as_slice())?;
}
Ok(())
}
fn build(&self) -> Self::Entity {
let mut inner = Vec::with_capacity(self.expected_length());
self.write(&mut inner)
.unwrap_or_else(|_| panic!("{} build should be ok", Self::NAME));
Bytes::new_unchecked(inner.into())
}
}
pub struct BytesIterator(Bytes, usize, usize);
impl ::core::iter::Iterator for BytesIterator {
type Item = Byte;
fn next(&mut self) -> Option<Self::Item> {
if self.1 >= self.2 {
None
} else {
let ret = self.0.get_unchecked(self.1);
self.1 += 1;
Some(ret)
}
}
}
impl ::core::iter::ExactSizeIterator for BytesIterator {
fn len(&self) -> usize {
self.2 - self.1
}
}
impl ::core::iter::IntoIterator for Bytes {
type Item = Byte;
type IntoIter = BytesIterator;
fn into_iter(self) -> Self::IntoIter {
let len = self.len();
BytesIterator(self, 0, len)
}
}
#[derive(Clone)]
pub struct String(molecule::bytes::Bytes);
impl ::core::fmt::LowerHex for String {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
use molecule::hex_string;
if f.alternate() {
write!(f, "0x")?;
}
write!(f, "{}", hex_string(self.as_slice()))
}
}
impl ::core::fmt::Debug for String {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{}({:#x})", Self::NAME, self)
}
}
impl ::core::fmt::Display for String {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
use molecule::hex_string;
let raw_data = hex_string(&self.raw_data());
write!(f, "{}(0x{})", Self::NAME, raw_data)
}
}
impl ::core::default::Default for String {
fn default() -> Self {
let v: Vec<u8> = vec![0, 0, 0, 0];
String::new_unchecked(v.into())
}
}
impl String {
pub const ITEM_SIZE: usize = 1;
pub fn total_size(&self) -> usize {
molecule::NUMBER_SIZE * (self.item_count() + 1)
}
pub fn item_count(&self) -> usize {
molecule::unpack_number(self.as_slice()) as usize
}
pub fn len(&self) -> usize {
self.item_count()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn get(&self, idx: usize) -> Option<Byte> {
if idx >= self.len() {
None
} else {
Some(self.get_unchecked(idx))
}
}
pub fn get_unchecked(&self, idx: usize) -> Byte {
let start = molecule::NUMBER_SIZE + Self::ITEM_SIZE * idx;
let end = start + Self::ITEM_SIZE;
Byte::new_unchecked(self.0.slice(start..end))
}
pub fn raw_data(&self) -> molecule::bytes::Bytes {
self.0.slice(molecule::NUMBER_SIZE..)
}
pub fn as_reader<'r>(&'r self) -> StringReader<'r> {
StringReader::new_unchecked(self.as_slice())
}
}
impl molecule::prelude::Entity for String {
type Builder = StringBuilder;
const NAME: &'static str = "String";
fn new_unchecked(data: molecule::bytes::Bytes) -> Self {
String(data)
}
fn as_bytes(&self) -> molecule::bytes::Bytes {
self.0.clone()
}
fn as_slice(&self) -> &[u8] {
&self.0[..]
}
fn from_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> {
StringReader::from_slice(slice).map(|reader| reader.to_entity())
}
fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> {
StringReader::from_compatible_slice(slice).map(|reader| reader.to_entity())
}
fn new_builder() -> Self::Builder {
::core::default::Default::default()
}
fn as_builder(self) -> Self::Builder {
Self::new_builder().extend(self.into_iter())
}
}
#[derive(Clone, Copy)]
pub struct StringReader<'r>(&'r [u8]);
impl<'r> ::core::fmt::LowerHex for StringReader<'r> {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
use molecule::hex_string;
if f.alternate() {
write!(f, "0x")?;
}
write!(f, "{}", hex_string(self.as_slice()))
}
}
impl<'r> ::core::fmt::Debug for StringReader<'r> {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{}({:#x})", Self::NAME, self)
}
}
impl<'r> ::core::fmt::Display for StringReader<'r> {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
use molecule::hex_string;
let raw_data = hex_string(&self.raw_data());
write!(f, "{}(0x{})", Self::NAME, raw_data)
}
}
impl<'r> StringReader<'r> {
pub const ITEM_SIZE: usize = 1;
pub fn total_size(&self) -> usize {
molecule::NUMBER_SIZE * (self.item_count() + 1)
}
pub fn item_count(&self) -> usize {
molecule::unpack_number(self.as_slice()) as usize
}
pub fn len(&self) -> usize {
self.item_count()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn get(&self, idx: usize) -> Option<ByteReader<'r>> {
if idx >= self.len() {
None
} else {
Some(self.get_unchecked(idx))
}
}
pub fn get_unchecked(&self, idx: usize) -> ByteReader<'r> {
let start = molecule::NUMBER_SIZE + Self::ITEM_SIZE * idx;
let end = start + Self::ITEM_SIZE;
ByteReader::new_unchecked(&self.as_slice()[start..end])
}
pub fn raw_data(&self) -> &'r [u8] {
&self.as_slice()[molecule::NUMBER_SIZE..]
}
}
impl<'r> molecule::prelude::Reader<'r> for StringReader<'r> {
type Entity = String;
const NAME: &'static str = "StringReader";
fn to_entity(&self) -> Self::Entity {
Self::Entity::new_unchecked(self.as_slice().to_owned().into())
}
fn new_unchecked(slice: &'r [u8]) -> Self {
StringReader(slice)
}
fn as_slice(&self) -> &'r [u8] {
self.0
}
fn verify(slice: &[u8], _compatible: bool) -> molecule::error::VerificationResult<()> {
use molecule::verification_error as ve;
let slice_len = slice.len();
if slice_len < molecule::NUMBER_SIZE {
return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE, slice_len);
}
let item_count = molecule::unpack_number(slice) as usize;
if item_count == 0 {
if slice_len != molecule::NUMBER_SIZE {
return ve!(Self, TotalSizeNotMatch, molecule::NUMBER_SIZE, slice_len);
}
return Ok(());
}
let total_size = molecule::NUMBER_SIZE + Self::ITEM_SIZE * item_count;
if slice_len != total_size {
return ve!(Self, TotalSizeNotMatch, total_size, slice_len);
}
Ok(())
}
}
#[derive(Debug, Default)]
pub struct StringBuilder(pub(crate) Vec<Byte>);
impl StringBuilder {
pub const ITEM_SIZE: usize = 1;
pub fn set(mut self, v: Vec<Byte>) -> Self {
self.0 = v;
self
}
pub fn push(mut self, v: Byte) -> Self {
self.0.push(v);
self
}
pub fn extend<T: ::core::iter::IntoIterator<Item = Byte>>(mut self, iter: T) -> Self {
for elem in iter {
self.0.push(elem);
}
self
}
}
impl molecule::prelude::Builder for StringBuilder {
type Entity = String;
const NAME: &'static str = "StringBuilder";
fn expected_length(&self) -> usize {
molecule::NUMBER_SIZE + Self::ITEM_SIZE * self.0.len()
}
fn write<W: ::molecule::io::Write>(&self, writer: &mut W) -> ::molecule::io::Result<()> {
writer.write_all(&molecule::pack_number(self.0.len() as molecule::Number))?;
for inner in &self.0[..] {
writer.write_all(inner.as_slice())?;
}
Ok(())
}
fn build(&self) -> Self::Entity {
let mut inner = Vec::with_capacity(self.expected_length());
self.write(&mut inner)
.unwrap_or_else(|_| panic!("{} build should be ok", Self::NAME));
String::new_unchecked(inner.into())
}
}
pub struct StringIterator(String, usize, usize);
impl ::core::iter::Iterator for StringIterator {
type Item = Byte;
fn next(&mut self) -> Option<Self::Item> {
if self.1 >= self.2 {
None
} else {
let ret = self.0.get_unchecked(self.1);
self.1 += 1;
Some(ret)
}
}
}
impl ::core::iter::ExactSizeIterator for StringIterator {
fn len(&self) -> usize {
self.2 - self.1
}
}
impl ::core::iter::IntoIterator for String {
type Item = Byte;
type IntoIter = StringIterator;
fn into_iter(self) -> Self::IntoIter {
let len = self.len();
StringIterator(self, 0, len)
}
}
#[derive(Clone)]
pub struct PublicKey(molecule::bytes::Bytes);
impl ::core::fmt::LowerHex for PublicKey {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
use molecule::hex_string;
if f.alternate() {
write!(f, "0x")?;
}
write!(f, "{}", hex_string(self.as_slice()))
}
}
impl ::core::fmt::Debug for PublicKey {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{}({:#x})", Self::NAME, self)
}
}
impl ::core::fmt::Display for PublicKey {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{}(", Self::NAME)?;
self.to_enum().display_inner(f)?;
write!(f, ")")
}
}
impl ::core::default::Default for PublicKey {
fn default() -> Self {
let v: Vec<u8> = vec![0, 0, 0, 0, 0, 0, 0, 0];
PublicKey::new_unchecked(v.into())
}
}
impl PublicKey {
pub const ITEMS_COUNT: usize = 1;
pub fn item_id(&self) -> molecule::Number {
molecule::unpack_number(self.as_slice())
}
pub fn to_enum(&self) -> PublicKeyUnion {
let inner = self.0.slice(molecule::NUMBER_SIZE..);
match self.item_id() {
0 => Secp256k1::new_unchecked(inner).into(),
_ => panic!("{}: invalid data", Self::NAME),
}
}
pub fn as_reader<'r>(&'r self) -> PublicKeyReader<'r> {
PublicKeyReader::new_unchecked(self.as_slice())
}
}
impl molecule::prelude::Entity for PublicKey {
type Builder = PublicKeyBuilder;
const NAME: &'static str = "PublicKey";
fn new_unchecked(data: molecule::bytes::Bytes) -> Self {
PublicKey(data)
}
fn as_bytes(&self) -> molecule::bytes::Bytes {
self.0.clone()
}
fn as_slice(&self) -> &[u8] {
&self.0[..]
}
fn from_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> {
PublicKeyReader::from_slice(slice).map(|reader| reader.to_entity())
}
fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> {
PublicKeyReader::from_compatible_slice(slice).map(|reader| reader.to_entity())
}
fn new_builder() -> Self::Builder {
::core::default::Default::default()
}
fn as_builder(self) -> Self::Builder {
Self::new_builder().set(self.to_enum())
}
}
#[derive(Clone, Copy)]
pub struct PublicKeyReader<'r>(&'r [u8]);
impl<'r> ::core::fmt::LowerHex for PublicKeyReader<'r> {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
use molecule::hex_string;
if f.alternate() {
write!(f, "0x")?;
}
write!(f, "{}", hex_string(self.as_slice()))
}
}
impl<'r> ::core::fmt::Debug for PublicKeyReader<'r> {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{}({:#x})", Self::NAME, self)
}
}
impl<'r> ::core::fmt::Display for PublicKeyReader<'r> {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{}(", Self::NAME)?;
self.to_enum().display_inner(f)?;
write!(f, ")")
}
}
impl<'r> PublicKeyReader<'r> {
pub const ITEMS_COUNT: usize = 1;
pub fn item_id(&self) -> molecule::Number {
molecule::unpack_number(self.as_slice())
}
pub fn to_enum(&self) -> PublicKeyUnionReader<'r> {
let inner = &self.as_slice()[molecule::NUMBER_SIZE..];
match self.item_id() {
0 => Secp256k1Reader::new_unchecked(inner).into(),
_ => panic!("{}: invalid data", Self::NAME),
}
}
}
impl<'r> molecule::prelude::Reader<'r> for PublicKeyReader<'r> {
type Entity = PublicKey;
const NAME: &'static str = "PublicKeyReader";
fn to_entity(&self) -> Self::Entity {
Self::Entity::new_unchecked(self.as_slice().to_owned().into())
}
fn new_unchecked(slice: &'r [u8]) -> Self {
PublicKeyReader(slice)
}
fn as_slice(&self) -> &'r [u8] {
self.0
}
fn verify(slice: &[u8], compatible: bool) -> molecule::error::VerificationResult<()> {
use molecule::verification_error as ve;
let slice_len = slice.len();
if slice_len < molecule::NUMBER_SIZE {
return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE, slice_len);
}
let item_id = molecule::unpack_number(slice);
let inner_slice = &slice[molecule::NUMBER_SIZE..];
match item_id {
0 => Secp256k1Reader::verify(inner_slice, compatible),
_ => ve!(Self, UnknownItem, Self::ITEMS_COUNT, item_id),
}?;
Ok(())
}
}
#[derive(Debug, Default)]
pub struct PublicKeyBuilder(pub(crate) PublicKeyUnion);
impl PublicKeyBuilder {
pub const ITEMS_COUNT: usize = 1;
pub fn set<I>(mut self, v: I) -> Self
where
I: ::core::convert::Into<PublicKeyUnion>,
{
self.0 = v.into();
self
}
}
impl molecule::prelude::Builder for PublicKeyBuilder {
type Entity = PublicKey;
const NAME: &'static str = "PublicKeyBuilder";
fn expected_length(&self) -> usize {
molecule::NUMBER_SIZE + self.0.as_slice().len()
}
fn write<W: ::molecule::io::Write>(&self, writer: &mut W) -> ::molecule::io::Result<()> {
writer.write_all(&molecule::pack_number(self.0.item_id()))?;
writer.write_all(self.0.as_slice())
}
fn build(&self) -> Self::Entity {
let mut inner = Vec::with_capacity(self.expected_length());
self.write(&mut inner)
.unwrap_or_else(|_| panic!("{} build should be ok", Self::NAME));
PublicKey::new_unchecked(inner.into())
}
}
#[derive(Debug, Clone)]
pub enum PublicKeyUnion {
Secp256k1(Secp256k1),
}
#[derive(Debug, Clone, Copy)]
pub enum PublicKeyUnionReader<'r> {
Secp256k1(Secp256k1Reader<'r>),
}
impl ::core::default::Default for PublicKeyUnion {
fn default() -> Self {
PublicKeyUnion::Secp256k1(::core::default::Default::default())
}
}
impl ::core::fmt::Display for PublicKeyUnion {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
PublicKeyUnion::Secp256k1(ref item) => {
write!(f, "{}::{}({})", Self::NAME, Secp256k1::NAME, item)
}
}
}
}
impl<'r> ::core::fmt::Display for PublicKeyUnionReader<'r> {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
PublicKeyUnionReader::Secp256k1(ref item) => {
write!(f, "{}::{}({})", Self::NAME, Secp256k1::NAME, item)
}
}
}
}
impl PublicKeyUnion {
pub(crate) fn display_inner(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
PublicKeyUnion::Secp256k1(ref item) => write!(f, "{}", item),
}
}
}
impl<'r> PublicKeyUnionReader<'r> {
pub(crate) fn display_inner(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
PublicKeyUnionReader::Secp256k1(ref item) => write!(f, "{}", item),
}
}
}
impl ::core::convert::From<Secp256k1> for PublicKeyUnion {
fn from(item: Secp256k1) -> Self {
PublicKeyUnion::Secp256k1(item)
}
}
impl<'r> ::core::convert::From<Secp256k1Reader<'r>> for PublicKeyUnionReader<'r> {
fn from(item: Secp256k1Reader<'r>) -> Self {
PublicKeyUnionReader::Secp256k1(item)
}
}
impl PublicKeyUnion {
pub const NAME: &'static str = "PublicKeyUnion";
pub fn as_bytes(&self) -> molecule::bytes::Bytes {
match self {
PublicKeyUnion::Secp256k1(item) => item.as_bytes(),
}
}
pub fn as_slice(&self) -> &[u8] {
match self {
PublicKeyUnion::Secp256k1(item) => item.as_slice(),
}
}
pub fn item_id(&self) -> molecule::Number {
match self {
PublicKeyUnion::Secp256k1(_) => 0,
}
}
pub fn item_name(&self) -> &str {
match self {
PublicKeyUnion::Secp256k1(_) => "Secp256k1",
}
}
pub fn as_reader<'r>(&'r self) -> PublicKeyUnionReader<'r> {
match self {
PublicKeyUnion::Secp256k1(item) => item.as_reader().into(),
}
}
}
impl<'r> PublicKeyUnionReader<'r> {
pub const NAME: &'r str = "PublicKeyUnionReader";
pub fn as_slice(&self) -> &'r [u8] {
match self {
PublicKeyUnionReader::Secp256k1(item) => item.as_slice(),
}
}
pub fn item_id(&self) -> molecule::Number {
match self {
PublicKeyUnionReader::Secp256k1(_) => 0,
}
}
pub fn item_name(&self) -> &str {
match self {
PublicKeyUnionReader::Secp256k1(_) => "Secp256k1",
}
}
}
#[derive(Clone)]
pub struct Propose(molecule::bytes::Bytes);
impl ::core::fmt::LowerHex for Propose {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
use molecule::hex_string;
if f.alternate() {
write!(f, "0x")?;
}
write!(f, "{}", hex_string(self.as_slice()))
}
}
impl ::core::fmt::Debug for Propose {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{}({:#x})", Self::NAME, self)
}
}
impl ::core::fmt::Display for Propose {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{} {{ ", Self::NAME)?;
write!(f, "{}: {}", "rand", self.rand())?;
write!(f, ", {}: {}", "pubkey", self.pubkey())?;
write!(f, ", {}: {}", "exchanges", self.exchanges())?;
write!(f, ", {}: {}", "ciphers", self.ciphers())?;
write!(f, ", {}: {}", "hashes", self.hashes())?;
let extra_count = self.count_extra_fields();
if extra_count != 0 {
write!(f, ", .. ({} fields)", extra_count)?;
}
write!(f, " }}")
}
}
impl ::core::default::Default for Propose {
fn default() -> Self {
let v: Vec<u8> = vec![
44, 0, 0, 0, 24, 0, 0, 0, 28, 0, 0, 0, 32, 0, 0, 0, 36, 0, 0, 0, 40, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
];
Propose::new_unchecked(v.into())
}
}
impl Propose {
pub const FIELD_COUNT: usize = 5;
pub fn total_size(&self) -> usize {
molecule::unpack_number(self.as_slice()) as usize
}
pub fn field_count(&self) -> usize {
if self.total_size() == molecule::NUMBER_SIZE {
0
} else {
(molecule::unpack_number(&self.as_slice()[molecule::NUMBER_SIZE..]) as usize / 4) - 1
}
}
pub fn count_extra_fields(&self) -> usize {
self.field_count() - Self::FIELD_COUNT
}
pub fn has_extra_fields(&self) -> bool {
Self::FIELD_COUNT != self.field_count()
}
pub fn rand(&self) -> Bytes {
let slice = self.as_slice();
let start = molecule::unpack_number(&slice[4..]) as usize;
let end = molecule::unpack_number(&slice[8..]) as usize;
Bytes::new_unchecked(self.0.slice(start..end))
}
pub fn pubkey(&self) -> Bytes {
let slice = self.as_slice();
let start = molecule::unpack_number(&slice[8..]) as usize;
let end = molecule::unpack_number(&slice[12..]) as usize;
Bytes::new_unchecked(self.0.slice(start..end))
}
pub fn exchanges(&self) -> String {
let slice = self.as_slice();
let start = molecule::unpack_number(&slice[12..]) as usize;
let end = molecule::unpack_number(&slice[16..]) as usize;
String::new_unchecked(self.0.slice(start..end))
}
pub fn ciphers(&self) -> String {
let slice = self.as_slice();
let start = molecule::unpack_number(&slice[16..]) as usize;
let end = molecule::unpack_number(&slice[20..]) as usize;
String::new_unchecked(self.0.slice(start..end))
}
pub fn hashes(&self) -> String {
let slice = self.as_slice();
let start = molecule::unpack_number(&slice[20..]) as usize;
if self.has_extra_fields() {
let end = molecule::unpack_number(&slice[24..]) as usize;
String::new_unchecked(self.0.slice(start..end))
} else {
String::new_unchecked(self.0.slice(start..))
}
}
pub fn as_reader<'r>(&'r self) -> ProposeReader<'r> {
ProposeReader::new_unchecked(self.as_slice())
}
}
impl molecule::prelude::Entity for Propose {
type Builder = ProposeBuilder;
const NAME: &'static str = "Propose";
fn new_unchecked(data: molecule::bytes::Bytes) -> Self {
Propose(data)
}
fn as_bytes(&self) -> molecule::bytes::Bytes {
self.0.clone()
}
fn as_slice(&self) -> &[u8] {
&self.0[..]
}
fn from_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> {
ProposeReader::from_slice(slice).map(|reader| reader.to_entity())
}
fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> {
ProposeReader::from_compatible_slice(slice).map(|reader| reader.to_entity())
}
fn new_builder() -> Self::Builder {
::core::default::Default::default()
}
fn as_builder(self) -> Self::Builder {
Self::new_builder()
.rand(self.rand())
.pubkey(self.pubkey())
.exchanges(self.exchanges())
.ciphers(self.ciphers())
.hashes(self.hashes())
}
}
#[derive(Clone, Copy)]
pub struct ProposeReader<'r>(&'r [u8]);
impl<'r> ::core::fmt::LowerHex for ProposeReader<'r> {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
use molecule::hex_string;
if f.alternate() {
write!(f, "0x")?;
}
write!(f, "{}", hex_string(self.as_slice()))
}
}
impl<'r> ::core::fmt::Debug for ProposeReader<'r> {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{}({:#x})", Self::NAME, self)
}
}
impl<'r> ::core::fmt::Display for ProposeReader<'r> {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{} {{ ", Self::NAME)?;
write!(f, "{}: {}", "rand", self.rand())?;
write!(f, ", {}: {}", "pubkey", self.pubkey())?;
write!(f, ", {}: {}", "exchanges", self.exchanges())?;
write!(f, ", {}: {}", "ciphers", self.ciphers())?;
write!(f, ", {}: {}", "hashes", self.hashes())?;
let extra_count = self.count_extra_fields();
if extra_count != 0 {
write!(f, ", .. ({} fields)", extra_count)?;
}
write!(f, " }}")
}
}
impl<'r> ProposeReader<'r> {
pub const FIELD_COUNT: usize = 5;
pub fn total_size(&self) -> usize {
molecule::unpack_number(self.as_slice()) as usize
}
pub fn field_count(&self) -> usize {
if self.total_size() == molecule::NUMBER_SIZE {
0
} else {
(molecule::unpack_number(&self.as_slice()[molecule::NUMBER_SIZE..]) as usize / 4) - 1
}
}
pub fn count_extra_fields(&self) -> usize {
self.field_count() - Self::FIELD_COUNT
}
pub fn has_extra_fields(&self) -> bool {
Self::FIELD_COUNT != self.field_count()
}
pub fn rand(&self) -> BytesReader<'r> {
let slice = self.as_slice();
let start = molecule::unpack_number(&slice[4..]) as usize;
let end = molecule::unpack_number(&slice[8..]) as usize;
BytesReader::new_unchecked(&self.as_slice()[start..end])
}
pub fn pubkey(&self) -> BytesReader<'r> {
let slice = self.as_slice();
let start = molecule::unpack_number(&slice[8..]) as usize;
let end = molecule::unpack_number(&slice[12..]) as usize;
BytesReader::new_unchecked(&self.as_slice()[start..end])
}
pub fn exchanges(&self) -> StringReader<'r> {
let slice = self.as_slice();
let start = molecule::unpack_number(&slice[12..]) as usize;
let end = molecule::unpack_number(&slice[16..]) as usize;
StringReader::new_unchecked(&self.as_slice()[start..end])
}
pub fn ciphers(&self) -> StringReader<'r> {
let slice = self.as_slice();
let start = molecule::unpack_number(&slice[16..]) as usize;
let end = molecule::unpack_number(&slice[20..]) as usize;
StringReader::new_unchecked(&self.as_slice()[start..end])
}
pub fn hashes(&self) -> StringReader<'r> {
let slice = self.as_slice();
let start = molecule::unpack_number(&slice[20..]) as usize;
if self.has_extra_fields() {
let end = molecule::unpack_number(&slice[24..]) as usize;
StringReader::new_unchecked(&self.as_slice()[start..end])
} else {
StringReader::new_unchecked(&self.as_slice()[start..])
}
}
}
impl<'r> molecule::prelude::Reader<'r> for ProposeReader<'r> {
type Entity = Propose;
const NAME: &'static str = "ProposeReader";
fn to_entity(&self) -> Self::Entity {
Self::Entity::new_unchecked(self.as_slice().to_owned().into())
}
fn new_unchecked(slice: &'r [u8]) -> Self {
ProposeReader(slice)
}
fn as_slice(&self) -> &'r [u8] {
self.0
}
fn verify(slice: &[u8], compatible: bool) -> molecule::error::VerificationResult<()> {
use molecule::verification_error as ve;
let slice_len = slice.len();
if slice_len < molecule::NUMBER_SIZE {
return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE, slice_len);
}
let total_size = molecule::unpack_number(slice) as usize;
if slice_len != total_size {
return ve!(Self, TotalSizeNotMatch, total_size, slice_len);
}
if slice_len == molecule::NUMBER_SIZE && Self::FIELD_COUNT == 0 {
return Ok(());
}
if slice_len < molecule::NUMBER_SIZE * 2 {
return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE * 2, slice_len);
}
let offset_first = molecule::unpack_number(&slice[molecule::NUMBER_SIZE..]) as usize;
if offset_first % molecule::NUMBER_SIZE != 0 || offset_first < molecule::NUMBER_SIZE * 2 {
return ve!(Self, OffsetsNotMatch);
}
if slice_len < offset_first {
return ve!(Self, HeaderIsBroken, offset_first, slice_len);
}
let field_count = offset_first / molecule::NUMBER_SIZE - 1;
if field_count < Self::FIELD_COUNT {
return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, field_count);
} else if !compatible && field_count > Self::FIELD_COUNT {
return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, field_count);
};
let mut offsets: Vec<usize> = slice[molecule::NUMBER_SIZE..offset_first]
.chunks_exact(molecule::NUMBER_SIZE)
.map(|x| molecule::unpack_number(x) as usize)
.collect();
offsets.push(total_size);
if offsets.windows(2).any(|i| i[0] > i[1]) {
return ve!(Self, OffsetsNotMatch);
}
BytesReader::verify(&slice[offsets[0]..offsets[1]], compatible)?;
BytesReader::verify(&slice[offsets[1]..offsets[2]], compatible)?;
StringReader::verify(&slice[offsets[2]..offsets[3]], compatible)?;
StringReader::verify(&slice[offsets[3]..offsets[4]], compatible)?;
StringReader::verify(&slice[offsets[4]..offsets[5]], compatible)?;
Ok(())
}
}
#[derive(Debug, Default)]
pub struct ProposeBuilder {
pub(crate) rand: Bytes,
pub(crate) pubkey: Bytes,
pub(crate) exchanges: String,
pub(crate) ciphers: String,
pub(crate) hashes: String,
}
impl ProposeBuilder {
pub const FIELD_COUNT: usize = 5;
pub fn rand(mut self, v: Bytes) -> Self {
self.rand = v;
self
}
pub fn pubkey(mut self, v: Bytes) -> Self {
self.pubkey = v;
self
}
pub fn exchanges(mut self, v: String) -> Self {
self.exchanges = v;
self
}
pub fn ciphers(mut self, v: String) -> Self {
self.ciphers = v;
self
}
pub fn hashes(mut self, v: String) -> Self {
self.hashes = v;
self
}
}
impl molecule::prelude::Builder for ProposeBuilder {
type Entity = Propose;
const NAME: &'static str = "ProposeBuilder";
fn expected_length(&self) -> usize {
molecule::NUMBER_SIZE * (Self::FIELD_COUNT + 1)
+ self.rand.as_slice().len()
+ self.pubkey.as_slice().len()
+ self.exchanges.as_slice().len()
+ self.ciphers.as_slice().len()
+ self.hashes.as_slice().len()
}
fn write<W: ::molecule::io::Write>(&self, writer: &mut W) -> ::molecule::io::Result<()> {
let mut total_size = molecule::NUMBER_SIZE * (Self::FIELD_COUNT + 1);
let mut offsets = Vec::with_capacity(Self::FIELD_COUNT);
offsets.push(total_size);
total_size += self.rand.as_slice().len();
offsets.push(total_size);
total_size += self.pubkey.as_slice().len();
offsets.push(total_size);
total_size += self.exchanges.as_slice().len();
offsets.push(total_size);
total_size += self.ciphers.as_slice().len();
offsets.push(total_size);
total_size += self.hashes.as_slice().len();
writer.write_all(&molecule::pack_number(total_size as molecule::Number))?;
for offset in offsets.into_iter() {
writer.write_all(&molecule::pack_number(offset as molecule::Number))?;
}
writer.write_all(self.rand.as_slice())?;
writer.write_all(self.pubkey.as_slice())?;
writer.write_all(self.exchanges.as_slice())?;
writer.write_all(self.ciphers.as_slice())?;
writer.write_all(self.hashes.as_slice())?;
Ok(())
}
fn build(&self) -> Self::Entity {
let mut inner = Vec::with_capacity(self.expected_length());
self.write(&mut inner)
.unwrap_or_else(|_| panic!("{} build should be ok", Self::NAME));
Propose::new_unchecked(inner.into())
}
}
#[derive(Clone)]
pub struct Exchange(molecule::bytes::Bytes);
impl ::core::fmt::LowerHex for Exchange {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
use molecule::hex_string;
if f.alternate() {
write!(f, "0x")?;
}
write!(f, "{}", hex_string(self.as_slice()))
}
}
impl ::core::fmt::Debug for Exchange {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{}({:#x})", Self::NAME, self)
}
}
impl ::core::fmt::Display for Exchange {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{} {{ ", Self::NAME)?;
write!(f, "{}: {}", "epubkey", self.epubkey())?;
write!(f, ", {}: {}", "signature", self.signature())?;
let extra_count = self.count_extra_fields();
if extra_count != 0 {
write!(f, ", .. ({} fields)", extra_count)?;
}
write!(f, " }}")
}
}
impl ::core::default::Default for Exchange {
fn default() -> Self {
let v: Vec<u8> = vec![
20, 0, 0, 0, 12, 0, 0, 0, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
];
Exchange::new_unchecked(v.into())
}
}
impl Exchange {
pub const FIELD_COUNT: usize = 2;
pub fn total_size(&self) -> usize {
molecule::unpack_number(self.as_slice()) as usize
}
pub fn field_count(&self) -> usize {
if self.total_size() == molecule::NUMBER_SIZE {
0
} else {
(molecule::unpack_number(&self.as_slice()[molecule::NUMBER_SIZE..]) as usize / 4) - 1
}
}
pub fn count_extra_fields(&self) -> usize {
self.field_count() - Self::FIELD_COUNT
}
pub fn has_extra_fields(&self) -> bool {
Self::FIELD_COUNT != self.field_count()
}
pub fn epubkey(&self) -> Bytes {
let slice = self.as_slice();
let start = molecule::unpack_number(&slice[4..]) as usize;
let end = molecule::unpack_number(&slice[8..]) as usize;
Bytes::new_unchecked(self.0.slice(start..end))
}
pub fn signature(&self) -> Bytes {
let slice = self.as_slice();
let start = molecule::unpack_number(&slice[8..]) as usize;
if self.has_extra_fields() {
let end = molecule::unpack_number(&slice[12..]) as usize;
Bytes::new_unchecked(self.0.slice(start..end))
} else {
Bytes::new_unchecked(self.0.slice(start..))
}
}
pub fn as_reader<'r>(&'r self) -> ExchangeReader<'r> {
ExchangeReader::new_unchecked(self.as_slice())
}
}
impl molecule::prelude::Entity for Exchange {
type Builder = ExchangeBuilder;
const NAME: &'static str = "Exchange";
fn new_unchecked(data: molecule::bytes::Bytes) -> Self {
Exchange(data)
}
fn as_bytes(&self) -> molecule::bytes::Bytes {
self.0.clone()
}
fn as_slice(&self) -> &[u8] {
&self.0[..]
}
fn from_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> {
ExchangeReader::from_slice(slice).map(|reader| reader.to_entity())
}
fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> {
ExchangeReader::from_compatible_slice(slice).map(|reader| reader.to_entity())
}
fn new_builder() -> Self::Builder {
::core::default::Default::default()
}
fn as_builder(self) -> Self::Builder {
Self::new_builder()
.epubkey(self.epubkey())
.signature(self.signature())
}
}
#[derive(Clone, Copy)]
pub struct ExchangeReader<'r>(&'r [u8]);
impl<'r> ::core::fmt::LowerHex for ExchangeReader<'r> {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
use molecule::hex_string;
if f.alternate() {
write!(f, "0x")?;
}
write!(f, "{}", hex_string(self.as_slice()))
}
}
impl<'r> ::core::fmt::Debug for ExchangeReader<'r> {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{}({:#x})", Self::NAME, self)
}
}
impl<'r> ::core::fmt::Display for ExchangeReader<'r> {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{} {{ ", Self::NAME)?;
write!(f, "{}: {}", "epubkey", self.epubkey())?;
write!(f, ", {}: {}", "signature", self.signature())?;
let extra_count = self.count_extra_fields();
if extra_count != 0 {
write!(f, ", .. ({} fields)", extra_count)?;
}
write!(f, " }}")
}
}
impl<'r> ExchangeReader<'r> {
pub const FIELD_COUNT: usize = 2;
pub fn total_size(&self) -> usize {
molecule::unpack_number(self.as_slice()) as usize
}
pub fn field_count(&self) -> usize {
if self.total_size() == molecule::NUMBER_SIZE {
0
} else {
(molecule::unpack_number(&self.as_slice()[molecule::NUMBER_SIZE..]) as usize / 4) - 1
}
}
pub fn count_extra_fields(&self) -> usize {
self.field_count() - Self::FIELD_COUNT
}
pub fn has_extra_fields(&self) -> bool {
Self::FIELD_COUNT != self.field_count()
}
pub fn epubkey(&self) -> BytesReader<'r> {
let slice = self.as_slice();
let start = molecule::unpack_number(&slice[4..]) as usize;
let end = molecule::unpack_number(&slice[8..]) as usize;
BytesReader::new_unchecked(&self.as_slice()[start..end])
}
pub fn signature(&self) -> BytesReader<'r> {
let slice = self.as_slice();
let start = molecule::unpack_number(&slice[8..]) as usize;
if self.has_extra_fields() {
let end = molecule::unpack_number(&slice[12..]) as usize;
BytesReader::new_unchecked(&self.as_slice()[start..end])
} else {
BytesReader::new_unchecked(&self.as_slice()[start..])
}
}
}
impl<'r> molecule::prelude::Reader<'r> for ExchangeReader<'r> {
type Entity = Exchange;
const NAME: &'static str = "ExchangeReader";
fn to_entity(&self) -> Self::Entity {
Self::Entity::new_unchecked(self.as_slice().to_owned().into())
}
fn new_unchecked(slice: &'r [u8]) -> Self {
ExchangeReader(slice)
}
fn as_slice(&self) -> &'r [u8] {
self.0
}
fn verify(slice: &[u8], compatible: bool) -> molecule::error::VerificationResult<()> {
use molecule::verification_error as ve;
let slice_len = slice.len();
if slice_len < molecule::NUMBER_SIZE {
return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE, slice_len);
}
let total_size = molecule::unpack_number(slice) as usize;
if slice_len != total_size {
return ve!(Self, TotalSizeNotMatch, total_size, slice_len);
}
if slice_len == molecule::NUMBER_SIZE && Self::FIELD_COUNT == 0 {
return Ok(());
}
if slice_len < molecule::NUMBER_SIZE * 2 {
return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE * 2, slice_len);
}
let offset_first = molecule::unpack_number(&slice[molecule::NUMBER_SIZE..]) as usize;
if offset_first % molecule::NUMBER_SIZE != 0 || offset_first < molecule::NUMBER_SIZE * 2 {
return ve!(Self, OffsetsNotMatch);
}
if slice_len < offset_first {
return ve!(Self, HeaderIsBroken, offset_first, slice_len);
}
let field_count = offset_first / molecule::NUMBER_SIZE - 1;
if field_count < Self::FIELD_COUNT {
return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, field_count);
} else if !compatible && field_count > Self::FIELD_COUNT {
return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, field_count);
};
let mut offsets: Vec<usize> = slice[molecule::NUMBER_SIZE..offset_first]
.chunks_exact(molecule::NUMBER_SIZE)
.map(|x| molecule::unpack_number(x) as usize)
.collect();
offsets.push(total_size);
if offsets.windows(2).any(|i| i[0] > i[1]) {
return ve!(Self, OffsetsNotMatch);
}
BytesReader::verify(&slice[offsets[0]..offsets[1]], compatible)?;
BytesReader::verify(&slice[offsets[1]..offsets[2]], compatible)?;
Ok(())
}
}
#[derive(Debug, Default)]
pub struct ExchangeBuilder {
pub(crate) epubkey: Bytes,
pub(crate) signature: Bytes,
}
impl ExchangeBuilder {
pub const FIELD_COUNT: usize = 2;
pub fn epubkey(mut self, v: Bytes) -> Self {
self.epubkey = v;
self
}
pub fn signature(mut self, v: Bytes) -> Self {
self.signature = v;
self
}
}
impl molecule::prelude::Builder for ExchangeBuilder {
type Entity = Exchange;
const NAME: &'static str = "ExchangeBuilder";
fn expected_length(&self) -> usize {
molecule::NUMBER_SIZE * (Self::FIELD_COUNT + 1)
+ self.epubkey.as_slice().len()
+ self.signature.as_slice().len()
}
fn write<W: ::molecule::io::Write>(&self, writer: &mut W) -> ::molecule::io::Result<()> {
let mut total_size = molecule::NUMBER_SIZE * (Self::FIELD_COUNT + 1);
let mut offsets = Vec::with_capacity(Self::FIELD_COUNT);
offsets.push(total_size);
total_size += self.epubkey.as_slice().len();
offsets.push(total_size);
total_size += self.signature.as_slice().len();
writer.write_all(&molecule::pack_number(total_size as molecule::Number))?;
for offset in offsets.into_iter() {
writer.write_all(&molecule::pack_number(offset as molecule::Number))?;
}
writer.write_all(self.epubkey.as_slice())?;
writer.write_all(self.signature.as_slice())?;
Ok(())
}
fn build(&self) -> Self::Entity {
let mut inner = Vec::with_capacity(self.expected_length());
self.write(&mut inner)
.unwrap_or_else(|_| panic!("{} build should be ok", Self::NAME));
Exchange::new_unchecked(inner.into())
}
}