blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
140
path
stringlengths
5
183
src_encoding
stringclasses
6 values
length_bytes
int64
12
5.32M
score
float64
2.52
4.94
int_score
int64
3
5
detected_licenses
listlengths
0
47
license_type
stringclasses
2 values
text
stringlengths
12
5.32M
download_success
bool
1 class
33836ee9c32fde50ee69c84e864f55391e2487c5
Rust
VersBinarii/spike
/src/controllers/session.rs
UTF-8
2,459
2.53125
3
[]
no_license
use actix_web::{ error::{ErrorBadRequest, ErrorInternalServerError, ErrorUnauthorized}, web, Error as ActixErr, HttpResponse, }; use futures::{Future, IntoFuture}; use crate::db; use crate::models::{LoginUser, LogoutUser}; use crate::AppState; pub fn login( user: web::Json<LoginUser>, state: web::Data<AppState>, ) -> impl Future<Item = HttpResponse, Error = ActixErr> { state .db .send(db::user::FetchUser { username: user.username.to_owned(), }) .from_err() .and_then(move |res| match res { Ok(fetched_user) => { if fetched_user.password == user.password { Ok(fetched_user) } else { return Err(ErrorUnauthorized( "Failed to authenticate user.", )); } } Err(_) => { return Err(ErrorInternalServerError( "Failed to authenticate user.", )); } }) .and_then(move |user| { state .db .send(db::token::InsertToken(user.username)) .from_err() .and_then(|token_response| match token_response { Ok(token) => Ok(HttpResponse::Ok().json(token)), Err(_) => Err(ErrorInternalServerError( "Failed to create session token", )), }) }) } pub fn logout( user: web::Json<LogoutUser>, state: web::Data<AppState>, ) -> impl IntoFuture<Item = HttpResponse, Error = ActixErr> { state .db .send(db::user::FetchUser { username: user.username.to_owned(), }) .from_err() .and_then(move |res| match res { Ok(fetched_user) => Ok(fetched_user), Err(e) => { return Err(ErrorBadRequest(e)); } }) .and_then(move |user| { state .db .send(db::token::DeleteToken(user.username)) .from_err() .and_then(|token_response| match token_response { Ok(_token) => Ok(HttpResponse::Ok().finish()), Err(_) => Err(ErrorInternalServerError( "Failed to create session token", )), }) }) }
true
61fec907976b385159dc3c4e3e23c9f3b975af47
Rust
databricks/click
/src/duct_mock.rs
UTF-8
2,979
2.53125
3
[ "Apache-2.0" ]
permissive
// Copyright 2017 Databricks, Inc. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! Test only code to mock out a duct command use chrono::offset::Utc; use std::ffi::OsString; use std::io::Result; #[derive(Clone)] pub struct MockExpression { cmd: String, #[allow(dead_code)] args: Vec<String>, } pub struct MockReader { read_from: String, pos: usize, } impl MockReader { fn new(read_from: String) -> MockReader { MockReader { read_from, pos: 0 } } } impl std::io::Read for MockReader { fn read(&mut self, buf: &mut [u8]) -> Result<usize> { let left = self.read_from.len() - self.pos; if left == 0 { Ok(0) } else if left < buf.len() { // copy remaining buf[0..left].copy_from_slice(&self.read_from.as_bytes()[self.pos..]); self.pos += left; Ok(left) } else { // copy what we can let lim = self.pos + buf.len(); buf.copy_from_slice(&self.read_from.as_bytes()[self.pos..lim]); self.pos += buf.len(); Ok(buf.len()) } } } impl MockExpression { pub fn full_env<T, U, V>(&self, _name_vals: T) -> MockExpression where T: IntoIterator<Item = (U, V)>, U: Into<OsString>, V: Into<OsString>, { self.clone() } pub fn read(&self) -> Result<String> { Ok("".to_string()) } pub fn reader(&self) -> Result<MockReader> { match self.cmd.as_str() { "aws" => Ok(MockReader::new(format!( r#"{{ "kind": "ExecCredential", "apiVersion": "client.authentication.k8s.io/v1alpha1", "spec": {{}}, "status": {{ "expirationTimestamp": "{}", "token": "testtoken" }} }}"#, (Utc::now() + chrono::Duration::hours(1)).format("%Y-%m-%dT%H:%M:%SZ") ))), _ => Ok(MockReader::new("not found".to_string())), } } } pub fn cmd<T, U>(program: T, args: U) -> MockExpression where T: Into<OsString>, U: IntoIterator, U::Item: Into<OsString>, { let os: OsString = program.into(); let args: Vec<String> = args .into_iter() .map(|a| a.into().into_string().unwrap()) .collect(); MockExpression { cmd: os.into_string().unwrap(), args, } }
true
2457a8f46b7867934520b5b5edd4e0e9cd6ce0f5
Rust
Cassy343/trojan
/src/keyboard.rs
UTF-8
8,303
2.546875
3
[]
no_license
/* NOTE: THIS CODE IS NOT ORIGINAL; IT WAS COPIED AND MODIFIED FROM THE PROJECT BELOW Source: https://github.com/obv-mikhail/InputBot */ use std::{ mem::MaybeUninit, ptr::null_mut, sync::{atomic::{AtomicPtr, Ordering}, Mutex}, }; use winapi::{ ctypes::*, shared::{minwindef::*, windef::*}, um::winuser::*, }; use once_cell::sync::Lazy; pub static KEYS: Lazy<Mutex<Vec<KeybdKey>>> = Lazy::new(|| { Mutex::new(Vec::new()) }); #[derive(Debug, Eq, PartialEq, Hash, Copy, Clone)] pub enum KeybdKey { BackspaceKey, TabKey, EnterKey, EscapeKey, SpaceKey, HomeKey, LeftKey, UpKey, RightKey, DownKey, InsertKey, DeleteKey, Numrow0Key, Numrow1Key, Numrow2Key, Numrow3Key, Numrow4Key, Numrow5Key, Numrow6Key, Numrow7Key, Numrow8Key, Numrow9Key, AKey, BKey, CKey, DKey, EKey, FKey, GKey, HKey, IKey, JKey, KKey, LKey, MKey, NKey, OKey, PKey, QKey, RKey, SKey, TKey, UKey, VKey, WKey, XKey, YKey, ZKey, Numpad0Key, Numpad1Key, Numpad2Key, Numpad3Key, Numpad4Key, Numpad5Key, Numpad6Key, Numpad7Key, Numpad8Key, Numpad9Key, F1Key, F2Key, F3Key, F4Key, F5Key, F6Key, F7Key, F8Key, F9Key, F10Key, F11Key, F12Key, F13Key, F14Key, F15Key, F16Key, F17Key, F18Key, F19Key, F20Key, F21Key, F22Key, F23Key, F24Key, NumLockKey, ScrollLockKey, CapsLockKey, LShiftKey, RShiftKey, LControlKey, RControlKey, OtherKey(u64), } use KeybdKey::*; impl From<KeybdKey> for u64 { fn from(key: KeybdKey) -> u64 { match key { BackspaceKey => 0x08, TabKey => 0x09, EnterKey => 0x0D, EscapeKey => 0x1B, SpaceKey => 0x20, HomeKey => 0x24, LeftKey => 0x25, UpKey => 0x26, RightKey => 0x27, DownKey => 0x28, InsertKey => 0x2D, DeleteKey => 0x2E, Numrow0Key => 0x30, Numrow1Key => 0x31, Numrow2Key => 0x32, Numrow3Key => 0x33, Numrow4Key => 0x34, Numrow5Key => 0x35, Numrow6Key => 0x36, Numrow7Key => 0x37, Numrow8Key => 0x38, Numrow9Key => 0x39, AKey => 0x41, BKey => 0x42, CKey => 0x43, DKey => 0x44, EKey => 0x45, FKey => 0x46, GKey => 0x47, HKey => 0x48, IKey => 0x49, JKey => 0x4A, KKey => 0x4B, LKey => 0x4C, MKey => 0x4D, NKey => 0x4E, OKey => 0x4F, PKey => 0x50, QKey => 0x51, RKey => 0x52, SKey => 0x53, TKey => 0x54, UKey => 0x55, VKey => 0x56, WKey => 0x57, XKey => 0x58, YKey => 0x59, ZKey => 0x5A, Numpad0Key => 0x60, Numpad1Key => 0x61, Numpad2Key => 0x62, Numpad3Key => 0x63, Numpad4Key => 0x64, Numpad5Key => 0x65, Numpad6Key => 0x66, Numpad7Key => 0x67, Numpad8Key => 0x68, Numpad9Key => 0x69, F1Key => 0x70, F2Key => 0x71, F3Key => 0x72, F4Key => 0x73, F5Key => 0x74, F6Key => 0x75, F7Key => 0x76, F8Key => 0x77, F9Key => 0x78, F10Key => 0x79, F11Key => 0x7A, F12Key => 0x7B, F13Key => 0x7C, F14Key => 0x7D, F15Key => 0x7E, F16Key => 0x7F, F17Key => 0x80, F18Key => 0x81, F19Key => 0x82, F20Key => 0x83, F21Key => 0x84, F22Key => 0x85, F23Key => 0x86, F24Key => 0x87, NumLockKey => 0x90, ScrollLockKey => 0x91, CapsLockKey => 0x14, LShiftKey => 0xA0, RShiftKey => 0xA1, LControlKey => 0xA2, RControlKey => 0xA3, OtherKey(code) => code, } } } impl From<u64> for KeybdKey { fn from(code: u64) -> KeybdKey { match code { 0x08 => BackspaceKey, 0x09 => TabKey, 0x0D => EnterKey, 0x1B => EscapeKey, 0x20 => SpaceKey, 0x24 => HomeKey, 0x25 => LeftKey, 0x26 => UpKey, 0x27 => RightKey, 0x28 => DownKey, 0x2D => InsertKey, 0x2E => DeleteKey, 0x30 => Numrow0Key, 0x31 => Numrow1Key, 0x32 => Numrow2Key, 0x33 => Numrow3Key, 0x34 => Numrow4Key, 0x35 => Numrow5Key, 0x36 => Numrow6Key, 0x37 => Numrow7Key, 0x38 => Numrow8Key, 0x39 => Numrow9Key, 0x41 => AKey, 0x42 => BKey, 0x43 => CKey, 0x44 => DKey, 0x45 => EKey, 0x46 => FKey, 0x47 => GKey, 0x48 => HKey, 0x49 => IKey, 0x4A => JKey, 0x4B => KKey, 0x4C => LKey, 0x4D => MKey, 0x4E => NKey, 0x4F => OKey, 0x50 => PKey, 0x51 => QKey, 0x52 => RKey, 0x53 => SKey, 0x54 => TKey, 0x55 => UKey, 0x56 => VKey, 0x57 => WKey, 0x58 => XKey, 0x59 => YKey, 0x5A => ZKey, 0x60 => Numpad0Key, 0x61 => Numpad1Key, 0x62 => Numpad2Key, 0x63 => Numpad3Key, 0x64 => Numpad4Key, 0x65 => Numpad5Key, 0x66 => Numpad6Key, 0x67 => Numpad7Key, 0x68 => Numpad8Key, 0x69 => Numpad9Key, 0x70 => F1Key, 0x71 => F2Key, 0x72 => F3Key, 0x73 => F4Key, 0x74 => F5Key, 0x75 => F6Key, 0x76 => F7Key, 0x77 => F8Key, 0x78 => F9Key, 0x79 => F10Key, 0x7A => F11Key, 0x7B => F12Key, 0x7C => F13Key, 0x7D => F14Key, 0x7E => F15Key, 0x7F => F16Key, 0x80 => F17Key, 0x81 => F18Key, 0x82 => F19Key, 0x83 => F20Key, 0x84 => F21Key, 0x85 => F22Key, 0x86 => F23Key, 0x87 => F24Key, 0x90 => NumLockKey, 0x91 => ScrollLockKey, 0x14 => CapsLockKey, 0xA0 => LShiftKey, 0xA1 => RShiftKey, 0xA2 => LControlKey, 0xA3 => RControlKey, _ => OtherKey(code), } } } static KEYBD_HHOOK: Lazy<AtomicPtr<HHOOK__>> = Lazy::new(AtomicPtr::default); impl KeybdKey { pub fn is_pressed(self) -> bool { (unsafe { GetAsyncKeyState(u64::from(self) as i32) } >> 15) != 0 } pub fn is_toggled(self) -> bool { unsafe { GetKeyState(u64::from(self) as i32) & 15 != 0 } } } pub fn handle_input_events() { set_hook(WH_KEYBOARD_LL, &*KEYBD_HHOOK, keybd_proc); let mut msg: MSG = unsafe { MaybeUninit::zeroed().assume_init() }; unsafe { GetMessageW(&mut msg, 0 as HWND, 0, 0) }; } unsafe extern "system" fn keybd_proc(code: c_int, w_param: WPARAM, l_param: LPARAM) -> LRESULT { if w_param as u32 == WM_KEYDOWN { let key = KeybdKey::from(u64::from( (*(l_param as *const KBDLLHOOKSTRUCT)).vkCode, )); KEYS.lock().unwrap().push(key); } CallNextHookEx(null_mut(), code, w_param, l_param) } fn set_hook( hook_id: i32, hook_ptr: &AtomicPtr<HHOOK__>, hook_proc: unsafe extern "system" fn(c_int, WPARAM, LPARAM) -> LRESULT, ) { hook_ptr.store( unsafe { SetWindowsHookExW(hook_id, Some(hook_proc), 0 as HINSTANCE, 0) }, Ordering::Relaxed, ); }
true
1e03a65b5243aafb2afbf02ac2434fec9322684e
Rust
amrosaeed/Fluence-Service
/quickstart/2-hosted-services/src/main.rs
UTF-8
2,112
2.78125
3
[ "Apache-2.0" ]
permissive
/* * Copyright 2021 Fluence Labs Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ use marine_rs_sdk::marine; use marine_rs_sdk::module_manifest; module_manifest!(); pub fn main() {} #[marine] pub struct CharCount { pub msg: String, pub reply: String, } #[marine] pub fn char_count(message: String) -> CharCount { let num_chars = message.chars().count(); let _msg; let _reply; if num_chars < 1 { _msg = format!("Your message was empty"); _reply = format!("Your message has 0 characters"); } else { _msg = format!("Message: {}", message); _reply = format!("Your message {} has {} character(s)", message, num_chars); } CharCount { msg: _msg, reply: _reply } } #[cfg(test)] mod tests { use marine_rs_sdk_test::marine_test; #[marine_test(config_path = "../configs/Config.toml", modules_dir = "../artifacts")] fn non_empty_string(char_count: marine_test_env::char_count::ModuleInterface) { let actual = char_count.char_count("SuperNode ☮".to_string()); assert_eq!(actual.msg, "Message: SuperNode ☮"); assert_eq!(actual.reply, "Your message SuperNode ☮ has 11 character(s)".to_string()); } #[marine_test(config_path = "../configs/Config.toml", modules_dir = "../artifacts")] fn empty_string(char_count: marine_test_env::char_count::ModuleInterface) { let actual = char_count.char_count("".to_string()); assert_eq!(actual.msg, "Your message was empty"); assert_eq!(actual.reply, "Your message has 0 characters"); } }
true
fd0fe1e1c5e399c2566ac2e54eead84899c22e79
Rust
astral-sh/ruff
/crates/ruff_python_parser/src/soft_keywords.rs
UTF-8
7,031
3.265625
3
[ "BSD-3-Clause", "0BSD", "LicenseRef-scancode-free-unknown", "GPL-1.0-or-later", "MIT", "Apache-2.0" ]
permissive
use crate::{lexer::LexResult, token::Tok, Mode}; use itertools::{Itertools, MultiPeek}; /// An [`Iterator`] that transforms a token stream to accommodate soft keywords (namely, `match` /// `case`, and `type`). /// /// [PEP 634](https://www.python.org/dev/peps/pep-0634/) introduced the `match` and `case` keywords /// as soft keywords, meaning that they can be used as identifiers (e.g., variable names) in certain /// contexts. /// /// Later, [PEP 695](https://peps.python.org/pep-0695/#generic-type-alias) introduced the `type` /// soft keyword. /// /// This function modifies a token stream to accommodate this change. In particular, it replaces /// soft keyword tokens with `identifier` tokens if they are used as identifiers. /// /// Handling soft keywords in this intermediary pass allows us to simplify both the lexer and /// `ruff_python_parser`, as neither of them need to be aware of soft keywords. pub struct SoftKeywordTransformer<I> where I: Iterator<Item = LexResult>, { underlying: MultiPeek<I>, start_of_line: bool, } impl<I> SoftKeywordTransformer<I> where I: Iterator<Item = LexResult>, { pub fn new(lexer: I, mode: Mode) -> Self { Self { underlying: lexer.multipeek(), // spell-checker:ignore multipeek start_of_line: matches!(mode, Mode::Module), } } } impl<I> Iterator for SoftKeywordTransformer<I> where I: Iterator<Item = LexResult>, { type Item = LexResult; #[inline] fn next(&mut self) -> Option<LexResult> { let mut next = self.underlying.next(); if let Some(Ok((tok, range))) = next.as_ref() { // If the token is a soft keyword e.g. `type`, `match`, or `case`, check if it's // used as an identifier. We assume every soft keyword use is an identifier unless // a heuristic is met. match tok { // For `match` and `case`, all of the following conditions must be met: // 1. The token is at the start of a logical line. // 2. The logical line contains a top-level colon (that is, a colon that is not nested // inside a parenthesized expression, list, or dictionary). // 3. The top-level colon is not the immediate sibling of a `match` or `case` token. // (This is to avoid treating `match` or `case` as identifiers when annotated with // type hints.) type hints.) Tok::Match | Tok::Case => { if self.start_of_line { let mut nesting = 0; let mut first = true; let mut seen_colon = false; let mut seen_lambda = false; while let Some(Ok((tok, _))) = self.underlying.peek() { match tok { Tok::Newline => break, Tok::Lambda if nesting == 0 => seen_lambda = true, Tok::Colon if nesting == 0 => { if seen_lambda { seen_lambda = false; } else if !first { seen_colon = true; } } Tok::Lpar | Tok::Lsqb | Tok::Lbrace => nesting += 1, Tok::Rpar | Tok::Rsqb | Tok::Rbrace => nesting -= 1, _ => {} } first = false; } if !seen_colon { next = Some(Ok((soft_to_name(tok), *range))); } } else { next = Some(Ok((soft_to_name(tok), *range))); } } // For `type` all of the following conditions must be met: // 1. The token is at the start of a logical line. // 2. The type token is immediately followed by a name token. // 3. The name token is eventually followed by an equality token. Tok::Type => { if self.start_of_line { let mut is_type_alias = false; if let Some(Ok((tok, _))) = self.underlying.peek() { if matches!( tok, Tok::Name { .. } | // We treat a soft keyword token following a type token as a // name to support cases like `type type = int` or `type match = int` Tok::Type | Tok::Match | Tok::Case ) { let mut nesting = 0; while let Some(Ok((tok, _))) = self.underlying.peek() { match tok { Tok::Newline => break, Tok::Equal if nesting == 0 => { is_type_alias = true; break; } Tok::Lsqb => nesting += 1, Tok::Rsqb => nesting -= 1, // Allow arbitrary content within brackets for now _ if nesting > 0 => {} // Exit if unexpected tokens are seen _ => break, } } } } if !is_type_alias { next = Some(Ok((soft_to_name(tok), *range))); } } else { next = Some(Ok((soft_to_name(tok), *range))); } } _ => (), // Not a soft keyword token } } self.start_of_line = next.as_ref().is_some_and(|lex_result| { lex_result.as_ref().is_ok_and(|(tok, _)| { if matches!(tok, Tok::NonLogicalNewline | Tok::Comment { .. }) { return self.start_of_line; } matches!( tok, Tok::StartModule | Tok::Newline | Tok::Indent | Tok::Dedent ) }) }); next } } #[inline] fn soft_to_name(tok: &Tok) -> Tok { let name = match tok { Tok::Match => "match", Tok::Case => "case", Tok::Type => "type", _ => unreachable!("other tokens never reach here"), }; Tok::Name { name: name.to_owned(), } }
true
86bc7a929900074162342b8bcc393010b3c6708a
Rust
Enigmatrix/aoc17
/src/day12.rs
UTF-8
1,360
2.84375
3
[]
no_license
use std::collections::*; use disjoint_sets::UnionFind; pub fn day12_1(s: String) -> usize { let m:Vec<_> = s.split('\n').map(|line| { let dat = line.split(" <-> ").collect::<Vec<&str>>(); ( dat[0].parse::<usize>().unwrap(), dat[1] .split(", ") .map(|f| f.parse::<usize>().unwrap()) .collect::<Vec<_>>(), ) }).collect(); let mut uf = UnionFind::new(m.len()); for &(src, ref dests) in m.iter() { for dst in dests { if !uf.equiv(src, *dst) { uf.union(src, *dst); } } } m.iter().filter(|v| uf.equiv(0, v.0)).count() } pub fn day12_2(s: String) -> usize { let m:Vec<_> = s.split('\n').map(|line| { let dat = line.split(" <-> ").collect::<Vec<&str>>(); ( dat[0].parse::<usize>().unwrap(), dat[1] .split(", ") .map(|f| f.parse::<usize>().unwrap()) .collect::<Vec<_>>(), ) }).collect(); let mut uf = UnionFind::new(m.len()); for &(src, ref dests) in m.iter() { for dst in dests { if !uf.equiv(src, *dst) { uf.union(src, *dst); } } } m.iter().map(|v| uf.find(v.0)).collect::<HashSet<usize>>().len() }
true
33bcdf9109194696348ae5e26be2a65f7c72181d
Rust
dennisss/dacha
/pkg/fan_controller/src/avr/debug.rs
UTF-8
1,931
3.203125
3
[ "Apache-2.0" ]
permissive
macro_rules! debug { ($a:expr) => {{ let tx = $crate::avr::usart::USART1Transmission::start().await; ($a).debug_write(&mut tx); drop(tx); }}; } // #[inline(never)] // pub fn uart_send_number_sync(num: u8) { // num_to_slice(num, |data| uart_send_sync(data)); // } pub fn num_to_slice<F: FnOnce(&[u8])>(mut num: u8, f: F) { // A u32 has a maximum length of 10 base-10 digits let mut buf: [u8; 3] = [0; 3]; let mut num_digits = 0; while num > 0 { // TODO: perform this as one operation? let r = (num % 10) as u8; num /= 10; num_digits += 1; buf[buf.len() - num_digits] = ('0' as u8) + r; } if num_digits == 0 { num_digits = 1; buf[buf.len() - 1] = '0' as u8; } f(&buf[(buf.len() - num_digits)..]); } pub fn num_to_slice16<F: FnOnce(&[u8])>(mut num: u16, f: F) { // A u32 has a maximum length of 10 base-10 digits let mut buf = [0u8; 5]; let mut num_digits = 0; while num > 0 { // TODO: perform this as one operation? let r = (num % 10) as u8; num /= 10; num_digits += 1; buf[buf.len() - num_digits] = ('0' as u8) + r; } if num_digits == 0 { num_digits = 1; buf[buf.len() - 1] = '0' as u8; } f(&buf[(buf.len() - num_digits)..]); } #[cfg(test)] mod tests { use super::*; #[test] fn test_num_to_slice() { fn run_test(num: u8, expected: &'static [u8]) { let mut called = false; num_to_slice(num, |v| { called = true; assert_eq!(v, expected); }); assert!(called); } run_test(0, b"0"); run_test(1, b"1"); run_test(2, b"2"); run_test(3, b"3"); run_test(50, b"50"); run_test(100, b"100"); run_test(202, b"202"); run_test(255, b"255"); } }
true
4d5cf9bc7cad6e42a9f79cc9e34689b7ac618697
Rust
gogobook/xmr
/p2p/src/net/connect.rs
UTF-8
2,099
2.59375
3
[]
no_license
use std::io; use std::sync::Arc; use std::net::SocketAddr; use futures::{Future, Poll}; use tokio_core::reactor::Handle; use tokio_core::net::{TcpStream, TcpStreamNew}; use uuid::Uuid; use p2p::Context; use levin::{LevinError, DefaultEndian, Invoke, invoke}; use protocol::handshake::CryptoNoteHandshake; pub fn connect(address: &SocketAddr, handle: &Handle, context: Arc<Context>) -> Connect { Connect { context, state: ConnectState::TcpConnect { future: TcpStream::connect(address, handle), } } } enum ConnectState { TcpConnect { future: TcpStreamNew, }, Handshake { future: Invoke<CryptoNoteHandshake, TcpStream, DefaultEndian>, } } pub struct Connect { state: ConnectState, context: Arc<Context>, } impl Future for Connect { type Item = Result<TcpStream, ConnectError>; type Error = io::Error; fn poll(&mut self) -> Poll<Self::Item, Self::Error> { loop { let next_state = match self.state { ConnectState::TcpConnect { ref mut future } => { let stream = try_ready!(future.poll()); ConnectState::Handhsake { future: invoke::<Handshake, TcpStream, DefaultEndian>(), } }, ConnectState::Handshake { ref mut future } => { let (stream, response) = try_ready!(future.poll()); let response = response?; if response.node_data.network_id != self.context.config.network_id { let uuid = response.node_data.network_id; return Ok(Err(ConnectError::WrongNetwork(uuid)).into()); } }, }; self.state = next_state; } } } pub enum ConnectError { /// A levin error. LevinError(LevinError), /// Wrong network Id. WrongNetwork(Uuid) } impl From<LevinError> for ConnectError { fn from(e: LevinError) -> ConnectError { ConnectError::LevinError(e) } }
true
882cbc98ab59cf21c43eebed42b0198c81052d3f
Rust
gleam-lang/gleam
/compiler-core/src/erlang/tests/let_assert.rs
UTF-8
857
3.21875
3
[ "Apache-2.0" ]
permissive
use crate::assert_erl; #[test] fn one_var() { // One var assert_erl!( r#"pub fn go() { let assert Ok(y) = Ok(1) y }"# ); } #[test] fn more_than_one_var() { // More vars assert_erl!( r#"pub fn go(x) { let assert [1, a, b, c] = x [a, b, c] }"# ); } #[test] fn pattern_let() { // Pattern::Let assert_erl!( r#"pub fn go(x) { let assert [1 as a, b, c] = x [a, b, c] }"# ); } #[test] fn variable_rewrites() { // Following asserts use appropriate variable rewrites assert_erl!( r#"pub fn go() { let assert Ok(y) = Ok(1) let assert Ok(y) = Ok(1) y }"# ); } // TODO: patterns that are just vars don't render a case expression // #[test] // fn just_pattern() { // assert_erl!( // r#"pub fn go() { // let assert x = Ok(1) // x // }"# // ); // }
true
2ff05bb5528573856fe7927aae5288a39f4fdcbc
Rust
shadowkun/wasm-learning
/faas/ocr/src/lib.rs
UTF-8
1,356
2.75
3
[]
no_license
use std::fs; use std::str; use std::fs::File; use std::io::{Write, Read}; use wasm_bindgen::prelude::*; use rust_process_interface_library::Command; use ssvm_wasi_helper::ssvm_wasi_helper::_initialize; #[wasm_bindgen] pub fn ocr(img_buf: &[u8]) -> String { _initialize(); // Create temp file to store image let path = String::from("temp_input_file"); let mut temp_file = File::create(&path).unwrap(); temp_file.write_all(img_buf).unwrap(); // Create temp filename for output let mut output_path: String = "temp_output_file".to_owned(); let output_extension: &str = ".txt"; // Execute OCR let mut cmd = Command::new("tesseract"); cmd.arg(&path) .arg(&output_path); let out = cmd.output(); if out.status != 0 { println!("Code: {}", out.status); println!("STDERR: {}", str::from_utf8(&out.stderr).unwrap()); println!("STDOUT: {}", str::from_utf8(&out.stdout).unwrap()); output_path.push_str(output_extension); fs::remove_file(output_path).expect("Unable to delete"); return out.status.to_string(); } output_path.push_str(output_extension); let mut f = File::open(&output_path).unwrap(); let mut s = String::new(); match f.read_to_string(&mut s) { Ok(_) => { fs::remove_file(output_path).expect("Unable to delete"); return s; }, Err(e) => e.to_string(), } }
true
086abd5ad408b2ac589ea73f7f8787f843f14f84
Rust
qkniep/qdb
/src/disk_manager.rs
UTF-8
2,426
3.171875
3
[ "MIT" ]
permissive
// Copyright (C) 2021 Quentin Kniep <hello@quentinkniep.com> // Distributed under terms of the MIT license. use std::convert::TryInto; use std::fs::{File, OpenOptions}; use std::io::{self, Read, Seek, SeekFrom, Write}; use crate::page::{PageID, PAGE_SIZE}; /// A trivial Disk Manager implementation that has all pages in a single large file. pub struct DiskManager { next_page_id: PageID, filename: String, db_file: File, } impl DiskManager { /// Initialize a new Disk Manager, creating a new file. // TODO handle file create error pub fn new(db_file_name: &str) -> Self { Self { next_page_id: 0, filename: db_file_name.to_owned(), db_file: OpenOptions::new() .read(true) .write(true) .create(true) .truncate(true) .open(db_file_name) .unwrap(), } } /// Read the given page of the disk file into the memory buffer. pub fn read_page(&mut self, page: PageID, buf: &mut [u8; PAGE_SIZE]) -> io::Result<()> { let offset: u64 = (page * PAGE_SIZE).try_into().unwrap(); self.db_file.seek(SeekFrom::Start(offset))?; self.db_file.read_exact(buf)?; Ok(()) } /// Write the data from the memory buffer to the given page of the disk file. pub fn write_page(&mut self, page: PageID, buf: &[u8; PAGE_SIZE]) -> io::Result<()> { let offset: u64 = (page * PAGE_SIZE).try_into().unwrap(); self.db_file.seek(SeekFrom::Start(offset))?; self.db_file.write(buf)?; self.db_file.flush()?; Ok(()) } /// pub fn allocate_page(&mut self) -> PageID { let id = self.next_page_id; self.next_page_id += 1; return id; } /// pub fn deallocate_page(page: PageID) {} } #[cfg(test)] mod tests { use super::*; #[test] fn write_read_page() { let mut buf1 = [0u8; PAGE_SIZE]; let mut buf2 = [0u8; PAGE_SIZE]; let mut dm = DiskManager::new("xxxxxxx.tmp"); // read past EOF assert!(dm.read_page(0, &mut buf1).is_err()); for i in 0..10 { let s = format!("Page {}", i); buf2[..s.len()].copy_from_slice(s.as_bytes()); assert!(dm.write_page(i, &buf2).is_ok()); assert!(dm.read_page(i, &mut buf1).is_ok()); assert_eq!(buf1, buf2); } } }
true
6130c0b384f3a1972fcb9ac30e88ba77af97e4c0
Rust
IThawk/rust-project
/rust-master/src/test/ui/privacy/restricted/auxiliary/pub_restricted.rs
UTF-8
263
2.515625
3
[ "MIT", "LicenseRef-scancode-other-permissive", "Apache-2.0", "BSD-3-Clause", "BSD-2-Clause", "NCSA" ]
permissive
#![feature(crate_visibility_modifier)] pub(crate) struct Crate; #[derive(Default)] pub struct Universe { pub x: i32, pub(crate) y: i32, crate z: i32, } impl Universe { pub fn f(&self) {} pub(crate) fn g(&self) {} crate fn h(&self) {} }
true
bea16555ef6273079691dce18e97a7fba53dff43
Rust
sankar-boro/loony
/loony-service/src/macros.rs
UTF-8
2,180
3.484375
3
[ "MIT" ]
permissive
/// An implementation of [`poll_ready`]() that always signals readiness. /// /// This should only be used for basic leaf services that have no concept of un-readiness. /// For wrapper or other serivice types, use [`forward_ready!`] for simple cases or write a bespoke /// `poll_ready` implementation. /// /// [`poll_ready`]: crate::Service::poll_ready /// /// # Examples /// ```no_run /// use actix_service::Service; /// use futures_util::future::{ready, Ready}; /// /// struct IdentityService; /// /// impl Service<u32> for IdentityService { /// type Response = u32; /// type Error = (); /// type Future = Ready<Result<Self::Response, Self::Error>>; /// /// actix_service::always_ready!(); /// /// fn call(&self, req: u32) -> Self::Future { /// ready(Ok(req)) /// } /// } /// ``` #[macro_export] macro_rules! always_ready { () => { #[inline] fn poll_ready( &self, _: &mut ::core::task::Context<'_>, ) -> ::core::task::Poll<Result<(), Self::Error>> { ::core::task::Poll::Ready(Ok(())) } }; } /// An implementation of [`poll_ready`] that forwards readiness checks to a /// named struct field. /// /// Tuple structs are not supported. /// /// [`poll_ready`]: crate::Service::poll_ready /// /// # Examples /// ```no_run /// use actix_service::Service; /// use futures_util::future::{ready, Ready}; /// /// struct WrapperService<S> { /// inner: S, /// } /// /// impl<S> Service<()> for WrapperService<S> /// where /// S: Service<()>, /// { /// type Response = S::Response; /// type Error = S::Error; /// type Future = S::Future; /// /// actix_service::forward_ready!(inner); /// /// fn call(&self, req: ()) -> Self::Future { /// self.inner.call(req) /// } /// } /// ``` #[macro_export] macro_rules! forward_ready { ($field:ident) => { #[inline] fn poll_ready( &self, cx: &mut ::core::task::Context<'_>, ) -> ::core::task::Poll<Result<(), Self::Error>> { self.$field .poll_ready(cx) .map_err(::core::convert::Into::into) } }; }
true
4f521786bdb091bb0963fe422d8c7cd5e2df3a49
Rust
vitiral/defrag-rs
/src/raw_pool.rs
UTF-8
28,140
2.84375
3
[ "MIT" ]
permissive
/* Contains all the logic related to the RawPool. The RawPool is what actually contains and maintains the indexes and memory. */ use core::mem; use core::ptr; use core::default::Default; use core::fmt; use cbuf::CBuf; use super::types::*; use super::free::{FreedBins, Free, NUM_BINS}; use super::utils; // ################################################## // # Block // a single block, currently == 2 Free blocks which // is 128 bits #[derive(Debug, Eq, PartialEq)] pub enum BlockType { Free, Full, } /// The Block is the smallest unit of allocation allowed. /// It is currently equal to 16 bytes #[repr(C, packed)] #[derive(Copy, Clone)] pub struct Block { _a: Free, _b: Free, } impl fmt::Debug for Block { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "B<{:?}> {{blocks: {}}}", self.ty(), self._a._blocks & BLOCK_BITMAP) } } impl fmt::Display for Block { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { unsafe { match self.ty() { BlockType::Free => write!(f, "{:?}", self.as_free()), BlockType::Full => write!(f, "{:?}", self.as_full()), } } } } impl Block { pub fn blocks(&self) -> BlockLoc { let out = self._a._blocks & BLOCK_BITMAP; assert_ne!(out, 0); out } pub unsafe fn block(&self, pool: &RawPool) -> BlockLoc { match self.ty() { BlockType::Free => self.as_free().block(), BlockType::Full => pool.index(self.as_full().index()).block(), } } pub unsafe fn next_mut(&mut self, pool: &RawPool) -> Option<&mut Block> { let block = self.block(pool); let blocks = self.blocks(); if block + blocks == pool.heap_block { None } else { assert!(block + blocks < pool.heap_block); let ptr = self as *mut Block; assert_ne!((*ptr).blocks(), 0); Some(&mut *ptr.offset(blocks as isize)) } } pub fn ty(&self) -> BlockType { if self._a._blocks & BLOCK_HIGH_BIT == 0 { BlockType::Free } else { BlockType::Full } } pub unsafe fn as_free(&self) -> &Free { assert_eq!(self.ty(), BlockType::Free); let ptr: *const Free = mem::transmute(self as *const Block); &*ptr } pub unsafe fn as_free_mut(&mut self) -> &mut Free { assert_eq!(self.ty(), BlockType::Free); let ptr: *mut Free = mem::transmute(self as *mut Block); &mut *ptr } pub unsafe fn as_full(&self) -> &Full { assert_eq!(self.ty(), BlockType::Full); let ptr: *const Full = mem::transmute(self as *const Block); &*ptr } pub unsafe fn as_full_mut(&mut self) -> &mut Full { assert_eq!(self.ty(), BlockType::Full); let ptr: *mut Full = mem::transmute(self as *mut Block); &mut *ptr } } impl Default for Block { fn default() -> Block { unsafe { mem::zeroed() } } } // ################################################## // # Index /// Index provides a non-moving location in memory for userspace /// to reference. There is a limited number of indexes. #[repr(C, packed)] #[derive(Debug, Copy, Clone)] pub struct Index { _block: BlockLoc, } impl Default for Index { fn default() -> Index { Index { _block: BLOCK_NULL } } } impl Index { /// get the block where the index is stored pub fn block(&self) -> BlockLoc { self._block } pub fn block_maybe(&self) -> Option<BlockLoc> { if self._block == BLOCK_NULL { None } else { Some(self._block) } } /// get size of Index DATA in bytes pub fn size(&self, pool: &RawPool) -> usize { unsafe { pool.full(self.block()).blocks() as usize * mem::size_of::<Block>() - mem::size_of::<Full>() } } } // ################################################## // # Full /// the Full struct represents data that has been allocated /// it contains only the size and a back-reference to the index /// that references it. /// It also contains the lock information inside it's index. #[repr(C, packed)] #[derive(Copy, Clone)] pub struct Full { // NOTE: DO NOT MOVE `_blocks`, IT IS SWAPPED WITH `_blocks` IN `Free` // The first bit of blocks is 1 for Full structs _blocks: BlockLoc, // size of this freed memory _index: IndexLoc, // data which contains the index and the lock information // space after this (until block + blocks) is invalid } impl fmt::Debug for Full { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let isvalid = if self.is_valid() { " " } else { "!" }; write!(f, "Full{}{{blocks: {}, index: {}, locked: {}}}{}", isvalid, self._blocks & BLOCK_BITMAP, self._index & BLOCK_BITMAP, if self._index & INDEX_HIGH_BIT == INDEX_HIGH_BIT { 1 } else { 0 }, isvalid) } } impl Full { /// get whether Full is locked pub fn is_locked(&self) -> bool { self.assert_valid(); self._index & INDEX_HIGH_BIT == INDEX_HIGH_BIT } /// set the lock on Full pub fn set_lock(&mut self) { self.assert_valid(); self._index |= INDEX_HIGH_BIT; } /// clear the lock on Full pub fn clear_lock(&mut self) { self.assert_valid(); self._index &= INDEX_BITMAP } pub fn blocks(&self) -> BlockLoc { self.assert_valid(); self._blocks & BLOCK_BITMAP } pub fn index(&self) -> BlockLoc { self.assert_valid(); self._index & INDEX_BITMAP } pub fn is_valid(&self) -> bool { self._blocks & BLOCK_HIGH_BIT == BLOCK_HIGH_BIT && self._blocks & BLOCK_BITMAP != 0 } pub fn assert_valid(&self) { assert!(self.is_valid(), "{:?}", self); } } // ################################################## // # RawPool /// `RawPool` is the private container and manager for all allocated /// and freed data. It handles the internals of allocation, deallocation /// and defragmentation. pub struct RawPool { // blocks and statistics pub _blocks: *mut Block, // actual data _blocks_len: BlockLoc, // len of blocks pub heap_block: BlockLoc, // the current location of the "heap" pub blocks_used: BlockLoc, // total memory currently used // indexes and statistics pub _indexes: *mut Index, // does not move and stores movable block location of data _indexes_len: IndexLoc, // len of indexes last_index_used: IndexLoc, // for speeding up finding indexes indexes_used: IndexLoc, // total number of indexes used // index cache pub index_cache: CBuf<'static, IndexLoc>, // freed data pub freed_bins: FreedBins, // freed bins } pub struct DisplayPool<'a> { pool: &'a RawPool, } impl<'a> fmt::Display for DisplayPool<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let p = self.pool; try!(write!(f, "RawPool {{\n")); try!(write!(f, " * index_ptr: {:?}\n", p._indexes)); try!(write!(f, " * Indexes: len: {}, used: {} remaining: {}\n", p.len_indexes(), p.indexes_used, p.indexes_remaining())); for i in 0..p.len_indexes() { let index = unsafe { p.index(i) }; if let Some(block) = index.block_maybe() { try!(write!(f, " {:<5}: {}\n", i, block)); } } try!(write!(f, " * blocks_ptr: {:?}\n", p._blocks)); try!(write!(f, " * Block Data (len: {}, used: {} remain: {})\n", p.len_blocks(), p.blocks_used, p.blocks_remaining())); unsafe { let ptr = p as *const RawPool; let mut block = (*ptr).first_block(); let first_block = match block { Some(b) => b as *const Block as usize, None => 0, }; while let Some(b) = block { try!(write!(f, " {:<5}: {}\n", (b as usize - first_block) / mem::size_of::<Block>(), *b)); block = (*b).next_mut(&*ptr).map(|b| b as *mut Block); } } try!(write!(f, " {:<5}: HEAP\n", p.heap_block)); try!(write!(f, " * Freed Bins (len: {}):\n", p.freed_bins.len)); unsafe { for b in 0..NUM_BINS { try!(write!(f, " [{}] bin {}: ", FreedBins::bin_repr(b), b)); let mut freed = p.freed_bins.bins[b as usize].root(p); while let Some(fr) = freed { try!(write!(f, "{} ", fr.block())); freed = fr.next().map(|b| p.freed(b)) } try!(write!(f, "\n")); } } write!(f, "}}") } } impl RawPool { pub fn display(&self) -> DisplayPool { DisplayPool { pool: self } } // Public unsafe API /// get a new RawPool /// /// This operation is unsafe because it is up to the user to ensure /// that `indexes` and `blocks` do not get deallocated for the lifetime /// of RawPool pub unsafe fn new(indexes: *mut Index, indexes_len: IndexLoc, blocks: *mut Block, blocks_len: BlockLoc, index_cache: CBuf<'static, IndexLoc>) -> RawPool { // initialize all indexes to INDEX_NULL let mut ptr = indexes; for _ in 0..indexes_len { *ptr = Index::default(); ptr = ptr.offset(1); } // initialize all blocks to 0 let mut ptr = blocks; for _ in 0..blocks_len { *ptr = Block::default(); ptr = ptr.offset(1); } RawPool { _blocks: blocks, _blocks_len: blocks_len, heap_block: 0, blocks_used: 0, _indexes: indexes, _indexes_len: indexes_len, last_index_used: indexes_len - 1, indexes_used: 0, index_cache: index_cache, freed_bins: FreedBins::default(), } } /// allocate data with a specified number of blocks, /// including the half block required to store `Full` struct pub unsafe fn alloc_index(&mut self, blocks: BlockLoc, fast: bool) -> Result<IndexLoc> { if blocks == 0 { return Err(Error::InvalidSize); } if self.blocks_remaining() < blocks { return Err(Error::OutOfMemory); } let prev_used_index = self.last_index_used; let i = try!(self.get_unused_index()); let block = if let Some(block) = self.use_freed(blocks, fast) { // we are reusing previously freed data block } else if (self.heap_block + blocks) <= self.len_blocks() { // we are using data on the heap let block = self.heap_block; self.heap_block += blocks; block } else { // we couldn't find enough contiguous memory (even though it exists) // i.e. we are too fragmented self.last_index_used = prev_used_index; self.index_cache.put(i); return Err(Error::Fragmented); }; // set the index data { let index = self.index_mut(i); index._block = block } // set the full data in the block { let full = self.full_mut(block); full._blocks = blocks | BLOCK_HIGH_BIT; full._index = i; // starts unlocked assert!(!full.is_locked()); } self.indexes_used += 1; self.blocks_used += blocks; Ok(i) } /// dealoc an index from the pool, this WILL corrupt any data that was there pub unsafe fn dealloc_index(&mut self, i: IndexLoc) { // get the size and location from the Index and clear it let block = self.index(i).block(); *self.index_mut(i) = Index::default(); self.index_cache.put(i); // ignore failure // start setting up freed let freed = self.freed_mut(block) as *mut Free; (*freed)._blocks &= BLOCK_BITMAP; // set first bit to 0, needed to read blocks() let blocks = (*freed).blocks(); // check if the freed is actually at the end of allocated heap, if so // just move the heap back if self.heap_block - blocks == block { self.heap_block = block; } else { assert!(block < self.heap_block - blocks); (*freed)._block = block; (*freed)._next = BLOCK_NULL; let selfptr = self as *mut RawPool; (*selfptr).freed_bins.insert(self, &mut *freed); } // statistics cleanup self.indexes_used -= 1; self.blocks_used -= blocks; } // /// combine all contiguous freed blocks together. pub unsafe fn clean(&mut self) { #[allow(unused_variables)] fn full_fn(pool: &mut RawPool, last_freed: Option<*mut Free>, full: &mut Full) -> Option<*mut Free> { None } utils::base_clean(self, &full_fn); } pub unsafe fn defrag(&mut self) { /// this is the function for handling when Full values are found /// it moves them backwards if they are unlocked #[allow(clone_on_copy)] // we want to be explicity that we are copying fn full_fn(pool: &mut RawPool, last_freed: Option<*mut Free>, full: &mut Full) -> Option<*mut Free> { unsafe { let poolptr = pool as *mut RawPool; match last_freed { Some(ref free) => { if full.is_locked() { None // locked full value, can't move } else { // found an unlocked full value and the last value is free -- move it! // moving is surprisingly simple because: // - the free.blocks does not change, so it does not change bins // - the free.prev/next do not change // - only the locations of full and free change, requiring their // data, and the items pointing at them, to be updated let i = full.index(); let blocks = full.blocks(); let mut free_tmp = (**free).clone(); let prev_free_block = free_tmp.block(); let fullptr = full as *mut Full as *mut Block; // perform the move of the data ptr::copy(fullptr, (*free) as *mut Block, blocks as usize); // Note: don't use free, full or fullptr after this // full's data was already copied (blocks + index), only need // to update the static Index's data (*poolptr).index_mut(i)._block = free_tmp.block(); // update the free block's location free_tmp._block += blocks; // update the items pointing TO free match free_tmp.prev() { Some(p) => (*poolptr).freed_mut(p)._next = free_tmp.block(), None => { // the previous item is a bin, so we have to // do surgery in the freed bins let freed_bins = &mut (*poolptr).freed_bins; let bin = freed_bins.get_insert_bin(free_tmp.blocks()); assert_eq!(freed_bins.bins[bin as usize]._root, prev_free_block); freed_bins.bins[bin as usize]._root = free_tmp.block(); } } if let Some(n) = free_tmp.next() { (*poolptr).freed_mut(n)._prev = free_tmp.block(); } // actually store the new free in pool._blocks let new_free_loc = (*poolptr).freed_mut(free_tmp.block()); *new_free_loc = free_tmp; // the new_free is the last_freed for the next cycle Some(new_free_loc as *mut Free) } } None => None, // the previous value is not free, can't move } } } utils::base_clean(self, &full_fn); } // public safe API /// raw pool size in blocks pub fn len_blocks(&self) -> BlockLoc { self._blocks_len } pub fn len_indexes(&self) -> IndexLoc { self._indexes_len } /// raw pool size in bytes pub fn size(&self) -> usize { self.len_blocks() as usize * mem::size_of::<Block>() } /// raw blocks remaining (fragmented or not) pub fn blocks_remaining(&self) -> BlockLoc { self.len_blocks() - self.blocks_used } /// raw bytes remaining (fragmented or not) pub fn bytes_remaining(&self) -> usize { self.blocks_remaining() as usize * mem::size_of::<Block>() } pub fn indexes_remaining(&self) -> IndexLoc { self.len_indexes() - self.indexes_used } /// get the index #[allow(should_implement_trait)] pub unsafe fn index(&self, i: IndexLoc) -> &Index { &*self._indexes.offset(i as isize) } // semi-private unsafe API #[allow(mut_from_ref)] pub unsafe fn index_mut(&self, i: IndexLoc) -> &mut Index { &mut *self._indexes.offset(i as isize) } /// get the raw ptr to the data at block pub unsafe fn data(&self, block: BlockLoc) -> *mut u8 { let p = self._blocks.offset(block as isize) as *mut u8; p.offset(mem::size_of::<Full>() as isize) } /// get the pointer to the first block pub unsafe fn first_block(&self) -> Option<*mut Block> { if self.heap_block == 0 { None } else { Some(self._blocks) } } pub unsafe fn block(&self, block: BlockLoc) -> *mut Block { self._blocks.offset(block as isize) } /// read the block as a Free block pub unsafe fn freed(&self, block: BlockLoc) -> &Free { &*(self._blocks.offset(block as isize) as *const Free) } /// mut the block as a Free block #[allow(mut_from_ref)] pub unsafe fn freed_mut(&self, block: BlockLoc) -> &mut Free { &mut *(self._blocks.offset(block as isize) as *mut Free) } /// read the block as a Full block pub unsafe fn full(&self, block: BlockLoc) -> &Full { &*(self._blocks.offset(block as isize) as *const Full) } /// mut the block as a Full block #[allow(mut_from_ref)] pub unsafe fn full_mut(&self, block: BlockLoc) -> &mut Full { &mut *(self._blocks.offset(block as isize) as *mut Full) } // private API /// get an unused index fn get_unused_index(&mut self) -> Result<IndexLoc> { if self.indexes_remaining() == 0 { return Err(Error::OutOfIndexes); } if let Some(i) = self.index_cache.get() { return Ok(i); } let mut i = (self.last_index_used + 1) % self.len_indexes(); while i != self.last_index_used { if unsafe { self.index(i)._block } == BLOCK_NULL { self.last_index_used = i; return Ok(i); } i = (i + 1) % self.len_indexes(); } unreachable!(); } /// get a freed value from the freed bins unsafe fn use_freed(&mut self, blocks: BlockLoc, fast: bool) -> Option<BlockLoc> { let selfptr = self as *mut RawPool; if fast { match (*selfptr).freed_bins.pop_fast(self, blocks) { Some(f) => Some(f), None => None, } } else { match (*selfptr).freed_bins.pop_slow(self, blocks) { Some(f) => Some(f), None => None, } } } } // ################################################## // # Internal Tests #[test] fn test_basic() { // assert that our bitmap is as expected let highbit = 1 << ((mem::size_of::<BlockLoc>() * 8) - 1); assert_eq!(BLOCK_BITMAP, !highbit, "{:b} != {:b}", BLOCK_BITMAP, !highbit); assert_eq!(BLOCK_HIGH_BIT, highbit, "{:b} != {:b}", BLOCK_HIGH_BIT, highbit); // assert that Full.blocks() cancels out the high bit let expected = highbit ^ BlockLoc::max_value(); let f = Full { _blocks: BLOCK_NULL, _index: 0, }; assert_eq!(f.blocks(), expected); // assert that Free.blocks() DOESN'T cancel out the high bit (not necessary) let mut f = Free { _blocks: BLOCK_BITMAP, _block: 0, _prev: 0, _next: 0, }; assert_eq!(f.blocks(), BLOCK_BITMAP); f._blocks = 42; assert_eq!(f.blocks(), 42); } #[test] /// test using raw indexes fn test_indexes() { use core::slice; unsafe { let (mut indexes, mut blocks): ([Index; 256], [Block; 4096]) = ([Index::default(); 256], mem::zeroed()); let iptr: *mut Index = mem::transmute(&mut indexes[..][0]); let bptr: *mut Block = mem::transmute(&mut blocks[..][0]); let mut cptr = [IndexLoc::default(); 10]; let cache_buf: &'static mut [IndexLoc] = slice::from_raw_parts_mut(&mut cptr[0] as *mut IndexLoc, 10); let cache = CBuf::new(cache_buf); let mut pool = RawPool::new(iptr, indexes.len() as IndexLoc, bptr, blocks.len() as BlockLoc, cache); assert_eq!(pool.get_unused_index().unwrap(), 0); assert_eq!(pool.get_unused_index().unwrap(), 1); assert_eq!(pool.get_unused_index().unwrap(), 2); let mut indexes_allocated = 3; let mut used_indexes = 0; let mut blocks_allocated = 0; // allocate an index println!("allocate 1"); assert_eq!(pool.freed_bins.len, 0); let i = pool.alloc_index(4, true).unwrap(); indexes_allocated += 1; assert_eq!(i, indexes_allocated - 1); let block; { let index = (*(&pool as *const RawPool)).index(i); assert_eq!(index._block, 0); block = index.block(); assert_eq!(pool.full(index.block()).blocks(), 4); assert_eq!(pool.full(index.block())._blocks, BLOCK_HIGH_BIT | 4); } // allocate another index and then free it, to show that the heap // just automatically get's reclaimed assert_eq!(pool.freed_bins.len, 0); let tmp_i = pool.alloc_index(100, true).unwrap(); pool.dealloc_index(tmp_i); assert_eq!(pool.freed_bins.len, 0); assert_eq!(pool.heap_block, 4); assert_eq!(pool.blocks_used, 4); // allocate an index so that the deallocated one doesn't // go back to the heap let i_a = pool.alloc_index(1, true).unwrap(); indexes_allocated += 1; used_indexes += 1; blocks_allocated += 1; assert_eq!(i_a, indexes_allocated - 1); // deallocate an index println!("free 1"); assert_eq!(pool.freed_bins.len, 0); pool.dealloc_index(i); indexes_allocated -= 1; { println!("deallocated 1"); assert_eq!(pool.index(i)._block, BLOCK_NULL); let freed = pool.freed(block); assert_eq!(freed.blocks(), 4); assert_eq!(freed._blocks, 4); assert_eq!(freed.prev(), None); assert_eq!(freed.next(), None); let bin = pool.freed_bins.get_insert_bin(4); assert_eq!(pool.freed_bins.bins[bin as usize] .root(&pool) .unwrap() .block(), block); } // allocate another index (that doesn't fit in the first) println!("allocate 2"); let i2 = pool.alloc_index(8, true).unwrap(); used_indexes += 1; blocks_allocated += 8; // we are using the index from the last freed value assert_eq!(i2, i); indexes_allocated += 1; { let index2 = (*(&pool as *const RawPool)).index(i2); assert_eq!(index2._block, 5); assert_eq!(pool.full(index2.block()).blocks(), 8); assert_eq!(pool.full(index2.block())._blocks, BLOCK_HIGH_BIT | 8); } // allocate a 3rd index (that does fit in the first) println!("allocate 3"); let i3 = pool.alloc_index(2, true).unwrap(); indexes_allocated += 1; used_indexes += 1; blocks_allocated += 2; assert_eq!(i3, indexes_allocated - 1); { let index3 = (*(&pool as *const RawPool)).index(i3); assert_eq!(index3._block, 0); assert_eq!(pool.full(index3.block()).blocks(), 2); assert_eq!(pool.full(index3.block())._blocks, BLOCK_HIGH_BIT | 2); } // tests related to the fact that i3 just overwrote the freed item let bin = pool.freed_bins.get_insert_bin(2); let free_block = pool.freed_bins.bins[bin as usize] .root(&pool) .unwrap() .block(); assert_eq!(free_block, 2); { // free1 has moved let free = pool.freed(free_block); assert_eq!(free.blocks(), 2); assert_eq!(free.prev(), None); assert_eq!(free.next(), None); } // allocate 3 indexes then free the first 2 // then run the freeing clean assert_eq!(i3, indexes_allocated - 1); let allocs = (pool.alloc_index(4, true).unwrap(), pool.alloc_index(4, true).unwrap(), pool.alloc_index(4, true).unwrap()); indexes_allocated += 3; assert_eq!(allocs.2, indexes_allocated - 1); used_indexes += 1; blocks_allocated += 4; let free_block = pool.index(allocs.0).block(); pool.dealloc_index(allocs.0); pool.dealloc_index(allocs.1); // indexes_allocated -= 2; println!("cleaning freed"); // println!("{}", pool.display()); pool.clean(); { let free = pool.freed(free_block); assert_eq!(free.blocks(), 8); } pool.clean(); pool.clean(); // defrag and make sure everything looks like how one would expect it println!("defragging"); // println!("{}", pool.display()); pool.defrag(); println!("done defragging"); // println!("{}", pool.display()); assert_eq!(pool.freed_bins.len, 0); assert_eq!(pool.blocks_used, blocks_allocated); assert_eq!(pool.indexes_used, used_indexes); } }
true
27662ef7a6413456156431b1337094f69853eb3c
Rust
Lucretia/Primes
/PrimeRust/solution_4/PrimeRust.rs
UTF-8
4,086
3.046875
3
[]
no_license
//------------------------------------------------------------------------------------------ // PrimeRust.rs : Ported to Rust by Joshua Allen Based on Dave's Garage Prime Sieve - No warranty for anything! // Also note: I tried to follow the structure of the CPP version as close as possible and may not be in a perfect Rust style //------------------------------------------------------------------------------------------ use std::collections::HashMap; use std::time::{Duration, Instant}; struct PrimeSieve { sieve_size: usize, results_dictionary: HashMap<usize,usize>, bits: Vec<bool>, } //builder function for prime sieve fn build_prime_sieve (sieve_size: usize) -> PrimeSieve { // Historical data for validating our results - the number of primes // to be found under some limit, such as 168 primes under 1000 let results_dictionary: HashMap<usize,usize> = [ ( 10, 4 ), ( 100, 25 ), ( 1000, 168 ), ( 10000, 1229 ), ( 100000, 9592 ), ( 1000000, 78498 ), ( 10000000, 664579 ), ( 100000000, 5761455 ), ( 1000000000, 50847534 ), ( 10000000000, 455052511 ), ].iter().cloned().collect(); //this converts the array to a collection let n_bits = sieve_size; PrimeSieve { sieve_size: sieve_size, results_dictionary: results_dictionary, bits: vec![true; n_bits] //fill up the bits with true based on the sieve size } } impl PrimeSieve { fn validate_results(&self) -> bool { let _num_primes: usize; match self.results_dictionary.get(&self.sieve_size) { Some(_prime) => return true, None => return false } } fn run_sieve(&mut self) { let mut factor: usize = 3; let float_sieve_size: f64 = self.sieve_size as f64; let q = float_sieve_size.sqrt() as usize; while factor <= q { let mut num = factor; while num < q { if self.bits[num]{ factor = num; break; } num +=2; } let mut num = factor * factor; while num < self.sieve_size { self.bits[num] = false; num += factor *2; } factor += 2; } } fn count_primes(&self)->usize{ let mut count = 0; if self.sieve_size >= 2{ count = 1; } let mut i = 3; loop { if self.bits[i]{ count +=1; } i +=2; if i >= self.sieve_size -1{ break } } return count; } fn print_results(&self, show_results: bool, duration: Duration, passes: usize){ if show_results { print!("2, "); } let mut _count = 0; if self.sieve_size >= 2{ _count = 1; } let mut num = 3; loop { if self.bits[num]{ if show_results{ print!("{}, ",num); } _count+=1; } num +=2; if num >= self.sieve_size -1{ break } } if show_results { println!(""); } println!("joshallen64;{};{};1;algorithm=base,faithful=yes", passes, duration.as_secs_f32() ) } } fn main() { let mut passes = 0; let time_start = Instant::now(); loop{ let mut prime_sieve = build_prime_sieve(1000000); prime_sieve.run_sieve(); passes += 1; if Instant::now() - time_start >= Duration::new(5,0){ prime_sieve.print_results(false, Instant::now()-time_start, passes); break; } } }
true
d017efd66a21e0de713fcfcd7e6a6dc867f74828
Rust
netvl/md.rs
/src/parser/config.rs
UTF-8
541
2.796875
3
[ "MIT" ]
permissive
#[derive(Copy)] pub struct MarkdownConfig { pub trim_newlines: bool } impl MarkdownConfig { #[inline] pub fn default() -> MarkdownConfig { MarkdownConfig { trim_newlines: true } } } macro_rules! impl_setters { ($target:ident; $($name:ident : $t:ty),+) => ($( impl $target { pub fn $name(mut self, value: $t) -> $target { self.$name = value; self } } )+) } impl_setters! { MarkdownConfig; trim_newlines: bool }
true
89075a262e008f2e7a3b3eecab009817509c2c29
Rust
sria91-rlox/rlox-3
/src/rlox/resolver/mod.rs
UTF-8
9,301
2.96875
3
[]
no_license
use rlox::parser::Stmt; use rlox::parser::Expr; use rlox::token::Token; use std::collections::hash_map::HashMap; #[derive(Clone, PartialEq)] enum ClassType { Class, SubClass, } #[derive(Clone, PartialEq)] enum FunctionType { Function, Method, Initializer, } pub struct Resolver { scopes: Vec<HashMap<String, bool>>, class_type: Option<ClassType>, function_type: Option<FunctionType>, } impl Resolver { pub fn new() -> Resolver { Resolver { scopes: Vec::new(), class_type: None, function_type: None, } } pub fn resolve_ast(&mut self, ast: &mut Vec<Stmt>) { for ref mut stmt in ast { self.resolve_statement(stmt); } } fn resolve_statement(&mut self, stmt: &mut Stmt) { match *stmt { Stmt::Block(ref mut stmts) => { self.begin_scope(); self.resolve_ast(stmts); self.end_scope(); } Stmt::Var(ref token, ref mut expr) => { self.declare(token.lexeme.clone()); self.resolve_expression(expr); // TODO: Can I use a reference to the string instead of having to own it? self.define(token.lexeme.clone()); } Stmt::Func(ref token, ref params, ref mut body) => { self.declare(token.lexeme.clone()); self.define(token.lexeme.clone()); self.resolve_function(params, body, Some(FunctionType::Function)); } Stmt::Expr(ref mut expr) => self.resolve_expression(expr), Stmt::If(ref mut condition, ref mut then_branch, ref mut else_branch) => { self.resolve_expression(condition); self.resolve_statement(then_branch); if let Some(ref mut else_branch) = **else_branch { self.resolve_statement(else_branch); } } Stmt::Print(ref mut expr) => self.resolve_expression(expr), Stmt::Return(_, ref mut expr) => { { let function_type = self.function_type .as_ref() .expect("UnexpectedTokenError: Cannot use `return` at the top level."); if *function_type == FunctionType::Initializer { panic!("UnexpectedTokenError: Cannot use `return` on an initializer.") } } self.resolve_expression(expr) } Stmt::While(ref mut condition, ref mut body) => { self.resolve_expression(condition); self.resolve_statement(body); } Stmt::Class(ref token, ref mut superclass, ref mut methods) => { self.declare(token.lexeme.clone()); let enclosing_class_type = self.class_type.clone(); self.class_type = Some(ClassType::Class); if let &mut Some(ref mut superclass) = superclass { self.class_type = Some(ClassType::SubClass); self.resolve_expression(superclass); self.begin_scope(); self.define("super".to_string()); } self.begin_scope(); self.define("this".to_string()); for method in methods { match method { &mut Stmt::Func(ref token, ref params, ref mut body) => { self.declare(token.lexeme.clone()); self.define(token.lexeme.clone()); let function_type = if token.lexeme == "init" { FunctionType::Initializer } else { FunctionType::Method }; self.resolve_function(params, body, Some(function_type)); } _ => {} } } self.end_scope(); if superclass.is_some() { self.end_scope(); } self.class_type = enclosing_class_type; self.define(token.lexeme.clone()); } } } fn resolve_expression(&mut self, expr: &mut Expr) { match *expr { Expr::Var(ref token, ref mut distance) => { if let Some(scope) = self.scopes.last() { if let Some(is_var_available) = scope.get(&token.lexeme) { if !is_var_available { // TODO: Error } } } *distance = self.resolve_local(token.lexeme.clone()); } Expr::Assign(ref token, ref mut expr, ref mut distance) => { self.resolve_expression(expr); *distance = self.resolve_local(token.lexeme.clone()); } Expr::Binary(ref mut left, _, ref mut right) => { self.resolve_expression(left); self.resolve_expression(right); } Expr::Call(ref mut callee, ref mut arguments, _) => { self.resolve_expression(callee); for ref mut arg in arguments { self.resolve_expression(arg); } } Expr::Grouping(ref mut expr) => { self.resolve_expression(expr); } Expr::Literal(_) => {} Expr::Logical(ref mut left, _, ref mut right) => { self.resolve_expression(left); self.resolve_expression(right); } Expr::Unary(_, ref mut expr) => { self.resolve_expression(expr); } Expr::Get(ref mut target, _) => { self.resolve_expression(target); } Expr::Set(ref mut target, _, ref mut value) => { self.resolve_expression(target); self.resolve_expression(value); } Expr::This(ref token, ref mut distance) => { if self.class_type.is_none() { panic!("UnexpectedTokenError: Cannot use `this` outside of a method."); } if let Some(scope) = self.scopes.last() { if let Some(is_var_available) = scope.get(&token.lexeme) { if !is_var_available { // TODO: Error } } } *distance = self.resolve_local(token.lexeme.clone()); } Expr::Super(ref token, _, ref mut distance) => { let class_type = self.class_type .as_ref() .expect("UnexpectedTokenError: Cannot use `super` outside of a method."); match class_type { &ClassType::Class => { panic!("UnexpectedTokenError: Cannot use `super` without a superclass.") } _ => { if let Some(scope) = self.scopes.last() { if let Some(is_var_available) = scope.get(&token.lexeme) { if !is_var_available { // TODO: Error } } } let resolved_distance = self.resolve_local(token.lexeme.clone()); *distance = resolved_distance; } } } } } fn resolve_local(&self, lexeme: String) -> Option<usize> { for (i, scope) in self.scopes.iter().rev().enumerate() { if scope.contains_key(&lexeme) { return Some(i); } } None } fn resolve_function( &mut self, params: &Vec<Token>, body: &mut Stmt, function_type: Option<FunctionType>, ) { let enclosing_function = self.function_type.clone(); self.function_type = function_type; self.begin_scope(); for param in params { self.declare(param.lexeme.clone()); self.define(param.lexeme.clone()); } match body { &mut Stmt::Block(ref mut stmts) => for stmt in stmts { self.resolve_statement(stmt); }, _ => panic!("The body of a function should never be other than Stmt::Block"), } self.end_scope(); self.function_type = enclosing_function; } fn begin_scope(&mut self) { self.scopes.push(HashMap::new()); } fn end_scope(&mut self) { self.scopes.pop(); } fn declare(&mut self, name: String) { if let Some(scope) = self.scopes.last_mut() { scope.insert(name, false); } } fn define(&mut self, name: String) { if let Some(scope) = self.scopes.last_mut() { scope.insert(name, true); } } }
true
e0bced6665d3f2e95ac53645c9a0ee4201da318f
Rust
MiyamonY/atcoder
/abc/040/c/01/src/main.rs
UTF-8
2,120
2.9375
3
[]
no_license
use std::cmp::min; #[allow(unused_macros)] macro_rules! scan { () => { { let mut line: String = String::new(); std::io::stdin().read_line(&mut line).unwrap(); line.trim().to_string() } }; (;;) => { { let mut line: String = String::new(); std::io::stdin().read_line(&mut line).unwrap(); line.trim().split_whitespace().map(|s| s.to_string()).collect::<Vec<String>>() } }; (;;$n:expr) => { { (0..$n).map(|_| scan!()).collect::<Vec<_>>() } }; ($t:ty) => { { let mut line: String = String::new(); std::io::stdin().read_line(&mut line).unwrap(); line.trim().parse::<$t>().unwrap() } }; ($($t:ty),*) => { { let mut line: String = String::new(); std::io::stdin().read_line(&mut line).unwrap(); let mut iter = line.split_whitespace(); ( $(iter.next().unwrap().parse::<$t>().unwrap(),)* ) } }; ($t:ty;;) => { { let mut line: String = String::new(); std::io::stdin().read_line(&mut line).unwrap(); line.split_whitespace() .map(|t| t.parse::<$t>().unwrap()) .collect::<Vec<_>>() } }; ($t:ty;;$n:expr) => { (0..$n).map(|_| scan!($t;;)).collect::<Vec<_>>() }; ($t:ty; $n:expr) => { (0..$n).map(|_| scan!($t) ).collect::<Vec<_>>() }; ($($t:ty),*; $n:expr) => { (0..$n).map(|_| scan!($($t),*) ).collect::<Vec<_>>() }; } fn main() { let n = scan!(usize); let vs = scan!(i64;;); let mut dp = vec![0; n + 1]; dp[1] = 0; dp[2] = (vs[1] - vs[0]).abs(); for (i, ((v2, v1), v0)) in vs .iter() .zip(vs[1..].iter()) .zip(vs[2..].iter()) .enumerate() { dp[i + 3] = min(dp[i + 2] + (v0 - v1).abs(), dp[i + 1] + (v0 - v2).abs()); } println!("{}", dp[n]); }
true
fa71c74ef65d8a710a52933f198205d3466b6735
Rust
dyedgreen/uncertain
/tests/basic_expect.rs
UTF-8
2,448
3.25
3
[ "MIT" ]
permissive
use rand_distr::{Normal, Poisson}; use rand_pcg::Pcg32; use uncertain::*; #[test] fn basic_gaussian() { let centers: Vec<f64> = vec![0.0, 3.5, 1.73, 234.23235]; for center in centers { let x = Distribution::from(Normal::new(center, 1.0).unwrap()); let mu = x.expect(0.1); assert!(mu.is_ok()); assert!((mu.unwrap() - center).abs() < 0.1); } let centers: Vec<f32> = vec![0.0, 3.5, 1.73, 234.23235]; for center in centers { let x = Distribution::from(Normal::new(center, 1.0).unwrap()); let mu = x.expect(0.1); assert!(mu.is_ok()); assert!((mu.unwrap() - center).abs() < 0.1); } } #[test] fn basic_poisson() { let centers: Vec<f64> = vec![1.0, 2.0, 3.0, 5.0, 15.0]; for center in centers { let x = Distribution::from(Poisson::new(center).unwrap()); let mu = x.expect(0.1); assert!(mu.is_ok()); assert!((mu.unwrap() - center).abs() < 0.1); } let centers: Vec<f64> = vec![100.0, 200.0, 300.0, 400.0, 500.0]; for center in centers { let x = Distribution::from(Poisson::new(center).unwrap()); let mu = x.expect(10.0); assert!(mu.is_ok()); assert!((mu.unwrap() - center).abs() < 10.0); } let centers: Vec<f64> = vec![0.35235, 1.234, 4.324234, 6.3435]; for center in centers { let x = Distribution::from(Poisson::new(center).unwrap()); let mu = x.expect(0.1); assert!(mu.is_ok()); assert!((mu.unwrap() - center).abs() < 0.1); } } #[test] fn very_easy() { let x = PointMass::new(5.0); assert_eq!(x.expect(0.01).unwrap(), 5.0); let x = Distribution::from(Normal::new(5.0, 2.0).unwrap()).into_ref(); let y = (&x).sub(&x); assert_eq!(y.expect(0.01).unwrap(), 0.0); } #[test] fn very_hard() { struct UncertainCounter; impl Uncertain for UncertainCounter { type Value = f64; fn sample(&self, _: &mut Pcg32, epoch: usize) -> Self::Value { epoch as f64 } } let c = UncertainCounter; let mu = c.expect(0.1); // should not converge (!) assert!(mu.is_err()); } #[test] fn composite_gaussian_poisson() { let g = Distribution::from(Normal::new(5.0, 2.0).unwrap()); let p = Distribution::from(Poisson::new(3.0).unwrap()); let s = g.add(p); let mu = s.expect(0.1 as f64); assert!(mu.is_ok()); assert!((mu.unwrap() - 8.0).abs() < 0.1); }
true
9f0263864f260adc464438fc836340982b306cc5
Rust
redox-os/syscall
/src/call.rs
UTF-8
12,001
2.84375
3
[ "MIT" ]
permissive
use super::arch::*; use super::data::{Map, SigAction, Stat, StatVfs, TimeSpec}; use super::error::Result; use super::flag::*; use super::number::*; use core::{mem, ptr}; // Signal restorer extern "C" fn restorer() -> ! { sigreturn().unwrap(); unreachable!(); } /// Close a file pub fn close(fd: usize) -> Result<usize> { unsafe { syscall1(SYS_CLOSE, fd) } } /// Get the current system time pub fn clock_gettime(clock: usize, tp: &mut TimeSpec) -> Result<usize> { unsafe { syscall2(SYS_CLOCK_GETTIME, clock, tp as *mut TimeSpec as usize) } } /// Copy and transform a file descriptor pub fn dup(fd: usize, buf: &[u8]) -> Result<usize> { unsafe { syscall3(SYS_DUP, fd, buf.as_ptr() as usize, buf.len()) } } /// Copy and transform a file descriptor pub fn dup2(fd: usize, newfd: usize, buf: &[u8]) -> Result<usize> { unsafe { syscall4(SYS_DUP2, fd, newfd, buf.as_ptr() as usize, buf.len()) } } /// Exit the current process pub fn exit(status: usize) -> Result<usize> { unsafe { syscall1(SYS_EXIT, status) } } /// Change file permissions pub fn fchmod(fd: usize, mode: u16) -> Result<usize> { unsafe { syscall2(SYS_FCHMOD, fd, mode as usize) } } /// Change file ownership pub fn fchown(fd: usize, uid: u32, gid: u32) -> Result<usize> { unsafe { syscall3(SYS_FCHOWN, fd, uid as usize, gid as usize) } } /// Change file descriptor flags pub fn fcntl(fd: usize, cmd: usize, arg: usize) -> Result<usize> { unsafe { syscall3(SYS_FCNTL, fd, cmd, arg) } } /// Map a file into memory, but with the ability to set the address to map into, either as a hint /// or as a requirement of the map. /// /// # Errors /// `EACCES` - the file descriptor was not open for reading /// `EBADF` - if the file descriptor was invalid /// `ENODEV` - mmapping was not supported /// `EINVAL` - invalid combination of flags /// `EEXIST` - if [`MapFlags::MAP_FIXED`] was set, and the address specified was already in use. /// pub unsafe fn fmap(fd: usize, map: &Map) -> Result<usize> { syscall3(SYS_FMAP, fd, map as *const Map as usize, mem::size_of::<Map>()) } /// Unmap whole (or partial) continous memory-mapped files pub unsafe fn funmap(addr: usize, len: usize) -> Result<usize> { syscall2(SYS_FUNMAP, addr, len) } /// Retrieve the canonical path of a file pub fn fpath(fd: usize, buf: &mut [u8]) -> Result<usize> { unsafe { syscall3(SYS_FPATH, fd, buf.as_mut_ptr() as usize, buf.len()) } } /// Rename a file pub fn frename<T: AsRef<str>>(fd: usize, path: T) -> Result<usize> { unsafe { syscall3(SYS_FRENAME, fd, path.as_ref().as_ptr() as usize, path.as_ref().len()) } } /// Get metadata about a file pub fn fstat(fd: usize, stat: &mut Stat) -> Result<usize> { unsafe { syscall3(SYS_FSTAT, fd, stat as *mut Stat as usize, mem::size_of::<Stat>()) } } /// Get metadata about a filesystem pub fn fstatvfs(fd: usize, stat: &mut StatVfs) -> Result<usize> { unsafe { syscall3(SYS_FSTATVFS, fd, stat as *mut StatVfs as usize, mem::size_of::<StatVfs>()) } } /// Sync a file descriptor to its underlying medium pub fn fsync(fd: usize) -> Result<usize> { unsafe { syscall1(SYS_FSYNC, fd) } } /// Truncate or extend a file to a specified length pub fn ftruncate(fd: usize, len: usize) -> Result<usize> { unsafe { syscall2(SYS_FTRUNCATE, fd, len) } } // Change modify and/or access times pub fn futimens(fd: usize, times: &[TimeSpec]) -> Result<usize> { unsafe { syscall3(SYS_FUTIMENS, fd, times.as_ptr() as usize, times.len() * mem::size_of::<TimeSpec>()) } } /// Fast userspace mutex pub unsafe fn futex(addr: *mut i32, op: usize, val: i32, val2: usize, addr2: *mut i32) -> Result<usize> { syscall5(SYS_FUTEX, addr as usize, op, (val as isize) as usize, val2, addr2 as usize) } /// Get the effective group ID pub fn getegid() -> Result<usize> { unsafe { syscall0(SYS_GETEGID) } } /// Get the effective namespace pub fn getens() -> Result<usize> { unsafe { syscall0(SYS_GETENS) } } /// Get the effective user ID pub fn geteuid() -> Result<usize> { unsafe { syscall0(SYS_GETEUID) } } /// Get the current group ID pub fn getgid() -> Result<usize> { unsafe { syscall0(SYS_GETGID) } } /// Get the current namespace pub fn getns() -> Result<usize> { unsafe { syscall0(SYS_GETNS) } } /// Get the current process ID pub fn getpid() -> Result<usize> { unsafe { syscall0(SYS_GETPID) } } /// Get the process group ID pub fn getpgid(pid: usize) -> Result<usize> { unsafe { syscall1(SYS_GETPGID, pid) } } /// Get the parent process ID pub fn getppid() -> Result<usize> { unsafe { syscall0(SYS_GETPPID) } } /// Get the current user ID pub fn getuid() -> Result<usize> { unsafe { syscall0(SYS_GETUID) } } /// Set the I/O privilege level /// /// # Errors /// /// * `EPERM` - `uid != 0` /// * `EINVAL` - `level > 3` pub unsafe fn iopl(level: usize) -> Result<usize> { syscall1(SYS_IOPL, level) } /// Send a signal `sig` to the process identified by `pid` pub fn kill(pid: usize, sig: usize) -> Result<usize> { unsafe { syscall2(SYS_KILL, pid, sig) } } /// Create a link to a file pub unsafe fn link(old: *const u8, new: *const u8) -> Result<usize> { syscall2(SYS_LINK, old as usize, new as usize) } /// Seek to `offset` bytes in a file descriptor pub fn lseek(fd: usize, offset: isize, whence: usize) -> Result<usize> { unsafe { syscall3(SYS_LSEEK, fd, offset as usize, whence) } } /// Make a new scheme namespace pub fn mkns(schemes: &[[usize; 2]]) -> Result<usize> { unsafe { syscall2(SYS_MKNS, schemes.as_ptr() as usize, schemes.len()) } } /// Change mapping flags pub unsafe fn mprotect(addr: usize, size: usize, flags: MapFlags) -> Result<usize> { syscall3(SYS_MPROTECT, addr, size, flags.bits()) } /// Sleep for the time specified in `req` pub fn nanosleep(req: &TimeSpec, rem: &mut TimeSpec) -> Result<usize> { unsafe { syscall2(SYS_NANOSLEEP, req as *const TimeSpec as usize, rem as *mut TimeSpec as usize) } } /// Open a file pub fn open<T: AsRef<str>>(path: T, flags: usize) -> Result<usize> { unsafe { syscall3(SYS_OPEN, path.as_ref().as_ptr() as usize, path.as_ref().len(), flags) } } /// Allocate frames, linearly in physical memory. /// /// # Errors /// /// * `EPERM` - `uid != 0` /// * `ENOMEM` - the system has run out of available memory pub unsafe fn physalloc(size: usize) -> Result<usize> { syscall1(SYS_PHYSALLOC, size) } /// Allocate frames, linearly in physical memory, with an extra set of flags. If the flags contain /// [`PARTIAL_ALLOC`], this will result in `physalloc3` with `min = 1`. /// /// Refer to the simpler [`physalloc`] and the more complex [`physalloc3`], that this convenience /// function is based on. /// /// # Errors /// /// * `EPERM` - `uid != 0` /// * `ENOMEM` - the system has run out of available memory pub unsafe fn physalloc2(size: usize, flags: usize) -> Result<usize> { let mut ret = 1usize; physalloc3(size, flags, &mut ret) } /// Allocate frames, linearly in physical memory, with an extra set of flags. If the flags contain /// [`PARTIAL_ALLOC`], the `min` parameter specifies the number of frames that have to be allocated /// for this operation to succeed. The return value is the offset of the first frame, and `min` is /// overwritten with the number of frames actually allocated. /// /// Refer to the simpler [`physalloc`] and the simpler library function [`physalloc2`]. /// /// # Errors /// /// * `EPERM` - `uid != 0` /// * `ENOMEM` - the system has run out of available memory /// * `EINVAL` - `min = 0` pub unsafe fn physalloc3(size: usize, flags: usize, min: &mut usize) -> Result<usize> { syscall3(SYS_PHYSALLOC3, size, flags, min as *mut usize as usize) } /// Free physically allocated pages /// /// # Errors /// /// * `EPERM` - `uid != 0` pub unsafe fn physfree(physical_address: usize, size: usize) -> Result<usize> { syscall2(SYS_PHYSFREE, physical_address, size) } /// Map physical memory to virtual memory /// /// # Errors /// /// * `EPERM` - `uid != 0` pub unsafe fn physmap(physical_address: usize, size: usize, flags: PhysmapFlags) -> Result<usize> { syscall3(SYS_PHYSMAP, physical_address, size, flags.bits()) } /// Create a pair of file descriptors referencing the read and write ends of a pipe pub fn pipe2(fds: &mut [usize; 2], flags: usize) -> Result<usize> { unsafe { syscall2(SYS_PIPE2, fds.as_ptr() as usize, flags) } } /// Read from a file descriptor into a buffer pub fn read(fd: usize, buf: &mut [u8]) -> Result<usize> { unsafe { syscall3(SYS_READ, fd, buf.as_mut_ptr() as usize, buf.len()) } } /// Remove a directory pub fn rmdir<T: AsRef<str>>(path: T) -> Result<usize> { unsafe { syscall2(SYS_RMDIR, path.as_ref().as_ptr() as usize, path.as_ref().len()) } } /// Set the process group ID pub fn setpgid(pid: usize, pgid: usize) -> Result<usize> { unsafe { syscall2(SYS_SETPGID, pid, pgid) } } /// Set the current process group IDs pub fn setregid(rgid: usize, egid: usize) -> Result<usize> { unsafe { syscall2(SYS_SETREGID, rgid, egid) } } /// Make a new scheme namespace pub fn setrens(rns: usize, ens: usize) -> Result<usize> { unsafe { syscall2(SYS_SETRENS, rns, ens) } } /// Set the current process user IDs pub fn setreuid(ruid: usize, euid: usize) -> Result<usize> { unsafe { syscall2(SYS_SETREUID, ruid, euid) } } /// Set up a signal handler pub fn sigaction(sig: usize, act: Option<&SigAction>, oldact: Option<&mut SigAction>) -> Result<usize> { unsafe { syscall4(SYS_SIGACTION, sig, act.map(|x| x as *const _).unwrap_or_else(ptr::null) as usize, oldact.map(|x| x as *mut _).unwrap_or_else(ptr::null_mut) as usize, restorer as usize) } } /// Get and/or set signal masks pub fn sigprocmask(how: usize, set: Option<&[u64; 2]>, oldset: Option<&mut [u64; 2]>) -> Result<usize> { unsafe { syscall3(SYS_SIGPROCMASK, how, set.map(|x| x as *const _).unwrap_or_else(ptr::null) as usize, oldset.map(|x| x as *mut _).unwrap_or_else(ptr::null_mut) as usize) } } // Return from signal handler pub fn sigreturn() -> Result<usize> { unsafe { syscall0(SYS_SIGRETURN) } } /// Set the file mode creation mask pub fn umask(mask: usize) -> Result<usize> { unsafe { syscall1(SYS_UMASK, mask) } } /// Remove a file pub fn unlink<T: AsRef<str>>(path: T) -> Result<usize> { unsafe { syscall2(SYS_UNLINK, path.as_ref().as_ptr() as usize, path.as_ref().len()) } } /// Convert a virtual address to a physical one /// /// # Errors /// /// * `EPERM` - `uid != 0` pub unsafe fn virttophys(virtual_address: usize) -> Result<usize> { syscall1(SYS_VIRTTOPHYS, virtual_address) } /// Check if a child process has exited or received a signal pub fn waitpid(pid: usize, status: &mut usize, options: WaitFlags) -> Result<usize> { unsafe { syscall3(SYS_WAITPID, pid, status as *mut usize as usize, options.bits()) } } /// Write a buffer to a file descriptor /// /// The kernel will attempt to write the bytes in `buf` to the file descriptor `fd`, returning /// either an `Err`, explained below, or `Ok(count)` where `count` is the number of bytes which /// were written. /// /// # Errors /// /// * `EAGAIN` - the file descriptor was opened with `O_NONBLOCK` and writing would block /// * `EBADF` - the file descriptor is not valid or is not open for writing /// * `EFAULT` - `buf` does not point to the process's addressible memory /// * `EIO` - an I/O error occurred /// * `ENOSPC` - the device containing the file descriptor has no room for data /// * `EPIPE` - the file descriptor refers to a pipe or socket whose reading end is closed pub fn write(fd: usize, buf: &[u8]) -> Result<usize> { unsafe { syscall3(SYS_WRITE, fd, buf.as_ptr() as usize, buf.len()) } } /// Yield the process's time slice to the kernel /// /// This function will return Ok(0) on success pub fn sched_yield() -> Result<usize> { unsafe { syscall0(SYS_YIELD) } }
true
e9befd833a1b174ea6ac57fcf20678859c7b8466
Rust
bouzuya/rust-atcoder
/cargo-atcoder/contests/arc006/src/bin/b.rs
UTF-8
1,174
3.0625
3
[]
no_license
fn read<T: std::str::FromStr>( stdin_lock: &mut std::io::StdinLock, buf: &mut Vec<u8>, delimiter: u8, ) -> T { buf.clear(); let l = std::io::BufRead::read_until(stdin_lock, delimiter, buf).unwrap(); buf.truncate(l - 1); // remove delimiter let s = unsafe { std::str::from_utf8_unchecked(&buf) }; s.parse().unwrap_or_else(|_| panic!("read")) } fn main() { let stdin = std::io::stdin(); let mut stdin_lock = stdin.lock(); let mut buf: Vec<u8> = Vec::new(); let _: usize = read(&mut stdin_lock, &mut buf, b' '); let n_l: usize = read(&mut stdin_lock, &mut buf, b'\n'); let mut l: Vec<Vec<char>> = Vec::new(); for _ in 0..n_l { let l_i: String = read(&mut stdin_lock, &mut buf, b'\n'); l.push(l_i.chars().collect::<Vec<char>>()); } let o: String = read(&mut stdin_lock, &mut buf, b'o'); let o: usize = o.len(); // Usize1 let mut i = o; for l_i in l.iter().rev() { if i > 1 && l_i[i - 1] == '-' { i = i - 2; } else if i < l_i.len() - 1 && l_i[i + 1] == '-' { i = i + 2; } } let ans = (i + 2) / 2; println!("{}", ans); }
true
025dd880a9c92b1e6ab63f4ee8dda1348ee0b6ff
Rust
wata-orz/santa17
/src/common.rs
UTF-8
2,019
2.734375
3
[ "MIT" ]
permissive
#[macro_export] macro_rules! debug { ($($v:expr),*) => { { use ::std::io::Write; $(let _ = write!(::std::io::stderr(), "{} = {:?} ", stringify!($v), $v);)* let _ = writeln!(::std::io::stderr(), "@ {}:{}", file!(), line!()); } } } #[macro_export] macro_rules! mat { ($e:expr) => { $e }; ($e:expr; $d:expr $(; $ds:expr)*) => { vec![mat![$e $(; $ds)*]; $d] }; } pub trait SetMin { fn setmin(&mut self, v: Self) -> bool; } impl<T> SetMin for T where T: PartialOrd { #[inline] fn setmin(&mut self, v: T) -> bool { *self > v && { *self = v; true } } } pub trait SetMax { fn setmax(&mut self, v: Self) -> bool; } impl<T> SetMax for T where T: PartialOrd { #[inline] fn setmax(&mut self, v: T) -> bool { *self < v && { *self = v; true } } } #[macro_export] macro_rules! ok { ($a:ident$([$i:expr])*.$f:ident()$(@$t:ident)*) => { $a$([$i])*.$f($($t),*) }; ($a:ident$([$i:expr])*.$f:ident($e:expr$(,$es:expr)*)$(@$t:ident)*) => { { let t = $e; ok!($a$([$i])*.$f($($es),*)$(@$t)*@t) } }; } macro_rules! impl_cmp { ($name:ident $(<$($t:ident),*>)*; |$x:ident, $y:ident| $e:expr; $($w:tt)*) => { impl $(<$($t),*>)* Ord for $name $(<$($t),*>)* $($w)* { #[inline] fn cmp(&self, $y: &Self) -> ::std::cmp::Ordering { let $x = &self; $e } } impl $(<$($t),*>)* PartialOrd for $name $(<$($t),*>)* $($w)* { #[inline] fn partial_cmp(&self, a: &Self) -> Option<::std::cmp::Ordering> { Some(self.cmp(a)) } } impl $(<$($t),*>)* PartialEq for $name $(<$($t),*>)* $($w)* { #[inline] fn eq(&self, a: &Self) -> bool { self.cmp(a) == ::std::cmp::Ordering::Equal } } impl $(<$($t),*>)* Eq for $name $(<$($t),*>)* $($w)* {} } } #[derive(Clone, Copy, Debug, Default, Hash)] pub struct Tot<T: PartialOrd>(pub T); impl_cmp!(Tot<T>; |a, b| a.0.partial_cmp(&b.0).unwrap(); where T: PartialOrd); #[derive(Clone, Copy, Debug, Default, Hash)] pub struct Rev<T: PartialOrd>(pub T); impl_cmp!(Rev<T>; |a, b| b.0.partial_cmp(&a.0).unwrap(); where T: PartialOrd);
true
9aeaa9e2198efdef8bea822ecf92cb972e4fa2ec
Rust
nylar/java-parser
/src/parser.rs
UTF-8
5,567
2.546875
3
[]
no_license
use super::{AccessModifier, Annotation, Class, CompilationUnit, Field, FieldType, Import, Method}; use nom::multispace; fn is_word(b: u8) -> bool { match b { b'a'...b'z' | b'A'...b'Z' | b'0'...b'9' | b'.' => true, _ => false, } } named!( word<String>, map_res!(take_while!(is_word), |b: &[u8]| String::from_utf8( b.to_vec() )) ); named!( comment<()>, do_parse!(tag!("//") >> take_until_and_consume!("\n") >> ()) ); named!( block_comment<()>, do_parse!(tag!("/*") >> take_until_and_consume!("*/") >> ()) ); named!( br<()>, alt!(map!(multispace, |_| ()) | comment | block_comment) ); named!( import<String>, do_parse!(tag!("import") >> many1!(br) >> import: word >> many0!(br) >> tag!(";") >> (import)) ); named!( field_type<FieldType>, alt!(tag!("String") => { |_| FieldType::String } | tag!("Boolean") => { |_| FieldType::Boolean } | tag!("boolean") => { |_| FieldType::Boolean } | tag!("long") => { |_| FieldType::Long } | tag!("Long") => { |_| FieldType::Long } | tag!("int") => { |_| FieldType::Int } | tag!("Integer") => { |_| FieldType::Int } | tag!("short") => { |_| FieldType::Short } | word => { |w| FieldType::Type(w) }) ); named!( access_modifier<AccessModifier>, alt!(tag!("public") => { |_| AccessModifier::Public } | tag!("protected") => { |_| AccessModifier::Protected } | tag!("private") => { |_| AccessModifier::Private }) ); named!( package<String>, do_parse!( tag!("package") >> many1!(br) >> package: word >> many0!(br) >> tag!(";") >> (package) ) ); named!( annotation<Annotation>, do_parse!( tag!("@") >> name: word >> tag!("(") >> options: take_until!(")") >> tag!(")") >> (Annotation { name: name, options: String::from_utf8_lossy(&options.to_vec()).to_string(), }) ) ); named!( method<Method>, do_parse!( access_modifier: opt!(access_modifier) >> many1!(br) >> typ: field_type >> many1!(br) >> name: word >> tag!("(") >> arguments: take_until!(")") >> tag!(")") >> many0!(br) >> tag!("{") >> take_until!("}") >> tag!("}") >> (Method { name: name, return_type: typ, arguments: String::from_utf8_lossy(&arguments.to_vec()).to_string(), access_modifier: access_modifier, }) ) ); named!( class_field<Field>, do_parse!( access_modifier: opt!(access_modifier) >> many1!(br) >> typ: field_type >> many1!(br) >> name: word >> many0!(br) >> tag!(";") >> (Field { name: name, field_type: typ, access_modifier: access_modifier, }) ) ); enum ClassEvent { Field(Field), Method(Method), Annotation(Annotation), Ignore, } named!( class_event<ClassEvent>, alt!(class_field => { |f| ClassEvent::Field(f) } | method => { |m| ClassEvent::Method(m) } | annotation => { |a| ClassEvent::Annotation(a) } | br => { |_| ClassEvent::Ignore }) ); named!( class_events<(String, Vec<ClassEvent>, Option<AccessModifier>)>, do_parse!( access_modifier: opt!(access_modifier) >> many0!(br) >> tag!("class") >> many1!(br) >> name: word >> many0!(br) >> tag!("{") >> many0!(br) >> events: many0!(class_event) >> many0!(br) >> tag!("}") >> many0!(br) >> many0!(tag!(";")) >> ((name, events, access_modifier)) ) ); named!( class<Class>, map!( class_events, |(name, events, access_modifier): (String, Vec<ClassEvent>, Option<AccessModifier>)| { let mut class = Class { name: name.to_owned(), fields: Vec::new(), methods: Vec::new(), access_modifier: access_modifier, annotations: Vec::new(), }; for event in events { match event { ClassEvent::Field(f) => class.fields.push(f), ClassEvent::Method(m) => class.methods.push(m), ClassEvent::Annotation(a) => class.annotations.push(a), ClassEvent::Ignore => (), } } class } ) ); enum Event { Package(String), Import(String), Annotation(Annotation), Class(Class), Ignore, } named!( event<Event>, alt!( package => { |p| Event::Package(p) } | import => { |i| Event::Import(i) } | class => { |c| Event::Class(c) } | annotation => { |a| Event::Annotation(a) } | br => { |_| Event::Ignore } ) ); named!(pub compilation_unit<CompilationUnit>, map!(many0!(event), |events: Vec<Event>| { let mut cu = CompilationUnit::new(); for event in events { match event { Event::Package(p) => cu.package = Some(p), Event::Import(i) => cu.imports.push(Import { path: i }), Event::Class(c) => cu.classes.push(c), Event::Annotation(a) => cu.annotations.push(a), Event::Ignore => (), } } cu }));
true
7f4780e0bee35ec775214db82d33be3286201cc9
Rust
mbillingr/miniKANREN
/rust-canonical/src/database.rs
UTF-8
2,241
3.203125
3
[ "MIT" ]
permissive
//! A simple relational database use crate::core::value::Value; use std::collections::HashMap; pub struct Database { db: HashMap<String, Vec<Vec<Value>>>, default_table: Vec<Vec<Value>>, } impl Database { pub fn new() -> Self { Database { db: HashMap::new(), default_table: vec![], } } pub fn insert(&mut self, table_name: &str, row: Vec<Value>) { if let Some(table) = self.db.get_mut(table_name) { table.push(row) } else { self.db.insert(table_name.to_string(), vec![row]); } } pub fn query( &self, table_name: &str, ) -> impl Iterator<Item = impl Iterator<Item = &Value> + '_> + '_ { let table = self.db.get(table_name).unwrap_or(&self.default_table); table.into_iter().map(|row| row.into_iter()) } } /// Defines a database relation. /// /// The macro produces a goal-generating function, which can be used /// to query the database. #[macro_export] macro_rules! db_rel { ($($rel:ident($($args:ident),*));* $(;)?) => { $( /// Creates a goal that succeeds if the relation is consistent with the database. fn $rel(db: &Arc<$crate::database::Database>, $($args: impl Into<$crate::prelude::Value>),*) -> impl Clone + $crate::prelude::Goal<$crate::prelude::Substitution<'static>> { let db = db.clone(); $(let $args = $args.into();)* move |s: $crate::prelude::Substitution<'static>| { let values = db.query(stringify!($rel)); let subs = values .filter_map(|mut value| { let s = s.clone(); $(let s = s.unify(&$args, value.next()?)?;)* Some(s) }); $crate::prelude::Stream::from_iter(subs) } } )* }; } /// Insert facts into databases. #[macro_export] macro_rules! db_facts { ($($db:ident { $($rel:ident($($args:expr),*));* $(;)? })*) => { $( $( $db.insert(stringify!($rel), vec![$($crate::prelude::Value::new($args)),*]); )* )* }; }
true
aacf8d8ae624ee4dbee23157de1b11d821cbbd9f
Rust
BurntSushi/ripgrep
/crates/matcher/tests/util.rs
UTF-8
2,490
2.796875
3
[ "MIT", "Unlicense" ]
permissive
use std::collections::HashMap; use std::result; use grep_matcher::{Captures, Match, Matcher, NoCaptures, NoError}; use regex::bytes::{CaptureLocations, Regex}; #[derive(Debug)] pub struct RegexMatcher { pub re: Regex, pub names: HashMap<String, usize>, } impl RegexMatcher { pub fn new(re: Regex) -> RegexMatcher { let mut names = HashMap::new(); for (i, optional_name) in re.capture_names().enumerate() { if let Some(name) = optional_name { names.insert(name.to_string(), i); } } RegexMatcher { re: re, names: names } } } type Result<T> = result::Result<T, NoError>; impl Matcher for RegexMatcher { type Captures = RegexCaptures; type Error = NoError; fn find_at(&self, haystack: &[u8], at: usize) -> Result<Option<Match>> { Ok(self .re .find_at(haystack, at) .map(|m| Match::new(m.start(), m.end()))) } fn new_captures(&self) -> Result<RegexCaptures> { Ok(RegexCaptures(self.re.capture_locations())) } fn captures_at( &self, haystack: &[u8], at: usize, caps: &mut RegexCaptures, ) -> Result<bool> { Ok(self.re.captures_read_at(&mut caps.0, haystack, at).is_some()) } fn capture_count(&self) -> usize { self.re.captures_len() } fn capture_index(&self, name: &str) -> Option<usize> { self.names.get(name).map(|i| *i) } // We purposely don't implement any other methods, so that we test the // default impls. The "real" Regex impl for Matcher provides a few more // impls. e.g., Its `find_iter` impl is faster than what we can do here, // since the regex crate avoids synchronization overhead. } #[derive(Debug)] pub struct RegexMatcherNoCaps(pub Regex); impl Matcher for RegexMatcherNoCaps { type Captures = NoCaptures; type Error = NoError; fn find_at(&self, haystack: &[u8], at: usize) -> Result<Option<Match>> { Ok(self .0 .find_at(haystack, at) .map(|m| Match::new(m.start(), m.end()))) } fn new_captures(&self) -> Result<NoCaptures> { Ok(NoCaptures::new()) } } #[derive(Clone, Debug)] pub struct RegexCaptures(CaptureLocations); impl Captures for RegexCaptures { fn len(&self) -> usize { self.0.len() } fn get(&self, i: usize) -> Option<Match> { self.0.pos(i).map(|(s, e)| Match::new(s, e)) } }
true
b6f8afdc42a405e9d619f19c920aea5e3e9e9728
Rust
YuriMalinov/rlox
/src/main.rs
UTF-8
976
2.84375
3
[]
no_license
use std::env; use std::fs; use std::io; use std::io::Write; use std::process::exit; use rlox::Scanner; use crate::rlox::StdErrErrorHandler; mod rlox; fn main() { let args: Vec<String> = env::args().collect(); if args.len() > 2 { println!("Usage: rlox [script]"); exit(64); } else if args.len() == 2 { run_file(&args[1]); } else { run_prompt(); } } fn run_file(file_name: &str) { println!("Reading {}", file_name); let data = fs::read_to_string(file_name).unwrap(); run(&data); } fn run_prompt() { let input = io::stdin(); let mut line = String::new(); loop { print!("> "); io::stdout().flush().unwrap(); input.read_line(&mut line).unwrap(); run(&line); } } fn run(program: &str) { let mut scanner = Scanner::new(program, &StdErrErrorHandler {}); let tokens = scanner.scan_tokens(); for token in tokens { println!("{:?}", token); } }
true
282a79c9d0170ee5945b99c11161f03ea7b725e8
Rust
indragiek/advent-of-code-2020
/day16part2/src/main.rs
UTF-8
4,597
2.921875
3
[ "MIT" ]
permissive
use std::collections::HashSet; use std::env; use std::fs::File; use std::io::{self, BufRead}; #[macro_use] extern crate lazy_static; extern crate regex; use regex::Regex; enum ParseStage { Rules, YourTicket, NearbyTickets, } fn main() { let args: Vec<String> = env::args().collect(); let filename = &args[1]; let file = File::open(filename).unwrap(); let mut stage = ParseStage::Rules; let mut rules = Vec::new(); let mut your_ticket = Vec::new(); let mut nearby_tickets = Vec::new(); io::BufReader::new(file) .lines() .map(|line| line.unwrap()) .for_each(|line| match line.as_str() { "" => {} "your ticket:" => stage = ParseStage::YourTicket, "nearby tickets:" => stage = ParseStage::NearbyTickets, l => match &stage { ParseStage::Rules => rules.push(parse_rule(&l).unwrap()), ParseStage::YourTicket => your_ticket = parse_ticket(l), ParseStage::NearbyTickets => nearby_tickets.push(parse_ticket(l)), }, }); let num_fields = your_ticket.len(); let valid_tickets: Vec<Vec<u32>> = nearby_tickets .into_iter() .filter(|ticket| is_valid_ticket(ticket, &rules)) .collect(); let mut valid_rules: Vec<(usize, Vec<String>)> = (0..num_fields) .map(|i| -> (usize, Vec<u32>) { (i, valid_tickets.iter().map(|ticket| ticket[i]).collect()) }) .map(|(i, values)| -> (usize, Vec<String>) { ( i, rules .iter() .filter(|rule| { values .iter() .map(|&value| !rule.validate(value)) .filter(|&x| x) .count() == 0 }) .map(|rule| rule.field.clone()) .collect(), ) }) .collect(); valid_rules.sort_by(|a, b| a.1.len().partial_cmp(&b.1.len()).unwrap()); let mut claimed_fields = HashSet::new(); let field_assignments: Vec<(usize, String)> = valid_rules .iter() .map(|(i, fields)| -> (usize, String) { let available_fields: Vec<String> = fields .clone() .into_iter() .filter(|field| !claimed_fields.contains(field)) .collect(); ( i.clone(), match available_fields.len() { 1 => { let field = available_fields[0].clone(); claimed_fields.insert(field.clone()); field } _ => "<undefined>".to_string(), }, ) }) .collect(); let product: u64 = field_assignments .iter() .filter(|(_, field)| field.starts_with("departure")) .map(|&(i, _)| your_ticket[i] as u64) .product(); println!("{}", product); } struct Range { start: u32, end: u32, } struct Rule { field: String, ranges: Vec<Range>, } impl Rule { fn validate(&self, value: u32) -> bool { for r in &self.ranges { if value >= r.start && value <= r.end { return true; } } return false; } } fn parse_ticket(line: &str) -> Vec<u32> { return line.split(",").map(|s| s.parse::<u32>().unwrap()).collect(); } fn parse_rule(line: &str) -> Option<Rule> { lazy_static! { static ref RE: Regex = Regex::new(r"([\w\s]+): (\d+)-(\d+) or (\d+)-(\d+)").unwrap(); } let captures = RE.captures(line)?; return Some(Rule { field: captures.get(1)?.as_str().to_string(), ranges: vec![ Range { start: captures.get(2)?.as_str().parse::<u32>().ok()?, end: captures.get(3)?.as_str().parse::<u32>().ok()?, }, Range { start: captures.get(4)?.as_str().parse::<u32>().ok()?, end: captures.get(5)?.as_str().parse::<u32>().ok()?, }, ], }); } fn is_valid_ticket(ticket: &Vec<u32>, rules: &Vec<Rule>) -> bool { return ticket .iter() .map(|&field| { rules .iter() .map(|rule| rule.validate(field)) .filter(|&x| x) .count() }) .find(|&count| count == 0) .is_none(); }
true
b92948ca91930ffe188933038f549363dcb0c141
Rust
pvginkel/noisy
/src/gen/simplex.rs
UTF-8
12,187
2.734375
3
[ "Unlicense" ]
permissive
//! An implementation of [Simplex Noise] //! (https://en.wikipedia.org/wiki/Simplex_noise). //! //! Based on a speed-improved simplex noise algorithm for 2D, 3D and 4D in Java. //! Which is based on example code by Stefan Gustavson (stegu@itn.liu.se). //! With Optimisations by Peter Eastman (peastman@drizzle.stanford.edu). //! Better rank ordering method by Stefan Gustavson in 2012. use std::rand::{ Rng, XorShiftRng, weak_rng }; use utils::fast_floor; use utils::grad::{ grad1, grad2, grad3 }; use gen::NoiseGen; static F2: f64 = 0.366025403784_f64; static G2: f64 = 0.211324865405_f64; static F3: f64 = 0.333333333333_f64; static G3: f64 = 0.166666666667_f64; /// A simplex noise generator. #[derive(Clone, PartialEq, Eq)] pub struct Simplex { perm: Vec<u8> } impl Simplex { /// Initializes a new simplex instance with a random seed using XorShiftRng. /// /// # Example /// /// ```rust /// use noisy::gen::Simplex; /// /// let simplex = Simplex::new(); /// ``` pub fn new() -> Simplex { let mut rng: XorShiftRng = weak_rng(); let p: Vec<u8> = (0..256).map(|_| rng.gen::<u8>()).collect(); let perm: Vec<u8> = (0..512).map(|idx:i32| {p[(idx & 255) as usize]}).collect(); Simplex { perm: perm } } /// Initializes a new simplex instance with a random number generator. /// /// # Example /// /// ```rust /// # use std::rand::StdRng; /// use noisy::gen::Simplex; /// /// let mut rng: StdRng = StdRng::new().unwrap(); /// let simplex = Simplex::from_rng(&mut rng); /// ``` /// /// This also allows you to initialize the instance with a seed: /// /// # Example /// /// ```rust /// # use std::rand::{StdRng, SeedableRng}; /// use noisy::gen::Simplex; /// /// let seed: &[_] = &[1337]; /// let mut rng: StdRng = SeedableRng::from_seed(seed); /// let simplex = Simplex::from_rng(&mut rng); /// ``` pub fn from_rng<R: Rng>(rng: &mut R) -> Simplex { let p: Vec<u8> = (0..256).map(|_| rng.gen::<u8>()).collect(); let perm: Vec<u8> = (0..512).map(|idx:i32| {p[(idx & 255) as usize]}).collect(); Simplex { perm: perm } } } impl NoiseGen for Simplex { /// Given an x coordinate, return a value in the interval [-1, 1]. /// /// # Example /// /// ```rust /// use noisy::gen::{NoiseGen, Simplex}; /// /// let simplex = Simplex::new(); /// let val = simplex.noise1d(123.0 * 0.02); /// ``` #[allow(non_snake_case)] fn noise1d(&self, xin: f64) -> f64 { // Noise contributions let mut n0: f64; let mut n1: f64; let i0: i64 = fast_floor(xin); let i1: i64 = i0 + 1; let x0: f64 = xin - i0 as f64; let x1: f64 = x0 - 1.0; // Work out the hashed gradient indices let gi0: u8 = self.perm[(i0 & 255) as usize] as u8; let gi1: u8 = self.perm[(i1 & 255) as usize] as u8; // Calculate the contributions let mut t0: f64 = 1.0 - x0 * x0; t0 *= t0; n0 = t0 * t0 * grad1(gi0, x0); let mut t1: f64 = 1.0 - x1 * x1; t1 *= t1; n1 = t1 * t1 * grad1(gi1, x1); // The maximum value of this noise is 8*(3/4)^4 = 2.53125. // A factor of 0.395 scales to fit exactly within [-1,1]. 0.395 * (n0 + n1) } /// Given a (x, y) coordinate, return a value in the interval [-1, 1]. /// /// # Example /// /// ```rust /// use noisy::gen::{NoiseGen, Simplex}; /// /// let simplex = Simplex::new(); /// let val = simplex.noise2d( /// 123.0 * 0.02, /// 132.0 * 0.02 /// ); /// ``` #[allow(non_snake_case)] fn noise2d(&self, xin: f64, yin: f64) -> f64 { // Noise contributions from the three corners let mut n0: f64; let mut n1: f64; let mut n2: f64; // Skew the input space to determine which simplex cell we're in let s: f64 = (xin + yin) * F2; // Hairy factor for 2D let i: i64 = fast_floor(xin + s); let j: i64 = fast_floor(yin + s); let t: f64 = ((i + j) as f64) * G2; // Unskew the cell origin back to (x, y) space let X0: f64 = (i as f64) - t; let Y0: f64 = (j as f64) - t; // The x and y distances from the cell origin let x0: f64 = xin - X0; let y0: f64 = yin - Y0; // For the 2D case, the simplex shape is an equilateral triangle. // Determine which shape we are in. let i1: usize; // Offsets for second (middle) corner of simplex in (i, j) coords let j1: usize; if x0 > y0 { // Lower triangle, XY order: (0, 0) -> (1, 0) -> (1, 1) i1 = 1; j1 = 0; } else { // Upper triangle, YX order: (0, 0) -> (0, 1) -> (1, 1) i1 = 0; j1 = 1; } // A step of (1, 0) in (i, j) means a step of (1 - c, -c) in (x, y), and // a step of (0, 1) in (i, j) means a step of (-c, 1 - c) in (x, y), where // c = (3 - sqrt(3.0))/6. // Offsets for middle corner in (x,y) unskewed coords let x1: f64 = x0 - (i1 as f64) + G2; let y1: f64 = y0 - (j1 as f64) + G2; // Offsets for last corner in (x,y) unskewed coords let x2: f64 = x0 - 1.0 + 2.0 * G2; let y2: f64 = y0 - 1.0 + 2.0 * G2; // Wrap the integer indices at 256, to avoid indexing perm[] out of bounds let ii: usize = (i & 255) as usize; let jj: usize = (j & 255) as usize; // Work out the hashed gradient indices of the three simplex corners let gi0: u8 = self.perm[ii + self.perm[jj] as usize] as u8; let gi1: u8 = self.perm[ii + i1 + (self.perm[jj + j1] as usize)] as u8; let gi2: u8 = self.perm[ii + 1 + (self.perm[jj + 1] as usize)] as u8; // Calculate the contribution from the three corners let mut t0: f64 = 0.5 - x0 * x0 - y0 * y0; if t0 < 0.0 { n0 = 0.0; } else { t0 *= t0; n0 = t0 * t0 * grad2(gi0, x0, y0); } let mut t1: f64 = 0.5 - x1 * x1 - y1 * y1; if t1 < 0.0 { n1 = 0.0; } else { t1 *= t1; n1 = t1 * t1 * grad2(gi1, x1, y1); } let mut t2: f64 = 0.5 - x2 * x2 - y2 * y2; if t2 < 0.0 { n2 = 0.0; } else { t2 *= t2; n2 = t2 * t2 * grad2(gi2, x2, y2); } // Add contributions from each corner to get the final noise value. // The result is scaled to return values in the interval [-1, 1]. 40.0 * (n0 + n1 + n2) } /// Given a (x, y, z) coordinate, return a value in the interval [-1, 1]. /// /// # Example /// /// ```rust /// use noisy::gen::{NoiseGen, Simplex}; /// /// let simplex = Simplex::new(); /// let val = simplex.noise3d( /// 123.0 * 0.02, /// 231.0 * 0.02, /// 321.0 * 0.02 /// ); /// ``` #[allow(non_snake_case)] fn noise3d(&self, xin: f64, yin: f64, zin: f64) -> f64 { // Noise contributions from the four corners let mut n0: f64; let mut n1: f64; let mut n2: f64; let mut n3: f64; // Skew the input space to determine which simplex cell we're in let s: f64 = (xin + yin + zin) * F3; // Very nice and simple skew factor for 3D let i: i64 = fast_floor(xin + s); let j: i64 = fast_floor(yin + s); let k: i64 = fast_floor(zin + s); let t: f64 = ((i + j + k) as f64) * G3; // Unskew the cell origin back to (x, y, z) space let X0: f64 = (i as f64) - t; let Y0: f64 = (j as f64) - t; let Z0: f64 = (k as f64) - t; // The x, y, and distances from the cell origin let x0: f64 = xin - X0; let y0: f64 = yin - Y0; let z0: f64 = zin - Z0; // For the 3D case, the simplex shape is a slightly irregular tetrahedron. // Determine which simplex we are in. let i1: usize; // Offsets for second corner of simplex in (i, j, k) coords let j1: usize; let k1: usize; let i2: usize; // Offsets for third corner of simplex in (i, j, k) coords let j2: usize; let k2: usize; if x0 >= y0 { if y0 >= z0 { // X Y Z order i1 = 1; j1 = 0; k1 = 0; i2 = 1; j2 = 1; k2 = 0; } else if x0 >= z0 { // X Z Y order i1 = 1; j1 = 0; k1 = 0; i2 = 1; j2 = 0; k2 = 1; } else { // Z X Y order i1 = 0; j1 = 0; k1 = 1; i2 = 1; j2 = 0; k2 = 1; } } else { // x0 < y0 if y0 < z0 { // Z Y X order i1 = 0; j1 = 0; k1 = 1; i2 = 0; j2 = 1; k2 = 1; } else if x0 < z0 { // Y Z X order i1 = 0; j1 = 1; k1 = 0; i2 = 0; j2 = 1; k2 = 1; } else { // Y X Z order i1 = 0; j1 = 1; k1 = 0; i2 = 1; j2 = 1; k2 = 0; } } // A step of (1, 0, 0) in (i, j, k) means a step of (1 - c, -c, -c) in (x, y, z), // a step of (0, 1, 0) in (i, j, k) means a step of (-c, 1 - c, -c) in (x, y, z), and // a step of (0, 0, 1) in (i, j, k) means a step of (-c, -c, 1 - c) in (x, y, z), where // c = 1/6. // Offsets for second corner in (x, y, z) coords let x1: f64 = x0 - (i1 as f64) + G3; let y1: f64 = y0 - (j1 as f64) + G3; let z1: f64 = z0 - (k1 as f64) + G3; // Offsets for third corner in (x, y, z) coords let x2: f64 = x0 - (i2 as f64) + 2.0 * G3; let y2: f64 = y0 - (j2 as f64) + 2.0 * G3; let z2: f64 = z0 - (k2 as f64) + 2.0 * G3; // Offsets for last corner in (x, y, z) coords let x3: f64 = x0 - 1.0 + 3.0 * G3; let y3: f64 = y0 - 1.0 + 3.0 * G3; let z3: f64 = z0 - 1.0 + 3.0 * G3; // Wrap the integer indices at 256, to avoid indexing perm[] out of bounds let ii: usize = (i & 255) as usize; let jj: usize = (j & 255) as usize; let kk: usize = (k & 255) as usize; // Work out the hashed gradient indices of the four simplex corners let gi0: u8 = self.perm[ii + (self.perm[jj + (self.perm[kk] as usize)] as usize)] as u8; let gi1: u8 = self.perm[ii + i1 + (self.perm[jj + j1 + (self.perm[kk + k1] as usize)] as usize)] as u8; let gi2: u8 = self.perm[ii + i2 + (self.perm[jj + j2 + (self.perm[kk + k2] as usize)] as usize)] as u8; let gi3: u8 = self.perm[ii + 1 + (self.perm[jj + 1 + (self.perm[kk + 1] as usize)] as usize)] as u8; // Calculate the contribution from the four corners let mut t0: f64 = 0.6 - x0 * x0 - y0 * y0 - z0 * z0; if t0 < 0.0 { n0 = 0.0; } else { t0 *= t0; n0 = t0 * t0 * grad3(gi0, x0, y0, z0); } let mut t1: f64 = 0.6 - x1 * x1 - y1 * y1 - z1 * z1; if t1 < 0.0 { n1 = 0.0; } else { t1 *= t1; n1 = t1 * t1 * grad3(gi1, x1, y1, z1); } let mut t2: f64 = 0.6 - x2 * x2 - y2 * y2 - z2 * z2; if t2 < 0.0 { n2 = 0.0; } else { t2 *= t2; n2 = t2 * t2 * grad3(gi2, x2, y2, z2); } let mut t3: f64 = 0.6 - x3 * x3 - y3 * y3 - z3 * z3; if t3 < 0.0 { n3 = 0.0; } else { t3 *= t3; n3 = t3 * t3 * grad3(gi3, x3, y3, z3); } // Add contributions from each corner to get the final noise value. // The result is scaled to return values in the interval [-1,1]. 32.0 * (n0 + n1 + n2 + n3) } }
true
020f0d1300b1ebb11077c8d686a2e47616b0a4c4
Rust
ChylerDev/BAE
/src/utils/mono_resampler.rs
UTF-8
3,044
3.421875
3
[ "MIT" ]
permissive
//! # MonoResampler //! //! Trans codes the given audio signal from it's source sampling rate to the //! sampling rate BAE runs at. use super::*; use sample_format::{SampleFormat, MonoTrackT}; /// Type used for fractional indexing. type IndexT = SampleT; /// Struct tracking all of the data required for resampling, with some extra /// features like playback speed and looping. pub struct MonoResampler { data: MonoTrackT, ind: IndexT, inc: SampleT, speed: MathT, loop_start: usize, loop_end: usize, } impl MonoResampler { /// Creates a new MonoResampler object. /// /// # Parameters /// /// * `data` - The track containing the original audio data to resample. /// * `source_sample_rate` - The sample rate the original data was recorded at. /// * `loop_start` - The start point of looping. /// * `loop_end` - The end point of looping. If this value is 0, no looping is assumed. /// /// If `loop_end` is less than `loop_start`, they are swapped. pub fn new(data:MonoTrackT, source_sample_rate: MathT, mut loop_start: usize, mut loop_end: usize) -> Self { if loop_end < loop_start { std::mem::swap(&mut loop_start, &mut loop_end); } MonoResampler { data, ind: 0.0, inc: (source_sample_rate as MathT * INV_SAMPLE_RATE) as SampleT, speed: 1.0, loop_start, loop_end, } } /// Sets the playback speed. pub fn set_playback_speed(&mut self, speed: MathT) { self.speed = speed; } /// Returns the playback speed. pub fn get_playback_speed(&self) -> MathT { self.speed } /// Calculates and returns the next sample. pub fn process(&mut self) -> SampleT { if self.ind as usize >= self.data.len() && self.loop_end == 0 { return SampleT::default(); } let p1: SampleT = if self.ind.trunc() as usize + 1 >= self.data.len() && self.loop_end != 0 { self.data[(self.ind - (self.loop_end - self.loop_start) as IndexT) as usize].into_sample() } else if self.ind.trunc() as usize + 1 >= self.data.len() { self.data[self.ind.trunc() as usize].into_sample() } else { self.data[(self.ind + 1.0).trunc() as usize].into_sample() }; let x1: SampleT = self.data[self.ind.trunc() as usize].into_sample(); let x2: SampleT = p1; let y = x1 + self.ind.fract() as SampleT * (x2 - x1); self.ind += self.inc * self.speed as SampleT; if self.ind >= self.loop_end as IndexT && self.loop_end != 0 { self.ind -= (self.loop_end - self.loop_start) as IndexT; } y } } impl Clone for MonoResampler { fn clone(&self) -> Self { MonoResampler { data: self.data.clone(), ind: 0.0, inc: self.inc, speed: self.speed, loop_start: self.loop_start, loop_end: self.loop_end, } } }
true
8df087eba5eaaf3909e4822617d92bc0a19bbb41
Rust
zoewithabang/zerotube
/backend/src/services/passwords.rs
UTF-8
772
2.671875
3
[]
no_license
use crate::messages::error::ErrorResponse; use argon2rs::verifier::Encoded; use rand::RngCore; pub fn compare_password(raw_password: &str, hashed_password: &str) -> Result<bool, ErrorResponse> { let encoded = Encoded::from_u8(hashed_password.as_bytes()).map_err(|_| { log::error!("Unable to reconstruct hash session for {}", hashed_password); ErrorResponse::InternalServerError })?; Ok(encoded.verify(raw_password.as_bytes())) } pub fn hash_password(password: &str) -> Result<String, ErrorResponse> { let salt = format!("{:X}", rand::thread_rng().next_u64()); let encoded = Encoded::default2i(password.as_bytes(), salt.as_bytes(), &[], &[]); String::from_utf8(encoded.to_u8()).map_err(|_| ErrorResponse::InternalServerError) }
true
e42da0cddca1227067733fe21c678041f10a2ddf
Rust
sampersand/quest
/parser/src/token/token.rs
UTF-8
3,512
3.328125
3
[ "MIT" ]
permissive
use crate::Result; use crate::stream::Stream; use crate::token::{ParenType, Operator, Primitive, Tokenizable}; use std::fmt::{self, Display, Formatter}; #[derive(Debug, PartialEq, Eq, Clone)] pub enum Token { Primitive(Primitive), Operator(Operator), Left(ParenType), Right(ParenType), Endline(bool), // whether or not it's a hard endline Comma } impl Display for Token { fn fmt(&self, f: &mut Formatter) -> fmt::Result { match self { Self::Primitive(p) => Display::fmt(p, f), Self::Operator(o) => Display::fmt(o, f), Self::Left(t) => Display::fmt(&t.left(), f), Self::Right(t) => Display::fmt(&t.right(), f), Self::Endline(true) => Display::fmt(&';', f), Self::Endline(false) => Display::fmt(&"\\n", f), Self::Comma => Display::fmt(&',', f), } } } /// parse whitespace that's not relevant. fn parse_whitespace<S: Stream>(stream: &mut S) -> Result<bool> { match stream.next().transpose()? { // Some('\n') => return Ok(true), Some(chr) if chr.is_whitespace() => while let Some(chr) = stream.next().transpose()? { if !chr.is_whitespace() { unseek_char!(stream; chr); return Ok(false); } }, Some(chr) => unseek_char!(stream; chr), None => {} } Ok(false) } enum CommentResult { NoCommentFound, CommentRemoved, StopParsing } fn parse_comment<S: Stream>(stream: &mut S) -> Result<CommentResult> { fn parse_line<S: Stream>(stream: &mut S) -> Result<()> { while let Some(chr) = stream.next().transpose()? { if chr == '\n' { break; } } Ok(()) } fn parse_block<S: Stream>(stream: &mut S) -> Result<()> { let begin_context = stream.context().clone(); while let Some(chr) = stream.next().transpose()? { match chr { // end of line '*' if stream.next().transpose()? == Some('/') => return Ok(()), // allow for nested block comments '/' if stream.next().transpose()? == Some('*') => parse_block(stream)?, _ => { /* do nothing, we ignore other characters */ } } } Err(parse_error!(context=begin_context, UnterminatedBlockComment)) } if stream.starts_with("##__EOF__##")? { Ok(CommentResult::StopParsing) } else if stream.starts_with("#")? { parse_line(stream).and(Ok(CommentResult::CommentRemoved)) } else if stream.next_if_starts_with("/*")? { parse_block(stream).and(Ok(CommentResult::CommentRemoved)) } else { Ok(CommentResult::NoCommentFound) } } impl Token { pub fn try_parse<S: Stream>(stream: &mut S) -> Result<Option<Self>> { if parse_whitespace(stream)? { // do nothing // return Ok(Some(Self::Endline(false))); } match parse_comment(stream)? { CommentResult::StopParsing => return Ok(None), CommentResult::CommentRemoved => return Self::try_parse(stream), CommentResult::NoCommentFound => {} } if let Some(prim) = Primitive::try_tokenize(stream)? { return Ok(Some(prim.into())) } else if let Some(op) = Operator::try_tokenize(stream)? { return Ok(Some(op.into())) } match stream.next().transpose()? { Some(';') => Ok(Some(Self::Endline(true))), Some(',') => Ok(Some(Self::Comma)), Some('(') => Ok(Some(Self::Left(ParenType::Round))), Some(')') => Ok(Some(Self::Right(ParenType::Round))), Some('[') => Ok(Some(Self::Left(ParenType::Square))), Some(']') => Ok(Some(Self::Right(ParenType::Square))), Some('{') => Ok(Some(Self::Left(ParenType::Curly))), Some('}') => Ok(Some(Self::Right(ParenType::Curly))), Some(chr) => Err(parse_error!(stream, UnknownTokenStart(chr))), None => Ok(None) } } }
true
d8b941fde399250ddd55f0f2572a2a3caf283549
Rust
Pyxxil/tech-interview-as-a-service
/src/traits/help.rs
UTF-8
323
2.78125
3
[ "MIT" ]
permissive
use serde::Serialize; pub trait Help { fn help_message() -> String; } impl<T: Serialize + Default> Help for T { fn help_message() -> String { format!( "Help: Try sending a JSON body with the following:\n{}\n", serde_json::to_string_pretty(&T::default()).unwrap() ) } }
true
f902731a34fd9bd7e619911ca2f185b0c1b02710
Rust
timglabisch/rustinvoice
/src/entity/invoice.rs
UTF-8
954
2.90625
3
[]
no_license
use entity::address::Address; use std::default::Default; #[derive(Serialize, Deserialize, Default, Debug, Clone)] pub struct Invoices { pub items : Vec<Invoice> } #[derive(Serialize, Deserialize, Default, Debug, Clone)] pub struct Invoice { #[serde(default)] pub short_name : String, #[serde(default)] pub project : String, #[serde(default)] pub shortcut : String, #[serde(default)] pub info : String, #[serde(default)] pub date : String, #[serde(default)] pub description : String, pub address : Address, pub items : Vec<InvoiceItem> } #[derive(Serialize, Deserialize, Debug, Clone)] pub struct InvoiceItem { #[serde(default)] pub quantity : i32, #[serde(default)] pub text : String, #[serde(default)] pub cost : i32 } impl Default for InvoiceItem { fn default() -> Self { InvoiceItem { quantity: 1, text: String::new(), cost: 0 } } }
true
eea992c960069d0e94110f555f9947b1dba8ea39
Rust
grogers0/advent_of_code
/2016/day19/src/main.rs
UTF-8
1,670
3.578125
4
[ "MIT" ]
permissive
use std::io::{self, Read}; use linked_list::{LinkedList, Cursor}; fn next_circular(cursor: &mut Cursor<usize>) -> usize { if let Some(elem) = cursor.next() { *elem } else { *cursor.next().unwrap() } } fn remove_circular(cursor: &mut Cursor<usize>) -> usize { if let Some(elem) = cursor.remove() { elem } else { cursor.next(); cursor.remove().unwrap() } } fn build_circle(num_elems: usize) -> LinkedList<usize> { let mut circle = LinkedList::new(); for i in 1..=num_elems { circle.push_back(i); } circle } fn part1(starting_cnt: usize) -> usize { let mut circle = build_circle(starting_cnt); let mut cur = circle.cursor(); next_circular(&mut cur); for _ in 1..starting_cnt { remove_circular(&mut cur); next_circular(&mut cur); } circle.pop_front().unwrap() } fn part2(starting_cnt: usize) -> usize { let mut circle = build_circle(starting_cnt); let mut cur = circle.cursor(); cur.seek_forward(starting_cnt/2); for i in 1..starting_cnt { remove_circular(&mut cur); if i % 2 == starting_cnt % 2 { next_circular(&mut cur); } } circle.pop_front().unwrap() } fn main() { let mut input = String::new(); io::stdin().read_to_string(&mut input).unwrap(); let starting_cnt = input.trim_end().parse().unwrap(); println!("{}", part1(starting_cnt)); println!("{}", part2(starting_cnt)); } #[cfg(test)] mod tests { use super::*; #[test] fn test_part1() { assert_eq!(part1(5), 3); } #[test] fn test_part2() { assert_eq!(part2(5), 2); } }
true
1919de1867a5222b2c89c7a6f6ae737f4c84ef38
Rust
brianduff/rust-playground
/src/threadfun.rs
UTF-8
692
3.125
3
[ "Apache-2.0" ]
permissive
use anyhow::Result; use std::sync::mpsc; use std::thread; pub struct Opt { pub project: Option<String> } impl Opt { pub fn options(&self) -> Options { match self.project { Some(ref p) => Options::Third(p.clone()), None => Options::First } } } pub enum Options { First, Second, Third(String), } pub struct Output { } pub fn get_latest(options: &Options) -> Output { Output {} } fn background_thing(options: Options) -> Result<Output> { let (tx, rx) = mpsc::channel(); let handle = thread::spawn(move || { let result = get_latest(&options); tx.send(result).unwrap(); }); handle.join().unwrap(); let result = rx.recv()?; Ok(result) }
true
788069f600ddda671e18d17d2d84fd5049d6b41e
Rust
JacobJohansen/psst
/psst-gui/src/data/config.rs
UTF-8
3,389
2.734375
3
[ "MIT" ]
permissive
use druid::{Data, Lens}; use platform_dirs::AppDirs; use psst_core::{ audio_player::PlaybackConfig, cache::mkdir_if_not_exists, connection::Credentials, }; use serde::{Deserialize, Serialize}; use std::{fs::File, path::PathBuf}; #[derive(Clone, Copy, Debug, Eq, PartialEq, Data)] pub enum PreferencesTab { General, Cache, } #[derive(Clone, Debug, Data, Lens)] pub struct Preferences { pub active: PreferencesTab, pub cache_size: Option<u64>, } impl Preferences { pub fn measure_cache_usage() -> Option<u64> { Config::cache_dir().and_then(|path| fs_extra::dir::get_size(&path).ok()) } } const APP_NAME: &str = "Psst"; const CONFIG_FILENAME: &str = "config.json"; #[derive(Clone, Debug, Default, Data, Lens, Serialize, Deserialize)] #[serde(default)] pub struct Config { pub username: String, pub password: String, pub audio_quality: AudioQuality, pub theme: Theme, } impl Config { fn app_dirs() -> Option<AppDirs> { const USE_XDG_ON_MACOS: bool = false; AppDirs::new(Some(APP_NAME), USE_XDG_ON_MACOS) } pub fn cache_dir() -> Option<PathBuf> { Self::app_dirs().map(|dirs| dirs.cache_dir) } pub fn config_dir() -> Option<PathBuf> { Self::app_dirs().map(|dirs| dirs.config_dir) } fn config_path() -> Option<PathBuf> { Self::config_dir().map(|dir| dir.join(CONFIG_FILENAME)) } pub fn load() -> Option<Config> { let path = Self::config_path().expect("Failed to get config path"); if let Ok(file) = File::open(&path) { log::info!("loading config: {:?}", &path); Some(serde_json::from_reader(file).expect("Failed to read config")) } else { None } } pub fn save(&self) { let dir = Self::config_dir().expect("Failed to get config dir"); let path = Self::config_path().expect("Failed to get config path"); mkdir_if_not_exists(&dir).expect("Failed to create config dir"); let file = File::create(path).expect("Failed to create config"); serde_json::to_writer_pretty(file, self).expect("Failed to write config"); } pub fn has_credentials(&self) -> bool { !self.username.is_empty() && !self.password.is_empty() } pub fn credentials(&self) -> Option<Credentials> { if self.has_credentials() { Some(Credentials::from_username_and_password( self.username.to_owned(), self.password.to_owned(), )) } else { None } } pub fn playback(&self) -> PlaybackConfig { PlaybackConfig { bitrate: self.audio_quality.as_bitrate(), ..PlaybackConfig::default() } } } #[derive(Copy, Clone, Debug, Eq, PartialEq, Data, Serialize, Deserialize)] pub enum AudioQuality { Low, Normal, High, } impl AudioQuality { fn as_bitrate(self) -> usize { match self { AudioQuality::Low => 96, AudioQuality::Normal => 160, AudioQuality::High => 320, } } } impl Default for AudioQuality { fn default() -> Self { Self::High } } #[derive(Copy, Clone, Debug, Eq, PartialEq, Data, Serialize, Deserialize)] pub enum Theme { Light, Dark, } impl Default for Theme { fn default() -> Self { Self::Light } }
true
642cb5800b306ab5587b7087b4d930c07393e88a
Rust
uzzol101/mystore
/tests/product_test.rs
UTF-8
1,773
2.515625
3
[]
no_license
extern crate mystore; mod common; use mystore::model::product::{Person, Product, NewProduct}; use mystore::routes::product::{init_routes, test}; use common::db::establish_connection; use serde::{Deserialize, Serialize}; #[cfg(test)] mod tests { use super::*; use actix_web::{test, web, App}; #[actix_rt::test] async fn create_product() { let mut app = test::init_service( App::new() .data(establish_connection()) .configure(init_routes) ).await; let payload = NewProduct{ name: "test_product".to_string(), stock: 100.20, price: Some(400), }; let req = test::TestRequest::post() .uri("/products") .set_json(&payload) .to_request(); let resp: Product = test::read_response_json(&mut app, req).await; println!("create product resp {:?}", resp); assert_eq!(resp.name, "test_product"); } #[actix_rt::test] async fn get_product_list() { let mut app = test::init_service( App::new() .data(establish_connection()) .configure(init_routes), ) .await; let req = test::TestRequest::get().uri("/products").to_request(); let resp: Vec<Product> = test::read_response_json(&mut app, req).await; assert_eq!(resp.len(), 5); } }
true
0188003e078e101c749ed4eab9ba775301ad811d
Rust
pypaut/plants
/plants/src/iterate.rs
UTF-8
1,246
2.71875
3
[]
no_license
use crate::pattern; use crate::symbolstring::SymbolString; use crate::iter_ctx::{IterCtx, LightCtx}; use std::collections::HashMap; // Apply rules once from left to right on the given word. pub fn iterate(s : &SymbolString, ctx_list : &mut HashMap<String, IterCtx>) -> SymbolString { let mut result = SymbolString::empty(); let light_ctx : HashMap<String, LightCtx> = ctx_list.iter() .map(|(s, ctx)| -> (String, LightCtx) { (s.clone(), ctx.to_light_ctx()) }).collect(); for i in 0..s.len() { let mut found = false; match ctx_list.get_mut(&s.symbols[i].rule_set) { Some(ctx) => { //println!("{:?}", ctx); for p in ctx.patterns.iter_mut() { //println!("{:?}", p); if p.test(i, s, &light_ctx[&s.symbols[i].rule_set]) { result.push_str(&p.replacement); found = true; break; } }}, _ => { //println!("Could not find IterCtx: {}", &s.symbols[i].rule_set); } }; if !found { result.push(s.symbols[i].clone()) } } result }
true
52ef1baff42a0bc4b725087ab040f9b5b5476812
Rust
neodigm/foxbot
/src/handlers/channel_photo.rs
UTF-8
8,330
2.53125
3
[]
no_license
use async_trait::async_trait; use failure::ResultExt; use tgbotapi::{requests::*, *}; use super::Status::*; use crate::needs_field; use crate::utils::{find_best_photo, get_message, match_image}; pub struct ChannelPhotoHandler; #[async_trait] impl super::Handler for ChannelPhotoHandler { fn name(&self) -> &'static str { "channel" } async fn handle( &self, handler: &crate::MessageHandler, update: &Update, _command: Option<&Command>, ) -> failure::Fallible<super::Status> { // Ensure we have a channel_post Message and a photo within. let message = needs_field!(update, channel_post); let sizes = needs_field!(&message, photo); // We only want messages from channels. I think this is always true // because this came from a channel_post. if message.chat.chat_type != ChatType::Channel { return Ok(Ignored); } // We can't edit forwarded messages, so we have to ignore. if message.forward_date.is_some() { return Ok(Completed); } let matches = get_matches(&handler.bot, &handler.fapi, &handler.conn, &sizes) .await .context("unable to get matches")?; let first = match matches { Some(first) => first, _ => return Ok(Completed), }; // Ignore unlikely matches if first.distance.unwrap() > 3 { return Ok(Completed); } // If this link was already in the message, we can ignore it. if link_was_seen(&extract_links(&message, &handler.finder), &first.url) { return Ok(Completed); } // If this photo was part of a media group, we should set a caption on // the image because we can't make an inline keyboard on it. if message.media_group_id.is_some() { let edit_caption_markup = EditMessageCaption { chat_id: message.chat_id(), message_id: Some(message.message_id), caption: Some(first.url()), ..Default::default() }; handler .make_request(&edit_caption_markup) .await .context("unable to edit channel caption markup")?; // Not a media group, we should create an inline keyboard. } else { let text = handler .get_fluent_bundle(None, |bundle| { get_message(&bundle, "inline-source", None).unwrap() }) .await; let markup = InlineKeyboardMarkup { inline_keyboard: vec![vec![InlineKeyboardButton { text, url: Some(first.url()), ..Default::default() }]], }; let edit_reply_markup = EditMessageReplyMarkup { chat_id: message.chat_id(), message_id: Some(message.message_id), reply_markup: Some(ReplyMarkup::InlineKeyboardMarkup(markup)), ..Default::default() }; handler .make_request(&edit_reply_markup) .await .context("unable to edit channel reply markup")?; } Ok(Completed) } } /// Extract all possible links from a Message. It looks at the text, /// caption, and all buttons within an inline keyboard. pub fn extract_links<'m>( message: &'m Message, finder: &linkify::LinkFinder, ) -> Vec<linkify::Link<'m>> { let mut links = vec![]; // Unlikely to be text posts here, but we'll consider anyway. if let Some(ref text) = message.text { links.extend(finder.links(&text)); } // Links could be in an image caption. if let Some(ref caption) = message.caption { links.extend(finder.links(&caption)); } // See if it was posted with a bot that included an inline keyboard. if let Some(ref markup) = message.reply_markup { for row in &markup.inline_keyboard { for button in row { if let Some(url) = &button.url { links.extend(finder.links(&url)); } } } } // Possible there's links generated by bots (or users). if let Some(ref entities) = message.entities { for entity in entities { if entity.entity_type == MessageEntityType::TextLink { links.extend(finder.links(entity.url.as_ref().unwrap())); } } } if let Some(ref entities) = message.caption_entities { for entity in entities { if entity.entity_type == MessageEntityType::TextLink { links.extend(finder.links(entity.url.as_ref().unwrap())); } } } links } /// Check if a link was contained within a linkify Link. pub fn link_was_seen(links: &[linkify::Link], source: &str) -> bool { links.iter().any(|link| link.as_str() == source) } async fn get_matches( bot: &Telegram, fapi: &fuzzysearch::FuzzySearch, conn: &quaint::pooled::Quaint, sizes: &[PhotoSize], ) -> failure::Fallible<Option<fuzzysearch::File>> { // Find the highest resolution size of the image and download. let best_photo = find_best_photo(&sizes).unwrap(); let matches = match_image(&bot, &conn, &fapi, &best_photo).await?; Ok(matches.into_iter().next()) } #[cfg(test)] mod tests { fn get_finder() -> linkify::LinkFinder { let mut finder = linkify::LinkFinder::new(); finder.kinds(&[linkify::LinkKind::Url]); finder } #[test] fn test_find_links() { let finder = get_finder(); let expected_links = vec![ "https://syfaro.net", "https://huefox.com", "https://e621.net", "https://www.furaffinity.net", "https://www.weasyl.com", "https://furrynetwork.com", ]; let message = tgbotapi::Message { text: Some( "My message has a link like this: https://syfaro.net and some words after it." .into(), ), caption: Some("There can also be links in the caption: https://huefox.com".into()), reply_markup: Some(tgbotapi::InlineKeyboardMarkup { inline_keyboard: vec![ vec![tgbotapi::InlineKeyboardButton { url: Some("https://e621.net".into()), ..Default::default() }], vec![tgbotapi::InlineKeyboardButton { url: Some("https://www.furaffinity.net".into()), ..Default::default() }], ], }), entities: Some(vec![tgbotapi::MessageEntity { entity_type: tgbotapi::MessageEntityType::TextLink, offset: 0, length: 10, url: Some("https://www.weasyl.com".to_string()), user: None, }]), caption_entities: Some(vec![tgbotapi::MessageEntity { entity_type: tgbotapi::MessageEntityType::TextLink, offset: 11, length: 20, url: Some("https://furrynetwork.com".to_string()), user: None, }]), ..Default::default() }; let links = super::extract_links(&message, &finder); assert_eq!( links.len(), expected_links.len(), "found different number of links" ); for (link, expected) in links.iter().zip(expected_links.iter()) { assert_eq!(&link.as_str(), expected); } } #[test] fn test_link_was_seen() { let finder = get_finder(); let test = "https://www.furaffinity.net/"; let found_links = finder.links(&test); let mut links = vec![]; links.extend(found_links); assert!( super::link_was_seen(&links, "https://www.furaffinity.net/"), "seen link was not found" ); assert!( !super::link_was_seen(&links, "https://e621.net/"), "unseen link was found" ); } }
true
a32996cfc9dff62d82b88bfe720649a38af7a376
Rust
LibreTuner/LibreTuner-rs
/src/error.rs
UTF-8
1,534
2.71875
3
[]
no_license
use tuneutils; use std::{result, io, fmt}; #[derive(Debug)] pub enum Error { TuneUtils(tuneutils::error::Error), Io(io::Error), NoHome, #[cfg(feature = "cli")] InvalidCommand, #[cfg(feature = "cli")] Clap(clap::Error), InvalidPlatform, UnknownModel, InvalidDatalink, DownloadUnsupported, InvalidRom, } pub type Result<T> = result::Result<T, Error>; impl From<tuneutils::error::Error> for Error { fn from(err: tuneutils::error::Error) -> Error { Error::TuneUtils(err) } } impl From<io::Error> for Error { fn from(err: io::Error) -> Error { Error::Io(err) } } #[cfg(feature = "cli")] impl From<clap::Error> for Error { fn from(err: clap::Error) -> Error { Error::Clap(err) } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Error::TuneUtils(ref err) => write!(f, "TuneUtils error: {}", err), Error::NoHome => write!(f, "No valid home directory path could be retrieved from the operating system"), Error::Io(ref err) => write!(f, "IO error: {}", err), #[cfg(feature = "cli")] Error::InvalidCommand => write!(f, "Invalid command"), #[cfg(feature = "cli")] Error::Clap(ref err) => write!(f, "{}", err), Error::InvalidPlatform => write!(f, "Invalid platform"), Error::InvalidDatalink => write!(f, "Invalid datalink"), Error::DownloadUnsupported => write!(f, "Downloading unsupported for a datalink or platform"), Error::UnknownModel => write!(f, "Unknown model"), Error::InvalidRom => write!(f, "Invalid ROM"), } } }
true
d7343163b3f6e01756946ad4aa813a2e0c49d257
Rust
kimkanu/hyperbolic-minesweeper
/wasm/src/utils/math/coord.rs
UTF-8
5,741
3.328125
3
[]
no_license
use num_complex::Complex; use num_traits::{Float, Num, Zero}; #[derive(PartialEq, Eq, Copy, Clone, Hash, Debug, Default)] pub struct Normal<T = f64>(pub Complex<T>); #[derive(PartialEq, Eq, Copy, Clone, Hash, Debug, Default)] pub struct Poincare<T = f64> { pub norm: T, pub arg: T, } impl<T: Float + HaveConstants> Poincare<T> { pub fn new(norm: T, arg: T) -> Self { Poincare { norm, arg: arg.principal_arg(), } } } #[derive(PartialEq, Eq, Copy, Clone, Hash, Debug)] pub enum Coord<T> { Normal(Normal<T>), Poincare(Poincare<T>), } /// Define `zero` without add operation pub trait LiteralZero: Sized { /// Returns `0`. fn zero() -> Self; /// Sets `self` to the additive identity element of `Self`, `0`. fn set_zero(&mut self) { *self = Self::zero(); } /// Returns `true` if `self` is equal to the additive identity. fn is_zero(&self) -> bool; } impl<T: Clone + Num> LiteralZero for Normal<T> { fn zero() -> Self { Normal(Complex::zero()) } fn is_zero(&self) -> bool { self.0.is_zero() } } impl<T: Clone + Num> LiteralZero for Poincare<T> { fn zero() -> Self { Poincare { norm: T::zero(), arg: T::zero(), } } fn is_zero(&self) -> bool { self.norm.is_zero() && self.arg.is_zero() } } pub trait HaveConstants: Float { const ZERO: Self; const ONE: Self; const TWO: Self; const FOUR: Self; const EIGHT: Self; const SIXTEEN: Self; const PI: Self; const TWO_PI: Self; const FRAC_PI_2: Self; const FRAC_PI_3: Self; const FRAC_PI_4: Self; const FRAC_PI_6: Self; const FRAC_PI_8: Self; /// shift arg into (-π, π] fn principal_arg(&self) -> Self { let arg = self.clone(); if arg <= Self::PI && arg > Self::PI.neg() { arg } else { let one_half = Self::one() / (Self::one() + Self::one()); arg + (one_half - arg / Self::TWO_PI).floor() * Self::TWO_PI } } } impl HaveConstants for f32 { const ZERO: f32 = 0f32; const ONE: f32 = 1f32; const TWO: f32 = 2f32; const FOUR: f32 = 4f32; const EIGHT: f32 = 8f32; const SIXTEEN: f32 = 16f32; const PI: f32 = std::f32::consts::PI; const TWO_PI: f32 = 2f32 * std::f32::consts::PI; const FRAC_PI_2: f32 = std::f32::consts::FRAC_PI_2; const FRAC_PI_3: f32 = std::f32::consts::FRAC_PI_3; const FRAC_PI_4: f32 = std::f32::consts::FRAC_PI_4; const FRAC_PI_6: f32 = std::f32::consts::FRAC_PI_6; const FRAC_PI_8: f32 = std::f32::consts::FRAC_PI_8; } impl HaveConstants for f64 { const ZERO: f64 = 0f64; const ONE: f64 = 1f64; const TWO: f64 = 2f64; const FOUR: f64 = 4f64; const EIGHT: f64 = 8f64; const SIXTEEN: f64 = 16f64; const PI: f64 = std::f64::consts::PI; const TWO_PI: f64 = 2f64 * std::f64::consts::PI; const FRAC_PI_2: f64 = std::f64::consts::FRAC_PI_2; const FRAC_PI_3: f64 = std::f64::consts::FRAC_PI_3; const FRAC_PI_4: f64 = std::f64::consts::FRAC_PI_4; const FRAC_PI_6: f64 = std::f64::consts::FRAC_PI_6; const FRAC_PI_8: f64 = std::f64::consts::FRAC_PI_8; } /// Define `norm`, `arg`, `conj`, and `rotate` pub trait CoordOps: Sized { type Norm; type Angle; const PI: Self::Angle; /// Returns the norm of a coordinate, i.e., the distance from the origin. /// /// Be careful that the norm of `Normal` and `Poincare` are NOT compatible. fn norm(&self) -> Self::Norm; /// Returns the arg of a coordinate. fn arg(&self) -> Self::Angle; /// Returns the conjugation of a coordinate. (without mutating itself) fn conj(&self) -> Self; /// Returns e^(iθ) * self. (without mutating itself) fn rotate(&self, theta: Self::Angle) -> Self; /// Returns -self. (without mutating itself) fn neg(&self) -> Self { self.rotate(Self::PI) } } impl<T: Float + HaveConstants> CoordOps for Normal<T> { type Norm = T; type Angle = T; const PI: T = T::PI; fn norm(&self) -> Self::Norm { self.0.norm() } fn arg(&self) -> Self::Angle { self.0.arg() } fn conj(&self) -> Self { Self(self.0.conj()) } fn rotate(&self, theta: Self::Angle) -> Self { Self(self.0 * Complex::from_polar(T::one(), theta)) } } impl<T: Float + HaveConstants> CoordOps for Poincare<T> { type Norm = T; type Angle = T; const PI: T = T::PI; fn norm(&self) -> Self::Norm { self.norm } fn arg(&self) -> Self::Angle { self.arg } fn conj(&self) -> Self { Self::new(self.norm, self.arg.neg()) } fn rotate(&self, theta: Self::Angle) -> Self { Self::new(self.norm, self.arg + theta) } } impl<T: Float + HaveConstants> CoordOps for Coord<T> { type Norm = T; type Angle = T; const PI: T = T::PI; fn norm(&self) -> Self::Norm { match self { Self::Normal(inner) => inner.norm(), Self::Poincare(inner) => inner.norm(), } } fn arg(&self) -> Self::Angle { match self { Self::Normal(inner) => inner.arg(), Self::Poincare(inner) => inner.arg(), } } fn conj(&self) -> Self { match self { Self::Normal(inner) => Self::Normal(inner.conj()), Self::Poincare(inner) => Self::Poincare(inner.conj()), } } fn rotate(&self, theta: Self::Angle) -> Self { match self { Self::Normal(inner) => Self::Normal(inner.rotate(theta)), Self::Poincare(inner) => Self::Poincare(inner.rotate(theta)), } } }
true
a993a4ab05366aac6184330655c98634c0aed05f
Rust
rust-vmm/vmm-sys-util
/src/syscall.rs
UTF-8
1,776
3.125
3
[ "BSD-3-Clause" ]
permissive
// Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: BSD-3-Clause //! Wrapper for interpreting syscall exit codes. use std::os::raw::c_int; /// Wrapper to interpret syscall exit codes and provide a rustacean `io::Result`. #[derive(Debug)] pub struct SyscallReturnCode<T: From<i8> + Eq = c_int>(pub T); impl<T: From<i8> + Eq> SyscallReturnCode<T> { /// Returns the last OS error if value is -1 or Ok(value) otherwise. pub fn into_result(self) -> std::io::Result<T> { if self.0 == T::from(-1) { Err(std::io::Error::last_os_error()) } else { Ok(self.0) } } /// Returns the last OS error if value is -1 or Ok(()) otherwise. pub fn into_empty_result(self) -> std::io::Result<()> { self.into_result().map(|_| ()) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_syscall_ops() { let mut syscall_code = SyscallReturnCode(1); match syscall_code.into_result() { Ok(_value) => (), _ => unreachable!(), } syscall_code = SyscallReturnCode(-1); assert!(syscall_code.into_result().is_err()); syscall_code = SyscallReturnCode(1); match syscall_code.into_empty_result() { Ok(()) => (), _ => unreachable!(), } syscall_code = SyscallReturnCode(-1); assert!(syscall_code.into_empty_result().is_err()); let mut syscall_code_long = SyscallReturnCode(1i64); match syscall_code_long.into_result() { Ok(_value) => (), _ => unreachable!(), } syscall_code_long = SyscallReturnCode(-1i64); assert!(syscall_code_long.into_result().is_err()); } }
true
2365739101ede53beaaa8228780654c90a7aa73a
Rust
MozarellaMan/aylox-lang
/alox-bytecode/src/vm.rs
UTF-8
2,530
3.296875
3
[ "MIT" ]
permissive
use crate::{chunk::{Chunk, Value}, compiler, opcodes::Op}; const STACK_UNDERFLOW: &str = "Stack underflow!"; macro_rules! binary_op { ($self:ident,$operator:tt) => { { let b = $self.pop(); let a = $self.pop(); $self.push(a $operator b); } }; } pub type InterpreterResult = Result<(), InterpreterError>; pub struct Vm { chunk: Chunk, ip: usize, stack: Vec<Value>, } impl Vm { pub fn new(chunk: Chunk) -> Self { Vm { chunk, ip: 0, stack: Vec::new(), } } pub fn interpret(&self, source: &str) -> InterpreterResult { compiler::compile(source); Ok(()) } pub fn interpret_current_chunk(&mut self) -> InterpreterResult { self.run() } fn run(&mut self) -> InterpreterResult { Ok(loop { if self.ip >= self.chunk.code.len() { break; } #[cfg(debug_assertions)] println!("{:?}", &self.stack); let next_byte = self.next_byte(); let instruction = Op::from_u8(next_byte); #[cfg(debug_assertions)] self.chunk.disassemble_instruction(self.ip - 1); match instruction { Op::Return => { println!("{}", self.pop()) } Op::Constant | Op::ConstantLong => { let index = self.next_byte(); let constant = self.read_constant(index); self.push(constant); } Op::Negate => *self.peek() = -*self.peek(), Op::Add => binary_op!(self, +), Op::Subract => binary_op!(self, -), Op::Multiply => binary_op!(self, *), Op::Divide => binary_op!(self, /) } }) } fn peek(&mut self) -> &mut Value { self.stack.last_mut().expect(STACK_UNDERFLOW) } #[inline] fn pop(&mut self) -> Value { self.stack.pop().expect(STACK_UNDERFLOW) } #[inline] fn push(&mut self, value: Value) { self.stack.push(value) } fn next_byte(&mut self) -> u8 { let byte = self.chunk.code[self.ip]; self.ip += 1; byte } fn read_constant(&self, index: u8) -> Value { self.chunk.constants[index as usize] } } #[derive(Debug)] pub enum InterpreterError { CompileError, RuntimeError, NoInstructions, UnknownInstruction, }
true
a20087d2865f9bc065f04e6b55053f49a5934aad
Rust
kiwiyou/tgbot
/src/types/chat/mod.rs
UTF-8
20,962
2.890625
3
[ "MIT" ]
permissive
use crate::types::{ chat::raw::{RawChat, RawChatKind}, message::Message, primitive::Integer, }; use serde::{de::Error, Deserialize, Deserializer, Serialize, Serializer}; use std::fmt; mod member; mod permissions; mod photo; mod raw; pub use self::{ member::{ChatMember, ChatMemberAdministrator, ChatMemberKicked, ChatMemberRestricted}, permissions::ChatPermissions, photo::ChatPhoto, }; /// Chat #[derive(Clone, Debug)] pub enum Chat { /// Channel Channel(ChannelChat), /// Group Group(GroupChat), /// Private chat Private(PrivateChat), /// Supergroup Supergroup(SupergroupChat), } impl<'de> Deserialize<'de> for Chat { fn deserialize<D>(deserializer: D) -> Result<Chat, D::Error> where D: Deserializer<'de>, { let raw_chat: RawChat = Deserialize::deserialize(deserializer)?; macro_rules! required { ($name:ident) => {{ match raw_chat.$name { Some(val) => val, None => return Err(D::Error::missing_field(stringify!($name))), } }}; }; Ok(match raw_chat.kind { RawChatKind::Channel => Chat::Channel(ChannelChat { id: raw_chat.id, username: raw_chat.username, title: required!(title), description: raw_chat.description, photo: raw_chat.photo, pinned_message: raw_chat.pinned_message, invite_link: raw_chat.invite_link, }), RawChatKind::Group => Chat::Group(GroupChat { id: raw_chat.id, title: required!(title), all_members_are_administrators: required!(all_members_are_administrators), photo: raw_chat.photo, pinned_message: raw_chat.pinned_message, invite_link: raw_chat.invite_link, permissions: raw_chat.permissions, }), RawChatKind::Private => Chat::Private(PrivateChat { id: raw_chat.id, username: raw_chat.username, first_name: required!(first_name), last_name: raw_chat.last_name, photo: raw_chat.photo, }), RawChatKind::Supergroup => Chat::Supergroup(SupergroupChat { id: raw_chat.id, title: required!(title), username: raw_chat.username, description: raw_chat.description, photo: raw_chat.photo, pinned_message: raw_chat.pinned_message, invite_link: raw_chat.invite_link, sticker_set_name: raw_chat.sticker_set_name, can_set_sticker_set: raw_chat.can_set_sticker_set, permissions: raw_chat.permissions, slow_mode_delay: raw_chat.slow_mode_delay, }), }) } } /// Channel chat #[derive(Clone, Debug)] pub struct ChannelChat { /// Unique identifier for this chat pub id: Integer, /// Title pub title: String, /// Username of a channel pub username: Option<String>, /// Chat photo /// /// Returned only in getChat pub photo: Option<ChatPhoto>, /// Description of a channel /// /// Returned only in getChat pub description: Option<String>, /// Invite link /// /// Returned only in getChat pub invite_link: Option<String>, /// Pinned message /// /// Returned only in getChat pub pinned_message: Option<Box<Message>>, } /// Group chat #[derive(Clone, Debug)] pub struct GroupChat { /// Unique identifier for this chat pub id: Integer, /// Title pub title: String, /// True if a group has ‘All Members Are Admins’ enabled /// /// The field is still returned in the object for backward compatibility, /// but new bots should use the permissions field instead pub all_members_are_administrators: bool, /// Chat photo /// /// Returned only in getChat pub photo: Option<ChatPhoto>, /// Invite link /// /// Returned only in getChat pub invite_link: Option<String>, /// Pinned message /// Returned only in getChat pub pinned_message: Option<Box<Message>>, /// Default chat member permissions, for groups and supergroups /// /// Returned only in getChat pub permissions: Option<ChatPermissions>, } /// Private chat #[derive(Clone, Debug)] pub struct PrivateChat { /// Unique identifier for this chat pub id: Integer, /// First name of the other party pub first_name: String, /// Last name of the other party pub last_name: Option<String>, /// Username of a chat pub username: Option<String>, /// Chat photo /// /// Returned only in getChat pub photo: Option<ChatPhoto>, } /// Supergroup chat #[derive(Clone, Debug)] pub struct SupergroupChat { /// Unique identifier for this chat pub id: Integer, /// Title pub title: String, /// Username of a supergroup pub username: Option<String>, /// Photo of a supergroup /// /// Returned only in getChat pub photo: Option<ChatPhoto>, /// Description of a supergroup /// /// Returned only in getChat pub description: Option<String>, /// Invite link /// /// Returned only in getChat pub invite_link: Option<String>, /// Pinned message /// /// Returned only in getChat pub pinned_message: Option<Box<Message>>, /// For supergroups, name of group sticker set /// /// Returned only in getChat pub sticker_set_name: Option<String>, /// True, if the bot can change the group sticker set /// /// Returned only in getChat pub can_set_sticker_set: Option<bool>, /// Default chat member permissions, for groups and supergroups /// /// Returned only in getChat pub permissions: Option<ChatPermissions>, /// The minimum allowed delay between consecutive messages sent by each unpriviledged user /// /// Returned only in getChat pub slow_mode_delay: Option<Integer>, } /// Chat ID or username #[derive(Clone, Debug, Eq, Hash, PartialEq, PartialOrd)] pub enum ChatId { /// @username of a chat Username(String), /// ID of a chat Id(Integer), } impl fmt::Display for ChatId { fn fmt(&self, out: &mut fmt::Formatter) -> fmt::Result { match self { ChatId::Username(username) => write!(out, "{}", username), ChatId::Id(chat_id) => write!(out, "{}", chat_id), } } } impl Serialize for ChatId { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { match self { ChatId::Username(username) => serializer.serialize_str(username), ChatId::Id(id) => serializer.serialize_i64(*id), } } } impl From<&str> for ChatId { fn from(username: &str) -> ChatId { ChatId::Username(String::from(username)) } } impl From<String> for ChatId { fn from(username: String) -> ChatId { ChatId::Username(username) } } impl From<Integer> for ChatId { fn from(id: Integer) -> ChatId { ChatId::Id(id) } } /// Type of action to tell the user that some is happening on the bot's side #[derive(Clone, Copy, Debug, Hash, PartialEq, PartialOrd, Serialize)] #[serde(rename_all = "snake_case")] pub enum ChatAction { /// For location data FindLocation, /// For audio files RecordAudio, /// For videos RecordVideo, /// For video notes RecordVideoNote, /// For text messages Typing, /// For audio files UploadAudio, /// For general files UploadDocument, /// For photos UploadPhoto, /// For videos UploadVideo, /// For video notes UploadVideoNote, } #[cfg(test)] mod tests { use super::*; use std::collections::HashMap; #[test] fn deserialize_channel() { let chat: Chat = serde_json::from_value(serde_json::json!({ "id": 1, "type": "channel", "title": "channeltitle", "username": "channelusername", "photo": { "small_file_id": "smallfileid", "small_file_unique_id": "smallfileuniqueid", "big_file_id": "bigfileid", "big_file_unique_id": "bigfileuniqueid", }, "description": "channeldescription", "invite_link": "channelinvitelink", "pinned_message": { "message_id": 1, "date": 0, "chat": { "id": 1, "type": "channel", "title": "channeltitle" }, "text": "test" } })) .unwrap(); if let Chat::Channel(chat) = chat { assert_eq!(chat.id, 1); assert_eq!(chat.title, "channeltitle"); assert_eq!(chat.username.unwrap(), "channelusername"); let photo = chat.photo.unwrap(); assert_eq!(photo.small_file_id, "smallfileid"); assert_eq!(photo.small_file_unique_id, "smallfileuniqueid"); assert_eq!(photo.big_file_id, "bigfileid"); assert_eq!(photo.big_file_unique_id, "bigfileuniqueid"); assert_eq!(chat.description.unwrap(), "channeldescription"); assert_eq!(chat.invite_link.unwrap(), "channelinvitelink"); assert!(chat.pinned_message.is_some()); } else { panic!("Unexpected chat: {:?}", chat); } let chat: Chat = serde_json::from_value(serde_json::json!({ "id": 1, "type": "channel", "title": "channeltitle" })) .unwrap(); if let Chat::Channel(chat) = chat { assert_eq!(chat.id, 1); assert_eq!(chat.title, "channeltitle"); assert!(chat.username.is_none()); assert!(chat.photo.is_none()); assert!(chat.description.is_none()); assert!(chat.invite_link.is_none()); assert!(chat.pinned_message.is_none()); } else { panic!("Unexpected chat: {:?}", chat); } } #[test] fn deserialize_group() { let chat: Chat = serde_json::from_value(serde_json::json!({ "id": 1, "type": "group", "title": "grouptitle", "all_members_are_administrators": true, "photo": { "small_file_id": "smallfileid", "small_file_unique_id": "smallfileuniqueid", "big_file_id": "bigfileid", "big_file_unique_id": "bigfileuniqueid", }, "invite_link": "groupinvitelink", "pinned_message": { "message_id": 1, "date": 0, "chat": { "id": 1, "type": "group", "title": "grouptitle", "all_members_are_administrators": true }, "from": { "id": 1, "is_bot": false, "first_name": "user" }, "text": "test" }, "permissions": {"can_send_messages": true} })) .unwrap(); if let Chat::Group(chat) = chat { assert_eq!(chat.id, 1); assert_eq!(chat.title, "grouptitle"); assert!(chat.all_members_are_administrators); let photo = chat.photo.unwrap(); assert_eq!(photo.small_file_id, "smallfileid"); assert_eq!(photo.small_file_unique_id, "smallfileuniqueid"); assert_eq!(photo.big_file_id, "bigfileid"); assert_eq!(photo.big_file_unique_id, "bigfileuniqueid"); assert_eq!(chat.invite_link.unwrap(), "groupinvitelink"); let permissions = chat.permissions.unwrap(); assert!(permissions.can_send_messages.unwrap()); assert!(chat.pinned_message.is_some()); } else { panic!("Unexpected chat: {:?}", chat); } let chat: Chat = serde_json::from_value(serde_json::json!({ "id": 1, "type": "group", "title": "grouptitle", "all_members_are_administrators": false })) .unwrap(); if let Chat::Group(chat) = chat { assert_eq!(chat.id, 1); assert_eq!(chat.title, "grouptitle"); assert!(!chat.all_members_are_administrators); assert!(chat.photo.is_none()); assert!(chat.invite_link.is_none()); assert!(chat.pinned_message.is_none()); assert!(chat.permissions.is_none()); } else { panic!("Unexpected chat: {:?}", chat); } } #[test] fn deserialize_private() { let chat: Chat = serde_json::from_value(serde_json::json!({ "id": 1, "type": "private", "username": "testusername", "first_name": "testfirstname", "last_name": "testlastname", "photo": { "small_file_id": "smallfileid", "small_file_unique_id": "smallfileuniqueid", "big_file_id": "bigfileid", "big_file_unique_id": "bigfileuniqueid", } })) .unwrap(); if let Chat::Private(chat) = chat { assert_eq!(chat.id, 1); assert_eq!(chat.username.unwrap(), "testusername"); assert_eq!(chat.first_name, "testfirstname"); assert_eq!(chat.last_name.unwrap(), "testlastname"); let photo = chat.photo.unwrap(); assert_eq!(photo.small_file_id, "smallfileid"); assert_eq!(photo.small_file_unique_id, "smallfileuniqueid"); assert_eq!(photo.big_file_id, "bigfileid"); assert_eq!(photo.big_file_unique_id, "bigfileuniqueid"); } else { panic!("Unexpected chat: {:?}", chat) } let chat: Chat = serde_json::from_value(serde_json::json!({ "id": 1, "type": "private", "first_name": "testfirstname" })) .unwrap(); if let Chat::Private(chat) = chat { assert_eq!(chat.id, 1); assert!(chat.username.is_none()); assert_eq!(chat.first_name, "testfirstname"); assert!(chat.last_name.is_none()); assert!(chat.photo.is_none()); } else { panic!("Unexpected chat: {:?}", chat) } } #[test] fn deserialize_supergroup_full() { let chat: Chat = serde_json::from_value(serde_json::json!({ "id": 1, "type": "supergroup", "title": "supergrouptitle", "username": "supergroupusername", "photo": { "small_file_id": "smallfileid", "small_file_unique_id": "smallfileuniqueid", "big_file_id": "bigfileid", "big_file_unique_id": "bigfileuniqueid", }, "description": "supergroupdescription", "invite_link": "supergroupinvitelink", "sticker_set_name": "supergroupstickersetname", "can_set_sticker_set": true, "slow_mode_delay": 10, "permissions": { "can_send_messages": true }, "pinned_message": { "message_id": 1, "date": 0, "chat": { "id": 1, "type": "supergroup", "title": "supergrouptitle", "username": "supergroupusername" }, "from": { "id": 1, "is_bot": false, "first_name": "user" }, "text": "test" } })) .unwrap(); if let Chat::Supergroup(chat) = chat { assert_eq!(chat.id, 1); assert_eq!(chat.title, "supergrouptitle"); assert_eq!(chat.username.unwrap(), "supergroupusername"); let photo = chat.photo.unwrap(); assert_eq!(photo.small_file_id, "smallfileid"); assert_eq!(photo.small_file_unique_id, "smallfileuniqueid"); assert_eq!(photo.big_file_id, "bigfileid"); assert_eq!(photo.big_file_unique_id, "bigfileuniqueid"); assert_eq!(chat.description.unwrap(), "supergroupdescription"); assert_eq!(chat.invite_link.unwrap(), "supergroupinvitelink"); assert_eq!(chat.sticker_set_name.unwrap(), "supergroupstickersetname"); assert_eq!(chat.slow_mode_delay.unwrap(), 10); assert!(chat.can_set_sticker_set.unwrap()); assert!(chat.pinned_message.is_some()); let permissions = chat.permissions.unwrap(); assert!(permissions.can_send_messages.unwrap()); } else { panic!("Unexpected chat: {:?}", chat) } } #[test] fn deserialize_supergroup_partial() { let chat: Chat = serde_json::from_value(serde_json::json!({ "id": 1, "type": "supergroup", "title": "supergrouptitle", "username": "supergroupusername" })) .unwrap(); if let Chat::Supergroup(chat) = chat { assert_eq!(chat.id, 1); assert_eq!(chat.title, "supergrouptitle"); assert_eq!(chat.username.unwrap(), "supergroupusername"); assert!(chat.photo.is_none()); assert!(chat.description.is_none()); assert!(chat.invite_link.is_none()); assert!(chat.sticker_set_name.is_none()); assert!(chat.can_set_sticker_set.is_none()); assert!(chat.pinned_message.is_none()); assert!(chat.permissions.is_none()); } else { panic!("Unexpected chat: {:?}", chat) } } #[test] fn chat_id() { let chat_id = ChatId::from(1); if let ChatId::Id(chat_id) = chat_id { assert_eq!(chat_id, 1); } else { panic!("Unexpected chat id: {:?}", chat_id); } assert_eq!(serde_json::to_string(&chat_id).unwrap(), r#"1"#); assert_eq!(chat_id.to_string(), "1"); let chat_id = ChatId::from("username"); if let ChatId::Username(ref username) = chat_id { assert_eq!(username, "username"); } else { panic!("Unexpected chat id: {:?}", chat_id); } assert_eq!(serde_json::to_string(&chat_id).unwrap(), r#""username""#); assert_eq!(chat_id.to_string(), "username"); let chat_id = ChatId::from(String::from("username")); if let ChatId::Username(ref username) = chat_id { assert_eq!(username, "username"); } else { panic!("Unexpected chat id: {:?}", chat_id); } assert_eq!(serde_json::to_string(&chat_id).unwrap(), r#""username""#); assert_eq!(chat_id.to_string(), "username"); let mut map = HashMap::new(); let chat_id_1 = ChatId::from(1); let chat_id_2 = ChatId::from("username"); map.insert(chat_id_1.clone(), "1".to_string()); map.insert(chat_id_2.clone(), "2".to_string()); assert_eq!(map.get(&chat_id_1).unwrap(), "1"); assert_eq!(map.get(&chat_id_2).unwrap(), "2"); } #[test] fn chat_action() { assert_eq!( serde_json::to_string(&ChatAction::FindLocation).unwrap(), r#""find_location""# ); assert_eq!( serde_json::to_string(&ChatAction::RecordAudio).unwrap(), r#""record_audio""# ); assert_eq!( serde_json::to_string(&ChatAction::RecordVideo).unwrap(), r#""record_video""# ); assert_eq!( serde_json::to_string(&ChatAction::RecordVideoNote).unwrap(), r#""record_video_note""# ); assert_eq!(serde_json::to_string(&ChatAction::Typing).unwrap(), r#""typing""#); assert_eq!( serde_json::to_string(&ChatAction::UploadAudio).unwrap(), r#""upload_audio""# ); assert_eq!( serde_json::to_string(&ChatAction::UploadDocument).unwrap(), r#""upload_document""# ); assert_eq!( serde_json::to_string(&ChatAction::UploadPhoto).unwrap(), r#""upload_photo""# ); assert_eq!( serde_json::to_string(&ChatAction::UploadVideo).unwrap(), r#""upload_video""# ); assert_eq!( serde_json::to_string(&ChatAction::UploadVideoNote).unwrap(), r#""upload_video_note""# ); } }
true
43690b62fb05ca2b85539aac936a2572f73631e2
Rust
zzzzzzzzzzz0/zhscript-rust
/src/keyword.rs
UTF-8
1,311
3.21875
3
[]
no_license
#[derive(PartialEq, Debug)] pub enum Id { No, Juhao, Kaiyinhao, Biyinhao, Eval, Print, Cr, Lf, Tab, Esc, } #[derive(Debug)] pub struct Item { val:&'static str, val2:Id, } impl Item { pub fn val(&self) -> &str { self.val } pub fn val2(&self) -> &Id { &self.val2 } } const fn new(val:&'static str, val2:Id) -> Item { Item {val:val, val2:val2} } pub static NO:Item = new("", Id::No); pub static JUHAO:Item = new("。", Id::Juhao); pub static KAIYINHAO:Item = new("“", Id::Kaiyinhao); pub static BIYINHAO:Item = new("”", Id::Biyinhao); pub static EVAL:Item = new("算术", Id::Eval); pub static PRINT:Item = new("显示", Id::Print); pub static CR:Item = new("回车", Id::Cr); pub static LF:Item = new("换行", Id::Lf); pub static TAB:Item = new("制表符", Id::Tab); pub static ESC:Item = new("ESC", Id::Esc); pub static ALL:[&'static Item; 9] = [ &JUHAO, &KAIYINHAO, &BIYINHAO, &EVAL, &PRINT, &CR, &LF, &TAB, &ESC, ]; pub fn get(s:&str, i:usize, i3:&mut usize) -> Option<&'static Item> { for i2 in ALL.into_iter() { *i3 = 0; let mut i4 = i; loop { if *i3 >= i2.val().chars().count() { return Some(i2); } if i4 >= s.chars().count() { break; } if s.chars().nth(i4) != i2.val().chars().nth(*i3) { break; } *i3 += 1; i4 += 1; } } None }
true
f2e294f1a5ae66544c5f94a3e1ab2c7724a69feb
Rust
MacTuitui/nannou
/nannou/src/state.rs
UTF-8
9,177
3.40625
3
[ "MIT", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
//! Small tracked parts of the application state. Includes **window**, **keys**, **mouse**, and //! **time** - each of which are stored in the **App**. pub use self::keys::Keys; pub use self::mouse::Mouse; pub use self::time::Time; pub use self::window::Window; /// Tracked state related to the focused window. pub mod window { use crate::geom; use crate::window; /// The default scalar value used for window positioning and sizing. pub type DefaultScalar = geom::scalar::Default; /// State of the window in focus. #[derive(Copy, Clone, Debug, PartialEq)] pub struct Window { /// ID of the window currently in focus. pub id: Option<window::Id>, } impl Window { /// Initialise the window state. pub fn new() -> Self { Window { id: None } } /// Expects that there will be a `window::Id` (the common case) and **panic!**s otherwise. pub fn id(&self) -> window::Id { self.id.unwrap() } } } /// Tracked state related to the keyboard. pub mod keys { use crate::event::{Key, ModifiersState}; use std::collections::HashSet; use std::ops::Deref; /// The state of the keyboard. #[derive(Clone, Debug, Default)] pub struct Keys { /// The state of the modifier keys as last indicated by winit. pub mods: ModifiersState, /// The state of all keys as tracked via the nannou App event handling. pub down: Down, } /// The set of keys that are currently pressed. #[derive(Clone, Debug, Default)] pub struct Down { pub(crate) keys: HashSet<Key>, } impl Deref for Down { type Target = HashSet<Key>; fn deref(&self) -> &Self::Target { &self.keys } } } /// Tracked state related to the mouse. pub mod mouse { use crate::geom::{self, Point2}; use crate::math::BaseFloat; use crate::window; use std; /// The default scalar value used for positions. pub type DefaultScalar = geom::scalar::Default; #[doc(inline)] pub use crate::event::MouseButton as Button; /// The max total number of buttons on a mouse. pub const NUM_BUTTONS: usize = 9; /// The state of the `Mouse` at a single moment in time. #[derive(Copy, Clone, Debug, PartialEq)] pub struct Mouse<S = DefaultScalar> { /// The ID of the last window currently in focus. pub window: Option<window::Id>, /// *x* position relative to the middle of `window`. pub x: S, /// *y* position relative to the middle of `window`. pub y: S, /// A map describing the state of each mouse button. pub buttons: ButtonMap, } /// Whether the button is up or down. #[derive(Copy, Clone, Debug, PartialEq)] pub enum ButtonPosition<S = DefaultScalar> { /// The button is up (i.e. pressed). Up, /// The button is down and was originally pressed down at the given `Point2`. Down(Point2<S>), } /// Stores the state of all mouse buttons. /// /// If the mouse button is down, it stores the position of the mouse when the button was pressed #[derive(Copy, Clone, Debug, PartialEq)] pub struct ButtonMap<S = DefaultScalar> { buttons: [ButtonPosition<S>; NUM_BUTTONS], } /// An iterator yielding all pressed buttons. #[derive(Clone)] pub struct PressedButtons<'a, S: 'a = DefaultScalar> { buttons: std::iter::Enumerate<std::slice::Iter<'a, ButtonPosition<S>>>, } impl<S> Mouse<S> where S: BaseFloat, { /// Construct a new default `Mouse`. pub fn new() -> Self { Mouse { window: None, buttons: ButtonMap::new(), x: S::zero(), y: S::zero(), } } /// The position of the mouse relative to the middle of the window in focus.. pub fn position(&self) -> Point2<S> { Point2 { x: self.x, y: self.y, } } } impl<S> ButtonPosition<S> where S: BaseFloat, { /// If the mouse button is down, return a new one with position relative to the given `xy`. pub fn relative_to(self, xy: Point2<S>) -> Self { match self { ButtonPosition::Down(pos) => { let rel_p = pos - xy; ButtonPosition::Down(Point2 { x: rel_p.x, y: rel_p.y, }) } button_pos => button_pos, } } /// Is the `ButtonPosition` down. pub fn is_down(&self) -> bool { match *self { ButtonPosition::Down(_) => true, _ => false, } } /// Is the `ButtonPosition` up. pub fn is_up(&self) -> bool { match *self { ButtonPosition::Up => true, _ => false, } } /// Returns the position at which the button was pressed. pub fn if_down(&self) -> Option<Point2<S>> { match *self { ButtonPosition::Down(xy) => Some(xy), _ => None, } } } impl<S> ButtonMap<S> where S: BaseFloat, { /// Returns a new button map with all states set to `None` pub fn new() -> Self { ButtonMap { buttons: [ButtonPosition::Up; NUM_BUTTONS], } } /// Returns a copy of the ButtonMap relative to the given `Point` pub fn relative_to(self, xy: Point2<S>) -> Self { self.buttons .iter() .enumerate() .fold(ButtonMap::new(), |mut map, (idx, button_pos)| { map.buttons[idx] = button_pos.relative_to(xy); map }) } /// The state of the left mouse button. pub fn left(&self) -> &ButtonPosition<S> { &self[Button::Left] } /// The state of the middle mouse button. pub fn middle(&self) -> &ButtonPosition<S> { &self[Button::Middle] } /// The state of the right mouse button. pub fn right(&self) -> &ButtonPosition<S> { &self[Button::Right] } /// Sets the `Button` in the `Down` position. pub fn press(&mut self, button: Button, xy: Point2<S>) { self.buttons[button_to_idx(button)] = ButtonPosition::Down(xy); } /// Set's the `Button` in the `Up` position. pub fn release(&mut self, button: Button) { self.buttons[button_to_idx(button)] = ButtonPosition::Up; } /// An iterator yielding all pressed mouse buttons along with the location at which they /// were originally pressed. pub fn pressed(&self) -> PressedButtons<S> { PressedButtons { buttons: self.buttons.iter().enumerate(), } } } impl<S> std::ops::Index<Button> for ButtonMap<S> { type Output = ButtonPosition<S>; fn index(&self, button: Button) -> &Self::Output { &self.buttons[button_to_idx(button)] } } impl<'a, S> Iterator for PressedButtons<'a, S> where S: BaseFloat, { type Item = (Button, Point2<S>); fn next(&mut self) -> Option<Self::Item> { while let Some((idx, button_pos)) = self.buttons.next() { if let ButtonPosition::Down(xy) = *button_pos { return Some((idx_to_button(idx), xy)); } } None } } fn idx_to_button(i: usize) -> Button { match i { n @ 0..=5 => Button::Other(n as u8), 6 => Button::Left, 7 => Button::Right, 8 => Button::Middle, _ => Button::Other(std::u8::MAX), } } fn button_to_idx(button: Button) -> usize { match button { Button::Other(n) => n as usize, Button::Left => 6, Button::Right => 7, Button::Middle => 8, } } } /// Tracked durations related to the App. pub mod time { /// The state of time tracked by the App. #[derive(Copy, Clone, Debug, Default, Eq, PartialEq, Hash)] pub struct Time { /// The duration since the app started running. pub since_start: std::time::Duration, /// The duration since the previous update. pub since_prev_update: std::time::Duration, } impl Time { /// The number of updates per second if `since_prev_update` were to remain constant pub fn updates_per_second(&self) -> f32 { if self.since_prev_update.as_secs() > 0 { return 0.0; } let millis = self.since_prev_update.subsec_millis() as f32; if millis == 0.0 { return std::f32::MAX; } 1000.0 / millis } } }
true
9165ba87003bed57dd57e1b1ee72e2da7b4559f5
Rust
crumblingstatue/advent-of-code
/src/bin/15d2.rs
UTF-8
1,450
3
3
[]
no_license
fn parse_lwh(text: &str) -> (i32, i32, i32) { let mut splits = text.split('x'); let l = splits.next().unwrap().parse().unwrap(); let w = splits.next().unwrap().parse().unwrap(); let h = splits.next().unwrap().parse().unwrap(); (l, w, h) } fn paper_req_lwh(l: i32, w: i32, h: i32) -> i32 { let side1 = l * w; let side2 = w * h; let side3 = h * l; let surface_area = 2 * side1 + 2 * side2 + 2 * side3; let extra = [side1, side2, side3].into_iter().min().unwrap(); surface_area + extra } fn paper_req_present_spec(spec: &str) -> i32 { let (l, w, h) = parse_lwh(spec); paper_req_lwh(l, w, h) } fn shortest_distance_around_sides(l: i32, w: i32, h: i32) -> i32 { let mut sides = [l, w, h]; sides.sort_unstable(); sides[0] * 2 + sides[1] * 2 } fn ribbon_req_lwh(l: i32, w: i32, h: i32) -> i32 { let ribbon_req = shortest_distance_around_sides(l, w, h); let volume = l * w * h; ribbon_req + volume } fn ribbon_req_present_spec(spec: &str) -> i32 { let (l, w, h) = parse_lwh(spec); ribbon_req_lwh(l, w, h) } fn part1(input: &str) -> i32 { input.lines().map(paper_req_present_spec).sum() } fn part2(input: &str) -> i32 { input.lines().map(ribbon_req_present_spec).sum() } aoc::tests! { fn part1: "2x3x4" => 58; "1x1x10" => 43; in => 1588178; fn part2: "2x3x4" => 34; "1x1x10" => 14; in => 3783758; } aoc::main!(part1, part2);
true
74448f6dfe4ebcca7ca92e656a1a59f24e0292e3
Rust
Kuzirashi/godwoken
/crates/types/src/generated/godwoken.rs
UTF-8
603,483
2.78125
3
[ "MIT" ]
permissive
// Generated by Molecule 0.7.2 use super::blockchain::*; use molecule::prelude::*; #[derive(Clone)] pub struct Uint32Vec(molecule::bytes::Bytes); impl ::core::fmt::LowerHex for Uint32Vec { 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 Uint32Vec { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl ::core::fmt::Display for Uint32Vec { 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 Uint32Vec { fn default() -> Self { let v: Vec<u8> = vec![0, 0, 0, 0]; Uint32Vec::new_unchecked(v.into()) } } impl Uint32Vec { pub const ITEM_SIZE: usize = 4; pub fn total_size(&self) -> usize { molecule::NUMBER_SIZE + Self::ITEM_SIZE * self.item_count() } pub fn item_count(&self) -> usize { molecule::unpack_number(self.as_slice()) as usize } pub fn len(&self) -> usize { self.item_count() } pub fn is_empty(&self) -> bool { self.len() == 0 } pub fn get(&self, idx: usize) -> Option<Uint32> { if idx >= self.len() { None } else { Some(self.get_unchecked(idx)) } } pub fn get_unchecked(&self, idx: usize) -> Uint32 { let start = molecule::NUMBER_SIZE + Self::ITEM_SIZE * idx; let end = start + Self::ITEM_SIZE; Uint32::new_unchecked(self.0.slice(start..end)) } pub fn as_reader<'r>(&'r self) -> Uint32VecReader<'r> { Uint32VecReader::new_unchecked(self.as_slice()) } } impl molecule::prelude::Entity for Uint32Vec { type Builder = Uint32VecBuilder; const NAME: &'static str = "Uint32Vec"; fn new_unchecked(data: molecule::bytes::Bytes) -> Self { Uint32Vec(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> { Uint32VecReader::from_slice(slice).map(|reader| reader.to_entity()) } fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> { Uint32VecReader::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 Uint32VecReader<'r>(&'r [u8]); impl<'r> ::core::fmt::LowerHex for Uint32VecReader<'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 Uint32VecReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl<'r> ::core::fmt::Display for Uint32VecReader<'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> Uint32VecReader<'r> { pub const ITEM_SIZE: usize = 4; pub fn total_size(&self) -> usize { molecule::NUMBER_SIZE + Self::ITEM_SIZE * self.item_count() } pub fn item_count(&self) -> usize { molecule::unpack_number(self.as_slice()) as usize } pub fn len(&self) -> usize { self.item_count() } pub fn is_empty(&self) -> bool { self.len() == 0 } pub fn get(&self, idx: usize) -> Option<Uint32Reader<'r>> { if idx >= self.len() { None } else { Some(self.get_unchecked(idx)) } } pub fn get_unchecked(&self, idx: usize) -> Uint32Reader<'r> { let start = molecule::NUMBER_SIZE + Self::ITEM_SIZE * idx; let end = start + Self::ITEM_SIZE; Uint32Reader::new_unchecked(&self.as_slice()[start..end]) } } impl<'r> molecule::prelude::Reader<'r> for Uint32VecReader<'r> { type Entity = Uint32Vec; const NAME: &'static str = "Uint32VecReader"; fn to_entity(&self) -> Self::Entity { Self::Entity::new_unchecked(self.as_slice().to_owned().into()) } fn new_unchecked(slice: &'r [u8]) -> Self { Uint32VecReader(slice) } fn as_slice(&self) -> &'r [u8] { self.0 } fn verify(slice: &[u8], _compatible: bool) -> molecule::error::VerificationResult<()> { use molecule::verification_error as ve; let slice_len = slice.len(); if slice_len < molecule::NUMBER_SIZE { return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE, slice_len); } let item_count = molecule::unpack_number(slice) as usize; if item_count == 0 { if slice_len != molecule::NUMBER_SIZE { return ve!(Self, TotalSizeNotMatch, molecule::NUMBER_SIZE, slice_len); } return Ok(()); } let total_size = molecule::NUMBER_SIZE + Self::ITEM_SIZE * item_count; if slice_len != total_size { return ve!(Self, TotalSizeNotMatch, total_size, slice_len); } Ok(()) } } #[derive(Debug, Default)] pub struct Uint32VecBuilder(pub(crate) Vec<Uint32>); impl Uint32VecBuilder { pub const ITEM_SIZE: usize = 4; pub fn set(mut self, v: Vec<Uint32>) -> Self { self.0 = v; self } pub fn push(mut self, v: Uint32) -> Self { self.0.push(v); self } pub fn extend<T: ::core::iter::IntoIterator<Item = Uint32>>(mut self, iter: T) -> Self { for elem in iter { self.0.push(elem); } self } } impl molecule::prelude::Builder for Uint32VecBuilder { type Entity = Uint32Vec; const NAME: &'static str = "Uint32VecBuilder"; fn expected_length(&self) -> usize { molecule::NUMBER_SIZE + Self::ITEM_SIZE * self.0.len() } fn write<W: molecule::io::Write>(&self, writer: &mut W) -> molecule::io::Result<()> { writer.write_all(&molecule::pack_number(self.0.len() as molecule::Number))?; for inner in &self.0[..] { writer.write_all(inner.as_slice())?; } Ok(()) } fn build(&self) -> Self::Entity { let mut inner = Vec::with_capacity(self.expected_length()); self.write(&mut inner) .unwrap_or_else(|_| panic!("{} build should be ok", Self::NAME)); Uint32Vec::new_unchecked(inner.into()) } } pub struct Uint32VecIterator(Uint32Vec, usize, usize); impl ::core::iter::Iterator for Uint32VecIterator { type Item = Uint32; 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 Uint32VecIterator { fn len(&self) -> usize { self.2 - self.1 } } impl ::core::iter::IntoIterator for Uint32Vec { type Item = Uint32; type IntoIter = Uint32VecIterator; fn into_iter(self) -> Self::IntoIter { let len = self.len(); Uint32VecIterator(self, 0, len) } } impl<'r> Uint32VecReader<'r> { pub fn iter<'t>(&'t self) -> Uint32VecReaderIterator<'t, 'r> { Uint32VecReaderIterator(&self, 0, self.len()) } } pub struct Uint32VecReaderIterator<'t, 'r>(&'t Uint32VecReader<'r>, usize, usize); impl<'t: 'r, 'r> ::core::iter::Iterator for Uint32VecReaderIterator<'t, 'r> { type Item = Uint32Reader<'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 Uint32VecReaderIterator<'t, 'r> { fn len(&self) -> usize { self.2 - self.1 } } #[derive(Clone)] pub struct BlockMerkleState(molecule::bytes::Bytes); impl ::core::fmt::LowerHex for BlockMerkleState { 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 BlockMerkleState { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl ::core::fmt::Display for BlockMerkleState { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; write!(f, "{}: {}", "merkle_root", self.merkle_root())?; write!(f, ", {}: {}", "count", self.count())?; write!(f, " }}") } } impl ::core::default::Default for BlockMerkleState { fn default() -> Self { let v: Vec<u8> = vec![ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ]; BlockMerkleState::new_unchecked(v.into()) } } impl BlockMerkleState { pub const TOTAL_SIZE: usize = 40; pub const FIELD_SIZES: [usize; 2] = [32, 8]; pub const FIELD_COUNT: usize = 2; pub fn merkle_root(&self) -> Byte32 { Byte32::new_unchecked(self.0.slice(0..32)) } pub fn count(&self) -> Uint64 { Uint64::new_unchecked(self.0.slice(32..40)) } pub fn as_reader<'r>(&'r self) -> BlockMerkleStateReader<'r> { BlockMerkleStateReader::new_unchecked(self.as_slice()) } } impl molecule::prelude::Entity for BlockMerkleState { type Builder = BlockMerkleStateBuilder; const NAME: &'static str = "BlockMerkleState"; fn new_unchecked(data: molecule::bytes::Bytes) -> Self { BlockMerkleState(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> { BlockMerkleStateReader::from_slice(slice).map(|reader| reader.to_entity()) } fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> { BlockMerkleStateReader::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() .merkle_root(self.merkle_root()) .count(self.count()) } } #[derive(Clone, Copy)] pub struct BlockMerkleStateReader<'r>(&'r [u8]); impl<'r> ::core::fmt::LowerHex for BlockMerkleStateReader<'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 BlockMerkleStateReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl<'r> ::core::fmt::Display for BlockMerkleStateReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; write!(f, "{}: {}", "merkle_root", self.merkle_root())?; write!(f, ", {}: {}", "count", self.count())?; write!(f, " }}") } } impl<'r> BlockMerkleStateReader<'r> { pub const TOTAL_SIZE: usize = 40; pub const FIELD_SIZES: [usize; 2] = [32, 8]; pub const FIELD_COUNT: usize = 2; pub fn merkle_root(&self) -> Byte32Reader<'r> { Byte32Reader::new_unchecked(&self.as_slice()[0..32]) } pub fn count(&self) -> Uint64Reader<'r> { Uint64Reader::new_unchecked(&self.as_slice()[32..40]) } } impl<'r> molecule::prelude::Reader<'r> for BlockMerkleStateReader<'r> { type Entity = BlockMerkleState; const NAME: &'static str = "BlockMerkleStateReader"; fn to_entity(&self) -> Self::Entity { Self::Entity::new_unchecked(self.as_slice().to_owned().into()) } fn new_unchecked(slice: &'r [u8]) -> Self { BlockMerkleStateReader(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(()) } } #[derive(Debug, Default)] pub struct BlockMerkleStateBuilder { pub(crate) merkle_root: Byte32, pub(crate) count: Uint64, } impl BlockMerkleStateBuilder { pub const TOTAL_SIZE: usize = 40; pub const FIELD_SIZES: [usize; 2] = [32, 8]; pub const FIELD_COUNT: usize = 2; pub fn merkle_root(mut self, v: Byte32) -> Self { self.merkle_root = v; self } pub fn count(mut self, v: Uint64) -> Self { self.count = v; self } } impl molecule::prelude::Builder for BlockMerkleStateBuilder { type Entity = BlockMerkleState; const NAME: &'static str = "BlockMerkleStateBuilder"; 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.merkle_root.as_slice())?; writer.write_all(self.count.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)); BlockMerkleState::new_unchecked(inner.into()) } } #[derive(Clone)] pub struct AccountMerkleState(molecule::bytes::Bytes); impl ::core::fmt::LowerHex for AccountMerkleState { 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 AccountMerkleState { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl ::core::fmt::Display for AccountMerkleState { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; write!(f, "{}: {}", "merkle_root", self.merkle_root())?; write!(f, ", {}: {}", "count", self.count())?; write!(f, " }}") } } impl ::core::default::Default for AccountMerkleState { fn default() -> Self { let v: Vec<u8> = vec![ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ]; AccountMerkleState::new_unchecked(v.into()) } } impl AccountMerkleState { pub const TOTAL_SIZE: usize = 36; pub const FIELD_SIZES: [usize; 2] = [32, 4]; pub const FIELD_COUNT: usize = 2; pub fn merkle_root(&self) -> Byte32 { Byte32::new_unchecked(self.0.slice(0..32)) } pub fn count(&self) -> Uint32 { Uint32::new_unchecked(self.0.slice(32..36)) } pub fn as_reader<'r>(&'r self) -> AccountMerkleStateReader<'r> { AccountMerkleStateReader::new_unchecked(self.as_slice()) } } impl molecule::prelude::Entity for AccountMerkleState { type Builder = AccountMerkleStateBuilder; const NAME: &'static str = "AccountMerkleState"; fn new_unchecked(data: molecule::bytes::Bytes) -> Self { AccountMerkleState(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> { AccountMerkleStateReader::from_slice(slice).map(|reader| reader.to_entity()) } fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> { AccountMerkleStateReader::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() .merkle_root(self.merkle_root()) .count(self.count()) } } #[derive(Clone, Copy)] pub struct AccountMerkleStateReader<'r>(&'r [u8]); impl<'r> ::core::fmt::LowerHex for AccountMerkleStateReader<'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 AccountMerkleStateReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl<'r> ::core::fmt::Display for AccountMerkleStateReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; write!(f, "{}: {}", "merkle_root", self.merkle_root())?; write!(f, ", {}: {}", "count", self.count())?; write!(f, " }}") } } impl<'r> AccountMerkleStateReader<'r> { pub const TOTAL_SIZE: usize = 36; pub const FIELD_SIZES: [usize; 2] = [32, 4]; pub const FIELD_COUNT: usize = 2; pub fn merkle_root(&self) -> Byte32Reader<'r> { Byte32Reader::new_unchecked(&self.as_slice()[0..32]) } pub fn count(&self) -> Uint32Reader<'r> { Uint32Reader::new_unchecked(&self.as_slice()[32..36]) } } impl<'r> molecule::prelude::Reader<'r> for AccountMerkleStateReader<'r> { type Entity = AccountMerkleState; const NAME: &'static str = "AccountMerkleStateReader"; fn to_entity(&self) -> Self::Entity { Self::Entity::new_unchecked(self.as_slice().to_owned().into()) } fn new_unchecked(slice: &'r [u8]) -> Self { AccountMerkleStateReader(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(()) } } #[derive(Debug, Default)] pub struct AccountMerkleStateBuilder { pub(crate) merkle_root: Byte32, pub(crate) count: Uint32, } impl AccountMerkleStateBuilder { pub const TOTAL_SIZE: usize = 36; pub const FIELD_SIZES: [usize; 2] = [32, 4]; pub const FIELD_COUNT: usize = 2; pub fn merkle_root(mut self, v: Byte32) -> Self { self.merkle_root = v; self } pub fn count(mut self, v: Uint32) -> Self { self.count = v; self } } impl molecule::prelude::Builder for AccountMerkleStateBuilder { type Entity = AccountMerkleState; const NAME: &'static str = "AccountMerkleStateBuilder"; 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.merkle_root.as_slice())?; writer.write_all(self.count.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)); AccountMerkleState::new_unchecked(inner.into()) } } #[derive(Clone)] pub struct GlobalStateV0(molecule::bytes::Bytes); impl ::core::fmt::LowerHex for GlobalStateV0 { 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 GlobalStateV0 { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl ::core::fmt::Display for GlobalStateV0 { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; write!(f, "{}: {}", "rollup_config_hash", self.rollup_config_hash())?; write!(f, ", {}: {}", "account", self.account())?; write!(f, ", {}: {}", "block", self.block())?; write!( f, ", {}: {}", "reverted_block_root", self.reverted_block_root() )?; write!(f, ", {}: {}", "tip_block_hash", self.tip_block_hash())?; write!( f, ", {}: {}", "last_finalized_block_number", self.last_finalized_block_number() )?; write!(f, ", {}: {}", "status", self.status())?; write!(f, " }}") } } impl ::core::default::Default for GlobalStateV0 { fn default() -> Self { let v: Vec<u8> = vec![ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ]; GlobalStateV0::new_unchecked(v.into()) } } impl GlobalStateV0 { pub const TOTAL_SIZE: usize = 181; pub const FIELD_SIZES: [usize; 7] = [32, 36, 40, 32, 32, 8, 1]; pub const FIELD_COUNT: usize = 7; pub fn rollup_config_hash(&self) -> Byte32 { Byte32::new_unchecked(self.0.slice(0..32)) } pub fn account(&self) -> AccountMerkleState { AccountMerkleState::new_unchecked(self.0.slice(32..68)) } pub fn block(&self) -> BlockMerkleState { BlockMerkleState::new_unchecked(self.0.slice(68..108)) } pub fn reverted_block_root(&self) -> Byte32 { Byte32::new_unchecked(self.0.slice(108..140)) } pub fn tip_block_hash(&self) -> Byte32 { Byte32::new_unchecked(self.0.slice(140..172)) } pub fn last_finalized_block_number(&self) -> Uint64 { Uint64::new_unchecked(self.0.slice(172..180)) } pub fn status(&self) -> Byte { Byte::new_unchecked(self.0.slice(180..181)) } pub fn as_reader<'r>(&'r self) -> GlobalStateV0Reader<'r> { GlobalStateV0Reader::new_unchecked(self.as_slice()) } } impl molecule::prelude::Entity for GlobalStateV0 { type Builder = GlobalStateV0Builder; const NAME: &'static str = "GlobalStateV0"; fn new_unchecked(data: molecule::bytes::Bytes) -> Self { GlobalStateV0(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> { GlobalStateV0Reader::from_slice(slice).map(|reader| reader.to_entity()) } fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> { GlobalStateV0Reader::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() .rollup_config_hash(self.rollup_config_hash()) .account(self.account()) .block(self.block()) .reverted_block_root(self.reverted_block_root()) .tip_block_hash(self.tip_block_hash()) .last_finalized_block_number(self.last_finalized_block_number()) .status(self.status()) } } #[derive(Clone, Copy)] pub struct GlobalStateV0Reader<'r>(&'r [u8]); impl<'r> ::core::fmt::LowerHex for GlobalStateV0Reader<'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 GlobalStateV0Reader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl<'r> ::core::fmt::Display for GlobalStateV0Reader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; write!(f, "{}: {}", "rollup_config_hash", self.rollup_config_hash())?; write!(f, ", {}: {}", "account", self.account())?; write!(f, ", {}: {}", "block", self.block())?; write!( f, ", {}: {}", "reverted_block_root", self.reverted_block_root() )?; write!(f, ", {}: {}", "tip_block_hash", self.tip_block_hash())?; write!( f, ", {}: {}", "last_finalized_block_number", self.last_finalized_block_number() )?; write!(f, ", {}: {}", "status", self.status())?; write!(f, " }}") } } impl<'r> GlobalStateV0Reader<'r> { pub const TOTAL_SIZE: usize = 181; pub const FIELD_SIZES: [usize; 7] = [32, 36, 40, 32, 32, 8, 1]; pub const FIELD_COUNT: usize = 7; pub fn rollup_config_hash(&self) -> Byte32Reader<'r> { Byte32Reader::new_unchecked(&self.as_slice()[0..32]) } pub fn account(&self) -> AccountMerkleStateReader<'r> { AccountMerkleStateReader::new_unchecked(&self.as_slice()[32..68]) } pub fn block(&self) -> BlockMerkleStateReader<'r> { BlockMerkleStateReader::new_unchecked(&self.as_slice()[68..108]) } pub fn reverted_block_root(&self) -> Byte32Reader<'r> { Byte32Reader::new_unchecked(&self.as_slice()[108..140]) } pub fn tip_block_hash(&self) -> Byte32Reader<'r> { Byte32Reader::new_unchecked(&self.as_slice()[140..172]) } pub fn last_finalized_block_number(&self) -> Uint64Reader<'r> { Uint64Reader::new_unchecked(&self.as_slice()[172..180]) } pub fn status(&self) -> ByteReader<'r> { ByteReader::new_unchecked(&self.as_slice()[180..181]) } } impl<'r> molecule::prelude::Reader<'r> for GlobalStateV0Reader<'r> { type Entity = GlobalStateV0; const NAME: &'static str = "GlobalStateV0Reader"; fn to_entity(&self) -> Self::Entity { Self::Entity::new_unchecked(self.as_slice().to_owned().into()) } fn new_unchecked(slice: &'r [u8]) -> Self { GlobalStateV0Reader(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(()) } } #[derive(Debug, Default)] pub struct GlobalStateV0Builder { pub(crate) rollup_config_hash: Byte32, pub(crate) account: AccountMerkleState, pub(crate) block: BlockMerkleState, pub(crate) reverted_block_root: Byte32, pub(crate) tip_block_hash: Byte32, pub(crate) last_finalized_block_number: Uint64, pub(crate) status: Byte, } impl GlobalStateV0Builder { pub const TOTAL_SIZE: usize = 181; pub const FIELD_SIZES: [usize; 7] = [32, 36, 40, 32, 32, 8, 1]; pub const FIELD_COUNT: usize = 7; pub fn rollup_config_hash(mut self, v: Byte32) -> Self { self.rollup_config_hash = v; self } pub fn account(mut self, v: AccountMerkleState) -> Self { self.account = v; self } pub fn block(mut self, v: BlockMerkleState) -> Self { self.block = v; self } pub fn reverted_block_root(mut self, v: Byte32) -> Self { self.reverted_block_root = v; self } pub fn tip_block_hash(mut self, v: Byte32) -> Self { self.tip_block_hash = v; self } pub fn last_finalized_block_number(mut self, v: Uint64) -> Self { self.last_finalized_block_number = v; self } pub fn status(mut self, v: Byte) -> Self { self.status = v; self } } impl molecule::prelude::Builder for GlobalStateV0Builder { type Entity = GlobalStateV0; const NAME: &'static str = "GlobalStateV0Builder"; 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.rollup_config_hash.as_slice())?; writer.write_all(self.account.as_slice())?; writer.write_all(self.block.as_slice())?; writer.write_all(self.reverted_block_root.as_slice())?; writer.write_all(self.tip_block_hash.as_slice())?; writer.write_all(self.last_finalized_block_number.as_slice())?; writer.write_all(self.status.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)); GlobalStateV0::new_unchecked(inner.into()) } } #[derive(Clone)] pub struct GlobalState(molecule::bytes::Bytes); impl ::core::fmt::LowerHex for GlobalState { 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 GlobalState { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl ::core::fmt::Display for GlobalState { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; write!(f, "{}: {}", "rollup_config_hash", self.rollup_config_hash())?; write!(f, ", {}: {}", "account", self.account())?; write!(f, ", {}: {}", "block", self.block())?; write!( f, ", {}: {}", "reverted_block_root", self.reverted_block_root() )?; write!(f, ", {}: {}", "tip_block_hash", self.tip_block_hash())?; write!( f, ", {}: {}", "tip_block_timestamp", self.tip_block_timestamp() )?; write!( f, ", {}: {}", "last_finalized_block_number", self.last_finalized_block_number() )?; write!(f, ", {}: {}", "status", self.status())?; write!(f, ", {}: {}", "version", self.version())?; write!(f, " }}") } } impl ::core::default::Default for GlobalState { fn default() -> Self { let v: Vec<u8> = vec![ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ]; GlobalState::new_unchecked(v.into()) } } impl GlobalState { pub const TOTAL_SIZE: usize = 190; pub const FIELD_SIZES: [usize; 9] = [32, 36, 40, 32, 32, 8, 8, 1, 1]; pub const FIELD_COUNT: usize = 9; pub fn rollup_config_hash(&self) -> Byte32 { Byte32::new_unchecked(self.0.slice(0..32)) } pub fn account(&self) -> AccountMerkleState { AccountMerkleState::new_unchecked(self.0.slice(32..68)) } pub fn block(&self) -> BlockMerkleState { BlockMerkleState::new_unchecked(self.0.slice(68..108)) } pub fn reverted_block_root(&self) -> Byte32 { Byte32::new_unchecked(self.0.slice(108..140)) } pub fn tip_block_hash(&self) -> Byte32 { Byte32::new_unchecked(self.0.slice(140..172)) } pub fn tip_block_timestamp(&self) -> Uint64 { Uint64::new_unchecked(self.0.slice(172..180)) } pub fn last_finalized_block_number(&self) -> Uint64 { Uint64::new_unchecked(self.0.slice(180..188)) } pub fn status(&self) -> Byte { Byte::new_unchecked(self.0.slice(188..189)) } pub fn version(&self) -> Byte { Byte::new_unchecked(self.0.slice(189..190)) } pub fn as_reader<'r>(&'r self) -> GlobalStateReader<'r> { GlobalStateReader::new_unchecked(self.as_slice()) } } impl molecule::prelude::Entity for GlobalState { type Builder = GlobalStateBuilder; const NAME: &'static str = "GlobalState"; fn new_unchecked(data: molecule::bytes::Bytes) -> Self { GlobalState(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> { GlobalStateReader::from_slice(slice).map(|reader| reader.to_entity()) } fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> { GlobalStateReader::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() .rollup_config_hash(self.rollup_config_hash()) .account(self.account()) .block(self.block()) .reverted_block_root(self.reverted_block_root()) .tip_block_hash(self.tip_block_hash()) .tip_block_timestamp(self.tip_block_timestamp()) .last_finalized_block_number(self.last_finalized_block_number()) .status(self.status()) .version(self.version()) } } #[derive(Clone, Copy)] pub struct GlobalStateReader<'r>(&'r [u8]); impl<'r> ::core::fmt::LowerHex for GlobalStateReader<'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 GlobalStateReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl<'r> ::core::fmt::Display for GlobalStateReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; write!(f, "{}: {}", "rollup_config_hash", self.rollup_config_hash())?; write!(f, ", {}: {}", "account", self.account())?; write!(f, ", {}: {}", "block", self.block())?; write!( f, ", {}: {}", "reverted_block_root", self.reverted_block_root() )?; write!(f, ", {}: {}", "tip_block_hash", self.tip_block_hash())?; write!( f, ", {}: {}", "tip_block_timestamp", self.tip_block_timestamp() )?; write!( f, ", {}: {}", "last_finalized_block_number", self.last_finalized_block_number() )?; write!(f, ", {}: {}", "status", self.status())?; write!(f, ", {}: {}", "version", self.version())?; write!(f, " }}") } } impl<'r> GlobalStateReader<'r> { pub const TOTAL_SIZE: usize = 190; pub const FIELD_SIZES: [usize; 9] = [32, 36, 40, 32, 32, 8, 8, 1, 1]; pub const FIELD_COUNT: usize = 9; pub fn rollup_config_hash(&self) -> Byte32Reader<'r> { Byte32Reader::new_unchecked(&self.as_slice()[0..32]) } pub fn account(&self) -> AccountMerkleStateReader<'r> { AccountMerkleStateReader::new_unchecked(&self.as_slice()[32..68]) } pub fn block(&self) -> BlockMerkleStateReader<'r> { BlockMerkleStateReader::new_unchecked(&self.as_slice()[68..108]) } pub fn reverted_block_root(&self) -> Byte32Reader<'r> { Byte32Reader::new_unchecked(&self.as_slice()[108..140]) } pub fn tip_block_hash(&self) -> Byte32Reader<'r> { Byte32Reader::new_unchecked(&self.as_slice()[140..172]) } pub fn tip_block_timestamp(&self) -> Uint64Reader<'r> { Uint64Reader::new_unchecked(&self.as_slice()[172..180]) } pub fn last_finalized_block_number(&self) -> Uint64Reader<'r> { Uint64Reader::new_unchecked(&self.as_slice()[180..188]) } pub fn status(&self) -> ByteReader<'r> { ByteReader::new_unchecked(&self.as_slice()[188..189]) } pub fn version(&self) -> ByteReader<'r> { ByteReader::new_unchecked(&self.as_slice()[189..190]) } } impl<'r> molecule::prelude::Reader<'r> for GlobalStateReader<'r> { type Entity = GlobalState; const NAME: &'static str = "GlobalStateReader"; fn to_entity(&self) -> Self::Entity { Self::Entity::new_unchecked(self.as_slice().to_owned().into()) } fn new_unchecked(slice: &'r [u8]) -> Self { GlobalStateReader(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(()) } } #[derive(Debug, Default)] pub struct GlobalStateBuilder { pub(crate) rollup_config_hash: Byte32, pub(crate) account: AccountMerkleState, pub(crate) block: BlockMerkleState, pub(crate) reverted_block_root: Byte32, pub(crate) tip_block_hash: Byte32, pub(crate) tip_block_timestamp: Uint64, pub(crate) last_finalized_block_number: Uint64, pub(crate) status: Byte, pub(crate) version: Byte, } impl GlobalStateBuilder { pub const TOTAL_SIZE: usize = 190; pub const FIELD_SIZES: [usize; 9] = [32, 36, 40, 32, 32, 8, 8, 1, 1]; pub const FIELD_COUNT: usize = 9; pub fn rollup_config_hash(mut self, v: Byte32) -> Self { self.rollup_config_hash = v; self } pub fn account(mut self, v: AccountMerkleState) -> Self { self.account = v; self } pub fn block(mut self, v: BlockMerkleState) -> Self { self.block = v; self } pub fn reverted_block_root(mut self, v: Byte32) -> Self { self.reverted_block_root = v; self } pub fn tip_block_hash(mut self, v: Byte32) -> Self { self.tip_block_hash = v; self } pub fn tip_block_timestamp(mut self, v: Uint64) -> Self { self.tip_block_timestamp = v; self } pub fn last_finalized_block_number(mut self, v: Uint64) -> Self { self.last_finalized_block_number = v; self } pub fn status(mut self, v: Byte) -> Self { self.status = v; self } pub fn version(mut self, v: Byte) -> Self { self.version = v; self } } impl molecule::prelude::Builder for GlobalStateBuilder { type Entity = GlobalState; const NAME: &'static str = "GlobalStateBuilder"; 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.rollup_config_hash.as_slice())?; writer.write_all(self.account.as_slice())?; writer.write_all(self.block.as_slice())?; writer.write_all(self.reverted_block_root.as_slice())?; writer.write_all(self.tip_block_hash.as_slice())?; writer.write_all(self.tip_block_timestamp.as_slice())?; writer.write_all(self.last_finalized_block_number.as_slice())?; writer.write_all(self.status.as_slice())?; writer.write_all(self.version.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)); GlobalState::new_unchecked(inner.into()) } } #[derive(Clone)] pub struct RollupConfig(molecule::bytes::Bytes); impl ::core::fmt::LowerHex for RollupConfig { 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 RollupConfig { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl ::core::fmt::Display for RollupConfig { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; write!( f, "{}: {}", "l1_sudt_script_type_hash", self.l1_sudt_script_type_hash() )?; write!( f, ", {}: {}", "custodian_script_type_hash", self.custodian_script_type_hash() )?; write!( f, ", {}: {}", "deposit_script_type_hash", self.deposit_script_type_hash() )?; write!( f, ", {}: {}", "withdrawal_script_type_hash", self.withdrawal_script_type_hash() )?; write!( f, ", {}: {}", "challenge_script_type_hash", self.challenge_script_type_hash() )?; write!( f, ", {}: {}", "stake_script_type_hash", self.stake_script_type_hash() )?; write!( f, ", {}: {}", "l2_sudt_validator_script_type_hash", self.l2_sudt_validator_script_type_hash() )?; write!(f, ", {}: {}", "burn_lock_hash", self.burn_lock_hash())?; write!( f, ", {}: {}", "required_staking_capacity", self.required_staking_capacity() )?; write!( f, ", {}: {}", "challenge_maturity_blocks", self.challenge_maturity_blocks() )?; write!(f, ", {}: {}", "finality_blocks", self.finality_blocks())?; write!(f, ", {}: {}", "reward_burn_rate", self.reward_burn_rate())?; write!( f, ", {}: {}", "allowed_eoa_type_hashes", self.allowed_eoa_type_hashes() )?; write!( f, ", {}: {}", "allowed_contract_type_hashes", self.allowed_contract_type_hashes() )?; let extra_count = self.count_extra_fields(); if extra_count != 0 { write!(f, ", .. ({} fields)", extra_count)?; } write!(f, " }}") } } impl ::core::default::Default for RollupConfig { fn default() -> Self { let v: Vec<u8> = vec![ 93, 1, 0, 0, 60, 0, 0, 0, 92, 0, 0, 0, 124, 0, 0, 0, 156, 0, 0, 0, 188, 0, 0, 0, 220, 0, 0, 0, 252, 0, 0, 0, 28, 1, 0, 0, 60, 1, 0, 0, 68, 1, 0, 0, 76, 1, 0, 0, 84, 1, 0, 0, 85, 1, 0, 0, 89, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ]; RollupConfig::new_unchecked(v.into()) } } impl RollupConfig { pub const FIELD_COUNT: usize = 14; 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 l1_sudt_script_type_hash(&self) -> Byte32 { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[4..]) as usize; let end = molecule::unpack_number(&slice[8..]) as usize; Byte32::new_unchecked(self.0.slice(start..end)) } pub fn custodian_script_type_hash(&self) -> Byte32 { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[8..]) as usize; let end = molecule::unpack_number(&slice[12..]) as usize; Byte32::new_unchecked(self.0.slice(start..end)) } pub fn deposit_script_type_hash(&self) -> Byte32 { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[12..]) as usize; let end = molecule::unpack_number(&slice[16..]) as usize; Byte32::new_unchecked(self.0.slice(start..end)) } pub fn withdrawal_script_type_hash(&self) -> Byte32 { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[16..]) as usize; let end = molecule::unpack_number(&slice[20..]) as usize; Byte32::new_unchecked(self.0.slice(start..end)) } pub fn challenge_script_type_hash(&self) -> Byte32 { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[20..]) as usize; let end = molecule::unpack_number(&slice[24..]) as usize; Byte32::new_unchecked(self.0.slice(start..end)) } pub fn stake_script_type_hash(&self) -> Byte32 { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[24..]) as usize; let end = molecule::unpack_number(&slice[28..]) as usize; Byte32::new_unchecked(self.0.slice(start..end)) } pub fn l2_sudt_validator_script_type_hash(&self) -> Byte32 { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[28..]) as usize; let end = molecule::unpack_number(&slice[32..]) as usize; Byte32::new_unchecked(self.0.slice(start..end)) } pub fn burn_lock_hash(&self) -> Byte32 { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[32..]) as usize; let end = molecule::unpack_number(&slice[36..]) as usize; Byte32::new_unchecked(self.0.slice(start..end)) } pub fn required_staking_capacity(&self) -> Uint64 { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[36..]) as usize; let end = molecule::unpack_number(&slice[40..]) as usize; Uint64::new_unchecked(self.0.slice(start..end)) } pub fn challenge_maturity_blocks(&self) -> Uint64 { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[40..]) as usize; let end = molecule::unpack_number(&slice[44..]) as usize; Uint64::new_unchecked(self.0.slice(start..end)) } pub fn finality_blocks(&self) -> Uint64 { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[44..]) as usize; let end = molecule::unpack_number(&slice[48..]) as usize; Uint64::new_unchecked(self.0.slice(start..end)) } pub fn reward_burn_rate(&self) -> Byte { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[48..]) as usize; let end = molecule::unpack_number(&slice[52..]) as usize; Byte::new_unchecked(self.0.slice(start..end)) } pub fn allowed_eoa_type_hashes(&self) -> Byte32Vec { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[52..]) as usize; let end = molecule::unpack_number(&slice[56..]) as usize; Byte32Vec::new_unchecked(self.0.slice(start..end)) } pub fn allowed_contract_type_hashes(&self) -> Byte32Vec { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[56..]) as usize; if self.has_extra_fields() { let end = molecule::unpack_number(&slice[60..]) as usize; Byte32Vec::new_unchecked(self.0.slice(start..end)) } else { Byte32Vec::new_unchecked(self.0.slice(start..)) } } pub fn as_reader<'r>(&'r self) -> RollupConfigReader<'r> { RollupConfigReader::new_unchecked(self.as_slice()) } } impl molecule::prelude::Entity for RollupConfig { type Builder = RollupConfigBuilder; const NAME: &'static str = "RollupConfig"; fn new_unchecked(data: molecule::bytes::Bytes) -> Self { RollupConfig(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> { RollupConfigReader::from_slice(slice).map(|reader| reader.to_entity()) } fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> { RollupConfigReader::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() .l1_sudt_script_type_hash(self.l1_sudt_script_type_hash()) .custodian_script_type_hash(self.custodian_script_type_hash()) .deposit_script_type_hash(self.deposit_script_type_hash()) .withdrawal_script_type_hash(self.withdrawal_script_type_hash()) .challenge_script_type_hash(self.challenge_script_type_hash()) .stake_script_type_hash(self.stake_script_type_hash()) .l2_sudt_validator_script_type_hash(self.l2_sudt_validator_script_type_hash()) .burn_lock_hash(self.burn_lock_hash()) .required_staking_capacity(self.required_staking_capacity()) .challenge_maturity_blocks(self.challenge_maturity_blocks()) .finality_blocks(self.finality_blocks()) .reward_burn_rate(self.reward_burn_rate()) .allowed_eoa_type_hashes(self.allowed_eoa_type_hashes()) .allowed_contract_type_hashes(self.allowed_contract_type_hashes()) } } #[derive(Clone, Copy)] pub struct RollupConfigReader<'r>(&'r [u8]); impl<'r> ::core::fmt::LowerHex for RollupConfigReader<'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 RollupConfigReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl<'r> ::core::fmt::Display for RollupConfigReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; write!( f, "{}: {}", "l1_sudt_script_type_hash", self.l1_sudt_script_type_hash() )?; write!( f, ", {}: {}", "custodian_script_type_hash", self.custodian_script_type_hash() )?; write!( f, ", {}: {}", "deposit_script_type_hash", self.deposit_script_type_hash() )?; write!( f, ", {}: {}", "withdrawal_script_type_hash", self.withdrawal_script_type_hash() )?; write!( f, ", {}: {}", "challenge_script_type_hash", self.challenge_script_type_hash() )?; write!( f, ", {}: {}", "stake_script_type_hash", self.stake_script_type_hash() )?; write!( f, ", {}: {}", "l2_sudt_validator_script_type_hash", self.l2_sudt_validator_script_type_hash() )?; write!(f, ", {}: {}", "burn_lock_hash", self.burn_lock_hash())?; write!( f, ", {}: {}", "required_staking_capacity", self.required_staking_capacity() )?; write!( f, ", {}: {}", "challenge_maturity_blocks", self.challenge_maturity_blocks() )?; write!(f, ", {}: {}", "finality_blocks", self.finality_blocks())?; write!(f, ", {}: {}", "reward_burn_rate", self.reward_burn_rate())?; write!( f, ", {}: {}", "allowed_eoa_type_hashes", self.allowed_eoa_type_hashes() )?; write!( f, ", {}: {}", "allowed_contract_type_hashes", self.allowed_contract_type_hashes() )?; let extra_count = self.count_extra_fields(); if extra_count != 0 { write!(f, ", .. ({} fields)", extra_count)?; } write!(f, " }}") } } impl<'r> RollupConfigReader<'r> { pub const FIELD_COUNT: usize = 14; 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 l1_sudt_script_type_hash(&self) -> Byte32Reader<'r> { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[4..]) as usize; let end = molecule::unpack_number(&slice[8..]) as usize; Byte32Reader::new_unchecked(&self.as_slice()[start..end]) } pub fn custodian_script_type_hash(&self) -> Byte32Reader<'r> { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[8..]) as usize; let end = molecule::unpack_number(&slice[12..]) as usize; Byte32Reader::new_unchecked(&self.as_slice()[start..end]) } pub fn deposit_script_type_hash(&self) -> Byte32Reader<'r> { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[12..]) as usize; let end = molecule::unpack_number(&slice[16..]) as usize; Byte32Reader::new_unchecked(&self.as_slice()[start..end]) } pub fn withdrawal_script_type_hash(&self) -> Byte32Reader<'r> { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[16..]) as usize; let end = molecule::unpack_number(&slice[20..]) as usize; Byte32Reader::new_unchecked(&self.as_slice()[start..end]) } pub fn challenge_script_type_hash(&self) -> Byte32Reader<'r> { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[20..]) as usize; let end = molecule::unpack_number(&slice[24..]) as usize; Byte32Reader::new_unchecked(&self.as_slice()[start..end]) } pub fn stake_script_type_hash(&self) -> Byte32Reader<'r> { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[24..]) as usize; let end = molecule::unpack_number(&slice[28..]) as usize; Byte32Reader::new_unchecked(&self.as_slice()[start..end]) } pub fn l2_sudt_validator_script_type_hash(&self) -> Byte32Reader<'r> { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[28..]) as usize; let end = molecule::unpack_number(&slice[32..]) as usize; Byte32Reader::new_unchecked(&self.as_slice()[start..end]) } pub fn burn_lock_hash(&self) -> Byte32Reader<'r> { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[32..]) as usize; let end = molecule::unpack_number(&slice[36..]) as usize; Byte32Reader::new_unchecked(&self.as_slice()[start..end]) } pub fn required_staking_capacity(&self) -> Uint64Reader<'r> { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[36..]) as usize; let end = molecule::unpack_number(&slice[40..]) as usize; Uint64Reader::new_unchecked(&self.as_slice()[start..end]) } pub fn challenge_maturity_blocks(&self) -> Uint64Reader<'r> { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[40..]) as usize; let end = molecule::unpack_number(&slice[44..]) as usize; Uint64Reader::new_unchecked(&self.as_slice()[start..end]) } pub fn finality_blocks(&self) -> Uint64Reader<'r> { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[44..]) as usize; let end = molecule::unpack_number(&slice[48..]) as usize; Uint64Reader::new_unchecked(&self.as_slice()[start..end]) } pub fn reward_burn_rate(&self) -> ByteReader<'r> { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[48..]) as usize; let end = molecule::unpack_number(&slice[52..]) as usize; ByteReader::new_unchecked(&self.as_slice()[start..end]) } pub fn allowed_eoa_type_hashes(&self) -> Byte32VecReader<'r> { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[52..]) as usize; let end = molecule::unpack_number(&slice[56..]) as usize; Byte32VecReader::new_unchecked(&self.as_slice()[start..end]) } pub fn allowed_contract_type_hashes(&self) -> Byte32VecReader<'r> { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[56..]) as usize; if self.has_extra_fields() { let end = molecule::unpack_number(&slice[60..]) as usize; Byte32VecReader::new_unchecked(&self.as_slice()[start..end]) } else { Byte32VecReader::new_unchecked(&self.as_slice()[start..]) } } } impl<'r> molecule::prelude::Reader<'r> for RollupConfigReader<'r> { type Entity = RollupConfig; const NAME: &'static str = "RollupConfigReader"; fn to_entity(&self) -> Self::Entity { Self::Entity::new_unchecked(self.as_slice().to_owned().into()) } fn new_unchecked(slice: &'r [u8]) -> Self { RollupConfigReader(slice) } fn as_slice(&self) -> &'r [u8] { self.0 } fn verify(slice: &[u8], compatible: bool) -> molecule::error::VerificationResult<()> { use molecule::verification_error as ve; let slice_len = slice.len(); if slice_len < molecule::NUMBER_SIZE { return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE, slice_len); } let total_size = molecule::unpack_number(slice) as usize; if slice_len != total_size { return ve!(Self, TotalSizeNotMatch, total_size, slice_len); } if slice_len == molecule::NUMBER_SIZE && Self::FIELD_COUNT == 0 { return Ok(()); } if slice_len < molecule::NUMBER_SIZE * 2 { return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE * 2, slice_len); } let offset_first = molecule::unpack_number(&slice[molecule::NUMBER_SIZE..]) as usize; if offset_first % molecule::NUMBER_SIZE != 0 || offset_first < molecule::NUMBER_SIZE * 2 { return ve!(Self, OffsetsNotMatch); } if slice_len < offset_first { return ve!(Self, HeaderIsBroken, offset_first, slice_len); } let field_count = offset_first / molecule::NUMBER_SIZE - 1; if field_count < Self::FIELD_COUNT { return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, field_count); } else if !compatible && field_count > Self::FIELD_COUNT { return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, field_count); }; let mut offsets: Vec<usize> = slice[molecule::NUMBER_SIZE..offset_first] .chunks_exact(molecule::NUMBER_SIZE) .map(|x| molecule::unpack_number(x) as usize) .collect(); offsets.push(total_size); if offsets.windows(2).any(|i| i[0] > i[1]) { return ve!(Self, OffsetsNotMatch); } Byte32Reader::verify(&slice[offsets[0]..offsets[1]], compatible)?; Byte32Reader::verify(&slice[offsets[1]..offsets[2]], compatible)?; Byte32Reader::verify(&slice[offsets[2]..offsets[3]], compatible)?; Byte32Reader::verify(&slice[offsets[3]..offsets[4]], compatible)?; Byte32Reader::verify(&slice[offsets[4]..offsets[5]], compatible)?; Byte32Reader::verify(&slice[offsets[5]..offsets[6]], compatible)?; Byte32Reader::verify(&slice[offsets[6]..offsets[7]], compatible)?; Byte32Reader::verify(&slice[offsets[7]..offsets[8]], compatible)?; Uint64Reader::verify(&slice[offsets[8]..offsets[9]], compatible)?; Uint64Reader::verify(&slice[offsets[9]..offsets[10]], compatible)?; Uint64Reader::verify(&slice[offsets[10]..offsets[11]], compatible)?; ByteReader::verify(&slice[offsets[11]..offsets[12]], compatible)?; Byte32VecReader::verify(&slice[offsets[12]..offsets[13]], compatible)?; Byte32VecReader::verify(&slice[offsets[13]..offsets[14]], compatible)?; Ok(()) } } #[derive(Debug, Default)] pub struct RollupConfigBuilder { pub(crate) l1_sudt_script_type_hash: Byte32, pub(crate) custodian_script_type_hash: Byte32, pub(crate) deposit_script_type_hash: Byte32, pub(crate) withdrawal_script_type_hash: Byte32, pub(crate) challenge_script_type_hash: Byte32, pub(crate) stake_script_type_hash: Byte32, pub(crate) l2_sudt_validator_script_type_hash: Byte32, pub(crate) burn_lock_hash: Byte32, pub(crate) required_staking_capacity: Uint64, pub(crate) challenge_maturity_blocks: Uint64, pub(crate) finality_blocks: Uint64, pub(crate) reward_burn_rate: Byte, pub(crate) allowed_eoa_type_hashes: Byte32Vec, pub(crate) allowed_contract_type_hashes: Byte32Vec, } impl RollupConfigBuilder { pub const FIELD_COUNT: usize = 14; pub fn l1_sudt_script_type_hash(mut self, v: Byte32) -> Self { self.l1_sudt_script_type_hash = v; self } pub fn custodian_script_type_hash(mut self, v: Byte32) -> Self { self.custodian_script_type_hash = v; self } pub fn deposit_script_type_hash(mut self, v: Byte32) -> Self { self.deposit_script_type_hash = v; self } pub fn withdrawal_script_type_hash(mut self, v: Byte32) -> Self { self.withdrawal_script_type_hash = v; self } pub fn challenge_script_type_hash(mut self, v: Byte32) -> Self { self.challenge_script_type_hash = v; self } pub fn stake_script_type_hash(mut self, v: Byte32) -> Self { self.stake_script_type_hash = v; self } pub fn l2_sudt_validator_script_type_hash(mut self, v: Byte32) -> Self { self.l2_sudt_validator_script_type_hash = v; self } pub fn burn_lock_hash(mut self, v: Byte32) -> Self { self.burn_lock_hash = v; self } pub fn required_staking_capacity(mut self, v: Uint64) -> Self { self.required_staking_capacity = v; self } pub fn challenge_maturity_blocks(mut self, v: Uint64) -> Self { self.challenge_maturity_blocks = v; self } pub fn finality_blocks(mut self, v: Uint64) -> Self { self.finality_blocks = v; self } pub fn reward_burn_rate(mut self, v: Byte) -> Self { self.reward_burn_rate = v; self } pub fn allowed_eoa_type_hashes(mut self, v: Byte32Vec) -> Self { self.allowed_eoa_type_hashes = v; self } pub fn allowed_contract_type_hashes(mut self, v: Byte32Vec) -> Self { self.allowed_contract_type_hashes = v; self } } impl molecule::prelude::Builder for RollupConfigBuilder { type Entity = RollupConfig; const NAME: &'static str = "RollupConfigBuilder"; fn expected_length(&self) -> usize { molecule::NUMBER_SIZE * (Self::FIELD_COUNT + 1) + self.l1_sudt_script_type_hash.as_slice().len() + self.custodian_script_type_hash.as_slice().len() + self.deposit_script_type_hash.as_slice().len() + self.withdrawal_script_type_hash.as_slice().len() + self.challenge_script_type_hash.as_slice().len() + self.stake_script_type_hash.as_slice().len() + self.l2_sudt_validator_script_type_hash.as_slice().len() + self.burn_lock_hash.as_slice().len() + self.required_staking_capacity.as_slice().len() + self.challenge_maturity_blocks.as_slice().len() + self.finality_blocks.as_slice().len() + self.reward_burn_rate.as_slice().len() + self.allowed_eoa_type_hashes.as_slice().len() + self.allowed_contract_type_hashes.as_slice().len() } fn write<W: molecule::io::Write>(&self, writer: &mut W) -> molecule::io::Result<()> { let mut total_size = molecule::NUMBER_SIZE * (Self::FIELD_COUNT + 1); let mut offsets = Vec::with_capacity(Self::FIELD_COUNT); offsets.push(total_size); total_size += self.l1_sudt_script_type_hash.as_slice().len(); offsets.push(total_size); total_size += self.custodian_script_type_hash.as_slice().len(); offsets.push(total_size); total_size += self.deposit_script_type_hash.as_slice().len(); offsets.push(total_size); total_size += self.withdrawal_script_type_hash.as_slice().len(); offsets.push(total_size); total_size += self.challenge_script_type_hash.as_slice().len(); offsets.push(total_size); total_size += self.stake_script_type_hash.as_slice().len(); offsets.push(total_size); total_size += self.l2_sudt_validator_script_type_hash.as_slice().len(); offsets.push(total_size); total_size += self.burn_lock_hash.as_slice().len(); offsets.push(total_size); total_size += self.required_staking_capacity.as_slice().len(); offsets.push(total_size); total_size += self.challenge_maturity_blocks.as_slice().len(); offsets.push(total_size); total_size += self.finality_blocks.as_slice().len(); offsets.push(total_size); total_size += self.reward_burn_rate.as_slice().len(); offsets.push(total_size); total_size += self.allowed_eoa_type_hashes.as_slice().len(); offsets.push(total_size); total_size += self.allowed_contract_type_hashes.as_slice().len(); writer.write_all(&molecule::pack_number(total_size as molecule::Number))?; for offset in offsets.into_iter() { writer.write_all(&molecule::pack_number(offset as molecule::Number))?; } writer.write_all(self.l1_sudt_script_type_hash.as_slice())?; writer.write_all(self.custodian_script_type_hash.as_slice())?; writer.write_all(self.deposit_script_type_hash.as_slice())?; writer.write_all(self.withdrawal_script_type_hash.as_slice())?; writer.write_all(self.challenge_script_type_hash.as_slice())?; writer.write_all(self.stake_script_type_hash.as_slice())?; writer.write_all(self.l2_sudt_validator_script_type_hash.as_slice())?; writer.write_all(self.burn_lock_hash.as_slice())?; writer.write_all(self.required_staking_capacity.as_slice())?; writer.write_all(self.challenge_maturity_blocks.as_slice())?; writer.write_all(self.finality_blocks.as_slice())?; writer.write_all(self.reward_burn_rate.as_slice())?; writer.write_all(self.allowed_eoa_type_hashes.as_slice())?; writer.write_all(self.allowed_contract_type_hashes.as_slice())?; Ok(()) } fn build(&self) -> Self::Entity { let mut inner = Vec::with_capacity(self.expected_length()); self.write(&mut inner) .unwrap_or_else(|_| panic!("{} build should be ok", Self::NAME)); RollupConfig::new_unchecked(inner.into()) } } #[derive(Clone)] pub struct RawL2Transaction(molecule::bytes::Bytes); impl ::core::fmt::LowerHex for RawL2Transaction { 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 RawL2Transaction { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl ::core::fmt::Display for RawL2Transaction { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; write!(f, "{}: {}", "from_id", self.from_id())?; write!(f, ", {}: {}", "to_id", self.to_id())?; write!(f, ", {}: {}", "nonce", self.nonce())?; write!(f, ", {}: {}", "args", self.args())?; let extra_count = self.count_extra_fields(); if extra_count != 0 { write!(f, ", .. ({} fields)", extra_count)?; } write!(f, " }}") } } impl ::core::default::Default for RawL2Transaction { fn default() -> Self { let v: Vec<u8> = vec![ 36, 0, 0, 0, 20, 0, 0, 0, 24, 0, 0, 0, 28, 0, 0, 0, 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ]; RawL2Transaction::new_unchecked(v.into()) } } impl RawL2Transaction { 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 from_id(&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 to_id(&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 nonce(&self) -> Uint32 { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[12..]) as usize; let end = molecule::unpack_number(&slice[16..]) as usize; Uint32::new_unchecked(self.0.slice(start..end)) } pub fn args(&self) -> Bytes { 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; Bytes::new_unchecked(self.0.slice(start..end)) } else { Bytes::new_unchecked(self.0.slice(start..)) } } pub fn as_reader<'r>(&'r self) -> RawL2TransactionReader<'r> { RawL2TransactionReader::new_unchecked(self.as_slice()) } } impl molecule::prelude::Entity for RawL2Transaction { type Builder = RawL2TransactionBuilder; const NAME: &'static str = "RawL2Transaction"; fn new_unchecked(data: molecule::bytes::Bytes) -> Self { RawL2Transaction(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> { RawL2TransactionReader::from_slice(slice).map(|reader| reader.to_entity()) } fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> { RawL2TransactionReader::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() .from_id(self.from_id()) .to_id(self.to_id()) .nonce(self.nonce()) .args(self.args()) } } #[derive(Clone, Copy)] pub struct RawL2TransactionReader<'r>(&'r [u8]); impl<'r> ::core::fmt::LowerHex for RawL2TransactionReader<'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 RawL2TransactionReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl<'r> ::core::fmt::Display for RawL2TransactionReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; write!(f, "{}: {}", "from_id", self.from_id())?; write!(f, ", {}: {}", "to_id", self.to_id())?; write!(f, ", {}: {}", "nonce", self.nonce())?; write!(f, ", {}: {}", "args", self.args())?; let extra_count = self.count_extra_fields(); if extra_count != 0 { write!(f, ", .. ({} fields)", extra_count)?; } write!(f, " }}") } } impl<'r> RawL2TransactionReader<'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 from_id(&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 to_id(&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 nonce(&self) -> Uint32Reader<'r> { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[12..]) as usize; let end = molecule::unpack_number(&slice[16..]) as usize; Uint32Reader::new_unchecked(&self.as_slice()[start..end]) } pub fn args(&self) -> BytesReader<'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; BytesReader::new_unchecked(&self.as_slice()[start..end]) } else { BytesReader::new_unchecked(&self.as_slice()[start..]) } } } impl<'r> molecule::prelude::Reader<'r> for RawL2TransactionReader<'r> { type Entity = RawL2Transaction; const NAME: &'static str = "RawL2TransactionReader"; fn to_entity(&self) -> Self::Entity { Self::Entity::new_unchecked(self.as_slice().to_owned().into()) } fn new_unchecked(slice: &'r [u8]) -> Self { RawL2TransactionReader(slice) } fn as_slice(&self) -> &'r [u8] { self.0 } fn verify(slice: &[u8], compatible: bool) -> molecule::error::VerificationResult<()> { use molecule::verification_error as ve; let slice_len = slice.len(); if slice_len < molecule::NUMBER_SIZE { return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE, slice_len); } let total_size = molecule::unpack_number(slice) as usize; if slice_len != total_size { return ve!(Self, TotalSizeNotMatch, total_size, slice_len); } if slice_len == molecule::NUMBER_SIZE && Self::FIELD_COUNT == 0 { return Ok(()); } if slice_len < molecule::NUMBER_SIZE * 2 { return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE * 2, slice_len); } let offset_first = molecule::unpack_number(&slice[molecule::NUMBER_SIZE..]) as usize; if offset_first % molecule::NUMBER_SIZE != 0 || offset_first < molecule::NUMBER_SIZE * 2 { return ve!(Self, OffsetsNotMatch); } if slice_len < offset_first { return ve!(Self, HeaderIsBroken, offset_first, slice_len); } let field_count = offset_first / molecule::NUMBER_SIZE - 1; if field_count < Self::FIELD_COUNT { return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, field_count); } else if !compatible && field_count > Self::FIELD_COUNT { return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, field_count); }; let mut offsets: Vec<usize> = slice[molecule::NUMBER_SIZE..offset_first] .chunks_exact(molecule::NUMBER_SIZE) .map(|x| molecule::unpack_number(x) as usize) .collect(); offsets.push(total_size); if offsets.windows(2).any(|i| i[0] > i[1]) { return ve!(Self, OffsetsNotMatch); } Uint32Reader::verify(&slice[offsets[0]..offsets[1]], compatible)?; Uint32Reader::verify(&slice[offsets[1]..offsets[2]], compatible)?; Uint32Reader::verify(&slice[offsets[2]..offsets[3]], compatible)?; BytesReader::verify(&slice[offsets[3]..offsets[4]], compatible)?; Ok(()) } } #[derive(Debug, Default)] pub struct RawL2TransactionBuilder { pub(crate) from_id: Uint32, pub(crate) to_id: Uint32, pub(crate) nonce: Uint32, pub(crate) args: Bytes, } impl RawL2TransactionBuilder { pub const FIELD_COUNT: usize = 4; pub fn from_id(mut self, v: Uint32) -> Self { self.from_id = v; self } pub fn to_id(mut self, v: Uint32) -> Self { self.to_id = v; self } pub fn nonce(mut self, v: Uint32) -> Self { self.nonce = v; self } pub fn args(mut self, v: Bytes) -> Self { self.args = v; self } } impl molecule::prelude::Builder for RawL2TransactionBuilder { type Entity = RawL2Transaction; const NAME: &'static str = "RawL2TransactionBuilder"; fn expected_length(&self) -> usize { molecule::NUMBER_SIZE * (Self::FIELD_COUNT + 1) + self.from_id.as_slice().len() + self.to_id.as_slice().len() + self.nonce.as_slice().len() + self.args.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.from_id.as_slice().len(); offsets.push(total_size); total_size += self.to_id.as_slice().len(); offsets.push(total_size); total_size += self.nonce.as_slice().len(); offsets.push(total_size); total_size += self.args.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.from_id.as_slice())?; writer.write_all(self.to_id.as_slice())?; writer.write_all(self.nonce.as_slice())?; writer.write_all(self.args.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)); RawL2Transaction::new_unchecked(inner.into()) } } #[derive(Clone)] pub struct L2Transaction(molecule::bytes::Bytes); impl ::core::fmt::LowerHex for L2Transaction { 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 L2Transaction { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl ::core::fmt::Display for L2Transaction { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; write!(f, "{}: {}", "raw", self.raw())?; write!(f, ", {}: {}", "signature", self.signature())?; let extra_count = self.count_extra_fields(); if extra_count != 0 { write!(f, ", .. ({} fields)", extra_count)?; } write!(f, " }}") } } impl ::core::default::Default for L2Transaction { fn default() -> Self { let v: Vec<u8> = vec![ 52, 0, 0, 0, 12, 0, 0, 0, 48, 0, 0, 0, 36, 0, 0, 0, 20, 0, 0, 0, 24, 0, 0, 0, 28, 0, 0, 0, 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ]; L2Transaction::new_unchecked(v.into()) } } impl L2Transaction { 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 raw(&self) -> RawL2Transaction { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[4..]) as usize; let end = molecule::unpack_number(&slice[8..]) as usize; RawL2Transaction::new_unchecked(self.0.slice(start..end)) } pub fn signature(&self) -> Bytes { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[8..]) as usize; if self.has_extra_fields() { let end = molecule::unpack_number(&slice[12..]) as usize; Bytes::new_unchecked(self.0.slice(start..end)) } else { Bytes::new_unchecked(self.0.slice(start..)) } } pub fn as_reader<'r>(&'r self) -> L2TransactionReader<'r> { L2TransactionReader::new_unchecked(self.as_slice()) } } impl molecule::prelude::Entity for L2Transaction { type Builder = L2TransactionBuilder; const NAME: &'static str = "L2Transaction"; fn new_unchecked(data: molecule::bytes::Bytes) -> Self { L2Transaction(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> { L2TransactionReader::from_slice(slice).map(|reader| reader.to_entity()) } fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> { L2TransactionReader::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() .raw(self.raw()) .signature(self.signature()) } } #[derive(Clone, Copy)] pub struct L2TransactionReader<'r>(&'r [u8]); impl<'r> ::core::fmt::LowerHex for L2TransactionReader<'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 L2TransactionReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl<'r> ::core::fmt::Display for L2TransactionReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; write!(f, "{}: {}", "raw", self.raw())?; write!(f, ", {}: {}", "signature", self.signature())?; let extra_count = self.count_extra_fields(); if extra_count != 0 { write!(f, ", .. ({} fields)", extra_count)?; } write!(f, " }}") } } impl<'r> L2TransactionReader<'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 raw(&self) -> RawL2TransactionReader<'r> { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[4..]) as usize; let end = molecule::unpack_number(&slice[8..]) as usize; RawL2TransactionReader::new_unchecked(&self.as_slice()[start..end]) } pub fn signature(&self) -> BytesReader<'r> { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[8..]) as usize; if self.has_extra_fields() { let end = molecule::unpack_number(&slice[12..]) as usize; BytesReader::new_unchecked(&self.as_slice()[start..end]) } else { BytesReader::new_unchecked(&self.as_slice()[start..]) } } } impl<'r> molecule::prelude::Reader<'r> for L2TransactionReader<'r> { type Entity = L2Transaction; const NAME: &'static str = "L2TransactionReader"; fn to_entity(&self) -> Self::Entity { Self::Entity::new_unchecked(self.as_slice().to_owned().into()) } fn new_unchecked(slice: &'r [u8]) -> Self { L2TransactionReader(slice) } fn as_slice(&self) -> &'r [u8] { self.0 } fn verify(slice: &[u8], compatible: bool) -> molecule::error::VerificationResult<()> { use molecule::verification_error as ve; let slice_len = slice.len(); if slice_len < molecule::NUMBER_SIZE { return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE, slice_len); } let total_size = molecule::unpack_number(slice) as usize; if slice_len != total_size { return ve!(Self, TotalSizeNotMatch, total_size, slice_len); } if slice_len == molecule::NUMBER_SIZE && Self::FIELD_COUNT == 0 { return Ok(()); } if slice_len < molecule::NUMBER_SIZE * 2 { return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE * 2, slice_len); } let offset_first = molecule::unpack_number(&slice[molecule::NUMBER_SIZE..]) as usize; if offset_first % molecule::NUMBER_SIZE != 0 || offset_first < molecule::NUMBER_SIZE * 2 { return ve!(Self, OffsetsNotMatch); } if slice_len < offset_first { return ve!(Self, HeaderIsBroken, offset_first, slice_len); } let field_count = offset_first / molecule::NUMBER_SIZE - 1; if field_count < Self::FIELD_COUNT { return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, field_count); } else if !compatible && field_count > Self::FIELD_COUNT { return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, field_count); }; let mut offsets: Vec<usize> = slice[molecule::NUMBER_SIZE..offset_first] .chunks_exact(molecule::NUMBER_SIZE) .map(|x| molecule::unpack_number(x) as usize) .collect(); offsets.push(total_size); if offsets.windows(2).any(|i| i[0] > i[1]) { return ve!(Self, OffsetsNotMatch); } RawL2TransactionReader::verify(&slice[offsets[0]..offsets[1]], compatible)?; BytesReader::verify(&slice[offsets[1]..offsets[2]], compatible)?; Ok(()) } } #[derive(Debug, Default)] pub struct L2TransactionBuilder { pub(crate) raw: RawL2Transaction, pub(crate) signature: Bytes, } impl L2TransactionBuilder { pub const FIELD_COUNT: usize = 2; pub fn raw(mut self, v: RawL2Transaction) -> Self { self.raw = v; self } pub fn signature(mut self, v: Bytes) -> Self { self.signature = v; self } } impl molecule::prelude::Builder for L2TransactionBuilder { type Entity = L2Transaction; const NAME: &'static str = "L2TransactionBuilder"; fn expected_length(&self) -> usize { molecule::NUMBER_SIZE * (Self::FIELD_COUNT + 1) + self.raw.as_slice().len() + self.signature.as_slice().len() } fn write<W: molecule::io::Write>(&self, writer: &mut W) -> molecule::io::Result<()> { let mut total_size = molecule::NUMBER_SIZE * (Self::FIELD_COUNT + 1); let mut offsets = Vec::with_capacity(Self::FIELD_COUNT); offsets.push(total_size); total_size += self.raw.as_slice().len(); offsets.push(total_size); total_size += self.signature.as_slice().len(); writer.write_all(&molecule::pack_number(total_size as molecule::Number))?; for offset in offsets.into_iter() { writer.write_all(&molecule::pack_number(offset as molecule::Number))?; } writer.write_all(self.raw.as_slice())?; writer.write_all(self.signature.as_slice())?; Ok(()) } fn build(&self) -> Self::Entity { let mut inner = Vec::with_capacity(self.expected_length()); self.write(&mut inner) .unwrap_or_else(|_| panic!("{} build should be ok", Self::NAME)); L2Transaction::new_unchecked(inner.into()) } } #[derive(Clone)] pub struct L2TransactionVec(molecule::bytes::Bytes); impl ::core::fmt::LowerHex for L2TransactionVec { 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 L2TransactionVec { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl ::core::fmt::Display for L2TransactionVec { 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 L2TransactionVec { fn default() -> Self { let v: Vec<u8> = vec![4, 0, 0, 0]; L2TransactionVec::new_unchecked(v.into()) } } impl L2TransactionVec { 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<L2Transaction> { if idx >= self.len() { None } else { Some(self.get_unchecked(idx)) } } pub fn get_unchecked(&self, idx: usize) -> L2Transaction { 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 { L2Transaction::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; L2Transaction::new_unchecked(self.0.slice(start..end)) } } pub fn as_reader<'r>(&'r self) -> L2TransactionVecReader<'r> { L2TransactionVecReader::new_unchecked(self.as_slice()) } } impl molecule::prelude::Entity for L2TransactionVec { type Builder = L2TransactionVecBuilder; const NAME: &'static str = "L2TransactionVec"; fn new_unchecked(data: molecule::bytes::Bytes) -> Self { L2TransactionVec(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> { L2TransactionVecReader::from_slice(slice).map(|reader| reader.to_entity()) } fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> { L2TransactionVecReader::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 L2TransactionVecReader<'r>(&'r [u8]); impl<'r> ::core::fmt::LowerHex for L2TransactionVecReader<'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 L2TransactionVecReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl<'r> ::core::fmt::Display for L2TransactionVecReader<'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> L2TransactionVecReader<'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<L2TransactionReader<'r>> { if idx >= self.len() { None } else { Some(self.get_unchecked(idx)) } } pub fn get_unchecked(&self, idx: usize) -> L2TransactionReader<'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 { L2TransactionReader::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; L2TransactionReader::new_unchecked(&self.as_slice()[start..end]) } } } impl<'r> molecule::prelude::Reader<'r> for L2TransactionVecReader<'r> { type Entity = L2TransactionVec; const NAME: &'static str = "L2TransactionVecReader"; fn to_entity(&self) -> Self::Entity { Self::Entity::new_unchecked(self.as_slice().to_owned().into()) } fn new_unchecked(slice: &'r [u8]) -> Self { L2TransactionVecReader(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]; L2TransactionReader::verify(&slice[start..end], compatible)?; } Ok(()) } } #[derive(Debug, Default)] pub struct L2TransactionVecBuilder(pub(crate) Vec<L2Transaction>); impl L2TransactionVecBuilder { pub fn set(mut self, v: Vec<L2Transaction>) -> Self { self.0 = v; self } pub fn push(mut self, v: L2Transaction) -> Self { self.0.push(v); self } pub fn extend<T: ::core::iter::IntoIterator<Item = L2Transaction>>(mut self, iter: T) -> Self { for elem in iter { self.0.push(elem); } self } } impl molecule::prelude::Builder for L2TransactionVecBuilder { type Entity = L2TransactionVec; const NAME: &'static str = "L2TransactionVecBuilder"; 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)); L2TransactionVec::new_unchecked(inner.into()) } } pub struct L2TransactionVecIterator(L2TransactionVec, usize, usize); impl ::core::iter::Iterator for L2TransactionVecIterator { type Item = L2Transaction; 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 L2TransactionVecIterator { fn len(&self) -> usize { self.2 - self.1 } } impl ::core::iter::IntoIterator for L2TransactionVec { type Item = L2Transaction; type IntoIter = L2TransactionVecIterator; fn into_iter(self) -> Self::IntoIter { let len = self.len(); L2TransactionVecIterator(self, 0, len) } } impl<'r> L2TransactionVecReader<'r> { pub fn iter<'t>(&'t self) -> L2TransactionVecReaderIterator<'t, 'r> { L2TransactionVecReaderIterator(&self, 0, self.len()) } } pub struct L2TransactionVecReaderIterator<'t, 'r>(&'t L2TransactionVecReader<'r>, usize, usize); impl<'t: 'r, 'r> ::core::iter::Iterator for L2TransactionVecReaderIterator<'t, 'r> { type Item = L2TransactionReader<'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 L2TransactionVecReaderIterator<'t, 'r> { fn len(&self) -> usize { self.2 - self.1 } } #[derive(Clone)] pub struct SubmitTransactions(molecule::bytes::Bytes); impl ::core::fmt::LowerHex for SubmitTransactions { 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 SubmitTransactions { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl ::core::fmt::Display for SubmitTransactions { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; write!(f, "{}: {}", "tx_witness_root", self.tx_witness_root())?; write!(f, ", {}: {}", "tx_count", self.tx_count())?; write!( f, ", {}: {}", "prev_state_checkpoint", self.prev_state_checkpoint() )?; let extra_count = self.count_extra_fields(); if extra_count != 0 { write!(f, ", .. ({} fields)", extra_count)?; } write!(f, " }}") } } impl ::core::default::Default for SubmitTransactions { fn default() -> Self { let v: Vec<u8> = vec![ 84, 0, 0, 0, 16, 0, 0, 0, 48, 0, 0, 0, 52, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ]; SubmitTransactions::new_unchecked(v.into()) } } impl SubmitTransactions { 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 tx_witness_root(&self) -> Byte32 { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[4..]) as usize; let end = molecule::unpack_number(&slice[8..]) as usize; Byte32::new_unchecked(self.0.slice(start..end)) } pub fn tx_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 prev_state_checkpoint(&self) -> Byte32 { 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; Byte32::new_unchecked(self.0.slice(start..end)) } else { Byte32::new_unchecked(self.0.slice(start..)) } } pub fn as_reader<'r>(&'r self) -> SubmitTransactionsReader<'r> { SubmitTransactionsReader::new_unchecked(self.as_slice()) } } impl molecule::prelude::Entity for SubmitTransactions { type Builder = SubmitTransactionsBuilder; const NAME: &'static str = "SubmitTransactions"; fn new_unchecked(data: molecule::bytes::Bytes) -> Self { SubmitTransactions(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> { SubmitTransactionsReader::from_slice(slice).map(|reader| reader.to_entity()) } fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> { SubmitTransactionsReader::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() .tx_witness_root(self.tx_witness_root()) .tx_count(self.tx_count()) .prev_state_checkpoint(self.prev_state_checkpoint()) } } #[derive(Clone, Copy)] pub struct SubmitTransactionsReader<'r>(&'r [u8]); impl<'r> ::core::fmt::LowerHex for SubmitTransactionsReader<'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 SubmitTransactionsReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl<'r> ::core::fmt::Display for SubmitTransactionsReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; write!(f, "{}: {}", "tx_witness_root", self.tx_witness_root())?; write!(f, ", {}: {}", "tx_count", self.tx_count())?; write!( f, ", {}: {}", "prev_state_checkpoint", self.prev_state_checkpoint() )?; let extra_count = self.count_extra_fields(); if extra_count != 0 { write!(f, ", .. ({} fields)", extra_count)?; } write!(f, " }}") } } impl<'r> SubmitTransactionsReader<'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 tx_witness_root(&self) -> Byte32Reader<'r> { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[4..]) as usize; let end = molecule::unpack_number(&slice[8..]) as usize; Byte32Reader::new_unchecked(&self.as_slice()[start..end]) } pub fn tx_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 prev_state_checkpoint(&self) -> Byte32Reader<'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; Byte32Reader::new_unchecked(&self.as_slice()[start..end]) } else { Byte32Reader::new_unchecked(&self.as_slice()[start..]) } } } impl<'r> molecule::prelude::Reader<'r> for SubmitTransactionsReader<'r> { type Entity = SubmitTransactions; const NAME: &'static str = "SubmitTransactionsReader"; fn to_entity(&self) -> Self::Entity { Self::Entity::new_unchecked(self.as_slice().to_owned().into()) } fn new_unchecked(slice: &'r [u8]) -> Self { SubmitTransactionsReader(slice) } fn as_slice(&self) -> &'r [u8] { self.0 } fn verify(slice: &[u8], compatible: bool) -> molecule::error::VerificationResult<()> { use molecule::verification_error as ve; let slice_len = slice.len(); if slice_len < molecule::NUMBER_SIZE { return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE, slice_len); } let total_size = molecule::unpack_number(slice) as usize; if slice_len != total_size { return ve!(Self, TotalSizeNotMatch, total_size, slice_len); } if slice_len == molecule::NUMBER_SIZE && Self::FIELD_COUNT == 0 { return Ok(()); } if slice_len < molecule::NUMBER_SIZE * 2 { return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE * 2, slice_len); } let offset_first = molecule::unpack_number(&slice[molecule::NUMBER_SIZE..]) as usize; if offset_first % molecule::NUMBER_SIZE != 0 || offset_first < molecule::NUMBER_SIZE * 2 { return ve!(Self, OffsetsNotMatch); } if slice_len < offset_first { return ve!(Self, HeaderIsBroken, offset_first, slice_len); } let field_count = offset_first / molecule::NUMBER_SIZE - 1; if field_count < Self::FIELD_COUNT { return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, field_count); } else if !compatible && field_count > Self::FIELD_COUNT { return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, field_count); }; let mut offsets: Vec<usize> = slice[molecule::NUMBER_SIZE..offset_first] .chunks_exact(molecule::NUMBER_SIZE) .map(|x| molecule::unpack_number(x) as usize) .collect(); offsets.push(total_size); if offsets.windows(2).any(|i| i[0] > i[1]) { return ve!(Self, OffsetsNotMatch); } Byte32Reader::verify(&slice[offsets[0]..offsets[1]], compatible)?; Uint32Reader::verify(&slice[offsets[1]..offsets[2]], compatible)?; Byte32Reader::verify(&slice[offsets[2]..offsets[3]], compatible)?; Ok(()) } } #[derive(Debug, Default)] pub struct SubmitTransactionsBuilder { pub(crate) tx_witness_root: Byte32, pub(crate) tx_count: Uint32, pub(crate) prev_state_checkpoint: Byte32, } impl SubmitTransactionsBuilder { pub const FIELD_COUNT: usize = 3; pub fn tx_witness_root(mut self, v: Byte32) -> Self { self.tx_witness_root = v; self } pub fn tx_count(mut self, v: Uint32) -> Self { self.tx_count = v; self } pub fn prev_state_checkpoint(mut self, v: Byte32) -> Self { self.prev_state_checkpoint = v; self } } impl molecule::prelude::Builder for SubmitTransactionsBuilder { type Entity = SubmitTransactions; const NAME: &'static str = "SubmitTransactionsBuilder"; fn expected_length(&self) -> usize { molecule::NUMBER_SIZE * (Self::FIELD_COUNT + 1) + self.tx_witness_root.as_slice().len() + self.tx_count.as_slice().len() + self.prev_state_checkpoint.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.tx_witness_root.as_slice().len(); offsets.push(total_size); total_size += self.tx_count.as_slice().len(); offsets.push(total_size); total_size += self.prev_state_checkpoint.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.tx_witness_root.as_slice())?; writer.write_all(self.tx_count.as_slice())?; writer.write_all(self.prev_state_checkpoint.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)); SubmitTransactions::new_unchecked(inner.into()) } } #[derive(Clone)] pub struct SubmitWithdrawals(molecule::bytes::Bytes); impl ::core::fmt::LowerHex for SubmitWithdrawals { 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 SubmitWithdrawals { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl ::core::fmt::Display for SubmitWithdrawals { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; write!( f, "{}: {}", "withdrawal_witness_root", self.withdrawal_witness_root() )?; write!(f, ", {}: {}", "withdrawal_count", self.withdrawal_count())?; write!(f, " }}") } } impl ::core::default::Default for SubmitWithdrawals { fn default() -> Self { let v: Vec<u8> = vec![ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ]; SubmitWithdrawals::new_unchecked(v.into()) } } impl SubmitWithdrawals { pub const TOTAL_SIZE: usize = 36; pub const FIELD_SIZES: [usize; 2] = [32, 4]; pub const FIELD_COUNT: usize = 2; pub fn withdrawal_witness_root(&self) -> Byte32 { Byte32::new_unchecked(self.0.slice(0..32)) } pub fn withdrawal_count(&self) -> Uint32 { Uint32::new_unchecked(self.0.slice(32..36)) } pub fn as_reader<'r>(&'r self) -> SubmitWithdrawalsReader<'r> { SubmitWithdrawalsReader::new_unchecked(self.as_slice()) } } impl molecule::prelude::Entity for SubmitWithdrawals { type Builder = SubmitWithdrawalsBuilder; const NAME: &'static str = "SubmitWithdrawals"; fn new_unchecked(data: molecule::bytes::Bytes) -> Self { SubmitWithdrawals(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> { SubmitWithdrawalsReader::from_slice(slice).map(|reader| reader.to_entity()) } fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> { SubmitWithdrawalsReader::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() .withdrawal_witness_root(self.withdrawal_witness_root()) .withdrawal_count(self.withdrawal_count()) } } #[derive(Clone, Copy)] pub struct SubmitWithdrawalsReader<'r>(&'r [u8]); impl<'r> ::core::fmt::LowerHex for SubmitWithdrawalsReader<'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 SubmitWithdrawalsReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl<'r> ::core::fmt::Display for SubmitWithdrawalsReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; write!( f, "{}: {}", "withdrawal_witness_root", self.withdrawal_witness_root() )?; write!(f, ", {}: {}", "withdrawal_count", self.withdrawal_count())?; write!(f, " }}") } } impl<'r> SubmitWithdrawalsReader<'r> { pub const TOTAL_SIZE: usize = 36; pub const FIELD_SIZES: [usize; 2] = [32, 4]; pub const FIELD_COUNT: usize = 2; pub fn withdrawal_witness_root(&self) -> Byte32Reader<'r> { Byte32Reader::new_unchecked(&self.as_slice()[0..32]) } pub fn withdrawal_count(&self) -> Uint32Reader<'r> { Uint32Reader::new_unchecked(&self.as_slice()[32..36]) } } impl<'r> molecule::prelude::Reader<'r> for SubmitWithdrawalsReader<'r> { type Entity = SubmitWithdrawals; const NAME: &'static str = "SubmitWithdrawalsReader"; fn to_entity(&self) -> Self::Entity { Self::Entity::new_unchecked(self.as_slice().to_owned().into()) } fn new_unchecked(slice: &'r [u8]) -> Self { SubmitWithdrawalsReader(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(()) } } #[derive(Debug, Default)] pub struct SubmitWithdrawalsBuilder { pub(crate) withdrawal_witness_root: Byte32, pub(crate) withdrawal_count: Uint32, } impl SubmitWithdrawalsBuilder { pub const TOTAL_SIZE: usize = 36; pub const FIELD_SIZES: [usize; 2] = [32, 4]; pub const FIELD_COUNT: usize = 2; pub fn withdrawal_witness_root(mut self, v: Byte32) -> Self { self.withdrawal_witness_root = v; self } pub fn withdrawal_count(mut self, v: Uint32) -> Self { self.withdrawal_count = v; self } } impl molecule::prelude::Builder for SubmitWithdrawalsBuilder { type Entity = SubmitWithdrawals; const NAME: &'static str = "SubmitWithdrawalsBuilder"; 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.withdrawal_witness_root.as_slice())?; writer.write_all(self.withdrawal_count.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)); SubmitWithdrawals::new_unchecked(inner.into()) } } #[derive(Clone)] pub struct RawL2Block(molecule::bytes::Bytes); impl ::core::fmt::LowerHex for RawL2Block { 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 RawL2Block { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl ::core::fmt::Display for RawL2Block { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; write!(f, "{}: {}", "number", self.number())?; write!(f, ", {}: {}", "block_producer_id", self.block_producer_id())?; write!(f, ", {}: {}", "parent_block_hash", self.parent_block_hash())?; write!( f, ", {}: {}", "stake_cell_owner_lock_hash", self.stake_cell_owner_lock_hash() )?; write!(f, ", {}: {}", "timestamp", self.timestamp())?; write!(f, ", {}: {}", "prev_account", self.prev_account())?; write!(f, ", {}: {}", "post_account", self.post_account())?; write!( f, ", {}: {}", "state_checkpoint_list", self.state_checkpoint_list() )?; write!( f, ", {}: {}", "submit_withdrawals", self.submit_withdrawals() )?; write!( f, ", {}: {}", "submit_transactions", self.submit_transactions() )?; let extra_count = self.count_extra_fields(); if extra_count != 0 { write!(f, ", .. ({} fields)", extra_count)?; } write!(f, " }}") } } impl ::core::default::Default for RawL2Block { fn default() -> Self { let v: Vec<u8> = vec![ 68, 1, 0, 0, 44, 0, 0, 0, 52, 0, 0, 0, 56, 0, 0, 0, 88, 0, 0, 0, 120, 0, 0, 0, 128, 0, 0, 0, 164, 0, 0, 0, 200, 0, 0, 0, 204, 0, 0, 0, 240, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 84, 0, 0, 0, 16, 0, 0, 0, 48, 0, 0, 0, 52, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ]; RawL2Block::new_unchecked(v.into()) } } impl RawL2Block { pub const FIELD_COUNT: usize = 10; 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 number(&self) -> Uint64 { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[4..]) as usize; let end = molecule::unpack_number(&slice[8..]) as usize; Uint64::new_unchecked(self.0.slice(start..end)) } pub fn block_producer_id(&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 parent_block_hash(&self) -> Byte32 { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[12..]) as usize; let end = molecule::unpack_number(&slice[16..]) as usize; Byte32::new_unchecked(self.0.slice(start..end)) } pub fn stake_cell_owner_lock_hash(&self) -> Byte32 { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[16..]) as usize; let end = molecule::unpack_number(&slice[20..]) as usize; Byte32::new_unchecked(self.0.slice(start..end)) } pub fn timestamp(&self) -> Uint64 { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[20..]) as usize; let end = molecule::unpack_number(&slice[24..]) as usize; Uint64::new_unchecked(self.0.slice(start..end)) } pub fn prev_account(&self) -> AccountMerkleState { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[24..]) as usize; let end = molecule::unpack_number(&slice[28..]) as usize; AccountMerkleState::new_unchecked(self.0.slice(start..end)) } pub fn post_account(&self) -> AccountMerkleState { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[28..]) as usize; let end = molecule::unpack_number(&slice[32..]) as usize; AccountMerkleState::new_unchecked(self.0.slice(start..end)) } pub fn state_checkpoint_list(&self) -> Byte32Vec { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[32..]) as usize; let end = molecule::unpack_number(&slice[36..]) as usize; Byte32Vec::new_unchecked(self.0.slice(start..end)) } pub fn submit_withdrawals(&self) -> SubmitWithdrawals { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[36..]) as usize; let end = molecule::unpack_number(&slice[40..]) as usize; SubmitWithdrawals::new_unchecked(self.0.slice(start..end)) } pub fn submit_transactions(&self) -> SubmitTransactions { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[40..]) as usize; if self.has_extra_fields() { let end = molecule::unpack_number(&slice[44..]) as usize; SubmitTransactions::new_unchecked(self.0.slice(start..end)) } else { SubmitTransactions::new_unchecked(self.0.slice(start..)) } } pub fn as_reader<'r>(&'r self) -> RawL2BlockReader<'r> { RawL2BlockReader::new_unchecked(self.as_slice()) } } impl molecule::prelude::Entity for RawL2Block { type Builder = RawL2BlockBuilder; const NAME: &'static str = "RawL2Block"; fn new_unchecked(data: molecule::bytes::Bytes) -> Self { RawL2Block(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> { RawL2BlockReader::from_slice(slice).map(|reader| reader.to_entity()) } fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> { RawL2BlockReader::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() .number(self.number()) .block_producer_id(self.block_producer_id()) .parent_block_hash(self.parent_block_hash()) .stake_cell_owner_lock_hash(self.stake_cell_owner_lock_hash()) .timestamp(self.timestamp()) .prev_account(self.prev_account()) .post_account(self.post_account()) .state_checkpoint_list(self.state_checkpoint_list()) .submit_withdrawals(self.submit_withdrawals()) .submit_transactions(self.submit_transactions()) } } #[derive(Clone, Copy)] pub struct RawL2BlockReader<'r>(&'r [u8]); impl<'r> ::core::fmt::LowerHex for RawL2BlockReader<'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 RawL2BlockReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl<'r> ::core::fmt::Display for RawL2BlockReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; write!(f, "{}: {}", "number", self.number())?; write!(f, ", {}: {}", "block_producer_id", self.block_producer_id())?; write!(f, ", {}: {}", "parent_block_hash", self.parent_block_hash())?; write!( f, ", {}: {}", "stake_cell_owner_lock_hash", self.stake_cell_owner_lock_hash() )?; write!(f, ", {}: {}", "timestamp", self.timestamp())?; write!(f, ", {}: {}", "prev_account", self.prev_account())?; write!(f, ", {}: {}", "post_account", self.post_account())?; write!( f, ", {}: {}", "state_checkpoint_list", self.state_checkpoint_list() )?; write!( f, ", {}: {}", "submit_withdrawals", self.submit_withdrawals() )?; write!( f, ", {}: {}", "submit_transactions", self.submit_transactions() )?; let extra_count = self.count_extra_fields(); if extra_count != 0 { write!(f, ", .. ({} fields)", extra_count)?; } write!(f, " }}") } } impl<'r> RawL2BlockReader<'r> { pub const FIELD_COUNT: usize = 10; 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 number(&self) -> Uint64Reader<'r> { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[4..]) as usize; let end = molecule::unpack_number(&slice[8..]) as usize; Uint64Reader::new_unchecked(&self.as_slice()[start..end]) } pub fn block_producer_id(&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 parent_block_hash(&self) -> Byte32Reader<'r> { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[12..]) as usize; let end = molecule::unpack_number(&slice[16..]) as usize; Byte32Reader::new_unchecked(&self.as_slice()[start..end]) } pub fn stake_cell_owner_lock_hash(&self) -> Byte32Reader<'r> { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[16..]) as usize; let end = molecule::unpack_number(&slice[20..]) as usize; Byte32Reader::new_unchecked(&self.as_slice()[start..end]) } pub fn timestamp(&self) -> Uint64Reader<'r> { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[20..]) as usize; let end = molecule::unpack_number(&slice[24..]) as usize; Uint64Reader::new_unchecked(&self.as_slice()[start..end]) } pub fn prev_account(&self) -> AccountMerkleStateReader<'r> { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[24..]) as usize; let end = molecule::unpack_number(&slice[28..]) as usize; AccountMerkleStateReader::new_unchecked(&self.as_slice()[start..end]) } pub fn post_account(&self) -> AccountMerkleStateReader<'r> { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[28..]) as usize; let end = molecule::unpack_number(&slice[32..]) as usize; AccountMerkleStateReader::new_unchecked(&self.as_slice()[start..end]) } pub fn state_checkpoint_list(&self) -> Byte32VecReader<'r> { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[32..]) as usize; let end = molecule::unpack_number(&slice[36..]) as usize; Byte32VecReader::new_unchecked(&self.as_slice()[start..end]) } pub fn submit_withdrawals(&self) -> SubmitWithdrawalsReader<'r> { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[36..]) as usize; let end = molecule::unpack_number(&slice[40..]) as usize; SubmitWithdrawalsReader::new_unchecked(&self.as_slice()[start..end]) } pub fn submit_transactions(&self) -> SubmitTransactionsReader<'r> { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[40..]) as usize; if self.has_extra_fields() { let end = molecule::unpack_number(&slice[44..]) as usize; SubmitTransactionsReader::new_unchecked(&self.as_slice()[start..end]) } else { SubmitTransactionsReader::new_unchecked(&self.as_slice()[start..]) } } } impl<'r> molecule::prelude::Reader<'r> for RawL2BlockReader<'r> { type Entity = RawL2Block; const NAME: &'static str = "RawL2BlockReader"; fn to_entity(&self) -> Self::Entity { Self::Entity::new_unchecked(self.as_slice().to_owned().into()) } fn new_unchecked(slice: &'r [u8]) -> Self { RawL2BlockReader(slice) } fn as_slice(&self) -> &'r [u8] { self.0 } fn verify(slice: &[u8], compatible: bool) -> molecule::error::VerificationResult<()> { use molecule::verification_error as ve; let slice_len = slice.len(); if slice_len < molecule::NUMBER_SIZE { return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE, slice_len); } let total_size = molecule::unpack_number(slice) as usize; if slice_len != total_size { return ve!(Self, TotalSizeNotMatch, total_size, slice_len); } if slice_len == molecule::NUMBER_SIZE && Self::FIELD_COUNT == 0 { return Ok(()); } if slice_len < molecule::NUMBER_SIZE * 2 { return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE * 2, slice_len); } let offset_first = molecule::unpack_number(&slice[molecule::NUMBER_SIZE..]) as usize; if offset_first % molecule::NUMBER_SIZE != 0 || offset_first < molecule::NUMBER_SIZE * 2 { return ve!(Self, OffsetsNotMatch); } if slice_len < offset_first { return ve!(Self, HeaderIsBroken, offset_first, slice_len); } let field_count = offset_first / molecule::NUMBER_SIZE - 1; if field_count < Self::FIELD_COUNT { return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, field_count); } else if !compatible && field_count > Self::FIELD_COUNT { return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, field_count); }; let mut offsets: Vec<usize> = slice[molecule::NUMBER_SIZE..offset_first] .chunks_exact(molecule::NUMBER_SIZE) .map(|x| molecule::unpack_number(x) as usize) .collect(); offsets.push(total_size); if offsets.windows(2).any(|i| i[0] > i[1]) { return ve!(Self, OffsetsNotMatch); } Uint64Reader::verify(&slice[offsets[0]..offsets[1]], compatible)?; Uint32Reader::verify(&slice[offsets[1]..offsets[2]], compatible)?; Byte32Reader::verify(&slice[offsets[2]..offsets[3]], compatible)?; Byte32Reader::verify(&slice[offsets[3]..offsets[4]], compatible)?; Uint64Reader::verify(&slice[offsets[4]..offsets[5]], compatible)?; AccountMerkleStateReader::verify(&slice[offsets[5]..offsets[6]], compatible)?; AccountMerkleStateReader::verify(&slice[offsets[6]..offsets[7]], compatible)?; Byte32VecReader::verify(&slice[offsets[7]..offsets[8]], compatible)?; SubmitWithdrawalsReader::verify(&slice[offsets[8]..offsets[9]], compatible)?; SubmitTransactionsReader::verify(&slice[offsets[9]..offsets[10]], compatible)?; Ok(()) } } #[derive(Debug, Default)] pub struct RawL2BlockBuilder { pub(crate) number: Uint64, pub(crate) block_producer_id: Uint32, pub(crate) parent_block_hash: Byte32, pub(crate) stake_cell_owner_lock_hash: Byte32, pub(crate) timestamp: Uint64, pub(crate) prev_account: AccountMerkleState, pub(crate) post_account: AccountMerkleState, pub(crate) state_checkpoint_list: Byte32Vec, pub(crate) submit_withdrawals: SubmitWithdrawals, pub(crate) submit_transactions: SubmitTransactions, } impl RawL2BlockBuilder { pub const FIELD_COUNT: usize = 10; pub fn number(mut self, v: Uint64) -> Self { self.number = v; self } pub fn block_producer_id(mut self, v: Uint32) -> Self { self.block_producer_id = v; self } pub fn parent_block_hash(mut self, v: Byte32) -> Self { self.parent_block_hash = v; self } pub fn stake_cell_owner_lock_hash(mut self, v: Byte32) -> Self { self.stake_cell_owner_lock_hash = v; self } pub fn timestamp(mut self, v: Uint64) -> Self { self.timestamp = v; self } pub fn prev_account(mut self, v: AccountMerkleState) -> Self { self.prev_account = v; self } pub fn post_account(mut self, v: AccountMerkleState) -> Self { self.post_account = v; self } pub fn state_checkpoint_list(mut self, v: Byte32Vec) -> Self { self.state_checkpoint_list = v; self } pub fn submit_withdrawals(mut self, v: SubmitWithdrawals) -> Self { self.submit_withdrawals = v; self } pub fn submit_transactions(mut self, v: SubmitTransactions) -> Self { self.submit_transactions = v; self } } impl molecule::prelude::Builder for RawL2BlockBuilder { type Entity = RawL2Block; const NAME: &'static str = "RawL2BlockBuilder"; fn expected_length(&self) -> usize { molecule::NUMBER_SIZE * (Self::FIELD_COUNT + 1) + self.number.as_slice().len() + self.block_producer_id.as_slice().len() + self.parent_block_hash.as_slice().len() + self.stake_cell_owner_lock_hash.as_slice().len() + self.timestamp.as_slice().len() + self.prev_account.as_slice().len() + self.post_account.as_slice().len() + self.state_checkpoint_list.as_slice().len() + self.submit_withdrawals.as_slice().len() + self.submit_transactions.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.number.as_slice().len(); offsets.push(total_size); total_size += self.block_producer_id.as_slice().len(); offsets.push(total_size); total_size += self.parent_block_hash.as_slice().len(); offsets.push(total_size); total_size += self.stake_cell_owner_lock_hash.as_slice().len(); offsets.push(total_size); total_size += self.timestamp.as_slice().len(); offsets.push(total_size); total_size += self.prev_account.as_slice().len(); offsets.push(total_size); total_size += self.post_account.as_slice().len(); offsets.push(total_size); total_size += self.state_checkpoint_list.as_slice().len(); offsets.push(total_size); total_size += self.submit_withdrawals.as_slice().len(); offsets.push(total_size); total_size += self.submit_transactions.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.number.as_slice())?; writer.write_all(self.block_producer_id.as_slice())?; writer.write_all(self.parent_block_hash.as_slice())?; writer.write_all(self.stake_cell_owner_lock_hash.as_slice())?; writer.write_all(self.timestamp.as_slice())?; writer.write_all(self.prev_account.as_slice())?; writer.write_all(self.post_account.as_slice())?; writer.write_all(self.state_checkpoint_list.as_slice())?; writer.write_all(self.submit_withdrawals.as_slice())?; writer.write_all(self.submit_transactions.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)); RawL2Block::new_unchecked(inner.into()) } } #[derive(Clone)] pub struct RawL2BlockVec(molecule::bytes::Bytes); impl ::core::fmt::LowerHex for RawL2BlockVec { 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 RawL2BlockVec { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl ::core::fmt::Display for RawL2BlockVec { 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 RawL2BlockVec { fn default() -> Self { let v: Vec<u8> = vec![4, 0, 0, 0]; RawL2BlockVec::new_unchecked(v.into()) } } impl RawL2BlockVec { 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<RawL2Block> { if idx >= self.len() { None } else { Some(self.get_unchecked(idx)) } } pub fn get_unchecked(&self, idx: usize) -> RawL2Block { 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 { RawL2Block::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; RawL2Block::new_unchecked(self.0.slice(start..end)) } } pub fn as_reader<'r>(&'r self) -> RawL2BlockVecReader<'r> { RawL2BlockVecReader::new_unchecked(self.as_slice()) } } impl molecule::prelude::Entity for RawL2BlockVec { type Builder = RawL2BlockVecBuilder; const NAME: &'static str = "RawL2BlockVec"; fn new_unchecked(data: molecule::bytes::Bytes) -> Self { RawL2BlockVec(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> { RawL2BlockVecReader::from_slice(slice).map(|reader| reader.to_entity()) } fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> { RawL2BlockVecReader::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 RawL2BlockVecReader<'r>(&'r [u8]); impl<'r> ::core::fmt::LowerHex for RawL2BlockVecReader<'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 RawL2BlockVecReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl<'r> ::core::fmt::Display for RawL2BlockVecReader<'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> RawL2BlockVecReader<'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<RawL2BlockReader<'r>> { if idx >= self.len() { None } else { Some(self.get_unchecked(idx)) } } pub fn get_unchecked(&self, idx: usize) -> RawL2BlockReader<'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 { RawL2BlockReader::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; RawL2BlockReader::new_unchecked(&self.as_slice()[start..end]) } } } impl<'r> molecule::prelude::Reader<'r> for RawL2BlockVecReader<'r> { type Entity = RawL2BlockVec; const NAME: &'static str = "RawL2BlockVecReader"; fn to_entity(&self) -> Self::Entity { Self::Entity::new_unchecked(self.as_slice().to_owned().into()) } fn new_unchecked(slice: &'r [u8]) -> Self { RawL2BlockVecReader(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]; RawL2BlockReader::verify(&slice[start..end], compatible)?; } Ok(()) } } #[derive(Debug, Default)] pub struct RawL2BlockVecBuilder(pub(crate) Vec<RawL2Block>); impl RawL2BlockVecBuilder { pub fn set(mut self, v: Vec<RawL2Block>) -> Self { self.0 = v; self } pub fn push(mut self, v: RawL2Block) -> Self { self.0.push(v); self } pub fn extend<T: ::core::iter::IntoIterator<Item = RawL2Block>>(mut self, iter: T) -> Self { for elem in iter { self.0.push(elem); } self } } impl molecule::prelude::Builder for RawL2BlockVecBuilder { type Entity = RawL2BlockVec; const NAME: &'static str = "RawL2BlockVecBuilder"; 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)); RawL2BlockVec::new_unchecked(inner.into()) } } pub struct RawL2BlockVecIterator(RawL2BlockVec, usize, usize); impl ::core::iter::Iterator for RawL2BlockVecIterator { type Item = RawL2Block; 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 RawL2BlockVecIterator { fn len(&self) -> usize { self.2 - self.1 } } impl ::core::iter::IntoIterator for RawL2BlockVec { type Item = RawL2Block; type IntoIter = RawL2BlockVecIterator; fn into_iter(self) -> Self::IntoIter { let len = self.len(); RawL2BlockVecIterator(self, 0, len) } } impl<'r> RawL2BlockVecReader<'r> { pub fn iter<'t>(&'t self) -> RawL2BlockVecReaderIterator<'t, 'r> { RawL2BlockVecReaderIterator(&self, 0, self.len()) } } pub struct RawL2BlockVecReaderIterator<'t, 'r>(&'t RawL2BlockVecReader<'r>, usize, usize); impl<'t: 'r, 'r> ::core::iter::Iterator for RawL2BlockVecReaderIterator<'t, 'r> { type Item = RawL2BlockReader<'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 RawL2BlockVecReaderIterator<'t, 'r> { fn len(&self) -> usize { self.2 - self.1 } } #[derive(Clone)] pub struct L2Block(molecule::bytes::Bytes); impl ::core::fmt::LowerHex for L2Block { 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 L2Block { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl ::core::fmt::Display for L2Block { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; write!(f, "{}: {}", "raw", self.raw())?; write!(f, ", {}: {}", "kv_state", self.kv_state())?; write!(f, ", {}: {}", "kv_state_proof", self.kv_state_proof())?; write!(f, ", {}: {}", "transactions", self.transactions())?; write!(f, ", {}: {}", "block_proof", self.block_proof())?; write!(f, ", {}: {}", "withdrawals", self.withdrawals())?; let extra_count = self.count_extra_fields(); if extra_count != 0 { write!(f, ", .. ({} fields)", extra_count)?; } write!(f, " }}") } } impl ::core::default::Default for L2Block { fn default() -> Self { let v: Vec<u8> = vec![ 116, 1, 0, 0, 28, 0, 0, 0, 96, 1, 0, 0, 100, 1, 0, 0, 104, 1, 0, 0, 108, 1, 0, 0, 112, 1, 0, 0, 68, 1, 0, 0, 44, 0, 0, 0, 52, 0, 0, 0, 56, 0, 0, 0, 88, 0, 0, 0, 120, 0, 0, 0, 128, 0, 0, 0, 164, 0, 0, 0, 200, 0, 0, 0, 204, 0, 0, 0, 240, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 84, 0, 0, 0, 16, 0, 0, 0, 48, 0, 0, 0, 52, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, ]; L2Block::new_unchecked(v.into()) } } impl L2Block { pub const FIELD_COUNT: usize = 6; 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 raw(&self) -> RawL2Block { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[4..]) as usize; let end = molecule::unpack_number(&slice[8..]) as usize; RawL2Block::new_unchecked(self.0.slice(start..end)) } pub fn kv_state(&self) -> KVPairVec { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[8..]) as usize; let end = molecule::unpack_number(&slice[12..]) as usize; KVPairVec::new_unchecked(self.0.slice(start..end)) } pub fn kv_state_proof(&self) -> Bytes { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[12..]) as usize; let end = molecule::unpack_number(&slice[16..]) as usize; Bytes::new_unchecked(self.0.slice(start..end)) } pub fn transactions(&self) -> L2TransactionVec { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[16..]) as usize; let end = molecule::unpack_number(&slice[20..]) as usize; L2TransactionVec::new_unchecked(self.0.slice(start..end)) } pub fn block_proof(&self) -> Bytes { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[20..]) as usize; let end = molecule::unpack_number(&slice[24..]) as usize; Bytes::new_unchecked(self.0.slice(start..end)) } pub fn withdrawals(&self) -> WithdrawalRequestVec { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[24..]) as usize; if self.has_extra_fields() { let end = molecule::unpack_number(&slice[28..]) as usize; WithdrawalRequestVec::new_unchecked(self.0.slice(start..end)) } else { WithdrawalRequestVec::new_unchecked(self.0.slice(start..)) } } pub fn as_reader<'r>(&'r self) -> L2BlockReader<'r> { L2BlockReader::new_unchecked(self.as_slice()) } } impl molecule::prelude::Entity for L2Block { type Builder = L2BlockBuilder; const NAME: &'static str = "L2Block"; fn new_unchecked(data: molecule::bytes::Bytes) -> Self { L2Block(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> { L2BlockReader::from_slice(slice).map(|reader| reader.to_entity()) } fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> { L2BlockReader::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() .raw(self.raw()) .kv_state(self.kv_state()) .kv_state_proof(self.kv_state_proof()) .transactions(self.transactions()) .block_proof(self.block_proof()) .withdrawals(self.withdrawals()) } } #[derive(Clone, Copy)] pub struct L2BlockReader<'r>(&'r [u8]); impl<'r> ::core::fmt::LowerHex for L2BlockReader<'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 L2BlockReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl<'r> ::core::fmt::Display for L2BlockReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; write!(f, "{}: {}", "raw", self.raw())?; write!(f, ", {}: {}", "kv_state", self.kv_state())?; write!(f, ", {}: {}", "kv_state_proof", self.kv_state_proof())?; write!(f, ", {}: {}", "transactions", self.transactions())?; write!(f, ", {}: {}", "block_proof", self.block_proof())?; write!(f, ", {}: {}", "withdrawals", self.withdrawals())?; let extra_count = self.count_extra_fields(); if extra_count != 0 { write!(f, ", .. ({} fields)", extra_count)?; } write!(f, " }}") } } impl<'r> L2BlockReader<'r> { pub const FIELD_COUNT: usize = 6; 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 raw(&self) -> RawL2BlockReader<'r> { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[4..]) as usize; let end = molecule::unpack_number(&slice[8..]) as usize; RawL2BlockReader::new_unchecked(&self.as_slice()[start..end]) } pub fn kv_state(&self) -> KVPairVecReader<'r> { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[8..]) as usize; let end = molecule::unpack_number(&slice[12..]) as usize; KVPairVecReader::new_unchecked(&self.as_slice()[start..end]) } pub fn kv_state_proof(&self) -> BytesReader<'r> { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[12..]) as usize; let end = molecule::unpack_number(&slice[16..]) as usize; BytesReader::new_unchecked(&self.as_slice()[start..end]) } pub fn transactions(&self) -> L2TransactionVecReader<'r> { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[16..]) as usize; let end = molecule::unpack_number(&slice[20..]) as usize; L2TransactionVecReader::new_unchecked(&self.as_slice()[start..end]) } pub fn block_proof(&self) -> BytesReader<'r> { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[20..]) as usize; let end = molecule::unpack_number(&slice[24..]) as usize; BytesReader::new_unchecked(&self.as_slice()[start..end]) } pub fn withdrawals(&self) -> WithdrawalRequestVecReader<'r> { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[24..]) as usize; if self.has_extra_fields() { let end = molecule::unpack_number(&slice[28..]) as usize; WithdrawalRequestVecReader::new_unchecked(&self.as_slice()[start..end]) } else { WithdrawalRequestVecReader::new_unchecked(&self.as_slice()[start..]) } } } impl<'r> molecule::prelude::Reader<'r> for L2BlockReader<'r> { type Entity = L2Block; const NAME: &'static str = "L2BlockReader"; fn to_entity(&self) -> Self::Entity { Self::Entity::new_unchecked(self.as_slice().to_owned().into()) } fn new_unchecked(slice: &'r [u8]) -> Self { L2BlockReader(slice) } fn as_slice(&self) -> &'r [u8] { self.0 } fn verify(slice: &[u8], compatible: bool) -> molecule::error::VerificationResult<()> { use molecule::verification_error as ve; let slice_len = slice.len(); if slice_len < molecule::NUMBER_SIZE { return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE, slice_len); } let total_size = molecule::unpack_number(slice) as usize; if slice_len != total_size { return ve!(Self, TotalSizeNotMatch, total_size, slice_len); } if slice_len == molecule::NUMBER_SIZE && Self::FIELD_COUNT == 0 { return Ok(()); } if slice_len < molecule::NUMBER_SIZE * 2 { return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE * 2, slice_len); } let offset_first = molecule::unpack_number(&slice[molecule::NUMBER_SIZE..]) as usize; if offset_first % molecule::NUMBER_SIZE != 0 || offset_first < molecule::NUMBER_SIZE * 2 { return ve!(Self, OffsetsNotMatch); } if slice_len < offset_first { return ve!(Self, HeaderIsBroken, offset_first, slice_len); } let field_count = offset_first / molecule::NUMBER_SIZE - 1; if field_count < Self::FIELD_COUNT { return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, field_count); } else if !compatible && field_count > Self::FIELD_COUNT { return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, field_count); }; let mut offsets: Vec<usize> = slice[molecule::NUMBER_SIZE..offset_first] .chunks_exact(molecule::NUMBER_SIZE) .map(|x| molecule::unpack_number(x) as usize) .collect(); offsets.push(total_size); if offsets.windows(2).any(|i| i[0] > i[1]) { return ve!(Self, OffsetsNotMatch); } RawL2BlockReader::verify(&slice[offsets[0]..offsets[1]], compatible)?; KVPairVecReader::verify(&slice[offsets[1]..offsets[2]], compatible)?; BytesReader::verify(&slice[offsets[2]..offsets[3]], compatible)?; L2TransactionVecReader::verify(&slice[offsets[3]..offsets[4]], compatible)?; BytesReader::verify(&slice[offsets[4]..offsets[5]], compatible)?; WithdrawalRequestVecReader::verify(&slice[offsets[5]..offsets[6]], compatible)?; Ok(()) } } #[derive(Debug, Default)] pub struct L2BlockBuilder { pub(crate) raw: RawL2Block, pub(crate) kv_state: KVPairVec, pub(crate) kv_state_proof: Bytes, pub(crate) transactions: L2TransactionVec, pub(crate) block_proof: Bytes, pub(crate) withdrawals: WithdrawalRequestVec, } impl L2BlockBuilder { pub const FIELD_COUNT: usize = 6; pub fn raw(mut self, v: RawL2Block) -> Self { self.raw = v; self } pub fn kv_state(mut self, v: KVPairVec) -> Self { self.kv_state = v; self } pub fn kv_state_proof(mut self, v: Bytes) -> Self { self.kv_state_proof = v; self } pub fn transactions(mut self, v: L2TransactionVec) -> Self { self.transactions = v; self } pub fn block_proof(mut self, v: Bytes) -> Self { self.block_proof = v; self } pub fn withdrawals(mut self, v: WithdrawalRequestVec) -> Self { self.withdrawals = v; self } } impl molecule::prelude::Builder for L2BlockBuilder { type Entity = L2Block; const NAME: &'static str = "L2BlockBuilder"; fn expected_length(&self) -> usize { molecule::NUMBER_SIZE * (Self::FIELD_COUNT + 1) + self.raw.as_slice().len() + self.kv_state.as_slice().len() + self.kv_state_proof.as_slice().len() + self.transactions.as_slice().len() + self.block_proof.as_slice().len() + self.withdrawals.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.raw.as_slice().len(); offsets.push(total_size); total_size += self.kv_state.as_slice().len(); offsets.push(total_size); total_size += self.kv_state_proof.as_slice().len(); offsets.push(total_size); total_size += self.transactions.as_slice().len(); offsets.push(total_size); total_size += self.block_proof.as_slice().len(); offsets.push(total_size); total_size += self.withdrawals.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.raw.as_slice())?; writer.write_all(self.kv_state.as_slice())?; writer.write_all(self.kv_state_proof.as_slice())?; writer.write_all(self.transactions.as_slice())?; writer.write_all(self.block_proof.as_slice())?; writer.write_all(self.withdrawals.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)); L2Block::new_unchecked(inner.into()) } } #[derive(Clone)] pub struct DepositRequest(molecule::bytes::Bytes); impl ::core::fmt::LowerHex for DepositRequest { 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 DepositRequest { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl ::core::fmt::Display for DepositRequest { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; write!(f, "{}: {}", "capacity", self.capacity())?; write!(f, ", {}: {}", "amount", self.amount())?; write!(f, ", {}: {}", "sudt_script_hash", self.sudt_script_hash())?; write!(f, ", {}: {}", "script", self.script())?; let extra_count = self.count_extra_fields(); if extra_count != 0 { write!(f, ", .. ({} fields)", extra_count)?; } write!(f, " }}") } } impl ::core::default::Default for DepositRequest { fn default() -> Self { let v: Vec<u8> = vec![ 129, 0, 0, 0, 20, 0, 0, 0, 28, 0, 0, 0, 44, 0, 0, 0, 76, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 53, 0, 0, 0, 16, 0, 0, 0, 48, 0, 0, 0, 49, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ]; DepositRequest::new_unchecked(v.into()) } } impl DepositRequest { 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 capacity(&self) -> Uint64 { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[4..]) as usize; let end = molecule::unpack_number(&slice[8..]) as usize; Uint64::new_unchecked(self.0.slice(start..end)) } pub fn amount(&self) -> Uint128 { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[8..]) as usize; let end = molecule::unpack_number(&slice[12..]) as usize; Uint128::new_unchecked(self.0.slice(start..end)) } pub fn sudt_script_hash(&self) -> Byte32 { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[12..]) as usize; let end = molecule::unpack_number(&slice[16..]) as usize; Byte32::new_unchecked(self.0.slice(start..end)) } pub fn script(&self) -> Script { 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; Script::new_unchecked(self.0.slice(start..end)) } else { Script::new_unchecked(self.0.slice(start..)) } } pub fn as_reader<'r>(&'r self) -> DepositRequestReader<'r> { DepositRequestReader::new_unchecked(self.as_slice()) } } impl molecule::prelude::Entity for DepositRequest { type Builder = DepositRequestBuilder; const NAME: &'static str = "DepositRequest"; fn new_unchecked(data: molecule::bytes::Bytes) -> Self { DepositRequest(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> { DepositRequestReader::from_slice(slice).map(|reader| reader.to_entity()) } fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> { DepositRequestReader::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() .capacity(self.capacity()) .amount(self.amount()) .sudt_script_hash(self.sudt_script_hash()) .script(self.script()) } } #[derive(Clone, Copy)] pub struct DepositRequestReader<'r>(&'r [u8]); impl<'r> ::core::fmt::LowerHex for DepositRequestReader<'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 DepositRequestReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl<'r> ::core::fmt::Display for DepositRequestReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; write!(f, "{}: {}", "capacity", self.capacity())?; write!(f, ", {}: {}", "amount", self.amount())?; write!(f, ", {}: {}", "sudt_script_hash", self.sudt_script_hash())?; write!(f, ", {}: {}", "script", self.script())?; let extra_count = self.count_extra_fields(); if extra_count != 0 { write!(f, ", .. ({} fields)", extra_count)?; } write!(f, " }}") } } impl<'r> DepositRequestReader<'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 capacity(&self) -> Uint64Reader<'r> { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[4..]) as usize; let end = molecule::unpack_number(&slice[8..]) as usize; Uint64Reader::new_unchecked(&self.as_slice()[start..end]) } pub fn amount(&self) -> Uint128Reader<'r> { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[8..]) as usize; let end = molecule::unpack_number(&slice[12..]) as usize; Uint128Reader::new_unchecked(&self.as_slice()[start..end]) } pub fn sudt_script_hash(&self) -> Byte32Reader<'r> { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[12..]) as usize; let end = molecule::unpack_number(&slice[16..]) as usize; Byte32Reader::new_unchecked(&self.as_slice()[start..end]) } pub fn script(&self) -> ScriptReader<'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; ScriptReader::new_unchecked(&self.as_slice()[start..end]) } else { ScriptReader::new_unchecked(&self.as_slice()[start..]) } } } impl<'r> molecule::prelude::Reader<'r> for DepositRequestReader<'r> { type Entity = DepositRequest; const NAME: &'static str = "DepositRequestReader"; fn to_entity(&self) -> Self::Entity { Self::Entity::new_unchecked(self.as_slice().to_owned().into()) } fn new_unchecked(slice: &'r [u8]) -> Self { DepositRequestReader(slice) } fn as_slice(&self) -> &'r [u8] { self.0 } fn verify(slice: &[u8], compatible: bool) -> molecule::error::VerificationResult<()> { use molecule::verification_error as ve; let slice_len = slice.len(); if slice_len < molecule::NUMBER_SIZE { return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE, slice_len); } let total_size = molecule::unpack_number(slice) as usize; if slice_len != total_size { return ve!(Self, TotalSizeNotMatch, total_size, slice_len); } if slice_len == molecule::NUMBER_SIZE && Self::FIELD_COUNT == 0 { return Ok(()); } if slice_len < molecule::NUMBER_SIZE * 2 { return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE * 2, slice_len); } let offset_first = molecule::unpack_number(&slice[molecule::NUMBER_SIZE..]) as usize; if offset_first % molecule::NUMBER_SIZE != 0 || offset_first < molecule::NUMBER_SIZE * 2 { return ve!(Self, OffsetsNotMatch); } if slice_len < offset_first { return ve!(Self, HeaderIsBroken, offset_first, slice_len); } let field_count = offset_first / molecule::NUMBER_SIZE - 1; if field_count < Self::FIELD_COUNT { return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, field_count); } else if !compatible && field_count > Self::FIELD_COUNT { return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, field_count); }; let mut offsets: Vec<usize> = slice[molecule::NUMBER_SIZE..offset_first] .chunks_exact(molecule::NUMBER_SIZE) .map(|x| molecule::unpack_number(x) as usize) .collect(); offsets.push(total_size); if offsets.windows(2).any(|i| i[0] > i[1]) { return ve!(Self, OffsetsNotMatch); } Uint64Reader::verify(&slice[offsets[0]..offsets[1]], compatible)?; Uint128Reader::verify(&slice[offsets[1]..offsets[2]], compatible)?; Byte32Reader::verify(&slice[offsets[2]..offsets[3]], compatible)?; ScriptReader::verify(&slice[offsets[3]..offsets[4]], compatible)?; Ok(()) } } #[derive(Debug, Default)] pub struct DepositRequestBuilder { pub(crate) capacity: Uint64, pub(crate) amount: Uint128, pub(crate) sudt_script_hash: Byte32, pub(crate) script: Script, } impl DepositRequestBuilder { pub const FIELD_COUNT: usize = 4; pub fn capacity(mut self, v: Uint64) -> Self { self.capacity = v; self } pub fn amount(mut self, v: Uint128) -> Self { self.amount = v; self } pub fn sudt_script_hash(mut self, v: Byte32) -> Self { self.sudt_script_hash = v; self } pub fn script(mut self, v: Script) -> Self { self.script = v; self } } impl molecule::prelude::Builder for DepositRequestBuilder { type Entity = DepositRequest; const NAME: &'static str = "DepositRequestBuilder"; fn expected_length(&self) -> usize { molecule::NUMBER_SIZE * (Self::FIELD_COUNT + 1) + self.capacity.as_slice().len() + self.amount.as_slice().len() + self.sudt_script_hash.as_slice().len() + self.script.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.capacity.as_slice().len(); offsets.push(total_size); total_size += self.amount.as_slice().len(); offsets.push(total_size); total_size += self.sudt_script_hash.as_slice().len(); offsets.push(total_size); total_size += self.script.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.capacity.as_slice())?; writer.write_all(self.amount.as_slice())?; writer.write_all(self.sudt_script_hash.as_slice())?; writer.write_all(self.script.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)); DepositRequest::new_unchecked(inner.into()) } } #[derive(Clone)] pub struct DepositRequestVec(molecule::bytes::Bytes); impl ::core::fmt::LowerHex for DepositRequestVec { 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 DepositRequestVec { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl ::core::fmt::Display for DepositRequestVec { 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 DepositRequestVec { fn default() -> Self { let v: Vec<u8> = vec![4, 0, 0, 0]; DepositRequestVec::new_unchecked(v.into()) } } impl DepositRequestVec { 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<DepositRequest> { if idx >= self.len() { None } else { Some(self.get_unchecked(idx)) } } pub fn get_unchecked(&self, idx: usize) -> DepositRequest { 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 { DepositRequest::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; DepositRequest::new_unchecked(self.0.slice(start..end)) } } pub fn as_reader<'r>(&'r self) -> DepositRequestVecReader<'r> { DepositRequestVecReader::new_unchecked(self.as_slice()) } } impl molecule::prelude::Entity for DepositRequestVec { type Builder = DepositRequestVecBuilder; const NAME: &'static str = "DepositRequestVec"; fn new_unchecked(data: molecule::bytes::Bytes) -> Self { DepositRequestVec(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> { DepositRequestVecReader::from_slice(slice).map(|reader| reader.to_entity()) } fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> { DepositRequestVecReader::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 DepositRequestVecReader<'r>(&'r [u8]); impl<'r> ::core::fmt::LowerHex for DepositRequestVecReader<'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 DepositRequestVecReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl<'r> ::core::fmt::Display for DepositRequestVecReader<'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> DepositRequestVecReader<'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<DepositRequestReader<'r>> { if idx >= self.len() { None } else { Some(self.get_unchecked(idx)) } } pub fn get_unchecked(&self, idx: usize) -> DepositRequestReader<'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 { DepositRequestReader::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; DepositRequestReader::new_unchecked(&self.as_slice()[start..end]) } } } impl<'r> molecule::prelude::Reader<'r> for DepositRequestVecReader<'r> { type Entity = DepositRequestVec; const NAME: &'static str = "DepositRequestVecReader"; fn to_entity(&self) -> Self::Entity { Self::Entity::new_unchecked(self.as_slice().to_owned().into()) } fn new_unchecked(slice: &'r [u8]) -> Self { DepositRequestVecReader(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]; DepositRequestReader::verify(&slice[start..end], compatible)?; } Ok(()) } } #[derive(Debug, Default)] pub struct DepositRequestVecBuilder(pub(crate) Vec<DepositRequest>); impl DepositRequestVecBuilder { pub fn set(mut self, v: Vec<DepositRequest>) -> Self { self.0 = v; self } pub fn push(mut self, v: DepositRequest) -> Self { self.0.push(v); self } pub fn extend<T: ::core::iter::IntoIterator<Item = DepositRequest>>(mut self, iter: T) -> Self { for elem in iter { self.0.push(elem); } self } } impl molecule::prelude::Builder for DepositRequestVecBuilder { type Entity = DepositRequestVec; const NAME: &'static str = "DepositRequestVecBuilder"; 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)); DepositRequestVec::new_unchecked(inner.into()) } } pub struct DepositRequestVecIterator(DepositRequestVec, usize, usize); impl ::core::iter::Iterator for DepositRequestVecIterator { type Item = DepositRequest; 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 DepositRequestVecIterator { fn len(&self) -> usize { self.2 - self.1 } } impl ::core::iter::IntoIterator for DepositRequestVec { type Item = DepositRequest; type IntoIter = DepositRequestVecIterator; fn into_iter(self) -> Self::IntoIter { let len = self.len(); DepositRequestVecIterator(self, 0, len) } } impl<'r> DepositRequestVecReader<'r> { pub fn iter<'t>(&'t self) -> DepositRequestVecReaderIterator<'t, 'r> { DepositRequestVecReaderIterator(&self, 0, self.len()) } } pub struct DepositRequestVecReaderIterator<'t, 'r>(&'t DepositRequestVecReader<'r>, usize, usize); impl<'t: 'r, 'r> ::core::iter::Iterator for DepositRequestVecReaderIterator<'t, 'r> { type Item = DepositRequestReader<'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 DepositRequestVecReaderIterator<'t, 'r> { fn len(&self) -> usize { self.2 - self.1 } } #[derive(Clone)] pub struct RawWithdrawalRequest(molecule::bytes::Bytes); impl ::core::fmt::LowerHex for RawWithdrawalRequest { 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 RawWithdrawalRequest { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl ::core::fmt::Display for RawWithdrawalRequest { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; write!(f, "{}: {}", "nonce", self.nonce())?; write!(f, ", {}: {}", "capacity", self.capacity())?; write!(f, ", {}: {}", "amount", self.amount())?; write!(f, ", {}: {}", "sudt_script_hash", self.sudt_script_hash())?; write!( f, ", {}: {}", "account_script_hash", self.account_script_hash() )?; write!(f, ", {}: {}", "sell_amount", self.sell_amount())?; write!(f, ", {}: {}", "sell_capacity", self.sell_capacity())?; write!(f, ", {}: {}", "owner_lock_hash", self.owner_lock_hash())?; write!(f, ", {}: {}", "payment_lock_hash", self.payment_lock_hash())?; write!(f, ", {}: {}", "fee", self.fee())?; write!(f, " }}") } } impl ::core::default::Default for RawWithdrawalRequest { fn default() -> Self { let v: Vec<u8> = vec![ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ]; RawWithdrawalRequest::new_unchecked(v.into()) } } impl RawWithdrawalRequest { pub const TOTAL_SIZE: usize = 200; pub const FIELD_SIZES: [usize; 10] = [4, 8, 16, 32, 32, 16, 8, 32, 32, 20]; pub const FIELD_COUNT: usize = 10; pub fn nonce(&self) -> Uint32 { Uint32::new_unchecked(self.0.slice(0..4)) } pub fn capacity(&self) -> Uint64 { Uint64::new_unchecked(self.0.slice(4..12)) } pub fn amount(&self) -> Uint128 { Uint128::new_unchecked(self.0.slice(12..28)) } pub fn sudt_script_hash(&self) -> Byte32 { Byte32::new_unchecked(self.0.slice(28..60)) } pub fn account_script_hash(&self) -> Byte32 { Byte32::new_unchecked(self.0.slice(60..92)) } pub fn sell_amount(&self) -> Uint128 { Uint128::new_unchecked(self.0.slice(92..108)) } pub fn sell_capacity(&self) -> Uint64 { Uint64::new_unchecked(self.0.slice(108..116)) } pub fn owner_lock_hash(&self) -> Byte32 { Byte32::new_unchecked(self.0.slice(116..148)) } pub fn payment_lock_hash(&self) -> Byte32 { Byte32::new_unchecked(self.0.slice(148..180)) } pub fn fee(&self) -> Fee { Fee::new_unchecked(self.0.slice(180..200)) } pub fn as_reader<'r>(&'r self) -> RawWithdrawalRequestReader<'r> { RawWithdrawalRequestReader::new_unchecked(self.as_slice()) } } impl molecule::prelude::Entity for RawWithdrawalRequest { type Builder = RawWithdrawalRequestBuilder; const NAME: &'static str = "RawWithdrawalRequest"; fn new_unchecked(data: molecule::bytes::Bytes) -> Self { RawWithdrawalRequest(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> { RawWithdrawalRequestReader::from_slice(slice).map(|reader| reader.to_entity()) } fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> { RawWithdrawalRequestReader::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()) .capacity(self.capacity()) .amount(self.amount()) .sudt_script_hash(self.sudt_script_hash()) .account_script_hash(self.account_script_hash()) .sell_amount(self.sell_amount()) .sell_capacity(self.sell_capacity()) .owner_lock_hash(self.owner_lock_hash()) .payment_lock_hash(self.payment_lock_hash()) .fee(self.fee()) } } #[derive(Clone, Copy)] pub struct RawWithdrawalRequestReader<'r>(&'r [u8]); impl<'r> ::core::fmt::LowerHex for RawWithdrawalRequestReader<'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 RawWithdrawalRequestReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl<'r> ::core::fmt::Display for RawWithdrawalRequestReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; write!(f, "{}: {}", "nonce", self.nonce())?; write!(f, ", {}: {}", "capacity", self.capacity())?; write!(f, ", {}: {}", "amount", self.amount())?; write!(f, ", {}: {}", "sudt_script_hash", self.sudt_script_hash())?; write!( f, ", {}: {}", "account_script_hash", self.account_script_hash() )?; write!(f, ", {}: {}", "sell_amount", self.sell_amount())?; write!(f, ", {}: {}", "sell_capacity", self.sell_capacity())?; write!(f, ", {}: {}", "owner_lock_hash", self.owner_lock_hash())?; write!(f, ", {}: {}", "payment_lock_hash", self.payment_lock_hash())?; write!(f, ", {}: {}", "fee", self.fee())?; write!(f, " }}") } } impl<'r> RawWithdrawalRequestReader<'r> { pub const TOTAL_SIZE: usize = 200; pub const FIELD_SIZES: [usize; 10] = [4, 8, 16, 32, 32, 16, 8, 32, 32, 20]; pub const FIELD_COUNT: usize = 10; pub fn nonce(&self) -> Uint32Reader<'r> { Uint32Reader::new_unchecked(&self.as_slice()[0..4]) } pub fn capacity(&self) -> Uint64Reader<'r> { Uint64Reader::new_unchecked(&self.as_slice()[4..12]) } pub fn amount(&self) -> Uint128Reader<'r> { Uint128Reader::new_unchecked(&self.as_slice()[12..28]) } pub fn sudt_script_hash(&self) -> Byte32Reader<'r> { Byte32Reader::new_unchecked(&self.as_slice()[28..60]) } pub fn account_script_hash(&self) -> Byte32Reader<'r> { Byte32Reader::new_unchecked(&self.as_slice()[60..92]) } pub fn sell_amount(&self) -> Uint128Reader<'r> { Uint128Reader::new_unchecked(&self.as_slice()[92..108]) } pub fn sell_capacity(&self) -> Uint64Reader<'r> { Uint64Reader::new_unchecked(&self.as_slice()[108..116]) } pub fn owner_lock_hash(&self) -> Byte32Reader<'r> { Byte32Reader::new_unchecked(&self.as_slice()[116..148]) } pub fn payment_lock_hash(&self) -> Byte32Reader<'r> { Byte32Reader::new_unchecked(&self.as_slice()[148..180]) } pub fn fee(&self) -> FeeReader<'r> { FeeReader::new_unchecked(&self.as_slice()[180..200]) } } impl<'r> molecule::prelude::Reader<'r> for RawWithdrawalRequestReader<'r> { type Entity = RawWithdrawalRequest; const NAME: &'static str = "RawWithdrawalRequestReader"; fn to_entity(&self) -> Self::Entity { Self::Entity::new_unchecked(self.as_slice().to_owned().into()) } fn new_unchecked(slice: &'r [u8]) -> Self { RawWithdrawalRequestReader(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(()) } } #[derive(Debug, Default)] pub struct RawWithdrawalRequestBuilder { pub(crate) nonce: Uint32, pub(crate) capacity: Uint64, pub(crate) amount: Uint128, pub(crate) sudt_script_hash: Byte32, pub(crate) account_script_hash: Byte32, pub(crate) sell_amount: Uint128, pub(crate) sell_capacity: Uint64, pub(crate) owner_lock_hash: Byte32, pub(crate) payment_lock_hash: Byte32, pub(crate) fee: Fee, } impl RawWithdrawalRequestBuilder { pub const TOTAL_SIZE: usize = 200; pub const FIELD_SIZES: [usize; 10] = [4, 8, 16, 32, 32, 16, 8, 32, 32, 20]; pub const FIELD_COUNT: usize = 10; pub fn nonce(mut self, v: Uint32) -> Self { self.nonce = v; self } pub fn capacity(mut self, v: Uint64) -> Self { self.capacity = v; self } pub fn amount(mut self, v: Uint128) -> Self { self.amount = v; self } pub fn sudt_script_hash(mut self, v: Byte32) -> Self { self.sudt_script_hash = v; self } pub fn account_script_hash(mut self, v: Byte32) -> Self { self.account_script_hash = v; self } pub fn sell_amount(mut self, v: Uint128) -> Self { self.sell_amount = v; self } pub fn sell_capacity(mut self, v: Uint64) -> Self { self.sell_capacity = v; self } pub fn owner_lock_hash(mut self, v: Byte32) -> Self { self.owner_lock_hash = v; self } pub fn payment_lock_hash(mut self, v: Byte32) -> Self { self.payment_lock_hash = v; self } pub fn fee(mut self, v: Fee) -> Self { self.fee = v; self } } impl molecule::prelude::Builder for RawWithdrawalRequestBuilder { type Entity = RawWithdrawalRequest; const NAME: &'static str = "RawWithdrawalRequestBuilder"; 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.nonce.as_slice())?; writer.write_all(self.capacity.as_slice())?; writer.write_all(self.amount.as_slice())?; writer.write_all(self.sudt_script_hash.as_slice())?; writer.write_all(self.account_script_hash.as_slice())?; writer.write_all(self.sell_amount.as_slice())?; writer.write_all(self.sell_capacity.as_slice())?; writer.write_all(self.owner_lock_hash.as_slice())?; writer.write_all(self.payment_lock_hash.as_slice())?; writer.write_all(self.fee.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)); RawWithdrawalRequest::new_unchecked(inner.into()) } } #[derive(Clone)] pub struct WithdrawalRequestVec(molecule::bytes::Bytes); impl ::core::fmt::LowerHex for WithdrawalRequestVec { 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 WithdrawalRequestVec { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl ::core::fmt::Display for WithdrawalRequestVec { 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 WithdrawalRequestVec { fn default() -> Self { let v: Vec<u8> = vec![4, 0, 0, 0]; WithdrawalRequestVec::new_unchecked(v.into()) } } impl WithdrawalRequestVec { 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<WithdrawalRequest> { if idx >= self.len() { None } else { Some(self.get_unchecked(idx)) } } pub fn get_unchecked(&self, idx: usize) -> WithdrawalRequest { 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 { WithdrawalRequest::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; WithdrawalRequest::new_unchecked(self.0.slice(start..end)) } } pub fn as_reader<'r>(&'r self) -> WithdrawalRequestVecReader<'r> { WithdrawalRequestVecReader::new_unchecked(self.as_slice()) } } impl molecule::prelude::Entity for WithdrawalRequestVec { type Builder = WithdrawalRequestVecBuilder; const NAME: &'static str = "WithdrawalRequestVec"; fn new_unchecked(data: molecule::bytes::Bytes) -> Self { WithdrawalRequestVec(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> { WithdrawalRequestVecReader::from_slice(slice).map(|reader| reader.to_entity()) } fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> { WithdrawalRequestVecReader::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 WithdrawalRequestVecReader<'r>(&'r [u8]); impl<'r> ::core::fmt::LowerHex for WithdrawalRequestVecReader<'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 WithdrawalRequestVecReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl<'r> ::core::fmt::Display for WithdrawalRequestVecReader<'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> WithdrawalRequestVecReader<'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<WithdrawalRequestReader<'r>> { if idx >= self.len() { None } else { Some(self.get_unchecked(idx)) } } pub fn get_unchecked(&self, idx: usize) -> WithdrawalRequestReader<'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 { WithdrawalRequestReader::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; WithdrawalRequestReader::new_unchecked(&self.as_slice()[start..end]) } } } impl<'r> molecule::prelude::Reader<'r> for WithdrawalRequestVecReader<'r> { type Entity = WithdrawalRequestVec; const NAME: &'static str = "WithdrawalRequestVecReader"; fn to_entity(&self) -> Self::Entity { Self::Entity::new_unchecked(self.as_slice().to_owned().into()) } fn new_unchecked(slice: &'r [u8]) -> Self { WithdrawalRequestVecReader(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]; WithdrawalRequestReader::verify(&slice[start..end], compatible)?; } Ok(()) } } #[derive(Debug, Default)] pub struct WithdrawalRequestVecBuilder(pub(crate) Vec<WithdrawalRequest>); impl WithdrawalRequestVecBuilder { pub fn set(mut self, v: Vec<WithdrawalRequest>) -> Self { self.0 = v; self } pub fn push(mut self, v: WithdrawalRequest) -> Self { self.0.push(v); self } pub fn extend<T: ::core::iter::IntoIterator<Item = WithdrawalRequest>>( mut self, iter: T, ) -> Self { for elem in iter { self.0.push(elem); } self } } impl molecule::prelude::Builder for WithdrawalRequestVecBuilder { type Entity = WithdrawalRequestVec; const NAME: &'static str = "WithdrawalRequestVecBuilder"; 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)); WithdrawalRequestVec::new_unchecked(inner.into()) } } pub struct WithdrawalRequestVecIterator(WithdrawalRequestVec, usize, usize); impl ::core::iter::Iterator for WithdrawalRequestVecIterator { type Item = WithdrawalRequest; 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 WithdrawalRequestVecIterator { fn len(&self) -> usize { self.2 - self.1 } } impl ::core::iter::IntoIterator for WithdrawalRequestVec { type Item = WithdrawalRequest; type IntoIter = WithdrawalRequestVecIterator; fn into_iter(self) -> Self::IntoIter { let len = self.len(); WithdrawalRequestVecIterator(self, 0, len) } } impl<'r> WithdrawalRequestVecReader<'r> { pub fn iter<'t>(&'t self) -> WithdrawalRequestVecReaderIterator<'t, 'r> { WithdrawalRequestVecReaderIterator(&self, 0, self.len()) } } pub struct WithdrawalRequestVecReaderIterator<'t, 'r>( &'t WithdrawalRequestVecReader<'r>, usize, usize, ); impl<'t: 'r, 'r> ::core::iter::Iterator for WithdrawalRequestVecReaderIterator<'t, 'r> { type Item = WithdrawalRequestReader<'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 WithdrawalRequestVecReaderIterator<'t, 'r> { fn len(&self) -> usize { self.2 - self.1 } } #[derive(Clone)] pub struct WithdrawalRequest(molecule::bytes::Bytes); impl ::core::fmt::LowerHex for WithdrawalRequest { 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 WithdrawalRequest { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl ::core::fmt::Display for WithdrawalRequest { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; write!(f, "{}: {}", "raw", self.raw())?; write!(f, ", {}: {}", "signature", self.signature())?; let extra_count = self.count_extra_fields(); if extra_count != 0 { write!(f, ", .. ({} fields)", extra_count)?; } write!(f, " }}") } } impl ::core::default::Default for WithdrawalRequest { fn default() -> Self { let v: Vec<u8> = vec![ 216, 0, 0, 0, 12, 0, 0, 0, 212, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ]; WithdrawalRequest::new_unchecked(v.into()) } } impl WithdrawalRequest { 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 raw(&self) -> RawWithdrawalRequest { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[4..]) as usize; let end = molecule::unpack_number(&slice[8..]) as usize; RawWithdrawalRequest::new_unchecked(self.0.slice(start..end)) } pub fn signature(&self) -> Bytes { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[8..]) as usize; if self.has_extra_fields() { let end = molecule::unpack_number(&slice[12..]) as usize; Bytes::new_unchecked(self.0.slice(start..end)) } else { Bytes::new_unchecked(self.0.slice(start..)) } } pub fn as_reader<'r>(&'r self) -> WithdrawalRequestReader<'r> { WithdrawalRequestReader::new_unchecked(self.as_slice()) } } impl molecule::prelude::Entity for WithdrawalRequest { type Builder = WithdrawalRequestBuilder; const NAME: &'static str = "WithdrawalRequest"; fn new_unchecked(data: molecule::bytes::Bytes) -> Self { WithdrawalRequest(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> { WithdrawalRequestReader::from_slice(slice).map(|reader| reader.to_entity()) } fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> { WithdrawalRequestReader::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() .raw(self.raw()) .signature(self.signature()) } } #[derive(Clone, Copy)] pub struct WithdrawalRequestReader<'r>(&'r [u8]); impl<'r> ::core::fmt::LowerHex for WithdrawalRequestReader<'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 WithdrawalRequestReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl<'r> ::core::fmt::Display for WithdrawalRequestReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; write!(f, "{}: {}", "raw", self.raw())?; write!(f, ", {}: {}", "signature", self.signature())?; let extra_count = self.count_extra_fields(); if extra_count != 0 { write!(f, ", .. ({} fields)", extra_count)?; } write!(f, " }}") } } impl<'r> WithdrawalRequestReader<'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 raw(&self) -> RawWithdrawalRequestReader<'r> { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[4..]) as usize; let end = molecule::unpack_number(&slice[8..]) as usize; RawWithdrawalRequestReader::new_unchecked(&self.as_slice()[start..end]) } pub fn signature(&self) -> BytesReader<'r> { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[8..]) as usize; if self.has_extra_fields() { let end = molecule::unpack_number(&slice[12..]) as usize; BytesReader::new_unchecked(&self.as_slice()[start..end]) } else { BytesReader::new_unchecked(&self.as_slice()[start..]) } } } impl<'r> molecule::prelude::Reader<'r> for WithdrawalRequestReader<'r> { type Entity = WithdrawalRequest; const NAME: &'static str = "WithdrawalRequestReader"; fn to_entity(&self) -> Self::Entity { Self::Entity::new_unchecked(self.as_slice().to_owned().into()) } fn new_unchecked(slice: &'r [u8]) -> Self { WithdrawalRequestReader(slice) } fn as_slice(&self) -> &'r [u8] { self.0 } fn verify(slice: &[u8], compatible: bool) -> molecule::error::VerificationResult<()> { use molecule::verification_error as ve; let slice_len = slice.len(); if slice_len < molecule::NUMBER_SIZE { return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE, slice_len); } let total_size = molecule::unpack_number(slice) as usize; if slice_len != total_size { return ve!(Self, TotalSizeNotMatch, total_size, slice_len); } if slice_len == molecule::NUMBER_SIZE && Self::FIELD_COUNT == 0 { return Ok(()); } if slice_len < molecule::NUMBER_SIZE * 2 { return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE * 2, slice_len); } let offset_first = molecule::unpack_number(&slice[molecule::NUMBER_SIZE..]) as usize; if offset_first % molecule::NUMBER_SIZE != 0 || offset_first < molecule::NUMBER_SIZE * 2 { return ve!(Self, OffsetsNotMatch); } if slice_len < offset_first { return ve!(Self, HeaderIsBroken, offset_first, slice_len); } let field_count = offset_first / molecule::NUMBER_SIZE - 1; if field_count < Self::FIELD_COUNT { return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, field_count); } else if !compatible && field_count > Self::FIELD_COUNT { return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, field_count); }; let mut offsets: Vec<usize> = slice[molecule::NUMBER_SIZE..offset_first] .chunks_exact(molecule::NUMBER_SIZE) .map(|x| molecule::unpack_number(x) as usize) .collect(); offsets.push(total_size); if offsets.windows(2).any(|i| i[0] > i[1]) { return ve!(Self, OffsetsNotMatch); } RawWithdrawalRequestReader::verify(&slice[offsets[0]..offsets[1]], compatible)?; BytesReader::verify(&slice[offsets[1]..offsets[2]], compatible)?; Ok(()) } } #[derive(Debug, Default)] pub struct WithdrawalRequestBuilder { pub(crate) raw: RawWithdrawalRequest, pub(crate) signature: Bytes, } impl WithdrawalRequestBuilder { pub const FIELD_COUNT: usize = 2; pub fn raw(mut self, v: RawWithdrawalRequest) -> Self { self.raw = v; self } pub fn signature(mut self, v: Bytes) -> Self { self.signature = v; self } } impl molecule::prelude::Builder for WithdrawalRequestBuilder { type Entity = WithdrawalRequest; const NAME: &'static str = "WithdrawalRequestBuilder"; fn expected_length(&self) -> usize { molecule::NUMBER_SIZE * (Self::FIELD_COUNT + 1) + self.raw.as_slice().len() + self.signature.as_slice().len() } fn write<W: molecule::io::Write>(&self, writer: &mut W) -> molecule::io::Result<()> { let mut total_size = molecule::NUMBER_SIZE * (Self::FIELD_COUNT + 1); let mut offsets = Vec::with_capacity(Self::FIELD_COUNT); offsets.push(total_size); total_size += self.raw.as_slice().len(); offsets.push(total_size); total_size += self.signature.as_slice().len(); writer.write_all(&molecule::pack_number(total_size as molecule::Number))?; for offset in offsets.into_iter() { writer.write_all(&molecule::pack_number(offset as molecule::Number))?; } writer.write_all(self.raw.as_slice())?; writer.write_all(self.signature.as_slice())?; Ok(()) } fn build(&self) -> Self::Entity { let mut inner = Vec::with_capacity(self.expected_length()); self.write(&mut inner) .unwrap_or_else(|_| panic!("{} build should be ok", Self::NAME)); WithdrawalRequest::new_unchecked(inner.into()) } } #[derive(Clone)] pub struct KVPair(molecule::bytes::Bytes); impl ::core::fmt::LowerHex for KVPair { 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 KVPair { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl ::core::fmt::Display for KVPair { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; write!(f, "{}: {}", "k", self.k())?; write!(f, ", {}: {}", "v", self.v())?; let extra_count = self.count_extra_fields(); if extra_count != 0 { write!(f, ", .. ({} fields)", extra_count)?; } write!(f, " }}") } } impl ::core::default::Default for KVPair { fn default() -> Self { let v: Vec<u8> = vec![ 76, 0, 0, 0, 12, 0, 0, 0, 44, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ]; KVPair::new_unchecked(v.into()) } } impl KVPair { 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 k(&self) -> Byte32 { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[4..]) as usize; let end = molecule::unpack_number(&slice[8..]) as usize; Byte32::new_unchecked(self.0.slice(start..end)) } pub fn v(&self) -> Byte32 { 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; Byte32::new_unchecked(self.0.slice(start..end)) } else { Byte32::new_unchecked(self.0.slice(start..)) } } pub fn as_reader<'r>(&'r self) -> KVPairReader<'r> { KVPairReader::new_unchecked(self.as_slice()) } } impl molecule::prelude::Entity for KVPair { type Builder = KVPairBuilder; const NAME: &'static str = "KVPair"; fn new_unchecked(data: molecule::bytes::Bytes) -> Self { KVPair(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> { KVPairReader::from_slice(slice).map(|reader| reader.to_entity()) } fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> { KVPairReader::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().k(self.k()).v(self.v()) } } #[derive(Clone, Copy)] pub struct KVPairReader<'r>(&'r [u8]); impl<'r> ::core::fmt::LowerHex for KVPairReader<'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 KVPairReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl<'r> ::core::fmt::Display for KVPairReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; write!(f, "{}: {}", "k", self.k())?; write!(f, ", {}: {}", "v", self.v())?; let extra_count = self.count_extra_fields(); if extra_count != 0 { write!(f, ", .. ({} fields)", extra_count)?; } write!(f, " }}") } } impl<'r> KVPairReader<'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 k(&self) -> Byte32Reader<'r> { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[4..]) as usize; let end = molecule::unpack_number(&slice[8..]) as usize; Byte32Reader::new_unchecked(&self.as_slice()[start..end]) } pub fn v(&self) -> Byte32Reader<'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; Byte32Reader::new_unchecked(&self.as_slice()[start..end]) } else { Byte32Reader::new_unchecked(&self.as_slice()[start..]) } } } impl<'r> molecule::prelude::Reader<'r> for KVPairReader<'r> { type Entity = KVPair; const NAME: &'static str = "KVPairReader"; fn to_entity(&self) -> Self::Entity { Self::Entity::new_unchecked(self.as_slice().to_owned().into()) } fn new_unchecked(slice: &'r [u8]) -> Self { KVPairReader(slice) } fn as_slice(&self) -> &'r [u8] { self.0 } fn verify(slice: &[u8], compatible: bool) -> molecule::error::VerificationResult<()> { use molecule::verification_error as ve; let slice_len = slice.len(); if slice_len < molecule::NUMBER_SIZE { return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE, slice_len); } let total_size = molecule::unpack_number(slice) as usize; if slice_len != total_size { return ve!(Self, TotalSizeNotMatch, total_size, slice_len); } if slice_len == molecule::NUMBER_SIZE && Self::FIELD_COUNT == 0 { return Ok(()); } if slice_len < molecule::NUMBER_SIZE * 2 { return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE * 2, slice_len); } let offset_first = molecule::unpack_number(&slice[molecule::NUMBER_SIZE..]) as usize; if offset_first % molecule::NUMBER_SIZE != 0 || offset_first < molecule::NUMBER_SIZE * 2 { return ve!(Self, OffsetsNotMatch); } if slice_len < offset_first { return ve!(Self, HeaderIsBroken, offset_first, slice_len); } let field_count = offset_first / molecule::NUMBER_SIZE - 1; if field_count < Self::FIELD_COUNT { return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, field_count); } else if !compatible && field_count > Self::FIELD_COUNT { return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, field_count); }; let mut offsets: Vec<usize> = slice[molecule::NUMBER_SIZE..offset_first] .chunks_exact(molecule::NUMBER_SIZE) .map(|x| molecule::unpack_number(x) as usize) .collect(); offsets.push(total_size); if offsets.windows(2).any(|i| i[0] > i[1]) { return ve!(Self, OffsetsNotMatch); } Byte32Reader::verify(&slice[offsets[0]..offsets[1]], compatible)?; Byte32Reader::verify(&slice[offsets[1]..offsets[2]], compatible)?; Ok(()) } } #[derive(Debug, Default)] pub struct KVPairBuilder { pub(crate) k: Byte32, pub(crate) v: Byte32, } impl KVPairBuilder { pub const FIELD_COUNT: usize = 2; pub fn k(mut self, v: Byte32) -> Self { self.k = v; self } pub fn v(mut self, v: Byte32) -> Self { self.v = v; self } } impl molecule::prelude::Builder for KVPairBuilder { type Entity = KVPair; const NAME: &'static str = "KVPairBuilder"; fn expected_length(&self) -> usize { molecule::NUMBER_SIZE * (Self::FIELD_COUNT + 1) + self.k.as_slice().len() + self.v.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.k.as_slice().len(); offsets.push(total_size); total_size += self.v.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.k.as_slice())?; writer.write_all(self.v.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)); KVPair::new_unchecked(inner.into()) } } #[derive(Clone)] pub struct KVPairVec(molecule::bytes::Bytes); impl ::core::fmt::LowerHex for KVPairVec { 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 KVPairVec { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl ::core::fmt::Display for KVPairVec { 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 KVPairVec { fn default() -> Self { let v: Vec<u8> = vec![4, 0, 0, 0]; KVPairVec::new_unchecked(v.into()) } } impl KVPairVec { 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<KVPair> { if idx >= self.len() { None } else { Some(self.get_unchecked(idx)) } } pub fn get_unchecked(&self, idx: usize) -> KVPair { 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 { KVPair::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; KVPair::new_unchecked(self.0.slice(start..end)) } } pub fn as_reader<'r>(&'r self) -> KVPairVecReader<'r> { KVPairVecReader::new_unchecked(self.as_slice()) } } impl molecule::prelude::Entity for KVPairVec { type Builder = KVPairVecBuilder; const NAME: &'static str = "KVPairVec"; fn new_unchecked(data: molecule::bytes::Bytes) -> Self { KVPairVec(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> { KVPairVecReader::from_slice(slice).map(|reader| reader.to_entity()) } fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> { KVPairVecReader::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 KVPairVecReader<'r>(&'r [u8]); impl<'r> ::core::fmt::LowerHex for KVPairVecReader<'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 KVPairVecReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl<'r> ::core::fmt::Display for KVPairVecReader<'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> KVPairVecReader<'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<KVPairReader<'r>> { if idx >= self.len() { None } else { Some(self.get_unchecked(idx)) } } pub fn get_unchecked(&self, idx: usize) -> KVPairReader<'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 { KVPairReader::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; KVPairReader::new_unchecked(&self.as_slice()[start..end]) } } } impl<'r> molecule::prelude::Reader<'r> for KVPairVecReader<'r> { type Entity = KVPairVec; const NAME: &'static str = "KVPairVecReader"; fn to_entity(&self) -> Self::Entity { Self::Entity::new_unchecked(self.as_slice().to_owned().into()) } fn new_unchecked(slice: &'r [u8]) -> Self { KVPairVecReader(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]; KVPairReader::verify(&slice[start..end], compatible)?; } Ok(()) } } #[derive(Debug, Default)] pub struct KVPairVecBuilder(pub(crate) Vec<KVPair>); impl KVPairVecBuilder { pub fn set(mut self, v: Vec<KVPair>) -> Self { self.0 = v; self } pub fn push(mut self, v: KVPair) -> Self { self.0.push(v); self } pub fn extend<T: ::core::iter::IntoIterator<Item = KVPair>>(mut self, iter: T) -> Self { for elem in iter { self.0.push(elem); } self } } impl molecule::prelude::Builder for KVPairVecBuilder { type Entity = KVPairVec; const NAME: &'static str = "KVPairVecBuilder"; 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)); KVPairVec::new_unchecked(inner.into()) } } pub struct KVPairVecIterator(KVPairVec, usize, usize); impl ::core::iter::Iterator for KVPairVecIterator { type Item = KVPair; 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 KVPairVecIterator { fn len(&self) -> usize { self.2 - self.1 } } impl ::core::iter::IntoIterator for KVPairVec { type Item = KVPair; type IntoIter = KVPairVecIterator; fn into_iter(self) -> Self::IntoIter { let len = self.len(); KVPairVecIterator(self, 0, len) } } impl<'r> KVPairVecReader<'r> { pub fn iter<'t>(&'t self) -> KVPairVecReaderIterator<'t, 'r> { KVPairVecReaderIterator(&self, 0, self.len()) } } pub struct KVPairVecReaderIterator<'t, 'r>(&'t KVPairVecReader<'r>, usize, usize); impl<'t: 'r, 'r> ::core::iter::Iterator for KVPairVecReaderIterator<'t, 'r> { type Item = KVPairReader<'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 KVPairVecReaderIterator<'t, 'r> { fn len(&self) -> usize { self.2 - self.1 } } #[derive(Clone)] pub struct BlockInfo(molecule::bytes::Bytes); impl ::core::fmt::LowerHex for BlockInfo { 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 BlockInfo { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl ::core::fmt::Display for BlockInfo { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; write!(f, "{}: {}", "block_producer_id", self.block_producer_id())?; write!(f, ", {}: {}", "number", self.number())?; write!(f, ", {}: {}", "timestamp", self.timestamp())?; write!(f, " }}") } } impl ::core::default::Default for BlockInfo { fn default() -> Self { let v: Vec<u8> = vec![0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; BlockInfo::new_unchecked(v.into()) } } impl BlockInfo { pub const TOTAL_SIZE: usize = 20; pub const FIELD_SIZES: [usize; 3] = [4, 8, 8]; pub const FIELD_COUNT: usize = 3; pub fn block_producer_id(&self) -> Uint32 { Uint32::new_unchecked(self.0.slice(0..4)) } pub fn number(&self) -> Uint64 { Uint64::new_unchecked(self.0.slice(4..12)) } pub fn timestamp(&self) -> Uint64 { Uint64::new_unchecked(self.0.slice(12..20)) } pub fn as_reader<'r>(&'r self) -> BlockInfoReader<'r> { BlockInfoReader::new_unchecked(self.as_slice()) } } impl molecule::prelude::Entity for BlockInfo { type Builder = BlockInfoBuilder; const NAME: &'static str = "BlockInfo"; fn new_unchecked(data: molecule::bytes::Bytes) -> Self { BlockInfo(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> { BlockInfoReader::from_slice(slice).map(|reader| reader.to_entity()) } fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> { BlockInfoReader::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() .block_producer_id(self.block_producer_id()) .number(self.number()) .timestamp(self.timestamp()) } } #[derive(Clone, Copy)] pub struct BlockInfoReader<'r>(&'r [u8]); impl<'r> ::core::fmt::LowerHex for BlockInfoReader<'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 BlockInfoReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl<'r> ::core::fmt::Display for BlockInfoReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; write!(f, "{}: {}", "block_producer_id", self.block_producer_id())?; write!(f, ", {}: {}", "number", self.number())?; write!(f, ", {}: {}", "timestamp", self.timestamp())?; write!(f, " }}") } } impl<'r> BlockInfoReader<'r> { pub const TOTAL_SIZE: usize = 20; pub const FIELD_SIZES: [usize; 3] = [4, 8, 8]; pub const FIELD_COUNT: usize = 3; pub fn block_producer_id(&self) -> Uint32Reader<'r> { Uint32Reader::new_unchecked(&self.as_slice()[0..4]) } pub fn number(&self) -> Uint64Reader<'r> { Uint64Reader::new_unchecked(&self.as_slice()[4..12]) } pub fn timestamp(&self) -> Uint64Reader<'r> { Uint64Reader::new_unchecked(&self.as_slice()[12..20]) } } impl<'r> molecule::prelude::Reader<'r> for BlockInfoReader<'r> { type Entity = BlockInfo; const NAME: &'static str = "BlockInfoReader"; fn to_entity(&self) -> Self::Entity { Self::Entity::new_unchecked(self.as_slice().to_owned().into()) } fn new_unchecked(slice: &'r [u8]) -> Self { BlockInfoReader(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(()) } } #[derive(Debug, Default)] pub struct BlockInfoBuilder { pub(crate) block_producer_id: Uint32, pub(crate) number: Uint64, pub(crate) timestamp: Uint64, } impl BlockInfoBuilder { pub const TOTAL_SIZE: usize = 20; pub const FIELD_SIZES: [usize; 3] = [4, 8, 8]; pub const FIELD_COUNT: usize = 3; pub fn block_producer_id(mut self, v: Uint32) -> Self { self.block_producer_id = v; self } pub fn number(mut self, v: Uint64) -> Self { self.number = v; self } pub fn timestamp(mut self, v: Uint64) -> Self { self.timestamp = v; self } } impl molecule::prelude::Builder for BlockInfoBuilder { type Entity = BlockInfo; const NAME: &'static str = "BlockInfoBuilder"; 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.block_producer_id.as_slice())?; writer.write_all(self.number.as_slice())?; writer.write_all(self.timestamp.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)); BlockInfo::new_unchecked(inner.into()) } } #[derive(Clone)] pub struct DepositLockArgs(molecule::bytes::Bytes); impl ::core::fmt::LowerHex for DepositLockArgs { 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 DepositLockArgs { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl ::core::fmt::Display for DepositLockArgs { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; write!(f, "{}: {}", "owner_lock_hash", self.owner_lock_hash())?; write!(f, ", {}: {}", "layer2_lock", self.layer2_lock())?; write!(f, ", {}: {}", "cancel_timeout", self.cancel_timeout())?; let extra_count = self.count_extra_fields(); if extra_count != 0 { write!(f, ", .. ({} fields)", extra_count)?; } write!(f, " }}") } } impl ::core::default::Default for DepositLockArgs { fn default() -> Self { let v: Vec<u8> = vec![ 109, 0, 0, 0, 16, 0, 0, 0, 48, 0, 0, 0, 101, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 53, 0, 0, 0, 16, 0, 0, 0, 48, 0, 0, 0, 49, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ]; DepositLockArgs::new_unchecked(v.into()) } } impl DepositLockArgs { 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 owner_lock_hash(&self) -> Byte32 { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[4..]) as usize; let end = molecule::unpack_number(&slice[8..]) as usize; Byte32::new_unchecked(self.0.slice(start..end)) } pub fn layer2_lock(&self) -> Script { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[8..]) as usize; let end = molecule::unpack_number(&slice[12..]) as usize; Script::new_unchecked(self.0.slice(start..end)) } pub fn cancel_timeout(&self) -> Uint64 { 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; Uint64::new_unchecked(self.0.slice(start..end)) } else { Uint64::new_unchecked(self.0.slice(start..)) } } pub fn as_reader<'r>(&'r self) -> DepositLockArgsReader<'r> { DepositLockArgsReader::new_unchecked(self.as_slice()) } } impl molecule::prelude::Entity for DepositLockArgs { type Builder = DepositLockArgsBuilder; const NAME: &'static str = "DepositLockArgs"; fn new_unchecked(data: molecule::bytes::Bytes) -> Self { DepositLockArgs(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> { DepositLockArgsReader::from_slice(slice).map(|reader| reader.to_entity()) } fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> { DepositLockArgsReader::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() .owner_lock_hash(self.owner_lock_hash()) .layer2_lock(self.layer2_lock()) .cancel_timeout(self.cancel_timeout()) } } #[derive(Clone, Copy)] pub struct DepositLockArgsReader<'r>(&'r [u8]); impl<'r> ::core::fmt::LowerHex for DepositLockArgsReader<'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 DepositLockArgsReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl<'r> ::core::fmt::Display for DepositLockArgsReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; write!(f, "{}: {}", "owner_lock_hash", self.owner_lock_hash())?; write!(f, ", {}: {}", "layer2_lock", self.layer2_lock())?; write!(f, ", {}: {}", "cancel_timeout", self.cancel_timeout())?; let extra_count = self.count_extra_fields(); if extra_count != 0 { write!(f, ", .. ({} fields)", extra_count)?; } write!(f, " }}") } } impl<'r> DepositLockArgsReader<'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 owner_lock_hash(&self) -> Byte32Reader<'r> { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[4..]) as usize; let end = molecule::unpack_number(&slice[8..]) as usize; Byte32Reader::new_unchecked(&self.as_slice()[start..end]) } pub fn layer2_lock(&self) -> ScriptReader<'r> { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[8..]) as usize; let end = molecule::unpack_number(&slice[12..]) as usize; ScriptReader::new_unchecked(&self.as_slice()[start..end]) } pub fn cancel_timeout(&self) -> Uint64Reader<'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; Uint64Reader::new_unchecked(&self.as_slice()[start..end]) } else { Uint64Reader::new_unchecked(&self.as_slice()[start..]) } } } impl<'r> molecule::prelude::Reader<'r> for DepositLockArgsReader<'r> { type Entity = DepositLockArgs; const NAME: &'static str = "DepositLockArgsReader"; fn to_entity(&self) -> Self::Entity { Self::Entity::new_unchecked(self.as_slice().to_owned().into()) } fn new_unchecked(slice: &'r [u8]) -> Self { DepositLockArgsReader(slice) } fn as_slice(&self) -> &'r [u8] { self.0 } fn verify(slice: &[u8], compatible: bool) -> molecule::error::VerificationResult<()> { use molecule::verification_error as ve; let slice_len = slice.len(); if slice_len < molecule::NUMBER_SIZE { return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE, slice_len); } let total_size = molecule::unpack_number(slice) as usize; if slice_len != total_size { return ve!(Self, TotalSizeNotMatch, total_size, slice_len); } if slice_len == molecule::NUMBER_SIZE && Self::FIELD_COUNT == 0 { return Ok(()); } if slice_len < molecule::NUMBER_SIZE * 2 { return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE * 2, slice_len); } let offset_first = molecule::unpack_number(&slice[molecule::NUMBER_SIZE..]) as usize; if offset_first % molecule::NUMBER_SIZE != 0 || offset_first < molecule::NUMBER_SIZE * 2 { return ve!(Self, OffsetsNotMatch); } if slice_len < offset_first { return ve!(Self, HeaderIsBroken, offset_first, slice_len); } let field_count = offset_first / molecule::NUMBER_SIZE - 1; if field_count < Self::FIELD_COUNT { return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, field_count); } else if !compatible && field_count > Self::FIELD_COUNT { return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, field_count); }; let mut offsets: Vec<usize> = slice[molecule::NUMBER_SIZE..offset_first] .chunks_exact(molecule::NUMBER_SIZE) .map(|x| molecule::unpack_number(x) as usize) .collect(); offsets.push(total_size); if offsets.windows(2).any(|i| i[0] > i[1]) { return ve!(Self, OffsetsNotMatch); } Byte32Reader::verify(&slice[offsets[0]..offsets[1]], compatible)?; ScriptReader::verify(&slice[offsets[1]..offsets[2]], compatible)?; Uint64Reader::verify(&slice[offsets[2]..offsets[3]], compatible)?; Ok(()) } } #[derive(Debug, Default)] pub struct DepositLockArgsBuilder { pub(crate) owner_lock_hash: Byte32, pub(crate) layer2_lock: Script, pub(crate) cancel_timeout: Uint64, } impl DepositLockArgsBuilder { pub const FIELD_COUNT: usize = 3; pub fn owner_lock_hash(mut self, v: Byte32) -> Self { self.owner_lock_hash = v; self } pub fn layer2_lock(mut self, v: Script) -> Self { self.layer2_lock = v; self } pub fn cancel_timeout(mut self, v: Uint64) -> Self { self.cancel_timeout = v; self } } impl molecule::prelude::Builder for DepositLockArgsBuilder { type Entity = DepositLockArgs; const NAME: &'static str = "DepositLockArgsBuilder"; fn expected_length(&self) -> usize { molecule::NUMBER_SIZE * (Self::FIELD_COUNT + 1) + self.owner_lock_hash.as_slice().len() + self.layer2_lock.as_slice().len() + self.cancel_timeout.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.owner_lock_hash.as_slice().len(); offsets.push(total_size); total_size += self.layer2_lock.as_slice().len(); offsets.push(total_size); total_size += self.cancel_timeout.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.owner_lock_hash.as_slice())?; writer.write_all(self.layer2_lock.as_slice())?; writer.write_all(self.cancel_timeout.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)); DepositLockArgs::new_unchecked(inner.into()) } } #[derive(Clone)] pub struct CustodianLockArgs(molecule::bytes::Bytes); impl ::core::fmt::LowerHex for CustodianLockArgs { 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 CustodianLockArgs { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl ::core::fmt::Display for CustodianLockArgs { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; write!(f, "{}: {}", "deposit_lock_args", self.deposit_lock_args())?; write!( f, ", {}: {}", "deposit_block_hash", self.deposit_block_hash() )?; write!( f, ", {}: {}", "deposit_block_number", self.deposit_block_number() )?; let extra_count = self.count_extra_fields(); if extra_count != 0 { write!(f, ", .. ({} fields)", extra_count)?; } write!(f, " }}") } } impl ::core::default::Default for CustodianLockArgs { fn default() -> Self { let v: Vec<u8> = vec![ 165, 0, 0, 0, 16, 0, 0, 0, 125, 0, 0, 0, 157, 0, 0, 0, 109, 0, 0, 0, 16, 0, 0, 0, 48, 0, 0, 0, 101, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 53, 0, 0, 0, 16, 0, 0, 0, 48, 0, 0, 0, 49, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ]; CustodianLockArgs::new_unchecked(v.into()) } } impl CustodianLockArgs { 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 deposit_lock_args(&self) -> DepositLockArgs { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[4..]) as usize; let end = molecule::unpack_number(&slice[8..]) as usize; DepositLockArgs::new_unchecked(self.0.slice(start..end)) } pub fn deposit_block_hash(&self) -> Byte32 { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[8..]) as usize; let end = molecule::unpack_number(&slice[12..]) as usize; Byte32::new_unchecked(self.0.slice(start..end)) } pub fn deposit_block_number(&self) -> Uint64 { 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; Uint64::new_unchecked(self.0.slice(start..end)) } else { Uint64::new_unchecked(self.0.slice(start..)) } } pub fn as_reader<'r>(&'r self) -> CustodianLockArgsReader<'r> { CustodianLockArgsReader::new_unchecked(self.as_slice()) } } impl molecule::prelude::Entity for CustodianLockArgs { type Builder = CustodianLockArgsBuilder; const NAME: &'static str = "CustodianLockArgs"; fn new_unchecked(data: molecule::bytes::Bytes) -> Self { CustodianLockArgs(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> { CustodianLockArgsReader::from_slice(slice).map(|reader| reader.to_entity()) } fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> { CustodianLockArgsReader::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() .deposit_lock_args(self.deposit_lock_args()) .deposit_block_hash(self.deposit_block_hash()) .deposit_block_number(self.deposit_block_number()) } } #[derive(Clone, Copy)] pub struct CustodianLockArgsReader<'r>(&'r [u8]); impl<'r> ::core::fmt::LowerHex for CustodianLockArgsReader<'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 CustodianLockArgsReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl<'r> ::core::fmt::Display for CustodianLockArgsReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; write!(f, "{}: {}", "deposit_lock_args", self.deposit_lock_args())?; write!( f, ", {}: {}", "deposit_block_hash", self.deposit_block_hash() )?; write!( f, ", {}: {}", "deposit_block_number", self.deposit_block_number() )?; let extra_count = self.count_extra_fields(); if extra_count != 0 { write!(f, ", .. ({} fields)", extra_count)?; } write!(f, " }}") } } impl<'r> CustodianLockArgsReader<'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 deposit_lock_args(&self) -> DepositLockArgsReader<'r> { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[4..]) as usize; let end = molecule::unpack_number(&slice[8..]) as usize; DepositLockArgsReader::new_unchecked(&self.as_slice()[start..end]) } pub fn deposit_block_hash(&self) -> Byte32Reader<'r> { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[8..]) as usize; let end = molecule::unpack_number(&slice[12..]) as usize; Byte32Reader::new_unchecked(&self.as_slice()[start..end]) } pub fn deposit_block_number(&self) -> Uint64Reader<'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; Uint64Reader::new_unchecked(&self.as_slice()[start..end]) } else { Uint64Reader::new_unchecked(&self.as_slice()[start..]) } } } impl<'r> molecule::prelude::Reader<'r> for CustodianLockArgsReader<'r> { type Entity = CustodianLockArgs; const NAME: &'static str = "CustodianLockArgsReader"; fn to_entity(&self) -> Self::Entity { Self::Entity::new_unchecked(self.as_slice().to_owned().into()) } fn new_unchecked(slice: &'r [u8]) -> Self { CustodianLockArgsReader(slice) } fn as_slice(&self) -> &'r [u8] { self.0 } fn verify(slice: &[u8], compatible: bool) -> molecule::error::VerificationResult<()> { use molecule::verification_error as ve; let slice_len = slice.len(); if slice_len < molecule::NUMBER_SIZE { return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE, slice_len); } let total_size = molecule::unpack_number(slice) as usize; if slice_len != total_size { return ve!(Self, TotalSizeNotMatch, total_size, slice_len); } if slice_len == molecule::NUMBER_SIZE && Self::FIELD_COUNT == 0 { return Ok(()); } if slice_len < molecule::NUMBER_SIZE * 2 { return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE * 2, slice_len); } let offset_first = molecule::unpack_number(&slice[molecule::NUMBER_SIZE..]) as usize; if offset_first % molecule::NUMBER_SIZE != 0 || offset_first < molecule::NUMBER_SIZE * 2 { return ve!(Self, OffsetsNotMatch); } if slice_len < offset_first { return ve!(Self, HeaderIsBroken, offset_first, slice_len); } let field_count = offset_first / molecule::NUMBER_SIZE - 1; if field_count < Self::FIELD_COUNT { return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, field_count); } else if !compatible && field_count > Self::FIELD_COUNT { return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, field_count); }; let mut offsets: Vec<usize> = slice[molecule::NUMBER_SIZE..offset_first] .chunks_exact(molecule::NUMBER_SIZE) .map(|x| molecule::unpack_number(x) as usize) .collect(); offsets.push(total_size); if offsets.windows(2).any(|i| i[0] > i[1]) { return ve!(Self, OffsetsNotMatch); } DepositLockArgsReader::verify(&slice[offsets[0]..offsets[1]], compatible)?; Byte32Reader::verify(&slice[offsets[1]..offsets[2]], compatible)?; Uint64Reader::verify(&slice[offsets[2]..offsets[3]], compatible)?; Ok(()) } } #[derive(Debug, Default)] pub struct CustodianLockArgsBuilder { pub(crate) deposit_lock_args: DepositLockArgs, pub(crate) deposit_block_hash: Byte32, pub(crate) deposit_block_number: Uint64, } impl CustodianLockArgsBuilder { pub const FIELD_COUNT: usize = 3; pub fn deposit_lock_args(mut self, v: DepositLockArgs) -> Self { self.deposit_lock_args = v; self } pub fn deposit_block_hash(mut self, v: Byte32) -> Self { self.deposit_block_hash = v; self } pub fn deposit_block_number(mut self, v: Uint64) -> Self { self.deposit_block_number = v; self } } impl molecule::prelude::Builder for CustodianLockArgsBuilder { type Entity = CustodianLockArgs; const NAME: &'static str = "CustodianLockArgsBuilder"; fn expected_length(&self) -> usize { molecule::NUMBER_SIZE * (Self::FIELD_COUNT + 1) + self.deposit_lock_args.as_slice().len() + self.deposit_block_hash.as_slice().len() + self.deposit_block_number.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.deposit_lock_args.as_slice().len(); offsets.push(total_size); total_size += self.deposit_block_hash.as_slice().len(); offsets.push(total_size); total_size += self.deposit_block_number.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.deposit_lock_args.as_slice())?; writer.write_all(self.deposit_block_hash.as_slice())?; writer.write_all(self.deposit_block_number.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)); CustodianLockArgs::new_unchecked(inner.into()) } } #[derive(Clone)] pub struct UnlockCustodianViaRevertWitness(molecule::bytes::Bytes); impl ::core::fmt::LowerHex for UnlockCustodianViaRevertWitness { 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 UnlockCustodianViaRevertWitness { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl ::core::fmt::Display for UnlockCustodianViaRevertWitness { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; write!(f, "{}: {}", "deposit_lock_hash", self.deposit_lock_hash())?; write!(f, " }}") } } impl ::core::default::Default for UnlockCustodianViaRevertWitness { fn default() -> Self { let v: Vec<u8> = vec![ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ]; UnlockCustodianViaRevertWitness::new_unchecked(v.into()) } } impl UnlockCustodianViaRevertWitness { pub const TOTAL_SIZE: usize = 32; pub const FIELD_SIZES: [usize; 1] = [32]; pub const FIELD_COUNT: usize = 1; pub fn deposit_lock_hash(&self) -> Byte32 { Byte32::new_unchecked(self.0.slice(0..32)) } pub fn as_reader<'r>(&'r self) -> UnlockCustodianViaRevertWitnessReader<'r> { UnlockCustodianViaRevertWitnessReader::new_unchecked(self.as_slice()) } } impl molecule::prelude::Entity for UnlockCustodianViaRevertWitness { type Builder = UnlockCustodianViaRevertWitnessBuilder; const NAME: &'static str = "UnlockCustodianViaRevertWitness"; fn new_unchecked(data: molecule::bytes::Bytes) -> Self { UnlockCustodianViaRevertWitness(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> { UnlockCustodianViaRevertWitnessReader::from_slice(slice).map(|reader| reader.to_entity()) } fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> { UnlockCustodianViaRevertWitnessReader::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().deposit_lock_hash(self.deposit_lock_hash()) } } #[derive(Clone, Copy)] pub struct UnlockCustodianViaRevertWitnessReader<'r>(&'r [u8]); impl<'r> ::core::fmt::LowerHex for UnlockCustodianViaRevertWitnessReader<'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 UnlockCustodianViaRevertWitnessReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl<'r> ::core::fmt::Display for UnlockCustodianViaRevertWitnessReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; write!(f, "{}: {}", "deposit_lock_hash", self.deposit_lock_hash())?; write!(f, " }}") } } impl<'r> UnlockCustodianViaRevertWitnessReader<'r> { pub const TOTAL_SIZE: usize = 32; pub const FIELD_SIZES: [usize; 1] = [32]; pub const FIELD_COUNT: usize = 1; pub fn deposit_lock_hash(&self) -> Byte32Reader<'r> { Byte32Reader::new_unchecked(&self.as_slice()[0..32]) } } impl<'r> molecule::prelude::Reader<'r> for UnlockCustodianViaRevertWitnessReader<'r> { type Entity = UnlockCustodianViaRevertWitness; const NAME: &'static str = "UnlockCustodianViaRevertWitnessReader"; fn to_entity(&self) -> Self::Entity { Self::Entity::new_unchecked(self.as_slice().to_owned().into()) } fn new_unchecked(slice: &'r [u8]) -> Self { UnlockCustodianViaRevertWitnessReader(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(()) } } #[derive(Debug, Default)] pub struct UnlockCustodianViaRevertWitnessBuilder { pub(crate) deposit_lock_hash: Byte32, } impl UnlockCustodianViaRevertWitnessBuilder { pub const TOTAL_SIZE: usize = 32; pub const FIELD_SIZES: [usize; 1] = [32]; pub const FIELD_COUNT: usize = 1; pub fn deposit_lock_hash(mut self, v: Byte32) -> Self { self.deposit_lock_hash = v; self } } impl molecule::prelude::Builder for UnlockCustodianViaRevertWitnessBuilder { type Entity = UnlockCustodianViaRevertWitness; const NAME: &'static str = "UnlockCustodianViaRevertWitnessBuilder"; 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.deposit_lock_hash.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)); UnlockCustodianViaRevertWitness::new_unchecked(inner.into()) } } #[derive(Clone)] pub struct WithdrawalLockArgs(molecule::bytes::Bytes); impl ::core::fmt::LowerHex for WithdrawalLockArgs { 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 WithdrawalLockArgs { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl ::core::fmt::Display for WithdrawalLockArgs { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; write!( f, "{}: {}", "account_script_hash", self.account_script_hash() )?; write!( f, ", {}: {}", "withdrawal_block_hash", self.withdrawal_block_hash() )?; write!( f, ", {}: {}", "withdrawal_block_number", self.withdrawal_block_number() )?; write!(f, ", {}: {}", "sudt_script_hash", self.sudt_script_hash())?; write!(f, ", {}: {}", "sell_amount", self.sell_amount())?; write!(f, ", {}: {}", "sell_capacity", self.sell_capacity())?; write!(f, ", {}: {}", "owner_lock_hash", self.owner_lock_hash())?; write!(f, ", {}: {}", "payment_lock_hash", self.payment_lock_hash())?; write!(f, " }}") } } impl ::core::default::Default for WithdrawalLockArgs { fn default() -> Self { let v: Vec<u8> = vec![ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ]; WithdrawalLockArgs::new_unchecked(v.into()) } } impl WithdrawalLockArgs { pub const TOTAL_SIZE: usize = 192; pub const FIELD_SIZES: [usize; 8] = [32, 32, 8, 32, 16, 8, 32, 32]; pub const FIELD_COUNT: usize = 8; pub fn account_script_hash(&self) -> Byte32 { Byte32::new_unchecked(self.0.slice(0..32)) } pub fn withdrawal_block_hash(&self) -> Byte32 { Byte32::new_unchecked(self.0.slice(32..64)) } pub fn withdrawal_block_number(&self) -> Uint64 { Uint64::new_unchecked(self.0.slice(64..72)) } pub fn sudt_script_hash(&self) -> Byte32 { Byte32::new_unchecked(self.0.slice(72..104)) } pub fn sell_amount(&self) -> Uint128 { Uint128::new_unchecked(self.0.slice(104..120)) } pub fn sell_capacity(&self) -> Uint64 { Uint64::new_unchecked(self.0.slice(120..128)) } pub fn owner_lock_hash(&self) -> Byte32 { Byte32::new_unchecked(self.0.slice(128..160)) } pub fn payment_lock_hash(&self) -> Byte32 { Byte32::new_unchecked(self.0.slice(160..192)) } pub fn as_reader<'r>(&'r self) -> WithdrawalLockArgsReader<'r> { WithdrawalLockArgsReader::new_unchecked(self.as_slice()) } } impl molecule::prelude::Entity for WithdrawalLockArgs { type Builder = WithdrawalLockArgsBuilder; const NAME: &'static str = "WithdrawalLockArgs"; fn new_unchecked(data: molecule::bytes::Bytes) -> Self { WithdrawalLockArgs(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> { WithdrawalLockArgsReader::from_slice(slice).map(|reader| reader.to_entity()) } fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> { WithdrawalLockArgsReader::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() .account_script_hash(self.account_script_hash()) .withdrawal_block_hash(self.withdrawal_block_hash()) .withdrawal_block_number(self.withdrawal_block_number()) .sudt_script_hash(self.sudt_script_hash()) .sell_amount(self.sell_amount()) .sell_capacity(self.sell_capacity()) .owner_lock_hash(self.owner_lock_hash()) .payment_lock_hash(self.payment_lock_hash()) } } #[derive(Clone, Copy)] pub struct WithdrawalLockArgsReader<'r>(&'r [u8]); impl<'r> ::core::fmt::LowerHex for WithdrawalLockArgsReader<'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 WithdrawalLockArgsReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl<'r> ::core::fmt::Display for WithdrawalLockArgsReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; write!( f, "{}: {}", "account_script_hash", self.account_script_hash() )?; write!( f, ", {}: {}", "withdrawal_block_hash", self.withdrawal_block_hash() )?; write!( f, ", {}: {}", "withdrawal_block_number", self.withdrawal_block_number() )?; write!(f, ", {}: {}", "sudt_script_hash", self.sudt_script_hash())?; write!(f, ", {}: {}", "sell_amount", self.sell_amount())?; write!(f, ", {}: {}", "sell_capacity", self.sell_capacity())?; write!(f, ", {}: {}", "owner_lock_hash", self.owner_lock_hash())?; write!(f, ", {}: {}", "payment_lock_hash", self.payment_lock_hash())?; write!(f, " }}") } } impl<'r> WithdrawalLockArgsReader<'r> { pub const TOTAL_SIZE: usize = 192; pub const FIELD_SIZES: [usize; 8] = [32, 32, 8, 32, 16, 8, 32, 32]; pub const FIELD_COUNT: usize = 8; pub fn account_script_hash(&self) -> Byte32Reader<'r> { Byte32Reader::new_unchecked(&self.as_slice()[0..32]) } pub fn withdrawal_block_hash(&self) -> Byte32Reader<'r> { Byte32Reader::new_unchecked(&self.as_slice()[32..64]) } pub fn withdrawal_block_number(&self) -> Uint64Reader<'r> { Uint64Reader::new_unchecked(&self.as_slice()[64..72]) } pub fn sudt_script_hash(&self) -> Byte32Reader<'r> { Byte32Reader::new_unchecked(&self.as_slice()[72..104]) } pub fn sell_amount(&self) -> Uint128Reader<'r> { Uint128Reader::new_unchecked(&self.as_slice()[104..120]) } pub fn sell_capacity(&self) -> Uint64Reader<'r> { Uint64Reader::new_unchecked(&self.as_slice()[120..128]) } pub fn owner_lock_hash(&self) -> Byte32Reader<'r> { Byte32Reader::new_unchecked(&self.as_slice()[128..160]) } pub fn payment_lock_hash(&self) -> Byte32Reader<'r> { Byte32Reader::new_unchecked(&self.as_slice()[160..192]) } } impl<'r> molecule::prelude::Reader<'r> for WithdrawalLockArgsReader<'r> { type Entity = WithdrawalLockArgs; const NAME: &'static str = "WithdrawalLockArgsReader"; fn to_entity(&self) -> Self::Entity { Self::Entity::new_unchecked(self.as_slice().to_owned().into()) } fn new_unchecked(slice: &'r [u8]) -> Self { WithdrawalLockArgsReader(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(()) } } #[derive(Debug, Default)] pub struct WithdrawalLockArgsBuilder { pub(crate) account_script_hash: Byte32, pub(crate) withdrawal_block_hash: Byte32, pub(crate) withdrawal_block_number: Uint64, pub(crate) sudt_script_hash: Byte32, pub(crate) sell_amount: Uint128, pub(crate) sell_capacity: Uint64, pub(crate) owner_lock_hash: Byte32, pub(crate) payment_lock_hash: Byte32, } impl WithdrawalLockArgsBuilder { pub const TOTAL_SIZE: usize = 192; pub const FIELD_SIZES: [usize; 8] = [32, 32, 8, 32, 16, 8, 32, 32]; pub const FIELD_COUNT: usize = 8; pub fn account_script_hash(mut self, v: Byte32) -> Self { self.account_script_hash = v; self } pub fn withdrawal_block_hash(mut self, v: Byte32) -> Self { self.withdrawal_block_hash = v; self } pub fn withdrawal_block_number(mut self, v: Uint64) -> Self { self.withdrawal_block_number = v; self } pub fn sudt_script_hash(mut self, v: Byte32) -> Self { self.sudt_script_hash = v; self } pub fn sell_amount(mut self, v: Uint128) -> Self { self.sell_amount = v; self } pub fn sell_capacity(mut self, v: Uint64) -> Self { self.sell_capacity = v; self } pub fn owner_lock_hash(mut self, v: Byte32) -> Self { self.owner_lock_hash = v; self } pub fn payment_lock_hash(mut self, v: Byte32) -> Self { self.payment_lock_hash = v; self } } impl molecule::prelude::Builder for WithdrawalLockArgsBuilder { type Entity = WithdrawalLockArgs; const NAME: &'static str = "WithdrawalLockArgsBuilder"; 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.account_script_hash.as_slice())?; writer.write_all(self.withdrawal_block_hash.as_slice())?; writer.write_all(self.withdrawal_block_number.as_slice())?; writer.write_all(self.sudt_script_hash.as_slice())?; writer.write_all(self.sell_amount.as_slice())?; writer.write_all(self.sell_capacity.as_slice())?; writer.write_all(self.owner_lock_hash.as_slice())?; writer.write_all(self.payment_lock_hash.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)); WithdrawalLockArgs::new_unchecked(inner.into()) } } #[derive(Clone)] pub struct UnlockWithdrawalWitness(molecule::bytes::Bytes); impl ::core::fmt::LowerHex for UnlockWithdrawalWitness { 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 UnlockWithdrawalWitness { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl ::core::fmt::Display for UnlockWithdrawalWitness { 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 UnlockWithdrawalWitness { fn default() -> Self { let v: Vec<u8> = vec![0, 0, 0, 0, 4, 0, 0, 0]; UnlockWithdrawalWitness::new_unchecked(v.into()) } } impl UnlockWithdrawalWitness { pub const ITEMS_COUNT: usize = 3; pub fn item_id(&self) -> molecule::Number { molecule::unpack_number(self.as_slice()) } pub fn to_enum(&self) -> UnlockWithdrawalWitnessUnion { let inner = self.0.slice(molecule::NUMBER_SIZE..); match self.item_id() { 0 => UnlockWithdrawalViaFinalize::new_unchecked(inner).into(), 1 => UnlockWithdrawalViaRevert::new_unchecked(inner).into(), 2 => UnlockWithdrawalViaTrade::new_unchecked(inner).into(), _ => panic!("{}: invalid data", Self::NAME), } } pub fn as_reader<'r>(&'r self) -> UnlockWithdrawalWitnessReader<'r> { UnlockWithdrawalWitnessReader::new_unchecked(self.as_slice()) } } impl molecule::prelude::Entity for UnlockWithdrawalWitness { type Builder = UnlockWithdrawalWitnessBuilder; const NAME: &'static str = "UnlockWithdrawalWitness"; fn new_unchecked(data: molecule::bytes::Bytes) -> Self { UnlockWithdrawalWitness(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> { UnlockWithdrawalWitnessReader::from_slice(slice).map(|reader| reader.to_entity()) } fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> { UnlockWithdrawalWitnessReader::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 UnlockWithdrawalWitnessReader<'r>(&'r [u8]); impl<'r> ::core::fmt::LowerHex for UnlockWithdrawalWitnessReader<'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 UnlockWithdrawalWitnessReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl<'r> ::core::fmt::Display for UnlockWithdrawalWitnessReader<'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> UnlockWithdrawalWitnessReader<'r> { pub const ITEMS_COUNT: usize = 3; pub fn item_id(&self) -> molecule::Number { molecule::unpack_number(self.as_slice()) } pub fn to_enum(&self) -> UnlockWithdrawalWitnessUnionReader<'r> { let inner = &self.as_slice()[molecule::NUMBER_SIZE..]; match self.item_id() { 0 => UnlockWithdrawalViaFinalizeReader::new_unchecked(inner).into(), 1 => UnlockWithdrawalViaRevertReader::new_unchecked(inner).into(), 2 => UnlockWithdrawalViaTradeReader::new_unchecked(inner).into(), _ => panic!("{}: invalid data", Self::NAME), } } } impl<'r> molecule::prelude::Reader<'r> for UnlockWithdrawalWitnessReader<'r> { type Entity = UnlockWithdrawalWitness; const NAME: &'static str = "UnlockWithdrawalWitnessReader"; fn to_entity(&self) -> Self::Entity { Self::Entity::new_unchecked(self.as_slice().to_owned().into()) } fn new_unchecked(slice: &'r [u8]) -> Self { UnlockWithdrawalWitnessReader(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 => UnlockWithdrawalViaFinalizeReader::verify(inner_slice, compatible), 1 => UnlockWithdrawalViaRevertReader::verify(inner_slice, compatible), 2 => UnlockWithdrawalViaTradeReader::verify(inner_slice, compatible), _ => ve!(Self, UnknownItem, Self::ITEMS_COUNT, item_id), }?; Ok(()) } } #[derive(Debug, Default)] pub struct UnlockWithdrawalWitnessBuilder(pub(crate) UnlockWithdrawalWitnessUnion); impl UnlockWithdrawalWitnessBuilder { pub const ITEMS_COUNT: usize = 3; pub fn set<I>(mut self, v: I) -> Self where I: ::core::convert::Into<UnlockWithdrawalWitnessUnion>, { self.0 = v.into(); self } } impl molecule::prelude::Builder for UnlockWithdrawalWitnessBuilder { type Entity = UnlockWithdrawalWitness; const NAME: &'static str = "UnlockWithdrawalWitnessBuilder"; 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)); UnlockWithdrawalWitness::new_unchecked(inner.into()) } } #[derive(Debug, Clone)] pub enum UnlockWithdrawalWitnessUnion { UnlockWithdrawalViaFinalize(UnlockWithdrawalViaFinalize), UnlockWithdrawalViaRevert(UnlockWithdrawalViaRevert), UnlockWithdrawalViaTrade(UnlockWithdrawalViaTrade), } #[derive(Debug, Clone, Copy)] pub enum UnlockWithdrawalWitnessUnionReader<'r> { UnlockWithdrawalViaFinalize(UnlockWithdrawalViaFinalizeReader<'r>), UnlockWithdrawalViaRevert(UnlockWithdrawalViaRevertReader<'r>), UnlockWithdrawalViaTrade(UnlockWithdrawalViaTradeReader<'r>), } impl ::core::default::Default for UnlockWithdrawalWitnessUnion { fn default() -> Self { UnlockWithdrawalWitnessUnion::UnlockWithdrawalViaFinalize( ::core::default::Default::default(), ) } } impl ::core::fmt::Display for UnlockWithdrawalWitnessUnion { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { match self { UnlockWithdrawalWitnessUnion::UnlockWithdrawalViaFinalize(ref item) => { write!( f, "{}::{}({})", Self::NAME, UnlockWithdrawalViaFinalize::NAME, item ) } UnlockWithdrawalWitnessUnion::UnlockWithdrawalViaRevert(ref item) => { write!( f, "{}::{}({})", Self::NAME, UnlockWithdrawalViaRevert::NAME, item ) } UnlockWithdrawalWitnessUnion::UnlockWithdrawalViaTrade(ref item) => { write!( f, "{}::{}({})", Self::NAME, UnlockWithdrawalViaTrade::NAME, item ) } } } } impl<'r> ::core::fmt::Display for UnlockWithdrawalWitnessUnionReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { match self { UnlockWithdrawalWitnessUnionReader::UnlockWithdrawalViaFinalize(ref item) => { write!( f, "{}::{}({})", Self::NAME, UnlockWithdrawalViaFinalize::NAME, item ) } UnlockWithdrawalWitnessUnionReader::UnlockWithdrawalViaRevert(ref item) => { write!( f, "{}::{}({})", Self::NAME, UnlockWithdrawalViaRevert::NAME, item ) } UnlockWithdrawalWitnessUnionReader::UnlockWithdrawalViaTrade(ref item) => { write!( f, "{}::{}({})", Self::NAME, UnlockWithdrawalViaTrade::NAME, item ) } } } } impl UnlockWithdrawalWitnessUnion { pub(crate) fn display_inner(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { match self { UnlockWithdrawalWitnessUnion::UnlockWithdrawalViaFinalize(ref item) => { write!(f, "{}", item) } UnlockWithdrawalWitnessUnion::UnlockWithdrawalViaRevert(ref item) => { write!(f, "{}", item) } UnlockWithdrawalWitnessUnion::UnlockWithdrawalViaTrade(ref item) => { write!(f, "{}", item) } } } } impl<'r> UnlockWithdrawalWitnessUnionReader<'r> { pub(crate) fn display_inner(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { match self { UnlockWithdrawalWitnessUnionReader::UnlockWithdrawalViaFinalize(ref item) => { write!(f, "{}", item) } UnlockWithdrawalWitnessUnionReader::UnlockWithdrawalViaRevert(ref item) => { write!(f, "{}", item) } UnlockWithdrawalWitnessUnionReader::UnlockWithdrawalViaTrade(ref item) => { write!(f, "{}", item) } } } } impl ::core::convert::From<UnlockWithdrawalViaFinalize> for UnlockWithdrawalWitnessUnion { fn from(item: UnlockWithdrawalViaFinalize) -> Self { UnlockWithdrawalWitnessUnion::UnlockWithdrawalViaFinalize(item) } } impl ::core::convert::From<UnlockWithdrawalViaRevert> for UnlockWithdrawalWitnessUnion { fn from(item: UnlockWithdrawalViaRevert) -> Self { UnlockWithdrawalWitnessUnion::UnlockWithdrawalViaRevert(item) } } impl ::core::convert::From<UnlockWithdrawalViaTrade> for UnlockWithdrawalWitnessUnion { fn from(item: UnlockWithdrawalViaTrade) -> Self { UnlockWithdrawalWitnessUnion::UnlockWithdrawalViaTrade(item) } } impl<'r> ::core::convert::From<UnlockWithdrawalViaFinalizeReader<'r>> for UnlockWithdrawalWitnessUnionReader<'r> { fn from(item: UnlockWithdrawalViaFinalizeReader<'r>) -> Self { UnlockWithdrawalWitnessUnionReader::UnlockWithdrawalViaFinalize(item) } } impl<'r> ::core::convert::From<UnlockWithdrawalViaRevertReader<'r>> for UnlockWithdrawalWitnessUnionReader<'r> { fn from(item: UnlockWithdrawalViaRevertReader<'r>) -> Self { UnlockWithdrawalWitnessUnionReader::UnlockWithdrawalViaRevert(item) } } impl<'r> ::core::convert::From<UnlockWithdrawalViaTradeReader<'r>> for UnlockWithdrawalWitnessUnionReader<'r> { fn from(item: UnlockWithdrawalViaTradeReader<'r>) -> Self { UnlockWithdrawalWitnessUnionReader::UnlockWithdrawalViaTrade(item) } } impl UnlockWithdrawalWitnessUnion { pub const NAME: &'static str = "UnlockWithdrawalWitnessUnion"; pub fn as_bytes(&self) -> molecule::bytes::Bytes { match self { UnlockWithdrawalWitnessUnion::UnlockWithdrawalViaFinalize(item) => item.as_bytes(), UnlockWithdrawalWitnessUnion::UnlockWithdrawalViaRevert(item) => item.as_bytes(), UnlockWithdrawalWitnessUnion::UnlockWithdrawalViaTrade(item) => item.as_bytes(), } } pub fn as_slice(&self) -> &[u8] { match self { UnlockWithdrawalWitnessUnion::UnlockWithdrawalViaFinalize(item) => item.as_slice(), UnlockWithdrawalWitnessUnion::UnlockWithdrawalViaRevert(item) => item.as_slice(), UnlockWithdrawalWitnessUnion::UnlockWithdrawalViaTrade(item) => item.as_slice(), } } pub fn item_id(&self) -> molecule::Number { match self { UnlockWithdrawalWitnessUnion::UnlockWithdrawalViaFinalize(_) => 0, UnlockWithdrawalWitnessUnion::UnlockWithdrawalViaRevert(_) => 1, UnlockWithdrawalWitnessUnion::UnlockWithdrawalViaTrade(_) => 2, } } pub fn item_name(&self) -> &str { match self { UnlockWithdrawalWitnessUnion::UnlockWithdrawalViaFinalize(_) => { "UnlockWithdrawalViaFinalize" } UnlockWithdrawalWitnessUnion::UnlockWithdrawalViaRevert(_) => { "UnlockWithdrawalViaRevert" } UnlockWithdrawalWitnessUnion::UnlockWithdrawalViaTrade(_) => "UnlockWithdrawalViaTrade", } } pub fn as_reader<'r>(&'r self) -> UnlockWithdrawalWitnessUnionReader<'r> { match self { UnlockWithdrawalWitnessUnion::UnlockWithdrawalViaFinalize(item) => { item.as_reader().into() } UnlockWithdrawalWitnessUnion::UnlockWithdrawalViaRevert(item) => { item.as_reader().into() } UnlockWithdrawalWitnessUnion::UnlockWithdrawalViaTrade(item) => item.as_reader().into(), } } } impl<'r> UnlockWithdrawalWitnessUnionReader<'r> { pub const NAME: &'r str = "UnlockWithdrawalWitnessUnionReader"; pub fn as_slice(&self) -> &'r [u8] { match self { UnlockWithdrawalWitnessUnionReader::UnlockWithdrawalViaFinalize(item) => { item.as_slice() } UnlockWithdrawalWitnessUnionReader::UnlockWithdrawalViaRevert(item) => item.as_slice(), UnlockWithdrawalWitnessUnionReader::UnlockWithdrawalViaTrade(item) => item.as_slice(), } } pub fn item_id(&self) -> molecule::Number { match self { UnlockWithdrawalWitnessUnionReader::UnlockWithdrawalViaFinalize(_) => 0, UnlockWithdrawalWitnessUnionReader::UnlockWithdrawalViaRevert(_) => 1, UnlockWithdrawalWitnessUnionReader::UnlockWithdrawalViaTrade(_) => 2, } } pub fn item_name(&self) -> &str { match self { UnlockWithdrawalWitnessUnionReader::UnlockWithdrawalViaFinalize(_) => { "UnlockWithdrawalViaFinalize" } UnlockWithdrawalWitnessUnionReader::UnlockWithdrawalViaRevert(_) => { "UnlockWithdrawalViaRevert" } UnlockWithdrawalWitnessUnionReader::UnlockWithdrawalViaTrade(_) => { "UnlockWithdrawalViaTrade" } } } } #[derive(Clone)] pub struct UnlockWithdrawalViaFinalize(molecule::bytes::Bytes); impl ::core::fmt::LowerHex for UnlockWithdrawalViaFinalize { 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 UnlockWithdrawalViaFinalize { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl ::core::fmt::Display for UnlockWithdrawalViaFinalize { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; let extra_count = self.count_extra_fields(); if extra_count != 0 { write!(f, ".. ({} fields)", extra_count)?; } write!(f, " }}") } } impl ::core::default::Default for UnlockWithdrawalViaFinalize { fn default() -> Self { let v: Vec<u8> = vec![4, 0, 0, 0]; UnlockWithdrawalViaFinalize::new_unchecked(v.into()) } } impl UnlockWithdrawalViaFinalize { pub const FIELD_COUNT: usize = 0; 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 as_reader<'r>(&'r self) -> UnlockWithdrawalViaFinalizeReader<'r> { UnlockWithdrawalViaFinalizeReader::new_unchecked(self.as_slice()) } } impl molecule::prelude::Entity for UnlockWithdrawalViaFinalize { type Builder = UnlockWithdrawalViaFinalizeBuilder; const NAME: &'static str = "UnlockWithdrawalViaFinalize"; fn new_unchecked(data: molecule::bytes::Bytes) -> Self { UnlockWithdrawalViaFinalize(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> { UnlockWithdrawalViaFinalizeReader::from_slice(slice).map(|reader| reader.to_entity()) } fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> { UnlockWithdrawalViaFinalizeReader::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() } } #[derive(Clone, Copy)] pub struct UnlockWithdrawalViaFinalizeReader<'r>(&'r [u8]); impl<'r> ::core::fmt::LowerHex for UnlockWithdrawalViaFinalizeReader<'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 UnlockWithdrawalViaFinalizeReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl<'r> ::core::fmt::Display for UnlockWithdrawalViaFinalizeReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; let extra_count = self.count_extra_fields(); if extra_count != 0 { write!(f, ".. ({} fields)", extra_count)?; } write!(f, " }}") } } impl<'r> UnlockWithdrawalViaFinalizeReader<'r> { pub const FIELD_COUNT: usize = 0; 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() } } impl<'r> molecule::prelude::Reader<'r> for UnlockWithdrawalViaFinalizeReader<'r> { type Entity = UnlockWithdrawalViaFinalize; const NAME: &'static str = "UnlockWithdrawalViaFinalizeReader"; fn to_entity(&self) -> Self::Entity { Self::Entity::new_unchecked(self.as_slice().to_owned().into()) } fn new_unchecked(slice: &'r [u8]) -> Self { UnlockWithdrawalViaFinalizeReader(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 && !compatible { return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, !0); } Ok(()) } } #[derive(Debug, Default)] pub struct UnlockWithdrawalViaFinalizeBuilder {} impl UnlockWithdrawalViaFinalizeBuilder { pub const FIELD_COUNT: usize = 0; } impl molecule::prelude::Builder for UnlockWithdrawalViaFinalizeBuilder { type Entity = UnlockWithdrawalViaFinalize; const NAME: &'static str = "UnlockWithdrawalViaFinalizeBuilder"; fn expected_length(&self) -> usize { molecule::NUMBER_SIZE } fn write<W: molecule::io::Write>(&self, writer: &mut W) -> molecule::io::Result<()> { writer.write_all(&molecule::pack_number( molecule::NUMBER_SIZE as molecule::Number, ))?; 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)); UnlockWithdrawalViaFinalize::new_unchecked(inner.into()) } } #[derive(Clone)] pub struct UnlockWithdrawalViaRevert(molecule::bytes::Bytes); impl ::core::fmt::LowerHex for UnlockWithdrawalViaRevert { 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 UnlockWithdrawalViaRevert { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl ::core::fmt::Display for UnlockWithdrawalViaRevert { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; write!( f, "{}: {}", "custodian_lock_hash", self.custodian_lock_hash() )?; write!(f, " }}") } } impl ::core::default::Default for UnlockWithdrawalViaRevert { fn default() -> Self { let v: Vec<u8> = vec![ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ]; UnlockWithdrawalViaRevert::new_unchecked(v.into()) } } impl UnlockWithdrawalViaRevert { pub const TOTAL_SIZE: usize = 32; pub const FIELD_SIZES: [usize; 1] = [32]; pub const FIELD_COUNT: usize = 1; pub fn custodian_lock_hash(&self) -> Byte32 { Byte32::new_unchecked(self.0.slice(0..32)) } pub fn as_reader<'r>(&'r self) -> UnlockWithdrawalViaRevertReader<'r> { UnlockWithdrawalViaRevertReader::new_unchecked(self.as_slice()) } } impl molecule::prelude::Entity for UnlockWithdrawalViaRevert { type Builder = UnlockWithdrawalViaRevertBuilder; const NAME: &'static str = "UnlockWithdrawalViaRevert"; fn new_unchecked(data: molecule::bytes::Bytes) -> Self { UnlockWithdrawalViaRevert(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> { UnlockWithdrawalViaRevertReader::from_slice(slice).map(|reader| reader.to_entity()) } fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> { UnlockWithdrawalViaRevertReader::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().custodian_lock_hash(self.custodian_lock_hash()) } } #[derive(Clone, Copy)] pub struct UnlockWithdrawalViaRevertReader<'r>(&'r [u8]); impl<'r> ::core::fmt::LowerHex for UnlockWithdrawalViaRevertReader<'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 UnlockWithdrawalViaRevertReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl<'r> ::core::fmt::Display for UnlockWithdrawalViaRevertReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; write!( f, "{}: {}", "custodian_lock_hash", self.custodian_lock_hash() )?; write!(f, " }}") } } impl<'r> UnlockWithdrawalViaRevertReader<'r> { pub const TOTAL_SIZE: usize = 32; pub const FIELD_SIZES: [usize; 1] = [32]; pub const FIELD_COUNT: usize = 1; pub fn custodian_lock_hash(&self) -> Byte32Reader<'r> { Byte32Reader::new_unchecked(&self.as_slice()[0..32]) } } impl<'r> molecule::prelude::Reader<'r> for UnlockWithdrawalViaRevertReader<'r> { type Entity = UnlockWithdrawalViaRevert; const NAME: &'static str = "UnlockWithdrawalViaRevertReader"; fn to_entity(&self) -> Self::Entity { Self::Entity::new_unchecked(self.as_slice().to_owned().into()) } fn new_unchecked(slice: &'r [u8]) -> Self { UnlockWithdrawalViaRevertReader(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(()) } } #[derive(Debug, Default)] pub struct UnlockWithdrawalViaRevertBuilder { pub(crate) custodian_lock_hash: Byte32, } impl UnlockWithdrawalViaRevertBuilder { pub const TOTAL_SIZE: usize = 32; pub const FIELD_SIZES: [usize; 1] = [32]; pub const FIELD_COUNT: usize = 1; pub fn custodian_lock_hash(mut self, v: Byte32) -> Self { self.custodian_lock_hash = v; self } } impl molecule::prelude::Builder for UnlockWithdrawalViaRevertBuilder { type Entity = UnlockWithdrawalViaRevert; const NAME: &'static str = "UnlockWithdrawalViaRevertBuilder"; 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.custodian_lock_hash.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)); UnlockWithdrawalViaRevert::new_unchecked(inner.into()) } } #[derive(Clone)] pub struct UnlockWithdrawalViaTrade(molecule::bytes::Bytes); impl ::core::fmt::LowerHex for UnlockWithdrawalViaTrade { 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 UnlockWithdrawalViaTrade { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl ::core::fmt::Display for UnlockWithdrawalViaTrade { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; write!(f, "{}: {}", "owner_lock", self.owner_lock())?; let extra_count = self.count_extra_fields(); if extra_count != 0 { write!(f, ", .. ({} fields)", extra_count)?; } write!(f, " }}") } } impl ::core::default::Default for UnlockWithdrawalViaTrade { fn default() -> Self { let v: Vec<u8> = vec![ 61, 0, 0, 0, 8, 0, 0, 0, 53, 0, 0, 0, 16, 0, 0, 0, 48, 0, 0, 0, 49, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ]; UnlockWithdrawalViaTrade::new_unchecked(v.into()) } } impl UnlockWithdrawalViaTrade { 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 owner_lock(&self) -> Script { 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; Script::new_unchecked(self.0.slice(start..end)) } else { Script::new_unchecked(self.0.slice(start..)) } } pub fn as_reader<'r>(&'r self) -> UnlockWithdrawalViaTradeReader<'r> { UnlockWithdrawalViaTradeReader::new_unchecked(self.as_slice()) } } impl molecule::prelude::Entity for UnlockWithdrawalViaTrade { type Builder = UnlockWithdrawalViaTradeBuilder; const NAME: &'static str = "UnlockWithdrawalViaTrade"; fn new_unchecked(data: molecule::bytes::Bytes) -> Self { UnlockWithdrawalViaTrade(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> { UnlockWithdrawalViaTradeReader::from_slice(slice).map(|reader| reader.to_entity()) } fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> { UnlockWithdrawalViaTradeReader::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().owner_lock(self.owner_lock()) } } #[derive(Clone, Copy)] pub struct UnlockWithdrawalViaTradeReader<'r>(&'r [u8]); impl<'r> ::core::fmt::LowerHex for UnlockWithdrawalViaTradeReader<'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 UnlockWithdrawalViaTradeReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl<'r> ::core::fmt::Display for UnlockWithdrawalViaTradeReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; write!(f, "{}: {}", "owner_lock", self.owner_lock())?; let extra_count = self.count_extra_fields(); if extra_count != 0 { write!(f, ", .. ({} fields)", extra_count)?; } write!(f, " }}") } } impl<'r> UnlockWithdrawalViaTradeReader<'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 owner_lock(&self) -> ScriptReader<'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; ScriptReader::new_unchecked(&self.as_slice()[start..end]) } else { ScriptReader::new_unchecked(&self.as_slice()[start..]) } } } impl<'r> molecule::prelude::Reader<'r> for UnlockWithdrawalViaTradeReader<'r> { type Entity = UnlockWithdrawalViaTrade; const NAME: &'static str = "UnlockWithdrawalViaTradeReader"; fn to_entity(&self) -> Self::Entity { Self::Entity::new_unchecked(self.as_slice().to_owned().into()) } fn new_unchecked(slice: &'r [u8]) -> Self { UnlockWithdrawalViaTradeReader(slice) } fn as_slice(&self) -> &'r [u8] { self.0 } fn verify(slice: &[u8], compatible: bool) -> molecule::error::VerificationResult<()> { use molecule::verification_error as ve; let slice_len = slice.len(); if slice_len < molecule::NUMBER_SIZE { return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE, slice_len); } let total_size = molecule::unpack_number(slice) as usize; if slice_len != total_size { return ve!(Self, TotalSizeNotMatch, total_size, slice_len); } if slice_len == molecule::NUMBER_SIZE && Self::FIELD_COUNT == 0 { return Ok(()); } if slice_len < molecule::NUMBER_SIZE * 2 { return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE * 2, slice_len); } let offset_first = molecule::unpack_number(&slice[molecule::NUMBER_SIZE..]) as usize; if offset_first % molecule::NUMBER_SIZE != 0 || offset_first < molecule::NUMBER_SIZE * 2 { return ve!(Self, OffsetsNotMatch); } if slice_len < offset_first { return ve!(Self, HeaderIsBroken, offset_first, slice_len); } let field_count = offset_first / molecule::NUMBER_SIZE - 1; if field_count < Self::FIELD_COUNT { return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, field_count); } else if !compatible && field_count > Self::FIELD_COUNT { return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, field_count); }; let mut offsets: Vec<usize> = slice[molecule::NUMBER_SIZE..offset_first] .chunks_exact(molecule::NUMBER_SIZE) .map(|x| molecule::unpack_number(x) as usize) .collect(); offsets.push(total_size); if offsets.windows(2).any(|i| i[0] > i[1]) { return ve!(Self, OffsetsNotMatch); } ScriptReader::verify(&slice[offsets[0]..offsets[1]], compatible)?; Ok(()) } } #[derive(Debug, Default)] pub struct UnlockWithdrawalViaTradeBuilder { pub(crate) owner_lock: Script, } impl UnlockWithdrawalViaTradeBuilder { pub const FIELD_COUNT: usize = 1; pub fn owner_lock(mut self, v: Script) -> Self { self.owner_lock = v; self } } impl molecule::prelude::Builder for UnlockWithdrawalViaTradeBuilder { type Entity = UnlockWithdrawalViaTrade; const NAME: &'static str = "UnlockWithdrawalViaTradeBuilder"; fn expected_length(&self) -> usize { molecule::NUMBER_SIZE * (Self::FIELD_COUNT + 1) + self.owner_lock.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.owner_lock.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.owner_lock.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)); UnlockWithdrawalViaTrade::new_unchecked(inner.into()) } } #[derive(Clone)] pub struct StakeLockArgs(molecule::bytes::Bytes); impl ::core::fmt::LowerHex for StakeLockArgs { 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 StakeLockArgs { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl ::core::fmt::Display for StakeLockArgs { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; write!(f, "{}: {}", "owner_lock_hash", self.owner_lock_hash())?; write!( f, ", {}: {}", "stake_block_number", self.stake_block_number() )?; write!(f, " }}") } } impl ::core::default::Default for StakeLockArgs { fn default() -> Self { let v: Vec<u8> = vec![ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ]; StakeLockArgs::new_unchecked(v.into()) } } impl StakeLockArgs { pub const TOTAL_SIZE: usize = 40; pub const FIELD_SIZES: [usize; 2] = [32, 8]; pub const FIELD_COUNT: usize = 2; pub fn owner_lock_hash(&self) -> Byte32 { Byte32::new_unchecked(self.0.slice(0..32)) } pub fn stake_block_number(&self) -> Uint64 { Uint64::new_unchecked(self.0.slice(32..40)) } pub fn as_reader<'r>(&'r self) -> StakeLockArgsReader<'r> { StakeLockArgsReader::new_unchecked(self.as_slice()) } } impl molecule::prelude::Entity for StakeLockArgs { type Builder = StakeLockArgsBuilder; const NAME: &'static str = "StakeLockArgs"; fn new_unchecked(data: molecule::bytes::Bytes) -> Self { StakeLockArgs(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> { StakeLockArgsReader::from_slice(slice).map(|reader| reader.to_entity()) } fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> { StakeLockArgsReader::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() .owner_lock_hash(self.owner_lock_hash()) .stake_block_number(self.stake_block_number()) } } #[derive(Clone, Copy)] pub struct StakeLockArgsReader<'r>(&'r [u8]); impl<'r> ::core::fmt::LowerHex for StakeLockArgsReader<'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 StakeLockArgsReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl<'r> ::core::fmt::Display for StakeLockArgsReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; write!(f, "{}: {}", "owner_lock_hash", self.owner_lock_hash())?; write!( f, ", {}: {}", "stake_block_number", self.stake_block_number() )?; write!(f, " }}") } } impl<'r> StakeLockArgsReader<'r> { pub const TOTAL_SIZE: usize = 40; pub const FIELD_SIZES: [usize; 2] = [32, 8]; pub const FIELD_COUNT: usize = 2; pub fn owner_lock_hash(&self) -> Byte32Reader<'r> { Byte32Reader::new_unchecked(&self.as_slice()[0..32]) } pub fn stake_block_number(&self) -> Uint64Reader<'r> { Uint64Reader::new_unchecked(&self.as_slice()[32..40]) } } impl<'r> molecule::prelude::Reader<'r> for StakeLockArgsReader<'r> { type Entity = StakeLockArgs; const NAME: &'static str = "StakeLockArgsReader"; fn to_entity(&self) -> Self::Entity { Self::Entity::new_unchecked(self.as_slice().to_owned().into()) } fn new_unchecked(slice: &'r [u8]) -> Self { StakeLockArgsReader(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(()) } } #[derive(Debug, Default)] pub struct StakeLockArgsBuilder { pub(crate) owner_lock_hash: Byte32, pub(crate) stake_block_number: Uint64, } impl StakeLockArgsBuilder { pub const TOTAL_SIZE: usize = 40; pub const FIELD_SIZES: [usize; 2] = [32, 8]; pub const FIELD_COUNT: usize = 2; pub fn owner_lock_hash(mut self, v: Byte32) -> Self { self.owner_lock_hash = v; self } pub fn stake_block_number(mut self, v: Uint64) -> Self { self.stake_block_number = v; self } } impl molecule::prelude::Builder for StakeLockArgsBuilder { type Entity = StakeLockArgs; const NAME: &'static str = "StakeLockArgsBuilder"; 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.owner_lock_hash.as_slice())?; writer.write_all(self.stake_block_number.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)); StakeLockArgs::new_unchecked(inner.into()) } } #[derive(Clone)] pub struct MetaContractArgs(molecule::bytes::Bytes); impl ::core::fmt::LowerHex for MetaContractArgs { 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 MetaContractArgs { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl ::core::fmt::Display for MetaContractArgs { 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 MetaContractArgs { fn default() -> Self { let v: Vec<u8> = vec![ 0, 0, 0, 0, 85, 0, 0, 0, 12, 0, 0, 0, 65, 0, 0, 0, 53, 0, 0, 0, 16, 0, 0, 0, 48, 0, 0, 0, 49, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ]; MetaContractArgs::new_unchecked(v.into()) } } impl MetaContractArgs { pub const ITEMS_COUNT: usize = 1; pub fn item_id(&self) -> molecule::Number { molecule::unpack_number(self.as_slice()) } pub fn to_enum(&self) -> MetaContractArgsUnion { let inner = self.0.slice(molecule::NUMBER_SIZE..); match self.item_id() { 0 => CreateAccount::new_unchecked(inner).into(), _ => panic!("{}: invalid data", Self::NAME), } } pub fn as_reader<'r>(&'r self) -> MetaContractArgsReader<'r> { MetaContractArgsReader::new_unchecked(self.as_slice()) } } impl molecule::prelude::Entity for MetaContractArgs { type Builder = MetaContractArgsBuilder; const NAME: &'static str = "MetaContractArgs"; fn new_unchecked(data: molecule::bytes::Bytes) -> Self { MetaContractArgs(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> { MetaContractArgsReader::from_slice(slice).map(|reader| reader.to_entity()) } fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> { MetaContractArgsReader::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 MetaContractArgsReader<'r>(&'r [u8]); impl<'r> ::core::fmt::LowerHex for MetaContractArgsReader<'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 MetaContractArgsReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl<'r> ::core::fmt::Display for MetaContractArgsReader<'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> MetaContractArgsReader<'r> { pub const ITEMS_COUNT: usize = 1; pub fn item_id(&self) -> molecule::Number { molecule::unpack_number(self.as_slice()) } pub fn to_enum(&self) -> MetaContractArgsUnionReader<'r> { let inner = &self.as_slice()[molecule::NUMBER_SIZE..]; match self.item_id() { 0 => CreateAccountReader::new_unchecked(inner).into(), _ => panic!("{}: invalid data", Self::NAME), } } } impl<'r> molecule::prelude::Reader<'r> for MetaContractArgsReader<'r> { type Entity = MetaContractArgs; const NAME: &'static str = "MetaContractArgsReader"; fn to_entity(&self) -> Self::Entity { Self::Entity::new_unchecked(self.as_slice().to_owned().into()) } fn new_unchecked(slice: &'r [u8]) -> Self { MetaContractArgsReader(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 => CreateAccountReader::verify(inner_slice, compatible), _ => ve!(Self, UnknownItem, Self::ITEMS_COUNT, item_id), }?; Ok(()) } } #[derive(Debug, Default)] pub struct MetaContractArgsBuilder(pub(crate) MetaContractArgsUnion); impl MetaContractArgsBuilder { pub const ITEMS_COUNT: usize = 1; pub fn set<I>(mut self, v: I) -> Self where I: ::core::convert::Into<MetaContractArgsUnion>, { self.0 = v.into(); self } } impl molecule::prelude::Builder for MetaContractArgsBuilder { type Entity = MetaContractArgs; const NAME: &'static str = "MetaContractArgsBuilder"; 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)); MetaContractArgs::new_unchecked(inner.into()) } } #[derive(Debug, Clone)] pub enum MetaContractArgsUnion { CreateAccount(CreateAccount), } #[derive(Debug, Clone, Copy)] pub enum MetaContractArgsUnionReader<'r> { CreateAccount(CreateAccountReader<'r>), } impl ::core::default::Default for MetaContractArgsUnion { fn default() -> Self { MetaContractArgsUnion::CreateAccount(::core::default::Default::default()) } } impl ::core::fmt::Display for MetaContractArgsUnion { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { match self { MetaContractArgsUnion::CreateAccount(ref item) => { write!(f, "{}::{}({})", Self::NAME, CreateAccount::NAME, item) } } } } impl<'r> ::core::fmt::Display for MetaContractArgsUnionReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { match self { MetaContractArgsUnionReader::CreateAccount(ref item) => { write!(f, "{}::{}({})", Self::NAME, CreateAccount::NAME, item) } } } } impl MetaContractArgsUnion { pub(crate) fn display_inner(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { match self { MetaContractArgsUnion::CreateAccount(ref item) => write!(f, "{}", item), } } } impl<'r> MetaContractArgsUnionReader<'r> { pub(crate) fn display_inner(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { match self { MetaContractArgsUnionReader::CreateAccount(ref item) => write!(f, "{}", item), } } } impl ::core::convert::From<CreateAccount> for MetaContractArgsUnion { fn from(item: CreateAccount) -> Self { MetaContractArgsUnion::CreateAccount(item) } } impl<'r> ::core::convert::From<CreateAccountReader<'r>> for MetaContractArgsUnionReader<'r> { fn from(item: CreateAccountReader<'r>) -> Self { MetaContractArgsUnionReader::CreateAccount(item) } } impl MetaContractArgsUnion { pub const NAME: &'static str = "MetaContractArgsUnion"; pub fn as_bytes(&self) -> molecule::bytes::Bytes { match self { MetaContractArgsUnion::CreateAccount(item) => item.as_bytes(), } } pub fn as_slice(&self) -> &[u8] { match self { MetaContractArgsUnion::CreateAccount(item) => item.as_slice(), } } pub fn item_id(&self) -> molecule::Number { match self { MetaContractArgsUnion::CreateAccount(_) => 0, } } pub fn item_name(&self) -> &str { match self { MetaContractArgsUnion::CreateAccount(_) => "CreateAccount", } } pub fn as_reader<'r>(&'r self) -> MetaContractArgsUnionReader<'r> { match self { MetaContractArgsUnion::CreateAccount(item) => item.as_reader().into(), } } } impl<'r> MetaContractArgsUnionReader<'r> { pub const NAME: &'r str = "MetaContractArgsUnionReader"; pub fn as_slice(&self) -> &'r [u8] { match self { MetaContractArgsUnionReader::CreateAccount(item) => item.as_slice(), } } pub fn item_id(&self) -> molecule::Number { match self { MetaContractArgsUnionReader::CreateAccount(_) => 0, } } pub fn item_name(&self) -> &str { match self { MetaContractArgsUnionReader::CreateAccount(_) => "CreateAccount", } } } #[derive(Clone)] pub struct Fee(molecule::bytes::Bytes); impl ::core::fmt::LowerHex for Fee { 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 Fee { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl ::core::fmt::Display for Fee { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; write!(f, "{}: {}", "sudt_id", self.sudt_id())?; write!(f, ", {}: {}", "amount", self.amount())?; write!(f, " }}") } } impl ::core::default::Default for Fee { fn default() -> Self { let v: Vec<u8> = vec![0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; Fee::new_unchecked(v.into()) } } impl Fee { pub const TOTAL_SIZE: usize = 20; pub const FIELD_SIZES: [usize; 2] = [4, 16]; pub const FIELD_COUNT: usize = 2; pub fn sudt_id(&self) -> Uint32 { Uint32::new_unchecked(self.0.slice(0..4)) } pub fn amount(&self) -> Uint128 { Uint128::new_unchecked(self.0.slice(4..20)) } pub fn as_reader<'r>(&'r self) -> FeeReader<'r> { FeeReader::new_unchecked(self.as_slice()) } } impl molecule::prelude::Entity for Fee { type Builder = FeeBuilder; const NAME: &'static str = "Fee"; fn new_unchecked(data: molecule::bytes::Bytes) -> Self { Fee(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> { FeeReader::from_slice(slice).map(|reader| reader.to_entity()) } fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> { FeeReader::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() .sudt_id(self.sudt_id()) .amount(self.amount()) } } #[derive(Clone, Copy)] pub struct FeeReader<'r>(&'r [u8]); impl<'r> ::core::fmt::LowerHex for FeeReader<'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 FeeReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl<'r> ::core::fmt::Display for FeeReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; write!(f, "{}: {}", "sudt_id", self.sudt_id())?; write!(f, ", {}: {}", "amount", self.amount())?; write!(f, " }}") } } impl<'r> FeeReader<'r> { pub const TOTAL_SIZE: usize = 20; pub const FIELD_SIZES: [usize; 2] = [4, 16]; pub const FIELD_COUNT: usize = 2; pub fn sudt_id(&self) -> Uint32Reader<'r> { Uint32Reader::new_unchecked(&self.as_slice()[0..4]) } pub fn amount(&self) -> Uint128Reader<'r> { Uint128Reader::new_unchecked(&self.as_slice()[4..20]) } } impl<'r> molecule::prelude::Reader<'r> for FeeReader<'r> { type Entity = Fee; const NAME: &'static str = "FeeReader"; fn to_entity(&self) -> Self::Entity { Self::Entity::new_unchecked(self.as_slice().to_owned().into()) } fn new_unchecked(slice: &'r [u8]) -> Self { FeeReader(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(()) } } #[derive(Debug, Default)] pub struct FeeBuilder { pub(crate) sudt_id: Uint32, pub(crate) amount: Uint128, } impl FeeBuilder { pub const TOTAL_SIZE: usize = 20; pub const FIELD_SIZES: [usize; 2] = [4, 16]; pub const FIELD_COUNT: usize = 2; pub fn sudt_id(mut self, v: Uint32) -> Self { self.sudt_id = v; self } pub fn amount(mut self, v: Uint128) -> Self { self.amount = v; self } } impl molecule::prelude::Builder for FeeBuilder { type Entity = Fee; const NAME: &'static str = "FeeBuilder"; 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.sudt_id.as_slice())?; writer.write_all(self.amount.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)); Fee::new_unchecked(inner.into()) } } #[derive(Clone)] pub struct CreateAccount(molecule::bytes::Bytes); impl ::core::fmt::LowerHex for CreateAccount { 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 CreateAccount { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl ::core::fmt::Display for CreateAccount { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; write!(f, "{}: {}", "script", self.script())?; write!(f, ", {}: {}", "fee", self.fee())?; let extra_count = self.count_extra_fields(); if extra_count != 0 { write!(f, ", .. ({} fields)", extra_count)?; } write!(f, " }}") } } impl ::core::default::Default for CreateAccount { fn default() -> Self { let v: Vec<u8> = vec![ 85, 0, 0, 0, 12, 0, 0, 0, 65, 0, 0, 0, 53, 0, 0, 0, 16, 0, 0, 0, 48, 0, 0, 0, 49, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ]; CreateAccount::new_unchecked(v.into()) } } impl CreateAccount { 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 script(&self) -> Script { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[4..]) as usize; let end = molecule::unpack_number(&slice[8..]) as usize; Script::new_unchecked(self.0.slice(start..end)) } pub fn fee(&self) -> Fee { 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; Fee::new_unchecked(self.0.slice(start..end)) } else { Fee::new_unchecked(self.0.slice(start..)) } } pub fn as_reader<'r>(&'r self) -> CreateAccountReader<'r> { CreateAccountReader::new_unchecked(self.as_slice()) } } impl molecule::prelude::Entity for CreateAccount { type Builder = CreateAccountBuilder; const NAME: &'static str = "CreateAccount"; fn new_unchecked(data: molecule::bytes::Bytes) -> Self { CreateAccount(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> { CreateAccountReader::from_slice(slice).map(|reader| reader.to_entity()) } fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> { CreateAccountReader::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().script(self.script()).fee(self.fee()) } } #[derive(Clone, Copy)] pub struct CreateAccountReader<'r>(&'r [u8]); impl<'r> ::core::fmt::LowerHex for CreateAccountReader<'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 CreateAccountReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl<'r> ::core::fmt::Display for CreateAccountReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; write!(f, "{}: {}", "script", self.script())?; write!(f, ", {}: {}", "fee", self.fee())?; let extra_count = self.count_extra_fields(); if extra_count != 0 { write!(f, ", .. ({} fields)", extra_count)?; } write!(f, " }}") } } impl<'r> CreateAccountReader<'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 script(&self) -> ScriptReader<'r> { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[4..]) as usize; let end = molecule::unpack_number(&slice[8..]) as usize; ScriptReader::new_unchecked(&self.as_slice()[start..end]) } pub fn fee(&self) -> FeeReader<'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; FeeReader::new_unchecked(&self.as_slice()[start..end]) } else { FeeReader::new_unchecked(&self.as_slice()[start..]) } } } impl<'r> molecule::prelude::Reader<'r> for CreateAccountReader<'r> { type Entity = CreateAccount; const NAME: &'static str = "CreateAccountReader"; fn to_entity(&self) -> Self::Entity { Self::Entity::new_unchecked(self.as_slice().to_owned().into()) } fn new_unchecked(slice: &'r [u8]) -> Self { CreateAccountReader(slice) } fn as_slice(&self) -> &'r [u8] { self.0 } fn verify(slice: &[u8], compatible: bool) -> molecule::error::VerificationResult<()> { use molecule::verification_error as ve; let slice_len = slice.len(); if slice_len < molecule::NUMBER_SIZE { return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE, slice_len); } let total_size = molecule::unpack_number(slice) as usize; if slice_len != total_size { return ve!(Self, TotalSizeNotMatch, total_size, slice_len); } if slice_len == molecule::NUMBER_SIZE && Self::FIELD_COUNT == 0 { return Ok(()); } if slice_len < molecule::NUMBER_SIZE * 2 { return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE * 2, slice_len); } let offset_first = molecule::unpack_number(&slice[molecule::NUMBER_SIZE..]) as usize; if offset_first % molecule::NUMBER_SIZE != 0 || offset_first < molecule::NUMBER_SIZE * 2 { return ve!(Self, OffsetsNotMatch); } if slice_len < offset_first { return ve!(Self, HeaderIsBroken, offset_first, slice_len); } let field_count = offset_first / molecule::NUMBER_SIZE - 1; if field_count < Self::FIELD_COUNT { return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, field_count); } else if !compatible && field_count > Self::FIELD_COUNT { return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, field_count); }; let mut offsets: Vec<usize> = slice[molecule::NUMBER_SIZE..offset_first] .chunks_exact(molecule::NUMBER_SIZE) .map(|x| molecule::unpack_number(x) as usize) .collect(); offsets.push(total_size); if offsets.windows(2).any(|i| i[0] > i[1]) { return ve!(Self, OffsetsNotMatch); } ScriptReader::verify(&slice[offsets[0]..offsets[1]], compatible)?; FeeReader::verify(&slice[offsets[1]..offsets[2]], compatible)?; Ok(()) } } #[derive(Debug, Default)] pub struct CreateAccountBuilder { pub(crate) script: Script, pub(crate) fee: Fee, } impl CreateAccountBuilder { pub const FIELD_COUNT: usize = 2; pub fn script(mut self, v: Script) -> Self { self.script = v; self } pub fn fee(mut self, v: Fee) -> Self { self.fee = v; self } } impl molecule::prelude::Builder for CreateAccountBuilder { type Entity = CreateAccount; const NAME: &'static str = "CreateAccountBuilder"; fn expected_length(&self) -> usize { molecule::NUMBER_SIZE * (Self::FIELD_COUNT + 1) + self.script.as_slice().len() + self.fee.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.script.as_slice().len(); offsets.push(total_size); total_size += self.fee.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.script.as_slice())?; writer.write_all(self.fee.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)); CreateAccount::new_unchecked(inner.into()) } } #[derive(Clone)] pub struct SUDTArgs(molecule::bytes::Bytes); impl ::core::fmt::LowerHex for SUDTArgs { 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 SUDTArgs { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl ::core::fmt::Display for SUDTArgs { 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 SUDTArgs { fn default() -> Self { let v: Vec<u8> = vec![0, 0, 0, 0, 12, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0]; SUDTArgs::new_unchecked(v.into()) } } impl SUDTArgs { pub const ITEMS_COUNT: usize = 2; pub fn item_id(&self) -> molecule::Number { molecule::unpack_number(self.as_slice()) } pub fn to_enum(&self) -> SUDTArgsUnion { let inner = self.0.slice(molecule::NUMBER_SIZE..); match self.item_id() { 0 => SUDTQuery::new_unchecked(inner).into(), 1 => SUDTTransfer::new_unchecked(inner).into(), _ => panic!("{}: invalid data", Self::NAME), } } pub fn as_reader<'r>(&'r self) -> SUDTArgsReader<'r> { SUDTArgsReader::new_unchecked(self.as_slice()) } } impl molecule::prelude::Entity for SUDTArgs { type Builder = SUDTArgsBuilder; const NAME: &'static str = "SUDTArgs"; fn new_unchecked(data: molecule::bytes::Bytes) -> Self { SUDTArgs(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> { SUDTArgsReader::from_slice(slice).map(|reader| reader.to_entity()) } fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> { SUDTArgsReader::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 SUDTArgsReader<'r>(&'r [u8]); impl<'r> ::core::fmt::LowerHex for SUDTArgsReader<'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 SUDTArgsReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl<'r> ::core::fmt::Display for SUDTArgsReader<'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> SUDTArgsReader<'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) -> SUDTArgsUnionReader<'r> { let inner = &self.as_slice()[molecule::NUMBER_SIZE..]; match self.item_id() { 0 => SUDTQueryReader::new_unchecked(inner).into(), 1 => SUDTTransferReader::new_unchecked(inner).into(), _ => panic!("{}: invalid data", Self::NAME), } } } impl<'r> molecule::prelude::Reader<'r> for SUDTArgsReader<'r> { type Entity = SUDTArgs; const NAME: &'static str = "SUDTArgsReader"; fn to_entity(&self) -> Self::Entity { Self::Entity::new_unchecked(self.as_slice().to_owned().into()) } fn new_unchecked(slice: &'r [u8]) -> Self { SUDTArgsReader(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 => SUDTQueryReader::verify(inner_slice, compatible), 1 => SUDTTransferReader::verify(inner_slice, compatible), _ => ve!(Self, UnknownItem, Self::ITEMS_COUNT, item_id), }?; Ok(()) } } #[derive(Debug, Default)] pub struct SUDTArgsBuilder(pub(crate) SUDTArgsUnion); impl SUDTArgsBuilder { pub const ITEMS_COUNT: usize = 2; pub fn set<I>(mut self, v: I) -> Self where I: ::core::convert::Into<SUDTArgsUnion>, { self.0 = v.into(); self } } impl molecule::prelude::Builder for SUDTArgsBuilder { type Entity = SUDTArgs; const NAME: &'static str = "SUDTArgsBuilder"; 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)); SUDTArgs::new_unchecked(inner.into()) } } #[derive(Debug, Clone)] pub enum SUDTArgsUnion { SUDTQuery(SUDTQuery), SUDTTransfer(SUDTTransfer), } #[derive(Debug, Clone, Copy)] pub enum SUDTArgsUnionReader<'r> { SUDTQuery(SUDTQueryReader<'r>), SUDTTransfer(SUDTTransferReader<'r>), } impl ::core::default::Default for SUDTArgsUnion { fn default() -> Self { SUDTArgsUnion::SUDTQuery(::core::default::Default::default()) } } impl ::core::fmt::Display for SUDTArgsUnion { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { match self { SUDTArgsUnion::SUDTQuery(ref item) => { write!(f, "{}::{}({})", Self::NAME, SUDTQuery::NAME, item) } SUDTArgsUnion::SUDTTransfer(ref item) => { write!(f, "{}::{}({})", Self::NAME, SUDTTransfer::NAME, item) } } } } impl<'r> ::core::fmt::Display for SUDTArgsUnionReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { match self { SUDTArgsUnionReader::SUDTQuery(ref item) => { write!(f, "{}::{}({})", Self::NAME, SUDTQuery::NAME, item) } SUDTArgsUnionReader::SUDTTransfer(ref item) => { write!(f, "{}::{}({})", Self::NAME, SUDTTransfer::NAME, item) } } } } impl SUDTArgsUnion { pub(crate) fn display_inner(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { match self { SUDTArgsUnion::SUDTQuery(ref item) => write!(f, "{}", item), SUDTArgsUnion::SUDTTransfer(ref item) => write!(f, "{}", item), } } } impl<'r> SUDTArgsUnionReader<'r> { pub(crate) fn display_inner(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { match self { SUDTArgsUnionReader::SUDTQuery(ref item) => write!(f, "{}", item), SUDTArgsUnionReader::SUDTTransfer(ref item) => write!(f, "{}", item), } } } impl ::core::convert::From<SUDTQuery> for SUDTArgsUnion { fn from(item: SUDTQuery) -> Self { SUDTArgsUnion::SUDTQuery(item) } } impl ::core::convert::From<SUDTTransfer> for SUDTArgsUnion { fn from(item: SUDTTransfer) -> Self { SUDTArgsUnion::SUDTTransfer(item) } } impl<'r> ::core::convert::From<SUDTQueryReader<'r>> for SUDTArgsUnionReader<'r> { fn from(item: SUDTQueryReader<'r>) -> Self { SUDTArgsUnionReader::SUDTQuery(item) } } impl<'r> ::core::convert::From<SUDTTransferReader<'r>> for SUDTArgsUnionReader<'r> { fn from(item: SUDTTransferReader<'r>) -> Self { SUDTArgsUnionReader::SUDTTransfer(item) } } impl SUDTArgsUnion { pub const NAME: &'static str = "SUDTArgsUnion"; pub fn as_bytes(&self) -> molecule::bytes::Bytes { match self { SUDTArgsUnion::SUDTQuery(item) => item.as_bytes(), SUDTArgsUnion::SUDTTransfer(item) => item.as_bytes(), } } pub fn as_slice(&self) -> &[u8] { match self { SUDTArgsUnion::SUDTQuery(item) => item.as_slice(), SUDTArgsUnion::SUDTTransfer(item) => item.as_slice(), } } pub fn item_id(&self) -> molecule::Number { match self { SUDTArgsUnion::SUDTQuery(_) => 0, SUDTArgsUnion::SUDTTransfer(_) => 1, } } pub fn item_name(&self) -> &str { match self { SUDTArgsUnion::SUDTQuery(_) => "SUDTQuery", SUDTArgsUnion::SUDTTransfer(_) => "SUDTTransfer", } } pub fn as_reader<'r>(&'r self) -> SUDTArgsUnionReader<'r> { match self { SUDTArgsUnion::SUDTQuery(item) => item.as_reader().into(), SUDTArgsUnion::SUDTTransfer(item) => item.as_reader().into(), } } } impl<'r> SUDTArgsUnionReader<'r> { pub const NAME: &'r str = "SUDTArgsUnionReader"; pub fn as_slice(&self) -> &'r [u8] { match self { SUDTArgsUnionReader::SUDTQuery(item) => item.as_slice(), SUDTArgsUnionReader::SUDTTransfer(item) => item.as_slice(), } } pub fn item_id(&self) -> molecule::Number { match self { SUDTArgsUnionReader::SUDTQuery(_) => 0, SUDTArgsUnionReader::SUDTTransfer(_) => 1, } } pub fn item_name(&self) -> &str { match self { SUDTArgsUnionReader::SUDTQuery(_) => "SUDTQuery", SUDTArgsUnionReader::SUDTTransfer(_) => "SUDTTransfer", } } } #[derive(Clone)] pub struct SUDTQuery(molecule::bytes::Bytes); impl ::core::fmt::LowerHex for SUDTQuery { 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 SUDTQuery { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl ::core::fmt::Display for SUDTQuery { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; write!(f, "{}: {}", "short_address", self.short_address())?; let extra_count = self.count_extra_fields(); if extra_count != 0 { write!(f, ", .. ({} fields)", extra_count)?; } write!(f, " }}") } } impl ::core::default::Default for SUDTQuery { fn default() -> Self { let v: Vec<u8> = vec![12, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0]; SUDTQuery::new_unchecked(v.into()) } } impl SUDTQuery { 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 short_address(&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) -> SUDTQueryReader<'r> { SUDTQueryReader::new_unchecked(self.as_slice()) } } impl molecule::prelude::Entity for SUDTQuery { type Builder = SUDTQueryBuilder; const NAME: &'static str = "SUDTQuery"; fn new_unchecked(data: molecule::bytes::Bytes) -> Self { SUDTQuery(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> { SUDTQueryReader::from_slice(slice).map(|reader| reader.to_entity()) } fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> { SUDTQueryReader::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().short_address(self.short_address()) } } #[derive(Clone, Copy)] pub struct SUDTQueryReader<'r>(&'r [u8]); impl<'r> ::core::fmt::LowerHex for SUDTQueryReader<'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 SUDTQueryReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl<'r> ::core::fmt::Display for SUDTQueryReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; write!(f, "{}: {}", "short_address", self.short_address())?; let extra_count = self.count_extra_fields(); if extra_count != 0 { write!(f, ", .. ({} fields)", extra_count)?; } write!(f, " }}") } } impl<'r> SUDTQueryReader<'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 short_address(&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 SUDTQueryReader<'r> { type Entity = SUDTQuery; const NAME: &'static str = "SUDTQueryReader"; fn to_entity(&self) -> Self::Entity { Self::Entity::new_unchecked(self.as_slice().to_owned().into()) } fn new_unchecked(slice: &'r [u8]) -> Self { SUDTQueryReader(slice) } fn as_slice(&self) -> &'r [u8] { self.0 } fn verify(slice: &[u8], compatible: bool) -> molecule::error::VerificationResult<()> { use molecule::verification_error as ve; let slice_len = slice.len(); if slice_len < molecule::NUMBER_SIZE { return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE, slice_len); } let total_size = molecule::unpack_number(slice) as usize; if slice_len != total_size { return ve!(Self, TotalSizeNotMatch, total_size, slice_len); } if slice_len == molecule::NUMBER_SIZE && Self::FIELD_COUNT == 0 { return Ok(()); } if slice_len < molecule::NUMBER_SIZE * 2 { return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE * 2, slice_len); } let offset_first = molecule::unpack_number(&slice[molecule::NUMBER_SIZE..]) as usize; if offset_first % molecule::NUMBER_SIZE != 0 || offset_first < molecule::NUMBER_SIZE * 2 { return ve!(Self, OffsetsNotMatch); } if slice_len < offset_first { return ve!(Self, HeaderIsBroken, offset_first, slice_len); } let field_count = offset_first / molecule::NUMBER_SIZE - 1; if field_count < Self::FIELD_COUNT { return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, field_count); } else if !compatible && field_count > Self::FIELD_COUNT { return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, field_count); }; let mut offsets: Vec<usize> = slice[molecule::NUMBER_SIZE..offset_first] .chunks_exact(molecule::NUMBER_SIZE) .map(|x| molecule::unpack_number(x) as usize) .collect(); offsets.push(total_size); if offsets.windows(2).any(|i| i[0] > i[1]) { return ve!(Self, OffsetsNotMatch); } BytesReader::verify(&slice[offsets[0]..offsets[1]], compatible)?; Ok(()) } } #[derive(Debug, Default)] pub struct SUDTQueryBuilder { pub(crate) short_address: Bytes, } impl SUDTQueryBuilder { pub const FIELD_COUNT: usize = 1; pub fn short_address(mut self, v: Bytes) -> Self { self.short_address = v; self } } impl molecule::prelude::Builder for SUDTQueryBuilder { type Entity = SUDTQuery; const NAME: &'static str = "SUDTQueryBuilder"; fn expected_length(&self) -> usize { molecule::NUMBER_SIZE * (Self::FIELD_COUNT + 1) + self.short_address.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.short_address.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.short_address.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)); SUDTQuery::new_unchecked(inner.into()) } } #[derive(Clone)] pub struct SUDTTransfer(molecule::bytes::Bytes); impl ::core::fmt::LowerHex for SUDTTransfer { 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 SUDTTransfer { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl ::core::fmt::Display for SUDTTransfer { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; write!(f, "{}: {}", "to", self.to())?; write!(f, ", {}: {}", "amount", self.amount())?; write!(f, ", {}: {}", "fee", self.fee())?; let extra_count = self.count_extra_fields(); if extra_count != 0 { write!(f, ", .. ({} fields)", extra_count)?; } write!(f, " }}") } } impl ::core::default::Default for SUDTTransfer { fn default() -> Self { let v: Vec<u8> = vec![ 52, 0, 0, 0, 16, 0, 0, 0, 20, 0, 0, 0, 36, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ]; SUDTTransfer::new_unchecked(v.into()) } } impl SUDTTransfer { 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 to(&self) -> Bytes { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[4..]) as usize; let end = molecule::unpack_number(&slice[8..]) as usize; Bytes::new_unchecked(self.0.slice(start..end)) } pub fn amount(&self) -> Uint128 { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[8..]) as usize; let end = molecule::unpack_number(&slice[12..]) as usize; Uint128::new_unchecked(self.0.slice(start..end)) } pub fn fee(&self) -> Uint128 { 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; Uint128::new_unchecked(self.0.slice(start..end)) } else { Uint128::new_unchecked(self.0.slice(start..)) } } pub fn as_reader<'r>(&'r self) -> SUDTTransferReader<'r> { SUDTTransferReader::new_unchecked(self.as_slice()) } } impl molecule::prelude::Entity for SUDTTransfer { type Builder = SUDTTransferBuilder; const NAME: &'static str = "SUDTTransfer"; fn new_unchecked(data: molecule::bytes::Bytes) -> Self { SUDTTransfer(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> { SUDTTransferReader::from_slice(slice).map(|reader| reader.to_entity()) } fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> { SUDTTransferReader::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() .to(self.to()) .amount(self.amount()) .fee(self.fee()) } } #[derive(Clone, Copy)] pub struct SUDTTransferReader<'r>(&'r [u8]); impl<'r> ::core::fmt::LowerHex for SUDTTransferReader<'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 SUDTTransferReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl<'r> ::core::fmt::Display for SUDTTransferReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; write!(f, "{}: {}", "to", self.to())?; write!(f, ", {}: {}", "amount", self.amount())?; write!(f, ", {}: {}", "fee", self.fee())?; let extra_count = self.count_extra_fields(); if extra_count != 0 { write!(f, ", .. ({} fields)", extra_count)?; } write!(f, " }}") } } impl<'r> SUDTTransferReader<'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 to(&self) -> BytesReader<'r> { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[4..]) as usize; let end = molecule::unpack_number(&slice[8..]) as usize; BytesReader::new_unchecked(&self.as_slice()[start..end]) } pub fn amount(&self) -> Uint128Reader<'r> { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[8..]) as usize; let end = molecule::unpack_number(&slice[12..]) as usize; Uint128Reader::new_unchecked(&self.as_slice()[start..end]) } pub fn fee(&self) -> Uint128Reader<'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; Uint128Reader::new_unchecked(&self.as_slice()[start..end]) } else { Uint128Reader::new_unchecked(&self.as_slice()[start..]) } } } impl<'r> molecule::prelude::Reader<'r> for SUDTTransferReader<'r> { type Entity = SUDTTransfer; const NAME: &'static str = "SUDTTransferReader"; fn to_entity(&self) -> Self::Entity { Self::Entity::new_unchecked(self.as_slice().to_owned().into()) } fn new_unchecked(slice: &'r [u8]) -> Self { SUDTTransferReader(slice) } fn as_slice(&self) -> &'r [u8] { self.0 } fn verify(slice: &[u8], compatible: bool) -> molecule::error::VerificationResult<()> { use molecule::verification_error as ve; let slice_len = slice.len(); if slice_len < molecule::NUMBER_SIZE { return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE, slice_len); } let total_size = molecule::unpack_number(slice) as usize; if slice_len != total_size { return ve!(Self, TotalSizeNotMatch, total_size, slice_len); } if slice_len == molecule::NUMBER_SIZE && Self::FIELD_COUNT == 0 { return Ok(()); } if slice_len < molecule::NUMBER_SIZE * 2 { return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE * 2, slice_len); } let offset_first = molecule::unpack_number(&slice[molecule::NUMBER_SIZE..]) as usize; if offset_first % molecule::NUMBER_SIZE != 0 || offset_first < molecule::NUMBER_SIZE * 2 { return ve!(Self, OffsetsNotMatch); } if slice_len < offset_first { return ve!(Self, HeaderIsBroken, offset_first, slice_len); } let field_count = offset_first / molecule::NUMBER_SIZE - 1; if field_count < Self::FIELD_COUNT { return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, field_count); } else if !compatible && field_count > Self::FIELD_COUNT { return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, field_count); }; let mut offsets: Vec<usize> = slice[molecule::NUMBER_SIZE..offset_first] .chunks_exact(molecule::NUMBER_SIZE) .map(|x| molecule::unpack_number(x) as usize) .collect(); offsets.push(total_size); if offsets.windows(2).any(|i| i[0] > i[1]) { return ve!(Self, OffsetsNotMatch); } BytesReader::verify(&slice[offsets[0]..offsets[1]], compatible)?; Uint128Reader::verify(&slice[offsets[1]..offsets[2]], compatible)?; Uint128Reader::verify(&slice[offsets[2]..offsets[3]], compatible)?; Ok(()) } } #[derive(Debug, Default)] pub struct SUDTTransferBuilder { pub(crate) to: Bytes, pub(crate) amount: Uint128, pub(crate) fee: Uint128, } impl SUDTTransferBuilder { pub const FIELD_COUNT: usize = 3; pub fn to(mut self, v: Bytes) -> Self { self.to = v; self } pub fn amount(mut self, v: Uint128) -> Self { self.amount = v; self } pub fn fee(mut self, v: Uint128) -> Self { self.fee = v; self } } impl molecule::prelude::Builder for SUDTTransferBuilder { type Entity = SUDTTransfer; const NAME: &'static str = "SUDTTransferBuilder"; fn expected_length(&self) -> usize { molecule::NUMBER_SIZE * (Self::FIELD_COUNT + 1) + self.to.as_slice().len() + self.amount.as_slice().len() + self.fee.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.to.as_slice().len(); offsets.push(total_size); total_size += self.amount.as_slice().len(); offsets.push(total_size); total_size += self.fee.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.to.as_slice())?; writer.write_all(self.amount.as_slice())?; writer.write_all(self.fee.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)); SUDTTransfer::new_unchecked(inner.into()) } } #[derive(Clone)] pub struct ChallengeTarget(molecule::bytes::Bytes); impl ::core::fmt::LowerHex for ChallengeTarget { 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 ChallengeTarget { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl ::core::fmt::Display for ChallengeTarget { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; write!(f, "{}: {}", "block_hash", self.block_hash())?; write!(f, ", {}: {}", "target_index", self.target_index())?; write!(f, ", {}: {}", "target_type", self.target_type())?; write!(f, " }}") } } impl ::core::default::Default for ChallengeTarget { fn default() -> Self { let v: Vec<u8> = vec![ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ]; ChallengeTarget::new_unchecked(v.into()) } } impl ChallengeTarget { pub const TOTAL_SIZE: usize = 37; pub const FIELD_SIZES: [usize; 3] = [32, 4, 1]; pub const FIELD_COUNT: usize = 3; pub fn block_hash(&self) -> Byte32 { Byte32::new_unchecked(self.0.slice(0..32)) } pub fn target_index(&self) -> Uint32 { Uint32::new_unchecked(self.0.slice(32..36)) } pub fn target_type(&self) -> Byte { Byte::new_unchecked(self.0.slice(36..37)) } pub fn as_reader<'r>(&'r self) -> ChallengeTargetReader<'r> { ChallengeTargetReader::new_unchecked(self.as_slice()) } } impl molecule::prelude::Entity for ChallengeTarget { type Builder = ChallengeTargetBuilder; const NAME: &'static str = "ChallengeTarget"; fn new_unchecked(data: molecule::bytes::Bytes) -> Self { ChallengeTarget(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> { ChallengeTargetReader::from_slice(slice).map(|reader| reader.to_entity()) } fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> { ChallengeTargetReader::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() .block_hash(self.block_hash()) .target_index(self.target_index()) .target_type(self.target_type()) } } #[derive(Clone, Copy)] pub struct ChallengeTargetReader<'r>(&'r [u8]); impl<'r> ::core::fmt::LowerHex for ChallengeTargetReader<'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 ChallengeTargetReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl<'r> ::core::fmt::Display for ChallengeTargetReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; write!(f, "{}: {}", "block_hash", self.block_hash())?; write!(f, ", {}: {}", "target_index", self.target_index())?; write!(f, ", {}: {}", "target_type", self.target_type())?; write!(f, " }}") } } impl<'r> ChallengeTargetReader<'r> { pub const TOTAL_SIZE: usize = 37; pub const FIELD_SIZES: [usize; 3] = [32, 4, 1]; pub const FIELD_COUNT: usize = 3; pub fn block_hash(&self) -> Byte32Reader<'r> { Byte32Reader::new_unchecked(&self.as_slice()[0..32]) } pub fn target_index(&self) -> Uint32Reader<'r> { Uint32Reader::new_unchecked(&self.as_slice()[32..36]) } pub fn target_type(&self) -> ByteReader<'r> { ByteReader::new_unchecked(&self.as_slice()[36..37]) } } impl<'r> molecule::prelude::Reader<'r> for ChallengeTargetReader<'r> { type Entity = ChallengeTarget; const NAME: &'static str = "ChallengeTargetReader"; fn to_entity(&self) -> Self::Entity { Self::Entity::new_unchecked(self.as_slice().to_owned().into()) } fn new_unchecked(slice: &'r [u8]) -> Self { ChallengeTargetReader(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(()) } } #[derive(Debug, Default)] pub struct ChallengeTargetBuilder { pub(crate) block_hash: Byte32, pub(crate) target_index: Uint32, pub(crate) target_type: Byte, } impl ChallengeTargetBuilder { pub const TOTAL_SIZE: usize = 37; pub const FIELD_SIZES: [usize; 3] = [32, 4, 1]; pub const FIELD_COUNT: usize = 3; pub fn block_hash(mut self, v: Byte32) -> Self { self.block_hash = v; self } pub fn target_index(mut self, v: Uint32) -> Self { self.target_index = v; self } pub fn target_type(mut self, v: Byte) -> Self { self.target_type = v; self } } impl molecule::prelude::Builder for ChallengeTargetBuilder { type Entity = ChallengeTarget; const NAME: &'static str = "ChallengeTargetBuilder"; 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.block_hash.as_slice())?; writer.write_all(self.target_index.as_slice())?; writer.write_all(self.target_type.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)); ChallengeTarget::new_unchecked(inner.into()) } } #[derive(Clone)] pub struct ChallengeLockArgs(molecule::bytes::Bytes); impl ::core::fmt::LowerHex for ChallengeLockArgs { 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 ChallengeLockArgs { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl ::core::fmt::Display for ChallengeLockArgs { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; write!(f, "{}: {}", "target", self.target())?; write!( f, ", {}: {}", "rewards_receiver_lock", self.rewards_receiver_lock() )?; let extra_count = self.count_extra_fields(); if extra_count != 0 { write!(f, ", .. ({} fields)", extra_count)?; } write!(f, " }}") } } impl ::core::default::Default for ChallengeLockArgs { fn default() -> Self { let v: Vec<u8> = vec![ 102, 0, 0, 0, 12, 0, 0, 0, 49, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 53, 0, 0, 0, 16, 0, 0, 0, 48, 0, 0, 0, 49, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ]; ChallengeLockArgs::new_unchecked(v.into()) } } impl ChallengeLockArgs { 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 target(&self) -> ChallengeTarget { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[4..]) as usize; let end = molecule::unpack_number(&slice[8..]) as usize; ChallengeTarget::new_unchecked(self.0.slice(start..end)) } pub fn rewards_receiver_lock(&self) -> Script { 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; Script::new_unchecked(self.0.slice(start..end)) } else { Script::new_unchecked(self.0.slice(start..)) } } pub fn as_reader<'r>(&'r self) -> ChallengeLockArgsReader<'r> { ChallengeLockArgsReader::new_unchecked(self.as_slice()) } } impl molecule::prelude::Entity for ChallengeLockArgs { type Builder = ChallengeLockArgsBuilder; const NAME: &'static str = "ChallengeLockArgs"; fn new_unchecked(data: molecule::bytes::Bytes) -> Self { ChallengeLockArgs(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> { ChallengeLockArgsReader::from_slice(slice).map(|reader| reader.to_entity()) } fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> { ChallengeLockArgsReader::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() .target(self.target()) .rewards_receiver_lock(self.rewards_receiver_lock()) } } #[derive(Clone, Copy)] pub struct ChallengeLockArgsReader<'r>(&'r [u8]); impl<'r> ::core::fmt::LowerHex for ChallengeLockArgsReader<'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 ChallengeLockArgsReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl<'r> ::core::fmt::Display for ChallengeLockArgsReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; write!(f, "{}: {}", "target", self.target())?; write!( f, ", {}: {}", "rewards_receiver_lock", self.rewards_receiver_lock() )?; let extra_count = self.count_extra_fields(); if extra_count != 0 { write!(f, ", .. ({} fields)", extra_count)?; } write!(f, " }}") } } impl<'r> ChallengeLockArgsReader<'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 target(&self) -> ChallengeTargetReader<'r> { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[4..]) as usize; let end = molecule::unpack_number(&slice[8..]) as usize; ChallengeTargetReader::new_unchecked(&self.as_slice()[start..end]) } pub fn rewards_receiver_lock(&self) -> ScriptReader<'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; ScriptReader::new_unchecked(&self.as_slice()[start..end]) } else { ScriptReader::new_unchecked(&self.as_slice()[start..]) } } } impl<'r> molecule::prelude::Reader<'r> for ChallengeLockArgsReader<'r> { type Entity = ChallengeLockArgs; const NAME: &'static str = "ChallengeLockArgsReader"; fn to_entity(&self) -> Self::Entity { Self::Entity::new_unchecked(self.as_slice().to_owned().into()) } fn new_unchecked(slice: &'r [u8]) -> Self { ChallengeLockArgsReader(slice) } fn as_slice(&self) -> &'r [u8] { self.0 } fn verify(slice: &[u8], compatible: bool) -> molecule::error::VerificationResult<()> { use molecule::verification_error as ve; let slice_len = slice.len(); if slice_len < molecule::NUMBER_SIZE { return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE, slice_len); } let total_size = molecule::unpack_number(slice) as usize; if slice_len != total_size { return ve!(Self, TotalSizeNotMatch, total_size, slice_len); } if slice_len == molecule::NUMBER_SIZE && Self::FIELD_COUNT == 0 { return Ok(()); } if slice_len < molecule::NUMBER_SIZE * 2 { return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE * 2, slice_len); } let offset_first = molecule::unpack_number(&slice[molecule::NUMBER_SIZE..]) as usize; if offset_first % molecule::NUMBER_SIZE != 0 || offset_first < molecule::NUMBER_SIZE * 2 { return ve!(Self, OffsetsNotMatch); } if slice_len < offset_first { return ve!(Self, HeaderIsBroken, offset_first, slice_len); } let field_count = offset_first / molecule::NUMBER_SIZE - 1; if field_count < Self::FIELD_COUNT { return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, field_count); } else if !compatible && field_count > Self::FIELD_COUNT { return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, field_count); }; let mut offsets: Vec<usize> = slice[molecule::NUMBER_SIZE..offset_first] .chunks_exact(molecule::NUMBER_SIZE) .map(|x| molecule::unpack_number(x) as usize) .collect(); offsets.push(total_size); if offsets.windows(2).any(|i| i[0] > i[1]) { return ve!(Self, OffsetsNotMatch); } ChallengeTargetReader::verify(&slice[offsets[0]..offsets[1]], compatible)?; ScriptReader::verify(&slice[offsets[1]..offsets[2]], compatible)?; Ok(()) } } #[derive(Debug, Default)] pub struct ChallengeLockArgsBuilder { pub(crate) target: ChallengeTarget, pub(crate) rewards_receiver_lock: Script, } impl ChallengeLockArgsBuilder { pub const FIELD_COUNT: usize = 2; pub fn target(mut self, v: ChallengeTarget) -> Self { self.target = v; self } pub fn rewards_receiver_lock(mut self, v: Script) -> Self { self.rewards_receiver_lock = v; self } } impl molecule::prelude::Builder for ChallengeLockArgsBuilder { type Entity = ChallengeLockArgs; const NAME: &'static str = "ChallengeLockArgsBuilder"; fn expected_length(&self) -> usize { molecule::NUMBER_SIZE * (Self::FIELD_COUNT + 1) + self.target.as_slice().len() + self.rewards_receiver_lock.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.target.as_slice().len(); offsets.push(total_size); total_size += self.rewards_receiver_lock.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.target.as_slice())?; writer.write_all(self.rewards_receiver_lock.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)); ChallengeLockArgs::new_unchecked(inner.into()) } } #[derive(Clone)] pub struct ChallengeWitness(molecule::bytes::Bytes); impl ::core::fmt::LowerHex for ChallengeWitness { 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 ChallengeWitness { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl ::core::fmt::Display for ChallengeWitness { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; write!(f, "{}: {}", "raw_l2block", self.raw_l2block())?; write!(f, ", {}: {}", "block_proof", self.block_proof())?; let extra_count = self.count_extra_fields(); if extra_count != 0 { write!(f, ", .. ({} fields)", extra_count)?; } write!(f, " }}") } } impl ::core::default::Default for ChallengeWitness { fn default() -> Self { let v: Vec<u8> = vec![ 84, 1, 0, 0, 12, 0, 0, 0, 80, 1, 0, 0, 68, 1, 0, 0, 44, 0, 0, 0, 52, 0, 0, 0, 56, 0, 0, 0, 88, 0, 0, 0, 120, 0, 0, 0, 128, 0, 0, 0, 164, 0, 0, 0, 200, 0, 0, 0, 204, 0, 0, 0, 240, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 84, 0, 0, 0, 16, 0, 0, 0, 48, 0, 0, 0, 52, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ]; ChallengeWitness::new_unchecked(v.into()) } } impl ChallengeWitness { 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 raw_l2block(&self) -> RawL2Block { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[4..]) as usize; let end = molecule::unpack_number(&slice[8..]) as usize; RawL2Block::new_unchecked(self.0.slice(start..end)) } pub fn block_proof(&self) -> Bytes { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[8..]) as usize; if self.has_extra_fields() { let end = molecule::unpack_number(&slice[12..]) as usize; Bytes::new_unchecked(self.0.slice(start..end)) } else { Bytes::new_unchecked(self.0.slice(start..)) } } pub fn as_reader<'r>(&'r self) -> ChallengeWitnessReader<'r> { ChallengeWitnessReader::new_unchecked(self.as_slice()) } } impl molecule::prelude::Entity for ChallengeWitness { type Builder = ChallengeWitnessBuilder; const NAME: &'static str = "ChallengeWitness"; fn new_unchecked(data: molecule::bytes::Bytes) -> Self { ChallengeWitness(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> { ChallengeWitnessReader::from_slice(slice).map(|reader| reader.to_entity()) } fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> { ChallengeWitnessReader::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() .raw_l2block(self.raw_l2block()) .block_proof(self.block_proof()) } } #[derive(Clone, Copy)] pub struct ChallengeWitnessReader<'r>(&'r [u8]); impl<'r> ::core::fmt::LowerHex for ChallengeWitnessReader<'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 ChallengeWitnessReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl<'r> ::core::fmt::Display for ChallengeWitnessReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; write!(f, "{}: {}", "raw_l2block", self.raw_l2block())?; write!(f, ", {}: {}", "block_proof", self.block_proof())?; let extra_count = self.count_extra_fields(); if extra_count != 0 { write!(f, ", .. ({} fields)", extra_count)?; } write!(f, " }}") } } impl<'r> ChallengeWitnessReader<'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 raw_l2block(&self) -> RawL2BlockReader<'r> { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[4..]) as usize; let end = molecule::unpack_number(&slice[8..]) as usize; RawL2BlockReader::new_unchecked(&self.as_slice()[start..end]) } pub fn block_proof(&self) -> BytesReader<'r> { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[8..]) as usize; if self.has_extra_fields() { let end = molecule::unpack_number(&slice[12..]) as usize; BytesReader::new_unchecked(&self.as_slice()[start..end]) } else { BytesReader::new_unchecked(&self.as_slice()[start..]) } } } impl<'r> molecule::prelude::Reader<'r> for ChallengeWitnessReader<'r> { type Entity = ChallengeWitness; const NAME: &'static str = "ChallengeWitnessReader"; fn to_entity(&self) -> Self::Entity { Self::Entity::new_unchecked(self.as_slice().to_owned().into()) } fn new_unchecked(slice: &'r [u8]) -> Self { ChallengeWitnessReader(slice) } fn as_slice(&self) -> &'r [u8] { self.0 } fn verify(slice: &[u8], compatible: bool) -> molecule::error::VerificationResult<()> { use molecule::verification_error as ve; let slice_len = slice.len(); if slice_len < molecule::NUMBER_SIZE { return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE, slice_len); } let total_size = molecule::unpack_number(slice) as usize; if slice_len != total_size { return ve!(Self, TotalSizeNotMatch, total_size, slice_len); } if slice_len == molecule::NUMBER_SIZE && Self::FIELD_COUNT == 0 { return Ok(()); } if slice_len < molecule::NUMBER_SIZE * 2 { return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE * 2, slice_len); } let offset_first = molecule::unpack_number(&slice[molecule::NUMBER_SIZE..]) as usize; if offset_first % molecule::NUMBER_SIZE != 0 || offset_first < molecule::NUMBER_SIZE * 2 { return ve!(Self, OffsetsNotMatch); } if slice_len < offset_first { return ve!(Self, HeaderIsBroken, offset_first, slice_len); } let field_count = offset_first / molecule::NUMBER_SIZE - 1; if field_count < Self::FIELD_COUNT { return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, field_count); } else if !compatible && field_count > Self::FIELD_COUNT { return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, field_count); }; let mut offsets: Vec<usize> = slice[molecule::NUMBER_SIZE..offset_first] .chunks_exact(molecule::NUMBER_SIZE) .map(|x| molecule::unpack_number(x) as usize) .collect(); offsets.push(total_size); if offsets.windows(2).any(|i| i[0] > i[1]) { return ve!(Self, OffsetsNotMatch); } RawL2BlockReader::verify(&slice[offsets[0]..offsets[1]], compatible)?; BytesReader::verify(&slice[offsets[1]..offsets[2]], compatible)?; Ok(()) } } #[derive(Debug, Default)] pub struct ChallengeWitnessBuilder { pub(crate) raw_l2block: RawL2Block, pub(crate) block_proof: Bytes, } impl ChallengeWitnessBuilder { pub const FIELD_COUNT: usize = 2; pub fn raw_l2block(mut self, v: RawL2Block) -> Self { self.raw_l2block = v; self } pub fn block_proof(mut self, v: Bytes) -> Self { self.block_proof = v; self } } impl molecule::prelude::Builder for ChallengeWitnessBuilder { type Entity = ChallengeWitness; const NAME: &'static str = "ChallengeWitnessBuilder"; fn expected_length(&self) -> usize { molecule::NUMBER_SIZE * (Self::FIELD_COUNT + 1) + self.raw_l2block.as_slice().len() + self.block_proof.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.raw_l2block.as_slice().len(); offsets.push(total_size); total_size += self.block_proof.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.raw_l2block.as_slice())?; writer.write_all(self.block_proof.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)); ChallengeWitness::new_unchecked(inner.into()) } } #[derive(Clone)] pub struct ScriptVec(molecule::bytes::Bytes); impl ::core::fmt::LowerHex for ScriptVec { 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 ScriptVec { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl ::core::fmt::Display for ScriptVec { 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 ScriptVec { fn default() -> Self { let v: Vec<u8> = vec![4, 0, 0, 0]; ScriptVec::new_unchecked(v.into()) } } impl ScriptVec { 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<Script> { if idx >= self.len() { None } else { Some(self.get_unchecked(idx)) } } pub fn get_unchecked(&self, idx: usize) -> Script { 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 { Script::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; Script::new_unchecked(self.0.slice(start..end)) } } pub fn as_reader<'r>(&'r self) -> ScriptVecReader<'r> { ScriptVecReader::new_unchecked(self.as_slice()) } } impl molecule::prelude::Entity for ScriptVec { type Builder = ScriptVecBuilder; const NAME: &'static str = "ScriptVec"; fn new_unchecked(data: molecule::bytes::Bytes) -> Self { ScriptVec(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> { ScriptVecReader::from_slice(slice).map(|reader| reader.to_entity()) } fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> { ScriptVecReader::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 ScriptVecReader<'r>(&'r [u8]); impl<'r> ::core::fmt::LowerHex for ScriptVecReader<'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 ScriptVecReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl<'r> ::core::fmt::Display for ScriptVecReader<'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> ScriptVecReader<'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<ScriptReader<'r>> { if idx >= self.len() { None } else { Some(self.get_unchecked(idx)) } } pub fn get_unchecked(&self, idx: usize) -> ScriptReader<'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 { ScriptReader::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; ScriptReader::new_unchecked(&self.as_slice()[start..end]) } } } impl<'r> molecule::prelude::Reader<'r> for ScriptVecReader<'r> { type Entity = ScriptVec; const NAME: &'static str = "ScriptVecReader"; fn to_entity(&self) -> Self::Entity { Self::Entity::new_unchecked(self.as_slice().to_owned().into()) } fn new_unchecked(slice: &'r [u8]) -> Self { ScriptVecReader(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]; ScriptReader::verify(&slice[start..end], compatible)?; } Ok(()) } } #[derive(Debug, Default)] pub struct ScriptVecBuilder(pub(crate) Vec<Script>); impl ScriptVecBuilder { pub fn set(mut self, v: Vec<Script>) -> Self { self.0 = v; self } pub fn push(mut self, v: Script) -> Self { self.0.push(v); self } pub fn extend<T: ::core::iter::IntoIterator<Item = Script>>(mut self, iter: T) -> Self { for elem in iter { self.0.push(elem); } self } } impl molecule::prelude::Builder for ScriptVecBuilder { type Entity = ScriptVec; const NAME: &'static str = "ScriptVecBuilder"; 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)); ScriptVec::new_unchecked(inner.into()) } } pub struct ScriptVecIterator(ScriptVec, usize, usize); impl ::core::iter::Iterator for ScriptVecIterator { type Item = Script; 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 ScriptVecIterator { fn len(&self) -> usize { self.2 - self.1 } } impl ::core::iter::IntoIterator for ScriptVec { type Item = Script; type IntoIter = ScriptVecIterator; fn into_iter(self) -> Self::IntoIter { let len = self.len(); ScriptVecIterator(self, 0, len) } } impl<'r> ScriptVecReader<'r> { pub fn iter<'t>(&'t self) -> ScriptVecReaderIterator<'t, 'r> { ScriptVecReaderIterator(&self, 0, self.len()) } } pub struct ScriptVecReaderIterator<'t, 'r>(&'t ScriptVecReader<'r>, usize, usize); impl<'t: 'r, 'r> ::core::iter::Iterator for ScriptVecReaderIterator<'t, 'r> { type Item = ScriptReader<'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 ScriptVecReaderIterator<'t, 'r> { fn len(&self) -> usize { self.2 - self.1 } } #[derive(Clone)] pub struct BlockHashEntry(molecule::bytes::Bytes); impl ::core::fmt::LowerHex for BlockHashEntry { 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 BlockHashEntry { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl ::core::fmt::Display for BlockHashEntry { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; write!(f, "{}: {}", "number", self.number())?; write!(f, ", {}: {}", "hash", self.hash())?; write!(f, " }}") } } impl ::core::default::Default for BlockHashEntry { fn default() -> Self { let v: Vec<u8> = vec![ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ]; BlockHashEntry::new_unchecked(v.into()) } } impl BlockHashEntry { pub const TOTAL_SIZE: usize = 40; pub const FIELD_SIZES: [usize; 2] = [8, 32]; pub const FIELD_COUNT: usize = 2; pub fn number(&self) -> Uint64 { Uint64::new_unchecked(self.0.slice(0..8)) } pub fn hash(&self) -> Byte32 { Byte32::new_unchecked(self.0.slice(8..40)) } pub fn as_reader<'r>(&'r self) -> BlockHashEntryReader<'r> { BlockHashEntryReader::new_unchecked(self.as_slice()) } } impl molecule::prelude::Entity for BlockHashEntry { type Builder = BlockHashEntryBuilder; const NAME: &'static str = "BlockHashEntry"; fn new_unchecked(data: molecule::bytes::Bytes) -> Self { BlockHashEntry(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> { BlockHashEntryReader::from_slice(slice).map(|reader| reader.to_entity()) } fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> { BlockHashEntryReader::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().number(self.number()).hash(self.hash()) } } #[derive(Clone, Copy)] pub struct BlockHashEntryReader<'r>(&'r [u8]); impl<'r> ::core::fmt::LowerHex for BlockHashEntryReader<'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 BlockHashEntryReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl<'r> ::core::fmt::Display for BlockHashEntryReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; write!(f, "{}: {}", "number", self.number())?; write!(f, ", {}: {}", "hash", self.hash())?; write!(f, " }}") } } impl<'r> BlockHashEntryReader<'r> { pub const TOTAL_SIZE: usize = 40; pub const FIELD_SIZES: [usize; 2] = [8, 32]; pub const FIELD_COUNT: usize = 2; pub fn number(&self) -> Uint64Reader<'r> { Uint64Reader::new_unchecked(&self.as_slice()[0..8]) } pub fn hash(&self) -> Byte32Reader<'r> { Byte32Reader::new_unchecked(&self.as_slice()[8..40]) } } impl<'r> molecule::prelude::Reader<'r> for BlockHashEntryReader<'r> { type Entity = BlockHashEntry; const NAME: &'static str = "BlockHashEntryReader"; fn to_entity(&self) -> Self::Entity { Self::Entity::new_unchecked(self.as_slice().to_owned().into()) } fn new_unchecked(slice: &'r [u8]) -> Self { BlockHashEntryReader(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(()) } } #[derive(Debug, Default)] pub struct BlockHashEntryBuilder { pub(crate) number: Uint64, pub(crate) hash: Byte32, } impl BlockHashEntryBuilder { pub const TOTAL_SIZE: usize = 40; pub const FIELD_SIZES: [usize; 2] = [8, 32]; pub const FIELD_COUNT: usize = 2; pub fn number(mut self, v: Uint64) -> Self { self.number = v; self } pub fn hash(mut self, v: Byte32) -> Self { self.hash = v; self } } impl molecule::prelude::Builder for BlockHashEntryBuilder { type Entity = BlockHashEntry; const NAME: &'static str = "BlockHashEntryBuilder"; 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.number.as_slice())?; writer.write_all(self.hash.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)); BlockHashEntry::new_unchecked(inner.into()) } } #[derive(Clone)] pub struct BlockHashEntryVec(molecule::bytes::Bytes); impl ::core::fmt::LowerHex for BlockHashEntryVec { 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 BlockHashEntryVec { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl ::core::fmt::Display for BlockHashEntryVec { 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 BlockHashEntryVec { fn default() -> Self { let v: Vec<u8> = vec![0, 0, 0, 0]; BlockHashEntryVec::new_unchecked(v.into()) } } impl BlockHashEntryVec { pub const ITEM_SIZE: usize = 40; pub fn total_size(&self) -> usize { molecule::NUMBER_SIZE + Self::ITEM_SIZE * self.item_count() } pub fn item_count(&self) -> usize { molecule::unpack_number(self.as_slice()) as usize } pub fn len(&self) -> usize { self.item_count() } pub fn is_empty(&self) -> bool { self.len() == 0 } pub fn get(&self, idx: usize) -> Option<BlockHashEntry> { if idx >= self.len() { None } else { Some(self.get_unchecked(idx)) } } pub fn get_unchecked(&self, idx: usize) -> BlockHashEntry { let start = molecule::NUMBER_SIZE + Self::ITEM_SIZE * idx; let end = start + Self::ITEM_SIZE; BlockHashEntry::new_unchecked(self.0.slice(start..end)) } pub fn as_reader<'r>(&'r self) -> BlockHashEntryVecReader<'r> { BlockHashEntryVecReader::new_unchecked(self.as_slice()) } } impl molecule::prelude::Entity for BlockHashEntryVec { type Builder = BlockHashEntryVecBuilder; const NAME: &'static str = "BlockHashEntryVec"; fn new_unchecked(data: molecule::bytes::Bytes) -> Self { BlockHashEntryVec(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> { BlockHashEntryVecReader::from_slice(slice).map(|reader| reader.to_entity()) } fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> { BlockHashEntryVecReader::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 BlockHashEntryVecReader<'r>(&'r [u8]); impl<'r> ::core::fmt::LowerHex for BlockHashEntryVecReader<'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 BlockHashEntryVecReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl<'r> ::core::fmt::Display for BlockHashEntryVecReader<'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> BlockHashEntryVecReader<'r> { pub const ITEM_SIZE: usize = 40; pub fn total_size(&self) -> usize { molecule::NUMBER_SIZE + Self::ITEM_SIZE * self.item_count() } pub fn item_count(&self) -> usize { molecule::unpack_number(self.as_slice()) as usize } pub fn len(&self) -> usize { self.item_count() } pub fn is_empty(&self) -> bool { self.len() == 0 } pub fn get(&self, idx: usize) -> Option<BlockHashEntryReader<'r>> { if idx >= self.len() { None } else { Some(self.get_unchecked(idx)) } } pub fn get_unchecked(&self, idx: usize) -> BlockHashEntryReader<'r> { let start = molecule::NUMBER_SIZE + Self::ITEM_SIZE * idx; let end = start + Self::ITEM_SIZE; BlockHashEntryReader::new_unchecked(&self.as_slice()[start..end]) } } impl<'r> molecule::prelude::Reader<'r> for BlockHashEntryVecReader<'r> { type Entity = BlockHashEntryVec; const NAME: &'static str = "BlockHashEntryVecReader"; fn to_entity(&self) -> Self::Entity { Self::Entity::new_unchecked(self.as_slice().to_owned().into()) } fn new_unchecked(slice: &'r [u8]) -> Self { BlockHashEntryVecReader(slice) } fn as_slice(&self) -> &'r [u8] { self.0 } fn verify(slice: &[u8], _compatible: bool) -> molecule::error::VerificationResult<()> { use molecule::verification_error as ve; let slice_len = slice.len(); if slice_len < molecule::NUMBER_SIZE { return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE, slice_len); } let item_count = molecule::unpack_number(slice) as usize; if item_count == 0 { if slice_len != molecule::NUMBER_SIZE { return ve!(Self, TotalSizeNotMatch, molecule::NUMBER_SIZE, slice_len); } return Ok(()); } let total_size = molecule::NUMBER_SIZE + Self::ITEM_SIZE * item_count; if slice_len != total_size { return ve!(Self, TotalSizeNotMatch, total_size, slice_len); } Ok(()) } } #[derive(Debug, Default)] pub struct BlockHashEntryVecBuilder(pub(crate) Vec<BlockHashEntry>); impl BlockHashEntryVecBuilder { pub const ITEM_SIZE: usize = 40; pub fn set(mut self, v: Vec<BlockHashEntry>) -> Self { self.0 = v; self } pub fn push(mut self, v: BlockHashEntry) -> Self { self.0.push(v); self } pub fn extend<T: ::core::iter::IntoIterator<Item = BlockHashEntry>>(mut self, iter: T) -> Self { for elem in iter { self.0.push(elem); } self } } impl molecule::prelude::Builder for BlockHashEntryVecBuilder { type Entity = BlockHashEntryVec; const NAME: &'static str = "BlockHashEntryVecBuilder"; fn expected_length(&self) -> usize { molecule::NUMBER_SIZE + Self::ITEM_SIZE * self.0.len() } fn write<W: molecule::io::Write>(&self, writer: &mut W) -> molecule::io::Result<()> { writer.write_all(&molecule::pack_number(self.0.len() as molecule::Number))?; for inner in &self.0[..] { writer.write_all(inner.as_slice())?; } Ok(()) } fn build(&self) -> Self::Entity { let mut inner = Vec::with_capacity(self.expected_length()); self.write(&mut inner) .unwrap_or_else(|_| panic!("{} build should be ok", Self::NAME)); BlockHashEntryVec::new_unchecked(inner.into()) } } pub struct BlockHashEntryVecIterator(BlockHashEntryVec, usize, usize); impl ::core::iter::Iterator for BlockHashEntryVecIterator { type Item = BlockHashEntry; 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 BlockHashEntryVecIterator { fn len(&self) -> usize { self.2 - self.1 } } impl ::core::iter::IntoIterator for BlockHashEntryVec { type Item = BlockHashEntry; type IntoIter = BlockHashEntryVecIterator; fn into_iter(self) -> Self::IntoIter { let len = self.len(); BlockHashEntryVecIterator(self, 0, len) } } impl<'r> BlockHashEntryVecReader<'r> { pub fn iter<'t>(&'t self) -> BlockHashEntryVecReaderIterator<'t, 'r> { BlockHashEntryVecReaderIterator(&self, 0, self.len()) } } pub struct BlockHashEntryVecReaderIterator<'t, 'r>(&'t BlockHashEntryVecReader<'r>, usize, usize); impl<'t: 'r, 'r> ::core::iter::Iterator for BlockHashEntryVecReaderIterator<'t, 'r> { type Item = BlockHashEntryReader<'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 BlockHashEntryVecReaderIterator<'t, 'r> { fn len(&self) -> usize { self.2 - self.1 } } #[derive(Clone)] pub struct VerifyTransactionContext(molecule::bytes::Bytes); impl ::core::fmt::LowerHex for VerifyTransactionContext { 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 VerifyTransactionContext { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl ::core::fmt::Display for VerifyTransactionContext { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; write!(f, "{}: {}", "account_count", self.account_count())?; write!(f, ", {}: {}", "kv_state", self.kv_state())?; write!(f, ", {}: {}", "load_data", self.load_data())?; write!(f, ", {}: {}", "scripts", self.scripts())?; write!(f, ", {}: {}", "return_data_hash", self.return_data_hash())?; write!(f, ", {}: {}", "block_hashes", self.block_hashes())?; let extra_count = self.count_extra_fields(); if extra_count != 0 { write!(f, ", .. ({} fields)", extra_count)?; } write!(f, " }}") } } impl ::core::default::Default for VerifyTransactionContext { fn default() -> Self { let v: Vec<u8> = vec![ 80, 0, 0, 0, 28, 0, 0, 0, 32, 0, 0, 0, 36, 0, 0, 0, 40, 0, 0, 0, 44, 0, 0, 0, 76, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 4, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ]; VerifyTransactionContext::new_unchecked(v.into()) } } impl VerifyTransactionContext { pub const FIELD_COUNT: usize = 6; 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 account_count(&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 kv_state(&self) -> KVPairVec { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[8..]) as usize; let end = molecule::unpack_number(&slice[12..]) as usize; KVPairVec::new_unchecked(self.0.slice(start..end)) } pub fn load_data(&self) -> BytesVec { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[12..]) as usize; let end = molecule::unpack_number(&slice[16..]) as usize; BytesVec::new_unchecked(self.0.slice(start..end)) } pub fn scripts(&self) -> ScriptVec { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[16..]) as usize; let end = molecule::unpack_number(&slice[20..]) as usize; ScriptVec::new_unchecked(self.0.slice(start..end)) } pub fn return_data_hash(&self) -> Byte32 { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[20..]) as usize; let end = molecule::unpack_number(&slice[24..]) as usize; Byte32::new_unchecked(self.0.slice(start..end)) } pub fn block_hashes(&self) -> BlockHashEntryVec { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[24..]) as usize; if self.has_extra_fields() { let end = molecule::unpack_number(&slice[28..]) as usize; BlockHashEntryVec::new_unchecked(self.0.slice(start..end)) } else { BlockHashEntryVec::new_unchecked(self.0.slice(start..)) } } pub fn as_reader<'r>(&'r self) -> VerifyTransactionContextReader<'r> { VerifyTransactionContextReader::new_unchecked(self.as_slice()) } } impl molecule::prelude::Entity for VerifyTransactionContext { type Builder = VerifyTransactionContextBuilder; const NAME: &'static str = "VerifyTransactionContext"; fn new_unchecked(data: molecule::bytes::Bytes) -> Self { VerifyTransactionContext(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> { VerifyTransactionContextReader::from_slice(slice).map(|reader| reader.to_entity()) } fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> { VerifyTransactionContextReader::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() .account_count(self.account_count()) .kv_state(self.kv_state()) .load_data(self.load_data()) .scripts(self.scripts()) .return_data_hash(self.return_data_hash()) .block_hashes(self.block_hashes()) } } #[derive(Clone, Copy)] pub struct VerifyTransactionContextReader<'r>(&'r [u8]); impl<'r> ::core::fmt::LowerHex for VerifyTransactionContextReader<'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 VerifyTransactionContextReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl<'r> ::core::fmt::Display for VerifyTransactionContextReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; write!(f, "{}: {}", "account_count", self.account_count())?; write!(f, ", {}: {}", "kv_state", self.kv_state())?; write!(f, ", {}: {}", "load_data", self.load_data())?; write!(f, ", {}: {}", "scripts", self.scripts())?; write!(f, ", {}: {}", "return_data_hash", self.return_data_hash())?; write!(f, ", {}: {}", "block_hashes", self.block_hashes())?; let extra_count = self.count_extra_fields(); if extra_count != 0 { write!(f, ", .. ({} fields)", extra_count)?; } write!(f, " }}") } } impl<'r> VerifyTransactionContextReader<'r> { pub const FIELD_COUNT: usize = 6; 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 account_count(&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 kv_state(&self) -> KVPairVecReader<'r> { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[8..]) as usize; let end = molecule::unpack_number(&slice[12..]) as usize; KVPairVecReader::new_unchecked(&self.as_slice()[start..end]) } pub fn load_data(&self) -> BytesVecReader<'r> { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[12..]) as usize; let end = molecule::unpack_number(&slice[16..]) as usize; BytesVecReader::new_unchecked(&self.as_slice()[start..end]) } pub fn scripts(&self) -> ScriptVecReader<'r> { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[16..]) as usize; let end = molecule::unpack_number(&slice[20..]) as usize; ScriptVecReader::new_unchecked(&self.as_slice()[start..end]) } pub fn return_data_hash(&self) -> Byte32Reader<'r> { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[20..]) as usize; let end = molecule::unpack_number(&slice[24..]) as usize; Byte32Reader::new_unchecked(&self.as_slice()[start..end]) } pub fn block_hashes(&self) -> BlockHashEntryVecReader<'r> { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[24..]) as usize; if self.has_extra_fields() { let end = molecule::unpack_number(&slice[28..]) as usize; BlockHashEntryVecReader::new_unchecked(&self.as_slice()[start..end]) } else { BlockHashEntryVecReader::new_unchecked(&self.as_slice()[start..]) } } } impl<'r> molecule::prelude::Reader<'r> for VerifyTransactionContextReader<'r> { type Entity = VerifyTransactionContext; const NAME: &'static str = "VerifyTransactionContextReader"; fn to_entity(&self) -> Self::Entity { Self::Entity::new_unchecked(self.as_slice().to_owned().into()) } fn new_unchecked(slice: &'r [u8]) -> Self { VerifyTransactionContextReader(slice) } fn as_slice(&self) -> &'r [u8] { self.0 } fn verify(slice: &[u8], compatible: bool) -> molecule::error::VerificationResult<()> { use molecule::verification_error as ve; let slice_len = slice.len(); if slice_len < molecule::NUMBER_SIZE { return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE, slice_len); } let total_size = molecule::unpack_number(slice) as usize; if slice_len != total_size { return ve!(Self, TotalSizeNotMatch, total_size, slice_len); } if slice_len == molecule::NUMBER_SIZE && Self::FIELD_COUNT == 0 { return Ok(()); } if slice_len < molecule::NUMBER_SIZE * 2 { return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE * 2, slice_len); } let offset_first = molecule::unpack_number(&slice[molecule::NUMBER_SIZE..]) as usize; if offset_first % molecule::NUMBER_SIZE != 0 || offset_first < molecule::NUMBER_SIZE * 2 { return ve!(Self, OffsetsNotMatch); } if slice_len < offset_first { return ve!(Self, HeaderIsBroken, offset_first, slice_len); } let field_count = offset_first / molecule::NUMBER_SIZE - 1; if field_count < Self::FIELD_COUNT { return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, field_count); } else if !compatible && field_count > Self::FIELD_COUNT { return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, field_count); }; let mut offsets: Vec<usize> = slice[molecule::NUMBER_SIZE..offset_first] .chunks_exact(molecule::NUMBER_SIZE) .map(|x| molecule::unpack_number(x) as usize) .collect(); offsets.push(total_size); if offsets.windows(2).any(|i| i[0] > i[1]) { return ve!(Self, OffsetsNotMatch); } Uint32Reader::verify(&slice[offsets[0]..offsets[1]], compatible)?; KVPairVecReader::verify(&slice[offsets[1]..offsets[2]], compatible)?; BytesVecReader::verify(&slice[offsets[2]..offsets[3]], compatible)?; ScriptVecReader::verify(&slice[offsets[3]..offsets[4]], compatible)?; Byte32Reader::verify(&slice[offsets[4]..offsets[5]], compatible)?; BlockHashEntryVecReader::verify(&slice[offsets[5]..offsets[6]], compatible)?; Ok(()) } } #[derive(Debug, Default)] pub struct VerifyTransactionContextBuilder { pub(crate) account_count: Uint32, pub(crate) kv_state: KVPairVec, pub(crate) load_data: BytesVec, pub(crate) scripts: ScriptVec, pub(crate) return_data_hash: Byte32, pub(crate) block_hashes: BlockHashEntryVec, } impl VerifyTransactionContextBuilder { pub const FIELD_COUNT: usize = 6; pub fn account_count(mut self, v: Uint32) -> Self { self.account_count = v; self } pub fn kv_state(mut self, v: KVPairVec) -> Self { self.kv_state = v; self } pub fn load_data(mut self, v: BytesVec) -> Self { self.load_data = v; self } pub fn scripts(mut self, v: ScriptVec) -> Self { self.scripts = v; self } pub fn return_data_hash(mut self, v: Byte32) -> Self { self.return_data_hash = v; self } pub fn block_hashes(mut self, v: BlockHashEntryVec) -> Self { self.block_hashes = v; self } } impl molecule::prelude::Builder for VerifyTransactionContextBuilder { type Entity = VerifyTransactionContext; const NAME: &'static str = "VerifyTransactionContextBuilder"; fn expected_length(&self) -> usize { molecule::NUMBER_SIZE * (Self::FIELD_COUNT + 1) + self.account_count.as_slice().len() + self.kv_state.as_slice().len() + self.load_data.as_slice().len() + self.scripts.as_slice().len() + self.return_data_hash.as_slice().len() + self.block_hashes.as_slice().len() } fn write<W: molecule::io::Write>(&self, writer: &mut W) -> molecule::io::Result<()> { let mut total_size = molecule::NUMBER_SIZE * (Self::FIELD_COUNT + 1); let mut offsets = Vec::with_capacity(Self::FIELD_COUNT); offsets.push(total_size); total_size += self.account_count.as_slice().len(); offsets.push(total_size); total_size += self.kv_state.as_slice().len(); offsets.push(total_size); total_size += self.load_data.as_slice().len(); offsets.push(total_size); total_size += self.scripts.as_slice().len(); offsets.push(total_size); total_size += self.return_data_hash.as_slice().len(); offsets.push(total_size); total_size += self.block_hashes.as_slice().len(); writer.write_all(&molecule::pack_number(total_size as molecule::Number))?; for offset in offsets.into_iter() { writer.write_all(&molecule::pack_number(offset as molecule::Number))?; } writer.write_all(self.account_count.as_slice())?; writer.write_all(self.kv_state.as_slice())?; writer.write_all(self.load_data.as_slice())?; writer.write_all(self.scripts.as_slice())?; writer.write_all(self.return_data_hash.as_slice())?; writer.write_all(self.block_hashes.as_slice())?; Ok(()) } fn build(&self) -> Self::Entity { let mut inner = Vec::with_capacity(self.expected_length()); self.write(&mut inner) .unwrap_or_else(|_| panic!("{} build should be ok", Self::NAME)); VerifyTransactionContext::new_unchecked(inner.into()) } } #[derive(Clone)] pub struct CKBMerkleProof(molecule::bytes::Bytes); impl ::core::fmt::LowerHex for CKBMerkleProof { 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 CKBMerkleProof { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl ::core::fmt::Display for CKBMerkleProof { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; write!(f, "{}: {}", "indices", self.indices())?; write!(f, ", {}: {}", "lemmas", self.lemmas())?; let extra_count = self.count_extra_fields(); if extra_count != 0 { write!(f, ", .. ({} fields)", extra_count)?; } write!(f, " }}") } } impl ::core::default::Default for CKBMerkleProof { fn default() -> Self { let v: Vec<u8> = vec![ 20, 0, 0, 0, 12, 0, 0, 0, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ]; CKBMerkleProof::new_unchecked(v.into()) } } impl CKBMerkleProof { 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 indices(&self) -> Uint32Vec { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[4..]) as usize; let end = molecule::unpack_number(&slice[8..]) as usize; Uint32Vec::new_unchecked(self.0.slice(start..end)) } pub fn lemmas(&self) -> Byte32Vec { 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; Byte32Vec::new_unchecked(self.0.slice(start..end)) } else { Byte32Vec::new_unchecked(self.0.slice(start..)) } } pub fn as_reader<'r>(&'r self) -> CKBMerkleProofReader<'r> { CKBMerkleProofReader::new_unchecked(self.as_slice()) } } impl molecule::prelude::Entity for CKBMerkleProof { type Builder = CKBMerkleProofBuilder; const NAME: &'static str = "CKBMerkleProof"; fn new_unchecked(data: molecule::bytes::Bytes) -> Self { CKBMerkleProof(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> { CKBMerkleProofReader::from_slice(slice).map(|reader| reader.to_entity()) } fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> { CKBMerkleProofReader::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() .indices(self.indices()) .lemmas(self.lemmas()) } } #[derive(Clone, Copy)] pub struct CKBMerkleProofReader<'r>(&'r [u8]); impl<'r> ::core::fmt::LowerHex for CKBMerkleProofReader<'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 CKBMerkleProofReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl<'r> ::core::fmt::Display for CKBMerkleProofReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; write!(f, "{}: {}", "indices", self.indices())?; write!(f, ", {}: {}", "lemmas", self.lemmas())?; let extra_count = self.count_extra_fields(); if extra_count != 0 { write!(f, ", .. ({} fields)", extra_count)?; } write!(f, " }}") } } impl<'r> CKBMerkleProofReader<'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 indices(&self) -> Uint32VecReader<'r> { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[4..]) as usize; let end = molecule::unpack_number(&slice[8..]) as usize; Uint32VecReader::new_unchecked(&self.as_slice()[start..end]) } pub fn lemmas(&self) -> Byte32VecReader<'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; Byte32VecReader::new_unchecked(&self.as_slice()[start..end]) } else { Byte32VecReader::new_unchecked(&self.as_slice()[start..]) } } } impl<'r> molecule::prelude::Reader<'r> for CKBMerkleProofReader<'r> { type Entity = CKBMerkleProof; const NAME: &'static str = "CKBMerkleProofReader"; fn to_entity(&self) -> Self::Entity { Self::Entity::new_unchecked(self.as_slice().to_owned().into()) } fn new_unchecked(slice: &'r [u8]) -> Self { CKBMerkleProofReader(slice) } fn as_slice(&self) -> &'r [u8] { self.0 } fn verify(slice: &[u8], compatible: bool) -> molecule::error::VerificationResult<()> { use molecule::verification_error as ve; let slice_len = slice.len(); if slice_len < molecule::NUMBER_SIZE { return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE, slice_len); } let total_size = molecule::unpack_number(slice) as usize; if slice_len != total_size { return ve!(Self, TotalSizeNotMatch, total_size, slice_len); } if slice_len == molecule::NUMBER_SIZE && Self::FIELD_COUNT == 0 { return Ok(()); } if slice_len < molecule::NUMBER_SIZE * 2 { return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE * 2, slice_len); } let offset_first = molecule::unpack_number(&slice[molecule::NUMBER_SIZE..]) as usize; if offset_first % molecule::NUMBER_SIZE != 0 || offset_first < molecule::NUMBER_SIZE * 2 { return ve!(Self, OffsetsNotMatch); } if slice_len < offset_first { return ve!(Self, HeaderIsBroken, offset_first, slice_len); } let field_count = offset_first / molecule::NUMBER_SIZE - 1; if field_count < Self::FIELD_COUNT { return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, field_count); } else if !compatible && field_count > Self::FIELD_COUNT { return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, field_count); }; let mut offsets: Vec<usize> = slice[molecule::NUMBER_SIZE..offset_first] .chunks_exact(molecule::NUMBER_SIZE) .map(|x| molecule::unpack_number(x) as usize) .collect(); offsets.push(total_size); if offsets.windows(2).any(|i| i[0] > i[1]) { return ve!(Self, OffsetsNotMatch); } Uint32VecReader::verify(&slice[offsets[0]..offsets[1]], compatible)?; Byte32VecReader::verify(&slice[offsets[1]..offsets[2]], compatible)?; Ok(()) } } #[derive(Debug, Default)] pub struct CKBMerkleProofBuilder { pub(crate) indices: Uint32Vec, pub(crate) lemmas: Byte32Vec, } impl CKBMerkleProofBuilder { pub const FIELD_COUNT: usize = 2; pub fn indices(mut self, v: Uint32Vec) -> Self { self.indices = v; self } pub fn lemmas(mut self, v: Byte32Vec) -> Self { self.lemmas = v; self } } impl molecule::prelude::Builder for CKBMerkleProofBuilder { type Entity = CKBMerkleProof; const NAME: &'static str = "CKBMerkleProofBuilder"; fn expected_length(&self) -> usize { molecule::NUMBER_SIZE * (Self::FIELD_COUNT + 1) + self.indices.as_slice().len() + self.lemmas.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.indices.as_slice().len(); offsets.push(total_size); total_size += self.lemmas.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.indices.as_slice())?; writer.write_all(self.lemmas.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)); CKBMerkleProof::new_unchecked(inner.into()) } } #[derive(Clone)] pub struct VerifyTransactionWitness(molecule::bytes::Bytes); impl ::core::fmt::LowerHex for VerifyTransactionWitness { 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 VerifyTransactionWitness { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl ::core::fmt::Display for VerifyTransactionWitness { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; write!(f, "{}: {}", "l2tx", self.l2tx())?; write!(f, ", {}: {}", "raw_l2block", self.raw_l2block())?; write!(f, ", {}: {}", "tx_proof", self.tx_proof())?; write!(f, ", {}: {}", "kv_state_proof", self.kv_state_proof())?; write!( f, ", {}: {}", "block_hashes_proof", self.block_hashes_proof() )?; write!(f, ", {}: {}", "context", self.context())?; let extra_count = self.count_extra_fields(); if extra_count != 0 { write!(f, ", .. ({} fields)", extra_count)?; } write!(f, " }}") } } impl ::core::default::Default for VerifyTransactionWitness { fn default() -> Self { let v: Vec<u8> = vec![ 0, 2, 0, 0, 28, 0, 0, 0, 80, 0, 0, 0, 148, 1, 0, 0, 168, 1, 0, 0, 172, 1, 0, 0, 176, 1, 0, 0, 52, 0, 0, 0, 12, 0, 0, 0, 48, 0, 0, 0, 36, 0, 0, 0, 20, 0, 0, 0, 24, 0, 0, 0, 28, 0, 0, 0, 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 68, 1, 0, 0, 44, 0, 0, 0, 52, 0, 0, 0, 56, 0, 0, 0, 88, 0, 0, 0, 120, 0, 0, 0, 128, 0, 0, 0, 164, 0, 0, 0, 200, 0, 0, 0, 204, 0, 0, 0, 240, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 84, 0, 0, 0, 16, 0, 0, 0, 48, 0, 0, 0, 52, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 20, 0, 0, 0, 12, 0, 0, 0, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 80, 0, 0, 0, 28, 0, 0, 0, 32, 0, 0, 0, 36, 0, 0, 0, 40, 0, 0, 0, 44, 0, 0, 0, 76, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 4, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ]; VerifyTransactionWitness::new_unchecked(v.into()) } } impl VerifyTransactionWitness { pub const FIELD_COUNT: usize = 6; 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 l2tx(&self) -> L2Transaction { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[4..]) as usize; let end = molecule::unpack_number(&slice[8..]) as usize; L2Transaction::new_unchecked(self.0.slice(start..end)) } pub fn raw_l2block(&self) -> RawL2Block { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[8..]) as usize; let end = molecule::unpack_number(&slice[12..]) as usize; RawL2Block::new_unchecked(self.0.slice(start..end)) } pub fn tx_proof(&self) -> CKBMerkleProof { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[12..]) as usize; let end = molecule::unpack_number(&slice[16..]) as usize; CKBMerkleProof::new_unchecked(self.0.slice(start..end)) } pub fn kv_state_proof(&self) -> Bytes { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[16..]) as usize; let end = molecule::unpack_number(&slice[20..]) as usize; Bytes::new_unchecked(self.0.slice(start..end)) } pub fn block_hashes_proof(&self) -> Bytes { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[20..]) as usize; let end = molecule::unpack_number(&slice[24..]) as usize; Bytes::new_unchecked(self.0.slice(start..end)) } pub fn context(&self) -> VerifyTransactionContext { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[24..]) as usize; if self.has_extra_fields() { let end = molecule::unpack_number(&slice[28..]) as usize; VerifyTransactionContext::new_unchecked(self.0.slice(start..end)) } else { VerifyTransactionContext::new_unchecked(self.0.slice(start..)) } } pub fn as_reader<'r>(&'r self) -> VerifyTransactionWitnessReader<'r> { VerifyTransactionWitnessReader::new_unchecked(self.as_slice()) } } impl molecule::prelude::Entity for VerifyTransactionWitness { type Builder = VerifyTransactionWitnessBuilder; const NAME: &'static str = "VerifyTransactionWitness"; fn new_unchecked(data: molecule::bytes::Bytes) -> Self { VerifyTransactionWitness(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> { VerifyTransactionWitnessReader::from_slice(slice).map(|reader| reader.to_entity()) } fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> { VerifyTransactionWitnessReader::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() .l2tx(self.l2tx()) .raw_l2block(self.raw_l2block()) .tx_proof(self.tx_proof()) .kv_state_proof(self.kv_state_proof()) .block_hashes_proof(self.block_hashes_proof()) .context(self.context()) } } #[derive(Clone, Copy)] pub struct VerifyTransactionWitnessReader<'r>(&'r [u8]); impl<'r> ::core::fmt::LowerHex for VerifyTransactionWitnessReader<'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 VerifyTransactionWitnessReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl<'r> ::core::fmt::Display for VerifyTransactionWitnessReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; write!(f, "{}: {}", "l2tx", self.l2tx())?; write!(f, ", {}: {}", "raw_l2block", self.raw_l2block())?; write!(f, ", {}: {}", "tx_proof", self.tx_proof())?; write!(f, ", {}: {}", "kv_state_proof", self.kv_state_proof())?; write!( f, ", {}: {}", "block_hashes_proof", self.block_hashes_proof() )?; write!(f, ", {}: {}", "context", self.context())?; let extra_count = self.count_extra_fields(); if extra_count != 0 { write!(f, ", .. ({} fields)", extra_count)?; } write!(f, " }}") } } impl<'r> VerifyTransactionWitnessReader<'r> { pub const FIELD_COUNT: usize = 6; 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 l2tx(&self) -> L2TransactionReader<'r> { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[4..]) as usize; let end = molecule::unpack_number(&slice[8..]) as usize; L2TransactionReader::new_unchecked(&self.as_slice()[start..end]) } pub fn raw_l2block(&self) -> RawL2BlockReader<'r> { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[8..]) as usize; let end = molecule::unpack_number(&slice[12..]) as usize; RawL2BlockReader::new_unchecked(&self.as_slice()[start..end]) } pub fn tx_proof(&self) -> CKBMerkleProofReader<'r> { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[12..]) as usize; let end = molecule::unpack_number(&slice[16..]) as usize; CKBMerkleProofReader::new_unchecked(&self.as_slice()[start..end]) } pub fn kv_state_proof(&self) -> BytesReader<'r> { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[16..]) as usize; let end = molecule::unpack_number(&slice[20..]) as usize; BytesReader::new_unchecked(&self.as_slice()[start..end]) } pub fn block_hashes_proof(&self) -> BytesReader<'r> { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[20..]) as usize; let end = molecule::unpack_number(&slice[24..]) as usize; BytesReader::new_unchecked(&self.as_slice()[start..end]) } pub fn context(&self) -> VerifyTransactionContextReader<'r> { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[24..]) as usize; if self.has_extra_fields() { let end = molecule::unpack_number(&slice[28..]) as usize; VerifyTransactionContextReader::new_unchecked(&self.as_slice()[start..end]) } else { VerifyTransactionContextReader::new_unchecked(&self.as_slice()[start..]) } } } impl<'r> molecule::prelude::Reader<'r> for VerifyTransactionWitnessReader<'r> { type Entity = VerifyTransactionWitness; const NAME: &'static str = "VerifyTransactionWitnessReader"; fn to_entity(&self) -> Self::Entity { Self::Entity::new_unchecked(self.as_slice().to_owned().into()) } fn new_unchecked(slice: &'r [u8]) -> Self { VerifyTransactionWitnessReader(slice) } fn as_slice(&self) -> &'r [u8] { self.0 } fn verify(slice: &[u8], compatible: bool) -> molecule::error::VerificationResult<()> { use molecule::verification_error as ve; let slice_len = slice.len(); if slice_len < molecule::NUMBER_SIZE { return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE, slice_len); } let total_size = molecule::unpack_number(slice) as usize; if slice_len != total_size { return ve!(Self, TotalSizeNotMatch, total_size, slice_len); } if slice_len == molecule::NUMBER_SIZE && Self::FIELD_COUNT == 0 { return Ok(()); } if slice_len < molecule::NUMBER_SIZE * 2 { return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE * 2, slice_len); } let offset_first = molecule::unpack_number(&slice[molecule::NUMBER_SIZE..]) as usize; if offset_first % molecule::NUMBER_SIZE != 0 || offset_first < molecule::NUMBER_SIZE * 2 { return ve!(Self, OffsetsNotMatch); } if slice_len < offset_first { return ve!(Self, HeaderIsBroken, offset_first, slice_len); } let field_count = offset_first / molecule::NUMBER_SIZE - 1; if field_count < Self::FIELD_COUNT { return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, field_count); } else if !compatible && field_count > Self::FIELD_COUNT { return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, field_count); }; let mut offsets: Vec<usize> = slice[molecule::NUMBER_SIZE..offset_first] .chunks_exact(molecule::NUMBER_SIZE) .map(|x| molecule::unpack_number(x) as usize) .collect(); offsets.push(total_size); if offsets.windows(2).any(|i| i[0] > i[1]) { return ve!(Self, OffsetsNotMatch); } L2TransactionReader::verify(&slice[offsets[0]..offsets[1]], compatible)?; RawL2BlockReader::verify(&slice[offsets[1]..offsets[2]], compatible)?; CKBMerkleProofReader::verify(&slice[offsets[2]..offsets[3]], compatible)?; BytesReader::verify(&slice[offsets[3]..offsets[4]], compatible)?; BytesReader::verify(&slice[offsets[4]..offsets[5]], compatible)?; VerifyTransactionContextReader::verify(&slice[offsets[5]..offsets[6]], compatible)?; Ok(()) } } #[derive(Debug, Default)] pub struct VerifyTransactionWitnessBuilder { pub(crate) l2tx: L2Transaction, pub(crate) raw_l2block: RawL2Block, pub(crate) tx_proof: CKBMerkleProof, pub(crate) kv_state_proof: Bytes, pub(crate) block_hashes_proof: Bytes, pub(crate) context: VerifyTransactionContext, } impl VerifyTransactionWitnessBuilder { pub const FIELD_COUNT: usize = 6; pub fn l2tx(mut self, v: L2Transaction) -> Self { self.l2tx = v; self } pub fn raw_l2block(mut self, v: RawL2Block) -> Self { self.raw_l2block = v; self } pub fn tx_proof(mut self, v: CKBMerkleProof) -> Self { self.tx_proof = v; self } pub fn kv_state_proof(mut self, v: Bytes) -> Self { self.kv_state_proof = v; self } pub fn block_hashes_proof(mut self, v: Bytes) -> Self { self.block_hashes_proof = v; self } pub fn context(mut self, v: VerifyTransactionContext) -> Self { self.context = v; self } } impl molecule::prelude::Builder for VerifyTransactionWitnessBuilder { type Entity = VerifyTransactionWitness; const NAME: &'static str = "VerifyTransactionWitnessBuilder"; fn expected_length(&self) -> usize { molecule::NUMBER_SIZE * (Self::FIELD_COUNT + 1) + self.l2tx.as_slice().len() + self.raw_l2block.as_slice().len() + self.tx_proof.as_slice().len() + self.kv_state_proof.as_slice().len() + self.block_hashes_proof.as_slice().len() + self.context.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.l2tx.as_slice().len(); offsets.push(total_size); total_size += self.raw_l2block.as_slice().len(); offsets.push(total_size); total_size += self.tx_proof.as_slice().len(); offsets.push(total_size); total_size += self.kv_state_proof.as_slice().len(); offsets.push(total_size); total_size += self.block_hashes_proof.as_slice().len(); offsets.push(total_size); total_size += self.context.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.l2tx.as_slice())?; writer.write_all(self.raw_l2block.as_slice())?; writer.write_all(self.tx_proof.as_slice())?; writer.write_all(self.kv_state_proof.as_slice())?; writer.write_all(self.block_hashes_proof.as_slice())?; writer.write_all(self.context.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)); VerifyTransactionWitness::new_unchecked(inner.into()) } } #[derive(Clone)] pub struct VerifyTransactionSignatureContext(molecule::bytes::Bytes); impl ::core::fmt::LowerHex for VerifyTransactionSignatureContext { 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 VerifyTransactionSignatureContext { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl ::core::fmt::Display for VerifyTransactionSignatureContext { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; write!(f, "{}: {}", "account_count", self.account_count())?; write!(f, ", {}: {}", "kv_state", self.kv_state())?; write!(f, ", {}: {}", "scripts", self.scripts())?; let extra_count = self.count_extra_fields(); if extra_count != 0 { write!(f, ", .. ({} fields)", extra_count)?; } write!(f, " }}") } } impl ::core::default::Default for VerifyTransactionSignatureContext { fn default() -> Self { let v: Vec<u8> = vec![ 28, 0, 0, 0, 16, 0, 0, 0, 20, 0, 0, 0, 24, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 4, 0, 0, 0, ]; VerifyTransactionSignatureContext::new_unchecked(v.into()) } } impl VerifyTransactionSignatureContext { 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 account_count(&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 kv_state(&self) -> KVPairVec { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[8..]) as usize; let end = molecule::unpack_number(&slice[12..]) as usize; KVPairVec::new_unchecked(self.0.slice(start..end)) } pub fn scripts(&self) -> ScriptVec { 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; ScriptVec::new_unchecked(self.0.slice(start..end)) } else { ScriptVec::new_unchecked(self.0.slice(start..)) } } pub fn as_reader<'r>(&'r self) -> VerifyTransactionSignatureContextReader<'r> { VerifyTransactionSignatureContextReader::new_unchecked(self.as_slice()) } } impl molecule::prelude::Entity for VerifyTransactionSignatureContext { type Builder = VerifyTransactionSignatureContextBuilder; const NAME: &'static str = "VerifyTransactionSignatureContext"; fn new_unchecked(data: molecule::bytes::Bytes) -> Self { VerifyTransactionSignatureContext(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> { VerifyTransactionSignatureContextReader::from_slice(slice).map(|reader| reader.to_entity()) } fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> { VerifyTransactionSignatureContextReader::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() .account_count(self.account_count()) .kv_state(self.kv_state()) .scripts(self.scripts()) } } #[derive(Clone, Copy)] pub struct VerifyTransactionSignatureContextReader<'r>(&'r [u8]); impl<'r> ::core::fmt::LowerHex for VerifyTransactionSignatureContextReader<'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 VerifyTransactionSignatureContextReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl<'r> ::core::fmt::Display for VerifyTransactionSignatureContextReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; write!(f, "{}: {}", "account_count", self.account_count())?; write!(f, ", {}: {}", "kv_state", self.kv_state())?; write!(f, ", {}: {}", "scripts", self.scripts())?; let extra_count = self.count_extra_fields(); if extra_count != 0 { write!(f, ", .. ({} fields)", extra_count)?; } write!(f, " }}") } } impl<'r> VerifyTransactionSignatureContextReader<'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 account_count(&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 kv_state(&self) -> KVPairVecReader<'r> { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[8..]) as usize; let end = molecule::unpack_number(&slice[12..]) as usize; KVPairVecReader::new_unchecked(&self.as_slice()[start..end]) } pub fn scripts(&self) -> ScriptVecReader<'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; ScriptVecReader::new_unchecked(&self.as_slice()[start..end]) } else { ScriptVecReader::new_unchecked(&self.as_slice()[start..]) } } } impl<'r> molecule::prelude::Reader<'r> for VerifyTransactionSignatureContextReader<'r> { type Entity = VerifyTransactionSignatureContext; const NAME: &'static str = "VerifyTransactionSignatureContextReader"; fn to_entity(&self) -> Self::Entity { Self::Entity::new_unchecked(self.as_slice().to_owned().into()) } fn new_unchecked(slice: &'r [u8]) -> Self { VerifyTransactionSignatureContextReader(slice) } fn as_slice(&self) -> &'r [u8] { self.0 } fn verify(slice: &[u8], compatible: bool) -> molecule::error::VerificationResult<()> { use molecule::verification_error as ve; let slice_len = slice.len(); if slice_len < molecule::NUMBER_SIZE { return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE, slice_len); } let total_size = molecule::unpack_number(slice) as usize; if slice_len != total_size { return ve!(Self, TotalSizeNotMatch, total_size, slice_len); } if slice_len == molecule::NUMBER_SIZE && Self::FIELD_COUNT == 0 { return Ok(()); } if slice_len < molecule::NUMBER_SIZE * 2 { return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE * 2, slice_len); } let offset_first = molecule::unpack_number(&slice[molecule::NUMBER_SIZE..]) as usize; if offset_first % molecule::NUMBER_SIZE != 0 || offset_first < molecule::NUMBER_SIZE * 2 { return ve!(Self, OffsetsNotMatch); } if slice_len < offset_first { return ve!(Self, HeaderIsBroken, offset_first, slice_len); } let field_count = offset_first / molecule::NUMBER_SIZE - 1; if field_count < Self::FIELD_COUNT { return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, field_count); } else if !compatible && field_count > Self::FIELD_COUNT { return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, field_count); }; let mut offsets: Vec<usize> = slice[molecule::NUMBER_SIZE..offset_first] .chunks_exact(molecule::NUMBER_SIZE) .map(|x| molecule::unpack_number(x) as usize) .collect(); offsets.push(total_size); if offsets.windows(2).any(|i| i[0] > i[1]) { return ve!(Self, OffsetsNotMatch); } Uint32Reader::verify(&slice[offsets[0]..offsets[1]], compatible)?; KVPairVecReader::verify(&slice[offsets[1]..offsets[2]], compatible)?; ScriptVecReader::verify(&slice[offsets[2]..offsets[3]], compatible)?; Ok(()) } } #[derive(Debug, Default)] pub struct VerifyTransactionSignatureContextBuilder { pub(crate) account_count: Uint32, pub(crate) kv_state: KVPairVec, pub(crate) scripts: ScriptVec, } impl VerifyTransactionSignatureContextBuilder { pub const FIELD_COUNT: usize = 3; pub fn account_count(mut self, v: Uint32) -> Self { self.account_count = v; self } pub fn kv_state(mut self, v: KVPairVec) -> Self { self.kv_state = v; self } pub fn scripts(mut self, v: ScriptVec) -> Self { self.scripts = v; self } } impl molecule::prelude::Builder for VerifyTransactionSignatureContextBuilder { type Entity = VerifyTransactionSignatureContext; const NAME: &'static str = "VerifyTransactionSignatureContextBuilder"; fn expected_length(&self) -> usize { molecule::NUMBER_SIZE * (Self::FIELD_COUNT + 1) + self.account_count.as_slice().len() + self.kv_state.as_slice().len() + self.scripts.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.account_count.as_slice().len(); offsets.push(total_size); total_size += self.kv_state.as_slice().len(); offsets.push(total_size); total_size += self.scripts.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.account_count.as_slice())?; writer.write_all(self.kv_state.as_slice())?; writer.write_all(self.scripts.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)); VerifyTransactionSignatureContext::new_unchecked(inner.into()) } } #[derive(Clone)] pub struct VerifyTransactionSignatureWitness(molecule::bytes::Bytes); impl ::core::fmt::LowerHex for VerifyTransactionSignatureWitness { 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 VerifyTransactionSignatureWitness { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl ::core::fmt::Display for VerifyTransactionSignatureWitness { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; write!(f, "{}: {}", "raw_l2block", self.raw_l2block())?; write!(f, ", {}: {}", "l2tx", self.l2tx())?; write!(f, ", {}: {}", "tx_proof", self.tx_proof())?; write!(f, ", {}: {}", "kv_state_proof", self.kv_state_proof())?; write!(f, ", {}: {}", "context", self.context())?; let extra_count = self.count_extra_fields(); if extra_count != 0 { write!(f, ", .. ({} fields)", extra_count)?; } write!(f, " }}") } } impl ::core::default::Default for VerifyTransactionSignatureWitness { fn default() -> Self { let v: Vec<u8> = vec![ 196, 1, 0, 0, 24, 0, 0, 0, 92, 1, 0, 0, 144, 1, 0, 0, 164, 1, 0, 0, 168, 1, 0, 0, 68, 1, 0, 0, 44, 0, 0, 0, 52, 0, 0, 0, 56, 0, 0, 0, 88, 0, 0, 0, 120, 0, 0, 0, 128, 0, 0, 0, 164, 0, 0, 0, 200, 0, 0, 0, 204, 0, 0, 0, 240, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 84, 0, 0, 0, 16, 0, 0, 0, 48, 0, 0, 0, 52, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 52, 0, 0, 0, 12, 0, 0, 0, 48, 0, 0, 0, 36, 0, 0, 0, 20, 0, 0, 0, 24, 0, 0, 0, 28, 0, 0, 0, 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 20, 0, 0, 0, 12, 0, 0, 0, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 28, 0, 0, 0, 16, 0, 0, 0, 20, 0, 0, 0, 24, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 4, 0, 0, 0, ]; VerifyTransactionSignatureWitness::new_unchecked(v.into()) } } impl VerifyTransactionSignatureWitness { pub const FIELD_COUNT: usize = 5; pub fn total_size(&self) -> usize { molecule::unpack_number(self.as_slice()) as usize } pub fn field_count(&self) -> usize { if self.total_size() == molecule::NUMBER_SIZE { 0 } else { (molecule::unpack_number(&self.as_slice()[molecule::NUMBER_SIZE..]) as usize / 4) - 1 } } pub fn count_extra_fields(&self) -> usize { self.field_count() - Self::FIELD_COUNT } pub fn has_extra_fields(&self) -> bool { Self::FIELD_COUNT != self.field_count() } pub fn raw_l2block(&self) -> RawL2Block { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[4..]) as usize; let end = molecule::unpack_number(&slice[8..]) as usize; RawL2Block::new_unchecked(self.0.slice(start..end)) } pub fn l2tx(&self) -> L2Transaction { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[8..]) as usize; let end = molecule::unpack_number(&slice[12..]) as usize; L2Transaction::new_unchecked(self.0.slice(start..end)) } pub fn tx_proof(&self) -> CKBMerkleProof { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[12..]) as usize; let end = molecule::unpack_number(&slice[16..]) as usize; CKBMerkleProof::new_unchecked(self.0.slice(start..end)) } pub fn kv_state_proof(&self) -> Bytes { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[16..]) as usize; let end = molecule::unpack_number(&slice[20..]) as usize; Bytes::new_unchecked(self.0.slice(start..end)) } pub fn context(&self) -> VerifyTransactionSignatureContext { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[20..]) as usize; if self.has_extra_fields() { let end = molecule::unpack_number(&slice[24..]) as usize; VerifyTransactionSignatureContext::new_unchecked(self.0.slice(start..end)) } else { VerifyTransactionSignatureContext::new_unchecked(self.0.slice(start..)) } } pub fn as_reader<'r>(&'r self) -> VerifyTransactionSignatureWitnessReader<'r> { VerifyTransactionSignatureWitnessReader::new_unchecked(self.as_slice()) } } impl molecule::prelude::Entity for VerifyTransactionSignatureWitness { type Builder = VerifyTransactionSignatureWitnessBuilder; const NAME: &'static str = "VerifyTransactionSignatureWitness"; fn new_unchecked(data: molecule::bytes::Bytes) -> Self { VerifyTransactionSignatureWitness(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> { VerifyTransactionSignatureWitnessReader::from_slice(slice).map(|reader| reader.to_entity()) } fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> { VerifyTransactionSignatureWitnessReader::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() .raw_l2block(self.raw_l2block()) .l2tx(self.l2tx()) .tx_proof(self.tx_proof()) .kv_state_proof(self.kv_state_proof()) .context(self.context()) } } #[derive(Clone, Copy)] pub struct VerifyTransactionSignatureWitnessReader<'r>(&'r [u8]); impl<'r> ::core::fmt::LowerHex for VerifyTransactionSignatureWitnessReader<'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 VerifyTransactionSignatureWitnessReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl<'r> ::core::fmt::Display for VerifyTransactionSignatureWitnessReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; write!(f, "{}: {}", "raw_l2block", self.raw_l2block())?; write!(f, ", {}: {}", "l2tx", self.l2tx())?; write!(f, ", {}: {}", "tx_proof", self.tx_proof())?; write!(f, ", {}: {}", "kv_state_proof", self.kv_state_proof())?; write!(f, ", {}: {}", "context", self.context())?; let extra_count = self.count_extra_fields(); if extra_count != 0 { write!(f, ", .. ({} fields)", extra_count)?; } write!(f, " }}") } } impl<'r> VerifyTransactionSignatureWitnessReader<'r> { pub const FIELD_COUNT: usize = 5; pub fn total_size(&self) -> usize { molecule::unpack_number(self.as_slice()) as usize } pub fn field_count(&self) -> usize { if self.total_size() == molecule::NUMBER_SIZE { 0 } else { (molecule::unpack_number(&self.as_slice()[molecule::NUMBER_SIZE..]) as usize / 4) - 1 } } pub fn count_extra_fields(&self) -> usize { self.field_count() - Self::FIELD_COUNT } pub fn has_extra_fields(&self) -> bool { Self::FIELD_COUNT != self.field_count() } pub fn raw_l2block(&self) -> RawL2BlockReader<'r> { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[4..]) as usize; let end = molecule::unpack_number(&slice[8..]) as usize; RawL2BlockReader::new_unchecked(&self.as_slice()[start..end]) } pub fn l2tx(&self) -> L2TransactionReader<'r> { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[8..]) as usize; let end = molecule::unpack_number(&slice[12..]) as usize; L2TransactionReader::new_unchecked(&self.as_slice()[start..end]) } pub fn tx_proof(&self) -> CKBMerkleProofReader<'r> { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[12..]) as usize; let end = molecule::unpack_number(&slice[16..]) as usize; CKBMerkleProofReader::new_unchecked(&self.as_slice()[start..end]) } pub fn kv_state_proof(&self) -> BytesReader<'r> { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[16..]) as usize; let end = molecule::unpack_number(&slice[20..]) as usize; BytesReader::new_unchecked(&self.as_slice()[start..end]) } pub fn context(&self) -> VerifyTransactionSignatureContextReader<'r> { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[20..]) as usize; if self.has_extra_fields() { let end = molecule::unpack_number(&slice[24..]) as usize; VerifyTransactionSignatureContextReader::new_unchecked(&self.as_slice()[start..end]) } else { VerifyTransactionSignatureContextReader::new_unchecked(&self.as_slice()[start..]) } } } impl<'r> molecule::prelude::Reader<'r> for VerifyTransactionSignatureWitnessReader<'r> { type Entity = VerifyTransactionSignatureWitness; const NAME: &'static str = "VerifyTransactionSignatureWitnessReader"; fn to_entity(&self) -> Self::Entity { Self::Entity::new_unchecked(self.as_slice().to_owned().into()) } fn new_unchecked(slice: &'r [u8]) -> Self { VerifyTransactionSignatureWitnessReader(slice) } fn as_slice(&self) -> &'r [u8] { self.0 } fn verify(slice: &[u8], compatible: bool) -> molecule::error::VerificationResult<()> { use molecule::verification_error as ve; let slice_len = slice.len(); if slice_len < molecule::NUMBER_SIZE { return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE, slice_len); } let total_size = molecule::unpack_number(slice) as usize; if slice_len != total_size { return ve!(Self, TotalSizeNotMatch, total_size, slice_len); } if slice_len == molecule::NUMBER_SIZE && Self::FIELD_COUNT == 0 { return Ok(()); } if slice_len < molecule::NUMBER_SIZE * 2 { return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE * 2, slice_len); } let offset_first = molecule::unpack_number(&slice[molecule::NUMBER_SIZE..]) as usize; if offset_first % molecule::NUMBER_SIZE != 0 || offset_first < molecule::NUMBER_SIZE * 2 { return ve!(Self, OffsetsNotMatch); } if slice_len < offset_first { return ve!(Self, HeaderIsBroken, offset_first, slice_len); } let field_count = offset_first / molecule::NUMBER_SIZE - 1; if field_count < Self::FIELD_COUNT { return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, field_count); } else if !compatible && field_count > Self::FIELD_COUNT { return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, field_count); }; let mut offsets: Vec<usize> = slice[molecule::NUMBER_SIZE..offset_first] .chunks_exact(molecule::NUMBER_SIZE) .map(|x| molecule::unpack_number(x) as usize) .collect(); offsets.push(total_size); if offsets.windows(2).any(|i| i[0] > i[1]) { return ve!(Self, OffsetsNotMatch); } RawL2BlockReader::verify(&slice[offsets[0]..offsets[1]], compatible)?; L2TransactionReader::verify(&slice[offsets[1]..offsets[2]], compatible)?; CKBMerkleProofReader::verify(&slice[offsets[2]..offsets[3]], compatible)?; BytesReader::verify(&slice[offsets[3]..offsets[4]], compatible)?; VerifyTransactionSignatureContextReader::verify( &slice[offsets[4]..offsets[5]], compatible, )?; Ok(()) } } #[derive(Debug, Default)] pub struct VerifyTransactionSignatureWitnessBuilder { pub(crate) raw_l2block: RawL2Block, pub(crate) l2tx: L2Transaction, pub(crate) tx_proof: CKBMerkleProof, pub(crate) kv_state_proof: Bytes, pub(crate) context: VerifyTransactionSignatureContext, } impl VerifyTransactionSignatureWitnessBuilder { pub const FIELD_COUNT: usize = 5; pub fn raw_l2block(mut self, v: RawL2Block) -> Self { self.raw_l2block = v; self } pub fn l2tx(mut self, v: L2Transaction) -> Self { self.l2tx = v; self } pub fn tx_proof(mut self, v: CKBMerkleProof) -> Self { self.tx_proof = v; self } pub fn kv_state_proof(mut self, v: Bytes) -> Self { self.kv_state_proof = v; self } pub fn context(mut self, v: VerifyTransactionSignatureContext) -> Self { self.context = v; self } } impl molecule::prelude::Builder for VerifyTransactionSignatureWitnessBuilder { type Entity = VerifyTransactionSignatureWitness; const NAME: &'static str = "VerifyTransactionSignatureWitnessBuilder"; fn expected_length(&self) -> usize { molecule::NUMBER_SIZE * (Self::FIELD_COUNT + 1) + self.raw_l2block.as_slice().len() + self.l2tx.as_slice().len() + self.tx_proof.as_slice().len() + self.kv_state_proof.as_slice().len() + self.context.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.raw_l2block.as_slice().len(); offsets.push(total_size); total_size += self.l2tx.as_slice().len(); offsets.push(total_size); total_size += self.tx_proof.as_slice().len(); offsets.push(total_size); total_size += self.kv_state_proof.as_slice().len(); offsets.push(total_size); total_size += self.context.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.raw_l2block.as_slice())?; writer.write_all(self.l2tx.as_slice())?; writer.write_all(self.tx_proof.as_slice())?; writer.write_all(self.kv_state_proof.as_slice())?; writer.write_all(self.context.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)); VerifyTransactionSignatureWitness::new_unchecked(inner.into()) } } #[derive(Clone)] pub struct VerifyWithdrawalWitness(molecule::bytes::Bytes); impl ::core::fmt::LowerHex for VerifyWithdrawalWitness { 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 VerifyWithdrawalWitness { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl ::core::fmt::Display for VerifyWithdrawalWitness { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; write!(f, "{}: {}", "raw_l2block", self.raw_l2block())?; write!( f, ", {}: {}", "withdrawal_request", self.withdrawal_request() )?; write!(f, ", {}: {}", "withdrawal_proof", self.withdrawal_proof())?; let extra_count = self.count_extra_fields(); if extra_count != 0 { write!(f, ", .. ({} fields)", extra_count)?; } write!(f, " }}") } } impl ::core::default::Default for VerifyWithdrawalWitness { fn default() -> Self { let v: Vec<u8> = vec![ 64, 2, 0, 0, 16, 0, 0, 0, 84, 1, 0, 0, 44, 2, 0, 0, 68, 1, 0, 0, 44, 0, 0, 0, 52, 0, 0, 0, 56, 0, 0, 0, 88, 0, 0, 0, 120, 0, 0, 0, 128, 0, 0, 0, 164, 0, 0, 0, 200, 0, 0, 0, 204, 0, 0, 0, 240, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 84, 0, 0, 0, 16, 0, 0, 0, 48, 0, 0, 0, 52, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 216, 0, 0, 0, 12, 0, 0, 0, 212, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 20, 0, 0, 0, 12, 0, 0, 0, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ]; VerifyWithdrawalWitness::new_unchecked(v.into()) } } impl VerifyWithdrawalWitness { 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 raw_l2block(&self) -> RawL2Block { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[4..]) as usize; let end = molecule::unpack_number(&slice[8..]) as usize; RawL2Block::new_unchecked(self.0.slice(start..end)) } pub fn withdrawal_request(&self) -> WithdrawalRequest { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[8..]) as usize; let end = molecule::unpack_number(&slice[12..]) as usize; WithdrawalRequest::new_unchecked(self.0.slice(start..end)) } pub fn withdrawal_proof(&self) -> CKBMerkleProof { 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; CKBMerkleProof::new_unchecked(self.0.slice(start..end)) } else { CKBMerkleProof::new_unchecked(self.0.slice(start..)) } } pub fn as_reader<'r>(&'r self) -> VerifyWithdrawalWitnessReader<'r> { VerifyWithdrawalWitnessReader::new_unchecked(self.as_slice()) } } impl molecule::prelude::Entity for VerifyWithdrawalWitness { type Builder = VerifyWithdrawalWitnessBuilder; const NAME: &'static str = "VerifyWithdrawalWitness"; fn new_unchecked(data: molecule::bytes::Bytes) -> Self { VerifyWithdrawalWitness(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> { VerifyWithdrawalWitnessReader::from_slice(slice).map(|reader| reader.to_entity()) } fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> { VerifyWithdrawalWitnessReader::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() .raw_l2block(self.raw_l2block()) .withdrawal_request(self.withdrawal_request()) .withdrawal_proof(self.withdrawal_proof()) } } #[derive(Clone, Copy)] pub struct VerifyWithdrawalWitnessReader<'r>(&'r [u8]); impl<'r> ::core::fmt::LowerHex for VerifyWithdrawalWitnessReader<'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 VerifyWithdrawalWitnessReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl<'r> ::core::fmt::Display for VerifyWithdrawalWitnessReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; write!(f, "{}: {}", "raw_l2block", self.raw_l2block())?; write!( f, ", {}: {}", "withdrawal_request", self.withdrawal_request() )?; write!(f, ", {}: {}", "withdrawal_proof", self.withdrawal_proof())?; let extra_count = self.count_extra_fields(); if extra_count != 0 { write!(f, ", .. ({} fields)", extra_count)?; } write!(f, " }}") } } impl<'r> VerifyWithdrawalWitnessReader<'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 raw_l2block(&self) -> RawL2BlockReader<'r> { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[4..]) as usize; let end = molecule::unpack_number(&slice[8..]) as usize; RawL2BlockReader::new_unchecked(&self.as_slice()[start..end]) } pub fn withdrawal_request(&self) -> WithdrawalRequestReader<'r> { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[8..]) as usize; let end = molecule::unpack_number(&slice[12..]) as usize; WithdrawalRequestReader::new_unchecked(&self.as_slice()[start..end]) } pub fn withdrawal_proof(&self) -> CKBMerkleProofReader<'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; CKBMerkleProofReader::new_unchecked(&self.as_slice()[start..end]) } else { CKBMerkleProofReader::new_unchecked(&self.as_slice()[start..]) } } } impl<'r> molecule::prelude::Reader<'r> for VerifyWithdrawalWitnessReader<'r> { type Entity = VerifyWithdrawalWitness; const NAME: &'static str = "VerifyWithdrawalWitnessReader"; fn to_entity(&self) -> Self::Entity { Self::Entity::new_unchecked(self.as_slice().to_owned().into()) } fn new_unchecked(slice: &'r [u8]) -> Self { VerifyWithdrawalWitnessReader(slice) } fn as_slice(&self) -> &'r [u8] { self.0 } fn verify(slice: &[u8], compatible: bool) -> molecule::error::VerificationResult<()> { use molecule::verification_error as ve; let slice_len = slice.len(); if slice_len < molecule::NUMBER_SIZE { return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE, slice_len); } let total_size = molecule::unpack_number(slice) as usize; if slice_len != total_size { return ve!(Self, TotalSizeNotMatch, total_size, slice_len); } if slice_len == molecule::NUMBER_SIZE && Self::FIELD_COUNT == 0 { return Ok(()); } if slice_len < molecule::NUMBER_SIZE * 2 { return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE * 2, slice_len); } let offset_first = molecule::unpack_number(&slice[molecule::NUMBER_SIZE..]) as usize; if offset_first % molecule::NUMBER_SIZE != 0 || offset_first < molecule::NUMBER_SIZE * 2 { return ve!(Self, OffsetsNotMatch); } if slice_len < offset_first { return ve!(Self, HeaderIsBroken, offset_first, slice_len); } let field_count = offset_first / molecule::NUMBER_SIZE - 1; if field_count < Self::FIELD_COUNT { return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, field_count); } else if !compatible && field_count > Self::FIELD_COUNT { return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, field_count); }; let mut offsets: Vec<usize> = slice[molecule::NUMBER_SIZE..offset_first] .chunks_exact(molecule::NUMBER_SIZE) .map(|x| molecule::unpack_number(x) as usize) .collect(); offsets.push(total_size); if offsets.windows(2).any(|i| i[0] > i[1]) { return ve!(Self, OffsetsNotMatch); } RawL2BlockReader::verify(&slice[offsets[0]..offsets[1]], compatible)?; WithdrawalRequestReader::verify(&slice[offsets[1]..offsets[2]], compatible)?; CKBMerkleProofReader::verify(&slice[offsets[2]..offsets[3]], compatible)?; Ok(()) } } #[derive(Debug, Default)] pub struct VerifyWithdrawalWitnessBuilder { pub(crate) raw_l2block: RawL2Block, pub(crate) withdrawal_request: WithdrawalRequest, pub(crate) withdrawal_proof: CKBMerkleProof, } impl VerifyWithdrawalWitnessBuilder { pub const FIELD_COUNT: usize = 3; pub fn raw_l2block(mut self, v: RawL2Block) -> Self { self.raw_l2block = v; self } pub fn withdrawal_request(mut self, v: WithdrawalRequest) -> Self { self.withdrawal_request = v; self } pub fn withdrawal_proof(mut self, v: CKBMerkleProof) -> Self { self.withdrawal_proof = v; self } } impl molecule::prelude::Builder for VerifyWithdrawalWitnessBuilder { type Entity = VerifyWithdrawalWitness; const NAME: &'static str = "VerifyWithdrawalWitnessBuilder"; fn expected_length(&self) -> usize { molecule::NUMBER_SIZE * (Self::FIELD_COUNT + 1) + self.raw_l2block.as_slice().len() + self.withdrawal_request.as_slice().len() + self.withdrawal_proof.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.raw_l2block.as_slice().len(); offsets.push(total_size); total_size += self.withdrawal_request.as_slice().len(); offsets.push(total_size); total_size += self.withdrawal_proof.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.raw_l2block.as_slice())?; writer.write_all(self.withdrawal_request.as_slice())?; writer.write_all(self.withdrawal_proof.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)); VerifyWithdrawalWitness::new_unchecked(inner.into()) } } #[derive(Clone)] pub struct RollupSubmitBlock(molecule::bytes::Bytes); impl ::core::fmt::LowerHex for RollupSubmitBlock { 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 RollupSubmitBlock { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl ::core::fmt::Display for RollupSubmitBlock { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; write!(f, "{}: {}", "block", self.block())?; write!( f, ", {}: {}", "reverted_block_hashes", self.reverted_block_hashes() )?; write!( f, ", {}: {}", "reverted_block_proof", self.reverted_block_proof() )?; let extra_count = self.count_extra_fields(); if extra_count != 0 { write!(f, ", .. ({} fields)", extra_count)?; } write!(f, " }}") } } impl ::core::default::Default for RollupSubmitBlock { fn default() -> Self { let v: Vec<u8> = vec![ 140, 1, 0, 0, 16, 0, 0, 0, 132, 1, 0, 0, 136, 1, 0, 0, 116, 1, 0, 0, 28, 0, 0, 0, 96, 1, 0, 0, 100, 1, 0, 0, 104, 1, 0, 0, 108, 1, 0, 0, 112, 1, 0, 0, 68, 1, 0, 0, 44, 0, 0, 0, 52, 0, 0, 0, 56, 0, 0, 0, 88, 0, 0, 0, 120, 0, 0, 0, 128, 0, 0, 0, 164, 0, 0, 0, 200, 0, 0, 0, 204, 0, 0, 0, 240, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 84, 0, 0, 0, 16, 0, 0, 0, 48, 0, 0, 0, 52, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ]; RollupSubmitBlock::new_unchecked(v.into()) } } impl RollupSubmitBlock { 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 block(&self) -> L2Block { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[4..]) as usize; let end = molecule::unpack_number(&slice[8..]) as usize; L2Block::new_unchecked(self.0.slice(start..end)) } pub fn reverted_block_hashes(&self) -> Byte32Vec { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[8..]) as usize; let end = molecule::unpack_number(&slice[12..]) as usize; Byte32Vec::new_unchecked(self.0.slice(start..end)) } pub fn reverted_block_proof(&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) -> RollupSubmitBlockReader<'r> { RollupSubmitBlockReader::new_unchecked(self.as_slice()) } } impl molecule::prelude::Entity for RollupSubmitBlock { type Builder = RollupSubmitBlockBuilder; const NAME: &'static str = "RollupSubmitBlock"; fn new_unchecked(data: molecule::bytes::Bytes) -> Self { RollupSubmitBlock(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> { RollupSubmitBlockReader::from_slice(slice).map(|reader| reader.to_entity()) } fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> { RollupSubmitBlockReader::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() .block(self.block()) .reverted_block_hashes(self.reverted_block_hashes()) .reverted_block_proof(self.reverted_block_proof()) } } #[derive(Clone, Copy)] pub struct RollupSubmitBlockReader<'r>(&'r [u8]); impl<'r> ::core::fmt::LowerHex for RollupSubmitBlockReader<'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 RollupSubmitBlockReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl<'r> ::core::fmt::Display for RollupSubmitBlockReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; write!(f, "{}: {}", "block", self.block())?; write!( f, ", {}: {}", "reverted_block_hashes", self.reverted_block_hashes() )?; write!( f, ", {}: {}", "reverted_block_proof", self.reverted_block_proof() )?; let extra_count = self.count_extra_fields(); if extra_count != 0 { write!(f, ", .. ({} fields)", extra_count)?; } write!(f, " }}") } } impl<'r> RollupSubmitBlockReader<'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 block(&self) -> L2BlockReader<'r> { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[4..]) as usize; let end = molecule::unpack_number(&slice[8..]) as usize; L2BlockReader::new_unchecked(&self.as_slice()[start..end]) } pub fn reverted_block_hashes(&self) -> Byte32VecReader<'r> { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[8..]) as usize; let end = molecule::unpack_number(&slice[12..]) as usize; Byte32VecReader::new_unchecked(&self.as_slice()[start..end]) } pub fn reverted_block_proof(&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 RollupSubmitBlockReader<'r> { type Entity = RollupSubmitBlock; const NAME: &'static str = "RollupSubmitBlockReader"; fn to_entity(&self) -> Self::Entity { Self::Entity::new_unchecked(self.as_slice().to_owned().into()) } fn new_unchecked(slice: &'r [u8]) -> Self { RollupSubmitBlockReader(slice) } fn as_slice(&self) -> &'r [u8] { self.0 } fn verify(slice: &[u8], compatible: bool) -> molecule::error::VerificationResult<()> { use molecule::verification_error as ve; let slice_len = slice.len(); if slice_len < molecule::NUMBER_SIZE { return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE, slice_len); } let total_size = molecule::unpack_number(slice) as usize; if slice_len != total_size { return ve!(Self, TotalSizeNotMatch, total_size, slice_len); } if slice_len == molecule::NUMBER_SIZE && Self::FIELD_COUNT == 0 { return Ok(()); } if slice_len < molecule::NUMBER_SIZE * 2 { return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE * 2, slice_len); } let offset_first = molecule::unpack_number(&slice[molecule::NUMBER_SIZE..]) as usize; if offset_first % molecule::NUMBER_SIZE != 0 || offset_first < molecule::NUMBER_SIZE * 2 { return ve!(Self, OffsetsNotMatch); } if slice_len < offset_first { return ve!(Self, HeaderIsBroken, offset_first, slice_len); } let field_count = offset_first / molecule::NUMBER_SIZE - 1; if field_count < Self::FIELD_COUNT { return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, field_count); } else if !compatible && field_count > Self::FIELD_COUNT { return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, field_count); }; let mut offsets: Vec<usize> = slice[molecule::NUMBER_SIZE..offset_first] .chunks_exact(molecule::NUMBER_SIZE) .map(|x| molecule::unpack_number(x) as usize) .collect(); offsets.push(total_size); if offsets.windows(2).any(|i| i[0] > i[1]) { return ve!(Self, OffsetsNotMatch); } L2BlockReader::verify(&slice[offsets[0]..offsets[1]], compatible)?; Byte32VecReader::verify(&slice[offsets[1]..offsets[2]], compatible)?; BytesReader::verify(&slice[offsets[2]..offsets[3]], compatible)?; Ok(()) } } #[derive(Debug, Default)] pub struct RollupSubmitBlockBuilder { pub(crate) block: L2Block, pub(crate) reverted_block_hashes: Byte32Vec, pub(crate) reverted_block_proof: Bytes, } impl RollupSubmitBlockBuilder { pub const FIELD_COUNT: usize = 3; pub fn block(mut self, v: L2Block) -> Self { self.block = v; self } pub fn reverted_block_hashes(mut self, v: Byte32Vec) -> Self { self.reverted_block_hashes = v; self } pub fn reverted_block_proof(mut self, v: Bytes) -> Self { self.reverted_block_proof = v; self } } impl molecule::prelude::Builder for RollupSubmitBlockBuilder { type Entity = RollupSubmitBlock; const NAME: &'static str = "RollupSubmitBlockBuilder"; fn expected_length(&self) -> usize { molecule::NUMBER_SIZE * (Self::FIELD_COUNT + 1) + self.block.as_slice().len() + self.reverted_block_hashes.as_slice().len() + self.reverted_block_proof.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.block.as_slice().len(); offsets.push(total_size); total_size += self.reverted_block_hashes.as_slice().len(); offsets.push(total_size); total_size += self.reverted_block_proof.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.block.as_slice())?; writer.write_all(self.reverted_block_hashes.as_slice())?; writer.write_all(self.reverted_block_proof.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)); RollupSubmitBlock::new_unchecked(inner.into()) } } #[derive(Clone)] pub struct RollupEnterChallenge(molecule::bytes::Bytes); impl ::core::fmt::LowerHex for RollupEnterChallenge { 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 RollupEnterChallenge { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl ::core::fmt::Display for RollupEnterChallenge { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; write!(f, "{}: {}", "witness", self.witness())?; let extra_count = self.count_extra_fields(); if extra_count != 0 { write!(f, ", .. ({} fields)", extra_count)?; } write!(f, " }}") } } impl ::core::default::Default for RollupEnterChallenge { fn default() -> Self { let v: Vec<u8> = vec![ 92, 1, 0, 0, 8, 0, 0, 0, 84, 1, 0, 0, 12, 0, 0, 0, 80, 1, 0, 0, 68, 1, 0, 0, 44, 0, 0, 0, 52, 0, 0, 0, 56, 0, 0, 0, 88, 0, 0, 0, 120, 0, 0, 0, 128, 0, 0, 0, 164, 0, 0, 0, 200, 0, 0, 0, 204, 0, 0, 0, 240, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 84, 0, 0, 0, 16, 0, 0, 0, 48, 0, 0, 0, 52, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ]; RollupEnterChallenge::new_unchecked(v.into()) } } impl RollupEnterChallenge { 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 witness(&self) -> ChallengeWitness { 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; ChallengeWitness::new_unchecked(self.0.slice(start..end)) } else { ChallengeWitness::new_unchecked(self.0.slice(start..)) } } pub fn as_reader<'r>(&'r self) -> RollupEnterChallengeReader<'r> { RollupEnterChallengeReader::new_unchecked(self.as_slice()) } } impl molecule::prelude::Entity for RollupEnterChallenge { type Builder = RollupEnterChallengeBuilder; const NAME: &'static str = "RollupEnterChallenge"; fn new_unchecked(data: molecule::bytes::Bytes) -> Self { RollupEnterChallenge(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> { RollupEnterChallengeReader::from_slice(slice).map(|reader| reader.to_entity()) } fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> { RollupEnterChallengeReader::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().witness(self.witness()) } } #[derive(Clone, Copy)] pub struct RollupEnterChallengeReader<'r>(&'r [u8]); impl<'r> ::core::fmt::LowerHex for RollupEnterChallengeReader<'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 RollupEnterChallengeReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl<'r> ::core::fmt::Display for RollupEnterChallengeReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; write!(f, "{}: {}", "witness", self.witness())?; let extra_count = self.count_extra_fields(); if extra_count != 0 { write!(f, ", .. ({} fields)", extra_count)?; } write!(f, " }}") } } impl<'r> RollupEnterChallengeReader<'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 witness(&self) -> ChallengeWitnessReader<'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; ChallengeWitnessReader::new_unchecked(&self.as_slice()[start..end]) } else { ChallengeWitnessReader::new_unchecked(&self.as_slice()[start..]) } } } impl<'r> molecule::prelude::Reader<'r> for RollupEnterChallengeReader<'r> { type Entity = RollupEnterChallenge; const NAME: &'static str = "RollupEnterChallengeReader"; fn to_entity(&self) -> Self::Entity { Self::Entity::new_unchecked(self.as_slice().to_owned().into()) } fn new_unchecked(slice: &'r [u8]) -> Self { RollupEnterChallengeReader(slice) } fn as_slice(&self) -> &'r [u8] { self.0 } fn verify(slice: &[u8], compatible: bool) -> molecule::error::VerificationResult<()> { use molecule::verification_error as ve; let slice_len = slice.len(); if slice_len < molecule::NUMBER_SIZE { return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE, slice_len); } let total_size = molecule::unpack_number(slice) as usize; if slice_len != total_size { return ve!(Self, TotalSizeNotMatch, total_size, slice_len); } if slice_len == molecule::NUMBER_SIZE && Self::FIELD_COUNT == 0 { return Ok(()); } if slice_len < molecule::NUMBER_SIZE * 2 { return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE * 2, slice_len); } let offset_first = molecule::unpack_number(&slice[molecule::NUMBER_SIZE..]) as usize; if offset_first % molecule::NUMBER_SIZE != 0 || offset_first < molecule::NUMBER_SIZE * 2 { return ve!(Self, OffsetsNotMatch); } if slice_len < offset_first { return ve!(Self, HeaderIsBroken, offset_first, slice_len); } let field_count = offset_first / molecule::NUMBER_SIZE - 1; if field_count < Self::FIELD_COUNT { return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, field_count); } else if !compatible && field_count > Self::FIELD_COUNT { return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, field_count); }; let mut offsets: Vec<usize> = slice[molecule::NUMBER_SIZE..offset_first] .chunks_exact(molecule::NUMBER_SIZE) .map(|x| molecule::unpack_number(x) as usize) .collect(); offsets.push(total_size); if offsets.windows(2).any(|i| i[0] > i[1]) { return ve!(Self, OffsetsNotMatch); } ChallengeWitnessReader::verify(&slice[offsets[0]..offsets[1]], compatible)?; Ok(()) } } #[derive(Debug, Default)] pub struct RollupEnterChallengeBuilder { pub(crate) witness: ChallengeWitness, } impl RollupEnterChallengeBuilder { pub const FIELD_COUNT: usize = 1; pub fn witness(mut self, v: ChallengeWitness) -> Self { self.witness = v; self } } impl molecule::prelude::Builder for RollupEnterChallengeBuilder { type Entity = RollupEnterChallenge; const NAME: &'static str = "RollupEnterChallengeBuilder"; fn expected_length(&self) -> usize { molecule::NUMBER_SIZE * (Self::FIELD_COUNT + 1) + self.witness.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.witness.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.witness.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)); RollupEnterChallenge::new_unchecked(inner.into()) } } #[derive(Clone)] pub struct RollupCancelChallenge(molecule::bytes::Bytes); impl ::core::fmt::LowerHex for RollupCancelChallenge { 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 RollupCancelChallenge { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl ::core::fmt::Display for RollupCancelChallenge { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; let extra_count = self.count_extra_fields(); if extra_count != 0 { write!(f, ".. ({} fields)", extra_count)?; } write!(f, " }}") } } impl ::core::default::Default for RollupCancelChallenge { fn default() -> Self { let v: Vec<u8> = vec![4, 0, 0, 0]; RollupCancelChallenge::new_unchecked(v.into()) } } impl RollupCancelChallenge { pub const FIELD_COUNT: usize = 0; 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 as_reader<'r>(&'r self) -> RollupCancelChallengeReader<'r> { RollupCancelChallengeReader::new_unchecked(self.as_slice()) } } impl molecule::prelude::Entity for RollupCancelChallenge { type Builder = RollupCancelChallengeBuilder; const NAME: &'static str = "RollupCancelChallenge"; fn new_unchecked(data: molecule::bytes::Bytes) -> Self { RollupCancelChallenge(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> { RollupCancelChallengeReader::from_slice(slice).map(|reader| reader.to_entity()) } fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> { RollupCancelChallengeReader::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() } } #[derive(Clone, Copy)] pub struct RollupCancelChallengeReader<'r>(&'r [u8]); impl<'r> ::core::fmt::LowerHex for RollupCancelChallengeReader<'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 RollupCancelChallengeReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl<'r> ::core::fmt::Display for RollupCancelChallengeReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; let extra_count = self.count_extra_fields(); if extra_count != 0 { write!(f, ".. ({} fields)", extra_count)?; } write!(f, " }}") } } impl<'r> RollupCancelChallengeReader<'r> { pub const FIELD_COUNT: usize = 0; 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() } } impl<'r> molecule::prelude::Reader<'r> for RollupCancelChallengeReader<'r> { type Entity = RollupCancelChallenge; const NAME: &'static str = "RollupCancelChallengeReader"; fn to_entity(&self) -> Self::Entity { Self::Entity::new_unchecked(self.as_slice().to_owned().into()) } fn new_unchecked(slice: &'r [u8]) -> Self { RollupCancelChallengeReader(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 && !compatible { return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, !0); } Ok(()) } } #[derive(Debug, Default)] pub struct RollupCancelChallengeBuilder {} impl RollupCancelChallengeBuilder { pub const FIELD_COUNT: usize = 0; } impl molecule::prelude::Builder for RollupCancelChallengeBuilder { type Entity = RollupCancelChallenge; const NAME: &'static str = "RollupCancelChallengeBuilder"; fn expected_length(&self) -> usize { molecule::NUMBER_SIZE } fn write<W: molecule::io::Write>(&self, writer: &mut W) -> molecule::io::Result<()> { writer.write_all(&molecule::pack_number( molecule::NUMBER_SIZE as molecule::Number, ))?; 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)); RollupCancelChallenge::new_unchecked(inner.into()) } } #[derive(Clone)] pub struct RollupRevert(molecule::bytes::Bytes); impl ::core::fmt::LowerHex for RollupRevert { 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 RollupRevert { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl ::core::fmt::Display for RollupRevert { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; write!(f, "{}: {}", "reverted_blocks", self.reverted_blocks())?; write!(f, ", {}: {}", "block_proof", self.block_proof())?; write!( f, ", {}: {}", "reverted_block_proof", self.reverted_block_proof() )?; write!(f, ", {}: {}", "new_tip_block", self.new_tip_block())?; let extra_count = self.count_extra_fields(); if extra_count != 0 { write!(f, ", .. ({} fields)", extra_count)?; } write!(f, " }}") } } impl ::core::default::Default for RollupRevert { fn default() -> Self { let v: Vec<u8> = vec![ 100, 1, 0, 0, 20, 0, 0, 0, 24, 0, 0, 0, 28, 0, 0, 0, 32, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 68, 1, 0, 0, 44, 0, 0, 0, 52, 0, 0, 0, 56, 0, 0, 0, 88, 0, 0, 0, 120, 0, 0, 0, 128, 0, 0, 0, 164, 0, 0, 0, 200, 0, 0, 0, 204, 0, 0, 0, 240, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 84, 0, 0, 0, 16, 0, 0, 0, 48, 0, 0, 0, 52, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ]; RollupRevert::new_unchecked(v.into()) } } impl RollupRevert { 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 reverted_blocks(&self) -> RawL2BlockVec { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[4..]) as usize; let end = molecule::unpack_number(&slice[8..]) as usize; RawL2BlockVec::new_unchecked(self.0.slice(start..end)) } pub fn block_proof(&self) -> Bytes { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[8..]) as usize; let end = molecule::unpack_number(&slice[12..]) as usize; Bytes::new_unchecked(self.0.slice(start..end)) } pub fn reverted_block_proof(&self) -> Bytes { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[12..]) as usize; let end = molecule::unpack_number(&slice[16..]) as usize; Bytes::new_unchecked(self.0.slice(start..end)) } pub fn new_tip_block(&self) -> RawL2Block { 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; RawL2Block::new_unchecked(self.0.slice(start..end)) } else { RawL2Block::new_unchecked(self.0.slice(start..)) } } pub fn as_reader<'r>(&'r self) -> RollupRevertReader<'r> { RollupRevertReader::new_unchecked(self.as_slice()) } } impl molecule::prelude::Entity for RollupRevert { type Builder = RollupRevertBuilder; const NAME: &'static str = "RollupRevert"; fn new_unchecked(data: molecule::bytes::Bytes) -> Self { RollupRevert(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> { RollupRevertReader::from_slice(slice).map(|reader| reader.to_entity()) } fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> { RollupRevertReader::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() .reverted_blocks(self.reverted_blocks()) .block_proof(self.block_proof()) .reverted_block_proof(self.reverted_block_proof()) .new_tip_block(self.new_tip_block()) } } #[derive(Clone, Copy)] pub struct RollupRevertReader<'r>(&'r [u8]); impl<'r> ::core::fmt::LowerHex for RollupRevertReader<'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 RollupRevertReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl<'r> ::core::fmt::Display for RollupRevertReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{} {{ ", Self::NAME)?; write!(f, "{}: {}", "reverted_blocks", self.reverted_blocks())?; write!(f, ", {}: {}", "block_proof", self.block_proof())?; write!( f, ", {}: {}", "reverted_block_proof", self.reverted_block_proof() )?; write!(f, ", {}: {}", "new_tip_block", self.new_tip_block())?; let extra_count = self.count_extra_fields(); if extra_count != 0 { write!(f, ", .. ({} fields)", extra_count)?; } write!(f, " }}") } } impl<'r> RollupRevertReader<'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 reverted_blocks(&self) -> RawL2BlockVecReader<'r> { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[4..]) as usize; let end = molecule::unpack_number(&slice[8..]) as usize; RawL2BlockVecReader::new_unchecked(&self.as_slice()[start..end]) } pub fn block_proof(&self) -> BytesReader<'r> { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[8..]) as usize; let end = molecule::unpack_number(&slice[12..]) as usize; BytesReader::new_unchecked(&self.as_slice()[start..end]) } pub fn reverted_block_proof(&self) -> BytesReader<'r> { let slice = self.as_slice(); let start = molecule::unpack_number(&slice[12..]) as usize; let end = molecule::unpack_number(&slice[16..]) as usize; BytesReader::new_unchecked(&self.as_slice()[start..end]) } pub fn new_tip_block(&self) -> RawL2BlockReader<'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; RawL2BlockReader::new_unchecked(&self.as_slice()[start..end]) } else { RawL2BlockReader::new_unchecked(&self.as_slice()[start..]) } } } impl<'r> molecule::prelude::Reader<'r> for RollupRevertReader<'r> { type Entity = RollupRevert; const NAME: &'static str = "RollupRevertReader"; fn to_entity(&self) -> Self::Entity { Self::Entity::new_unchecked(self.as_slice().to_owned().into()) } fn new_unchecked(slice: &'r [u8]) -> Self { RollupRevertReader(slice) } fn as_slice(&self) -> &'r [u8] { self.0 } fn verify(slice: &[u8], compatible: bool) -> molecule::error::VerificationResult<()> { use molecule::verification_error as ve; let slice_len = slice.len(); if slice_len < molecule::NUMBER_SIZE { return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE, slice_len); } let total_size = molecule::unpack_number(slice) as usize; if slice_len != total_size { return ve!(Self, TotalSizeNotMatch, total_size, slice_len); } if slice_len == molecule::NUMBER_SIZE && Self::FIELD_COUNT == 0 { return Ok(()); } if slice_len < molecule::NUMBER_SIZE * 2 { return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE * 2, slice_len); } let offset_first = molecule::unpack_number(&slice[molecule::NUMBER_SIZE..]) as usize; if offset_first % molecule::NUMBER_SIZE != 0 || offset_first < molecule::NUMBER_SIZE * 2 { return ve!(Self, OffsetsNotMatch); } if slice_len < offset_first { return ve!(Self, HeaderIsBroken, offset_first, slice_len); } let field_count = offset_first / molecule::NUMBER_SIZE - 1; if field_count < Self::FIELD_COUNT { return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, field_count); } else if !compatible && field_count > Self::FIELD_COUNT { return ve!(Self, FieldCountNotMatch, Self::FIELD_COUNT, field_count); }; let mut offsets: Vec<usize> = slice[molecule::NUMBER_SIZE..offset_first] .chunks_exact(molecule::NUMBER_SIZE) .map(|x| molecule::unpack_number(x) as usize) .collect(); offsets.push(total_size); if offsets.windows(2).any(|i| i[0] > i[1]) { return ve!(Self, OffsetsNotMatch); } RawL2BlockVecReader::verify(&slice[offsets[0]..offsets[1]], compatible)?; BytesReader::verify(&slice[offsets[1]..offsets[2]], compatible)?; BytesReader::verify(&slice[offsets[2]..offsets[3]], compatible)?; RawL2BlockReader::verify(&slice[offsets[3]..offsets[4]], compatible)?; Ok(()) } } #[derive(Debug, Default)] pub struct RollupRevertBuilder { pub(crate) reverted_blocks: RawL2BlockVec, pub(crate) block_proof: Bytes, pub(crate) reverted_block_proof: Bytes, pub(crate) new_tip_block: RawL2Block, } impl RollupRevertBuilder { pub const FIELD_COUNT: usize = 4; pub fn reverted_blocks(mut self, v: RawL2BlockVec) -> Self { self.reverted_blocks = v; self } pub fn block_proof(mut self, v: Bytes) -> Self { self.block_proof = v; self } pub fn reverted_block_proof(mut self, v: Bytes) -> Self { self.reverted_block_proof = v; self } pub fn new_tip_block(mut self, v: RawL2Block) -> Self { self.new_tip_block = v; self } } impl molecule::prelude::Builder for RollupRevertBuilder { type Entity = RollupRevert; const NAME: &'static str = "RollupRevertBuilder"; fn expected_length(&self) -> usize { molecule::NUMBER_SIZE * (Self::FIELD_COUNT + 1) + self.reverted_blocks.as_slice().len() + self.block_proof.as_slice().len() + self.reverted_block_proof.as_slice().len() + self.new_tip_block.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.reverted_blocks.as_slice().len(); offsets.push(total_size); total_size += self.block_proof.as_slice().len(); offsets.push(total_size); total_size += self.reverted_block_proof.as_slice().len(); offsets.push(total_size); total_size += self.new_tip_block.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.reverted_blocks.as_slice())?; writer.write_all(self.block_proof.as_slice())?; writer.write_all(self.reverted_block_proof.as_slice())?; writer.write_all(self.new_tip_block.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)); RollupRevert::new_unchecked(inner.into()) } } #[derive(Clone)] pub struct RollupAction(molecule::bytes::Bytes); impl ::core::fmt::LowerHex for RollupAction { 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 RollupAction { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl ::core::fmt::Display for RollupAction { 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 RollupAction { fn default() -> Self { let v: Vec<u8> = vec![ 0, 0, 0, 0, 140, 1, 0, 0, 16, 0, 0, 0, 132, 1, 0, 0, 136, 1, 0, 0, 116, 1, 0, 0, 28, 0, 0, 0, 96, 1, 0, 0, 100, 1, 0, 0, 104, 1, 0, 0, 108, 1, 0, 0, 112, 1, 0, 0, 68, 1, 0, 0, 44, 0, 0, 0, 52, 0, 0, 0, 56, 0, 0, 0, 88, 0, 0, 0, 120, 0, 0, 0, 128, 0, 0, 0, 164, 0, 0, 0, 200, 0, 0, 0, 204, 0, 0, 0, 240, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 84, 0, 0, 0, 16, 0, 0, 0, 48, 0, 0, 0, 52, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ]; RollupAction::new_unchecked(v.into()) } } impl RollupAction { pub const ITEMS_COUNT: usize = 4; pub fn item_id(&self) -> molecule::Number { molecule::unpack_number(self.as_slice()) } pub fn to_enum(&self) -> RollupActionUnion { let inner = self.0.slice(molecule::NUMBER_SIZE..); match self.item_id() { 0 => RollupSubmitBlock::new_unchecked(inner).into(), 1 => RollupEnterChallenge::new_unchecked(inner).into(), 2 => RollupCancelChallenge::new_unchecked(inner).into(), 3 => RollupRevert::new_unchecked(inner).into(), _ => panic!("{}: invalid data", Self::NAME), } } pub fn as_reader<'r>(&'r self) -> RollupActionReader<'r> { RollupActionReader::new_unchecked(self.as_slice()) } } impl molecule::prelude::Entity for RollupAction { type Builder = RollupActionBuilder; const NAME: &'static str = "RollupAction"; fn new_unchecked(data: molecule::bytes::Bytes) -> Self { RollupAction(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> { RollupActionReader::from_slice(slice).map(|reader| reader.to_entity()) } fn from_compatible_slice(slice: &[u8]) -> molecule::error::VerificationResult<Self> { RollupActionReader::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 RollupActionReader<'r>(&'r [u8]); impl<'r> ::core::fmt::LowerHex for RollupActionReader<'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 RollupActionReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "{}({:#x})", Self::NAME, self) } } impl<'r> ::core::fmt::Display for RollupActionReader<'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> RollupActionReader<'r> { pub const ITEMS_COUNT: usize = 4; pub fn item_id(&self) -> molecule::Number { molecule::unpack_number(self.as_slice()) } pub fn to_enum(&self) -> RollupActionUnionReader<'r> { let inner = &self.as_slice()[molecule::NUMBER_SIZE..]; match self.item_id() { 0 => RollupSubmitBlockReader::new_unchecked(inner).into(), 1 => RollupEnterChallengeReader::new_unchecked(inner).into(), 2 => RollupCancelChallengeReader::new_unchecked(inner).into(), 3 => RollupRevertReader::new_unchecked(inner).into(), _ => panic!("{}: invalid data", Self::NAME), } } } impl<'r> molecule::prelude::Reader<'r> for RollupActionReader<'r> { type Entity = RollupAction; const NAME: &'static str = "RollupActionReader"; fn to_entity(&self) -> Self::Entity { Self::Entity::new_unchecked(self.as_slice().to_owned().into()) } fn new_unchecked(slice: &'r [u8]) -> Self { RollupActionReader(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 => RollupSubmitBlockReader::verify(inner_slice, compatible), 1 => RollupEnterChallengeReader::verify(inner_slice, compatible), 2 => RollupCancelChallengeReader::verify(inner_slice, compatible), 3 => RollupRevertReader::verify(inner_slice, compatible), _ => ve!(Self, UnknownItem, Self::ITEMS_COUNT, item_id), }?; Ok(()) } } #[derive(Debug, Default)] pub struct RollupActionBuilder(pub(crate) RollupActionUnion); impl RollupActionBuilder { pub const ITEMS_COUNT: usize = 4; pub fn set<I>(mut self, v: I) -> Self where I: ::core::convert::Into<RollupActionUnion>, { self.0 = v.into(); self } } impl molecule::prelude::Builder for RollupActionBuilder { type Entity = RollupAction; const NAME: &'static str = "RollupActionBuilder"; 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)); RollupAction::new_unchecked(inner.into()) } } #[derive(Debug, Clone)] pub enum RollupActionUnion { RollupSubmitBlock(RollupSubmitBlock), RollupEnterChallenge(RollupEnterChallenge), RollupCancelChallenge(RollupCancelChallenge), RollupRevert(RollupRevert), } #[derive(Debug, Clone, Copy)] pub enum RollupActionUnionReader<'r> { RollupSubmitBlock(RollupSubmitBlockReader<'r>), RollupEnterChallenge(RollupEnterChallengeReader<'r>), RollupCancelChallenge(RollupCancelChallengeReader<'r>), RollupRevert(RollupRevertReader<'r>), } impl ::core::default::Default for RollupActionUnion { fn default() -> Self { RollupActionUnion::RollupSubmitBlock(::core::default::Default::default()) } } impl ::core::fmt::Display for RollupActionUnion { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { match self { RollupActionUnion::RollupSubmitBlock(ref item) => { write!(f, "{}::{}({})", Self::NAME, RollupSubmitBlock::NAME, item) } RollupActionUnion::RollupEnterChallenge(ref item) => { write!( f, "{}::{}({})", Self::NAME, RollupEnterChallenge::NAME, item ) } RollupActionUnion::RollupCancelChallenge(ref item) => { write!( f, "{}::{}({})", Self::NAME, RollupCancelChallenge::NAME, item ) } RollupActionUnion::RollupRevert(ref item) => { write!(f, "{}::{}({})", Self::NAME, RollupRevert::NAME, item) } } } } impl<'r> ::core::fmt::Display for RollupActionUnionReader<'r> { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { match self { RollupActionUnionReader::RollupSubmitBlock(ref item) => { write!(f, "{}::{}({})", Self::NAME, RollupSubmitBlock::NAME, item) } RollupActionUnionReader::RollupEnterChallenge(ref item) => { write!( f, "{}::{}({})", Self::NAME, RollupEnterChallenge::NAME, item ) } RollupActionUnionReader::RollupCancelChallenge(ref item) => { write!( f, "{}::{}({})", Self::NAME, RollupCancelChallenge::NAME, item ) } RollupActionUnionReader::RollupRevert(ref item) => { write!(f, "{}::{}({})", Self::NAME, RollupRevert::NAME, item) } } } } impl RollupActionUnion { pub(crate) fn display_inner(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { match self { RollupActionUnion::RollupSubmitBlock(ref item) => write!(f, "{}", item), RollupActionUnion::RollupEnterChallenge(ref item) => write!(f, "{}", item), RollupActionUnion::RollupCancelChallenge(ref item) => write!(f, "{}", item), RollupActionUnion::RollupRevert(ref item) => write!(f, "{}", item), } } } impl<'r> RollupActionUnionReader<'r> { pub(crate) fn display_inner(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { match self { RollupActionUnionReader::RollupSubmitBlock(ref item) => write!(f, "{}", item), RollupActionUnionReader::RollupEnterChallenge(ref item) => write!(f, "{}", item), RollupActionUnionReader::RollupCancelChallenge(ref item) => write!(f, "{}", item), RollupActionUnionReader::RollupRevert(ref item) => write!(f, "{}", item), } } } impl ::core::convert::From<RollupSubmitBlock> for RollupActionUnion { fn from(item: RollupSubmitBlock) -> Self { RollupActionUnion::RollupSubmitBlock(item) } } impl ::core::convert::From<RollupEnterChallenge> for RollupActionUnion { fn from(item: RollupEnterChallenge) -> Self { RollupActionUnion::RollupEnterChallenge(item) } } impl ::core::convert::From<RollupCancelChallenge> for RollupActionUnion { fn from(item: RollupCancelChallenge) -> Self { RollupActionUnion::RollupCancelChallenge(item) } } impl ::core::convert::From<RollupRevert> for RollupActionUnion { fn from(item: RollupRevert) -> Self { RollupActionUnion::RollupRevert(item) } } impl<'r> ::core::convert::From<RollupSubmitBlockReader<'r>> for RollupActionUnionReader<'r> { fn from(item: RollupSubmitBlockReader<'r>) -> Self { RollupActionUnionReader::RollupSubmitBlock(item) } } impl<'r> ::core::convert::From<RollupEnterChallengeReader<'r>> for RollupActionUnionReader<'r> { fn from(item: RollupEnterChallengeReader<'r>) -> Self { RollupActionUnionReader::RollupEnterChallenge(item) } } impl<'r> ::core::convert::From<RollupCancelChallengeReader<'r>> for RollupActionUnionReader<'r> { fn from(item: RollupCancelChallengeReader<'r>) -> Self { RollupActionUnionReader::RollupCancelChallenge(item) } } impl<'r> ::core::convert::From<RollupRevertReader<'r>> for RollupActionUnionReader<'r> { fn from(item: RollupRevertReader<'r>) -> Self { RollupActionUnionReader::RollupRevert(item) } } impl RollupActionUnion { pub const NAME: &'static str = "RollupActionUnion"; pub fn as_bytes(&self) -> molecule::bytes::Bytes { match self { RollupActionUnion::RollupSubmitBlock(item) => item.as_bytes(), RollupActionUnion::RollupEnterChallenge(item) => item.as_bytes(), RollupActionUnion::RollupCancelChallenge(item) => item.as_bytes(), RollupActionUnion::RollupRevert(item) => item.as_bytes(), } } pub fn as_slice(&self) -> &[u8] { match self { RollupActionUnion::RollupSubmitBlock(item) => item.as_slice(), RollupActionUnion::RollupEnterChallenge(item) => item.as_slice(), RollupActionUnion::RollupCancelChallenge(item) => item.as_slice(), RollupActionUnion::RollupRevert(item) => item.as_slice(), } } pub fn item_id(&self) -> molecule::Number { match self { RollupActionUnion::RollupSubmitBlock(_) => 0, RollupActionUnion::RollupEnterChallenge(_) => 1, RollupActionUnion::RollupCancelChallenge(_) => 2, RollupActionUnion::RollupRevert(_) => 3, } } pub fn item_name(&self) -> &str { match self { RollupActionUnion::RollupSubmitBlock(_) => "RollupSubmitBlock", RollupActionUnion::RollupEnterChallenge(_) => "RollupEnterChallenge", RollupActionUnion::RollupCancelChallenge(_) => "RollupCancelChallenge", RollupActionUnion::RollupRevert(_) => "RollupRevert", } } pub fn as_reader<'r>(&'r self) -> RollupActionUnionReader<'r> { match self { RollupActionUnion::RollupSubmitBlock(item) => item.as_reader().into(), RollupActionUnion::RollupEnterChallenge(item) => item.as_reader().into(), RollupActionUnion::RollupCancelChallenge(item) => item.as_reader().into(), RollupActionUnion::RollupRevert(item) => item.as_reader().into(), } } } impl<'r> RollupActionUnionReader<'r> { pub const NAME: &'r str = "RollupActionUnionReader"; pub fn as_slice(&self) -> &'r [u8] { match self { RollupActionUnionReader::RollupSubmitBlock(item) => item.as_slice(), RollupActionUnionReader::RollupEnterChallenge(item) => item.as_slice(), RollupActionUnionReader::RollupCancelChallenge(item) => item.as_slice(), RollupActionUnionReader::RollupRevert(item) => item.as_slice(), } } pub fn item_id(&self) -> molecule::Number { match self { RollupActionUnionReader::RollupSubmitBlock(_) => 0, RollupActionUnionReader::RollupEnterChallenge(_) => 1, RollupActionUnionReader::RollupCancelChallenge(_) => 2, RollupActionUnionReader::RollupRevert(_) => 3, } } pub fn item_name(&self) -> &str { match self { RollupActionUnionReader::RollupSubmitBlock(_) => "RollupSubmitBlock", RollupActionUnionReader::RollupEnterChallenge(_) => "RollupEnterChallenge", RollupActionUnionReader::RollupCancelChallenge(_) => "RollupCancelChallenge", RollupActionUnionReader::RollupRevert(_) => "RollupRevert", } } }
true
2096be842770d3c4856391b13d2855613bf532ec
Rust
clinuxrulz/sodium-rust-push-pull
/src/sodium/impl_/latch.rs
UTF-8
1,528
2.828125
3
[]
no_license
use sodium::gc::Finalize; use sodium::gc::GcDep; use sodium::gc::Trace; use std::cell::UnsafeCell; use std::rc::Rc; pub struct Latch<A> { data: Rc<UnsafeCell<LatchData<A>>> } struct LatchData<A> { thunk: Box<Fn()->A>, val: A } impl<A: Trace> Trace for Latch<A> { fn trace(&self, f: &mut FnMut(&GcDep)) { let self_ = unsafe { &*(*self.data).get() }; self_.val.trace(f); } } impl<A: Finalize> Finalize for Latch<A> { fn finalize(&mut self) { let self_ = unsafe { &mut *(*self.data).get() }; self_.val.finalize(); } } impl<A:Clone + 'static> Latch<A> { pub fn const_(value: A) -> Latch<A> { Latch::new(move || value.clone()) } } impl<A> Latch<A> { pub fn new<F: Fn()->A + 'static>(thunk: F) -> Latch<A> { let val = thunk(); Latch { data: Rc::new(UnsafeCell::new( LatchData { thunk: Box::new(thunk), val } )) } } pub fn get(&self) -> &A { let self_ = unsafe { &*(*self.data).get() }; &self_.val } pub fn get_mut(&mut self) -> &mut A { let self_ = unsafe { &mut *(*self.data).get() }; &mut self_.val } pub fn reset(&mut self) { let self_ = unsafe { &mut *(*self.data).get() }; self_.val = (self_.thunk)(); } } impl<A: Clone> Clone for Latch<A> { fn clone(&self) -> Self { Latch { data: self.data.clone() } } }
true
2c2e9c6091399f5c51b6c0de771751f078f2ea99
Rust
ccqpein/Arithmetic-Exercises
/Capacity-To-Ship-Packages-Within-D-Days/C2SPWDD.rs
UTF-8
1,603
3.578125
4
[ "Apache-2.0" ]
permissive
pub fn ship_within_days(weights: Vec<i32>, days: i32) -> i32 { //helper(&weights, days).unwrap() helper2(&weights, days) } // beyond time limit fn helper(w: &[i32], days: i32) -> Option<i32> { if w.len() == 0 { return None; } if days == 1 { return Some(w.iter().sum()); } let mut cache = vec![]; for i in 0..w.len() { let a = w[0..i].iter().sum(); let rest = helper(&w[i..], days - 1); if let None = rest { continue; } if a >= rest.unwrap() { cache.push(a); } else { cache.push(rest.unwrap()) } } Some(*cache.iter().min().unwrap()) } fn helper2(w: &[i32], days: i32) -> i32 { let (mut left, mut right) = (*w.iter().max().unwrap(), w.iter().sum::<i32>()); while left < right { let (mid, mut need, mut cur) = ((left + right) / 2, 1, 0); for v in w { if cur + v > mid { need += 1; cur = 0; } cur += v } if need > days { left = mid + 1; } else { right = mid } } left } fn main() { assert_eq!(ship_within_days(vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 5), 15); assert_eq!(ship_within_days(vec![3, 2, 2, 4, 1, 4], 3), 6); assert_eq!(ship_within_days(vec![1, 2, 3, 1, 1], 4), 3); dbg!(ship_within_days( vec![ 180, 373, 75, 82, 497, 23, 303, 299, 53, 426, 152, 314, 206, 433, 283, 370, 179, 254, 265, 431, 453, 17, 189, 224 ], 12 )); }
true
fa478b2d31812688107125235640b7cdc179fd69
Rust
wombat-hue/rust-book-code-listings
/listings/ch15-smart-pointers/listing-15-08/src/main.rs
UTF-8
110
2.65625
3
[]
no_license
struct MyBox<T>(T); impl<T> MyBox<T> { fn new(x: T) -> MyBox<T> { MyBox(x) } } fn main() {}
true
0104d75db46ebdfcf323cf632241e52d93fd9dba
Rust
qinxiaoguang/rs-lc
/src/solution/l029.rs
UTF-8
2,025
3.484375
3
[]
no_license
pub struct Solution {} impl Solution { // 不使用除法,乘法,mod计算两个数相除的商 // 不使用除法,但是可以使用加法,减法,此题可以考虑快速蜜 #![allow(dead_code)] pub fn divide(dividend: i32, divisor: i32) -> i32 { let mut is_neg = false; if (dividend > 0 && divisor < 0) || (dividend < 0 && divisor > 0) { is_neg = true } let (mut cnt, _) = Self::my_divide((dividend as i64).abs(), (divisor as i64).abs()); if is_neg { cnt = -cnt; } if is_neg && cnt <= std::i32::MIN as i64 { std::i32::MIN } else if !is_neg && cnt >= std::i32::MAX as i64 { std::i32::MAX } else { cnt as i32 } } // 类似快速蜜的方式,divisor在下次递归的时候会变为两倍 // 第二个数是mod后的值 fn my_divide(dividend: i64, divisor: i64) -> (i64, i64) { if dividend < divisor { return (0, dividend); } let mut dividend = dividend; if divisor <= dividend && dividend < divisor + divisor { let (mut cnt, mod_v) = Self::my_divide(dividend - divisor, divisor); cnt += 1; return (cnt, mod_v); } else { let mut res = 0; while dividend >= divisor + divisor { let (cnt, mod_v) = Self::my_divide(dividend, divisor + divisor); res += cnt + cnt; dividend = mod_v; } if dividend < divisor { return (res, dividend); } else { let (cnt, mod_v) = Self::my_divide(dividend, divisor); return (res + cnt, mod_v); } } } } #[cfg(test)] mod test { use super::*; #[test] fn test_l029() { assert_eq!(2147483647, Solution::divide(-2147483648, -1)); assert_eq!(3, Solution::divide(10, 3)); assert_eq!(-2, Solution::divide(7, -3)); } }
true
37bb13ca7e0b2e22c0b5b35aeda49c14f56105ff
Rust
mashiro-no-rabo/pingcap-tp
/examples/bb3-serde.rs
UTF-8
2,259
3
3
[]
no_license
// serde data format // Rust types -- (impl Serialize) --> serde data model (types) -- (impl Serializer) --> String/Vec<u8>/Write... // &str/&[u8]/Read... -- (impl Deserializer) --> serde data model (types) -- (impl Deserialize) --> Rust types use anyhow::{Context, Result}; use resp_serde::{read_command, read_reply, write_command, write_reply}; use serde::{Deserialize, Serialize}; use std::io::BufReader; use std::net::{TcpListener, TcpStream}; use std::str; use std::thread::sleep; use std::time::Duration; use structopt::StructOpt; #[derive(StructOpt)] #[structopt(name = "bb3")] enum RunAs { Client, Server, } #[derive(Debug, PartialEq, Serialize, Deserialize)] enum Command { Ping, } fn main() -> Result<()> { match RunAs::from_args() { RunAs::Client => { let stream = TcpStream::connect("127.0.0.1:6379").context("Cannot connect")?; stream.set_read_timeout(Some(Duration::from_secs(10)))?; stream.set_write_timeout(Some(Duration::from_secs(10)))?; let mut reader = BufReader::new(stream); loop { let cmd = Command::Ping; write_command(&cmd, reader.get_mut()).context("Writing command")?; println!("sent PING"); let reply: std::result::Result<String, String> = read_reply(&mut reader).context("Reading reply")?; match reply { Ok(reply) => println!("recv {}", &reply), Err(err) => println!("error {}", &err), } sleep(Duration::from_secs(2)); } } RunAs::Server => { let listener = TcpListener::bind("127.0.0.1:6379").context("Cannot bind")?; for stream in listener.incoming() { server_loop(stream?)?; } } } Ok(()) } fn server_loop(stream: TcpStream) -> Result<()> { stream.set_read_timeout(Some(Duration::from_secs(10)))?; stream.set_write_timeout(Some(Duration::from_secs(10)))?; let mut reader = BufReader::new(stream); loop { // always expect PING command here let cmd = read_command(&mut reader).context("Reading command")?; assert_eq!(Command::Ping, cmd); // Good PING command! println!("recv PING"); let reply = "PONG".to_owned(); write_reply(&reply, reader.get_mut()).context("Writing reply")?; println!("sent PONG"); } }
true
b8eb8ff12c8e6b4818ce8a7f062a779127fe5457
Rust
carrotflakes/termaze
/src/main.rs
UTF-8
1,048
2.609375
3
[]
no_license
mod maze; mod maze_maker; mod maze_state; mod terminal; use maze_state::MazeState; use std::time::SystemTime; fn main() { let mut seed = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap().as_millis() as u64; let maze = maze_maker::make_maze(8, 5, seed); let mut maze_state = MazeState::new(maze); terminal::mount_terminal(&mut move |k| { if let Some(k) = k { let k = match k { terminal::KeyEvent::Left => maze_state::KeyEvent::Left, terminal::KeyEvent::Right => maze_state::KeyEvent::Right, terminal::KeyEvent::Up => maze_state::KeyEvent::Up, terminal::KeyEvent::Down => maze_state::KeyEvent::Down, }; maze_state.mv(k); if maze_state.is_goal() { seed += 1; let maze = maze_maker::make_maze(8, 5, seed); maze_state = MazeState::new(maze); } } format!("{}- Arrow key to move.\r\n- q key to exit.", maze_state) }); }
true
4a33d4e7ed07f8e1ad16f936fb0a9fce7221226c
Rust
neodes-h/design-pattern-rust
/src/builder/main.rs
UTF-8
1,498
3.859375
4
[]
no_license
#[derive(Debug, Copy, Clone)] enum Gender { Male, Female, } #[derive(Debug)] struct Person { name: String, gender: Gender, age: u8, } #[derive(Debug)] struct PersonBuilder { name: String, gender: Gender, age: u8, } impl Default for PersonBuilder { fn default() -> Self { Self { name: "".to_owned(), gender: Gender::Male, age: 0, } } } impl PersonBuilder { fn new() -> Self { Self::default() } fn get_name(&self) -> String { self.name.clone() } fn set_name<T: AsRef<str>>(&mut self, name: T) -> &mut Self { self.name = name.as_ref().to_owned(); self } fn get_gender(&self) -> Gender { self.gender } fn set_gender(&mut self, gender: Gender) -> &mut Self { self.gender = gender; self } fn get_age(&self) -> u8 { self.age } fn set_age(&mut self, age: u8) -> &mut Self { self.age = age; self } fn finish(&mut self) -> Person { Person { name: self.name.clone(), age: self.age, gender: self.gender, } } } fn main() { let mut builder = PersonBuilder::new(); builder.set_name("Bob"); builder.set_age(12); builder.set_gender(Gender::Male); println!("{:?}", builder.finish()); builder.set_name("Mary"); builder.set_gender(Gender::Female); println!("{:?}", builder.finish()); }
true
6008cfda029b6fde6f315c7cf105e5937aa9bdbc
Rust
piperRyan/rust-postgres-interval
/src/integrations/duration.rs
UTF-8
2,713
3.625
4
[ "MIT" ]
permissive
use crate::{interval_norm::IntervalNorm, Interval}; use chrono::Duration; const NANOS_PER_SEC: i64 = 1_000_000_000; const NANOS_PER_MICRO: i64 = 1000; impl Interval { /// Tries to convert from the `Duration` type to a `Interval`. Will /// return `None` on a overflow. This is a lossy conversion in that /// any units smaller than a microsecond will be lost. pub fn from_duration(duration: Duration) -> Option<Interval> { let mut days = duration.num_days(); let mut new_dur = duration - Duration::days(days); let mut hours = duration.num_hours(); new_dur = new_dur - Duration::hours(hours); let minutes = new_dur.num_minutes(); new_dur = new_dur - Duration::minutes(minutes); let nano_secs = new_dur.num_nanoseconds()?; if days > (i32::max_value() as i64) { let overflow_days = days - (i32::max_value() as i64); let added_hours = overflow_days.checked_mul(24)?; hours = hours.checked_add(added_hours)?; days -= overflow_days; } let (seconds, remaining_nano) = reduce_by_units(nano_secs, NANOS_PER_SEC); // We have to discard any remaining nanoseconds let (microseconds, _remaining_nano) = reduce_by_units(remaining_nano, NANOS_PER_MICRO); let norm_interval = IntervalNorm { years: 0, months: 0, days: days as i32, hours, minutes, seconds, microseconds, }; norm_interval.try_into_interval().ok() } } fn reduce_by_units(nano_secs: i64, unit: i64) -> (i64, i64) { let new_time_unit = (nano_secs - (nano_secs % unit)) / unit; let remaining_nano = nano_secs - (new_time_unit * unit); (new_time_unit, remaining_nano) } #[cfg(test)] mod tests { use super::*; use chrono::Duration; #[test] fn can_convert_small_amount_of_days() { let dur = Duration::days(5); let interval = Interval::from_duration(dur); assert_eq!(interval, Some(Interval::new(0,5,0))) } #[test] fn overflow_on_days() { let dur = Duration::days(100000000000); let interval = Interval::from_duration(dur); assert_eq!(interval, None) } #[test] fn can_convert_small_amount_of_secs() { let dur = Duration::seconds(1); let interval = Interval::from_duration(dur); assert_eq!(interval, Some(Interval::new(0,0,1_000_000))) } #[test] fn can_convert_one_micro() { let dur = Duration::nanoseconds(1000); let interval = Interval::from_duration(dur); assert_eq!(interval, Some(Interval::new(0,0,1))) } }
true
6dbf17ec99006ac6dd118de5d3d4758e31f35426
Rust
n1tram1/gameboy
/src/main.rs
UTF-8
1,037
2.640625
3
[]
no_license
use std::path; use std::time::{Duration, Instant}; use std::thread::sleep; mod cpu; mod mbc; mod mmu; mod registers; mod ppu; mod decode; mod lcd; mod palette; mod joypad; mod timer; fn main() { let start = Instant::now(); let rom_path = path::Path::new("/home/martin/Documents/gameboy-rs/roms/Tetris.GB"); let mut cpu = cpu::CPU::new(rom_path); let mut cycles_count = 0; let mut prev = Instant::now(); let one_sec = Duration::from_millis(1); loop { cpu.do_cycle(); // if cycles_count > 4 * 10u32.pow(0) { // println!("elapsed {}ms", start.elapsed().as_micros()); // // // let diff = Instant::now().duration_since(prev); // if diff > one_sec { // eprintln!("running late"); // } else { // let remaining = one_sec - diff; // sleep(remaining); // } // // // prev = Instant::now(); // cycles_count = 0; // } } }
true
81a8da42693c207bc0b02ee338205e9c0083c6c3
Rust
boyminty/my_horrible_rust_program
/src/main.rs
UTF-8
2,042
2.921875
3
[]
no_license
use regex::Regex; extern crate clap; use clap::{App, Arg}; use reqwest::blocking; use unicode_segmentation::{UnicodeSegmentation, UnicodeSentences}; // use tokio::io::{AsyncReadExt, AsyncWriteExt}; // use structopt::{StructOpt}; fn main() -> Result<(),Box<dyn std::error::Error>> { let app = App::new("rr") .author("hapash. <boymintyfresh@gmail.com>") .bin_name("my_horrible_rust_program") .arg( Arg::with_name("get") .short("g") .value_name("urls") .required(true) .takes_value(true) .multiple(true), ); let matches = app.get_matches(); let regex_of_url = Regex::new("^(http://)|^(https://)")?; let urls = matches.values_of("get").unwrap(); let mut vals: Vec<String> = urls.map(move | str| str.to_string()).collect(); for vale in & mut vals{ if regex_of_url.is_match(vale.as_str())==true{ println!("{}",vale); continue; } else { vale.insert_str(0, "http://"); println!("{}",vale); } } let client = reqwest::blocking::Client::new(); // let get = client.get("http://gnu.org").send().await?; // let data = &get.text().await?; // println!("{}", data); let data = handle_urls(&client, &vals)?; println!("{}",data[0]); Ok(()) } fn handle_urls( client: &reqwest::blocking::Client, urls: &[String], ) -> Result<Vec<String>, Box<dyn std::error::Error>> { let mut textcontent = Vec::<String>::new(); for url in urls { let result = client.get(url).send(); let respone = match result { Ok(res) => { // println!("cool"); Ok(res) } Err(e) => { eprintln!("the url is:{}\n{}", url, &e); continue; Err(e) } }; let text = respone?.text()?; textcontent.push(text); std::hint::spin_loop(); } Ok(textcontent) }
true
0a4bf55472b1785eaf4940d50c570d4e92422072
Rust
tex-other/tex-rs
/src/section_0899.rs
UTF-8
2,030
2.53125
3
[ "MIT", "Apache-2.0" ]
permissive
//! ` ` // @<Check that the nodes following |hb| permit hyphenation...@>= macro_rules! Check_that_the_nodes_following_hb_permit_hyphenation_and_that_at_least_l_hyf_plus_r_hyf_letters_have_been_found__otherwise_goto_done1 { ($globals:expr, $s:expr, $lbl_done1:lifetime) => {{ region_forward_label!( |'done4| { // if hn<l_hyf+r_hyf then goto done1; {|l_hyf| and |r_hyf| are |>=1|} if ($globals.hn.get() as integer) < $globals.l_hyf + $globals.r_hyf { /// `l_hyf` and `r_hyf` are `>=1` const _ : () = (); goto_forward_label!($lbl_done1); } // loop@+ begin if not(is_char_node(s)) then loop { if !is_char_node!($globals, $s) { // case type(s) of let type_s = r#type!($globals, $s); // ligature_node: do_nothing; if type_s == ligature_node { do_nothing!(); } // kern_node: if subtype(s)<>normal then goto done4; else if type_s == kern_node { if subtype!($globals, $s) as integer != kern_node_subtype::normal as integer { goto_forward_label!('done4); } } // whatsit_node,glue_node,penalty_node,ins_node,adjust_node,mark_node: else if type_s == whatsit_node || type_s == glue_node || type_s == penalty_node || type_s == ins_node || type_s == adjust_node || type_s == mark_node { // goto done4; goto_forward_label!('done4); } // othercases goto done1 else { goto_forward_label!($lbl_done1); } // endcases; } // s:=link(s); $s = link!($globals, $s); // end; } } // done4: 'done4 <- ); use crate::pascal::integer; }} }
true
41a5346bd437f87e65e7003c9c8b4d0c3bd42c28
Rust
uwapcs/discord-bot
/src/util.rs
UTF-8
1,635
2.890625
3
[]
no_license
use serenity::model::{channel::ReactionType, guild::PartialGuild}; pub fn get_string_from_react(react: &ReactionType) -> String { match react { ReactionType::Custom { name: Some(name), .. } => name.to_string(), ReactionType::Custom { id, name: None, .. } => id.to_string(), ReactionType::Unicode(name) => name.to_string(), _ => format!("Unrecognised reaction type: {:?}", react), } } pub fn get_react_from_string(string: String, guild: PartialGuild) -> ReactionType { guild .emojis .values() .find(|e| e.name == string) .map_or_else( || ReactionType::from(string), // unicode emoji |custom_emoji| ReactionType::from(custom_emoji.clone()), ) } #[macro_use] macro_rules! e { ($error: literal, $x:expr) => { match $x { Ok(_) => (), Err(why) => error!($error, why), } }; } #[macro_use] macro_rules! send_message { ($chan:expr, $context:expr, $message:expr) => { $chan.say($context, $message).map_err(|why| { error!("Error sending message: {:?}", why); why }) }; } #[allow(unused_macros)] // remove this if you start using it #[macro_use] macro_rules! send_delete_message { ($chan:expr, $context:expr, $message:expr) => { match $chan.say($context, $message) { Ok(the_new_msg) => e!( "Error deleting register message: {:?}", the_new_msg.delete($context) ), Err(why) => error!("Error sending message: {:?}", why), } }; }
true
e98ded79e17524170a07f7dd9e8b5eebd7c4bd13
Rust
ids1024/rust_os
/Kernel/Core/lib/btree_map.rs
UTF-8
3,103
3.125
3
[ "BSD-2-Clause" ]
permissive
// "Tifflin" Kernel // - By John Hodge (thePowersGang) // // Core/lib/btree_map.rs //! B-Tree map //! //! B-Trees are a more memory/cache efficient version of binary trees, storing up to `b` items //! per node use prelude::*; pub struct BTreeMap<K: Ord,V> { root_node: Node<K,V>, max_node_size: usize, // aka 'b' } // Contains the children for a node struct Node<K, V> { values: Vec< Item<K,V> >, children: Vec< Node<K,V> >, } // Contains an item, and any children before it struct Item<K, V> { key: K, val: V, } pub enum Entry<'a, K: 'a, V: 'a> { Vacant(VacantEntry<'a,K,V>), Occupied(OccupiedEntry<'a,K,V>), } pub struct VacantEntry<'a, K:'a,V:'a> { node: &'a mut Node<K,V>, idx: usize, key: K, } pub struct OccupiedEntry<'a, K:'a,V:'a> { item: &'a mut Item<K,V> } impl<K: Ord,V> BTreeMap<K,V> { pub fn new() -> BTreeMap<K,V> { BTreeMap::with_b(8) } pub fn with_b(b: usize) -> Self { BTreeMap { root_node: Default::default(), max_node_size: b, } } fn rebalance(&mut self) { } fn get_ptr<Q: ?Sized>(&self, key: &Q) -> Option<*mut V> where Q: Ord, K: ::lib::borrow::Borrow<Q> { let mut node = &self.root_node; loop { match node.values.binary_search_by(|v| v.key.borrow().cmp(key)) { Ok(idx) => return Some(&node.values[idx].val as *const _ as *mut _), Err(idx) => if idx <= node.children.len() { node = &node.children[idx]; } else { return None; }, } } } pub fn entry(&mut self, key: K) -> Entry<K,V> { match self.root_node.find(&key) { Ok(it) => Entry::Occupied( OccupiedEntry { item: it } ), Err((nr,idx)) => Entry::Vacant( VacantEntry { node: nr, idx: idx, key: key } ) } } pub fn get<Q: ?Sized>(&self, key: &Q) -> Option<&V> where Q: Ord, K: ::lib::borrow::Borrow<Q> { // SAFE: get_ptr returns a valid pointer, self is & so no mut possible unsafe { self.get_ptr(key).map(|x| &*x) } } pub fn get_mut<Q: ?Sized>(&mut self, key: &Q) -> Option<&mut V> where Q: Ord, K: ::lib::borrow::Borrow<Q> { // SAFE: get_ptr returns a valid pointer, self is &mut so no aliasing unsafe { self.get_ptr(key).map(|x| &mut *x) } } } impl<K: Ord, V> Default for BTreeMap<K,V> { fn default() -> BTreeMap<K,V> { BTreeMap::new() } } impl<K: Ord, V> Node<K,V> { fn find(&mut self, key: &K) -> Result<&mut Item<K,V>, (&mut Node<K,V>, usize)> { match self.values.binary_search_by(|v| v.key.cmp(&key)) { Ok(idx) => Ok( &mut self.values[idx] ), Err(idx) => if idx < self.children.len() { self.children[idx].find(key) } else { Err( (self, idx) ) }, } } } impl<K,V> Default for Node<K,V> { fn default() -> Node<K,V> { Node { values: Default::default(), children: Default::default(), } } } impl<'a,K,V> VacantEntry<'a,K,V> { pub fn insert(self, value: V) -> &'a mut V { // 1. Allocate a slot (which may require splitting a node and hence rebalancing the tree) unimplemented!() } } impl<'a,K,V> OccupiedEntry<'a,K,V> { pub fn get_mut(&mut self) -> &mut V { &mut self.item.val } pub fn into_mut(self) -> &'a mut V { &mut self.item.val } }
true
46a0b4b24050a63bb0aab0edebdc32ac8fba56b1
Rust
mapleFU/md-snippets
/components/ratelimiter/src/leaky_bucket.rs
UTF-8
1,996
2.75
3
[]
no_license
use crate::{Config, Limiter}; use std::time::SystemTime; use chrono::Duration as ChronoDuration; use std::sync::{Arc, Mutex}; fn max_slack_time(slack_seconds: u32) -> ChronoDuration { ChronoDuration::seconds(slack_seconds as i64) * -1 } #[derive(Clone)] pub struct LeakyBucketLimiter { limiter: Arc<Mutex<LeakyBucketLimiterImpl>>, } impl LeakyBucketLimiter { pub fn new(conf: Config) -> Self { LeakyBucketLimiter { limiter: Arc::new(Mutex::new(LeakyBucketLimiterImpl { last: None, sleep_dur: ChronoDuration::seconds(0), conf: conf, })), } } } pub struct LeakyBucketLimiterImpl { last: Option<SystemTime>, sleep_dur: ChronoDuration, // immutable conf: Config, } impl LeakyBucketLimiterImpl { fn take_impl(&mut self) -> SystemTime { let now = self.conf.clock.now(); if let None = self.last { self.last = Some(now); return now; } self.sleep_dur = ChronoDuration::from_std(self.conf.per_req).unwrap() + ChronoDuration::from_std(now.duration_since(self.last.unwrap()).unwrap()).unwrap(); if self.sleep_dur < max_slack_time(self.conf.slack) { self.sleep_dur = max_slack_time(self.conf.slack); } if self.sleep_dur > ChronoDuration::seconds(0) { let current_sleep_duration = self.sleep_dur.to_std().unwrap(); self.sleep_dur = ChronoDuration::seconds(0); self.conf.clock.sleep(current_sleep_duration); self.last = now.checked_add(current_sleep_duration); } else { self.last = Some(now); } // Note: it must hold the right value. self.last.unwrap() } } unsafe impl Sync for LeakyBucketLimiter {} unsafe impl Send for LeakyBucketLimiter {} impl Limiter for LeakyBucketLimiter { fn take(&self) -> SystemTime { self.limiter.lock().unwrap().take_impl() } }
true
17fcfc233f29e0cdc0be9bfa8d9f5845584d0bdf
Rust
FreddieRidell/hypertask
/rust/hypertask_engine/src/error.rs
UTF-8
4,493
3.078125
3
[]
no_license
use std::error::Error; use std::fmt; #[derive(Debug, PartialEq)] pub enum HyperTaskErrorDomain { Render, Config, Input, Mutation, Query, ScoreCalculator, Task, Syncing, } impl fmt::Display for HyperTaskErrorDomain { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "{}", match self { HyperTaskErrorDomain::Config => "config", HyperTaskErrorDomain::Syncing => "syncing", HyperTaskErrorDomain::Render => "render", HyperTaskErrorDomain::Input => "input", HyperTaskErrorDomain::Mutation => "mutation", HyperTaskErrorDomain::Query => "query", HyperTaskErrorDomain::ScoreCalculator => "scoreCalculator", HyperTaskErrorDomain::Task => "task", } ) } } #[derive(Debug, PartialEq)] pub enum HyperTaskErrorAction { Compare, Create, Delete, Parse, Read, Run, Write, } impl fmt::Display for HyperTaskErrorAction { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "{}", match self { HyperTaskErrorAction::Compare => "compare", HyperTaskErrorAction::Create => "create", HyperTaskErrorAction::Delete => "delete", HyperTaskErrorAction::Parse => "parse", HyperTaskErrorAction::Read => "read", HyperTaskErrorAction::Run => "run", HyperTaskErrorAction::Write => "write", } ) } } #[derive(Debug)] pub struct HyperTaskError { domain: HyperTaskErrorDomain, action: HyperTaskErrorAction, meta: Option<String>, source: Option<Box<dyn Error + 'static>>, } pub type HyperTaskResult<T> = Result<T, HyperTaskError>; impl HyperTaskError { pub fn new(domain: HyperTaskErrorDomain, action: HyperTaskErrorAction) -> Self { Self { domain, action, meta: None, source: None, } } pub fn msg(mut self, meta: &'static str) -> Self { self.meta = Some(meta.to_owned()); self } pub fn with_msg<F: Fn() -> String>(mut self, meta_factory: F) -> Self { self.meta = Some(meta_factory()); self } pub fn from<E: 'static + Error>(mut self, source: E) -> Self { self.source = Some(Box::new(source)); self } } unsafe impl std::marker::Sync for HyperTaskError {} unsafe impl std::marker::Send for HyperTaskError {} impl PartialEq for HyperTaskError { fn eq(&self, other: &HyperTaskError) -> bool { self.domain == other.domain && self.action == other.action } } impl fmt::Display for HyperTaskError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "HyperTaskError[{}::{}]", self.domain, self.action)?; if let Some(meta_text) = &self.meta { write!(f, ": {}", meta_text)? } Ok(()) } } impl Error for HyperTaskError { fn source(&self) -> Option<&(dyn Error + 'static)> { if let Some(source_box) = &self.source { Some(source_box.as_ref()) } else { None } } } impl From<HyperTaskError> for String { fn from(error: HyperTaskError) -> Self { format!("{}", error) } } #[cfg(target_arch = "wasm32")] impl Into<wasm_bindgen::JsValue> for HyperTaskError { fn into(self) -> wasm_bindgen::JsValue { wasm_bindgen::JsValue::from_str(&format!("{}", self)) } } pub fn print_error_chain(err: &(dyn Error + 'static)) { print_error_chain_recursive(err, 1) } pub fn print_error_chain_recursive(err: &(dyn Error + 'static), i: u32) { error!("Error {}: {}", i, err); if let Some(boxed_source) = err.source() { print_error_chain_recursive(boxed_source, i + 1); } } pub fn run_result_producing_function(r: Result<(), HyperTaskError>) { if let Err(e) = r { print_error_chain(&e); } } #[cfg(all(test, target_arch = "wasm32"))] mod test { extern crate wasm_bindgen_test; use super::*; use wasm_bindgen::JsValue; use wasm_bindgen_test::*; #[wasm_bindgen_test] fn can_convert_hypertask_error_to_js_value() { let error = HyperTaskError::new(HyperTaskErrorDomain::Syncing, HyperTaskErrorAction::Run); let _js_value: JsValue = error.into(); } }
true
e2540ed6abcd336f28771c6eaa024b6a494d4bdb
Rust
pdav/z33-emulator
/emulator/src/runtime/instructions.rs
UTF-8
15,911
3.171875
3
[ "MIT" ]
permissive
use std::convert::TryInto; use parse_display::Display; use tracing::{debug, info}; use crate::constants::*; use super::{ arguments::{DirIndIdx, ExtractValue, ImmReg, ImmRegDirIndIdx, RegDirIndIdx, ResolveAddress}, exception::Exception, memory::Cell, registers::{Reg, StatusRegister}, Computer, ProcessorError, }; #[derive(Debug, Clone, PartialEq, Display)] pub enum Instruction { /// Add a value to a register #[display("add {0}, {1}")] Add(ImmRegDirIndIdx, Reg), /// Bitwise `and` with a given value #[display("and {0}, {1}")] And(ImmRegDirIndIdx, Reg), /// Push `%pc` and go to the given address #[display("call {0}")] Call(ImmRegDirIndIdx), /// Compare a value with a register #[display("cmp {0}, {1}")] Cmp(ImmRegDirIndIdx, Reg), /// Divide a register by a value #[display("div {0}, {1}")] Div(ImmRegDirIndIdx, Reg), /// Load a memory cell to a register and set this cell to 1 #[display("fas {0}, {1}")] Fas(DirIndIdx, Reg), /// Read a value from an I/O controller #[display("in {0}, {1}")] In(DirIndIdx, Reg), /// Unconditional jump #[display("jmp {0}")] Jmp(ImmRegDirIndIdx), /// Jump if equal #[display("jeq {0}")] Jeq(ImmRegDirIndIdx), /// Jump if not equal #[display("jne {0}")] Jne(ImmRegDirIndIdx), /// Jump if less or equal #[display("jle {0}")] Jle(ImmRegDirIndIdx), /// Jump if strictly less #[display("jlt {0}")] Jlt(ImmRegDirIndIdx), /// Jump if greater of equal #[display("jge {0}")] Jge(ImmRegDirIndIdx), /// Jump if strictly greater #[display("jgt {0}")] Jgt(ImmRegDirIndIdx), /// Load a register with a value #[display("ld {0}, {1}")] Ld(ImmRegDirIndIdx, Reg), /// Multiply a value to a register #[display("mul {0}, {1}")] Mul(ImmRegDirIndIdx, Reg), #[display("neg {0}")] Neg(Reg), /// No-op #[display("nop")] Nop, /// Bitwise negation of a register #[display("not {0}")] Not(Reg), /// Bitwise `or` with a given value #[display("or {0}, {1}")] Or(ImmRegDirIndIdx, Reg), /// Write a value to an I/O controller #[display("out {0}, {1}")] Out(ImmReg, DirIndIdx), /// Pop a value from the stack #[display("pop {0}")] Pop(Reg), /// Push a value into the stack #[display("push {0}")] Push(ImmReg), /// Reset the computer #[display("reset")] Reset, /// Return from an interrupt or an exception #[display("rti")] Rti, /// Return from a `call` #[display("rtn")] Rtn, /// Bitshift to the left #[display("shl {0}, {1}")] Shl(ImmRegDirIndIdx, Reg), /// Bitshift to the right #[display("shr {0}, {1}")] Shr(ImmRegDirIndIdx, Reg), /// Store a register value in memory #[display("st {0}, {1}")] St(Reg, DirIndIdx), /// Substract a value from a register #[display("sub {0}, {1}")] Sub(ImmRegDirIndIdx, Reg), /// Swap a value and a register #[display("swap {0}, {1}")] Swap(RegDirIndIdx, Reg), /// Start a `trap` exception #[display("trap")] Trap, /// Bitwise `xor` with a given value #[display("xor {0}, {1}")] Xor(ImmRegDirIndIdx, Reg), /// Show registers content #[display("debugreg")] DebugReg, } impl Instruction { /// Execute the instruction #[tracing::instrument(skip(computer))] pub(crate) fn execute(&self, computer: &mut Computer) -> Result<(), ProcessorError> { use Instruction::*; match self { Add(arg, reg) => { let a = arg.extract_word(computer)?; let b = reg.extract_word(computer)?; let (res, overflow) = a.overflowing_add(b); debug!("{} + {} = {}", a, b, res); computer.set_register(reg, res.into())?; computer .registers .sr .set(StatusRegister::OVERFLOW, overflow); } And(arg, reg) => { let a = arg.extract_word(computer)?; let b = reg.extract_word(computer)?; let res = a & b; debug!("{} & {} = {}", a, b, res); computer.set_register(reg, res.into())?; } Call(arg) => { // Push PC let pc = computer.registers.pc; computer.push(pc)?; // Jump let addr = arg.extract_address(computer)?; computer.jump(addr); } Cmp(arg, reg) => { let a = arg.extract_word(computer)?; let b = reg.extract_word(computer)?; computer.registers.sr.set(StatusRegister::ZERO, a == b); computer.registers.sr.set(StatusRegister::NEGATIVE, a < b); debug!( "cmp({}, {}) => {:?}", a, b, computer.registers.sr & (StatusRegister::ZERO | StatusRegister::NEGATIVE) ); } Div(arg, reg) => { let a = arg.extract_word(computer)?; let b = reg.extract_word(computer)?; let res = b.checked_div(a).ok_or(Exception::DivByZero)?; debug!("{} / {} = {}", b, a, res); computer.set_register(reg, res.into())?; } Fas(addr, reg) => { let addr = addr.resolve_address(&computer.registers)?; let cell = computer.memory.get_mut(addr)?; let val = cell.clone(); *cell = Cell::Word(1); computer.set_register(reg, val)?; } In(_, _) => { computer.check_privileged()?; todo!(); } Jmp(arg) => { let val = arg.extract_address(computer)?; debug!("Jumping to address {:#x}", val); computer.registers.pc = val; } Jeq(arg) => { if computer.registers.sr.contains(StatusRegister::ZERO) { let val = arg.extract_address(computer)?; debug!("Jumping to address {:#x}", val); computer.registers.pc = val; } } Jne(arg) => { if !computer.registers.sr.contains(StatusRegister::ZERO) { let val = arg.extract_address(computer)?; debug!("Jumping to address {:#x}", val); computer.registers.pc = val; } } Jle(arg) => { if computer.registers.sr.contains(StatusRegister::ZERO) || computer.registers.sr.contains(StatusRegister::NEGATIVE) { let val = arg.extract_address(computer)?; debug!("Jumping to address {:#x}", val); computer.registers.pc = val; } } Jlt(arg) => { if !computer.registers.sr.contains(StatusRegister::ZERO) && computer.registers.sr.contains(StatusRegister::NEGATIVE) { let val = arg.extract_address(computer)?; debug!("Jumping to address {:#x}", val); computer.registers.pc = val; } } Jge(arg) => { if computer.registers.sr.contains(StatusRegister::ZERO) || !computer.registers.sr.contains(StatusRegister::NEGATIVE) { let val = arg.extract_address(computer)?; debug!("Jumping to address {:#x}", val); computer.registers.pc = val; } } Jgt(arg) => { if !computer.registers.sr.contains(StatusRegister::ZERO) && !computer.registers.sr.contains(StatusRegister::NEGATIVE) { let val = arg.extract_address(computer)?; debug!("Jumping to address {:#x}", val); computer.registers.pc = val; } } Ld(arg, reg) => { let val = arg.extract_cell(computer)?; computer.set_register(reg, val)?; } Mul(arg, reg) => { let a = arg.extract_word(computer)?; let b = reg.extract_word(computer)?; let (res, overflow) = a.overflowing_mul(b); debug!("{} * {} = {}", a, b, res); computer.set_register(reg, res.into())?; computer .registers .sr .set(StatusRegister::OVERFLOW, overflow); } Neg(reg) => { let val = reg.extract_word(computer)?; let res = -(val as i64); let res = res as Word; debug!("-{} = {}", val, res); computer.set_register(reg, res.into())?; } Nop => {} Not(reg) => { let val = reg.extract_word(computer)?; let res = !val; debug!("!{} = {}", val, res); computer.set_register(reg, res.into())?; } Or(arg, reg) => { let a = arg.extract_word(computer)?; let b = reg.extract_word(computer)?; let res = a | b; debug!("{} | {} = {}", a, b, res); computer.set_register(reg, res.into())?; } Out(_, _) => { computer.check_privileged()?; todo!() } Pop(reg) => { let val = computer.pop()?.clone(); debug!("pop => {:?}", val); computer.set_register(reg, val)?; } Push(val) => { let val = val.extract_cell(computer)?; debug!("push({:?})", val); computer.push(val)?; } Reset => return Err(ProcessorError::Reset), Rti => { computer.check_privileged()?; computer.registers.pc = computer.memory.get(INTERRUPT_PC_SAVE)?.extract_address()?; computer.registers.sr = StatusRegister::from_bits_truncate( computer.memory.get(INTERRUPT_SR_SAVE)?.extract_word()?, ); } Rtn => { let ret = computer.pop()?; // Pop the return address let ret = ret.extract_address()?; // Convert it to an address debug!("Returning to {}", ret); computer.registers.pc = ret; // and jump to it } Shl(arg, reg) => { let a = arg.extract_word(computer)?; let b = reg.extract_word(computer)?; let b: u32 = b.try_into().map_err(|_| Exception::InvalidInstruction)?; let res = a.checked_shl(b).ok_or(Exception::InvalidInstruction)?; debug!("{} << {} = {}", a, b, res); computer.set_register(reg, res.into())?; } Shr(arg, reg) => { let a = arg.extract_word(computer)?; let b = reg.extract_word(computer)?; let b: u32 = b.try_into().map_err(|_| Exception::InvalidInstruction)?; let res = a.checked_shr(b).ok_or(Exception::InvalidInstruction)?; debug!("{} >> {} = {}", a, b, res); computer.set_register(reg, res.into())?; } St(reg, address) => { let val = reg.extract_word(computer)?; let address = address.resolve_address(&computer.registers)?; computer.write(address, val)?; } Sub(arg, reg) => { let a = arg.extract_word(computer)?; let b = reg.extract_word(computer)?; let (res, overflow) = b.overflowing_sub(a); computer.set_register(reg, res.into())?; debug!("{} - {} = {}", b, a, res); computer .registers .sr .set(StatusRegister::OVERFLOW, overflow); } Swap(arg, reg) => { // First we extract the value from both arguments let value = arg.extract_cell(computer)?; let value2 = reg.extract_cell(computer)?; // And set the value of the register specified by the second argument computer.set_register(reg, value)?; // Then handle the two kind of cases: a register and a memory address if let RegDirIndIdx::Reg(arg) = arg { // Set the value of the register by the first argument computer.set_register(arg, value2)?; } else { // Convert the reg/dir/ind/idx arg to only dir/ind/idx, since we already // handled the reg case. Despite the unwrap, this should never fail. let arg: DirIndIdx = arg.clone().try_into().unwrap(); // Resolve the address and write the second value let addr = arg.resolve_address(&computer.registers)?; computer.write(addr, value2)?; } } Trap => { return Err(Exception::Trap.into()); } Xor(arg, reg) => { let a = arg.extract_word(computer)?; let b = reg.extract_word(computer)?; let res = a ^ b; debug!("{} ^ {} = {}", a, b, res); computer.set_register(reg, res.into())?; } DebugReg => { info!("debugreg: {}", computer.registers); } }; Ok(()) } /// Get the total cost of an instruction in terms of CPU cycles pub(crate) const fn cost(&self) -> usize { use Instruction::*; // All instruction cost one CPU cycle itself, plus the cost of each of its arguments match self { DebugReg => 0, // The only exception being `debugreg`, which costs nothing Add(a, b) => 1 + a.cost() + b.cost(), And(a, b) => 1 + a.cost() + b.cost(), Call(a) => 1 + a.cost(), Cmp(a, b) => 1 + a.cost() + b.cost(), Div(a, b) => 1 + a.cost() + b.cost(), Fas(a, b) => 1 + a.cost() + b.cost(), In(a, b) => 1 + a.cost() + b.cost(), Jmp(a) => 1 + a.cost(), Jeq(a) => 1 + a.cost(), Jne(a) => 1 + a.cost(), Jle(a) => 1 + a.cost(), Jlt(a) => 1 + a.cost(), Jge(a) => 1 + a.cost(), Jgt(a) => 1 + a.cost(), Ld(a, b) => 1 + a.cost() + b.cost(), Mul(a, b) => 1 + a.cost() + b.cost(), Neg(a) => 1 + a.cost(), Nop => 1, Not(a) => 1 + a.cost(), Or(a, b) => 1 + a.cost() + b.cost(), Out(a, b) => 1 + a.cost() + b.cost(), Pop(a) => 1 + a.cost(), Push(a) => 1 + a.cost(), Reset => 1, Rti => 1, Rtn => 1, Shl(a, b) => 1 + a.cost() + b.cost(), Shr(a, b) => 1 + a.cost() + b.cost(), St(a, b) => 1 + a.cost() + b.cost(), Sub(a, b) => 1 + a.cost() + b.cost(), Swap(a, b) => 1 + a.cost() + b.cost(), Trap => 1, Xor(a, b) => 1 + a.cost() + b.cost(), } } }
true
8c151660f201f7730029ae2baae2a799be106347
Rust
Origen-SDK/o2
/rust/origen/src/generator/processors/pin_action_combiner.rs
UTF-8
3,984
3.234375
3
[ "MIT" ]
permissive
//! A simple processor which will combine pin actions not separated by a cycle into a single PinAction node use super::super::nodes::PAT; use crate::Result; use origen_metal::ast::{Node, Processor, Return}; use std::collections::HashMap; /// Combines adjacent pin actions into a single pin action pub struct PinActionCombiner { current_state: HashMap<usize, String>, i: usize, first_pass: bool, delete_current_index: bool, indices_to_delete: Vec<usize>, } /// Combines pin actions so that only pin actions which change the pin states are left. /// Note: this processor assumes that anything that touches PinAction nodes has already completed. /// Because some form of lookahead is needed, and to avoid missing actions that may occur in child nodes, /// this processor is run in two passes: /// First, all nodes are run through and indices of pin changes are marked. /// Second, all non-PinAction nodes are copied over, with only PinAction nodes whose indices were marked are copied over. impl PinActionCombiner { pub fn run(node: &Node<PAT>) -> Result<Node<PAT>> { let mut p = PinActionCombiner { current_state: HashMap::new(), i: 0, first_pass: true, delete_current_index: false, indices_to_delete: vec![], }; node.process(&mut p)?.unwrap(); p.advance_to_second_pass(); let n = node.process(&mut p)?.unwrap(); Ok(n) } pub fn advance_to_second_pass(&mut self) { self.i = 0; self.first_pass = false; } } impl Processor<PAT> for PinActionCombiner { fn on_node(&mut self, node: &Node<PAT>) -> origen_metal::Result<Return<PAT>> { match &node.attrs { // Grab the pins and push them into the running vectors, then delete this node. PAT::PinGroupAction(_grp_id, _actions, _metadata) => { if self.first_pass { // On the first pass, only mark the pin group's index self.delete_current_index = true; Ok(Return::ProcessChildren) } else { // On the second pass, delete the pin group if necessary if self.indices_to_delete.contains(&self.i) { self.i += 1; Ok(Return::None) } else { self.i += 1; Ok(Return::Unmodified) } } } PAT::PinAction(pin_id, action, _metadata) => { if self.first_pass { // Compare to the last seen pin actions. If these are the same, then this node can be deleted on the next pass. // If they're different, then these updates must be saved. if let Some(a) = self.current_state.get_mut(pin_id) { if a != action { self.delete_current_index = false; self.current_state.insert(*pin_id, action.clone()); } } else { self.current_state.insert(*pin_id, action.clone()); self.delete_current_index = false; } } Ok(Return::Unmodified) } _ => Ok(Return::ProcessChildren), } } fn on_end_of_block(&mut self, node: &Node<PAT>) -> origen_metal::Result<Return<PAT>> { match &node.attrs { PAT::PinGroupAction(_grp_id, _actions, _metadata) => { if self.first_pass { if self.delete_current_index { self.indices_to_delete.push(self.i); } self.delete_current_index = false; } self.i += 1; Ok(Return::None) } _ => Ok(Return::None), } } }
true
6f7ad37c9bd298871788afdf87fda35917ffbcc0
Rust
bollo35/cryptopals
/src/bin/p026.rs
UTF-8
1,491
3.078125
3
[]
no_license
extern crate ooga; use ooga::cipher_utils::ctr_stream; use ooga::byte_utils::xor; extern crate rand; use rand::Rng; fn main() { // generate a random key let mut rng = rand::thread_rng(); let key = rng.gen_iter::<u8>().take(16).collect::<Vec<u8>>(); let mut ciphertext = user_input(b":admin<true", &key); ciphertext[32] ^= 0x01; ciphertext[38] ^= 0x01; let success = dec_and_search(&ciphertext, &key); println!("Success? {}", success); } fn user_input(input: &[u8], key: &[u8]) -> Vec<u8> { let prefix = b"comment1=cooking%20MCs;userdata="; let suffix = b";comment2=%20like%20a%20pound%20of%20bacon"; let mut to_enc = Vec::with_capacity(prefix.len() + input.len() + suffix.len()); to_enc.extend_from_slice(&prefix[..]); // quote ';' and '=' characters for byte in input { if *byte == b';' || *byte == b'=' { to_enc.push(b'"'); to_enc.push(*byte); to_enc.push(b'"'); } else { to_enc.push(*byte); } } to_enc.extend_from_slice(&suffix[..]); let num_blocks = to_enc.len() / 16 + if to_enc.len() % 16 > 0 { 1 } else { 0 }; let nonce = [0u8;8]; let stream = ctr_stream(&key, &nonce, num_blocks as usize); xor(&to_enc, &stream) } fn dec_and_search(ciphertext: &[u8], key: &[u8]) -> bool { let num_blocks = (ciphertext.len() + 16) / 16; let nonce = [0u8;8]; let stream = ctr_stream(&key, &nonce, num_blocks as usize); let decrypted = xor(&ciphertext, &stream); let string = String::from_utf8(decrypted).unwrap(); string.contains(";admin=true;") }
true
6e64b33873c9622cf7fb88c5b3c6bc5755b4ab45
Rust
bnavetta/lifx-rs
/lifx-proto/src/color.rs
UTF-8
2,892
3.453125
3
[]
no_license
use std::{convert::TryFrom, f32, u16}; use bytes::{Buf, BufMut}; use thiserror::Error; use crate::ProtocolError; /// Color and color temperature, represented in HSB and Kelvin #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Hsbk { pub hue: u16, pub saturation: u16, pub brightness: u16, pub temperature: Kelvin, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Kelvin(u16); impl Hsbk { /// Size of a Hsbk value on the wire, in bytes pub const SIZE: usize = 8; pub fn encode<B: BufMut>(self, buf: &mut B) { buf.put_u16_le(self.hue); buf.put_u16_le(self.saturation); buf.put_u16_le(self.brightness); buf.put_u16_le(self.temperature.0); } pub fn decode<B: Buf>(buf: &mut B) -> Result<Hsbk, ProtocolError> { let hue = buf.get_u16_le(); let saturation = buf.get_u16_le(); let brightness = buf.get_u16_le(); let temperature = Kelvin::try_from(buf.get_u16_le()).map_err(|err| ProtocolError::InvalidPayload(err.to_string()))?; Ok(Hsbk { hue, saturation, brightness, temperature }) } } impl Kelvin { pub fn new(value: u16) -> Kelvin { Kelvin::try_from(value).expect("Temperature out of bounds") } } impl TryFrom<u16> for Kelvin { type Error = KelvinError; fn try_from(value: u16) -> Result<Self, Self::Error> { match value { 2500..=9000 => Ok(Kelvin(value)), _ => Err(KelvinError(value)) } } } #[cfg(feature = "palette")] impl Hsbk { pub fn new(color: palette::Hsv, temperature: Kelvin) -> Hsbk { use palette::Component; // Palette's Hsv type requires that components be floats, so we have to decompose it and convert to u16 ourselves let (hue, saturation, value) = color.into_components(); // Scale the 0-360 value to an 0-2^16 value let hue_degrees = (u16::MAX as f32) * (hue.to_positive_degrees() / 360f32); let hue_int = hue_degrees.round() as u16; let saturation_int = saturation.convert::<u16>(); let value_int = value.convert::<u16>(); Hsbk { hue: hue_int, saturation: saturation_int, brightness: value_int, temperature } } pub fn color(&self) -> palette::Hsv { use palette::{Component, Hsv, RgbHue}; // Scale the 0-2^16 value to an 0-360 value let hue = RgbHue::from_degrees((self.hue as f32) / (std::u16::MAX as f32) * 360f32); let saturation = self.saturation.convert::<f32>(); let value = self.brightness.convert::<f32>(); Hsv::new(hue, saturation, value) } } #[derive(Error, Debug)] #[error("invalid Kelvin value: {0}")] pub struct KelvinError(u16); impl Into<u16> for Kelvin { fn into(self) -> u16 { self.0 } }
true
e37ea3490fbcfc096eb12e1b59f039a7ce5ba684
Rust
lcdsmao/leetcode-rust
/problem/src/solution/p041_first_missing_positive.rs
UTF-8
1,051
3.546875
4
[ "MIT" ]
permissive
pub struct Solution {} impl Solution { pub fn first_missing_positive(nums: Vec<i32>) -> i32 { let mut nums = nums; // LeetCode rust version is old // let valid_range = 1..=(nums.len() as i32); for i in 0..nums.len() { let mut n = nums[i]; while n >= 1 && n < (nums.len() as i32) && n != nums[(n - 1) as usize] && n != i as i32 + 1 { nums.swap(i, (n - 1) as usize); n = nums[i] } } for (i, &n) in nums.iter().enumerate() { if n != i as i32 + 1 { return i as i32 + 1; } } nums.len() as i32 + 1 } } #[cfg(test)] mod tests { use super::*; #[test] fn it_works() { assert_eq!(Solution::first_missing_positive(vec![1, 2, 0]), 3); assert_eq!(Solution::first_missing_positive(vec![3, 4, -1, 1]), 2); assert_eq!(Solution::first_missing_positive(vec![7, 8, 9, 11, 12]), 1); } }
true
316b3f38af56da4242c2836ef6f9b4ca9f6713ed
Rust
jimpo/experiments
/bulletproof-gadgets/src/main.rs
UTF-8
11,873
2.640625
3
[]
no_license
use bulletproofs::r1cs::{ ConstraintSystem, LinearCombination, Prover, R1CSError, Variable, Verifier, }; use bulletproofs::{ BulletproofGens, PedersenGens, }; use curve25519_dalek::scalar::Scalar; use merlin::Transcript; use rand::Rng; use std::u64; struct TaxBrackets(Vec<(u64, u64)>); fn negate_bit<T>(x: T) -> LinearCombination where T: Into<LinearCombination> { LinearCombination::from(Variable::One()) - x } fn scalar_to_bits_le<CS: ConstraintSystem>( cs: &mut CS, n_bits: usize, var: LinearCombination ) -> Result<Vec<Variable>, R1CSError> { // This is a helper function that caches the evaluation of the input variable so that it // doesn't get recomputed and verified for each bit allocation. let mut cache_evaluation = { let get_bit = |scalar: &Scalar, i: usize| (scalar.as_bytes()[i >> 3] >> (i & 7)) & 1; let local_var = var.clone(); let mut val_cache = None; move |eval: &dyn Fn(&LinearCombination) -> Scalar, i: usize| -> Result<u8, R1CSError> { if val_cache.is_none() { let val = eval(&local_var); let valid = (n_bits..256).any(|i| get_bit(&val, i) == 0); val_cache = Some( if valid { Ok(val) } else { Err(R1CSError::GadgetError { description: format!("Value is not represented in {} bits", n_bits) }) } ); } val_cache.as_ref() .expect("the value must have been computed and cached by the block above") .as_ref() .map(|scalar| get_bit(scalar, i)) .map_err(|e| e.clone()) } }; let bit_vars = (0..n_bits) .map(|i| { let (lhs, rhs, out) = cs.allocate(|eval| { let bit = cache_evaluation(eval, i)?; Ok((bit.into(), (1 - bit).into(), Scalar::zero())) })?; // Enforce that lhs variable represents a bit. // b (1 - b) = 0 cs.constrain(LinearCombination::default() + rhs + lhs - Variable::One()); cs.constrain(out.into()); Ok(lhs) }) .collect::<Result<Vec<_>, _>>()?; let two_powers = (0..n_bits).map(|i| { let mut two_power_repr = [0u8; 32]; two_power_repr[i >> 3] |= 1 << (i & 7); Scalar::from_bits(two_power_repr) }); let bit_sum = bit_vars.iter() .cloned() .zip(two_powers) .collect::<LinearCombination>(); // Enforce that var is equal to the inner product of the bits with powers of two. cs.constrain(var - bit_sum); Ok(bit_vars) } fn lt_gate<CS: ConstraintSystem>( cs: &mut CS, n_bits: usize, lhs: LinearCombination, rhs: LinearCombination ) -> Result<LinearCombination, R1CSError> { let lhs_bits = scalar_to_bits_le(cs, n_bits, lhs)?; let rhs_bits = scalar_to_bits_le(cs, n_bits, rhs)?; let zero = LinearCombination::default(); // Iterate through bits from most significant to least, comparing each pair. let (lt, _) = lhs_bits.into_iter().zip(rhs_bits.into_iter()) .rev() .fold((zero.clone(), zero.clone()), |(lt, gt), (l_bit, r_bit)| { // lt and gt are boolean LinearCombinations that are 1 if lhs < rhs or lhs > rhs // respectively after the first i most significant bits. // Invariant: lt & gt will never both be 1, so (lt || gt) = (lt + gt). // eq = !(lt || gt) let eq = negate_bit(lt.clone() + gt.clone()); // Whether left bit i is < or > right bit i. // bit_lt = !l_bit && r_bit = (1 - l_bit) * r_bit // bit_gt = l_bit && !r_bit = l_bit * (1 - r_bit) let (_, _, bit_lt) = cs.multiply(negate_bit(l_bit), r_bit.into()); let (_, _, bit_gt) = cs.multiply(l_bit.into(), negate_bit(r_bit)); // new_lt = lt + eq && bit_lt // -> lt_diff = new_lt - lt = eq * bit_lt // new_gt = gt + eq && bit_gt // -> gt_diff = new_gt - gt = eq * bit_gt let (_, _, lt_diff) = cs.multiply(eq.clone(), bit_lt.into()); let (_, _, gt_diff) = cs.multiply(eq.clone(), bit_gt.into()); (lt + lt_diff, gt + gt_diff) }); Ok(lt) } fn synthesize<CS: ConstraintSystem>( cs: &mut CS, brackets: &TaxBrackets, values: &[Variable], expected: &Variable ) -> Result<(), R1CSError> { // Compute Σ values. let total = values.iter() .map(|val| (val.clone(), Scalar::one())) .collect::<LinearCombination>(); let mut last_cutoff = Scalar::zero(); let mut cumulative = LinearCombination::default(); for (cutoff, rate) in brackets.0.iter() { let next_cutoff = Scalar::from(*cutoff); let rate_scalar = Scalar::from(*rate); let gt_last = lt_gate(cs, 64, last_cutoff.into(), total.clone())?; let gt_next = lt_gate(cs, 64, next_cutoff.into(), total.clone())?; let (_, _, between_last_next) = cs.multiply(gt_last.clone(), negate_bit(gt_next.clone())); let (_, _, between_value) = cs.multiply( total.clone() - last_cutoff, LinearCombination::from(between_last_next) * rate_scalar ); let (_, _, exceeds_value) = cs.multiply( LinearCombination::from(next_cutoff - last_cutoff), gt_next * rate_scalar ); cumulative = cumulative + between_value + exceeds_value; last_cutoff = next_cutoff; } cumulative = cumulative - expected.clone(); cs.constrain(cumulative); Ok(()) } fn compute_taxes(brackets: &TaxBrackets, total: u64) -> u64 { (0..brackets.0.len()) .map(|i| { let last_cutoff = if i == 0 { 0u64 } else { brackets.0[i-1].0 }; let (next_cutoff, rate) = brackets.0[i]; let amount = if total > next_cutoff { next_cutoff - last_cutoff } else if total > last_cutoff { total - last_cutoff } else { 0 }; amount * rate }) .fold(0, |sum, v| sum + v) } fn main() { let brackets = TaxBrackets(vec![ (952500, 10), (3870000, 12), (8250000, 22), (15750000, 24), (20000000, 32), (50000000, 35), (u64::MAX, 37), ]); let pc_gens = PedersenGens::default(); let bp_gens = BulletproofGens::new(8192, 1); let mut prover_transcript = Transcript::new(b"zk taxes"); let mut prover = Prover::new( &bp_gens, &pc_gens, &mut prover_transcript, ); let mut rng = rand::thread_rng(); let income_amounts = (0..4) // Multiply by 100 cents to ensure there is no rounding necessary. .map(|_| rng.gen_range(0, 100000) * 100) .collect::<Vec<_>>(); let total_income = income_amounts.iter().fold(0, |sum, v| sum + v); let total_tax = compute_taxes(&brackets, total_income); println!("Total: {}, Taxes: {}", total_income, total_tax); let inputs = income_amounts.iter() .map(|value| (Scalar::from(*value), Scalar::random(&mut rng))) .collect::<Vec<_>>(); let output_v = Scalar::from(total_tax); let output_r = Scalar::random(&mut rng); let (input_pts, input_vars) = inputs.iter() .map(|(v, r)| prover.commit(*v, *r)) .unzip::<_, _, Vec<_>, Vec<_>>(); let (output_pt, output_var) = prover.commit(output_v, output_r); synthesize(&mut prover, &brackets, &input_vars, &output_var).unwrap(); let proof = prover.prove().unwrap(); let mut verifier_transcript = Transcript::new(b"zk taxes"); let mut verifier = Verifier::new( &bp_gens, &pc_gens, &mut verifier_transcript, ); let input_vars = input_pts.iter() .map(|pt| verifier.commit(*pt)) .collect::<Vec<_>>(); let output_var = verifier.commit(output_pt); synthesize(&mut verifier, &brackets, &input_vars, &output_var).unwrap(); assert!(verifier.verify(&proof).is_ok()); println!("Success!"); } #[cfg(test)] mod tests { use super::*; #[test] fn test_to_bits_gadget() { let pc_gens = PedersenGens::default(); let bp_gens = BulletproofGens::new(128, 1); let mut rng = rand::thread_rng(); for _ in 0..100 { let x = rng.gen::<u64>(); let mut prover_transcript = Transcript::new(b"test"); let mut prover = Prover::new( &bp_gens, &pc_gens, &mut prover_transcript, ); let (in_pt, in_var) = prover.commit(x.into(), Scalar::random(&mut rng)); let (out_pts, out_vars) = (0..64) .map(|i| { prover.commit(((x >> i) & 1).into(), Scalar::random(&mut rng)) }) .unzip::<_, _, Vec<_>, Vec<_>>(); let result = scalar_to_bits_le(&mut prover, 64, in_var.into()).unwrap(); for (wire1, wire2) in result.into_iter().zip(out_vars.into_iter()) { prover.constrain(wire1 - wire2); } let proof = prover.prove().unwrap(); let mut verifier_transcript = Transcript::new(b"test"); let mut verifier = Verifier::new( &bp_gens, &pc_gens, &mut verifier_transcript, ); let in_var = verifier.commit(in_pt); let out_vars = out_pts.into_iter() .map(|out_pt| verifier.commit(out_pt)) .collect::<Vec<_>>(); let result = scalar_to_bits_le(&mut verifier, 64, in_var.into()).unwrap(); for (wire1, wire2) in result.into_iter().zip(out_vars.into_iter()) { verifier.constrain(wire1 - wire2); } assert!(verifier.verify(&proof).is_ok()); } } #[test] fn test_lt_gadget() { let pc_gens = PedersenGens::default(); let bp_gens = BulletproofGens::new(512, 1); let mut rng = rand::thread_rng(); for _ in 0..100 { let x1 = rng.gen::<u64>(); let x2 = rng.gen::<u64>(); let expected_out = if x1 < x2 { 1u64 } else { 0u64 }; let mut prover_transcript = Transcript::new(b"test"); let mut prover = Prover::new( &bp_gens, &pc_gens, &mut prover_transcript, ); let (in1_pt, in1_var) = prover.commit(x1.into(), Scalar::random(&mut rng)); let (in2_pt, in2_var) = prover.commit(x2.into(), Scalar::random(&mut rng)); let (out_pt, out_var) = prover.commit(expected_out.into(), Scalar::random(&mut rng)); let result = lt_gate( &mut prover, 64, in1_var.into(), in2_var.into() ).unwrap(); prover.constrain(result - out_var); let proof = prover.prove().unwrap(); let mut verifier_transcript = Transcript::new(b"test"); let mut verifier = Verifier::new( &bp_gens, &pc_gens, &mut verifier_transcript, ); let in1_var = verifier.commit(in1_pt); let in2_var = verifier.commit(in2_pt); let out_var = verifier.commit(out_pt); let result = lt_gate( &mut verifier, 64, in1_var.into(), in2_var.into() ).unwrap(); verifier.constrain(result - out_var); assert!(verifier.verify(&proof).is_ok()); } } }
true
af0e0941a6a367a1015bd215ca4d85fa3f4dd2ff
Rust
amol9/matasano
/src/set1/xorcipher.rs
UTF-8
729
2.8125
3
[ "MIT" ]
permissive
use common::{err, challenge, ascii, hex, util}; use common::cipher::one_byte_xor as obx; pub static info: challenge::Info = challenge::Info { no: 3, title: "Single-byte XOR cipher", help: "", execute_fn: interactive }; pub fn interactive() -> err::ExitCode { let input = rtry!(util::input("enter the hex string to be deciphered"), exit_err!()); match obx::guess_key(&rtry!(hex::hex_to_raw(input.trim()), exit_err!()), None) { Ok(v) => { let p = rtry!(ascii::raw_to_str(&v.plain), exit_err!()); println!("{}", p); exit_ok!() }, Err(e) => { println!("{}", e); exit_err!() } } }
true
28e9fedcfde4d624dbfa2cd3a52ecc198bfba3f5
Rust
hreinn91/rust_adventofcode_2019
/src/day2/src/intcode.rs
UTF-8
1,692
3.1875
3
[]
no_license
pub mod intcode { use crate::get_input; pub fn run_intcode_program_part1(file: &str) -> i32 { let intcode = get_input(file); run_program(12, 2, intcode) } pub fn run_intcode_program_part2(file: &str) -> i32 { let intcode = get_input(file); find_noun_verb_prod(19690720, intcode) } pub fn find_noun_verb_prod(fin_state: i32, intcode: Vec<i32>) -> i32 { for noun in 0..100 { for verb in 0..100 { if run_program(noun, verb, intcode.to_owned()) == fin_state { return 100 * noun + verb; } } } return -1; } pub fn run_program(noun: i32, verb: i32, mut intcode: Vec<i32>) -> i32 { intcode[1] = noun; intcode[2] = verb; let halt_state = parse(0, intcode); return halt_state[0]; } pub fn parse(counter: usize, mut intcode: Vec<i32>) -> Vec<i32> { let optcode = intcode[counter]; return if optcode == 99 { intcode } else if optcode == 1 || optcode == 2 { let pos1 = intcode[counter + 1]; let value1 = intcode[pos1 as usize]; let pos2 = intcode[counter + 2]; let value2 = intcode[pos2 as usize]; let position = intcode[counter + 3]; if optcode == 1 { let sum = value1 + value2; intcode[position as usize] = sum; } else if optcode == 2 { let prod = value1 * value2; intcode[position as usize] = prod; } parse(counter + 4, intcode) } else { vec![-1] }; } }
true
0243d6c60476e0debd7302e72e7f14a6af0d1dc4
Rust
rust-lang/rust
/tests/rustdoc/inline_cross/auxiliary/ret-pos-impl-trait-in-trait.rs
UTF-8
641
2.578125
3
[ "Apache-2.0", "LLVM-exception", "NCSA", "BSD-2-Clause", "LicenseRef-scancode-unicode", "MIT", "LicenseRef-scancode-other-permissive" ]
permissive
#![feature(return_position_impl_trait_in_trait)] pub trait Trait { fn create() -> impl Iterator<Item = u64> { std::iter::empty() } } pub struct Basic; pub struct Intermediate; pub struct Advanced; impl Trait for Basic { // method provided by the trait } impl Trait for Intermediate { fn create() -> std::ops::Range<u64> { // concrete return type 0..1 } } impl Trait for Advanced { fn create() -> impl Iterator<Item = u64> { // opaque return type std::iter::repeat(0) } } // Regression test for issue #113929: pub trait Def { fn def<T>() -> impl Default {} } impl Def for () {}
true
871f9e402ffc529c38359a69647687a735db21c0
Rust
benkonz/advent_of_code_2019
/day_03/part_2/src/main.rs
UTF-8
3,992
3.0625
3
[]
no_license
use std::cmp; use std::io::{self, Read}; use std::iter::FromIterator; fn main() -> io::Result<()> { let mut buffer = String::new(); io::stdin().read_to_string(&mut buffer)?; let parsed: Vec<&str> = buffer.split_whitespace().collect(); let wire1_path: Vec<(char, i64)> = parsed[0].trim().split(',').map(parse_segment).collect(); let wire2_path: Vec<(char, i64)> = parsed[1].trim().split(',').map(parse_segment).collect(); let mut intersections = Vec::new(); let mut wire1_current_start = (1, 1); let mut wire1_distance = 0; for wire1_segment in wire1_path { let wire1_current_end = add_segment_to_point(wire1_current_start, wire1_segment); let mut wire2_current_start = (1, 1); let mut wire2_distance = 0; for wire2_segment in &wire2_path { let wire2_current_end = add_segment_to_point(wire2_current_start, *wire2_segment); if let Some(intersection) = get_intersection( (wire1_current_start, wire1_current_end), (wire2_current_start, wire2_current_end), ) { if intersection != (1, 1) { let wire1_point_distance = get_distance(wire1_segment, intersection, wire1_current_start); let wire2_point_distance = get_distance(*wire2_segment, intersection, wire2_current_start); let total_distance = wire1_distance + wire2_distance + wire1_point_distance + wire2_point_distance; intersections.push(total_distance); } } wire2_current_start = wire2_current_end; wire2_distance += (*wire2_segment).1; } wire1_current_start = wire1_current_end; wire1_distance += wire1_segment.1; } intersections.sort(); println!("{:?}", intersections[0]); Ok(()) } fn parse_segment(s: &str) -> (char, i64) { let chars: Vec<char> = s.chars().collect(); let direction = chars[0]; let magnitude = String::from_iter(&chars[1..]).parse::<i64>().unwrap(); (direction, magnitude) } fn add_segment_to_point(point: (i64, i64), segment: (char, i64)) -> (i64, i64) { match segment { ('R', magnitude) => (point.0 + magnitude, point.1), ('L', magnitude) => (point.0 - magnitude, point.1), ('U', magnitude) => (point.0, point.1 + magnitude), ('D', magnitude) => (point.0, point.1 - magnitude), _ => panic!("invalid direction"), } } fn get_intersection( line1: ((i64, i64), (i64, i64)), line2: ((i64, i64), (i64, i64)), ) -> Option<(i64, i64)> { let a = line1.0; let b = line1.1; let a1 = b.1 - a.1; let b1 = a.0 - b.0; let c1 = a1 * a.0 + b1 * a.1; let c = line2.0; let d = line2.1; let a2 = d.1 - c.1; let b2 = c.0 - d.0; let c2 = a2 * c.0 + b2 * c.1; let det = a1 * b2 - a2 * b1; if det == 0 { None } else { let x = (b2 * c1 - b1 * c2) / det; let y = (a1 * c2 - a2 * c1) / det; let point = (x, y); if point_is_on_line(point, line1) && point_is_on_line(point, line2) { Some(point) } else { None } } } fn point_is_on_line(point: (i64, i64), line: ((i64, i64), (i64, i64))) -> bool { let line_a = line.0; let line_b = line.1; cmp::max(line_a.0, line_b.0) >= point.0 && cmp::min(line_a.0, line_b.0) <= point.0 && cmp::max(line_a.1, line_b.1) >= point.1 && cmp::min(line_a.1, line_b.1) <= point.1 } fn get_distance(segment: (char, i64), start_point: (i64, i64), end_point: (i64, i64)) -> i64 { match segment { (dir, _) if dir == 'R' || dir == 'L' => i64::abs(start_point.0 - end_point.0), (dir, _) if dir == 'U' || dir == 'D' => i64::abs(start_point.1 - end_point.1), _ => panic!("unknown direction"), } }
true
fe2f14a163fcf8c98b57a6e7aa4304572d5753e9
Rust
pd/tenx
/src/lib.rs
UTF-8
7,765
2.921875
3
[]
no_license
extern crate rand; #[macro_use(lazy_static)] extern crate lazy_static; extern crate itertools; pub mod board; pub mod piece; use std::iter::Iterator; use itertools::Itertools; use std::ops::Not; use board::{Bitboard, Line, PlacementError}; use piece::{Piece, Points}; pub type PlayResult = Result<(GameState, History), PlayError>; #[derive(Debug)] pub enum PlayError { PieceOutOfBounds(usize), SquareOutOfBounds(usize, usize), PiecePlayed(usize), PieceDoesNotFit(Piece, usize, usize), } impl From<PlacementError> for PlayError { fn from(err: PlacementError) -> PlayError { use PlayError::*; match err { PlacementError::OutOfBounds(x, y) => SquareOutOfBounds(x, y), PlacementError::Occupied(pc, x, y) => PieceDoesNotFit(pc, x, y), } } } #[derive(Debug, Copy, Clone)] pub enum GameStateChange { Gen { pieces: [&'static Piece; 3] }, Play { piece: &'static Piece, x: usize, y: usize, points: Points, }, Clear { line: Line, points: Points }, GameOver, } impl GameStateChange { pub fn score(&self) -> Points { match self { &GameStateChange::Play { points, .. } | &GameStateChange::Clear { points, .. } => points, _ => 0, } } } pub type History = Vec<GameStateChange>; #[derive(Debug, Copy, Clone)] pub struct Move { pub piece_number: usize, pub x: usize, pub y: usize, } fn generate_pieces() -> ([&'static Piece; 3], GameStateChange) { let pieces = [Piece::random(), Piece::random(), Piece::random()]; let change = GameStateChange::Gen { pieces: pieces }; (pieces, change) } fn clear_filled(board: Bitboard) -> (Bitboard, History) { // kinda guessing at the scoring values right now: // I *think* the first cleared line is worth 10, all extras are worth 20. // But it's tedious to play through the game and validate that reliably... let mut cleared = board; let mut history: History = vec![]; for (i, &line) in cleared.filled().iter().enumerate() { cleared = cleared.without_line(line); history.push(GameStateChange::Clear { line: line, points: 10 * (i as Points + 1), }); } (cleared, history) } #[derive(Debug, Copy, Clone)] pub struct GameState { pub board: Bitboard, pub score: Points, } impl GameState { pub fn new() -> GameState { GameState { board: Bitboard::new().with_pieces([Piece::random(), Piece::random(), Piece::random()]), score: 0, } } pub fn pieces(&self) -> [Option<&'static Piece>; 3] { self.board.pieces() } pub fn play(&self, mv: &Move) -> PlayResult { use PlayError::*; let &Move { piece_number: n, x, y } = mv; if n > 2 { return Err(PieceOutOfBounds(n)); } match self.board.piece(n) { None => Err(PiecePlayed(n)), Some(pc) => { let board = try!(self.board.with_piece_at(pc, x, y)).without_piece(n); let mut history: History = vec![GameStateChange::Play { piece: pc, x: x, y: y, points: pc.value, }]; let board = if board.no_remaining_pieces() { let (pieces, gen) = generate_pieces(); history.push(gen); board.with_pieces(pieces) } else { board }; let (cleared, changes) = clear_filled(board); history.extend(changes); let points_scored: u64 = history.iter().map(|change| change.score()).sum(); let next_state = GameState { board: cleared, score: self.score + points_scored, }; if next_state.is_game_over() { history.push(GameStateChange::GameOver); } Ok((next_state, history)) } } } pub fn is_game_over(&self) -> bool { self.board .pieces() .iter() .flat_map(|x| x) .any(|pc| (0..10).cartesian_product(0..10).any(|(x, y)| self.board.can_fit(pc, x, y))) .not() } pub fn moves(&self) -> Vec<Move> { (0..3).fold(vec![], |mut v, n| { v.extend(self.moves_for_piece(n)); v }) } pub fn moves_for_piece(&self, piece_number: usize) -> Vec<Move> { match self.board.piece(piece_number) { Some(pc) => { let mut moves = vec![]; for (x, y) in (0..10).cartesian_product(0..10) { if !self.board.can_fit(pc, x, y) { continue; } moves.push(Move { piece_number: piece_number, x: x, y: y, }); } moves } None => vec![], } } } #[cfg(test)] mod tests { use super::{GameState, GameStateChange, Move}; use itertools::Itertools; use board::Bitboard; use piece; #[test] fn test_new_game() { let state = GameState::new(); assert_eq!(state.score, 0); assert!(state.board.is_empty()); assert!(state.board.pieces().iter().all(|s| s.is_some())); } #[test] fn test_play_first_piece() { let initial_state = GameState::new(); let result = initial_state.play(&Move { piece_number: 0, x: 3, y: 0, }); assert!(result.is_ok(), "Move failed! Err: {:?}\n\nStarting state: {:?}", result.err().unwrap(), initial_state); } #[test] fn test_clear_three_lines() { let board = Bitboard::filled_at((0..9).cartesian_product(0..3)); let state = GameState { board: board.with_pieces([piece::by_name("TriUD"), piece::by_name("Uni"), piece::by_name("Uni")]), score: 0, }; // play TriUD at the NE edge let result = state.play(&Move { piece_number: 0, x: 9, y: 0, }); assert!(result.is_ok()); let (new_state, history) = result.unwrap(); assert_eq!(new_state.score, 63); assert_eq!(history.len(), 4); } #[test] fn test_losing() { let board = Bitboard::filled_at((0..9).cartesian_product(0..9)); assert_eq!(board.filled().len(), 0); let state = GameState { board: board.with_pieces([piece::by_name("Uni"), piece::by_name("Square3"), piece::by_name("Square3")]), score: 0, }; // Clear one line, but not enough to make space for the 3x3s. Game over. let result = state.play(&Move { piece_number: 0, x: 9, y: 0, }); assert!(result.is_ok()); let (new_state, history) = result.unwrap(); assert_eq!(new_state.score, 11); if let Some(change) = history.last() { match *change { GameStateChange::GameOver => (), _ => panic!("Should be game over, but isn't"), } } } }
true
78fe7296801cfd9f15ad12c5205fc8c4c79b4cce
Rust
fujitayy/hashmap-benchmark
/rust/hash_bench/src/main.rs
UTF-8
1,734
3.484375
3
[]
no_license
use std::collections::HashMap; use std::hash::Hash; use std::time; fn main() { simple_hash(); complex_hash(); } fn simple_hash() { let start = time::Instant::now(); let mut m: HashMap<i64, i64> = HashMap::new(); for i in 0..10000 { m.insert(i, i); } let mut ans = 0; for k in m.keys() { ans += m[k]; } let end = start.elapsed(); println!("[simple_hash key:int] answer={}, {} sec", ans, end.as_secs_f64()); } #[derive(Debug, Clone, PartialEq, Eq, Hash)] struct Key { k1: Key2, k2: String, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] struct Key2 { k1: i64, k2: i64, } fn gen_keys() -> Vec<Key> { let chars = ["あ", "い", "う", "え", "お"]; let mut keys = Vec::new(); for _ in 0..10000 { keys.push(Key { k1: Key2 { k1: rand::random::<i64>() % 100, k2: rand::random::<i64>() % 100, }, k2: itertools::join( &[ chars[rand::random::<usize>() % 5], chars[rand::random::<usize>() % 5], chars[rand::random::<usize>() % 5], ], "", ), }); } return keys; } fn complex_hash() { let keys = gen_keys(); let start = time::Instant::now(); let mut m: HashMap<Key, Key> = keys.iter().fold(HashMap::new(), |mut m, k| { m.insert(k.clone(), k.clone()); m }); let ans = m.keys().into_iter().fold(0, |mut acc, k| { acc += k.k1.k2; acc }); let end = start.elapsed(); println!("[complex_hash key:int/int/stringな構造体] answer={}, {} sec", ans, end.as_secs_f64()); }
true
804d6c49115be10fe8d1c2afd41f89605c72dfab
Rust
sulabhkothari/SkRustLearn
/common_collections/src/main.rs
UTF-8
11,703
3.90625
4
[]
no_license
use std::string::ToString; fn main() { vectors(); strings(); hashmaps(); } fn vectors() { let v: Vec<i32> = Vec::new(); let mut v = vec![1, 2, 3]; match v.binary_search(&16) { Ok(pos) => v.insert(pos, 16), Err(_) => v.push(16) } match v.binary_search(&12) { Ok(pos) => v.insert(pos, 12), Err(pos) => v.insert(pos, 12) } println!("Binary Search -> {:?}", v); let mut v = Vec::new(); v.push(5); v.push(6); v.push(7); v.push(8); let v = vec![1, 2, 3, 4, 5]; let third: &i32 = &v[2]; println!("The third element is {}", third); match v.get(2) { Some(third) => println!("The third element is {}", third), None => println!("There is no third element."), } // When the program has a valid reference, the borrow checker enforces the ownership and // borrowing rules (covered in Chapter 4) to ensure this reference and any other references to // the contents of the vector remain valid. Recall the rule that states you can’t have mutable // and immutable references in the same scope. That rule applies in Listing 8-7, where we hold // an immutable reference to the first element in a vector and try to add an element to the end, // which won’t work. let mut v = vec![1, 2, 3, 4, 5]; let first = &v[0]; v.push(6); //Below line causes Compilation Error //println!("The first element is: {}", first); // This error is due to the way vectors work: adding a new element onto the end of the vector // might require allocating new memory and copying the old elements to the new space, if there // isn’t enough room to put all the elements next to each other where the vector currently is. // In that case, the reference to the first element would be pointing to deallocated memory. // The borrowing rules prevent programs from ending up in that situation. let v = vec![100, 32, 57]; for i in &v { println!("{}", i); } // To change the value that the mutable reference refers to, we have to use the dereference // operator (*) to get to the value in i before we can use the += operator. let mut v = vec![100, 32, 57]; for i in &mut v { *i += 50; } for i in &v { println!("{}", i); } enum SpreadsheetCell { Int(i32), Float(f64), Text(String), } let row = vec![ SpreadsheetCell::Int(3), SpreadsheetCell::Text(String::from("blue")), SpreadsheetCell::Float(10.12), ]; } fn strings() { let mut s = String::new(); let m = String::from("sdfsdf"); let data = "initial contents"; let s = data.to_string(); // the method also works on a literal directly: let s = "initial contents".to_string(); let hello = String::from("السلام عليكم"); let hello = String::from("Dobrý den"); let hello = String::from("Hello"); let hello = String::from("שָׁלוֹם"); let hello = String::from("नमस्ते"); let hello = String::from("こんにちは"); let hello = String::from("안녕하세요"); let hello = String::from("你好"); let hello = String::from("Olá"); let hello = String::from("Здравствуйте"); let hello = String::from("Hola"); let mut s1 = String::from("foo"); let s2 = "bar"; s1.push_str(s2); println!("s2 is {}", s2); let mut s = String::from("lo"); s.push('l'); use std::ops::Add; let s1 = String::from("Hello, "); let s2 = String::from("world!"); // The reason we’re able to use &s2 in the call to add is that the compiler can coerce the // &String argument into a &str. When we call the add method, Rust uses a deref coercion, which // here turns &s2 into &s2[..]. We’ll discuss deref coercion in more depth in Chapter 15. // Because add does not take ownership of the s parameter, s2 will still be a valid String after // this operation. // looks like it will copy both strings and create a new one, this statement actually takes // ownership of s1, appends a copy of the contents of s2, and then returns ownership of the // result. In other words, it looks like it’s making a lot of copies but isn’t; the // implementation is more efficient than copying. //let s3 = s1.add(&s2); let s3 = s1 + &s2; println!("{}", s3); let s1 = String::from("tic"); let s2 = String::from("tac"); let s3 = String::from("toe"); //let s = s1 + "-" + &s2 + "-" + &s3; let s = format!("{}-{}-{}", s1, s2, s3); println!("{}", s); // The version of the code using format! is much easier to read and doesn’t take ownership of // any of its parameters. println!("{}", s1); // A String is a wrapper over a Vec<u8> let len = String::from("Hola").len(); // In this case, len will be 4, which means the vector storing the string “Hola” is 4 bytes long. // Each of these letters takes 1 byte when encoded in UTF-8 println!("{}", len); let len = String::from("Здравствуйте").len(); println!("{}", len); // It takes 24 bytes to encode “Здравствуйте” in UTF-8, because each Unicode scalar value in that string // takes 2 bytes of storage. Therefore, an index into the string’s bytes will not always // correlate to a valid Unicode scalar value. To demonstrate, consider this invalid Rust code: // let hello = "Здравствуйте"; // let answer = &hello[0]; // println!("{}", answer); // error[E0277]: the type `str` cannot be indexed by `{integer}` // Another point about UTF-8 is that there are actually three relevant ways to look at strings // from Rust’s perspective: as bytes, scalar values, and grapheme clusters (the closest thing to // what we would call letters). // “नमस्ते” // Bytes: [224, 164, 168, 224, 164, 174, 224, 164, 184, 224, 165, 141, 224, 164, 164, 224, 165, 135] // Unicode scalar values (Rust's char type): ['न', 'म', 'स', '्', 'त', 'े'] // There are six char values here, but the fourth and sixth are not letters: they’re diacritics // that don’t make sense on their own // Grapheme clusters: ["न", "म", "स्", "ते"] let namaste = "नमस्ते"; println!("{}", &namaste[0..12]); let hello = "Здравствуйте"; let s = &hello[0..4]; println!("{}", s); for c in "नमस्ते".chars() { println!("{}", c); } for b in "नमस्ते".bytes() { print!("{},", b); } // But be sure to remember that valid Unicode scalar values may be made up of more than 1 byte. // Getting grapheme clusters from strings is complex, so this functionality is not provided by // the standard library. Crates are available on crates.io if this is the functionality you need. } fn hashmaps() { use std::collections::HashMap; let mut scores = HashMap::new(); scores.insert(String::from("Blue"), 10); scores.insert(String::from("Yellow"), 50); // Note that we need to first use the HashMap from the collections portion of the standard // library. Of our three common collections, this one is the least often used, so it’s not // included in the features brought into scope automatically in the prelude. // The type annotation HashMap<_, _> is needed here because it’s possible to collect into many // different data structures and Rust doesn’t know which you want unless you specify. For the // parameters for the key and value types, however, we use underscores, and Rust can infer the // types that the hash map contains based on the types of the data in the vectors. let teams = vec![String::from("Blue"), String::from("Yellow")]; let initial_scores = vec![10, 50]; println!(""); let scores: HashMap<_, _> = teams.iter().zip(initial_scores.iter()).collect(); for (k, v) in &scores { println!("{},{}", k, v); } let score = scores.get(&String::from("Blue")); match score { Some(s) => println!("{}", s), None => () } // For types that implement the Copy trait, like i32, the values are copied into the hash map. // For owned values like String, the values will be moved and the hash map will be the owner of // those values let field_name = String::from("Favorite color"); let field_value = String::from("Blue"); let mut map = HashMap::new(); map.insert(field_name, field_value); //error[E0382]: borrow of moved value: `field_name` //println!("{}", field_name); // If we insert references to values into the hash map, the values won’t be moved into the hash // map. The values that the references point to must be valid for at least as long as the hash // map is valid. let mut scores = HashMap::new(); scores.insert(String::from("Blue"), 10); scores.insert(String::from("Yellow"), 50); // Here, score will have the value that’s associated with the Blue team, and the result will be // Some(&10). The result is wrapped in Some because get returns an Option<&V> let team_name = String::from("Blue"); // get borrows key so its passed using & let score = scores.get(&team_name); match score { Some(num) => println!("{}", num), None => () } let mut scores = HashMap::new(); scores.insert(String::from("Blue"), 10); scores.insert(String::from("Yellow"), 50); for (key, value) in &scores { println!("{}: {}", key, value); } // Overwriting a Value let mut scores = HashMap::new(); scores.insert(String::from("Blue"), 10); scores.insert(String::from("Blue"), 25); println!("{:?}", scores); // Only Inserting a Value If the Key Has No Value let mut scores = HashMap::new(); scores.insert(String::from("Blue"), 10); scores.entry(String::from("Yellow")).or_insert(50); scores.entry(String::from("Blue")).or_insert(50); println!("{:?}", scores); // Updating a Value Based on the Old Value let text = "hello world wonderful world"; let mut map = HashMap::new(); for word in text.split_whitespace() { let count = map.entry(word).or_insert(0); *count += 1; } println!("{:?}", map); // The or_insert method actually returns a mutable reference (&mut V) to the value for this key. // Here we store that mutable reference in the count variable, so in order to assign to that // value, we must first dereference count using the asterisk (*). The mutable reference goes out // of scope at the end of the for loop, so all of these changes are safe and allowed by the // borrowing rules. // Hashing Functions // By default, HashMap uses a “cryptographically strong”1 hashing function that can provide // resistance to Denial of Service (DoS) attacks. This is not the fastest hashing algorithm // available, but the trade-off for better security that comes with the drop in performance is // worth it. If you profile your code and find that the default hash function is too slow for // your purposes, you can switch to another function by specifying a different hasher. A hasher // is a type that implements the BuildHasher trait. We’ll talk about traits and how to implement // them in Chapter 10. You don’t necessarily have to implement your own hasher from scratch; // crates.io has libraries shared by other Rust users that provide hashers implementing many // common hashing algorithms. }
true
078ec6529a3b56c577953b03d84f1fe124e4e6e9
Rust
hamza1311/tower-http
/tower-http/src/follow_redirect/policy/clone_body_fn.rs
UTF-8
1,089
3.390625
3
[ "MIT" ]
permissive
use super::{Action, Attempt, Policy}; use std::fmt; /// A redirection [`Policy`] created from a closure. /// /// See [`clone_body_fn`] for more details. #[derive(Clone, Copy)] pub struct CloneBodyFn<F> { f: F, } impl<F> fmt::Debug for CloneBodyFn<F> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("CloneBodyFn") .field("f", &std::any::type_name::<F>()) .finish() } } impl<F, B, E> Policy<B, E> for CloneBodyFn<F> where F: Fn(&B) -> Option<B>, { fn redirect(&mut self, _: &Attempt<'_>) -> Result<Action, E> { Ok(Action::Follow) } fn clone_body(&self, body: &B) -> Option<B> { (self.f)(body) } } /// Create a new redirection [`Policy`] from a closure `F: Fn(&B) -> Option<B>`. /// /// [`clone_body`][Policy::clone_body] method of the returned `Policy` delegates to the wrapped /// closure and [`redirect`][Policy::redirect] method always returns [`Action::Follow`]. pub fn clone_body_fn<F, B>(f: F) -> CloneBodyFn<F> where F: Fn(&B) -> Option<B>, { CloneBodyFn { f } }
true
8b64fb20f7a1a7e4a30dbd70590bab17a4db16cb
Rust
flip1995/rust-clippy
/tests/ui/branches_sharing_code/shared_at_top_and_bottom.rs
UTF-8
2,549
3.078125
3
[ "MIT", "Apache-2.0" ]
permissive
#![deny(clippy::branches_sharing_code, clippy::if_same_then_else)] #![allow(dead_code)] #![allow(clippy::uninlined_format_args)] //@no-rustfix // branches_sharing_code at the top and bottom of the if blocks struct DataPack { id: u32, name: String, some_data: Vec<u8>, } fn overlapping_eq_regions() { let x = 9; // Overlap with separator if x == 7 { let t = 7; let _overlap_start = t * 2; let _overlap_end = 2 * t; let _u = 9; } else { let t = 7; let _overlap_start = t * 2; let _overlap_end = 2 * t; println!("Overlap separator"); let _overlap_start = t * 2; let _overlap_end = 2 * t; let _u = 9; } // Overlap with separator if x == 99 { let r = 7; let _overlap_start = r; let _overlap_middle = r * r; let _overlap_end = r * r * r; let z = "end"; } else { let r = 7; let _overlap_start = r; let _overlap_middle = r * r; let _overlap_middle = r * r; let _overlap_end = r * r * r; let z = "end"; } } fn complexer_example() { fn gen_id(x: u32, y: u32) -> u32 { let x = x & 0x0000_ffff; let y = (y & 0xffff_0000) << 16; x | y } fn process_data(data: DataPack) { let _ = data; } let x = 8; let y = 9; if (x > 7 && y < 13) || (x + y) % 2 == 1 { let a = 0xcafe; let b = 0xffff00ff; let e_id = gen_id(a, b); println!("From the a `{}` to the b `{}`", a, b); let pack = DataPack { id: e_id, name: "Player 1".to_string(), some_data: vec![0x12, 0x34, 0x56, 0x78, 0x90], }; process_data(pack); } else { let a = 0xcafe; let b = 0xffff00ff; let e_id = gen_id(a, b); println!("The new ID is '{}'", e_id); let pack = DataPack { id: e_id, name: "Player 1".to_string(), some_data: vec![0x12, 0x34, 0x56, 0x78, 0x90], }; process_data(pack); } } /// This should add a note to the lint msg since the moved expression is not `()` fn added_note_for_expression_use() -> u32 { let x = 9; let _ = if x == 7 { let _ = 19; let _splitter = 6; x << 2 } else { let _ = 19; x << 2 }; if x == 9 { let _ = 17; let _splitter = 6; x * 4 } else { let _ = 17; x * 4 } } fn main() {}
true
0585c96f69c525928c1c114751577b1b23ac98ee
Rust
kyco/snap-backend
/src/routes/send.rs
UTF-8
2,406
2.953125
3
[]
no_license
use crate::db::paired::is_paired; use crate::db::users::device_id_exists; use crate::push::push_notification; use crate::routes::json_generic::{JsonGeneric, JsonGenericCodes}; use rocket::response::status::BadRequest; use rocket_contrib::json::Json; #[derive(Serialize, Deserialize, Debug)] pub struct Message { pub from: String, pub to: String, pub contents: String, } // Send push notification to paired device #[post("/", format = "json", data = "<message>")] pub fn send(message: Json<Message>) -> Result<Json<JsonGeneric>, BadRequest<Json<JsonGeneric>>> { // Check if the from device ID exists match device_id_exists(&message.from) { Ok(result) => { if result == false { return Err(JsonGeneric::new_bad_request( JsonGenericCodes::NotFound, "from: ".to_owned() + &message.from + " doesn't exist", )); } } Err(err) => { return Err(JsonGeneric::new_bad_request_generic(err.to_string())); } }; // Check if the to device ID exists match device_id_exists(&message.to) { Ok(result) => { if result == false { return Err(JsonGeneric::new_bad_request( JsonGenericCodes::NotFound, "to: ".to_owned() + &message.to + " doesn't exist", )); } } Err(err) => { return Err(JsonGeneric::new_bad_request_generic(err.to_string())); } }; // Check if from is paired with to match is_paired(&message.from, &message.to) { Ok(result) => { if result == false { return Err(JsonGeneric::new_bad_request( JsonGenericCodes::NotPaired, message.from.to_string() + " is not paired with " + &message.to, )); } } Err(err) => { return Err(JsonGeneric::new_bad_request_generic(err.to_string())); } }; // Send push notification to device let push = push_notification::PushNotification::new(&message.from, &message.to, &message.contents); // Send push notification match push.send() { Ok(_) => return Ok(JsonGeneric::new_ok("ok".to_string())), Err(e) => return Err(JsonGeneric::new_bad_request_generic(e.to_string())), } }
true
3195e26eae0fca4556b0e4db2467faf2aee1b99a
Rust
bcully/rust-crates-index
/src/bare_index.rs
UTF-8
17,899
2.703125
3
[ "Apache-2.0" ]
permissive
use crate::{Crate, Error, IndexConfig}; use std::marker::PhantomPinned; use std::{ io, path::{Path, PathBuf}, }; /// Access to a "bare" git index that fetches files directly from the repo instead of local checkout /// /// Uses Cargo's cache pub struct BareIndex { path: PathBuf, pub url: String, } impl BareIndex { /// Creates a bare index from a provided URL, opening the same location on /// disk that cargo uses for that registry index. pub fn from_url(url: &str) -> Result<Self, Error> { let (dir_name, canonical_url) = url_to_local_dir(url)?; let mut path = home::cargo_home().unwrap_or_default(); path.push("registry/index"); path.push(dir_name); Ok(Self { path, url: canonical_url, }) } /// Creates a bare index at the provided path with the specified repository URL. #[inline] pub fn with_path(path: PathBuf, url: &str) -> Self { Self { path, url: url.to_owned(), } } /// Creates an index for the default crates.io registry, using the same /// disk location as cargo itself. #[inline] pub fn new_cargo_default() -> Self { // UNWRAP: The default index git URL is known to safely convert to a path. Self::from_url(crate::INDEX_GIT_URL).unwrap() } /// Opens the local index, which acts as a kind of lock for source control /// operations #[inline] pub fn open_or_clone(&self) -> Result<BareIndexRepo<'_>, Error> { BareIndexRepo::new(self) } /// Get the index directory. #[inline] pub fn path(&self) -> &Path { &self.path } } /// Self-referential struct where `Tree` borrows from `Repository` struct UnsafeRepoTree { /// Warning: order of the fields is necessary for safety. `tree` must Drop before `repo`. tree: git2::Tree<'static>, repo: Box<git2::Repository>, // Currently !Unpin is Rust's heuristic for self-referential structs _self_referential: PhantomPinned, } /// Opened instance of [`BareIndex`] pub struct BareIndexRepo<'a> { inner: &'a BareIndex, head_str: String, rt: UnsafeRepoTree, } impl<'a> BareIndexRepo<'a> { fn new(index: &'a BareIndex) -> Result<Self, Error> { let exists = git2::Repository::discover(&index.path) .map(|repository| { repository .find_remote("origin") .ok() // Cargo creates a checkout without an origin set, // so default to true in case of missing origin .map_or(true, |remote| { remote.url().map_or(true, |url| url == index.url) }) }) .unwrap_or(false); let repo = if !exists { let mut opts = git2::RepositoryInitOptions::new(); opts.external_template(false); let repo = git2::Repository::init_opts(&index.path, &opts)?; { let mut origin_remote = repo .find_remote("origin") .or_else(|_| repo.remote_anonymous(&index.url))?; origin_remote.fetch( &[ "HEAD:refs/remotes/origin/HEAD", "master:refs/remotes/origin/master", ], Some(&mut crate::fetch_opts()), None, )?; } repo } else { git2::Repository::open(&index.path)? }; // It's going to be used in a self-referential type. Boxing prevents it from being moved // and adds a layer of indirection that will hopefully not upset noalias analysis. let repo = Box::new(repo); let head = repo // Fallback to HEAD, as a fresh clone won't have a FETCH_HEAD .refname_to_id("FETCH_HEAD") .or_else(|_| repo.refname_to_id("HEAD"))?; let head_str = head.to_string(); let tree = { let commit = repo.find_commit(head)?; let tree = commit.tree()?; // See `UnsafeRepoTree` unsafe { std::mem::transmute::<git2::Tree<'_>, git2::Tree<'static>>(tree) } }; Ok(Self { inner: index, head_str, rt: UnsafeRepoTree { repo, tree, _self_referential: PhantomPinned, }, }) } /// Fetches latest from the remote index repository. Note that using this /// method will mean no cache entries will be used, if a new commit is fetched /// from the repository, as their commit version will no longer match. pub fn retrieve(&mut self) -> Result<(), Error> { { let mut origin_remote = self .rt .repo .find_remote("origin") .or_else(|_| self.rt.repo.remote_anonymous(&self.inner.url))?; origin_remote.fetch( &[ "HEAD:refs/remotes/origin/HEAD", "master:refs/remotes/origin/master", ], Some(&mut crate::fetch_opts()), None, )?; } let head = self .rt .repo .refname_to_id("FETCH_HEAD") .or_else(|_| self.rt.repo.refname_to_id("HEAD"))?; let head_str = head.to_string(); let commit = self.rt.repo.find_commit(head)?; let tree = commit.tree()?; // See `UnsafeRepoTree` let tree = unsafe { std::mem::transmute::<git2::Tree<'_>, git2::Tree<'static>>(tree) }; self.head_str = head_str; self.rt.tree = tree; Ok(()) } /// Reads a crate from the index, it will attempt to use a cached entry if /// one is available, otherwise it will fallback to reading the crate /// directly from the git blob containing the crate information. pub fn crate_(&self, name: &str) -> Option<Crate> { let rel_path = match crate::crate_name_to_relative_path(name) { Some(rp) => rp, None => return None, }; // Attempt to load the .cache/ entry first, this is purely an acceleration // mechanism and can fail for a few reasons that are non-fatal { let mut cache_path = self.inner.path.join(".cache"); cache_path.push(&rel_path); if let Ok(cache_bytes) = std::fs::read(&cache_path) { if let Ok(krate) = Crate::from_cache_slice(&cache_bytes, &self.head_str) { return Some(krate); } } } // Fallback to reading the blob directly via git if we don't have a // valid cache entry self.crate_from_rel_path(&rel_path).ok() } fn crate_from_rel_path(&self, path: &str) -> Result<Crate, Error> { let entry = self.rt.tree.get_path(&Path::new(path))?; let object = entry.to_object(&self.rt.repo)?; let blob = object .as_blob() .ok_or_else(|| Error::Io(io::Error::new(io::ErrorKind::NotFound, path.to_owned())))?; Crate::from_slice(blob.content()).map_err(Error::Io) } /// Retrieve an iterator over all the crates in the index. /// skips crates that can not be parsed. #[inline] pub fn crates(&self) -> Crates<'_> { Crates { blobs: self.crates_refs(), } } /// Retrieve an iterator over all the crates in the index. /// Returns opaque reference for each crate in the index, which can be used with [`CrateRef::parse`] fn crates_refs(&self) -> CrateRefs<'_> { let mut stack = Vec::with_capacity(800); // Scan only directories at top level (skip config.json, etc.) for entry in self.rt.tree.iter() { let entry = entry.to_object(&self.rt.repo).unwrap(); if entry.as_tree().is_some() { stack.push(entry); } } CrateRefs { stack, rt: &self.rt, } } /// Get the global configuration of the index. pub fn index_config(&self) -> Result<IndexConfig, Error> { let entry = self.rt.tree.get_path(&Path::new("config.json"))?; let object = entry.to_object(&self.rt.repo)?; let blob = object .as_blob() .ok_or_else(|| Error::Io(io::Error::new(io::ErrorKind::NotFound, "config.json")))?; serde_json::from_slice(blob.content()).map_err(Error::Json) } } /// Iterator over all crates in the index, but returns opaque objects that can be parsed separately. /// /// See [`CrateRef::parse`]. struct CrateRefs<'a> { stack: Vec<git2::Object<'a>>, rt: &'a UnsafeRepoTree, } /// Opaque representation of a crate in the index. See [`CrateRef::parse`]. pub(crate) struct CrateRef<'a>(pub(crate) git2::Object<'a>); impl CrateRef<'_> { #[inline] /// Parse a crate from [`BareIndex::crates_blobs`] iterator pub fn parse(&self) -> Option<Crate> { Crate::from_slice(self.as_slice()?).ok() } /// Raw crate data that can be parsed with [`Crate::from_slice`] pub fn as_slice(&self) -> Option<&[u8]> { Some(self.0.as_blob()?.content()) } } impl<'a> Iterator for CrateRefs<'a> { type Item = CrateRef<'a>; fn next(&mut self) -> Option<Self::Item> { while let Some(last) = self.stack.pop() { match last.as_tree() { None => return Some(CrateRef(last)), Some(tree) => { for entry in tree.iter().rev() { self.stack.push(entry.to_object(&self.rt.repo).unwrap()); } continue; } } } None } } pub struct Crates<'a> { blobs: CrateRefs<'a>, } impl<'a> Iterator for Crates<'a> { type Item = Crate; fn next(&mut self) -> Option<Self::Item> { while let Some(next) = self.blobs.next() { if let Some(k) = CrateRef::parse(&next) { return Some(k); } } None } } /// Converts a full url, eg https://github.com/rust-lang/crates.io-index, into /// the root directory name where cargo itself will fetch it on disk fn url_to_local_dir(url: &str) -> Result<(String, String), Error> { fn to_hex(num: u64) -> String { const CHARS: &[u8] = b"0123456789abcdef"; let bytes = &[ num as u8, (num >> 8) as u8, (num >> 16) as u8, (num >> 24) as u8, (num >> 32) as u8, (num >> 40) as u8, (num >> 48) as u8, (num >> 56) as u8, ]; let mut output = vec![0u8; 16]; let mut ind = 0; for &byte in bytes { output[ind] = CHARS[(byte >> 4) as usize]; output[ind + 1] = CHARS[(byte & 0xf) as usize]; ind += 2; } String::from_utf8(output).expect("valid utf-8 hex string") } #[allow(deprecated)] fn hash_u64(url: &str) -> u64 { use std::hash::{Hash, Hasher, SipHasher}; let mut hasher = SipHasher::new_with_keys(0, 0); // Registry 2usize.hash(&mut hasher); // Url url.hash(&mut hasher); hasher.finish() } // Ensure we have a registry or bare url let (url, scheme_ind) = { let scheme_ind = url .find("://") .ok_or_else(|| Error::Url(format!("'{}' is not a valid url", url)))?; let scheme_str = &url[..scheme_ind]; if let Some(ind) = scheme_str.find('+') { if &scheme_str[..ind] != "registry" { return Err(Error::Url(format!("'{}' is not a valid registry url", url))); } (&url[ind + 1..], scheme_ind - ind - 1) } else { (url, scheme_ind) } }; // Could use the Url crate for this, but it's simple enough and we don't // need to deal with every possible url (I hope...) let host = match url[scheme_ind + 3..].find('/') { Some(end) => &url[scheme_ind + 3..scheme_ind + 3 + end], None => &url[scheme_ind + 3..], }; // cargo special cases github.com for reasons, so do the same let mut canonical = if host == "github.com" { url.to_lowercase() } else { url.to_owned() }; // Chop off any query params/fragments if let Some(hash) = canonical.rfind('#') { canonical.truncate(hash); } if let Some(query) = canonical.rfind('?') { canonical.truncate(query); } let ident = to_hex(hash_u64(&canonical)); if canonical.ends_with('/') { canonical.pop(); } if canonical.ends_with(".git") { canonical.truncate(canonical.len() - 4); } Ok((format!("{}-{}", host, ident), canonical)) } #[cfg(test)] mod test { #[test] fn matches_cargo() { assert_eq!( super::url_to_local_dir(crate::INDEX_GIT_URL).unwrap(), ( "github.com-1ecc6299db9ec823".to_owned(), crate::INDEX_GIT_URL.to_owned() ) ); // I've confirmed this also works with a custom registry, unfortunately // that one includes a secret key as part of the url which would allow // anyone to publish to the registry, so uhh...here's a fake one instead assert_eq!( super::url_to_local_dir( "https://dl.cloudsmith.io/aBcW1234aBcW1234/embark/rust/cargo/index.git" ) .unwrap(), ( "dl.cloudsmith.io-ff79e51ddd2b38fd".to_owned(), "https://dl.cloudsmith.io/aBcW1234aBcW1234/embark/rust/cargo/index".to_owned() ) ); // Ensure we actually strip off the irrelevant parts of a url, note that // the .git suffix is not part of the canonical url, but *is* used when hashing assert_eq!( super::url_to_local_dir(&format!( "registry+{}.git?one=1&two=2#fragment", crate::INDEX_GIT_URL )) .unwrap(), ( "github.com-c786010fb7ef2e6e".to_owned(), crate::INDEX_GIT_URL.to_owned() ) ); } #[test] fn bare_iterator() { use super::BareIndex; let tmp_dir = tempdir::TempDir::new("bare_iterator").unwrap(); let index = BareIndex::with_path(tmp_dir.path().to_owned(), crate::INDEX_GIT_URL); let repo = index .open_or_clone() .expect("Failed to clone crates.io index"); let mut found_gcc_crate = false; for c in repo.crates() { if c.name() == "gcc" { found_gcc_crate = true; } } assert!(found_gcc_crate); } #[test] fn clones_bare_index() { use super::BareIndex; let tmp_dir = tempdir::TempDir::new("clones_bare_index").unwrap(); let index = BareIndex::with_path(tmp_dir.path().to_owned(), crate::INDEX_GIT_URL); let mut repo = index .open_or_clone() .expect("Failed to clone crates.io index"); fn test_sval(repo: &super::BareIndexRepo<'_>) { let krate = repo .crate_("sval") .expect("Could not find the crate sval in the index"); let version = krate .versions() .iter() .find(|v| v.version() == "0.0.1") .expect("Version 0.0.1 of sval does not exist?"); let dep_with_package_name = version .dependencies() .iter() .find(|d| d.name() == "serde_lib") .expect("sval does not have expected dependency?"); assert_ne!( dep_with_package_name.name(), dep_with_package_name.package().unwrap() ); assert_eq!( dep_with_package_name.crate_name(), dep_with_package_name.package().unwrap() ); } test_sval(&repo); repo.retrieve().expect("Failed to fetch crates.io index"); test_sval(&repo); } #[test] fn opens_bare_index() { use super::BareIndex; let tmp_dir = tempdir::TempDir::new("opens_bare_index").unwrap(); let index = BareIndex::with_path(tmp_dir.path().to_owned(), crate::INDEX_GIT_URL); { let _ = index .open_or_clone() .expect("Failed to clone crates.io index"); } let mut repo = index .open_or_clone() .expect("Failed to open crates.io index"); fn test_sval(repo: &super::BareIndexRepo<'_>) { let krate = repo .crate_("sval") .expect("Could not find the crate sval in the index"); let version = krate .versions() .iter() .find(|v| v.version() == "0.0.1") .expect("Version 0.0.1 of sval does not exist?"); let dep_with_package_name = version .dependencies() .iter() .find(|d| d.name() == "serde_lib") .expect("sval does not have expected dependency?"); assert_ne!( dep_with_package_name.name(), dep_with_package_name.package().unwrap() ); assert_eq!( dep_with_package_name.crate_name(), dep_with_package_name.package().unwrap() ); } test_sval(&repo); repo.retrieve().expect("Failed to fetch crates.io index"); test_sval(&repo); } }
true
2c67c0ec662e561abe904384c1baaad45ad722f3
Rust
liufoyang/rust_demo
/demobin/src/flycoin.rs
UTF-8
5,736
3.546875
4
[]
no_license
pub mod fly_coin { pub struct FlyCoin{ amount:u64, currency: String, ownAccountId:String, } pub enum Result { SUCCESS{code:String, msg:String, item:FlyCoin}, SUCCESS_BOTH{code:String, msg:String, credit:FlyCoin, debit:FlyCoin}, FAIL{code:String, msg:String, credit:FlyCoin, debit:FlyCoin} } impl FlyCoin{ pub fn create(amountNum:u64, currencyCode:String, ownAdId:String) -> FlyCoin{ let coin = FlyCoin { amount:amountNum, currency:currencyCode, ownAccountId:ownAdId }; return coin; } /** 转移币,新建一个币,老的币因为ownShip放进来了, 函数结束币就自动回收销毁了。 */ pub fn moveTo(self, toAddress:String) -> Result{ if toAddress == self.ownAccountId { let coin = FlyCoin { amount: 0, currency: self.currency.clone(), ownAccountId: toAddress }; return Result::FAIL { code: String::from("FAIL"), msg: String::from("can move the coin to same account"), credit: self, debit: coin }; } else { // 检查没问题,这里直接转移self的amount, currenty的ownership, self再也不能使用了 let coin = FlyCoin { amount:self.amount, currency:self.currency, ownAccountId:toAddress }; return Result::SUCCESS{code:String::from("SUCCESS"),msg:String::from("Move coin to new account"), item:coin}; } } /** 两个币组合成新的一个币。 如果成功,返回一个新的币。 **/ pub fn add(self, anotherCoin:FlyCoin) -> Result { if self.ownAccountId != anotherCoin.ownAccountId { return Result::FAIL {code:String::from("FAIL"), msg:String::from("can add the coin to not same account"), credit:self, debit:anotherCoin}; } if self.currency != anotherCoin.currency { return Result::FAIL {code:String::from("FAIL"), msg:String::from("can add the coin to not same currency"),credit:self, debit:anotherCoin}; } let coin = FlyCoin { amount:self.amount + anotherCoin.amount, currency:self.currency, ownAccountId:self.ownAccountId }; // 相加成功,返回新的币 return Result::SUCCESS{code:String::from("SUCCESS"),msg:String::from("Move coin to new account"), item:coin }; } /** 使用一个币,给一个人某个数额的量, **/ pub fn sub(self, subAmount:u64, toAddress: &String) -> Result { // if self.ownAccountId != anotherCoin.ownAccountId { // return Result::FAIL {code:String::from("FAIL"), msg:String::from("can sub the coin to not same account"),credit:self, debit:anotherCoin}; // } // if self.currency != anotherCoin.currency { // return Result::FAIL {code:String::from("FAIL"), msg:String::from("can sub the coin to not same currency"),credit:self, debit:anotherCoin}; // } if self.amount < subAmount { // 币数量不够,失败,新币是0; let coin = FlyCoin { amount: 0, currency: self.currency.clone(), ownAccountId: toAddress.clone(), }; return Result::FAIL {code:String::from("FAIL"), msg:String::from("can sub the coin less than"),credit:self, debit:coin}; } let coinB = FlyCoin { amount:subAmount, currency:self.currency.clone(), ownAccountId:toAddress.clone(), }; let coinA = FlyCoin { amount:self.amount - subAmount, currency:self.currency, ownAccountId:self.ownAccountId }; // 减少成功,返回新的币 return Result::SUCCESS_BOTH{code:String::from("SUCCESS"),msg:String::from("Move coin to new account"), credit:coinB, debit:coinA}; } } #[test] pub fn test_lfy() { let mut coinA = FlyCoin::create(100, String::from("CNY"), String::from("address_A")); let moveResult = coinA.moveTo(String::from("address_B")); // let coin2 = match moveResult { // Result::SUCCESS{code, msg, item} => item, // Result::FAIL{code, msg, credit, debit} => credit, // }; let mut coinB:FlyCoin = match moveResult { Result::SUCCESS{code, msg, item} => item, Result::FAIL{code, msg, credit, debit} => credit, }; // if let Result::SUCCESS{code, msg, item} = moveResult { // // // coinB = item; // } else if let Result::FAIL{code, msg, credit, debit} = moveResult { // // 如果是失败, 退回给A, B得到的是空. // coinB = credit; // } println!("move coin1 to address_B "); // 转移成功, 这里再使用coin1就回报错 // coin1.moveTo("address_B") let coinC = FlyCoin::create(50, String::from("CNY"), String::from("address_B")); let addResult = coinB.add(coinC); let coinD = match addResult { Result::SUCCESS{code, msg, item} => item, Result::FAIL{code, msg, credit, debit} => credit, }; println!("add coin3 to coin2 become to coinD {}", coinD.amount); } }
true
6bb6e6a94e3c0042a3a3ea91668729ad37b4d59a
Rust
arafat1/cprocessor
/src/circuit/comparator.rs
UTF-8
924
3.328125
3
[]
no_license
use crate::gate::logic_gates::{and8, not, xor2}; use crate::memory::register::Register8Bits; /// Compare two 8 bit words and return 1 if they are equal else return 0 pub fn compare8(r1: &Register8Bits, r2: &Register8Bits) -> u8 { and8( not(xor2(r1.a0, r2.a0)), not(xor2(r1.a1, r2.a1)), not(xor2(r1.a2, r2.a2)), not(xor2(r1.a3, r2.a3)), not(xor2(r1.a4, r2.a4)), not(xor2(r1.a5, r2.a5)), not(xor2(r1.a6, r2.a6)), not(xor2(r1.a7, r2.a7)), ) } #[cfg(test)] mod tests { use super::*; #[test] fn compare_equal() { let r1 = Register8Bits::new(); let r2 = Register8Bits::new(); assert_eq!(compare8(&r1, &r2), 1); } #[test] fn compare_not_equal() { let mut r1 = Register8Bits::new(); let r2 = Register8Bits::new(); r1.change_bit1(1); assert_eq!(compare8(&r1, &r2), 0); } }
true
d766f13f88509f8dda187d21deccd27bb3405539
Rust
TheKK/rustnes
/src/opcode/ldx.rs
UTF-8
6,918
2.9375
3
[]
no_license
use super::Cycle; use super::OpCode; use cpu::Registers; use cpu::Memory; #[inline] fn ldx(registers: &mut Registers, val: u8) { set_flag!(zero -> (registers, val)); set_flag!(sign -> (registers, val)); registers.x = val; } opcode_fn_with_mode!(imm -> (ldx_imm, ldx, Cycle(2))); opcode_fn_with_mode!(zero_page -> (ldx_zero_page, ldx, Cycle(3))); opcode_fn_with_mode!(zero_page_y -> (ldx_zero_page_y, ldx, Cycle(4))); opcode_fn_with_mode!(abs -> (ldx_abs, ldx, Cycle(4))); opcode_fn_with_mode!(abs_y -> (ldx_abs_y, ldx, page_crossed Cycle(5), or_else Cycle(4))); #[cfg(test)] mod test { use super::*; use cpu::RP2A03; use opcode::utils::test::*; macro_rules! ldx_test ( (test_name=$test_name: ident, $opcode: expr, arrange_fn=$arrange_fn: expr, reg_x=$expected_reg_x: expr, zero_flag=$zero_flag: expr, sign_flag=$sign_flag: expr ) => { #[test] fn $test_name() { let mut cpu = RP2A03::new(); cpu.memory.write(0, $opcode.into()); $arrange_fn(&mut cpu, $expected_reg_x); let mem_snapshot = cpu.memory.clone(); let regs_snaptshot = cpu.registers.clone(); cpu.execute(); assert_eq!(cpu.memory, mem_snapshot); assert_eq!(cpu.registers.x, $expected_reg_x); assert_eq!(cpu.registers.zero_flag(), $zero_flag); assert_eq!(cpu.registers.sign_flag(), $sign_flag); assert_field_eq!(cpu.registers, regs_snaptshot, [ carry_flag(), interrupt_disable_flag(), decimal_mode_flag(), break_command_flag(), overflow_flag() ]); assert_field_eq!(cpu.registers, regs_snaptshot, [sp, a, y]); } } ); #[test] fn ldx_should_work() { let mut actual_registers = Registers::new(); let expected_val = 0x42; let expected_registers = { let mut reg_clone = actual_registers.clone(); reg_clone.x = expected_val; reg_clone }; ldx(&mut actual_registers, expected_val); assert_eq!(actual_registers, expected_registers) } #[test] fn ldx_with_zero_value() { let mut actual_registers = Registers::new(); let expected_val = 0x00; let expected_registers = { let mut reg_clone = actual_registers.clone(); reg_clone.x = expected_val; reg_clone.set_zero_flag(true); reg_clone }; ldx(&mut actual_registers, expected_val); assert_eq!(actual_registers, expected_registers) } #[test] fn ldx_with_sign_value() { let mut actual_registers = Registers::new(); let expected_val = 0b10000000; let expected_registers = { let mut reg_clone = actual_registers.clone(); reg_clone.x = expected_val; reg_clone.set_sign_flag(true); reg_clone }; ldx(&mut actual_registers, expected_val); assert_eq!(actual_registers, expected_registers) } ldx_test!( test_name = ldx_imm, OpCode::LdxImm, arrange_fn = arrange_for_imm, reg_x = 0x42, zero_flag = false, sign_flag = false ); ldx_test!( test_name = ldx_zero_page, OpCode::LdxZeroPage, arrange_fn = arrange_for_zero_page, reg_x = 0x42, zero_flag = false, sign_flag = false ); ldx_test!( test_name = ldx_zero_page_y, OpCode::LdxZeroPageY, arrange_fn = arrange_for_zero_page_y, reg_x = 0x42, zero_flag = false, sign_flag = false ); ldx_test!( test_name = ldx_abs, OpCode::LdxAbs, arrange_fn = arrange_for_abs, reg_x = 0x42, zero_flag = false, sign_flag = false ); ldx_test!( test_name = ldx_abs_y, OpCode::LdxAbsY, arrange_fn = arrange_for_abs_y, reg_x = 0x42, zero_flag = false, sign_flag = false ); ldx_test!( test_name = ldx_abs_y_with_page_crossing, OpCode::LdxAbsY, arrange_fn = arrange_for_abs_y_with_page_crossing, reg_x = 0x42, zero_flag = false, sign_flag = false ); ldx_test!( test_name = ldx_imm_zero, OpCode::LdxImm, arrange_fn = arrange_for_imm, reg_x = 0x00, zero_flag = true, sign_flag = false ); ldx_test!( test_name = ldx_zero_zero, OpCode::LdxZeroPage, arrange_fn = arrange_for_zero_page, reg_x = 0x00, zero_flag = true, sign_flag = false ); ldx_test!( test_name = ldx_zero_page_y_zero, OpCode::LdxZeroPageY, arrange_fn = arrange_for_zero_page_y, reg_x = 0x00, zero_flag = true, sign_flag = false ); ldx_test!( test_name = ldx_abs_zero, OpCode::LdxAbs, arrange_fn = arrange_for_abs, reg_x = 0x00, zero_flag = true, sign_flag = false ); ldx_test!( test_name = ldx_abs_y_zero, OpCode::LdxAbsY, arrange_fn = arrange_for_abs_y, reg_x = 0x00, zero_flag = true, sign_flag = false ); ldx_test!( test_name = ldx_imm_sign, OpCode::LdxImm, arrange_fn = arrange_for_imm, reg_x = 0b10000000, zero_flag = false, sign_flag = true ); ldx_test!( test_name = ldx_zero_page_sign, OpCode::LdxZeroPage, arrange_fn = arrange_for_zero_page, reg_x = 0b10000000, zero_flag = false, sign_flag = true ); ldx_test!( test_name = ldx_zero_page_y_sign, OpCode::LdxZeroPageY, arrange_fn = arrange_for_zero_page_y, reg_x = 0b10000000, zero_flag = false, sign_flag = true ); ldx_test!( test_name = ldx_abs_sign, OpCode::LdxAbs, arrange_fn = arrange_for_abs, reg_x = 0b10000000, zero_flag = false, sign_flag = true ); ldx_test!( test_name = ldx_abs_y_sign, OpCode::LdxAbsY, arrange_fn = arrange_for_abs_y, reg_x = 0b10000000, zero_flag = false, sign_flag = true ); cross_boundary_cycle_count_add_one_test!( test_name = ldx_abs_y_cycle_count, OpCode::LdxAbsY, no_boundary_crossing_arrange_fn = arrange_for_abs_y, boundary_crossing_arrange_fn = arrange_for_abs_y_with_page_crossing, ); }
true
25ecf2058d14ebf0b8a143e8f44d3269908dd8f5
Rust
ant1441/slack-token
/src/token.rs
UTF-8
8,565
3.375
3
[]
no_license
//! A `Token` tracks the current "owner" of something, and is unique per channel. #![allow(dead_code)] use std::collections::{HashMap, VecDeque}; use std::sync::{Arc, Mutex, RwLock}; use std::fmt; use slack::{TeamId, ChannelId}; #[derive(Debug, PartialEq, Eq, Clone)] pub struct User { user_id: String, user_name: String, } impl User { pub fn new(user_id: String, user_name: String) -> User { User { user_id: user_id, user_name: user_name, } } pub fn as_slack_str(&self) -> String { format!("<@{}|{}>", self.user_id, self.user_name) } } impl fmt::Display for User { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.user_name) } } #[derive(Debug, PartialEq, Eq)] pub struct Token { users: VecDeque<User>, } pub type TokenRef = Arc<RwLock<Token>>; pub type TokensType = Mutex<HashMap<(TeamId, ChannelId), TokenRef>>; pub struct Tokens(pub TokensType); impl Tokens { pub fn new() -> Tokens { Tokens(Mutex::new(HashMap::new())) } } impl Token { /// Constructs a new, empty `Vec<T>`. /// /// The vector will not allocate until elements are pushed onto it. /// /// # Examples /// /// ``` /// # #![allow(unused_mut)] /// let mut vec: Vec<i32> = Vec::new(); /// ``` pub fn new() -> Token { let users = VecDeque::new(); Token { users: users } } pub fn len(&self) -> usize { self.users.len() } pub fn get(&mut self, user: User) -> Result<(), &'static str> { // We want the queue to be unique if self.users.iter().position(|u| *u == user).is_none() { Ok(self.users.push_back(user)) } else { Err("You are already in the queue!") } } pub fn drop(&mut self, user: &User) -> Result<(), &'static str> { if let Some(_) = self.users.iter().position(|u| u == user) { Ok((&mut self.users).retain(|u| u != user)) } else { Err("You are not in the queue!") } } pub fn step_back(&mut self, user: &User) -> Result<(), &'static str> { if let Some(pos) = self.users.iter().position(|u| u == user) { // Are we at the end of the queue? if pos >= self.len() - 1 { Err("You are at the end of the queue!") } else { Ok(self.users.swap(pos, pos + 1)) } } else { Err("You are not in the queue!") } } pub fn to_front(&mut self, user: &User) -> Result<(), &'static str> { if let Some(pos) = self.users.iter().position(|u| u == user) { // Are we already at the front of the queue? if pos == 0 { Err("You are already holding the token!") } else if pos == 1 { Err("You are already at the start of the queue!") } else { Ok(self.users.swap(pos, 1)) } } else { Err("You are not in the queue!") } } pub fn steal(&mut self, user: &User) -> Result<User, &'static str> { if let Some(pos) = self.users.iter().position(|u| u == user) { // Are we already at the front of the queue? if pos == 0 { Err("You are already holding the token!") } else { self.users.swap(pos, 0); // We know there is an item here, so unwrap is safe Ok(self.users.remove(pos).unwrap()) } } else { Err("You are not in the queue!") } } pub fn iter<'a>(&'a self) -> impl Iterator<Item=&'a User> { (&self.users).iter() } pub fn list_user_name(&self) -> Vec<&str> { (&self.users).iter().map(|u| u.user_name.as_str()).collect() } /// Test if the given user is holding the token pub fn is_holding(&self, user: &User) -> bool { self.users.front() == Some(user) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_get() { let mut t = Token::new(); let u = User::new("id".to_string(), "name".to_string()); t.get(u.clone()).unwrap(); assert!(t.is_holding(&u)); } #[test] fn test_drop() { let mut t = Token::new(); let u = User::new("id".to_string(), "name".to_string()); t.get(u.clone()).unwrap(); assert!(t.is_holding(&u)); t.drop(&u).unwrap(); assert!(!t.is_holding(&u)); } #[test] fn test_len() { let mut t = Token::new(); let u0 = User::new("id0".to_string(), "name0".to_string()); let u1 = User::new("id1".to_string(), "name1".to_string()); let u2 = User::new("id2".to_string(), "name2".to_string()); let u3 = User::new("id3".to_string(), "name3".to_string()); t.get(u0.clone()).unwrap(); assert_eq!(t.len(), 1); t.get(u1.clone()).unwrap(); assert_eq!(t.len(), 2); t.get(u2.clone()).unwrap(); assert_eq!(t.len(), 3); t.get(u3.clone()).unwrap(); assert_eq!(t.len(), 4); assert!(t.is_holding(&u0)); } #[test] fn test_list_user_name() { let mut t = Token::new(); let u0 = User::new("id0".to_string(), "name0".to_string()); let u1 = User::new("id1".to_string(), "name1".to_string()); let u2 = User::new("id2".to_string(), "name2".to_string()); let u3 = User::new("id3".to_string(), "name3".to_string()); t.get(u0).unwrap(); t.get(u1).unwrap(); t.get(u2).unwrap(); t.get(u3).unwrap(); assert_eq!(t.list_user_name(), vec!["name0", "name1", "name2", "name3"]); } #[test] fn test_step_back() { let mut t = Token::new(); let u0 = User::new("id0".to_string(), "name0".to_string()); let u1 = User::new("id1".to_string(), "name1".to_string()); let u2 = User::new("id2".to_string(), "name2".to_string()); let u3 = User::new("id3".to_string(), "name3".to_string()); t.get(u0.clone()).unwrap(); t.get(u1.clone()).unwrap(); t.get(u2.clone()).unwrap(); t.get(u3.clone()).unwrap(); t.step_back(&u0).unwrap(); assert_eq!(t.list_user_name(), vec!["name1", "name0", "name2", "name3"]); t.step_back(&u0).unwrap(); assert_eq!(t.list_user_name(), vec!["name1", "name2", "name0", "name3"]); t.step_back(&u0).unwrap(); assert_eq!(t.list_user_name(), vec!["name1", "name2", "name3", "name0"]); assert!(t.step_back(&u0).is_err()); } #[test] fn test_to_front() { let mut t = Token::new(); let u0 = User::new("id0".to_string(), "name0".to_string()); let u1 = User::new("id1".to_string(), "name1".to_string()); let u2 = User::new("id2".to_string(), "name2".to_string()); let u3 = User::new("id3".to_string(), "name3".to_string()); t.get(u0.clone()).unwrap(); t.get(u1.clone()).unwrap(); t.get(u2.clone()).unwrap(); t.get(u3.clone()).unwrap(); t.to_front(&u2).unwrap(); assert_eq!(t.list_user_name(), vec!["name0", "name2", "name1", "name3"]); assert!(t.to_front(&u2).is_err()); } #[test] fn test_steal() { let mut t = Token::new(); let u0 = User::new("id0".to_string(), "name0".to_string()); let u1 = User::new("id1".to_string(), "name1".to_string()); let u2 = User::new("id2".to_string(), "name2".to_string()); let u3 = User::new("id3".to_string(), "name3".to_string()); t.get(u0.clone()).unwrap(); t.get(u1.clone()).unwrap(); t.get(u2.clone()).unwrap(); t.get(u3.clone()).unwrap(); t.steal(&u2).unwrap(); assert_eq!(t.list_user_name(), vec!["name2", "name1", "name3"]); t.steal(&u3).unwrap(); assert_eq!(t.list_user_name(), vec!["name3", "name1"]); assert!(t.steal(&u2).is_err()); } #[test] fn test_is_holding() { let mut t = Token::new(); let u0 = User::new("id0".to_string(), "name0".to_string()); let u1 = User::new("id1".to_string(), "name1".to_string()); let u2 = User::new("id2".to_string(), "name2".to_string()); let u3 = User::new("id3".to_string(), "name3".to_string()); t.get(u0.clone()).unwrap(); t.get(u1.clone()).unwrap(); t.get(u2.clone()).unwrap(); t.get(u3.clone()).unwrap(); assert!(t.is_holding(&u0)) } }
true
b0bd1f205c20b5d3d46bf4542e7d32a59b1326aa
Rust
reitermarkus/serverless
/functions/log-data/src/lib.rs
UTF-8
2,623
2.734375
3
[]
no_license
use std::error::Error; use http::{HeaderMap, Method, Uri, StatusCode}; use serde::{Deserialize, Serialize}; use serde_json::{self, json, Value}; use openfaas; const SUPPORTED_DATA_TYPES: [&'static str; 15] = [ "cpu_frequency", "proximity", "acceleration", "cpu_temperature", "gravity", "humidity", "illuminance", "magnetic_field", "magnetic_field_uncalibrated", "orientation", "pressure", "rotation", "rotation_rate", "rotation_rate_uncalibrated", "temperature", ]; #[derive(Deserialize, Serialize)] struct Data { device_id: String, #[serde(rename = "type", skip_serializing)] data_type: String, time: String, value: Value, } pub async fn handle(method: Method, _uri: Uri, _headers: HeaderMap, body: String) -> Result<(StatusCode, String), Box<dyn Error + Send + Sync>> { if method != Method::POST { return Ok((StatusCode::METHOD_NOT_ALLOWED, format!("Method '{}' is not allowed.", method))) } let data = match serde_json::from_str::<Data>(&body) { Ok(data) => data, _ => { log::error!("Invalid JSON format:\n{}", body); return Ok((StatusCode::BAD_REQUEST, "Invalid format.".to_string())) }, }; if !SUPPORTED_DATA_TYPES.iter().any(|&t| t == data.data_type) { log::error!("Data type '{}' is not supported.", data.data_type); return Ok((StatusCode::BAD_REQUEST, format!("Data type '{}' is not supported.", data.data_type))); } if data.data_type == "illuminance" { log::debug!("Illuminance for device '{}': {:?}", data.device_id, data.value); } let res = openfaas::call("database", json!({ "collection": "devices", "action": "update", "query": { "_id": data.device_id, }, "update": { "$addToSet": { "data_types": data.data_type }, } }).to_string()).await; match res { Ok((code, err)) if !code.is_success() => { log::error!("Error updating device '{}': {}", data.device_id, err); return Ok((code, err)) }, Err(err) => { log::error!("Error updating device '{}': {}", data.device_id, err); return Err(err) } _ => {}, } let res = openfaas::call("database", json!({ "collection": data.data_type, "action": "insert", "doc": data, }).to_string()).await; match res { Ok((code, err)) if !code.is_success() => { log::error!("Error inserting '{}' data for device '{}': {}", data.data_type, data.device_id, err); return Ok((code, err)) }, Err(err) => { log::error!("Error inserting '{}' data for device '{}': {}", data.data_type, data.device_id, err); Err(err) }, ok => ok, } }
true
df1062828cec6380b2c9b515cf9a0f47b9ef3c6b
Rust
pakky94/rnes
/src/ppu/mod.rs
UTF-8
33,329
2.546875
3
[]
no_license
pub mod buffer; mod sprite_unit; use self::sprite_unit::SpriteUnit; use crate::{bus::PpuAction, memory::PpuMemory}; use buffer::Buffer; const IMAGE_COLOR_PALETTE_ADDRESS: u16 = 0x3F00; const SPRITE_COLOR_PALETTE_ADDRESS: u16 = 0x3F10; const SCREEN_WIDTH: usize = 256; const SCREEN_HEIGHT: usize = 240; pub struct Ppu { memory: PpuMemory, buffers: Vec<Buffer>, current_frame: Buffer, even_frame: bool, cycles: usize, x: usize, y: usize, nmi_enabled: bool, vblank_flag: bool, rendering_enabled: bool, sprite_zero_hit: bool, sprite_height: u8, sprite_pattern_table: u16, background_pattern_table: u16, sprites_pattern_table: u16, vram_address_increment: u16, // internal registers reg_v: u16, reg_t: u16, reg_x: u8, reg_w: bool, fine_x: u8, x_increment_counter: u8, // OAM stuff current_line_has_sprite_zero: bool, next_line_has_sprite_zero: bool, sprite_evaluation_state: SpriteEvaluationState, oam_n: usize, secondary_oam: [u8; 0x20], secondary_oam_pointer: usize, oam_addr: u8, oam_buffer: u8, oam_initializing: bool, sprite_units: [SpriteUnit; 8], sprite_pattern_address: u16, // PPUCTRL grayscale: bool, show_backgroudn_leftmost: bool, show_sprites_leftmost: bool, show_background: bool, show_sprites: bool, emphasize_red: bool, emphasize_green: bool, emphasize_blue: bool, // rendering pipeline pattern_table_buffer1: u8, pattern_table_buffer2: u8, current_tile: u8, current_attribute_quadrant: u8, current_attribute_address: u16, pattern_table_reg1: u16, pattern_table_reg2: u16, palette_attribute_buffer1: u8, palette_attribute_buffer2: u8, palette_attriubutes_reg1: u16, palette_attriubutes_reg2: u16, io_latch: u8, pixels: usize, } pub struct PpuTickResult { pub(crate) nmi_triggered: bool, pub(crate) frame_ended: bool, } enum SpriteEvaluationState { Read0(usize), Copy0(usize), Read1(usize), Copy1(usize), Read2(usize), Copy2(usize), Read3(usize), Copy3(usize), } impl Ppu { pub(crate) fn new(memory: PpuMemory) -> Self { Ppu { memory, buffers: Vec::new(), current_frame: Buffer::empty(SCREEN_WIDTH, SCREEN_HEIGHT), even_frame: false, cycles: 0, x: 340, y: 261, nmi_enabled: true, vblank_flag: false, rendering_enabled: true, sprite_zero_hit: false, sprite_height: 8, sprite_pattern_table: 0, background_pattern_table: 0, sprites_pattern_table: 0, vram_address_increment: 1, reg_v: 0, reg_t: 0, reg_x: 0, reg_w: false, fine_x: 0, x_increment_counter: 0, current_line_has_sprite_zero: false, next_line_has_sprite_zero: false, sprite_evaluation_state: SpriteEvaluationState::Read0(0), oam_n: 0, secondary_oam: [0u8; 0x20], secondary_oam_pointer: 0, oam_addr: 0, oam_buffer: 0, oam_initializing: false, sprite_units: SpriteUnit::units(), sprite_pattern_address: 0, grayscale: false, show_backgroudn_leftmost: false, show_sprites_leftmost: false, show_background: false, show_sprites: false, emphasize_red: false, emphasize_green: false, emphasize_blue: false, current_tile: 0, current_attribute_quadrant: 0, current_attribute_address: 0, pattern_table_buffer1: 0, pattern_table_buffer2: 0, pattern_table_reg1: 0, pattern_table_reg2: 0, palette_attribute_buffer1: 0, palette_attribute_buffer2: 0, palette_attriubutes_reg1: 0, palette_attriubutes_reg2: 0, io_latch: 0, pixels: 0, } } pub fn tick(&mut self, action: PpuAction) -> PpuTickResult { self.oam_addr = self.memory.oam_address_mirror_read(); self.update_position(); self.update_flags(); self.handle_bus_action(action); // TODO: self.sprite_evaluation(); if self.is_rendering_enabled() { self.rendering(); } // Reset sprite zero hit if self.y == 261 && self.x == 1 { self.sprite_zero_hit = false; } self.cycles += 1; let mut nmi_triggered = false; let mut frame_ended = false; if self.x == 1 && self.y == 241 { frame_ended = true; println!("pixels this frame: {}", self.pixels); self.pixels = 0; if self.nmi_enabled { nmi_triggered = true; } else { println!("NMI disabled") } } self.memory.oam_address_mirror_write(self.oam_addr); self.memory.set_v(self.reg_v); PpuTickResult { nmi_triggered, frame_ended, } } fn rendering(&mut self) { if self.x == 0 { // Idle cycle return; } if self.y < 240 { if self.x >= 2 && self.x <= 257 { self.shift_registers(); self.shift_sprites(); } else if self.x >= 322 && self.x <= 337 { self.shift_registers(); } } else if self.y == 261 { if self.x >= 322 && self.x <= 337 { //if self.x == 322 { //println!("fine_x: {}", self.fine_x); //self.fine_x = self.reg_x; //} self.shift_registers(); } } if self.x <= 256 { if self.y < 240 { let fine_x = self.reg_x; let mut bg_color = (self.pattern_table_reg1 >> (15 - fine_x)) & 1; bg_color = bg_color | ((self.pattern_table_reg2 >> (15 - fine_x)) & 1) << 1; //color = color | 0b0000; bg_color = bg_color | ((self.palette_attriubutes_reg1 >> (15 - fine_x)) & 1) << 2; bg_color = bg_color | ((self.palette_attriubutes_reg2 >> (15 - fine_x)) & 1) << 3; // TODO: render sprites here let (sprite_color, sprite_fg, sprite_zero) = self.get_sprite_color(); if sprite_zero && (sprite_color & 3 != 0) && (bg_color & 3 != 0) { self.sprite_zero_hit = true; } //if (self.y % 8 == 0) && (self.x % 8 < 4) { //self.current_frame //.set_pixel(self.x - 1, self.y, 0, 0xFF, 0xFF); //} else { let (r, g, b) = if (sprite_color & 0x03) == 0 || (!sprite_fg && bg_color & 0x03 != 0) { if bg_color & 0x03 == 0 { bg_color = 0; } self.map_background_color(bg_color as u8) } else { //println!("sprite_color: {:08b}, fg: {}", sprite_color, sprite_fg); self.map_sprite_color(sprite_color) }; self.current_frame.set_pixel(self.x - 1, self.y, r, g, b); //} } } if self.y < 240 { if (self.x % 8 == 1) && ((self.x >= 9 && self.x <= 257) || (self.x == 329 || self.x == 337)) { self.merge_buffers_into_shift_registers(); } if self.x >= 1 && self.x <= 256 { //self.shift_registers(); self.fetch_background_data(); } else if self.x >= 321 && self.x <= 336 { //self.shift_registers(); self.fetch_background_data(); } } else if self.y == 261 { if self.x == 329 || self.x == 337 { self.merge_buffers_into_shift_registers(); } if self.x >= 321 && self.x <= 336 { //self.shift_registers(); self.fetch_background_data(); } } if self.y < 240 { if (self.x >= 1 && self.x <= 240) || (self.x >= 321 && self.x <= 336) { self.increment_x(); } else if self.x == 256 { self.increment_y(); self.pixels += 1; } else if self.x == 257 { self.copy_tx_to_v(); } } else if self.y == 261 { if self.x >= 321 && self.x <= 336 { self.increment_x(); //self.pixels += 1; } else if self.x >= 280 && self.x <= 304 { self.copy_ty_to_v(); } } } fn sprite_evaluation(&mut self) { //if self.x == 0 || (self.y != 261 && self.y >= 240) { if self.x == 0 || self.y >= 240 { return; } if self.x == 1 { self.oam_n = 0; self.secondary_oam_pointer = 0; self.sprite_evaluation_state = SpriteEvaluationState::Read0(0); self.current_line_has_sprite_zero = self.next_line_has_sprite_zero; self.next_line_has_sprite_zero = false; } //let eval_y = if self.y == 261 { 0 } else { self.y + 1 }; let eval_y = self.y; if self.x <= 64 { if self.x % 2 == 0 { self.secondary_oam[(self.x / 2) as usize - 1] = 0xFF; } } else if self.x <= 256 { // TODO: Sprite overflow flag //println!("secondary oam pointer: {}", self.secondary_oam_pointer); match self.sprite_evaluation_state { SpriteEvaluationState::Read0(n) => { self.oam_buffer = self.memory.read_oam(n * 4); self.sprite_evaluation_state = SpriteEvaluationState::Copy0(n); } SpriteEvaluationState::Copy0(n) => { if self.secondary_oam_pointer >= 32 { // Already found 8 sprites, ignore write. self.sprite_evaluation_state = SpriteEvaluationState::Read0(0); } else { self.secondary_oam[self.secondary_oam_pointer] = self.oam_buffer; self.sprite_evaluation_state = if self.sprite_in_range(self.oam_buffer, eval_y) { if n == 0 { self.next_line_has_sprite_zero = true; } self.secondary_oam_pointer += 1; SpriteEvaluationState::Read1(n) } else { SpriteEvaluationState::Read0((n + 1) % 64) }; } } SpriteEvaluationState::Read1(n) => { self.oam_buffer = self.memory.read_oam(n * 4 + 1); self.sprite_evaluation_state = SpriteEvaluationState::Copy1(n); } SpriteEvaluationState::Copy1(n) => { self.secondary_oam[self.secondary_oam_pointer] = self.oam_buffer; self.secondary_oam_pointer += 1; self.sprite_evaluation_state = SpriteEvaluationState::Read2(n); } SpriteEvaluationState::Read2(n) => { self.oam_buffer = self.memory.read_oam(n * 4 + 2); self.sprite_evaluation_state = SpriteEvaluationState::Copy2(n); } SpriteEvaluationState::Copy2(n) => { self.secondary_oam[self.secondary_oam_pointer] = self.oam_buffer; self.secondary_oam_pointer += 1; self.sprite_evaluation_state = SpriteEvaluationState::Read3(n); } SpriteEvaluationState::Read3(n) => { self.oam_buffer = self.memory.read_oam(n * 4 + 3); self.sprite_evaluation_state = SpriteEvaluationState::Copy3(n); } SpriteEvaluationState::Copy3(n) => { self.secondary_oam[self.secondary_oam_pointer] = self.oam_buffer; self.secondary_oam_pointer += 1; self.sprite_evaluation_state = SpriteEvaluationState::Read0((n + 1) % 64); } } } else if self.x <= 320 { // Sprite fetches let sprite_id = ((self.x - 257) & 0b111000) >> 3; let sprite_found = (sprite_id * 4 + 1) < self.secondary_oam_pointer; if sprite_found { match (self.x - 257) % 8 { 0 => { self.sprite_units[sprite_id].y = self.secondary_oam[sprite_id * 4]; } 1 => { self.sprite_units[sprite_id].tile_number = self.secondary_oam[sprite_id * 4 + 1]; } 2 => { self.sprite_units[sprite_id].attributes = self.secondary_oam[sprite_id * 4 + 2]; } 3 => { self.sprite_units[sprite_id].position = self.secondary_oam[sprite_id * 4 + 3]; } 4 => { self.sprite_pattern_address = self.sprite_units[sprite_id] .get_low_data_address( eval_y, self.sprite_pattern_table, self.sprite_height == 8, ); } 5 => { self.sprite_units[sprite_id] .set_low_color(self.memory.read(self.sprite_pattern_address)); } 6 => { self.sprite_pattern_address = self.sprite_units[sprite_id] .get_high_data_address( eval_y, self.sprite_pattern_table, self.sprite_height == 8, ); } 7 => { self.sprite_units[sprite_id] .set_high_color(self.memory.read(self.sprite_pattern_address)); } _ => unreachable!(), } } else { self.sprite_units[sprite_id].set_transparent(); } } } fn get_sprite_color(&self) -> (u8, bool, bool) { for (i, sprite) in self.sprite_units.iter().enumerate() { let color = sprite.get_color(); if (color & 3) != 0 { return (color, sprite.is_foreground(), i == 0); } } (0, false, false) } fn shift_sprites(&mut self) { self.sprite_units.iter_mut().for_each(|sprite| { sprite.shift_left(); }); } fn sprite_in_range(&mut self, sprite_y: u8, screen_y: usize) -> bool { (sprite_y as usize) <= screen_y && (sprite_y as usize + self.sprite_height as usize) > screen_y } fn copy_tx_to_v(&mut self) { let t_x = self.reg_t & 0b00000100_00011111; let new_v = self.reg_v & 0b11111011_11100000; self.reg_v = new_v | t_x; } fn copy_ty_to_v(&mut self) { let t_y = self.reg_t & 0b01111011_11100000; let new_v = self.reg_v & 0b10000100_00011111; self.reg_v = new_v | t_y; } fn shift_registers(&mut self) { // shift bits self.pattern_table_reg1 <<= 1; self.pattern_table_reg2 <<= 1; self.palette_attriubutes_reg1 <<= 1; self.palette_attriubutes_reg2 <<= 1; } fn merge_buffers_into_shift_registers(&mut self) { self.pattern_table_reg1 = (self.pattern_table_reg1 & 0xFF00) | (self.pattern_table_buffer1 as u16); self.pattern_table_reg2 = (self.pattern_table_reg2 & 0xFF00) | (self.pattern_table_buffer2 as u16); self.palette_attriubutes_reg1 = (self.palette_attriubutes_reg1 & 0xFF00) | (self.palette_attribute_buffer1 as u16); self.palette_attriubutes_reg2 = (self.palette_attriubutes_reg2 & 0xFF00) | (self.palette_attribute_buffer2 as u16); } fn fetch_background_data(&mut self) { match self.x % 8 { 1 => { let tile_address = self.get_tile_address(); self.current_tile = self.memory.read(tile_address); let bit2_y = ((self.reg_v & 0x40) >> 5) as u8; // Second bit of coarse Y let bit2_x = ((self.reg_v & 2) >> 1) as u8; // Second bit of coarse X self.current_attribute_quadrant = bit2_x | bit2_y; //self.current_attribute_quadrant = 3 - self.current_attribute_quadrant; self.current_attribute_address = self.get_attribute_address(); } 3 => { let attribute_data = self.memory.read(self.current_attribute_address); self.palette_attribute_buffer1 = ((attribute_data >> (2 * self.current_attribute_quadrant)) & 1) * 255; self.palette_attribute_buffer2 = ((attribute_data >> (2 * self.current_attribute_quadrant + 1)) & 1) * 255; } 5 => { let pattern_address = self.background_pattern_table | ((self.current_tile as u16) << 4); let pattern_address = pattern_address | self.fine_y(); self.pattern_table_buffer1 = self.memory.read(pattern_address); } 7 => { let pattern_address = self.background_pattern_table | ((self.current_tile as u16) << 4); let pattern_address = pattern_address | self.fine_y() | 8; self.pattern_table_buffer2 = self.memory.read(pattern_address); } _ => {} } } fn map_sprite_color(&mut self, color_idx: u8) -> (u8, u8, u8) { let system_color = self .memory .read(SPRITE_COLOR_PALETTE_ADDRESS | color_idx as u16); map_system_color_to_rgb(system_color) } fn map_background_color(&mut self, color_idx: u8) -> (u8, u8, u8) { let system_color = self .memory .read(IMAGE_COLOR_PALETTE_ADDRESS | color_idx as u16); map_system_color_to_rgb(system_color) } pub fn get_frame(&mut self) -> Buffer { let mut new_buffer = if let Some(buf) = self.buffers.pop() { buf } else { Buffer::empty(SCREEN_WIDTH, SCREEN_HEIGHT) }; std::mem::swap(&mut self.current_frame, &mut new_buffer); new_buffer } pub fn transfer_io_registers(&mut self) { self.memory.set_ppu_io_registers(self.get_io_registers()) } fn get_io_registers(&self) -> PpuIoRegisters { let status = if self.vblank_flag { 128 } else { 0 }; let status = status | if self.sprite_zero_hit { 0x40 } else { 0 }; PpuIoRegisters { status, last_written: self.io_latch, } } pub fn return_frame(&mut self, buffer: Buffer) { self.buffers.push(buffer); } fn handle_bus_action(&mut self, action: PpuAction) { match action { PpuAction::PpuCtrlWrite(val) => { println!("t was: {:016b}", self.reg_t); self.io_latch = val; let background_table = val >> 4; let background_table = background_table & 1 == 1; if background_table { self.background_pattern_table = 0x1000; } else { self.background_pattern_table = 0; } let sprite_table = val >> 3; let sprite_table = sprite_table & 1 == 1; if sprite_table { self.sprite_pattern_table = 0x1000; } else { self.sprite_pattern_table = 0; } let sprite_size = val >> 5; let sprite_size = sprite_size & 1 == 1; if sprite_size { self.sprite_height = 16; } else { self.sprite_height = 8; } let t_temp = self.reg_t & 0b11110011_11111111; let new_t = ((val & 0b00000011) as u16) << 10; self.reg_t = t_temp | new_t; let nmi_enable = val & 128 != 0; self.nmi_enabled = nmi_enable; self.vram_address_increment = if val & 4 == 0 { 1 } else { 32 }; println!("t is: {:016b}", self.reg_t); } PpuAction::PpuMaskWrite(val) => { self.io_latch = val; self.grayscale = val & 1 != 0; self.show_backgroudn_leftmost = val & 2 != 0; self.show_sprites_leftmost = val & 4 != 0; self.show_background = val & 8 != 0; self.show_sprites = val & 16 != 0; self.emphasize_red = val & 32 != 0; self.emphasize_green = val & 64 != 0; self.emphasize_blue = val & 128 != 0; } PpuAction::PpuStatusRead => { self.vblank_flag = false; self.reg_w = false; } PpuAction::OamAddrWrite(val) => { self.oam_addr = val; } PpuAction::OamDataWrite(val) => { // TODO: println!("OAM data write {:#04x} at addr: {:#04x}", val, self.oam_addr); if self.y >= 240 && self.y != 261 { self.memory.write_oam(self.oam_addr as usize, val); } self.oam_addr = self.oam_addr.wrapping_add(1); } PpuAction::PpuScrollWrite(val) => { println!("t was: {:016b}", self.reg_t); if self.reg_w == false { let t_temp = self.reg_t & 0b11111111_11100000; let new_t = (val as u16) >> 3; self.reg_t = t_temp | new_t; self.reg_x = val & 0b00000111; self.reg_w = true; } else { let t_temp = self.reg_t & 0b00001100_00011111; let fgh = ((val & 0b00000111) as u16) << 12; let abcde = ((val & 0b11111000) as u16) << 2; self.reg_t = t_temp | fgh | abcde; self.reg_w = false; } println!("t is: {:016b}", self.reg_t); } PpuAction::PpuAddrWrite(val) => { println!("t was: {:016b}", self.reg_t); if self.reg_w == false { let t_temp = self.reg_t & 0b10000000_11111111; let cdefgh = ((val & 0b00111111) as u16) << 8; self.reg_t = (t_temp | cdefgh) & 0b00111111_11111111; self.reg_w = true; } else { let t_temp = self.reg_t & 0b11111111_00000000; self.reg_t = t_temp | (val as u16); self.reg_v = self.reg_t; self.reg_w = false; } println!("t is: {:016b}", self.reg_t); println!("v is: {:016b}", self.reg_v); } PpuAction::PpuDataRead => { self.reg_v = self.reg_v.wrapping_add(self.vram_address_increment); println!("ppu address: {:#06x}", self.reg_v); // TODO: //todo!(); } PpuAction::PpuDataWrite(val) => { self.memory.write(self.reg_v, val); self.reg_v = self.reg_v.wrapping_add(self.vram_address_increment); } PpuAction::OamDmaWrite(_) => todo!(), PpuAction::None => {} } } fn update_flags(&mut self) { if self.x == 1 { if self.y == 241 { println!("VBLANK STARTED"); self.vblank_flag = true; } else if self.y == 261 { println!("VBLANK ENDED"); self.vblank_flag = false; } } } fn update_position(&mut self) { self.x += 1; if self.x > 340 { self.x = 0; self.y += 1; if self.y > 261 { self.y = 0; self.even_frame = !self.even_frame; if !self.even_frame { self.x = 1; } } } } fn is_rendering_enabled(&self) -> bool { // TODO: check this self.show_background | self.show_sprites } fn get_tile_address(&self) -> u16 { let v = self.reg_v; let addr = 0x2000 | (v & 0x0FFF); //println!("{:#06x}", addr); addr } fn get_attribute_address(&self) -> u16 { let v = self.reg_v; 0x23C0 | (v & 0x0C00) | ((v >> 4) & 0x38) | ((v >> 2) & 0x07) } fn increment_x(&mut self) { self.x_increment_counter += 1; if self.x_increment_counter == 8 { self.x_increment_counter = 0; self.coarse_increment_x(); } } fn coarse_increment_x(&mut self) { let mut v = self.reg_v; // Increment coarse X if (v & 0x001F) == 31 { // if coarse X == 31 v &= !0x001F; // coarse X = 0 v ^= 0x0400; // switch horizontal nametable } else { v += 1 // increment coarse X } self.reg_v = v; } fn increment_y(&mut self) { let mut v = self.reg_v; if (v & 0x7000) != 0x7000 { // if fine Y < 7 v += 0x1000 // increment fine Y } else { v &= !0x7000; // fine Y = 0 let mut y = (v & 0x03E0) >> 5; // let y = coarse Y if y == 29 { y = 0; // coarse Y = 0 v ^= 0x0800; // switch vertical nametable } else if y == 31 { y = 0; // coarse Y = 0, nametable not switched } else { y += 1; // increment coarse Y } v = (v & !0x03E0) | (y << 5); // put coarse Y back into v } self.reg_v = v; } fn fine_y(&self) -> u16 { let y = self.reg_v >> 12; assert!(y < 8); y } pub(crate) fn render_pattern_table(&mut self, table_addr: u16, palette_idx: usize) -> Buffer { let mut buf = Buffer::empty(128, 128); for y in 0..16 { for x in 0..16 { let tile = self.render_tile(table_addr + y * 0x100 + x * 0x10, palette_idx); for y_fine in 0..8 { for x_fine in 0..8 { let pixel = tile[y_fine][x_fine]; let (r, g, b) = map_system_color_to_rgb(pixel); buf.set_pixel(x as usize * 8 + x_fine, y as usize * 8 + y_fine, r, g, b); } } } } buf } pub(crate) fn render_nametable(&mut self, idx: usize) -> Buffer { let nametable_addr = (idx * 0x400 + 0x2000) as u16; let patterntable_addr = self.background_pattern_table; let mut buf = Buffer::empty(256, 240); for y in 0..30 { for x in 0..32 { let tile_offset = y * 32 + x; let tile_addr_offset = self.memory.read(nametable_addr + tile_offset) as u16 * 16; let attribute_addr_offset = ((y & 0b11100) << 1) | ((x & 0b11100) >> 2); let attribute_byte = self.memory.read(nametable_addr + 960 + attribute_addr_offset); let attribute_idx = y & 0b10 | ((x & 0b10) >> 1); let palette = (attribute_byte >> (2 * attribute_idx)) & 0b11; let tile = self.render_tile(tile_addr_offset + patterntable_addr, palette as usize); for y_fine in 0..8 { for x_fine in 0..8 { let pixel = tile[y_fine][x_fine]; let (r, g, b) = map_system_color_to_rgb(pixel); buf.set_pixel(x as usize * 8 + x_fine, y as usize * 8 + y_fine, r, g, b); } } } } buf } fn render_tile(&mut self, address: u16, palette_idx: usize) -> [[u8; 8]; 8] { let mut palette = [0u8; 4]; let bg_color = self.memory.read(IMAGE_COLOR_PALETTE_ADDRESS); for i in 0..4 { palette[i] = self .memory .read(IMAGE_COLOR_PALETTE_ADDRESS + palette_idx as u16 * 4 + i as u16); } let mut out = [[0; 8]; 8]; for y in 0..8 { let low = self.memory.read(address + y); let high = self.memory.read(address + y + 8); for x in 0..8 { let pixel = ((low >> (7 - x)) & 1) | (((high >> (7 - x)) & 1) << 1); let pixel = if pixel == 0 { bg_color } else { palette[pixel as usize] }; out[y as usize][x as usize] = pixel } } out } pub(crate) fn render_palettes(&mut self) -> Buffer { let mut buf = Buffer::empty(256, 32); for y in 0..2 { for x in 0..16 { let color_idx = y * 16 + x; let color_idx = self.memory.read(color_idx + 0x3F00); let (r, g, b) = map_system_color_to_rgb(color_idx); for y_fine in 0..16 { for x_fine in 0..16 { buf.set_pixel(x as usize * 16 + x_fine, y as usize * 16 + y_fine, r, g, b); } } } } buf } } fn map_system_color_to_rgb(color: u8) -> (u8, u8, u8) { match color & 0x3F { 0x00 => (0x75, 0x75, 0x75), 0x01 => (0x27, 0x1B, 0x8F), 0x02 => (0x00, 0x00, 0xAB), 0x03 => (0x47, 0x00, 0x9F), 0x04 => (0x8F, 0x00, 0x77), 0x05 => (0xAB, 0x00, 0x13), 0x06 => (0xA7, 0x00, 0x00), 0x07 => (0x7F, 0x0B, 0x00), 0x08 => (0x43, 0x2F, 0x00), 0x09 => (0x00, 0x47, 0x00), 0x0A => (0x00, 0x51, 0x00), 0x0B => (0x00, 0x3F, 0x17), 0x0C => (0x1B, 0x3F, 0x5F), 0x0D => (0x00, 0x00, 0x00), 0x0E => (0x00, 0x00, 0x00), 0x0F => (0x00, 0x00, 0x00), 0x10 => (0xBC, 0xBC, 0xBC), 0x11 => (0x00, 0x73, 0xEF), 0x12 => (0x23, 0x3B, 0xEF), 0x13 => (0x83, 0x00, 0xF3), 0x14 => (0xBF, 0x00, 0xBF), 0x15 => (0xE7, 0x00, 0x5B), 0x16 => (0xDB, 0x2B, 0x00), 0x17 => (0xCB, 0x4F, 0x0F), 0x18 => (0x8B, 0x73, 0x00), 0x19 => (0x00, 0x97, 0x00), 0x1A => (0x00, 0xAB, 0x00), 0x1B => (0x00, 0x93, 0x3B), 0x1C => (0x00, 0x83, 0x8B), 0x1D => (0x00, 0x00, 0x00), 0x1E => (0x00, 0x00, 0x00), 0x1F => (0x00, 0x00, 0x00), 0x20 => (0xFF, 0xFF, 0xFF), 0x21 => (0x3F, 0xBF, 0xFF), 0x22 => (0x5F, 0x97, 0xFF), 0x23 => (0xA7, 0x8B, 0xFD), 0x24 => (0xF7, 0x7B, 0xFF), 0x25 => (0xFF, 0x77, 0xB7), 0x26 => (0xFF, 0x77, 0x63), 0x27 => (0xFF, 0x9B, 0x3B), 0x28 => (0xF3, 0xBF, 0x3F), 0x29 => (0x83, 0xD3, 0x13), 0x2A => (0x4F, 0xDF, 0x4B), 0x2B => (0x58, 0xF8, 0x98), 0x2C => (0x00, 0xEB, 0xDB), 0x2D => (0x00, 0x00, 0x00), 0x2E => (0x00, 0x00, 0x00), 0x2F => (0x00, 0x00, 0x00), 0x30 => (0xFF, 0xFF, 0xFF), 0x31 => (0xAB, 0xE7, 0xFF), 0x32 => (0xC7, 0xD7, 0xFF), 0x33 => (0xD7, 0xCB, 0xFF), 0x34 => (0xFF, 0xC7, 0xFF), 0x35 => (0xFF, 0xC7, 0xDB), 0x36 => (0xFF, 0xBF, 0xB3), 0x37 => (0xFF, 0xDB, 0xAB), 0x38 => (0xFF, 0xE7, 0xA3), 0x39 => (0xE3, 0xFF, 0xA3), 0x3A => (0xAB, 0xF3, 0xBF), 0x3B => (0xB3, 0xFF, 0xCF), 0x3C => (0x9F, 0xFF, 0xF3), 0x3D => (0x00, 0x00, 0x00), 0x3E => (0x00, 0x00, 0x00), 0x3F => (0x00, 0x00, 0x00), //_ => (0xFF, 0x00, 0x00), _ => unreachable!("Unimplemented color {:#04x}", color), } } #[derive(Clone, Copy)] pub struct PpuIoRegisters { pub(crate) status: u8, pub(crate) last_written: u8, } impl PpuIoRegisters { pub fn new() -> Self { Self { status: 0, last_written: 0, } } }
true
7e1c9cc8f0ab6213aea136bef9ca24749ff3c778
Rust
seanpianka/slack-blocks-rs
/src/blocks/section.rs
UTF-8
11,638
3.21875
3
[ "MIT", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
//! # Section Block //! //! _[slack api docs 🔗]_ //! //! Available in surfaces: //! - [modals 🔗] //! - [messages 🔗] //! - [home tabs 🔗] //! //! A `section` is one of the most flexible blocks available - //! it can be used as a simple text block, //! in combination with text fields, //! or side-by-side with any of the available [block elements 🔗] //! //! [slack api docs 🔗]: https://api.slack.com/reference/block-kit/blocks#section //! [modals 🔗]: https://api.slack.com/surfaces/modals //! [messages 🔗]: https://api.slack.com/surfaces/messages //! [home tabs 🔗]: https://api.slack.com/surfaces/tabs //! [block elements 🔗]: https://api.slack.com/reference/messaging/block-elements use std::borrow::Cow; use serde::{Deserialize, Serialize}; #[cfg(feature = "validation")] use validator::Validate; #[cfg(feature = "validation")] use crate::val_helpr::ValidationResult; use crate::{compose::text, elems::BlockElement}; /// # Section Block /// /// _[slack api docs 🔗]_ /// /// Available in surfaces: /// - [modals 🔗] /// - [messages 🔗] /// - [home tabs 🔗] /// /// A `section` is one of the most flexible blocks available - /// it can be used as a simple text block, /// in combination with text fields, /// or side-by-side with any of the available [block elements 🔗] /// /// [slack api docs 🔗]: https://api.slack.com/reference/block-kit/blocks#section /// [modals 🔗]: https://api.slack.com/surfaces/modals /// [messages 🔗]: https://api.slack.com/surfaces/messages /// [home tabs 🔗]: https://api.slack.com/surfaces/tabs /// [block elements 🔗]: https://api.slack.com/reference/messaging/block-elements #[derive(Clone, Debug, Deserialize, Hash, PartialEq, Serialize)] #[cfg_attr(feature = "validation", derive(Validate))] pub struct Section<'a> { #[serde(skip_serializing_if = "Option::is_none")] #[cfg_attr(feature = "validation", validate(custom = "validate::fields"))] fields: Option<Cow<'a, [text::Text]>>, #[serde(skip_serializing_if = "Option::is_none")] #[cfg_attr(feature = "validation", validate(custom = "validate::text"))] text: Option<text::Text>, #[serde(skip_serializing_if = "Option::is_none")] #[cfg_attr(feature = "validation", validate(custom = "validate::block_id"))] block_id: Option<Cow<'a, str>>, /// One of the available [element objects 🔗][element_objects]. /// /// [element_objects]: https://api.slack.com/reference/messaging/block-elements #[serde(skip_serializing_if = "Option::is_none")] accessory: Option<BlockElement<'a>>, } impl<'a> Section<'a> { /// Build a new section block /// /// For example, see `blocks::section::build::SectionBuilder`. pub fn builder() -> build::SectionBuilderInit<'a> { build::SectionBuilderInit::new() } /// Validate that this Section block agrees with Slack's model requirements /// /// # Errors /// - If `fields` contains more than 10 fields /// - If one of `fields` longer than 2000 chars /// - If `text` longer than 3000 chars /// - If `block_id` longer than 255 chars /// /// # Example /// ``` /// use slack_blocks::{blocks, compose::text}; /// /// let long_string = std::iter::repeat(' ').take(256).collect::<String>(); /// /// let block = blocks::Section::builder().text(text::Plain::from("file_id")) /// .block_id(long_string) /// .build(); /// /// assert_eq!(true, matches!(block.validate(), Err(_))); /// ``` #[cfg(feature = "validation")] #[cfg_attr(docsrs, doc(cfg(feature = "validation")))] pub fn validate(&self) -> ValidationResult { Validate::validate(self) } } /// Section block builder pub mod build { use std::marker::PhantomData; use super::*; use crate::build::*; /// Compile-time markers for builder methods #[allow(non_camel_case_types)] pub mod method { /// SectionBuilder.text #[derive(Clone, Copy, Debug)] pub struct text; } /// Initial state for `SectionBuilder` pub type SectionBuilderInit<'a> = SectionBuilder<'a, RequiredMethodNotCalled<method::text>>; /// Build an Section block /// /// Allows you to construct safely, with compile-time checks /// on required setter methods. /// /// # Required Methods /// `SectionBuilder::build()` is only available if these methods have been called: /// - `text` **or** `field(s)`, both may be called. /// /// # Example /// ``` /// use slack_blocks::{blocks::Section, /// elems::Image, /// text, /// text::ToSlackPlaintext}; /// /// let block = /// Section::builder().text("foo".plaintext()) /// .field("bar".plaintext()) /// .field("baz".plaintext()) /// // alternatively: /// .fields(vec!["bar".plaintext(), /// "baz".plaintext()] /// .into_iter() /// .map(text::Text::from) /// ) /// .accessory(Image::builder().image_url("foo.png") /// .alt_text("pic of foo") /// .build()) /// .build(); /// ``` #[derive(Debug)] pub struct SectionBuilder<'a, Text> { accessory: Option<BlockElement<'a>>, text: Option<text::Text>, fields: Option<Vec<text::Text>>, block_id: Option<Cow<'a, str>>, state: PhantomData<Text>, } impl<'a, E> SectionBuilder<'a, E> { /// Create a new SectionBuilder pub fn new() -> Self { Self { accessory: None, text: None, fields: None, block_id: None, state: PhantomData::<_> } } /// Set `accessory` (Optional) pub fn accessory<B>(mut self, acc: B) -> Self where B: Into<BlockElement<'a>> { self.accessory = Some(acc.into()); self } /// Add `text` (**Required: this or `field(s)`**) /// /// The text for the block, in the form of a [text object 🔗]. /// /// Maximum length for the text in this field is 3000 characters. /// /// [text object 🔗]: https://api.slack.com/reference/messaging/composition-objects#text pub fn text<T>(self, text: T) -> SectionBuilder<'a, Set<method::text>> where T: Into<text::Text> { SectionBuilder { accessory: self.accessory, text: Some(text.into()), fields: self.fields, block_id: self.block_id, state: PhantomData::<_> } } /// Set `fields` (**Required: this or `text`**) /// /// A collection of [text objects 🔗]. /// /// Any text objects included with fields will be /// rendered in a compact format that allows for /// 2 columns of side-by-side text. /// /// Maximum number of items is 10. /// /// Maximum length for the text in each item is 2000 characters. /// /// [text objects 🔗]: https://api.slack.com/reference/messaging/composition-objects#text pub fn fields<I>(self, fields: I) -> SectionBuilder<'a, Set<method::text>> where I: IntoIterator<Item = text::Text> { SectionBuilder { accessory: self.accessory, text: self.text, fields: Some(fields.into_iter().collect()), block_id: self.block_id, state: PhantomData::<_> } } /// Append a single field to `fields`. pub fn field<T>(mut self, text: T) -> SectionBuilder<'a, Set<method::text>> where T: Into<text::Text> { let mut fields = self.fields.take().unwrap_or_default(); fields.push(text.into()); self.fields(fields) } /// XML macro children, appends `fields` to the Section. /// /// To set `text`, use the `text` attribute. /// ``` /// use slack_blocks::{blocks::Section, blox::*, text, text::ToSlackPlaintext}; /// /// let xml = blox! { /// <section_block text={"Section".plaintext()}> /// <text kind=plain>"Foo"</text> /// <text kind=plain>"Bar"</text> /// </section_block> /// }; /// /// let equiv = Section::builder().text("Section".plaintext()) /// .field("Foo".plaintext()) /// .field("Bar".plaintext()) /// .build(); /// /// assert_eq!(xml, equiv); /// ``` #[cfg(feature = "blox")] #[cfg_attr(docsrs, doc(cfg(feature = "blox")))] pub fn child<T>(self, text: T) -> SectionBuilder<'a, Set<method::text>> where T: Into<text::Text> { self.field(text) } /// Set `block_id` (Optional) /// /// A string acting as a unique identifier for a block. /// /// You can use this `block_id` when you receive an interaction payload /// to [identify the source of the action 🔗]. /// /// If not specified, a `block_id` will be generated. /// /// Maximum length for this field is 255 characters. /// /// [identify the source of the action 🔗]: https://api.slack.com/interactivity/handling#payloads pub fn block_id<S>(mut self, block_id: S) -> Self where S: Into<Cow<'a, str>> { self.block_id = Some(block_id.into()); self } } impl<'a> SectionBuilder<'a, Set<method::text>> { /// All done building, now give me a darn actions block! /// /// > `no method name 'build' found for struct 'SectionBuilder<...>'`? /// Make sure all required setter methods have been called. See docs for `SectionBuilder`. /// /// ```compile_fail /// use slack_blocks::blocks::Section; /// /// let foo = Section::builder().build(); // Won't compile! /// ``` /// /// ``` /// use slack_blocks::{blocks::Section, /// compose::text::ToSlackPlaintext, /// elems::Image}; /// /// let block = /// Section::builder().text("foo".plaintext()) /// .accessory(Image::builder().image_url("foo.png") /// .alt_text("pic of foo") /// .build()) /// .build(); /// ``` pub fn build(self) -> Section<'a> { Section { text: self.text, fields: self.fields.map(|fs| fs.into()), accessory: self.accessory, block_id: self.block_id } } } } #[cfg(feature = "validation")] mod validate { use super::*; use crate::{compose::text, val_helpr::{below_len, ValidatorResult}}; pub(super) fn text(text: &text::Text) -> ValidatorResult { below_len("Section.text", 3000, text.as_ref()) } pub(super) fn block_id(text: &Cow<str>) -> ValidatorResult { below_len("Section.block_id", 255, text.as_ref()) } pub(super) fn fields(texts: &Cow<[text::Text]>) -> ValidatorResult { below_len("Section.fields", 10, texts.as_ref()).and( texts.iter() .map(|text| { below_len( "Section.fields", 2000, text.as_ref()) }) .collect(), ) } }
true
f56ef80871732ec71d858325f1220465a3f9cbfa
Rust
NotSoClassy/Moon
/src/parser/parser.rs
UTF-8
11,393
3.4375
3
[ "MIT" ]
permissive
use crate::parser::ast::{ Stmt, Expr, UnOp, BinOp, Node }; use crate::lexer::{ Lexer, Token }; use std::process::exit; pub struct Parser { lex: Lexer, line: usize, token: Token, pub nodes: Vec<Node> } impl Parser { pub fn new(code: String, name: String) -> Self { let lexer = Lexer::new(code, name); Parser { token: lexer.token, line: 1, lex: lexer, nodes: Vec::new() } } pub fn parse(&mut self) -> Result<(), String> { self.next(); if self.token == Token::Eof { return Ok(()) } while self.token != Token::Eof { let stmt = self.stmt()?; self.nodes.push(self.to_node(stmt)); } Ok(()) } fn to_node(&self, stmt: Stmt) -> Node { Node { line: self.line, stmt } } #[inline] fn stmt(&mut self) -> Result<Stmt, String> { self._stmt(true) } fn _stmt(&mut self, consume_semi: bool) -> Result<Stmt, String> { macro_rules! stmt { ($i:expr) => { { self.line = self.lex.line; let res = $i; if consume_semi { self.test_next(Token::Semi); } return Ok(res) } }; } match self.token { Token::LeftBrace => stmt!(self.block_stmt()?), Token::Return => stmt!(self.return_stmt()?), Token::While => stmt!(self.while_stmt()?), Token::For => stmt!(self.for_stmt()?), Token::Let => stmt!(self.let_stmt()?), Token::If => stmt!(self.if_stmt()?), Token::Fn => stmt!(self.fn_stmt()?), _ => stmt!(Stmt::Expr(self.expr()?)) } } fn let_stmt(&mut self) -> Result<Stmt, String> { self.expect(Token::Name)?; let name = self.lex.buf.clone(); self.next(); let value = if self.test_next(Token::Equal) { self.expr()? } else { Expr::Nil }; Ok(Stmt::Let(name, value)) } fn for_stmt(&mut self) -> Result<Stmt, String> { self.expect_next(Token::LeftParen)?; let tkn = self.token2str(self.token); let pre = self._stmt(false)?; match pre { Stmt::Let(..) | Stmt::Expr(..) => {} _ => return Err(self.lex.error(format!("unexpected statement near '{}'", tkn).as_str())) } self.check_next(Token::Semi)?; let cond = self.expr()?; self.check_next(Token::Semi)?; let post = self.expr()?; self.check_next(Token::RightParen)?; let block = self.block()?; Ok(Stmt::For(Box::new(self.to_node(pre)), cond, post, Box::new(block))) } fn if_stmt(&mut self) -> Result<Stmt, String> { self.expect_next(Token::LeftParen)?; let cond = self.expr()?; self.check_next(Token::RightParen)?; let body = self.block()?; let mut else_block: Option<Node> = None; if self.test_next(Token::Else) { let stmt = self.block()?; else_block = Some(stmt); } Ok(Stmt::If(cond, Box::new((body, else_block)))) } fn fn_stmt(&mut self) -> Result<Stmt, String> { self.expect(Token::Name)?; let name = self.lex.buf.clone(); self.expect_next(Token::LeftParen)?; let params = self.name_list(Token::RightParen)?; let body = self.block_stmt()?; Ok(Stmt::Fn(name, params, Box::new(self.to_node(body)))) } fn return_stmt(&mut self) -> Result<Stmt, String> { self.next(); let val = if self.token == Token::Semi { Expr::Nil } else { self.expr()? }; Ok(Stmt::Return(val)) } fn while_stmt(&mut self) -> Result<Stmt, String> { self.expect_next(Token::LeftParen)?; let cond = self.expr()?; self.check_next(Token::RightParen)?; let body = self.block()?; Ok(Stmt::While(cond, Box::new(body))) } fn block_stmt(&mut self) -> Result<Stmt, String> { self.check_next(Token::LeftBrace)?; let mut body = Vec::new(); while self.token != Token::RightBrace && self.token != Token::Eof { let stmt = self.stmt()?; body.push(self.to_node(stmt)); } self.check_next(Token::RightBrace)?; Ok(Stmt::Block(body)) } fn block(&mut self) -> Result<Node, String> { let stmt = self.stmt()?; let stmt = match stmt { Stmt::Block(..) => stmt, _ => Stmt::Block(vec![self.to_node(stmt)]) }; Ok(self.to_node(stmt)) } fn prefix_expr(&mut self) -> Result<Expr, String> { match self.token { Token::LeftParen => { self.next(); let exp = self.expr(); self.check(Token::RightParen)?; exp } Token::Name => Ok(Expr::Name(self.lex.buf.clone())), _ => Err(self.error("unexpected token", self.token)) } } fn primary_expr(&mut self) -> Result<Expr, String> { let mut exp = self.prefix_expr()?; self.next(); loop { match self.token { Token::LeftSquare => { self.next(); exp = self.index(exp)?; } Token::Dot => { self.next(); exp = self.dot_index(exp)?; } Token::LeftParen => { self.next(); exp = self.call(exp)?; } _ => return Ok(exp) } } } fn simple_expr(&mut self) -> Result<Expr, String> { macro_rules! simple { ($t:ident, $v:expr) => { { let v = $v; self.next(); Ok(Expr::$t(v)) } }; } match self.token { Token::True | Token::False => simple!(Bool, self.token == Token::True), Token::String => simple!(String, self.lex.buf.clone()), Token::Number => simple!(Number, self.lex.buf.parse().unwrap()), // this shouldn't error Token::Line => { self.next(); self.anon_func() }, Token::Nil => { self.next(); Ok(Expr::Nil) }, Token::LeftBrace => { self.next(); self.table() } Token::LeftSquare => { self.next(); self.array() } _ => self.primary_expr() } } fn sub_expr(&mut self, priority: u8) -> Result<Expr, String> { let unop = self.get_unop(); let mut left = if let Some(op) = unop { self.next(); Expr::Unary(op, self.simple_expr()?.boxed()) } else { self.simple_expr()? }; while let Some(op) = self.get_binop() { if op.priority() > priority { self.next(); let right = self.sub_expr(op.priority())?; left = Expr::Binary(left.boxed(), op, right.boxed()); self.check_bin_exp(left.clone())? } else { break } } Ok(left) } #[inline] pub fn expr(&mut self) -> Result<Expr, String> { self.sub_expr(0) } fn anon_func(&mut self) -> Result<Expr, String> { let params = self.name_list(Token::Line)?; let body = self.block()?; Ok(Expr::AnonFn(params, Box::new(body))) } fn index(&mut self, exp: Expr) -> Result<Expr, String> { let idx = self.expr()?; self.check_next(Token::RightSquare)?; Ok(Expr::Index(exp.boxed(), idx.boxed())) } fn dot_index(&mut self, exp: Expr) -> Result<Expr, String> { let idx = match self.token { Token::Number => { self.expr() } Token::Name => { let name = self.lex.buf.clone(); self.next(); Ok(Expr::String(name)) } _ => Err(self.error("unexpected token", self.token)) }?; Ok(Expr::Index(exp.boxed(), idx.boxed())) } fn pair(&mut self) -> Result<(Expr, Expr), String> { let key = if self.test(Token::Name) { let name = self.lex.buf.clone(); self.next(); Expr::String(name) } else { self.check_next(Token::LeftSquare)?; let exp = self.expr()?; self.check_next(Token::RightSquare)?; exp }; self.check_next(Token::Colon)?; Ok((key, self.expr()?)) } fn table(&mut self) -> Result<Expr, String> { let mut pairs = Vec::new(); if self.token != Token::RightBrace { let pair = self.pair()?; pairs.push(pair); while self.token == Token::Comma { self.next(); if self.token == Token::RightBrace { break } let pair = self.pair()?; pairs.push(pair); } } self.check_next(Token::RightBrace)?; Ok(Expr::Table(pairs)) } fn array(&mut self) -> Result<Expr, String> { let elems = self.exp_list(Token::RightSquare)?; Ok(Expr::Array(elems)) } fn call(&mut self, func: Expr) -> Result<Expr, String> { let args = self.exp_list(Token::RightParen)?; Ok(Expr::Call(func.boxed(), args)) } fn name_list(&mut self, end: Token) -> Result<Vec<String>, String> { let mut names = Vec::new(); if self.token != end { loop { self.check(Token::Name)?; names.push(self.lex.buf.clone()); self.next(); if self.token != Token::Comma { break } self.next(); } } self.check_next(end)?; Ok(names) } fn exp_list(&mut self, end: Token) -> Result<Vec<Expr>, String> { let mut exps = Vec::new(); if self.token != end { exps.push(self.expr()?); while self.token == Token::Comma { self.next(); exps.push(self.expr()?); } } self.check_next(end)?; Ok(exps) } fn get_unop(&self) -> Option<UnOp> { match self.token { Token::Bang => Some(UnOp::Not), Token::Dash => Some(UnOp::Neg), _ => None } } fn get_binop(&self) -> Option<BinOp> { match self.token { Token::Neq => Some(BinOp::Neq), Token::Eq => Some(BinOp::Eq), Token::Ge => Some(BinOp::Ge), Token::Gt => Some(BinOp::Gt), Token::Le => Some(BinOp::Le), Token::Lt => Some(BinOp::Lt), Token::Plus => Some(BinOp::Add), Token::Dash => Some(BinOp::Sub), Token::Star => Some(BinOp::Mul), Token::Slash => Some(BinOp::Div), Token::Percent => Some(BinOp::Mod), Token::Equal => Some(BinOp::Assign), Token::And => Some(BinOp::And), Token::Or => Some(BinOp::Or), _ => None } } // util functions fn check_bin_exp(&self, e: Expr) -> Result<(), String> { if let Expr::Binary(lhs, op, _rhs) = e { match op { BinOp::Assign => { if !matches!(*lhs, Expr::Name(..) | Expr::Index(..)) { return Err(self.error("unexpected token", Token::Equal)) } } _ => {} } } Ok(()) } fn test(&mut self, token: Token) -> bool { return self.token == token } fn test_next(&mut self, token: Token) -> bool { if self.token == token { self.next(); return true } false } fn check(&self, token: Token) -> Result<(), String> { if self.token != token { return Err(self.error_expected(token)) } Ok(()) } fn check_next(&mut self, token: Token) -> Result<(), String> { let res = self.check(token); if res.is_ok() { self.next() } res } fn expect(&mut self, token: Token) -> Result<(), String> { self.next(); self.check(token) } fn expect_next(&mut self, token: Token) -> Result<(), String> { self.next(); self.check_next(token) } fn error_expected(&self, expected: Token) -> String { self.error(&format!("expected '{}'", self.token2str(expected)), self.token) } fn next(&mut self) { let res = self.lex.lex_next(); if let Err(e) = res { eprintln!("{}", e); drop(self); exit(1); } self.token = self.lex.token; } fn token2str(&self, token: Token) -> String { self.lex.token2str(token) } fn error(&self, err: &str, token: Token) -> String { self.lex.error_near(err, token) } }
true
6dbead483d166e1bbd51fd2f4400f9a7a867fa1d
Rust
jfsulliv-zz/thrtest
/src/functional/park.rs
UTF-8
2,987
3.65625
4
[]
no_license
/// Functional tests for thread parking/unparking. /// /// # Tested Assertions: /// * thread::park() pauses execution of a thread. /// * thread::Thread::unpark() unpauses execution of a thread. #[cfg(all(test))] mod tests { use std::sync::{Arc,Mutex}; use std::thread; use std::time::{Duration,Instant}; /// Verifies that threads are paused by park_timeout. #[test] fn thread_park() { // The minimum time the test may take to complete. const TIMEOUT_THRESHOLD_S : u64 = 4; // The time to park the thread. const TIMEOUT_S : u64 = 5; let start_time = Instant::now(); let thr = thread::spawn(move || { thread::park_timeout(Duration::from_secs(TIMEOUT_S)); }); thr.join().unwrap(); // False positives are possible in this assertion if the test // actually took a long time. This is very unlikely. // // False negatives are possible if park_timeout completes before // its timeout is expired (which is possible since park can // spuriously return, but also not likely). assert!(start_time.elapsed() >= Duration::from_secs(TIMEOUT_THRESHOLD_S)); } /// Verifies that threads are re-started by unpark. #[test] fn thread_unpark() { let mtx = Arc::new(Mutex::new(0)); let outer_thr = thread::current(); // The maximum time the test may take to complete. const TIMEOUT_THRESHOLD_S : u64 = 8; // The timer that we assign to the park so the test doesn't hang // if the unpark operation fails. const TIMEOUT_S : u64 = 10; let cloned_mtx = mtx.clone(); let thr = thread::spawn(move || { // If the unpark fails, we will hang on acquiring the // lock. outer_thr.unpark(); { let mut v = cloned_mtx.lock().unwrap(); *v = 1; } }); // This thread ensures that the test does not take too long. // If the run-time exceeds the threshold, there are one of two // possibilities: // // 1) The call to unpark() did not actually start the main // thread again, i.e. unpark() is broken. // 2) The test actually took a long time. // // The second is possible but unlikely. let start_time = Instant::now(); let timer_thr = thread::spawn(move || { thr.join().unwrap(); if start_time.elapsed() > Duration::from_secs(TIMEOUT_THRESHOLD_S) { panic!("The thread probably hung.") } else { 0 } }); { let _v = mtx.lock().unwrap(); thread::park_timeout(Duration::from_secs(TIMEOUT_S)); } timer_thr.join().unwrap(); { let v = mtx.lock().unwrap(); assert_eq!(*v, 1); } } }
true
c9d7b5410af914224e010a4141c78e0b7b692038
Rust
StragaSevera/aoc2018
/src/bin/02b/main.rs
UTF-8
1,574
3.25
3
[]
no_license
use std::iter::FromIterator; fn main() { let input = aoc2018::read_file("src/bin/02b/input.txt"); let result = find_correct_id(input); println!("{}", result) } fn find_correct_id(input: impl Iterator<Item=String>) -> String { let mut strings: Vec<Vec<char>> = Vec::new(); let input = input.map(|s| s.chars().collect::<Vec<_>>()); let mut diff_idx: Option<usize> = None; let mut result: Option<Vec<char>> = None; 'outer: for input_line in input { if !strings.is_empty() { for string in &strings { for (i, (a, b)) in input_line.iter().zip(string).enumerate() { if *a != *b { match diff_idx { None => diff_idx = Some(i), Some(_) => { diff_idx = None; break; } } } } if diff_idx.is_some() { result = Some(input_line); break 'outer; } } } strings.push(input_line) } let mut result = result.unwrap(); result.remove(diff_idx.unwrap()); String::from_iter(result) } #[cfg(test)] mod tests { use super::*; const INPUT: &str = "abcde fghij klmno pqrst fguij axcye wvxyz"; #[test] fn find_correct_id_test() { let result = find_correct_id(INPUT.split('\n').map(String::from)); assert_eq!(result, "fgij") } }
true
e920d062134faa1c903cebc32ce4d46f8b4375a8
Rust
dennisss/dacha
/pkg/container/src/init.rs
UTF-8
6,879
2.796875
3
[ "Apache-2.0" ]
permissive
use nix::sys::signal::Signal; use nix::sys::signal::{sigaction, SaFlags, SigAction, SigHandler, SigSet}; use sys::{sigprocmask, sigsuspend, Errno, SignalSet, SigprocmaskHow}; static mut RECEIVED_SIGNAL: Option<sys::c_int> = None; pub struct MainProcessOptions { /// If true, start the child process in a new process group. pub use_setsid: bool, /// Extra flags to use when calling clone() to start the child process. /// /// MUST NOT include CLONE_THREAD or CLONE_VM pub clone_flags: sys::CloneFlags, /// If true, if we get two SIGINTs while waiting for a child process, the /// second SIGINT will be increased to a SIGKILL before being forwarded to /// the client. pub raise_second_sigint: bool, } /// A primary singleton subprocess which is wrapped by the current caller /// process. Signals, ttys, etc. are forwarded to this subprocess and when the /// child exits, so will the parent. /// /// NOTE: This should only be used in a single threaded process with no other /// signal dependencies. Additionally there should NEVER be more than one /// instance of this in a single process. pub struct MainProcess { pid: sys::pid_t, options: MainProcessOptions, } impl MainProcess { /// Starts a child process running the given code. pub fn start<F: FnMut() -> sys::ExitCode>( options: MainProcessOptions, child_process: F, ) -> Result<Self, Errno> { unsafe { Self::start_impl(options, child_process) } } unsafe fn start_impl<F: FnMut() -> sys::ExitCode>( options: MainProcessOptions, mut child_process: F, ) -> Result<Self, Errno> { /* If using use_setsid(), TIOCNOTTY to detach stdin from the parent -> Must ignore SIGHUP and SIGCONT (if we are a session leader getsid(0) == getpid()) then in the child use TIOCSCTTY to attach it ^ Errors should be ok. */ // Detach the stdin tty device. // TODO: Only do if isatty() // if options.use_setsid { // sys::ioctl(0, sys::bindings::TIOCNOTTY, 0)?; // } // Block all signals in the parent process so that we don't notice signals until // we set up signal handlers for it (to avoid race conditions like the child // process exiting before we are ready to monitor it). sigprocmask(SigprocmaskHow::SIG_BLOCK, Some(&SignalSet::all()), None)?; let pid = sys::CloneArgs::new() .flags(options.clone_flags) .sigchld() .spawn_process(|| { if let Err(e) = Self::prepare_child(&options) { eprintln!("Failed to initialize child: {}", e); return 1; } child_process() })?; Ok(Self { options, pid }) } unsafe fn prepare_child(options: &MainProcessOptions) -> Result<(), Errno> { // Unblock everything we blocked in the parent. sigprocmask(SigprocmaskHow::SIG_UNBLOCK, Some(&SignalSet::all()), None)?; // sys::ioctl(0, sys::bindings::TIOCSCTTY, 0)?; if options.use_setsid { sys::setsid()?; } Ok(()) } pub fn pid(&self) -> sys::pid_t { self.pid } /// Waits until the child process exits. /// /// - Any signals received by the init process will be forwarded to the /// child. /// - Any subprocesses other than the main child will also be reaped (e.g. /// if the current process has pid == 1). /// - Once the main child exits, the init process exits with the same exit /// mode. /// /// NOTE: This function should normally never return unless there is an /// error. pub fn wait(self) -> Result<(), Errno> { unsafe { self.wait_impl() } } unsafe fn wait_impl(&self) -> Result<(), Errno> { // Configure a handler for all signals. // Signal numbers 1 to 31 as normal signals (there may be holes though). Above // that are realtime signals. { let action = SigAction::new( SigHandler::Handler(handle_signal), SaFlags::empty(), SigSet::all(), ); let mut some_succeeded = false; for signal_num in 1..=31 { some_succeeded |= sigaction(core::mem::transmute(signal_num), &action).is_ok(); } // Some may fail as not all systems have all 31 syscall numbers defined. if !some_succeeded { return Err(Errno::EIO); } } let mut got_sigint = false; // Wait for signals to occur. loop { // Unmask all signals while waiting. sys::sigsuspend(&SignalSet::empty()); let mut signal = match RECEIVED_SIGNAL.take() { Some(num) => sys::Signal::from_raw(num as u32), None => continue, }; if signal == sys::Signal::SIGCHLD { loop { let v = sys::waitpid(-1, sys::WaitOptions::WNOHANG)?; match v { sys::WaitStatus::Exited { pid, status } => { if pid == self.pid { sys::exit(status); } } sys::WaitStatus::Signaled { pid, signal, core_dumped, } => { if pid == self.pid { // TODO: Verify this shows up correctly in waitpid of the parent // process. sys::exit(128 + signal.to_raw() as u8); } } sys::WaitStatus::NoStatus => { break; } _ => {} } } } else { if signal == sys::Signal::SIGINT { if got_sigint { println!("Killing..."); signal = sys::Signal::SIGKILL; } got_sigint = true; } // Forward signals sys::kill( if self.options.use_setsid { -self.pid } else { self.pid }, signal, )?; } } Ok(()) } } extern "C" fn handle_signal(signal: sys::c_int) { unsafe { assert!(RECEIVED_SIGNAL.is_none()); RECEIVED_SIGNAL = Some(signal); } }
true
ecac16002e82ed90d663afbb57e8fa079ef1147c
Rust
koba-e964/calc-rust
/src/ast.rs
UTF-8
1,640
3.140625
3
[]
no_license
// AST #[derive(PartialEq, Clone, Debug)] pub enum AST { Num(i64), Str(String), Var(String), OpNode(Op, Box<AST>, Box<AST>), IfNode(Box<AST>, Box<AST>, Box<AST>), // If the first evaluates to non-zero, return the second. Otherwise, return the third. LetEx(String, Box<AST>, Box<AST>), FunApp(String, Vec<AST>), } #[derive(Clone, Debug)] pub struct FunDec(pub String, pub Vec<(String, Type)>, pub Type, pub AST); #[derive(PartialEq, Clone, Copy, Debug)] pub enum Op { Add, Sub, Mul, Div, } #[derive(PartialEq, Clone, Debug)] pub enum Value { VNum(i64), VStr(String), } /* * Copy trait cannot be implemented because we might add some recursive constructors. */ #[derive(PartialEq, Clone, Debug)] pub enum Type { Int, Str, } #[derive(PartialEq, Clone, Debug)] pub enum TypedAST { Num(i64), Str(String), Var(String, Type), OpNode(Op, Type, Box<TypedAST>, Box<TypedAST>), IfNode(Box<TypedAST>, Type, Box<TypedAST>, Box<TypedAST>), LetEx(String, Type, Box<TypedAST>, Box<TypedAST>), FunApp(String, Vec<Type>, Type, Vec<TypedAST>), // name, argtype, rettype, arg } pub type TypedFunDec = (String, Vec<(String, Type)>, Type, TypedAST); pub fn ty_of_ast(tast: &TypedAST) -> Type { match *tast { TypedAST::Num(_) => Type::Int, TypedAST::Str(_) => Type::Str, TypedAST::Var(_, ref ty) => ty.clone(), TypedAST::OpNode(_, ref ty, _, _) => ty.clone(), TypedAST::IfNode(_, ref ty, _, _) => ty.clone(), TypedAST::LetEx(_, ref ty, _, _) => ty.clone(), TypedAST::FunApp(_, _, ref ty, _) => ty.clone(), } }
true
8a9f1e8f24dae6293802939a62168254160ba382
Rust
djmittens/learn-rust
/cargo-hal/learn-vulkan/src/main.rs
UTF-8
2,576
2.625
3
[]
no_license
use vulkano::buffer::{BufferUsage, CpuAccessibleBuffer}; use vulkano::command_buffer::{AutoCommandBufferBuilder, CommandBuffer}; use vulkano::device::{Device, DeviceExtensions, Features}; use vulkano::instance::{Instance, InstanceExtensions, PhysicalDevice}; use vulkano::sync::GpuFuture; fn main() { println!("Hello, world!"); let instance = Instance::new(None, &InstanceExtensions::none(), None).expect("Failed to create instance"); let physical = PhysicalDevice::enumerate(&instance) .next() .expect("no device available"); for family in physical.queue_families() { println!( "Found a queue family with {:?} queue(s)", family.queues_count() ); } let queue_family = physical .queue_families() .find(|&q| q.supports_graphics()) .expect("couldn't find a graphical queue family"); let (device, mut queues) = { Device::new( physical, &Features::none(), &DeviceExtensions::none(), [(queue_family, 0.5)].iter().cloned(), ) .expect("failed to create device") }; let queue = queues.next().unwrap(); // let data = 12; // let buffer = CpuAccessibleBuffer::from_data(device.clone(), BufferUsage::all(), data) // .expect"failed to create buffer"); let source_content = 0..64; let source = CpuAccessibleBuffer::from_iter(device.clone(), BufferUsage::all(), source_content) .expect("failed to create buffer"); let dest_content = (0..64).map(|_| 0); let dest = CpuAccessibleBuffer::from_iter(device.clone(), BufferUsage::all(), dest_content) .expect("failed to create buffer"); let command_buffer = AutoCommandBufferBuilder::new(device.clone(), queue.family()) .map_err(|_| "dammit cant create this stuff") .and_then(|x| { x.copy_buffer(source.clone(), dest.clone()) .map_err(|_| "cant copy to buffer?") }) .and_then(|x| x.build().map_err(|_| "whuuut")) .unwrap(); let finished = command_buffer.execute(queue.clone()).unwrap(); finished .then_signal_fence_and_flush() .and_then(|x| x.wait(None)) .unwrap(); let source_content = source.read().unwrap(); let dest_content = dest.read().unwrap(); assert_eq!(&*source_content, &*dest_content); let data_iter = 0..65536; let data_buffer = CpuAccessibleBuffer::from_iter(device.clone(), BufferUsage::all(), data_iter) .expect("Failed to create buffer"); }
true
395b3c47c1495dc053cca19fe02358e008f4d980
Rust
wmmxk/OOP_Rust
/bugs/enum_include_structure/ownership/main.rs
UTF-8
564
3.265625
3
[]
no_license
// source: https://github.com/rust-lang/rust/issues/40666 #[derive(Debug)] enum myenum { Number, Character {x : String, y: String}, } fn main() { let aenum = myenum::Character{x:String::from("hello"),y: String::from("world")}; match aenum { myenum::Character { ref x, ref y} => { println!("The value of x: {} ", *x ) }, _ => {println!("Others ")}, } match aenum { myenum::Character {x, y} => { println!("The value of x: {} ",x ) }, _ => {println!("Others ")}, } }
true
9d71bc18a0fbafcef108f37103e054480e224585
Rust
superoles/rescue_block_cipher
/rescue-poseidon/src/common/domain_strategy.rs
UTF-8
4,214
3.390625
3
[ "Apache-2.0", "MIT" ]
permissive
use franklin_crypto::bellman::{Engine, Field, PrimeField}; /// Padding prevents trivial collisions. /// Each hash function nearly uses same padding strategies. /// The only difference is that Rescue Prime requires no padding for /// fixed length input. Rescue and Poseidon require same padding rule /// for variable length input. #[derive(Clone)] pub enum DomainStrategy { // The capacity value is length x (2^64 ) + (o − 1) // where o the output length. The padding consists of the field elements being 0. FixedLength, /// Padding is necessary for variable-length inputs, even if the input is already /// a multiple of the rate in length. // The capacity value is 2^64 + (o − 1) where o the output length. // The padding consists of one field element being 1, // and the remaining elements being 0 VariableLength, // This is a variation of fixed length strategy. Only difference is value of capacity // element is being set to input length. CustomFixedLength, CustomVariableLength, // No specialization and padding rule. NoPadding, } impl DomainStrategy { /// Computes capacity value for specialization and domain seperation. pub(crate) fn compute_capacity<E: Engine>( &self, input_len: usize, rate: usize, ) -> Option<E::Fr> { let mut repr = <E::Fr as PrimeField>::Repr::default(); repr.as_mut()[1] = 1u64; // 2^64 corresponds second le limb let mut el = E::Fr::from_repr(repr).unwrap(); let mut out_repr = <E::Fr as PrimeField>::Repr::default(); out_repr.as_mut()[0] = (rate - 1) as u64; let out_el = E::Fr::from_repr(repr).unwrap(); match &self { Self::FixedLength => { // length * 2^64 + (o-1) // since we always use output length equals rate let length_as_fe = E::Fr::from_str(&input_len.to_string()).unwrap(); el.mul_assign(&length_as_fe); el.add_assign(&out_el); Some(el) } Self::VariableLength => { // 2^64 + (o-1) el.add_assign(&out_el); Some(el) } Self::CustomFixedLength => { let mut repr = <E::Fr as PrimeField>::Repr::default(); repr.as_mut()[0] = input_len as u64; E::Fr::from_repr(repr).ok() } Self::CustomVariableLength => None, _ => unimplemented!("unknown domain strategy"), } } /// Computes values for padding. pub(crate) fn generate_padding_values<E: Engine>( &self, input_len: usize, rate: usize ) -> Vec<E::Fr> { assert!(input_len != 0, "empty input"); if input_len % rate == 0 { // input doesn't need padding return vec![]; } let mut values_for_padding = vec![]; match self { Self::FixedLength => { values_for_padding.resize(rate - input_len, E::Fr::zero()); values_for_padding } Self::VariableLength => { values_for_padding.push(E::Fr::one()); while (values_for_padding.len() + input_len) % rate != 0 { values_for_padding.push(E::Fr::zero()); } values_for_padding } Self::CustomFixedLength => { let mut cycle = input_len / rate; if input_len % rate != 0 { cycle += 1; } let padding_len = cycle * rate - input_len; for _ in 0..padding_len { values_for_padding.push(E::Fr::one()); } values_for_padding } Self::CustomVariableLength => { values_for_padding.push(E::Fr::one()); while (values_for_padding.len() + input_len) % rate != 0 { values_for_padding.push(E::Fr::one()); } values_for_padding } _ => unimplemented!("unknown domain strategy"), } } }
true
9632675940ce55957165f0d620f9d4b150a49404
Rust
modulus-os/kernel
/src/io/pio/mod.rs
UTF-8
1,062
2.625
3
[ "Apache-2.0" ]
permissive
#[cfg_attr(rustfmt, rustfmt_skip)] pub fn outb(port: u16, value: u8) { unsafe{ asm!("outb %al, %dx" : : "{dx}"(port), "{al}"(value) : : "volatile"); } } #[cfg_attr(rustfmt, rustfmt_skip)] pub fn outw(port: u16, value: u16) { unsafe{ asm!("outw %ax, %dx" : : "{dx}"(port), "{ax}"(value) : : "volatile"); } } #[cfg_attr(rustfmt, rustfmt_skip)] pub fn outl(port: u16, value: u32) { unsafe{ asm!("outl %eax, %dx" : : "{dx}"(port), "{eax}"(value) : : "volatile"); } } #[cfg_attr(rustfmt, rustfmt_skip)] pub fn inb(port: u16) -> u8{ unsafe{ let res: u8; asm!("inb %dx, %al" : "={al}"(res) : "{dx}"(port) : : "volatile"); res } } #[cfg_attr(rustfmt, rustfmt_skip)] pub fn inw(port: u16) -> u16{ unsafe{ let res: u16; asm!("inw %dx, %ax" : "={ax}"(res) : "{dx}"(port) : : "volatile"); res } } #[cfg_attr(rustfmt, rustfmt_skip)] pub fn inl(port: u16) -> u32{ unsafe{ let res: u32; asm!("inl %dx, %eax" : "={eax}"(res) : "{dx}"(port) : : "volatile"); res } }
true
0db22943b51b5682cff916461c03ab16c46b4631
Rust
age-rs/fast_image_resize
/src/alpha/avx2/mul.rs
UTF-8
2,810
2.515625
3
[ "MIT", "Apache-2.0" ]
permissive
use std::arch::x86_64::*; use crate::alpha::native; use crate::image_view::{TypedImageView, TypedImageViewMut}; use crate::pixels::U8x4; use crate::simd_utils; pub(crate) fn multiply_alpha_avx2( src_image: TypedImageView<U8x4>, mut dst_image: TypedImageViewMut<U8x4>, ) { let width = src_image.width().get() as usize; let src_rows = src_image.iter_rows(0, src_image.height().get()); let dst_rows = dst_image.iter_rows_mut(); for (src_row, dst_row) in src_rows.zip(dst_rows) { unsafe { multiply_alpha_row_avx2(src_row, dst_row, width); } } } pub(crate) fn multiply_alpha_inplace_avx2(mut image: TypedImageViewMut<U8x4>) { let width = image.width().get() as usize; for dst_row in image.iter_rows_mut() { unsafe { let src_row = std::slice::from_raw_parts(dst_row.as_ptr(), dst_row.len()); multiply_alpha_row_avx2(src_row, dst_row, width); } } } /// https://github.com/Wizermil/premultiply_alpha/blob/master/premultiply_alpha/premultiply_alpha.hpp#L232 #[target_feature(enable = "avx2")] unsafe fn multiply_alpha_row_avx2(src_row: &[u32], dst_row: &mut [u32], width: usize) { let mask_alpha_color_odd_255 = _mm256_set1_epi32(0xff000000u32 as i32); let div_255 = _mm256_set1_epi16(0x8081u16 as i16); #[rustfmt::skip] let mask_shuffle_alpha = _mm256_set_epi8( 15, -1, 15, -1, 11, -1, 11, -1, 7, -1, 7, -1, 3, -1, 3, -1, 15, -1, 15, -1, 11, -1, 11, -1, 7, -1, 7, -1, 3, -1, 3, -1, ); #[rustfmt::skip] let mask_shuffle_color_odd = _mm256_set_epi8( -1, -1, 13, -1, -1, -1, 9, -1, -1, -1, 5, -1, -1, -1, 1, -1, -1, -1, 13, -1, -1, -1, 9, -1, -1, -1, 5, -1, -1, -1, 1, -1, ); let mut x: usize = 0; while x < width.saturating_sub(7) { let mut color = simd_utils::loadu_si256(src_row, x); let alpha = _mm256_shuffle_epi8(color, mask_shuffle_alpha); let mut color_even = _mm256_slli_epi16::<8>(color); let mut color_odd = _mm256_shuffle_epi8(color, mask_shuffle_color_odd); color_odd = _mm256_or_si256(color_odd, mask_alpha_color_odd_255); color_odd = _mm256_mulhi_epu16(color_odd, alpha); color_even = _mm256_mulhi_epu16(color_even, alpha); color_odd = _mm256_srli_epi16::<7>(_mm256_mulhi_epu16(color_odd, div_255)); color_even = _mm256_srli_epi16::<7>(_mm256_mulhi_epu16(color_even, div_255)); color = _mm256_or_si256(color_even, _mm256_slli_epi16::<8>(color_odd)); let dst_ptr = dst_row.get_unchecked_mut(x..).as_mut_ptr() as *mut __m256i; _mm256_storeu_si256(dst_ptr, color); x += 8; } let src_tail = &src_row[x..]; let dst_tail = &mut dst_row[x..]; native::multiply_alpha_row_native(src_tail, dst_tail); }
true
da1a90d1bcb410dcc1bd68c442bf6a9340267409
Rust
jonasvandervennet/advent-of-code-2020
/src/day18.rs
UTF-8
5,706
3.703125
4
[ "MIT" ]
permissive
use crate::util::{print_part_1, print_part_2}; use std::collections::VecDeque; use std::fs::read_to_string; use std::time::Instant; #[derive(Clone, Copy)] struct State { lhs: usize, op: char, initialised: bool, parantheses_state: bool, // reason for push } impl State { fn new(by_parentheses: bool) -> Self { State { initialised: false, parantheses_state: by_parentheses, lhs: 0, op: '+', } } fn do_op(&mut self, rhs: usize) { if !self.initialised { self.initialised = true; self.lhs = rhs; return; } match self.op { '+' => { self.lhs += rhs; } '*' => { self.lhs *= rhs; } _ => { panic!("What is happening?"); } } } fn value(&self) -> usize { self.lhs } } fn evaluate_expression(expr: &str, part: usize) -> usize { let mut states: VecDeque<State> = VecDeque::new(); let mut curr_state = State::new(false); // put everything between a set of parentheses let expr = format!("({})", expr); for c in expr.chars() { match c { ' ' => { continue; } '+' => { curr_state.op = c; } '*' => { curr_state.op = c; if part == 2 { // addition has precedence over muiltiplication // so hold off on performing the mult for now states.push_back(curr_state); curr_state = State::new(false); } } '(' => { states.push_back(curr_state); curr_state = State::new(true); } ')' => loop { // reduce for all values inside the same parentheses let rhs = curr_state.value(); let parentheses_state = curr_state.parantheses_state; curr_state = states.pop_back().unwrap(); curr_state.do_op(rhs); if parentheses_state { break; } }, _ => { let digit = c.to_digit(10).unwrap() as usize; curr_state.do_op(digit); } } } curr_state.value() as usize } fn sum_expressions(input: &str, part: usize) -> usize { input .lines() .map(|line| evaluate_expression(line, part)) .sum() } pub fn main() { let input = read_to_string("inputs/day18.txt").expect("Input not found.."); // PART 1 let start = Instant::now(); let known_answer = "1451467526514"; let part_1: usize = sum_expressions(&input, 1); let duration = start.elapsed(); print_part_1(&part_1.to_string(), &known_answer, duration); // PART 2 let start = Instant::now(); let known_answer = "224973686321527"; let part_2: usize = sum_expressions(&input, 2); let duration = start.elapsed(); print_part_2(&part_2.to_string(), &known_answer, duration); } #[cfg(test)] mod tests { use super::*; #[test] fn test_example_1() { let input: &str = "1 + 2 * 3 + 4 * 5 + 6"; let answer = evaluate_expression(&input, 1); assert_eq!(answer, 71); } #[test] fn test_example_2() { let input: &str = "1 + (2 * 3) + (4 * (5 + 6))"; let answer = evaluate_expression(&input, 1); assert_eq!(answer, 51); } #[test] fn test_example_3() { let input: &str = "2 * 3 + (4 * 5)"; let answer = evaluate_expression(&input, 1); assert_eq!(answer, 26); } #[test] fn test_example_4() { let input: &str = "5 + (8 * 3 + 9 + 3 * 4 * 3)"; let answer = evaluate_expression(&input, 1); assert_eq!(answer, 437); } #[test] fn test_example_5() { let input: &str = "5 * 9 * (7 * 3 * 3 + 9 * 3 + (8 + 6 * 4))"; let answer = evaluate_expression(&input, 1); assert_eq!(answer, 12240); } #[test] fn test_example_6() { let input: &str = "((2 + 4 * 9) * (6 + 9 * 8 + 6) + 6) + 2 + 4 * 2"; let answer = evaluate_expression(&input, 1); assert_eq!(answer, 13632); } #[test] fn test_example_2_0() { let input: &str = "4 * 9 + 3"; let answer = evaluate_expression(&input, 2); assert_eq!(answer, 48); } #[test] fn test_example_2_1() { let input: &str = "1 + 2 * 3 + 4 * 5 + 6"; let answer = evaluate_expression(&input, 2); assert_eq!(answer, 231); } #[test] fn test_example_2_2() { let input: &str = "1 + (2 * 3) + (4 * (5 + 6))"; let answer = evaluate_expression(&input, 2); assert_eq!(answer, 51); } #[test] fn test_example_2_3() { let input: &str = "2 * 3 + (4 * 5)"; let answer = evaluate_expression(&input, 2); assert_eq!(answer, 46); } #[test] fn test_example_2_4() { let input: &str = "5 + (8 * 3 + 9 + 3 * 4 * 3)"; let answer = evaluate_expression(&input, 2); assert_eq!(answer, 1445); } #[test] fn test_example_2_5() { let input: &str = "5 * 9 * (7 * 3 * 3 + 9 * 3 + (8 + 6 * 4))"; let answer = evaluate_expression(&input, 2); assert_eq!(answer, 669060); } #[test] fn test_example_2_6() { let input: &str = "((2 + 4 * 9) * (6 + 9 * 8 + 6) + 6) + 2 + 4 * 2"; let answer = evaluate_expression(&input, 2); assert_eq!(answer, 23340); } }
true
70df4876858332c2940ccd40e2a274670bc99a74
Rust
exercism/rust
/exercises/practice/beer-song/tests/beer-song.rs
UTF-8
1,810
3.078125
3
[ "MIT" ]
permissive
use beer_song as beer; #[test] fn test_verse_0() { assert_eq!(beer::verse(0), "No more bottles of beer on the wall, no more bottles of beer.\nGo to the store and buy some more, 99 bottles of beer on the wall.\n"); } #[test] #[ignore] fn test_verse_1() { assert_eq!(beer::verse(1), "1 bottle of beer on the wall, 1 bottle of beer.\nTake it down and pass it around, no more bottles of beer on the wall.\n"); } #[test] #[ignore] fn test_verse_2() { assert_eq!(beer::verse(2), "2 bottles of beer on the wall, 2 bottles of beer.\nTake one down and pass it around, 1 bottle of beer on the wall.\n"); } #[test] #[ignore] fn test_verse_8() { assert_eq!(beer::verse(8), "8 bottles of beer on the wall, 8 bottles of beer.\nTake one down and pass it around, 7 bottles of beer on the wall.\n"); } #[test] #[ignore] fn test_song_8_6() { assert_eq!(beer::sing(8, 6), "8 bottles of beer on the wall, 8 bottles of beer.\nTake one down and pass it around, 7 bottles of beer on the wall.\n\n7 bottles of beer on the wall, 7 bottles of beer.\nTake one down and pass it around, 6 bottles of beer on the wall.\n\n6 bottles of beer on the wall, 6 bottles of beer.\nTake one down and pass it around, 5 bottles of beer on the wall.\n"); } #[test] #[ignore] fn test_song_3_0() { assert_eq!(beer::sing(3, 0), "3 bottles of beer on the wall, 3 bottles of beer.\nTake one down and pass it around, 2 bottles of beer on the wall.\n\n2 bottles of beer on the wall, 2 bottles of beer.\nTake one down and pass it around, 1 bottle of beer on the wall.\n\n1 bottle of beer on the wall, 1 bottle of beer.\nTake it down and pass it around, no more bottles of beer on the wall.\n\nNo more bottles of beer on the wall, no more bottles of beer.\nGo to the store and buy some more, 99 bottles of beer on the wall.\n"); }
true
1bb7b3fe12c69c4bdf32fee451dbcde2d1e6286b
Rust
Robbepop/type-metadata
/src/type_id.rs
UTF-8
8,042
2.5625
3
[ "Apache-2.0" ]
permissive
// Copyright 2019 // by Centrality Investments Ltd. // and Parity Technologies (UK) Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use crate::tm_std::*; use crate::{ form::{CompactForm, Form, MetaForm}, utils::is_rust_identifier, IntoCompact, MetaType, Metadata, Registry, }; use derive_more::From; use serde::Serialize; /// Implementors return their meta type identifiers. pub trait HasTypeId { /// Returns the static type identifier for `Self`. fn type_id() -> TypeId; } /// Represents the namespace of a type definition. /// /// This consists of several segments that each have to be a valid Rust identifier. /// The first segment represents the crate name in which the type has been defined. /// /// Rust prelude type may have an empty namespace definition. #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Serialize, Debug)] pub struct Namespace<F: Form = MetaForm> { /// The segments of the namespace. segments: Vec<F::String>, } /// An error that may be encountered upon constructing namespaces. #[derive(PartialEq, Eq, Debug)] pub enum NamespaceError { /// If the module path does not at least have one segment. MissingSegments, /// If a segment within a module path is not a proper Rust identifier. InvalidIdentifier { /// The index of the errorneous segment. segment: usize, }, } impl IntoCompact for Namespace { type Output = Namespace<CompactForm>; /// Compacts this namespace using the given registry. fn into_compact(self, registry: &mut Registry) -> Self::Output { Namespace { segments: self .segments .into_iter() .map(|seg| registry.register_string(seg)) .collect::<Vec<_>>(), } } } impl Namespace { /// Creates a new namespace from the given segments. pub fn new<S>(segments: S) -> Result<Self, NamespaceError> where S: IntoIterator<Item = <MetaForm as Form>::String>, { let segments = segments.into_iter().collect::<Vec<_>>(); if segments.len() == 0 { return Err(NamespaceError::MissingSegments); } if let Some(err_at) = segments.iter().position(|seg| !is_rust_identifier(seg)) { return Err(NamespaceError::InvalidIdentifier { segment: err_at }); } Ok(Self { segments }) } /// Creates a new namespace from the given module path. /// /// # Note /// /// Module path is generally obtained from the `module_path!` Rust macro. pub fn from_str(module_path: <MetaForm as Form>::String) -> Result<Self, NamespaceError> { Self::new(module_path.split("::")) } /// Creates the prelude namespace. pub fn prelude() -> Self { Self { segments: vec![] } } } #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, From, Debug, Serialize)] #[serde(bound = " F::TypeId: Serialize, F::IndirectTypeId: Serialize ")] pub enum TypeId<F: Form = MetaForm> { Custom(TypeIdCustom<F>), Slice(TypeIdSlice<F>), Array(TypeIdArray<F>), Tuple(TypeIdTuple<F>), Primitive(TypeIdPrimitive), } impl IntoCompact for TypeId { type Output = TypeId<CompactForm>; fn into_compact(self, registry: &mut Registry) -> Self::Output { match self { TypeId::Custom(custom) => custom.into_compact(registry).into(), TypeId::Slice(slice) => slice.into_compact(registry).into(), TypeId::Array(array) => array.into_compact(registry).into(), TypeId::Tuple(tuple) => tuple.into_compact(registry).into(), TypeId::Primitive(primitive) => primitive.into(), } } } #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Serialize, Debug)] #[serde(rename_all = "lowercase")] pub enum TypeIdPrimitive { Bool, Char, Str, U8, U16, U32, U64, U128, I8, I16, I32, I64, I128, } #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Serialize, Debug)] #[serde(bound = "F::TypeId: Serialize")] pub struct TypeIdCustom<F: Form = MetaForm> { name: F::String, namespace: Namespace<F>, #[serde(rename = "type")] type_params: Vec<F::TypeId>, } impl IntoCompact for TypeIdCustom { type Output = TypeIdCustom<CompactForm>; fn into_compact(self, registry: &mut Registry) -> Self::Output { TypeIdCustom { name: registry.register_string(self.name), namespace: self.namespace.into_compact(registry), type_params: self .type_params .into_iter() .map(|param| registry.register_type(&param)) .collect::<Vec<_>>(), } } } impl TypeIdCustom { pub fn new<T>(name: &'static str, namespace: Namespace, type_params: T) -> Self where T: IntoIterator<Item = MetaType>, { Self { name, namespace, type_params: type_params.into_iter().collect(), } } } #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Serialize, Debug)] #[serde(bound = "F::IndirectTypeId: Serialize")] pub struct TypeIdArray<F: Form = MetaForm> { pub len: u16, #[serde(rename = "type")] pub type_param: F::IndirectTypeId, } impl IntoCompact for TypeIdArray { type Output = TypeIdArray<CompactForm>; fn into_compact(self, registry: &mut Registry) -> Self::Output { TypeIdArray { len: self.len, type_param: registry.register_type(&self.type_param), } } } impl TypeIdArray { pub fn new(len: u16, type_param: MetaType) -> Self { Self { len, type_param } } } #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Serialize, Debug)] #[serde(bound = "F::TypeId: Serialize")] pub struct TypeIdTuple<F: Form = MetaForm> { #[serde(rename = "type")] pub type_params: Vec<F::TypeId>, } impl IntoCompact for TypeIdTuple { type Output = TypeIdTuple<CompactForm>; fn into_compact(self, registry: &mut Registry) -> Self::Output { TypeIdTuple { type_params: self .type_params .into_iter() .map(|param| registry.register_type(&param)) .collect::<Vec<_>>(), } } } impl TypeIdTuple { pub fn new<T>(type_params: T) -> Self where T: IntoIterator<Item = MetaType>, { Self { type_params: type_params.into_iter().collect(), } } pub fn unit() -> Self { Self::new(vec![]) } } #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Serialize, Debug)] #[serde(bound = "F::IndirectTypeId: Serialize")] pub struct TypeIdSlice<F: Form = MetaForm> { #[serde(rename = "type")] type_param: F::IndirectTypeId, } impl IntoCompact for TypeIdSlice { type Output = TypeIdSlice<CompactForm>; fn into_compact(self, registry: &mut Registry) -> Self::Output { TypeIdSlice { type_param: registry.register_type(&self.type_param), } } } impl TypeIdSlice { pub fn new(type_param: MetaType) -> Self { Self { type_param } } pub fn of<T>() -> Self where T: Metadata + 'static, { Self::new(MetaType::new::<T>()) } } #[cfg(test)] mod tests { use super::*; #[test] fn namespace_ok() { assert_eq!( Namespace::new(vec!["hello"]), Ok(Namespace { segments: vec!["hello"] }) ); assert_eq!( Namespace::new(vec!["Hello", "World"]), Ok(Namespace { segments: vec!["Hello", "World"] }) ); assert_eq!(Namespace::new(vec!["_"]), Ok(Namespace { segments: vec!["_"] })); } #[test] fn namespace_err() { assert_eq!(Namespace::new(vec![]), Err(NamespaceError::MissingSegments)); assert_eq!( Namespace::new(vec![""]), Err(NamespaceError::InvalidIdentifier { segment: 0 }) ); assert_eq!( Namespace::new(vec!["1"]), Err(NamespaceError::InvalidIdentifier { segment: 0 }) ); assert_eq!( Namespace::new(vec!["Hello", ", World!"]), Err(NamespaceError::InvalidIdentifier { segment: 1 }) ); } #[test] fn namespace_from_str() { assert_eq!( Namespace::from_str("hello::world"), Ok(Namespace { segments: vec!["hello", "world"] }) ); assert_eq!( Namespace::from_str("::world"), Err(NamespaceError::InvalidIdentifier { segment: 0 }) ); } }
true