use super::blockchain::*;
use super::extensions::*;
use molecule::prelude::*;
#[derive(Clone)]
pub struct PingPayload(molecule::bytes::Bytes);
impl ::core::fmt::LowerHex for PingPayload {
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 PingPayload {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{}({:#x})", Self::NAME, self)
}
}
impl ::core::fmt::Display for PingPayload {
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 PingPayload {
fn default() -> Self {
let v = molecule::bytes::Bytes::from_static(&Self::DEFAULT_VALUE);
PingPayload::new_unchecked(v)
}
}
impl PingPayload {
const DEFAULT_VALUE: [u8; 16] = [0, 0, 0, 0, 12, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0];
pub const ITEMS_COUNT: usize = 2;
pub fn item_id(&self) -> molecule::Number {
molecule::unpack_number(self.as_slice())
}
pub fn to_enum(&self) -> PingPayloadUnion {
let inner = self.0.slice(molecule::NUMBER_SIZE..);
match self.item_id() {
0 => Ping::new_unchecked(inner).into(),
1 => Pong::new_unchecked(inner).into(),
_ => panic!("{}: invalid data", Self::NAME),
}
}
pub fn as_reader<'r>(&'r self) -> PingPayloadReader<'r> {
PingPayloadReader::new_unchecked(self.as_slice())
}
}
impl molecule::prelude::Entity for PingPayload {
type Builder = PingPayloadBuilder;
const NAME: &'static str = "PingPayload";
fn new_unchecked(data: molecule::bytes::Bytes) -> Self {
PingPayload(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> {
PingPayloadReader::from_slice(slice).map(|reader| reader.to_entity())
}
fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> {
PingPayloadReader::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 PingPayloadReader<'r>(&'r [u8]);
impl<'r> ::core::fmt::LowerHex for PingPayloadReader<'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 PingPayloadReader<'r> {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{}({:#x})", Self::NAME, self)
}
}
impl<'r> ::core::fmt::Display for PingPayloadReader<'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> PingPayloadReader<'r> {
pub const ITEMS_COUNT: usize = 2;
pub fn item_id(&self) -> molecule::Number {
molecule::unpack_number(self.as_slice())
}
pub fn to_enum(&self) -> PingPayloadUnionReader<'r> {
let inner = &self.as_slice()[molecule::NUMBER_SIZE..];
match self.item_id() {
0 => PingReader::new_unchecked(inner).into(),
1 => PongReader::new_unchecked(inner).into(),
_ => panic!("{}: invalid data", Self::NAME),
}
}
}
impl<'r> molecule::prelude::Reader<'r> for PingPayloadReader<'r> {
type Entity = PingPayload;
const NAME: &'static str = "PingPayloadReader";
fn to_entity(&self) -> Self::Entity {
Self::Entity::new_unchecked(self.as_slice().to_owned().into())
}
fn new_unchecked(slice: &'r [u8]) -> Self {
PingPayloadReader(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 => PingReader::verify(inner_slice, compatible),
1 => PongReader::verify(inner_slice, compatible),
_ => ve!(Self, UnknownItem, Self::ITEMS_COUNT, item_id),
}?;
Ok(())
}
}
#[derive(Debug, Default)]
pub struct PingPayloadBuilder(pub(crate) PingPayloadUnion);
impl PingPayloadBuilder {
pub const ITEMS_COUNT: usize = 2;
pub fn set<I>(mut self, v: I) -> Self
where
I: ::core::convert::Into<PingPayloadUnion>,
{
self.0 = v.into();
self
}
}
impl molecule::prelude::Builder for PingPayloadBuilder {
type Entity = PingPayload;
const NAME: &'static str = "PingPayloadBuilder";
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));
PingPayload::new_unchecked(inner.into())
}
}
#[derive(Debug, Clone)]
pub enum PingPayloadUnion {
Ping(Ping),
Pong(Pong),
}
#[derive(Debug, Clone, Copy)]
pub enum PingPayloadUnionReader<'r> {
Ping(PingReader<'r>),
Pong(PongReader<'r>),
}
impl ::core::default::Default for PingPayloadUnion {
fn default() -> Self {
PingPayloadUnion::Ping(::core::default::Default::default())
}
}
impl ::core::fmt::Display for PingPayloadUnion {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
PingPayloadUnion::Ping(ref item) => {
write!(f, "{}::{}({})", Self::NAME, Ping::NAME, item)
}
PingPayloadUnion::Pong(ref item) => {
write!(f, "{}::{}({})", Self::NAME, Pong::NAME, item)
}
}
}
}
impl<'r> ::core::fmt::Display for PingPayloadUnionReader<'r> {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
PingPayloadUnionReader::Ping(ref item) => {
write!(f, "{}::{}({})", Self::NAME, Ping::NAME, item)
}
PingPayloadUnionReader::Pong(ref item) => {
write!(f, "{}::{}({})", Self::NAME, Pong::NAME, item)
}
}
}
}
impl PingPayloadUnion {
pub(crate) fn display_inner(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
PingPayloadUnion::Ping(ref item) => write!(f, "{}", item),
PingPayloadUnion::Pong(ref item) => write!(f, "{}", item),
}
}
}
impl<'r> PingPayloadUnionReader<'r> {
pub(crate) fn display_inner(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
PingPayloadUnionReader::Ping(ref item) => write!(f, "{}", item),
PingPayloadUnionReader::Pong(ref item) => write!(f, "{}", item),
}
}
}
impl ::core::convert::From<Ping> for PingPayloadUnion {
fn from(item: Ping) -> Self {
PingPayloadUnion::Ping(item)
}
}
impl ::core::convert::From<Pong> for PingPayloadUnion {
fn from(item: Pong) -> Self {
PingPayloadUnion::Pong(item)
}
}
impl<'r> ::core::convert::From<PingReader<'r>> for PingPayloadUnionReader<'r> {
fn from(item: PingReader<'r>) -> Self {
PingPayloadUnionReader::Ping(item)
}
}
impl<'r> ::core::convert::From<PongReader<'r>> for PingPayloadUnionReader<'r> {
fn from(item: PongReader<'r>) -> Self {
PingPayloadUnionReader::Pong(item)
}
}
impl PingPayloadUnion {
pub const NAME: &'static str = "PingPayloadUnion";
pub fn as_bytes(&self) -> molecule::bytes::Bytes {
match self {
PingPayloadUnion::Ping(item) => item.as_bytes(),
PingPayloadUnion::Pong(item) => item.as_bytes(),
}
}
pub fn as_slice(&self) -> &[u8] {
match self {
PingPayloadUnion::Ping(item) => item.as_slice(),
PingPayloadUnion::Pong(item) => item.as_slice(),
}
}
pub fn item_id(&self) -> molecule::Number {
match self {
PingPayloadUnion::Ping(_) => 0,
PingPayloadUnion::Pong(_) => 1,
}
}
pub fn item_name(&self) -> &str {
match self {
PingPayloadUnion::Ping(_) => "Ping",
PingPayloadUnion::Pong(_) => "Pong",
}
}
pub fn as_reader<'r>(&'r self) -> PingPayloadUnionReader<'r> {
match self {
PingPayloadUnion::Ping(item) => item.as_reader().into(),
PingPayloadUnion::Pong(item) => item.as_reader().into(),
}
}
}
impl<'r> PingPayloadUnionReader<'r> {
pub const NAME: &'r str = "PingPayloadUnionReader";
pub fn as_slice(&self) -> &'r [u8] {
match self {
PingPayloadUnionReader::Ping(item) => item.as_slice(),
PingPayloadUnionReader::Pong(item) => item.as_slice(),
}
}
pub fn item_id(&self) -> molecule::Number {
match self {
PingPayloadUnionReader::Ping(_) => 0,
PingPayloadUnionReader::Pong(_) => 1,
}
}
pub fn item_name(&self) -> &str {
match self {
PingPayloadUnionReader::Ping(_) => "Ping",
PingPayloadUnionReader::Pong(_) => "Pong",
}
}
}
#[derive(Clone)]
pub struct PingMessage(molecule::bytes::Bytes);
impl ::core::fmt::LowerHex for PingMessage {
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 PingMessage {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{}({:#x})", Self::NAME, self)
}
}
impl ::core::fmt::Display for PingMessage {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{} {{ ", Self::NAME)?;
write!(f, "{}: {}", "payload", self.payload())?;
let extra_count = self.count_extra_fields();
if extra_count != 0 {
write!(f, ", .. ({} fields)", extra_count)?;
}
write!(f, " }}")
}
}
impl ::core::default::Default for PingMessage {
fn default() -> Self {
let v = molecule::bytes::Bytes::from_static(&Self::DEFAULT_VALUE);
PingMessage::new_unchecked(v)
}
}
impl PingMessage {
const DEFAULT_VALUE: [u8; 24] = [
24, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 12, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0,
];
pub const FIELD_COUNT: usize = 1;
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 payload(&self) -> PingPayload {
let slice = self.as_slice();
let start = molecule::unpack_number(&slice[4..]) as usize;
if self.has_extra_fields() {
let end = molecule::unpack_number(&slice[8..]) as usize;
PingPayload::new_unchecked(self.0.slice(start..end))
} else {
PingPayload::new_unchecked(self.0.slice(start..))
}
}
pub fn as_reader<'r>(&'r self) -> PingMessageReader<'r> {
PingMessageReader::new_unchecked(self.as_slice())
}
}
impl molecule::prelude::Entity for PingMessage {
type Builder = PingMessageBuilder;
const NAME: &'static str = "PingMessage";
fn new_unchecked(data: molecule::bytes::Bytes) -> Self {
PingMessage(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> {
PingMessageReader::from_slice(slice).map(|reader| reader.to_entity())
}
fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> {
PingMessageReader::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().payload(self.payload())
}
}
#[derive(Clone, Copy)]
pub struct PingMessageReader<'r>(&'r [u8]);
impl<'r> ::core::fmt::LowerHex for PingMessageReader<'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 PingMessageReader<'r> {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{}({:#x})", Self::NAME, self)
}
}
impl<'r> ::core::fmt::Display for PingMessageReader<'r> {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{} {{ ", Self::NAME)?;
write!(f, "{}: {}", "payload", self.payload())?;
let extra_count = self.count_extra_fields();
if extra_count != 0 {
write!(f, ", .. ({} fields)", extra_count)?;
}
write!(f, " }}")
}
}
impl<'r> PingMessageReader<'r> {
pub const FIELD_COUNT: usize = 1;
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 payload(&self) -> PingPayloadReader<'r> {
let slice = self.as_slice();
let start = molecule::unpack_number(&slice[4..]) as usize;
if self.has_extra_fields() {
let end = molecule::unpack_number(&slice[8..]) as usize;
PingPayloadReader::new_unchecked(&self.as_slice()[start..end])
} else {
PingPayloadReader::new_unchecked(&self.as_slice()[start..])
}
}
}
impl<'r> molecule::prelude::Reader<'r> for PingMessageReader<'r> {
type Entity = PingMessage;
const NAME: &'static str = "PingMessageReader";
fn to_entity(&self) -> Self::Entity {
Self::Entity::new_unchecked(self.as_slice().to_owned().into())
}
fn new_unchecked(slice: &'r [u8]) -> Self {
PingMessageReader(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 * 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);
}
PingPayloadReader::verify(&slice[offsets[0]..offsets[1]], compatible)?;
Ok(())
}
}
#[derive(Debug, Default)]
pub struct PingMessageBuilder {
pub(crate) payload: PingPayload,
}
impl PingMessageBuilder {
pub const FIELD_COUNT: usize = 1;
pub fn payload(mut self, v: PingPayload) -> Self {
self.payload = v;
self
}
}
impl molecule::prelude::Builder for PingMessageBuilder {
type Entity = PingMessage;
const NAME: &'static str = "PingMessageBuilder";
fn expected_length(&self) -> usize {
molecule::NUMBER_SIZE * (Self::FIELD_COUNT + 1) + self.payload.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.payload.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.payload.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));
PingMessage::new_unchecked(inner.into())
}
}
#[derive(Clone)]
pub struct Ping(molecule::bytes::Bytes);
impl ::core::fmt::LowerHex for Ping {
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 Ping {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{}({:#x})", Self::NAME, self)
}
}
impl ::core::fmt::Display for Ping {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{} {{ ", Self::NAME)?;
write!(f, "{}: {}", "nonce", self.nonce())?;
let extra_count = self.count_extra_fields();
if extra_count != 0 {
write!(f, ", .. ({} fields)", extra_count)?;
}
write!(f, " }}")
}
}
impl ::core::default::Default for Ping {
fn default() -> Self {
let v = molecule::bytes::Bytes::from_static(&Self::DEFAULT_VALUE);
Ping::new_unchecked(v)
}
}
impl Ping {
const DEFAULT_VALUE: [u8; 12] = [12, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0];
pub const FIELD_COUNT: usize = 1;
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 nonce(&self) -> Uint32 {
let slice = self.as_slice();
let start = molecule::unpack_number(&slice[4..]) as usize;
if self.has_extra_fields() {
let end = molecule::unpack_number(&slice[8..]) as usize;
Uint32::new_unchecked(self.0.slice(start..end))
} else {
Uint32::new_unchecked(self.0.slice(start..))
}
}
pub fn as_reader<'r>(&'r self) -> PingReader<'r> {
PingReader::new_unchecked(self.as_slice())
}
}
impl molecule::prelude::Entity for Ping {
type Builder = PingBuilder;
const NAME: &'static str = "Ping";
fn new_unchecked(data: molecule::bytes::Bytes) -> Self {
Ping(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> {
PingReader::from_slice(slice).map(|reader| reader.to_entity())
}
fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> {
PingReader::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().nonce(self.nonce())
}
}
#[derive(Clone, Copy)]
pub struct PingReader<'r>(&'r [u8]);
impl<'r> ::core::fmt::LowerHex for PingReader<'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 PingReader<'r> {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{}({:#x})", Self::NAME, self)
}
}
impl<'r> ::core::fmt::Display for PingReader<'r> {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{} {{ ", Self::NAME)?;
write!(f, "{}: {}", "nonce", self.nonce())?;
let extra_count = self.count_extra_fields();
if extra_count != 0 {
write!(f, ", .. ({} fields)", extra_count)?;
}
write!(f, " }}")
}
}
impl<'r> PingReader<'r> {
pub const FIELD_COUNT: usize = 1;
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 nonce(&self) -> Uint32Reader<'r> {
let slice = self.as_slice();
let start = molecule::unpack_number(&slice[4..]) as usize;
if self.has_extra_fields() {
let end = molecule::unpack_number(&slice[8..]) as usize;
Uint32Reader::new_unchecked(&self.as_slice()[start..end])
} else {
Uint32Reader::new_unchecked(&self.as_slice()[start..])
}
}
}
impl<'r> molecule::prelude::Reader<'r> for PingReader<'r> {
type Entity = Ping;
const NAME: &'static str = "PingReader";
fn to_entity(&self) -> Self::Entity {
Self::Entity::new_unchecked(self.as_slice().to_owned().into())
}
fn new_unchecked(slice: &'r [u8]) -> Self {
PingReader(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 * 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);
}
Uint32Reader::verify(&slice[offsets[0]..offsets[1]], compatible)?;
Ok(())
}
}
#[derive(Debug, Default)]
pub struct PingBuilder {
pub(crate) nonce: Uint32,
}
impl PingBuilder {
pub const FIELD_COUNT: usize = 1;
pub fn nonce(mut self, v: Uint32) -> Self {
self.nonce = v;
self
}
}
impl molecule::prelude::Builder for PingBuilder {
type Entity = Ping;
const NAME: &'static str = "PingBuilder";
fn expected_length(&self) -> usize {
molecule::NUMBER_SIZE * (Self::FIELD_COUNT + 1) + self.nonce.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.nonce.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.nonce.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));
Ping::new_unchecked(inner.into())
}
}
#[derive(Clone)]
pub struct Pong(molecule::bytes::Bytes);
impl ::core::fmt::LowerHex for Pong {
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 Pong {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{}({:#x})", Self::NAME, self)
}
}
impl ::core::fmt::Display for Pong {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{} {{ ", Self::NAME)?;
write!(f, "{}: {}", "nonce", self.nonce())?;
let extra_count = self.count_extra_fields();
if extra_count != 0 {
write!(f, ", .. ({} fields)", extra_count)?;
}
write!(f, " }}")
}
}
impl ::core::default::Default for Pong {
fn default() -> Self {
let v = molecule::bytes::Bytes::from_static(&Self::DEFAULT_VALUE);
Pong::new_unchecked(v)
}
}
impl Pong {
const DEFAULT_VALUE: [u8; 12] = [12, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0];
pub const FIELD_COUNT: usize = 1;
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 nonce(&self) -> Uint32 {
let slice = self.as_slice();
let start = molecule::unpack_number(&slice[4..]) as usize;
if self.has_extra_fields() {
let end = molecule::unpack_number(&slice[8..]) as usize;
Uint32::new_unchecked(self.0.slice(start..end))
} else {
Uint32::new_unchecked(self.0.slice(start..))
}
}
pub fn as_reader<'r>(&'r self) -> PongReader<'r> {
PongReader::new_unchecked(self.as_slice())
}
}
impl molecule::prelude::Entity for Pong {
type Builder = PongBuilder;
const NAME: &'static str = "Pong";
fn new_unchecked(data: molecule::bytes::Bytes) -> Self {
Pong(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> {
PongReader::from_slice(slice).map(|reader| reader.to_entity())
}
fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> {
PongReader::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().nonce(self.nonce())
}
}
#[derive(Clone, Copy)]
pub struct PongReader<'r>(&'r [u8]);
impl<'r> ::core::fmt::LowerHex for PongReader<'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 PongReader<'r> {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{}({:#x})", Self::NAME, self)
}
}
impl<'r> ::core::fmt::Display for PongReader<'r> {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{} {{ ", Self::NAME)?;
write!(f, "{}: {}", "nonce", self.nonce())?;
let extra_count = self.count_extra_fields();
if extra_count != 0 {
write!(f, ", .. ({} fields)", extra_count)?;
}
write!(f, " }}")
}
}
impl<'r> PongReader<'r> {
pub const FIELD_COUNT: usize = 1;
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 nonce(&self) -> Uint32Reader<'r> {
let slice = self.as_slice();
let start = molecule::unpack_number(&slice[4..]) as usize;
if self.has_extra_fields() {
let end = molecule::unpack_number(&slice[8..]) as usize;
Uint32Reader::new_unchecked(&self.as_slice()[start..end])
} else {
Uint32Reader::new_unchecked(&self.as_slice()[start..])
}
}
}
impl<'r> molecule::prelude::Reader<'r> for PongReader<'r> {
type Entity = Pong;
const NAME: &'static str = "PongReader";
fn to_entity(&self) -> Self::Entity {
Self::Entity::new_unchecked(self.as_slice().to_owned().into())
}
fn new_unchecked(slice: &'r [u8]) -> Self {
PongReader(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 * 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);
}
Uint32Reader::verify(&slice[offsets[0]..offsets[1]], compatible)?;
Ok(())
}
}
#[derive(Debug, Default)]
pub struct PongBuilder {
pub(crate) nonce: Uint32,
}
impl PongBuilder {
pub const FIELD_COUNT: usize = 1;
pub fn nonce(mut self, v: Uint32) -> Self {
self.nonce = v;
self
}
}
impl molecule::prelude::Builder for PongBuilder {
type Entity = Pong;
const NAME: &'static str = "PongBuilder";
fn expected_length(&self) -> usize {
molecule::NUMBER_SIZE * (Self::FIELD_COUNT + 1) + self.nonce.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.nonce.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.nonce.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));
Pong::new_unchecked(inner.into())
}
}
#[derive(Clone)]
pub struct NodeVec(molecule::bytes::Bytes);
impl ::core::fmt::LowerHex for NodeVec {
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 NodeVec {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{}({:#x})", Self::NAME, self)
}
}
impl ::core::fmt::Display for NodeVec {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{} [", Self::NAME)?;
for i in 0..self.len() {
if i == 0 {
write!(f, "{}", self.get_unchecked(i))?;
} else {
write!(f, ", {}", self.get_unchecked(i))?;
}
}
write!(f, "]")
}
}
impl ::core::default::Default for NodeVec {
fn default() -> Self {
let v = molecule::bytes::Bytes::from_static(&Self::DEFAULT_VALUE);
NodeVec::new_unchecked(v)
}
}
impl NodeVec {
const DEFAULT_VALUE: [u8; 4] = [4, 0, 0, 0];
pub fn total_size(&self) -> usize {
molecule::unpack_number(self.as_slice()) as usize
}
pub fn item_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 len(&self) -> usize {
self.item_count()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn get(&self, idx: usize) -> Option<Node> {
if idx >= self.len() {
None
} else {
Some(self.get_unchecked(idx))
}
}
pub fn get_unchecked(&self, idx: usize) -> Node {
let slice = self.as_slice();
let start_idx = molecule::NUMBER_SIZE * (1 + idx);
let start = molecule::unpack_number(&slice[start_idx..]) as usize;
if idx == self.len() - 1 {
Node::new_unchecked(self.0.slice(start..))
} else {
let end_idx = start_idx + molecule::NUMBER_SIZE;
let end = molecule::unpack_number(&slice[end_idx..]) as usize;
Node::new_unchecked(self.0.slice(start..end))
}
}
pub fn as_reader<'r>(&'r self) -> NodeVecReader<'r> {
NodeVecReader::new_unchecked(self.as_slice())
}
}
impl molecule::prelude::Entity for NodeVec {
type Builder = NodeVecBuilder;
const NAME: &'static str = "NodeVec";
fn new_unchecked(data: molecule::bytes::Bytes) -> Self {
NodeVec(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> {
NodeVecReader::from_slice(slice).map(|reader| reader.to_entity())
}
fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> {
NodeVecReader::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 NodeVecReader<'r>(&'r [u8]);
impl<'r> ::core::fmt::LowerHex for NodeVecReader<'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 NodeVecReader<'r> {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{}({:#x})", Self::NAME, self)
}
}
impl<'r> ::core::fmt::Display for NodeVecReader<'r> {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{} [", Self::NAME)?;
for i in 0..self.len() {
if i == 0 {
write!(f, "{}", self.get_unchecked(i))?;
} else {
write!(f, ", {}", self.get_unchecked(i))?;
}
}
write!(f, "]")
}
}
impl<'r> NodeVecReader<'r> {
pub fn total_size(&self) -> usize {
molecule::unpack_number(self.as_slice()) as usize
}
pub fn item_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 len(&self) -> usize {
self.item_count()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn get(&self, idx: usize) -> Option<NodeReader<'r>> {
if idx >= self.len() {
None
} else {
Some(self.get_unchecked(idx))
}
}
pub fn get_unchecked(&self, idx: usize) -> NodeReader<'r> {
let slice = self.as_slice();
let start_idx = molecule::NUMBER_SIZE * (1 + idx);
let start = molecule::unpack_number(&slice[start_idx..]) as usize;
if idx == self.len() - 1 {
NodeReader::new_unchecked(&self.as_slice()[start..])
} else {
let end_idx = start_idx + molecule::NUMBER_SIZE;
let end = molecule::unpack_number(&slice[end_idx..]) as usize;
NodeReader::new_unchecked(&self.as_slice()[start..end])
}
}
}
impl<'r> molecule::prelude::Reader<'r> for NodeVecReader<'r> {
type Entity = NodeVec;
const NAME: &'static str = "NodeVecReader";
fn to_entity(&self) -> Self::Entity {
Self::Entity::new_unchecked(self.as_slice().to_owned().into())
}
fn new_unchecked(slice: &'r [u8]) -> Self {
NodeVecReader(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 {
return Ok(());
}
if slice_len < molecule::NUMBER_SIZE * 2 {
return ve!(
Self,
TotalSizeNotMatch,
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 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);
}
for pair in offsets.windows(2) {
let start = pair[0];
let end = pair[1];
NodeReader::verify(&slice[start..end], compatible)?;
}
Ok(())
}
}
#[derive(Debug, Default)]
pub struct NodeVecBuilder(pub(crate) Vec<Node>);
impl NodeVecBuilder {
pub fn set(mut self, v: Vec<Node>) -> Self {
self.0 = v;
self
}
pub fn push(mut self, v: Node) -> Self {
self.0.push(v);
self
}
pub fn extend<T: ::core::iter::IntoIterator<Item = Node>>(mut self, iter: T) -> Self {
for elem in iter {
self.0.push(elem);
}
self
}
pub fn replace(&mut self, index: usize, v: Node) -> Option<Node> {
self.0
.get_mut(index)
.map(|item| ::core::mem::replace(item, v))
}
}
impl molecule::prelude::Builder for NodeVecBuilder {
type Entity = NodeVec;
const NAME: &'static str = "NodeVecBuilder";
fn expected_length(&self) -> usize {
molecule::NUMBER_SIZE * (self.0.len() + 1)
+ self
.0
.iter()
.map(|inner| inner.as_slice().len())
.sum::<usize>()
}
fn write<W: molecule::io::Write>(&self, writer: &mut W) -> molecule::io::Result<()> {
let item_count = self.0.len();
if item_count == 0 {
writer.write_all(&molecule::pack_number(
molecule::NUMBER_SIZE as molecule::Number,
))?;
} else {
let (total_size, offsets) = self.0.iter().fold(
(
molecule::NUMBER_SIZE * (item_count + 1),
Vec::with_capacity(item_count),
),
|(start, mut offsets), inner| {
offsets.push(start);
(start + inner.as_slice().len(), offsets)
},
);
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))?;
}
for inner in self.0.iter() {
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));
NodeVec::new_unchecked(inner.into())
}
}
pub struct NodeVecIterator(NodeVec, usize, usize);
impl ::core::iter::Iterator for NodeVecIterator {
type Item = Node;
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 NodeVecIterator {
fn len(&self) -> usize {
self.2 - self.1
}
}
impl ::core::iter::IntoIterator for NodeVec {
type Item = Node;
type IntoIter = NodeVecIterator;
fn into_iter(self) -> Self::IntoIter {
let len = self.len();
NodeVecIterator(self, 0, len)
}
}
impl<'r> NodeVecReader<'r> {
pub fn iter<'t>(&'t self) -> NodeVecReaderIterator<'t, 'r> {
NodeVecReaderIterator(&self, 0, self.len())
}
}
pub struct NodeVecReaderIterator<'t, 'r>(&'t NodeVecReader<'r>, usize, usize);
impl<'t: 'r, 'r> ::core::iter::Iterator for NodeVecReaderIterator<'t, 'r> {
type Item = NodeReader<'t>;
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<'t: 'r, 'r> ::core::iter::ExactSizeIterator for NodeVecReaderIterator<'t, 'r> {
fn len(&self) -> usize {
self.2 - self.1
}
}
#[derive(Clone)]
pub struct Node2Vec(molecule::bytes::Bytes);
impl ::core::fmt::LowerHex for Node2Vec {
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 Node2Vec {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{}({:#x})", Self::NAME, self)
}
}
impl ::core::fmt::Display for Node2Vec {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{} [", Self::NAME)?;
for i in 0..self.len() {
if i == 0 {
write!(f, "{}", self.get_unchecked(i))?;
} else {
write!(f, ", {}", self.get_unchecked(i))?;
}
}
write!(f, "]")
}
}
impl ::core::default::Default for Node2Vec {
fn default() -> Self {
let v = molecule::bytes::Bytes::from_static(&Self::DEFAULT_VALUE);
Node2Vec::new_unchecked(v)
}
}
impl Node2Vec {
const DEFAULT_VALUE: [u8; 4] = [4, 0, 0, 0];
pub fn total_size(&self) -> usize {
molecule::unpack_number(self.as_slice()) as usize
}
pub fn item_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 len(&self) -> usize {
self.item_count()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn get(&self, idx: usize) -> Option<Node2> {
if idx >= self.len() {
None
} else {
Some(self.get_unchecked(idx))
}
}
pub fn get_unchecked(&self, idx: usize) -> Node2 {
let slice = self.as_slice();
let start_idx = molecule::NUMBER_SIZE * (1 + idx);
let start = molecule::unpack_number(&slice[start_idx..]) as usize;
if idx == self.len() - 1 {
Node2::new_unchecked(self.0.slice(start..))
} else {
let end_idx = start_idx + molecule::NUMBER_SIZE;
let end = molecule::unpack_number(&slice[end_idx..]) as usize;
Node2::new_unchecked(self.0.slice(start..end))
}
}
pub fn as_reader<'r>(&'r self) -> Node2VecReader<'r> {
Node2VecReader::new_unchecked(self.as_slice())
}
}
impl molecule::prelude::Entity for Node2Vec {
type Builder = Node2VecBuilder;
const NAME: &'static str = "Node2Vec";
fn new_unchecked(data: molecule::bytes::Bytes) -> Self {
Node2Vec(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> {
Node2VecReader::from_slice(slice).map(|reader| reader.to_entity())
}
fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> {
Node2VecReader::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 Node2VecReader<'r>(&'r [u8]);
impl<'r> ::core::fmt::LowerHex for Node2VecReader<'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 Node2VecReader<'r> {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{}({:#x})", Self::NAME, self)
}
}
impl<'r> ::core::fmt::Display for Node2VecReader<'r> {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{} [", Self::NAME)?;
for i in 0..self.len() {
if i == 0 {
write!(f, "{}", self.get_unchecked(i))?;
} else {
write!(f, ", {}", self.get_unchecked(i))?;
}
}
write!(f, "]")
}
}
impl<'r> Node2VecReader<'r> {
pub fn total_size(&self) -> usize {
molecule::unpack_number(self.as_slice()) as usize
}
pub fn item_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 len(&self) -> usize {
self.item_count()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn get(&self, idx: usize) -> Option<Node2Reader<'r>> {
if idx >= self.len() {
None
} else {
Some(self.get_unchecked(idx))
}
}
pub fn get_unchecked(&self, idx: usize) -> Node2Reader<'r> {
let slice = self.as_slice();
let start_idx = molecule::NUMBER_SIZE * (1 + idx);
let start = molecule::unpack_number(&slice[start_idx..]) as usize;
if idx == self.len() - 1 {
Node2Reader::new_unchecked(&self.as_slice()[start..])
} else {
let end_idx = start_idx + molecule::NUMBER_SIZE;
let end = molecule::unpack_number(&slice[end_idx..]) as usize;
Node2Reader::new_unchecked(&self.as_slice()[start..end])
}
}
}
impl<'r> molecule::prelude::Reader<'r> for Node2VecReader<'r> {
type Entity = Node2Vec;
const NAME: &'static str = "Node2VecReader";
fn to_entity(&self) -> Self::Entity {
Self::Entity::new_unchecked(self.as_slice().to_owned().into())
}
fn new_unchecked(slice: &'r [u8]) -> Self {
Node2VecReader(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 {
return Ok(());
}
if slice_len < molecule::NUMBER_SIZE * 2 {
return ve!(
Self,
TotalSizeNotMatch,
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 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);
}
for pair in offsets.windows(2) {
let start = pair[0];
let end = pair[1];
Node2Reader::verify(&slice[start..end], compatible)?;
}
Ok(())
}
}
#[derive(Debug, Default)]
pub struct Node2VecBuilder(pub(crate) Vec<Node2>);
impl Node2VecBuilder {
pub fn set(mut self, v: Vec<Node2>) -> Self {
self.0 = v;
self
}
pub fn push(mut self, v: Node2) -> Self {
self.0.push(v);
self
}
pub fn extend<T: ::core::iter::IntoIterator<Item = Node2>>(mut self, iter: T) -> Self {
for elem in iter {
self.0.push(elem);
}
self
}
pub fn replace(&mut self, index: usize, v: Node2) -> Option<Node2> {
self.0
.get_mut(index)
.map(|item| ::core::mem::replace(item, v))
}
}
impl molecule::prelude::Builder for Node2VecBuilder {
type Entity = Node2Vec;
const NAME: &'static str = "Node2VecBuilder";
fn expected_length(&self) -> usize {
molecule::NUMBER_SIZE * (self.0.len() + 1)
+ self
.0
.iter()
.map(|inner| inner.as_slice().len())
.sum::<usize>()
}
fn write<W: molecule::io::Write>(&self, writer: &mut W) -> molecule::io::Result<()> {
let item_count = self.0.len();
if item_count == 0 {
writer.write_all(&molecule::pack_number(
molecule::NUMBER_SIZE as molecule::Number,
))?;
} else {
let (total_size, offsets) = self.0.iter().fold(
(
molecule::NUMBER_SIZE * (item_count + 1),
Vec::with_capacity(item_count),
),
|(start, mut offsets), inner| {
offsets.push(start);
(start + inner.as_slice().len(), offsets)
},
);
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))?;
}
for inner in self.0.iter() {
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));
Node2Vec::new_unchecked(inner.into())
}
}
pub struct Node2VecIterator(Node2Vec, usize, usize);
impl ::core::iter::Iterator for Node2VecIterator {
type Item = Node2;
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 Node2VecIterator {
fn len(&self) -> usize {
self.2 - self.1
}
}
impl ::core::iter::IntoIterator for Node2Vec {
type Item = Node2;
type IntoIter = Node2VecIterator;
fn into_iter(self) -> Self::IntoIter {
let len = self.len();
Node2VecIterator(self, 0, len)
}
}
impl<'r> Node2VecReader<'r> {
pub fn iter<'t>(&'t self) -> Node2VecReaderIterator<'t, 'r> {
Node2VecReaderIterator(&self, 0, self.len())
}
}
pub struct Node2VecReaderIterator<'t, 'r>(&'t Node2VecReader<'r>, usize, usize);
impl<'t: 'r, 'r> ::core::iter::Iterator for Node2VecReaderIterator<'t, 'r> {
type Item = Node2Reader<'t>;
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<'t: 'r, 'r> ::core::iter::ExactSizeIterator for Node2VecReaderIterator<'t, 'r> {
fn len(&self) -> usize {
self.2 - self.1
}
}
#[derive(Clone)]
pub struct Uint16(molecule::bytes::Bytes);
impl ::core::fmt::LowerHex for Uint16 {
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 Uint16 {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{}({:#x})", Self::NAME, self)
}
}
impl ::core::fmt::Display for Uint16 {
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 Uint16 {
fn default() -> Self {
let v = molecule::bytes::Bytes::from_static(&Self::DEFAULT_VALUE);
Uint16::new_unchecked(v)
}
}
impl Uint16 {
const DEFAULT_VALUE: [u8; 2] = [0, 0];
pub const TOTAL_SIZE: usize = 2;
pub const ITEM_SIZE: usize = 1;
pub const ITEM_COUNT: usize = 2;
pub fn nth0(&self) -> Byte {
Byte::new_unchecked(self.0.slice(0..1))
}
pub fn nth1(&self) -> Byte {
Byte::new_unchecked(self.0.slice(1..2))
}
pub fn raw_data(&self) -> molecule::bytes::Bytes {
self.as_bytes()
}
pub fn as_reader<'r>(&'r self) -> Uint16Reader<'r> {
Uint16Reader::new_unchecked(self.as_slice())
}
}
impl molecule::prelude::Entity for Uint16 {
type Builder = Uint16Builder;
const NAME: &'static str = "Uint16";
fn new_unchecked(data: molecule::bytes::Bytes) -> Self {
Uint16(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> {
Uint16Reader::from_slice(slice).map(|reader| reader.to_entity())
}
fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> {
Uint16Reader::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.nth0(), self.nth1()])
}
}
#[derive(Clone, Copy)]
pub struct Uint16Reader<'r>(&'r [u8]);
impl<'r> ::core::fmt::LowerHex for Uint16Reader<'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 Uint16Reader<'r> {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{}({:#x})", Self::NAME, self)
}
}
impl<'r> ::core::fmt::Display for Uint16Reader<'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> Uint16Reader<'r> {
pub const TOTAL_SIZE: usize = 2;
pub const ITEM_SIZE: usize = 1;
pub const ITEM_COUNT: usize = 2;
pub fn nth0(&self) -> ByteReader<'r> {
ByteReader::new_unchecked(&self.as_slice()[0..1])
}
pub fn nth1(&self) -> ByteReader<'r> {
ByteReader::new_unchecked(&self.as_slice()[1..2])
}
pub fn raw_data(&self) -> &'r [u8] {
self.as_slice()
}
}
impl<'r> molecule::prelude::Reader<'r> for Uint16Reader<'r> {
type Entity = Uint16;
const NAME: &'static str = "Uint16Reader";
fn to_entity(&self) -> Self::Entity {
Self::Entity::new_unchecked(self.as_slice().to_owned().into())
}
fn new_unchecked(slice: &'r [u8]) -> Self {
Uint16Reader(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 != Self::TOTAL_SIZE {
return ve!(Self, TotalSizeNotMatch, Self::TOTAL_SIZE, slice_len);
}
Ok(())
}
}
pub struct Uint16Builder(pub(crate) [Byte; 2]);
impl ::core::fmt::Debug for Uint16Builder {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{}({:?})", Self::NAME, &self.0[..])
}
}
impl ::core::default::Default for Uint16Builder {
fn default() -> Self {
Uint16Builder([Byte::default(), Byte::default()])
}
}
impl Uint16Builder {
pub const TOTAL_SIZE: usize = 2;
pub const ITEM_SIZE: usize = 1;
pub const ITEM_COUNT: usize = 2;
pub fn set(mut self, v: [Byte; 2]) -> Self {
self.0 = v;
self
}
pub fn nth0(mut self, v: Byte) -> Self {
self.0[0] = v;
self
}
pub fn nth1(mut self, v: Byte) -> Self {
self.0[1] = v;
self
}
}
impl molecule::prelude::Builder for Uint16Builder {
type Entity = Uint16;
const NAME: &'static str = "Uint16Builder";
fn expected_length(&self) -> usize {
Self::TOTAL_SIZE
}
fn write<W: molecule::io::Write>(&self, writer: &mut W) -> molecule::io::Result<()> {
writer.write_all(self.0[0].as_slice())?;
writer.write_all(self.0[1].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));
Uint16::new_unchecked(inner.into())
}
}
#[derive(Clone)]
pub struct PortOpt(molecule::bytes::Bytes);
impl ::core::fmt::LowerHex for PortOpt {
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 PortOpt {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{}({:#x})", Self::NAME, self)
}
}
impl ::core::fmt::Display for PortOpt {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
if let Some(v) = self.to_opt() {
write!(f, "{}(Some({}))", Self::NAME, v)
} else {
write!(f, "{}(None)", Self::NAME)
}
}
}
impl ::core::default::Default for PortOpt {
fn default() -> Self {
let v = molecule::bytes::Bytes::from_static(&Self::DEFAULT_VALUE);
PortOpt::new_unchecked(v)
}
}
impl PortOpt {
const DEFAULT_VALUE: [u8; 0] = [];
pub fn is_none(&self) -> bool {
self.0.is_empty()
}
pub fn is_some(&self) -> bool {
!self.0.is_empty()
}
pub fn to_opt(&self) -> Option<Uint16> {
if self.is_none() {
None
} else {
Some(Uint16::new_unchecked(self.0.clone()))
}
}
pub fn as_reader<'r>(&'r self) -> PortOptReader<'r> {
PortOptReader::new_unchecked(self.as_slice())
}
}
impl molecule::prelude::Entity for PortOpt {
type Builder = PortOptBuilder;
const NAME: &'static str = "PortOpt";
fn new_unchecked(data: molecule::bytes::Bytes) -> Self {
PortOpt(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> {
PortOptReader::from_slice(slice).map(|reader| reader.to_entity())
}
fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> {
PortOptReader::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_opt())
}
}
#[derive(Clone, Copy)]
pub struct PortOptReader<'r>(&'r [u8]);
impl<'r> ::core::fmt::LowerHex for PortOptReader<'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 PortOptReader<'r> {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{}({:#x})", Self::NAME, self)
}
}
impl<'r> ::core::fmt::Display for PortOptReader<'r> {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
if let Some(v) = self.to_opt() {
write!(f, "{}(Some({}))", Self::NAME, v)
} else {
write!(f, "{}(None)", Self::NAME)
}
}
}
impl<'r> PortOptReader<'r> {
pub fn is_none(&self) -> bool {
self.0.is_empty()
}
pub fn is_some(&self) -> bool {
!self.0.is_empty()
}
pub fn to_opt(&self) -> Option<Uint16Reader<'r>> {
if self.is_none() {
None
} else {
Some(Uint16Reader::new_unchecked(self.as_slice()))
}
}
}
impl<'r> molecule::prelude::Reader<'r> for PortOptReader<'r> {
type Entity = PortOpt;
const NAME: &'static str = "PortOptReader";
fn to_entity(&self) -> Self::Entity {
Self::Entity::new_unchecked(self.as_slice().to_owned().into())
}
fn new_unchecked(slice: &'r [u8]) -> Self {
PortOptReader(slice)
}
fn as_slice(&self) -> &'r [u8] {
self.0
}
fn verify(slice: &[u8], compatible: bool) -> molecule::error::VerificationResult<()> {
if !slice.is_empty() {
Uint16Reader::verify(&slice[..], compatible)?;
}
Ok(())
}
}
#[derive(Debug, Default)]
pub struct PortOptBuilder(pub(crate) Option<Uint16>);
impl PortOptBuilder {
pub fn set(mut self, v: Option<Uint16>) -> Self {
self.0 = v;
self
}
}
impl molecule::prelude::Builder for PortOptBuilder {
type Entity = PortOpt;
const NAME: &'static str = "PortOptBuilder";
fn expected_length(&self) -> usize {
self.0
.as_ref()
.map(|ref inner| inner.as_slice().len())
.unwrap_or(0)
}
fn write<W: molecule::io::Write>(&self, writer: &mut W) -> molecule::io::Result<()> {
self.0
.as_ref()
.map(|ref inner| writer.write_all(inner.as_slice()))
.unwrap_or(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));
PortOpt::new_unchecked(inner.into())
}
}
#[derive(Clone)]
pub struct DiscoveryPayload(molecule::bytes::Bytes);
impl ::core::fmt::LowerHex for DiscoveryPayload {
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 DiscoveryPayload {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{}({:#x})", Self::NAME, self)
}
}
impl ::core::fmt::Display for DiscoveryPayload {
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 DiscoveryPayload {
fn default() -> Self {
let v = molecule::bytes::Bytes::from_static(&Self::DEFAULT_VALUE);
DiscoveryPayload::new_unchecked(v)
}
}
impl DiscoveryPayload {
const DEFAULT_VALUE: [u8; 28] = [
0, 0, 0, 0, 24, 0, 0, 0, 16, 0, 0, 0, 20, 0, 0, 0, 24, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
];
pub const ITEMS_COUNT: usize = 2;
pub fn item_id(&self) -> molecule::Number {
molecule::unpack_number(self.as_slice())
}
pub fn to_enum(&self) -> DiscoveryPayloadUnion {
let inner = self.0.slice(molecule::NUMBER_SIZE..);
match self.item_id() {
0 => GetNodes::new_unchecked(inner).into(),
1 => Nodes::new_unchecked(inner).into(),
_ => panic!("{}: invalid data", Self::NAME),
}
}
pub fn as_reader<'r>(&'r self) -> DiscoveryPayloadReader<'r> {
DiscoveryPayloadReader::new_unchecked(self.as_slice())
}
}
impl molecule::prelude::Entity for DiscoveryPayload {
type Builder = DiscoveryPayloadBuilder;
const NAME: &'static str = "DiscoveryPayload";
fn new_unchecked(data: molecule::bytes::Bytes) -> Self {
DiscoveryPayload(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> {
DiscoveryPayloadReader::from_slice(slice).map(|reader| reader.to_entity())
}
fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> {
DiscoveryPayloadReader::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 DiscoveryPayloadReader<'r>(&'r [u8]);
impl<'r> ::core::fmt::LowerHex for DiscoveryPayloadReader<'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 DiscoveryPayloadReader<'r> {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{}({:#x})", Self::NAME, self)
}
}
impl<'r> ::core::fmt::Display for DiscoveryPayloadReader<'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> DiscoveryPayloadReader<'r> {
pub const ITEMS_COUNT: usize = 2;
pub fn item_id(&self) -> molecule::Number {
molecule::unpack_number(self.as_slice())
}
pub fn to_enum(&self) -> DiscoveryPayloadUnionReader<'r> {
let inner = &self.as_slice()[molecule::NUMBER_SIZE..];
match self.item_id() {
0 => GetNodesReader::new_unchecked(inner).into(),
1 => NodesReader::new_unchecked(inner).into(),
_ => panic!("{}: invalid data", Self::NAME),
}
}
}
impl<'r> molecule::prelude::Reader<'r> for DiscoveryPayloadReader<'r> {
type Entity = DiscoveryPayload;
const NAME: &'static str = "DiscoveryPayloadReader";
fn to_entity(&self) -> Self::Entity {
Self::Entity::new_unchecked(self.as_slice().to_owned().into())
}
fn new_unchecked(slice: &'r [u8]) -> Self {
DiscoveryPayloadReader(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 => GetNodesReader::verify(inner_slice, compatible),
1 => NodesReader::verify(inner_slice, compatible),
_ => ve!(Self, UnknownItem, Self::ITEMS_COUNT, item_id),
}?;
Ok(())
}
}
#[derive(Debug, Default)]
pub struct DiscoveryPayloadBuilder(pub(crate) DiscoveryPayloadUnion);
impl DiscoveryPayloadBuilder {
pub const ITEMS_COUNT: usize = 2;
pub fn set<I>(mut self, v: I) -> Self
where
I: ::core::convert::Into<DiscoveryPayloadUnion>,
{
self.0 = v.into();
self
}
}
impl molecule::prelude::Builder for DiscoveryPayloadBuilder {
type Entity = DiscoveryPayload;
const NAME: &'static str = "DiscoveryPayloadBuilder";
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));
DiscoveryPayload::new_unchecked(inner.into())
}
}
#[derive(Debug, Clone)]
pub enum DiscoveryPayloadUnion {
GetNodes(GetNodes),
Nodes(Nodes),
}
#[derive(Debug, Clone, Copy)]
pub enum DiscoveryPayloadUnionReader<'r> {
GetNodes(GetNodesReader<'r>),
Nodes(NodesReader<'r>),
}
impl ::core::default::Default for DiscoveryPayloadUnion {
fn default() -> Self {
DiscoveryPayloadUnion::GetNodes(::core::default::Default::default())
}
}
impl ::core::fmt::Display for DiscoveryPayloadUnion {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
DiscoveryPayloadUnion::GetNodes(ref item) => {
write!(f, "{}::{}({})", Self::NAME, GetNodes::NAME, item)
}
DiscoveryPayloadUnion::Nodes(ref item) => {
write!(f, "{}::{}({})", Self::NAME, Nodes::NAME, item)
}
}
}
}
impl<'r> ::core::fmt::Display for DiscoveryPayloadUnionReader<'r> {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
DiscoveryPayloadUnionReader::GetNodes(ref item) => {
write!(f, "{}::{}({})", Self::NAME, GetNodes::NAME, item)
}
DiscoveryPayloadUnionReader::Nodes(ref item) => {
write!(f, "{}::{}({})", Self::NAME, Nodes::NAME, item)
}
}
}
}
impl DiscoveryPayloadUnion {
pub(crate) fn display_inner(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
DiscoveryPayloadUnion::GetNodes(ref item) => write!(f, "{}", item),
DiscoveryPayloadUnion::Nodes(ref item) => write!(f, "{}", item),
}
}
}
impl<'r> DiscoveryPayloadUnionReader<'r> {
pub(crate) fn display_inner(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
DiscoveryPayloadUnionReader::GetNodes(ref item) => write!(f, "{}", item),
DiscoveryPayloadUnionReader::Nodes(ref item) => write!(f, "{}", item),
}
}
}
impl ::core::convert::From<GetNodes> for DiscoveryPayloadUnion {
fn from(item: GetNodes) -> Self {
DiscoveryPayloadUnion::GetNodes(item)
}
}
impl ::core::convert::From<Nodes> for DiscoveryPayloadUnion {
fn from(item: Nodes) -> Self {
DiscoveryPayloadUnion::Nodes(item)
}
}
impl<'r> ::core::convert::From<GetNodesReader<'r>> for DiscoveryPayloadUnionReader<'r> {
fn from(item: GetNodesReader<'r>) -> Self {
DiscoveryPayloadUnionReader::GetNodes(item)
}
}
impl<'r> ::core::convert::From<NodesReader<'r>> for DiscoveryPayloadUnionReader<'r> {
fn from(item: NodesReader<'r>) -> Self {
DiscoveryPayloadUnionReader::Nodes(item)
}
}
impl DiscoveryPayloadUnion {
pub const NAME: &'static str = "DiscoveryPayloadUnion";
pub fn as_bytes(&self) -> molecule::bytes::Bytes {
match self {
DiscoveryPayloadUnion::GetNodes(item) => item.as_bytes(),
DiscoveryPayloadUnion::Nodes(item) => item.as_bytes(),
}
}
pub fn as_slice(&self) -> &[u8] {
match self {
DiscoveryPayloadUnion::GetNodes(item) => item.as_slice(),
DiscoveryPayloadUnion::Nodes(item) => item.as_slice(),
}
}
pub fn item_id(&self) -> molecule::Number {
match self {
DiscoveryPayloadUnion::GetNodes(_) => 0,
DiscoveryPayloadUnion::Nodes(_) => 1,
}
}
pub fn item_name(&self) -> &str {
match self {
DiscoveryPayloadUnion::GetNodes(_) => "GetNodes",
DiscoveryPayloadUnion::Nodes(_) => "Nodes",
}
}
pub fn as_reader<'r>(&'r self) -> DiscoveryPayloadUnionReader<'r> {
match self {
DiscoveryPayloadUnion::GetNodes(item) => item.as_reader().into(),
DiscoveryPayloadUnion::Nodes(item) => item.as_reader().into(),
}
}
}
impl<'r> DiscoveryPayloadUnionReader<'r> {
pub const NAME: &'r str = "DiscoveryPayloadUnionReader";
pub fn as_slice(&self) -> &'r [u8] {
match self {
DiscoveryPayloadUnionReader::GetNodes(item) => item.as_slice(),
DiscoveryPayloadUnionReader::Nodes(item) => item.as_slice(),
}
}
pub fn item_id(&self) -> molecule::Number {
match self {
DiscoveryPayloadUnionReader::GetNodes(_) => 0,
DiscoveryPayloadUnionReader::Nodes(_) => 1,
}
}
pub fn item_name(&self) -> &str {
match self {
DiscoveryPayloadUnionReader::GetNodes(_) => "GetNodes",
DiscoveryPayloadUnionReader::Nodes(_) => "Nodes",
}
}
}
#[derive(Clone)]
pub struct DiscoveryMessage(molecule::bytes::Bytes);
impl ::core::fmt::LowerHex for DiscoveryMessage {
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 DiscoveryMessage {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{}({:#x})", Self::NAME, self)
}
}
impl ::core::fmt::Display for DiscoveryMessage {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{} {{ ", Self::NAME)?;
write!(f, "{}: {}", "payload", self.payload())?;
let extra_count = self.count_extra_fields();
if extra_count != 0 {
write!(f, ", .. ({} fields)", extra_count)?;
}
write!(f, " }}")
}
}
impl ::core::default::Default for DiscoveryMessage {
fn default() -> Self {
let v = molecule::bytes::Bytes::from_static(&Self::DEFAULT_VALUE);
DiscoveryMessage::new_unchecked(v)
}
}
impl DiscoveryMessage {
const DEFAULT_VALUE: [u8; 36] = [
36, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 24, 0, 0, 0, 16, 0, 0, 0, 20, 0, 0, 0, 24, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0,
];
pub const FIELD_COUNT: usize = 1;
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 payload(&self) -> DiscoveryPayload {
let slice = self.as_slice();
let start = molecule::unpack_number(&slice[4..]) as usize;
if self.has_extra_fields() {
let end = molecule::unpack_number(&slice[8..]) as usize;
DiscoveryPayload::new_unchecked(self.0.slice(start..end))
} else {
DiscoveryPayload::new_unchecked(self.0.slice(start..))
}
}
pub fn as_reader<'r>(&'r self) -> DiscoveryMessageReader<'r> {
DiscoveryMessageReader::new_unchecked(self.as_slice())
}
}
impl molecule::prelude::Entity for DiscoveryMessage {
type Builder = DiscoveryMessageBuilder;
const NAME: &'static str = "DiscoveryMessage";
fn new_unchecked(data: molecule::bytes::Bytes) -> Self {
DiscoveryMessage(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> {
DiscoveryMessageReader::from_slice(slice).map(|reader| reader.to_entity())
}
fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> {
DiscoveryMessageReader::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().payload(self.payload())
}
}
#[derive(Clone, Copy)]
pub struct DiscoveryMessageReader<'r>(&'r [u8]);
impl<'r> ::core::fmt::LowerHex for DiscoveryMessageReader<'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 DiscoveryMessageReader<'r> {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{}({:#x})", Self::NAME, self)
}
}
impl<'r> ::core::fmt::Display for DiscoveryMessageReader<'r> {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{} {{ ", Self::NAME)?;
write!(f, "{}: {}", "payload", self.payload())?;
let extra_count = self.count_extra_fields();
if extra_count != 0 {
write!(f, ", .. ({} fields)", extra_count)?;
}
write!(f, " }}")
}
}
impl<'r> DiscoveryMessageReader<'r> {
pub const FIELD_COUNT: usize = 1;
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 payload(&self) -> DiscoveryPayloadReader<'r> {
let slice = self.as_slice();
let start = molecule::unpack_number(&slice[4..]) as usize;
if self.has_extra_fields() {
let end = molecule::unpack_number(&slice[8..]) as usize;
DiscoveryPayloadReader::new_unchecked(&self.as_slice()[start..end])
} else {
DiscoveryPayloadReader::new_unchecked(&self.as_slice()[start..])
}
}
}
impl<'r> molecule::prelude::Reader<'r> for DiscoveryMessageReader<'r> {
type Entity = DiscoveryMessage;
const NAME: &'static str = "DiscoveryMessageReader";
fn to_entity(&self) -> Self::Entity {
Self::Entity::new_unchecked(self.as_slice().to_owned().into())
}
fn new_unchecked(slice: &'r [u8]) -> Self {
DiscoveryMessageReader(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 * 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);
}
DiscoveryPayloadReader::verify(&slice[offsets[0]..offsets[1]], compatible)?;
Ok(())
}
}
#[derive(Debug, Default)]
pub struct DiscoveryMessageBuilder {
pub(crate) payload: DiscoveryPayload,
}
impl DiscoveryMessageBuilder {
pub const FIELD_COUNT: usize = 1;
pub fn payload(mut self, v: DiscoveryPayload) -> Self {
self.payload = v;
self
}
}
impl molecule::prelude::Builder for DiscoveryMessageBuilder {
type Entity = DiscoveryMessage;
const NAME: &'static str = "DiscoveryMessageBuilder";
fn expected_length(&self) -> usize {
molecule::NUMBER_SIZE * (Self::FIELD_COUNT + 1) + self.payload.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.payload.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.payload.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));
DiscoveryMessage::new_unchecked(inner.into())
}
}
#[derive(Clone)]
pub struct GetNodes(molecule::bytes::Bytes);
impl ::core::fmt::LowerHex for GetNodes {
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 GetNodes {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{}({:#x})", Self::NAME, self)
}
}
impl ::core::fmt::Display for GetNodes {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{} {{ ", Self::NAME)?;
write!(f, "{}: {}", "version", self.version())?;
write!(f, ", {}: {}", "count", self.count())?;
write!(f, ", {}: {}", "listen_port", self.listen_port())?;
let extra_count = self.count_extra_fields();
if extra_count != 0 {
write!(f, ", .. ({} fields)", extra_count)?;
}
write!(f, " }}")
}
}
impl ::core::default::Default for GetNodes {
fn default() -> Self {
let v = molecule::bytes::Bytes::from_static(&Self::DEFAULT_VALUE);
GetNodes::new_unchecked(v)
}
}
impl GetNodes {
const DEFAULT_VALUE: [u8; 24] = [
24, 0, 0, 0, 16, 0, 0, 0, 20, 0, 0, 0, 24, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
];
pub const FIELD_COUNT: usize = 3;
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 version(&self) -> Uint32 {
let slice = self.as_slice();
let start = molecule::unpack_number(&slice[4..]) as usize;
let end = molecule::unpack_number(&slice[8..]) as usize;
Uint32::new_unchecked(self.0.slice(start..end))
}
pub fn count(&self) -> Uint32 {
let slice = self.as_slice();
let start = molecule::unpack_number(&slice[8..]) as usize;
let end = molecule::unpack_number(&slice[12..]) as usize;
Uint32::new_unchecked(self.0.slice(start..end))
}
pub fn listen_port(&self) -> PortOpt {
let slice = self.as_slice();
let start = molecule::unpack_number(&slice[12..]) as usize;
if self.has_extra_fields() {
let end = molecule::unpack_number(&slice[16..]) as usize;
PortOpt::new_unchecked(self.0.slice(start..end))
} else {
PortOpt::new_unchecked(self.0.slice(start..))
}
}
pub fn as_reader<'r>(&'r self) -> GetNodesReader<'r> {
GetNodesReader::new_unchecked(self.as_slice())
}
}
impl molecule::prelude::Entity for GetNodes {
type Builder = GetNodesBuilder;
const NAME: &'static str = "GetNodes";
fn new_unchecked(data: molecule::bytes::Bytes) -> Self {
GetNodes(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> {
GetNodesReader::from_slice(slice).map(|reader| reader.to_entity())
}
fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> {
GetNodesReader::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()
.version(self.version())
.count(self.count())
.listen_port(self.listen_port())
}
}
#[derive(Clone, Copy)]
pub struct GetNodesReader<'r>(&'r [u8]);
impl<'r> ::core::fmt::LowerHex for GetNodesReader<'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 GetNodesReader<'r> {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{}({:#x})", Self::NAME, self)
}
}
impl<'r> ::core::fmt::Display for GetNodesReader<'r> {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{} {{ ", Self::NAME)?;
write!(f, "{}: {}", "version", self.version())?;
write!(f, ", {}: {}", "count", self.count())?;
write!(f, ", {}: {}", "listen_port", self.listen_port())?;
let extra_count = self.count_extra_fields();
if extra_count != 0 {
write!(f, ", .. ({} fields)", extra_count)?;
}
write!(f, " }}")
}
}
impl<'r> GetNodesReader<'r> {
pub const FIELD_COUNT: usize = 3;
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 version(&self) -> Uint32Reader<'r> {
let slice = self.as_slice();
let start = molecule::unpack_number(&slice[4..]) as usize;
let end = molecule::unpack_number(&slice[8..]) as usize;
Uint32Reader::new_unchecked(&self.as_slice()[start..end])
}
pub fn count(&self) -> Uint32Reader<'r> {
let slice = self.as_slice();
let start = molecule::unpack_number(&slice[8..]) as usize;
let end = molecule::unpack_number(&slice[12..]) as usize;
Uint32Reader::new_unchecked(&self.as_slice()[start..end])
}
pub fn listen_port(&self) -> PortOptReader<'r> {
let slice = self.as_slice();
let start = molecule::unpack_number(&slice[12..]) as usize;
if self.has_extra_fields() {
let end = molecule::unpack_number(&slice[16..]) as usize;
PortOptReader::new_unchecked(&self.as_slice()[start..end])
} else {
PortOptReader::new_unchecked(&self.as_slice()[start..])
}
}
}
impl<'r> molecule::prelude::Reader<'r> for GetNodesReader<'r> {
type Entity = GetNodes;
const NAME: &'static str = "GetNodesReader";
fn to_entity(&self) -> Self::Entity {
Self::Entity::new_unchecked(self.as_slice().to_owned().into())
}
fn new_unchecked(slice: &'r [u8]) -> Self {
GetNodesReader(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 * 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);
}
Uint32Reader::verify(&slice[offsets[0]..offsets[1]], compatible)?;
Uint32Reader::verify(&slice[offsets[1]..offsets[2]], compatible)?;
PortOptReader::verify(&slice[offsets[2]..offsets[3]], compatible)?;
Ok(())
}
}
#[derive(Debug, Default)]
pub struct GetNodesBuilder {
pub(crate) version: Uint32,
pub(crate) count: Uint32,
pub(crate) listen_port: PortOpt,
}
impl GetNodesBuilder {
pub const FIELD_COUNT: usize = 3;
pub fn version(mut self, v: Uint32) -> Self {
self.version = v;
self
}
pub fn count(mut self, v: Uint32) -> Self {
self.count = v;
self
}
pub fn listen_port(mut self, v: PortOpt) -> Self {
self.listen_port = v;
self
}
}
impl molecule::prelude::Builder for GetNodesBuilder {
type Entity = GetNodes;
const NAME: &'static str = "GetNodesBuilder";
fn expected_length(&self) -> usize {
molecule::NUMBER_SIZE * (Self::FIELD_COUNT + 1)
+ self.version.as_slice().len()
+ self.count.as_slice().len()
+ self.listen_port.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.version.as_slice().len();
offsets.push(total_size);
total_size += self.count.as_slice().len();
offsets.push(total_size);
total_size += self.listen_port.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.version.as_slice())?;
writer.write_all(self.count.as_slice())?;
writer.write_all(self.listen_port.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));
GetNodes::new_unchecked(inner.into())
}
}
#[derive(Clone)]
pub struct GetNodes2(molecule::bytes::Bytes);
impl ::core::fmt::LowerHex for GetNodes2 {
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 GetNodes2 {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{}({:#x})", Self::NAME, self)
}
}
impl ::core::fmt::Display for GetNodes2 {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{} {{ ", Self::NAME)?;
write!(f, "{}: {}", "version", self.version())?;
write!(f, ", {}: {}", "count", self.count())?;
write!(f, ", {}: {}", "listen_port", self.listen_port())?;
write!(f, ", {}: {}", "required_flags", self.required_flags())?;
let extra_count = self.count_extra_fields();
if extra_count != 0 {
write!(f, ", .. ({} fields)", extra_count)?;
}
write!(f, " }}")
}
}
impl ::core::default::Default for GetNodes2 {
fn default() -> Self {
let v = molecule::bytes::Bytes::from_static(&Self::DEFAULT_VALUE);
GetNodes2::new_unchecked(v)
}
}
impl GetNodes2 {
const DEFAULT_VALUE: [u8; 36] = [
36, 0, 0, 0, 20, 0, 0, 0, 24, 0, 0, 0, 28, 0, 0, 0, 28, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0,
];
pub const FIELD_COUNT: usize = 4;
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 version(&self) -> Uint32 {
let slice = self.as_slice();
let start = molecule::unpack_number(&slice[4..]) as usize;
let end = molecule::unpack_number(&slice[8..]) as usize;
Uint32::new_unchecked(self.0.slice(start..end))
}
pub fn count(&self) -> Uint32 {
let slice = self.as_slice();
let start = molecule::unpack_number(&slice[8..]) as usize;
let end = molecule::unpack_number(&slice[12..]) as usize;
Uint32::new_unchecked(self.0.slice(start..end))
}
pub fn listen_port(&self) -> PortOpt {
let slice = self.as_slice();
let start = molecule::unpack_number(&slice[12..]) as usize;
let end = molecule::unpack_number(&slice[16..]) as usize;
PortOpt::new_unchecked(self.0.slice(start..end))
}
pub fn required_flags(&self) -> Uint64 {
let slice = self.as_slice();
let start = molecule::unpack_number(&slice[16..]) as usize;
if self.has_extra_fields() {
let end = molecule::unpack_number(&slice[20..]) as usize;
Uint64::new_unchecked(self.0.slice(start..end))
} else {
Uint64::new_unchecked(self.0.slice(start..))
}
}
pub fn as_reader<'r>(&'r self) -> GetNodes2Reader<'r> {
GetNodes2Reader::new_unchecked(self.as_slice())
}
}
impl molecule::prelude::Entity for GetNodes2 {
type Builder = GetNodes2Builder;
const NAME: &'static str = "GetNodes2";
fn new_unchecked(data: molecule::bytes::Bytes) -> Self {
GetNodes2(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> {
GetNodes2Reader::from_slice(slice).map(|reader| reader.to_entity())
}
fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> {
GetNodes2Reader::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()
.version(self.version())
.count(self.count())
.listen_port(self.listen_port())
.required_flags(self.required_flags())
}
}
#[derive(Clone, Copy)]
pub struct GetNodes2Reader<'r>(&'r [u8]);
impl<'r> ::core::fmt::LowerHex for GetNodes2Reader<'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 GetNodes2Reader<'r> {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{}({:#x})", Self::NAME, self)
}
}
impl<'r> ::core::fmt::Display for GetNodes2Reader<'r> {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{} {{ ", Self::NAME)?;
write!(f, "{}: {}", "version", self.version())?;
write!(f, ", {}: {}", "count", self.count())?;
write!(f, ", {}: {}", "listen_port", self.listen_port())?;
write!(f, ", {}: {}", "required_flags", self.required_flags())?;
let extra_count = self.count_extra_fields();
if extra_count != 0 {
write!(f, ", .. ({} fields)", extra_count)?;
}
write!(f, " }}")
}
}
impl<'r> GetNodes2Reader<'r> {
pub const FIELD_COUNT: usize = 4;
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 version(&self) -> Uint32Reader<'r> {
let slice = self.as_slice();
let start = molecule::unpack_number(&slice[4..]) as usize;
let end = molecule::unpack_number(&slice[8..]) as usize;
Uint32Reader::new_unchecked(&self.as_slice()[start..end])
}
pub fn count(&self) -> Uint32Reader<'r> {
let slice = self.as_slice();
let start = molecule::unpack_number(&slice[8..]) as usize;
let end = molecule::unpack_number(&slice[12..]) as usize;
Uint32Reader::new_unchecked(&self.as_slice()[start..end])
}
pub fn listen_port(&self) -> PortOptReader<'r> {
let slice = self.as_slice();
let start = molecule::unpack_number(&slice[12..]) as usize;
let end = molecule::unpack_number(&slice[16..]) as usize;
PortOptReader::new_unchecked(&self.as_slice()[start..end])
}
pub fn required_flags(&self) -> Uint64Reader<'r> {
let slice = self.as_slice();
let start = molecule::unpack_number(&slice[16..]) as usize;
if self.has_extra_fields() {
let end = molecule::unpack_number(&slice[20..]) as usize;
Uint64Reader::new_unchecked(&self.as_slice()[start..end])
} else {
Uint64Reader::new_unchecked(&self.as_slice()[start..])
}
}
}
impl<'r> molecule::prelude::Reader<'r> for GetNodes2Reader<'r> {
type Entity = GetNodes2;
const NAME: &'static str = "GetNodes2Reader";
fn to_entity(&self) -> Self::Entity {
Self::Entity::new_unchecked(self.as_slice().to_owned().into())
}
fn new_unchecked(slice: &'r [u8]) -> Self {
GetNodes2Reader(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 * 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);
}
Uint32Reader::verify(&slice[offsets[0]..offsets[1]], compatible)?;
Uint32Reader::verify(&slice[offsets[1]..offsets[2]], compatible)?;
PortOptReader::verify(&slice[offsets[2]..offsets[3]], compatible)?;
Uint64Reader::verify(&slice[offsets[3]..offsets[4]], compatible)?;
Ok(())
}
}
#[derive(Debug, Default)]
pub struct GetNodes2Builder {
pub(crate) version: Uint32,
pub(crate) count: Uint32,
pub(crate) listen_port: PortOpt,
pub(crate) required_flags: Uint64,
}
impl GetNodes2Builder {
pub const FIELD_COUNT: usize = 4;
pub fn version(mut self, v: Uint32) -> Self {
self.version = v;
self
}
pub fn count(mut self, v: Uint32) -> Self {
self.count = v;
self
}
pub fn listen_port(mut self, v: PortOpt) -> Self {
self.listen_port = v;
self
}
pub fn required_flags(mut self, v: Uint64) -> Self {
self.required_flags = v;
self
}
}
impl molecule::prelude::Builder for GetNodes2Builder {
type Entity = GetNodes2;
const NAME: &'static str = "GetNodes2Builder";
fn expected_length(&self) -> usize {
molecule::NUMBER_SIZE * (Self::FIELD_COUNT + 1)
+ self.version.as_slice().len()
+ self.count.as_slice().len()
+ self.listen_port.as_slice().len()
+ self.required_flags.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.version.as_slice().len();
offsets.push(total_size);
total_size += self.count.as_slice().len();
offsets.push(total_size);
total_size += self.listen_port.as_slice().len();
offsets.push(total_size);
total_size += self.required_flags.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.version.as_slice())?;
writer.write_all(self.count.as_slice())?;
writer.write_all(self.listen_port.as_slice())?;
writer.write_all(self.required_flags.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));
GetNodes2::new_unchecked(inner.into())
}
}
#[derive(Clone)]
pub struct Nodes(molecule::bytes::Bytes);
impl ::core::fmt::LowerHex for Nodes {
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 Nodes {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{}({:#x})", Self::NAME, self)
}
}
impl ::core::fmt::Display for Nodes {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{} {{ ", Self::NAME)?;
write!(f, "{}: {}", "announce", self.announce())?;
write!(f, ", {}: {}", "items", self.items())?;
let extra_count = self.count_extra_fields();
if extra_count != 0 {
write!(f, ", .. ({} fields)", extra_count)?;
}
write!(f, " }}")
}
}
impl ::core::default::Default for Nodes {
fn default() -> Self {
let v = molecule::bytes::Bytes::from_static(&Self::DEFAULT_VALUE);
Nodes::new_unchecked(v)
}
}
impl Nodes {
const DEFAULT_VALUE: [u8; 17] = [17, 0, 0, 0, 12, 0, 0, 0, 13, 0, 0, 0, 0, 4, 0, 0, 0];
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 announce(&self) -> Bool {
let slice = self.as_slice();
let start = molecule::unpack_number(&slice[4..]) as usize;
let end = molecule::unpack_number(&slice[8..]) as usize;
Bool::new_unchecked(self.0.slice(start..end))
}
pub fn items(&self) -> NodeVec {
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;
NodeVec::new_unchecked(self.0.slice(start..end))
} else {
NodeVec::new_unchecked(self.0.slice(start..))
}
}
pub fn as_reader<'r>(&'r self) -> NodesReader<'r> {
NodesReader::new_unchecked(self.as_slice())
}
}
impl molecule::prelude::Entity for Nodes {
type Builder = NodesBuilder;
const NAME: &'static str = "Nodes";
fn new_unchecked(data: molecule::bytes::Bytes) -> Self {
Nodes(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> {
NodesReader::from_slice(slice).map(|reader| reader.to_entity())
}
fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> {
NodesReader::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()
.announce(self.announce())
.items(self.items())
}
}
#[derive(Clone, Copy)]
pub struct NodesReader<'r>(&'r [u8]);
impl<'r> ::core::fmt::LowerHex for NodesReader<'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 NodesReader<'r> {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{}({:#x})", Self::NAME, self)
}
}
impl<'r> ::core::fmt::Display for NodesReader<'r> {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{} {{ ", Self::NAME)?;
write!(f, "{}: {}", "announce", self.announce())?;
write!(f, ", {}: {}", "items", self.items())?;
let extra_count = self.count_extra_fields();
if extra_count != 0 {
write!(f, ", .. ({} fields)", extra_count)?;
}
write!(f, " }}")
}
}
impl<'r> NodesReader<'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 announce(&self) -> BoolReader<'r> {
let slice = self.as_slice();
let start = molecule::unpack_number(&slice[4..]) as usize;
let end = molecule::unpack_number(&slice[8..]) as usize;
BoolReader::new_unchecked(&self.as_slice()[start..end])
}
pub fn items(&self) -> NodeVecReader<'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;
NodeVecReader::new_unchecked(&self.as_slice()[start..end])
} else {
NodeVecReader::new_unchecked(&self.as_slice()[start..])
}
}
}
impl<'r> molecule::prelude::Reader<'r> for NodesReader<'r> {
type Entity = Nodes;
const NAME: &'static str = "NodesReader";
fn to_entity(&self) -> Self::Entity {
Self::Entity::new_unchecked(self.as_slice().to_owned().into())
}
fn new_unchecked(slice: &'r [u8]) -> Self {
NodesReader(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 * 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);
}
BoolReader::verify(&slice[offsets[0]..offsets[1]], compatible)?;
NodeVecReader::verify(&slice[offsets[1]..offsets[2]], compatible)?;
Ok(())
}
}
#[derive(Debug, Default)]
pub struct NodesBuilder {
pub(crate) announce: Bool,
pub(crate) items: NodeVec,
}
impl NodesBuilder {
pub const FIELD_COUNT: usize = 2;
pub fn announce(mut self, v: Bool) -> Self {
self.announce = v;
self
}
pub fn items(mut self, v: NodeVec) -> Self {
self.items = v;
self
}
}
impl molecule::prelude::Builder for NodesBuilder {
type Entity = Nodes;
const NAME: &'static str = "NodesBuilder";
fn expected_length(&self) -> usize {
molecule::NUMBER_SIZE * (Self::FIELD_COUNT + 1)
+ self.announce.as_slice().len()
+ self.items.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.announce.as_slice().len();
offsets.push(total_size);
total_size += self.items.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.announce.as_slice())?;
writer.write_all(self.items.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));
Nodes::new_unchecked(inner.into())
}
}
#[derive(Clone)]
pub struct Nodes2(molecule::bytes::Bytes);
impl ::core::fmt::LowerHex for Nodes2 {
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 Nodes2 {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{}({:#x})", Self::NAME, self)
}
}
impl ::core::fmt::Display for Nodes2 {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{} {{ ", Self::NAME)?;
write!(f, "{}: {}", "announce", self.announce())?;
write!(f, ", {}: {}", "items", self.items())?;
let extra_count = self.count_extra_fields();
if extra_count != 0 {
write!(f, ", .. ({} fields)", extra_count)?;
}
write!(f, " }}")
}
}
impl ::core::default::Default for Nodes2 {
fn default() -> Self {
let v = molecule::bytes::Bytes::from_static(&Self::DEFAULT_VALUE);
Nodes2::new_unchecked(v)
}
}
impl Nodes2 {
const DEFAULT_VALUE: [u8; 17] = [17, 0, 0, 0, 12, 0, 0, 0, 13, 0, 0, 0, 0, 4, 0, 0, 0];
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 announce(&self) -> Bool {
let slice = self.as_slice();
let start = molecule::unpack_number(&slice[4..]) as usize;
let end = molecule::unpack_number(&slice[8..]) as usize;
Bool::new_unchecked(self.0.slice(start..end))
}
pub fn items(&self) -> Node2Vec {
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;
Node2Vec::new_unchecked(self.0.slice(start..end))
} else {
Node2Vec::new_unchecked(self.0.slice(start..))
}
}
pub fn as_reader<'r>(&'r self) -> Nodes2Reader<'r> {
Nodes2Reader::new_unchecked(self.as_slice())
}
}
impl molecule::prelude::Entity for Nodes2 {
type Builder = Nodes2Builder;
const NAME: &'static str = "Nodes2";
fn new_unchecked(data: molecule::bytes::Bytes) -> Self {
Nodes2(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> {
Nodes2Reader::from_slice(slice).map(|reader| reader.to_entity())
}
fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> {
Nodes2Reader::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()
.announce(self.announce())
.items(self.items())
}
}
#[derive(Clone, Copy)]
pub struct Nodes2Reader<'r>(&'r [u8]);
impl<'r> ::core::fmt::LowerHex for Nodes2Reader<'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 Nodes2Reader<'r> {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{}({:#x})", Self::NAME, self)
}
}
impl<'r> ::core::fmt::Display for Nodes2Reader<'r> {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{} {{ ", Self::NAME)?;
write!(f, "{}: {}", "announce", self.announce())?;
write!(f, ", {}: {}", "items", self.items())?;
let extra_count = self.count_extra_fields();
if extra_count != 0 {
write!(f, ", .. ({} fields)", extra_count)?;
}
write!(f, " }}")
}
}
impl<'r> Nodes2Reader<'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 announce(&self) -> BoolReader<'r> {
let slice = self.as_slice();
let start = molecule::unpack_number(&slice[4..]) as usize;
let end = molecule::unpack_number(&slice[8..]) as usize;
BoolReader::new_unchecked(&self.as_slice()[start..end])
}
pub fn items(&self) -> Node2VecReader<'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;
Node2VecReader::new_unchecked(&self.as_slice()[start..end])
} else {
Node2VecReader::new_unchecked(&self.as_slice()[start..])
}
}
}
impl<'r> molecule::prelude::Reader<'r> for Nodes2Reader<'r> {
type Entity = Nodes2;
const NAME: &'static str = "Nodes2Reader";
fn to_entity(&self) -> Self::Entity {
Self::Entity::new_unchecked(self.as_slice().to_owned().into())
}
fn new_unchecked(slice: &'r [u8]) -> Self {
Nodes2Reader(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 * 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);
}
BoolReader::verify(&slice[offsets[0]..offsets[1]], compatible)?;
Node2VecReader::verify(&slice[offsets[1]..offsets[2]], compatible)?;
Ok(())
}
}
#[derive(Debug, Default)]
pub struct Nodes2Builder {
pub(crate) announce: Bool,
pub(crate) items: Node2Vec,
}
impl Nodes2Builder {
pub const FIELD_COUNT: usize = 2;
pub fn announce(mut self, v: Bool) -> Self {
self.announce = v;
self
}
pub fn items(mut self, v: Node2Vec) -> Self {
self.items = v;
self
}
}
impl molecule::prelude::Builder for Nodes2Builder {
type Entity = Nodes2;
const NAME: &'static str = "Nodes2Builder";
fn expected_length(&self) -> usize {
molecule::NUMBER_SIZE * (Self::FIELD_COUNT + 1)
+ self.announce.as_slice().len()
+ self.items.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.announce.as_slice().len();
offsets.push(total_size);
total_size += self.items.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.announce.as_slice())?;
writer.write_all(self.items.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));
Nodes2::new_unchecked(inner.into())
}
}
#[derive(Clone)]
pub struct Node(molecule::bytes::Bytes);
impl ::core::fmt::LowerHex for Node {
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 Node {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{}({:#x})", Self::NAME, self)
}
}
impl ::core::fmt::Display for Node {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{} {{ ", Self::NAME)?;
write!(f, "{}: {}", "addresses", self.addresses())?;
let extra_count = self.count_extra_fields();
if extra_count != 0 {
write!(f, ", .. ({} fields)", extra_count)?;
}
write!(f, " }}")
}
}
impl ::core::default::Default for Node {
fn default() -> Self {
let v = molecule::bytes::Bytes::from_static(&Self::DEFAULT_VALUE);
Node::new_unchecked(v)
}
}
impl Node {
const DEFAULT_VALUE: [u8; 12] = [12, 0, 0, 0, 8, 0, 0, 0, 4, 0, 0, 0];
pub const FIELD_COUNT: usize = 1;
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 addresses(&self) -> BytesVec {
let slice = self.as_slice();
let start = molecule::unpack_number(&slice[4..]) as usize;
if self.has_extra_fields() {
let end = molecule::unpack_number(&slice[8..]) as usize;
BytesVec::new_unchecked(self.0.slice(start..end))
} else {
BytesVec::new_unchecked(self.0.slice(start..))
}
}
pub fn as_reader<'r>(&'r self) -> NodeReader<'r> {
NodeReader::new_unchecked(self.as_slice())
}
}
impl molecule::prelude::Entity for Node {
type Builder = NodeBuilder;
const NAME: &'static str = "Node";
fn new_unchecked(data: molecule::bytes::Bytes) -> Self {
Node(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> {
NodeReader::from_slice(slice).map(|reader| reader.to_entity())
}
fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> {
NodeReader::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().addresses(self.addresses())
}
}
#[derive(Clone, Copy)]
pub struct NodeReader<'r>(&'r [u8]);
impl<'r> ::core::fmt::LowerHex for NodeReader<'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 NodeReader<'r> {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{}({:#x})", Self::NAME, self)
}
}
impl<'r> ::core::fmt::Display for NodeReader<'r> {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{} {{ ", Self::NAME)?;
write!(f, "{}: {}", "addresses", self.addresses())?;
let extra_count = self.count_extra_fields();
if extra_count != 0 {
write!(f, ", .. ({} fields)", extra_count)?;
}
write!(f, " }}")
}
}
impl<'r> NodeReader<'r> {
pub const FIELD_COUNT: usize = 1;
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 addresses(&self) -> BytesVecReader<'r> {
let slice = self.as_slice();
let start = molecule::unpack_number(&slice[4..]) as usize;
if self.has_extra_fields() {
let end = molecule::unpack_number(&slice[8..]) as usize;
BytesVecReader::new_unchecked(&self.as_slice()[start..end])
} else {
BytesVecReader::new_unchecked(&self.as_slice()[start..])
}
}
}
impl<'r> molecule::prelude::Reader<'r> for NodeReader<'r> {
type Entity = Node;
const NAME: &'static str = "NodeReader";
fn to_entity(&self) -> Self::Entity {
Self::Entity::new_unchecked(self.as_slice().to_owned().into())
}
fn new_unchecked(slice: &'r [u8]) -> Self {
NodeReader(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 * 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);
}
BytesVecReader::verify(&slice[offsets[0]..offsets[1]], compatible)?;
Ok(())
}
}
#[derive(Debug, Default)]
pub struct NodeBuilder {
pub(crate) addresses: BytesVec,
}
impl NodeBuilder {
pub const FIELD_COUNT: usize = 1;
pub fn addresses(mut self, v: BytesVec) -> Self {
self.addresses = v;
self
}
}
impl molecule::prelude::Builder for NodeBuilder {
type Entity = Node;
const NAME: &'static str = "NodeBuilder";
fn expected_length(&self) -> usize {
molecule::NUMBER_SIZE * (Self::FIELD_COUNT + 1) + self.addresses.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.addresses.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.addresses.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));
Node::new_unchecked(inner.into())
}
}
#[derive(Clone)]
pub struct Node2(molecule::bytes::Bytes);
impl ::core::fmt::LowerHex for Node2 {
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 Node2 {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{}({:#x})", Self::NAME, self)
}
}
impl ::core::fmt::Display for Node2 {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{} {{ ", Self::NAME)?;
write!(f, "{}: {}", "addresses", self.addresses())?;
write!(f, ", {}: {}", "flags", self.flags())?;
let extra_count = self.count_extra_fields();
if extra_count != 0 {
write!(f, ", .. ({} fields)", extra_count)?;
}
write!(f, " }}")
}
}
impl ::core::default::Default for Node2 {
fn default() -> Self {
let v = molecule::bytes::Bytes::from_static(&Self::DEFAULT_VALUE);
Node2::new_unchecked(v)
}
}
impl Node2 {
const DEFAULT_VALUE: [u8; 24] = [
24, 0, 0, 0, 12, 0, 0, 0, 16, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
];
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 addresses(&self) -> BytesVec {
let slice = self.as_slice();
let start = molecule::unpack_number(&slice[4..]) as usize;
let end = molecule::unpack_number(&slice[8..]) as usize;
BytesVec::new_unchecked(self.0.slice(start..end))
}
pub fn flags(&self) -> Uint64 {
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;
Uint64::new_unchecked(self.0.slice(start..end))
} else {
Uint64::new_unchecked(self.0.slice(start..))
}
}
pub fn as_reader<'r>(&'r self) -> Node2Reader<'r> {
Node2Reader::new_unchecked(self.as_slice())
}
}
impl molecule::prelude::Entity for Node2 {
type Builder = Node2Builder;
const NAME: &'static str = "Node2";
fn new_unchecked(data: molecule::bytes::Bytes) -> Self {
Node2(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> {
Node2Reader::from_slice(slice).map(|reader| reader.to_entity())
}
fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> {
Node2Reader::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()
.addresses(self.addresses())
.flags(self.flags())
}
}
#[derive(Clone, Copy)]
pub struct Node2Reader<'r>(&'r [u8]);
impl<'r> ::core::fmt::LowerHex for Node2Reader<'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 Node2Reader<'r> {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{}({:#x})", Self::NAME, self)
}
}
impl<'r> ::core::fmt::Display for Node2Reader<'r> {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{} {{ ", Self::NAME)?;
write!(f, "{}: {}", "addresses", self.addresses())?;
write!(f, ", {}: {}", "flags", self.flags())?;
let extra_count = self.count_extra_fields();
if extra_count != 0 {
write!(f, ", .. ({} fields)", extra_count)?;
}
write!(f, " }}")
}
}
impl<'r> Node2Reader<'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 addresses(&self) -> BytesVecReader<'r> {
let slice = self.as_slice();
let start = molecule::unpack_number(&slice[4..]) as usize;
let end = molecule::unpack_number(&slice[8..]) as usize;
BytesVecReader::new_unchecked(&self.as_slice()[start..end])
}
pub fn flags(&self) -> Uint64Reader<'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;
Uint64Reader::new_unchecked(&self.as_slice()[start..end])
} else {
Uint64Reader::new_unchecked(&self.as_slice()[start..])
}
}
}
impl<'r> molecule::prelude::Reader<'r> for Node2Reader<'r> {
type Entity = Node2;
const NAME: &'static str = "Node2Reader";
fn to_entity(&self) -> Self::Entity {
Self::Entity::new_unchecked(self.as_slice().to_owned().into())
}
fn new_unchecked(slice: &'r [u8]) -> Self {
Node2Reader(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 * 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);
}
BytesVecReader::verify(&slice[offsets[0]..offsets[1]], compatible)?;
Uint64Reader::verify(&slice[offsets[1]..offsets[2]], compatible)?;
Ok(())
}
}
#[derive(Debug, Default)]
pub struct Node2Builder {
pub(crate) addresses: BytesVec,
pub(crate) flags: Uint64,
}
impl Node2Builder {
pub const FIELD_COUNT: usize = 2;
pub fn addresses(mut self, v: BytesVec) -> Self {
self.addresses = v;
self
}
pub fn flags(mut self, v: Uint64) -> Self {
self.flags = v;
self
}
}
impl molecule::prelude::Builder for Node2Builder {
type Entity = Node2;
const NAME: &'static str = "Node2Builder";
fn expected_length(&self) -> usize {
molecule::NUMBER_SIZE * (Self::FIELD_COUNT + 1)
+ self.addresses.as_slice().len()
+ self.flags.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.addresses.as_slice().len();
offsets.push(total_size);
total_size += self.flags.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.addresses.as_slice())?;
writer.write_all(self.flags.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));
Node2::new_unchecked(inner.into())
}
}
#[derive(Clone)]
pub struct AddressVec(molecule::bytes::Bytes);
impl ::core::fmt::LowerHex for AddressVec {
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 AddressVec {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{}({:#x})", Self::NAME, self)
}
}
impl ::core::fmt::Display for AddressVec {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{} [", Self::NAME)?;
for i in 0..self.len() {
if i == 0 {
write!(f, "{}", self.get_unchecked(i))?;
} else {
write!(f, ", {}", self.get_unchecked(i))?;
}
}
write!(f, "]")
}
}
impl ::core::default::Default for AddressVec {
fn default() -> Self {
let v = molecule::bytes::Bytes::from_static(&Self::DEFAULT_VALUE);
AddressVec::new_unchecked(v)
}
}
impl AddressVec {
const DEFAULT_VALUE: [u8; 4] = [4, 0, 0, 0];
pub fn total_size(&self) -> usize {
molecule::unpack_number(self.as_slice()) as usize
}
pub fn item_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 len(&self) -> usize {
self.item_count()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn get(&self, idx: usize) -> Option<Address> {
if idx >= self.len() {
None
} else {
Some(self.get_unchecked(idx))
}
}
pub fn get_unchecked(&self, idx: usize) -> Address {
let slice = self.as_slice();
let start_idx = molecule::NUMBER_SIZE * (1 + idx);
let start = molecule::unpack_number(&slice[start_idx..]) as usize;
if idx == self.len() - 1 {
Address::new_unchecked(self.0.slice(start..))
} else {
let end_idx = start_idx + molecule::NUMBER_SIZE;
let end = molecule::unpack_number(&slice[end_idx..]) as usize;
Address::new_unchecked(self.0.slice(start..end))
}
}
pub fn as_reader<'r>(&'r self) -> AddressVecReader<'r> {
AddressVecReader::new_unchecked(self.as_slice())
}
}
impl molecule::prelude::Entity for AddressVec {
type Builder = AddressVecBuilder;
const NAME: &'static str = "AddressVec";
fn new_unchecked(data: molecule::bytes::Bytes) -> Self {
AddressVec(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> {
AddressVecReader::from_slice(slice).map(|reader| reader.to_entity())
}
fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> {
AddressVecReader::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 AddressVecReader<'r>(&'r [u8]);
impl<'r> ::core::fmt::LowerHex for AddressVecReader<'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 AddressVecReader<'r> {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{}({:#x})", Self::NAME, self)
}
}
impl<'r> ::core::fmt::Display for AddressVecReader<'r> {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{} [", Self::NAME)?;
for i in 0..self.len() {
if i == 0 {
write!(f, "{}", self.get_unchecked(i))?;
} else {
write!(f, ", {}", self.get_unchecked(i))?;
}
}
write!(f, "]")
}
}
impl<'r> AddressVecReader<'r> {
pub fn total_size(&self) -> usize {
molecule::unpack_number(self.as_slice()) as usize
}
pub fn item_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 len(&self) -> usize {
self.item_count()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn get(&self, idx: usize) -> Option<AddressReader<'r>> {
if idx >= self.len() {
None
} else {
Some(self.get_unchecked(idx))
}
}
pub fn get_unchecked(&self, idx: usize) -> AddressReader<'r> {
let slice = self.as_slice();
let start_idx = molecule::NUMBER_SIZE * (1 + idx);
let start = molecule::unpack_number(&slice[start_idx..]) as usize;
if idx == self.len() - 1 {
AddressReader::new_unchecked(&self.as_slice()[start..])
} else {
let end_idx = start_idx + molecule::NUMBER_SIZE;
let end = molecule::unpack_number(&slice[end_idx..]) as usize;
AddressReader::new_unchecked(&self.as_slice()[start..end])
}
}
}
impl<'r> molecule::prelude::Reader<'r> for AddressVecReader<'r> {
type Entity = AddressVec;
const NAME: &'static str = "AddressVecReader";
fn to_entity(&self) -> Self::Entity {
Self::Entity::new_unchecked(self.as_slice().to_owned().into())
}
fn new_unchecked(slice: &'r [u8]) -> Self {
AddressVecReader(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 {
return Ok(());
}
if slice_len < molecule::NUMBER_SIZE * 2 {
return ve!(
Self,
TotalSizeNotMatch,
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 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);
}
for pair in offsets.windows(2) {
let start = pair[0];
let end = pair[1];
AddressReader::verify(&slice[start..end], compatible)?;
}
Ok(())
}
}
#[derive(Debug, Default)]
pub struct AddressVecBuilder(pub(crate) Vec<Address>);
impl AddressVecBuilder {
pub fn set(mut self, v: Vec<Address>) -> Self {
self.0 = v;
self
}
pub fn push(mut self, v: Address) -> Self {
self.0.push(v);
self
}
pub fn extend<T: ::core::iter::IntoIterator<Item = Address>>(mut self, iter: T) -> Self {
for elem in iter {
self.0.push(elem);
}
self
}
pub fn replace(&mut self, index: usize, v: Address) -> Option<Address> {
self.0
.get_mut(index)
.map(|item| ::core::mem::replace(item, v))
}
}
impl molecule::prelude::Builder for AddressVecBuilder {
type Entity = AddressVec;
const NAME: &'static str = "AddressVecBuilder";
fn expected_length(&self) -> usize {
molecule::NUMBER_SIZE * (self.0.len() + 1)
+ self
.0
.iter()
.map(|inner| inner.as_slice().len())
.sum::<usize>()
}
fn write<W: molecule::io::Write>(&self, writer: &mut W) -> molecule::io::Result<()> {
let item_count = self.0.len();
if item_count == 0 {
writer.write_all(&molecule::pack_number(
molecule::NUMBER_SIZE as molecule::Number,
))?;
} else {
let (total_size, offsets) = self.0.iter().fold(
(
molecule::NUMBER_SIZE * (item_count + 1),
Vec::with_capacity(item_count),
),
|(start, mut offsets), inner| {
offsets.push(start);
(start + inner.as_slice().len(), offsets)
},
);
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))?;
}
for inner in self.0.iter() {
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));
AddressVec::new_unchecked(inner.into())
}
}
pub struct AddressVecIterator(AddressVec, usize, usize);
impl ::core::iter::Iterator for AddressVecIterator {
type Item = Address;
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 AddressVecIterator {
fn len(&self) -> usize {
self.2 - self.1
}
}
impl ::core::iter::IntoIterator for AddressVec {
type Item = Address;
type IntoIter = AddressVecIterator;
fn into_iter(self) -> Self::IntoIter {
let len = self.len();
AddressVecIterator(self, 0, len)
}
}
impl<'r> AddressVecReader<'r> {
pub fn iter<'t>(&'t self) -> AddressVecReaderIterator<'t, 'r> {
AddressVecReaderIterator(&self, 0, self.len())
}
}
pub struct AddressVecReaderIterator<'t, 'r>(&'t AddressVecReader<'r>, usize, usize);
impl<'t: 'r, 'r> ::core::iter::Iterator for AddressVecReaderIterator<'t, 'r> {
type Item = AddressReader<'t>;
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<'t: 'r, 'r> ::core::iter::ExactSizeIterator for AddressVecReaderIterator<'t, 'r> {
fn len(&self) -> usize {
self.2 - self.1
}
}
#[derive(Clone)]
pub struct Address(molecule::bytes::Bytes);
impl ::core::fmt::LowerHex for Address {
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 Address {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{}({:#x})", Self::NAME, self)
}
}
impl ::core::fmt::Display for Address {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{} {{ ", Self::NAME)?;
write!(f, "{}: {}", "bytes", self.bytes())?;
let extra_count = self.count_extra_fields();
if extra_count != 0 {
write!(f, ", .. ({} fields)", extra_count)?;
}
write!(f, " }}")
}
}
impl ::core::default::Default for Address {
fn default() -> Self {
let v = molecule::bytes::Bytes::from_static(&Self::DEFAULT_VALUE);
Address::new_unchecked(v)
}
}
impl Address {
const DEFAULT_VALUE: [u8; 12] = [12, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0];
pub const FIELD_COUNT: usize = 1;
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 bytes(&self) -> Bytes {
let slice = self.as_slice();
let start = molecule::unpack_number(&slice[4..]) as usize;
if self.has_extra_fields() {
let end = molecule::unpack_number(&slice[8..]) 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) -> AddressReader<'r> {
AddressReader::new_unchecked(self.as_slice())
}
}
impl molecule::prelude::Entity for Address {
type Builder = AddressBuilder;
const NAME: &'static str = "Address";
fn new_unchecked(data: molecule::bytes::Bytes) -> Self {
Address(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> {
AddressReader::from_slice(slice).map(|reader| reader.to_entity())
}
fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> {
AddressReader::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().bytes(self.bytes())
}
}
#[derive(Clone, Copy)]
pub struct AddressReader<'r>(&'r [u8]);
impl<'r> ::core::fmt::LowerHex for AddressReader<'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 AddressReader<'r> {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{}({:#x})", Self::NAME, self)
}
}
impl<'r> ::core::fmt::Display for AddressReader<'r> {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{} {{ ", Self::NAME)?;
write!(f, "{}: {}", "bytes", self.bytes())?;
let extra_count = self.count_extra_fields();
if extra_count != 0 {
write!(f, ", .. ({} fields)", extra_count)?;
}
write!(f, " }}")
}
}
impl<'r> AddressReader<'r> {
pub const FIELD_COUNT: usize = 1;
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 bytes(&self) -> BytesReader<'r> {
let slice = self.as_slice();
let start = molecule::unpack_number(&slice[4..]) as usize;
if self.has_extra_fields() {
let end = molecule::unpack_number(&slice[8..]) 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 AddressReader<'r> {
type Entity = Address;
const NAME: &'static str = "AddressReader";
fn to_entity(&self) -> Self::Entity {
Self::Entity::new_unchecked(self.as_slice().to_owned().into())
}
fn new_unchecked(slice: &'r [u8]) -> Self {
AddressReader(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 * 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)?;
Ok(())
}
}
#[derive(Debug, Default)]
pub struct AddressBuilder {
pub(crate) bytes: Bytes,
}
impl AddressBuilder {
pub const FIELD_COUNT: usize = 1;
pub fn bytes(mut self, v: Bytes) -> Self {
self.bytes = v;
self
}
}
impl molecule::prelude::Builder for AddressBuilder {
type Entity = Address;
const NAME: &'static str = "AddressBuilder";
fn expected_length(&self) -> usize {
molecule::NUMBER_SIZE * (Self::FIELD_COUNT + 1) + self.bytes.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.bytes.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.bytes.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));
Address::new_unchecked(inner.into())
}
}
#[derive(Clone)]
pub struct IdentifyMessage(molecule::bytes::Bytes);
impl ::core::fmt::LowerHex for IdentifyMessage {
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 IdentifyMessage {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{}({:#x})", Self::NAME, self)
}
}
impl ::core::fmt::Display for IdentifyMessage {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{} {{ ", Self::NAME)?;
write!(f, "{}: {}", "listen_addrs", self.listen_addrs())?;
write!(f, ", {}: {}", "observed_addr", self.observed_addr())?;
write!(f, ", {}: {}", "identify", self.identify())?;
let extra_count = self.count_extra_fields();
if extra_count != 0 {
write!(f, ", .. ({} fields)", extra_count)?;
}
write!(f, " }}")
}
}
impl ::core::default::Default for IdentifyMessage {
fn default() -> Self {
let v = molecule::bytes::Bytes::from_static(&Self::DEFAULT_VALUE);
IdentifyMessage::new_unchecked(v)
}
}
impl IdentifyMessage {
const DEFAULT_VALUE: [u8; 36] = [
36, 0, 0, 0, 16, 0, 0, 0, 20, 0, 0, 0, 32, 0, 0, 0, 4, 0, 0, 0, 12, 0, 0, 0, 8, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0,
];
pub const FIELD_COUNT: usize = 3;
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 listen_addrs(&self) -> AddressVec {
let slice = self.as_slice();
let start = molecule::unpack_number(&slice[4..]) as usize;
let end = molecule::unpack_number(&slice[8..]) as usize;
AddressVec::new_unchecked(self.0.slice(start..end))
}
pub fn observed_addr(&self) -> Address {
let slice = self.as_slice();
let start = molecule::unpack_number(&slice[8..]) as usize;
let end = molecule::unpack_number(&slice[12..]) as usize;
Address::new_unchecked(self.0.slice(start..end))
}
pub fn identify(&self) -> Bytes {
let slice = self.as_slice();
let start = molecule::unpack_number(&slice[12..]) as usize;
if self.has_extra_fields() {
let end = molecule::unpack_number(&slice[16..]) 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) -> IdentifyMessageReader<'r> {
IdentifyMessageReader::new_unchecked(self.as_slice())
}
}
impl molecule::prelude::Entity for IdentifyMessage {
type Builder = IdentifyMessageBuilder;
const NAME: &'static str = "IdentifyMessage";
fn new_unchecked(data: molecule::bytes::Bytes) -> Self {
IdentifyMessage(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> {
IdentifyMessageReader::from_slice(slice).map(|reader| reader.to_entity())
}
fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> {
IdentifyMessageReader::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()
.listen_addrs(self.listen_addrs())
.observed_addr(self.observed_addr())
.identify(self.identify())
}
}
#[derive(Clone, Copy)]
pub struct IdentifyMessageReader<'r>(&'r [u8]);
impl<'r> ::core::fmt::LowerHex for IdentifyMessageReader<'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 IdentifyMessageReader<'r> {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{}({:#x})", Self::NAME, self)
}
}
impl<'r> ::core::fmt::Display for IdentifyMessageReader<'r> {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{} {{ ", Self::NAME)?;
write!(f, "{}: {}", "listen_addrs", self.listen_addrs())?;
write!(f, ", {}: {}", "observed_addr", self.observed_addr())?;
write!(f, ", {}: {}", "identify", self.identify())?;
let extra_count = self.count_extra_fields();
if extra_count != 0 {
write!(f, ", .. ({} fields)", extra_count)?;
}
write!(f, " }}")
}
}
impl<'r> IdentifyMessageReader<'r> {
pub const FIELD_COUNT: usize = 3;
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 listen_addrs(&self) -> AddressVecReader<'r> {
let slice = self.as_slice();
let start = molecule::unpack_number(&slice[4..]) as usize;
let end = molecule::unpack_number(&slice[8..]) as usize;
AddressVecReader::new_unchecked(&self.as_slice()[start..end])
}
pub fn observed_addr(&self) -> AddressReader<'r> {
let slice = self.as_slice();
let start = molecule::unpack_number(&slice[8..]) as usize;
let end = molecule::unpack_number(&slice[12..]) as usize;
AddressReader::new_unchecked(&self.as_slice()[start..end])
}
pub fn identify(&self) -> BytesReader<'r> {
let slice = self.as_slice();
let start = molecule::unpack_number(&slice[12..]) as usize;
if self.has_extra_fields() {
let end = molecule::unpack_number(&slice[16..]) 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 IdentifyMessageReader<'r> {
type Entity = IdentifyMessage;
const NAME: &'static str = "IdentifyMessageReader";
fn to_entity(&self) -> Self::Entity {
Self::Entity::new_unchecked(self.as_slice().to_owned().into())
}
fn new_unchecked(slice: &'r [u8]) -> Self {
IdentifyMessageReader(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 * 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);
}
AddressVecReader::verify(&slice[offsets[0]..offsets[1]], compatible)?;
AddressReader::verify(&slice[offsets[1]..offsets[2]], compatible)?;
BytesReader::verify(&slice[offsets[2]..offsets[3]], compatible)?;
Ok(())
}
}
#[derive(Debug, Default)]
pub struct IdentifyMessageBuilder {
pub(crate) listen_addrs: AddressVec,
pub(crate) observed_addr: Address,
pub(crate) identify: Bytes,
}
impl IdentifyMessageBuilder {
pub const FIELD_COUNT: usize = 3;
pub fn listen_addrs(mut self, v: AddressVec) -> Self {
self.listen_addrs = v;
self
}
pub fn observed_addr(mut self, v: Address) -> Self {
self.observed_addr = v;
self
}
pub fn identify(mut self, v: Bytes) -> Self {
self.identify = v;
self
}
}
impl molecule::prelude::Builder for IdentifyMessageBuilder {
type Entity = IdentifyMessage;
const NAME: &'static str = "IdentifyMessageBuilder";
fn expected_length(&self) -> usize {
molecule::NUMBER_SIZE * (Self::FIELD_COUNT + 1)
+ self.listen_addrs.as_slice().len()
+ self.observed_addr.as_slice().len()
+ self.identify.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.listen_addrs.as_slice().len();
offsets.push(total_size);
total_size += self.observed_addr.as_slice().len();
offsets.push(total_size);
total_size += self.identify.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.listen_addrs.as_slice())?;
writer.write_all(self.observed_addr.as_slice())?;
writer.write_all(self.identify.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));
IdentifyMessage::new_unchecked(inner.into())
}
}