lang
stringclasses
3 values
file_path
stringlengths
5
150
repo_name
stringlengths
6
110
commit
stringlengths
40
40
file_code
stringlengths
1.52k
18.9k
prefix
stringlengths
82
16.5k
suffix
stringlengths
0
15.1k
middle
stringlengths
121
8.18k
strategy
stringclasses
8 values
context_items
listlengths
0
100
Rust
src/directory/error.rs
pentlander/tantivy
0e8fcd57274e4276186f8fc32e46f9e9dccdc088
use std::error::Error as StdError; use std::fmt; use std::io; use std::path::PathBuf; #[derive(Debug)] pub struct IOError { path: Option<PathBuf>, err: io::Error, } impl fmt::Display for IOError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.path { Some(ref path) => write!(f, "io error occurred on path '{:?}': '{}'", path, self.err), None => write!(f, "io error occurred: '{}'", self.err), } } } impl StdError for IOError { fn description(&self) -> &str { "io error occurred" } fn cause(&self) -> Option<&StdError> { Some(&self.err) } } impl IOError { pub(crate) fn with_path(path: PathBuf, err: io::Error) -> Self { IOError { path: Some(path), err, } } } impl From<io::Error> for IOError { fn from(err: io::Error) -> IOError { IOError { path: None, err } } } #[derive(Debug)] pub enum OpenDirectoryError { DoesNotExist(PathBuf), NotADirectory(PathBuf), } impl fmt::Display for OpenDirectoryError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { OpenDirectoryError::DoesNotExist(ref path) => { write!(f, "the underlying directory '{:?}' does not exist", path) } OpenDirectoryError::NotADirectory(ref path) => { write!(f, "the path '{:?}' exists but is not a directory", path) } } } } impl StdError for OpenDirectoryError { fn description(&self) -> &str { "error occurred while opening a directory" } fn cause(&self) -> Option<&StdError> { None } } #[derive(Debug)] pub enum OpenWriteError { FileAlreadyExists(PathBuf), IOError(IOError), } impl From<IOError> for OpenWriteError { fn from(err: IOError) -> OpenWriteError { OpenWriteError::IOError(err) } } impl fmt::Display for OpenWriteError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { OpenWriteError::FileAlreadyExists(ref path) => { write!(f, "the file '{:?}' already exists", path) } OpenWriteError::IOError(ref err) => write!( f, "an io error occurred while opening a file for writing: '{}'", err ), } } } impl StdError for OpenWriteError { fn description(&self) -> &str { "error occurred while opening a file for writing" } fn cause(&self) -> Option<&StdError> { match *self { OpenWriteError::FileAlreadyExists(_) => None, OpenWriteError::IOError(ref err) => Some(err), } } } #[derive(Debug)] pub enum OpenReadError { FileDoesNotExist(PathBuf), IOError(IOError), } impl From<IOError> for OpenReadError { fn from(err: IOError) -> OpenReadError { OpenReadError::IOError(err) } } impl fmt::Display for OpenReadError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { OpenReadError::FileDoesNotExist(ref path) => { write!(f, "the file '{:?}' does not exist", path) } OpenReadError::IOError(ref err) => write!( f, "an io error occurred while opening a file for reading: '{}'", err ), } } } impl StdError for OpenReadError { fn description(&self) -> &str { "error occurred while opening a file for reading" } fn cause(&self) -> Option<&StdError> { match *self { OpenReadError::FileDoesNotExist(_) => None, OpenReadError::IOError(ref err) => Some(err), } } } #[derive(Debug)] pub enum DeleteError { FileDoesNotExist(PathBuf), IOError(IOError), } impl From<IOError> for DeleteError { fn from(err: IOError) -> DeleteError { DeleteError::IOError(err) } } impl fmt::Display for DeleteError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { DeleteError::FileDoesNotExist(ref path) => { write!(f, "the file '{:?}' does not exist", path) } DeleteError::IOError(ref err) => { write!(f, "an io error occurred while deleting a file: '{}'", err) } } } } impl StdError for DeleteError { fn description(&self) -> &str { "error occurred while deleting a file" } fn cause(&self) -> Option<&StdError> { match *self { DeleteError::FileDoesNotExist(_) => None, DeleteError::IOError(ref err) => Some(err), } } }
use std::error::Error as StdError; use std::fmt; use std::io; use std::path::PathBuf; #[derive(Debug)] pub struct IOError { path: Option<PathBuf>, err: io::Error, } impl fmt::Display for IOError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.path { Some(ref path) => write!(f, "io error occurred on path '{:?}': '{}'", path, self.err), None => write!(f, "io error occurred: '{}'", self.err), } } } impl StdError for IOError { fn description(&self) -> &str { "io error occurred" } fn cause(&self) -> Option<&StdError> { Some(&self.err) } } impl IOError { pub(crate) fn with_path(path: PathBuf, err: io::Error) -> Self { IOError { path: Some(path), err, } } } impl From<io::Error> for IOError { fn from(err: io::Error) -> IOError { IOError { path: None, err } } } #[derive(Debug)] pub enum OpenDirectoryError { DoesNotExist(PathBuf), NotADirectory(PathBuf), } impl fmt::Display for OpenDirectoryError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { OpenDirectoryError::DoesNotExist(ref path) => { write!(f, "the underlying directory '{:?}' does not exist", path) } OpenDirectoryError::NotADirectory(ref path) => { write!(f, "the path '{:?}' exists but is not a directory", path) } } } } impl StdError for OpenDirectoryError { fn description(&self) -> &str { "error occurred while opening a directory" } fn cause(&self) -> Option<&StdError> { None } } #[derive(Debug)] pub enum OpenWriteError { FileAlreadyExists(PathBuf), IOError(IOError), } impl From<IOError> for OpenWriteError { fn from(err: IOError) -> OpenWriteError { OpenWriteError::IOError(err) } } impl fmt::Display for OpenWriteError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { OpenWriteError::FileAlreadyExists(ref path) => { write!(f, "the file '{:?}' already exists", path) } OpenWriteError::IOError(ref err) => write!( f, "an io error occurred while opening a file for writing: '{}'", err ), } } } impl StdError for OpenWriteError { fn description(&self) -> &str { "error occurred while opening a file for writing" }
} #[derive(Debug)] pub enum OpenReadError { FileDoesNotExist(PathBuf), IOError(IOError), } impl From<IOError> for OpenReadError { fn from(err: IOError) -> OpenReadError { OpenReadError::IOError(err) } } impl fmt::Display for OpenReadError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { OpenReadError::FileDoesNotExist(ref path) => { write!(f, "the file '{:?}' does not exist", path) } OpenReadError::IOError(ref err) => write!( f, "an io error occurred while opening a file for reading: '{}'", err ), } } } impl StdError for OpenReadError { fn description(&self) -> &str { "error occurred while opening a file for reading" } fn cause(&self) -> Option<&StdError> { match *self { OpenReadError::FileDoesNotExist(_) => None, OpenReadError::IOError(ref err) => Some(err), } } } #[derive(Debug)] pub enum DeleteError { FileDoesNotExist(PathBuf), IOError(IOError), } impl From<IOError> for DeleteError { fn from(err: IOError) -> DeleteError { DeleteError::IOError(err) } } impl fmt::Display for DeleteError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { DeleteError::FileDoesNotExist(ref path) => { write!(f, "the file '{:?}' does not exist", path) } DeleteError::IOError(ref err) => { write!(f, "an io error occurred while deleting a file: '{}'", err) } } } } impl StdError for DeleteError { fn description(&self) -> &str { "error occurred while deleting a file" } fn cause(&self) -> Option<&StdError> { match *self { DeleteError::FileDoesNotExist(_) => None, DeleteError::IOError(ref err) => Some(err), } } }
fn cause(&self) -> Option<&StdError> { match *self { OpenWriteError::FileAlreadyExists(_) => None, OpenWriteError::IOError(ref err) => Some(err), } }
function_block-full_function
[ { "content": "/// Write a `u32` as a vint payload.\n\npub fn write_u32_vint<W: io::Write>(val: u32, writer: &mut W) -> io::Result<()> {\n\n let (val, num_bytes) = serialize_vint_u32(val);\n\n let mut buffer = [0u8; 8];\n\n LittleEndian::write_u64(&mut buffer, val);\n\n writer.write_all(&buffer[..num...
Rust
src/content.rs
silvrwolfboy/hubcaps
f173a3be1e5135b389587afe355b49103a49f8d8
use std::fmt; use std::ops; use serde::Deserialize; use serde::de::{self, Visitor}; use crate::utils::{percent_encode, PATH}; use crate::{Future, Github, Stream}; pub struct Content { github: Github, owner: String, repo: String, } impl Content { #[doc(hidden)] pub fn new<O, R>(github: Github, owner: O, repo: R) -> Self where O: Into<String>, R: Into<String>, { Content { github, owner: owner.into(), repo: repo.into(), } } fn path(&self, location: &str) -> String { let location = percent_encode(location.as_ref(), PATH); format!("/repos/{}/{}/contents{}", self.owner, self.repo, location) } pub fn get(&self, location: &str) -> Future<Contents> { self.github.get(&self.path(location)) } pub fn file(&self, location: &str) -> Future<File> { self.github.get(&self.path(location)) } pub fn root(&self) -> Stream<DirectoryItem> { self.iter("/") } pub fn iter(&self, location: &str) -> Stream<DirectoryItem> { self.github.get_stream(&self.path(location)) } } #[derive(Debug, Deserialize)] #[serde(rename_all = "snake_case", tag = "type")] pub enum Contents { File(File), Symlink(Symlink), Submodule(Submodule), } #[derive(Debug, Deserialize)] #[serde(rename_all = "snake_case")] pub enum Encoding { Base64, } #[derive(Debug, Deserialize)] pub struct File { pub encoding: Encoding, pub size: u32, pub name: String, pub path: String, pub content: DecodedContents, pub sha: String, pub url: String, pub git_url: String, pub html_url: String, pub download_url: String, pub _links: Links, } #[derive(Debug, Deserialize)] pub struct DirectoryItem { #[serde(rename = "type")] pub _type: String, pub size: u32, pub name: String, pub path: String, pub sha: String, pub url: String, pub git_url: String, pub html_url: String, pub download_url: Option<String>, pub _links: Links, } #[derive(Debug, Deserialize)] pub struct Symlink { pub target: String, pub size: u32, pub name: String, pub path: String, pub sha: String, pub url: String, pub git_url: String, pub html_url: String, pub download_url: String, pub _links: Links, } #[derive(Debug, Deserialize)] pub struct Submodule { pub submodule_git_url: String, pub size: u32, pub name: String, pub path: String, pub sha: String, pub url: String, pub git_url: String, pub html_url: String, pub download_url: Option<String>, pub _links: Links, } #[derive(Debug, Deserialize)] pub struct Links { pub git: String, #[serde(rename = "self")] pub _self: String, pub html: String, } #[derive(Debug)] pub struct DecodedContents(Vec<u8>); impl Into<Vec<u8>> for DecodedContents { fn into(self) -> Vec<u8> { self.0 } } impl AsRef<[u8]> for DecodedContents { fn as_ref(&self) -> &[u8] { &self.0 } } impl ops::Deref for DecodedContents { type Target = [u8]; fn deref(&self) -> &Self::Target { &self.0 } } impl<'de> Deserialize<'de> for DecodedContents { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { struct DecodedContentsVisitor; impl<'de> Visitor<'de> for DecodedContentsVisitor { type Value = DecodedContents; fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "base64 string") } fn visit_str<E>(self, v: &str) -> Result<Self::Value, E> where E: de::Error, { let v = v.replace("\n", ""); let decoded = base64::decode_config(&v, base64::STANDARD).map_err(|e| match e { base64::DecodeError::InvalidLength => { E::invalid_length(v.len(), &"invalid base64 length") } base64::DecodeError::InvalidByte(offset, byte) => E::invalid_value( de::Unexpected::Bytes(&[byte]), &format!("valid base64 character at offset {}", offset).as_str(), ), base64::DecodeError::InvalidLastSymbol(offset, byte) => E::invalid_value( de::Unexpected::Bytes(&[byte]), &format!("valid last base64 character at offset {}", offset).as_str(), ), })?; Ok(DecodedContents(decoded)) } } deserializer.deserialize_str(DecodedContentsVisitor) } }
use std::fmt; use std::ops; use serde::Deserialize; use serde::de::{self, Visitor}; use crate::utils::{percent_encode, PATH}; use crate::{Future, Github, Stream}; pub struct Content { github: Github, owner: String, repo: String, } impl Content { #[doc(hidden)] pub fn new<O, R>(github: Github, owner: O, repo: R) -> Self where O: Into<String>, R: Into<String>, { Content { github, owner: owner.into(), repo: repo.into(), } } fn path(&self, location: &str) -> String { let location = percent_encode(location.as_ref(), PATH); format!("/repos/{}/{}/contents{}", self.owner, self.repo, location) } pub fn get(&self, location: &str) -> Future<Contents> { self.github.get(&self.path(location)) } pub fn file(&self, location: &str) -> Future<File> { self.github.get(&self.path(location)) } pub fn root(&self) -> Stream<DirectoryItem> { self.iter("/") } pub fn iter(&self, location: &str) -> Stream<DirectoryItem> { self.github.get_stream(&self.path(location)) } } #[derive(Debug, Deserialize)] #[serde(rename_all = "snake_case", tag = "type")] pub enum Contents { File(File), Symlink(Symlink), Submodule(Submodule), } #[derive(Debug, Deserialize)] #[serde(rename_all = "snake_case")] pub enum Encoding { Base64, } #[derive(Debug, Deserialize)] pub struct File { pub encoding: Encoding, pub size: u32, pub name: String, pub path: String, pub content: DecodedContents, pub sha: String, pub url: String, pub git_url: String, pub html_url: String, pub download_url: String, pub _links: Links, } #[derive(Debug, Deserialize)] pub struct DirectoryItem { #[serde(rename = "type")] pub _type: String, pub size: u32, pub name: String, pub path: String, pub sha: String, pub url: String, pub git_url: String, pub html_url: String, pub download_url: Option<String>, pub _links: Links, } #[derive(Debug, Deserialize)] pub struct Symlink { pub target: String, pub size: u32, pub name: String, pub path: String, pub sha: String, pub url: String, pub git_url: String, pub html_url: String, pub download_url: String, pub _links: Links, } #[derive(Debug, Deserialize)] pub struct Submodule { pub submodule_git_url: String, pub size: u32, pub name: String, pub path: String, pub sha: String, pub url: String, pub git_url: String, pub html_url: String, pub download_url: Option<String>, pub _links: Links, } #[derive(Debug, Deserialize)] pub struct Links { pub git: String, #[serde(rename = "self")] pub _self: String, pub html: String, } #[derive(Debug)] pub struct DecodedContents(Vec<u8>); impl Into<Vec<u8>> for DecodedContents { fn into(self) -> Vec<u8> { self.0 } } impl AsRef<[u8]> for DecodedContents { fn as_ref(&self) -> &[u8] { &self.0 } } impl ops::Deref for DecodedContents { type Target = [u8]; fn deref(&self) -> &Self::Target { &self.0 } } impl<'de> Deserialize<'de> for DecodedContents {
}
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { struct DecodedContentsVisitor; impl<'de> Visitor<'de> for DecodedContentsVisitor { type Value = DecodedContents; fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "base64 string") } fn visit_str<E>(self, v: &str) -> Result<Self::Value, E> where E: de::Error, { let v = v.replace("\n", ""); let decoded = base64::decode_config(&v, base64::STANDARD).map_err(|e| match e { base64::DecodeError::InvalidLength => { E::invalid_length(v.len(), &"invalid base64 length") } base64::DecodeError::InvalidByte(offset, byte) => E::invalid_value( de::Unexpected::Bytes(&[byte]), &format!("valid base64 character at offset {}", offset).as_str(), ), base64::DecodeError::InvalidLastSymbol(offset, byte) => E::invalid_value( de::Unexpected::Bytes(&[byte]), &format!("valid last base64 character at offset {}", offset).as_str(), ), })?; Ok(DecodedContents(decoded)) } } deserializer.deserialize_str(DecodedContentsVisitor) }
function_block-full_function
[ { "content": "fn var(name: &str) -> Result<String> {\n\n if let Some(v) = env::var(name).ok() {\n\n Ok(v)\n\n } else {\n\n Err(format!(\"example missing {}\", name).into())\n\n }\n\n}\n\n\n\nconst USER_AGENT: &str = concat!(env!(\"CARGO_PKG_NAME\"), \"/\", env!(\"CARGO_PKG_VERSION\"));\n\...
Rust
lib/engine/src/window/input.rs
OrangeBacon/opengl-rust
842354c929db9d60b73fb54781420d41f8e99f23
use std::collections::HashMap; use super::scancode::Scancode; #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] pub enum KeyState { None, Down, Hold, Up, } #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Default)] pub struct MouseState { x: i32, y: i32, delta_x: i32, delta_y: i32, wheel_x: i32, wheel_y: i32, wheel_delta_x: i32, wheel_delta_y: i32, left_button: bool, middle_button: bool, right_button: bool, mouse_four: bool, mouse_five: bool, } #[derive(Clone, PartialEq, Eq, Debug, Default)] pub struct InputState { mouse: MouseState, keys: HashMap<Scancode, KeyState>, } impl InputState { pub fn update(&mut self, mouse_state: MouseState) { self.mouse = mouse_state; self.keys = self .keys .iter() .map(|(scan, state)| { let new_state = match state { KeyState::Down => KeyState::Hold, KeyState::Up => KeyState::None, a => *a, }; (*scan, new_state) }) .collect(); } pub fn key_state(&self, key: Scancode) -> KeyState { *self.keys.get(&key).unwrap_or(&KeyState::None) } pub(crate) fn set_key_state(&mut self, key: Scancode, state: KeyState) { self.keys.insert(key, state); } pub fn is_key_pressed(&self, key: Scancode) -> bool { let key = *self.keys.get(&key).unwrap_or(&KeyState::None); if key == KeyState::Down || key == KeyState::Hold { true } else { false } } pub fn mouse_position(&self) -> (i32, i32) { (self.mouse.x, self.mouse.y) } pub(crate) fn set_mouse_position(&mut self, x: i32, y: i32) { self.mouse.x = x; self.mouse.y = y; } pub fn mouse_delta(&self) -> (i32, i32) { (self.mouse.delta_x, self.mouse.delta_y) } pub(crate) fn set_mouse_delta(&mut self, x: i32, y: i32) { self.mouse.delta_x = x; self.mouse.delta_y = y; } pub fn wheel_position(&self) -> (i32, i32) { (self.mouse.wheel_x, self.mouse.wheel_y) } pub(crate) fn set_wheel_position(&mut self, x: i32, y: i32) { self.mouse.wheel_x = x; self.mouse.wheel_y = y; } pub fn wheel_delta(&self) -> (i32, i32) { (self.mouse.wheel_delta_x, self.mouse.wheel_delta_y) } pub(crate) fn set_wheel_delta(&mut self, x: i32, y: i32) { self.mouse.wheel_delta_x = x; self.mouse.wheel_delta_y = y; } pub fn mouse_left(&self) -> bool { self.mouse.left_button } pub(crate) fn set_mouse_left(&mut self, value: bool) { self.mouse.left_button = value; } pub fn mouse_middle(&self) -> bool { self.mouse.middle_button } pub(crate) fn set_mouse_middle(&mut self, value: bool) { self.mouse.middle_button = value; } pub fn mouse_right(&self) -> bool { self.mouse.right_button } pub(crate) fn set_mouse_right(&mut self, value: bool) { self.mouse.right_button = value; } pub fn mouse_four(&self) -> bool { self.mouse.mouse_four } pub(crate) fn set_mouse_four(&mut self, value: bool) { self.mouse.mouse_four = value; } pub fn mouse_five(&self) -> bool { self.mouse.mouse_five } pub(crate) fn set_mouse_five(&mut self, value: bool) { self.mouse.mouse_five = value; } }
use std::collections::HashMap; use super::scancode::Scancode; #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] pub enum KeyState { None, Down, Hold, Up, } #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Default)] pub struct MouseState { x: i32, y: i32, delta_x: i32, delta_y: i32, wheel_x: i32, wheel_y: i32, wheel_delta_x: i32, wheel_delta_y: i32, left_button: bool, middle_button: bool, right_button: bool, mouse_four: bool, mouse_five: bool, } #[derive(Clone, PartialEq, Eq, Debug, Default)] pub struct InputState { mouse: MouseState, keys: HashMap<Scancode, KeyState>, } impl InputState { pub fn update(&mut self, mouse_state: MouseState) { self.mouse = mouse_state; self.keys = self .keys .iter() .map(|(scan, state)| { let new_state = match state { KeyState::Down => KeyState::Hold, KeyState::Up => KeyState::None, a => *a, }; (*scan, new_state) }) .collect(); } pub fn key_state(&self, key: Scancode) -> KeyState { *self.keys.get(&key).unwrap_or(&KeyState::None) } pub(crate) fn set_key_state(&mut self, key: Scancode, state: KeyState) { self.keys.insert(key, state); }
pub fn mouse_position(&self) -> (i32, i32) { (self.mouse.x, self.mouse.y) } pub(crate) fn set_mouse_position(&mut self, x: i32, y: i32) { self.mouse.x = x; self.mouse.y = y; } pub fn mouse_delta(&self) -> (i32, i32) { (self.mouse.delta_x, self.mouse.delta_y) } pub(crate) fn set_mouse_delta(&mut self, x: i32, y: i32) { self.mouse.delta_x = x; self.mouse.delta_y = y; } pub fn wheel_position(&self) -> (i32, i32) { (self.mouse.wheel_x, self.mouse.wheel_y) } pub(crate) fn set_wheel_position(&mut self, x: i32, y: i32) { self.mouse.wheel_x = x; self.mouse.wheel_y = y; } pub fn wheel_delta(&self) -> (i32, i32) { (self.mouse.wheel_delta_x, self.mouse.wheel_delta_y) } pub(crate) fn set_wheel_delta(&mut self, x: i32, y: i32) { self.mouse.wheel_delta_x = x; self.mouse.wheel_delta_y = y; } pub fn mouse_left(&self) -> bool { self.mouse.left_button } pub(crate) fn set_mouse_left(&mut self, value: bool) { self.mouse.left_button = value; } pub fn mouse_middle(&self) -> bool { self.mouse.middle_button } pub(crate) fn set_mouse_middle(&mut self, value: bool) { self.mouse.middle_button = value; } pub fn mouse_right(&self) -> bool { self.mouse.right_button } pub(crate) fn set_mouse_right(&mut self, value: bool) { self.mouse.right_button = value; } pub fn mouse_four(&self) -> bool { self.mouse.mouse_four } pub(crate) fn set_mouse_four(&mut self, value: bool) { self.mouse.mouse_four = value; } pub fn mouse_five(&self) -> bool { self.mouse.mouse_five } pub(crate) fn set_mouse_five(&mut self, value: bool) { self.mouse.mouse_five = value; } }
pub fn is_key_pressed(&self, key: Scancode) -> bool { let key = *self.keys.get(&key).unwrap_or(&KeyState::None); if key == KeyState::Down || key == KeyState::Hold { true } else { false } }
function_block-full_function
[ { "content": "fn default_event_handler(state: &mut EngineState, event: &Event) -> EventResult {\n\n match event {\n\n Event::Quit { .. } => return EventResult::Exit,\n\n Event::KeyDown { key, .. } => {\n\n state.inputs.set_key_state(*key, KeyState::Down);\n\n }\n\n Even...
Rust
delivery-service/ds-lib/src/lib.rs
greydot/openmls
fca1cbd3400d377dae06ef9ceebda5e0392c6c89
use openmls::{framing::VerifiableMlsPlaintext, prelude::*}; use tls_codec::{ Size, TlsByteSliceU16, TlsByteVecU16, TlsByteVecU32, TlsByteVecU8, TlsDeserialize, TlsSerialize, TlsSize, TlsVecU32, }; #[derive(Debug, Default, Clone)] pub struct ClientInfo<'a> { pub client_name: String, pub key_packages: ClientKeyPackages, pub id: Vec<u8>, pub msgs: Vec<DsMlsMessage<'a>>, pub welcome_queue: Vec<Welcome>, } #[derive(Debug, Default, Clone, PartialEq, TlsSerialize, TlsDeserialize, TlsSize)] pub struct ClientKeyPackages(pub TlsVecU32<(TlsByteVecU8, KeyPackage)>); impl<'a> ClientInfo<'a> { pub fn new(client_name: String, mut key_packages: Vec<(Vec<u8>, KeyPackage)>) -> Self { Self { client_name, id: key_packages[0].1.credential().identity().to_vec(), key_packages: ClientKeyPackages( key_packages .drain(..) .map(|(e1, e2)| (e1.into(), e2)) .collect::<Vec<(TlsByteVecU8, KeyPackage)>>() .into(), ), msgs: Vec::new(), welcome_queue: Vec::new(), } } pub fn id(&self) -> &[u8] { self.id.as_slice() } } #[derive(Debug, Clone)] pub enum DsMlsMessage<'a> { Plaintext(VerifiableMlsPlaintext<'a>), Ciphertext(MlsCiphertext), } impl<'a> DsMlsMessage<'a> { pub fn group_id(&self) -> &[u8] { match self { DsMlsMessage::Plaintext(p) => p.payload().group_id(), DsMlsMessage::Ciphertext(c) => c.group_id().as_slice(), } } pub fn epoch(&self) -> u64 { match self { DsMlsMessage::Ciphertext(m) => m.epoch().0, DsMlsMessage::Plaintext(m) => m.payload().epoch().0, } } pub fn is_handshake_message(&self) -> bool { match self { DsMlsMessage::Ciphertext(m) => m.is_handshake_message(), DsMlsMessage::Plaintext(m) => m.payload().is_handshake_message(), } } } #[derive(Debug)] pub enum Message<'a> { MlsMessage(DsMlsMessage<'a>), Welcome(Welcome), } #[derive(Debug, Clone, Copy, TlsSerialize, TlsDeserialize, TlsSize)] #[repr(u8)] pub enum MessageType { MlsCiphertext = 0, MlsPlaintext = 1, Welcome = 2, } #[derive(Debug)] pub struct GroupMessage<'a> { pub msg: DsMlsMessage<'a>, pub recipients: TlsVecU32<TlsByteVecU32>, } impl<'a> GroupMessage<'a> { pub fn new(msg: DsMlsMessage<'a>, recipients: &[Vec<u8>]) -> Self { Self { msg, recipients: recipients .iter() .map(|r| r.clone().into()) .collect::<Vec<TlsByteVecU32>>() .into(), } } pub fn group_id(&self) -> &[u8] { self.msg.group_id() } pub fn epoch(&self) -> u64 { self.msg.epoch() } pub fn is_handshake_message(&self) -> bool { self.msg.is_handshake_message() } } impl<'a> tls_codec::Size for ClientInfo<'a> { fn tls_serialized_len(&self) -> usize { TlsByteSliceU16(self.client_name.as_bytes()).tls_serialized_len() + self.key_packages.tls_serialized_len() } } impl<'a> tls_codec::Serialize for ClientInfo<'a> { fn tls_serialize<W: std::io::Write>(&self, writer: &mut W) -> Result<usize, tls_codec::Error> { let written = TlsByteSliceU16(self.client_name.as_bytes()).tls_serialize(writer)?; self.key_packages.tls_serialize(writer).map(|l| l + written) } } impl<'a> tls_codec::Deserialize for ClientInfo<'a> { fn tls_deserialize<R: std::io::Read>(bytes: &mut R) -> Result<Self, tls_codec::Error> { let client_name = String::from_utf8_lossy(TlsByteVecU16::tls_deserialize(bytes)?.as_slice()).into(); let mut key_packages: Vec<(TlsByteVecU8, KeyPackage)> = TlsVecU32::<(TlsByteVecU8, KeyPackage)>::tls_deserialize(bytes)?.into(); let key_packages = key_packages .drain(..) .map(|(e1, e2)| (e1.into(), e2)) .collect(); Ok(Self::new(client_name, key_packages)) } } impl<'a> tls_codec::Size for Message<'a> { fn tls_serialized_len(&self) -> usize { MessageType::MlsCiphertext.tls_serialized_len() + match self { Message::MlsMessage(mm) => match mm { DsMlsMessage::Plaintext(p) => p.tls_serialized_len(), DsMlsMessage::Ciphertext(c) => c.tls_serialized_len(), }, Message::Welcome(w) => w.tls_serialized_len(), } } } impl<'a> tls_codec::Serialize for Message<'a> { fn tls_serialize<W: std::io::Write>(&self, writer: &mut W) -> Result<usize, tls_codec::Error> { let written; match self { Message::MlsMessage(m) => match m { DsMlsMessage::Ciphertext(m) => { written = MessageType::MlsCiphertext.tls_serialize(writer)?; m.tls_serialize(writer) } DsMlsMessage::Plaintext(m) => { written = MessageType::MlsPlaintext.tls_serialize(writer)?; m.tls_serialize(writer) } }, Message::Welcome(m) => { written = MessageType::Welcome.tls_serialize(writer)?; m.tls_serialize(writer) } } .map(|l| l + written) } } impl<'a> tls_codec::Deserialize for Message<'a> { fn tls_deserialize<R: std::io::Read>(bytes: &mut R) -> Result<Self, tls_codec::Error> { let msg_type = MessageType::tls_deserialize(bytes)?; Ok(match msg_type { MessageType::MlsCiphertext => Message::MlsMessage(DsMlsMessage::Ciphertext( MlsCiphertext::tls_deserialize(bytes)?, )), MessageType::MlsPlaintext => Message::MlsMessage(DsMlsMessage::Plaintext( VerifiableMlsPlaintext::tls_deserialize(bytes)?, )), MessageType::Welcome => Message::Welcome(Welcome::tls_deserialize(bytes)?), }) } } impl<'a> tls_codec::Size for GroupMessage<'a> { fn tls_serialized_len(&self) -> usize { MessageType::MlsCiphertext.tls_serialized_len() + match &self.msg { DsMlsMessage::Plaintext(p) => p.tls_serialized_len(), DsMlsMessage::Ciphertext(c) => c.tls_serialized_len(), } + self.recipients.tls_serialized_len() } } impl<'a> tls_codec::Serialize for GroupMessage<'a> { fn tls_serialize<W: std::io::Write>(&self, writer: &mut W) -> Result<usize, tls_codec::Error> { let mut written = 0; written += match &self.msg { DsMlsMessage::Ciphertext(m) => { MessageType::MlsCiphertext.tls_serialize(writer)? + m.tls_serialize(writer)? } DsMlsMessage::Plaintext(m) => { MessageType::MlsPlaintext.tls_serialize(writer)? + m.tls_serialize(writer)? } }; self.recipients.tls_serialize(writer).map(|l| l + written) } } impl<'a> tls_codec::Deserialize for GroupMessage<'a> { fn tls_deserialize<R: std::io::Read>(bytes: &mut R) -> Result<Self, tls_codec::Error> { let msg_type = MessageType::tls_deserialize(bytes)?; let msg = match msg_type { MessageType::MlsCiphertext => { DsMlsMessage::Ciphertext(MlsCiphertext::tls_deserialize(bytes)?) } MessageType::MlsPlaintext => { DsMlsMessage::Plaintext(VerifiableMlsPlaintext::tls_deserialize(bytes)?) } _ => { return Err(tls_codec::Error::DecodingError(format!( "Invalid message type {:?}", msg_type ))) } }; let recipients = TlsVecU32::<TlsByteVecU32>::tls_deserialize(bytes)?; Ok(Self { msg, recipients }) } }
use openmls::{framing::VerifiableMlsPlaintext, prelude::*}; use tls_codec::{ Size, TlsByteSliceU16, TlsByteVecU16, TlsByteVecU32, TlsByteVecU8, TlsDeserialize, TlsSerialize, TlsSize, TlsVecU32, }; #[derive(Debug, Default, Clone)] pub struct ClientInfo<'a> { pub client_name: String, pub key_packages: ClientKeyPackages, pub id: Vec<u8>, pub msgs: Vec<DsMlsMessage<'a>>, pub welcome_queue: Vec<Welcome>, } #[derive(Debug, Default, Clone, PartialEq, TlsSerialize, TlsDeserialize, TlsSize)] pub struct ClientKeyPackages(pub TlsVecU32<(TlsByteVecU8, KeyPackage)>); impl<'a> ClientInfo<'a> { pub fn new(client_name: String, mut key_packages: Vec<(Vec<u8>, KeyPackage)>) -> Self { Self { client_name, id: key_packages[0].1.credential().identity().to_vec(), key_packages: ClientKeyPackages( key_packages .drain(..) .map(|(e1, e2)| (e1.into(), e2)) .collect::<Vec<(TlsByteVecU8, KeyPackage)>>() .into(), ), msgs: Vec::new(), welcome_queue: Vec::new(), } } pub fn id(&self) -> &[u8] { self.id.as_slice() } } #[derive(Debug, Clone)] pub enum DsMlsMessage<'a> { Plaintext(VerifiableMlsPlaintext<'a>), Ciphertext(MlsCiphertext), } impl<'a> DsMlsMessage<'a> { pub fn group_id(&self) -> &[u8] { match self { DsMlsMessage::Plaintext(p) => p.payload().group_id(), DsMlsMessage::Ciphertext(c) => c.group_id().as_slice(), } } pub fn epoch(&self) -> u64 { match self { DsMlsMessage::Ciphertext(m) => m.epoch().0, DsMlsMessage::Plaintext(m) => m.payload().epoch().0, } } pub fn is_handshake_message(&self) -> bool { match self { DsMlsMessage::Ciphertext(m) => m.is_handshake_message(), DsMlsMessage::Plaintext(m) => m.payload().is_handshake_message(), } } } #[derive(Debug)] pub enum Message<'a> { MlsMessage(DsMlsMessage<'a>), Welcome(Welcome), } #[derive(Debug, Clone, Copy, TlsSerialize, TlsDeserialize, TlsSize)] #[repr(u8)] pub enum MessageType { MlsCiphertext = 0, MlsPlaintext = 1, Welcome = 2, } #[derive(Debug)] pub struct GroupMessage<'a> { pub msg: DsMlsMessage<'a>, pub recipients: TlsVecU32<TlsByteVecU32>, } impl<'a> GroupMessage<'a> { pub fn new(msg: DsMlsMessage<'a>, recipients: &[Vec<u8>]) -> Self { Self { msg, recipients: recipients .iter() .map(|r| r.clone().into()) .collect::<Vec<TlsByteVecU32>>() .into(), } } pub fn group_id(&self) -> &[u8] { self.msg.group_id() } pub fn epoch(&self) -> u64 { self.msg.epoch() } pub fn is_handshake_message(&self) -> bool { self.msg.is_handshake_message() } } impl<'a> tls_codec::Size for ClientInfo<'a> { fn tls_serialized_len(&self) -> usize { TlsByteSliceU16(self.client_name.as_bytes()).tls_serialized_len() + self.key_packages.tls_serialized_len() } } impl<'a> tls_codec::Serialize for ClientInfo<'a> { fn tls_serialize<W: std::io::Write>(&self, writer: &mut W) -> Result<usize, tls_codec::Error> { let written = TlsByteSliceU16(self.client_name.as_bytes()).tls_serialize(writer)?; self.key_packages.tls_serialize(writer).map(|l| l + written) } } impl<'a> tls_codec::Dese
(bytes)?, )), MessageType::Welcome => Message::Welcome(Welcome::tls_deserialize(bytes)?), }) } } impl<'a> tls_codec::Size for GroupMessage<'a> { fn tls_serialized_len(&self) -> usize { MessageType::MlsCiphertext.tls_serialized_len() + match &self.msg { DsMlsMessage::Plaintext(p) => p.tls_serialized_len(), DsMlsMessage::Ciphertext(c) => c.tls_serialized_len(), } + self.recipients.tls_serialized_len() } } impl<'a> tls_codec::Serialize for GroupMessage<'a> { fn tls_serialize<W: std::io::Write>(&self, writer: &mut W) -> Result<usize, tls_codec::Error> { let mut written = 0; written += match &self.msg { DsMlsMessage::Ciphertext(m) => { MessageType::MlsCiphertext.tls_serialize(writer)? + m.tls_serialize(writer)? } DsMlsMessage::Plaintext(m) => { MessageType::MlsPlaintext.tls_serialize(writer)? + m.tls_serialize(writer)? } }; self.recipients.tls_serialize(writer).map(|l| l + written) } } impl<'a> tls_codec::Deserialize for GroupMessage<'a> { fn tls_deserialize<R: std::io::Read>(bytes: &mut R) -> Result<Self, tls_codec::Error> { let msg_type = MessageType::tls_deserialize(bytes)?; let msg = match msg_type { MessageType::MlsCiphertext => { DsMlsMessage::Ciphertext(MlsCiphertext::tls_deserialize(bytes)?) } MessageType::MlsPlaintext => { DsMlsMessage::Plaintext(VerifiableMlsPlaintext::tls_deserialize(bytes)?) } _ => { return Err(tls_codec::Error::DecodingError(format!( "Invalid message type {:?}", msg_type ))) } }; let recipients = TlsVecU32::<TlsByteVecU32>::tls_deserialize(bytes)?; Ok(Self { msg, recipients }) } }
rialize for ClientInfo<'a> { fn tls_deserialize<R: std::io::Read>(bytes: &mut R) -> Result<Self, tls_codec::Error> { let client_name = String::from_utf8_lossy(TlsByteVecU16::tls_deserialize(bytes)?.as_slice()).into(); let mut key_packages: Vec<(TlsByteVecU8, KeyPackage)> = TlsVecU32::<(TlsByteVecU8, KeyPackage)>::tls_deserialize(bytes)?.into(); let key_packages = key_packages .drain(..) .map(|(e1, e2)| (e1.into(), e2)) .collect(); Ok(Self::new(client_name, key_packages)) } } impl<'a> tls_codec::Size for Message<'a> { fn tls_serialized_len(&self) -> usize { MessageType::MlsCiphertext.tls_serialized_len() + match self { Message::MlsMessage(mm) => match mm { DsMlsMessage::Plaintext(p) => p.tls_serialized_len(), DsMlsMessage::Ciphertext(c) => c.tls_serialized_len(), }, Message::Welcome(w) => w.tls_serialized_len(), } } } impl<'a> tls_codec::Serialize for Message<'a> { fn tls_serialize<W: std::io::Write>(&self, writer: &mut W) -> Result<usize, tls_codec::Error> { let written; match self { Message::MlsMessage(m) => match m { DsMlsMessage::Ciphertext(m) => { written = MessageType::MlsCiphertext.tls_serialize(writer)?; m.tls_serialize(writer) } DsMlsMessage::Plaintext(m) => { written = MessageType::MlsPlaintext.tls_serialize(writer)?; m.tls_serialize(writer) } }, Message::Welcome(m) => { written = MessageType::Welcome.tls_serialize(writer)?; m.tls_serialize(writer) } } .map(|l| l + written) } } impl<'a> tls_codec::Deserialize for Message<'a> { fn tls_deserialize<R: std::io::Read>(bytes: &mut R) -> Result<Self, tls_codec::Error> { let msg_type = MessageType::tls_deserialize(bytes)?; Ok(match msg_type { MessageType::MlsCiphertext => Message::MlsMessage(DsMlsMessage::Ciphertext( MlsCiphertext::tls_deserialize(bytes)?, )), MessageType::MlsPlaintext => Message::MlsMessage(DsMlsMessage::Plaintext( VerifiableMlsPlaintext::tls_deserialize
random
[ { "content": "pub fn post(url: &Url, msg: &impl Serialize) -> Result<Vec<u8>, String> {\n\n let serialized_msg = msg.tls_serialize_detached().unwrap();\n\n log::debug!(\"Post {:?}\", url);\n\n log::trace!(\"Payload: {:?}\", serialized_msg);\n\n let client = Client::new();\n\n let response = clien...
Rust
compiler/crates/graphql-ir/src/transform.rs
nathalia234/relay
e1435c834383927947d2f38d32948305ed3baed9
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use crate::ir::*; use common::Spanned; use std::sync::Arc; pub trait Transformer { const NAME: &'static str; const VISIT_ARGUMENTS: bool; const VISIT_DIRECTIVES: bool; fn transform_fragment( &mut self, fragment: &FragmentDefinition, ) -> Transformed<FragmentDefinition> { self.default_transform_fragment(fragment) } fn default_transform_fragment( &mut self, fragment: &FragmentDefinition, ) -> Transformed<FragmentDefinition> { let selections = self.transform_selections(&fragment.selections); if let Some(selections) = &selections { if selections.is_empty() { return Transformed::Delete; } } let directives = self.transform_directives(&fragment.directives); if selections.is_none() && directives.is_none() { return Transformed::Keep; } Transformed::Replace(FragmentDefinition { directives: directives.unwrap_or_else(|| fragment.directives.clone()), selections: selections.unwrap_or_else(|| fragment.selections.clone()), ..fragment.clone() }) } fn transform_operation( &mut self, operation: &OperationDefinition, ) -> Transformed<OperationDefinition> { self.default_transform_operation(operation) } fn default_transform_operation( &mut self, operation: &OperationDefinition, ) -> Transformed<OperationDefinition> { let selections = self.transform_selections(&operation.selections); if let Some(selections) = &selections { if selections.is_empty() { return Transformed::Delete; } } let directives = self.transform_directives(&operation.directives); if selections.is_none() && directives.is_none() { return Transformed::Keep; } Transformed::Replace(OperationDefinition { directives: directives.unwrap_or_else(|| operation.directives.clone()), selections: selections.unwrap_or_else(|| operation.selections.clone()), ..operation.clone() }) } fn transform_selections(&mut self, selections: &[Selection]) -> Option<Vec<Selection>> { self.transform_list(selections, Self::transform_selection) } fn transform_selection(&mut self, selection: &Selection) -> Transformed<Selection> { self.default_transform_selection(selection) } fn default_transform_selection(&mut self, selection: &Selection) -> Transformed<Selection> { match selection { Selection::FragmentSpread(selection) => self .transform_fragment_spread(selection) .map(Selection::FragmentSpread), Selection::InlineFragment(selection) => self .transform_inline_fragment(selection) .map(Selection::InlineFragment), Selection::LinkedField(selection) => self .transform_linked_field(selection) .map(Selection::LinkedField), Selection::ScalarField(selection) => self .transform_scalar_field(selection) .map(Selection::ScalarField), } } fn transform_scalar_field(&mut self, field: &ScalarField) -> Transformed<Arc<ScalarField>> { self.default_transform_scalar_field(field) } fn default_transform_scalar_field( &mut self, field: &ScalarField, ) -> Transformed<Arc<ScalarField>> { let arguments = self.transform_arguments(&field.arguments); let directives = self.transform_directives(&field.directives); if arguments.is_none() && directives.is_none() { return Transformed::Keep; } Transformed::Replace(Arc::new(ScalarField { arguments: arguments.unwrap_or_else(|| field.arguments.clone()), directives: directives.unwrap_or_else(|| field.directives.clone()), ..field.clone() })) } fn transform_linked_field(&mut self, field: &LinkedField) -> Transformed<Arc<LinkedField>> { self.default_transform_linked_field(field) } fn default_transform_linked_field( &mut self, field: &LinkedField, ) -> Transformed<Arc<LinkedField>> { let selections = self.transform_selections(&field.selections); if let Some(selections) = &selections { if selections.is_empty() { return Transformed::Delete; } } let arguments = self.transform_arguments(&field.arguments); let directives = self.transform_directives(&field.directives); if selections.is_none() && arguments.is_none() && directives.is_none() { return Transformed::Keep; } Transformed::Replace(Arc::new(LinkedField { arguments: arguments.unwrap_or_else(|| field.arguments.clone()), directives: directives.unwrap_or_else(|| field.directives.clone()), selections: selections.unwrap_or_else(|| field.selections.clone()), ..field.clone() })) } fn transform_inline_fragment( &mut self, fragment: &InlineFragment, ) -> Transformed<Arc<InlineFragment>> { self.default_transform_inline_fragment(fragment) } fn default_transform_inline_fragment( &mut self, fragment: &InlineFragment, ) -> Transformed<Arc<InlineFragment>> { let selections = self.transform_selections(&fragment.selections); if let Some(selections) = &selections { if selections.is_empty() { return Transformed::Delete; } } let directives = self.transform_directives(&fragment.directives); if selections.is_none() && directives.is_none() { return Transformed::Keep; } Transformed::Replace(Arc::new(InlineFragment { directives: directives.unwrap_or_else(|| fragment.directives.clone()), selections: selections.unwrap_or_else(|| fragment.selections.clone()), ..fragment.clone() })) } fn transform_fragment_spread( &mut self, spread: &FragmentSpread, ) -> Transformed<Arc<FragmentSpread>> { self.default_transform_fragment_spread(spread) } fn default_transform_fragment_spread( &mut self, spread: &FragmentSpread, ) -> Transformed<Arc<FragmentSpread>> { let arguments = self.transform_arguments(&spread.arguments); let directives = self.transform_directives(&spread.directives); if arguments.is_none() && directives.is_none() { return Transformed::Keep; } Transformed::Replace(Arc::new(FragmentSpread { arguments: arguments.unwrap_or_else(|| spread.arguments.clone()), directives: directives.unwrap_or_else(|| spread.directives.clone()), ..spread.clone() })) } fn transform_directives(&mut self, directives: &[Directive]) -> Option<Vec<Directive>> { if Self::VISIT_DIRECTIVES { self.transform_list(directives, Self::transform_directive) } else { None } } fn transform_directive(&mut self, directive: &Directive) -> Transformed<Directive> { self.default_transform_directive(directive) } fn default_transform_directive(&mut self, directive: &Directive) -> Transformed<Directive> { let arguments = self.transform_arguments(&directive.arguments); match arguments { None => Transformed::Keep, Some(replacement) => Transformed::Replace(Directive { arguments: replacement, ..directive.clone() }), } } fn transform_arguments(&mut self, arguments: &[Argument]) -> Option<Vec<Argument>> { if Self::VISIT_ARGUMENTS { self.transform_list(arguments, Self::transform_argument) } else { None } } fn transform_argument(&mut self, argument: &Argument) -> Transformed<Argument> { self.default_transform_argument(argument) } fn default_transform_argument(&mut self, argument: &Argument) -> Transformed<Argument> { match self.transform_value(&argument.value.item) { Transformed::Delete => Transformed::Delete, Transformed::Keep => Transformed::Keep, Transformed::Replace(replacement) => Transformed::Replace(Argument { value: Spanned::new(argument.value.span, replacement), ..argument.clone() }), } } fn transform_value(&mut self, value: &Value) -> Transformed<Value> { self.default_transform_value(value) } fn default_transform_value(&mut self, value: &Value) -> Transformed<Value> { match value { Value::Variable(variable) => self.transform_variable(variable).map(Value::Variable), Value::Constant(_) => Transformed::Keep, Value::List(items) => match self.transform_list(items, Self::transform_value) { None => Transformed::Keep, Some(replacement) => Transformed::Replace(Value::List(replacement)), }, Value::Object(arguments) => match self.transform_arguments(arguments) { None => Transformed::Keep, Some(replacement) => Transformed::Replace(Value::Object(replacement)), }, } } fn transform_variable(&mut self, value: &Variable) -> Transformed<Variable> { let _ = value; Transformed::Keep } fn transform_list<F, T>(&mut self, list: &[T], f: F) -> Option<Vec<T>> where F: Fn(&mut Self, &T) -> Transformed<T>, T: Clone, { if list.is_empty() { return None; } let mut result = Vec::new(); let mut has_changes = false; for (index, prev_item) in list.iter().enumerate() { let next_item = f(self, prev_item); match next_item { Transformed::Keep => { if has_changes { result.push(prev_item.clone()); } } Transformed::Delete => { if !has_changes { debug_assert!(result.capacity() == 0); result.reserve(list.len()); result.extend(list.iter().take(index).cloned()); } has_changes = true; } Transformed::Replace(next_item) => { if !has_changes { debug_assert!(result.capacity() == 0); result.reserve(list.len()); result.extend(list.iter().take(index).cloned()); } result.push(next_item); has_changes = true; } } } if has_changes { Some(result) } else { None } } } #[derive(Clone)] pub enum Transformed<T> { Delete, Keep, Replace(T), } impl<T> Transformed<T> { pub fn map<F, U>(self, f: F) -> Transformed<U> where F: FnOnce(T) -> U, { match self { Transformed::Delete => Transformed::Delete, Transformed::Keep => Transformed::Keep, Transformed::Replace(replacement) => Transformed::Replace(f(replacement)), } } }
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use crate::ir::*; use common::Spanned; use std::sync::Arc; pub trait Transformer { const NAME: &'static str; const VISIT_ARGUMENTS: bool; const VISIT_DIRECTIVES: bool; fn transform_fragment( &mut self, fragment: &FragmentDefinition, ) -> Transformed<FragmentDefinition> { self.default_transform_fragment(fragment) } fn default_transform_fragment( &mut self, fragment: &FragmentDefinition, ) -> Transformed<FragmentDefinition> { let selections = self.transform_selections(&fragment.selections); if let Some(selections) = &selections { if selections.is_empty() { return Transformed::Delete; } } let directives = self.transform_directives(&fragment.directives); if selections.is_none() && directives.is_none() { return Transformed::Keep; } Transformed::Replace(FragmentDefinition {
fn transform_operation( &mut self, operation: &OperationDefinition, ) -> Transformed<OperationDefinition> { self.default_transform_operation(operation) } fn default_transform_operation( &mut self, operation: &OperationDefinition, ) -> Transformed<OperationDefinition> { let selections = self.transform_selections(&operation.selections); if let Some(selections) = &selections { if selections.is_empty() { return Transformed::Delete; } } let directives = self.transform_directives(&operation.directives); if selections.is_none() && directives.is_none() { return Transformed::Keep; } Transformed::Replace(OperationDefinition { directives: directives.unwrap_or_else(|| operation.directives.clone()), selections: selections.unwrap_or_else(|| operation.selections.clone()), ..operation.clone() }) } fn transform_selections(&mut self, selections: &[Selection]) -> Option<Vec<Selection>> { self.transform_list(selections, Self::transform_selection) } fn transform_selection(&mut self, selection: &Selection) -> Transformed<Selection> { self.default_transform_selection(selection) } fn default_transform_selection(&mut self, selection: &Selection) -> Transformed<Selection> { match selection { Selection::FragmentSpread(selection) => self .transform_fragment_spread(selection) .map(Selection::FragmentSpread), Selection::InlineFragment(selection) => self .transform_inline_fragment(selection) .map(Selection::InlineFragment), Selection::LinkedField(selection) => self .transform_linked_field(selection) .map(Selection::LinkedField), Selection::ScalarField(selection) => self .transform_scalar_field(selection) .map(Selection::ScalarField), } } fn transform_scalar_field(&mut self, field: &ScalarField) -> Transformed<Arc<ScalarField>> { self.default_transform_scalar_field(field) } fn default_transform_scalar_field( &mut self, field: &ScalarField, ) -> Transformed<Arc<ScalarField>> { let arguments = self.transform_arguments(&field.arguments); let directives = self.transform_directives(&field.directives); if arguments.is_none() && directives.is_none() { return Transformed::Keep; } Transformed::Replace(Arc::new(ScalarField { arguments: arguments.unwrap_or_else(|| field.arguments.clone()), directives: directives.unwrap_or_else(|| field.directives.clone()), ..field.clone() })) } fn transform_linked_field(&mut self, field: &LinkedField) -> Transformed<Arc<LinkedField>> { self.default_transform_linked_field(field) } fn default_transform_linked_field( &mut self, field: &LinkedField, ) -> Transformed<Arc<LinkedField>> { let selections = self.transform_selections(&field.selections); if let Some(selections) = &selections { if selections.is_empty() { return Transformed::Delete; } } let arguments = self.transform_arguments(&field.arguments); let directives = self.transform_directives(&field.directives); if selections.is_none() && arguments.is_none() && directives.is_none() { return Transformed::Keep; } Transformed::Replace(Arc::new(LinkedField { arguments: arguments.unwrap_or_else(|| field.arguments.clone()), directives: directives.unwrap_or_else(|| field.directives.clone()), selections: selections.unwrap_or_else(|| field.selections.clone()), ..field.clone() })) } fn transform_inline_fragment( &mut self, fragment: &InlineFragment, ) -> Transformed<Arc<InlineFragment>> { self.default_transform_inline_fragment(fragment) } fn default_transform_inline_fragment( &mut self, fragment: &InlineFragment, ) -> Transformed<Arc<InlineFragment>> { let selections = self.transform_selections(&fragment.selections); if let Some(selections) = &selections { if selections.is_empty() { return Transformed::Delete; } } let directives = self.transform_directives(&fragment.directives); if selections.is_none() && directives.is_none() { return Transformed::Keep; } Transformed::Replace(Arc::new(InlineFragment { directives: directives.unwrap_or_else(|| fragment.directives.clone()), selections: selections.unwrap_or_else(|| fragment.selections.clone()), ..fragment.clone() })) } fn transform_fragment_spread( &mut self, spread: &FragmentSpread, ) -> Transformed<Arc<FragmentSpread>> { self.default_transform_fragment_spread(spread) } fn default_transform_fragment_spread( &mut self, spread: &FragmentSpread, ) -> Transformed<Arc<FragmentSpread>> { let arguments = self.transform_arguments(&spread.arguments); let directives = self.transform_directives(&spread.directives); if arguments.is_none() && directives.is_none() { return Transformed::Keep; } Transformed::Replace(Arc::new(FragmentSpread { arguments: arguments.unwrap_or_else(|| spread.arguments.clone()), directives: directives.unwrap_or_else(|| spread.directives.clone()), ..spread.clone() })) } fn transform_directives(&mut self, directives: &[Directive]) -> Option<Vec<Directive>> { if Self::VISIT_DIRECTIVES { self.transform_list(directives, Self::transform_directive) } else { None } } fn transform_directive(&mut self, directive: &Directive) -> Transformed<Directive> { self.default_transform_directive(directive) } fn default_transform_directive(&mut self, directive: &Directive) -> Transformed<Directive> { let arguments = self.transform_arguments(&directive.arguments); match arguments { None => Transformed::Keep, Some(replacement) => Transformed::Replace(Directive { arguments: replacement, ..directive.clone() }), } } fn transform_arguments(&mut self, arguments: &[Argument]) -> Option<Vec<Argument>> { if Self::VISIT_ARGUMENTS { self.transform_list(arguments, Self::transform_argument) } else { None } } fn transform_argument(&mut self, argument: &Argument) -> Transformed<Argument> { self.default_transform_argument(argument) } fn default_transform_argument(&mut self, argument: &Argument) -> Transformed<Argument> { match self.transform_value(&argument.value.item) { Transformed::Delete => Transformed::Delete, Transformed::Keep => Transformed::Keep, Transformed::Replace(replacement) => Transformed::Replace(Argument { value: Spanned::new(argument.value.span, replacement), ..argument.clone() }), } } fn transform_value(&mut self, value: &Value) -> Transformed<Value> { self.default_transform_value(value) } fn default_transform_value(&mut self, value: &Value) -> Transformed<Value> { match value { Value::Variable(variable) => self.transform_variable(variable).map(Value::Variable), Value::Constant(_) => Transformed::Keep, Value::List(items) => match self.transform_list(items, Self::transform_value) { None => Transformed::Keep, Some(replacement) => Transformed::Replace(Value::List(replacement)), }, Value::Object(arguments) => match self.transform_arguments(arguments) { None => Transformed::Keep, Some(replacement) => Transformed::Replace(Value::Object(replacement)), }, } } fn transform_variable(&mut self, value: &Variable) -> Transformed<Variable> { let _ = value; Transformed::Keep } fn transform_list<F, T>(&mut self, list: &[T], f: F) -> Option<Vec<T>> where F: Fn(&mut Self, &T) -> Transformed<T>, T: Clone, { if list.is_empty() { return None; } let mut result = Vec::new(); let mut has_changes = false; for (index, prev_item) in list.iter().enumerate() { let next_item = f(self, prev_item); match next_item { Transformed::Keep => { if has_changes { result.push(prev_item.clone()); } } Transformed::Delete => { if !has_changes { debug_assert!(result.capacity() == 0); result.reserve(list.len()); result.extend(list.iter().take(index).cloned()); } has_changes = true; } Transformed::Replace(next_item) => { if !has_changes { debug_assert!(result.capacity() == 0); result.reserve(list.len()); result.extend(list.iter().take(index).cloned()); } result.push(next_item); has_changes = true; } } } if has_changes { Some(result) } else { None } } } #[derive(Clone)] pub enum Transformed<T> { Delete, Keep, Replace(T), } impl<T> Transformed<T> { pub fn map<F, U>(self, f: F) -> Transformed<U> where F: FnOnce(T) -> U, { match self { Transformed::Delete => Transformed::Delete, Transformed::Keep => Transformed::Keep, Transformed::Replace(replacement) => Transformed::Replace(f(replacement)), } } }
directives: directives.unwrap_or_else(|| fragment.directives.clone()), selections: selections.unwrap_or_else(|| fragment.selections.clone()), ..fragment.clone() }) }
function_block-function_prefix_line
[ { "content": "pub fn parse(source: &str, file: &str) -> SyntaxResult<Document> {\n\n let parser = Parser::new(source, file);\n\n parser.parse_document()\n\n}\n\n\n", "file_path": "compiler/crates/graphql-syntax/src/lib.rs", "rank": 0, "score": 324088.214504415 }, { "content": "pub fn p...
Rust
crush/src/soc/bdd/differential/post_processing.rs
Simula-UiB/CRHS
8f3dd34c8b99680188d9314c6897e0c790f5358f
use std::collections::VecDeque; use std::num::NonZeroUsize; use std::ops::Range; use vob::Vob; use crate::soc::bdd::Bdd; use crate::soc::system::System; use super::dependency_finder::DepPathFinder; #[allow(unused_variables, dead_code)] pub struct PostProcessing { soc: System, step: usize, active_area: Range<usize>, } impl PostProcessing{ pub fn new(soc: System, step: usize, active_area: Range<usize>) -> Self { Self { soc, step, active_area } } } #[allow(unused_variables, dead_code)] pub struct ASolution { lhs: Vec<Vob>, rhs: Vec<bool>, } impl Bdd { pub fn extract_an_lsb_path(&self, active_area: &Range<usize>, step: usize) -> Vec<(Vob, bool)> { let top = active_area.start; let (arena, _) = self.ensure_level_is_in_arena(&top, &active_area, step); let (lsb, _) = arena.lowest_lsb_in_level(&top); let mut candidate_nodes = arena.nodes_with_lsb_at_level(&top, lsb); let mut path: VecDeque<bool> = VecDeque::with_capacity(self.get_levels_size()); let start_node = candidate_nodes.pop().unwrap().0; let mut deps = DepPathFinder::new(start_node, top, NonZeroUsize::new(step).unwrap(), &self); let mut root_lsb = lsb; let second_last = active_area.end - (step*2); for root_depth in (top..=second_last).step_by(step) { for (id, sub_path) in deps.iter() { let mut traversed_ones = false; for edge in sub_path.iter() { traversed_ones |= edge; } if traversed_ones { let shifted_lsb = root_lsb - 1; if arena.node_lsb(&(root_depth + step), id) == shifted_lsb { root_lsb = shifted_lsb; path.extend(sub_path); deps = DepPathFinder::new(*id, root_depth+step, NonZeroUsize::new(step).unwrap(), &self); break; } } else { if arena.node_lsb(&(root_depth + step), id) == root_lsb { path.extend(sub_path); deps = DepPathFinder::new(*id, root_depth+step, NonZeroUsize::new(step).unwrap(), &self); break; } } } } let mut trivial_root = None; for (id, sub_path) in deps.iter() { let mut traversed_ones = false; for edge in sub_path.iter() { traversed_ones |= edge; } if !traversed_ones { path.extend(sub_path); trivial_root = Some(id); break; } } if trivial_root.is_some() { } else { let (id, sub_path) = deps.iter().next().expect("Missing dependencies?"); path.extend(sub_path); } #[cfg(debug_assertions)] let control = path.len(); let mut i = top; let mut current_node = start_node; loop { if i == 0 { break; } for parent_node in self.levels[i-1].iter_nodes() { if let Some(e0) = parent_node.1.get_e0() { if e0 == current_node { path.push_front(false); current_node = *parent_node.0; break; } } if let Some(e1) = parent_node.1.get_e1() { if e1 == current_node { path.push_front(true); current_node = *parent_node.0; break; } } } i -= 1; } #[cfg(debug_assertions)] { assert_ne!(control, path.len(), "We were unsuccessful in finding a path from source to start of active area!"); assert_eq!(self.get_levels_size()-1, path.len(), "The path is not of same length as we have levels!"); } self.get_lhs().iter() .zip(path.iter()) .map(|(vob, edge)| (vob.clone(), *edge) ) .collect() } pub fn extract_a_sol(&self, active_area: &Range<usize>, step: usize) -> String { let a_path = self.extract_an_lsb_path(active_area, step); let mut formatted = String::new(); let setup: Vec<(usize, usize)> = a_path.iter() .map(|(lhs, rhs)| { let iter = lhs.iter_set_bits(..); let count = iter.clone().count(); let max_elem_size = iter.last().expect("Encountered an unexpected all zero LHS!") .to_string().chars().count(); (count, max_elem_size) }) .collect(); let elem_size = setup.iter() .map(|(_, max_elem_size)| max_elem_size).max().unwrap(); let max_vars = setup.iter() .map(|(count, _)| count).max().unwrap(); let elem_size = elem_size + 1; let row_len = max_vars * (elem_size + 3) - 3; for (i, (lhs, rhs)) in a_path.iter().enumerate() { if i % step == 0 { formatted.push_str(&format!("{:->r$}\n", "", r = row_len + 3)); } let mut lhs_buff = String::new(); for int in lhs.iter_set_bits(..) { lhs_buff.push_str(&format!("{: >e$} + ", &format!("x{}", int), e = elem_size)); } lhs_buff.pop(); lhs_buff.pop(); lhs_buff.pop(); formatted.push_str(&format!("{: <r$}: {}\n", lhs_buff, *rhs as u8, r = row_len)); } formatted } pub fn stringify_sol_as_hex(&self, active_area: &Range<usize>, step: usize) -> String { let a_path = self.extract_an_lsb_path(active_area, step); let mut lhss = Vec::new(); let mut rhss = Vec::new(); for (lhs, rhs) in a_path.iter() { let lhs_int = lhs.iter_set_bits(..).next().unwrap(); lhss.push(lhs_int); rhss.push(*rhs); } let rhs_bytes = Self::bools_to_u8(&rhss); let s = Bdd::u8s_to_hex_separated(&rhs_bytes); s } fn u8s_to_hex_separated(bytes: &[u8] ) -> String { let bytes_rev: Vec<u8> = bytes.into_iter().rev().cloned().collect(); let mut s = String::new(); for four_bytes in bytes_rev.chunks(4) { println!("Four bytes: {:?}", four_bytes); for byte in four_bytes.iter(){ s.push_str(&format!("{:0>2x}", byte)); } s.push_str(" "); } s.pop(); s } fn bools_to_u8(bits: &Vec<bool>) -> Vec<u8>{ let b = bits.chunks(8) .map(|v| { v.iter().enumerate() .fold(0u8, |acc, (idx, x)| { acc | ((*x as u8) << idx)} ) }) .collect(); println!("As vec of u8: {:?}", &b); b } } #[cfg(test)] mod test { use super::*; #[test] fn test_bool_to_hex() { let bools = vec![ false, true, true, false, false, false, false, false, false, false, false, true, false, false, false, false, false, false, false, false, false, true, false, false, false, false, false]; let expected_u8s = vec![6, 8, 32, 0]; assert_eq!(expected_u8s, Bdd::bools_to_u8(&bools)); println!("Passed first assert."); let expected_hex = "00200806".to_owned(); assert_eq!(expected_hex, Bdd::u8s_to_hex_separated(&expected_u8s)); } }
use std::collections::VecDeque; use std::num::NonZeroUsize; use std::ops::Range; use vob::Vob; use crate::soc::bdd::Bdd; use crate::soc::system::System; use super::dependency_finder::DepPathFinder; #[allow(unused_variables, dead_code)] pub struct PostProcessing { soc: System, step: usize, active_area: Range<usize>, } impl PostProcessing{ pub fn new(soc: System, step: usize, active_area: Range<usize>) -> Self { Self { soc, step, active_area } } } #[allow(unused_variables, dead_code)] pub struct ASolution { lhs: Vec<Vob>, rhs: Vec<bool>, } impl Bdd { pub fn extract_an_lsb_path(&self, active_area: &Range<usize>, step: usize) -> Vec<(Vob, bool)> { let top = active_area.start; let (arena, _) = self.ensure_level_is_in_arena(&top, &active_area, step); let (lsb, _) = arena.lowest_lsb_in_level(&top); let mut candidate_nodes = arena.nodes_with_lsb_at_level(&top, lsb); let mut path: VecDeque<bool> = VecDeque::with_capacity(self.get_levels_size()); let start_node = candidate_nodes.pop().unwrap().0; let mut deps = DepPathFinder::new(start_node, top, NonZeroUsize::new(step).unwrap(), &self); let mut root_lsb = lsb; let second_last = active_area.end - (step*2); for root_depth in (top..=second_last).step_by(step) { for (id, sub_path) in deps.iter() { let mut traversed_ones = false; for edge in sub_path.iter() { traversed_ones |= edge; } if traversed_ones { let shifted_lsb = root_lsb - 1; if arena.node_lsb(&(root_depth + step), id) == shifted_lsb { root_lsb = shifted_lsb; path.extend(sub_path); deps = DepPathFinder::new(*id, root_depth+step, NonZeroUsize::new(step).unwrap(), &self); break; } } else { if arena.node_lsb(&(root_depth + step), id) == root_lsb { path.extend(sub_path); deps = DepPathFinder::new(*id, root_depth+step, NonZeroUsize::new(step).unwrap(), &self); break; } } } } let mut trivial_root = None; for (id, sub_path) in deps.iter() { let mut traversed_ones = false; for edge in sub_path.iter() { traversed_ones |= edge; } if !traversed_ones { path.extend(sub_path); trivial_root = Some(id); break; } } if trivial_root.is_some() { } else { let (id, sub_path) = deps.iter().next().expect("Missing dependencies?"); path.extend(sub_path); } #[cfg(debug_assertions)] let control = path.len(); let mut i = top; let mut current_node = start_node; loop { if i == 0 { break; } for parent_node in self.levels[i-1].iter_nodes() { if let Some(e0) = parent_node.1.get_e0() { if e0 == current_node { path.push_front(false); current_node = *parent_node.0; break; } } if let Some(e1) = parent_node.1.get_e1() { if e1 == current_node { path.push_front(true); current_node = *parent_node.0; break; } } } i -= 1; } #[cfg(debug_assertions)] { assert_ne!(control, path.len(), "We were unsuccessful in finding a path from source to start of active area!"); assert_eq!(self.get_levels_size()-1, path.len(), "The path is not of same length as we have levels!"); } self.get_lhs().iter() .zip(path.iter()) .map(|(vob, edge)| (vob.clone(), *edge) ) .collect() } pub fn extract_a_sol(&self, active_area: &Range<usize>, step: usize) -> String { let a_path = self.extract_an_lsb_path(active_area, step); let mut formatted = String::new(); let setup: Vec<(usize, usize)> = a_path.iter() .map(|(lhs, rhs)| { let iter = lhs.iter_set_bits(..); let count = iter.clone().count(); let max_elem_size = iter.last().expect("Encountered an unexpected all zero LHS!") .to_string().chars().count(); (count, max_elem_size) }) .collect(); let elem_size = setup.iter() .map(|(_, max_elem_size)| max_elem_size).max().unwrap(); let max_vars = setup.iter() .map(|(count, _)| count).max().unwrap(); let elem_size = elem_size + 1; let row_len = max_vars * (elem_size + 3) - 3; for (i, (lhs, rhs)) in a_path.iter().enumerate() { if i % step == 0 { formatted.push_str(&format!("{:->r$}\n", "", r = row_len + 3)); } let mut lhs_buff = String::new(); for int in lhs.iter_set_bits(..) { lhs_buff.push_str(&format!("{: >e$} + ", &format!("x{}", int), e = elem_size)); } lhs_buff.pop(); lhs_buff.pop(); lhs_buff.pop(); formatted.push_str(&format!("{: <r$}: {}\n", lhs_buff, *rhs as u8, r = row_len)); } formatted } pub fn stringify_sol_as_hex(&self, active_area: &Range<usize>, step: usize) -> String { let a_path = self.extract_an_lsb_path(active_area, step); let mut lhss = Vec::new(); let mut rhss = Vec::new(); for (lhs, rhs) in a_path.iter() { let lhs_int = lhs.iter_set_bits(..).next().unwrap(); lhss.push(lhs_int); rhss.push(*rhs); } let rhs_bytes = Self::bools_to_u8(&rhss); let s = Bdd::u8s_to_hex_separated(&rhs_bytes); s }
fn bools_to_u8(bits: &Vec<bool>) -> Vec<u8>{ let b = bits.chunks(8) .map(|v| { v.iter().enumerate() .fold(0u8, |acc, (idx, x)| { acc | ((*x as u8) << idx)} ) }) .collect(); println!("As vec of u8: {:?}", &b); b } } #[cfg(test)] mod test { use super::*; #[test] fn test_bool_to_hex() { let bools = vec![ false, true, true, false, false, false, false, false, false, false, false, true, false, false, false, false, false, false, false, false, false, true, false, false, false, false, false]; let expected_u8s = vec![6, 8, 32, 0]; assert_eq!(expected_u8s, Bdd::bools_to_u8(&bools)); println!("Passed first assert."); let expected_hex = "00200806".to_owned(); assert_eq!(expected_hex, Bdd::u8s_to_hex_separated(&expected_u8s)); } }
fn u8s_to_hex_separated(bytes: &[u8] ) -> String { let bytes_rev: Vec<u8> = bytes.into_iter().rev().cloned().collect(); let mut s = String::new(); for four_bytes in bytes_rev.chunks(4) { println!("Four bytes: {:?}", four_bytes); for byte in four_bytes.iter(){ s.push_str(&format!("{:0>2x}", byte)); } s.push_str(" "); } s.pop(); s }
function_block-full_function
[ { "content": "/// From a `BddSpec` and a `nvar` build a `Bdd` following the specifications.\n\n/// \n\n/// We create an empty `Bdd`, set its `id` according to the spec then create all the levels\n\n/// (removing the `-1` from the `lhs` beforehand) without connecting the nodes.\n\n/// \n\n/// Once all the level ...
Rust
examples/aes/ta/src/main.rs
mathias-arm/rust-optee-trustzone-sdk
a1954b8a95dd77e396fb86e21dea2dec3fa5d9a4
#![no_main] use optee_utee::{ ta_close_session, ta_create, ta_destroy, ta_invoke_command, ta_open_session, trace_println, }; use optee_utee::{AlgorithmId, Cipher, OperationMode}; use optee_utee::{AttributeId, AttributeMemref, TransientObject, TransientObjectType}; use optee_utee::{Error, ErrorKind, Parameters, Result}; use proto::{Algo, Command, KeySize, Mode}; use std::boxed::Box; pub struct AesCipher { pub key_size: usize, pub cipher: Cipher, pub key_object: TransientObject, } impl Default for AesCipher { fn default() -> Self { Self { key_size: 0, cipher: Cipher::null(), key_object: TransientObject::null_object(), } } } #[ta_create] fn create() -> Result<()> { trace_println!("[+] TA create"); Ok(()) } #[ta_open_session] fn open_session(_params: &mut Parameters, _sess_ctx: &mut AesCipher) -> Result<()> { trace_println!("[+] TA open session"); Ok(()) } #[ta_close_session] fn close_session(_sess_ctx: &mut AesCipher) { trace_println!("[+] TA close session"); } #[ta_destroy] fn destroy() { trace_println!("[+] TA destory"); } #[ta_invoke_command] fn invoke_command(sess_ctx: &mut AesCipher, cmd_id: u32, params: &mut Parameters) -> Result<()> { trace_println!("[+] TA invoke command"); match Command::from(cmd_id) { Command::Prepare => { return alloc_resources(sess_ctx, params); } Command::SetKey => { return set_aes_key(sess_ctx, params); } Command::SetIV => { return reset_aes_iv(sess_ctx, params); } Command::Cipher => { return cipher_buffer(sess_ctx, params); } _ => { return Err(Error::new(ErrorKind::BadParameters)); } } } pub fn ta2tee_algo_id(algo_id: u32) -> Result<AlgorithmId> { match Algo::from(algo_id) { Algo::ECB => Ok(AlgorithmId::AesEcbNopad), Algo::CBC => Ok(AlgorithmId::AesCbcNopad), Algo::CTR => Ok(AlgorithmId::AesCtr), _ => Err(Error::new(ErrorKind::BadParameters)), } } pub fn ta2tee_key_size(key_sz: u32) -> Result<usize> { match KeySize::from(key_sz) { KeySize::Bit128 | KeySize::Bit256 => Ok(key_sz as usize), _ => Err(Error::new(ErrorKind::BadParameters)), } } pub fn ta2tee_mode_id(mode: u32) -> Result<OperationMode> { match Mode::from(mode) { Mode::Encode => Ok(OperationMode::Encrypt), Mode::Decode => Ok(OperationMode::Decrypt), _ => Err(Error::new(ErrorKind::BadParameters)), } } pub fn alloc_resources(aes: &mut AesCipher, params: &mut Parameters) -> Result<()> { let algo_value = unsafe { params.0.as_value().unwrap().a() }; let key_size_value = unsafe { params.1.as_value().unwrap().a() }; let mode_id_value = unsafe { params.2.as_value().unwrap().a() }; aes.key_size = ta2tee_key_size(key_size_value).unwrap(); aes.cipher = Cipher::allocate( ta2tee_algo_id(algo_value).unwrap(), ta2tee_mode_id(mode_id_value).unwrap(), aes.key_size * 8, ) .unwrap(); aes.key_object = TransientObject::allocate(TransientObjectType::Aes, aes.key_size * 8).unwrap(); let key = vec![0u8; aes.key_size as usize]; let attr = AttributeMemref::from_ref(AttributeId::SecretValue, &key); aes.key_object.populate(&[attr.into()])?; aes.cipher.set_key(&aes.key_object)?; Ok(()) } pub fn set_aes_key(aes: &mut AesCipher, params: &mut Parameters) -> Result<()> { let mut param0 = unsafe { params.0.as_memref().unwrap() }; let key = param0.buffer(); if key.len() != aes.key_size { trace_println!("[+] Get wrong key size !\n"); return Err(Error::new(ErrorKind::BadParameters)); } let attr = AttributeMemref::from_ref(AttributeId::SecretValue, &key); aes.key_object.reset(); aes.key_object.populate(&[attr.into()])?; aes.cipher.set_key(&aes.key_object)?; Ok(()) } pub fn reset_aes_iv(aes: &mut AesCipher, params: &mut Parameters) -> Result<()> { let mut param0 = unsafe { params.0.as_memref().unwrap() }; let iv = param0.buffer(); aes.cipher.init(iv); trace_println!("[+] TA initial vectore reset done!"); Ok(()) } pub fn cipher_buffer(aes: &mut AesCipher, params: &mut Parameters) -> Result<()> { let mut param0 = unsafe { params.0.as_memref().unwrap() }; let mut param1 = unsafe { params.1.as_memref().unwrap() }; let input = param0.buffer(); let output = param1.buffer(); if output.len() < input.len() { return Err(Error::new(ErrorKind::BadParameters)); } trace_println!("[+] TA tries to update ciphers!"); let tmp_size = aes.cipher.update(input, output).unwrap(); param1.set_updated_size(tmp_size); Ok(()) } const TA_FLAGS: u32 = 0; const TA_STACK_SIZE: u32 = 2 * 1024; const TA_DATA_SIZE: u32 = 1 * 1024 * 1024; const TA_VERSION: &[u8] = b"Undefined version\0"; const TA_DESCRIPTION: &[u8] = b"This is an AES example\0"; const EXT_PROP_VALUE_1: &[u8] = b"AES TA\0"; const EXT_PROP_VALUE_2: u32 = 0x0010; const TRACE_LEVEL: i32 = 4; const TRACE_EXT_PREFIX: &[u8] = b"TA\0"; const TA_FRAMEWORK_STACK_SIZE: u32 = 2048; include!(concat!(env!("OUT_DIR"), "/user_ta_header.rs"));
#![no_main] use optee_utee::{ ta_close_session, ta_create, ta_destroy, ta_invoke_command, ta_open_session, trace_println, }; use optee_utee::{AlgorithmId, Cipher, OperationMode}; use optee_utee::{AttributeId, AttributeMemref, TransientObject, TransientObjectType}; use optee_utee::{Error, ErrorKind, Parameters, Result}; use proto::{Algo, Command, KeySize, Mode}; use std::boxed::Box; pub struct AesCipher { pub key_size: usize, pub cipher: Cipher, pub key_object: TransientObject, } impl Default for AesCipher { fn default() -> Self { Self { key_size: 0, cipher: Cipher::null(), key_object: TransientObject::null_object(), } } } #[ta_create] fn create() -> Result<()> { trace_println!("[+] TA create"); Ok(()) } #[ta_open_session] fn open_session(_params: &mut Parameters, _sess_ctx: &mut AesCipher) -> Result<()> { trace_println!("[+] TA open session"); Ok(()) } #[ta_close_session] fn close_session(_sess_ctx: &mut AesCipher) { trace_println!("[+] TA close session"); } #[ta_destroy] fn destroy() { trace_println!("[+] TA destory"); } #[ta_invoke_command] fn invoke_command(sess_ctx: &mut AesCipher, cmd_id: u32, params: &mut Parameters) -> Result<()> { trace_println!("[+] TA invoke command"); match Command::from(cmd_id) { Command::Prepare => { return alloc_resources(sess_ctx, params); } Command::SetKey => { return set_aes_key(sess_ctx, params); } Command::SetIV => { return reset_aes_iv(sess_ctx, params); } Command::Cipher => { return cipher_buffer(sess_ctx, params); } _ => { return Err(Error::new(ErrorKind::BadParameters)); } } } pub fn ta2tee_algo_id(algo_id: u32) -> Result<AlgorithmId> { match Algo::from(algo_id) { Algo::ECB => Ok(AlgorithmId::AesEcbNopad), Algo::CBC => Ok(AlgorithmId::AesCbcNopad), Algo::CTR => Ok(AlgorithmId::AesCtr), _ => Err(Error::new(ErrorKind::BadParameters)), } } pub fn ta2tee_key_size(key_sz: u32) -> Result<usize> { match KeySize::from(key_sz) { KeySize::Bit128 | KeySize::Bit256 => Ok(key_sz as usize), _ => Err(Error::new(ErrorKind::BadParameters)), } } pub fn ta2tee_mode_id(mode: u32) -> Result<OperationMode> { match Mode::from(mode) { Mode::Encode => Ok(OperationMode::Encrypt), Mode::Decode => Ok(OperationMode::Decrypt), _ => Err(Error::new(ErrorKind::BadParameters)), } } pub fn alloc_resources(aes: &mut AesCipher, params: &mut Parameters) -> Result<()> { let algo_value = unsafe { params.0.as_value().unwrap().a() }; let key_size_value = unsafe { params.1.as_value().unwrap().a() }; let mode_id_value = unsafe { params.2.as_value().unwrap().a() }; aes.key_size = ta2tee_key_size(key_size_value).unwrap(); aes.cipher = Cipher::allocate( ta2tee_algo_id(algo_value).unwrap(), ta2tee_mode_id(mode_id_value).unwrap(), aes.key_size * 8, ) .unwrap(); aes.key_object = TransientObject::allocate(TransientObjectType::Aes, aes.key_size * 8).unwrap(); let key = vec![0u8; aes.key_size as usize]; let attr = AttributeMemref::from_ref(AttributeId::SecretValue, &key); aes.key_object.populate(&[attr.into()])?; aes.cipher.set_key(&aes.key_object)?; Ok(()) } pub fn set_aes_key(aes: &mut AesCipher, params: &mut Parameters) -> Result<()> { let mut param0 = unsafe { params.0.as_memref().unwrap() }; let key = param0.buffer(); if key.len() != aes.key_size { trace_println!("[+] Get wrong key size !\n"); return Err(Error::new(ErrorKind::BadParameters)); } let attr = AttributeMemref::from_ref(AttributeId::SecretValue, &key); aes.key_object.reset(); aes.key_object.populate(&[attr.into()])?; aes.cipher.set_key(&aes.key_object)?; Ok(()) } pub fn reset_aes_iv(aes: &mut AesCipher, params: &mut Parameters) -> Result<()> { let mut param0 = unsafe { params.0.as_memref().unwrap() }; let iv = param0.buffer(); aes.cipher.init(iv); trace_println!("[+] TA initial vectore reset done!"); Ok(()) }
const TA_FLAGS: u32 = 0; const TA_STACK_SIZE: u32 = 2 * 1024; const TA_DATA_SIZE: u32 = 1 * 1024 * 1024; const TA_VERSION: &[u8] = b"Undefined version\0"; const TA_DESCRIPTION: &[u8] = b"This is an AES example\0"; const EXT_PROP_VALUE_1: &[u8] = b"AES TA\0"; const EXT_PROP_VALUE_2: u32 = 0x0010; const TRACE_LEVEL: i32 = 4; const TRACE_EXT_PREFIX: &[u8] = b"TA\0"; const TA_FRAMEWORK_STACK_SIZE: u32 = 2048; include!(concat!(env!("OUT_DIR"), "/user_ta_header.rs"));
pub fn cipher_buffer(aes: &mut AesCipher, params: &mut Parameters) -> Result<()> { let mut param0 = unsafe { params.0.as_memref().unwrap() }; let mut param1 = unsafe { params.1.as_memref().unwrap() }; let input = param0.buffer(); let output = param1.buffer(); if output.len() < input.len() { return Err(Error::new(ErrorKind::BadParameters)); } trace_println!("[+] TA tries to update ciphers!"); let tmp_size = aes.cipher.update(input, output).unwrap(); param1.set_updated_size(tmp_size); Ok(()) }
function_block-full_function
[ { "content": "#[ta_invoke_command]\n\nfn invoke_command(sess_ctx: &mut RsaCipher, cmd_id: u32, params: &mut Parameters) -> Result<()> {\n\n trace_println!(\"[+] TA invoke command\");\n\n match Command::from(cmd_id) {\n\n Command::GenKey => gen_key(sess_ctx, params),\n\n Command::GetSize => g...
Rust
crates/prost/tests/src/build.rs
Zha0Chan/crates-sgx
73dc6d9e130757d9e585ee757b3d94d5078512a9
#[macro_use] extern crate cfg_if; cfg_if! { if #[cfg(feature = "edition-2015")] { extern crate env_logger; extern crate prost_build; } } use std::env; use std::fs; use std::path::PathBuf; fn main() { env_logger::init(); let src = PathBuf::from("../tests/src"); let includes = &[src.clone()]; let mut config = prost_build::Config::new(); config.btree_map(&["."]); config.type_attribute("Foo.Bar_Baz.Foo_barBaz", "#[derive(Eq, PartialOrd, Ord)]"); config.type_attribute( "Foo.Bar_Baz.Foo_barBaz.fuzz_buster", "#[derive(Eq, PartialOrd, Ord)]", ); config.type_attribute("Foo.Custom.Attrs.Msg", "#[allow(missing_docs)]"); config.type_attribute("Foo.Custom.Attrs.Msg.field", "/// Oneof docs"); config.type_attribute("Foo.Custom.Attrs.AnEnum", "#[allow(missing_docs)]"); config.type_attribute("Foo.Custom.Attrs.AnotherEnum", "/// Oneof docs"); config.type_attribute( "Foo.Custom.OneOfAttrs.Msg.field", "#[derive(Eq, PartialOrd, Ord)]", ); config.field_attribute("Foo.Custom.Attrs.AnotherEnum.C", "/// The C docs"); config.field_attribute("Foo.Custom.Attrs.AnotherEnum.D", "/// The D docs"); config.field_attribute("Foo.Custom.Attrs.Msg.field.a", "/// Oneof A docs"); config.field_attribute("Foo.Custom.Attrs.Msg.field.b", "/// Oneof B docs"); config .compile_protos(&[src.join("ident_conversion.proto")], includes) .unwrap(); config .compile_protos(&[src.join("nesting.proto")], includes) .unwrap(); config .compile_protos(&[src.join("recursive_oneof.proto")], includes) .unwrap(); config .compile_protos(&[src.join("custom_attributes.proto")], includes) .unwrap(); config .compile_protos(&[src.join("oneof_attributes.proto")], includes) .unwrap(); config .compile_protos(&[src.join("no_unused_results.proto")], includes) .unwrap(); config .compile_protos(&[src.join("default_enum_value.proto")], includes) .unwrap(); config .compile_protos(&[src.join("groups.proto")], includes) .unwrap(); config .compile_protos(&[src.join("deprecated_field.proto")], includes) .unwrap(); config .compile_protos(&[src.join("well_known_types.proto")], includes) .unwrap(); config .compile_protos( &[src.join("packages/widget_factory.proto")], &[src.join("packages")], ) .unwrap(); config .compile_protos(&[src.join("no_package.proto")], includes) .err() .unwrap(); let out_dir = &PathBuf::from(env::var("OUT_DIR").expect("OUT_DIR environment variable not set")) .join("extern_paths"); fs::create_dir_all(out_dir).expect("failed to create prefix directory"); config.out_dir(out_dir); cfg_if! { if #[cfg(feature = "edition-2015")] { const EXTERN_PATH: &str = "::packages::gizmo"; } else { const EXTERN_PATH: &str = "crate::packages::gizmo"; } }; config.extern_path(".packages.gizmo", EXTERN_PATH); config .compile_protos( &[src.join("packages").join("widget_factory.proto")], &[src.join("packages")], ) .unwrap(); }
#[macro_use] extern crate cfg_if; cfg_if! { if #[cfg(feature = "edition-2015")] { extern crate env_logger; extern crate prost_build; } } use std::env; use std::fs; use std::path::PathBuf;
fn main() { env_logger::init(); let src = PathBuf::from("../tests/src"); let includes = &[src.clone()]; let mut config = prost_build::Config::new(); config.btree_map(&["."]); config.type_attribute("Foo.Bar_Baz.Foo_barBaz", "#[derive(Eq, PartialOrd, Ord)]"); config.type_attribute( "Foo.Bar_Baz.Foo_barBaz.fuzz_buster", "#[derive(Eq, PartialOrd, Ord)]", ); config.type_attribute("Foo.Custom.Attrs.Msg", "#[allow(missing_docs)]"); config.type_attribute("Foo.Custom.Attrs.Msg.field", "/// Oneof docs"); config.type_attribute("Foo.Custom.Attrs.AnEnum", "#[allow(missing_docs)]"); config.type_attribute("Foo.Custom.Attrs.AnotherEnum", "/// Oneof docs"); config.type_attribute( "Foo.Custom.OneOfAttrs.Msg.field", "#[derive(Eq, PartialOrd, Ord)]", ); config.field_attribute("Foo.Custom.Attrs.AnotherEnum.C", "/// The C docs"); config.field_attribute("Foo.Custom.Attrs.AnotherEnum.D", "/// The D docs"); config.field_attribute("Foo.Custom.Attrs.Msg.field.a", "/// Oneof A docs"); config.field_attribute("Foo.Custom.Attrs.Msg.field.b", "/// Oneof B docs"); config .compile_protos(&[src.join("ident_conversion.proto")], includes) .unwrap(); config .compile_protos(&[src.join("nesting.proto")], includes) .unwrap(); config .compile_protos(&[src.join("recursive_oneof.proto")], includes) .unwrap(); config .compile_protos(&[src.join("custom_attributes.proto")], includes) .unwrap(); config .compile_protos(&[src.join("oneof_attributes.proto")], includes) .unwrap(); config .compile_protos(&[src.join("no_unused_results.proto")], includes) .unwrap(); config .compile_protos(&[src.join("default_enum_value.proto")], includes) .unwrap(); config .compile_protos(&[src.join("groups.proto")], includes) .unwrap(); config .compile_protos(&[src.join("deprecated_field.proto")], includes) .unwrap(); config .compile_protos(&[src.join("well_known_types.proto")], includes) .unwrap(); config .compile_protos( &[src.join("packages/widget_factory.proto")], &[src.join("packages")], ) .unwrap(); config .compile_protos(&[src.join("no_package.proto")], includes) .err() .unwrap(); let out_dir = &PathBuf::from(env::var("OUT_DIR").expect("OUT_DIR environment variable not set")) .join("extern_paths"); fs::create_dir_all(out_dir).expect("failed to create prefix directory"); config.out_dir(out_dir); cfg_if! { if #[cfg(feature = "edition-2015")] { const EXTERN_PATH: &str = "::packages::gizmo"; } else { const EXTERN_PATH: &str = "crate::packages::gizmo"; } }; config.extern_path(".packages.gizmo", EXTERN_PATH); config .compile_protos( &[src.join("packages").join("widget_factory.proto")], &[src.join("packages")], ) .unwrap(); }
function_block-full_function
[]
Rust
src/double/div.rs
pwnorbitals/qd
2e4b3234d80adc90199bfd6496778e81568318a3
use crate::common::primitive as p; use crate::common::utils as u; use crate::double::Double; use std::ops::{Div, DivAssign}; #[inline] fn mul_f64(a: Double, b: f64) -> Double { let (p, e) = p::two_prod(a.0, b); let (a, b) = u::renorm2(p, e + a.1 * b); Double(a, b) } #[allow(clippy::suspicious_arithmetic_impl)] impl Div for Double { type Output = Double; fn div(self, other: Double) -> Double { match self.pre_div(&other) { Some(r) => r, None => { let q1 = self.0 / other.0; let mut r = self - mul_f64(other, q1); let q2 = r.0 / other.0; r -= mul_f64(other, q2); let q3 = r.0 / other.0; let (a, b) = u::renorm3(q1, q2, q3); Double(a, b) } } } } impl Div for &Double { type Output = Double; fn div(self, other: &Double) -> Double { (*self).div(*other) } } impl Div<&Double> for Double { type Output = Double; #[inline] fn div(self, other: &Double) -> Double { self.div(*other) } } impl Div<Double> for &Double { type Output = Double; #[inline] fn div(self, other: Double) -> Double { (*self).div(other) } } impl DivAssign for Double { #[inline] fn div_assign(&mut self, other: Double) { let r = self.div(other); self.0 = r.0; self.1 = r.1; } } impl DivAssign<&Double> for Double { #[inline] fn div_assign(&mut self, other: &Double) { let r = self.div(*other); self.0 = r.0; self.1 = r.1; } } impl Double { #[inline] fn pre_div(&self, other: &Double) -> Option<Double> { if self.is_nan() || other.is_nan() { Some(Double::NAN) } else if other.is_zero() { if self.is_zero() { Some(Double::NAN) } else if self.is_sign_negative() == other.is_sign_positive() { Some(Double::NEG_INFINITY) } else { Some(Double::INFINITY) } } else if self.is_infinite() { if other.is_infinite() { Some(Double::NAN) } else if self.is_sign_positive() == other.is_sign_positive() { Some(Double::INFINITY) } else { Some(Double::NEG_INFINITY) } } else if other.is_infinite() { if self.is_sign_positive() == other.is_sign_positive() { Some(Double::ZERO) } else { Some(Double::NEG_ZERO) } } else { None } } } #[cfg(test)] mod tests { use super::*; test_all_near!( num_num: dd!("1.1557273497909217179100931833126961"), Double::PI / Double::E; num_ref: dd!("1.1557273497909217179100931833126961"), Double::PI / &Double::E; ref_num: dd!("1.1557273497909217179100931833126961"), &Double::PI / Double::E; ref_ref: dd!("1.1557273497909217179100931833126961"), &Double::PI / &Double::E; num_neg_num: dd!("-1.1557273497909217179100931833126961"), Double::PI / -Double::E; num_neg_ref: dd!("-1.1557273497909217179100931833126961"), Double::PI / -&Double::E; ref_neg_num: dd!("-1.1557273497909217179100931833126961"), &Double::PI / -Double::E; ref_neg_ref: dd!("-1.1557273497909217179100931833126961"), &Double::PI / -&Double::E; num_id: Double::PI, Double::PI / Double::ONE; id_num: Double::FRAC_1_PI, Double::ONE / Double::PI; num_small: dd!("3141592653589793238462643383279.5039"), Double::PI / dd!("1e-30"); small_num: dd!("3.1830988618379067153776752674502853e-31"), dd!("1e-30") / Double::PI; three_nums: dd!("1.6673621161631071223063639072253465"), Double::PI / Double::E / Double::LN_2; lassoc: dd!("1.6673621161631071223063639072253465"), (Double::PI / Double::E) / Double::LN_2; rassoc: dd!("12.320232213560921976987672083576714"), Double::PI / (Double::LN_2 / Double::E); ); test_all_exact!( zero_inf: Double::ZERO, Double::ZERO / Double::INFINITY; zero_neg_inf: Double::NEG_ZERO, Double::ZERO / Double::NEG_INFINITY; inf_zero: Double::INFINITY, Double::INFINITY / Double::ZERO; neg_inf_zero: Double::NEG_INFINITY, Double::NEG_INFINITY / Double::ZERO; nan_zero: Double::NAN, Double::NAN / Double::ZERO; zero_nan: Double::NAN, Double::ZERO / Double::NAN; zero_zero: Double::NAN, Double::ZERO / Double::ZERO; one_inf: Double::ZERO, Double::ONE / Double::INFINITY; one_neg_inf: Double::NEG_ZERO, Double::ONE / Double::NEG_INFINITY; inf_one: Double::INFINITY, Double::INFINITY / Double::ONE; neg_inf_one: Double::NEG_INFINITY, Double::NEG_INFINITY / Double::ONE; inf_inf: Double::NAN, Double::INFINITY / Double::INFINITY; inf_neg_inf: Double::NAN, Double::INFINITY / Double::NEG_INFINITY; neg_inf_inf: Double::NAN, Double::NEG_INFINITY / Double::INFINITY; neg_inf_neg_inf: Double::NAN, Double::NEG_INFINITY / Double::NEG_INFINITY; one_zero: Double::INFINITY, Double::ONE / Double::ZERO; neg_one_zero: Double::NEG_INFINITY, Double::NEG_ONE / Double::ZERO; nan_one: Double::NAN, Double::NAN / Double::ONE; one_nan: Double::NAN, Double::ONE / Double::NAN; ); test_all!( assign_num: { let mut a = Double::PI; a /= Double::E; near!(dd!("1.1557273497909217179100931833126961"), a); } assign_ref: { let mut b = Double::PI; b /= &Double::E; near!(dd!("1.1557273497909217179100931833126961"), b); } ); test!(chain_tens: { let mut value = Double::LN_2; let ten = dd!(10); near!("6.9314718055994530941723212145818e-1", value); value /= ten; near!("6.9314718055994530941723212145818e-2", value); value /= ten; near!("6.9314718055994530941723212145818e-3", value); value /= ten; near!("6.9314718055994530941723212145818e-4", value); value /= ten; near!("6.9314718055994530941723212145818e-5", value); value /= ten; near!("6.9314718055994530941723212145818e-6", value); value /= ten; near!("6.9314718055994530941723212145818e-7", value); value /= ten; near!("6.9314718055994530941723212145818e-8", value); value /= ten; near!("6.9314718055994530941723212145818e-9", value); value /= ten; near!("6.9314718055994530941723212145818e-10", value); value /= ten; near!("6.9314718055994530941723212145818e-11", value); value /= ten; near!("6.9314718055994530941723212145818e-12", value); value /= ten; near!("6.9314718055994530941723212145818e-13", value); value /= ten; near!("6.9314718055994530941723212145818e-14", value); value /= ten; near!("6.9314718055994530941723212145818e-15", value); value /= ten; near!("6.9314718055994530941723212145818e-16", value); value /= ten; near!("6.9314718055994530941723212145818e-17", value); value /= ten; near!("6.9314718055994530941723212145818e-18", value); value /= ten; near!("6.9314718055994530941723212145818e-19", value); value /= ten; near!("6.9314718055994530941723212145818e-20", value); value /= ten; near!("6.9314718055994530941723212145818e-21", value); value /= ten; near!("6.9314718055994530941723212145818e-22", value); value /= ten; near!("6.9314718055994530941723212145818e-23", value); value /= ten; near!("6.9314718055994530941723212145818e-24", value); value /= ten; near!("6.9314718055994530941723212145818e-25", value); value /= ten; near!("6.9314718055994530941723212145818e-26", value); value /= ten; near!("6.9314718055994530941723212145818e-27", value); value /= ten; near!("6.9314718055994530941723212145818e-28", value); value /= ten; near!("6.9314718055994530941723212145818e-29", value); value /= ten; near!("6.9314718055994530941723212145818e-30", value); }); }
use crate::common::primitive as p; use crate::common::utils as u; use crate::double::Double; use std::ops::{Div, DivAssign}; #[inline] fn mul_f64(a: Double, b: f64) -> Double { let (p, e) = p::two_prod(a.0, b); let (a, b) = u::renorm2(p, e + a.1 * b); Double(a, b) } #[allow(clippy::suspicious_arithmetic_impl)] impl Div for Double { type Output = Double; fn div(self, other: Double) -> Double { match self.pre_div(&other) { Some(r) => r,
} impl Div for &Double { type Output = Double; fn div(self, other: &Double) -> Double { (*self).div(*other) } } impl Div<&Double> for Double { type Output = Double; #[inline] fn div(self, other: &Double) -> Double { self.div(*other) } } impl Div<Double> for &Double { type Output = Double; #[inline] fn div(self, other: Double) -> Double { (*self).div(other) } } impl DivAssign for Double { #[inline] fn div_assign(&mut self, other: Double) { let r = self.div(other); self.0 = r.0; self.1 = r.1; } } impl DivAssign<&Double> for Double { #[inline] fn div_assign(&mut self, other: &Double) { let r = self.div(*other); self.0 = r.0; self.1 = r.1; } } impl Double { #[inline] fn pre_div(&self, other: &Double) -> Option<Double> { if self.is_nan() || other.is_nan() { Some(Double::NAN) } else if other.is_zero() { if self.is_zero() { Some(Double::NAN) } else if self.is_sign_negative() == other.is_sign_positive() { Some(Double::NEG_INFINITY) } else { Some(Double::INFINITY) } } else if self.is_infinite() { if other.is_infinite() { Some(Double::NAN) } else if self.is_sign_positive() == other.is_sign_positive() { Some(Double::INFINITY) } else { Some(Double::NEG_INFINITY) } } else if other.is_infinite() { if self.is_sign_positive() == other.is_sign_positive() { Some(Double::ZERO) } else { Some(Double::NEG_ZERO) } } else { None } } } #[cfg(test)] mod tests { use super::*; test_all_near!( num_num: dd!("1.1557273497909217179100931833126961"), Double::PI / Double::E; num_ref: dd!("1.1557273497909217179100931833126961"), Double::PI / &Double::E; ref_num: dd!("1.1557273497909217179100931833126961"), &Double::PI / Double::E; ref_ref: dd!("1.1557273497909217179100931833126961"), &Double::PI / &Double::E; num_neg_num: dd!("-1.1557273497909217179100931833126961"), Double::PI / -Double::E; num_neg_ref: dd!("-1.1557273497909217179100931833126961"), Double::PI / -&Double::E; ref_neg_num: dd!("-1.1557273497909217179100931833126961"), &Double::PI / -Double::E; ref_neg_ref: dd!("-1.1557273497909217179100931833126961"), &Double::PI / -&Double::E; num_id: Double::PI, Double::PI / Double::ONE; id_num: Double::FRAC_1_PI, Double::ONE / Double::PI; num_small: dd!("3141592653589793238462643383279.5039"), Double::PI / dd!("1e-30"); small_num: dd!("3.1830988618379067153776752674502853e-31"), dd!("1e-30") / Double::PI; three_nums: dd!("1.6673621161631071223063639072253465"), Double::PI / Double::E / Double::LN_2; lassoc: dd!("1.6673621161631071223063639072253465"), (Double::PI / Double::E) / Double::LN_2; rassoc: dd!("12.320232213560921976987672083576714"), Double::PI / (Double::LN_2 / Double::E); ); test_all_exact!( zero_inf: Double::ZERO, Double::ZERO / Double::INFINITY; zero_neg_inf: Double::NEG_ZERO, Double::ZERO / Double::NEG_INFINITY; inf_zero: Double::INFINITY, Double::INFINITY / Double::ZERO; neg_inf_zero: Double::NEG_INFINITY, Double::NEG_INFINITY / Double::ZERO; nan_zero: Double::NAN, Double::NAN / Double::ZERO; zero_nan: Double::NAN, Double::ZERO / Double::NAN; zero_zero: Double::NAN, Double::ZERO / Double::ZERO; one_inf: Double::ZERO, Double::ONE / Double::INFINITY; one_neg_inf: Double::NEG_ZERO, Double::ONE / Double::NEG_INFINITY; inf_one: Double::INFINITY, Double::INFINITY / Double::ONE; neg_inf_one: Double::NEG_INFINITY, Double::NEG_INFINITY / Double::ONE; inf_inf: Double::NAN, Double::INFINITY / Double::INFINITY; inf_neg_inf: Double::NAN, Double::INFINITY / Double::NEG_INFINITY; neg_inf_inf: Double::NAN, Double::NEG_INFINITY / Double::INFINITY; neg_inf_neg_inf: Double::NAN, Double::NEG_INFINITY / Double::NEG_INFINITY; one_zero: Double::INFINITY, Double::ONE / Double::ZERO; neg_one_zero: Double::NEG_INFINITY, Double::NEG_ONE / Double::ZERO; nan_one: Double::NAN, Double::NAN / Double::ONE; one_nan: Double::NAN, Double::ONE / Double::NAN; ); test_all!( assign_num: { let mut a = Double::PI; a /= Double::E; near!(dd!("1.1557273497909217179100931833126961"), a); } assign_ref: { let mut b = Double::PI; b /= &Double::E; near!(dd!("1.1557273497909217179100931833126961"), b); } ); test!(chain_tens: { let mut value = Double::LN_2; let ten = dd!(10); near!("6.9314718055994530941723212145818e-1", value); value /= ten; near!("6.9314718055994530941723212145818e-2", value); value /= ten; near!("6.9314718055994530941723212145818e-3", value); value /= ten; near!("6.9314718055994530941723212145818e-4", value); value /= ten; near!("6.9314718055994530941723212145818e-5", value); value /= ten; near!("6.9314718055994530941723212145818e-6", value); value /= ten; near!("6.9314718055994530941723212145818e-7", value); value /= ten; near!("6.9314718055994530941723212145818e-8", value); value /= ten; near!("6.9314718055994530941723212145818e-9", value); value /= ten; near!("6.9314718055994530941723212145818e-10", value); value /= ten; near!("6.9314718055994530941723212145818e-11", value); value /= ten; near!("6.9314718055994530941723212145818e-12", value); value /= ten; near!("6.9314718055994530941723212145818e-13", value); value /= ten; near!("6.9314718055994530941723212145818e-14", value); value /= ten; near!("6.9314718055994530941723212145818e-15", value); value /= ten; near!("6.9314718055994530941723212145818e-16", value); value /= ten; near!("6.9314718055994530941723212145818e-17", value); value /= ten; near!("6.9314718055994530941723212145818e-18", value); value /= ten; near!("6.9314718055994530941723212145818e-19", value); value /= ten; near!("6.9314718055994530941723212145818e-20", value); value /= ten; near!("6.9314718055994530941723212145818e-21", value); value /= ten; near!("6.9314718055994530941723212145818e-22", value); value /= ten; near!("6.9314718055994530941723212145818e-23", value); value /= ten; near!("6.9314718055994530941723212145818e-24", value); value /= ten; near!("6.9314718055994530941723212145818e-25", value); value /= ten; near!("6.9314718055994530941723212145818e-26", value); value /= ten; near!("6.9314718055994530941723212145818e-27", value); value /= ten; near!("6.9314718055994530941723212145818e-28", value); value /= ten; near!("6.9314718055994530941723212145818e-29", value); value /= ten; near!("6.9314718055994530941723212145818e-30", value); }); }
None => { let q1 = self.0 / other.0; let mut r = self - mul_f64(other, q1); let q2 = r.0 / other.0; r -= mul_f64(other, q2); let q3 = r.0 / other.0; let (a, b) = u::renorm3(q1, q2, q3); Double(a, b) } } }
function_block-function_prefix_line
[ { "content": "#[inline]\n\nfn mul_f64(a: Quad, b: f64) -> Quad {\n\n let (h0, l0) = p::two_prod(a.0, b);\n\n let (h1, l1) = p::two_prod(a.1, b);\n\n let (h2, l2) = p::two_prod(a.2, b);\n\n let h3 = a.3 * b;\n\n\n\n let s0 = h0;\n\n let (s1, t0) = p::two_sum(h1, l0);\n\n let (s2, t1, t2) = u...
Rust
rs/orchestrator/src/error.rs
Deland-Labs/ic
047172b01e0afc0e61448669d4ec98b2425c6853
use ic_http_utils::file_downloader::FileDownloadError; use ic_types::replica_version::ReplicaVersionParseError; use ic_types::{registry::RegistryClientError, NodeId, RegistryVersion, ReplicaVersion, SubnetId}; use std::error::Error; use std::fmt; use std::io; use std::path::{Path, PathBuf}; use std::process::Command; pub type OrchestratorResult<T> = Result<T, OrchestratorError>; #[derive(Debug)] #[allow(clippy::enum_variant_names)] pub enum OrchestratorError { NodeUnassignedError(NodeId, RegistryVersion), SubnetMissingError(SubnetId, RegistryVersion), RegistryClientError(RegistryClientError), MakeRegistryCupError(SubnetId, RegistryVersion), ReplicaVersionMissingError(ReplicaVersion, RegistryVersion), ReplicaVersionParseError(ReplicaVersionParseError), IoError(String, io::Error), FileDownloadError(FileDownloadError), ExecError(PathBuf, exec::Error), InvalidConfigurationError(String), UpgradeError(String), } impl OrchestratorError { pub(crate) fn file_write_error(file_path: &Path, e: io::Error) -> Self { OrchestratorError::IoError(format!("Failed to write to file: {:?}", file_path), e) } pub(crate) fn dir_create_error(dir: &Path, e: io::Error) -> Self { OrchestratorError::IoError(format!("Failed to create dir: {:?}", dir), e) } pub(crate) fn invalid_configuration_error(msg: impl ToString) -> Self { OrchestratorError::InvalidConfigurationError(msg.to_string()) } pub(crate) fn file_command_error(e: io::Error, cmd: &Command) -> Self { OrchestratorError::IoError(format!("Failed to executing command: {:?}", cmd), e) } } impl fmt::Display for OrchestratorError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { OrchestratorError::NodeUnassignedError(node_id, registry_version) => write!( f, "Node {:?} is not found in any subnet at registry version {:?}", node_id, registry_version ), OrchestratorError::RegistryClientError(e) => write!(f, "{:?}", e), OrchestratorError::ReplicaVersionMissingError(replica_version, registry_version) => { write!( f, "Replica version {} was not found in the Registry at registry version {:?}", replica_version, registry_version ) } OrchestratorError::IoError(msg, e) => { write!(f, "IO error, message: {:?}, error: {:?}", msg, e) } OrchestratorError::FileDownloadError(e) => write!(f, "File download error: {:?}", e), OrchestratorError::ExecError(path, e) => write!( f, "Failed to exec new Orchestrator process: {:?}, error: {:?}", path, e ), OrchestratorError::InvalidConfigurationError(msg) => { write!(f, "Invalid configuration: {}", msg) } OrchestratorError::SubnetMissingError(subnet_id, registry_version) => write!( f, "Subnet ID {:?} does not exist in the Registry at registry version {:?}", subnet_id, registry_version ), OrchestratorError::ReplicaVersionParseError(e) => { write!(f, "Failed to parse replica version: {}", e) } OrchestratorError::MakeRegistryCupError(subnet_id, registry_version) => write!( f, "Failed to construct the genesis/recovery CUP, subnet_id: {}, registry_version: {}", subnet_id, registry_version, ), OrchestratorError::UpgradeError(msg) => write!(f, "Failed to upgrade: {}", msg), } } } impl From<FileDownloadError> for OrchestratorError { fn from(e: FileDownloadError) -> Self { OrchestratorError::FileDownloadError(e) } } impl Error for OrchestratorError {}
use ic_http_utils::file_downloader::FileDownloadError; use ic_types::replica_version::ReplicaVersionParseError; use ic_types::{registry::RegistryClientError, NodeId, RegistryVersion, ReplicaVersion, SubnetId}; use std::error::Error; use std::fmt; use std::io; use std::path::{Path, PathBuf}; use std::process::Command; pub type OrchestratorResult<T> = Result<T, OrchestratorError>; #[derive(Debug)] #[allow(clippy::enum_variant_names)] pub enum OrchestratorError { NodeUnassignedError(NodeId, RegistryVersion), SubnetMissingError(SubnetId, RegistryVersion), RegistryClientError(RegistryClientError), MakeRegistryCupError(SubnetId, RegistryVersion), ReplicaVersionMissingError(ReplicaVersion, RegistryVersion), ReplicaVersionParseError(ReplicaVersionParseError), IoError(String, io::Error), FileDownloadError(FileDownloadError), ExecError(PathBuf, exec::Error), InvalidConfigurationError(String), UpgradeError(String), } impl OrchestratorError { pub(crate) fn file_write_error(file_path: &Path, e: io::Error) -> Self { OrchestratorError::IoError(format!("Failed to write to file: {:?}", file_path), e) } pub(crate) fn dir_create_error(dir: &Path, e: io::Error) -> Self { OrchestratorError::IoError(format!("Failed to create dir: {:?}", dir), e) } pub(crate) fn invalid_configuration_error(msg: impl ToString) -> Self { OrchestratorError::InvalidConfigurationError(msg.to_string()) } pub(crate) fn file_command_error(e: io::Error, cmd: &Command) -> Self { OrchestratorError::IoError(format!("Failed to executing command: {:?}", cmd), e) } } impl fmt::Display for OrchestratorError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { OrchestratorError::NodeUnassignedError(node_id, registry_version) => write!( f, "Node {:?} is not found in any subnet at registry version {:?}", node_id, registry_version ), OrchestratorError::RegistryClientError(e) => write!(f, "{:?}", e), OrchestratorError::ReplicaVersionMissingError(replica_version, registry_version) => { write!( f, "Replica version {} was not found in the Registry at registry version {:?}", replica_version, registry_version ) } OrchestratorError::IoError(msg, e) => { write!(f, "IO error, message: {:?}, error: {:?}", msg, e) } OrchestratorError::FileDownloadError(e) => write!(f, "File download error: {:?}", e), OrchestratorError::ExecError(path, e) => write!( f, "Failed to exec new Orchestrator process: {:?}, error: {:?}", path, e ), OrchestratorError::InvalidConfigurationError(msg) => { write!(f, "Invalid configuration: {}", msg) } OrchestratorError::SubnetMissingError(subnet_id, registry_version) => write!( f, "Subnet ID {:?} does not exist in the Registry at registry version {:?}", subnet_id, registry_version ),
} impl From<FileDownloadError> for OrchestratorError { fn from(e: FileDownloadError) -> Self { OrchestratorError::FileDownloadError(e) } } impl Error for OrchestratorError {}
OrchestratorError::ReplicaVersionParseError(e) => { write!(f, "Failed to parse replica version: {}", e) } OrchestratorError::MakeRegistryCupError(subnet_id, registry_version) => write!( f, "Failed to construct the genesis/recovery CUP, subnet_id: {}, registry_version: {}", subnet_id, registry_version, ), OrchestratorError::UpgradeError(msg) => write!(f, "Failed to upgrade: {}", msg), } }
function_block-function_prefix_line
[ { "content": "fn some_checkpoint_dir(backup_dir: &Path, subnet_id: &SubnetId) -> Option<PathBuf> {\n\n let dir = backup_dir\n\n .join(\"data\")\n\n .join(subnet_id.to_string())\n\n .join(\"ic_state\");\n\n if !dir.exists() {\n\n return None;\n\n }\n\n let lcp = last_check...
Rust
core/src/avm2/object/dictionary_object.rs
threeoh6000/ruffle
7df5370ec1b9519f30df9a67cfafe8b41db6b116
use crate::avm2::activation::Activation; use crate::avm2::object::script_object::ScriptObjectData; use crate::avm2::object::{ClassObject, Object, ObjectPtr, TObject}; use crate::avm2::value::Value; use crate::avm2::Error; use fnv::FnvHashMap; use gc_arena::{Collect, GcCell, MutationContext}; use std::cell::{Ref, RefMut}; pub fn dictionary_allocator<'gc>( class: ClassObject<'gc>, proto: Object<'gc>, activation: &mut Activation<'_, 'gc, '_>, ) -> Result<Object<'gc>, Error> { let base = ScriptObjectData::base_new(Some(proto), Some(class)); Ok(DictionaryObject(GcCell::allocate( activation.context.gc_context, DictionaryObjectData { base, object_space: Default::default(), }, )) .into()) } #[derive(Clone, Collect, Debug, Copy)] #[collect(no_drop)] pub struct DictionaryObject<'gc>(GcCell<'gc, DictionaryObjectData<'gc>>); #[derive(Clone, Collect, Debug)] #[collect(no_drop)] pub struct DictionaryObjectData<'gc> { base: ScriptObjectData<'gc>, object_space: FnvHashMap<Object<'gc>, Value<'gc>>, } impl<'gc> DictionaryObject<'gc> { pub fn get_property_by_object(self, name: Object<'gc>) -> Value<'gc> { self.0 .read() .object_space .get(&name) .cloned() .unwrap_or(Value::Undefined) } pub fn set_property_by_object( self, name: Object<'gc>, value: Value<'gc>, mc: MutationContext<'gc, '_>, ) { self.0.write(mc).object_space.insert(name, value); } pub fn delete_property_by_object(self, name: Object<'gc>, mc: MutationContext<'gc, '_>) { self.0.write(mc).object_space.remove(&name); } pub fn has_property_by_object(self, name: Object<'gc>) -> bool { self.0.read().object_space.get(&name).is_some() } } impl<'gc> TObject<'gc> for DictionaryObject<'gc> { fn base(&self) -> Ref<ScriptObjectData<'gc>> { Ref::map(self.0.read(), |read| &read.base) } fn base_mut(&self, mc: MutationContext<'gc, '_>) -> RefMut<ScriptObjectData<'gc>> { RefMut::map(self.0.write(mc), |write| &mut write.base) } fn as_ptr(&self) -> *const ObjectPtr { self.0.as_ptr() as *const ObjectPtr } fn value_of(&self, _mc: MutationContext<'gc, '_>) -> Result<Value<'gc>, Error> { Ok(Object::from(*self).into()) } fn as_dictionary_object(self) -> Option<DictionaryObject<'gc>> { Some(self) } fn get_next_enumerant( self, last_index: u32, _activation: &mut Activation<'_, 'gc, '_>, ) -> Result<Option<u32>, Error> { let read = self.0.read(); let last_enumerant = read.base.get_last_enumerant(); let object_space_length = read.object_space.keys().len() as u32; if last_index < last_enumerant + object_space_length { Ok(Some(last_index.saturating_add(1))) } else { Ok(None) } } fn get_enumerant_name( self, index: u32, _activation: &mut Activation<'_, 'gc, '_>, ) -> Result<Value<'gc>, Error> { let read = self.0.read(); let last_enumerant = read.base.get_last_enumerant(); if index < last_enumerant { Ok(read .base .get_enumerant_name(index) .unwrap_or(Value::Undefined)) } else { let object_space_index = index.saturating_sub(last_enumerant); Ok(read .object_space .keys() .nth(object_space_index as usize) .cloned() .map(|v| v.into()) .unwrap_or(Value::Undefined)) } } }
use crate::avm2::activation::Activation; use crate::avm2::object::script_object::ScriptObjectData; use crate::avm2::object::{ClassObject, Object, ObjectPtr, TObject}; use crate::avm2::value::Value; use crate::avm2::Error; use fnv::FnvHashMap; use gc_arena::{Collect, GcCell, MutationContext}; use std::cell::{Ref, RefMut}; pub fn dictionary_allocator<'gc>( class: ClassObject<'gc>, proto: Object<'gc>, activation: &mut Activation<'_, 'gc, '_>, ) -> Result<Object<'gc>, Error> { let base = ScriptObjectData::base_new(Some(proto), Some(class)); Ok(DictionaryObject(GcCell::allocate( activation.context.gc_context, DictionaryObjectData { base, object_space: Default::default(), }, )) .into()) } #[derive(Clone, Collect, Debug, Copy)] #[collect(no_drop)] pub struct DictionaryObject<'gc>(GcCell<'gc, DictionaryObjectData<'gc>>); #[derive(Clone, Collect, Debug)] #[collect(no_drop)] pub struct DictionaryObjectData<'gc> { base: ScriptObjectData<'gc>, object_space: FnvHashMap<Object<'gc>, Value<'gc>>, } impl<'gc> DictionaryObject<'gc> { pub fn get_property_by_object(self, name: Object<'gc>) -> Value<'gc> { self.
pub fn set_property_by_object( self, name: Object<'gc>, value: Value<'gc>, mc: MutationContext<'gc, '_>, ) { self.0.write(mc).object_space.insert(name, value); } pub fn delete_property_by_object(self, name: Object<'gc>, mc: MutationContext<'gc, '_>) { self.0.write(mc).object_space.remove(&name); } pub fn has_property_by_object(self, name: Object<'gc>) -> bool { self.0.read().object_space.get(&name).is_some() } } impl<'gc> TObject<'gc> for DictionaryObject<'gc> { fn base(&self) -> Ref<ScriptObjectData<'gc>> { Ref::map(self.0.read(), |read| &read.base) } fn base_mut(&self, mc: MutationContext<'gc, '_>) -> RefMut<ScriptObjectData<'gc>> { RefMut::map(self.0.write(mc), |write| &mut write.base) } fn as_ptr(&self) -> *const ObjectPtr { self.0.as_ptr() as *const ObjectPtr } fn value_of(&self, _mc: MutationContext<'gc, '_>) -> Result<Value<'gc>, Error> { Ok(Object::from(*self).into()) } fn as_dictionary_object(self) -> Option<DictionaryObject<'gc>> { Some(self) } fn get_next_enumerant( self, last_index: u32, _activation: &mut Activation<'_, 'gc, '_>, ) -> Result<Option<u32>, Error> { let read = self.0.read(); let last_enumerant = read.base.get_last_enumerant(); let object_space_length = read.object_space.keys().len() as u32; if last_index < last_enumerant + object_space_length { Ok(Some(last_index.saturating_add(1))) } else { Ok(None) } } fn get_enumerant_name( self, index: u32, _activation: &mut Activation<'_, 'gc, '_>, ) -> Result<Value<'gc>, Error> { let read = self.0.read(); let last_enumerant = read.base.get_last_enumerant(); if index < last_enumerant { Ok(read .base .get_enumerant_name(index) .unwrap_or(Value::Undefined)) } else { let object_space_index = index.saturating_sub(last_enumerant); Ok(read .object_space .keys() .nth(object_space_index as usize) .cloned() .map(|v| v.into()) .unwrap_or(Value::Undefined)) } } }
0 .read() .object_space .get(&name) .cloned() .unwrap_or(Value::Undefined) }
function_block-function_prefixed
[ { "content": "pub fn root_error_handler<'gc>(activation: &mut Activation<'_, 'gc, '_>, error: Error<'gc>) {\n\n match &error {\n\n Error::ThrownValue(value) => {\n\n let message = value\n\n .coerce_to_string(activation)\n\n .unwrap_or_else(|_| \"undefined\".int...
Rust
src/stage/ast/mod.rs
ncatelli/mossy
25211cc1e871dfe8d06d0a04d23271a321870fdc
macro_rules! generate_type_specifier { (integer, $sign:expr, $width:expr) => { $crate::stage::ast::Type::Integer($sign, $width) }; (char) => { generate_type_specifier!(i8) }; (ptr => $ty:expr) => { $crate::stage::ast::Type::Pointer(Box::new($ty)) }; (i8) => { generate_type_specifier!( integer, $crate::stage::ast::Signed::Signed, $crate::stage::ast::IntegerWidth::Eight ) }; (u8) => { generate_type_specifier!( integer, $crate::stage::ast::Signed::Unsigned, $crate::stage::ast::IntegerWidth::Eight ) }; (i16) => { generate_type_specifier!( integer, $crate::stage::ast::Signed::Signed, $crate::stage::ast::IntegerWidth::Sixteen ) }; (i32) => { generate_type_specifier!( integer, $crate::stage::ast::Signed::Signed, $crate::stage::ast::IntegerWidth::ThirtyTwo ) }; (u32) => { generate_type_specifier!( integer, $crate::stage::ast::Signed::Unsigned, $crate::stage::ast::IntegerWidth::ThirtyTwo ) }; (i64) => { generate_type_specifier!( integer, $crate::stage::ast::Signed::Signed, $crate::stage::ast::IntegerWidth::SixtyFour ) }; (u64) => { generate_type_specifier!( integer, $crate::stage::ast::Signed::Unsigned, $crate::stage::ast::IntegerWidth::SixtyFour ) }; } #[derive(Debug)] pub struct TypedProgram { pub defs: Vec<TypedGlobalDecls>, } impl TypedProgram { pub fn new(defs: Vec<TypedGlobalDecls>) -> Self { Self { defs } } } #[derive(PartialEq, Debug, Clone)] pub struct TypedFunctionDeclaration { pub id: String, pub block: TypedCompoundStmts, } impl TypedFunctionDeclaration { pub fn new(id: String, block: TypedCompoundStmts) -> Self { Self { id, block } } } #[derive(PartialEq, Debug, Clone)] pub enum TypedGlobalDecls { Func(TypedFunctionDeclaration), Var(Declaration), } #[derive(PartialEq, Debug, Clone)] pub struct TypedCompoundStmts { inner: Vec<TypedStmtNode>, } impl TypedCompoundStmts { pub fn new(inner: Vec<TypedStmtNode>) -> Self { Self { inner } } } impl From<TypedCompoundStmts> for Vec<TypedStmtNode> { fn from(src: TypedCompoundStmts) -> Self { src.inner } } #[derive(PartialEq, Debug, Clone)] pub enum Declaration { Scalar(Type, Vec<String>), Array { ty: Type, id: String, size: usize }, } #[derive(PartialEq, Debug, Clone)] pub enum TypedStmtNode { Declaration(Declaration), Return(Type, String, Option<TypedExprNode>), Expression(TypedExprNode), If( TypedExprNode, TypedCompoundStmts, Option<TypedCompoundStmts>, ), While(TypedExprNode, TypedCompoundStmts), For( Box<TypedStmtNode>, TypedExprNode, Box<TypedStmtNode>, TypedCompoundStmts, ), } #[derive(PartialEq, Debug, Clone)] pub enum TypedExprNode { Primary(Type, Primary), FunctionCall(Type, String, Option<Box<TypedExprNode>>), IdentifierAssignment(Type, String, Box<TypedExprNode>), DerefAssignment(Type, Box<TypedExprNode>, Box<TypedExprNode>), Equal(Type, Box<TypedExprNode>, Box<TypedExprNode>), NotEqual(Type, Box<TypedExprNode>, Box<TypedExprNode>), LessThan(Type, Box<TypedExprNode>, Box<TypedExprNode>), GreaterThan(Type, Box<TypedExprNode>, Box<TypedExprNode>), LessEqual(Type, Box<TypedExprNode>, Box<TypedExprNode>), GreaterEqual(Type, Box<TypedExprNode>, Box<TypedExprNode>), Addition(Type, Box<TypedExprNode>, Box<TypedExprNode>), Subtraction(Type, Box<TypedExprNode>, Box<TypedExprNode>), Division(Type, Box<TypedExprNode>, Box<TypedExprNode>), Modulo(Type, Box<TypedExprNode>, Box<TypedExprNode>), Multiplication(Type, Box<TypedExprNode>, Box<TypedExprNode>), LogicalNot(Type, Box<TypedExprNode>), Negate(Type, Box<TypedExprNode>), Invert(Type, Box<TypedExprNode>), Ref(Type, String), Deref(Type, Box<TypedExprNode>), ScaleBy(Type, Box<TypedExprNode>), Grouping(Type, Box<TypedExprNode>), } impl Typed for TypedExprNode { fn r#type(&self) -> Type { match self { TypedExprNode::Primary(ty, _) | TypedExprNode::FunctionCall(ty, _, _) | TypedExprNode::IdentifierAssignment(ty, _, _) | TypedExprNode::DerefAssignment(ty, _, _) | TypedExprNode::Equal(ty, _, _) | TypedExprNode::NotEqual(ty, _, _) | TypedExprNode::LessThan(ty, _, _) | TypedExprNode::GreaterThan(ty, _, _) | TypedExprNode::LessEqual(ty, _, _) | TypedExprNode::GreaterEqual(ty, _, _) | TypedExprNode::Addition(ty, _, _) | TypedExprNode::Subtraction(ty, _, _) | TypedExprNode::Division(ty, _, _) | TypedExprNode::Multiplication(ty, _, _) | TypedExprNode::Modulo(ty, _, _) | TypedExprNode::LogicalNot(ty, _) | TypedExprNode::Negate(ty, _) | TypedExprNode::Invert(ty, _) | TypedExprNode::Ref(ty, _) | TypedExprNode::Deref(ty, _) | TypedExprNode::ScaleBy(ty, _) | TypedExprNode::Grouping(ty, _) => ty.clone(), } } } #[derive(PartialEq, Debug, Clone)] pub enum Primary { Integer { sign: Signed, width: IntegerWidth, value: [u8; 8], }, Identifier(Type, String), Str(Vec<u8>), } impl Typed for Primary { fn r#type(&self) -> Type { match self { Primary::Integer { sign, width, value: _, } => Type::Integer(*sign, *width), Primary::Identifier(ty, _) => ty.clone(), Primary::Str(_) => generate_type_specifier!(ptr => generate_type_specifier!(char)), } } } pub trait ByteSized { fn size(&self) -> usize; } pub trait Typed { fn r#type(&self) -> Type; } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Signed { Signed, Unsigned, } #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd)] pub enum IntegerWidth { Eight, Sixteen, ThirtyTwo, SixtyFour, } impl ByteSized for IntegerWidth { fn size(&self) -> usize { match self { Self::Eight => 1, Self::Sixteen => 2, Self::ThirtyTwo => 4, Self::SixtyFour => 8, } } } #[derive(Debug, Clone, PartialEq, Eq)] pub struct FuncProto { pub return_type: Box<Type>, pub args: Vec<Type>, } impl FuncProto { pub fn new(return_type: Box<Type>, args: Vec<Type>) -> Self { Self { return_type, args } } } const POINTER_BYTE_WIDTH: usize = (usize::BITS / 8) as usize; #[derive(Debug, Clone, PartialEq, Eq)] pub enum Type { Integer(Signed, IntegerWidth), Void, Func(FuncProto), Pointer(Box<Type>), } impl ByteSized for Type { fn size(&self) -> usize { match self { Self::Integer(_, iw) => iw.size(), Self::Void => 0, Self::Func { .. } => POINTER_BYTE_WIDTH, Self::Pointer(_) => POINTER_BYTE_WIDTH, } } } impl Type { pub fn pointer_to(&self) -> Self { Self::Pointer(Box::new(self.clone())) } pub fn value_at(&self) -> Option<Self> { match self { Type::Pointer(ty) => Some(*(ty.clone())), _ => None, } } }
macro_rules! generate_type_specifier { (integer, $sign:expr, $width:expr) => { $crate::stage::ast::Type::Integer($sign, $width) }; (char) => { generate_type_specifier!(i8) }; (ptr => $ty:expr) => { $crate::stage::ast::Type::Pointer(Box::new($ty)) }; (i8) => { generate_type_specifier!( integer, $crate::stage::ast::Signed::Signed, $crate::stage::ast::IntegerWidth::Eight ) }; (u8) => { generate_type_specifier!( integer, $crate::stage::ast::Signed::Unsigned, $crate::stage::ast::IntegerWidth::Eight ) }; (i16) => { generate_type_specifier!( integer, $crate::stage::ast::Signed::Signed, $crate::stage::ast::IntegerWidth::Sixteen ) }; (i32) => { generate_type_specifier!( integer, $crate::stage::ast::Signed::Signed, $crate::stage::ast::IntegerWidth::ThirtyTwo ) }; (u32) => { generate_type_specifier!( integer, $crate::stage::ast::Signed::Unsigned, $crate::stage::ast::IntegerWidth::ThirtyTwo ) }; (i64) => { generate_type_specifier!( integer, $crate::stage::ast::Signed::Signed, $crate::stage::ast::IntegerWidth::SixtyFour ) }; (u64) => { generate_type_specifier!( integer, $crate::stage::ast::Signed::Unsigned, $crate::stage::ast::IntegerWidth::SixtyFour ) }; } #[derive(Debug)] pub struct TypedProgram { pub defs: Vec<TypedGlobalDecls>, } impl TypedProgram { pub fn new(defs: Vec<TypedGlobalDecls>) -> Self { Self { defs } } } #[derive(PartialEq, Debug, Clone)] pub struct TypedFunctionDeclaration { pub id: String, pub block: TypedCompoundStmts, } impl TypedFunctionDeclaration { pub fn new(id: String, block: TypedCompoundStmts) -> Self { Self { id, block } } } #[derive(PartialEq, Debug, Clone)] pub enum TypedGlobalDecls { Func(TypedFunctionDeclaration), Var(Declaration), } #[derive(PartialEq, Debug, Clone)] pub struct TypedCompoundStmts { inner: Vec<TypedStmtNode>, } impl TypedCompoundStmts { pub fn new(inner: Vec<TypedStmtNode>) -> Self { Self { inner } } } impl From<TypedCompoundStmts> for Vec<TypedStmtNode> { fn from(src: TypedCompoundStmts) -> Self { src.inner } } #[derive(PartialEq, Debug, Clone)] pub enum Declaration { Scalar(Type, Vec<String>), Array { ty: Type, id: String, size: usize }, } #[derive(PartialEq, Debug, Clone)] pub enum TypedStmtNode { Declaration(Declaration), Return(Type, String, Option<TypedExprNode>), Expression(TypedExprNode), If( TypedExprNode, TypedCompoundStmts, Option<TypedCompoundStmts>, ), While(TypedExprNode, TypedCompoundStmts), For( Box<TypedStmtNode>, TypedExprNode, Box<TypedStmtNode>, TypedCompoundStmts, ), } #[derive(PartialEq, Debug, Clone)] pub enum TypedExprNode { Primary(Type, Primary), FunctionCall(Type, String, Option<Box<TypedExprNode>>), IdentifierAssignment(Type, String, Box<TypedExprNode>), DerefAssignment(Type, Box<TypedExprNode>, Box<TypedExprNode>), Equal(Type, Box<TypedExprNode>, Box<TypedExprNode>), NotEqual(Type, Box<TypedExprNode>, Box<TypedExprNode>), LessThan(Type, Box<TypedExprNode>, Box<TypedExprNode>), GreaterThan(Type, Box<TypedExprNode>, Box<TypedExprNode>), LessEqual(Type, Box<TypedExprNode>, Box<TypedExprNode>), GreaterEqual(Type, Box<TypedExprNode>, Box<TypedExprNode>), Addition(Type, Box<TypedExprNode>, Box<TypedExprNode>), Subtraction(Type, Box<TypedExprNode>, Box<TypedExprNode>), Division(Type, Box<TypedExprNode>, Box<TypedExprNode>), Modulo(Type, Box<TypedExprNode>, Box<TypedExprNode>), Multiplication(Type, Box<TypedExprNode>, Box<TypedExprNode>), LogicalNot(Type, Box<TypedExprNode>), Negate(Type, Box<TypedExprNode>), Invert(Type, Box<TypedExprNode>), Ref(Type, String), Deref(Type, Box<TypedExprNode>), ScaleBy(Type, Box<TypedExprNode>), Grouping(Type, Box<TypedExprNode>), } impl Typed for TypedExprNode { fn r#type(&self) -> Type { match self { TypedExprNode::Primary(ty, _) | TypedExprNode::FunctionCall(ty, _, _) | TypedExprNode::IdentifierAssignment(ty, _, _) | TypedExprNode::DerefAssignment(ty, _, _) | TypedExprNode::Equal(ty, _, _) | TypedExprNode::NotEqual(ty, _, _) | TypedExprNode::LessThan(ty, _, _) | TypedExprNode::GreaterThan(ty, _, _) | TypedExprNode::LessEqual(ty, _, _) | TypedExprNode::GreaterEqual(ty, _, _) | TypedExprNode::Addition(ty, _, _) | TypedExprNode::Subtraction(ty, _, _) | TypedExprNode::Division(ty, _, _) | TypedExprNode::Multiplication(ty, _, _) | TypedExprNode::Modulo(ty, _, _) | TypedExprNode::LogicalNot(ty, _) | TypedExprNode::Negate(ty, _) | TypedExprNode::Invert(ty, _) | TypedExprNode::Ref(ty, _) | TypedExprNode::Deref(ty, _) | TypedExprNode::ScaleBy(ty, _) | TypedExprNode::Grouping(ty, _) => ty.clone(), } } } #[derive(PartialEq, Debug, Clone)] pub enum Primary { Integer { sign: Signed, width: IntegerWidth, value: [u8; 8], }, Identifier(Type, String), Str(Vec<u8>), } impl Typed for Primary { fn r#type(&self) -> Type { match self { Primary::Integer { sign, width, value: _, } => Type::Integer(*sign, *width), Primary::Identifier(ty, _) => ty.clone(), Primary::Str(_) => generate_type_specifier!(ptr => generate_type_specifier!(char)), } } } pub trait ByteSized { fn size(&self) -> usize; } pub trait Typed { fn r#type(&self) -> Type; } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Signed { Signed, Unsigned, } #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd)] pub enum IntegerWidth { Eight, Sixteen, ThirtyTwo, SixtyFour, } impl ByteSized for IntegerWidth {
} #[derive(Debug, Clone, PartialEq, Eq)] pub struct FuncProto { pub return_type: Box<Type>, pub args: Vec<Type>, } impl FuncProto { pub fn new(return_type: Box<Type>, args: Vec<Type>) -> Self { Self { return_type, args } } } const POINTER_BYTE_WIDTH: usize = (usize::BITS / 8) as usize; #[derive(Debug, Clone, PartialEq, Eq)] pub enum Type { Integer(Signed, IntegerWidth), Void, Func(FuncProto), Pointer(Box<Type>), } impl ByteSized for Type { fn size(&self) -> usize { match self { Self::Integer(_, iw) => iw.size(), Self::Void => 0, Self::Func { .. } => POINTER_BYTE_WIDTH, Self::Pointer(_) => POINTER_BYTE_WIDTH, } } } impl Type { pub fn pointer_to(&self) -> Self { Self::Pointer(Box::new(self.clone())) } pub fn value_at(&self) -> Option<Self> { match self { Type::Pointer(ty) => Some(*(ty.clone())), _ => None, } } }
fn size(&self) -> usize { match self { Self::Eight => 1, Self::Sixteen => 2, Self::ThirtyTwo => 4, Self::SixtyFour => 8, } }
function_block-full_function
[ { "content": "fn type_declarator<'a>() -> impl parcel::Parser<'a, &'a [(usize, char)], Type> {\n\n whitespace_wrapped(\n\n parcel::join(\n\n type_specifier(),\n\n whitespace_wrapped(expect_character('*').one_or_more()),\n\n )\n\n .map(|(ty, pointer_depth)| {\n\n ...
Rust
src/fileoperation.rs
DrStiev/rs-handlegfa
89c59bb1e6b0b2aad23061ab894b958467a14ae3
use gfa2::gfa1::GFA; use gfa2::gfa2::GFA2; use handlegraph2::hashgraph::HashGraph; use bstr::BString; use std::fs::File; use std::io::prelude::*; use std::path::Path; pub fn save_as_gfa2_file(graph: &HashGraph, path: Option<String>) -> Result<(), std::io::Error> { use handlegraph2::conversion; let path = path.unwrap_or_else(|| String::from("./tests/output_files/default_path/file_gfa2.gfa2")); let path = Path::new(&path); let mut file = File::create(path)?; let gfa_file: GFA2<BString, ()> = conversion::to_gfa2(&graph); file.write_all(format!("{}", gfa_file).as_bytes())?; file.sync_all()?; Ok(()) } pub fn save_as_gfa1_file(graph: &HashGraph, path: Option<String>) -> Result<(), std::io::Error> { use handlegraph2::conversion; let path = path.unwrap_or_else(|| String::from("./tests/output_files/default_path/file_gfa1.gfa")); let path = Path::new(&path); let mut file = File::create(path)?; let gfa_file: GFA<BString, ()> = conversion::to_gfa(&graph); file.write_all(format!("{}", gfa_file).as_bytes())?; file.sync_all()?; Ok(()) } #[cfg(test)] mod tests { use super::*; use handlegraph2::mutablehandlegraph::*; #[test] fn can_save_handlegraph_as_gfa2_file() { use handlegraph2::{ handle::Edge, hashgraph::HashGraph, mutablehandlegraph::MutableHandleGraph, pathgraph::PathHandleGraph, }; let mut graph = HashGraph::new(); let h1 = graph.create_handle(b"ACCTT", 11); let h2 = graph.create_handle(b"TCAAGG", 12); let h3 = graph.create_handle(b"CTTGATT", 13); graph.apply_orientation(h2.flip()); graph.create_edge(Edge(h1, h2)); graph.create_edge(Edge(h2, h3)); graph.create_edge(Edge(h1, h3)); let path = graph.create_path_handle(b"1", false); graph.append_step(&path, h1); graph.append_step(&path, h2); graph.append_step(&path, h3); match save_as_gfa2_file( &graph, Some(String::from("./tests/output_files/file_gfa2.gfa2")), ) { Ok(_) => println!("Handlegraph saved correctly!"), Err(why) => println!("Error: {}", why), }; } #[test] fn can_save_handlegraph_as_gfa2_file_default_path() { use handlegraph2::{ handle::Edge, hashgraph::HashGraph, mutablehandlegraph::MutableHandleGraph, pathgraph::PathHandleGraph, }; let mut graph = HashGraph::new(); let h1 = graph.create_handle(b"ACCTT", 11); let h2 = graph.create_handle(b"TCAAGG", 12); let h3 = graph.create_handle(b"CTTGATT", 13); graph.apply_orientation(h2.flip()); graph.create_edge(Edge(h1, h2)); graph.create_edge(Edge(h2, h3)); graph.create_edge(Edge(h1, h3)); let path = graph.create_path_handle(b"1", false); graph.append_step(&path, h1); graph.append_step(&path, h2); graph.append_step(&path, h3); match save_as_gfa2_file(&graph, None) { Ok(_) => println!("Handlegraph saved correctly!"), Err(why) => println!("Error: {}", why), }; } #[test] fn can_save_handlegraph_as_gfa1_file() { use handlegraph2::{ handle::Edge, hashgraph::HashGraph, mutablehandlegraph::MutableHandleGraph, pathgraph::PathHandleGraph, }; let mut graph = HashGraph::new(); let h1 = graph.create_handle(b"ACCTT", 11); let h2 = graph.create_handle(b"TCAAGG", 12); let h3 = graph.create_handle(b"CTTGATT", 13); graph.apply_orientation(h2.flip()); graph.create_edge(Edge(h1, h2)); graph.create_edge(Edge(h2, h3)); graph.create_edge(Edge(h1, h3)); let path = graph.create_path_handle(b"1", false); graph.append_step(&path, h1); graph.append_step(&path, h2); graph.append_step(&path, h3); match save_as_gfa1_file( &graph, Some(String::from("./tests/output_files/file_gfa1.gfa")), ) { Ok(_) => println!("Handlegraph saved correctly!"), Err(why) => println!("Error: {}", why), }; } #[test] fn can_save_handlegraph_as_gfa1_file_default_path() { use handlegraph2::{ handle::Edge, hashgraph::HashGraph, mutablehandlegraph::MutableHandleGraph, pathgraph::PathHandleGraph, }; let mut graph = HashGraph::new(); let h1 = graph.create_handle(b"ACCTT", 11); let h2 = graph.create_handle(b"TCAAGG", 12); let h3 = graph.create_handle(b"CTTGATT", 13); graph.apply_orientation(h2.flip()); graph.create_edge(Edge(h1, h2)); graph.create_edge(Edge(h2, h3)); graph.create_edge(Edge(h1, h3)); let path = graph.create_path_handle(b"1", false); graph.append_step(&path, h1); graph.append_step(&path, h2); graph.append_step(&path, h3); match save_as_gfa1_file(&graph, None) { Ok(_) => println!("Handlegraph saved correctly!"), Err(why) => println!("Error: {}", why), }; } #[test] fn can_use_file_gfa2_saved() { use gfa2::{parser_gfa2::GFA2Parser, tag::OptionalFields}; let parser: GFA2Parser<bstr::BString, OptionalFields> = GFA2Parser::new(); let gfa2: GFA2<BString, OptionalFields> = parser .parse_file("./tests/output_files/file_gfa2.gfa2") .unwrap(); println!("{}", gfa2); } #[test] fn can_use_file_gfa1_saved() { use gfa2::{parser_gfa1::GFAParser, tag::OptionalFields}; let parser: GFAParser<bstr::BString, OptionalFields> = GFAParser::new(); let gfa: GFA<BString, OptionalFields> = parser .parse_file("./tests/output_files/file_gfa1.gfa") .unwrap(); println!("{}", gfa); } }
use gfa2::gfa1::GFA; use gfa2::gfa2::GFA2; use handlegraph2::hashgraph::HashGraph; use bstr::BString; use std::fs::File; use std::io::prelude::*; use std::path::Path; pub fn save_as_gfa2_file(graph: &HashGraph, path: Option<String>) -> Result<(), std::io::Error> { use handlegraph2::conversion; let path = path.unwrap_or_else(|| String::from("./tests/output_files/default_path/file_gfa2.gfa2")); let path = Path::new(&path); let mut file = File::create(path)?; let gfa_file: GFA2<BString, ()> = conversion::to_gfa2(&graph); file.write_all(format!("{}", gfa_file).as_bytes())?; file.sync_all()?; Ok(()) } pub fn save_as_gfa1_file(graph: &HashGraph, path: Option<String>) -> Result<(), std::io::Error> { use handlegraph2::conversion; let path = path.unwrap_or_else(|| String::from("./tests/output_files/default_path/file_gfa1.gfa")); let path = Path::new(&path); let mut file = File::create(path)?; let gfa_file: GFA<BString, ()> = conversion::to_gfa(&graph); file.write_all(format!("{}", gfa_file).as_bytes())?; file.sync_all()?; Ok(()) } #[cfg(test)] mod tests { use super::*; use handlegraph2::mutablehandlegraph::*; #[test] fn can_save_handlegraph_as_gfa2_file() { use handlegraph2::{ handle::Edge, hashgraph::HashGraph, mutablehandlegraph::MutableHandleGraph, pathgraph::PathHandleGraph, }; let mut graph = HashGraph::new(); let h1 = graph.create_handle(b"ACCTT", 11); let h2 = graph.create_handle(b"TCAAGG", 12); let h3 = graph.create_handle(b"CTTGATT", 13); graph.apply_orientation(h2.flip()); graph.create_edge(Edge(h1, h2)); graph.create_edge(Edge(h2, h3)); graph.create_edge(Edge(h1, h3)); let path = graph.create_path_handle(b"1", false); graph.append_step(&path, h1); graph.append_step(&path, h2); graph.append_step(&path, h3); match save_as_gfa2_file( &graph, Some(String::from("./tests/output_files/file_gfa2.gfa2")), ) { Ok(_) => println!("Handlegraph saved correctly!"), Err(why) => println!("Error: {}", why), }; } #[test] fn can_save_handlegraph_as_gfa2_file_default_path() { use handlegraph2::{ handle::Edge, hashgraph::HashGraph, mutablehandlegraph::MutableHandleGraph, pathgraph::PathHandleGraph, }; let mut graph = HashGraph::new(); let h1 = graph.create_handle(b"ACCTT", 11); let h2 = graph.create_handle(b"TCAAGG", 12); let h3 = graph.create_handle(b"CTTGATT", 13); graph.apply_orientation(h2.flip()); graph.create_edge(Edge(h1, h2)); graph.create_edge(Edge(h2, h3)); graph.create_edge(Edge(h1, h3)); let path = graph.create_path_handle(b"1", false); graph.append_step(&path, h1); graph.append_step(&path, h2); graph.append_step(&path, h3); match save_as_gfa2_file(&graph, None) { Ok(_) => println!("Handlegraph saved correctly!"), Err(why) => println!("Error: {}", why), }; } #[test] fn can_save_handlegraph_as_gfa1_file() { use handlegraph2::{ handle::Edge, hashgraph::HashGraph, mutablehandlegraph::MutableHandleGraph, pathgraph::PathHandleGraph, }; let mut graph = HashGraph::new(); let h1 = graph.create_handle(b"ACCTT", 11); let h2 = graph.create_handle(b"TCAAGG", 12); let h3 = graph.create_handle(b"CTTGATT", 13); graph.apply_orientation(h2.flip()); graph.create_edge(Edge(h1, h2)); graph.create_edge(Edge(h2, h3)); graph.create_edge(Edge(h1, h3)); let path = graph.create_path_handle(b"1", false); graph.append_step(&path, h1); graph.append_step(&path, h2); graph.append_step(&path, h3); match save_as_gfa1_file( &graph, Some(String::from("./tests/output_files/file_gfa1.gfa")), ) { Ok(_) => println!("Handlegraph saved correctly!"), Err(why) => println!("Error: {}", why), }; } #[test] fn can_save_handlegraph_as_gfa1_file_default_path() { use handlegraph2::{ handle::Edge, hashgraph::HashGraph, mutablehandlegraph::MutableHandleGraph, pathgraph::PathHandleGraph, }; let mut graph = HashGraph::new(); let h1 = graph.create_handle(b"ACCTT", 11); let h2 = graph.create_handle(b"TCAAGG", 12); let h3 =
#[test] fn can_use_file_gfa2_saved() { use gfa2::{parser_gfa2::GFA2Parser, tag::OptionalFields}; let parser: GFA2Parser<bstr::BString, OptionalFields> = GFA2Parser::new(); let gfa2: GFA2<BString, OptionalFields> = parser .parse_file("./tests/output_files/file_gfa2.gfa2") .unwrap(); println!("{}", gfa2); } #[test] fn can_use_file_gfa1_saved() { use gfa2::{parser_gfa1::GFAParser, tag::OptionalFields}; let parser: GFAParser<bstr::BString, OptionalFields> = GFAParser::new(); let gfa: GFA<BString, OptionalFields> = parser .parse_file("./tests/output_files/file_gfa1.gfa") .unwrap(); println!("{}", gfa); } }
graph.create_handle(b"CTTGATT", 13); graph.apply_orientation(h2.flip()); graph.create_edge(Edge(h1, h2)); graph.create_edge(Edge(h2, h3)); graph.create_edge(Edge(h1, h3)); let path = graph.create_path_handle(b"1", false); graph.append_step(&path, h1); graph.append_step(&path, h2); graph.append_step(&path, h3); match save_as_gfa1_file(&graph, None) { Ok(_) => println!("Handlegraph saved correctly!"), Err(why) => println!("Error: {}", why), }; }
function_block-function_prefixed
[ { "content": "/// Function that reads a ```GFA1``` files passed as input and return its\n\n/// corresponding ```HandleGraph```\n\npub fn gfa1_to_handlegraph(path: String) -> Result<HashGraph, GraphOperationError> {\n\n use gfa2::{gfa1::GFA, parser_gfa1::GFAParser};\n\n\n\n let parser: GFAParser<usize, ()>...
Rust
rust/src/checkpoints.rs
rdettai/delta-rs
f1f9782196e3f3420399b44377acd153a3d0d7cf
use arrow::datatypes::Schema as ArrowSchema; use arrow::error::ArrowError; use arrow::json::reader::Decoder; use log::*; use parquet::arrow::ArrowWriter; use parquet::errors::ParquetError; use parquet::file::writer::InMemoryWriteableCursor; use std::convert::TryFrom; use super::action; use super::delta_arrow::delta_log_schema_for_table; use super::open_table_with_version; use super::schema::*; use super::storage; use super::storage::{StorageBackend, StorageError}; use super::{CheckPoint, DeltaTableError, DeltaTableState}; #[derive(thiserror::Error, Debug)] pub enum CheckPointWriterError { #[error("DeltaTableMetadata not present in DeltaTableState")] MissingMetaData, #[error("DeltaTableError: {source}")] DeltaTable { #[from] source: DeltaTableError, }, #[error("Failed to write parquet: {}", .source)] ParquetError { #[from] source: ParquetError, }, #[error("Failed to convert into Arrow schema: {}", .source)] ArrowError { #[from] source: ArrowError, }, #[error("StorageError: {source}")] Storage { #[from] source: StorageError, }, #[error("serde_json::Error: {source}")] JSONSerialization { #[from] source: serde_json::Error, }, } pub struct CheckPointWriter { table_uri: String, delta_log_uri: String, last_checkpoint_uri: String, storage: Box<dyn StorageBackend>, } impl CheckPointWriter { pub fn new(table_uri: &str, storage: Box<dyn StorageBackend>) -> Self { let delta_log_uri = storage.join_path(table_uri, "_delta_log"); let last_checkpoint_uri = storage.join_path(delta_log_uri.as_str(), "_last_checkpoint"); Self { table_uri: table_uri.to_string(), delta_log_uri, last_checkpoint_uri, storage, } } pub fn new_for_table_uri(table_uri: &str) -> Result<Self, CheckPointWriterError> { let storage_backend = storage::get_backend_for_uri(table_uri)?; Ok(Self::new(table_uri, storage_backend)) } pub async fn create_checkpoint_for_version( &self, version: DeltaDataTypeVersion, ) -> Result<(), CheckPointWriterError> { let table = open_table_with_version(self.table_uri.as_str(), version).await?; self.create_checkpoint_from_state(version, table.get_state()) .await } pub async fn create_checkpoint_from_state( &self, version: DeltaDataTypeVersion, state: &DeltaTableState, ) -> Result<(), CheckPointWriterError> { info!("Writing parquet bytes to checkpoint buffer."); let parquet_bytes = self.parquet_bytes_from_state(state)?; let size = parquet_bytes.len() as i64; let checkpoint = CheckPoint::new(version, size, None); let file_name = format!("{:020}.checkpoint.parquet", version); let checkpoint_uri = self.storage.join_path(&self.delta_log_uri, &file_name); info!("Writing checkpoint to {:?}.", checkpoint_uri); self.storage .put_obj(&checkpoint_uri, &parquet_bytes) .await?; let last_checkpoint_content: serde_json::Value = serde_json::to_value(&checkpoint)?; let last_checkpoint_content = serde_json::to_string(&last_checkpoint_content)?; info!( "Writing _last_checkpoint to {:?}.", self.last_checkpoint_uri ); self.storage .put_obj( self.last_checkpoint_uri.as_str(), last_checkpoint_content.as_bytes(), ) .await?; Ok(()) } fn parquet_bytes_from_state( &self, state: &DeltaTableState, ) -> Result<Vec<u8>, CheckPointWriterError> { let current_metadata = state .current_metadata() .ok_or(CheckPointWriterError::MissingMetaData)?; let mut jsons = std::iter::once(action::Action::protocol(action::Protocol { min_reader_version: state.min_reader_version(), min_writer_version: state.min_writer_version(), })) .chain(std::iter::once(action::Action::metaData( action::MetaData::try_from(current_metadata.clone())?, ))) .chain(state.files().iter().map(|f| action::Action::add(f.clone()))) .chain( state .tombstones() .iter() .map(|f| action::Action::remove(f.clone())), ) .chain( state .app_transaction_version() .iter() .map(|(app_id, version)| { action::Action::txn(action::Txn { app_id: app_id.clone(), version: *version, last_updated: None, }) }), ) .map(|a| serde_json::to_value(a).map_err(ArrowError::from)); debug!("Preparing checkpoint parquet buffer."); let arrow_schema = delta_log_schema_for_table( <ArrowSchema as TryFrom<&Schema>>::try_from(&current_metadata.schema)?, current_metadata.partition_columns.as_slice(), ); let writeable_cursor = InMemoryWriteableCursor::default(); let mut writer = ArrowWriter::try_new(writeable_cursor.clone(), arrow_schema.clone(), None)?; debug!("Writing to checkpoint parquet buffer..."); let batch_size = state.app_transaction_version().len() + state.tombstones().len() + state.files().len() + 2; let decoder = Decoder::new(arrow_schema, batch_size, None); while let Some(batch) = decoder.next_batch(&mut jsons)? { writer.write(&batch)?; } let _ = writer.close()?; debug!("Finished writing checkpoint parquet buffer."); Ok(writeable_cursor.data()) } }
use arrow::datatypes::Schema as ArrowSchema; use arrow::error::ArrowError; use arrow::json::reader::Decoder; use log::*; use parquet::arrow::ArrowWriter; use parquet::errors::ParquetError; use parquet::file::writer::InMemoryWriteableCursor; use std::convert::TryFrom; use super::action; use super::delta_arrow::delta_log_schema_for_table; use super::open_table_with_version; use super::schema::*; use super::storage; use super::storage::{StorageBackend, StorageError}; use super::{CheckPoint, DeltaTableError, DeltaTableState}; #[derive(thiserror::Error, Debug)] pub enum CheckPointWriterError { #[error("DeltaTableMetadata not present in DeltaTableState")] MissingMetaData, #[error("DeltaTableError: {source}")] DeltaTable { #[from] source: DeltaTableError, }, #[error("Failed to write parquet: {}", .source)] ParquetError { #[from] source: ParquetError, }, #[error("Failed to convert into Arrow schema: {}", .source)] ArrowError { #[from] source: ArrowError, }, #[error("StorageError: {source}")] Storage { #[from] source: StorageError, }, #[error("serde_json::Error: {source}")] JSONSerialization { #[from] source: serde_json::Error, }, } pub struct CheckPointWriter { table_uri: String, delta_log_uri: String, last_checkpoint_uri: String, storage: Box<dyn StorageBackend>, } impl CheckPointWriter { pub fn new(table_uri: &str, storage: Box<dyn StorageBackend>) -> Self { let delta_log_uri = storage.join_path(table_uri, "_delta_log"); let last_checkpoint_uri = storage.join_path(delta_log_uri.as_str(), "_last_checkpoint"); Self { table_uri: table_uri.to_string(), delta_log_uri, last_checkpoint_uri, storage, } } pub fn new_for_table_uri(table_uri: &str) -> Result<Self, CheckPointWriterError> { let storage_backend = storage::get_backend_for_uri(table_uri)?; Ok(Self::new(table_uri, storage_backend)) } pub async fn create_checkpoint_for_version( &self, version: DeltaDataTypeVersion, ) -> Result<(), CheckPointWriterError> { let table = open_table_with_version(self.table_uri.as_str(), version).await?; self.create_checkpoint_from_state(version, table.get_state()) .await }
fn parquet_bytes_from_state( &self, state: &DeltaTableState, ) -> Result<Vec<u8>, CheckPointWriterError> { let current_metadata = state .current_metadata() .ok_or(CheckPointWriterError::MissingMetaData)?; let mut jsons = std::iter::once(action::Action::protocol(action::Protocol { min_reader_version: state.min_reader_version(), min_writer_version: state.min_writer_version(), })) .chain(std::iter::once(action::Action::metaData( action::MetaData::try_from(current_metadata.clone())?, ))) .chain(state.files().iter().map(|f| action::Action::add(f.clone()))) .chain( state .tombstones() .iter() .map(|f| action::Action::remove(f.clone())), ) .chain( state .app_transaction_version() .iter() .map(|(app_id, version)| { action::Action::txn(action::Txn { app_id: app_id.clone(), version: *version, last_updated: None, }) }), ) .map(|a| serde_json::to_value(a).map_err(ArrowError::from)); debug!("Preparing checkpoint parquet buffer."); let arrow_schema = delta_log_schema_for_table( <ArrowSchema as TryFrom<&Schema>>::try_from(&current_metadata.schema)?, current_metadata.partition_columns.as_slice(), ); let writeable_cursor = InMemoryWriteableCursor::default(); let mut writer = ArrowWriter::try_new(writeable_cursor.clone(), arrow_schema.clone(), None)?; debug!("Writing to checkpoint parquet buffer..."); let batch_size = state.app_transaction_version().len() + state.tombstones().len() + state.files().len() + 2; let decoder = Decoder::new(arrow_schema, batch_size, None); while let Some(batch) = decoder.next_batch(&mut jsons)? { writer.write(&batch)?; } let _ = writer.close()?; debug!("Finished writing checkpoint parquet buffer."); Ok(writeable_cursor.data()) } }
pub async fn create_checkpoint_from_state( &self, version: DeltaDataTypeVersion, state: &DeltaTableState, ) -> Result<(), CheckPointWriterError> { info!("Writing parquet bytes to checkpoint buffer."); let parquet_bytes = self.parquet_bytes_from_state(state)?; let size = parquet_bytes.len() as i64; let checkpoint = CheckPoint::new(version, size, None); let file_name = format!("{:020}.checkpoint.parquet", version); let checkpoint_uri = self.storage.join_path(&self.delta_log_uri, &file_name); info!("Writing checkpoint to {:?}.", checkpoint_uri); self.storage .put_obj(&checkpoint_uri, &parquet_bytes) .await?; let last_checkpoint_content: serde_json::Value = serde_json::to_value(&checkpoint)?; let last_checkpoint_content = serde_json::to_string(&last_checkpoint_content)?; info!( "Writing _last_checkpoint to {:?}.", self.last_checkpoint_uri ); self.storage .put_obj( self.last_checkpoint_uri.as_str(), last_checkpoint_content.as_bytes(), ) .await?; Ok(()) }
function_block-full_function
[ { "content": "#[inline]\n\npub fn get_version() -> Result<Version, String> {\n\n imp::get_version()\n\n}\n", "file_path": "glibc_version/src/lib.rs", "rank": 0, "score": 266271.3643664542 }, { "content": "#[inline]\n\npub fn atomic_rename(from: &str, to: &str) -> Result<(), StorageError> ...
Rust
kernel/src/net/netmapping.rs
lqd/chocolate_milk
ad7fc8f99721d70c06d825a30d8ecfd82263c5fd
use core::ops::{Deref, DerefMut}; use core::alloc::Layout; use core::convert::TryInto; use alloc::boxed::Box; use alloc::borrow::Cow; use noodle::*; use falktp::ServerMessage; use page_table::{VirtAddr, PageType, PhysMem}; use page_table::{PAGE_NX, PAGE_WRITE, PAGE_PRESENT}; use lockcell::LockCell; use crate::core_locals::LockInterrupts; use crate::mm::{self, PhysicalMemory}; use crate::net::{NetDevice, UdpAddress, UdpBind}; use crate::interrupts::{register_fault_handler, FaultReg, PageFaultHandler}; pub struct NetMapHandler { vaddr: VirtAddr, udp: UdpBind, file_id: u64, size: usize, server: UdpAddress, read_only: bool, handling: LockCell<(), LockInterrupts>, } impl PageFaultHandler for NetMapHandler { unsafe fn page_fault(&mut self, fault_addr: VirtAddr, code: u64) -> bool { let end = VirtAddr(self.vaddr.0 + (self.size as u64 - 1)); if self.read_only && (code & (1 << 1)) != 0 { return false; } if fault_addr >= self.vaddr && fault_addr <= end { let _lock = self.handling.lock(); { let mut pmem = PhysicalMemory; let mut page_table = core!().boot_args.page_table.lock(); let page_table = page_table.as_mut().unwrap(); if page_table.translate(&mut pmem, VirtAddr(fault_addr.0 & !0xfff)) .map(|x| x.page).flatten().is_some() { return true; } } let offset = ((fault_addr.0 & !0xfff) - self.vaddr.0) as usize; let page = { let mut pmem = PhysicalMemory; pmem.alloc_phys(Layout::from_size_align(4096, 4096).unwrap()) }; let new_page = mm::slice_phys_mut(page, 4096); let to_recv = core::cmp::min(4096, self.size - offset); new_page[to_recv..].iter_mut().for_each(|x| *x = 0); let mut retries = 0; 'retry: loop { retries += 1; if retries > 100 { panic!("Failed to download backing page"); } let mut packet = self.udp.device().allocate_packet(); { let mut pkt = packet.create_udp(&self.server); ServerMessage::Read { id: self.file_id, offset: offset, size: to_recv, }.serialize(&mut pkt).unwrap(); } self.udp.device().send(packet, true); if self.udp.recv_timeout(100_000, |_, udp| { let mut ptr = &udp.payload[..]; match ServerMessage::deserialize(&mut ptr)? { ServerMessage::ReadOk => Some(()), ServerMessage::ReadErr => panic!("Could not satisfy network mapping read"), _ => unreachable!(), } }).is_none() { continue 'retry; } let mut recv_off = 0; while recv_off < to_recv { if self.udp.recv_timeout(100_000, |_, udp| { assert!(udp.payload.len() <= to_recv - recv_off, "Whoa, larger packet than expected"); new_page[recv_off..recv_off + udp.payload.len()] .copy_from_slice(&udp.payload); recv_off += udp.payload.len(); Some(()) }).is_none() { continue 'retry; } } break; } let mut pmem = PhysicalMemory; let mut page_table = core!().boot_args.page_table.lock(); let page_table = page_table.as_mut().unwrap(); page_table.map_raw(&mut pmem, VirtAddr(fault_addr.0 & !0xfff), PageType::Page4K, page.0 | PAGE_NX | if self.read_only { 0 } else { PAGE_WRITE } | PAGE_PRESENT) .expect("Failed to map in network mapped memory"); true } else { false } } } pub struct NetMapping<'a> { backing: &'a mut [u8], _fault_reg: FaultReg, read_only: bool, } impl<'a> NetMapping<'a> { pub fn new(server: &str, filename: &str, read_only: bool) -> Option<Self> { let netdev = NetDevice::get()?; let udp = NetDevice::bind_udp(netdev.clone())?; let server = UdpAddress::resolve( &netdev, udp.port(), server) .expect("Couldn't resolve target address"); let mut packet = netdev.allocate_packet(); { let mut pkt = packet.create_udp(&server); ServerMessage::GetFileId(Cow::Borrowed(filename)) .serialize(&mut pkt).unwrap(); } netdev.send(packet, true); let (file_id, size) = udp.recv_timeout(5_000_000, |_, udp| { let mut ptr = &udp.payload[..]; let msg = ServerMessage::deserialize(&mut ptr) .expect("Failed to deserialize File ID response"); match msg { ServerMessage::FileId { id, size } => Some(Some((id, size))), ServerMessage::FileIdErr => Some(None), _ => unreachable!(), } })??; if size <= 0 { return None; } let size_align = size.checked_add(0xfff)? & !0xfff; let virt_addr = crate::mm::alloc_virt_addr_4k(size_align as u64); let handler = Box::new(NetMapHandler { vaddr: virt_addr, file_id: file_id, udp: udp, size: size, server: server, read_only: read_only, handling: LockCell::new_no_preempt(()), }); Some(NetMapping { backing: unsafe { core::slice::from_raw_parts_mut(virt_addr.0 as *mut u8, size.try_into().ok()?) }, _fault_reg: register_fault_handler(handler), read_only, }) } } impl<'a> Deref for NetMapping<'a> { type Target = [u8]; fn deref(&self) -> &Self::Target { self.backing } } impl<'a> DerefMut for NetMapping<'a> { fn deref_mut(&mut self) -> &mut Self::Target { assert!(!self.read_only, "Attempted write access to read-only network mapping"); self.backing } }
use core::ops::{Deref, DerefMut}; use core::alloc::Layout; use core::convert::TryInto; use alloc::boxed::Box; use alloc::borrow::Cow; use noodle::*; use falktp::ServerMessage; use page_table::{VirtAddr, PageType, PhysMem}; use page_table::{PAGE_NX, PAGE_WRITE, PAGE_PRESENT}; use lockcell::LockCell; use crate::core_locals::LockInterrupts; use crate::mm::{self, PhysicalMemory}; use crate::net::{NetDevice, UdpAddress, UdpBind}; use crate::interrupts::{register_fault_handler, FaultReg, PageFaultHandler}; pub struct NetMapHandler { vaddr: VirtAddr, udp: UdpBind, file_id: u64, size: usize, server: UdpAddress, read_only: bool, handling: LockCell<(), LockInterrupts>, } impl PageFaultHandler for NetMapHandler { unsafe fn page_fault(&mut self, fault_addr: VirtAddr, code: u64) -> bool { let end = VirtAddr(self.vaddr.0 + (self.size as u64 - 1)); if self.read_only && (code & (1 << 1)) != 0 { return false; } if fault_addr >= self.vaddr && fault_addr <= end { let _lock = self.handling.lock(); { let mut pmem = PhysicalMemory; let mut page_table = core!().boot_args.page_table.lock(); let page_table = page_table.as_mut().unwrap(); if page_table.translate(&mut pmem, VirtAddr(fault_addr.0 & !0xfff)) .map(|x| x.page).flatten().is_some() { return true; } } let offset = ((fault_addr.0 & !0xfff) - self.vaddr.0) as usize; let page = { let mut pmem = PhysicalMemory; pmem.alloc_phys(Layout::from_size_align(4096, 4096).unwrap()) }; let new_page = mm::slice_phys_mut(page, 4096); let to_recv = core::cmp::min(4096, self.size - offset); new_page[to_recv..].iter_mut().for_each(|x| *x = 0); let mut retries = 0; 'retry: loop { retries += 1; if retries > 100 { panic!("Failed to download backing page"); } let mut packet = self.udp.device().allocate_packet(); { let mut pkt = packet.create_udp(&self.server); ServerMessage::Read { id: self.file_id, offset: offset, size: to_recv, }.serialize(&mut pkt).unwrap(); } self.udp.device().send(packet, true); if self.udp.recv_timeout(100_000, |_, udp| { let mut ptr = &udp.payload[..]; match ServerMessage::deserialize(&mut ptr)? { ServerMessage::ReadOk => Some(()), ServerMessage::ReadErr => panic!("Could not satisfy network mapping read"), _ => unreachable!(), } }).is_none() { continue 'retry; } let mut recv_off = 0; while recv_off < to_recv { if self.udp.recv_timeout(100_000, |_, udp| { assert!(udp.payload.len() <= to_recv - recv_off, "Whoa, larger packet than expected"); new_page[recv_off..recv_off + udp.payload.len()] .copy_from_slice(&udp.payload); recv_off += udp.payload.len(); Some(()) }).is_none() { continue 'retry; } } break; } let mut pmem = PhysicalMemory; let mut page_table = core!().boot_args.page_table.lock(); let page_table = page_table.as_mut().unwrap(); page_table.map_raw(&mut pmem, VirtAddr(fault_addr.0 & !0xfff), PageType::Page4K, page.0 | PAGE_NX | if self.read_only { 0 } else { PAGE_WRITE } | PAGE_PRESENT) .expect("Failed to map in network mapped memory"); true } else { false } } } pub struct NetMapping<'a> { backing: &'a mut [u8], _fault_reg: FaultReg, read_only: bool, } impl<'a> NetMapping<'a> { pub fn new(server: &str, filename: &str, read_only: bool) -> Option<Self> { let netdev = NetDevice::get()?; let udp = NetDevice::bind_udp(netdev.clone())?; let server = UdpAddress::resolve( &netdev, udp.port(), server) .expect("Couldn't resolve target address"); let mut packet = netdev.allocate_packet(); { let mut pkt = packet.create_udp(&server); ServerMessage::GetFileId(Cow::Borrowed(filename)) .serialize(&mut pkt).unwrap(); } netdev.send(packet, true); let (file_id, size) = udp.recv_timeout(5_000_000, |_, udp| { let mut ptr = &udp.payload[..]; let msg = ServerMessage::deserialize(&mut ptr) .expect("Failed to deserialize File ID response"); match msg { ServerMessage::FileId { id, size } => Some(Some((id, size))), ServerMessage::FileIdErr => Some(None), _ => unreachable!(), } })??; if size <= 0 { return None; } let size_align = size.checked_add(0xfff)? & !0xfff; let virt_addr = crate::mm::alloc_virt_addr_4k(size_align as u64); let handler = Box::new(NetMapHandler { vaddr: virt_addr, file_id: file_id, udp: udp, size: size, server: server, read_only: read_only, handling: LockCell::new_no_preempt(()), });
} } impl<'a> Deref for NetMapping<'a> { type Target = [u8]; fn deref(&self) -> &Self::Target { self.backing } } impl<'a> DerefMut for NetMapping<'a> { fn deref_mut(&mut self) -> &mut Self::Target { assert!(!self.read_only, "Attempted write access to read-only network mapping"); self.backing } }
Some(NetMapping { backing: unsafe { core::slice::from_raw_parts_mut(virt_addr.0 as *mut u8, size.try_into().ok()?) }, _fault_reg: register_fault_handler(handler), read_only, })
call_expression
[ { "content": "/// Download a file with the `filename` over TFTP with the PXE 16-bit API\n\npub fn download<P: AsRef<[u8]>>(filename: P) -> Option<Vec<u8>> {\n\n // Lock access to PXE\n\n let _guard = PXE_GUARD.lock();\n\n\n\n // Convert the filename to a slice of bytes\n\n let filename: &[u8] = file...
Rust
roapi-http/tests/helpers.rs
zemelLeong/roapi
3ace6078fa9b31cde12e367caf88ca31938c00cb
use std::path::PathBuf; use columnq::datafusion::arrow; use columnq::table::{KeyValueSource, TableColumn, TableLoadOption, TableSchema, TableSource}; use roapi_http::config::Config; use roapi_http::startup::Application; pub fn test_data_path(relative_path: &str) -> String { let mut d = PathBuf::from(env!("CARGO_MANIFEST_DIR")); d.push("../test_data"); d.push(relative_path); d.to_string_lossy().to_string() } pub async fn test_api_app_with_tables(tables: Vec<TableSource>) -> (Application, String) { test_api_app(tables, vec![]).await } pub async fn test_api_app_with_kvstores(kvstores: Vec<KeyValueSource>) -> (Application, String) { test_api_app(vec![], kvstores).await } pub async fn test_api_app( tables: Vec<TableSource>, kvstores: Vec<KeyValueSource>, ) -> (Application, String) { let config = Config { addr: "localhost:0".to_string().into(), tables, disable_read_only: false, kvstores, }; let app = Application::build(config) .await .expect("Failed to build application config"); let port = app.port(); let address = format!("http://localhost:{}", port); (app, address) } pub async fn http_get(url: &str, accept: Option<&str>) -> reqwest::Response { let request = reqwest::Client::new().get(url); let request = if let Some(accept) = accept { request.header("Accept", accept) } else { request }; request.send().await.expect("Unable to execute GET request") } pub async fn http_post(url: &str, payload: impl Into<reqwest::Body>) -> reqwest::Response { reqwest::Client::new() .post(url) .body(payload) .send() .await .expect("Unable to execute POST request") } pub fn get_spacex_table() -> TableSource { let json_source_path = test_data_path("spacex_launches.json"); TableSource::new("spacex_launches".to_string(), json_source_path) } pub fn get_uk_cities_table() -> TableSource { TableSource::new( "uk_cities".to_string(), test_data_path("uk_cities_with_headers.csv"), ) } pub fn get_ubuntu_ami_table() -> TableSource { TableSource::new("ubuntu_ami", test_data_path("ubuntu-ami.json")) .with_option(TableLoadOption::json { pointer: Some("/aaData".to_string()), array_encoded: Some(true), }) .with_schema(TableSchema { columns: vec![ TableColumn { name: "zone".to_string(), data_type: arrow::datatypes::DataType::Utf8, nullable: true, }, TableColumn { name: "name".to_string(), data_type: arrow::datatypes::DataType::Utf8, nullable: true, }, TableColumn { name: "version".to_string(), data_type: arrow::datatypes::DataType::Utf8, nullable: true, }, TableColumn { name: "arch".to_string(), data_type: arrow::datatypes::DataType::Utf8, nullable: true, }, TableColumn { name: "instance_type".to_string(), data_type: arrow::datatypes::DataType::Utf8, nullable: true, }, TableColumn { name: "release".to_string(), data_type: arrow::datatypes::DataType::Utf8, nullable: true, }, TableColumn { name: "ami_id".to_string(), data_type: arrow::datatypes::DataType::Utf8, nullable: true, }, TableColumn { name: "aki_id".to_string(), data_type: arrow::datatypes::DataType::Utf8, nullable: true, }, ], }) } pub fn get_spacex_launch_name_kvstore() -> KeyValueSource { KeyValueSource::new( "spacex_launch_name", test_data_path("spacex_launches.json"), "id", "name", ) }
use std::path::PathBuf; use columnq::datafusion::arrow; use columnq::table::{KeyValueSource, TableColumn, TableLoadOption, TableSchema, TableSource}; use roapi_http::config::Config; use roapi_http::startup::Application; pub fn test_data_path(relative_path: &str) -> String { let mut d = PathBuf::from(env!("CARGO_MANIFEST_DIR")); d.push("../test_data"); d.push(relative_path); d.to_string_lossy().to_string() } pub async fn test_api_app_with_tables(tables: Vec<TableSource>) -> (Application, String) { test_api_app(tables, vec![]).await } pub async fn test_api_app_with_kvstores(kvstores: Vec<KeyValueSource>) -> (Application, String) { test_api_app(vec![], kvstores).await } pub async fn test_api_app( tables: Vec<TableSource>, kvstores: Vec<KeyValueSource>, ) -> (Application, String) { let config = Config { addr: "localhost:0".to_string().into(), tables, disable_read_only: false, kvstores, }; let app = Application::build(config) .await .expect("Failed to build application config"); let port = app.port(); let address = format!("http://localhost:{}", port); (app, address) } pub async fn http_get(url: &str, accept: Option<&str>) -> reqwest::Response { let request = reqwest::Client::new().get(url); let request = if let Some(accept) = accept { request.header("Accept", accept) } else { request }; request.send().await.expect("Unable to execute GET request") } pub async fn http_post(url: &str, payload: impl Into<reqwest::Body>) -> reqwest::Response { reqwest::Client::new() .post(url) .body(payload) .send() .await .expect("Unable to execute POST request") } pub fn get_spacex_table() -> TableSource { let json_source_path = test_data_path("spacex_launches.json"); TableSource::new("spacex_launches".to_string(), json_source_path) } pub fn get_uk_cities_table() -> TableSource { TableSource::new( "uk_cities".to_string(), test_data_path("uk_cities_with_headers.csv"), ) } pub fn get_ubuntu_ami_table() -> TableSource { TableSource::new("ubuntu_ami", test_data_path("ubuntu-ami.json")) .with_option(TableLoadOption::json { pointer: Some("/aaData".to_string()), array_encoded: Some(true), }) .with_schema(TableSchema { columns: vec![ TableColumn { name: "zone".to_string(), data_type: arrow::datatypes::DataType::Utf8, nullable: true, }, TableColumn { name: "name".to_string(), data_type: arrow::datatypes::DataType::Utf8, nullable: true, }, TableColumn { name: "version".to_string(), data_type: arrow::datatypes::DataType::Utf8, nullable: true, }, TableColumn { name: "arch".to_string(), data_type: arrow::datatypes::DataType::Utf8, nullable: true, }, TableColumn { name: "instance_type".to_string(), data_type: arrow::datatypes::DataType::Utf8, nullable: true, }, TableColumn { name: "release".to_string(), data_type: arrow::datatypes::DataType::Utf8, nullable: true, }, TableColumn { name: "ami_id".to_string(), data_type: arrow::datatypes::DataType::Utf8, nullable: true, }, TableColumn { name: "aki_id".to_string(), data_type: arrow::datatypes::DataType::Utf8, nullable: true, }, ], }) }
pub fn get_spacex_launch_name_kvstore() -> KeyValueSource { KeyValueSource::new( "spacex_launch_name", test_data_path("spacex_launches.json"), "id", "name", ) }
function_block-full_function
[ { "content": "pub fn column_sort_expr_asc(column: impl Into<String>) -> Expr {\n\n Expr::Sort {\n\n expr: Box::new(Expr::Column(Column::from_name(column))),\n\n asc: true,\n\n nulls_first: true,\n\n }\n\n}\n\n\n\npub mod graphql;\n\npub mod rest;\n\npub mod sql;\n", "file_path": "...
Rust
src/testdrive/src/action/verify_timestamp_compaction.rs
ruchirK/materialize
94a022c1bca35726b0b1efa7516200a41d4a12d9
use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::Arc; use std::time::Duration; use async_trait::async_trait; use coord::catalog::Catalog; use coord::session::Session; use ore::now::NOW_ZERO; use ore::result::ResultExt; use ore::retry::Retry; use sql::catalog::SessionCatalog; use sql::names::PartialName; use crate::action::{Action, State}; use crate::parser::BuiltinCommand; pub struct VerifyTimestampsAction { source: String, max_size: usize, permit_progress: bool, } pub fn build_verify_timestamp_compaction( mut cmd: BuiltinCommand, ) -> Result<VerifyTimestampsAction, String> { let source = cmd.args.string("source")?; let max_size = cmd .args .opt_string("max-size") .map(|s| s.parse::<usize>().expect("unable to parse usize")) .unwrap_or(3); let permit_progress = cmd .args .opt_bool("permit-progress") .expect("require valid bool if specified") .unwrap_or(false); cmd.args.done()?; Ok(VerifyTimestampsAction { source, max_size, permit_progress, }) } #[async_trait] impl Action for VerifyTimestampsAction { async fn undo(&self, _: &mut State) -> Result<(), String> { Ok(()) } async fn redo(&self, state: &mut State) -> Result<(), String> { if let Some(path) = &state.materialized_catalog_path { let initial_highest_base = Arc::new(AtomicU64::new(u64::MAX)); Retry::default() .initial_backoff(Duration::from_secs(1)) .max_duration(Duration::from_secs(10)) .retry(|retry_state| { let initial_highest = initial_highest_base.clone(); async move { let mut catalog = Catalog::open_debug(path, NOW_ZERO.clone()) .await .map_err_to_string()?; let item_id = catalog .for_session(&Session::dummy()) .resolve_item(&PartialName { database: None, schema: None, item: self.source.clone(), }) .map_err_to_string()? .id(); let bindings = catalog .load_timestamp_bindings(item_id) .map_err_to_string()?; let progress = if retry_state.i == 0 { initial_highest.store( bindings.iter().map(|(_, ts, _)| ts).fold(u64::MIN, |a, &b| a.max(b)), Ordering::SeqCst, ); false } else { self.permit_progress && (bindings.iter().map(|(_, ts, _)| ts).fold(u64::MAX, |a, &b| a.min(b)) >= initial_highest.load(Ordering::SeqCst)) }; println!( "Verifying timestamp binding compaction for {:?}. Found {:?} vs expected {:?}. Progress: {:?}", self.source, bindings.len(), self.max_size, progress, ); if bindings.len() <= self.max_size || progress { Ok(()) } else { Err(format!( "There are {:?} bindings compared to max size {:?}", bindings.len(), self.max_size, )) } } }).await } else { println!( "Skipping timestamp binding compaction verification for {:?}.", self.source ); Ok(()) } } }
use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::Arc; use std::time::Duration; use async_trait::async_trait; use coord::catalog::Catalog; use coord::session::Session; use ore::now::NOW_ZERO; use ore::result::ResultExt; use ore::retry::Retry; use sql::catalog::SessionCatalog; use sql::names::PartialName; use crate::action::{Action, State}; use crate::parser::BuiltinCommand; pub struct VerifyTimestampsAction { source: String, max_size: usize, permit_progress: bool, } pub fn build_verify_timestamp_compaction( mut cmd: BuiltinCommand, ) -> Result<VerifyTimestampsAction, String> { let source = cmd.args.string("source")?; let max_size = cmd .args .opt_string("max-size") .map(|s| s.parse::<usize>().expect("unable to parse usize")) .unwrap_or(3);
cmd.args.done()?; Ok(VerifyTimestampsAction { source, max_size, permit_progress, }) } #[async_trait] impl Action for VerifyTimestampsAction { async fn undo(&self, _: &mut State) -> Result<(), String> { Ok(()) } async fn redo(&self, state: &mut State) -> Result<(), String> { if let Some(path) = &state.materialized_catalog_path { let initial_highest_base = Arc::new(AtomicU64::new(u64::MAX)); Retry::default() .initial_backoff(Duration::from_secs(1)) .max_duration(Duration::from_secs(10)) .retry(|retry_state| { let initial_highest = initial_highest_base.clone(); async move { let mut catalog = Catalog::open_debug(path, NOW_ZERO.clone()) .await .map_err_to_string()?; let item_id = catalog .for_session(&Session::dummy()) .resolve_item(&PartialName { database: None, schema: None, item: self.source.clone(), }) .map_err_to_string()? .id(); let bindings = catalog .load_timestamp_bindings(item_id) .map_err_to_string()?; let progress = if retry_state.i == 0 { initial_highest.store( bindings.iter().map(|(_, ts, _)| ts).fold(u64::MIN, |a, &b| a.max(b)), Ordering::SeqCst, ); false } else { self.permit_progress && (bindings.iter().map(|(_, ts, _)| ts).fold(u64::MAX, |a, &b| a.min(b)) >= initial_highest.load(Ordering::SeqCst)) }; println!( "Verifying timestamp binding compaction for {:?}. Found {:?} vs expected {:?}. Progress: {:?}", self.source, bindings.len(), self.max_size, progress, ); if bindings.len() <= self.max_size || progress { Ok(()) } else { Err(format!( "There are {:?} bindings compared to max size {:?}", bindings.len(), self.max_size, )) } } }).await } else { println!( "Skipping timestamp binding compaction verification for {:?}.", self.source ); Ok(()) } } }
let permit_progress = cmd .args .opt_bool("permit-progress") .expect("require valid bool if specified") .unwrap_or(false);
assignment_statement
[ { "content": "pub fn build_compression(cmd: &mut BuiltinCommand) -> Result<Compression, String> {\n\n match cmd.args.opt_string(\"compression\") {\n\n Some(s) => s.parse(),\n\n None => Ok(Compression::None),\n\n }\n\n}\n\n\n", "file_path": "src/testdrive/src/action/file.rs", "rank": ...
Rust
gtk4/src/auto/icon_theme.rs
haecker-felix/gtk4-rs
f225c9f2d1b4f563aafb0c54581b8e8cafd5807c
use crate::IconLookupFlags; use crate::IconPaintable; use crate::TextDirection; use glib::object::Cast; use glib::object::IsA; use glib::object::ObjectType as ObjectType_; use glib::signal::connect_raw; use glib::signal::SignalHandlerId; use glib::translate::*; use glib::StaticType; use glib::ToValue; use std::boxed::Box as Box_; use std::fmt; use std::mem::transmute; glib::wrapper! { pub struct IconTheme(Object<ffi::GtkIconTheme>); match fn { get_type => || ffi::gtk_icon_theme_get_type(), } } impl IconTheme { #[doc(alias = "gtk_icon_theme_new")] pub fn new() -> IconTheme { assert_initialized_main_thread!(); unsafe { from_glib_full(ffi::gtk_icon_theme_new()) } } #[doc(alias = "gtk_icon_theme_add_resource_path")] pub fn add_resource_path(&self, path: &str) { unsafe { ffi::gtk_icon_theme_add_resource_path(self.to_glib_none().0, path.to_glib_none().0); } } #[doc(alias = "gtk_icon_theme_add_search_path")] pub fn add_search_path<P: AsRef<std::path::Path>>(&self, path: P) { unsafe { ffi::gtk_icon_theme_add_search_path( self.to_glib_none().0, path.as_ref().to_glib_none().0, ); } } #[doc(alias = "gtk_icon_theme_get_display")] pub fn get_display(&self) -> Option<gdk::Display> { unsafe { from_glib_none(ffi::gtk_icon_theme_get_display(self.to_glib_none().0)) } } #[doc(alias = "gtk_icon_theme_get_icon_names")] pub fn get_icon_names(&self) -> Vec<glib::GString> { unsafe { FromGlibPtrContainer::from_glib_full(ffi::gtk_icon_theme_get_icon_names( self.to_glib_none().0, )) } } #[doc(alias = "gtk_icon_theme_get_resource_path")] pub fn get_resource_path(&self) -> Vec<glib::GString> { unsafe { FromGlibPtrContainer::from_glib_full(ffi::gtk_icon_theme_get_resource_path( self.to_glib_none().0, )) } } #[doc(alias = "gtk_icon_theme_get_search_path")] pub fn get_search_path(&self) -> Vec<std::path::PathBuf> { unsafe { FromGlibPtrContainer::from_glib_full(ffi::gtk_icon_theme_get_search_path( self.to_glib_none().0, )) } } #[doc(alias = "gtk_icon_theme_get_theme_name")] pub fn get_theme_name(&self) -> Option<glib::GString> { unsafe { from_glib_full(ffi::gtk_icon_theme_get_theme_name(self.to_glib_none().0)) } } #[doc(alias = "gtk_icon_theme_has_icon")] pub fn has_icon(&self, icon_name: &str) -> bool { unsafe { from_glib(ffi::gtk_icon_theme_has_icon( self.to_glib_none().0, icon_name.to_glib_none().0, )) } } #[doc(alias = "gtk_icon_theme_lookup_by_gicon")] pub fn lookup_by_gicon<P: IsA<gio::Icon>>( &self, icon: &P, size: i32, scale: i32, direction: TextDirection, flags: IconLookupFlags, ) -> Option<IconPaintable> { unsafe { from_glib_full(ffi::gtk_icon_theme_lookup_by_gicon( self.to_glib_none().0, icon.as_ref().to_glib_none().0, size, scale, direction.to_glib(), flags.to_glib(), )) } } #[doc(alias = "gtk_icon_theme_lookup_icon")] pub fn lookup_icon( &self, icon_name: &str, fallbacks: &[&str], size: i32, scale: i32, direction: TextDirection, flags: IconLookupFlags, ) -> Option<IconPaintable> { unsafe { from_glib_full(ffi::gtk_icon_theme_lookup_icon( self.to_glib_none().0, icon_name.to_glib_none().0, fallbacks.to_glib_none().0, size, scale, direction.to_glib(), flags.to_glib(), )) } } #[doc(alias = "gtk_icon_theme_set_search_path")] pub fn set_search_path(&self, path: &[&std::path::Path]) { unsafe { ffi::gtk_icon_theme_set_search_path(self.to_glib_none().0, path.to_glib_none().0); } } #[doc(alias = "gtk_icon_theme_set_theme_name")] pub fn set_theme_name(&self, theme_name: Option<&str>) { unsafe { ffi::gtk_icon_theme_set_theme_name(self.to_glib_none().0, theme_name.to_glib_none().0); } } pub fn set_property_display(&self, display: Option<&gdk::Display>) { unsafe { glib::gobject_ffi::g_object_set_property( self.as_ptr() as *mut glib::gobject_ffi::GObject, b"display\0".as_ptr() as *const _, glib::Value::from(display).to_glib_none().0, ); } } pub fn set_property_resource_path(&self, resource_path: &[&str]) { unsafe { glib::gobject_ffi::g_object_set_property( self.as_ptr() as *mut glib::gobject_ffi::GObject, b"resource-path\0".as_ptr() as *const _, glib::Value::from(resource_path).to_glib_none().0, ); } } #[doc(alias = "gtk_icon_theme_get_for_display")] pub fn get_for_display(display: &gdk::Display) -> Option<IconTheme> { assert_initialized_main_thread!(); unsafe { from_glib_none(ffi::gtk_icon_theme_get_for_display( display.to_glib_none().0, )) } } pub fn connect_changed<F: Fn(&IconTheme) + 'static>(&self, f: F) -> SignalHandlerId { unsafe extern "C" fn changed_trampoline<F: Fn(&IconTheme) + 'static>( this: *mut ffi::GtkIconTheme, f: glib::ffi::gpointer, ) { let f: &F = &*(f as *const F); f(&from_glib_borrow(this)) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"changed\0".as_ptr() as *const _, Some(transmute::<_, unsafe extern "C" fn()>( changed_trampoline::<F> as *const (), )), Box_::into_raw(f), ) } } pub fn connect_property_display_notify<F: Fn(&IconTheme) + 'static>( &self, f: F, ) -> SignalHandlerId { unsafe extern "C" fn notify_display_trampoline<F: Fn(&IconTheme) + 'static>( this: *mut ffi::GtkIconTheme, _param_spec: glib::ffi::gpointer, f: glib::ffi::gpointer, ) { let f: &F = &*(f as *const F); f(&from_glib_borrow(this)) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::display\0".as_ptr() as *const _, Some(transmute::<_, unsafe extern "C" fn()>( notify_display_trampoline::<F> as *const (), )), Box_::into_raw(f), ) } } pub fn connect_property_icon_names_notify<F: Fn(&IconTheme) + 'static>( &self, f: F, ) -> SignalHandlerId { unsafe extern "C" fn notify_icon_names_trampoline<F: Fn(&IconTheme) + 'static>( this: *mut ffi::GtkIconTheme, _param_spec: glib::ffi::gpointer, f: glib::ffi::gpointer, ) { let f: &F = &*(f as *const F); f(&from_glib_borrow(this)) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::icon-names\0".as_ptr() as *const _, Some(transmute::<_, unsafe extern "C" fn()>( notify_icon_names_trampoline::<F> as *const (), )), Box_::into_raw(f), ) } } pub fn connect_property_resource_path_notify<F: Fn(&IconTheme) + 'static>( &self, f: F, ) -> SignalHandlerId { unsafe extern "C" fn notify_resource_path_trampoline<F: Fn(&IconTheme) + 'static>( this: *mut ffi::GtkIconTheme, _param_spec: glib::ffi::gpointer, f: glib::ffi::gpointer, ) { let f: &F = &*(f as *const F); f(&from_glib_borrow(this)) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::resource-path\0".as_ptr() as *const _, Some(transmute::<_, unsafe extern "C" fn()>( notify_resource_path_trampoline::<F> as *const (), )), Box_::into_raw(f), ) } } pub fn connect_property_search_path_notify<F: Fn(&IconTheme) + 'static>( &self, f: F, ) -> SignalHandlerId { unsafe extern "C" fn notify_search_path_trampoline<F: Fn(&IconTheme) + 'static>( this: *mut ffi::GtkIconTheme, _param_spec: glib::ffi::gpointer, f: glib::ffi::gpointer, ) { let f: &F = &*(f as *const F); f(&from_glib_borrow(this)) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::search-path\0".as_ptr() as *const _, Some(transmute::<_, unsafe extern "C" fn()>( notify_search_path_trampoline::<F> as *const (), )), Box_::into_raw(f), ) } } pub fn connect_property_theme_name_notify<F: Fn(&IconTheme) + 'static>( &self, f: F, ) -> SignalHandlerId { unsafe extern "C" fn notify_theme_name_trampoline<F: Fn(&IconTheme) + 'static>( this: *mut ffi::GtkIconTheme, _param_spec: glib::ffi::gpointer, f: glib::ffi::gpointer, ) { let f: &F = &*(f as *const F); f(&from_glib_borrow(this)) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::theme-name\0".as_ptr() as *const _, Some(transmute::<_, unsafe extern "C" fn()>( notify_theme_name_trampoline::<F> as *const (), )), Box_::into_raw(f), ) } } } impl Default for IconTheme { fn default() -> Self { Self::new() } } #[derive(Clone, Default)] pub struct IconThemeBuilder { display: Option<gdk::Display>, resource_path: Option<Vec<String>>, search_path: Option<Vec<String>>, theme_name: Option<String>, } impl IconThemeBuilder { pub fn new() -> Self { Self::default() } pub fn build(self) -> IconTheme { let mut properties: Vec<(&str, &dyn ToValue)> = vec![]; if let Some(ref display) = self.display { properties.push(("display", display)); } if let Some(ref resource_path) = self.resource_path { properties.push(("resource-path", resource_path)); } if let Some(ref search_path) = self.search_path { properties.push(("search-path", search_path)); } if let Some(ref theme_name) = self.theme_name { properties.push(("theme-name", theme_name)); } let ret = glib::Object::new::<IconTheme>(&properties).expect("object new"); ret } pub fn display(mut self, display: &gdk::Display) -> Self { self.display = Some(display.clone()); self } pub fn resource_path(mut self, resource_path: Vec<String>) -> Self { self.resource_path = Some(resource_path); self } pub fn search_path(mut self, search_path: Vec<String>) -> Self { self.search_path = Some(search_path); self } pub fn theme_name(mut self, theme_name: &str) -> Self { self.theme_name = Some(theme_name.to_string()); self } } impl fmt::Display for IconTheme { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str("IconTheme") } }
use crate::IconLookupFlags; use crate::IconPaintable; use crate::TextDirection; use glib::object::Cast; use glib::object::IsA; use glib::object::ObjectType as ObjectType_; use glib::signal::connect_raw; use glib::signal::SignalHandlerId; use glib::translate::*; use glib::StaticType; use glib::ToValue; use std::boxed::Box as Box_; use std::fmt; use std::mem::transmute; glib::wrapper! { pub struct IconTheme(Object<ffi::GtkIconTheme>); match fn { get_type => || ffi::gtk_icon_theme_get_type(), } } impl IconTheme { #[doc(alias = "gtk_icon_theme_new")] pub fn new() -> IconTheme { assert_initialized_main_thread!(); unsafe { from_glib_full(ffi::gtk_icon_theme_new()) } } #[doc(alias = "gtk_icon_theme_add_resource_path")] pub fn add_resource_path(&self, path: &str) { unsafe { ffi::gtk_icon_theme_add_resource_path(self.to_glib_none().0, path.to_glib_none().0); } } #[doc(alias = "gtk_icon_theme_add_search_path")] pub fn add_search_path<P: AsRef<std::path::Path>>(&self, path: P) { unsafe { ffi::gtk_icon_theme_add_search_path( self.to_glib_none().0, path.as_ref().to_glib_none().0, ); } } #[doc(alias = "gtk_icon_theme_get_display")] pub fn get_display(&self) -> Option<gdk::Display> { unsafe { from_glib_none(ffi::gtk_icon_theme_get_display(self.to_glib_none().0)) } } #[doc(alias = "gtk_icon_theme_get_icon_names")] pub fn get_icon_names(&self) -> Vec<glib::GString> { unsafe { FromGlibPtrContainer::from_glib_full(ffi::gtk_icon_theme_get_icon_names( self.to_glib_none().0, )) } } #[doc(alias = "gtk_icon_theme_get_resource_path")] pub fn get_resource_path(&self) -> Vec<glib::GString> { unsafe { FromGlibPtrContainer::from_glib_full(ffi::gtk_icon_theme_get_resource_path( self.to_glib_none().0, )) } } #[doc(alias = "gtk_icon_theme_get_search_path")] pub fn get_search_path(&self) -> Vec<std::path::PathBuf> { unsafe { FromGlibPtrContainer::from_glib_full(ffi::gtk_icon_theme_get_search_path( self.to_glib_none().0, )) } } #[doc(alias = "gtk_icon_theme_get_theme_name")] pub fn get_theme_name(&self) -> Option<glib::GString> { unsafe { from_glib_full(ffi::gtk_icon_theme_get
b_full(ffi::gtk_icon_theme_lookup_icon( self.to_glib_none().0, icon_name.to_glib_none().0, fallbacks.to_glib_none().0, size, scale, direction.to_glib(), flags.to_glib(), )) } } #[doc(alias = "gtk_icon_theme_set_search_path")] pub fn set_search_path(&self, path: &[&std::path::Path]) { unsafe { ffi::gtk_icon_theme_set_search_path(self.to_glib_none().0, path.to_glib_none().0); } } #[doc(alias = "gtk_icon_theme_set_theme_name")] pub fn set_theme_name(&self, theme_name: Option<&str>) { unsafe { ffi::gtk_icon_theme_set_theme_name(self.to_glib_none().0, theme_name.to_glib_none().0); } } pub fn set_property_display(&self, display: Option<&gdk::Display>) { unsafe { glib::gobject_ffi::g_object_set_property( self.as_ptr() as *mut glib::gobject_ffi::GObject, b"display\0".as_ptr() as *const _, glib::Value::from(display).to_glib_none().0, ); } } pub fn set_property_resource_path(&self, resource_path: &[&str]) { unsafe { glib::gobject_ffi::g_object_set_property( self.as_ptr() as *mut glib::gobject_ffi::GObject, b"resource-path\0".as_ptr() as *const _, glib::Value::from(resource_path).to_glib_none().0, ); } } #[doc(alias = "gtk_icon_theme_get_for_display")] pub fn get_for_display(display: &gdk::Display) -> Option<IconTheme> { assert_initialized_main_thread!(); unsafe { from_glib_none(ffi::gtk_icon_theme_get_for_display( display.to_glib_none().0, )) } } pub fn connect_changed<F: Fn(&IconTheme) + 'static>(&self, f: F) -> SignalHandlerId { unsafe extern "C" fn changed_trampoline<F: Fn(&IconTheme) + 'static>( this: *mut ffi::GtkIconTheme, f: glib::ffi::gpointer, ) { let f: &F = &*(f as *const F); f(&from_glib_borrow(this)) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"changed\0".as_ptr() as *const _, Some(transmute::<_, unsafe extern "C" fn()>( changed_trampoline::<F> as *const (), )), Box_::into_raw(f), ) } } pub fn connect_property_display_notify<F: Fn(&IconTheme) + 'static>( &self, f: F, ) -> SignalHandlerId { unsafe extern "C" fn notify_display_trampoline<F: Fn(&IconTheme) + 'static>( this: *mut ffi::GtkIconTheme, _param_spec: glib::ffi::gpointer, f: glib::ffi::gpointer, ) { let f: &F = &*(f as *const F); f(&from_glib_borrow(this)) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::display\0".as_ptr() as *const _, Some(transmute::<_, unsafe extern "C" fn()>( notify_display_trampoline::<F> as *const (), )), Box_::into_raw(f), ) } } pub fn connect_property_icon_names_notify<F: Fn(&IconTheme) + 'static>( &self, f: F, ) -> SignalHandlerId { unsafe extern "C" fn notify_icon_names_trampoline<F: Fn(&IconTheme) + 'static>( this: *mut ffi::GtkIconTheme, _param_spec: glib::ffi::gpointer, f: glib::ffi::gpointer, ) { let f: &F = &*(f as *const F); f(&from_glib_borrow(this)) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::icon-names\0".as_ptr() as *const _, Some(transmute::<_, unsafe extern "C" fn()>( notify_icon_names_trampoline::<F> as *const (), )), Box_::into_raw(f), ) } } pub fn connect_property_resource_path_notify<F: Fn(&IconTheme) + 'static>( &self, f: F, ) -> SignalHandlerId { unsafe extern "C" fn notify_resource_path_trampoline<F: Fn(&IconTheme) + 'static>( this: *mut ffi::GtkIconTheme, _param_spec: glib::ffi::gpointer, f: glib::ffi::gpointer, ) { let f: &F = &*(f as *const F); f(&from_glib_borrow(this)) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::resource-path\0".as_ptr() as *const _, Some(transmute::<_, unsafe extern "C" fn()>( notify_resource_path_trampoline::<F> as *const (), )), Box_::into_raw(f), ) } } pub fn connect_property_search_path_notify<F: Fn(&IconTheme) + 'static>( &self, f: F, ) -> SignalHandlerId { unsafe extern "C" fn notify_search_path_trampoline<F: Fn(&IconTheme) + 'static>( this: *mut ffi::GtkIconTheme, _param_spec: glib::ffi::gpointer, f: glib::ffi::gpointer, ) { let f: &F = &*(f as *const F); f(&from_glib_borrow(this)) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::search-path\0".as_ptr() as *const _, Some(transmute::<_, unsafe extern "C" fn()>( notify_search_path_trampoline::<F> as *const (), )), Box_::into_raw(f), ) } } pub fn connect_property_theme_name_notify<F: Fn(&IconTheme) + 'static>( &self, f: F, ) -> SignalHandlerId { unsafe extern "C" fn notify_theme_name_trampoline<F: Fn(&IconTheme) + 'static>( this: *mut ffi::GtkIconTheme, _param_spec: glib::ffi::gpointer, f: glib::ffi::gpointer, ) { let f: &F = &*(f as *const F); f(&from_glib_borrow(this)) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::theme-name\0".as_ptr() as *const _, Some(transmute::<_, unsafe extern "C" fn()>( notify_theme_name_trampoline::<F> as *const (), )), Box_::into_raw(f), ) } } } impl Default for IconTheme { fn default() -> Self { Self::new() } } #[derive(Clone, Default)] pub struct IconThemeBuilder { display: Option<gdk::Display>, resource_path: Option<Vec<String>>, search_path: Option<Vec<String>>, theme_name: Option<String>, } impl IconThemeBuilder { pub fn new() -> Self { Self::default() } pub fn build(self) -> IconTheme { let mut properties: Vec<(&str, &dyn ToValue)> = vec![]; if let Some(ref display) = self.display { properties.push(("display", display)); } if let Some(ref resource_path) = self.resource_path { properties.push(("resource-path", resource_path)); } if let Some(ref search_path) = self.search_path { properties.push(("search-path", search_path)); } if let Some(ref theme_name) = self.theme_name { properties.push(("theme-name", theme_name)); } let ret = glib::Object::new::<IconTheme>(&properties).expect("object new"); ret } pub fn display(mut self, display: &gdk::Display) -> Self { self.display = Some(display.clone()); self } pub fn resource_path(mut self, resource_path: Vec<String>) -> Self { self.resource_path = Some(resource_path); self } pub fn search_path(mut self, search_path: Vec<String>) -> Self { self.search_path = Some(search_path); self } pub fn theme_name(mut self, theme_name: &str) -> Self { self.theme_name = Some(theme_name.to_string()); self } } impl fmt::Display for IconTheme { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str("IconTheme") } }
_theme_name(self.to_glib_none().0)) } } #[doc(alias = "gtk_icon_theme_has_icon")] pub fn has_icon(&self, icon_name: &str) -> bool { unsafe { from_glib(ffi::gtk_icon_theme_has_icon( self.to_glib_none().0, icon_name.to_glib_none().0, )) } } #[doc(alias = "gtk_icon_theme_lookup_by_gicon")] pub fn lookup_by_gicon<P: IsA<gio::Icon>>( &self, icon: &P, size: i32, scale: i32, direction: TextDirection, flags: IconLookupFlags, ) -> Option<IconPaintable> { unsafe { from_glib_full(ffi::gtk_icon_theme_lookup_by_gicon( self.to_glib_none().0, icon.as_ref().to_glib_none().0, size, scale, direction.to_glib(), flags.to_glib(), )) } } #[doc(alias = "gtk_icon_theme_lookup_icon")] pub fn lookup_icon( &self, icon_name: &str, fallbacks: &[&str], size: i32, scale: i32, direction: TextDirection, flags: IconLookupFlags, ) -> Option<IconPaintable> { unsafe { from_gli
random
[]
Rust
src/utils.rs
drahnr/pyroscope-rs
c0a64b7b3d3b9a166bf3648ff3c53534a24d68b1
use crate::error::Result; use crate::PyroscopeError; use std::collections::HashMap; pub fn merge_tags_with_app_name( application_name: String, tags: HashMap<String, String>, ) -> Result<String> { let mut tags_vec = tags .into_iter() .filter(|(k, _)| k != "__name__") .map(|(k, v)| format!("{}={}", k, v)) .collect::<Vec<String>>(); tags_vec.sort(); let tags_str = tags_vec.join(","); if !tags_str.is_empty() { Ok(format!("{}{{{}}}", application_name, tags_str,)) } else { Ok(application_name) } } #[cfg(test)] mod merge_tags_with_app_name_tests { use std::collections::HashMap; use crate::utils::merge_tags_with_app_name; #[test] fn merge_tags_with_app_name_with_tags() { let mut tags = HashMap::new(); tags.insert("env".to_string(), "staging".to_string()); tags.insert("region".to_string(), "us-west-1".to_string()); tags.insert("__name__".to_string(), "reserved".to_string()); assert_eq!( merge_tags_with_app_name("my.awesome.app.cpu".to_string(), tags).unwrap(), "my.awesome.app.cpu{env=staging,region=us-west-1}".to_string() ) } #[test] fn merge_tags_with_app_name_without_tags() { assert_eq!( merge_tags_with_app_name("my.awesome.app.cpu".to_string(), HashMap::default()).unwrap(), "my.awesome.app.cpu".to_string() ) } } pub fn check_err<T: Ord + Default>(num: T) -> Result<T> { if num < T::default() { return Err(PyroscopeError::from(std::io::Error::last_os_error())); } Ok(num) } #[cfg(test)] mod check_err_tests { use crate::utils::check_err; #[test] fn check_err_success() { assert_eq!(check_err(1).unwrap(), 1) } #[test] fn check_err_error() { assert!(check_err(-1).is_err()) } } pub fn get_current_time_secs() -> Result<u64> { Ok(std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH)? .as_secs()) } #[cfg(test)] mod get_current_time_secs_tests { use crate::utils::get_current_time_secs; #[test] fn get_current_time_secs_success() { assert!(get_current_time_secs().is_ok()) } } #[derive(Debug, PartialEq)] pub struct TimeRange { pub from: u64, pub until: u64, pub current: u64, pub rem: u64, } pub fn get_time_range(timestamp: u64) -> Result<TimeRange> { if timestamp == 0 { return get_time_range(get_current_time_secs()?); } Ok(TimeRange { from: timestamp / 10 * 10, until: timestamp / 10 * 10 + 10, current: timestamp, rem: 10 - (timestamp % 10), }) } #[cfg(test)] mod get_time_range_tests { use crate::utils::{get_time_range, TimeRange}; #[test] fn get_time_range_verify() { assert_eq!( get_time_range(1644194479).unwrap(), TimeRange { from: 1644194470, until: 1644194480, current: 1644194479, rem: 1, } ); assert_eq!( get_time_range(1644194470).unwrap(), TimeRange { from: 1644194470, until: 1644194480, current: 1644194470, rem: 10, } ); assert_eq!( get_time_range(1644194476).unwrap(), TimeRange { from: 1644194470, until: 1644194480, current: 1644194476, rem: 4, } ); } }
use crate::error::Result; use crate::PyroscopeError; use std::collections::HashMap; pub fn merge_tags_with_app_name( application_name: String, tags: HashMap<String, String>, ) -> Result<String> { let mut tags_vec = tags .into_iter() .filter(|(k, _)| k != "__name__") .map(|(k, v)| format!("{}={}", k, v)) .collect::<Vec<String>>(); tags_vec.sort(); let tags_str = tags_vec.join(","); if !tags_str.is_empty() { Ok(format!("{}{{{}}}", application_name, tags_str,)) } else { Ok(application_name) } } #[cfg(test)] mod merge_tags_with_app_name_tests { use std::collections::HashMap; use crate::utils::merge_tags_with_app_name; #[test] fn merge_tags_with_app_name_with_tags() { let mut tags = HashMap::new(); tags.insert("env".to_string(), "staging".to_string()); tags.insert("region".to_string(), "us-west-1".to_string()); tags.insert("__name__".to_string(), "reserved".to_string()); assert_eq!( merge_tags_with_app_name("my.awesome.app.cpu".to_string(), tags).unwrap(), "my.awesome.app.cpu{env=staging,region=us-west-1}".to_string() ) } #[test] fn merge_tags_with_app_name_without_tags() { assert_eq!( merge_tags_with_app_name("my.awesome.app.cpu".to_string(), HashMap::default()).unwrap(), "my.awesome.app.cpu".to_string() ) } } pub fn check_err<T: Ord + Default>(num: T) -> Result<T> { if num < T::default() { return Err(PyroscopeError::from(std::io::Error::last_os_error())); } Ok(num) } #[cfg(test)] mod check_err_tests { use crate::utils::check_err; #[test] fn check_err_success() { assert_eq!(check_err(1).unwrap(), 1) } #[test] fn check_err_error() { assert!(check_err(-1).is_err()) } } pub fn get_current_time_secs() -> Result<u64> { Ok(std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH)? .as_secs()) } #[cfg(test)] mod get_current_time_secs_tests { use crate::utils::get_current_time_secs; #[test] fn get_current_time_secs_success() { assert!(get_current_time_secs().is_ok()) } } #[derive(Debug, PartialEq)] pub struct TimeRange { pub from: u64, pub until: u64, pub current: u64, pub rem: u64, } pub fn get_time_range(timestamp: u64) -> Result<TimeRange> { if timestamp == 0 { return get_time_range(get_current_time_secs()?); } Ok(TimeRange { from: timestamp / 10 * 10, until: timestamp / 10 * 10 + 10, current: timestamp, rem: 10 - (timestamp % 10), }) } #[cfg(test)] mod get_time_range_tests { use crate::utils::{get_time_range, TimeRange}; #[test] fn get_time_range_verify() { assert_eq!( get_time_range(1644194479).unwrap(), TimeRange { from: 1644194470, until: 1644194480, current: 1644194479, rem: 1, } ); assert_eq!( get_time_range(1644194470).unwrap(), TimeRange { from: 1644194470, until: 1644194480,
until: 1644194480, current: 1644194476, rem: 4, } ); } }
current: 1644194470, rem: 10, } ); assert_eq!( get_time_range(1644194476).unwrap(), TimeRange { from: 1644194470,
random
[ { "content": "fn fibonacci(n: u64) -> u64 {\n\n match n {\n\n 0 | 1 => 1,\n\n n => fibonacci(n - 1) + fibonacci(n - 2),\n\n }\n\n}\n\n\n", "file_path": "examples/tags.rs", "rank": 3, "score": 102153.85947132888 }, { "content": "fn fibonacci(n: u64) -> u64 {\n\n match n...
Rust
src/writer/file_writer.rs
cspinetta/jon-listen
89134524b67443d7620b11bb840dfb9dfe04d0f8
use std::fs::File; use std::io::prelude::*; use std::fs::OpenOptions; use std::thread::{self, JoinHandle}; use std::path::PathBuf; use std::fs; use std::time::Duration; use chrono::prelude::*; use std::borrow::BorrowMut; use std::sync::mpsc::{sync_channel, SyncSender, Receiver}; use ::settings::FileWriterConfig; use ::settings::RotationPolicyType; use writer::file_rotation::FileRotation; use writer::rotation_policy::{RotationPolicy, RotationByDuration, RotationByDay}; pub struct FileWriter { file_dir_path: PathBuf, file_path: PathBuf, file_name: String, file: File, pub tx: SyncSender<FileWriterCommand>, rx: Receiver<FileWriterCommand>, file_config: FileWriterConfig, } impl FileWriter { pub fn new(buffer_bound: usize, file_config: FileWriterConfig) -> Self { let file_dir_path = file_config.filedir.clone(); let mut file_path = file_dir_path.clone(); file_path.push(file_config.filename.clone()); let file = Self::open_file(&file_path, file_config.formatting.startingmsg, true).unwrap(); let (tx, rx) = sync_channel(buffer_bound); FileWriter { file_dir_path, file_path, file_name: file_config.filename.clone(), file, tx, rx, file_config } } pub fn start(&mut self) -> Result<(), String> { info!("File writer starting"); let rotation_policy: Box<RotationPolicy> = match self.file_config.rotation.policy { RotationPolicyType::ByDuration => Box::new(RotationByDuration::new(Duration::from_secs(self.file_config.rotation.duration.unwrap()))), RotationPolicyType::ByDay => Box::new(RotationByDay::new()) }; let file_rotation = FileRotation::new( self.file_dir_path.clone(),self.file_path.clone(), self.file_name.clone(), self.file_config.rotation.count, rotation_policy, self.tx.clone()); let rotation_handle: JoinHandle<Result<(), String>> = file_rotation.start_async(); self.listen_commands()?; rotation_handle.join().unwrap_or_else(|e| Err(format!("Failed trying to join. Reason: {:?}", e)))?; Ok(()) } pub fn start_async(mut self) -> JoinHandle<Result<(), String>> { thread::spawn(move || { self.start() }) } fn listen_commands(&mut self) -> Result<(), String> { let mut count = 0; loop { let mut command = self.rx.recv() .map_err(|e| format!("Error getting file-write-command from channel: {}", e))?; debug!("Command received: {:?}", command); match command { FileWriterCommand::WriteDebug(id, value, i) => { count += 1; info!("WriteDebug - {} - Count in FileWriter: {} - In Server: {}", id, count, i); self.write(value.as_slice())? }, FileWriterCommand::Write(ref value) if value.last().map(|x| x.eq(&('\n' as u8))).unwrap_or(false) => { self.write(value)? }, FileWriterCommand::Write(ref mut value) => { let value: &mut Vec<u8> = value.as_mut(); value.push('\n' as u8); self.write((value).as_slice())? }, FileWriterCommand::Rename(new_path) => self.rotate(new_path)?, } } Ok(()) } pub fn write(&mut self, buf: &[u8]) -> Result<(), String> { Self::write_with(self.file.borrow_mut(), buf) } fn write_with(file: &mut File, buf: &[u8]) -> Result<(), String> { debug!("Writing to file {:?}", file); file.write(buf) .map_err(|e| format!("Failed trying to write to the log file. Reason: {}", e))?; Ok(()) } fn open_file(filepath: &PathBuf, with_starting_msg: bool, keep_content: bool) -> Result<File, String> { let starting_msg = format!("Starting {} at {}\n", filepath.to_string_lossy(), Local::now().to_rfc2822()); info!("Opening file {:?}", filepath); info!("{}", starting_msg); let mut options = OpenOptions::new(); let mut options = if keep_content { options.append(true) } else { options.write(true) }; let mut file = options.create(true).open(filepath) .expect(format!("Open the log file {:?}", filepath).as_ref()); if with_starting_msg { Self::write_with(file.borrow_mut(), starting_msg.as_bytes()); } Ok(file) } fn rotate(&mut self, new_path: PathBuf) -> Result<(), String> { fs::rename(self.file_path.clone(), new_path.clone()) .map_err(|e| format!("Failed trying to rename the file {:?} to {:?}. Reason: {}", self.file_path.clone(), new_path, e)) .and_then(|_| { let ending_msg = format!("Ending log as {} at {}\n", new_path.as_path().to_string_lossy(), Local::now().to_rfc2822()); info!("File rename successfully. {}", ending_msg); if self.file_config.formatting.endingmsg { self.write(ending_msg.as_bytes())?; } self.file = Self::open_file(&self.file_path.clone(), self.file_config.formatting.startingmsg, false)?; Ok(()) }) } } #[derive(Debug, Clone, PartialEq)] pub enum FileWriterCommand { Write(Vec<u8>), Rename(PathBuf), WriteDebug(String, Vec<u8>, i32), }
use std::fs::File; use std::io::prelude::*; use std::fs::OpenOptions; use std::thread::{self, JoinHandle}; use std::path::PathBuf; use std::fs; use std::time::Duration; use chrono::prelude::*; use std::borrow::BorrowMut; use std::sync::mpsc::{sync_channel, SyncSender, Receiver}; use ::settings::FileWriterConfig; use ::settings::RotationPolicyType; use writer::file_rotation::FileRotation; use writer::rotation_policy::{RotationPolicy, RotationByDuration, RotationByDay}; pub struct FileWriter { file_dir_path: PathBuf, file_path: PathBuf, file_name: String, file: File, pub tx: SyncSender<FileWriterCommand>, rx: Receiver<FileWriterCommand>, file_config: FileWriterConfig, } impl FileWriter { pub fn new(buffer_bound: usize, file_config: FileWriterConfig) -> Self { let file_dir_path = file_config.filedir.clone(); let mut file_path = file_dir_path.clone(); file_path.push(file_config.filename.clone()); let file = Self::open_file(&file_path, file_config.formatting.startingmsg, true).unwrap(); let (tx, rx) = sync_channel(buffer_bound); FileWriter { file_dir_path, file_path, file_name: file_config.filename.clone(), file, tx, rx, file_config } } pub fn start(&mut self) -> Result<(), String> { info!("File writer starting"); let rotation_policy: Box<RotationPolicy> = match self.file_config.rotation.policy { RotationPolicyType::ByDuration => Box::new(RotationByDuration::new(Duration::from_secs(self.file_config.rotation.duration.unwrap()))), RotationPolicyType::ByDay => Box::new(RotationByDay::new()) }; let file_rotation = FileRotation::new( self.file_dir_path.clone(),self.file_path.clone(), self.file_name.clone(), self.file_config.rotation.count, rotation_policy, self.tx.clone()); let rotation_handle: JoinHandle<Result<(), String>> = file_rotation.start_async(); self.listen_commands()?; rotation_handle.join().unwrap_or_else(|e| Err(format!("Failed trying to join. Reason: {:?}", e)))?; Ok(()) } pub fn start_async(mut self) -> JoinHandle<Result<(), String>> { thread::spawn(move || { self.start() }) } fn listen_commands(&mut self) -> Result<(), String> { let mut count = 0; loop { let mut command = self.rx.recv() .map_err(|e| format!("Error getting file-write-command from channel: {}", e))?; debug!("Command received: {:?}", command); match command { FileWriterCommand::WriteDebug(id, value, i) => { count += 1; info!("WriteDebug - {} - Count in FileWriter: {} - In Server: {}", id, count, i); self.write(value.as_slice())? }, FileWriterCommand::Write(ref value) if value.last().map(|x| x.eq(&('\n' as u8))).unwrap_or(false) => { self.write(value)? }, FileWriterCommand::Write(ref mut value) => { let value: &mut Vec<u8> = value.as_mut(); value.push('\n' as u8); self.write((value).as_slice())? }, FileWriterCommand::Rename(new_path) => self.rotate(new_path)?, } } Ok(()) } pub fn write(&mut self, buf: &[u8]) -> Result<(), String> { Self::write_with(self.file.borrow_mut(), buf) } fn write_with(file: &mut File, buf: &[u8]) -> Result<(), String> { debug!("Writing to file {:?}", file); file.write(buf) .map_err(|e| format!("Failed trying to write to the log file. Reason: {}", e))?; Ok(()) }
fn rotate(&mut self, new_path: PathBuf) -> Result<(), String> { fs::rename(self.file_path.clone(), new_path.clone()) .map_err(|e| format!("Failed trying to rename the file {:?} to {:?}. Reason: {}", self.file_path.clone(), new_path, e)) .and_then(|_| { let ending_msg = format!("Ending log as {} at {}\n", new_path.as_path().to_string_lossy(), Local::now().to_rfc2822()); info!("File rename successfully. {}", ending_msg); if self.file_config.formatting.endingmsg { self.write(ending_msg.as_bytes())?; } self.file = Self::open_file(&self.file_path.clone(), self.file_config.formatting.startingmsg, false)?; Ok(()) }) } } #[derive(Debug, Clone, PartialEq)] pub enum FileWriterCommand { Write(Vec<u8>), Rename(PathBuf), WriteDebug(String, Vec<u8>, i32), }
fn open_file(filepath: &PathBuf, with_starting_msg: bool, keep_content: bool) -> Result<File, String> { let starting_msg = format!("Starting {} at {}\n", filepath.to_string_lossy(), Local::now().to_rfc2822()); info!("Opening file {:?}", filepath); info!("{}", starting_msg); let mut options = OpenOptions::new(); let mut options = if keep_content { options.append(true) } else { options.write(true) }; let mut file = options.create(true).open(filepath) .expect(format!("Open the log file {:?}", filepath).as_ref()); if with_starting_msg { Self::write_with(file.borrow_mut(), starting_msg.as_bytes()); } Ok(file) }
function_block-full_function
[ { "content": "fn extract_command_arg(args: &mut Vec<String>, names: Vec<String>) -> bool {\n\n match args.iter().position(|a| names.contains(a)) {\n\n Some(i) => {\n\n args.remove(i);\n\n true\n\n }\n\n None => false,\n\n }\n\n}\n\n\n\nmod tcp {\n\n use std::i...
Rust
src/connection/info.rs
bayne/libpq.rs
124f73ac438fd542f933e94499550b1158b8d38e
#[derive(Clone, Debug, PartialEq)] pub struct Info { pub keyword: String, pub envvar: Option<String>, pub compiled: Option<String>, pub val: Option<String>, pub label: Option<String>, pub dispchar: String, pub dispsize: i32, } impl Info { /** * Returns the default connection options. * * See [PQconndefaults](https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-PQCONNDEFAULTS) */ pub fn new() -> Self { Self::default() } /** * Returns parsed connection options from the provided connection string. * * See * [PQconninfoParse](https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-PQCONNINFOPARSE). */ pub fn from(dsn: &str) -> std::result::Result<Vec<Self>, String> { let c_dsn = crate::ffi::to_cstr(dsn); unsafe { let mut errmsg: *mut i8 = std::ptr::null_mut(); let raw = pq_sys::PQconninfoParse(c_dsn.as_ptr(), &mut errmsg); if raw.is_null() { if errmsg.is_null() { return Err("Unknow error".to_string()); } else { let err = crate::ffi::to_string(errmsg); pq_sys::PQfreemem(errmsg as *mut std::ffi::c_void); return Err(err); } } let info = Self::vec_from_nta(raw); pq_sys::PQconninfoFree(raw); Ok(info) } } fn from_raw(info: *mut pq_sys::_PQconninfoOption) -> Self { unsafe { Self { keyword: crate::ffi::to_string((*info).keyword), envvar: if (*info).envvar.is_null() { None } else { Some(crate::ffi::to_string((*info).envvar)) }, compiled: if (*info).compiled.is_null() { None } else { Some(crate::ffi::to_string((*info).compiled)) }, val: if (*info).val.is_null() { None } else { Some(crate::ffi::to_string((*info).val)) }, label: if (*info).label.is_null() { None } else { Some(crate::ffi::to_string((*info).label)) }, dispchar: crate::ffi::to_string((*info).dispchar), dispsize: (*info).dispsize, } } } fn vec_from_nta(raw: *mut pq_sys::_PQconninfoOption) -> Vec<Self> { let mut vec = Vec::new(); for x in 0.. { unsafe { if (*raw.offset(x)).keyword.is_null() { break; } else { let info = raw.offset(x).into(); vec.push(info); } } } vec } } impl Default for Info { fn default() -> Self { unsafe { let raw = pq_sys::PQconndefaults(); let info = raw.into(); pq_sys::PQconninfoFree(raw); info } } } #[doc(hidden)] impl From<*mut pq_sys::_PQconninfoOption> for Info { fn from(info: *mut pq_sys::_PQconninfoOption) -> Self { Self::from_raw(info) } } #[cfg(test)] mod test { #[test] fn parse_info() { assert!(crate::connection::Info::from("host=localhost user=postgres").is_ok()); assert_eq!( crate::connection::Info::from("'"), Err("missing \"=\" after \"'\" in connection info string\n".to_string()) ); } #[test] fn defaults() { let _ = crate::connection::Info::default(); } }
#[derive(Clone, Debug, PartialEq)] pub struct Info { pub keyword: String, pub envvar: Option<String>, pub compiled: Option<String>, pub val: Option<String>, pub label: Option<String>, pub dispchar: String, pub dispsize: i32, } impl Info { /** * Returns the default connection options. * * See [PQconndefaults](https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-PQCONNDEFAULTS) */ pub fn new() -> Self { Self::default() } /** * Returns parsed connection options from the provided connection string. * * See * [PQconninfoParse](https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-PQCONNINFOPARSE). */ pub fn from(dsn: &str) -> std::result::Result<Vec<Self>, String> { let c_dsn = crate::ffi::to_cstr(dsn); unsafe { let mut errmsg: *mut i8 = std::ptr::null_mut(); let raw = pq_sys::PQconninfoParse(c_dsn.as_ptr(), &mut errmsg); if raw.is_null() { if errmsg.is_null() { return Err("Unknow error".to_string()); } else { let err = crate::ffi::to_string(errmsg); pq_sys::PQfreemem(errmsg as *mut std::ffi::c_void); return Err(err); } } let info = Self::vec_from_nta(raw); pq_sys::PQconninfoFree(raw); Ok(info) } } fn from_raw(info: *mut pq_sys::_PQconninfoOption) -> Self { unsafe { Self { keyword: crate::ffi::to_string((*info).keyword), envvar: if (*info).envvar.is_null() { None } else { Some(crate::ffi::to_string((*info).envvar)) }, compiled: if (*info).compiled.is_null() { None } else { Some(crate::ffi::to_string((*info).compiled)) }, val: if (*info).val.is_null() { None } else { Some(crate::ffi::to_string((*info).val)) }, label: if (*info).label.is_null() { None } else { Some(crate::ffi::to_string((*info).label)) }, dispchar: crate::ffi::to_string((*info).dispchar), dispsize: (*info).dispsize, } } } fn vec_from_nta(raw: *mut pq_sys::_PQconninfoOption) -> Vec<Self> { let mut vec = Vec::new(); for x in 0.. { unsafe { if (*raw.offset(x)).keyword.is_nul
} impl Default for Info { fn default() -> Self { unsafe { let raw = pq_sys::PQconndefaults(); let info = raw.into(); pq_sys::PQconninfoFree(raw); info } } } #[doc(hidden)] impl From<*mut pq_sys::_PQconninfoOption> for Info { fn from(info: *mut pq_sys::_PQconninfoOption) -> Self { Self::from_raw(info) } } #[cfg(test)] mod test { #[test] fn parse_info() { assert!(crate::connection::Info::from("host=localhost user=postgres").is_ok()); assert_eq!( crate::connection::Info::from("'"), Err("missing \"=\" after \"'\" in connection info string\n".to_string()) ); } #[test] fn defaults() { let _ = crate::connection::Info::default(); } }
l() { break; } else { let info = raw.offset(x).into(); vec.push(info); } } } vec }
function_block-function_prefixed
[ { "content": "#[deprecated(note = \"Use libpq::Connection::escape_string instead\")]\n\npub fn string(from: &str) -> String {\n\n let c_from = crate::ffi::to_cstr(from);\n\n // @see https://github.com/postgres/postgres/blob/REL_12_2/src/interfaces/libpq/fe-exec.c#L3329\n\n let cstring = crate::ffi::new...
Rust
simulator/src/sim/actions/yin_yang_magic.rs
rainbowbismuth/birb-brains-bot
f168ec06c5c5cc8d41589437c6f91f0d97289167
use crate::sim::actions::{Ability, AbilityImpl, Action, AoE, ALLY_OK, FOE_OK}; use crate::sim::common::{mod_6_formula, AddConditionSpellImpl, ConditionClearSpellImpl}; use crate::sim::{ Combatant, CombatantId, Condition, Element, Event, Simulation, Source, CAN_BE_CALCULATED, CAN_BE_REFLECTED, SILENCEABLE, }; pub const YIN_YANG_MAGIC_ABILITIES: &[Ability] = &[ Ability { name: "Blind", flags: FOE_OK | SILENCEABLE | CAN_BE_REFLECTED | CAN_BE_CALCULATED, mp_cost: 4, aoe: AoE::Diamond(1, Some(1)), implementation: &AddConditionSpellImpl { condition: &[Condition::Darkness], can_be_evaded: true, ignore_magic_def: false, base_chance: 200, ctr: 2, range: 5, }, }, Ability { name: "Spell Absorb", flags: FOE_OK | SILENCEABLE, mp_cost: 2, aoe: AoE::None, implementation: &AbsorbSpellImpl { hp_not_mp: false, amount: 0.33, base_chance: 175, ctr: 2, range: 5, }, }, Ability { name: "Life Drain", flags: FOE_OK | SILENCEABLE, mp_cost: 16, aoe: AoE::None, implementation: &AbsorbSpellImpl { hp_not_mp: true, amount: 0.25, base_chance: 185, ctr: 2, range: 5, }, }, Ability { name: "Pray Faith", flags: ALLY_OK | FOE_OK | SILENCEABLE | CAN_BE_REFLECTED | CAN_BE_CALCULATED, mp_cost: 6, aoe: AoE::None, implementation: &AddConditionSpellImpl { condition: &[Condition::Faith], can_be_evaded: false, ignore_magic_def: false, base_chance: 150, ctr: 4, range: 5, }, }, Ability { name: "Doubt Faith", flags: ALLY_OK | FOE_OK | SILENCEABLE | CAN_BE_REFLECTED | CAN_BE_CALCULATED, mp_cost: 6, aoe: AoE::None, implementation: &AddConditionSpellImpl { condition: &[Condition::Innocent], can_be_evaded: false, ignore_magic_def: false, base_chance: 150, ctr: 4, range: 5, }, }, Ability { name: "Zombie", flags: FOE_OK | SILENCEABLE | CAN_BE_REFLECTED | CAN_BE_CALCULATED, mp_cost: 20, aoe: AoE::None, implementation: &AddConditionSpellImpl { condition: &[Condition::Undead], can_be_evaded: true, ignore_magic_def: false, base_chance: 115, ctr: 5, range: 5, }, }, Ability { name: "Silence Song", flags: FOE_OK | SILENCEABLE | CAN_BE_REFLECTED | CAN_BE_CALCULATED, mp_cost: 16, aoe: AoE::Diamond(1, Some(1)), implementation: &AddConditionSpellImpl { condition: &[Condition::Silence], can_be_evaded: true, ignore_magic_def: false, base_chance: 180, ctr: 3, range: 5, }, }, Ability { name: "Blind Rage", flags: FOE_OK | SILENCEABLE | CAN_BE_REFLECTED | CAN_BE_CALCULATED, mp_cost: 16, aoe: AoE::None, implementation: &AddConditionSpellImpl { condition: &[Condition::Berserk], can_be_evaded: true, ignore_magic_def: false, base_chance: 130, ctr: 5, range: 5, }, }, Ability { name: "Confusion Song", flags: FOE_OK | SILENCEABLE | CAN_BE_REFLECTED | CAN_BE_CALCULATED, mp_cost: 20, aoe: AoE::None, implementation: &AddConditionSpellImpl { condition: &[Condition::Confusion], can_be_evaded: true, ignore_magic_def: false, base_chance: 135, ctr: 5, range: 5, }, }, Ability { name: "Dispel Magic", flags: FOE_OK | SILENCEABLE | CAN_BE_CALCULATED, mp_cost: 34, aoe: AoE::None, implementation: &ConditionClearSpellImpl { conditions: &[ Condition::Float, Condition::Reraise, Condition::Transparent, Condition::Regen, Condition::Protect, Condition::Shell, Condition::Haste, Condition::Faith, Condition::Reflect, ], base_chance: 200, ignore_magic_def: false, ctr: 3, range: 5, }, }, Ability { name: "Paralyze", flags: ALLY_OK | FOE_OK | SILENCEABLE | CAN_BE_REFLECTED | CAN_BE_CALCULATED, mp_cost: 10, aoe: AoE::Diamond(1, Some(0)), implementation: &AddConditionSpellImpl { condition: &[Condition::DontAct], can_be_evaded: true, ignore_magic_def: false, base_chance: 185, ctr: 5, range: 5, }, }, Ability { name: "Sleep", flags: ALLY_OK | FOE_OK | SILENCEABLE | CAN_BE_REFLECTED | CAN_BE_CALCULATED, mp_cost: 24, aoe: AoE::Diamond(1, Some(1)), implementation: &AddConditionSpellImpl { condition: &[Condition::Sleep], can_be_evaded: true, ignore_magic_def: false, base_chance: 175, ctr: 6, range: 5, }, }, Ability { name: "Petrify", flags: FOE_OK | SILENCEABLE | CAN_BE_REFLECTED | CAN_BE_CALCULATED, mp_cost: 16, aoe: AoE::None, implementation: &AddConditionSpellImpl { condition: &[Condition::Petrify], can_be_evaded: true, ignore_magic_def: false, base_chance: 125, ctr: 9, range: 5, }, }, ]; struct AbsorbSpellImpl { hp_not_mp: bool, amount: f32, base_chance: i16, range: u8, ctr: u8, } impl AbilityImpl for AbsorbSpellImpl { fn consider<'a>( &self, actions: &mut Vec<Action<'a>>, ability: &'a Ability<'a>, _sim: &Simulation<'a>, _user: &Combatant<'a>, target: &Combatant<'a>, ) { actions.push(Action::new( ability, self.range, Some(self.ctr), target.id(), )); } fn perform<'a>(&self, sim: &mut Simulation<'a>, user_id: CombatantId, target_id: CombatantId) { let user = sim.combatant(user_id); let target = sim.combatant(target_id); if sim.do_magical_evade(user, target, Source::Ability) { return; } let success_chance = mod_6_formula(user, target, Element::None, self.base_chance, false); if !(sim.roll_auto_succeed() < success_chance) { sim.log_event(Event::AbilityMissed(user_id, target_id)); return; } if self.hp_not_mp { let absorbed_amount = (target.max_hp() as f32 * self.amount) as i16; sim.change_target_hp(target_id, absorbed_amount, Source::Ability); sim.change_target_hp(user_id, -absorbed_amount, Source::Ability); } else { let absorbed_amount = (target.max_mp() as f32 * self.amount) as i16; sim.change_target_mp(target_id, absorbed_amount, Source::Ability); sim.change_target_mp(user_id, -absorbed_amount, Source::Ability); } } }
use crate::sim::actions::{Ability, AbilityImpl, Action, AoE, ALLY_OK, FOE_OK}; use crate::sim::common::{mod_6_formula, AddConditionSpellImpl, ConditionClearSpellImpl}; use crate::sim::{ Combatant, CombatantId, Condition, Element, Event, Simulation, Source, CAN_BE_CALCULATED, CAN_BE_REFLECTED, SILENCEABLE, }; pub const YIN_YANG_MAGIC_ABILITIES: &[Ability] = &[ Ability { name: "Blind", flags: FOE_OK | SILENCEABLE | CAN_BE_REFLECTED | CAN_BE_CALCULATED, mp_cost: 4, aoe: AoE::Diamond(1, Some(1)), implementation: &AddConditionSpellImpl { condition: &[Condition::Darkness], can_be_evaded: true, ignore_magic_def: false, base_chance: 200, ctr: 2, range: 5, }, }, Ability { name: "Spell Absorb", flags: FOE_OK | SILENCEABLE, mp_cost: 2, aoe: AoE::None, implementation: &AbsorbSpellImpl { hp_not_mp: false, amount: 0.33, base_chance: 175, ctr: 2, range: 5, }, }, Ability { name: "Life Drain", flags: FOE_OK | SILENCEABLE, mp_cost: 16, aoe: AoE::None, implementation: &AbsorbSpellImpl { hp_not_mp: true, amount: 0.25, base_chance: 185, ctr: 2, range: 5, }, }, Ability { name: "Pray Faith", flags: ALLY_OK | FOE_OK | SILENCEABLE | CAN_BE_REFLECTED | CAN_BE_CALCULATED, mp_cost: 6, aoe: AoE::None, implementation: &AddConditionSpellImpl { condition: &[Condition::Faith], can_be_evaded: false, ignore_magic_def: false, base_chance: 150, ctr: 4, range: 5, }, }, Ability { name: "Doubt Faith", flags: ALLY_OK | FOE_OK | SILENCEABLE | CAN_BE_REFLECTED | CAN_BE_CALCULATED, mp_cost: 6, aoe: AoE::None, implementation: &AddConditionSpellImpl { condition: &[Condition::Innocent], can_be_evaded: false, ignore_magic_def: false, base_chance: 150, ctr: 4, range: 5, }, }, Ability { name: "Zombie", flags: FOE_OK | SILENCEABLE | CAN_BE_REFLECTED | CAN_BE_CALCULATED, mp_cost: 20, aoe: AoE::None, implementation: &AddConditionSpellImpl { condition: &[Condition::Undead], can_be_evaded: true, ignore_magic_def: false, base_chance: 115, ctr: 5, range: 5, }, }, Ability { name: "Silence Song", flags: FOE_OK | SILENCEABLE | CAN_BE_REFLECTED | CAN_BE_CALCULATED, mp_cost: 16, aoe: AoE::Diamond(1, Some(1)), implementation: &AddConditionSpellImpl { condition: &[Condition::Silence], can_be_evaded: true, ignore_magic_def: false, base_chance: 180, ctr: 3, range: 5, }, }, Ability { name: "Blind Rage", flags: FOE_OK | SILENCEABLE | CAN_BE_REFLECTED | CAN_BE_CALCULATED, mp_cost: 16, aoe: AoE::None, implementation: &AddConditionSpellImpl { condition: &[Condition::Berserk], can_be_evaded: true, ignore_magic_def: false, base_chance: 130, ctr: 5, range: 5, }, }, Ability { name: "Confusion Song", flags: FOE_OK | SILENCEABLE | CAN_BE_REFLECTED | CAN_BE_CALCULATED, mp_cost: 20, aoe: AoE::None, implementation: &AddConditionSpellImpl { condition: &[Condition::Confusion], can_be_evaded: true, ignore_magic_def: false, base_chance: 135, ctr: 5, range: 5, }, }, Ability { name: "Dispel Magic", flags: FOE_OK | SILENCEABLE | CAN_BE_CALCULATED, mp_cost: 34, aoe: AoE::None, implementation: &ConditionClearSpellImpl { conditions: &[ Condition::Float, Condition::Reraise, Condition::Transparent, Condition::Regen, Condition::Protect, Condition::Shell, Condition::Haste, Condition::Faith, Condition::Reflect, ], base_chance: 200, ignore_magic_def: false, ctr: 3, range: 5, }, }, Ability { name: "Paralyze", flags: ALLY_OK | FOE_OK | SILENCEABLE | CAN_BE_REFLECTED | CAN_BE_CALCULATED, mp_cost: 10, aoe: AoE::Diamond(1, Some(0)), implementation: &AddConditionSpellImpl { condition: &[Condition::DontAct], can_be_evaded: true, ignore_magic_def: false, base_chance: 185, ctr: 5, range: 5, }, }, Ability { name: "Sleep", flags: ALLY_OK | FOE_OK | SILENCEABLE | CAN_BE_REFLECTED | CAN_BE_CALCULATED, mp_cost: 24, aoe: AoE::Diamond(1, Some(1)), implementation: &AddConditionSpellImpl { condition: &[Condition::Sleep], can_be_evaded: true, ignore_magic_def: false, base_chance: 175, ctr: 6, range: 5, }, }, Ability { name: "Petrify", flags: FOE_OK | SILENCEABLE | CAN_BE_REFLECTED | CAN_BE_CALCULATED, mp_cost: 16, aoe: AoE::None, implementation: &AddConditionSpellImpl { condition: &[Condition::Petrify], can_be_evaded: true, ignore_magic_def: false, base_chance: 125, ctr: 9, range: 5, }, }, ]; struct AbsorbSpellImpl { hp_not_mp: bool, amount: f32, base_chance: i16, range: u8, ctr: u8, } impl AbilityImpl for AbsorbSpellImpl { fn consider<'a>( &self, actions: &mut Vec<Action<'a>>, ability: &'a Ability<'a>, _sim: &Simulation<'a>, _user: &Combatant<'a>, target: &Combatant<'a>, ) { actions.push(Action::new( ability, self.range, Some(self.ctr), target.id(), )); } fn perform<'a>(&self, sim: &mut Simulation<'a>, user_id: CombatantId, target_id: CombatantId) { let user = sim.combatant(user_id); let target = sim.combatant(target_id); if sim.do_magi
tyMissed(user_id, target_id)); return; } if self.hp_not_mp { let absorbed_amount = (target.max_hp() as f32 * self.amount) as i16; sim.change_target_hp(target_id, absorbed_amount, Source::Ability); sim.change_target_hp(user_id, -absorbed_amount, Source::Ability); } else { let absorbed_amount = (target.max_mp() as f32 * self.amount) as i16; sim.change_target_mp(target_id, absorbed_amount, Source::Ability); sim.change_target_mp(user_id, -absorbed_amount, Source::Ability); } } }
cal_evade(user, target, Source::Ability) { return; } let success_chance = mod_6_formula(user, target, Element::None, self.base_chance, false); if !(sim.roll_auto_succeed() < success_chance) { sim.log_event(Event::Abili
function_block-random_span
[ { "content": "pub fn in_range(user: &Combatant, range: u8, target: &Combatant) -> bool {\n\n let dist = user.distance(target);\n\n dist <= range as i16\n\n}\n\n\n", "file_path": "simulator/src/sim/simulation.rs", "rank": 0, "score": 452225.96033337904 }, { "content": "pub fn can_move_i...
Rust
src/kms/gcpkms.rs
stemid/roughenough
7bc4ea5d34fac53d33ff2ed53bb7a70a2c1aca93
#[cfg(feature = "gcpkms")] pub mod inner { extern crate base64; extern crate google_cloudkms1 as cloudkms1; extern crate hyper; extern crate hyper_rustls; extern crate yup_oauth2 as oauth2; use std::default::Default; use std::env; use std::path::Path; use std::result::Result; use self::cloudkms1::CloudKMS; use self::cloudkms1::{DecryptRequest, EncryptRequest}; use self::hyper::net::HttpsConnector; use self::hyper::status::StatusCode; use self::hyper_rustls::TlsClient; use self::oauth2::{ServiceAccountAccess, ServiceAccountKey}; use crate::kms::{EncryptedDEK, KmsError, KmsProvider, PlaintextDEK, AD}; const GOOGLE_APP_CREDS: &str = &"GOOGLE_APPLICATION_CREDENTIALS"; pub struct GcpKms { key_resource_id: String, service_account: ServiceAccountKey, } impl GcpKms { pub fn from_resource_id(resource_id: &str) -> Result<Self, KmsError> { let svc_acct = load_gcp_credential()?; Ok(GcpKms { key_resource_id: resource_id.to_string(), service_account: svc_acct, }) } fn new_hub(&self) -> CloudKMS<hyper::Client, ServiceAccountAccess<hyper::Client>> { let client1 = hyper::Client::with_connector(HttpsConnector::new(TlsClient::new())); let access = oauth2::ServiceAccountAccess::new(self.service_account.clone(), client1); let client2 = hyper::Client::with_connector(HttpsConnector::new(TlsClient::new())); CloudKMS::new(client2, access) } fn pretty_http_error(&self, resp: &hyper::client::Response) -> KmsError { let code = resp.status; let url = &resp.url; KmsError::OperationFailed(format!("Response {} from {}", code, url)) } } impl KmsProvider for GcpKms { fn encrypt_dek(&self, plaintext_dek: &PlaintextDEK) -> Result<EncryptedDEK, KmsError> { let mut request = EncryptRequest::default(); request.plaintext = Some(base64::encode(plaintext_dek)); request.additional_authenticated_data = Some(base64::encode(AD)); let hub = self.new_hub(); let result = hub .projects() .locations_key_rings_crypto_keys_encrypt(request, &self.key_resource_id) .doit(); match result { Ok((http_resp, enc_resp)) => { if http_resp.status == StatusCode::Ok { let ciphertext = enc_resp.ciphertext.unwrap(); let ct = base64::decode(&ciphertext)?; Ok(ct) } else { Err(self.pretty_http_error(&http_resp)) } } Err(e) => Err(KmsError::OperationFailed(format!("encrypt_dek() {:?}", e))), } } fn decrypt_dek(&self, encrypted_dek: &EncryptedDEK) -> Result<PlaintextDEK, KmsError> { let mut request = DecryptRequest::default(); request.ciphertext = Some(base64::encode(encrypted_dek)); request.additional_authenticated_data = Some(base64::encode(AD)); let hub = self.new_hub(); let result = hub .projects() .locations_key_rings_crypto_keys_decrypt(request, &self.key_resource_id) .doit(); match result { Ok((http_resp, enc_resp)) => { if http_resp.status == StatusCode::Ok { let plaintext = enc_resp.plaintext.unwrap(); let ct = base64::decode(&plaintext)?; Ok(ct) } else { Err(self.pretty_http_error(&http_resp)) } } Err(e) => Err(KmsError::OperationFailed(format!("decrypt_dek() {:?}", e))), } } } fn load_gcp_credential() -> Result<ServiceAccountKey, KmsError> { if let Ok(gac) = env::var(GOOGLE_APP_CREDS.to_string()) { return if Path::new(&gac).exists() { match oauth2::service_account_key_from_file(&gac) { Ok(svc_acct_key) => Ok(svc_acct_key), Err(e) => { Err(KmsError::InvalidConfiguration(format!( "Can't load service account credential '{}': {:?}", gac, e ))) } } } else { Err(KmsError::InvalidConfiguration(format!( "{} ='{}' does not exist", GOOGLE_APP_CREDS, gac ))) } } panic!( "Failed to load service account credential. Is {} set?", GOOGLE_APP_CREDS ); } }
#[cfg(feature = "gcpkms")] pub mod inner { extern crate base64; extern crate google_cloudkms1 as cloudkms1; extern crate hyper; extern crate hyper_rustls; extern crate yup_oauth2 as oauth2; use std::default::Default; use std::env; use std::path::Path; use std::result::Result; use self::cloudkms1::CloudKMS; use self::cloudkms1::{DecryptRequest, EncryptRequest}; use self::hyper::net::HttpsConnector; use self::hyper::status::StatusCode; use self::hyper_rustls::TlsClient; use self::oauth2::{ServiceAccountAccess, ServiceAccountKey}; use crate::kms::{EncryptedDEK, KmsError, KmsProvider, PlaintextDEK, AD}; const GOOGLE_APP_CREDS: &str = &"GOOGLE_APPLICATION_CREDENTIALS"; pub struct GcpKms { key_resource_id: String, service_account: ServiceAccountKey, } impl GcpKms { pub fn from_resource_id(resource_id: &str) -> Result<Self, KmsError> { let svc_acct = load_gcp_credential()?; Ok(GcpKms { key_resource_id: resource_id.to_string(), service_account: svc_acct, }) } fn new_hub(&self) -> CloudKMS<hyper::Client, ServiceAccountAccess<hyper::Client>> { let client1 = hyper::Client::with_connector(HttpsConnector::new(TlsClient::new())); let access = oauth2::ServiceAccountAccess::new(self.service_account.clone(), client1); let client2 = hyper::Client::with_connector(HttpsConnector::new(TlsClient::new())); CloudKMS::new(client2, access) } fn pretty_http_error(&self, resp: &hyper::client::Response) -> KmsError { let code = resp.status; let url = &resp.url; KmsError::OperationFailed(format!("Response {} from {}", code, url)) } } impl KmsProvider for GcpKms { fn encrypt_dek(&self, plaintext_dek: &PlaintextDEK) -> Result<EncryptedDEK, KmsError> { let mut request = EncryptRequest::default(); request.plaintext = Some(base64::encode(plaintext_dek)); request.additional_authenticated_data = Some(base64::encode(AD)); let hub = self.new_hub(); let result = hub .projects() .locations_key_rings_crypto_keys_encrypt(request, &self.key_resource_id) .doit();
} fn decrypt_dek(&self, encrypted_dek: &EncryptedDEK) -> Result<PlaintextDEK, KmsError> { let mut request = DecryptRequest::default(); request.ciphertext = Some(base64::encode(encrypted_dek)); request.additional_authenticated_data = Some(base64::encode(AD)); let hub = self.new_hub(); let result = hub .projects() .locations_key_rings_crypto_keys_decrypt(request, &self.key_resource_id) .doit(); match result { Ok((http_resp, enc_resp)) => { if http_resp.status == StatusCode::Ok { let plaintext = enc_resp.plaintext.unwrap(); let ct = base64::decode(&plaintext)?; Ok(ct) } else { Err(self.pretty_http_error(&http_resp)) } } Err(e) => Err(KmsError::OperationFailed(format!("decrypt_dek() {:?}", e))), } } } fn load_gcp_credential() -> Result<ServiceAccountKey, KmsError> { if let Ok(gac) = env::var(GOOGLE_APP_CREDS.to_string()) { return if Path::new(&gac).exists() { match oauth2::service_account_key_from_file(&gac) { Ok(svc_acct_key) => Ok(svc_acct_key), Err(e) => { Err(KmsError::InvalidConfiguration(format!( "Can't load service account credential '{}': {:?}", gac, e ))) } } } else { Err(KmsError::InvalidConfiguration(format!( "{} ='{}' does not exist", GOOGLE_APP_CREDS, gac ))) } } panic!( "Failed to load service account credential. Is {} set?", GOOGLE_APP_CREDS ); } }
match result { Ok((http_resp, enc_resp)) => { if http_resp.status == StatusCode::Ok { let ciphertext = enc_resp.ciphertext.unwrap(); let ct = base64::decode(&ciphertext)?; Ok(ct) } else { Err(self.pretty_http_error(&http_resp)) } } Err(e) => Err(KmsError::OperationFailed(format!("encrypt_dek() {:?}", e))), }
if_condition
[ { "content": "/// Factory function to create a `ServerConfig` _trait object_ based on the value\n\n/// of the provided `arg`.\n\n///\n\n/// * `ENV` will return an [`EnvironmentConfig`](struct.EnvironmentConfig.html)\n\n/// * any other value returns a [`FileConfig`](struct.FileConfig.html)\n\n///\n\npub fn m...
Rust
embrs/src/stm32f4/rcc/mod.rs
DCasFer/RustSimpleScheduler
25cda9d5d9601a56296589861556e7c173fbff04
use arm_m; use arm_m::reg::AtomicReg; use super::flash::FLASH; pub mod raw; pub use self::raw::{AhbPrescaler, ApbPrescaler, Cr, Cfgr, Pllcfgr}; pub use self::raw::Pllp as SysPrescaler; use self::raw::ClockDivisor; pub const BOOT_CLOCK_HZ : u32 = 16_000_000; pub struct Rcc; pub struct ClockConfig { pub crystal_hz: f32, pub crystal_divisor: u32, pub vco_multiplier: u32, pub general_divisor: SysPrescaler, pub pll48_divisor: u32, pub ahb_divisor: Option<AhbPrescaler>, pub apb1_divisor: Option<ApbPrescaler>, pub apb2_divisor: Option<ApbPrescaler>, pub flash_latency: u32, } pub struct ClockSpeeds { pub cpu: f32, pub ahb: f32, pub apb1: f32, pub apb2: f32, pub pll48: f32, } impl ClockSpeeds { pub fn get_clock_for<P: PeripheralName>(&self, p: P) -> f32 { p.get_clock(self) } } impl ClockConfig { pub fn compute_speeds(&self) -> ClockSpeeds { let vco_in_hz = self.crystal_hz / (self.crystal_divisor as f32); let vco_out_hz = vco_in_hz * (self.vco_multiplier as f32); let cpu = vco_out_hz / (self.general_divisor.to_divisor() as f32); ClockSpeeds { cpu: cpu, ahb: cpu / (self.ahb_divisor.to_divisor() as f32), apb1: cpu / (self.apb1_divisor.to_divisor() as f32), apb2: cpu / (self.apb2_divisor.to_divisor() as f32), pll48: vco_out_hz / (self.pll48_divisor as f32), } } } pub trait PeripheralName { fn enable_clock(self, rcc: &Rcc); fn get_clock(self, speeds: &ClockSpeeds) -> f32; } impl Rcc { fn reg(&self) -> &raw::Registers { unsafe { &*(raw::RCC_ADDRESS as *const raw::Registers) } } pub fn enable_clock<P: PeripheralName>(&self, p: P) { p.enable_clock(self); arm_m::data_synchronization_barrier(); } pub fn read_cr(&self) -> Cr { Cr(self.reg().cr.get()) } pub fn write_cr(&self, v: Cr) { self.reg().cr.set(v.0) } pub fn update_cr<F: FnOnce(Cr) -> Cr>(&self, f: F) { self.write_cr(f(self.read_cr())) } pub fn read_cfgr(&self) -> Cfgr { Cfgr(self.reg().cfgr.get()) } pub fn write_cfgr(&self, v: Cfgr) { self.reg().cfgr.set(v.0) } pub fn update_cfgr<F: FnOnce(Cfgr) -> Cfgr>(&self, f: F) { self.write_cfgr(f(self.read_cfgr())) } pub fn read_pllcfgr(&self) -> Pllcfgr { Pllcfgr(self.reg().pllcfgr.get()) } pub fn write_pllcfgr(&self, v: Pllcfgr) { self.reg().pllcfgr.set(v.0) } pub fn update_pllcfgr<F: FnOnce(Pllcfgr) -> Pllcfgr>(&self, f: F) { self.write_pllcfgr(f(self.read_pllcfgr())) } pub fn configure_clocks(&self, cfg: &ClockConfig) { self.update_cr(|v| v.with_hsion(true)); while !self.read_cr().get_hsirdy() {} self.update_cfgr(|v| v.with_sw(raw::ClockSwitch::Hsi)); while self.read_cfgr().get_sws() != Ok(raw::ClockSwitch::Hsi) {} self.update_cr(|v| v.with_pllon(false)); while self.read_cr().get_pllrdy() {} self.update_cfgr(|v| v.with_hpre(cfg.ahb_divisor) .with_ppre1(cfg.apb1_divisor) .with_ppre2(cfg.apb2_divisor)); FLASH.update_acr(|v| v.with_latency(cfg.flash_latency)); self.update_cr(|v| v.with_hseon(true)); while !self.read_cr().get_hserdy() {} self.update_pllcfgr(|v| v.with_pllm(cfg.crystal_divisor) .with_plln(cfg.vco_multiplier) .with_pllp(cfg.general_divisor) .with_pllq(cfg.pll48_divisor) .with_pllsrc(raw::PllSource::Hse)); self.update_cr(|v| v.with_pllon(true)); while !self.read_cr().get_pllrdy() {} self.update_cfgr(|v| v.with_sw(raw::ClockSwitch::Pll)); while self.read_cfgr().get_sws() != Ok(raw::ClockSwitch::Pll) {} } } #[derive(Copy, Clone)] pub enum AhbBus { Ahb1 = 0, Ahb2 = 1, Ahb3 = 2, } macro_rules! peripheral_enum { ( $(#[$m:meta])* pub enum $tyname:ident ($bty:ident) { $( $(#[$e_m:meta])* p $name:ident = $bus:tt | $idx:tt | $rst:tt | $clk:tt | $lp:tt, )* } ) => { $(#[$m])* #[derive(Copy, Clone, Eq, PartialEq)] #[repr(u32)] pub enum $tyname { $( $(#[$e_m])* $name = ($bty::$bus as u32) | ($idx << 8) | ($rst << 16) | ($clk << 17) | ($lp << 18), )* } impl $tyname { #[inline] pub fn get_bus(self) -> $bty { let idx = (self as u32) & 0xF; unsafe { ::core::mem::transmute(idx as u8) } } #[inline] pub fn get_bit_index(self) -> u32 { ((self as u32) >> 8) & 0x1F } #[inline] pub fn has_rst(self) -> bool { ((self as u32) & (1 << 16)) != 0 } #[inline] pub fn has_enr(self) -> bool { ((self as u32) & (1 << 17)) != 0 } #[inline] pub fn has_lpenr(self) -> bool { ((self as u32) & (1 << 18)) != 0 } } }; } peripheral_enum! { pub enum AhbPeripheral (AhbBus) { p GpioA = Ahb1 | 0 | 1 | 1 | 1, p GpioB = Ahb1 | 1 | 1 | 1 | 1, p GpioC = Ahb1 | 2 | 1 | 1 | 1, p GpioD = Ahb1 | 3 | 1 | 1 | 1, p GpioE = Ahb1 | 4 | 1 | 1 | 1, p GpioF = Ahb1 | 5 | 1 | 1 | 1, p GpioG = Ahb1 | 6 | 1 | 1 | 1, p GpioH = Ahb1 | 7 | 1 | 1 | 1, p GpioI = Ahb1 | 8 | 1 | 1 | 1, #[cfg(feature = "soc_family:stm32f4[23]")] p GpioJ = Ahb1 | 9 | 1 | 1 | 1, #[cfg(feature = "soc_family:stm32f4[23]")] p GpioK = Ahb1 | 10 | 1 | 1 | 1, p Crc = Ahb1 | 12 | 1 | 1 | 1, p FlashIface = Ahb1 | 15 | 0 | 0 | 1, p Sram1 = Ahb1 | 16 | 0 | 0 | 1, p Sram2 = Ahb1 | 17 | 0 | 0 | 1, p BackupSram = Ahb1 | 18 | 0 | 1 | 1, #[cfg(feature = "soc_family:stm32f4[23]")] p Sram3 = Ahb1 | 19 | 0 | 0 | 1, p CcmDataRam = Ahb1 | 20 | 0 | 1 | 0, p Dma1 = Ahb1 | 21 | 1 | 1 | 1, p Dma2 = Ahb1 | 22 | 1 | 1 | 1, #[cfg(feature = "soc_family:stm32f4[23]")] p Dma2d = Ahb1 | 23 | 1 | 1 | 1, p Ethernet = Ahb1 | 25 | 1 | 1 | 1, p EthernetTx = Ahb1 | 26 | 0 | 1 | 1, p EthernetRx = Ahb1 | 27 | 0 | 1 | 1, p EthernetPtp = Ahb1 | 28 | 0 | 1 | 1, p UsbOtgHs = Ahb1 | 29 | 1 | 1 | 1, p UsbOtgHsUlpi = Ahb1 | 30 | 0 | 1 | 1, p Dcmi = Ahb2 | 0 | 1 | 1 | 1, p Cryp = Ahb2 | 4 | 1 | 1 | 1, p Hash = Ahb2 | 5 | 1 | 1 | 1, p Rng = Ahb2 | 6 | 1 | 1 | 1, p UsbOtgFs = Ahb2 | 7 | 1 | 1 | 1, p Fsmc = Ahb3 | 0 | 1 | 1 | 1, } } impl PeripheralName for AhbPeripheral { fn enable_clock(self, rcc: &Rcc) { if !self.has_enr() { panic!("cannot control clock for AHB{} idx {}", (self.get_bus() as u32) + 1, self.get_bit_index()) } rcc.reg() .ahb_enr[self.get_bus() as usize] .atomic_or(1 << self.get_bit_index()) } fn get_clock(self, speeds: &ClockSpeeds) -> f32 { speeds.ahb } } #[derive(Copy, Clone)] pub enum ApbBus { Apb1 = 0, Apb2 = 1, } peripheral_enum! { pub enum ApbPeripheral (ApbBus) { p Tim2 = Apb1 | 0 | 1 | 1 | 1, p Tim3 = Apb1 | 1 | 1 | 1 | 1, p Tim4 = Apb1 | 2 | 1 | 1 | 1, p Tim5 = Apb1 | 3 | 1 | 1 | 1, p Tim6 = Apb1 | 4 | 1 | 1 | 1, p Tim7 = Apb1 | 5 | 1 | 1 | 1, p Tim12 = Apb1 | 6 | 1 | 1 | 1, p Tim13 = Apb1 | 7 | 1 | 1 | 1, p Tim14 = Apb1 | 8 | 1 | 1 | 1, p Wwdg = Apb1 | 11 | 1 | 1 | 1, p Spi2 = Apb1 | 14 | 1 | 1 | 1, p Spi3 = Apb1 | 15 | 1 | 1 | 1, p Usart2 = Apb1 | 17 | 1 | 1 | 1, p Usart3 = Apb1 | 18 | 1 | 1 | 1, p Uart4 = Apb1 | 19 | 1 | 1 | 1, p Uart5 = Apb1 | 20 | 1 | 1 | 1, p I2c1 = Apb1 | 21 | 1 | 1 | 1, p I2c2 = Apb1 | 22 | 1 | 1 | 1, p I2c3 = Apb1 | 23 | 1 | 1 | 1, p Can1 = Apb1 | 25 | 1 | 1 | 1, p Can2 = Apb1 | 26 | 1 | 1 | 1, p Pwr = Apb1 | 28 | 1 | 1 | 1, p Dac = Apb1 | 29 | 1 | 1 | 1, #[cfg(feature = "soc_family:stm32f4[23]")] p Uart7 = Apb1 | 30 | 1 | 1 | 1, #[cfg(feature = "soc_family:stm32f4[23]")] p Uart8 = Apb1 | 31 | 1 | 1 | 1, p Tim1 = Apb2 | 0 | 1 | 1 | 1, p Tim8 = Apb2 | 1 | 1 | 1 | 1, p Usart1 = Apb2 | 4 | 1 | 1 | 1, p Usart6 = Apb2 | 5 | 1 | 1 | 1, p Adc1 = Apb2 | 8 | 1 | 1 | 1, p Adc2 = Apb2 | 9 | 0 | 1 | 1, p Adc3 = Apb2 | 10 | 0 | 1 | 1, p Sdio = Apb2 | 11 | 1 | 1 | 1, p Spi1 = Apb2 | 12 | 1 | 1 | 1, #[cfg(feature = "soc_family:stm32f4[23]")] p Spi4 = Apb2 | 13 | 1 | 1 | 1, p Syscfg = Apb2 | 14 | 1 | 1 | 1, p Tim9 = Apb2 | 16 | 1 | 1 | 1, p Tim10 = Apb2 | 17 | 1 | 1 | 1, p Tim11 = Apb2 | 18 | 1 | 1 | 1, #[cfg(feature = "soc_family:stm32f4[23]")] p Spi5 = Apb2 | 20 | 1 | 1 | 1, #[cfg(feature = "soc_family:stm32f4[23]")] p Spi6 = Apb2 | 21 | 1 | 1 | 1, #[cfg(feature = "soc_family:stm32f4[23]")] p Sai1 = Apb2 | 22 | 1 | 1 | 1, #[cfg(feature = "soc_family:stm32f4[23]")] p Ltdc = Apb2 | 26 | 1 | 1 | 1, } } impl PeripheralName for ApbPeripheral { fn enable_clock(self, rcc: &Rcc) { if !self.has_enr() { panic!("cannot control clock for APB{} idx {}", (self.get_bus() as u32) + 1, self.get_bit_index()) } rcc.reg() .apb_enr[self.get_bus() as usize] .atomic_or(1 << self.get_bit_index()) } fn get_clock(self, speeds: &ClockSpeeds) -> f32 { match self.get_bus() { ApbBus::Apb1 => speeds.apb1, ApbBus::Apb2 => speeds.apb2, } } } pub static RCC: Rcc = Rcc;
use arm_m; use arm_m::reg::AtomicReg; use super::flash::FLASH; pub mod raw; pub use self::raw::{AhbPrescaler, ApbPrescaler, Cr, Cfgr, Pllcfgr}; pub use self::raw::Pllp as SysPrescaler; use self::raw::ClockDivisor; pub const BOOT_CLOCK_HZ : u32 = 16_000_000; pub struct Rcc; pub struct ClockConfig { pub crystal_hz: f32, pub crystal_divisor: u32, pub vco_multiplier: u32, pub general_divisor: SysPrescaler, pub pll48_divisor: u32, pub ahb_divisor: Option<AhbPrescaler>, pub apb1_divisor: Option<ApbPrescaler>, pub apb2_divisor: Option<ApbPrescaler>, pub flash_latency: u32, } pub struct ClockSpeeds { pub cpu: f32, pub ahb: f32, pub apb1: f32, pub apb2: f32, pub pll48: f32, } impl ClockSpeeds { pub fn get_clock_for<P: PeripheralName>(&self, p: P) -> f32 { p.get_clock(self) } } impl ClockConfig { pub fn compute_speeds(&self) -> ClockSpeeds { let vco_in_hz = self.crystal_hz / (self.crystal_divisor as f32); let vco_out_hz = vco_in_hz * (self.vco_multiplier as f32); let cpu = vco_out_hz / (self.general_divisor.to_divisor() as f32); ClockSpeeds { cpu: cpu, ahb: cpu / (self.ahb_divisor.to_divisor() as f32), apb1: cpu / (self.apb1_divisor.to_divisor() as f32), apb2: cpu / (self.apb2_divisor.to_divisor() as f32), pll48: vco_out_hz / (self.pll48_divisor as f32), } } } pub trait PeripheralName { fn enable_clock(self, rcc: &Rcc); fn get_clock(self, speeds: &ClockSpeeds) -> f32; } impl Rcc { fn reg(&self) -> &raw::Registers { unsafe { &*(raw::RCC_ADDRESS as *const raw::Registers) } } pub fn enable_clock<P: PeripheralName>(&self, p: P) { p.enable_clock(self); arm_m::data_synchronization_barrier(); } pub fn read_cr(&self) -> Cr { Cr(self.reg().cr.get()) } pub fn write_cr(&self, v: Cr) { self.reg().cr.set(v.0) } pub fn update_cr<F: FnOnce(Cr) -> Cr>(&self, f: F) { self.write_cr(f(self.read_cr())) } pub fn read_cfgr(&self) -> Cfgr { Cfgr(self.reg().cfgr.get()) } pub fn write_cfgr(&self, v: Cfgr) { self.reg().cfgr.set(v.0) } pub fn update_cfgr<F: FnOnce(Cfgr) -> Cfgr>(&self, f: F) { self.write_cfgr(f(self.read_cfgr())) } pub fn read_pllcfgr(&self) -> Pllcfgr { Pllcfgr(self.reg().pllcfgr.get()) } pub fn write_pllcfgr(&self, v: Pllcfgr) { self.reg().pllcfgr.set(v.0) } pub fn update_pllcfgr<F: FnOnce(Pllcfgr) -> Pllcfgr>(&self, f: F) { self.write_pllcfgr(f(self.read_pllcfgr())) } pub fn configure_clocks(&self, cfg: &ClockConfig) { self.update_cr(|v| v.with_hsion(true)); while !self.read_cr().get_hsirdy() {} self.update_cfgr(|v| v.with_sw(raw::ClockSwitch::Hsi)); while self.read_cfgr().get_sws() != Ok(raw::ClockSwitch::Hsi) {} self.update_cr(|v| v.with_pllon(false)); while self.read_cr().get_pllrdy() {} self.update_cfgr(|v| v.with_hpre(cfg.ahb_divisor) .with_ppre1(cfg.apb1_divisor) .with_ppre2(cfg.apb2_divisor)); FLASH.update_acr(|v| v.with_latency(cfg.flash_latency)); self.update_cr(|v| v.with_hseon(true)); while !self.read_cr().get_hserdy() {} self.update_pllcfgr(|v| v.with_pllm(cfg.crystal_divisor) .with_plln(cfg.vco_multiplier) .with_pllp(cfg.general_divisor) .with_pllq(cfg.pll48_divisor) .with_pllsrc(raw::PllSource::Hse)); self.update_cr(|v| v.with_pllon(true)); while !self.read_cr().get_pllrdy() {} self.update_cfgr(|v| v.with_sw(raw::ClockSwitch::Pll)); while self.read_cfgr().get_sws() != Ok(raw::ClockSwitch::Pll) {} } } #[derive(Copy, Clone)] pub enum AhbBus { Ahb1 = 0, Ahb2 = 1, Ahb3 = 2, } macro_rules! peripheral_enum { ( $(#[$m:meta])* pub enum $tyname:ident ($bty:ident) { $( $(#[$e_m:meta])* p $name:ident = $bus:tt | $idx:tt | $rst:tt | $clk:tt | $lp:tt, )* } ) => { $(#[$m])* #[derive(Copy, Clone, Eq, PartialEq)] #[repr(u32)] pub enum $tyname { $( $(#[$e_m])* $name = ($bty::$bus as u32) | ($idx << 8) | ($rst << 16) | ($clk << 17) | ($lp << 18), )* } impl $tyname { #[inline] pub fn get_bus(self) -> $bty { let idx = (self as u32) & 0xF; unsafe { ::core::mem::transmute(idx as u8) } } #[inline] pub fn get_bit_index(self) -> u32 { ((self as u32) >> 8) & 0x1F } #[inline] pub fn has_rst(self) -> bool { ((self as u32) & (1 << 16)) != 0 } #[inline] pub fn has_enr(self) -> bool { ((self as u32) & (1 << 17)) != 0 } #[inline] pub fn has_lpenr(self) -> bool { ((self as u32) & (1 << 18)) != 0 } } }; } peripheral_enum! { pub enum AhbPeripheral (AhbBus) { p GpioA = Ahb1 | 0 | 1 | 1 | 1, p GpioB = Ahb1 | 1 | 1 | 1 | 1, p GpioC = Ahb1 | 2 | 1 | 1 | 1, p GpioD = Ahb1 | 3 | 1 | 1 | 1, p GpioE = Ahb1 | 4 | 1 | 1 | 1, p GpioF = Ahb1 | 5 | 1 | 1 | 1, p GpioG = Ahb1 | 6 | 1 | 1 | 1, p GpioH = Ahb1 | 7 | 1 | 1 | 1, p GpioI = Ahb1 | 8 | 1 | 1 | 1, #[cfg(feature = "soc_family:stm32f4[23]")] p GpioJ = Ahb1 | 9 | 1 | 1 | 1, #[cfg(feature = "soc_family:stm32f4[23]")] p GpioK = Ahb1 | 10 | 1 | 1 | 1, p Crc = Ahb1 | 12 | 1 | 1 | 1, p FlashIface = Ahb1 | 15 | 0 | 0 | 1, p Sram1 = Ahb1 | 16 | 0 | 0 | 1, p Sram2 = Ahb1 | 17 | 0 | 0 | 1, p BackupSram = Ahb1 | 18 | 0 | 1 | 1, #[cfg(feature = "soc_family:stm32f4[23]")] p Sram3 = Ahb1 | 19 | 0 | 0 | 1, p CcmDataRam = Ahb1 | 20 | 0 | 1 | 0, p Dma1 = Ahb1 | 21 | 1 | 1 | 1, p Dma2 = Ahb1 | 22 | 1 | 1 | 1, #[cfg(feature = "soc_family:stm32f4[23]")] p Dma2d = Ahb1 | 23 | 1 | 1 | 1, p Ethernet = Ahb1 | 25 | 1 | 1 | 1, p EthernetTx = Ahb1 | 26 | 0 | 1 | 1, p EthernetRx = Ahb1 | 27 | 0 | 1 | 1, p EthernetPtp = Ahb1 | 28 | 0 | 1 | 1, p UsbOtgHs = Ahb1 | 29 | 1 | 1 | 1, p UsbOtgHsUlpi = Ahb1 | 30 | 0 | 1 | 1, p Dcmi = Ahb2 | 0 | 1 | 1 | 1, p Cryp = Ahb2 | 4 | 1 | 1 | 1, p Hash = Ahb2 | 5 | 1 | 1 | 1, p Rng = Ahb2 | 6 | 1 | 1 | 1, p UsbOtgFs = Ahb2 | 7 | 1 | 1 | 1, p Fsmc = Ahb3 | 0 | 1 | 1 | 1, } } impl PeripheralName for AhbPeripheral { f
fn get_clock(self, speeds: &ClockSpeeds) -> f32 { speeds.ahb } } #[derive(Copy, Clone)] pub enum ApbBus { Apb1 = 0, Apb2 = 1, } peripheral_enum! { pub enum ApbPeripheral (ApbBus) { p Tim2 = Apb1 | 0 | 1 | 1 | 1, p Tim3 = Apb1 | 1 | 1 | 1 | 1, p Tim4 = Apb1 | 2 | 1 | 1 | 1, p Tim5 = Apb1 | 3 | 1 | 1 | 1, p Tim6 = Apb1 | 4 | 1 | 1 | 1, p Tim7 = Apb1 | 5 | 1 | 1 | 1, p Tim12 = Apb1 | 6 | 1 | 1 | 1, p Tim13 = Apb1 | 7 | 1 | 1 | 1, p Tim14 = Apb1 | 8 | 1 | 1 | 1, p Wwdg = Apb1 | 11 | 1 | 1 | 1, p Spi2 = Apb1 | 14 | 1 | 1 | 1, p Spi3 = Apb1 | 15 | 1 | 1 | 1, p Usart2 = Apb1 | 17 | 1 | 1 | 1, p Usart3 = Apb1 | 18 | 1 | 1 | 1, p Uart4 = Apb1 | 19 | 1 | 1 | 1, p Uart5 = Apb1 | 20 | 1 | 1 | 1, p I2c1 = Apb1 | 21 | 1 | 1 | 1, p I2c2 = Apb1 | 22 | 1 | 1 | 1, p I2c3 = Apb1 | 23 | 1 | 1 | 1, p Can1 = Apb1 | 25 | 1 | 1 | 1, p Can2 = Apb1 | 26 | 1 | 1 | 1, p Pwr = Apb1 | 28 | 1 | 1 | 1, p Dac = Apb1 | 29 | 1 | 1 | 1, #[cfg(feature = "soc_family:stm32f4[23]")] p Uart7 = Apb1 | 30 | 1 | 1 | 1, #[cfg(feature = "soc_family:stm32f4[23]")] p Uart8 = Apb1 | 31 | 1 | 1 | 1, p Tim1 = Apb2 | 0 | 1 | 1 | 1, p Tim8 = Apb2 | 1 | 1 | 1 | 1, p Usart1 = Apb2 | 4 | 1 | 1 | 1, p Usart6 = Apb2 | 5 | 1 | 1 | 1, p Adc1 = Apb2 | 8 | 1 | 1 | 1, p Adc2 = Apb2 | 9 | 0 | 1 | 1, p Adc3 = Apb2 | 10 | 0 | 1 | 1, p Sdio = Apb2 | 11 | 1 | 1 | 1, p Spi1 = Apb2 | 12 | 1 | 1 | 1, #[cfg(feature = "soc_family:stm32f4[23]")] p Spi4 = Apb2 | 13 | 1 | 1 | 1, p Syscfg = Apb2 | 14 | 1 | 1 | 1, p Tim9 = Apb2 | 16 | 1 | 1 | 1, p Tim10 = Apb2 | 17 | 1 | 1 | 1, p Tim11 = Apb2 | 18 | 1 | 1 | 1, #[cfg(feature = "soc_family:stm32f4[23]")] p Spi5 = Apb2 | 20 | 1 | 1 | 1, #[cfg(feature = "soc_family:stm32f4[23]")] p Spi6 = Apb2 | 21 | 1 | 1 | 1, #[cfg(feature = "soc_family:stm32f4[23]")] p Sai1 = Apb2 | 22 | 1 | 1 | 1, #[cfg(feature = "soc_family:stm32f4[23]")] p Ltdc = Apb2 | 26 | 1 | 1 | 1, } } impl PeripheralName for ApbPeripheral { fn enable_clock(self, rcc: &Rcc) { if !self.has_enr() { panic!("cannot control clock for APB{} idx {}", (self.get_bus() as u32) + 1, self.get_bit_index()) } rcc.reg() .apb_enr[self.get_bus() as usize] .atomic_or(1 << self.get_bit_index()) } fn get_clock(self, speeds: &ClockSpeeds) -> f32 { match self.get_bus() { ApbBus::Apb1 => speeds.apb1, ApbBus::Apb2 => speeds.apb2, } } } pub static RCC: Rcc = Rcc;
n enable_clock(self, rcc: &Rcc) { if !self.has_enr() { panic!("cannot control clock for AHB{} idx {}", (self.get_bus() as u32) + 1, self.get_bit_index()) } rcc.reg() .ahb_enr[self.get_bus() as usize] .atomic_or(1 << self.get_bit_index()) }
function_block-function_prefixed
[ { "content": "#[inline]\n\npub fn set_primask(val: bool) {\n\n unsafe {\n\n asm!(\"msr PRIMASK, $0\"\n\n :: \"r\"(val)\n\n :: \"volatile\")\n\n }\n\n}\n\n\n\n/// Generates an instruction synchronization barrier (`ISB`) instruction.\n", "file_path": "embrs/src/arm_m/mod.r...
Rust
src/lib.rs
jsgf/eventfd-rust
b2db38af64f731ccdd84e10968948ab1ab8d123e
#![cfg(target_os = "linux")] extern crate nix; pub use nix::sys::eventfd::{EventFdFlag, EFD_CLOEXEC, EFD_NONBLOCK, EFD_SEMAPHORE}; use nix::sys::eventfd::eventfd; use nix::unistd::{dup, close, write, read}; use std::io; use std::os::unix::io::{AsRawFd,RawFd}; use std::thread; use std::sync::mpsc; use std::mem; pub struct EventFD { fd: RawFd, flags: EventFdFlag, } unsafe impl Send for EventFD {} unsafe impl Sync for EventFD {} impl EventFD { pub fn new(initval: usize, flags: EventFdFlag) -> io::Result<EventFD> { Ok(EventFD { fd: try!(eventfd(initval, flags)), flags: flags }) } pub fn read(&self) -> io::Result<u64> { let mut buf = [0u8; 8]; let _ = try!(read(self.fd, &mut buf)); let val = unsafe { mem::transmute(buf) }; Ok(val) } pub fn write(&self, val: u64) -> io::Result<()> { let buf: [u8; 8] = unsafe { mem::transmute(val) }; try!(write(self.fd, &buf)); Ok(()) } pub fn events(&self) -> mpsc::Receiver<u64> { let (tx, rx) = mpsc::sync_channel(1); let c = self.clone(); thread::spawn(move || { loop { match c.read() { Ok(v) => match tx.send(v) { Ok(_) => (), Err(_) => break, }, Err(e) => panic!("read failed: {}", e), } } }); rx } } impl AsRawFd for EventFD { fn as_raw_fd(&self) -> RawFd { self.fd as RawFd } } impl Drop for EventFD { fn drop(&mut self) { let _ = close(self.fd); } } impl Clone for EventFD { fn clone(&self) -> EventFD { EventFD { fd: dup(self.fd).unwrap(), flags: self.flags } } } #[cfg(test)] mod test { extern crate std; use super::{EventFdFlag, EventFD, EFD_SEMAPHORE, EFD_NONBLOCK}; use std::thread; #[test] fn test_basic() { let (tx,rx) = std::sync::mpsc::channel(); let efd = match EventFD::new(10, EventFdFlag::empty()) { Err(e) => panic!("new failed {}", e), Ok(fd) => fd, }; let cefd = efd.clone(); assert_eq!(efd.read().unwrap(), 10); thread::spawn(move || { assert_eq!(cefd.read().unwrap(), 7); assert_eq!(cefd.write(1).unwrap(), ()); assert_eq!(cefd.write(2).unwrap(), ()); assert!(tx.send(()).is_ok()); }); assert_eq!(efd.write(7).unwrap(), ()); let _ = rx.recv(); assert_eq!(efd.read().unwrap(), 3); } #[test] fn test_sema() { let efd = match EventFD::new(0, EFD_SEMAPHORE | EFD_NONBLOCK) { Err(e) => panic!("new failed {}", e), Ok(fd) => fd, }; match efd.read() { Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => (), Err(e) => panic!("unexpected error {}", e), Ok(v) => panic!("unexpected success {}", v), } assert_eq!(efd.write(5).unwrap(), ()); assert_eq!(efd.read().unwrap(), 1); assert_eq!(efd.read().unwrap(), 1); assert_eq!(efd.read().unwrap(), 1); assert_eq!(efd.read().unwrap(), 1); assert_eq!(efd.read().unwrap(), 1); match efd.read() { Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => (), Err(e) => panic!("unexpected error {}", e), Ok(v) => panic!("unexpected success {}", v), } } #[test] fn test_stream() { let efd = match EventFD::new(11, EFD_SEMAPHORE) { Err(e) => panic!("new failed {}", e), Ok(fd) => fd, }; let mut count = 0; for v in efd.events().iter().take(10) { assert_eq!(v, 1); count += v; } assert_eq!(count, 10) } #[test] fn test_chan() { let (tx,rx) = std::sync::mpsc::channel(); let efd = match EventFD::new(10, EventFdFlag::empty()) { Err(e) => panic!("new failed {}", e), Ok(fd) => fd, }; assert_eq!(efd.write(1).unwrap(), ()); assert!(tx.send(efd).is_ok()); let t = thread::spawn(move || { let efd = rx.recv().unwrap(); assert_eq!(efd.read().unwrap(), 11) }).join(); match t { Ok(_) => println!("ok"), Err(_) => panic!("failed"), } } }
#![cfg(target_os = "linux")] extern crate nix; pub use nix::sys::eventfd::{EventFdFlag, EFD_CLOEXEC, EFD_NONBLOCK, EFD_SEMAPHORE}; use nix::sys::eventfd::eventfd; use nix::unistd::{dup, close, write, read}; use std::io; use std::os::unix::io::{AsRawFd,RawFd}; use std::thread; use std::sync::mpsc; use std::mem; pub struct EventFD { fd: RawFd, flags: EventFdFlag, } unsafe impl Send for EventFD {} unsafe impl Sync for EventFD {} impl EventFD { pub fn new(initval: usize, flags: EventFdFlag) -> io::Result<EventFD> { Ok(EventFD { fd: try!(eventfd(initval, flags)), flags: flags }) } pub fn read(&self) -> io::Result<u64> { let mut
pub fn write(&self, val: u64) -> io::Result<()> { let buf: [u8; 8] = unsafe { mem::transmute(val) }; try!(write(self.fd, &buf)); Ok(()) } pub fn events(&self) -> mpsc::Receiver<u64> { let (tx, rx) = mpsc::sync_channel(1); let c = self.clone(); thread::spawn(move || { loop { match c.read() { Ok(v) => match tx.send(v) { Ok(_) => (), Err(_) => break, }, Err(e) => panic!("read failed: {}", e), } } }); rx } } impl AsRawFd for EventFD { fn as_raw_fd(&self) -> RawFd { self.fd as RawFd } } impl Drop for EventFD { fn drop(&mut self) { let _ = close(self.fd); } } impl Clone for EventFD { fn clone(&self) -> EventFD { EventFD { fd: dup(self.fd).unwrap(), flags: self.flags } } } #[cfg(test)] mod test { extern crate std; use super::{EventFdFlag, EventFD, EFD_SEMAPHORE, EFD_NONBLOCK}; use std::thread; #[test] fn test_basic() { let (tx,rx) = std::sync::mpsc::channel(); let efd = match EventFD::new(10, EventFdFlag::empty()) { Err(e) => panic!("new failed {}", e), Ok(fd) => fd, }; let cefd = efd.clone(); assert_eq!(efd.read().unwrap(), 10); thread::spawn(move || { assert_eq!(cefd.read().unwrap(), 7); assert_eq!(cefd.write(1).unwrap(), ()); assert_eq!(cefd.write(2).unwrap(), ()); assert!(tx.send(()).is_ok()); }); assert_eq!(efd.write(7).unwrap(), ()); let _ = rx.recv(); assert_eq!(efd.read().unwrap(), 3); } #[test] fn test_sema() { let efd = match EventFD::new(0, EFD_SEMAPHORE | EFD_NONBLOCK) { Err(e) => panic!("new failed {}", e), Ok(fd) => fd, }; match efd.read() { Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => (), Err(e) => panic!("unexpected error {}", e), Ok(v) => panic!("unexpected success {}", v), } assert_eq!(efd.write(5).unwrap(), ()); assert_eq!(efd.read().unwrap(), 1); assert_eq!(efd.read().unwrap(), 1); assert_eq!(efd.read().unwrap(), 1); assert_eq!(efd.read().unwrap(), 1); assert_eq!(efd.read().unwrap(), 1); match efd.read() { Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => (), Err(e) => panic!("unexpected error {}", e), Ok(v) => panic!("unexpected success {}", v), } } #[test] fn test_stream() { let efd = match EventFD::new(11, EFD_SEMAPHORE) { Err(e) => panic!("new failed {}", e), Ok(fd) => fd, }; let mut count = 0; for v in efd.events().iter().take(10) { assert_eq!(v, 1); count += v; } assert_eq!(count, 10) } #[test] fn test_chan() { let (tx,rx) = std::sync::mpsc::channel(); let efd = match EventFD::new(10, EventFdFlag::empty()) { Err(e) => panic!("new failed {}", e), Ok(fd) => fd, }; assert_eq!(efd.write(1).unwrap(), ()); assert!(tx.send(efd).is_ok()); let t = thread::spawn(move || { let efd = rx.recv().unwrap(); assert_eq!(efd.read().unwrap(), 11) }).join(); match t { Ok(_) => println!("ok"), Err(_) => panic!("failed"), } } }
buf = [0u8; 8]; let _ = try!(read(self.fd, &mut buf)); let val = unsafe { mem::transmute(buf) }; Ok(val) }
function_block-function_prefixed
[ { "content": "Eventfd Binding\n\n===============\n\n\n\n[![Build Status](https://travis-ci.org/jsgf/eventfd-rust.svg?branch=master)](https://travis-ci.org/jsgf/eventfd-rust)\n\n\n\nThis crate implements a binding for eventfd. This isn't especially\n\nuseful on its own; the primary use case is as part of the API...
Rust
src/client/tokens.rs
lann/bindle
ec1513554a4b088d5c9f7b25020be3d05cc58a62
use std::{ path::{Path, PathBuf}, sync::Arc, }; use oauth2::reqwest::async_http_client; use oauth2::{ basic::*, devicecode::DeviceAuthorizationResponse, AuthUrl, Client as Oauth2Client, ClientId, RefreshToken, StandardRevocableToken, StandardTokenResponse, TokenResponse, TokenUrl, }; use reqwest::{ header::{HeaderValue, AUTHORIZATION}, Client as HttpClient, RequestBuilder, }; use time::{serde::timestamp, OffsetDateTime}; use tokio::fs::OpenOptions; use tokio::io::AsyncWriteExt; use tokio::sync::RwLock; use super::{ClientError, Result}; #[derive(serde::Deserialize, serde::Serialize, Debug, Clone)] struct OidcTokenExtraFields { pub id_token: String, #[serde(default)] pub issuer: String, #[serde(default)] pub client_id: String, #[serde(default)] pub token_url: String, } impl oauth2::ExtraTokenFields for OidcTokenExtraFields {} #[derive(serde::Deserialize, Debug)] struct Claims { pub iss: String, #[serde(with = "timestamp")] pub exp: OffsetDateTime, } #[async_trait::async_trait] pub trait TokenManager { async fn apply_auth_header(&self, builder: RequestBuilder) -> Result<RequestBuilder>; } #[derive(Clone, Default)] pub struct NoToken; #[async_trait::async_trait] impl TokenManager for NoToken { async fn apply_auth_header(&self, builder: RequestBuilder) -> Result<RequestBuilder> { Ok(builder) } } #[derive(Clone)] pub struct LongLivedToken { token: String, } impl LongLivedToken { pub fn new(token: &str) -> Self { LongLivedToken { token: token.to_owned(), } } } #[async_trait::async_trait] impl TokenManager for LongLivedToken { async fn apply_auth_header(&self, builder: RequestBuilder) -> Result<RequestBuilder> { let mut header_val = HeaderValue::from_str(&format!("Bearer {}", self.token)) .map_err(|e| ClientError::Other(e.to_string()))?; header_val.set_sensitive(true); Ok(builder.header(AUTHORIZATION, header_val)) } } #[derive(Clone)] pub struct HttpBasic { username: String, password: String, } impl HttpBasic { pub fn new(username: &str, password: &str) -> Self { HttpBasic { username: username.to_owned(), password: password.to_owned(), } } } #[async_trait::async_trait] impl TokenManager for HttpBasic { async fn apply_auth_header(&self, builder: RequestBuilder) -> Result<RequestBuilder> { let data = base64::encode(format!("{}:{}", self.username, self.password)); let mut header_val = HeaderValue::from_str(&format!("Basic {}", data)) .map_err(|e| ClientError::Other(e.to_string()))?; header_val.set_sensitive(true); Ok(builder.header(AUTHORIZATION, header_val)) } } type LockData<T> = Arc<RwLock<T>>; #[derive(Clone)] pub struct OidcToken { id_token: LockData<String>, refresh_token: LockData<RefreshToken>, expiry_time: LockData<OffsetDateTime>, #[allow(dead_code)] issuer: String, #[allow(dead_code)] scopes: Vec<String>, client_id: String, token_url: String, token_file: Option<PathBuf>, } impl OidcToken { pub async fn new_from_parts( id_token: &str, refresh_token: &str, client_id: &str, token_url: &str, scopes: Vec<String>, ) -> Result<Self> { let (expiry_time, issuer) = data_from_token(id_token)?; let me = OidcToken { id_token: Arc::new(RwLock::new(id_token.to_owned())), refresh_token: Arc::new(RwLock::new(RefreshToken::new(refresh_token.to_owned()))), expiry_time: Arc::new(RwLock::new(expiry_time)), issuer, scopes, client_id: client_id.to_owned(), token_url: token_url.to_owned(), token_file: None, }; me.ensure_token().await?; Ok(me) } pub async fn new_from_file(token_file: impl AsRef<Path>) -> Result<Self> { let path = token_file.as_ref().to_owned(); let raw = tokio::fs::read(&path).await?; let token_res: StandardTokenResponse<OidcTokenExtraFields, BasicTokenType> = toml::from_slice(&raw)?; let mut me = Self::new_from_parts( &token_res.extra_fields().id_token, token_res .refresh_token() .ok_or_else(|| { ClientError::TokenError( "Token response does not contain a refresh token".into(), ) })? .secret(), &token_res.extra_fields().client_id, &token_res.extra_fields().token_url, token_res .scopes() .map(|s| s.iter().map(|s| s.to_string()).collect()) .unwrap_or_default(), ) .await?; me.token_file = Some(path); Ok(me) } pub async fn login(bindle_base_url: &str, token_file: impl AsRef<Path>) -> Result<Self> { let (base_url, headers) = super::base_url_and_headers(bindle_base_url)?; let login_resp = HttpClient::builder() .build()? .get(base_url.join(super::LOGIN_ENDPOINT).unwrap()) .query(&crate::LoginParams { provider: "nothing".into(), }) .headers(headers) .send() .await?; let login_resp = super::unwrap_status(login_resp, super::Endpoint::Login, super::Operation::Login) .await?; let device_code_details: DeviceAuthorizationResponse< crate::DeviceAuthorizationExtraFields, > = toml::from_slice(&login_resp.bytes().await?)?; println!( "Open this URL in your browser:\n{}\nand then enter the code when prompted: {}", **device_code_details.verification_uri(), device_code_details.user_code().secret() ); let oauth_client: Oauth2Client< BasicErrorResponse, StandardTokenResponse<OidcTokenExtraFields, BasicTokenType>, BasicTokenType, BasicTokenIntrospectionResponse, StandardRevocableToken, BasicRevocationErrorResponse, > = Oauth2Client::new( ClientId::new(device_code_details.extra_fields().client_id.clone()), None, AuthUrl::new("https://not.needed.com".into()).unwrap(), Some(TokenUrl::new(device_code_details.extra_fields().token_url.clone()).unwrap()), ) .set_auth_type(oauth2::AuthType::RequestBody); let token_res = match oauth_client .exchange_device_access_token(&device_code_details) .request_async(async_http_client, tokio::time::sleep, None) .await { Ok(t) => t, Err(e) => { return Err(ClientError::Other(format!("{:?}", e))); } }; let (expiry_time, issuer) = data_from_token(&token_res.extra_fields().id_token)?; let me = OidcToken { id_token: Arc::new(RwLock::new(token_res.extra_fields().id_token.to_owned())), refresh_token: Arc::new(RwLock::new(RefreshToken::new( token_res .refresh_token() .ok_or_else(|| { ClientError::TokenError( "Token response does not contain a refresh token".into(), ) })? .secret() .to_owned(), ))), expiry_time: Arc::new(RwLock::new(expiry_time)), issuer, scopes: token_res .scopes() .map(|s| s.iter().map(|s| s.to_string()).collect()) .unwrap_or_default(), client_id: device_code_details.extra_fields().client_id.clone(), token_url: device_code_details.extra_fields().token_url.clone(), token_file: Some(token_file.as_ref().to_owned()), }; me.write_token_file(token_res).await?; Ok(me) } async fn ensure_token(&self) -> Result<()> { let is_expired = OffsetDateTime::now_utc() - time::Duration::minutes(1) >= *self.expiry_time.read().await; if is_expired { tracing::debug!("Token has expired, attempting to refresh token"); let oauth_client: Oauth2Client< BasicErrorResponse, StandardTokenResponse<OidcTokenExtraFields, BasicTokenType>, BasicTokenType, BasicTokenIntrospectionResponse, StandardRevocableToken, BasicRevocationErrorResponse, > = Oauth2Client::new( ClientId::new(self.client_id.clone()), None, AuthUrl::new("https://not.needed.com".into()).unwrap(), Some(TokenUrl::new(self.token_url.clone()).map_err(|e| { ClientError::TokenError(format!("Invalid token url: {}", e)) })?), ) .set_auth_type(oauth2::AuthType::RequestBody); let token_res = { let mut refresh_token = self.refresh_token.write().await; let token_res = match oauth_client .exchange_refresh_token(&refresh_token) .request_async(async_http_client) .await { Ok(t) => t, Err(e) => { return Err(ClientError::TokenError(format!( "Unable to refresh token {:?}", e ))); } }; let (expiry, _) = data_from_token(&token_res.extra_fields().id_token)?; let mut expiry_time = self.expiry_time.write().await; let mut id_token = self.id_token.write().await; *expiry_time = expiry; *id_token = token_res.extra_fields().id_token.clone(); *refresh_token = RefreshToken::new( token_res .refresh_token() .ok_or_else(|| { ClientError::TokenError( "Token response does not contain a refresh token".into(), ) })? .secret() .to_owned(), ); token_res }; if let Some(p) = self.token_file.as_ref() { tracing::trace!(path = %p.display(), "Token refreshed and token file is set. Updating with token data"); self.write_token_file(token_res).await?; } } Ok(()) } async fn write_token_file( &self, mut token_res: StandardTokenResponse<OidcTokenExtraFields, BasicTokenType>, ) -> Result<()> { let token_file = match self.token_file.as_ref() { Some(p) => p, None => return Ok(()), }; let mut extra = token_res.extra_fields().to_owned(); let (_, issuer) = data_from_token(&token_res.extra_fields().id_token)?; extra.issuer = issuer.clone(); extra.client_id = self.client_id.clone(); extra.token_url = self.token_url.clone(); token_res.set_extra_fields(extra); tracing::info!(path = %token_file.display(), "Writing access token to file"); #[cfg(not(target_family = "windows"))] let mut file = OpenOptions::new() .create(true) .write(true) .mode(0o600) .truncate(true) .open(token_file) .await?; #[cfg(target_family = "windows")] let mut file = OpenOptions::new() .create(true) .write(true) .truncate(true) .open(token_file) .await?; file.write_all(&toml::to_vec(&token_res)?).await?; file.flush().await?; Ok(()) } } #[async_trait::async_trait] impl TokenManager for OidcToken { async fn apply_auth_header(&self, builder: RequestBuilder) -> Result<RequestBuilder> { self.ensure_token().await?; let mut header_val = HeaderValue::from_str(&format!("Bearer {}", (*self.id_token.read().await).clone())) .map_err(|e| ClientError::Other(e.to_string()))?; header_val.set_sensitive(true); Ok(builder.header(AUTHORIZATION, header_val)) } } fn data_from_token(token: &str) -> Result<(OffsetDateTime, String)> { let mut validation = jsonwebtoken::Validation::default(); validation.validate_exp = false; validation.insecure_disable_signature_validation(); let fake_key = jsonwebtoken::DecodingKey::from_secret(b"fake"); let parsed_token = jsonwebtoken::decode::<Claims>(token, &fake_key, &validation) .map_err(|e| ClientError::TokenError(format!("Invalid token data: {}", e)))?; Ok((parsed_token.claims.exp, parsed_token.claims.iss)) }
use std::{ path::{Path, PathBuf}, sync::Arc, }; use oauth2::reqwest::async_http_client; use oauth2::{ basic::*, devicecode::DeviceAuthorizationResponse, AuthUrl, Client as Oauth2Client, ClientId, RefreshToken, StandardRevocableToken, StandardTokenResponse, TokenResponse, TokenUrl, }; use reqwest::{ header::{HeaderValue, AUTHORIZATION}, Client as HttpClient, RequestBuilder, }; use time::{serde::timestamp, OffsetDateTime}; use tokio::fs::OpenOptions; use tokio::io::AsyncWriteExt; use tokio::sync::RwLock; use super::{ClientError, Result}; #[derive(serde::Deserialize, serde::Serialize, Debug, Clone)] struct OidcTokenExtraFields { pub id_token: String, #[serde(default)] pub issuer: String, #[serde(default)] pub client_id: String, #[serde(default)] pub token_url: String, } impl oauth2::ExtraTokenFields for OidcTokenExtraFields {} #[derive(serde::Deserialize, Debug)] struct Claims { pub iss: String, #[serde(with = "timestamp")] pub exp: OffsetDateTime, } #[async_trait::async_trait] pub trait TokenManager { async fn apply_auth_header(&self, builder: RequestBuilder) -> Result<RequestBuilder>; } #[derive(Clone, Default)] pub struct NoToken; #[async_trait::async_trait] impl TokenManager for NoToken { async fn apply_auth_header(&self, builder: RequestBuilder) -> Result<RequestBuilder> { Ok(builder) } } #[derive(Clone)] pub struct LongLivedToken { token: String, } impl LongLivedToken { pub fn new(token: &str) -> Self { LongLivedToken { token: token.to_owned(), } } } #[async_trait::async_trait] impl TokenManager for LongLivedToken { async fn apply_auth_header(&self, builder: RequestBuilder) -> Result<RequestBuilder> { let mut header_val = HeaderValue::from_str(&format!("Bearer {}", self.token)) .map_err(|e| ClientError::Other(e.to_string()))?; header_val.set_sensitive(true); Ok(builder.header(AUTHORIZATION, header_val)) } } #[derive(Clone)] pub struct HttpBasic { username: String, password: String, } impl HttpBasic { pub fn new(username: &str, password: &str) -> Self { HttpBasic { username: username.to_owned(), password: password.to_owned(), } } } #[async_trait::async_trait] impl TokenManager for HttpBasic { async fn apply_auth_header(&self, builder: RequestBuilder) -> Result<RequestBuilder> { let data = base64::encode(format!("{}:{}", self.username, self.password)); let mut header_val = HeaderValue::from_str(&format!("Basic {}", data)) .map_err(|e| ClientError::Other(e.to_string()))?; header_val.set_sensitive(true); Ok(builder.header(AUTHORIZATION, header_val)) } } type LockData<T> = Arc<RwLock<T>>; #[derive(Clone)] pub struct OidcToken { id_token: LockData<String>, refresh_token: LockData<RefreshToken>, expiry_time: LockData<OffsetDateTime>, #[allow(dead_code)] issuer: String, #[allow(dead_code)] scopes: Vec<String>, client_id: String, token_url: String, token_file: Option<PathBuf>, } impl OidcToken { pub async fn new_from_parts( id_token: &str, refresh_token: &str, client_id: &str, token_url: &str, scopes: Vec<String>, ) -> Result<Self> { let (expiry_time, issuer) = data_from_token(id_token)?; let me = OidcToken { id_token: Arc::new(RwLock::new(id_token.to_owned())), refresh_token: Arc::new(RwLock::new(RefreshToken::new(refresh_token.to_owned()))), expiry_time: Arc::new(RwLock::new(expiry_time)), issuer, scopes, client_id: client_id.to_owned(), token_url: token_url.to_owned(), token_file: None, }; me.ensure_token().await?; Ok(me) } pub async fn new_from_file(token_file: impl AsRef<Path>) -> Result<Self> { let path = token_file.as_ref().to_owned(); let raw = tokio::fs::read(&path).await?; let token_res: StandardTokenResponse<OidcTokenExtraFields, BasicTokenType> = toml::from_slice(&raw)?; let mut me = Self::new_from_parts( &token_res.extra_fields().id_token, token_res .refresh_token() .ok_or_else(|| { ClientError::TokenError( "Token response does not contain a refresh token".into(), ) })? .secret(), &token_res.extra_fields().client_id, &token_res.extra_fields().token_url, token_res .scopes() .map(|s| s.iter().map(|s| s.to_string()).collect()) .unwrap_or_default(), ) .await?; me.token_file = Some(path); Ok(me) } pub async fn login(bindle_base_url: &str, token_file: impl AsRef<Path>) -> Result<Self> { let (base_url, headers) = super::base_url_and_headers(bindle_base_url)?; let login_resp = HttpClient::builder() .build()? .get(base_url.join(super::LOGIN_ENDPOINT).unwrap()) .query(&crate::LoginParams { provider: "nothing".into(), }) .headers(headers) .send() .await?; let login_resp = super::unwrap_status(login_resp, super::Endpoint::Login, super::Operation::Login) .await?; let device_code_details: DeviceAuthorizationResponse< crate::DeviceAuthorizationExtraFields, > = toml::from_slice(&login_resp.bytes().await?)?; println!( "Open this URL in your browser:\n{}\nand then enter the code when prompted: {}", **device_code_details.verification_uri(), device_code_details.user_code().secret() ); let oauth_client: Oauth2Client< BasicErrorResponse, StandardTokenResponse<OidcTokenExtraFields, BasicTokenType>, BasicTokenType, BasicTokenIntrospectionResponse, StandardRevocableToken, BasicRevocationErrorResponse, > = Oauth2Client::new( ClientId::new(device_code_details.extra_fields().client_id.clone()), None, AuthUrl::new("https://not.needed.com".into()).unwrap(), Some(TokenUrl::new(device_code_details.extra_fields().token_url.clone()).unwrap()), ) .set_auth_type(oauth2::AuthType::RequestBody); let token_res = match oauth_client .exchange_device_access_token(&device_code_details) .request_async(async_http_client, tokio::time::sleep, None) .await { Ok(t) => t, Err(e) => { return Err(ClientError::Other(format!("{:?}", e))); } }; let (expiry_time, issuer) = data_from_token(&token_res.extra_fields().id_token)?; let me = OidcToken { id_token: Arc::new(RwLock::new(token_res.extra_fields().id_token.to_owned())), refresh_token: Arc::new(RwLock::new(RefreshToken::new( token_res .refresh_token() .ok_or_else(|| { ClientError::TokenError( "Token response does not contain a refresh token".into(), ) })? .secret() .to_owned(), ))), expiry_time: Arc::new(RwLock::new(expiry_time)), issuer, scopes: token_res .scopes() .map(|s| s.iter().map(|s| s.to_string()).collect()) .unwrap_or_default(), client_id: device_code_details.extra_fields().client_id.clone(), token_url: device_code_details.extra_fields().token_url.clone(), token_file: Some(token_file.as_ref().to_owned()), }; me.write_token_file(token_res).await?; Ok(me) } async fn ensure_token(&self) -> Result<()> { let is_expired = OffsetDateTime::now_utc() - time::Duration::minutes(1) >= *self.expiry_time.read().await; if is_expired { tracing::debug!("Token has expired, attempting to refresh token"); let oauth_client: Oauth2Client< BasicErrorResponse, StandardTokenResponse<OidcTokenExtraFields, BasicTokenType>, BasicTokenType, BasicTokenIntrospectionResponse, StandardRevocableToken, BasicRevocationErrorResponse, > = Oauth2Client::new( ClientId::new(self.client_id.clone()), None, AuthUrl::new("https://not.needed.com".into()).unwrap(),
, ) .set_auth_type(oauth2::AuthType::RequestBody); let token_res = { let mut refresh_token = self.refresh_token.write().await; let token_res = match oauth_client .exchange_refresh_token(&refresh_token) .request_async(async_http_client) .await { Ok(t) => t, Err(e) => { return Err(ClientError::TokenError(format!( "Unable to refresh token {:?}", e ))); } }; let (expiry, _) = data_from_token(&token_res.extra_fields().id_token)?; let mut expiry_time = self.expiry_time.write().await; let mut id_token = self.id_token.write().await; *expiry_time = expiry; *id_token = token_res.extra_fields().id_token.clone(); *refresh_token = RefreshToken::new( token_res .refresh_token() .ok_or_else(|| { ClientError::TokenError( "Token response does not contain a refresh token".into(), ) })? .secret() .to_owned(), ); token_res }; if let Some(p) = self.token_file.as_ref() { tracing::trace!(path = %p.display(), "Token refreshed and token file is set. Updating with token data"); self.write_token_file(token_res).await?; } } Ok(()) } async fn write_token_file( &self, mut token_res: StandardTokenResponse<OidcTokenExtraFields, BasicTokenType>, ) -> Result<()> { let token_file = match self.token_file.as_ref() { Some(p) => p, None => return Ok(()), }; let mut extra = token_res.extra_fields().to_owned(); let (_, issuer) = data_from_token(&token_res.extra_fields().id_token)?; extra.issuer = issuer.clone(); extra.client_id = self.client_id.clone(); extra.token_url = self.token_url.clone(); token_res.set_extra_fields(extra); tracing::info!(path = %token_file.display(), "Writing access token to file"); #[cfg(not(target_family = "windows"))] let mut file = OpenOptions::new() .create(true) .write(true) .mode(0o600) .truncate(true) .open(token_file) .await?; #[cfg(target_family = "windows")] let mut file = OpenOptions::new() .create(true) .write(true) .truncate(true) .open(token_file) .await?; file.write_all(&toml::to_vec(&token_res)?).await?; file.flush().await?; Ok(()) } } #[async_trait::async_trait] impl TokenManager for OidcToken { async fn apply_auth_header(&self, builder: RequestBuilder) -> Result<RequestBuilder> { self.ensure_token().await?; let mut header_val = HeaderValue::from_str(&format!("Bearer {}", (*self.id_token.read().await).clone())) .map_err(|e| ClientError::Other(e.to_string()))?; header_val.set_sensitive(true); Ok(builder.header(AUTHORIZATION, header_val)) } } fn data_from_token(token: &str) -> Result<(OffsetDateTime, String)> { let mut validation = jsonwebtoken::Validation::default(); validation.validate_exp = false; validation.insecure_disable_signature_validation(); let fake_key = jsonwebtoken::DecodingKey::from_secret(b"fake"); let parsed_token = jsonwebtoken::decode::<Claims>(token, &fake_key, &validation) .map_err(|e| ClientError::TokenError(format!("Invalid token data: {}", e)))?; Ok((parsed_token.claims.exp, parsed_token.claims.iss)) }
Some(TokenUrl::new(self.token_url.clone()).map_err(|e| { ClientError::TokenError(format!("Invalid token url: {}", e)) })?)
call_expression
[ { "content": "fn parse_basic(auth_data: &str) -> anyhow::Result<(String, String)> {\n\n match auth_data.strip_prefix(HTTP_BASIC_PREFIX) {\n\n None => anyhow::bail!(\"Wrong auth type. Only Basic auth is supported\"),\n\n Some(suffix) => {\n\n // suffix should be base64 string\n\n ...
Rust
primitives/mmr/src/mmr/utils.rs
redmaner/core-rs-albatross
9721dd99e8fef949e7e89a8047f95eaaa8ec9fd7
use crate::error::Error; use crate::hash::Merge; const USIZE_BITS: u32 = 0usize.count_zeros(); #[inline] pub(crate) fn bit_length(v: usize) -> u32 { USIZE_BITS - v.leading_zeros() } pub(crate) fn bagging<H: Merge, I: Iterator<Item = Result<(H, usize), Error>>>( peaks_rev: I, ) -> Result<H, Error> { let mut bagging_info = None; for item in peaks_rev { let (peak_hash, peak_leaves) = item?; bagging_info = match bagging_info { None => Some((peak_hash, peak_leaves)), Some((root_hash, root_leaves)) => { let sum_leaves = root_leaves + peak_leaves; Some((peak_hash.merge(&root_hash, sum_leaves as u64), sum_leaves)) } }; } let (root, _) = bagging_info.ok_or(Error::ProveInvalidLeaves)?; Ok(root) } #[cfg(test)] pub(crate) mod test_utils { use crate::hash::{Hash, Merge}; use super::*; pub(crate) fn hash_perfect_tree<H: Merge, T: Hash<H>>(values: &[T]) -> Option<H> { let len = values.len(); if len == 0 { return Some(H::empty(0)); } if len.count_ones() != 1 { return None; } if len == 1 { return Some(values[0].hash(1)); } let mid = len >> 1; Some(H::merge( &hash_perfect_tree(&values[..mid])?, &hash_perfect_tree(&values[mid..])?, len as u64, )) } pub(crate) fn hash_mmr<H: Merge, T: Hash<H>>(values: &[T]) -> H { let mut peaks = vec![]; let mut i = 0; while i < values.len() { let max_height = bit_length(values.len() - i) as usize - 1; let max_leaves = 1 << max_height; let root = hash_perfect_tree(&values[i..i + max_leaves]).unwrap(); peaks.push(Ok((root, max_leaves))); i += max_leaves; } bagging(peaks.into_iter().rev()).unwrap() } #[derive(Debug, Clone, Eq, PartialEq)] pub(crate) struct TestHash(pub(crate) usize); impl Merge for TestHash { fn empty(prefix: u64) -> Self { TestHash(prefix as usize) } fn merge(&self, other: &Self, prefix: u64) -> Self { TestHash(self.0 * 2 + other.0 * 3 + prefix as usize) } } impl Hash<TestHash> for usize { fn hash(&self, prefix: u64) -> TestHash { TestHash(self * 2 + prefix as usize) } } #[test] fn test_utils_hash_correctly() { let values = vec![1, 3, 5, 7]; assert_eq!(hash_perfect_tree(&values[..0]), Some(TestHash(0))); assert_eq!(hash_perfect_tree(&values[..3]), None); assert_eq!(hash_perfect_tree(&values[..1]), Some(TestHash(3))); assert_eq!(hash_perfect_tree(&values[1..2]), Some(TestHash(7))); assert_eq!(hash_perfect_tree(&values[2..3]), Some(TestHash(11))); assert_eq!(hash_perfect_tree(&values[3..]), Some(TestHash(15))); assert_eq!(hash_perfect_tree(&values[..2]), Some(TestHash(29))); assert_eq!(hash_perfect_tree(&values[2..]), Some(TestHash(69))); assert_eq!(hash_perfect_tree(&values), Some(TestHash(269))); assert_eq!(hash_mmr(&values[..1]), TestHash(3)); assert_eq!(hash_mmr(&values[1..2]), TestHash(7)); assert_eq!(hash_mmr(&values[2..3]), TestHash(11)); assert_eq!(hash_mmr(&values[3..]), TestHash(15)); assert_eq!(hash_mmr(&values[..2]), TestHash(29)); assert_eq!(hash_mmr(&values[2..]), TestHash(69)); assert_eq!(hash_mmr(&values), TestHash(269)); assert_eq!(hash_mmr(&values[..3]), TestHash(94)); } } #[cfg(test)] mod tests { use crate::mmr::utils::test_utils::TestHash; use super::*; #[test] fn it_correctly_compute_bit_length() { assert_eq!(bit_length(0), 0); assert_eq!(bit_length(1), 1); assert_eq!(bit_length(2), 2); assert_eq!(bit_length(3), 2); assert_eq!(bit_length(255), 8); assert_eq!(bit_length(256), 9); } #[test] fn it_correctly_performs_bagging() { assert!(bagging::<TestHash, _>(vec![].into_iter()).is_err()); let mut positions = vec![Ok((TestHash(2), 2))]; assert_eq!( bagging(positions.clone().into_iter().rev()), Ok(TestHash(2)) ); assert_eq!(bagging(positions.clone().into_iter()), Ok(TestHash(2))); positions.push(Ok((TestHash(1), 1))); assert_eq!( bagging(positions.clone().into_iter().rev()), Ok(TestHash(10)) ); assert_eq!(bagging(positions.clone().into_iter()), Ok(TestHash(11))); positions.push(Ok((TestHash(2), 2))); assert_eq!( bagging(positions.clone().into_iter().rev()), Ok(TestHash(42)) ); assert_eq!(bagging(positions.into_iter()), Ok(TestHash(42))); } }
use crate::error::Error; use crate::hash::Merge; const USIZE_BITS: u32 = 0usize.count_zeros(); #[inline] pub(crate) fn bit_length(v: usize) -> u32 { USIZE_BITS - v.leading_zeros() } pub(crate) fn bagging<H: Merge, I: Iterator<Item = Result<(H, usize), Error>>>( peaks_rev: I, ) -> Result<H, Error> { let mut bagging_info = None; for item in peaks_rev { let (peak_hash, peak_leaves) = item?; bagging_info = match bagging_info { None => Some((peak_hash, peak_leaves)), Some((root_hash, root_leaves)) => { let sum_leaves = root_leaves + peak_leaves; Some((peak_hash.merge(&root_hash, sum_leaves as u64), sum_leaves)) } }; } let (root, _) = bagging_info.ok_or(Error::ProveInvalidLeaves)?; Ok(root) } #[cfg(test)] pub(crate) mod test_utils { use crate::hash::{Hash, Merge}; use super::*; pub(crate) fn hash_perfect_tree<H: Merge, T: Hash<H>>(values: &[T]) -> Option<H> { let len = values.len(); if len == 0 { return Some(H::empty(0)); } if len.count_ones() != 1 { return None; } if len == 1 { return Some(values[0].hash(1)); } let mid = len >> 1;
} pub(crate) fn hash_mmr<H: Merge, T: Hash<H>>(values: &[T]) -> H { let mut peaks = vec![]; let mut i = 0; while i < values.len() { let max_height = bit_length(values.len() - i) as usize - 1; let max_leaves = 1 << max_height; let root = hash_perfect_tree(&values[i..i + max_leaves]).unwrap(); peaks.push(Ok((root, max_leaves))); i += max_leaves; } bagging(peaks.into_iter().rev()).unwrap() } #[derive(Debug, Clone, Eq, PartialEq)] pub(crate) struct TestHash(pub(crate) usize); impl Merge for TestHash { fn empty(prefix: u64) -> Self { TestHash(prefix as usize) } fn merge(&self, other: &Self, prefix: u64) -> Self { TestHash(self.0 * 2 + other.0 * 3 + prefix as usize) } } impl Hash<TestHash> for usize { fn hash(&self, prefix: u64) -> TestHash { TestHash(self * 2 + prefix as usize) } } #[test] fn test_utils_hash_correctly() { let values = vec![1, 3, 5, 7]; assert_eq!(hash_perfect_tree(&values[..0]), Some(TestHash(0))); assert_eq!(hash_perfect_tree(&values[..3]), None); assert_eq!(hash_perfect_tree(&values[..1]), Some(TestHash(3))); assert_eq!(hash_perfect_tree(&values[1..2]), Some(TestHash(7))); assert_eq!(hash_perfect_tree(&values[2..3]), Some(TestHash(11))); assert_eq!(hash_perfect_tree(&values[3..]), Some(TestHash(15))); assert_eq!(hash_perfect_tree(&values[..2]), Some(TestHash(29))); assert_eq!(hash_perfect_tree(&values[2..]), Some(TestHash(69))); assert_eq!(hash_perfect_tree(&values), Some(TestHash(269))); assert_eq!(hash_mmr(&values[..1]), TestHash(3)); assert_eq!(hash_mmr(&values[1..2]), TestHash(7)); assert_eq!(hash_mmr(&values[2..3]), TestHash(11)); assert_eq!(hash_mmr(&values[3..]), TestHash(15)); assert_eq!(hash_mmr(&values[..2]), TestHash(29)); assert_eq!(hash_mmr(&values[2..]), TestHash(69)); assert_eq!(hash_mmr(&values), TestHash(269)); assert_eq!(hash_mmr(&values[..3]), TestHash(94)); } } #[cfg(test)] mod tests { use crate::mmr::utils::test_utils::TestHash; use super::*; #[test] fn it_correctly_compute_bit_length() { assert_eq!(bit_length(0), 0); assert_eq!(bit_length(1), 1); assert_eq!(bit_length(2), 2); assert_eq!(bit_length(3), 2); assert_eq!(bit_length(255), 8); assert_eq!(bit_length(256), 9); } #[test] fn it_correctly_performs_bagging() { assert!(bagging::<TestHash, _>(vec![].into_iter()).is_err()); let mut positions = vec![Ok((TestHash(2), 2))]; assert_eq!( bagging(positions.clone().into_iter().rev()), Ok(TestHash(2)) ); assert_eq!(bagging(positions.clone().into_iter()), Ok(TestHash(2))); positions.push(Ok((TestHash(1), 1))); assert_eq!( bagging(positions.clone().into_iter().rev()), Ok(TestHash(10)) ); assert_eq!(bagging(positions.clone().into_iter()), Ok(TestHash(11))); positions.push(Ok((TestHash(2), 2))); assert_eq!( bagging(positions.clone().into_iter().rev()), Ok(TestHash(42)) ); assert_eq!(bagging(positions.into_iter()), Ok(TestHash(42))); } }
Some(H::merge( &hash_perfect_tree(&values[..mid])?, &hash_perfect_tree(&values[mid..])?, len as u64, ))
call_expression
[]
Rust
vendor/wayland-client/src/globals.rs
nwtnni/icfp-2020
0eeb7851cd70bdec9343d6a4257d7286275fa79f
use std::sync::{Arc, Mutex}; use crate::protocol::wl_display; use crate::protocol::wl_registry; use crate::{Attached, DispatchData, Interface, Main, Proxy}; struct Inner { list: Vec<(u32, String, u32)>, } #[derive(Clone)] pub struct GlobalManager { inner: Arc<Mutex<Inner>>, registry: Main<wl_registry::WlRegistry>, } #[derive(Debug, PartialEq)] pub enum GlobalError { Missing, VersionTooLow(u32), } impl ::std::error::Error for GlobalError { fn description(&self) -> &str { match *self { GlobalError::Missing => "The requested global was missing.", GlobalError::VersionTooLow(_) => "The requested global's version is too low.", } } } impl ::std::fmt::Display for GlobalError { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> Result<(), ::std::fmt::Error> { f.write_str(::std::error::Error::description(self)) } } pub enum GlobalEvent { New { id: u32, interface: String, version: u32, }, Removed { id: u32, interface: String, }, } impl GlobalManager { pub fn new(display: &Attached<wl_display::WlDisplay>) -> GlobalManager { let inner = Arc::new(Mutex::new(Inner { list: Vec::new() })); let inner_clone = inner.clone(); let registry = display .as_ref() .send::<wl_registry::WlRegistry>(wl_display::Request::GetRegistry {}, None) .unwrap(); registry.quick_assign(move |_proxy, msg, _data| { let mut inner = inner.lock().unwrap(); match msg { wl_registry::Event::Global { name, interface, version, } => { inner.list.push((name, interface, version)); } wl_registry::Event::GlobalRemove { name } => { inner.list.retain(|&(n, _, _)| n != name); } } }); GlobalManager { inner: inner_clone, registry, } } pub fn new_with_cb<F>(display: &Attached<wl_display::WlDisplay>, mut callback: F) -> GlobalManager where F: FnMut(GlobalEvent, Attached<wl_registry::WlRegistry>, DispatchData) + 'static, { let inner = Arc::new(Mutex::new(Inner { list: Vec::new() })); let inner_clone = inner.clone(); let registry = display .as_ref() .send::<wl_registry::WlRegistry>(wl_display::Request::GetRegistry {}, None) .unwrap(); registry.quick_assign(move |proxy, msg, data| { let mut inner = inner.lock().unwrap(); let inner = &mut *inner; match msg { wl_registry::Event::Global { name, interface, version, } => { inner.list.push((name, interface.clone(), version)); callback( GlobalEvent::New { id: name, interface, version, }, (*proxy).clone(), data, ); } wl_registry::Event::GlobalRemove { name } => { if let Some((i, _)) = inner.list.iter().enumerate().find(|&(_, &(n, _, _))| n == name) { let (id, interface, _) = inner.list.swap_remove(i); callback(GlobalEvent::Removed { id, interface }, (*proxy).clone(), data); } else { panic!( "Wayland protocol error: the server removed non-existing global \"{}\".", name ); } } } }); GlobalManager { inner: inner_clone, registry, } } pub fn instantiate_exact<I>(&self, version: u32) -> Result<Main<I>, GlobalError> where I: Interface + AsRef<Proxy<I>> + From<Proxy<I>>, { let inner = self.inner.lock().unwrap(); for &(id, ref interface, server_version) in &inner.list { if interface == I::NAME { if version > server_version { return Err(GlobalError::VersionTooLow(server_version)); } else { return Ok(self.registry.bind::<I>(version, id)); } } } Err(GlobalError::Missing) } pub fn instantiate_range<I>(&self, min_version: u32, max_version: u32) -> Result<Main<I>, GlobalError> where I: Interface + AsRef<Proxy<I>> + From<Proxy<I>>, { let inner = self.inner.lock().unwrap(); for &(id, ref interface, version) in &inner.list { if interface == I::NAME { if version >= min_version { let version = ::std::cmp::min(version, max_version); return Ok(self.registry.bind::<I>(version, id)); } else { return Err(GlobalError::VersionTooLow(version)); } } } Err(GlobalError::Missing) } pub fn list(&self) -> Vec<(u32, String, u32)> { self.inner.lock().unwrap().list.clone() } } pub trait GlobalImplementor<I: Interface + AsRef<Proxy<I>> + From<Proxy<I>>> { fn new_global(&mut self, global: Main<I>, data: DispatchData); fn error(&mut self, _version: u32, _data: DispatchData) {} } impl<F, I: Interface> GlobalImplementor<I> for F where I: Interface + AsRef<Proxy<I>> + From<Proxy<I>>, F: FnMut(Main<I>, DispatchData), { fn new_global(&mut self, global: Main<I>, data: DispatchData) { (*self)(global, data) } } #[macro_export] macro_rules! global_filter { ($([$interface:ty, $version:expr, $callback:expr]),*) => { { use $crate::protocol::wl_registry; use $crate::{GlobalEvent, Interface, Attached, GlobalImplementor, DispatchData}; type Callback = Box<dyn FnMut(u32, u32, Attached<wl_registry::WlRegistry>, DispatchData<'_>)>; let mut callbacks: Vec<(&'static str, Callback)> = Vec::new(); $({ let mut cb = { $callback }; callbacks.push(( <$interface as Interface>::NAME, Box::new(move |id, version, registry: Attached<wl_registry::WlRegistry>, ddata: DispatchData| { if version < $version { GlobalImplementor::<$interface>::error(&mut cb, version, ddata); } else { let proxy = registry.bind::<$interface>(version, id); GlobalImplementor::<$interface>::new_global(&mut cb, proxy, ddata); } }) as Box<_> )); })* move |event: GlobalEvent, registry: Attached<wl_registry::WlRegistry>, ddata| { if let GlobalEvent::New { id, interface, version } = event { for &mut (iface, ref mut cb) in &mut callbacks { if iface == interface { cb(id, version, registry, ddata); break; } } } } } } }
use std::sync::{Arc, Mutex}; use crate::protocol::wl_display; use crate::protocol::wl_registry; use crate::{Attached, DispatchData, Interface, Main, Proxy}; struct Inner { list: Vec<(u32, String, u32)>, } #[derive(Clone)] pub struct GlobalManager { inner: Arc<Mutex<Inner>>, registry: Main<wl_registry::WlRegistry>, } #[derive(Debug, PartialEq)] pub enum GlobalError { Missing, VersionTooLow(u32), } impl ::std::error::Error for GlobalError { fn description(&self) -> &str { match *self { GlobalError::Missing => "The requested global was missing.", GlobalError::VersionTooLow(_) => "The requested global's version is too low.", } } } impl ::std::fmt::Display for GlobalError { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> Result<(), ::std::fmt::Error> { f.write_str(::std::error::Error::description(self)) } } pub enum GlobalEvent { New { id: u32, interface: String, version: u32, }, Removed { id: u32, interface: String, }, } impl GlobalManager { pub fn new(display: &Attached<wl_display::WlDisplay>) -> GlobalManager { let inner = Arc::new(Mutex::new(Inner { list: Vec::new() })); let inner_clone = inner.clone(); let registry = display .as_ref() .send::<wl_registry::WlRegistry>(wl_display::Request::GetRegistry {}, None) .unwrap(); registry.quick_assign(move |_proxy, msg, _data| { let mut inner = inner.lock().unwrap();
}); GlobalManager { inner: inner_clone, registry, } } pub fn new_with_cb<F>(display: &Attached<wl_display::WlDisplay>, mut callback: F) -> GlobalManager where F: FnMut(GlobalEvent, Attached<wl_registry::WlRegistry>, DispatchData) + 'static, { let inner = Arc::new(Mutex::new(Inner { list: Vec::new() })); let inner_clone = inner.clone(); let registry = display .as_ref() .send::<wl_registry::WlRegistry>(wl_display::Request::GetRegistry {}, None) .unwrap(); registry.quick_assign(move |proxy, msg, data| { let mut inner = inner.lock().unwrap(); let inner = &mut *inner; match msg { wl_registry::Event::Global { name, interface, version, } => { inner.list.push((name, interface.clone(), version)); callback( GlobalEvent::New { id: name, interface, version, }, (*proxy).clone(), data, ); } wl_registry::Event::GlobalRemove { name } => { if let Some((i, _)) = inner.list.iter().enumerate().find(|&(_, &(n, _, _))| n == name) { let (id, interface, _) = inner.list.swap_remove(i); callback(GlobalEvent::Removed { id, interface }, (*proxy).clone(), data); } else { panic!( "Wayland protocol error: the server removed non-existing global \"{}\".", name ); } } } }); GlobalManager { inner: inner_clone, registry, } } pub fn instantiate_exact<I>(&self, version: u32) -> Result<Main<I>, GlobalError> where I: Interface + AsRef<Proxy<I>> + From<Proxy<I>>, { let inner = self.inner.lock().unwrap(); for &(id, ref interface, server_version) in &inner.list { if interface == I::NAME { if version > server_version { return Err(GlobalError::VersionTooLow(server_version)); } else { return Ok(self.registry.bind::<I>(version, id)); } } } Err(GlobalError::Missing) } pub fn instantiate_range<I>(&self, min_version: u32, max_version: u32) -> Result<Main<I>, GlobalError> where I: Interface + AsRef<Proxy<I>> + From<Proxy<I>>, { let inner = self.inner.lock().unwrap(); for &(id, ref interface, version) in &inner.list { if interface == I::NAME { if version >= min_version { let version = ::std::cmp::min(version, max_version); return Ok(self.registry.bind::<I>(version, id)); } else { return Err(GlobalError::VersionTooLow(version)); } } } Err(GlobalError::Missing) } pub fn list(&self) -> Vec<(u32, String, u32)> { self.inner.lock().unwrap().list.clone() } } pub trait GlobalImplementor<I: Interface + AsRef<Proxy<I>> + From<Proxy<I>>> { fn new_global(&mut self, global: Main<I>, data: DispatchData); fn error(&mut self, _version: u32, _data: DispatchData) {} } impl<F, I: Interface> GlobalImplementor<I> for F where I: Interface + AsRef<Proxy<I>> + From<Proxy<I>>, F: FnMut(Main<I>, DispatchData), { fn new_global(&mut self, global: Main<I>, data: DispatchData) { (*self)(global, data) } } #[macro_export] macro_rules! global_filter { ($([$interface:ty, $version:expr, $callback:expr]),*) => { { use $crate::protocol::wl_registry; use $crate::{GlobalEvent, Interface, Attached, GlobalImplementor, DispatchData}; type Callback = Box<dyn FnMut(u32, u32, Attached<wl_registry::WlRegistry>, DispatchData<'_>)>; let mut callbacks: Vec<(&'static str, Callback)> = Vec::new(); $({ let mut cb = { $callback }; callbacks.push(( <$interface as Interface>::NAME, Box::new(move |id, version, registry: Attached<wl_registry::WlRegistry>, ddata: DispatchData| { if version < $version { GlobalImplementor::<$interface>::error(&mut cb, version, ddata); } else { let proxy = registry.bind::<$interface>(version, id); GlobalImplementor::<$interface>::new_global(&mut cb, proxy, ddata); } }) as Box<_> )); })* move |event: GlobalEvent, registry: Attached<wl_registry::WlRegistry>, ddata| { if let GlobalEvent::New { id, interface, version } = event { for &mut (iface, ref mut cb) in &mut callbacks { if iface == interface { cb(id, version, registry, ddata); break; } } } } } } }
match msg { wl_registry::Event::Global { name, interface, version, } => { inner.list.push((name, interface, version)); } wl_registry::Event::GlobalRemove { name } => { inner.list.retain(|&(n, _, _)| n != name); } }
if_condition
[ { "content": "pub fn demodulate(list: &str, cache: &mut AtomCache) -> Rc<Exp> {\n\n let (ret, _) = demodulate_list(list, cache);\n\n ret.set_cached(Rc::clone(&ret));\n\n ret\n\n}\n\n\n", "file_path": "src/transport.rs", "rank": 0, "score": 154818.572826611 }, { "content": "pub fn mo...
Rust
jormungandr/src/topology/mod.rs
MitchellTesla/jormungandr-rom_io
2325582d4dced77e2b023b12ffe6d014005078c8
use crate::network::p2p::Address; use jormungandr_lib::{interfaces::Subscription, time::SystemTime}; use serde::{Serialize, Serializer}; use std::{ convert::{TryFrom, TryInto}, fmt, hash::{Hash, Hasher}, }; mod gossip; pub mod layers; mod process; mod quarantine; #[allow(clippy::module_inception)] mod topology; pub use self::{ gossip::{Gossip, Gossips}, process::{start, TaskData, DEFAULT_NETWORK_STUCK_INTERVAL}, topology::{P2pTopology, View}, }; pub use quarantine::{QuarantineConfig, ReportRecords}; /** # topics definition for p2p interest subscriptions */ pub mod topic { use poldercast::Topic; pub const MESSAGES: Topic = Topic::new([0; 32]); pub const BLOCKS: Topic = Topic::new([1; 32]); } /** limits for the property::{Serialize/Deserialize} implementations */ pub mod limits { pub const MAX_GOSSIP_SIZE: usize = 512; pub const MAX_ID_SIZE: u64 = 32; } #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)] pub struct NodeId(keynesis::key::ed25519::PublicKey); impl From<jormungandr_lib::interfaces::NodeId> for NodeId { fn from(id: jormungandr_lib::interfaces::NodeId) -> Self { let id_bytes = id.as_ref().as_ref(); NodeId(id_bytes.try_into().unwrap()) } } impl From<NodeId> for jormungandr_lib::interfaces::NodeId { fn from(node_id: NodeId) -> jormungandr_lib::interfaces::NodeId { jormungandr_lib::interfaces::NodeId::from_hex(&node_id.0.to_string()).unwrap() } } impl TryFrom<&[u8]> for NodeId { type Error = chain_crypto::PublicKeyError; fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> { use chain_crypto::{Ed25519, PublicKey}; Ok(Self::from( PublicKey::<Ed25519>::from_binary(bytes) .map(jormungandr_lib::interfaces::NodeId::from)?, )) } } impl fmt::Display for NodeId { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.0) } } impl AsRef<keynesis::key::ed25519::PublicKey> for NodeId { fn as_ref(&self) -> &keynesis::key::ed25519::PublicKey { &self.0 } } impl Serialize for NodeId { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { if serializer.is_human_readable() { self.0.to_string().serialize(serializer) } else { self.0.as_ref().serialize(serializer) } } } pub type Peer = Gossip; #[derive(Eq, Clone, Serialize, Debug)] pub struct PeerInfo { pub id: NodeId, pub address: Address, pub last_update: SystemTime, pub quarantined: Option<SystemTime>, pub subscriptions: Vec<Subscription>, } impl PartialEq for PeerInfo { fn eq(&self, other: &Self) -> bool { self.id == other.id && self.address == other.address } } impl Hash for PeerInfo { fn hash<H: Hasher>(&self, state: &mut H) { self.id.hash(state); self.address.hash(state); } } impl From<Peer> for PeerInfo { fn from(other: Peer) -> Self { let other: poldercast::Gossip = other.into(); Self { id: NodeId(other.id()), address: other.address(), last_update: other.time().to_system_time().into(), quarantined: None, subscriptions: other .subscriptions() .iter() .map(|s| Subscription { topic: s.topic().to_string(), interest: s .interest_level() .priority_score(poldercast::InterestLevel::ZERO) as u32, }) .collect(), } } }
use crate::network::p2p::Address; use jormungandr_lib::{interfaces::Subscription, time::SystemTime}; use serde::{Serialize, Serializer}; use std::{ convert::{TryFrom, TryInto}, fmt, hash::{Hash, Hasher}, }; mod gossip; pub mod layers; mod process; mod quarantine; #[allow(clippy::module_inception)] mod topology; pub use self::{ gossip::{Gossip, Gossips}, process::{start, TaskData, DEFAULT_NETWORK_STUCK_INTERVAL}, topology::{P2pTopology, View}, }; pub use quarantine::{QuarantineConfig, ReportRecords}; /** # topics definition for p2p interest subscriptions */ pub mod topic { use poldercast::Topic; pub const MESSAGES: Topic = Topic::new([0; 32]); pub const BLOCKS: Topic = Topic::new([1; 32]); } /** limits for the property::{Serialize/Deserialize} implementations */ pub mod limits { pub const MAX_GOSSIP_SIZE: usize = 512; pub const MAX_ID_SIZE: u64 = 32; } #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)] pub struct NodeId(keynesis::key::ed25519::PublicKey); impl From<jormungandr_lib::interfaces::NodeId> for NodeId { fn from(id: jormungandr_lib::interfaces::NodeId) -> Self { let id_bytes = id.as_ref().as_ref(); NodeId(id_bytes.try_into().unwrap()) } } impl From<NodeId> for jormungandr_lib::interfaces::NodeId { fn from(node_id: NodeId) -> jormungandr_lib::interfaces::NodeId { jormungandr_lib::interfaces::NodeId::from_hex(&node_id.0.to_string()).unwrap() } } impl TryFrom<&[u8]> for NodeId { type Error = chain_crypto::PublicKeyError; fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> { use chain_crypto::{Ed25519, PublicKey}; Ok(Self::from( PublicKey::<Ed25519>::from_binary(bytes) .map(jormungandr_lib::interfaces::NodeId::from)?, )) } } impl fmt::Display for NodeId { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.0) } } impl AsRef<keynesis::key::ed25519::PublicKey> for NodeId { fn as_ref(&self) -> &keynesis::key::ed25519::PublicKey { &self.0 } } impl Serialize for NodeId { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { if serializer.is_human_readable() { self.0.to_string().serialize(serializer) } else { self.0.as_ref().serialize(serializer) } } } pub type Peer = Gossip; #[derive(Eq, Clone, Serialize, Debug)] pub struct PeerInfo { pub id: NodeId, pub address: Address, pub last_update: SystemTime, pub quarantined: Option<SystemTime>, pub subscriptions: Vec<Subscription>, } impl PartialEq for PeerInfo { fn eq(&self, other: &Self) -> bool { self.id == other.id && self.address == other.address } } impl Hash for PeerInfo { fn hash<H: Hasher>(&self, state: &mut H) { self.id.hash(state); self.address.hash(state); } } impl From<Peer> for PeerInfo {
}
fn from(other: Peer) -> Self { let other: poldercast::Gossip = other.into(); Self { id: NodeId(other.id()), address: other.address(), last_update: other.time().to_system_time().into(), quarantined: None, subscriptions: other .subscriptions() .iter() .map(|s| Subscription { topic: s.topic().to_string(), interest: s .interest_level() .priority_score(poldercast::InterestLevel::ZERO) as u32, }) .collect(), } }
function_block-full_function
[ { "content": "pub fn load_block(block_reader: impl BufRead) -> Result<Block, Error> {\n\n Block::deserialize(&mut Codec::new(block_reader)).map_err(Error::BlockFileCorrupted)\n\n}\n\n\n\n#[derive(StructOpt)]\n\npub struct Common {\n\n #[structopt(flatten)]\n\n pub input: Input,\n\n\n\n /// the file ...
Rust
src/dynamics/world.rs
Gohla/rust_box2d
d5431f905a09c0b2670f648c15f6d5120c0693c3
#[path = "world_callbacks.rs"] pub mod callbacks; use std::mem; use std::ptr; use std::marker::PhantomData; use std::cell::{Ref, RefMut}; use wrap::*; use handle::*; use common::{Draw, DrawLink, DrawFlags}; use common::math::Vec2; use collision::AABB; use dynamics::Profile; use user_data::UserDataTypes; use dynamics::body::{BodyDef, MetaBody, Body}; use dynamics::joints::{Joint, JointDef, MetaJoint}; use dynamics::contacts::Contact; use self::callbacks::{ContactFilter, ContactFilterLink, ContactListener, ContactListenerLink, QueryCallback, QueryCallbackLink, RayCastCallback, RayCastCallbackLink}; pub type BodyHandle = TypedHandle<Body>; pub type JointHandle = TypedHandle<Joint>; pub struct World<U: UserDataTypes> { ptr: *mut ffi::World, bodies: HandleMap<MetaBody<U>, Body>, joints: HandleMap<MetaJoint<U>, Joint>, contact_filter_link: ContactFilterLink, contact_listener_link: ContactListenerLink, draw_link: DrawLink, } impl<U: UserDataTypes> Wrapped<ffi::World> for World<U> { unsafe fn ptr(&self) -> *const ffi::World { self.ptr as *const ffi::World } unsafe fn mut_ptr(&mut self) -> *mut ffi::World { self.ptr } } impl<U: UserDataTypes> World<U> { pub fn new(gravity: &Vec2) -> Self { unsafe { World { ptr: ffi::World_new(gravity), bodies: HandleMap::new(), joints: HandleMap::new(), contact_filter_link: ContactFilterLink::new(), contact_listener_link: ContactListenerLink::new(), draw_link: DrawLink::new(), } } } pub fn set_contact_filter<F: ContactFilter<U>>(&mut self, filter: Box<F>) { unsafe { let filter_ptr = self.contact_filter_link.use_with(filter); ffi::World_set_contact_filter(self.mut_ptr(), filter_ptr); } } pub fn set_contact_listener<L: ContactListener<U>>(&mut self, listener: Box<L>) { unsafe { let listener_ptr = self.contact_listener_link.use_with(listener); ffi::World_set_contact_listener(self.mut_ptr(), listener_ptr); } } pub fn create_body(&mut self, def: &BodyDef) -> BodyHandle where U::BodyData: Default { self.create_body_with(def, U::BodyData::default()) } pub fn create_body_with(&mut self, def: &BodyDef, data: U::BodyData) -> BodyHandle { unsafe { let body = ffi::World_create_body(self.mut_ptr(), def); self.bodies.insert_with(|h| MetaBody::new(body, h, data)) } } pub fn body(&self, handle: BodyHandle) -> Ref<MetaBody<U>> { self.bodies.get(handle).expect("invalid body handle") } pub fn body_mut(&self, handle: BodyHandle) -> RefMut<MetaBody<U>> { self.bodies.get_mut(handle).expect("invalid body handle") } pub fn destroy_body(&mut self, handle: BodyHandle) { let mut body = self.bodies.remove(handle); World::remove_body_joint_handles(&mut body, &mut self.joints); unsafe { ffi::World_destroy_body(self.mut_ptr(), body.mut_ptr()); } } pub fn bodies(&self) -> HandleIter<Body, MetaBody<U>> { self.bodies.iter() } fn remove_body_joint_handles(body: &mut Body, joints: &mut HandleMap<MetaJoint<U>, Joint>) { for (_, joint) in body.joints() { joints.remove(joint); } } pub fn create_joint<JD: JointDef>(&mut self, def: &JD) -> JointHandle where U::JointData: Default { self.create_joint_with(def, U::JointData::default()) } pub fn create_joint_with<JD: JointDef>(&mut self, def: &JD, data: U::JointData) -> JointHandle { unsafe { let joint = def.create(self); self.joints.insert_with(|h| MetaJoint::new(joint, h, data)) } } pub fn joint(&self, handle: JointHandle) -> Ref<MetaJoint<U>> { self.joints.get(handle).expect("invalid joint handle") } pub fn joint_mut(&self, handle: JointHandle) -> RefMut<MetaJoint<U>> { self.joints.get_mut(handle).expect("invalid joint handle") } pub fn destroy_joint(&mut self, handle: JointHandle) { let mut joint = self.joints.remove(handle); unsafe { ffi::World_destroy_joint(self.mut_ptr(), joint.mut_base_ptr()); } } pub fn joints(&self) -> HandleIter<Joint, MetaJoint<U>> { self.joints.iter() } pub fn step(&mut self, time_step: f32, velocity_iterations: i32, position_iterations: i32) { unsafe { ffi::World_step(self.mut_ptr(), time_step, velocity_iterations, position_iterations); } } pub fn clear_forces(&mut self) { unsafe { ffi::World_clear_forces(self.mut_ptr()) } } pub fn draw_debug_data<D: Draw>(&mut self, draw: &mut D, flags: DrawFlags) { unsafe { let ptr = self.draw_link.use_with(draw, flags); ffi::World_set_debug_draw(self.mut_ptr(), ptr); ffi::World_draw_debug_data(self.mut_ptr()); ffi::World_set_debug_draw(self.mut_ptr(), ptr::null_mut()); } } pub fn query_aabb<C: QueryCallback>(&self, callback: &mut C, aabb: &AABB) { unsafe { let mut link = QueryCallbackLink::new(); let ptr = link.use_with(callback); ffi::World_query_aabb(self.ptr(), ptr, aabb); } } pub fn ray_cast<C: RayCastCallback>(&self, callback: &mut C, p1: &Vec2, p2: &Vec2) { unsafe { let mut link = RayCastCallbackLink::new(); let ptr = link.use_with(callback); ffi::World_ray_cast(self.ptr(), ptr, p1, p2); } } pub fn contacts_mut(&mut self) -> ContactIterMut { ContactIterMut { ptr: unsafe { ffi::World_get_contact_list(self.mut_ptr()) }, phantom: PhantomData, } } pub fn contacts(&self) -> ContactIter { ContactIter { ptr: unsafe { ffi::World_get_contact_list_const(self.ptr()) }, phantom: PhantomData, } } pub fn set_sleeping_allowed(&mut self, flag: bool) { unsafe { ffi::World_set_allow_sleeping(self.mut_ptr(), flag) } } pub fn is_sleeping_allowed(&self) -> bool { unsafe { ffi::World_get_allow_sleeping(self.ptr()) } } pub fn set_warm_starting(&mut self, flag: bool) { unsafe { ffi::World_set_warm_starting(self.mut_ptr(), flag) } } pub fn is_warm_starting(&self) -> bool { unsafe { ffi::World_get_warm_starting(self.ptr()) } } pub fn set_continuous_physics(&mut self, flag: bool) { unsafe { ffi::World_set_continuous_physics(self.mut_ptr(), flag) } } pub fn is_continuous_physics(&self) -> bool { unsafe { ffi::World_get_continuous_physics(self.ptr()) } } pub fn set_sub_stepping(&mut self, flag: bool) { unsafe { ffi::World_set_sub_stepping(self.mut_ptr(), flag) } } pub fn is_sub_stepping(&self) -> bool { unsafe { ffi::World_get_sub_stepping(self.ptr()) } } pub fn proxy_count(&self) -> i32 { unsafe { ffi::World_get_proxy_count(self.ptr()) } } pub fn body_count(&self) -> i32 { unsafe { ffi::World_get_body_count(self.ptr()) } } pub fn joint_count(&self) -> i32 { unsafe { ffi::World_get_joint_count(self.ptr()) } } pub fn contact_count(&self) -> i32 { unsafe { ffi::World_get_contact_count(self.ptr()) } } pub fn tree_height(&self) -> i32 { unsafe { ffi::World_get_tree_height(self.ptr()) } } pub fn tree_balance(&self) -> i32 { unsafe { ffi::World_get_tree_balance(self.ptr()) } } pub fn tree_quality(&self) -> f32 { unsafe { ffi::World_get_tree_quality(self.ptr()) } } pub fn set_gravity(&mut self, gravity: &Vec2) { unsafe { ffi::World_set_gravity(self.mut_ptr(), gravity) } } pub fn gravity(&self) -> Vec2 { unsafe { ffi::World_get_gravity(self.ptr()) } } pub fn is_locked(&self) -> bool { unsafe { ffi::World_is_locked(self.ptr()) } } pub fn set_auto_clearing_forces(&mut self, flag: bool) { unsafe { ffi::World_set_auto_clear_forces(self.mut_ptr(), flag) } } pub fn is_auto_clearing_forces(&self) -> bool { unsafe { ffi::World_get_auto_clear_forces(self.ptr()) } } pub fn shift_origin(&mut self, origin: &Vec2) { unsafe { ffi::World_shift_origin(self.mut_ptr(), origin) } } pub fn profile<'a>(&'a self) -> &'a Profile { unsafe { &*ffi::World_get_profile(self.ptr()) } } pub fn dump(&mut self) { unsafe { ffi::World_dump(self.mut_ptr()) } } } impl<U: UserDataTypes> Drop for World<U> { fn drop(&mut self) { unsafe { ffi::World_drop(self.mut_ptr()) } } } pub struct ContactIterMut<'a> { ptr: *mut ffi::Contact, phantom: PhantomData<&'a ()>, } impl<'a> Iterator for ContactIterMut<'a> { type Item = WrappedRefMut<'a, Contact>; fn next(&mut self) -> Option<Self::Item> { if self.ptr.is_null() { None } else { unsafe { let next = ffi::Contact_get_next(self.ptr); Some(WrappedRefMut::new(Contact::from_ffi(mem::replace(&mut self.ptr, next)))) } } } } pub struct ContactIter<'a> { ptr: *const ffi::Contact, phantom: PhantomData<&'a ()>, } impl<'a> Iterator for ContactIter<'a> { type Item = WrappedRef<'a, Contact>; fn next(&mut self) -> Option<Self::Item> { if self.ptr.is_null() { None } else { unsafe { let next = ffi::Contact_get_next_const(self.ptr); Some(WrappedRef::new(Contact::from_ffi( mem::replace(&mut self.ptr, next) as *mut ffi::Contact ))) } } } } #[doc(hidden)] pub mod ffi { pub use common::ffi::Draw; pub use dynamics::body::ffi::Body; pub use dynamics::joints::ffi::Joint; pub use dynamics::contacts::ffi::{Contact, Contact_get_next, Contact_get_next_const}; pub use super::callbacks::ffi::{ContactFilter, ContactListener, QueryCallback, RayCastCallback}; use common::math::Vec2; use collision::AABB; use dynamics::Profile; use dynamics::body::BodyDef; pub enum World {} extern "C" { pub fn World_new(gravity: *const Vec2) -> *mut World; pub fn World_drop(slf: *mut World); pub fn World_set_contact_filter(slf: *mut World, cf: *mut ContactFilter); pub fn World_set_contact_listener(slf: *mut World, cl: *mut ContactListener); pub fn World_set_debug_draw(slf: *mut World, dd: *mut Draw); pub fn World_create_body(slf: *mut World, def: *const BodyDef) -> *mut Body; pub fn World_destroy_body(slf: *mut World, body: *mut Body); pub fn World_destroy_joint(slf: *mut World, joint: *mut Joint); pub fn World_step(slf: *mut World, time_step: f32, velocity_iterations: i32, position_iterations: i32); pub fn World_clear_forces(slf: *mut World); pub fn World_draw_debug_data(slf: *mut World); pub fn World_query_aabb(slf: *const World, qc: *mut QueryCallback, aabb: *const AABB); pub fn World_ray_cast(slf: *const World, rcc: *mut RayCastCallback, p1: *const Vec2, p2: *const Vec2); pub fn World_get_contact_list(slf: *mut World) -> *mut Contact; pub fn World_get_contact_list_const(slf: *const World) -> *const Contact; pub fn World_set_allow_sleeping(slf: *mut World, flag: bool); pub fn World_get_allow_sleeping(slf: *const World) -> bool; pub fn World_set_warm_starting(slf: *mut World, flag: bool); pub fn World_get_warm_starting(slf: *const World) -> bool; pub fn World_set_continuous_physics(slf: *mut World, flag: bool); pub fn World_get_continuous_physics(slf: *const World) -> bool; pub fn World_set_sub_stepping(slf: *mut World, flag: bool); pub fn World_get_sub_stepping(slf: *const World) -> bool; pub fn World_get_proxy_count(slf: *const World) -> i32; pub fn World_get_body_count(slf: *const World) -> i32; pub fn World_get_joint_count(slf: *const World) -> i32; pub fn World_get_contact_count(slf: *const World) -> i32; pub fn World_get_tree_height(slf: *const World) -> i32; pub fn World_get_tree_balance(slf: *const World) -> i32; pub fn World_get_tree_quality(slf: *const World) -> f32; pub fn World_set_gravity(slf: *mut World, gravity: *const Vec2); pub fn World_get_gravity(slf: *const World) -> Vec2; pub fn World_is_locked(slf: *const World) -> bool; pub fn World_set_auto_clear_forces(slf: *mut World, flag: bool); pub fn World_get_auto_clear_forces(slf: *const World) -> bool; pub fn World_shift_origin(slf: *mut World, origin: *const Vec2); pub fn World_get_profile(slf: *const World) -> *const Profile; pub fn World_dump(slf: *mut World); } }
#[path = "world_callbacks.rs"] pub mod callbacks; use std::mem; use std::ptr; use std::marker::PhantomData; use std::cell::{Ref, RefMut}; use wrap::*; use handle::*; use common::{Draw, DrawLink, DrawFlags}; use common::math::Vec2; use collision::AABB; use dynamics::Profile; use user_data::UserDataTypes; use dynamics::body::{BodyDef, MetaBody, Body}; use dynamics::joints::{Joint, JointDef, MetaJoint}; use dynamics::contacts::Contact; use self::callbacks::{ContactFilter, ContactFilterLink, ContactListener, ContactListenerLink, QueryCallback, QueryCallbackLink, RayCastCallback, RayCastCallbackLink}; pub type BodyHandle = TypedHandle<Body>; pub type JointHandle = TypedHandle<Joint>; pub struct World<U: UserDataTypes> { ptr: *mut ffi::World, bodies: HandleMap<MetaBody<U>, Body>, joints: HandleMap<MetaJoint<U>, Joint>, contact_filter_link: ContactFilterLink, contact_listener_link: ContactListenerLink, draw_link: DrawLink, } impl<U: UserDataTypes> Wrapped<ffi::World> for World<U> { unsafe fn ptr(&self) -> *const ffi::World { self.ptr as *const ffi::World } unsafe fn mut_ptr(&mut self) -> *mut ffi::World { self.ptr } } impl<U: UserDataTypes> World<U> { pub fn new(gravity: &Vec2) -> Self { unsafe { World { ptr: ffi::World_new(gravity), bodies: HandleMap::new(), joints: HandleMap::new(), contact_filter_link: ContactFilterLink::new(), contact_listener_link: ContactListenerLink::new(), draw_link: DrawLink::new(), } } } pub fn set_contact_filter<F: ContactFilter<U>>(&mut self, filter: Box<F>) { unsafe { let filter_ptr = self.contact_filter_link.use_with(filter); ffi::World_set_contact_filter(self.mut_ptr(), filter_ptr); } } pub fn set_contact_listener<L: ContactListener<U>>(&mut self, listener: Box<L>) { unsafe { let listener_ptr = self.contact_listener_link.use_with(listener); ffi::World_set_contact_listener(self.mut_ptr(), listener_ptr); } } pub fn create_body(&mut self, def: &BodyDef) -> BodyHandle where U::BodyData: Default { self.create_body_with(def, U::BodyData::default()) } pub fn create_body_with(&mut self, def: &BodyDef, data: U::BodyData) -> BodyHandle { unsafe { let body = ffi::World_create_body(self.mut_ptr(), def); self.bodies.insert_with(|h| MetaBody::new(body, h, data)) } } pub fn body(&self, handle: BodyHandle) -> Ref<MetaBody<U>> { self.bodies.get(handle).expect("invalid body handle") } pub fn body_mut(&self, handle: BodyHandle) -> RefMut<MetaBody<U>> { self.bodies.get_mut(handle).expect("invalid body handle") } pub fn destroy_body(&mut self, handle: BodyHandle) { let mut body = self.bodies.remove(handle); World::remove_body_joint_handles(&mut body, &mut self.joints); unsafe { ffi::World_destroy_body(self.mut_ptr(), body.mut_ptr()); } } pub fn bodies(&self) -> HandleIter<Body, MetaBody<U>> { self.bodies.iter() } fn remove_body_joint_handles(body: &mut Body, joints: &mut HandleMap<MetaJoint<U>, Joint>) { for (_, joint) in body.joints() { joints.remove(joint); } } pub fn create_joint<JD: JointDef>(&mut self, def: &JD) -> JointHandle where U::JointData: Default { self.create_joint_with(def, U::JointData::default()) } pub fn create_joint_with<JD: JointDef>(&mut self, def: &JD, data: U::JointData) -> JointHandle { unsafe { let joint = def.create(self); self.joints.insert_with(|h| MetaJoint::new(joint, h, data)) } } pub fn joint(&self, handle: JointHandle) -> Ref<MetaJoint<U>> { self.joints.get(handle).expect("invalid joint handle") } pub fn joint_mut(&self, handle: JointHandle) -> RefMut<MetaJoint<U>> { self.joints.get_mut(handle).expect("invalid joint handle") } pub fn destroy_joint(&mut self, handle: JointHandle) { let mut joint = self.joints.remove(handle); unsafe { ffi::World_destroy_joint(self.mut_ptr(), joint.mut_base_ptr()); } } pub fn joints(&self) -> HandleIter<Joint, MetaJoint<U>> { self.joints.iter() } pub fn step(&mut self, time_step: f32, velocity_iterations: i32, position_iterations: i32) { unsafe { ffi::World_step(self.mut_ptr(), time_step, velocity_iterations, position_iterations); } } pub fn clear_forces(&mut self) { unsafe { ffi::World_clear_forces(self.mut_ptr()) } } pub fn draw_debug_data<D: Draw>(&mut self, draw: &mut D, flags: DrawFlags) { unsafe { let ptr = self.draw_link.use_with(draw, flags); ffi::World_set_debug_draw(self.mut_ptr(), ptr); ffi::World_draw_debug_data(self.mut_ptr()); ffi::World_set_debug_draw(self.mut_ptr(), ptr::null_mut()); } } pub fn query_aabb<C: QueryCallback>(&self, callback: &mut C, aabb: &AABB) {
(WrappedRef::new(Contact::from_ffi( mem::replace(&mut self.ptr, next) as *mut ffi::Contact ))) } } } } #[doc(hidden)] pub mod ffi { pub use common::ffi::Draw; pub use dynamics::body::ffi::Body; pub use dynamics::joints::ffi::Joint; pub use dynamics::contacts::ffi::{Contact, Contact_get_next, Contact_get_next_const}; pub use super::callbacks::ffi::{ContactFilter, ContactListener, QueryCallback, RayCastCallback}; use common::math::Vec2; use collision::AABB; use dynamics::Profile; use dynamics::body::BodyDef; pub enum World {} extern "C" { pub fn World_new(gravity: *const Vec2) -> *mut World; pub fn World_drop(slf: *mut World); pub fn World_set_contact_filter(slf: *mut World, cf: *mut ContactFilter); pub fn World_set_contact_listener(slf: *mut World, cl: *mut ContactListener); pub fn World_set_debug_draw(slf: *mut World, dd: *mut Draw); pub fn World_create_body(slf: *mut World, def: *const BodyDef) -> *mut Body; pub fn World_destroy_body(slf: *mut World, body: *mut Body); pub fn World_destroy_joint(slf: *mut World, joint: *mut Joint); pub fn World_step(slf: *mut World, time_step: f32, velocity_iterations: i32, position_iterations: i32); pub fn World_clear_forces(slf: *mut World); pub fn World_draw_debug_data(slf: *mut World); pub fn World_query_aabb(slf: *const World, qc: *mut QueryCallback, aabb: *const AABB); pub fn World_ray_cast(slf: *const World, rcc: *mut RayCastCallback, p1: *const Vec2, p2: *const Vec2); pub fn World_get_contact_list(slf: *mut World) -> *mut Contact; pub fn World_get_contact_list_const(slf: *const World) -> *const Contact; pub fn World_set_allow_sleeping(slf: *mut World, flag: bool); pub fn World_get_allow_sleeping(slf: *const World) -> bool; pub fn World_set_warm_starting(slf: *mut World, flag: bool); pub fn World_get_warm_starting(slf: *const World) -> bool; pub fn World_set_continuous_physics(slf: *mut World, flag: bool); pub fn World_get_continuous_physics(slf: *const World) -> bool; pub fn World_set_sub_stepping(slf: *mut World, flag: bool); pub fn World_get_sub_stepping(slf: *const World) -> bool; pub fn World_get_proxy_count(slf: *const World) -> i32; pub fn World_get_body_count(slf: *const World) -> i32; pub fn World_get_joint_count(slf: *const World) -> i32; pub fn World_get_contact_count(slf: *const World) -> i32; pub fn World_get_tree_height(slf: *const World) -> i32; pub fn World_get_tree_balance(slf: *const World) -> i32; pub fn World_get_tree_quality(slf: *const World) -> f32; pub fn World_set_gravity(slf: *mut World, gravity: *const Vec2); pub fn World_get_gravity(slf: *const World) -> Vec2; pub fn World_is_locked(slf: *const World) -> bool; pub fn World_set_auto_clear_forces(slf: *mut World, flag: bool); pub fn World_get_auto_clear_forces(slf: *const World) -> bool; pub fn World_shift_origin(slf: *mut World, origin: *const Vec2); pub fn World_get_profile(slf: *const World) -> *const Profile; pub fn World_dump(slf: *mut World); } }
unsafe { let mut link = QueryCallbackLink::new(); let ptr = link.use_with(callback); ffi::World_query_aabb(self.ptr(), ptr, aabb); } } pub fn ray_cast<C: RayCastCallback>(&self, callback: &mut C, p1: &Vec2, p2: &Vec2) { unsafe { let mut link = RayCastCallbackLink::new(); let ptr = link.use_with(callback); ffi::World_ray_cast(self.ptr(), ptr, p1, p2); } } pub fn contacts_mut(&mut self) -> ContactIterMut { ContactIterMut { ptr: unsafe { ffi::World_get_contact_list(self.mut_ptr()) }, phantom: PhantomData, } } pub fn contacts(&self) -> ContactIter { ContactIter { ptr: unsafe { ffi::World_get_contact_list_const(self.ptr()) }, phantom: PhantomData, } } pub fn set_sleeping_allowed(&mut self, flag: bool) { unsafe { ffi::World_set_allow_sleeping(self.mut_ptr(), flag) } } pub fn is_sleeping_allowed(&self) -> bool { unsafe { ffi::World_get_allow_sleeping(self.ptr()) } } pub fn set_warm_starting(&mut self, flag: bool) { unsafe { ffi::World_set_warm_starting(self.mut_ptr(), flag) } } pub fn is_warm_starting(&self) -> bool { unsafe { ffi::World_get_warm_starting(self.ptr()) } } pub fn set_continuous_physics(&mut self, flag: bool) { unsafe { ffi::World_set_continuous_physics(self.mut_ptr(), flag) } } pub fn is_continuous_physics(&self) -> bool { unsafe { ffi::World_get_continuous_physics(self.ptr()) } } pub fn set_sub_stepping(&mut self, flag: bool) { unsafe { ffi::World_set_sub_stepping(self.mut_ptr(), flag) } } pub fn is_sub_stepping(&self) -> bool { unsafe { ffi::World_get_sub_stepping(self.ptr()) } } pub fn proxy_count(&self) -> i32 { unsafe { ffi::World_get_proxy_count(self.ptr()) } } pub fn body_count(&self) -> i32 { unsafe { ffi::World_get_body_count(self.ptr()) } } pub fn joint_count(&self) -> i32 { unsafe { ffi::World_get_joint_count(self.ptr()) } } pub fn contact_count(&self) -> i32 { unsafe { ffi::World_get_contact_count(self.ptr()) } } pub fn tree_height(&self) -> i32 { unsafe { ffi::World_get_tree_height(self.ptr()) } } pub fn tree_balance(&self) -> i32 { unsafe { ffi::World_get_tree_balance(self.ptr()) } } pub fn tree_quality(&self) -> f32 { unsafe { ffi::World_get_tree_quality(self.ptr()) } } pub fn set_gravity(&mut self, gravity: &Vec2) { unsafe { ffi::World_set_gravity(self.mut_ptr(), gravity) } } pub fn gravity(&self) -> Vec2 { unsafe { ffi::World_get_gravity(self.ptr()) } } pub fn is_locked(&self) -> bool { unsafe { ffi::World_is_locked(self.ptr()) } } pub fn set_auto_clearing_forces(&mut self, flag: bool) { unsafe { ffi::World_set_auto_clear_forces(self.mut_ptr(), flag) } } pub fn is_auto_clearing_forces(&self) -> bool { unsafe { ffi::World_get_auto_clear_forces(self.ptr()) } } pub fn shift_origin(&mut self, origin: &Vec2) { unsafe { ffi::World_shift_origin(self.mut_ptr(), origin) } } pub fn profile<'a>(&'a self) -> &'a Profile { unsafe { &*ffi::World_get_profile(self.ptr()) } } pub fn dump(&mut self) { unsafe { ffi::World_dump(self.mut_ptr()) } } } impl<U: UserDataTypes> Drop for World<U> { fn drop(&mut self) { unsafe { ffi::World_drop(self.mut_ptr()) } } } pub struct ContactIterMut<'a> { ptr: *mut ffi::Contact, phantom: PhantomData<&'a ()>, } impl<'a> Iterator for ContactIterMut<'a> { type Item = WrappedRefMut<'a, Contact>; fn next(&mut self) -> Option<Self::Item> { if self.ptr.is_null() { None } else { unsafe { let next = ffi::Contact_get_next(self.ptr); Some(WrappedRefMut::new(Contact::from_ffi(mem::replace(&mut self.ptr, next)))) } } } } pub struct ContactIter<'a> { ptr: *const ffi::Contact, phantom: PhantomData<&'a ()>, } impl<'a> Iterator for ContactIter<'a> { type Item = WrappedRef<'a, Contact>; fn next(&mut self) -> Option<Self::Item> { if self.ptr.is_null() { None } else { unsafe { let next = ffi::Contact_get_next_const(self.ptr); Some
random
[ { "content": "pub fn step<U: UserDataTypes>(data: &mut Data<U>, dt: f32) {\n\n data.world.step(dt, VELOCITY_ITERATIONS, POSITION_ITERATIONS);\n\n}\n\n\n\nimpl<U: UserDataTypes> Test<U> for () {}\n\n\n\nimpl<F, U: UserDataTypes> Test<U> for F\n\n where F: FnMut(&Input, &mut Data<U>)\n\n{\n\n fn process_...
Rust
applications/vote-purge-stress/main.rs
pratikfegade/noria
0460dd90ff8950cf1262bd66b58fd03620221b85
#![allow(clippy::many_single_char_names)] use clap::{value_t_or_exit, App, Arg}; use hdrhistogram::Histogram; use noria::{Builder, DurabilityMode, FrontierStrategy, PersistenceParameters}; use std::time::{Duration, Instant}; const RECIPE: &str = "# base tables CREATE TABLE Article (id int, title varchar(255), PRIMARY KEY(id)); CREATE TABLE Vote (article_id int, user int); # read queries CREATE VIEW VoteCount AS \ SELECT Vote.article_id, COUNT(user) AS votes FROM Vote GROUP BY Vote.article_id; QUERY ArticleWithVoteCount: SELECT Article.id, title, VoteCount.votes AS votes \ FROM Article \ LEFT JOIN VoteCount \ ON (Article.id = VoteCount.article_id) WHERE Article.id = ?;"; #[tokio::main] async fn main() { let args = App::new("purge-stress") .about("Benchmarks the latency of full replays in a user-curated news aggregator") .arg( Arg::with_name("flush-timeout") .long("flush-timeout") .takes_value(true) .default_value("100000") .help("Time to wait before processing a merged packet, in nanoseconds."), ) .arg( Arg::with_name("replay-timeout") .long("replay-timeout") .takes_value(true) .default_value("100000") .help("Time to batch replay requests for, in nanoseconds."), ) .arg( Arg::with_name("time") .short("t") .takes_value(true) .default_value("10") .help("Time to run benchmark for, in seconds."), ) .arg( Arg::with_name("purge") .long("purge") .takes_value(true) .possible_values(&["none", "reader", "all"]) .default_value("none") .help("Disable purging"), ) .arg(Arg::with_name("verbose").long("verbose").short("v")) .get_matches(); let runtime = value_t_or_exit!(args, "time", u64); let mut builder = Builder::default(); if args.is_present("verbose") { builder.log_with(noria::logger_pls()); } builder.set_persistence(PersistenceParameters { mode: DurabilityMode::MemoryOnly, flush_timeout: Duration::new(0, value_t_or_exit!(args, "flush-timeout", u32)), ..Default::default() }); builder.set_sharding(None); builder.set_partial_replay_batch_timeout(Duration::new( 0, value_t_or_exit!(args, "replay-timeout", u32), )); match args.value_of("purge").unwrap() { "all" => { builder.set_frontier_strategy(FrontierStrategy::AllPartial); } "reader" => { builder.set_frontier_strategy(FrontierStrategy::Readers); } "none" => {} _ => unreachable!(), } let (mut g, done) = builder.start_local().await.unwrap(); { g.ready().await.unwrap(); g.install_recipe(RECIPE).await.unwrap(); let mut a = g.table("Article").await.unwrap(); let mut v = g.table("Vote").await.unwrap(); let mut r = g.view("ArticleWithVoteCount").await.unwrap(); a.insert(vec![1.into(), "Hello world #1".into()]) .await .unwrap(); a.insert(vec![2.into(), "Hello world #2".into()]) .await .unwrap(); v.insert(vec![1.into(), "a".into()]).await.unwrap(); v.insert(vec![2.into(), "a".into()]).await.unwrap(); v.insert(vec![1.into(), "b".into()]).await.unwrap(); v.insert(vec![2.into(), "c".into()]).await.unwrap(); v.insert(vec![2.into(), "d".into()]).await.unwrap(); let one = 1.into(); let two = 2.into(); assert_eq!( r.lookup(&[one], true).await.unwrap(), vec![vec![1.into(), "Hello world #1".into(), 2.into()]] ); assert_eq!( r.lookup(&[two], true).await.unwrap(), vec![vec![2.into(), "Hello world #2".into(), 3.into()]] ); let mut n = 0; let start = Instant::now(); let mut stats = Histogram::<u64>::new_with_bounds(1, 60_000_000, 3).unwrap(); while start.elapsed() < Duration::from_secs(runtime) { for &id in &[1, 2] { let start = Instant::now(); r.lookup(&[id.into()], true).await.unwrap(); stats.saturating_record(start.elapsed().as_micros() as u64); n += 1; std::thread::sleep(Duration::from_millis(50)); } } println!("# purge mode: {}", args.value_of("purge").unwrap()); println!( "# replays/s: {:.2}", f64::from(n) / start.elapsed().as_secs_f64() ); println!("# op\tpct\ttime"); println!("replay\t50\t{:.2}\tµs", stats.value_at_quantile(0.5)); println!("replay\t95\t{:.2}\tµs", stats.value_at_quantile(0.95)); println!("replay\t99\t{:.2}\tµs", stats.value_at_quantile(0.99)); println!("replay\t100\t{:.2}\tµs", stats.max()); } drop(g); done.await; }
#![allow(clippy::many_single_char_names)] use clap::{value_t_or_exit, App, Arg}; use hdrhistogram::Histogram; use noria::{Builder, DurabilityMode, FrontierStrategy, PersistenceParameters}; use std::time::{Duration, Instant}; const RECIPE: &str = "# base tables CREATE TABLE Article (id int, title varchar(255), PRIMARY KEY(id)); CREATE TABLE Vote (article_id int, user int); # read queries CREATE VIEW VoteCount AS \ SELECT Vote.article_id, COUNT(user) AS votes FROM Vote GROUP BY Vote.article_id; QUERY ArticleWithVoteCount: SELECT Article.id, title, VoteCount.votes AS votes \ FROM Article \ LEFT JOIN VoteCount \ ON (Article.id = VoteCount.article_id) WHERE Article.id = ?;"; #[tokio::main] async fn main() { let args = App::new("purge-stress") .about("Benchmarks the latency of full replays in a user-curated news aggregator") .arg( Arg::with_name("flush-timeout") .long("flush-timeout") .takes_value(true) .default_value("100000") .help("Time to wait before processing a merged packet, in nanoseconds."), ) .arg( Arg::with_name("replay-timeout") .long("replay-timeout") .takes_value(true) .default_value("100000") .help("Time to batch replay requests for, in nanoseconds."), ) .arg( Arg::with_name("time") .short("t") .takes_value(true) .default_value("10") .help("Time to run benchmark for, in seconds."), ) .arg( Arg::with_name("purge") .long("purge") .takes_value(true) .possible_values(&["none", "reader", "all"]) .default_value("none") .help("Disable purging"), ) .arg(Arg::with_name("verbose").long("verbose").short("v")) .get_matches(); let runtime = value_t_or_exit!(args, "time", u64); let mut builder = Builder::default(); if args.is_present("verbose") { builder.log_with(noria::logger_pls()); } builder.set_persistence(PersistenceParameters { mode: DurabilityMode::MemoryOnly, flush_timeout: Duration::new(0, value_t_or_exit!(args, "flush-timeout", u32)), ..Default::default() }); builder.set_sharding(None); builder.set_partial_replay_batch_timeout(Duration::new( 0, value_t_or_exit!(args, "replay-timeout", u32), )); match args.value_of("purge").unwrap() { "all" => { builder.set_frontier_strategy(FrontierStrategy::AllPartial); } "reader" => { builder.set_frontier_strategy(FrontierStrategy::Readers); } "none" => {} _ => unreachable!(), } let (mut g, done) = builder.start_local().await.unwrap(); { g.ready().await.unwrap(); g.install_recipe(RECIPE).await.unwrap(); let mut a = g.table("Article").await.unwrap(); let mut v = g.table("Vote").await.unwrap(); let mut r = g.view("ArticleWithVoteCount").await.unwrap(); a.insert(vec![1.into(), "Hello world #1".into()]) .await .unwrap(); a.insert(vec![2.into(), "Hello world #2".into()]) .await .unwrap(); v.insert(vec![1.into(), "a".into()]).await.unwrap(); v.insert(vec![2.into(), "a".into()]).await.unwrap(); v.insert(vec![1.into(), "b".into()]).await.unwrap(); v.insert(vec![2.into(), "c".into()]).await.unwrap(); v.insert(vec![2.into(), "d".into()]).await.unwrap(); let one = 1.into(); let two = 2.into(); assert_eq!( r.lookup(&[one], true).await.unwrap(), vec![vec![1.into(), "Hello world #1".into(), 2.into()]] ); assert_eq!( r.lookup(&[two], true).await.unwrap(), vec![vec![2.into(), "Hello world #2".into(), 3.into()]] ); let mut n = 0; let start = Instant::now(); let mut stats = Histogram::<u64>::new_with_bounds(1, 60_000_000, 3).unwrap(); while start.elapsed() < Duration::from_secs(runtime) { for &id in &[1, 2] { let start = Instant::now(); r.lookup(&[id.into()], true).await.unwrap(); stats.saturating_record(start.elapsed().as_micros() as u64); n += 1; std::thread::sleep(Duration::from_milli
s(50)); } } println!("# purge mode: {}", args.value_of("purge").unwrap()); println!( "# replays/s: {:.2}", f64::from(n) / start.elapsed().as_secs_f64() ); println!("# op\tpct\ttime"); println!("replay\t50\t{:.2}\tµs", stats.value_at_quantile(0.5)); println!("replay\t95\t{:.2}\tµs", stats.value_at_quantile(0.95)); println!("replay\t99\t{:.2}\tµs", stats.value_at_quantile(0.99)); println!("replay\t100\t{:.2}\tµs", stats.max()); } drop(g); done.await; }
function_block-function_prefixed
[ { "content": "CREATE TABLE Vote (article_id int, user int);\n\n\n", "file_path": "applications/vote/clients/localsoup/graph.rs", "rank": 2, "score": 473892.9226471856 }, { "content": "CREATE VIEW user_stats AS SELECT users.id, user_comments.comments, user_stories.stories FROM users LEFT JOIN...
Rust
src/game.rs
afarinetti/gameoflife-rs
4d664f9122178727d2b3216876aa9409b9b7b97b
use std::fmt; #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub enum Cell { Dead, Alive, } impl fmt::Display for Cell { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Cell::Alive => write!(f, "ALIVE"), Cell::Dead => write!(f, "DEAD"), } } } pub struct Grid { num_rows: u32, num_cols: u32, grid: Vec<Cell>, } impl Grid { pub fn new(num_rows: u32, num_cols: u32) -> Grid { Grid { num_rows: num_rows, num_cols: num_cols, grid: vec![Cell::Dead; (num_rows * num_cols) as usize], } } pub fn set_cells(&mut self, cells: &[(u32, u32)]) { for (row, col) in cells.iter().cloned() { let idx = self.cell_to_index(row, col); self.grid[idx] = Cell::Alive; } } fn cell_to_index(&self, row: u32, col: u32) -> usize { ((row * self.num_cols) + col) as usize } pub fn get(&self, row: u32, col: u32) -> Cell { let index = self.cell_to_index(row, col); self.grid[index] } fn set(&mut self, row: u32, col: u32, state: Cell) { let index = self.cell_to_index(row, col); self.grid[index] = state } } impl fmt::Display for Grid { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { for line in self.grid.as_slice().chunks(self.num_cols as usize) { for &cell in line { let smybol = if cell == Cell::Dead { '◻' } else { '◼' }; write!(f, "{}", smybol)?; } write!(f, "\n")?; } Ok(()) } } struct Operation { row: u32, col: u32, state: Cell } impl Operation { fn new(row: u32, col: u32, state: Cell) -> Operation { Operation { row, col, state } } } impl fmt::Display for Operation { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Operation[row: {}, col: {}, state: {}]", self.row, self.col, self.state) } } pub struct ConwaySim { grid: Grid, generation: u32, } impl ConwaySim { pub fn new(num_rows: u32, num_cols: u32) -> ConwaySim { ConwaySim { grid: Grid::new(num_rows, num_cols), generation: 0, } } #[allow(dead_code)] pub fn new_with_grid(grid: Grid) -> ConwaySim { ConwaySim { grid, generation: 0 } } pub fn get_generation(&self) -> u32 { self.generation } pub fn is_cell_alive(&self, row: u32, col: u32) -> bool { self.grid.get(row, col) == Cell::Alive } pub fn is_any_cell_alive(&self) -> bool { let mut alive = false; for &cell in self.grid.grid.iter() { if cell == Cell::Alive { alive = true; break; } } return alive; } pub fn get_neighbor_count(&self, row: u32, col: u32) -> u8 { let mut count: u8 = 0; let mut new_row: u32; let mut new_col: u32; if (row > 0) && (col > 0) { new_row = row - 1; new_col = col - 1; if self.is_cell_alive(new_row, new_col) { count += 1; } } if row > 0 { new_row = row - 1; new_col = col; if self.is_cell_alive(new_row, new_col) { count += 1; } } if (row > 0) && ((col + 1) < self.grid.num_cols) { new_row = row - 1; new_col = col + 1; if self.is_cell_alive(new_row, new_col) { count += 1; } } if col > 0 { new_row = row; new_col = col - 1; if self.is_cell_alive(new_row, new_col) { count += 1; } } if (col + 1) < self.grid.num_cols { new_row = row; new_col = col + 1; if self.is_cell_alive(new_row, new_col) { count += 1; } } if ((row + 1) < self.grid.num_rows) && (col > 0) { new_row = row + 1; new_col = col - 1; if self.is_cell_alive(new_row, new_col) { count += 1; } } if (row + 1) < self.grid.num_rows { new_row = row + 1; new_col = col; if self.is_cell_alive(new_row, new_col) { count += 1; } } if ((row + 1) < self.grid.num_rows) && ((col + 1) < self.grid.num_cols) { new_row = row + 1; new_col = col + 1; if self.is_cell_alive(new_row, new_col) { count += 1; } } return count; } pub fn set_cells(&mut self, cells: &[(u32, u32)]) { self.grid.set_cells(cells); } fn apply_rules(&self, row: u32, col: u32) -> Vec<Operation> { let mut operations: Vec<Operation> = Vec::new(); let neighbor_count = self.get_neighbor_count(row, col); let alive = self.is_cell_alive(row, col); if alive { if neighbor_count < 2 { operations.push(Operation::new(row, col, Cell::Dead)); } else if neighbor_count <= 3 { } else { operations.push(Operation::new(row, col, Cell::Dead)); } } else { if neighbor_count == 3 { operations.push(Operation::new(row, col, Cell::Alive)); } } return operations; } pub fn step(&mut self) { let mut operations: Vec<Operation> = Vec::new(); self.generation += 1; for row in 0..self.grid.num_rows { for col in 0..self.grid.num_cols { let results = self.apply_rules(row, col); operations.extend(results); } } for operation in operations { self.grid.set(operation.row, operation.col, operation.state) } } } impl fmt::Display for ConwaySim { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.grid.fmt(f) } }
use std::fmt; #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub enum Cell { Dead, Alive, } impl fmt::Display for Cell { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Cell::Alive => write!(f, "ALIVE"), Cell::Dead => write!(f, "DEAD"), } } } pub struct Grid { num_rows: u32, num_cols: u32, grid: Vec<Cell>, } impl Grid { pub fn new(num_rows: u32, num_cols: u32) -> Grid { Grid { num_rows: num_rows, num_cols: num_cols, grid: vec![Cell::Dead; (num_rows * num_cols) as usize], } } pub fn set_cells(&mut self, cells: &[(u32, u32)]) { for (row, col) in cells.iter().cloned() { let idx = self.cell_to_index(row, col); self.grid[idx] = Cell::Alive; } } fn cell_to_index(&self, row: u32, col: u32) -> usize { ((row * self.num_cols) + col) as usize } pub fn get(&self, row: u32, col: u32) -> Cell { let index = self.cell_to_index(row, col); self.grid[index] } fn set(&mut self, row: u32, col: u32, state: Cell) { let index = self.cell_to_index(row, col); self.grid[index] = state } } impl fmt::Display for Grid { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { for line in self.grid.as_slice().chunks(self.num_cols as usize) { for &cell in line { let smybol = if cell == Cell::Dead { '◻' } else { '◼' }; write!(f, "{}", smybol)?; } write!(f, "\n")?; } Ok(()) } } struct Operation { row: u32, col: u32, state: Cell } impl Operation { fn new(row: u32, col: u32, state: Cell) -> Operation { Operation { row, col, state } } } impl fmt::Display for Operation { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Operation[row: {}, col: {}, state: {}]", self.row, self.col, self.state) } } pub struct ConwaySim { grid: Grid, generation: u32, } impl ConwaySim { pub fn new(num_rows: u32, nu
#[allow(dead_code)] pub fn new_with_grid(grid: Grid) -> ConwaySim { ConwaySim { grid, generation: 0 } } pub fn get_generation(&self) -> u32 { self.generation } pub fn is_cell_alive(&self, row: u32, col: u32) -> bool { self.grid.get(row, col) == Cell::Alive } pub fn is_any_cell_alive(&self) -> bool { let mut alive = false; for &cell in self.grid.grid.iter() { if cell == Cell::Alive { alive = true; break; } } return alive; } pub fn get_neighbor_count(&self, row: u32, col: u32) -> u8 { let mut count: u8 = 0; let mut new_row: u32; let mut new_col: u32; if (row > 0) && (col > 0) { new_row = row - 1; new_col = col - 1; if self.is_cell_alive(new_row, new_col) { count += 1; } } if row > 0 { new_row = row - 1; new_col = col; if self.is_cell_alive(new_row, new_col) { count += 1; } } if (row > 0) && ((col + 1) < self.grid.num_cols) { new_row = row - 1; new_col = col + 1; if self.is_cell_alive(new_row, new_col) { count += 1; } } if col > 0 { new_row = row; new_col = col - 1; if self.is_cell_alive(new_row, new_col) { count += 1; } } if (col + 1) < self.grid.num_cols { new_row = row; new_col = col + 1; if self.is_cell_alive(new_row, new_col) { count += 1; } } if ((row + 1) < self.grid.num_rows) && (col > 0) { new_row = row + 1; new_col = col - 1; if self.is_cell_alive(new_row, new_col) { count += 1; } } if (row + 1) < self.grid.num_rows { new_row = row + 1; new_col = col; if self.is_cell_alive(new_row, new_col) { count += 1; } } if ((row + 1) < self.grid.num_rows) && ((col + 1) < self.grid.num_cols) { new_row = row + 1; new_col = col + 1; if self.is_cell_alive(new_row, new_col) { count += 1; } } return count; } pub fn set_cells(&mut self, cells: &[(u32, u32)]) { self.grid.set_cells(cells); } fn apply_rules(&self, row: u32, col: u32) -> Vec<Operation> { let mut operations: Vec<Operation> = Vec::new(); let neighbor_count = self.get_neighbor_count(row, col); let alive = self.is_cell_alive(row, col); if alive { if neighbor_count < 2 { operations.push(Operation::new(row, col, Cell::Dead)); } else if neighbor_count <= 3 { } else { operations.push(Operation::new(row, col, Cell::Dead)); } } else { if neighbor_count == 3 { operations.push(Operation::new(row, col, Cell::Alive)); } } return operations; } pub fn step(&mut self) { let mut operations: Vec<Operation> = Vec::new(); self.generation += 1; for row in 0..self.grid.num_rows { for col in 0..self.grid.num_cols { let results = self.apply_rules(row, col); operations.extend(results); } } for operation in operations { self.grid.set(operation.row, operation.col, operation.state) } } } impl fmt::Display for ConwaySim { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.grid.fmt(f) } }
m_cols: u32) -> ConwaySim { ConwaySim { grid: Grid::new(num_rows, num_cols), generation: 0, } }
function_block-function_prefixed
[ { "content": "fn main() {\n\n let mut sim = game::ConwaySim::new(5, 5);\n\n\n\n sim.set_cells(&[\n\n (2, 1),\n\n (2, 2),\n\n (2, 3)\n\n ]);\n\n\n\n for _i in 0..105 {\n\n sim.step();\n\n \n\n println!(\"Generation: {}\", sim.get_generation());\n\n pri...
Rust
fly-query-rs/src/current_search.rs
HeroicosHM/Hackathon2020
1960fded5de849dca6b2eebdfcd4082d8f7c62f7
use crate::BEARER_AUTH; use reqwest::Client; use serde::{de::IgnoredAny, Deserialize, Serialize}; use wasm_bindgen::prelude::*; const AIRPORT_QUERY: &'static str = " query findAirports($query: String!) { airports(query: $query) { edges { node { ...Airport } } } } fragment Airport on AirportSuggestion { iataCode title selectedText subSuggestions { iataCode title selectedText } } "; #[wasm_bindgen] extern "C" { #[wasm_bindgen(js_namespace = console)] pub fn log(s: &str); } #[derive(Serialize)] struct ApQueryVariables<'a> { query: &'a str, } #[derive(Serialize)] struct ApQuery<'a> { query: &'static str, variables: ApQueryVariables<'a>, } impl<'a> ApQuery<'a> { fn new(search: &'a str) -> Self { ApQuery { query: AIRPORT_QUERY, variables: ApQueryVariables { query: search }, } } } #[derive(Deserialize)] struct ApQueryResponseNode { #[serde(rename(deserialize = "iataCode"))] _iata_code: IgnoredAny, #[serde(rename(deserialize = "title"))] _title: IgnoredAny, #[serde(rename(deserialize = "selectedText"))] selected_text: String, } #[derive(Deserialize)] struct ApQueryResponseNodeMG { #[serde(rename(deserialize = "iataCode"), skip_deserializing)] _iata_code: IgnoredAny, #[serde(rename(deserialize = "title"), skip_deserializing)] _title: IgnoredAny, #[serde(rename(deserialize = "selectedText"))] selected_text: String, #[serde(rename(serialize = "subSuggestions"), default)] subsuggestions: Option<Vec<ApQueryResponseNode>>, } impl ApQueryResponseNodeMG { fn flatten(self, collection: &mut Vec<String>) { if let Some(inner) = self.subsuggestions { for item in inner { collection.push(item.selected_text); } } else { collection.push(self.selected_text); } } } #[derive(Deserialize)] struct ApQueryResponseNodeMGWrapper { node: ApQueryResponseNodeMG, } #[derive(Deserialize)] struct ApQueryResponseAirports { edges: Vec<ApQueryResponseNodeMGWrapper>, } #[derive(Deserialize)] struct ApQueryResponseData { airports: ApQueryResponseAirports, } #[derive(Deserialize)] struct ApQueryResponse { data: ApQueryResponseData, } #[derive(Serialize)] struct ApQueryOut { data: Vec<String>, } impl ApQueryOut { fn new(data: Vec<String>) -> Self { ApQueryOut { data } } fn build_from(api_response: String) -> String { let deserialized = match serde_json::from_str::<ApQueryResponse>(&api_response) { Ok(deserialized) => deserialized, Err(e) => return format!("Error (2): {:?}", e), }; let data = deserialized.data.airports.edges; if data.len() == 0 { log("empty response"); String::new() } else { let mut collection = Vec::with_capacity( data.iter() .map(|mg| { mg.node .subsuggestions .as_ref() .map_or_else(|| 1, |inner| inner.len()) }) .sum(), ); data.into_iter() .for_each(|item| item.node.flatten(&mut collection)); let out = ApQueryOut::new(collection); match serde_json::to_string(&out) { Ok(serialized_out) => serialized_out, Err(e) => format!("Error (3): {:?}", e), } } } } #[wasm_bindgen] pub async fn query_current_search(search: String) -> String { console_error_panic_hook::set_once(); let response = match Client::new() .post("http://localhost:3000/api/graphql") .header("authorization", BEARER_AUTH) .header("content-type", "application/json") .body(serde_json::to_string(&ApQuery::new(&search)).unwrap()) .send() .await { Ok(response) => match response.text().await { Ok(response) => response, Err(e) => format!("Error: {}", e), }, Err(e) => format!("Error: {}", e), }; ApQueryOut::build_from(response) }
use crate::BEARER_AUTH; use reqwest::Client; use serde::{de::IgnoredAny, Deserialize, Serialize}; use wasm_bindgen::prelude::*; const AIRPORT_QUERY: &'static str = " query findAirports($query: String!) { airports(query: $query) { edges { node { ...Airport } } } } fragment Airport on AirportSuggestion { iataCode title selectedText subSuggestions { iataCode title selectedText } } "; #[wasm_bindgen] extern "C" { #[wasm_bindgen(js_namespace = console)] pub fn log(s: &str); } #[derive(Serialize)] struct ApQueryVariables<'a> { query: &'a str, } #[derive(Serialize)] struct ApQuery<'a> { query: &'static str, variables: ApQueryVariables<'a>, } impl<'a> ApQuery<'a> { fn new(search: &'a str) -> Self { ApQuery { query: AIRPORT_QUERY, variables: ApQueryVariables { query: search }, } } } #[derive(Deserialize)] struct ApQueryResponseNode { #[serde(rename(deserialize = "iataCode"))] _iata_code: IgnoredAny, #[serde(rename(deserialize = "title"))] _title: IgnoredAny, #[serde(rename(deserialize = "selectedText"))] selected_text: String, } #[derive(Deserialize)] struct ApQueryResponseNodeMG { #[serde(rename(deserialize = "iataCode"), skip_deserializing)] _iata_code: IgnoredAny, #[serde(rename(deserialize = "title"), skip_deserializing)] _title: IgnoredAny, #[serde(rename(deserialize = "selectedText"))] selected_text: String, #[serde(rename(serialize = "subSuggestions"), default)] subsuggestions: Option<Vec<ApQueryResponseNode>>, } impl ApQueryResponseNodeMG { fn flatten(self, collection: &mut Vec<String>) { if let Some(inner) = self.subsuggestions { for item in inner { collection.push(item.selected_text); } } else { collection.push(self.selected_text); } } } #[derive(Deserialize)] struct ApQueryResponseNodeMGWrapper { node: ApQueryResponseNodeMG, } #[derive(Deserialize)] struct ApQueryResponseAirports { edges: Vec<ApQueryResponseNodeMGWrapper>, } #[derive(Deserialize)] struct ApQueryResponseData { airports: ApQueryResponseAirports, } #[derive(Deserialize)] struct ApQueryResponse { data: ApQueryResponseData, } #[derive(Serialize)] struct ApQueryOut { data: Vec<String>, } impl ApQueryOut { fn new(data: Vec<String>) -> Self { ApQueryOut { data } } fn build_from(api_response: String) -> String { let deserialized = match serde_json::from_str::<ApQueryResponse>(&api_response) { Ok(deserialized) => deserialized, Err(e) => return format!("Error (2): {:?}", e), }; let data = deserialized.data.airports.edges; if data.len() == 0 { log("empty response"); String::new() } else { let mut collection = Vec::with_capacity( data.iter() .map(|mg| { mg.node .subsuggestions .as_ref() .map_or_else(|| 1, |inner| inner.len()) }) .sum(), ); data.into_iter() .for_each(|item| item.node.flatten(&mut collection)); let out = ApQueryOut::new(collection); match serde_json::to_string(&out) { Ok(serialized_out) => serialized_out, Err(e) => format!("Error (3): {:?}", e), } } } } #[wasm_bindgen]
pub async fn query_current_search(search: String) -> String { console_error_panic_hook::set_once(); let response = match Client::new() .post("http://localhost:3000/api/graphql") .header("authorization", BEARER_AUTH) .header("content-type", "application/json") .body(serde_json::to_string(&ApQuery::new(&search)).unwrap()) .send() .await { Ok(response) => match response.text().await { Ok(response) => response, Err(e) => format!("Error: {}", e), }, Err(e) => format!("Error: {}", e), }; ApQueryOut::build_from(response) }
function_block-full_function
[ { "content": "#[derive(Serialize)]\n\nstruct FlightQueryVariables<'a> {\n\n ap_from: &'a str,\n\n ap_to: &'a str,\n\n depart_date: &'a str,\n\n return_date: Option<&'a str>,\n\n round_trip: bool,\n\n}\n\n\n\nimpl<'a> FlightQueryVariables<'a> {\n\n fn new(\n\n ap_from: &'a str,\n\n ...
Rust
src/validation.rs
djc/rpki-validator
a133f7dad930290ad51d65dbecf862d7063099f0
use std::sync::Arc; use std::sync::RwLock; use ipnetwork::IpNetwork; use rpki::asres::AsId; use storage::{RecordStorage, Record}; pub struct RecordValidator { storage: Arc<RwLock<RecordStorage>>, } impl RecordValidator { pub fn new(storage: Arc<RwLock<RecordStorage>>) -> Self { RecordValidator { storage } } pub fn validate(&self, prefix: &IpNetwork, origin: u32) -> ValidationResult { let origin = AsId::from(origin); let records = self.storage.read().unwrap().find_records(prefix); let mut valid_records = Vec::new(); let mut invalid_length = Vec::new(); let mut invalid_origin = Vec::new(); let mut found_valid_origin = false; for record in records { let has_valid_length = record.max_length() >= prefix.prefix(); let has_valid_origin = record.origin() == origin; if has_valid_origin && has_valid_length { valid_records.push(record); } else { if !has_valid_origin { invalid_origin.push(record); } else if !has_valid_length { invalid_length.push(record); } } found_valid_origin = found_valid_origin || has_valid_origin; } let records = ValidationRecords::new( valid_records, invalid_origin, invalid_length, ); if !records.matched().is_empty() { ValidationResult::Valid(records) } else if !records.unmatched_origin().is_empty() || !records.unmatched_length().is_empty() { if records.unmatched_origin().is_empty() || found_valid_origin { ValidationResult::InvalidPrefixLength(records) } else { ValidationResult::InvalidOrigin(records) } } else { ValidationResult::NotFound } } } #[derive(Debug, Default, PartialEq)] pub struct ValidationRecords { matched : Vec<Record>, unmatched_origin : Vec<Record>, unmatched_length : Vec<Record>, } impl ValidationRecords { pub fn new(matched: Vec<Record>, unmatched_origin: Vec<Record>, unmatched_length: Vec<Record>) -> Self { ValidationRecords { matched, unmatched_origin, unmatched_length } } pub fn matched(&self) -> &Vec<Record> { &self.matched } pub fn unmatched_origin(&self) -> &Vec<Record> { &self.unmatched_origin } pub fn unmatched_length(&self) -> &Vec<Record> { &self.unmatched_length } } #[derive(Debug, PartialEq)] pub enum ValidationResult { Valid(ValidationRecords), InvalidOrigin(ValidationRecords), InvalidPrefixLength(ValidationRecords), NotFound, } impl ValidationResult { pub fn is_valid(&self) -> bool { match self { ValidationResult::Valid(_) => true, _ => false } } } #[cfg(test)] mod tests { use std::path::PathBuf; use storage::TrustAnchor; use super::*; fn create_records() -> Vec<Record> { vec![ Record::new(IpNetwork::V4("1.2.3.0/24".parse().unwrap()), AsId::from(1), 26), Record::new(IpNetwork::V4("1.2.2.0/23".parse().unwrap()), AsId::from(1), 24), Record::new(IpNetwork::V4("1.2.0.0/16".parse().unwrap()), AsId::from(3), 16), Record::new(IpNetwork::V4("1.2.3.0/24".parse().unwrap()), AsId::from(4), 24), Record::new(IpNetwork::V4("4.4.4.0/24".parse().unwrap()), AsId::from(1), 26), ] } fn create_verifier(records: Vec<Record>) -> RecordValidator { let mut storage = RecordStorage::new(); let trust_anchor = Arc::new(TrustAnchor::new("foo".to_string())); storage.add_records(records, PathBuf::new(), &trust_anchor); RecordValidator::new(Arc::new(RwLock::new(storage))) } #[test] fn verify_valid() { let records = create_records(); let verifier = create_verifier(records.clone()); assert_eq!( ValidationResult::Valid( ValidationRecords::new( vec![ records[0].clone(), records[1].clone() ], vec![ records[3].clone(), records[2].clone() ], vec![], ) ), verifier.validate(&IpNetwork::V4("1.2.3.0/24".parse().unwrap()), 1), ); assert_eq!( ValidationResult::Valid( ValidationRecords::new( vec![ records[0].clone() ], vec![ records[3].clone(), records[2].clone() ], vec![ records[1].clone() ], ) ), verifier.validate(&IpNetwork::V4("1.2.3.0/25".parse().unwrap()), 1), ); } #[test] fn verify_invalid_origin() { let records = create_records(); let verifier = create_verifier(records.clone()); assert_eq!( ValidationResult::InvalidOrigin( ValidationRecords::new( vec![ ], vec![ records[0].clone(), records[3].clone(), records[1].clone(), records[2].clone(), ], vec![ ], ) ), verifier.validate(&IpNetwork::V4("1.2.3.0/24".parse().unwrap()), 10), ); } #[test] fn verify_invalid_prefix_length() { let records = create_records(); let verifier = create_verifier(records.clone()); assert_eq!( ValidationResult::InvalidPrefixLength( ValidationRecords::new( vec![ ], vec![ ], vec![ records[4].clone() ], ) ), verifier.validate(&IpNetwork::V4("4.4.4.0/27".parse().unwrap()), 1), ); } #[test] fn verify_not_found() { let records = create_records(); let verifier = create_verifier(records.clone()); assert_eq!( ValidationResult::NotFound, verifier.validate(&IpNetwork::V4("3.3.3.0/24".parse().unwrap()), 1), ); assert_eq!( ValidationResult::NotFound, verifier.validate(&IpNetwork::V4("1.2.0.0/15".parse().unwrap()), 1), ); } }
use std::sync::Arc; use std::sync::RwLock; use ipnetwork::IpNetwork; use rpki::asres::AsId; use storage::{RecordStorage, Record}; pub struct RecordValidator { storage: Arc<RwLock<RecordStorage>>, } impl RecordValidator { pub fn new(storage: Arc<RwLock<RecordStorage>>) -> Self { RecordValidator { storage } } pub fn validate(&self, prefix: &IpNetwork, origin: u32) -> ValidationResult { let origin = AsId::from(origin); let records = self.storage.read().unwrap().find_records(prefix); let mut valid_records = Vec::new(); let mut invalid_length = Vec::new(); let mut invalid_origin = Vec::new(); let mut found_valid_origin = false; for record in records { let has_valid_length = record.max_length() >= prefix.prefix(); let has_valid_origin = record.origin() == origin; if has_valid_origin && has_valid_length { valid_records.push(record); } else { if !has_valid_origin { invalid_origin.push(record); } else if !has_valid_length { invalid_length.push(record); } } found_valid_origin = found_valid_origin || has_valid_origin; } let records = ValidationRecords::new( valid_records, invalid_origin, invalid_length, ); if !records.matched().is_empty() { ValidationResult::Valid(records) } else if !records.unmatched_origin().is_empty() || !records.unmatched_length().is_empty() { if records.unmatched_origin().is_empty() || found_valid_origin { ValidationResult::InvalidPrefixLength(records) } else { ValidationResult::InvalidOrigin(records) } } else { ValidationResult::NotFound } } } #[derive(Debug, Default, PartialEq)] pub struct ValidationRecords { matched : Vec<Record>, unmatched_origin : Vec<Record>, unmatched_length : Vec<Record>, } impl ValidationRecords {
pub fn matched(&self) -> &Vec<Record> { &self.matched } pub fn unmatched_origin(&self) -> &Vec<Record> { &self.unmatched_origin } pub fn unmatched_length(&self) -> &Vec<Record> { &self.unmatched_length } } #[derive(Debug, PartialEq)] pub enum ValidationResult { Valid(ValidationRecords), InvalidOrigin(ValidationRecords), InvalidPrefixLength(ValidationRecords), NotFound, } impl ValidationResult { pub fn is_valid(&self) -> bool { match self { ValidationResult::Valid(_) => true, _ => false } } } #[cfg(test)] mod tests { use std::path::PathBuf; use storage::TrustAnchor; use super::*; fn create_records() -> Vec<Record> { vec![ Record::new(IpNetwork::V4("1.2.3.0/24".parse().unwrap()), AsId::from(1), 26), Record::new(IpNetwork::V4("1.2.2.0/23".parse().unwrap()), AsId::from(1), 24), Record::new(IpNetwork::V4("1.2.0.0/16".parse().unwrap()), AsId::from(3), 16), Record::new(IpNetwork::V4("1.2.3.0/24".parse().unwrap()), AsId::from(4), 24), Record::new(IpNetwork::V4("4.4.4.0/24".parse().unwrap()), AsId::from(1), 26), ] } fn create_verifier(records: Vec<Record>) -> RecordValidator { let mut storage = RecordStorage::new(); let trust_anchor = Arc::new(TrustAnchor::new("foo".to_string())); storage.add_records(records, PathBuf::new(), &trust_anchor); RecordValidator::new(Arc::new(RwLock::new(storage))) } #[test] fn verify_valid() { let records = create_records(); let verifier = create_verifier(records.clone()); assert_eq!( ValidationResult::Valid( ValidationRecords::new( vec![ records[0].clone(), records[1].clone() ], vec![ records[3].clone(), records[2].clone() ], vec![], ) ), verifier.validate(&IpNetwork::V4("1.2.3.0/24".parse().unwrap()), 1), ); assert_eq!( ValidationResult::Valid( ValidationRecords::new( vec![ records[0].clone() ], vec![ records[3].clone(), records[2].clone() ], vec![ records[1].clone() ], ) ), verifier.validate(&IpNetwork::V4("1.2.3.0/25".parse().unwrap()), 1), ); } #[test] fn verify_invalid_origin() { let records = create_records(); let verifier = create_verifier(records.clone()); assert_eq!( ValidationResult::InvalidOrigin( ValidationRecords::new( vec![ ], vec![ records[0].clone(), records[3].clone(), records[1].clone(), records[2].clone(), ], vec![ ], ) ), verifier.validate(&IpNetwork::V4("1.2.3.0/24".parse().unwrap()), 10), ); } #[test] fn verify_invalid_prefix_length() { let records = create_records(); let verifier = create_verifier(records.clone()); assert_eq!( ValidationResult::InvalidPrefixLength( ValidationRecords::new( vec![ ], vec![ ], vec![ records[4].clone() ], ) ), verifier.validate(&IpNetwork::V4("4.4.4.0/27".parse().unwrap()), 1), ); } #[test] fn verify_not_found() { let records = create_records(); let verifier = create_verifier(records.clone()); assert_eq!( ValidationResult::NotFound, verifier.validate(&IpNetwork::V4("3.3.3.0/24".parse().unwrap()), 1), ); assert_eq!( ValidationResult::NotFound, verifier.validate(&IpNetwork::V4("1.2.0.0/15".parse().unwrap()), 1), ); } }
pub fn new(matched: Vec<Record>, unmatched_origin: Vec<Record>, unmatched_length: Vec<Record>) -> Self { ValidationRecords { matched, unmatched_origin, unmatched_length } }
function_block-full_function
[ { "content": "#[derive(Eq, Ord, PartialEq, PartialOrd)]\n\nstruct RecordMetadata {\n\n origin: AsId,\n\n max_length: u8,\n\n path: Arc<PathBuf>,\n\n trust_anchor: Arc<TrustAnchor>,\n\n}\n\n\n\nimpl RecordMetadata {\n\n fn new(origin: AsId,\n\n max_length: u8,\n\n path: Arc<Pat...
Rust
day-12/src/matt.rs
rust-nairobi/aoc-2020
1d39ff72936833c216c89a91f3ba3a4c9c2aac3e
use std::fs::File; use std::io::{self, BufRead}; struct Position { x: isize, y: isize, } struct Ship { dir: f64, pos: Position, waypoint: Position, } impl Ship { fn new() -> Ship { Ship { dir: 0f64, pos: Position { x: 0, y: 0 }, waypoint: Position { x: 10, y: 1 }, } } fn navigate(&mut self, actions: &[Action]) { for action in actions { match action { Action::Right(v) => self.dir = ((self.dir - *v as f64) as isize % 360) as f64, Action::Left(v) => self.dir = ((self.dir + *v as f64) as isize % 360) as f64, Action::Forward(v) => { self.pos.x += self.dir.to_radians().cos() as isize * *v; self.pos.y += self.dir.to_radians().sin() as isize * *v; } Action::North(v) => self.pos.y += *v, Action::South(v) => self.pos.y -= *v, Action::East(v) => self.pos.x += *v, Action::West(v) => self.pos.x -= *v, } } } fn turn(&mut self, v: isize) { let r = ((self.waypoint.x.pow(2) + self.waypoint.y.pow(2)) as f64).sqrt(); let t = (self.waypoint.y as f64).atan2(self.waypoint.x as f64); let t = t - (v as f64).to_radians(); self.waypoint.x = (r * t.cos()).round() as isize; self.waypoint.y = (r * t.sin()).round() as isize; } fn navigate2(&mut self, actions: &[Action]) { for action in actions { match action { Action::Right(v) => self.turn(*v), Action::Left(v) => self.turn(*v - 2 * v), Action::Forward(v) => { self.pos.x += self.waypoint.x * *v; self.pos.y += self.waypoint.y * *v; } Action::North(v) => self.waypoint.y += *v, Action::South(v) => self.waypoint.y -= *v, Action::East(v) => self.waypoint.x += *v, Action::West(v) => self.waypoint.x -= *v, } } } fn mdist(&self) -> isize { self.pos.x.abs() + self.pos.y.abs() } } enum Action { East(isize), North(isize), South(isize), West(isize), Forward(isize), Left(isize), Right(isize), } fn part_one(actions: &[Action]) -> isize { let mut ship = Ship::new(); ship.navigate(actions); ship.mdist() } fn part_two(actions: &[Action]) -> isize { let mut ship = Ship::new(); ship.navigate2(actions); ship.mdist() } fn main() { let actions = load_input("input.txt").unwrap(); println!("Part One: {} ", part_one(&actions)); println!("Part Two: {} ", part_two(&actions)); } fn load_input(fname: &str) -> io::Result<Vec<Action>> { let file = File::open(fname)?; let buf = io::BufReader::new(file); Ok(buf .lines() .filter_map(|x| x.ok()) .map(|x| { let val = x[1..].parse::<isize>().unwrap(); match &x[0..1] { "E" => Action::East(val), "F" => Action::Forward(val), "L" => Action::Left(val), "N" => Action::North(val), "R" => Action::Right(val), "S" => Action::South(val), "W" => Action::West(val), _ => unreachable!(), } }) .collect()) } #[test] fn test() { let actions = load_input("test.txt").unwrap(); let mut ship = Ship::new(); ship.navigate(&actions); assert_eq!(25, ship.mdist()); }
use std::fs::File; use std::io::{self, BufRead}; struct Position { x: isize, y: isize, } struct Ship { dir: f64, pos: Position, waypoint: Position, } impl Ship { fn new() -> Ship { Ship { dir: 0f64, pos: Position { x: 0, y: 0 }, waypoint: Position { x: 10, y: 1 }, } } fn navigate(&mut self, actions: &[Action]) { for action in actions { match action { Action::Right(v) => self.dir = ((self.dir - *v as f64) as isize % 360) as f64, Action::Left(v) => self.dir = ((self.dir + *v as f64) as isize % 360) as f64, Action::Forward(v) => { self.pos.x += self.dir.to_radians().cos() as isize * *v; self.pos.y += self.dir.to_radians().sin() as isize * *v; } Action::North(v) => self.pos.y += *v, Action::South(v) => self.pos.y -= *v, Action::East(v) => self.pos.x += *v, Action::West(v) => self.pos.x -= *v, } } } fn turn(&mut self, v: isize) { let r = ((self.waypoint.x.pow(2) + self.waypoint.y.pow(2)) as f64).sqrt(); let t = (self.waypoint.y as f64).atan2(self.waypoint.x as f64); let t = t - (v as f64).to_radians(); self.waypoint.x = (r * t.cos()).round() as isize; self.waypoint.y = (r * t.sin()).round() as isize; } fn navigate2(&mut self, actions: &[Action]) { for action in actions { match action { Action::Right(v) => self.turn(*v), Action::Left(v) => self.turn(*v - 2 * v), Action::Forward(v) => { self.pos.x += self.waypoint.x * *v; self.pos.y += self.waypoint.y * *v; } Action::North(v) => self.waypoint.y += *v, Action::South(v) => self.waypoint.y -= *v, Action::East(v) => self.waypoint.x += *v, Action::West(v) => self.waypoint.x -= *v, } } } fn mdist(&self) -> isize { self.pos.x.abs() + self.pos.y.abs() } } enum Action { East(isize), North(isize), South(isize), West(isize), Forward(isize), Left(isize), Right(isize), } fn part_one(actions: &[Action]) -> isize { let mut ship = Ship::new(); ship.navigate(actions); ship.mdist() } fn part_two(actions: &[Action]) -> isize { let mut ship = Ship::new(); ship.navigate2(actions); ship.mdist() } fn main() { let actions = load_input("input.txt").unwrap(); println!("Part One: {} ", part_one(&actions)); println!("Part Two: {} ", part_two(&actions)); } fn load_input(fname: &str) -> io::Result<Vec<Action>> { let file = File::open(fname)?; let buf = io::BufReader::new(file); Ok(buf .line
#[test] fn test() { let actions = load_input("test.txt").unwrap(); let mut ship = Ship::new(); ship.navigate(&actions); assert_eq!(25, ship.mdist()); }
s() .filter_map(|x| x.ok()) .map(|x| { let val = x[1..].parse::<isize>().unwrap(); match &x[0..1] { "E" => Action::East(val), "F" => Action::Forward(val), "L" => Action::Left(val), "N" => Action::North(val), "R" => Action::Right(val), "S" => Action::South(val), "W" => Action::West(val), _ => unreachable!(), } }) .collect()) }
function_block-function_prefixed
[ { "content": "fn parse_input_line(line: &str) -> GridLine {\n\n let mut grid_line = vec![];\n\n for chr in line.chars() {\n\n match chr {\n\n '#' => grid_line.push(GridPoint::Tree),\n\n '.' => grid_line.push(GridPoint::OpenSquare),\n\n _ => unreachable!(),\n\n ...
Rust
libs/prisma-models/src/record.rs
VanCoding/prisma-engines
bec4da3195df1ce40b2559939510abce2159b635
use crate::{DomainError, ModelProjection, OrderBy, PrismaValue, RecordProjection, ScalarFieldRef, SortOrder}; use itertools::Itertools; use std::collections::HashMap; #[derive(Debug, Clone)] pub struct SingleRecord { pub record: Record, pub field_names: Vec<String>, } impl Into<ManyRecords> for SingleRecord { fn into(self) -> ManyRecords { ManyRecords { records: vec![self.record], field_names: self.field_names, } } } impl SingleRecord { pub fn new(record: Record, field_names: Vec<String>) -> Self { Self { record, field_names } } pub fn projection(&self, projection: &ModelProjection) -> crate::Result<RecordProjection> { self.record.projection(&self.field_names, projection) } pub fn get_field_value(&self, field: &str) -> crate::Result<&PrismaValue> { self.record.get_field_value(&self.field_names, field) } } #[derive(Debug, Clone, Default)] pub struct ManyRecords { pub records: Vec<Record>, pub field_names: Vec<String>, } impl ManyRecords { pub fn new(field_names: Vec<String>) -> Self { Self { records: Vec::new(), field_names, } } pub fn empty(selected_fields: &ModelProjection) -> Self { Self { records: Vec::new(), field_names: selected_fields.names().map(|n| n.to_string()).collect(), } } pub fn from_projection(projection: Vec<Vec<PrismaValue>>, selected_fields: &ModelProjection) -> Self { Self { records: projection .into_iter() .map(|v| Record { values: v, parent_id: None, }) .collect(), field_names: selected_fields.db_names().collect(), } } pub fn order_by(&mut self, order_bys: &[OrderBy]) { let field_indices: HashMap<&str, usize> = self .field_names .iter() .enumerate() .map(|(i, name)| (name.as_str(), i)) .collect(); self.records.sort_by(|a, b| { let mut orderings = order_bys.iter().map(|o| { let index = field_indices[o.field.db_name()]; match o.sort_order { SortOrder::Ascending => a.values[index].cmp(&b.values[index]), SortOrder::Descending => b.values[index].cmp(&a.values[index]), } }); orderings .next() .map(|first| orderings.fold(first, |acc, ord| acc.then(ord))) .unwrap() }) } pub fn push(&mut self, record: Record) { self.records.push(record); } pub fn projections(&self, model_projection: &ModelProjection) -> crate::Result<Vec<RecordProjection>> { self.records .iter() .map(|record| record.projection(&self.field_names, model_projection)) .collect() } pub fn as_pairs(&self) -> Vec<Vec<(String, PrismaValue)>> { self.records .iter() .map(|record| { record .values .iter() .zip(self.field_names.iter()) .map(|(value, name)| (name.clone(), value.clone())) .collect() }) .collect() } pub fn reverse(&mut self) { self.records.reverse(); } pub fn with_unique_records(mut self) -> Self { self.records = self.records.into_iter().unique().collect(); self } } #[derive(Debug, Default, Clone, Eq, PartialEq, Hash)] pub struct Record { pub values: Vec<PrismaValue>, pub parent_id: Option<RecordProjection>, } impl Record { pub fn new(values: Vec<PrismaValue>) -> Record { Record { values, ..Default::default() } } pub fn projection( &self, field_names: &[String], model_projection: &ModelProjection, ) -> crate::Result<RecordProjection> { let pairs: Vec<(ScalarFieldRef, PrismaValue)> = model_projection .fields() .into_iter() .flat_map(|field| { field.scalar_fields().into_iter().map(|field| { self.get_field_value(field_names, field.db_name()) .map(|val| (field, val.clone())) }) }) .collect::<crate::Result<Vec<_>>>()?; Ok(RecordProjection { pairs }) } pub fn identifying_values( &self, field_names: &[String], model_projection: &ModelProjection, ) -> crate::Result<Vec<&PrismaValue>> { let x: Vec<&PrismaValue> = model_projection .fields() .into_iter() .flat_map(|field| { field .scalar_fields() .into_iter() .map(|source_field| self.get_field_value(field_names, &source_field.name)) }) .collect::<crate::Result<Vec<_>>>()?; Ok(x) } pub fn get_field_value(&self, field_names: &[String], field: &str) -> crate::Result<&PrismaValue> { let index = field_names.iter().position(|r| r == field).map(Ok).unwrap_or_else(|| { Err(DomainError::FieldNotFound { name: field.to_string(), model: format!( "Field not found in record {:?}. Field names are: {:?}, looking for: {:?}", &self, &field_names, field ), }) })?; Ok(&self.values[index]) } pub fn set_parent_id(&mut self, parent_id: RecordProjection) { self.parent_id = Some(parent_id); } }
use crate::{DomainError, ModelProjection, OrderBy, PrismaValue, RecordProjection, ScalarFieldRef, SortOrder}; use itertools::Itertools; use std::collections::HashMap; #[derive(Debug, Clone)] pub struct SingleRecord { pub record: Record, pub field_names: Vec<String>, } impl Into<ManyRecords> for SingleRecord { fn into(self) -> ManyRecords { ManyRecords { records: vec![self.record], field_names: self.field_names, } } } impl SingleRecord { pub fn new(record: Record, field_names: Vec<String>) -> Self { Self { record, field_names } } pub fn projection(&self, projection: &ModelProjection) -> crate::Result<RecordProjection> { self.record.projection(&self.field_names, projection) } pub fn get_field_value(&self, field: &str) -> crate::Result<&PrismaValue> { self.record.get_field_value(&self.field_names, field) } } #[derive(Debug, Clone, Default)] pub struct ManyRecords { pub records: Vec<Record>, pub field_names: Vec<String>, } impl ManyRecords { pub fn new(field_names: Vec<String>) -> Self { Self { records: Vec::new(), field_names, } } pub fn empty(selected_fields: &ModelProjection) -> Self { Self { records: Vec::new(), field_names: selected_fields.names().map(|n| n.to_string()).collect(), } } pub fn from_projection(projection: Vec<Vec<PrismaValue>>, selected_fields: &ModelProjection) -> Self { Self { records: projection .into_iter() .map(|v| Record { values: v, parent_id: None, }) .collect(), field_names: selected_fields.db_names().collect(), } } pub fn order_by(&mut self, order_bys: &[OrderBy]) { let field_indices: HashMap<&str, usize> = self .field_names .iter() .enumerate() .map(|(i, name)| (name.as_str(), i)) .collect(); self.records.sort_by(|a, b| { let mut orderings = order_bys.iter().map(|o| { let index = field_indices[o.field.db_name()];
}); orderings .next() .map(|first| orderings.fold(first, |acc, ord| acc.then(ord))) .unwrap() }) } pub fn push(&mut self, record: Record) { self.records.push(record); } pub fn projections(&self, model_projection: &ModelProjection) -> crate::Result<Vec<RecordProjection>> { self.records .iter() .map(|record| record.projection(&self.field_names, model_projection)) .collect() } pub fn as_pairs(&self) -> Vec<Vec<(String, PrismaValue)>> { self.records .iter() .map(|record| { record .values .iter() .zip(self.field_names.iter()) .map(|(value, name)| (name.clone(), value.clone())) .collect() }) .collect() } pub fn reverse(&mut self) { self.records.reverse(); } pub fn with_unique_records(mut self) -> Self { self.records = self.records.into_iter().unique().collect(); self } } #[derive(Debug, Default, Clone, Eq, PartialEq, Hash)] pub struct Record { pub values: Vec<PrismaValue>, pub parent_id: Option<RecordProjection>, } impl Record { pub fn new(values: Vec<PrismaValue>) -> Record { Record { values, ..Default::default() } } pub fn projection( &self, field_names: &[String], model_projection: &ModelProjection, ) -> crate::Result<RecordProjection> { let pairs: Vec<(ScalarFieldRef, PrismaValue)> = model_projection .fields() .into_iter() .flat_map(|field| { field.scalar_fields().into_iter().map(|field| { self.get_field_value(field_names, field.db_name()) .map(|val| (field, val.clone())) }) }) .collect::<crate::Result<Vec<_>>>()?; Ok(RecordProjection { pairs }) } pub fn identifying_values( &self, field_names: &[String], model_projection: &ModelProjection, ) -> crate::Result<Vec<&PrismaValue>> { let x: Vec<&PrismaValue> = model_projection .fields() .into_iter() .flat_map(|field| { field .scalar_fields() .into_iter() .map(|source_field| self.get_field_value(field_names, &source_field.name)) }) .collect::<crate::Result<Vec<_>>>()?; Ok(x) } pub fn get_field_value(&self, field_names: &[String], field: &str) -> crate::Result<&PrismaValue> { let index = field_names.iter().position(|r| r == field).map(Ok).unwrap_or_else(|| { Err(DomainError::FieldNotFound { name: field.to_string(), model: format!( "Field not found in record {:?}. Field names are: {:?}, looking for: {:?}", &self, &field_names, field ), }) })?; Ok(&self.values[index]) } pub fn set_parent_id(&mut self, parent_id: RecordProjection) { self.parent_id = Some(parent_id); } }
match o.sort_order { SortOrder::Ascending => a.values[index].cmp(&b.values[index]), SortOrder::Descending => b.values[index].cmp(&a.values[index]), }
if_condition
[ { "content": "pub fn replace_field_names(target: &mut Vec<String>, old_name: &str, new_name: &str) {\n\n target\n\n .iter_mut()\n\n .map(|v| {\n\n if v == old_name {\n\n *v = new_name.to_string()\n\n }\n\n })\n\n .for_each(drop);\n\n}\n", "...
Rust
bench-streamer/src/main.rs
YandriHN/solana
456e6711f0c24b13ae5e923ff8cd2af3caab496d
#![allow(clippy::integer_arithmetic)] use { clap::{crate_description, crate_name, Arg, Command}, crossbeam_channel::unbounded, solana_streamer::{ packet::{Packet, PacketBatch, PacketBatchRecycler, PACKET_DATA_SIZE}, streamer::{receiver, PacketBatchReceiver, StreamerReceiveStats}, }, std::{ cmp::max, net::{IpAddr, Ipv4Addr, SocketAddr, UdpSocket}, sync::{ atomic::{AtomicBool, AtomicUsize, Ordering}, Arc, }, thread::{sleep, spawn, JoinHandle, Result}, time::{Duration, SystemTime}, }, }; fn producer(addr: &SocketAddr, exit: Arc<AtomicBool>) -> JoinHandle<()> { let send = UdpSocket::bind("0.0.0.0:0").unwrap(); let mut packet_batch = PacketBatch::default(); packet_batch.packets.resize(10, Packet::default()); for w in packet_batch.packets.iter_mut() { w.meta.size = PACKET_DATA_SIZE; w.meta.set_addr(addr); } let packet_batch = Arc::new(packet_batch); spawn(move || loop { if exit.load(Ordering::Relaxed) { return; } let mut num = 0; for p in &packet_batch.packets { let a = p.meta.addr(); assert!(p.meta.size <= PACKET_DATA_SIZE); send.send_to(&p.data[..p.meta.size], &a).unwrap(); num += 1; } assert_eq!(num, 10); }) } fn sink(exit: Arc<AtomicBool>, rvs: Arc<AtomicUsize>, r: PacketBatchReceiver) -> JoinHandle<()> { spawn(move || loop { if exit.load(Ordering::Relaxed) { return; } let timer = Duration::new(1, 0); if let Ok(packet_batch) = r.recv_timeout(timer) { rvs.fetch_add(packet_batch.packets.len(), Ordering::Relaxed); } }) } fn main() -> Result<()> { let mut num_sockets = 1usize; let matches = Command::new(crate_name!()) .about(crate_description!()) .version(solana_version::version!()) .arg( Arg::new("num-recv-sockets") .long("num-recv-sockets") .value_name("NUM") .takes_value(true) .help("Use NUM receive sockets"), ) .arg( Arg::new("num-producers") .long("num-producers") .value_name("NUM") .takes_value(true) .help("Use this many producer threads."), ) .get_matches(); if let Some(n) = matches.value_of("num-recv-sockets") { num_sockets = max(num_sockets, n.to_string().parse().expect("integer")); } let num_producers: u64 = matches.value_of_t("num_producers").unwrap_or(4); let port = 0; let ip_addr = IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)); let mut addr = SocketAddr::new(ip_addr, 0); let exit = Arc::new(AtomicBool::new(false)); let mut read_channels = Vec::new(); let mut read_threads = Vec::new(); let recycler = PacketBatchRecycler::default(); let (_port, read_sockets) = solana_net_utils::multi_bind_in_range( ip_addr, (port, port + num_sockets as u16), num_sockets, ) .unwrap(); let stats = Arc::new(StreamerReceiveStats::new("bench-streamer-test")); for read in read_sockets { read.set_read_timeout(Some(Duration::new(1, 0))).unwrap(); addr = read.local_addr().unwrap(); let (s_reader, r_reader) = unbounded(); read_channels.push(r_reader); read_threads.push(receiver( Arc::new(read), exit.clone(), s_reader, recycler.clone(), stats.clone(), 1, true, None, )); } let producer_threads: Vec<_> = (0..num_producers) .into_iter() .map(|_| producer(&addr, exit.clone())) .collect(); let rvs = Arc::new(AtomicUsize::new(0)); let sink_threads: Vec<_> = read_channels .into_iter() .map(|r_reader| sink(exit.clone(), rvs.clone(), r_reader)) .collect(); let start = SystemTime::now(); let start_val = rvs.load(Ordering::Relaxed); sleep(Duration::new(5, 0)); let elapsed = start.elapsed().unwrap(); let end_val = rvs.load(Ordering::Relaxed); let time = elapsed.as_secs() * 10_000_000_000 + u64::from(elapsed.subsec_nanos()); let ftime = (time as f64) / 10_000_000_000_f64; let fcount = (end_val - start_val) as f64; println!("performance: {:?}", fcount / ftime); exit.store(true, Ordering::Relaxed); for t_reader in read_threads { t_reader.join()?; } for t_producer in producer_threads { t_producer.join()?; } for t_sink in sink_threads { t_sink.join()?; } Ok(()) }
#![allow(clippy::integer_arithmetic)] use { clap::{crate_description, crate_name, Arg, Command}, crossbeam_channel::unbounded, solana_streamer::{ packet::{Packet, PacketBatch, PacketBatchRecycler, PACKET_DATA_SIZE}, streamer::{receiver, PacketBatchReceiver, StreamerReceiveStats}, }, std::{ cmp::max, net::{IpAddr, Ipv4Addr, SocketAddr, UdpSocket}, sync::{ atomic::{AtomicBool, AtomicUsize, Ordering}, Arc, }, thread::{sleep, spawn, JoinHandle, Result}, time::{Duration, SystemTime}, }, }; fn producer(addr: &SocketAddr, exit: Arc<AtomicBool>) -> JoinHandle<()> { let send = UdpSocket::bind("0.0.0.0:0").unwrap(); let mut packet_batch = PacketBatch::default(); packet_batch.packets.resize(10, Packet::default()); for w in packet_batch.packets.iter_mut() { w.meta.size = PACKET_DATA_SIZE; w.meta.set_addr(addr); } let packet_batch = Arc::new(packet_batch); spawn(move || loop { if exit.load(Ordering::Relaxed) { return; } let mut num = 0; for p in &packet_batch.packets { let a = p.meta.addr(); assert!(p.meta.size <= PACKET_DATA_SIZE); send.send_to(&p.data[..p.meta.size], &a).unwrap(); num += 1; } assert_eq!(num, 10); }) }
fn main() -> Result<()> { let mut num_sockets = 1usize; let matches = Command::new(crate_name!()) .about(crate_description!()) .version(solana_version::version!()) .arg( Arg::new("num-recv-sockets") .long("num-recv-sockets") .value_name("NUM") .takes_value(true) .help("Use NUM receive sockets"), ) .arg( Arg::new("num-producers") .long("num-producers") .value_name("NUM") .takes_value(true) .help("Use this many producer threads."), ) .get_matches(); if let Some(n) = matches.value_of("num-recv-sockets") { num_sockets = max(num_sockets, n.to_string().parse().expect("integer")); } let num_producers: u64 = matches.value_of_t("num_producers").unwrap_or(4); let port = 0; let ip_addr = IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)); let mut addr = SocketAddr::new(ip_addr, 0); let exit = Arc::new(AtomicBool::new(false)); let mut read_channels = Vec::new(); let mut read_threads = Vec::new(); let recycler = PacketBatchRecycler::default(); let (_port, read_sockets) = solana_net_utils::multi_bind_in_range( ip_addr, (port, port + num_sockets as u16), num_sockets, ) .unwrap(); let stats = Arc::new(StreamerReceiveStats::new("bench-streamer-test")); for read in read_sockets { read.set_read_timeout(Some(Duration::new(1, 0))).unwrap(); addr = read.local_addr().unwrap(); let (s_reader, r_reader) = unbounded(); read_channels.push(r_reader); read_threads.push(receiver( Arc::new(read), exit.clone(), s_reader, recycler.clone(), stats.clone(), 1, true, None, )); } let producer_threads: Vec<_> = (0..num_producers) .into_iter() .map(|_| producer(&addr, exit.clone())) .collect(); let rvs = Arc::new(AtomicUsize::new(0)); let sink_threads: Vec<_> = read_channels .into_iter() .map(|r_reader| sink(exit.clone(), rvs.clone(), r_reader)) .collect(); let start = SystemTime::now(); let start_val = rvs.load(Ordering::Relaxed); sleep(Duration::new(5, 0)); let elapsed = start.elapsed().unwrap(); let end_val = rvs.load(Ordering::Relaxed); let time = elapsed.as_secs() * 10_000_000_000 + u64::from(elapsed.subsec_nanos()); let ftime = (time as f64) / 10_000_000_000_f64; let fcount = (end_val - start_val) as f64; println!("performance: {:?}", fcount / ftime); exit.store(true, Ordering::Relaxed); for t_reader in read_threads { t_reader.join()?; } for t_producer in producer_threads { t_producer.join()?; } for t_sink in sink_threads { t_sink.join()?; } Ok(()) }
fn sink(exit: Arc<AtomicBool>, rvs: Arc<AtomicUsize>, r: PacketBatchReceiver) -> JoinHandle<()> { spawn(move || loop { if exit.load(Ordering::Relaxed) { return; } let timer = Duration::new(1, 0); if let Ok(packet_batch) = r.recv_timeout(timer) { rvs.fetch_add(packet_batch.packets.len(), Ordering::Relaxed); } }) }
function_block-full_function
[ { "content": "#[cfg(not(windows))]\n\nfn symlink_dir<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> std::io::Result<()> {\n\n std::os::unix::fs::symlink(src, dst)\n\n}\n\n\n", "file_path": "install/src/command.rs", "rank": 0, "score": 301982.69425580115 }, { "content": "#[cfg(target_o...
Rust
src/rate_limiter/src/persist.rs
parampavar/firecracker
a97b3f6c5c048c84a49ee501c48833deb8189c18
use super::*; use snapshot::Persist; use versionize::{VersionMap, Versionize, VersionizeResult}; use versionize_derive::Versionize; #[derive(Versionize)] pub struct TokenBucketState { size: u64, one_time_burst: Option<u64>, refill_time: u64, budget: u64, elapsed_ns: u64, } impl Persist<'_> for TokenBucket { type State = TokenBucketState; type ConstructorArgs = (); type Error = (); fn save(&self) -> Self::State { TokenBucketState { size: self.size, one_time_burst: self.one_time_burst, refill_time: self.refill_time, budget: self.budget, elapsed_ns: self.last_update.elapsed().as_nanos() as u64, } } fn restore(_: Self::ConstructorArgs, state: &Self::State) -> Result<Self, Self::Error> { let now = Instant::now(); let last_update = now .checked_sub(Duration::from_nanos(state.elapsed_ns)) .unwrap_or(now); let mut token_bucket = TokenBucket::new(state.size, state.one_time_burst, state.refill_time); token_bucket.budget = state.budget; token_bucket.last_update = last_update; Ok(token_bucket) } } #[derive(Versionize)] pub struct RateLimiterState { ops: Option<TokenBucketState>, bandwidth: Option<TokenBucketState>, } impl Persist<'_> for RateLimiter { type State = RateLimiterState; type ConstructorArgs = (); type Error = io::Error; fn save(&self) -> Self::State { RateLimiterState { ops: self.ops.as_ref().map(|ops| ops.save()), bandwidth: self.bandwidth.as_ref().map(|bw| bw.save()), } } fn restore(_: Self::ConstructorArgs, state: &Self::State) -> Result<Self, Self::Error> { let rate_limiter = RateLimiter { ops: state .ops .as_ref() .map(|ops| TokenBucket::restore((), ops).unwrap()), bandwidth: state .bandwidth .as_ref() .map(|bw| TokenBucket::restore((), bw).unwrap()), timer_fd: TimerFd::new_custom(ClockId::Monotonic, true, true)?, timer_active: false, }; Ok(rate_limiter) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_token_bucket_persistence() { let mut tb = TokenBucket::new(1000, Some(2000), 3000); let restored_tb = TokenBucket::restore((), &tb.save()).unwrap(); assert!(tb.partial_eq(&restored_tb)); tb.reduce(100); let restored_tb = TokenBucket::restore((), &tb.save()).unwrap(); assert!(tb.partial_eq(&restored_tb)); tb.replenish(100); let restored_tb = TokenBucket::restore((), &tb.save()).unwrap(); assert!(tb.partial_eq(&restored_tb)); let mut mem = vec![0; 4096]; let version_map = VersionMap::new(); tb.save() .serialize(&mut mem.as_mut_slice(), &version_map, 1) .unwrap(); let restored_tb = TokenBucket::restore( (), &TokenBucketState::deserialize(&mut mem.as_slice(), &version_map, 1).unwrap(), ) .unwrap(); assert!(tb.partial_eq(&restored_tb)); } #[test] fn test_rate_limiter_persistence() { let refill_time = 100_000; let mut rate_limiter = RateLimiter::new(100, None, refill_time, 10, None, refill_time).unwrap(); let restored_rate_limiter = RateLimiter::restore((), &rate_limiter.save()).expect("Unable to restore rate limiter"); assert!(rate_limiter .ops() .unwrap() .partial_eq(&restored_rate_limiter.ops().unwrap())); assert!(rate_limiter .bandwidth() .unwrap() .partial_eq(&restored_rate_limiter.bandwidth().unwrap())); assert_eq!( restored_rate_limiter.timer_fd.get_state(), TimerState::Disarmed ); rate_limiter.consume(10, TokenType::Bytes); rate_limiter.consume(10, TokenType::Ops); let restored_rate_limiter = RateLimiter::restore((), &rate_limiter.save()).expect("Unable to restore rate limiter"); assert!(rate_limiter .ops() .unwrap() .partial_eq(&restored_rate_limiter.ops().unwrap())); assert!(rate_limiter .bandwidth() .unwrap() .partial_eq(&restored_rate_limiter.bandwidth().unwrap())); assert_eq!( restored_rate_limiter.timer_fd.get_state(), TimerState::Disarmed ); rate_limiter.consume(1000, TokenType::Bytes); let restored_rate_limiter = RateLimiter::restore((), &rate_limiter.save()).expect("Unable to restore rate limiter"); assert!(rate_limiter .ops() .unwrap() .partial_eq(&restored_rate_limiter.ops().unwrap())); assert!(rate_limiter .bandwidth() .unwrap() .partial_eq(&restored_rate_limiter.bandwidth().unwrap())); let mut mem = vec![0; 4096]; let version_map = VersionMap::new(); rate_limiter .save() .serialize(&mut mem.as_mut_slice(), &version_map, 1) .unwrap(); let restored_rate_limiter = RateLimiter::restore( (), &RateLimiterState::deserialize(&mut mem.as_slice(), &version_map, 1).unwrap(), ) .unwrap(); assert!(rate_limiter .ops() .unwrap() .partial_eq(&restored_rate_limiter.ops().unwrap())); assert!(rate_limiter .bandwidth() .unwrap() .partial_eq(&restored_rate_limiter.bandwidth().unwrap())); } }
use super::*; use snapshot::Persist; use versionize::{VersionMap, Versionize, VersionizeResult}; use versionize_derive::Versionize; #[derive(Versionize)] pub struct TokenBucketState { size: u64, one_time_burst: Option<u64>,
.partial_eq(&restored_rate_limiter.ops().unwrap())); assert!(rate_limiter .bandwidth() .unwrap() .partial_eq(&restored_rate_limiter.bandwidth().unwrap())); assert_eq!( restored_rate_limiter.timer_fd.get_state(), TimerState::Disarmed ); rate_limiter.consume(10, TokenType::Bytes); rate_limiter.consume(10, TokenType::Ops); let restored_rate_limiter = RateLimiter::restore((), &rate_limiter.save()).expect("Unable to restore rate limiter"); assert!(rate_limiter .ops() .unwrap() .partial_eq(&restored_rate_limiter.ops().unwrap())); assert!(rate_limiter .bandwidth() .unwrap() .partial_eq(&restored_rate_limiter.bandwidth().unwrap())); assert_eq!( restored_rate_limiter.timer_fd.get_state(), TimerState::Disarmed ); rate_limiter.consume(1000, TokenType::Bytes); let restored_rate_limiter = RateLimiter::restore((), &rate_limiter.save()).expect("Unable to restore rate limiter"); assert!(rate_limiter .ops() .unwrap() .partial_eq(&restored_rate_limiter.ops().unwrap())); assert!(rate_limiter .bandwidth() .unwrap() .partial_eq(&restored_rate_limiter.bandwidth().unwrap())); let mut mem = vec![0; 4096]; let version_map = VersionMap::new(); rate_limiter .save() .serialize(&mut mem.as_mut_slice(), &version_map, 1) .unwrap(); let restored_rate_limiter = RateLimiter::restore( (), &RateLimiterState::deserialize(&mut mem.as_slice(), &version_map, 1).unwrap(), ) .unwrap(); assert!(rate_limiter .ops() .unwrap() .partial_eq(&restored_rate_limiter.ops().unwrap())); assert!(rate_limiter .bandwidth() .unwrap() .partial_eq(&restored_rate_limiter.bandwidth().unwrap())); } }
refill_time: u64, budget: u64, elapsed_ns: u64, } impl Persist<'_> for TokenBucket { type State = TokenBucketState; type ConstructorArgs = (); type Error = (); fn save(&self) -> Self::State { TokenBucketState { size: self.size, one_time_burst: self.one_time_burst, refill_time: self.refill_time, budget: self.budget, elapsed_ns: self.last_update.elapsed().as_nanos() as u64, } } fn restore(_: Self::ConstructorArgs, state: &Self::State) -> Result<Self, Self::Error> { let now = Instant::now(); let last_update = now .checked_sub(Duration::from_nanos(state.elapsed_ns)) .unwrap_or(now); let mut token_bucket = TokenBucket::new(state.size, state.one_time_burst, state.refill_time); token_bucket.budget = state.budget; token_bucket.last_update = last_update; Ok(token_bucket) } } #[derive(Versionize)] pub struct RateLimiterState { ops: Option<TokenBucketState>, bandwidth: Option<TokenBucketState>, } impl Persist<'_> for RateLimiter { type State = RateLimiterState; type ConstructorArgs = (); type Error = io::Error; fn save(&self) -> Self::State { RateLimiterState { ops: self.ops.as_ref().map(|ops| ops.save()), bandwidth: self.bandwidth.as_ref().map(|bw| bw.save()), } } fn restore(_: Self::ConstructorArgs, state: &Self::State) -> Result<Self, Self::Error> { let rate_limiter = RateLimiter { ops: state .ops .as_ref() .map(|ops| TokenBucket::restore((), ops).unwrap()), bandwidth: state .bandwidth .as_ref() .map(|bw| TokenBucket::restore((), bw).unwrap()), timer_fd: TimerFd::new_custom(ClockId::Monotonic, true, true)?, timer_active: false, }; Ok(rate_limiter) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_token_bucket_persistence() { let mut tb = TokenBucket::new(1000, Some(2000), 3000); let restored_tb = TokenBucket::restore((), &tb.save()).unwrap(); assert!(tb.partial_eq(&restored_tb)); tb.reduce(100); let restored_tb = TokenBucket::restore((), &tb.save()).unwrap(); assert!(tb.partial_eq(&restored_tb)); tb.replenish(100); let restored_tb = TokenBucket::restore((), &tb.save()).unwrap(); assert!(tb.partial_eq(&restored_tb)); let mut mem = vec![0; 4096]; let version_map = VersionMap::new(); tb.save() .serialize(&mut mem.as_mut_slice(), &version_map, 1) .unwrap(); let restored_tb = TokenBucket::restore( (), &TokenBucketState::deserialize(&mut mem.as_slice(), &version_map, 1).unwrap(), ) .unwrap(); assert!(tb.partial_eq(&restored_tb)); } #[test] fn test_rate_limiter_persistence() { let refill_time = 100_000; let mut rate_limiter = RateLimiter::new(100, None, refill_time, 10, None, refill_time).unwrap(); let restored_rate_limiter = RateLimiter::restore((), &rate_limiter.save()).expect("Unable to restore rate limiter"); assert!(rate_limiter .ops() .unwrap()
random
[ { "content": "/// Returns the memory address where the initrd could be loaded.\n\npub fn initrd_load_addr(guest_mem: &GuestMemoryMmap, initrd_size: usize) -> super::Result<u64> {\n\n let round_to_pagesize = |size| (size + (super::PAGE_SIZE - 1)) & !(super::PAGE_SIZE - 1);\n\n match GuestAddress(get_fdt_ad...
Rust
cli/src/run.rs
russellwmy/tract
e53430a65eac501f3145ff7fbaa80d6aac8c9e40
use crate::CliResult; use crate::{Model, Parameters}; use tract_hir::internal::*; #[cfg(feature = "pulse")] use tract_pulse::internal::*; pub fn handle(params: &Parameters, options: &clap::ArgMatches) -> CliResult<()> { let dump = options.is_present("dump"); #[cfg(feature = "pulse")] let outputs = if let Some(pulse) = params.tract_model.downcast_ref::<PulsedModel>() { run_pulse_t(pulse, &params)? } else { dispatch_model!(&*params.tract_model, |m| run_regular(m, &params, options))? }; #[cfg(not(feature = "pulse"))] let outputs = dispatch_model!(&*params.tract_model, |m| run_regular(m, &params, options))?; if dump { for (ix, output) in outputs.iter().enumerate() { println!("output #{}\n{}\n", ix, output.dump(true)?); } } if let Some(asserts) = &params.assertions.assert_outputs { crate::utils::check_outputs(&*outputs, &asserts)?; } if let Some(facts) = &params.assertions.assert_output_facts { let outputs: Vec<InferenceFact> = outputs.iter().map(|t| InferenceFact::dt_shape(t.datum_type(), t.shape())).collect(); crate::utils::check_inferred(&*outputs, &*facts)?; } Ok(()) } fn run_regular( tract: &dyn Model, params: &Parameters, options: &clap::ArgMatches, ) -> CliResult<TVec<Arc<Tensor>>> { let steps = options.is_present("steps"); let assert_sane_floats = options.is_present("assert-sane-floats"); let mut inputs: TVec<Tensor> = tvec!(); for (ix, input) in tract.input_outlets().iter().enumerate() { if let Some(input) = params.input_values.get(ix).and_then(|x| x.as_ref()) { inputs.push(input.clone().into_tensor()) } else { let fact = tract.outlet_typedfact(*input)?; inputs.push(crate::tensor::tensor_for_fact(&fact, None)?); } } dispatch_model!(tract, |m| { let plan = SimplePlan::new(m)?; let mut state = SimpleState::new(plan)?; Ok(state.run_plan_with_eval(inputs, |session_state, state, node, input| { if steps { eprintln!("{}: <{:?}", node, input); } let r = tract_core::plan::eval(session_state, state, node, input); if steps { eprintln!("{}: >{:?}", node, r); } let r = r?; if assert_sane_floats { for (ix, o) in r.iter().enumerate() { if let Ok(floats) = o.as_slice::<f32>() { if let Some(pos) = floats.iter().position(|f| !f.is_finite()) { eprintln!("{:?}", floats); tract_core::anyhow::bail!( "Found {} in output {} of {}", floats[pos], ix, node ); } } } } Ok(r) })?) }) } #[cfg(feature = "pulse")] fn run_pulse_t(model: &PulsedModel, params: &Parameters) -> CliResult<TVec<Arc<Tensor>>> { let input_fact = model.input_fact(0)?; let output_fact = model.output_fact(0)?; let output_pulse = output_fact.pulse(); let axis = input_fact.axis; let input: &Tensor = &params.input_values[0].as_ref().unwrap(); let input_dim = input.shape()[axis]; let output_dim = output_fact .dim .eval(&SymbolValues::default().with(stream_symbol(), input_dim as i64)) .to_usize()?; let mut output_shape = output_fact.shape.to_vec(); output_shape[output_fact.axis] = (output_dim as usize + output_fact.delay + 4 * output_fact.pulse()).to_dim(); let output_shape: TVec<usize> = output_shape.iter().map(|d| d.to_usize().unwrap()).collect(); let plan = SimplePlan::new(model)?; let mut state = ::tract_core::plan::SimpleState::new(&plan)?; let pulse = input_fact.pulse(); let mut result = tract_ndarray::ArrayD::<f32>::default(&*output_shape); let input = input.to_array_view::<f32>()?; for ix in 0..input_dim.div_ceil(pulse) { let chunk = input.slice_axis(tract_ndarray::Axis(axis), (ix * pulse..(ix + 1) * pulse).into()); let input = if chunk.shape()[input_fact.axis] < pulse { let mut chunk_shape = chunk.shape().to_vec(); chunk_shape[input_fact.axis] = pulse; let mut padded_chunk = tract_ndarray::ArrayD::<f32>::default(chunk_shape); padded_chunk .slice_axis_mut( tract_ndarray::Axis(input_fact.axis), (..chunk.shape()[input_fact.axis]).into(), ) .assign(&chunk); padded_chunk } else { chunk.to_owned() }; let outputs = state.run(tvec!(input.into()))?; let result_chunk = outputs[0].to_array_view::<f32>()?; result .slice_axis_mut( tract_ndarray::Axis(output_fact.axis), ((output_pulse * ix)..(output_pulse * (ix + 1))).into(), ) .assign(&result_chunk); } result.slice_axis_inplace(tract_ndarray::Axis(output_fact.axis), (output_fact.delay..).into()); result .slice_axis_inplace(tract_ndarray::Axis(output_fact.axis), (..output_dim as usize).into()); Ok(tvec!(result.into_arc_tensor())) }
use crate::CliResult; use crate::{Model, Parameters}; use tract_hir::internal::*; #[cfg(feature = "pulse")] use tract_pulse::internal::*; pub fn handle(params: &Parameters, options: &clap::ArgMatches) -> CliResult<()> { let dump = options.is_present("dump"); #[cfg(feature = "pulse")] let outputs = if let Some(pulse) = params.tract_model.downcast_ref::<PulsedModel>() { run_pulse_t(pulse, &params)? } else { dispatch_model!(&*params.tract_model, |m| run_regular(m, &params, options))? }; #[cfg(not(feature = "pulse"))] let outputs = dispatch_model!(&*params.tract_model, |m| run_regular(m, &params, options))?; if dump { for (ix, output) in outputs.iter().enumerate() { println!("output #{}\n{}\n", ix, output.dump(true)?); } } if let Some(asserts) = &params.assertions.assert_outputs { crate::utils::check_outputs(&*outputs, &asserts)?; } if let Some(facts) = &params.assertions.assert_output_facts { let outputs: Vec<InferenceFact> = outputs.iter().map(|t| InferenceFact::dt_shape(t.datum_type(), t.shape())).collect(); crate::utils::check_inferred(&*outputs, &*facts)?; } Ok(()) } fn run_regular( tract: &dyn Model, params: &Parameters, options: &clap::ArgMatches, ) -> CliResult<TVec<Arc<Tensor>>> { let steps = options.is_present("steps"); let assert_sane_floats = options.is_present("assert-sane-floats"); let mut inputs: TVec<Tensor> = tvec!(); for (ix, input) in tract.input_outlets().iter().enumerate() { if let Some(input) = params.input_values.get(ix).and_then(|x| x.as_ref()) { inputs.push(input.clone().into_tensor()) } else { let fact = tract.outlet_typedfact(*input)?; inputs.push(crate::tensor::tensor_for_fact(&fact, None)?); } } dispatch_model!(tract, |m| { let plan = SimplePlan::new(m)?; let mut state = SimpleState::new(plan)?; Ok(state.run_plan_with_eval(inputs, |session_state, state, node, input| { if steps { eprintln!("{}: <{:?}", node, input); } let r = tract_core::plan::eval(session_state, state, node, input); if steps { eprintln!("{}: >{:?}", node, r); } let r = r?; if assert_sane_floats { for (ix, o) in r.iter().enumerate() { if let Ok(floats) = o.as_slice::<f32>() { if let Some(pos) = floats.iter().position(|f| !f.is_finite()) { eprintln!("{:?}", floats); tract_core::anyhow::bail!( "Found {} in output {} of {}", floats[pos], ix, node ); } } } } Ok(r) })?) }) } #[cfg(feature = "pulse")] fn run_pulse_t(model: &PulsedModel, params: &Parameters) -> CliResult<TVec<Arc<Tensor>>> { let input_fact = model.input_fact(0)?; let output_fact = model.output_fact(0)?; let output_pulse = output_fact.pulse(); let axis = input_fact.axis; let input: &Tensor = &params.input_values[0].as_ref().unwrap(); let input_dim = input.shape()[axis]; let output_dim = output_fact .dim .eval(&SymbolValues::default().
shape); let input = input.to_array_view::<f32>()?; for ix in 0..input_dim.div_ceil(pulse) { let chunk = input.slice_axis(tract_ndarray::Axis(axis), (ix * pulse..(ix + 1) * pulse).into()); let input = if chunk.shape()[input_fact.axis] < pulse { let mut chunk_shape = chunk.shape().to_vec(); chunk_shape[input_fact.axis] = pulse; let mut padded_chunk = tract_ndarray::ArrayD::<f32>::default(chunk_shape); padded_chunk .slice_axis_mut( tract_ndarray::Axis(input_fact.axis), (..chunk.shape()[input_fact.axis]).into(), ) .assign(&chunk); padded_chunk } else { chunk.to_owned() }; let outputs = state.run(tvec!(input.into()))?; let result_chunk = outputs[0].to_array_view::<f32>()?; result .slice_axis_mut( tract_ndarray::Axis(output_fact.axis), ((output_pulse * ix)..(output_pulse * (ix + 1))).into(), ) .assign(&result_chunk); } result.slice_axis_inplace(tract_ndarray::Axis(output_fact.axis), (output_fact.delay..).into()); result .slice_axis_inplace(tract_ndarray::Axis(output_fact.axis), (..output_dim as usize).into()); Ok(tvec!(result.into_arc_tensor())) }
with(stream_symbol(), input_dim as i64)) .to_usize()?; let mut output_shape = output_fact.shape.to_vec(); output_shape[output_fact.axis] = (output_dim as usize + output_fact.delay + 4 * output_fact.pulse()).to_dim(); let output_shape: TVec<usize> = output_shape.iter().map(|d| d.to_usize().unwrap()).collect(); let plan = SimplePlan::new(model)?; let mut state = ::tract_core::plan::SimpleState::new(&plan)?; let pulse = input_fact.pulse(); let mut result = tract_ndarray::ArrayD::<f32>::default(&*output_
random
[ { "content": "pub fn dump(ast: &mut IntoAst, node: &TypedNode) -> TractResult<Option<Arc<RValue>>> {\n\n let lrn = node.op_as::<Lrn>().unwrap();\n\n let input = ast.mapping[&node.inputs[0]].clone();\n\n Ok(Some(invocation(\n\n \"tract_onnx_lrn\",\n\n &[input],\n\n &[\n\n ...
Rust
dpu-cluster-core/src/pipeline/stages/loader.rs
upmem/dpu_cluster
92f143a9d7757a29e79a863d25afb4e6daeccc56
use std::sync::mpsc::Receiver; use std::sync::mpsc::Sender; use crate::pipeline::transfer::OutputMemoryTransfer; use crate::pipeline::PipelineError; use std::sync::Arc; use std::sync::Mutex; use crate::pipeline::transfer::InputMemoryTransfer; use crate::view::View; use crate::pipeline::stages::DpuGroup; use crate::pipeline::OutputResult; use crate::pipeline::stages::GroupJob; use crate::cluster::Cluster; use crate::memory::MemoryTransfer; use crate::error::ClusterError; use crate::pipeline::monitoring::EventMonitor; use crate::pipeline::monitoring::Process; use crate::pipeline::monitoring::Event; use crate::driver::Driver; use std::sync::mpsc::SyncSender; use crate::pipeline::stages::Stage; pub struct InputLoader<InputHandle> { cluster: Arc<Cluster>, transfer_receiver: Receiver<(DpuGroup, Vec<Vec<InputMemoryTransfer>>, Vec<(InputHandle, OutputMemoryTransfer)>)>, job_sender: Sender<GroupJob<InputHandle>>, output_sender: SyncSender<OutputResult<InputHandle>>, monitoring: EventMonitor, shutdown: Arc<Mutex<bool>> } impl <InputHandle> InputLoader<InputHandle> where InputHandle: Send + 'static { pub fn new(cluster: Arc<Cluster>, transfer_receiver: Receiver<(DpuGroup, Vec<Vec<InputMemoryTransfer>>, Vec<(InputHandle, OutputMemoryTransfer)>)>, job_sender: Sender<GroupJob<InputHandle>>, output_sender: SyncSender<OutputResult<InputHandle>>, mut monitoring: EventMonitor, shutdown: Arc<Mutex<bool>>) -> Self { monitoring.set_process(Process::Loader); InputLoader { cluster, transfer_receiver, job_sender, output_sender, monitoring, shutdown } } } impl <InputHandle> Stage for InputLoader<InputHandle> where InputHandle: Send + 'static { fn run(self) { let monitoring = self.monitoring; monitoring.record(Event::ProcessBegin); let driver = self.cluster.driver(); for (group, inputs, outputs) in self.transfer_receiver { let group_id = group.id; monitoring.record(Event::GroupLoadingBegin(group_id)); let is_ok = load_input_chunk(driver, &group, inputs, &self.output_sender); monitoring.record(Event::GroupLoadingEnd(group_id)); if is_ok { self.job_sender.send((group, outputs)).unwrap(); } } } } fn load_input_chunk<T>(driver: &Driver, group: &DpuGroup, chunk: Vec<Vec<InputMemoryTransfer>>, output_sender: &SyncSender<OutputResult<T>>) -> bool { match chunk.iter().max_by_key(|t| t.len()).map(|t| t.len()) { None => true, Some(max_len) => match do_memory_transfers(driver, group, chunk, max_len) { Err(err) => { output_sender.send(Err(PipelineError::InfrastructureError(err))).unwrap(); false }, Ok(_) => { let mut is_ok = true; for dpu in group.active_dpus() { match driver.boot(&View::one(dpu.clone())) { Ok(_) => (), Err(err) => { output_sender.send(Err(PipelineError::InfrastructureError(err))).unwrap(); is_ok = false; break; } } } is_ok }, }, } } fn do_memory_transfers(driver: &Driver, group: &DpuGroup, mut chunk: Vec<Vec<InputMemoryTransfer>>, max_len: usize) -> Result<(), ClusterError> { let mut memory_transfers = Vec::with_capacity(max_len); for _ in 0..max_len { memory_transfers.push(MemoryTransfer::default()); } let dpus = group.active_dpus().collect::<Vec<_>>(); for (idx, transfers) in chunk.iter_mut().enumerate() { for (i, transfer) in transfers.iter_mut().enumerate() { let memory_transfer = memory_transfers.get_mut(i).unwrap(); memory_transfer.add_in_place(*dpus.get(idx).unwrap().clone(), transfer.offset, transfer.content.as_mut_slice()); } } for memory_transfer in memory_transfers.iter_mut() { driver.copy_to_memory(memory_transfer)?; } Ok(()) }
use std::sync::mpsc::Receiver; use std::sync::mpsc::Sender; use crate::pipeline::transfer::OutputMemoryTransfer; use crate::pipeline::PipelineError; use std::sync::Arc; use std::sync::Mutex; use crate::pipeline::transfer::InputMemoryTransfer; use crate::view::View; use crate::pipeline::stages::DpuGroup; use crate::pipeline::OutputResult; use crate::pipeline::stages::GroupJob; use crate::cluster::Cluster; use crate::memory::MemoryTransfer; use crate::error::ClusterError; use crate::pipeline::monitoring::EventMonitor; use crate::pipeline::monitoring::Process; use crate::pipeline::monitoring::Event; use crate::driver::Driver; use std::sync::mpsc::SyncSender; use crate::pipeline::stages::Stage; pub struct InputLoader<InputHandle> { cluster: Arc<Cluster>, transfer_receiver: Receiver<(DpuGroup, Vec<Vec<InputMemoryTransfer>>, Vec<(InputHandle, OutputMemoryTransfer)>)>, job_sender: Sender<GroupJob<InputHandle>>, output_sender: SyncSender<OutputResult<InputHandle>>, monitoring: EventMonitor, shutdown: Arc<Mutex<bool>> } impl <InputHandle> InputLoader<InputHandle> where InputHandle: Send + 'static { pub fn new(cluster: Arc<Cluster>, transfer_receiver: Receiver<(DpuGroup, Vec<Vec<InputMemoryTransfer>>, Vec<(InputHandle, OutputMemoryTransfer)>)>, job_sender: Sender<GroupJob<InputHandle>>, output_sender: SyncSender<OutputResult<InputHandle>>, mut monitoring: EventMonitor, shutdown: Arc<Mutex<bool>>) -> Self { monitoring.set_process(Process::Loader); InputLoader { cluster, transfer_receiver, job_sender, output_sender, monitoring, shutdown } } } impl <InputHandle> Stage for InputLoader<InputHandle> where InputHandle: Send + 'static { fn run(self) { let monitoring = self.monitoring; monitoring.record(Event::ProcessBegin); let driver = self.cluster.driver(); for (group, inputs, outputs) in self.transfer_receiver { let group_id = group.id; monitoring.record(Event::GroupLoadingBegin(group_id)); let is_ok = load_input_chunk(driver, &group, inputs, &self.output_sender); monitoring.record(Event::GroupLoadingEnd(group_i
} fn load_input_chunk<T>(driver: &Driver, group: &DpuGroup, chunk: Vec<Vec<InputMemoryTransfer>>, output_sender: &SyncSender<OutputResult<T>>) -> bool { match chunk.iter().max_by_key(|t| t.len()).map(|t| t.len()) { None => true, Some(max_len) => match do_memory_transfers(driver, group, chunk, max_len) { Err(err) => { output_sender.send(Err(PipelineError::InfrastructureError(err))).unwrap(); false }, Ok(_) => { let mut is_ok = true; for dpu in group.active_dpus() { match driver.boot(&View::one(dpu.clone())) { Ok(_) => (), Err(err) => { output_sender.send(Err(PipelineError::InfrastructureError(err))).unwrap(); is_ok = false; break; } } } is_ok }, }, } } fn do_memory_transfers(driver: &Driver, group: &DpuGroup, mut chunk: Vec<Vec<InputMemoryTransfer>>, max_len: usize) -> Result<(), ClusterError> { let mut memory_transfers = Vec::with_capacity(max_len); for _ in 0..max_len { memory_transfers.push(MemoryTransfer::default()); } let dpus = group.active_dpus().collect::<Vec<_>>(); for (idx, transfers) in chunk.iter_mut().enumerate() { for (i, transfer) in transfers.iter_mut().enumerate() { let memory_transfer = memory_transfers.get_mut(i).unwrap(); memory_transfer.add_in_place(*dpus.get(idx).unwrap().clone(), transfer.offset, transfer.content.as_mut_slice()); } } for memory_transfer in memory_transfers.iter_mut() { driver.copy_to_memory(memory_transfer)?; } Ok(()) }
d)); if is_ok { self.job_sender.send((group, outputs)).unwrap(); } } }
function_block-function_prefixed
[ { "content": "pub trait Stage: Sized + Send + 'static {\n\n fn launch(mut self) -> Result<ThreadHandle, PipelineError> {\n\n self.init()?;\n\n\n\n Ok(Some(thread::spawn(|| self.run())))\n\n }\n\n\n\n fn init(&mut self) -> Result<(), PipelineError> { Ok(()) }\n\n fn run(self);\n\n}\n\n\...
Rust
algebra/src/fields/models/fp6_2over3.rs
ZencashOfficial/zexe
deaabb1c47d2a01fbd7514dc4ed4e255ebaec890
use super::quadratic_extension::*; use std::marker::PhantomData; use std::ops::{MulAssign, Neg}; use crate::{ bits::{FromBits, FromCompressedBits, ToBits, ToCompressedBits}, fields::{Field, Fp3, Fp3Parameters, SquareRootField}, BitSerializationError, Error, }; pub trait Fp6Parameters: 'static + Send + Sync { type Fp3Params: Fp3Parameters; const NONRESIDUE: Fp3<Self::Fp3Params>; const FROBENIUS_COEFF_FP6_C1: &'static [<Self::Fp3Params as Fp3Parameters>::Fp]; #[inline(always)] fn mul_fp3_by_nonresidue(fe: &Fp3<Self::Fp3Params>) -> Fp3<Self::Fp3Params> { let mut res = *fe; res.c0 = fe.c2; res.c1 = fe.c0; res.c2 = fe.c1; res.c0 = <Self::Fp3Params as Fp3Parameters>::mul_fp_by_nonresidue(&res.c0); res } } pub struct Fp6ParamsWrapper<P: Fp6Parameters>(PhantomData<P>); impl<P: Fp6Parameters> QuadExtParameters for Fp6ParamsWrapper<P> { type BasePrimeField = <P::Fp3Params as Fp3Parameters>::Fp; type BaseField = Fp3<P::Fp3Params>; type FrobCoeff = Self::BasePrimeField; const DEGREE_OVER_BASE_PRIME_FIELD: usize = 6; const NONRESIDUE: Self::BaseField = P::NONRESIDUE; const FROBENIUS_COEFF_C1: &'static [Self::FrobCoeff] = P::FROBENIUS_COEFF_FP6_C1; #[inline(always)] fn mul_base_field_by_nonresidue(fe: &Self::BaseField) -> Self::BaseField { P::mul_fp3_by_nonresidue(fe) } fn mul_base_field_by_frob_coeff(fe: &mut Self::BaseField, power: usize) { fe.mul_assign_by_fp(&Self::FROBENIUS_COEFF_C1[power % Self::DEGREE_OVER_BASE_PRIME_FIELD]); } } pub type Fp6<P> = QuadExtField<Fp6ParamsWrapper<P>>; impl<P: Fp6Parameters> Fp6<P> { pub fn mul_by_034( &mut self, c0: &<P::Fp3Params as Fp3Parameters>::Fp, c3: &<P::Fp3Params as Fp3Parameters>::Fp, c4: &<P::Fp3Params as Fp3Parameters>::Fp, ) { let z0 = self.c0.c0; let z1 = self.c0.c1; let z2 = self.c0.c2; let z3 = self.c1.c0; let z4 = self.c1.c1; let z5 = self.c1.c2; let x0 = *c0; let x3 = *c3; let x4 = *c4; let mut tmp1 = x3; tmp1.mul_assign(&<P::Fp3Params as Fp3Parameters>::NONRESIDUE); let mut tmp2 = x4; tmp2.mul_assign(&<P::Fp3Params as Fp3Parameters>::NONRESIDUE); self.c0.c0 = x0 * &z0 + &(tmp1 * &z5) + &(tmp2 * &z4); self.c0.c1 = x0 * &z1 + &(x3 * &z3) + &(tmp2 * &z5); self.c0.c2 = x0 * &z2 + &(x3 * &z4) + &(x4 * &z3); self.c1.c0 = x0 * &z3 + &(x3 * &z0) + &(tmp2 * &z2); self.c1.c1 = x0 * &z4 + &(x3 * &z1) + &(x4 * &z0); self.c1.c2 = x0 * &z5 + &(x3 * &z2) + &(x4 * &z1); } pub fn mul_by_014( &mut self, c0: &<P::Fp3Params as Fp3Parameters>::Fp, c1: &<P::Fp3Params as Fp3Parameters>::Fp, c4: &<P::Fp3Params as Fp3Parameters>::Fp, ) { let z0 = self.c0.c0; let z1 = self.c0.c1; let z2 = self.c0.c2; let z3 = self.c1.c0; let z4 = self.c1.c1; let z5 = self.c1.c2; let x0 = *c0; let x1 = *c1; let x4 = *c4; let mut tmp1 = x1; tmp1.mul_assign(&<P::Fp3Params as Fp3Parameters>::NONRESIDUE); let mut tmp2 = x4; tmp2.mul_assign(&<P::Fp3Params as Fp3Parameters>::NONRESIDUE); self.c0.c0 = x0 * &z0 + &(tmp1 * &z2) + &(tmp2 * &z4); self.c0.c1 = x0 * &z1 + &(x1 * &z0) + &(tmp2 * &z5); self.c0.c2 = x0 * &z2 + &(x1 * &z1) + &(x4 * &z3); self.c1.c0 = x0 * &z3 + &(tmp1 * &z5) + &(tmp2 * &z2); self.c1.c1 = x0 * &z4 + &(x1 * &z3) + &(x4 * &z0); self.c1.c2 = x0 * &z5 + &(x1 * &z4) + &(x4 * &z1); } pub fn mul_by_2345(self, other: &Self) -> Self /* Devegili OhEig Scott Dahab --- Multiplication and Squaring on Pairing-Friendly Fields.pdf; Section 3 (Karatsuba) */ { let v0 = { let t = other.c0.c2 * &<P::Fp3Params as Fp3Parameters>::NONRESIDUE; Fp3::<P::Fp3Params>::new(self.c0.c1 * &t, self.c0.c2 * &t, self.c0.c0 * &other.c0.c2) }; let v1 = self.c1 * &other.c1; let beta_v1 = P::mul_fp3_by_nonresidue(&v1); let c0 = v0 + &beta_v1; let c1 = (self.c0 + &self.c1) * &(other.c0 + &other.c1) - &v0 - &v1; Self::new(c0, c1) } } impl<P: Fp6Parameters> ToCompressedBits for Fp6<P> { #[inline] fn compress(&self) -> Vec<bool> { let mut res = self.c1.write_bits(); let parity = self.c0.is_odd(); res.push(parity); res } } impl<P: Fp6Parameters> FromCompressedBits for Fp6<P> { #[inline] fn decompress(compressed: Vec<bool>) -> Result<Self, Error> { let len = compressed.len() - 1; let parity_flag_set = compressed[len]; let c1 = Fp3::read_bits(compressed[..len].to_vec())?; let c0 = { let t = Fp3::one() + &P::mul_fp3_by_nonresidue(&(c1.square())); t.sqrt() }; match c0 { Some(c0_u) => { let neg_c0u = c0_u.neg(); let c0_s = if c0_u.is_odd() ^ parity_flag_set { neg_c0u } else { c0_u }; Ok(Self::new(c0_s, c1)) } _ => Err(Box::new(BitSerializationError::UndefinedSqrt)), } } }
use super::quadratic_extension::*; use std::marker::PhantomData; use std::ops::{MulAssign, Neg}; use crate::{ bits::{FromBits, FromCompressedBits, ToBits, ToCompressedBits}, fields::{Field, Fp3, Fp3Parameters, SquareRootField}, BitSerializationError, Error, }; pub trait Fp6Parameters: 'static + Send + Sync { type Fp3Params: Fp3Parameters; const NONRESIDUE: Fp3<Self::Fp3Params>; const FROBENIUS_COEFF_FP6_C1: &'static [<Self::Fp3Params as Fp3Parameters>::Fp]; #[inline(always)] fn mul_fp3_by_nonresidue(fe: &Fp3<Self::Fp3Params>) -> Fp3<Self::Fp3Params> { let mut res = *fe; res.c0 = fe.c2; res.c1 = fe.c0; res.c2 = fe.c1; res.c0 = <Self::Fp3Params as Fp3Parameters>::mul_fp_by_nonresidue(&res.c0); res } } pub struct Fp6ParamsWrapper<P: Fp6Parameters>(PhantomData<P>); impl<P: Fp6Parameters> QuadExtParameters for Fp6ParamsWrapper<P> { type BasePrimeField = <P::Fp3Params as Fp3Parameters>::Fp; type BaseField = Fp3<P::Fp3Params>; type FrobCoeff = Self::BasePrimeField; const DEGREE_OVER_BASE_PRIME_FIELD: usize = 6; const NONRESIDUE: Self::BaseField = P::NONRESIDUE; const FROBENIUS_COEFF_C1: &'static [Self::FrobCoeff] = P::FROBENIUS_COEFF_FP6_C1; #[inline(always)] fn mul_base_field_by_nonresidue(fe: &Self::BaseField) -> Self::BaseField { P::mul_fp3_by_nonresidue(fe) } fn mul_base_field_by_frob_coeff(fe: &mut Self::BaseField, power: usize) { fe.mul_assign_by_fp(&Self::FROBENIUS_COEFF_C1[power % Self::DEGREE_OVER_BASE_PRIME_FIELD]); } } pub type Fp6<P> = QuadExtField<Fp6ParamsWrapper<P>>; impl<P: Fp6Parameters> Fp6<P> { pub fn mul_by_034( &mut self, c0: &<P::Fp3Params as Fp3Parameters>::Fp, c3: &<P::Fp3Params as Fp3Parameters>::Fp, c4: &<P::Fp3Params as Fp3Parameters>::Fp, ) { let z0 = self.c0.c0; let z1 = self.c0.c1; let z2 = self.c0.c2; let z3 = self.c1.c0; let z4 = self.c1.c1; let z5 = self.c1.c2; let x0 = *c0; let x3 = *c3; let x4 = *c4; let mut tmp1 = x3; tmp1.mul_assign(&<P::Fp3Params as Fp3Parameters>::NONRESIDUE); let mut tmp2 = x4; tmp2.mul_assign(&<P::Fp3Params as Fp3Parameters>::NONRESIDUE); self.c0.c0 = x0 * &z0 + &(tmp1 * &z5) + &(tmp2 * &z4); self.c0.c1 = x0 * &z1 + &(x3 * &z3) + &(tmp2 * &z5); self.c0.c2 = x0 * &z2 + &(x3 * &z4) + &(x4 * &z3); self.c1.c0 = x0 * &z3 + &(x3 * &z0) + &(tmp2 * &z2); self.c1.c1 = x0 * &z4 + &(x3 * &z1) + &(x4 * &z0); self.c1.c2 = x0 * &z5 + &(x3 * &z2) + &(x4 * &z1); } pub fn mul_by_014( &
pub fn mul_by_2345(self, other: &Self) -> Self /* Devegili OhEig Scott Dahab --- Multiplication and Squaring on Pairing-Friendly Fields.pdf; Section 3 (Karatsuba) */ { let v0 = { let t = other.c0.c2 * &<P::Fp3Params as Fp3Parameters>::NONRESIDUE; Fp3::<P::Fp3Params>::new(self.c0.c1 * &t, self.c0.c2 * &t, self.c0.c0 * &other.c0.c2) }; let v1 = self.c1 * &other.c1; let beta_v1 = P::mul_fp3_by_nonresidue(&v1); let c0 = v0 + &beta_v1; let c1 = (self.c0 + &self.c1) * &(other.c0 + &other.c1) - &v0 - &v1; Self::new(c0, c1) } } impl<P: Fp6Parameters> ToCompressedBits for Fp6<P> { #[inline] fn compress(&self) -> Vec<bool> { let mut res = self.c1.write_bits(); let parity = self.c0.is_odd(); res.push(parity); res } } impl<P: Fp6Parameters> FromCompressedBits for Fp6<P> { #[inline] fn decompress(compressed: Vec<bool>) -> Result<Self, Error> { let len = compressed.len() - 1; let parity_flag_set = compressed[len]; let c1 = Fp3::read_bits(compressed[..len].to_vec())?; let c0 = { let t = Fp3::one() + &P::mul_fp3_by_nonresidue(&(c1.square())); t.sqrt() }; match c0 { Some(c0_u) => { let neg_c0u = c0_u.neg(); let c0_s = if c0_u.is_odd() ^ parity_flag_set { neg_c0u } else { c0_u }; Ok(Self::new(c0_s, c1)) } _ => Err(Box::new(BitSerializationError::UndefinedSqrt)), } } }
mut self, c0: &<P::Fp3Params as Fp3Parameters>::Fp, c1: &<P::Fp3Params as Fp3Parameters>::Fp, c4: &<P::Fp3Params as Fp3Parameters>::Fp, ) { let z0 = self.c0.c0; let z1 = self.c0.c1; let z2 = self.c0.c2; let z3 = self.c1.c0; let z4 = self.c1.c1; let z5 = self.c1.c2; let x0 = *c0; let x1 = *c1; let x4 = *c4; let mut tmp1 = x1; tmp1.mul_assign(&<P::Fp3Params as Fp3Parameters>::NONRESIDUE); let mut tmp2 = x4; tmp2.mul_assign(&<P::Fp3Params as Fp3Parameters>::NONRESIDUE); self.c0.c0 = x0 * &z0 + &(tmp1 * &z2) + &(tmp2 * &z4); self.c0.c1 = x0 * &z1 + &(x1 * &z0) + &(tmp2 * &z5); self.c0.c2 = x0 * &z2 + &(x1 * &z1) + &(x4 * &z3); self.c1.c0 = x0 * &z3 + &(tmp1 * &z5) + &(tmp2 * &z2); self.c1.c1 = x0 * &z4 + &(x1 * &z3) + &(x4 * &z0); self.c1.c2 = x0 * &z5 + &(x1 * &z4) + &(x4 * &z1); }
function_block-function_prefix_line
[ { "content": "pub trait Fp3Parameters: 'static + Send + Sync {\n\n type Fp: PrimeField + SquareRootField;\n\n\n\n //alpha\n\n const NONRESIDUE: Self::Fp;\n\n // coefficients of the powers of the Frobenius automorphism as linear map over F\n\n // (pi^0(X), pi^1(X), pi^2(X)) = (C1_0*X, C1_1*X +C1_2...
Rust
cleu-orm/src/crud/utils.rs
c410-f3r/cleu-orm
34d22f1f4bb01ff792262ebb63bdeec36dc0d603
use crate::{ buffer_try_push_str, buffer_write_fmt, crud::{TdEntity, TdError}, write_column_alias, write_select_field, FromRowsSuffix, SelectLimit, SelectOrderBy, SqlWriter, Suffix, Table, TableDefs, }; use sqlx_core::{ postgres::{PgPool, PgRow}, query::query, row::Row, }; #[inline] pub fn seek_related_entities<'entity, B, F, R, TD>( buffer: &mut B, rows: &[PgRow], suffix: Suffix, suffix_related: Suffix, mut cb: F, ) -> Result<usize, TD::Error> where B: cl_traits::String, F: FnMut(R) -> Result<(), TD::Error>, R: FromRowsSuffix<B, Error = TD::Error>, TD: TableDefs<'entity>, { if rows.is_empty() { return Ok(0); } let first_row = if let Some(elem) = rows.first() { elem } else { return Ok(0); }; let first_rslt = R::from_rows_suffix(rows, buffer, suffix_related, first_row); let (mut counter, mut previous) = if let Ok((skip, entity)) = first_rslt { write_column_alias(buffer, TD::TABLE_NAME, suffix, TD::PRIMARY_KEY_NAME)?; let previous = first_row.try_get(buffer.as_ref()).map_err(Into::into)?; buffer.clear(); cb(entity)?; (skip, previous) } else { buffer.clear(); return Ok(1); }; loop { if counter >= rows.len() { break; } let row = if let Some(elem) = rows.get(counter) { elem } else { break; }; let curr_rows = rows.get(counter..).unwrap_or_default(); let (skip, entity) = R::from_rows_suffix(curr_rows, buffer, suffix_related, row)?; write_column_alias(buffer, TD::TABLE_NAME, suffix, TD::PRIMARY_KEY_NAME)?; let curr: i64 = row.try_get(buffer.as_ref()).map_err(Into::into)?; buffer.clear(); if previous == curr { cb(entity)?; counter = counter.wrapping_add(skip); } else { break; } previous = curr; } Ok(counter) } #[inline] pub(crate) async fn read_all<'entity, R, B, TD>( buffer: &mut B, pool: &PgPool, table: &Table<'entity, TD>, ) -> Result<Vec<R>, TdError<'entity, TD>> where B: cl_traits::String, R: FromRowsSuffix<B, Error = TD::Error>, TD: TableDefs<'entity>, TD::Associations: SqlWriter<B, Error = TD::Error>, TD::Error: From<crate::Error>, { table.write_select(buffer, SelectOrderBy::Ascending, SelectLimit::All, &mut |_| Ok(()))?; let rows = query(buffer.as_ref()).fetch_all(pool).await.map_err(Into::into)?; buffer.clear(); collect_entities_tables(buffer, &rows, table) } #[inline] pub(crate) async fn read_by_id<'entity, B, TD>( buffer: &mut B, id: &TD::PrimaryKeyValue, pool: &PgPool, table: &Table<'entity, TD>, ) -> Result<TdEntity<'entity, TD>, TdError<'entity, TD>> where B: cl_traits::String, TD: TableDefs<'entity>, TD::Associations: SqlWriter<B, Error = TD::Error>, TD::Entity: FromRowsSuffix<B, Error = TD::Error>, TD::Error: From<crate::Error>, { table.write_select(buffer, SelectOrderBy::Ascending, SelectLimit::All, &mut |b| { write_select_field( b, TD::TABLE_NAME, TD::TABLE_NAME_ALIAS, table.suffix(), table.id_field().name(), )?; buffer_write_fmt(b, format_args!(" = {id}")) })?; let rows = query(buffer.as_ref()).fetch_all(pool).await.map_err(Into::into)?; buffer.clear(); let first_row = rows.first().ok_or(crate::Error::NoDatabaseRowResult)?; Ok(TD::Entity::from_rows_suffix(&rows, buffer, table.suffix(), first_row)?.1) } #[inline] pub(crate) async fn read_all_with_params<'entity, R, B, TD>( buffer: &mut B, pool: &PgPool, table: &Table<'entity, TD>, order_by: SelectOrderBy, select_limit: SelectLimit, where_str: &str, ) -> Result<Vec<R>, TdError<'entity, TD>> where B: cl_traits::String, R: FromRowsSuffix<B, Error = TD::Error>, TD: TableDefs<'entity>, TD::Associations: SqlWriter<B, Error = TD::Error>, TD::Error: From<crate::Error>, { table.write_select(buffer, order_by, select_limit, &mut |b| buffer_try_push_str(b, where_str))?; let rows = query(buffer.as_ref()).fetch_all(pool).await.map_err(Into::into)?; buffer.clear(); collect_entities_tables(buffer, &rows, table) } #[inline] fn collect_entities_tables<'entity, R, B, TD>( buffer: &mut B, rows: &[PgRow], table: &Table<'entity, TD>, ) -> Result<Vec<R>, TD::Error> where B: cl_traits::String, R: FromRowsSuffix<B, Error = TD::Error>, TD: TableDefs<'entity>, { let mut rslt = Vec::new(); let mut counter: usize = 0; loop { if counter >= rows.len() { break; } let actual_rows = rows.get(counter..).unwrap_or_default(); let skip = seek_related_entities::<_, _, _, TD>( buffer, actual_rows, table.suffix(), table.suffix(), |entity| { rslt.push(entity); Ok(()) }, )?; counter = counter.wrapping_add(skip); } Ok(rslt) }
use crate::{ buffer_try_push_str, buffer_write_fmt, crud::{TdEntity, TdError}, write_column_alias, write_select_field, FromRowsSuffix, SelectLimit, SelectOrderBy, SqlWriter, Suffix, Table, TableDefs, }; use sqlx_core::{ postgres::{PgPool, PgRow}, query::query, row::Row, }; #[inline] pub fn seek_related_entities<'entity, B, F, R, TD>( buffer: &mut B, rows: &[PgRow], suffix: Suffix, suffix_related: Suffix, mut cb: F, ) -> Result<usize, TD::Error> where B: cl_traits::String, F: FnMut(R) -> Result<(), TD::Error>, R: FromRowsSuffix<B, Error = TD::Error>, TD: TableDefs<'entity>, { if rows.is_empty() { return Ok(0); } let first_row = if let Some(elem) = rows.first() { elem } else { return Ok(0); }; let first_rslt = R::from_rows_suffix(rows, buffer, suffix_related, first_row); let (mut counter, mut previous) = if let Ok((skip, entity)) = first_rslt { write_column_alias(buffer, TD::TABLE_NAME, suffix, TD::PRIMARY_KEY_NAME)?; let previous = first_row.try_get(buffer.as_ref()).map_err(Into::into)?; buffer.clear(); cb(entity)?; (skip, previous) } else { buffer.clear(); return Ok(1); }; loop { if counter >= rows.len() { break; } let row = if let Some(elem) = rows.get(counter) { elem } else { break; }; let curr_rows = rows.get(counte
ated_entities::<_, _, _, TD>( buffer, actual_rows, table.suffix(), table.suffix(), |entity| { rslt.push(entity); Ok(()) }, )?; counter = counter.wrapping_add(skip); } Ok(rslt) }
r..).unwrap_or_default(); let (skip, entity) = R::from_rows_suffix(curr_rows, buffer, suffix_related, row)?; write_column_alias(buffer, TD::TABLE_NAME, suffix, TD::PRIMARY_KEY_NAME)?; let curr: i64 = row.try_get(buffer.as_ref()).map_err(Into::into)?; buffer.clear(); if previous == curr { cb(entity)?; counter = counter.wrapping_add(skip); } else { break; } previous = curr; } Ok(counter) } #[inline] pub(crate) async fn read_all<'entity, R, B, TD>( buffer: &mut B, pool: &PgPool, table: &Table<'entity, TD>, ) -> Result<Vec<R>, TdError<'entity, TD>> where B: cl_traits::String, R: FromRowsSuffix<B, Error = TD::Error>, TD: TableDefs<'entity>, TD::Associations: SqlWriter<B, Error = TD::Error>, TD::Error: From<crate::Error>, { table.write_select(buffer, SelectOrderBy::Ascending, SelectLimit::All, &mut |_| Ok(()))?; let rows = query(buffer.as_ref()).fetch_all(pool).await.map_err(Into::into)?; buffer.clear(); collect_entities_tables(buffer, &rows, table) } #[inline] pub(crate) async fn read_by_id<'entity, B, TD>( buffer: &mut B, id: &TD::PrimaryKeyValue, pool: &PgPool, table: &Table<'entity, TD>, ) -> Result<TdEntity<'entity, TD>, TdError<'entity, TD>> where B: cl_traits::String, TD: TableDefs<'entity>, TD::Associations: SqlWriter<B, Error = TD::Error>, TD::Entity: FromRowsSuffix<B, Error = TD::Error>, TD::Error: From<crate::Error>, { table.write_select(buffer, SelectOrderBy::Ascending, SelectLimit::All, &mut |b| { write_select_field( b, TD::TABLE_NAME, TD::TABLE_NAME_ALIAS, table.suffix(), table.id_field().name(), )?; buffer_write_fmt(b, format_args!(" = {id}")) })?; let rows = query(buffer.as_ref()).fetch_all(pool).await.map_err(Into::into)?; buffer.clear(); let first_row = rows.first().ok_or(crate::Error::NoDatabaseRowResult)?; Ok(TD::Entity::from_rows_suffix(&rows, buffer, table.suffix(), first_row)?.1) } #[inline] pub(crate) async fn read_all_with_params<'entity, R, B, TD>( buffer: &mut B, pool: &PgPool, table: &Table<'entity, TD>, order_by: SelectOrderBy, select_limit: SelectLimit, where_str: &str, ) -> Result<Vec<R>, TdError<'entity, TD>> where B: cl_traits::String, R: FromRowsSuffix<B, Error = TD::Error>, TD: TableDefs<'entity>, TD::Associations: SqlWriter<B, Error = TD::Error>, TD::Error: From<crate::Error>, { table.write_select(buffer, order_by, select_limit, &mut |b| buffer_try_push_str(b, where_str))?; let rows = query(buffer.as_ref()).fetch_all(pool).await.map_err(Into::into)?; buffer.clear(); collect_entities_tables(buffer, &rows, table) } #[inline] fn collect_entities_tables<'entity, R, B, TD>( buffer: &mut B, rows: &[PgRow], table: &Table<'entity, TD>, ) -> Result<Vec<R>, TD::Error> where B: cl_traits::String, R: FromRowsSuffix<B, Error = TD::Error>, TD: TableDefs<'entity>, { let mut rslt = Vec::new(); let mut counter: usize = 0; loop { if counter >= rows.len() { break; } let actual_rows = rows.get(counter..).unwrap_or_default(); let skip = seek_rel
random
[]
Rust
awc/src/responses/response.rs
LGU-Web3-0/actix-web
5fd5875d2c72194232cc4356c7093c54e0fc700b
use std::{ cell::{Ref, RefCell, RefMut}, fmt, mem, pin::Pin, task::{Context, Poll}, time::{Duration, Instant}, }; use actix_http::{ error::PayloadError, header::HeaderMap, BoxedPayloadStream, Extensions, HttpMessage, Payload, ResponseHead, StatusCode, Version, }; use actix_rt::time::{sleep, Sleep}; use bytes::Bytes; use futures_core::Stream; use pin_project_lite::pin_project; use serde::de::DeserializeOwned; #[cfg(feature = "cookies")] use crate::cookie::{Cookie, ParseError as CookieParseError}; use super::{JsonBody, ResponseBody, ResponseTimeout}; pin_project! { pub struct ClientResponse<S = BoxedPayloadStream> { pub(crate) head: ResponseHead, #[pin] pub(crate) payload: Payload<S>, pub(crate) timeout: ResponseTimeout, pub(crate) extensions: RefCell<Extensions>, } } impl<S> ClientResponse<S> { pub(crate) fn new(head: ResponseHead, payload: Payload<S>) -> Self { ClientResponse { head, payload, timeout: ResponseTimeout::default(), extensions: RefCell::new(Extensions::new()), } } #[inline] pub(crate) fn head(&self) -> &ResponseHead { &self.head } #[inline] pub fn version(&self) -> Version { self.head().version } #[inline] pub fn status(&self) -> StatusCode { self.head().status } #[inline] pub fn headers(&self) -> &HeaderMap { &self.head().headers } pub fn map_body<F, U>(mut self, f: F) -> ClientResponse<U> where F: FnOnce(&mut ResponseHead, Payload<S>) -> Payload<U>, { let payload = f(&mut self.head, self.payload); ClientResponse { payload, head: self.head, timeout: self.timeout, extensions: self.extensions, } } pub fn timeout(self, dur: Duration) -> Self { let timeout = match self.timeout { ResponseTimeout::Disabled(Some(mut timeout)) | ResponseTimeout::Enabled(mut timeout) => match Instant::now().checked_add(dur) { Some(deadline) => { timeout.as_mut().reset(deadline.into()); ResponseTimeout::Enabled(timeout) } None => ResponseTimeout::Enabled(Box::pin(sleep(dur))), }, _ => ResponseTimeout::Enabled(Box::pin(sleep(dur))), }; Self { payload: self.payload, head: self.head, timeout, extensions: self.extensions, } } pub(crate) fn _timeout(mut self, timeout: Option<Pin<Box<Sleep>>>) -> Self { self.timeout = ResponseTimeout::Disabled(timeout); self } #[cfg(feature = "cookies")] pub fn cookies(&self) -> Result<Ref<'_, Vec<Cookie<'static>>>, CookieParseError> { struct Cookies(Vec<Cookie<'static>>); if self.extensions().get::<Cookies>().is_none() { let mut cookies = Vec::new(); for hdr in self.headers().get_all(&actix_http::header::SET_COOKIE) { let s = std::str::from_utf8(hdr.as_bytes()).map_err(CookieParseError::from)?; cookies.push(Cookie::parse_encoded(s)?.into_owned()); } self.extensions_mut().insert(Cookies(cookies)); } Ok(Ref::map(self.extensions(), |ext| { &ext.get::<Cookies>().unwrap().0 })) } #[cfg(feature = "cookies")] pub fn cookie(&self, name: &str) -> Option<Cookie<'static>> { if let Ok(cookies) = self.cookies() { for cookie in cookies.iter() { if cookie.name() == name { return Some(cookie.to_owned()); } } } None } } impl<S> ClientResponse<S> where S: Stream<Item = Result<Bytes, PayloadError>>, { pub fn body(&mut self) -> ResponseBody<S> { ResponseBody::new(self) } pub fn json<T: DeserializeOwned>(&mut self) -> JsonBody<S, T> { JsonBody::new(self) } } impl<S> fmt::Debug for ClientResponse<S> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { writeln!(f, "\nClientResponse {:?} {}", self.version(), self.status(),)?; writeln!(f, " headers:")?; for (key, val) in self.headers().iter() { writeln!(f, " {:?}: {:?}", key, val)?; } Ok(()) } } impl<S> HttpMessage for ClientResponse<S> { type Stream = S; fn headers(&self) -> &HeaderMap { &self.head.headers } fn take_payload(&mut self) -> Payload<S> { mem::replace(&mut self.payload, Payload::None) } fn extensions(&self) -> Ref<'_, Extensions> { self.extensions.borrow() } fn extensions_mut(&self) -> RefMut<'_, Extensions> { self.extensions.borrow_mut() } } impl<S> Stream for ClientResponse<S> where S: Stream<Item = Result<Bytes, PayloadError>> + Unpin, { type Item = Result<Bytes, PayloadError>; fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { let this = self.project(); this.timeout.poll_timeout(cx)?; this.payload.poll_next(cx) } } #[cfg(test)] mod tests { use static_assertions::assert_impl_all; use super::*; use crate::any_body::AnyBody; assert_impl_all!(ClientResponse: Unpin); assert_impl_all!(ClientResponse<()>: Unpin); assert_impl_all!(ClientResponse<AnyBody>: Unpin); }
use std::{ cell::{Ref, RefCell, RefMut}, fmt, mem, pin::Pin, task::{Context, Poll}, time::{Duration, Instant}, }; use actix_http::{ error::PayloadError, header::HeaderMap, BoxedPayloadStream, Extensions, HttpMessage, Payload, ResponseHead, StatusCode, Version, }; use actix_rt::time::{sleep, Sleep}; use bytes::Bytes; use futures_core::Stream; use pin_project_lite::pin_project; use serde::de::DeserializeOwned; #[cfg(feature = "cookies")] use crate::cookie::{Cookie, ParseError as CookieParseError}; use super::{JsonBody, ResponseBody, ResponseTimeout}; pin_project! { pub struct ClientResponse<S = BoxedPayloadStream> { pub(crate) head: ResponseHead, #[pin] pub(crate) payload: Payload<S>, pub(crate) timeout: ResponseTimeout, pub(crate) extensions: RefCell<Extensions>, } } impl<S> ClientResponse<S> { pub(crate) fn new(head: ResponseHead, payload: Payload<S>) -> Self { ClientResponse { head, payload, timeout: ResponseTimeout::default(), extensions: RefCell::new(Extensions::new()), } } #[inline] pub(crate) fn head(&self) -> &ResponseHead { &self.head } #[inline] pub fn version(&self) -> Version { self.head().version } #[inline] pub fn status(&self) -> StatusCode { self.head().status } #[inline] pub fn headers(&self) -> &HeaderMap { &self.head().headers } pub fn map_body<F, U>(mut self, f: F) -> ClientResponse<U> where F: FnOnce(&mut ResponseHead, Payload<S>) -> Payload<U>, { let payload = f(&mut self.head, self.payload); ClientResponse { payload, head: self.head, timeout: self.timeout, extensions: self.extensions, } } pub fn timeout(self, dur: Duration) -> Self { let timeout = match self.timeout { ResponseTimeout::Disabled(Some(mut timeout)) | ResponseTimeout::Enabled(mut timeout) => match Instant::now().checked_add(dur) { Some(deadline) => { timeout.as_mut().reset(deadline.into()); ResponseTimeout::Enabled(timeout) } None => ResponseTimeout::Enabled(Box::pin(sleep(dur))), }, _ => ResponseTimeout::Enabled(Box::pin(sleep(dur))), }; Self { payload: self.payload, head: self.head, timeout, extensions: self.extensions, } } pub(crate) fn _timeout(mut self, timeout: Option<Pin<Box<Sleep>>>) -> Self { self.timeout = ResponseTimeout::Disabled(timeout); self } #[cfg(feature = "cookies")] pub fn cookies(&self) -> Result<Ref<'_, Vec<Cookie<'static>>>, CookieParseError> { struct Cookies(Vec<Cookie<'static>>); if self.extensions().get::<Cookies>().is_none() { let mut cookies = Vec::new(); for hdr in self.headers().get_all(&actix_http::header::SET_COOKIE) { let s = std::str::from_utf8(hdr.as_bytes()).map_err(CookieParseError::from)?; cookies.push(Cookie::parse_encoded(s)?.into_owned()); } self.extensions_mut().insert(Cookies(cookies)); } Ok(Ref::map(self.extensions(), |ext| { &ext.get::<Cookies>().unwrap().0 })) } #[cfg(feature = "cookies")] pub fn cookie(&self, name: &str) -> Option<Cookie<'static>> { if let Ok(cookies) = self.cookies() { for cookie in cookies.iter() {
} impl<S> ClientResponse<S> where S: Stream<Item = Result<Bytes, PayloadError>>, { pub fn body(&mut self) -> ResponseBody<S> { ResponseBody::new(self) } pub fn json<T: DeserializeOwned>(&mut self) -> JsonBody<S, T> { JsonBody::new(self) } } impl<S> fmt::Debug for ClientResponse<S> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { writeln!(f, "\nClientResponse {:?} {}", self.version(), self.status(),)?; writeln!(f, " headers:")?; for (key, val) in self.headers().iter() { writeln!(f, " {:?}: {:?}", key, val)?; } Ok(()) } } impl<S> HttpMessage for ClientResponse<S> { type Stream = S; fn headers(&self) -> &HeaderMap { &self.head.headers } fn take_payload(&mut self) -> Payload<S> { mem::replace(&mut self.payload, Payload::None) } fn extensions(&self) -> Ref<'_, Extensions> { self.extensions.borrow() } fn extensions_mut(&self) -> RefMut<'_, Extensions> { self.extensions.borrow_mut() } } impl<S> Stream for ClientResponse<S> where S: Stream<Item = Result<Bytes, PayloadError>> + Unpin, { type Item = Result<Bytes, PayloadError>; fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { let this = self.project(); this.timeout.poll_timeout(cx)?; this.payload.poll_next(cx) } } #[cfg(test)] mod tests { use static_assertions::assert_impl_all; use super::*; use crate::any_body::AnyBody; assert_impl_all!(ClientResponse: Unpin); assert_impl_all!(ClientResponse<()>: Unpin); assert_impl_all!(ClientResponse<AnyBody>: Unpin); }
if cookie.name() == name { return Some(cookie.to_owned()); } } } None }
function_block-function_prefix_line
[ { "content": "#[allow(non_snake_case)]\n\npub fn Header(name: &'static str, value: &'static str) -> impl Guard {\n\n HeaderGuard(\n\n header::HeaderName::try_from(name).unwrap(),\n\n header::HeaderValue::from_static(value),\n\n )\n\n}\n\n\n", "file_path": "actix-web/src/guard.rs", "r...
Rust
day16/main2.rs
allonsy/advent2017
644dd55ca9cc4319136123126c40330e9ba52de0
mod util; use std::collections::HashSet; const ARR_SIZE: usize = 16; struct Dance { index_arr: [u8; ARR_SIZE], char_arr: [char; ARR_SIZE], } impl Dance { fn new() -> Dance { Dance { index_arr: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], char_arr: [ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', ], } } fn rotate(&mut self, num: u8) { for i in 0..ARR_SIZE { self.index_arr[i] = (self.index_arr[i] + num) % ARR_SIZE as u8; self.char_arr[self.index_arr[i] as usize] = (i as u8 + 97) as char; } } fn swap_index(&mut self, from_index: usize, to_index: usize) { let temp = self.char_arr[to_index]; self.char_arr[to_index] = self.char_arr[from_index]; self.index_arr[self.char_arr[to_index] as usize - 97] = to_index as u8; self.char_arr[from_index] = temp; self.index_arr[temp as usize - 97] = from_index as u8; } fn swap_char(&mut self, from_char: char, to_char: char) { let from_char_idx: usize = from_char as usize - 97; let to_char_idx: usize = to_char as usize - 97; let temp = self.index_arr[to_char_idx]; self.index_arr[to_char_idx] = self.index_arr[from_char_idx]; self.char_arr[self.index_arr[to_char_idx] as usize] = to_char; self.index_arr[from_char_idx] = temp; self.char_arr[self.index_arr[from_char_idx] as usize] = from_char; } fn print_array(&self) { print!("array is: "); for i in 0..ARR_SIZE { print!("{}", self.char_arr[i]); } println!(""); } fn get_arr_str(&self) -> String { let mut arr_str: String = String::new(); for i in 0..ARR_SIZE { arr_str += &format!("{}", self.char_arr[i]); } return arr_str; } } enum Instruction { Spin(usize), Exchange(usize, usize), Partner(char, char), } fn main() { let total_num_iters = 1000000000; let instructions = get_instructions(); let mut dance = Dance::new(); let mut seen_before: HashSet<String> = HashSet::new(); let mut num_iters: Option<i32> = Option::None; for i in 0..total_num_iters { for instruction in &instructions { match instruction { Instruction::Spin(s) => dance.rotate(*s as u8), Instruction::Exchange(x, y) => dance.swap_index(*x, *y), Instruction::Partner(a, b) => dance.swap_char(*a, *b), } } let this_dance = dance.get_arr_str(); if seen_before.contains(&this_dance) { num_iters = Some(total_num_iters % i); break; } else { seen_before.insert(this_dance); } } println!("num_cycles is: {}", num_iters.unwrap()); dance = Dance::new(); for _ in 0..num_iters.unwrap() { for instruction in &instructions { match instruction { Instruction::Spin(s) => dance.rotate(*s as u8), Instruction::Exchange(x, y) => dance.swap_index(*x, *y), Instruction::Partner(a, b) => dance.swap_char(*a, *b), } } } dance.print_array(); } fn get_instructions() -> Vec<Instruction> { let line = util::read_file_string("input.txt"); let mut instructions = Vec::new(); for inst_str in line.split(",") { let bytes = inst_str.as_bytes(); match bytes[0] as char { 's' => { let num_str = String::from_utf8_lossy(&bytes[1..bytes.len()]).to_string(); instructions.push(Instruction::Spin(num_str.trim().parse().unwrap())); } 'x' => { let (slice1, slice2) = split_input(&bytes[1..bytes.len()]); let str1 = String::from_utf8_lossy(slice1).to_string(); let str2 = String::from_utf8_lossy(slice2).to_string(); instructions.push(Instruction::Exchange( str1.trim().parse().unwrap(), str2.trim().parse().unwrap(), )); } 'p' => instructions.push(Instruction::Partner(bytes[1] as char, bytes[3] as char)), _ => panic!("unknown character: {}", bytes[0]), } } return instructions; } fn split_input(input: &[u8]) -> (&[u8], &[u8]) { let mut i = 0; while i < input.len() { if input[i] == '/' as u8 { break; } i += 1; } return (&input[0..i], &input[i + 1..input.len()]); }
mod util; use std::collections::HashSet; const ARR_SIZE: usize = 16; struct Dance { index_arr: [u8; ARR_SIZE], char_arr: [char; ARR_SIZE], } impl Dance { fn new() -> Dance { Dance { index_arr: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], char_arr: [ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', ], } } fn rotate(&mut self, num: u8) { for i in 0..ARR_SIZE { self.index_arr[i] = (self.index_arr[i] + num) % ARR_SIZE as u8; self.char_arr[self.index_arr[i] as usize] = (i as u8 + 97) as char; } }
fn swap_char(&mut self, from_char: char, to_char: char) { let from_char_idx: usize = from_char as usize - 97; let to_char_idx: usize = to_char as usize - 97; let temp = self.index_arr[to_char_idx]; self.index_arr[to_char_idx] = self.index_arr[from_char_idx]; self.char_arr[self.index_arr[to_char_idx] as usize] = to_char; self.index_arr[from_char_idx] = temp; self.char_arr[self.index_arr[from_char_idx] as usize] = from_char; } fn print_array(&self) { print!("array is: "); for i in 0..ARR_SIZE { print!("{}", self.char_arr[i]); } println!(""); } fn get_arr_str(&self) -> String { let mut arr_str: String = String::new(); for i in 0..ARR_SIZE { arr_str += &format!("{}", self.char_arr[i]); } return arr_str; } } enum Instruction { Spin(usize), Exchange(usize, usize), Partner(char, char), } fn main() { let total_num_iters = 1000000000; let instructions = get_instructions(); let mut dance = Dance::new(); let mut seen_before: HashSet<String> = HashSet::new(); let mut num_iters: Option<i32> = Option::None; for i in 0..total_num_iters { for instruction in &instructions { match instruction { Instruction::Spin(s) => dance.rotate(*s as u8), Instruction::Exchange(x, y) => dance.swap_index(*x, *y), Instruction::Partner(a, b) => dance.swap_char(*a, *b), } } let this_dance = dance.get_arr_str(); if seen_before.contains(&this_dance) { num_iters = Some(total_num_iters % i); break; } else { seen_before.insert(this_dance); } } println!("num_cycles is: {}", num_iters.unwrap()); dance = Dance::new(); for _ in 0..num_iters.unwrap() { for instruction in &instructions { match instruction { Instruction::Spin(s) => dance.rotate(*s as u8), Instruction::Exchange(x, y) => dance.swap_index(*x, *y), Instruction::Partner(a, b) => dance.swap_char(*a, *b), } } } dance.print_array(); } fn get_instructions() -> Vec<Instruction> { let line = util::read_file_string("input.txt"); let mut instructions = Vec::new(); for inst_str in line.split(",") { let bytes = inst_str.as_bytes(); match bytes[0] as char { 's' => { let num_str = String::from_utf8_lossy(&bytes[1..bytes.len()]).to_string(); instructions.push(Instruction::Spin(num_str.trim().parse().unwrap())); } 'x' => { let (slice1, slice2) = split_input(&bytes[1..bytes.len()]); let str1 = String::from_utf8_lossy(slice1).to_string(); let str2 = String::from_utf8_lossy(slice2).to_string(); instructions.push(Instruction::Exchange( str1.trim().parse().unwrap(), str2.trim().parse().unwrap(), )); } 'p' => instructions.push(Instruction::Partner(bytes[1] as char, bytes[3] as char)), _ => panic!("unknown character: {}", bytes[0]), } } return instructions; } fn split_input(input: &[u8]) -> (&[u8], &[u8]) { let mut i = 0; while i < input.len() { if input[i] == '/' as u8 { break; } i += 1; } return (&input[0..i], &input[i + 1..input.len()]); }
fn swap_index(&mut self, from_index: usize, to_index: usize) { let temp = self.char_arr[to_index]; self.char_arr[to_index] = self.char_arr[from_index]; self.index_arr[self.char_arr[to_index] as usize - 97] = to_index as u8; self.char_arr[from_index] = temp; self.index_arr[temp as usize - 97] = from_index as u8; }
function_block-full_function
[ { "content": "fn rotate(num: usize, arr: [char; ARR_SIZE]) -> [char; ARR_SIZE] {\n\n let mut new_arr = ['\\0'; ARR_SIZE];\n\n for i in 0..ARR_SIZE {\n\n let new_index = (i + num) % ARR_SIZE;\n\n new_arr[new_index] = arr[i];\n\n }\n\n return new_arr;\n\n}\n\n\n", "file_path": "day16...
Rust
src/screen/agent_info.rs
timcryt/zemeroth
7b6b51add0f90e9c85e3a9c3a3cd890c9239b4a6
use std::{collections::HashMap, time::Duration}; use gwg::{ graphics::{self, Color, Image, Point2, Text}, Context, }; use heck::TitleCase; use ui::{self, Gui, Widget}; use crate::{ core::battle::{ ability::{Ability, PassiveAbility}, component::{self, Component, ObjType, Prototypes}, }, screen::{self, Screen, StackCommand}, sprite_info::SpriteInfo, utils, ZResult, }; #[derive(Clone, Debug, Default)] struct StaticObjectInfo { meta: Option<component::Meta>, strength: Option<component::Strength>, armor: Option<component::Armor>, agent: Option<component::Agent>, blocker: Option<component::Blocker>, abilities: Option<component::Abilities>, passive_abilities: Option<component::PassiveAbilities>, summoner: Option<component::Summoner>, } impl StaticObjectInfo { fn new(typename: &ObjType, components: &[Component]) -> Self { let mut this = StaticObjectInfo::default(); let name = typename.clone(); this.meta = Some(component::Meta { name }); for component in components { match component.clone() { Component::Strength(c) => this.strength = Some(c), Component::Armor(c) => this.armor = Some(c), Component::Meta(c) => this.meta = Some(c), Component::Agent(c) => this.agent = Some(c), Component::Abilities(c) => this.abilities = Some(c), Component::PassiveAbilities(c) => this.passive_abilities = Some(c), Component::Summoner(c) => this.summoner = Some(c), Component::Blocker(c) => this.blocker = Some(c), Component::BelongsTo(_) | Component::Pos(_) | Component::Effects(_) | Component::Schedule(_) => (), } } this } } type SpritesInfo = HashMap<String, SpriteInfo>; fn load_sprites_info(context: &mut Context) -> ZResult<SpritesInfo> { let info = utils::deserialize_from_file(context, "/sprites.ron")?; Ok(info) } fn agent_image(context: &mut Context, typename: &ObjType) -> ZResult<Box<dyn ui::Widget>> { let h = 0.3; let sprites_info = load_sprites_info(context)?; let sprite_info = sprites_info[&typename.0].clone(); let default_frame = ""; let default_frame_path = &sprite_info.paths[default_frame]; let image = Image::new(context, default_frame_path).expect("Can't load agent's image"); let label = ui::Label::new(context, Box::new(image), h)? .with_color(Color::new(1.0, 1.0, 1.0, 1.0)) .stretchable(true); Ok(Box::new(label)) } #[derive(Clone, Debug)] enum Message { Back, AbilityInfo(Ability), PassiveAbilityInfo(PassiveAbility), } fn info_panel( context: &mut Context, font: graphics::Font, gui: &mut ui::Gui<Message>, prototypes: &Prototypes, typename: &ObjType, ) -> ZResult<Box<dyn ui::Widget>> { let proto = &prototypes.0[&typename]; let info = StaticObjectInfo::new(&typename, proto); let h = utils::line_heights().normal; let space_between_buttons = h / 8.0; let mut layout = Box::new(ui::VLayout::new().stretchable(true)); layout.add(agent_image(context, typename)?); let mut add = |w| layout.add(w); let text_ = |s: &str| Box::new(Text::new((s, font, utils::font_size()))); let label_ = |context: &mut Context, text: &str| -> ZResult<_> { Ok(ui::Label::new(context, text_(text), h)?) }; let label = |context: &mut Context, text: &str| -> ZResult<Box<_>> { Ok(Box::new(label_(context, text)?)) }; let label_s = |context: &mut Context, text: &str| -> ZResult<_> { Ok(Box::new(label_(context, text)?.stretchable(true))) }; let spacer_v = || Box::new(ui::Spacer::new_vertical(h * 0.5)); let spacer_s = || Box::new(ui::Spacer::new_horizontal(h * 0.5).stretchable(true)); let line = |context: &mut Context, arg: &str, val: &str| -> ZResult<_> { let mut line = ui::HLayout::new().stretchable(true); line.add(label(context, arg)?); line.add(spacer_s()); line.add(label(context, val)?); Ok(Box::new(line)) }; let line_i = |context: &mut Context, arg: &str, val: i32| -> ZResult<_> { line(context, arg, &val.to_string()) }; { if let Some(meta) = info.meta { let title = meta.name.0.to_title_case(); add(label_s(context, &format!("~~~ {} ~~~", title))?); add(spacer_v()); } if let Some(strength) = info.strength { add(line_i(context, "strength:", strength.base_strength.0)?); } if let Some(a) = info.agent { add(line_i(context, "attacks:", a.base_attacks.0)?); add(line_i(context, "moves:", a.base_moves.0)?); if a.base_jokers.0 != 0 { add(line_i(context, "jokers:", a.base_jokers.0)?); } if a.reactive_attacks.0 != 0 { add(line_i(context, "reactive attacks:", a.reactive_attacks.0)?); } if a.attack_distance.0 != 1 { add(line_i(context, "attack distance:", a.attack_distance.0)?); } add(line_i(context, "attack strength:", a.attack_strength.0)?); add(line_i(context, "attack accuracy:", a.attack_accuracy.0)?); if a.attack_break.0 > 0 { add(line_i(context, "armor break:", a.attack_break.0)?); } if a.dodge.0 > 0 { add(line_i(context, "dodge:", a.dodge.0)?); } add(line_i(context, "move points:", a.move_points.0)?); } if let Some(armor) = info.armor { let armor = armor.armor.0; if armor != 0 { add(line_i(context, "armor:", armor)?); } } if let Some(blocker) = info.blocker { add(line(context, "weight:", &format!("{}", blocker.weight))?); } if let Some(abilities) = info.abilities { if !abilities.0.is_empty() { add(label_s(context, "~ abilities ~")?); for r_ability in &abilities.0 { let s = r_ability.ability.title(); let cooldown = r_ability.ability.base_cooldown(); let text = format!("{} (cooldown: {}t)", s, cooldown); let mut line_layout = ui::HLayout::new().stretchable(true); line_layout.add(label(context, &text)?); line_layout.add(spacer_s()); let icon = Box::new(graphics::Image::new(context, "/img/icon_info.png")?); let message = Message::AbilityInfo(r_ability.ability.clone()); let button = ui::Button::new(context, icon, h, gui.sender(), message)?; line_layout.add(Box::new(button)); add(Box::new(line_layout)); add(Box::new(ui::Spacer::new_vertical(space_between_buttons))); } } } if let Some(abilities) = info.passive_abilities { if !abilities.0.is_empty() { add(label_s(context, "~ passive abilities ~")?); for &ability in &abilities.0 { let mut line_layout = ui::HLayout::new().stretchable(true); line_layout.add(label(context, &ability.title())?); line_layout.add(spacer_s()); let icon = Box::new(graphics::Image::new(context, "/img/icon_info.png")?); let message = Message::PassiveAbilityInfo(ability); let button = ui::Button::new(context, icon, h, gui.sender(), message)?; line_layout.add(Box::new(button)); add(Box::new(line_layout)); add(Box::new(ui::Spacer::new_vertical(space_between_buttons))); } } } } layout.stretch_to_self(context)?; Ok(layout) } fn button_back( context: &mut Context, font: graphics::Font, gui: &mut ui::Gui<Message>, layout_width: f32, ) -> ZResult<Box<dyn ui::Widget>> { let h = utils::line_heights().normal; let text = Box::new(Text::new(("back", font, utils::font_size()))); let msg = Message::Back; let mut button = ui::Button::new(context, text, h, gui.sender(), msg)?.stretchable(true); button.stretch(context, layout_width / 3.0)?; button.set_stretchable(false); Ok(Box::new(button)) } #[derive(Debug)] pub struct AgentInfo { font: graphics::Font, gui: Gui<Message>, } impl AgentInfo { pub fn new_agent_info( context: &mut Context, prototypes: &Prototypes, typename: &ObjType, ) -> ZResult<Self> { let font = utils::default_font(context); let mut gui = ui::Gui::new(context); let mut layout = ui::VLayout::new(); let h = utils::line_heights().big; layout.add(info_panel(context, font, &mut gui, prototypes, typename)?); layout.add(Box::new(ui::Spacer::new_vertical(h))); layout.add(button_back(context, font, &mut gui, layout.rect().w)?); let layout = utils::add_offsets_and_bg_big(context, Box::new(layout))?; let anchor = ui::Anchor(ui::HAnchor::Middle, ui::VAnchor::Middle); gui.add(&ui::pack(layout), anchor); Ok(Self { font, gui }) } pub fn new_upgrade_info( context: &mut Context, prototypes: &Prototypes, from: &ObjType, to: &ObjType, ) -> ZResult<Self> { let font = utils::default_font(context); let mut gui = ui::Gui::new(context); let mut layout = ui::VLayout::new(); let h = utils::line_heights().big; let line = { let mut line = Box::new(ui::HLayout::new()); let panel_from = info_panel(context, font, &mut gui, prototypes, from)?; let panel_from_height = panel_from.rect().h; line.add(panel_from); line.add(Box::new(ui::Spacer::new_horizontal(h))); let col = { let mut col = Box::new(ui::VLayout::new()); col.add(Box::new(ui::Spacer::new_vertical(panel_from_height * 0.5))); let text = Box::new(Text::new(("=>", font, utils::font_size()))); col.add(Box::new(ui::Label::new(context, text, h)?)); col }; line.add(col); line.add(Box::new(ui::Spacer::new_horizontal(h))); line.add(info_panel(context, font, &mut gui, prototypes, to)?); line }; layout.add(line); layout.add(Box::new(ui::Spacer::new_vertical(h))); layout.add(button_back(context, font, &mut gui, layout.rect().w)?); let layout = utils::add_offsets_and_bg_big(context, Box::new(layout))?; let anchor = ui::Anchor(ui::HAnchor::Middle, ui::VAnchor::Middle); gui.add(&ui::pack(layout), anchor); Ok(Self { font, gui }) } } impl Screen for AgentInfo { fn update(&mut self, _context: &mut Context, _dtime: Duration) -> ZResult<StackCommand> { Ok(StackCommand::None) } fn draw(&self, context: &mut Context) -> ZResult { self.gui.draw(context)?; Ok(()) } fn click(&mut self, context: &mut Context, pos: Point2) -> ZResult<StackCommand> { let message = self.gui.click(pos); match message { Some(Message::Back) => Ok(StackCommand::Pop), Some(Message::AbilityInfo(info)) => { let mut description = info.description(); description.push(format!("Cooldown: {}t", info.base_cooldown())); let screen = screen::GeneralInfo::new(context, &info.title(), &description)?; Ok(StackCommand::PushPopup(Box::new(screen))) } Some(Message::PassiveAbilityInfo(info)) => { let screen = screen::GeneralInfo::new(context, &info.title(), &info.description())?; Ok(StackCommand::PushPopup(Box::new(screen))) } None => Ok(StackCommand::None), } } fn resize(&mut self, aspect_ratio: f32) { self.gui.resize(aspect_ratio); } fn move_mouse(&mut self, _context: &mut Context, pos: Point2) -> ZResult { self.gui.move_mouse(pos); Ok(()) } }
use std::{collections::HashMap, time::Duration}; use gwg::{ graphics::{self, Color, Image, Point2, Text}, Context, }; use heck::TitleCase; use ui::{self, Gui, Widget}; use crate::{ core::battle::{ ability::{Ability, PassiveAbility}, component::{self, Component, ObjType, Prototypes}, }, screen::{self, Screen, StackCommand}, sprite_info::SpriteInfo, utils, ZResult, }; #[derive(Clone, Debug, Default)] struct StaticObjectInfo { meta: Option<component::Meta>, strength: Option<component::Strength>, armor: Option<component::Armor>, agent: Option<component::Agent>, blocker: Option<component::Blocker>, abilities: Option<component::Abilities>, passive_abilities: Option<component::PassiveAbilities>, summoner: Option<component::Summoner>, } impl StaticObjectInfo { fn new(typename: &ObjType, components: &[Component]) -> Self { let mut this = StaticObjectInfo::default(); let name = typename.clone(); this.meta = Some(component::Meta { name }); for component in components { match component.clone() { Component::Strength(c) => this.strength = Some(c), Component::Armor(c) => this.armor = Some(c), Component::Meta(c) => this.meta = Some(c), Component::Agent(c) => this.agent = Some(c), Component::Abilities(c) => this.abilities = Some(c), Component::PassiveAbilities(c) => this.passive_abilities = Some(c), Component::Summoner(c) => this.summoner = Some(c), Component::Blocker(c) => this.blocker = Some(c), Component::BelongsTo(_) | Component::Pos(_) | Component::Effects(_) | Component::Schedule(_) => (), } } this } } type SpritesInfo = HashMap<String, SpriteInfo>; fn load_sprites_info(context: &mut Context) -> ZResult<SpritesInfo> { let info = utils::deserialize_from_file(context, "/sprites.ron")?; Ok(info) } fn agent_image(context: &mut Context, typename: &ObjType) -> ZResult<Box<dyn ui::Widget>> { let h = 0.3; let sprites_info = load_sprites_info(context)?; let sprite_info = sprites_info[&typename.0].clone(); let default_frame = ""; let default_frame_path = &sprite_info.paths[default_frame]; let image = Image::new(context, default_frame_path).expect("Can't load agent's image"); let label = ui::Label::new(context, Box::new(image), h)? .with_color(Color::new(1.0, 1.0, 1.0, 1.0)) .stretchable(true); Ok(Box::new(label)) } #[derive(Clone, Debug)] enum Message { Back, AbilityInfo(Ability), PassiveAbilityInfo(PassiveAbility), } fn info_panel( context: &mut Context, font: graphics::Font, gui: &mut ui::Gui<Message>, prototypes: &Prototypes, typename: &ObjType, ) -> ZResult<Box<dyn ui::Widget>> { let proto = &prototypes.0[&typename]; let info = StaticObjectInfo::new(&typename, proto); let h = utils::line_heights().normal; let space_between_buttons = h / 8.0; let mut layout = Box::new(ui::VLayout::new().stretchable(true)); layout.add(agent_image(context, typename)?); let mut add = |w| layout.add(w); let text_ = |s: &str| Box::new(Text::new((s, font, utils::font_size()))); let label_ = |context: &mut Context, text: &str| -> ZResult<_> { Ok(ui::Label::new(context, text_(text), h)?) }; let label = |context: &mut Context, text: &str| -> ZResult<Box<_>> { Ok(Box::new(label_(context, text)?)) }; let label_s = |context: &mut Context, text: &str| -> ZResult<_> { Ok(Box::new(label_(context, text)?.stretchable(true))) }; let spacer_v = || Box::new(ui::Spacer::new_vertical(h * 0.5)); let spacer_s = || Box::new(ui::Spacer::new_horizontal(h * 0.5).stretchable(true)); let line = |context: &mut Context, arg: &str, val: &str| -> ZResult<_> { let mut line = ui::HLayout::new().stretchable(true); line.add(label(context, arg)?); line.add(spacer_s()); line.add(label(context, val)?); Ok(Box::new(line)) }; let line_i = |context: &mut Context, arg: &str, val: i32| -> ZResult<_> { line(context, arg, &val.to_string()) }; { if let Some(meta) = info.meta { let title = meta.name.0.to_title_case(); add(label_s(context, &format!("~~~ {} ~~~", title))?); add(spacer_v()); } if let Some(strength) = info.strength { add(line_i(context, "strength:", strength.base_strength.0)?); } if let Some(a) = info.agent { add(line_i(context, "attacks:", a.base_attacks.0)?); add(line_i(context, "moves:", a.base_moves.0)?); if a.base_jokers.0 != 0 { add(line_i(context, "jokers:", a.base_jokers.0)?); } if a.reactive_attacks.0 != 0 { add(line_i(context, "reactive attacks:", a.reactive_attacks.0)?); } if a.attack_distance.0 != 1 { add(line_i(context, "attack distance:", a.attack_distance.0)?); } add(line_i(context, "attack strength:", a.attack_strength.0)?); add(line_i(context, "attack accuracy:", a.attack_accuracy.0)?); if a.attack_break.0 > 0 { add(line_i(context, "armor break:", a.attack_break.0)?); } if a.dodge.0 > 0 { add(line_i(context, "dodge:", a.dodge.0)?); } add(line_i(context, "move points:", a.move_points.0)?); } if let Some(armor) = info.armor { let armor = armor.armor.0; if armor != 0 { add(line_i(context, "armor:", armor)?); } } if let Some(blocker) = info.blocker { add(line(context, "weight:", &format!("{}", blocker.weight))?); } if let Some(abilities) = info.abilities { if !abilities.0.is_empty() { add(label_s(context, "~ abilities ~")?); for r_ability in &abilities.0 { let s = r_ability.ability.title(); let cooldown = r_ability.ability.base_cooldown(); let text = format!("{} (cooldown: {}t)", s, cooldown); let mut line_layout = ui::HLayout::new().stretchable(true); line_layout.add(label(context, &text)?); line_layout.add(spacer_s()); let icon = Box::new(graphics::Image::new(context, "/img/icon_info.png")?); let message = Message::AbilityInfo(r_ability.ability.clone()); let button = ui::Button::new(context, icon, h, gui.sender(), message)?; line_layout.add(Box::new(button)); add(Box::new(line_layout)); add(Box::new(ui::Spacer::new_vertical(space_between_buttons))); } } } if let Some(abilities) = info.passive_abilities { if !abilities.0.is_empty() { add(label_s(context, "~ passive abilities ~")?); for &ability in &abilities.0 { let mut line_layout = ui::HLayout::new().stretchable(true); line_layout.add(label(context, &ability.title())?); line_layout.add(spacer_s()); let icon = Box::new(graphics::Image::new(context, "/img/icon_info.png")?); let message = Message::PassiveAbilityInfo(ability); let button = ui::Button::new(context, icon, h, gui.sender(), message)?; line_layout.add(Box::new(button)); add(Box::new(line_layout)); add(Box::new(ui::Spacer::new_vertical(space_between_buttons))); } } } } layout.stretch_to_self(context)?; Ok(layout) } fn button_back( context: &mut Context, font: graphics::Font, gui: &mut ui::Gui<Message>, layout_width: f32, ) -> ZResult<Box<dyn ui::Widget>> { let h = utils::line_heights().normal; let text = Box::new(Text::new(("back", font, utils::font_size()))); let msg = Message::Back; let mut button = ui::Button::new(context, text, h, gui.sender(), msg)?.stretchable(true); button.stretch(context, layout_width / 3.0)?; button.set_stretchable(false); Ok(Box::new(button)) } #[derive(Debug)] pub struct AgentInfo { font: graphics::Font, gui: Gui<Message>, } impl AgentInfo {
pub fn new_upgrade_info( context: &mut Context, prototypes: &Prototypes, from: &ObjType, to: &ObjType, ) -> ZResult<Self> { let font = utils::default_font(context); let mut gui = ui::Gui::new(context); let mut layout = ui::VLayout::new(); let h = utils::line_heights().big; let line = { let mut line = Box::new(ui::HLayout::new()); let panel_from = info_panel(context, font, &mut gui, prototypes, from)?; let panel_from_height = panel_from.rect().h; line.add(panel_from); line.add(Box::new(ui::Spacer::new_horizontal(h))); let col = { let mut col = Box::new(ui::VLayout::new()); col.add(Box::new(ui::Spacer::new_vertical(panel_from_height * 0.5))); let text = Box::new(Text::new(("=>", font, utils::font_size()))); col.add(Box::new(ui::Label::new(context, text, h)?)); col }; line.add(col); line.add(Box::new(ui::Spacer::new_horizontal(h))); line.add(info_panel(context, font, &mut gui, prototypes, to)?); line }; layout.add(line); layout.add(Box::new(ui::Spacer::new_vertical(h))); layout.add(button_back(context, font, &mut gui, layout.rect().w)?); let layout = utils::add_offsets_and_bg_big(context, Box::new(layout))?; let anchor = ui::Anchor(ui::HAnchor::Middle, ui::VAnchor::Middle); gui.add(&ui::pack(layout), anchor); Ok(Self { font, gui }) } } impl Screen for AgentInfo { fn update(&mut self, _context: &mut Context, _dtime: Duration) -> ZResult<StackCommand> { Ok(StackCommand::None) } fn draw(&self, context: &mut Context) -> ZResult { self.gui.draw(context)?; Ok(()) } fn click(&mut self, context: &mut Context, pos: Point2) -> ZResult<StackCommand> { let message = self.gui.click(pos); match message { Some(Message::Back) => Ok(StackCommand::Pop), Some(Message::AbilityInfo(info)) => { let mut description = info.description(); description.push(format!("Cooldown: {}t", info.base_cooldown())); let screen = screen::GeneralInfo::new(context, &info.title(), &description)?; Ok(StackCommand::PushPopup(Box::new(screen))) } Some(Message::PassiveAbilityInfo(info)) => { let screen = screen::GeneralInfo::new(context, &info.title(), &info.description())?; Ok(StackCommand::PushPopup(Box::new(screen))) } None => Ok(StackCommand::None), } } fn resize(&mut self, aspect_ratio: f32) { self.gui.resize(aspect_ratio); } fn move_mouse(&mut self, _context: &mut Context, pos: Point2) -> ZResult { self.gui.move_mouse(pos); Ok(()) } }
pub fn new_agent_info( context: &mut Context, prototypes: &Prototypes, typename: &ObjType, ) -> ZResult<Self> { let font = utils::default_font(context); let mut gui = ui::Gui::new(context); let mut layout = ui::VLayout::new(); let h = utils::line_heights().big; layout.add(info_panel(context, font, &mut gui, prototypes, typename)?); layout.add(Box::new(ui::Spacer::new_vertical(h))); layout.add(button_back(context, font, &mut gui, layout.rect().w)?); let layout = utils::add_offsets_and_bg_big(context, Box::new(layout))?; let anchor = ui::Anchor(ui::HAnchor::Middle, ui::VAnchor::Middle); gui.add(&ui::pack(layout), anchor); Ok(Self { font, gui }) }
function_block-full_function
[ { "content": "fn label(context: &mut Context, font: Font, text: &str) -> ZResult<Box<dyn ui::Widget>> {\n\n let text = Box::new(Text::new((text, font, FONT_SIZE)));\n\n Ok(Box::new(ui::Label::new(context, text, line_height())?))\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct Campaign {\n\n state: State,\n\...
Rust
git-packetline/src/read/async_io.rs
mellowagain/gitoxide
dc58eca510e5a067acdeaad4b595a34b4598a0cd
use std::io; use bstr::ByteSlice; use futures_io::AsyncRead; use futures_lite::AsyncReadExt; use crate::{ decode, read::{ExhaustiveOutcome, WithSidebands}, PacketLine, StreamingPeekableIter, MAX_LINE_LEN, U16_HEX_BYTES, }; impl<T> StreamingPeekableIter<T> where T: AsyncRead + Unpin, { #[allow(clippy::needless_lifetimes)] async fn read_line_inner<'a>( reader: &mut T, buf: &'a mut Vec<u8>, ) -> io::Result<Result<PacketLine<'a>, decode::Error>> { let (hex_bytes, data_bytes) = buf.split_at_mut(4); reader.read_exact(hex_bytes).await?; let num_data_bytes = match decode::hex_prefix(hex_bytes) { Ok(decode::PacketLineOrWantedSize::Line(line)) => return Ok(Ok(line)), Ok(decode::PacketLineOrWantedSize::Wanted(additional_bytes)) => additional_bytes as usize, Err(err) => return Ok(Err(err)), }; let (data_bytes, _) = data_bytes.split_at_mut(num_data_bytes); reader.read_exact(data_bytes).await?; match decode::to_data_line(data_bytes) { Ok(line) => Ok(Ok(line)), Err(err) => Ok(Err(err)), } } async fn read_line_inner_exhaustive<'a>( reader: &mut T, buf: &'a mut Vec<u8>, delimiters: &[PacketLine<'static>], fail_on_err_lines: bool, buf_resize: bool, ) -> ExhaustiveOutcome<'a> { ( false, None, Some(match Self::read_line_inner(reader, buf).await { Ok(Ok(line)) => { if delimiters.contains(&line) { let stopped_at = delimiters.iter().find(|l| **l == line).cloned(); buf.clear(); return (true, stopped_at, None); } else if fail_on_err_lines { if let Some(err) = line.check_error() { let err = err.0.as_bstr().to_string(); buf.clear(); return (true, None, Some(Err(io::Error::new(io::ErrorKind::Other, err)))); } } let len = line .as_slice() .map(|s| s.len() + U16_HEX_BYTES) .unwrap_or(U16_HEX_BYTES); if buf_resize { buf.resize(len, 0); } Ok(Ok(crate::decode(buf).expect("only valid data here"))) } Ok(Err(err)) => { buf.clear(); Ok(Err(err)) } Err(err) => { buf.clear(); Err(err) } }), ) } pub async fn read_line(&mut self) -> Option<io::Result<Result<PacketLine<'_>, decode::Error>>> { if self.is_done { return None; } if !self.peek_buf.is_empty() { std::mem::swap(&mut self.peek_buf, &mut self.buf); self.peek_buf.clear(); Some(Ok(Ok(crate::decode(&self.buf).expect("only valid data in peek buf")))) } else { if self.buf.len() != MAX_LINE_LEN { self.buf.resize(MAX_LINE_LEN, 0); } let (is_done, stopped_at, res) = Self::read_line_inner_exhaustive( &mut self.read, &mut self.buf, self.delimiters, self.fail_on_err_lines, false, ) .await; self.is_done = is_done; self.stopped_at = stopped_at; res } } pub async fn peek_line(&mut self) -> Option<io::Result<Result<PacketLine<'_>, decode::Error>>> { if self.is_done { return None; } if self.peek_buf.is_empty() { self.peek_buf.resize(MAX_LINE_LEN, 0); let (is_done, stopped_at, res) = Self::read_line_inner_exhaustive( &mut self.read, &mut self.peek_buf, self.delimiters, self.fail_on_err_lines, true, ) .await; self.is_done = is_done; self.stopped_at = stopped_at; res } else { Some(Ok(Ok(crate::decode(&self.peek_buf).expect("only valid data here")))) } } pub fn as_read(&mut self) -> WithSidebands<'_, T, fn(bool, &[u8])> { WithSidebands::new(self) } pub fn as_read_with_sidebands<F: FnMut(bool, &[u8]) + Unpin>( &mut self, handle_progress: F, ) -> WithSidebands<'_, T, F> { WithSidebands::with_progress_handler(self, handle_progress) } pub fn as_read_without_sidebands<F: FnMut(bool, &[u8]) + Unpin>(&mut self) -> WithSidebands<'_, T, F> { WithSidebands::without_progress_handler(self) } }
use std::io; use bstr::ByteSlice; use futures_io::AsyncRead; use futures_lite::AsyncReadExt; use crate::{ decode, read::{ExhaustiveOutcome, WithSidebands}, PacketLine, StreamingPeekableIter, MAX_LINE_LEN, U16_HEX_BYTES, }; impl<T> StreamingPeekableIter<T> where T: AsyncRead + Unpin, { #[allow(clippy::needless_lifetimes)] async fn read_line_inner<'a>( reader: &mut T, buf: &'a mut Vec<u8>, ) -> io::Result<Result<PacketLine<'a>, decode::Error>> { let (hex_bytes, data_bytes) = buf.split_at_mut(4); reader.read_exact(hex_bytes).await?; let num_data_bytes = match decode::hex_prefix(hex_bytes) { Ok(decode::PacketLineOrWantedSize::Line(line)) => return Ok(Ok(line)), Ok(decode::PacketLineOrWantedSize::Wanted(additional_bytes)) => additional_bytes as usize, Err(err) => return Ok(Err(err)), }; let (data_bytes, _) = data_bytes.split_at_mut(num_data_bytes); reader.read_exact(data_bytes).await?; match decode::to_data_line(data_bytes) { Ok(line) => Ok(Ok(line)), Err(err) => Ok(Err(err)), } } async fn read_line_inner_exhaustive<'a>( reader: &mut T, buf: &'a mut Vec<u8>, delimiters: &[PacketLine<'static>], fail_on_err_lines: bool, buf_resize: bool, ) -> ExhaustiveOutcome<'a> { ( false, None, Some(match Self::read_line_inner(reader, buf).await { Ok(Ok(line)) => { if delimiters.contains(&line) { let stopped_at = delimiters.iter().find(|l| **l == line).cloned(); buf.clear(); return (true, stopped_at, None); } else if fail_on_err_lines { if let Some(err) = line.check_error() { let err = err.0.as_bstr().to_string(); buf.clear(); return (true, None, Some(Err(io::Error::new(io::ErrorKind::Other, err)))); } }
if buf_resize { buf.resize(len, 0); } Ok(Ok(crate::decode(buf).expect("only valid data here"))) } Ok(Err(err)) => { buf.clear(); Ok(Err(err)) } Err(err) => { buf.clear(); Err(err) } }), ) } pub async fn read_line(&mut self) -> Option<io::Result<Result<PacketLine<'_>, decode::Error>>> { if self.is_done { return None; } if !self.peek_buf.is_empty() { std::mem::swap(&mut self.peek_buf, &mut self.buf); self.peek_buf.clear(); Some(Ok(Ok(crate::decode(&self.buf).expect("only valid data in peek buf")))) } else { if self.buf.len() != MAX_LINE_LEN { self.buf.resize(MAX_LINE_LEN, 0); } let (is_done, stopped_at, res) = Self::read_line_inner_exhaustive( &mut self.read, &mut self.buf, self.delimiters, self.fail_on_err_lines, false, ) .await; self.is_done = is_done; self.stopped_at = stopped_at; res } } pub async fn peek_line(&mut self) -> Option<io::Result<Result<PacketLine<'_>, decode::Error>>> { if self.is_done { return None; } if self.peek_buf.is_empty() { self.peek_buf.resize(MAX_LINE_LEN, 0); let (is_done, stopped_at, res) = Self::read_line_inner_exhaustive( &mut self.read, &mut self.peek_buf, self.delimiters, self.fail_on_err_lines, true, ) .await; self.is_done = is_done; self.stopped_at = stopped_at; res } else { Some(Ok(Ok(crate::decode(&self.peek_buf).expect("only valid data here")))) } } pub fn as_read(&mut self) -> WithSidebands<'_, T, fn(bool, &[u8])> { WithSidebands::new(self) } pub fn as_read_with_sidebands<F: FnMut(bool, &[u8]) + Unpin>( &mut self, handle_progress: F, ) -> WithSidebands<'_, T, F> { WithSidebands::with_progress_handler(self, handle_progress) } pub fn as_read_without_sidebands<F: FnMut(bool, &[u8]) + Unpin>(&mut self) -> WithSidebands<'_, T, F> { WithSidebands::without_progress_handler(self) } }
let len = line .as_slice() .map(|s| s.len() + U16_HEX_BYTES) .unwrap_or(U16_HEX_BYTES);
assignment_statement
[ { "content": "fn into_io_err(err: Error) -> io::Error {\n\n io::Error::new(io::ErrorKind::Other, err)\n\n}\n\n\n\nimpl<W: AsyncWrite + Unpin> AsyncWrite for LineWriter<'_, W> {\n\n fn poll_write(self: Pin<&mut Self>, cx: &mut Context<'_>, data: &[u8]) -> Poll<io::Result<usize>> {\n\n use futures_li...
Rust
src/dnsmx.rs
oxidizers/drdns
98c1153a09642c2a5d8d2ed77ef7d9429d94995a
use buffer::{Buffer, STDOUT_BUFFER}; use byte; use dns; use libc; use stralloc::StrAlloc; use strerr::{StrErr, STRERR_SYS}; use uint16; use ulong; #[no_mangle] pub unsafe extern "C" fn nomem() { StrErr::die( 111i32, (*b"dnsmx: fatal: \0").as_ptr(), (*b"out of memory\0").as_ptr(), 0i32 as (*const u8), 0i32 as (*const u8), 0i32 as (*const u8), 0i32 as (*const u8), 0i32 as (*const StrErr), ); } static mut seed: [u8; 128] = [0u8; 128]; static mut fqdn: StrAlloc = StrAlloc { s: 0 as (*mut u8), len: 0u32, a: 0u32, }; static mut q: *mut u8 = 0 as (*mut u8); static mut out: StrAlloc = StrAlloc { s: 0 as (*mut u8), len: 0u32, a: 0u32, }; #[no_mangle] pub static mut strnum: [u8; 40] = [0u8; 40]; fn main() { use std::os::unix::ffi::OsStringExt; let mut argv_storage = ::std::env::args_os() .map(|str| { let mut vec = str.into_vec(); vec.push(b'\0'); vec }) .collect::<Vec<_>>(); let mut argv = argv_storage .iter_mut() .map(|vec| vec.as_mut_ptr()) .chain(Some(::std::ptr::null_mut())) .collect::<Vec<_>>(); let ret = unsafe { _c_main(argv_storage.len() as (i32), argv.as_mut_ptr()) }; ::std::process::exit(ret); } #[no_mangle] pub unsafe extern "C" fn _c_main(mut argc: i32, mut argv: *mut *mut u8) -> i32 { let mut i: i32; let mut j: i32; let mut pref: u16; dns::random::init(seed.as_mut_ptr() as (*const u8)); if !(*argv).is_null() { argv = argv.offset(1isize); } 'loop2: loop { if (*argv).is_null() { break; } if StrAlloc::copys(&mut fqdn as (*mut StrAlloc), *argv as (*const u8)) == 0 { nomem(); } if dns::mx::mx( &mut out as (*mut StrAlloc), &mut fqdn as (*mut StrAlloc) as (*const StrAlloc), ) == -1i32 { StrErr::die( 111i32, (*b"dnsmx: fatal: \0").as_ptr(), (*b"unable to find MX records for \0").as_ptr(), *argv as (*const u8), (*b": \0").as_ptr(), 0i32 as (*const u8), 0i32 as (*const u8), &mut STRERR_SYS as (*mut StrErr) as (*const StrErr), ); } if out.len == 0 { if dns::domain::fromdot( &mut q as (*mut *mut u8), *argv as (*const u8), libc::strlen(*argv as *const i8) as u32, ) == 0 { nomem(); } if StrAlloc::copys(&mut out as (*mut StrAlloc), (*b"0 \0").as_ptr()) == 0 { nomem(); } if dns::domain::todot_cat(&mut out as (*mut StrAlloc), q as (*const u8)) == 0 { nomem(); } if StrAlloc::cats(&mut out as (*mut StrAlloc), (*b"\n\0").as_ptr()) == 0 { nomem(); } Buffer::put(STDOUT_BUFFER.as_mut_ptr(), out.s as (*const u8), out.len); } else { i = 0i32; 'loop10: loop { if !((i + 2i32) as (u32) < out.len) { break; } j = byte::chr( out.s.offset(i as (isize)).offset(2isize), out.len.wrapping_sub(i as (u32)).wrapping_sub(2u32), 0i32, ) as (i32); uint16::unpack_big( out.s.offset(i as (isize)) as (*const u8), &mut pref as (*mut u16), ); Buffer::put( STDOUT_BUFFER.as_mut_ptr(), strnum.as_mut_ptr() as (*const u8), ulong::fmt(strnum.as_mut_ptr(), pref as (usize)), ); Buffer::puts(STDOUT_BUFFER.as_mut_ptr(), (*b" \0").as_ptr()); Buffer::put( STDOUT_BUFFER.as_mut_ptr(), out.s.offset(i as (isize)).offset(2isize) as (*const u8), j as (u32), ); Buffer::puts(STDOUT_BUFFER.as_mut_ptr(), (*b"\n\0").as_ptr()); i = i + (j + 3i32); } } argv = argv.offset(1isize); } Buffer::flush(STDOUT_BUFFER.as_mut_ptr()); libc::_exit(0i32); }
use buffer::{Buffer, STDOUT_BUFFER}; use byte; use dns; use libc; use stralloc::StrAlloc; use strerr::{StrErr, STRERR_SYS}; use uint16; use ulong; #[no_mangle]
static mut seed: [u8; 128] = [0u8; 128]; static mut fqdn: StrAlloc = StrAlloc { s: 0 as (*mut u8), len: 0u32, a: 0u32, }; static mut q: *mut u8 = 0 as (*mut u8); static mut out: StrAlloc = StrAlloc { s: 0 as (*mut u8), len: 0u32, a: 0u32, }; #[no_mangle] pub static mut strnum: [u8; 40] = [0u8; 40]; fn main() { use std::os::unix::ffi::OsStringExt; let mut argv_storage = ::std::env::args_os() .map(|str| { let mut vec = str.into_vec(); vec.push(b'\0'); vec }) .collect::<Vec<_>>(); let mut argv = argv_storage .iter_mut() .map(|vec| vec.as_mut_ptr()) .chain(Some(::std::ptr::null_mut())) .collect::<Vec<_>>(); let ret = unsafe { _c_main(argv_storage.len() as (i32), argv.as_mut_ptr()) }; ::std::process::exit(ret); } #[no_mangle] pub unsafe extern "C" fn _c_main(mut argc: i32, mut argv: *mut *mut u8) -> i32 { let mut i: i32; let mut j: i32; let mut pref: u16; dns::random::init(seed.as_mut_ptr() as (*const u8)); if !(*argv).is_null() { argv = argv.offset(1isize); } 'loop2: loop { if (*argv).is_null() { break; } if StrAlloc::copys(&mut fqdn as (*mut StrAlloc), *argv as (*const u8)) == 0 { nomem(); } if dns::mx::mx( &mut out as (*mut StrAlloc), &mut fqdn as (*mut StrAlloc) as (*const StrAlloc), ) == -1i32 { StrErr::die( 111i32, (*b"dnsmx: fatal: \0").as_ptr(), (*b"unable to find MX records for \0").as_ptr(), *argv as (*const u8), (*b": \0").as_ptr(), 0i32 as (*const u8), 0i32 as (*const u8), &mut STRERR_SYS as (*mut StrErr) as (*const StrErr), ); } if out.len == 0 { if dns::domain::fromdot( &mut q as (*mut *mut u8), *argv as (*const u8), libc::strlen(*argv as *const i8) as u32, ) == 0 { nomem(); } if StrAlloc::copys(&mut out as (*mut StrAlloc), (*b"0 \0").as_ptr()) == 0 { nomem(); } if dns::domain::todot_cat(&mut out as (*mut StrAlloc), q as (*const u8)) == 0 { nomem(); } if StrAlloc::cats(&mut out as (*mut StrAlloc), (*b"\n\0").as_ptr()) == 0 { nomem(); } Buffer::put(STDOUT_BUFFER.as_mut_ptr(), out.s as (*const u8), out.len); } else { i = 0i32; 'loop10: loop { if !((i + 2i32) as (u32) < out.len) { break; } j = byte::chr( out.s.offset(i as (isize)).offset(2isize), out.len.wrapping_sub(i as (u32)).wrapping_sub(2u32), 0i32, ) as (i32); uint16::unpack_big( out.s.offset(i as (isize)) as (*const u8), &mut pref as (*mut u16), ); Buffer::put( STDOUT_BUFFER.as_mut_ptr(), strnum.as_mut_ptr() as (*const u8), ulong::fmt(strnum.as_mut_ptr(), pref as (usize)), ); Buffer::puts(STDOUT_BUFFER.as_mut_ptr(), (*b" \0").as_ptr()); Buffer::put( STDOUT_BUFFER.as_mut_ptr(), out.s.offset(i as (isize)).offset(2isize) as (*const u8), j as (u32), ); Buffer::puts(STDOUT_BUFFER.as_mut_ptr(), (*b"\n\0").as_ptr()); i = i + (j + 3i32); } } argv = argv.offset(1isize); } Buffer::flush(STDOUT_BUFFER.as_mut_ptr()); libc::_exit(0i32); }
pub unsafe extern "C" fn nomem() { StrErr::die( 111i32, (*b"dnsmx: fatal: \0").as_ptr(), (*b"out of memory\0").as_ptr(), 0i32 as (*const u8), 0i32 as (*const u8), 0i32 as (*const u8), 0i32 as (*const u8), 0i32 as (*const StrErr), ); }
function_block-full_function
[ { "content": "//! `uint16.rs`: network byte order (i.e. big endian) conversions\n\n//!\n\n//! This should probably be replaced by the byteorder crate\n\n\n\npub unsafe fn pack(s: *mut u8, u: u16) {\n\n *s.offset(0isize) = (u as (i32) & 255i32) as (u8);\n\n *s.offset(1isize) = (u as (i32) >> 8i32) as (u8);...
Rust
src/lisp_subr.rs
tjshaffer21/rustl
31c786c32b35f364a2b2c282874c2bda81fe01ef
use std::rc::Rc; use lisp_types::{ LispResult, LispParam, sexpr::*, errors::* }; use environment::Env; pub fn atom<'a>(args_ptr: &LispParam<'a>, env: &'a Env<'a>) -> LispResult<'a> { let args = args_ptr.borrow(); let len = args.len(); if len == 0 { Err(LispError::TooFewArguments) } else if len > 1 { Err(LispError::TooManyArguments) } else { match args.front().unwrap() { SExpr::Atom(_) => Ok(env.get(&"t").unwrap()), _ => Ok(env.get(&"nil").unwrap()), } } } pub fn eq<'a>(args_ptr: &LispParam<'a>, env: &'a Env<'a>) -> LispResult<'a> { let mut args = args_ptr.borrow_mut(); if args.len() > 2 { return Err(LispError::TooManyArguments) } if let Some(x) = args.pop_front() { if let Some(y) = args.pop_front() { if x == y { Ok(env.get(&"t").unwrap()) } else { Ok(env.get(&"nil").unwrap()) } } else { Err(LispError::TooFewArguments) } } else { Err(LispError::TooFewArguments) } } pub fn car<'a>(args_ptr: &LispParam<'a>, _env: &Env) -> LispResult<'a> { let mut args = args_ptr.borrow_mut(); let len = args.len(); if len == 0 { Err(LispError::TooFewArguments) } else if len > 1 { Err(LispError::TooManyArguments) } else { if let Some(val) = args.pop_front() { match val { SExpr::Cons(mut v) => { if let Some(r) = v.pop_front() { Ok(Rc::new(r)) } else { Err(LispError::InvalidArgument) } }, _ => Err(LispError::InvalidArgument), } } else { Err(LispError::InvalidArgument) } } } pub fn cdr<'a>(args_ptr: &LispParam<'a>, _env: &Env) -> LispResult<'a> { let mut args = args_ptr.borrow_mut(); let len = args.len(); if len == 0 { Err(LispError::TooFewArguments) } else if len > 1 { Err(LispError::TooManyArguments) } else { let arg = args.pop_front(); if let Some(val) = arg { match val { SExpr::Cons(mut v) => { v.pop_front(); Ok(Rc::new(create_sexpr!(cons v))) }, _ => Err(LispError::InvalidArgument) } } else { Err(LispError::InvalidArgument) } } } pub fn cons<'a>(args_ptr: &LispParam<'a>, _env: &Env) -> LispResult<'a> { let mut args = args_ptr.borrow_mut(); let len = args.len(); if len <= 1 { Err(LispError::TooFewArguments) } else if len > 2 { Err(LispError::TooManyArguments) } else { if let Some(elov) = args.pop_front() { if let Some(eltv) = args.pop_front() { let mut new_list = std::collections::LinkedList::new(); new_list.push_front(eltv); new_list.push_front(elov); Ok(Rc::new(create_sexpr!(cons new_list))) } else { Err(LispError::InvalidArgument) } } else { Err(LispError::InvalidArgument) } } } pub fn add<'a>(args_ptr: &LispParam<'a>, _env: &Env) -> LispResult<'a> { let args = args_ptr.borrow_mut(); let mut sum: f64 = 0.0; let mut float_flag = false; for i in args.iter() { match i { SExpr::Atom(Atom::Number(Number::Integer(i))) => sum += *i as f64, SExpr::Atom(Atom::Number(Number::FloatingPoint(f))) => { float_flag = true; sum += *f }, _ => return Err(LispError::InvalidArgument), } } if float_flag { Ok(Rc::new(create_sexpr!(float sum))) } else { Ok(Rc::new(create_sexpr!(int sum as i64))) } }
use std::rc::Rc; use lisp_types::{ LispResult, LispParam, sexpr::*, errors::* }; use environment::Env; pub fn atom<'a>(args_ptr: &LispParam<'a>, env: &'a Env<'a>) -> LispResult<'a> { let args = args_ptr.borrow(); let len = args.len(); if len == 0 { Err(LispError::TooFewArguments) }
pub fn eq<'a>(args_ptr: &LispParam<'a>, env: &'a Env<'a>) -> LispResult<'a> { let mut args = args_ptr.borrow_mut(); if args.len() > 2 { return Err(LispError::TooManyArguments) } if let Some(x) = args.pop_front() { if let Some(y) = args.pop_front() { if x == y { Ok(env.get(&"t").unwrap()) } else { Ok(env.get(&"nil").unwrap()) } } else { Err(LispError::TooFewArguments) } } else { Err(LispError::TooFewArguments) } } pub fn car<'a>(args_ptr: &LispParam<'a>, _env: &Env) -> LispResult<'a> { let mut args = args_ptr.borrow_mut(); let len = args.len(); if len == 0 { Err(LispError::TooFewArguments) } else if len > 1 { Err(LispError::TooManyArguments) } else { if let Some(val) = args.pop_front() { match val { SExpr::Cons(mut v) => { if let Some(r) = v.pop_front() { Ok(Rc::new(r)) } else { Err(LispError::InvalidArgument) } }, _ => Err(LispError::InvalidArgument), } } else { Err(LispError::InvalidArgument) } } } pub fn cdr<'a>(args_ptr: &LispParam<'a>, _env: &Env) -> LispResult<'a> { let mut args = args_ptr.borrow_mut(); let len = args.len(); if len == 0 { Err(LispError::TooFewArguments) } else if len > 1 { Err(LispError::TooManyArguments) } else { let arg = args.pop_front(); if let Some(val) = arg { match val { SExpr::Cons(mut v) => { v.pop_front(); Ok(Rc::new(create_sexpr!(cons v))) }, _ => Err(LispError::InvalidArgument) } } else { Err(LispError::InvalidArgument) } } } pub fn cons<'a>(args_ptr: &LispParam<'a>, _env: &Env) -> LispResult<'a> { let mut args = args_ptr.borrow_mut(); let len = args.len(); if len <= 1 { Err(LispError::TooFewArguments) } else if len > 2 { Err(LispError::TooManyArguments) } else { if let Some(elov) = args.pop_front() { if let Some(eltv) = args.pop_front() { let mut new_list = std::collections::LinkedList::new(); new_list.push_front(eltv); new_list.push_front(elov); Ok(Rc::new(create_sexpr!(cons new_list))) } else { Err(LispError::InvalidArgument) } } else { Err(LispError::InvalidArgument) } } } pub fn add<'a>(args_ptr: &LispParam<'a>, _env: &Env) -> LispResult<'a> { let args = args_ptr.borrow_mut(); let mut sum: f64 = 0.0; let mut float_flag = false; for i in args.iter() { match i { SExpr::Atom(Atom::Number(Number::Integer(i))) => sum += *i as f64, SExpr::Atom(Atom::Number(Number::FloatingPoint(f))) => { float_flag = true; sum += *f }, _ => return Err(LispError::InvalidArgument), } } if float_flag { Ok(Rc::new(create_sexpr!(float sum))) } else { Ok(Rc::new(create_sexpr!(int sum as i64))) } }
else if len > 1 { Err(LispError::TooManyArguments) } else { match args.front().unwrap() { SExpr::Atom(_) => Ok(env.get(&"t").unwrap()), _ => Ok(env.get(&"nil").unwrap()), } } }
function_block-function_prefix_line
[]
Rust
src/parse/header.rs
MikuroXina/bms-rs
16f5301fe8847a6aa6791dd7e1a3308204172cf4
use std::{collections::HashMap, fmt::Debug, path::PathBuf}; use super::{ParseError, Result}; use crate::lex::{command::*, token::Token}; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum LnType { Rdm, Mgq, } impl Default for LnType { fn default() -> Self { Self::Rdm } } #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct Bmp { pub file: PathBuf, pub transparent_color: Argb, } #[derive(Debug, Default, Clone, PartialEq)] pub struct Header { pub player: Option<PlayerMode>, pub genre: Option<String>, pub title: Option<String>, pub subtitle: Option<String>, pub artist: Option<String>, pub sub_artist: Option<String>, pub maker: Option<String>, pub comment: Option<Vec<String>>, pub email: Option<String>, pub url: Option<String>, pub options: Option<Vec<String>>, pub bpm: Option<f64>, pub play_level: Option<u8>, pub rank: Option<JudgeLevel>, pub difficulty: Option<u8>, pub total: Option<f64>, pub volume: Volume, pub ln_type: LnType, pub poor_bga_mode: PoorMode, pub back_bmp: Option<PathBuf>, pub stage_file: Option<PathBuf>, pub banner: Option<PathBuf>, pub is_octave: bool, pub midi_file: Option<PathBuf>, pub video_file: Option<PathBuf>, pub wav_path_root: Option<PathBuf>, pub wav_files: HashMap<ObjId, PathBuf>, pub poor_bmp: Option<PathBuf>, pub bmp_files: HashMap<ObjId, Bmp>, pub bpm_changes: HashMap<ObjId, f64>, pub texts: HashMap<ObjId, String>, pub change_options: HashMap<ObjId, String>, } impl Header { pub(crate) fn parse(&mut self, token: &Token) -> Result<()> { match *token { Token::Artist(artist) => self.artist = Some(artist.into()), Token::AtBga { .. } => todo!(), Token::Banner(file) => self.banner = Some(file.into()), Token::BackBmp(bmp) => self.back_bmp = Some(bmp.into()), Token::Bga { .. } => todo!(), Token::Bmp(id, path) => { if id.is_none() { self.poor_bmp = Some(path.into()); return Ok(()); } let id = id.unwrap(); if self .bmp_files .insert( id, Bmp { file: path.into(), transparent_color: Argb::default(), }, ) .is_some() { eprintln!( "duplicated bmp definition found: {:?} {:?}", id, path.display() ); } } Token::Bpm(bpm) => { if let Ok(parsed) = bpm.parse() { if 0.0 < parsed { self.bpm = Some(parsed); } else { eprintln!("not positive bpm found: {:?}", parsed); } } else { eprintln!("not number bpm found: {:?}", bpm); } } Token::BpmChange(id, bpm) => { let parsed: f64 = bpm .parse() .map_err(|_| ParseError::BpmParseError(bpm.into()))?; if parsed <= 0.0 || !parsed.is_finite() { return Err(ParseError::BpmParseError(bpm.into())); } if self.bpm_changes.insert(id, parsed).is_some() { eprintln!("duplicated bpm change definition found: {:?} {:?}", id, bpm); } } Token::ChangeOption(id, option) => { if self.change_options.insert(id, option.into()).is_some() { eprintln!( "duplicated change option definition found: {:?} {}", id, option ); } } Token::Comment(comment) => self .comment .get_or_insert_with(Vec::new) .push(comment.into()), Token::Difficulty(diff) => self.difficulty = Some(diff), Token::Email(email) => self.email = Some(email.into()), Token::ExBmp(id, transparent_color, path) => { if self .bmp_files .insert( id, Bmp { file: path.into(), transparent_color, }, ) .is_some() { eprintln!( "duplicated bmp definition found: {:?} {:?}", id, path.display() ); } } Token::ExRank(_, _) => todo!(), Token::ExWav(_, _, _) => todo!(), Token::Genre(genre) => self.genre = Some(genre.to_owned()), Token::LnTypeRdm => { self.ln_type = LnType::Rdm; } Token::LnTypeMgq => { self.ln_type = LnType::Mgq; } Token::Maker(maker) => self.maker = Some(maker.into()), Token::MidiFile(midi_file) => self.midi_file = Some(midi_file.into()), Token::OctFp => self.is_octave = true, Token::Option(option) => self .options .get_or_insert_with(Vec::new) .push(option.into()), Token::PathWav(wav_path_root) => self.wav_path_root = Some(wav_path_root.into()), Token::Player(player) => self.player = Some(player), Token::PlayLevel(play_level) => self.play_level = Some(play_level), Token::PoorBga(poor_bga_mode) => self.poor_bga_mode = poor_bga_mode, Token::Rank(rank) => self.rank = Some(rank), Token::StageFile(file) => self.stage_file = Some(file.into()), Token::SubArtist(sub_artist) => self.sub_artist = Some(sub_artist.into()), Token::SubTitle(subtitle) => self.subtitle = Some(subtitle.into()), Token::Text(id, text) => { if self.texts.insert(id, text.into()).is_some() { eprintln!("duplicated text definition found: {:?} {}", id, text); } } Token::Title(title) => self.title = Some(title.into()), Token::Total(total) => { if let Ok(parsed) = total.parse() { self.total = Some(parsed); } else { eprintln!("not number total found: {:?}", total); } } Token::Url(url) => self.url = Some(url.into()), Token::VideoFile(video_file) => self.video_file = Some(video_file.into()), Token::VolWav(volume) => self.volume = volume, Token::Wav(id, path) => { if self.wav_files.insert(id, path.into()).is_some() { eprintln!( "duplicated wav definition found: {:?} {:?}", id, path.display() ); } } _ => {} } Ok(()) } }
use std::{collections::HashMap, fmt::Debug, path::PathBuf}; use super::{ParseError, Result}; use crate::lex::{command::*, token::Token}; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum LnType { Rdm, Mgq, } impl Default for LnType { fn default() -> Self { Self::Rdm } } #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct Bmp { pub file: PathBuf, pub transparent_color: Argb, } #[derive(Debug, Default, Clone, PartialEq)] pub struct Header { pub player: Option<PlayerMode>, pub genre: Option<String>, pub title: Option<String>, pub subtitle: Option<String>, pub artist: Option<String>, pub sub_artist: Option<String>, pub maker: Option<String>, pub comment: Option<Vec<String>>, pub email: Option<String>, pub url: Option<String>, pub options: Option<Vec<String>>, pub bpm: Option<f64>, pub play_level: Option<u8>, pub rank: Option<JudgeLevel>, pub difficulty: Option<u8>, pub total: Option<f64>, pub volume: Volume, pub ln_type: LnType, pub poor_bga_mode: PoorMode, pub back_bmp: Option<PathBuf>, pub stage_file: Option<PathBuf>, pub banner: Option<PathBuf>, pub is_octave: bool, pub midi_file: Option<PathBuf>, pub video_file: Option<PathBuf>, pub wav_path_root: Option<PathBuf>, pub wav_files: HashMap<ObjId, PathBuf>, pub poor_bmp: Option<PathBuf>, pub bmp_files: HashMap<ObjId, Bmp>, pub bpm_changes: HashMap<ObjId, f64>, pub texts: HashMap<ObjId, String>, pub change_options: HashMap<ObjId, String>, } impl Header { pub(crate) fn parse(&mut self, token: &Token) -> Result<()> { match *token { Token::Artist(artist) => self.artist = Some(artist.into()), Token::AtBga { .. } => todo!(), Token::Banner(file) => self.banner = Some(file.into()), Token::BackBmp(bmp) => self.back_bmp = Some(bmp.into()), Token::Bga { .. } => todo!(), Token::Bmp(id, path) => { if id.is_none() { self.poor_bmp = Some(path.into()); return Ok(()); } let id = id.unwrap(); if self .bmp_files .insert( id, Bmp { file: path.into(), transparent_color: Argb::default(), }, ) .is_some() { eprintln!( "duplicated bmp definition found: {:?} {:?}", id, path.display() ); } } Token::Bpm(bpm) => { if let Ok(parsed) = bpm.parse() { if 0.0 < parsed { self.bpm = Some(parsed); } else { eprintln!("not positive bpm found: {:?}", parsed); } } else { eprintln!("not number bpm found: {:?}", bpm); } } Token::BpmChange(id, bpm) => { let parsed: f64 = bpm .parse() .map_err(|_| ParseError::BpmParseError(bpm.into()))?; if parsed <= 0.0 || !parsed.is_finite() { return Err(ParseError::BpmParseError(bpm.into())); } if self.bpm_changes.insert(id, parsed).is_some() { eprintln!("duplicated bpm change definition found: {:?} {:?}", id, bpm); } } Token::ChangeOption(id, option) => { if self.change_options.insert(id, option.into()).is_some() { eprintln!( "duplicated change option definition found: {:?} {}", id, option ); } } Token::Comment(comment) => self .comment .get_or_insert_with(Vec::new) .push(comment.into()), Token::Difficulty(diff) => self.difficulty = Some(diff), Token::Email(email) => self.email = Some(email.into()), Token::ExBmp(id, transparent_color, path) => { if self .bmp_files .insert( id, Bmp { file: path.into(), transparent_color, }, ) .is_some() { eprintln!( "duplicated bmp definition found: {:?} {:?}", id, path.display() ); } } Token::ExRank(_, _) => todo!(), Token::ExWav(_, _, _) => todo!(), Token::Genre(genre) => self.genre = Some(genre.to_owned()), Token::LnTypeRdm => { self.ln_type = LnType::Rdm; } Token::LnTypeMgq => { self.ln_type = LnType::Mgq; } Token::Maker(maker) => self.maker = Some(maker.into()), Token::MidiFile(midi_file) => self.midi_file = Some(midi_file.into()), Token::OctFp => self.is_octave = true, Token::Option(option) => self .options .get_or_insert_with(Vec::new) .push(option.into()), Token::PathWav(wav_path_root) => self.wav_path_root = Some(wav_path_root.into()), Token::Player(player) => self.player = Some(player), Token::PlayLevel(play_level) => self.play_level = Some(play_level), Token::PoorBga(poor_bga_mode) => self.poor_bga_mode = poor_bga_mode, Token::Rank(rank) => self.rank = Some(rank), Token::StageFile(file) => self.stage_file = Some(file.into()), Token::SubArtist(sub_artist) => self.sub_artist = Some(sub_artist.into()), Token::SubTitle(subtitle) => self.subtitle = Some(subtitle.into()), Token::Text(id, text) => { if self.texts.insert(id, text.into()).is_some() { eprintln!("duplicated text definition found: {:?} {}", id, text); } } Token::Title(title) => self.title = Some(title.into()), Token::Total(total) => { if let Ok(parsed) = total.parse() { self.total = Some(parsed); }
}
else { eprintln!("not number total found: {:?}", total); } } Token::Url(url) => self.url = Some(url.into()), Token::VideoFile(video_file) => self.video_file = Some(video_file.into()), Token::VolWav(volume) => self.volume = volume, Token::Wav(id, path) => { if self.wav_files.insert(id, path.into()).is_some() { eprintln!( "duplicated wav definition found: {:?} {:?}", id, path.display() ); } } _ => {} } Ok(()) }
function_block-function_prefix_line
[ { "content": "/// Analyzes and converts the BMS format text into [`TokenStream`].\n\npub fn parse(source: &str) -> Result<TokenStream> {\n\n let mut cursor = Cursor::new(source);\n\n\n\n let mut tokens = vec![];\n\n while !cursor.is_end() {\n\n tokens.push(Token::parse(&mut cursor)?);\n\n }\n...
Rust
src/common/core.rs
hbeimf/crust
2cc9414ef5ad57133ad25de2193ba1734798a9de
use crate::common::{CommonError, Result, State}; use maidsafe_utilities::thread::{self, Joiner}; use mio::{Event, Events, Poll, PollOpt, Ready, Token}; use mio_extras::channel::{self, Receiver, Sender}; use mio_extras::timer::{Timeout, Timer}; use std::cell::RefCell; use std::collections::HashMap; use std::rc::Rc; use std::sync::mpsc::TryRecvError; use std::time::Duration; const EVENT_CAPACITY: usize = 1024; const CHANNEL_TOKEN_OFFSET: usize = 0; const TIMER_TOKEN_OFFSET: usize = CHANNEL_TOKEN_OFFSET + 1; const USER_TOKEN_OFFSET: usize = TIMER_TOKEN_OFFSET + 1; pub struct EventLoop<T> { tx: Sender<CoreMessage<T>>, _joiner: Joiner, } impl<T> EventLoop<T> { pub fn send(&self, msg: CoreMessage<T>) -> Result<()> { self.tx.send(msg).map_err(|_e| CommonError::CoreMsgTx) } } impl<T> Drop for EventLoop<T> { fn drop(&mut self) { if let Err(e) = self.tx.send(CoreMessage(None)) { warn!( "Could not send a terminator to event-loop. We will possibly not be able to \ gracefully exit. Error: {:?}", e ); } } } pub fn spawn_event_loop<T: 'static, F>( token_counter_start: usize, event_loop_id: Option<&str>, init_user_data: F, ) -> Result<EventLoop<T>> where F: 'static + FnOnce() -> T + Send, { let poll = Poll::new()?; let (tx, rx) = channel::channel(); let timer = Timer::default(); poll.register( &rx, Token(token_counter_start + CHANNEL_TOKEN_OFFSET), Ready::readable(), PollOpt::edge(), )?; poll.register( &timer, Token(token_counter_start + TIMER_TOKEN_OFFSET), Ready::readable(), PollOpt::edge(), )?; let mut name = "CRUST-Event-Loop".to_string(); if let Some(id) = event_loop_id { name.push_str(": "); name.push_str(id); } let tx_clone = tx.clone(); let joiner = thread::named(name, move || { let user_data = init_user_data(); let core = Core::new( token_counter_start + USER_TOKEN_OFFSET, tx_clone, timer, user_data, ); match event_loop_impl(token_counter_start, &poll, &rx, core) { Ok(()) => trace!("Graceful event loop exit."), Err(e) => error!("Event loop killed due to {:?}", e), } }); Ok(EventLoop { tx, _joiner: joiner, }) } fn event_loop_impl<T>( token_counter_start: usize, poll: &Poll, rx: &Receiver<CoreMessage<T>>, mut core: Core<T>, ) -> Result<()> { let mut events = Events::with_capacity(EVENT_CAPACITY); 'event_loop: loop { let _ = poll.poll(&mut events, None)?; for event in events.iter() { match event.token() { Token(t) if t == token_counter_start + CHANNEL_TOKEN_OFFSET => { if !event.readiness().is_readable() { warn!( "Communication channel to event loop errored out: {:?}", event ); continue; } loop { let msg = match rx.try_recv() { Ok(msg) => msg, Err(TryRecvError::Empty) => break, Err(TryRecvError::Disconnected) => break 'event_loop, }; match msg.0 { Some(mut f) => f(&mut core, poll), None => break 'event_loop, } } } Token(t) if t == token_counter_start + TIMER_TOKEN_OFFSET => { core.handle_timer(poll, event.readiness()) } _ => core.handle_event(poll, event), } } } Ok(()) } type CoreMessageHandler<T> = Box<FnMut(&mut Core<T>, &Poll) + Send>; pub struct CoreMessage<T>(Option<CoreMessageHandler<T>>); #[derive(Hash, Eq, PartialEq, Ord, PartialOrd, Copy, Clone, Debug)] pub struct CoreTimer { pub state_id: Token, pub timer_id: u8, } pub struct Core<T> { tx: Sender<CoreMessage<T>>, timer: Timer<CoreTimer>, token_counter: usize, states: HashMap<Token, Rc<RefCell<State<T>>>>, user_data: T, } impl<T> Core<T> { fn new( token_counter_start: usize, tx: Sender<CoreMessage<T>>, timer: Timer<CoreTimer>, user_data: T, ) -> Self { Core { tx, timer, token_counter: token_counter_start, states: HashMap::new(), user_data, } } #[cfg(test)] pub fn new_for_tests( token_counter_start: usize, tx: Sender<CoreMessage<T>>, timer: Timer<CoreTimer>, user_data: T, ) -> Self { Self::new(token_counter_start, tx, timer, user_data) } pub fn sender(&self) -> &Sender<CoreMessage<T>> { &self.tx } pub fn set_timeout(&mut self, interval: Duration, core_timer: CoreTimer) -> Timeout { self.timer.set_timeout(interval, core_timer) } pub fn cancel_timeout(&mut self, timeout: &Timeout) -> Option<CoreTimer> { self.timer.cancel_timeout(timeout) } pub fn get_new_token(&mut self) -> Token { let token = Token(self.token_counter); self.token_counter += 1; token } pub fn insert_state( &mut self, token: Token, state: Rc<RefCell<State<T>>>, ) -> Option<Rc<RefCell<State<T>>>> { self.states.insert(token, state) } pub fn remove_state(&mut self, token: Token) -> Option<Rc<RefCell<State<T>>>> { self.states.remove(&token) } pub fn get_state(&self, key: Token) -> Option<Rc<RefCell<State<T>>>> { self.states.get(&key).cloned() } pub fn user_data(&self) -> &T { &self.user_data } pub fn user_data_mut(&mut self) -> &mut T { &mut self.user_data } fn handle_event(&mut self, poll: &Poll, event: Event) { if let Some(state) = self.get_state(event.token()) { state.borrow_mut().ready(self, poll, event.readiness()); } } fn handle_timer(&mut self, poll: &Poll, kind: Ready) { if !kind.is_readable() { warn!("Timer errored out: {:?}", kind); return; } while let Some(core_timer) = self.timer.poll() { if let Some(state) = self.get_state(core_timer.state_id) { state.borrow_mut().timeout(self, poll, core_timer.timer_id); } } } } impl<T> CoreMessage<T> { pub fn new<F: FnOnce(&mut Core<T>, &Poll) + Send + 'static>(f: F) -> Self { let mut f = Some(f); CoreMessage(Some(Box::new(move |core: &mut Core<T>, poll: &Poll| { if let Some(f) = f.take() { f(core, poll) } }))) } } impl CoreTimer { pub fn new(state_id: Token, timer_id: u8) -> Self { CoreTimer { state_id, timer_id } } }
use crate::common::{CommonError, Result, State}; use maidsafe_utilities::thread::{self, Joiner}; use mio::{Event, Events, Poll, PollOpt, Ready, Token}; use mio_extras::channel::{self, Receiver, Sender}; use mio_extras::timer::{Timeout, Timer}; use std::cell::RefCell; use std::collections::HashMap; use std::rc::Rc; use std::sync::mpsc::TryRecvError; use std::time::Duration; const EVENT_CAPACITY: usize = 1024; const CHANNEL_TOKEN_OFFSET: usize = 0; const TIMER_TOKEN_OFFSET: usize = CHANNEL_TOKEN_OFFSET + 1; const USER_TOKEN_OFFSET: usize = TIMER_TOKEN_OFFSET + 1; pub struct EventLoop<T> { tx: Sender<CoreMessage<T>>, _joiner: Joiner, } impl<T> EventLoop<T> { pub fn send(&self, msg: CoreMessage<T>) -> Result<()> { self.tx.send(msg).map_err(|_e| CommonError::CoreMsgTx) } } impl<T> Drop for EventLoop<T> { fn drop(&mut self) { if let Err(e) = self.tx.send(CoreMessage(None)) { warn!( "Could not send a terminator to event-loop. We will possibly not be able to \ gracefully exit. Error: {:?}", e ); } } } pub fn spawn_event_loop<T: 'static, F>( token_counter_start: usize, event_loop_id: Option<&str>, init_user_data: F, ) -> Result<EventLoop<T>> where F: 'static + FnOnce() -> T + Send, { let poll = Poll::new()?; let (tx, rx) = channel::channel(); let timer = Timer::default(); poll.register( &rx, Token(token_counter_start + CHANNEL_TOKEN_OFFSET), Ready::readable(), PollOpt::edge(), )?; poll.register( &timer, Token(token_counter_start + TIMER_TOKEN_OFFSET), Ready::readable(), PollOpt::edge(), )?; let mut name = "CRUST-Event-Loop".to_string(); if let Some(id) = event_loop_id { name.push_str(": "); name.push_str(id); } let tx_clone = tx.clone(); let joiner = thread::named(name, move || { let user_data = init_user_data(); let core = Core::new( token_counter_start + USER_TOKEN_OFFSET, tx_clone, timer, user_data, ); match event_loop_impl(token_counter_start, &poll, &rx, core) { Ok(()) => trace!("Graceful event loop exit."), Err(e) => error!("Event loop killed due to {:?}", e), } }); Ok(EventLoop { tx, _joiner: joiner, }) } fn event_loop_impl<T>( token_counter_start: usize, poll: &Poll, rx: &Receiver<CoreMessage<T>>, mut core: Core<T>, ) -> Result<()> { let mut events = Events::with_capacity(EVENT_CAPACITY); 'event_loop: loop { let _ = poll.poll(&mut events, None)?; for event in events.iter() { match event.token() { Token(t) if t == token_counter_start + CHANNEL_TOKEN_OFFSET => { if !event.readiness().is_readable() { warn!( "Communication channel to event loop errored out: {:?}", event ); continue; } loop { let msg = match rx.try_recv() { Ok(msg) => msg, Err(TryRecvError::Empty) => break, Err(TryRecvError::Disconnected) => break 'event_loop, }; match msg.0 { Some(mut f) => f(&mut core, poll), None => break 'event_loop, } } } Token(t) if t == token_counter_start + TIMER_TOKEN_OFFSET => { core.handle_timer(poll, event.readiness()) } _ => core.handle_event(poll, event), } } } Ok(()) } type CoreMessageHandler<T> = Box<FnMut(&mut Core<T>, &Poll) + Send>; pub struct CoreMessage<T>(Option<CoreMessageHandler<T>>); #[derive(Hash, Eq, PartialEq, Ord, PartialOrd, Copy, Clone, Debug)] pub struct CoreTimer { pub state_id: Token, pub timer_id: u8, } pub struct Core<T> { tx: Sender<CoreMessage<T>>, timer: Timer<CoreTimer>, token_counter: usize, states: HashMap<Token, Rc<RefCell<State<T>>>>, user_data: T, } impl<T> Core<T> { fn new( token_counter_start: usize, tx: Sender<CoreMessage<T>>, timer: Timer<CoreTimer>, user_data: T, ) -> Self { Core { tx, timer, token_counter: token_counter_start, states: HashMap::new(), user_data, } } #[cfg(test)] pub fn new_for_tests( token_counter_start: usize, tx: Sender<CoreMessage<T>>, timer: Timer<CoreTimer>, user_data: T, ) -> Self { Self::new(token_counter_start, tx, timer, user_data) } pub fn sender(&self) -> &Sender<CoreMessage<T>> { &self.tx } pub fn set_timeout(&mut self, interval: Duration, core_timer: CoreTimer) -> Timeout { self.timer.set_timeout(interval, core_timer) } pub fn cancel_timeout(&mut self, timeout: &Timeout) -> Option<CoreTimer> { self.timer.cancel_timeout(timeout) } pub fn get_new_token(&mut self) -> Token { let token = Token(self.token_counter); self.token_counter += 1; token } pub fn insert_state( &mut self, token: Token, state: Rc<RefCell<State<T>>>, ) -> Option<Rc<RefCell<State<T>>>> { self.states.insert(token, state) } pub fn remove_state(&mut self, token: Token) -> Option<Rc<RefCell<State<T>>>> { self.states.remove(&token) } pub fn get_state(&self, key: Token) -> Option<Rc<RefCell<State<T>>>> { self.states.get(&key).cloned() } pub fn user_data(&self) -> &T { &self.user_data } pub fn user_data_mut(&mut self) -> &mut T { &mut self.user_data } fn handle_event(&mut self, poll: &Poll, event: Event) { if let Some(state) = self.get_state(event.token()) { state.borrow_mut().ready(self, poll, event.readiness()); } } fn handle_timer(&mut self, poll: &Poll, kind: Ready) { if !kind.is_readable() { warn!("Timer errored out: {:?}", kind); return; } while let Some(core_timer) = self.timer.poll() { if let Some(state) = self.get_state(core_timer.state_id) { state.borrow_mut().timeout(self, poll, core_timer.timer_id); }
r_id: u8) -> Self { CoreTimer { state_id, timer_id } } }
} } } impl<T> CoreMessage<T> { pub fn new<F: FnOnce(&mut Core<T>, &Poll) + Send + 'static>(f: F) -> Self { let mut f = Some(f); CoreMessage(Some(Box::new(move |core: &mut Core<T>, poll: &Poll| { if let Some(f) = f.take() { f(core, poll) } }))) } } impl CoreTimer { pub fn new(state_id: Token, time
random
[ { "content": "/// Puts given peer contacts into bootstrap cache which is then written to disk.\n\npub fn cache_peer_info(core: &mut EventLoopCore, peer_info: PeerInfo, config: &CrustConfig) {\n\n let hard_coded_peers = &unwrap!(config.lock()).cfg.hard_coded_contacts;\n\n if hard_coded_peers.contains(&peer...
Rust
src/main.rs
adumbidiot/pikadick-rs
da2610a36f6a137543e6261dfb43d3d6fd288138
#![deny( unused_qualifications, clippy::all, unused_qualifications, unused_import_braces, unreachable_pub, trivial_numeric_casts, rustdoc::all, missing_debug_implementations, missing_copy_implementations, deprecated_in_future, meta_variable_misuse, non_ascii_idents, rust_2018_compatibility, rust_2018_idioms, future_incompatible, nonstandard_style )] #![allow(missing_doc_code_examples)] pub mod checks; pub mod client_data; pub mod commands; pub mod config; pub mod database; pub mod logger; pub mod util; use crate::{ client_data::ClientData, commands::*, config::{ ActivityKind, Config, Severity, }, database::Database, }; use anyhow::Context as _; use serenity::{ client::bridge::gateway::ShardManager, framework::standard::{ help_commands, macros::{ group, help, }, Args, CommandGroup, CommandResult, DispatchError, HelpOptions, Reason, StandardFramework, }, futures::future::BoxFuture, model::prelude::*, prelude::*, FutureExt, }; use std::{ collections::HashSet, path::Path, sync::Arc, time::{ Duration, Instant, }, }; use tokio::runtime::Builder as RuntimeBuilder; use tracing::{ error, info, warn, }; use tracing_appender::non_blocking::WorkerGuard; const TOKIO_RT_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(10); struct Handler; #[serenity::async_trait] impl EventHandler for Handler { async fn ready(&self, ctx: Context, ready: Ready) { let data_lock = ctx.data.read().await; let client_data = data_lock .get::<ClientDataKey>() .expect("missing client data"); let config = client_data.config.clone(); drop(data_lock); if let (Some(status), Some(kind)) = (config.status_name(), config.status_type()) { match kind { ActivityKind::Listening => { ctx.set_activity(Activity::listening(status)).await; } ActivityKind::Streaming => { ctx.set_activity(Activity::streaming(status, config.status_url().unwrap())) .await; } ActivityKind::Playing => { ctx.set_activity(Activity::playing(status)).await; } } } info!("logged in as '{}'", ready.user.name); } async fn resume(&self, _ctx: Context, resumed: ResumedEvent) { warn!("resumed connection. trace: {:?}", resumed.trace); } #[tracing::instrument(skip(self, ctx, msg), fields(author = %msg.author.id, guild = ?msg.guild_id, content = %msg.content))] async fn message(&self, ctx: Context, msg: Message) { let data_lock = ctx.data.read().await; let client_data = data_lock .get::<ClientDataKey>() .expect("missing client data"); let reddit_embed_data = client_data.reddit_embed_data.clone(); drop(data_lock); if let Err(e) = reddit_embed_data.process_msg(&ctx, &msg).await { error!("failed to generate reddit embed: {}", e); } } } #[derive(Debug, Clone, Copy)] pub struct ClientDataKey; impl TypeMapKey for ClientDataKey { type Value = ClientData; } #[help] async fn help( ctx: &Context, msg: &Message, args: Args, help_options: &'static HelpOptions, groups: &[&'static CommandGroup], owners: HashSet<UserId>, ) -> CommandResult { let _ = help_commands::with_embeds(ctx, msg, args, help_options, groups, owners) .await .is_some(); Ok(()) } #[group] #[commands( ping, nekos, r6stats, r6tracker, rule34, system, quizizz, fml, zalgo, shift, reddit_embed, invite, vaporwave, cmd, latency, uwuify, cache_stats, insta_dl, deviantart, urban, xkcd, tic_tac_toe, iqdb )] struct General; async fn handle_ctrl_c(shard_manager: Arc<Mutex<ShardManager>>) { match tokio::signal::ctrl_c().await { Ok(_) => { info!("shutting down..."); info!("stopping client..."); shard_manager.lock().await.shutdown_all().await; } Err(e) => { warn!("failed to set ctrl-c handler: {}", e); } }; } #[tracing::instrument(skip(_ctx, msg), fields(author = %msg.author.id, guild = ?msg.guild_id, content = %msg.content))] fn before_handler<'fut>( _ctx: &'fut Context, msg: &'fut Message, cmd_name: &'fut str, ) -> BoxFuture<'fut, bool> { info!("allowing command to process"); async move { true }.boxed() } fn after_handler<'fut>( _ctx: &'fut Context, _msg: &'fut Message, command_name: &'fut str, command_result: CommandResult, ) -> BoxFuture<'fut, ()> { async move { if let Err(e) = command_result { error!("failed to process command '{}': {}", command_name, e); } } .boxed() } fn unrecognised_command_handler<'fut>( ctx: &'fut Context, msg: &'fut Message, command_name: &'fut str, ) -> BoxFuture<'fut, ()> { async move { error!("unrecognized command '{}'", command_name); let _ = msg .channel_id .say( &ctx.http, format!("Could not find command '{}'", command_name), ) .await .is_ok(); } .boxed() } fn process_dispatch_error<'fut>( ctx: &'fut Context, msg: &'fut Message, error: DispatchError, ) -> BoxFuture<'fut, ()> { process_dispatch_error_future(ctx, msg, error).boxed() } async fn process_dispatch_error_future<'fut>( ctx: &'fut Context, msg: &'fut Message, error: DispatchError, ) { match error { DispatchError::Ratelimited(s) => { let _ = msg .channel_id .say( &ctx.http, format!("Wait {} seconds to use that command again", s.as_secs()), ) .await .is_ok(); } DispatchError::NotEnoughArguments { min, given } => { let _ = msg .channel_id .say( &ctx.http, format!( "Expected at least {} argument(s) for this command, but only got {}", min, given ), ) .await .is_ok(); } DispatchError::TooManyArguments { max, given } => { let response_str = format!("Expected no more than {} argument(s) for this command, but got {}. Try using quotation marks if your argument has spaces.", max, given ); let _ = msg.channel_id.say(&ctx.http, response_str).await.is_ok(); } DispatchError::CheckFailed(check_name, reason) => match reason { Reason::User(user_reason_str) => { let _ = msg.channel_id.say(&ctx.http, user_reason_str).await.is_ok(); } _ => { let _ = msg .channel_id .say( &ctx.http, format!("{} check failed: {:#?}", check_name, reason), ) .await .is_ok(); } }, e => { let _ = msg .channel_id .say(&ctx.http, format!("Unhandled Dispatch Error: {:?}", e)) .await .is_ok(); } }; } fn load_config() -> anyhow::Result<Config> { let config_path: &Path = "./config.toml".as_ref(); eprintln!("loading `{}`...", config_path.display()); let mut config = Config::load_from_path(config_path) .with_context(|| format!("failed to load `{}`", config_path.display()))?; eprintln!("validating config..."); let errors = config.validate(); let mut error_count = 0; for e in errors { match e.severity() { Severity::Warn => { eprintln!("validation warning: {}", e.error()); } Severity::Error => { eprintln!("validation error: {}", e.error()); error_count += 1; } } } if error_count != 0 { anyhow::bail!("validation failed with {} errors.", error_count); } Ok(config) } fn setup() -> anyhow::Result<(tokio::runtime::Runtime, Config, bool, WorkerGuard)> { eprintln!("starting tokio runtime..."); let tokio_rt = RuntimeBuilder::new_multi_thread() .enable_all() .thread_name("pikadick-tokio-worker") .build() .context("failed to start tokio runtime")?; let config = load_config().context("failed to load config")?; eprintln!("opening data directory..."); if config.data_dir.is_file() { anyhow::bail!("failed to create or open data directory, the path is a file"); } let missing_data_dir = !config.data_dir.exists(); if missing_data_dir { eprintln!("data directory does not exist. creating..."); std::fs::create_dir_all(&config.data_dir).context("failed to create data directory")?; } else if config.data_dir.is_dir() { eprintln!("data directory already exists."); } std::fs::create_dir_all(&config.log_file_dir()).context("failed to create log file dir")?; eprintln!("setting up logger..."); let guard = tokio_rt .block_on(async { crate::logger::setup(&config) }) .context("failed to initialize logger")?; eprintln!(); Ok((tokio_rt, config, missing_data_dir, guard)) } fn main() { let (tokio_rt, config, missing_data_dir, worker_guard) = match setup() { Ok(data) => data, Err(e) => { eprintln!("{:?}", e); drop(e); std::process::exit(1); } }; let exit_code = match real_main(tokio_rt, config, missing_data_dir, worker_guard) { Ok(()) => 0, Err(e) => { error!("{:?}", e); 1 } }; std::process::exit(exit_code); } fn real_main( tokio_rt: tokio::runtime::Runtime, config: Config, missing_data_dir: bool, _worker_guard: WorkerGuard, ) -> anyhow::Result<()> { let ret = tokio_rt.block_on(async_main(config, missing_data_dir)); let shutdown_start = Instant::now(); info!( "shutting down tokio runtime (shutdown timeout is {:?})...", TOKIO_RT_SHUTDOWN_TIMEOUT ); tokio_rt.shutdown_timeout(TOKIO_RT_SHUTDOWN_TIMEOUT); info!("shutdown tokio runtime in {:?}", shutdown_start.elapsed()); info!("successful shutdown"); ret } async fn async_main(config: Config, _missing_data_dir: bool) -> anyhow::Result<()> { info!("opening database..."); let db_path = config.data_dir.join("pikadick.sqlite"); let db = Database::new(&db_path, true) .await .context("failed to open database")?; let uppercase_prefix = config.prefix.to_uppercase(); let framework = StandardFramework::new() .configure(|c| { c.prefixes(&[&config.prefix, &uppercase_prefix]) .case_insensitivity(true) }) .help(&HELP) .group(&GENERAL_GROUP) .bucket("nekos", |b| b.delay(1)) .await .bucket("r6stats", |b| b.delay(7)) .await .bucket("r6tracker", |b| b.delay(7)) .await .bucket("system", |b| b.delay(30)) .await .bucket("quizizz", |b| b.delay(10)) .await .bucket("insta-dl", |b| b.delay(10)) .await .bucket("ttt-board", |b| b.delay(1)) .await .bucket("default", |b| b.delay(1)) .await .before(before_handler) .after(after_handler) .unrecognised_command(unrecognised_command_handler) .on_dispatch_error(process_dispatch_error); info!("using prefix '{}'", &config.prefix); let mut client = Client::builder(&config.token) .event_handler(Handler) .framework(framework) .await .context("failed to create client")?; tokio::spawn(handle_ctrl_c(client.shard_manager.clone())); let client_data = ClientData::init(client.shard_manager.clone(), config, db) .await .context("client data initialization failed")?; { client_data.enabled_check_data.add_groups(&[&GENERAL_GROUP]); } { let mut data = client.data.write().await; data.insert::<ClientDataKey>(client_data); } info!("logging in..."); if let Err(why) = client.start().await { error!("error while running client: {}", why); } drop(client); Ok(()) }
#![deny( unused_qualifications, clippy::all, unused_qualifications, unused_import_braces, unreachable_pub, trivial_numeric_casts, rustdoc::all, missing_debug_implementations, missing_copy_implementations, deprecated_in_future, meta_variable_misuse, non_ascii_idents, rust_2018_compatibility, rust_2018_idioms, future_incompatible, nonstandard_style )] #![allow(missing_doc_code_examples)] pub mod checks; pub mod client_data; pub mod commands; pub mod config; pub mod database; pub mod logger; pub mod util; use crate::{ client_data::ClientData, commands::*, config::{ ActivityKind, Config, Severity, }, database::Database, }; use anyhow::Context as _; use serenity::{ client::bridge::gateway::ShardManager, framework::standard::{ help_commands, macros::{ group, help, }, Args, CommandGroup, CommandResult, DispatchError, HelpOptions, Reason, StandardFramework, }, futures::future::BoxFuture, model::prelude::*, prelude::*, FutureExt, }; use std::{ collections::HashSet, path::Path, sync::Arc, time::{ Duration, Instant, }, }; use tokio::runtime::Builder as RuntimeBuilder; use tracing::{ error, info, warn, }; use tracing_appender::non_blocking::WorkerGuard; const TOKIO_RT_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(10); struct Handler; #[serenity::async_trait] impl EventHandler for Handler { async fn ready(&self, ctx: Context, ready: Ready) { let data_lock = ctx.data.read().await; let client_data = data_lock .get::<ClientDataKey>() .expect("missing client data"); let config = client_data.config.clone(); drop(data_lock); if let (Some(status), Some(kind)) = (config.status_name(), config.status_type()) { match kind { ActivityKind::Listening => { ctx.set_activity(Activity::listening(status)).await; } ActivityKind::Streaming => { ctx.set_activity(Activity::streaming(status, config.status_url().unwrap())) .await; } ActivityKind::Playing => { ctx.set_activity(Activity::playing(status)).await; } } } info!("logged in as '{}'", ready.user.name); } async fn resume(&self, _ctx: Context, resumed: ResumedEvent) { warn!("resumed connection. trace: {:?}", resumed.trace); } #[tracing::instrument(skip(self, ctx, msg), fields(author = %msg.author.id, guild = ?msg.guild_id, content = %msg.content))] async fn message(&self, ctx: Context, msg: Message) { let data_lock = ctx.data.read().await; let client_data = data_lock .get::<ClientDataKey>() .expect("missing client data"); let reddit_embed_data = client_data.reddit_embed_data.clone(); drop(data_lock); if let Err(e) = reddit_embed_data.process_msg(&ctx, &msg).await { error!("failed to generate reddit embed: {}", e); } } } #[derive(Debug, Clone, Copy)] pub struct ClientDataKey; impl TypeMapKey for ClientDataKey { type Value = ClientData; } #[help] async fn help( ctx: &Context, msg: &Message, args: Args, help_options: &'static HelpOptions, groups: &[&'static CommandGroup], owners: HashSet<UserId>, ) -> CommandResult { let _ = help_commands::with_embeds(ctx, msg, args, help_options, groups, owners) .await .is_some(); Ok(()) } #[group] #[commands( ping, nekos, r6stats, r6tracker, rule34, system, quizizz, fml, zalgo, shift, reddit_embed, invite, vaporwave, cmd, latency, uwuify, cache_stats, insta_dl, deviantart, urban, xkcd, tic_tac_toe, iqdb )] struct General; async fn handle_ctrl_c(shard_manager: Arc<Mutex<ShardManager>>) { match tokio::signal::ctrl_c().await { Ok(_) => { info!("shutting down..."); info!("stopping client..."); shard_manager.lock().await.shutdown_all().await; } Err(e) => { warn!("failed to set ctrl-c handler: {}", e); } }; } #[tracing::instrument(skip(_ctx, msg), fields(author = %msg.author.id, guild = ?msg.guild_id, content = %msg.content))] fn before_handler<'fut>( _ctx: &'fut Context, msg: &'fut Message, cmd_name: &'fut str, ) -> BoxFuture<'fut, bool> { info!("allowing command to process"); async move { true }.boxed() } fn after_handler<'fut>( _ctx: &'fut Context, _msg: &'fut Message, command_name: &'fut str, command_result: CommandResult, ) -> BoxFuture<'fut, ()> { async move { if let Err(e) = command_result { error!("failed to process command '{}': {}", command_name, e); } } .boxed() } fn unrecognised_command_handler<'fut>( ctx: &'fut Context, msg: &'fut Message, command_name: &'fut str, ) -> BoxFuture<'fut, ()> { async move { error!("unrecognized command '{}'", command_name); let _ = msg .channel_id .say( &ctx.http, format!("Could not find command '{}'", command_name), ) .await .is_ok(); } .boxed() } fn process_dispatch_error<'fut>( ctx: &'fut Context, msg: &'fut Message, error: DispatchError, ) -> BoxFuture<'fut, ()> { process_dispatch_error_future(ctx, msg, error).boxed() } async fn process_dispatch_error_future<'fut>( ctx: &'fut Context, msg: &'fut Message, error: DispatchError, ) { match error { DispatchError::Ratelimited(s) => { let _ = msg .channel_id .say( &ctx.http, format!("Wait {} seconds to use that command again", s.as_secs()), ) .await .is_ok(); } DispatchError::NotEnoughArguments { min, given } => { let _ = msg .channel_id .say( &ctx.http, format!( "Expected at least {} argument(s) for this command, but only got {}", min, given ), ) .await .is_ok(); } DispatchError::TooManyArguments { max, given } => { let response_str = format!("Expected no more than {} argument(s) for this command, but got {}. Try using quotation marks if your argument has spaces.", max, given ); let _ = msg.channel_id.say(&ctx.http, response_str).await.is_ok(); } DispatchError::CheckFailed(check_name, reason) => match reason { Reason::User(user_reason_str) => { let _ = msg.channel_id.say(&ctx.http, user_reason_str).await.is_ok(); } _ => { let _ = msg .channel_id .say( &ctx.http, format!("{} check failed: {:#?}", check_name, reason), ) .await .is_ok(); } }, e => { let _ = msg .channel_id .say(&ctx.http, format!("Unhandled Dispatch Error: {:?}", e)) .await .is_ok(); } }; } fn load_config() -> anyhow::Result<Config> {
fn setup() -> anyhow::Result<(tokio::runtime::Runtime, Config, bool, WorkerGuard)> { eprintln!("starting tokio runtime..."); let tokio_rt = RuntimeBuilder::new_multi_thread() .enable_all() .thread_name("pikadick-tokio-worker") .build() .context("failed to start tokio runtime")?; let config = load_config().context("failed to load config")?; eprintln!("opening data directory..."); if config.data_dir.is_file() { anyhow::bail!("failed to create or open data directory, the path is a file"); } let missing_data_dir = !config.data_dir.exists(); if missing_data_dir { eprintln!("data directory does not exist. creating..."); std::fs::create_dir_all(&config.data_dir).context("failed to create data directory")?; } else if config.data_dir.is_dir() { eprintln!("data directory already exists."); } std::fs::create_dir_all(&config.log_file_dir()).context("failed to create log file dir")?; eprintln!("setting up logger..."); let guard = tokio_rt .block_on(async { crate::logger::setup(&config) }) .context("failed to initialize logger")?; eprintln!(); Ok((tokio_rt, config, missing_data_dir, guard)) } fn main() { let (tokio_rt, config, missing_data_dir, worker_guard) = match setup() { Ok(data) => data, Err(e) => { eprintln!("{:?}", e); drop(e); std::process::exit(1); } }; let exit_code = match real_main(tokio_rt, config, missing_data_dir, worker_guard) { Ok(()) => 0, Err(e) => { error!("{:?}", e); 1 } }; std::process::exit(exit_code); } fn real_main( tokio_rt: tokio::runtime::Runtime, config: Config, missing_data_dir: bool, _worker_guard: WorkerGuard, ) -> anyhow::Result<()> { let ret = tokio_rt.block_on(async_main(config, missing_data_dir)); let shutdown_start = Instant::now(); info!( "shutting down tokio runtime (shutdown timeout is {:?})...", TOKIO_RT_SHUTDOWN_TIMEOUT ); tokio_rt.shutdown_timeout(TOKIO_RT_SHUTDOWN_TIMEOUT); info!("shutdown tokio runtime in {:?}", shutdown_start.elapsed()); info!("successful shutdown"); ret } async fn async_main(config: Config, _missing_data_dir: bool) -> anyhow::Result<()> { info!("opening database..."); let db_path = config.data_dir.join("pikadick.sqlite"); let db = Database::new(&db_path, true) .await .context("failed to open database")?; let uppercase_prefix = config.prefix.to_uppercase(); let framework = StandardFramework::new() .configure(|c| { c.prefixes(&[&config.prefix, &uppercase_prefix]) .case_insensitivity(true) }) .help(&HELP) .group(&GENERAL_GROUP) .bucket("nekos", |b| b.delay(1)) .await .bucket("r6stats", |b| b.delay(7)) .await .bucket("r6tracker", |b| b.delay(7)) .await .bucket("system", |b| b.delay(30)) .await .bucket("quizizz", |b| b.delay(10)) .await .bucket("insta-dl", |b| b.delay(10)) .await .bucket("ttt-board", |b| b.delay(1)) .await .bucket("default", |b| b.delay(1)) .await .before(before_handler) .after(after_handler) .unrecognised_command(unrecognised_command_handler) .on_dispatch_error(process_dispatch_error); info!("using prefix '{}'", &config.prefix); let mut client = Client::builder(&config.token) .event_handler(Handler) .framework(framework) .await .context("failed to create client")?; tokio::spawn(handle_ctrl_c(client.shard_manager.clone())); let client_data = ClientData::init(client.shard_manager.clone(), config, db) .await .context("client data initialization failed")?; { client_data.enabled_check_data.add_groups(&[&GENERAL_GROUP]); } { let mut data = client.data.write().await; data.insert::<ClientDataKey>(client_data); } info!("logging in..."); if let Err(why) = client.start().await { error!("error while running client: {}", why); } drop(client); Ok(()) }
let config_path: &Path = "./config.toml".as_ref(); eprintln!("loading `{}`...", config_path.display()); let mut config = Config::load_from_path(config_path) .with_context(|| format!("failed to load `{}`", config_path.display()))?; eprintln!("validating config..."); let errors = config.validate(); let mut error_count = 0; for e in errors { match e.severity() { Severity::Warn => { eprintln!("validation warning: {}", e.error()); } Severity::Error => { eprintln!("validation error: {}", e.error()); error_count += 1; } } } if error_count != 0 { anyhow::bail!("validation failed with {} errors.", error_count); } Ok(config) }
function_block-function_prefix_line
[ { "content": "pub fn vaporwave_str(data: &str) -> String {\n\n data.chars()\n\n .filter_map(|c| {\n\n let c = c as u32;\n\n if (33..=270).contains(&c) {\n\n std::char::from_u32(c + 65248) // unwrap or c ?\n\n } else {\n\n Some(32 as char)\...
Rust
phper/src/functions.rs
erasin/phper
ec1a67cac3e3d101242786e950246f76fd92f921
use std::{mem::zeroed, os::raw::c_char}; use crate::{ alloc::EBox, classes::Visibility, errors::{ArgumentCountError, CallFunctionError, CallMethodError}, objects::Object, strings::ZendString, sys::*, utils::ensure_end_with_zero, values::{ExecuteData, SetVal, Val}, }; use std::{ marker::PhantomData, mem::{forget, size_of}, ptr::null_mut, }; pub(crate) trait Callable { fn call(&self, execute_data: &mut ExecuteData, arguments: &mut [Val], return_value: &mut Val); } pub(crate) struct Function<F, R>(F) where F: Fn(&mut [Val]) -> R + Send + Sync, R: SetVal; impl<F, R> Function<F, R> where F: Fn(&mut [Val]) -> R + Send + Sync, R: SetVal, { pub fn new(f: F) -> Self { Self(f) } } impl<F, R> Callable for Function<F, R> where F: Fn(&mut [Val]) -> R + Send + Sync, R: SetVal, { fn call(&self, _: &mut ExecuteData, arguments: &mut [Val], return_value: &mut Val) { let r = (self.0)(arguments); unsafe { r.set_val(return_value); } } } pub(crate) struct Method<F, R, T> where F: Fn(&mut Object<T>, &mut [Val]) -> R + Send + Sync, R: SetVal, { f: F, _p0: PhantomData<R>, _p1: PhantomData<T>, } impl<F, R, T> Method<F, R, T> where F: Fn(&mut Object<T>, &mut [Val]) -> R + Send + Sync, R: SetVal, { pub(crate) fn new(f: F) -> Self { Self { f, _p0: Default::default(), _p1: Default::default(), } } } impl<F, R, T: 'static> Callable for Method<F, R, T> where F: Fn(&mut Object<T>, &mut [Val]) -> R + Send + Sync, R: SetVal, { fn call(&self, execute_data: &mut ExecuteData, arguments: &mut [Val], return_value: &mut Val) { unsafe { let this = execute_data.get_this::<T>().unwrap(); let r = (self.f)(this, arguments); r.set_val(return_value); } } } #[repr(transparent)] pub struct FunctionEntry { #[allow(dead_code)] inner: zend_function_entry, } pub struct FunctionEntity { pub(crate) name: String, pub(crate) handler: Box<dyn Callable>, pub(crate) arguments: Vec<Argument>, pub(crate) visibility: Option<Visibility>, pub(crate) r#static: Option<bool>, } impl FunctionEntity { pub(crate) fn new( name: impl ToString, handler: Box<dyn Callable>, arguments: Vec<Argument>, visibility: Option<Visibility>, r#static: Option<bool>, ) -> Self { let name = ensure_end_with_zero(name); FunctionEntity { name, handler, arguments, visibility, r#static, } } pub(crate) unsafe fn entry(&self) -> zend_function_entry { let mut infos = Vec::new(); let require_arg_count = self.arguments.iter().filter(|arg| arg.required).count(); infos.push(create_zend_arg_info( require_arg_count as *const c_char, false, )); for arg in &self.arguments { infos.push(create_zend_arg_info( arg.name.as_ptr().cast(), arg.pass_by_ref, )); } infos.push(zeroed::<zend_internal_arg_info>()); let translator = CallableTranslator { callable: self.handler.as_ref(), }; let last_arg_info: zend_internal_arg_info = translator.internal_arg_info; infos.push(last_arg_info); let flags = self.visibility.map(|v| v as u32).unwrap_or_default() | self .r#static .and_then(|v| if v { Some(ZEND_ACC_STATIC) } else { None }) .unwrap_or_default(); zend_function_entry { fname: self.name.as_ptr().cast(), handler: Some(invoke), arg_info: Box::into_raw(infos.into_boxed_slice()).cast(), num_args: self.arguments.len() as u32, flags, } } } pub struct Argument { pub(crate) name: String, pub(crate) pass_by_ref: bool, pub(crate) required: bool, } impl Argument { pub fn by_val(name: impl ToString) -> Self { let name = ensure_end_with_zero(name); Self { name, pass_by_ref: false, required: true, } } pub fn by_ref(name: impl ToString) -> Self { let name = ensure_end_with_zero(name); Self { name, pass_by_ref: true, required: true, } } pub fn by_val_optional(name: impl ToString) -> Self { let name = ensure_end_with_zero(name); Self { name, pass_by_ref: false, required: false, } } pub fn by_ref_optional(name: impl ToString) -> Self { let name = ensure_end_with_zero(name); Self { name, pass_by_ref: true, required: false, } } } #[repr(transparent)] pub struct ZendFunction { inner: zend_function, } impl ZendFunction { pub(crate) unsafe fn from_mut_ptr<'a>(ptr: *mut zend_function) -> &'a mut ZendFunction { let ptr = ptr as *mut Self; ptr.as_mut().expect("ptr shouldn't be null") } #[inline] pub fn as_ptr(&self) -> *const zend_function { &self.inner } #[inline] pub fn as_mut_ptr(&mut self) -> *mut zend_function { &mut self.inner } pub fn get_name(&self) -> EBox<ZendString> { unsafe { let s = phper_get_function_or_method_name(self.as_ptr()); ZendString::from_raw(s) } } pub fn call_method<T: 'static>( &mut self, object: &mut Object<T>, mut arguments: impl AsMut<[Val]>, ) -> crate::Result<EBox<Val>> { let mut ret_val = EBox::new(Val::undef()); let arguments = arguments.as_mut(); let mut fci = zend_fcall_info { size: size_of::<zend_fcall_info>(), function_name: Val::undef().into_inner(), retval: ret_val.as_mut_ptr(), params: arguments.as_mut_ptr().cast(), object: object.as_mut_ptr(), param_count: arguments.len() as u32, #[cfg(phper_major_version = "8")] named_params: null_mut(), #[cfg(phper_major_version = "7")] no_separation: 1, #[cfg(all(phper_major_version = "7", phper_minor_version = "0"))] function_table: null_mut(), #[cfg(all(phper_major_version = "7", phper_minor_version = "0"))] symbol_table: null_mut(), }; let called_scope = unsafe { let mut called_scope = object.get_class().as_ptr() as *mut zend_class_entry; if called_scope.is_null() { called_scope = self.inner.common.scope; } called_scope }; let mut fcc = zend_fcall_info_cache { function_handler: self.as_mut_ptr(), calling_scope: null_mut(), called_scope, object: object.as_mut_ptr(), #[cfg(all( phper_major_version = "7", any( phper_minor_version = "0", phper_minor_version = "1", phper_minor_version = "2", ) ))] initialized: 1, }; unsafe { if zend_call_function(&mut fci, &mut fcc) != ZEND_RESULT_CODE_SUCCESS || ret_val.get_type().is_undef() { Err(CallMethodError::new( object.get_class().get_name().as_str()?.to_owned(), self.get_name().as_str()?.to_owned(), ) .into()) } else { Ok(ret_val) } } } } pub(crate) union CallableTranslator { pub(crate) callable: *const dyn Callable, pub(crate) internal_arg_info: zend_internal_arg_info, pub(crate) arg_info: zend_arg_info, } unsafe extern "C" fn invoke(execute_data: *mut zend_execute_data, return_value: *mut zval) { let execute_data = ExecuteData::from_mut_ptr(execute_data); let return_value = Val::from_mut_ptr(return_value); let num_args = execute_data.common_num_args(); let arg_info = execute_data.common_arg_info(); let last_arg_info = arg_info.offset((num_args + 1) as isize); let translator = CallableTranslator { arg_info: *last_arg_info, }; let handler = translator.callable; let handler = handler.as_ref().expect("handler is null"); let num_args = execute_data.num_args() as usize; let required_num_args = execute_data.common_required_num_args() as usize; if num_args < required_num_args { let func_name = execute_data.func().get_name(); let result = func_name .as_str() .map(|func_name| { Err::<(), _>(ArgumentCountError::new( func_name.to_owned(), required_num_args, num_args, )) }) .map_err(crate::Error::Utf8); SetVal::set_val(result, return_value); return; } let mut arguments = execute_data.get_parameters_array(); handler.call(execute_data, &mut arguments, return_value); for argument in arguments { forget(argument); } } pub(crate) const fn create_zend_arg_info( name: *const c_char, _pass_by_ref: bool, ) -> zend_internal_arg_info { #[cfg(phper_php_version = "8.0")] { zend_internal_arg_info { name, type_: zend_type { ptr: null_mut(), type_mask: 0, }, default_value: null_mut(), } } #[cfg(any( phper_php_version = "7.4", phper_php_version = "7.3", phper_php_version = "7.2" ))] { zend_internal_arg_info { name, type_: 0 as crate::sys::zend_type, pass_by_reference: _pass_by_ref as zend_uchar, is_variadic: 0, } } #[cfg(any(phper_php_version = "7.1", phper_php_version = "7.0"))] { zend_internal_arg_info { name, class_name: std::ptr::null(), type_hint: 0, allow_null: 0, pass_by_reference: _pass_by_ref as zend_uchar, is_variadic: 0, } } } pub fn call(fn_name: &str, arguments: &mut [Val]) -> Result<EBox<Val>, CallFunctionError> { let mut func = Val::new(fn_name); let mut ret = EBox::new(Val::null()); unsafe { if phper_call_user_function( compiler_globals.function_table, null_mut(), func.as_mut_ptr(), ret.as_mut_ptr(), arguments.len() as u32, arguments.as_mut_ptr().cast(), ) && !ret.get_type().is_undef() { Ok(ret) } else { Err(CallFunctionError::new(fn_name.to_owned())) } } }
use std::{mem::zeroed, os::raw::c_char}; use crate::{ alloc::EBox, classes::Visibility, errors::{ArgumentCountError, CallFunctionError, CallMethodError}, objects::Object, strings::ZendString, sys::*, utils::ensure_end_with_zero, values::{ExecuteData, SetVal, Val}, }; use std::{ marker::PhantomData, mem::{forget, size_of}, ptr::null_mut, }; pub(crate) trait Callable { fn call(&self, execute_data: &mut ExecuteData, arguments: &mut [Val], return_value: &mut Val); } pub(crate) struct Function<F, R>(F) where F: Fn(&mut [Val]) -> R + Send + Sync, R: SetVal; impl<F, R> Function<F, R> where F: Fn(&mut [Val]) -> R + Send + Sync, R: SetVal, { pub fn new(f: F) -> Self { Self(f) } } impl<F, R> Callable for Function<F, R> where F: Fn(&mut [Val]) -> R + Send + Sync, R: SetVal, { fn call(&self, _: &mut ExecuteDa
} pub(crate) struct Method<F, R, T> where F: Fn(&mut Object<T>, &mut [Val]) -> R + Send + Sync, R: SetVal, { f: F, _p0: PhantomData<R>, _p1: PhantomData<T>, } impl<F, R, T> Method<F, R, T> where F: Fn(&mut Object<T>, &mut [Val]) -> R + Send + Sync, R: SetVal, { pub(crate) fn new(f: F) -> Self { Self { f, _p0: Default::default(), _p1: Default::default(), } } } impl<F, R, T: 'static> Callable for Method<F, R, T> where F: Fn(&mut Object<T>, &mut [Val]) -> R + Send + Sync, R: SetVal, { fn call(&self, execute_data: &mut ExecuteData, arguments: &mut [Val], return_value: &mut Val) { unsafe { let this = execute_data.get_this::<T>().unwrap(); let r = (self.f)(this, arguments); r.set_val(return_value); } } } #[repr(transparent)] pub struct FunctionEntry { #[allow(dead_code)] inner: zend_function_entry, } pub struct FunctionEntity { pub(crate) name: String, pub(crate) handler: Box<dyn Callable>, pub(crate) arguments: Vec<Argument>, pub(crate) visibility: Option<Visibility>, pub(crate) r#static: Option<bool>, } impl FunctionEntity { pub(crate) fn new( name: impl ToString, handler: Box<dyn Callable>, arguments: Vec<Argument>, visibility: Option<Visibility>, r#static: Option<bool>, ) -> Self { let name = ensure_end_with_zero(name); FunctionEntity { name, handler, arguments, visibility, r#static, } } pub(crate) unsafe fn entry(&self) -> zend_function_entry { let mut infos = Vec::new(); let require_arg_count = self.arguments.iter().filter(|arg| arg.required).count(); infos.push(create_zend_arg_info( require_arg_count as *const c_char, false, )); for arg in &self.arguments { infos.push(create_zend_arg_info( arg.name.as_ptr().cast(), arg.pass_by_ref, )); } infos.push(zeroed::<zend_internal_arg_info>()); let translator = CallableTranslator { callable: self.handler.as_ref(), }; let last_arg_info: zend_internal_arg_info = translator.internal_arg_info; infos.push(last_arg_info); let flags = self.visibility.map(|v| v as u32).unwrap_or_default() | self .r#static .and_then(|v| if v { Some(ZEND_ACC_STATIC) } else { None }) .unwrap_or_default(); zend_function_entry { fname: self.name.as_ptr().cast(), handler: Some(invoke), arg_info: Box::into_raw(infos.into_boxed_slice()).cast(), num_args: self.arguments.len() as u32, flags, } } } pub struct Argument { pub(crate) name: String, pub(crate) pass_by_ref: bool, pub(crate) required: bool, } impl Argument { pub fn by_val(name: impl ToString) -> Self { let name = ensure_end_with_zero(name); Self { name, pass_by_ref: false, required: true, } } pub fn by_ref(name: impl ToString) -> Self { let name = ensure_end_with_zero(name); Self { name, pass_by_ref: true, required: true, } } pub fn by_val_optional(name: impl ToString) -> Self { let name = ensure_end_with_zero(name); Self { name, pass_by_ref: false, required: false, } } pub fn by_ref_optional(name: impl ToString) -> Self { let name = ensure_end_with_zero(name); Self { name, pass_by_ref: true, required: false, } } } #[repr(transparent)] pub struct ZendFunction { inner: zend_function, } impl ZendFunction { pub(crate) unsafe fn from_mut_ptr<'a>(ptr: *mut zend_function) -> &'a mut ZendFunction { let ptr = ptr as *mut Self; ptr.as_mut().expect("ptr shouldn't be null") } #[inline] pub fn as_ptr(&self) -> *const zend_function { &self.inner } #[inline] pub fn as_mut_ptr(&mut self) -> *mut zend_function { &mut self.inner } pub fn get_name(&self) -> EBox<ZendString> { unsafe { let s = phper_get_function_or_method_name(self.as_ptr()); ZendString::from_raw(s) } } pub fn call_method<T: 'static>( &mut self, object: &mut Object<T>, mut arguments: impl AsMut<[Val]>, ) -> crate::Result<EBox<Val>> { let mut ret_val = EBox::new(Val::undef()); let arguments = arguments.as_mut(); let mut fci = zend_fcall_info { size: size_of::<zend_fcall_info>(), function_name: Val::undef().into_inner(), retval: ret_val.as_mut_ptr(), params: arguments.as_mut_ptr().cast(), object: object.as_mut_ptr(), param_count: arguments.len() as u32, #[cfg(phper_major_version = "8")] named_params: null_mut(), #[cfg(phper_major_version = "7")] no_separation: 1, #[cfg(all(phper_major_version = "7", phper_minor_version = "0"))] function_table: null_mut(), #[cfg(all(phper_major_version = "7", phper_minor_version = "0"))] symbol_table: null_mut(), }; let called_scope = unsafe { let mut called_scope = object.get_class().as_ptr() as *mut zend_class_entry; if called_scope.is_null() { called_scope = self.inner.common.scope; } called_scope }; let mut fcc = zend_fcall_info_cache { function_handler: self.as_mut_ptr(), calling_scope: null_mut(), called_scope, object: object.as_mut_ptr(), #[cfg(all( phper_major_version = "7", any( phper_minor_version = "0", phper_minor_version = "1", phper_minor_version = "2", ) ))] initialized: 1, }; unsafe { if zend_call_function(&mut fci, &mut fcc) != ZEND_RESULT_CODE_SUCCESS || ret_val.get_type().is_undef() { Err(CallMethodError::new( object.get_class().get_name().as_str()?.to_owned(), self.get_name().as_str()?.to_owned(), ) .into()) } else { Ok(ret_val) } } } } pub(crate) union CallableTranslator { pub(crate) callable: *const dyn Callable, pub(crate) internal_arg_info: zend_internal_arg_info, pub(crate) arg_info: zend_arg_info, } unsafe extern "C" fn invoke(execute_data: *mut zend_execute_data, return_value: *mut zval) { let execute_data = ExecuteData::from_mut_ptr(execute_data); let return_value = Val::from_mut_ptr(return_value); let num_args = execute_data.common_num_args(); let arg_info = execute_data.common_arg_info(); let last_arg_info = arg_info.offset((num_args + 1) as isize); let translator = CallableTranslator { arg_info: *last_arg_info, }; let handler = translator.callable; let handler = handler.as_ref().expect("handler is null"); let num_args = execute_data.num_args() as usize; let required_num_args = execute_data.common_required_num_args() as usize; if num_args < required_num_args { let func_name = execute_data.func().get_name(); let result = func_name .as_str() .map(|func_name| { Err::<(), _>(ArgumentCountError::new( func_name.to_owned(), required_num_args, num_args, )) }) .map_err(crate::Error::Utf8); SetVal::set_val(result, return_value); return; } let mut arguments = execute_data.get_parameters_array(); handler.call(execute_data, &mut arguments, return_value); for argument in arguments { forget(argument); } } pub(crate) const fn create_zend_arg_info( name: *const c_char, _pass_by_ref: bool, ) -> zend_internal_arg_info { #[cfg(phper_php_version = "8.0")] { zend_internal_arg_info { name, type_: zend_type { ptr: null_mut(), type_mask: 0, }, default_value: null_mut(), } } #[cfg(any( phper_php_version = "7.4", phper_php_version = "7.3", phper_php_version = "7.2" ))] { zend_internal_arg_info { name, type_: 0 as crate::sys::zend_type, pass_by_reference: _pass_by_ref as zend_uchar, is_variadic: 0, } } #[cfg(any(phper_php_version = "7.1", phper_php_version = "7.0"))] { zend_internal_arg_info { name, class_name: std::ptr::null(), type_hint: 0, allow_null: 0, pass_by_reference: _pass_by_ref as zend_uchar, is_variadic: 0, } } } pub fn call(fn_name: &str, arguments: &mut [Val]) -> Result<EBox<Val>, CallFunctionError> { let mut func = Val::new(fn_name); let mut ret = EBox::new(Val::null()); unsafe { if phper_call_user_function( compiler_globals.function_table, null_mut(), func.as_mut_ptr(), ret.as_mut_ptr(), arguments.len() as u32, arguments.as_mut_ptr().cast(), ) && !ret.get_type().is_undef() { Ok(ret) } else { Err(CallFunctionError::new(fn_name.to_owned())) } } }
ta, arguments: &mut [Val], return_value: &mut Val) { let r = (self.0)(arguments); unsafe { r.set_val(return_value); } }
function_block-function_prefixed
[ { "content": "pub fn replace_and_get<T: Default, R>(t: &mut T, f: impl FnOnce(T) -> R) -> R {\n\n f(replace(t, Default::default()))\n\n}\n", "file_path": "examples/http-client/src/utils.rs", "rank": 1, "score": 210667.59407539124 }, { "content": "fn integration_values_return_val(_: &mut [...
Rust
ezgui/src/event_ctx.rs
jinzhong2/abstreet
e1c5edc76d636af4f3e4593efc25055bdd637dd7
use crate::widgets::ContextMenu; use crate::{ Canvas, Color, GfxCtx, HorizontalAlignment, Line, Prerender, Text, UserInput, VerticalAlignment, }; use abstutil::{elapsed_seconds, Timer, TimerSink}; use geom::Angle; use glium_glyph::glyph_brush::rusttype::Font; use glium_glyph::GlyphBrush; use std::collections::VecDeque; use std::time::Instant; pub struct EventCtx<'a> { pub input: &'a mut UserInput, pub canvas: &'a mut Canvas, pub prerender: &'a Prerender<'a>, pub(crate) program: &'a glium::Program, } impl<'a> EventCtx<'a> { pub fn loading_screen<O, F: FnOnce(&mut EventCtx, &mut Timer) -> O>( &mut self, timer_name: &str, f: F, ) -> O { let mut timer = Timer::new_with_sink( timer_name, Box::new(LoadingScreen::new( self.prerender, self.program, self.canvas.window_width, self.canvas.window_height, self.canvas.font_size, timer_name.to_string(), )), ); f(self, &mut timer) } pub fn redo_mouseover(&self) -> bool { self.input.window_lost_cursor() || (!self.canvas.is_dragging() && self.input.get_moved_mouse().is_some()) || self.input.get_mouse_scroll().is_some() } pub fn set_textures( &mut self, skip_textures: Vec<(&str, Color)>, textures: Vec<(&str, TextureType)>, timer: &mut Timer, ) { self.canvas.textures.clear(); self.canvas.texture_lookups.clear(); for (filename, fallback) in skip_textures { self.canvas .texture_lookups .insert(filename.to_string(), fallback); } if textures.len() > 15 { panic!("Due to lovely hacks, only 15 textures supported"); } timer.start_iter("upload textures", textures.len()); for (idx, (filename, tex_type)) in textures.into_iter().enumerate() { timer.next(); let img = image::open(filename).unwrap().to_rgba(); let dims = img.dimensions(); let tex = glium::texture::Texture2d::new( self.prerender.display, glium::texture::RawImage2d::from_raw_rgba_reversed(&img.into_raw(), dims), ) .unwrap(); self.canvas.textures.push((filename.to_string(), tex)); self.canvas.texture_lookups.insert( filename.to_string(), match tex_type { TextureType::Stretch => Color::StretchTexture(idx as f32, Angle::ZERO), TextureType::Tile => { Color::TileTexture(idx as f32, (f64::from(dims.0), f64::from(dims.1))) } TextureType::CustomUV => Color::CustomUVTexture(idx as f32), }, ); } } } pub struct LoadingScreen<'a> { canvas: Canvas, prerender: &'a Prerender<'a>, program: &'a glium::Program, lines: VecDeque<String>, max_capacity: usize, last_drawn: Option<Instant>, title: String, } impl<'a> LoadingScreen<'a> { pub fn new( prerender: &'a Prerender<'a>, program: &'a glium::Program, initial_width: f64, initial_height: f64, font_size: usize, title: String, ) -> LoadingScreen<'a> { let dejavu: &[u8] = include_bytes!("assets/DejaVuSans.ttf"); let screenspace_glyphs = GlyphBrush::new(prerender.display, vec![Font::from_bytes(dejavu).unwrap()]); let mapspace_glyphs = GlyphBrush::new(prerender.display, vec![Font::from_bytes(dejavu).unwrap()]); let canvas = Canvas::new( initial_width, initial_height, screenspace_glyphs, mapspace_glyphs, font_size, ); LoadingScreen { prerender, program, lines: VecDeque::new(), max_capacity: (0.8 * initial_height / canvas.line_height) as usize, last_drawn: None, title, canvas, } } fn redraw(&mut self) { if let Some(t) = self.last_drawn { if elapsed_seconds(t) < 0.2 { return; } } self.last_drawn = Some(Instant::now()); let mut txt = Text::prompt(&self.title); txt.override_width = Some(self.canvas.window_width * 0.8); txt.override_height = Some(self.canvas.window_height * 0.8); for l in &self.lines { txt.add(Line(l)); } let mut target = self.prerender.display.draw(); let context_menu = ContextMenu::new(); let mut g = GfxCtx::new( &self.canvas, self.prerender, &mut target, self.program, &context_menu, false, ); g.clear(Color::BLACK); g.draw_blocking_text( &txt, (HorizontalAlignment::Center, VerticalAlignment::Center), ); self.canvas .screenspace_glyphs .borrow_mut() .draw_queued(self.prerender.display, &mut target); target.finish().unwrap(); } } impl<'a> TimerSink for LoadingScreen<'a> { fn println(&mut self, line: String) { if self.lines.len() == self.max_capacity { self.lines.pop_front(); } self.lines.push_back(line); self.redraw(); } fn reprintln(&mut self, line: String) { self.lines.pop_back(); self.lines.push_back(line); self.redraw(); } } pub enum TextureType { Stretch, Tile, CustomUV, }
use crate::widgets::ContextMenu; use crate::{ Canvas, Color, GfxCtx, HorizontalAlignment, Line, Prerender, Text, UserInput, VerticalAlignment, }; use abstutil::{elapsed_seconds, Timer, TimerSink}; use geom::Angle; use glium_glyph::glyph_brush::rusttype::Font; use glium_glyph::GlyphBrush; use std::collections::VecDeque; use std::time::Instant; pub struct EventCtx<'a> { pub input: &'a mut UserInput, pub canvas: &'a mut Canvas, pub prerender: &'a Prerender<'a>, pub(crate) program: &'a glium::Program, } impl<'a> EventCtx<'a> { pub fn loading_screen<O, F: FnOnce(&mut EventCtx, &mut Timer) -> O>( &mut self, timer_name: &str, f: F, ) -> O { let mut timer = Timer::new_with_sink( timer_na
pub fn redo_mouseover(&self) -> bool { self.input.window_lost_cursor() || (!self.canvas.is_dragging() && self.input.get_moved_mouse().is_some()) || self.input.get_mouse_scroll().is_some() } pub fn set_textures( &mut self, skip_textures: Vec<(&str, Color)>, textures: Vec<(&str, TextureType)>, timer: &mut Timer, ) { self.canvas.textures.clear(); self.canvas.texture_lookups.clear(); for (filename, fallback) in skip_textures { self.canvas .texture_lookups .insert(filename.to_string(), fallback); } if textures.len() > 15 { panic!("Due to lovely hacks, only 15 textures supported"); } timer.start_iter("upload textures", textures.len()); for (idx, (filename, tex_type)) in textures.into_iter().enumerate() { timer.next(); let img = image::open(filename).unwrap().to_rgba(); let dims = img.dimensions(); let tex = glium::texture::Texture2d::new( self.prerender.display, glium::texture::RawImage2d::from_raw_rgba_reversed(&img.into_raw(), dims), ) .unwrap(); self.canvas.textures.push((filename.to_string(), tex)); self.canvas.texture_lookups.insert( filename.to_string(), match tex_type { TextureType::Stretch => Color::StretchTexture(idx as f32, Angle::ZERO), TextureType::Tile => { Color::TileTexture(idx as f32, (f64::from(dims.0), f64::from(dims.1))) } TextureType::CustomUV => Color::CustomUVTexture(idx as f32), }, ); } } } pub struct LoadingScreen<'a> { canvas: Canvas, prerender: &'a Prerender<'a>, program: &'a glium::Program, lines: VecDeque<String>, max_capacity: usize, last_drawn: Option<Instant>, title: String, } impl<'a> LoadingScreen<'a> { pub fn new( prerender: &'a Prerender<'a>, program: &'a glium::Program, initial_width: f64, initial_height: f64, font_size: usize, title: String, ) -> LoadingScreen<'a> { let dejavu: &[u8] = include_bytes!("assets/DejaVuSans.ttf"); let screenspace_glyphs = GlyphBrush::new(prerender.display, vec![Font::from_bytes(dejavu).unwrap()]); let mapspace_glyphs = GlyphBrush::new(prerender.display, vec![Font::from_bytes(dejavu).unwrap()]); let canvas = Canvas::new( initial_width, initial_height, screenspace_glyphs, mapspace_glyphs, font_size, ); LoadingScreen { prerender, program, lines: VecDeque::new(), max_capacity: (0.8 * initial_height / canvas.line_height) as usize, last_drawn: None, title, canvas, } } fn redraw(&mut self) { if let Some(t) = self.last_drawn { if elapsed_seconds(t) < 0.2 { return; } } self.last_drawn = Some(Instant::now()); let mut txt = Text::prompt(&self.title); txt.override_width = Some(self.canvas.window_width * 0.8); txt.override_height = Some(self.canvas.window_height * 0.8); for l in &self.lines { txt.add(Line(l)); } let mut target = self.prerender.display.draw(); let context_menu = ContextMenu::new(); let mut g = GfxCtx::new( &self.canvas, self.prerender, &mut target, self.program, &context_menu, false, ); g.clear(Color::BLACK); g.draw_blocking_text( &txt, (HorizontalAlignment::Center, VerticalAlignment::Center), ); self.canvas .screenspace_glyphs .borrow_mut() .draw_queued(self.prerender.display, &mut target); target.finish().unwrap(); } } impl<'a> TimerSink for LoadingScreen<'a> { fn println(&mut self, line: String) { if self.lines.len() == self.max_capacity { self.lines.pop_front(); } self.lines.push_back(line); self.redraw(); } fn reprintln(&mut self, line: String) { self.lines.pop_back(); self.lines.push_back(line); self.redraw(); } } pub enum TextureType { Stretch, Tile, CustomUV, }
me, Box::new(LoadingScreen::new( self.prerender, self.program, self.canvas.window_width, self.canvas.window_height, self.canvas.font_size, timer_name.to_string(), )), ); f(self, &mut timer) }
function_block-function_prefixed
[ { "content": "fn use_parking_hints(map: &mut RawMap, path: &str, timer: &mut Timer) {\n\n timer.start(\"apply parking hints\");\n\n let shapes: ExtraShapes = abstutil::read_binary(path, timer).expect(\"loading blockface failed\");\n\n\n\n // Match shapes with the nearest road + direction (true for forw...
Rust
vrp-core/src/solver/telemetry.rs
valerivp/vrp
27ee30e5f4c44e051e5cec1248e606305b52fc00
#[cfg(test)] #[path = "../../tests/unit/solver/telemetry_test.rs"] mod telemetry_test; use crate::algorithms::nsga2::Objective; use crate::construction::heuristics::InsertionContext; use crate::solver::population::SelectionPhase; use crate::solver::{RefinementContext, Statistics}; use crate::utils::Timer; use std::fmt::Write; use std::ops::Deref; use std::sync::Arc; pub type InfoLogger = Arc<dyn Fn(&str)>; pub struct Metrics { pub duration: usize, pub generations: usize, pub speed: f64, pub evolution: Vec<Generation>, } pub struct Generation { pub number: usize, pub timestamp: f64, pub i_all_ratio: f64, pub i_1000_ratio: f64, pub is_improvement: bool, pub population: Population, } pub struct Individual { pub rank: usize, pub tours: usize, pub unassigned: usize, pub cost: f64, pub improvement: f64, pub fitness: Vec<f64>, } pub struct Population { pub individuals: Vec<Individual>, } pub enum TelemetryMode { None, OnlyLogging { logger: InfoLogger, log_best: usize, log_population: usize, dump_population: bool, }, OnlyMetrics { track_population: usize, }, All { logger: InfoLogger, log_best: usize, log_population: usize, track_population: usize, dump_population: bool, }, } pub struct Telemetry { metrics: Metrics, time: Timer, mode: TelemetryMode, improvement_tracker: ImprovementTracker, next_generation: Option<usize>, } impl Telemetry { pub fn new(mode: TelemetryMode) -> Self { Self { time: Timer::start(), metrics: Metrics { duration: 0, generations: 0, speed: 0.0, evolution: vec![] }, mode, improvement_tracker: ImprovementTracker::new(1000), next_generation: None, } } pub fn start(&mut self) { self.time = Timer::start(); } pub fn on_initial(&mut self, item_idx: usize, total_items: usize, item_time: Timer, termination_estimate: f64) { match &self.mode { TelemetryMode::OnlyLogging { .. } | TelemetryMode::All { .. } => self.log( format!( "[{}s] created {} of {} initial solutions in {}ms (ts: {})", self.time.elapsed_secs(), item_idx + 1, total_items, item_time.elapsed_millis(), termination_estimate, ) .as_str(), ), _ => {} }; } pub fn on_generation( &mut self, refinement_ctx: &mut RefinementContext, termination_estimate: f64, generation_time: Timer, is_improved: bool, ) { let generation = self.next_generation.unwrap_or(0); self.metrics.generations = generation; self.improvement_tracker.track(generation, is_improved); refinement_ctx.statistics = Statistics { generation, improvement_all_ratio: self.improvement_tracker.i_all_ratio, improvement_1000_ratio: self.improvement_tracker.i_1000_ratio, termination_estimate, }; self.next_generation = Some(generation + 1); let (log_best, log_population, track_population, should_dump_population) = match &self.mode { TelemetryMode::None => return, TelemetryMode::OnlyLogging { log_best, log_population, dump_population, .. } => { (Some(log_best), Some(log_population), None, *dump_population) } TelemetryMode::OnlyMetrics { track_population, .. } => (None, None, Some(track_population), false), TelemetryMode::All { log_best, log_population, track_population, dump_population, .. } => { (Some(log_best), Some(log_population), Some(track_population), *dump_population) } }; if let Some((best_individual, rank)) = refinement_ctx.population.ranked().next() { let should_log_best = generation % *log_best.unwrap_or(&usize::MAX) == 0; let should_log_population = generation % *log_population.unwrap_or(&usize::MAX) == 0; let should_track_population = generation % *track_population.unwrap_or(&usize::MAX) == 0; if should_log_best { self.log_individual( &self.get_individual_metrics(refinement_ctx, &best_individual, rank), Some((refinement_ctx.statistics.generation, generation_time)), ) } self.on_population(&refinement_ctx, should_log_population, should_track_population, should_dump_population); } else { self.log("no progress yet"); } } fn on_population( &mut self, refinement_ctx: &RefinementContext, should_log_population: bool, should_track_population: bool, should_dump_population: bool, ) { if !should_log_population && !should_track_population { return; } if should_log_population { self.log( format!( "[{}s] population state (phase: {}, speed: {:.2} gen/sec, improvement ratio: {:.3}:{:.3}):", self.time.elapsed_secs(), Self::get_selection_phase(refinement_ctx), refinement_ctx.statistics.generation as f64 / self.time.elapsed_secs_as_f64(), self.improvement_tracker.i_all_ratio, self.improvement_tracker.i_1000_ratio, ) .as_str(), ); } let individuals = refinement_ctx .population .ranked() .map(|(insertion_ctx, rank)| self.get_individual_metrics(refinement_ctx, &insertion_ctx, rank)) .collect::<Vec<_>>(); if should_log_population { individuals.iter().for_each(|metrics| self.log_individual(&metrics, None)); if should_dump_population { self.log(&format!("\t{}", Self::get_population_state(refinement_ctx))); } } if should_track_population { self.metrics.evolution.push(Generation { number: refinement_ctx.statistics.generation, timestamp: self.time.elapsed_secs_as_f64(), i_all_ratio: self.improvement_tracker.i_all_ratio, i_1000_ratio: self.improvement_tracker.i_1000_ratio, is_improvement: self.improvement_tracker.is_last_improved, population: Population { individuals }, }); } } pub fn on_result(&mut self, refinement_ctx: &RefinementContext) { let generations = refinement_ctx.statistics.generation; let (should_log_population, should_track_population) = match &self.mode { TelemetryMode::OnlyLogging { .. } => (true, false), TelemetryMode::OnlyMetrics { track_population, .. } => (false, generations % track_population != 0), TelemetryMode::All { track_population, .. } => (true, generations % track_population != 0), _ => return, }; self.on_population(refinement_ctx, should_log_population, should_track_population, false); let elapsed = self.time.elapsed_secs() as usize; let speed = refinement_ctx.statistics.generation as f64 / self.time.elapsed_secs_as_f64(); self.log(format!("[{}s] total generations: {}, speed: {:.2} gen/sec", elapsed, generations, speed).as_str()); self.metrics.duration = elapsed; self.metrics.speed = speed; } pub fn get_metrics(self) -> Option<Metrics> { match &self.mode { TelemetryMode::OnlyMetrics { .. } | TelemetryMode::All { .. } => Some(self.metrics), _ => None, } } pub fn log(&self, message: &str) { match &self.mode { TelemetryMode::OnlyLogging { logger, .. } => logger.deref()(message), TelemetryMode::All { logger, .. } => logger.deref()(message), _ => {} } } fn get_individual_metrics( &self, refinement_ctx: &RefinementContext, insertion_ctx: &InsertionContext, rank: usize, ) -> Individual { let fitness_values = insertion_ctx.get_fitness_values().collect::<Vec<_>>(); let (cost, cost_difference) = Self::get_fitness(refinement_ctx, insertion_ctx); Individual { rank, tours: insertion_ctx.solution.routes.len(), unassigned: insertion_ctx.solution.unassigned.len(), cost, improvement: cost_difference, fitness: fitness_values, } } fn log_individual(&self, metrics: &Individual, gen_info: Option<(usize, Timer)>) { self.log( format!( "{} rank: {}, cost: {:.2}({:.3}%), tours: {}, unassigned: {}, fitness: ({})", gen_info.map_or("\t".to_string(), |(gen, gen_time)| format!( "[{}s] generation {} took {}ms,", self.time.elapsed_secs(), gen, gen_time.elapsed_millis() )), metrics.rank, metrics.cost, metrics.improvement, metrics.tours, metrics.unassigned, metrics.fitness.iter().map(|v| format!("{:.3}", v)).collect::<Vec<_>>().join(", ") ) .as_str(), ); } fn get_fitness(refinement_ctx: &RefinementContext, insertion_ctx: &InsertionContext) -> (f64, f64) { let fitness_value = refinement_ctx.problem.objective.fitness(insertion_ctx); let fitness_change = refinement_ctx .population .ranked() .next() .map(|(best_ctx, _)| refinement_ctx.problem.objective.fitness(best_ctx)) .map(|best_fitness| (fitness_value - best_fitness) / best_fitness * 100.) .unwrap_or(0.); (fitness_value, fitness_change) } fn get_population_state(refinement_ctx: &RefinementContext) -> String { let mut state = String::new(); write!(state, "{}", refinement_ctx.population).unwrap(); state } fn get_selection_phase(refinement_ctx: &RefinementContext) -> &str { match refinement_ctx.population.selection_phase() { SelectionPhase::Initial => "initial", SelectionPhase::Exploration => "exploration", SelectionPhase::Exploitation => "exploitation", } } } struct ImprovementTracker { buffer: Vec<bool>, total_improvements: usize, pub i_all_ratio: f64, pub i_1000_ratio: f64, pub is_last_improved: bool, } impl ImprovementTracker { pub fn new(size: usize) -> Self { Self { buffer: vec![false; size], total_improvements: 0, i_all_ratio: 0., i_1000_ratio: 0., is_last_improved: false, } } pub fn track(&mut self, generation: usize, is_improved: bool) { let length = self.buffer.len(); if is_improved { self.total_improvements += 1; } self.is_last_improved = is_improved; self.buffer[generation % length] = is_improved; let improvements = (0..generation + 1).zip(self.buffer.iter()).filter(|(_, is_improved)| **is_improved).count(); self.i_all_ratio = (self.total_improvements as f64) / ((generation + 1) as f64); self.i_1000_ratio = (improvements as f64) / ((generation + 1).min(self.buffer.len()) as f64); } }
#[cfg(test)] #[path = "../../tests/unit/solver/telemetry_test.rs"] mod telemetry_test; use crate::algorithms::nsga2::Objective; use crate::construction::heuristics::InsertionContext; use crate::solver::population::SelectionPhase; use crate::solver::{RefinementContext, Statistics}; use crate::utils::Ti
termination_estimate, }; self.next_generation = Some(generation + 1); let (log_best, log_population, track_population, should_dump_population) = match &self.mode { TelemetryMode::None => return, TelemetryMode::OnlyLogging { log_best, log_population, dump_population, .. } => { (Some(log_best), Some(log_population), None, *dump_population) } TelemetryMode::OnlyMetrics { track_population, .. } => (None, None, Some(track_population), false), TelemetryMode::All { log_best, log_population, track_population, dump_population, .. } => { (Some(log_best), Some(log_population), Some(track_population), *dump_population) } }; if let Some((best_individual, rank)) = refinement_ctx.population.ranked().next() { let should_log_best = generation % *log_best.unwrap_or(&usize::MAX) == 0; let should_log_population = generation % *log_population.unwrap_or(&usize::MAX) == 0; let should_track_population = generation % *track_population.unwrap_or(&usize::MAX) == 0; if should_log_best { self.log_individual( &self.get_individual_metrics(refinement_ctx, &best_individual, rank), Some((refinement_ctx.statistics.generation, generation_time)), ) } self.on_population(&refinement_ctx, should_log_population, should_track_population, should_dump_population); } else { self.log("no progress yet"); } } fn on_population( &mut self, refinement_ctx: &RefinementContext, should_log_population: bool, should_track_population: bool, should_dump_population: bool, ) { if !should_log_population && !should_track_population { return; } if should_log_population { self.log( format!( "[{}s] population state (phase: {}, speed: {:.2} gen/sec, improvement ratio: {:.3}:{:.3}):", self.time.elapsed_secs(), Self::get_selection_phase(refinement_ctx), refinement_ctx.statistics.generation as f64 / self.time.elapsed_secs_as_f64(), self.improvement_tracker.i_all_ratio, self.improvement_tracker.i_1000_ratio, ) .as_str(), ); } let individuals = refinement_ctx .population .ranked() .map(|(insertion_ctx, rank)| self.get_individual_metrics(refinement_ctx, &insertion_ctx, rank)) .collect::<Vec<_>>(); if should_log_population { individuals.iter().for_each(|metrics| self.log_individual(&metrics, None)); if should_dump_population { self.log(&format!("\t{}", Self::get_population_state(refinement_ctx))); } } if should_track_population { self.metrics.evolution.push(Generation { number: refinement_ctx.statistics.generation, timestamp: self.time.elapsed_secs_as_f64(), i_all_ratio: self.improvement_tracker.i_all_ratio, i_1000_ratio: self.improvement_tracker.i_1000_ratio, is_improvement: self.improvement_tracker.is_last_improved, population: Population { individuals }, }); } } pub fn on_result(&mut self, refinement_ctx: &RefinementContext) { let generations = refinement_ctx.statistics.generation; let (should_log_population, should_track_population) = match &self.mode { TelemetryMode::OnlyLogging { .. } => (true, false), TelemetryMode::OnlyMetrics { track_population, .. } => (false, generations % track_population != 0), TelemetryMode::All { track_population, .. } => (true, generations % track_population != 0), _ => return, }; self.on_population(refinement_ctx, should_log_population, should_track_population, false); let elapsed = self.time.elapsed_secs() as usize; let speed = refinement_ctx.statistics.generation as f64 / self.time.elapsed_secs_as_f64(); self.log(format!("[{}s] total generations: {}, speed: {:.2} gen/sec", elapsed, generations, speed).as_str()); self.metrics.duration = elapsed; self.metrics.speed = speed; } pub fn get_metrics(self) -> Option<Metrics> { match &self.mode { TelemetryMode::OnlyMetrics { .. } | TelemetryMode::All { .. } => Some(self.metrics), _ => None, } } pub fn log(&self, message: &str) { match &self.mode { TelemetryMode::OnlyLogging { logger, .. } => logger.deref()(message), TelemetryMode::All { logger, .. } => logger.deref()(message), _ => {} } } fn get_individual_metrics( &self, refinement_ctx: &RefinementContext, insertion_ctx: &InsertionContext, rank: usize, ) -> Individual { let fitness_values = insertion_ctx.get_fitness_values().collect::<Vec<_>>(); let (cost, cost_difference) = Self::get_fitness(refinement_ctx, insertion_ctx); Individual { rank, tours: insertion_ctx.solution.routes.len(), unassigned: insertion_ctx.solution.unassigned.len(), cost, improvement: cost_difference, fitness: fitness_values, } } fn log_individual(&self, metrics: &Individual, gen_info: Option<(usize, Timer)>) { self.log( format!( "{} rank: {}, cost: {:.2}({:.3}%), tours: {}, unassigned: {}, fitness: ({})", gen_info.map_or("\t".to_string(), |(gen, gen_time)| format!( "[{}s] generation {} took {}ms,", self.time.elapsed_secs(), gen, gen_time.elapsed_millis() )), metrics.rank, metrics.cost, metrics.improvement, metrics.tours, metrics.unassigned, metrics.fitness.iter().map(|v| format!("{:.3}", v)).collect::<Vec<_>>().join(", ") ) .as_str(), ); } fn get_fitness(refinement_ctx: &RefinementContext, insertion_ctx: &InsertionContext) -> (f64, f64) { let fitness_value = refinement_ctx.problem.objective.fitness(insertion_ctx); let fitness_change = refinement_ctx .population .ranked() .next() .map(|(best_ctx, _)| refinement_ctx.problem.objective.fitness(best_ctx)) .map(|best_fitness| (fitness_value - best_fitness) / best_fitness * 100.) .unwrap_or(0.); (fitness_value, fitness_change) } fn get_population_state(refinement_ctx: &RefinementContext) -> String { let mut state = String::new(); write!(state, "{}", refinement_ctx.population).unwrap(); state } fn get_selection_phase(refinement_ctx: &RefinementContext) -> &str { match refinement_ctx.population.selection_phase() { SelectionPhase::Initial => "initial", SelectionPhase::Exploration => "exploration", SelectionPhase::Exploitation => "exploitation", } } } struct ImprovementTracker { buffer: Vec<bool>, total_improvements: usize, pub i_all_ratio: f64, pub i_1000_ratio: f64, pub is_last_improved: bool, } impl ImprovementTracker { pub fn new(size: usize) -> Self { Self { buffer: vec![false; size], total_improvements: 0, i_all_ratio: 0., i_1000_ratio: 0., is_last_improved: false, } } pub fn track(&mut self, generation: usize, is_improved: bool) { let length = self.buffer.len(); if is_improved { self.total_improvements += 1; } self.is_last_improved = is_improved; self.buffer[generation % length] = is_improved; let improvements = (0..generation + 1).zip(self.buffer.iter()).filter(|(_, is_improved)| **is_improved).count(); self.i_all_ratio = (self.total_improvements as f64) / ((generation + 1) as f64); self.i_1000_ratio = (improvements as f64) / ((generation + 1).min(self.buffer.len()) as f64); } }
mer; use std::fmt::Write; use std::ops::Deref; use std::sync::Arc; pub type InfoLogger = Arc<dyn Fn(&str)>; pub struct Metrics { pub duration: usize, pub generations: usize, pub speed: f64, pub evolution: Vec<Generation>, } pub struct Generation { pub number: usize, pub timestamp: f64, pub i_all_ratio: f64, pub i_1000_ratio: f64, pub is_improvement: bool, pub population: Population, } pub struct Individual { pub rank: usize, pub tours: usize, pub unassigned: usize, pub cost: f64, pub improvement: f64, pub fitness: Vec<f64>, } pub struct Population { pub individuals: Vec<Individual>, } pub enum TelemetryMode { None, OnlyLogging { logger: InfoLogger, log_best: usize, log_population: usize, dump_population: bool, }, OnlyMetrics { track_population: usize, }, All { logger: InfoLogger, log_best: usize, log_population: usize, track_population: usize, dump_population: bool, }, } pub struct Telemetry { metrics: Metrics, time: Timer, mode: TelemetryMode, improvement_tracker: ImprovementTracker, next_generation: Option<usize>, } impl Telemetry { pub fn new(mode: TelemetryMode) -> Self { Self { time: Timer::start(), metrics: Metrics { duration: 0, generations: 0, speed: 0.0, evolution: vec![] }, mode, improvement_tracker: ImprovementTracker::new(1000), next_generation: None, } } pub fn start(&mut self) { self.time = Timer::start(); } pub fn on_initial(&mut self, item_idx: usize, total_items: usize, item_time: Timer, termination_estimate: f64) { match &self.mode { TelemetryMode::OnlyLogging { .. } | TelemetryMode::All { .. } => self.log( format!( "[{}s] created {} of {} initial solutions in {}ms (ts: {})", self.time.elapsed_secs(), item_idx + 1, total_items, item_time.elapsed_millis(), termination_estimate, ) .as_str(), ), _ => {} }; } pub fn on_generation( &mut self, refinement_ctx: &mut RefinementContext, termination_estimate: f64, generation_time: Timer, is_improved: bool, ) { let generation = self.next_generation.unwrap_or(0); self.metrics.generations = generation; self.improvement_tracker.track(generation, is_improved); refinement_ctx.statistics = Statistics { generation, improvement_all_ratio: self.improvement_tracker.i_all_ratio, improvement_1000_ratio: self.improvement_tracker.i_1000_ratio,
random
[ { "content": "fn create_file(path: &str, description: &str) -> File {\n\n File::create(path).unwrap_or_else(|err| {\n\n eprintln!(\"Cannot create {} file '{}': '{}'\", description, path, err.to_string());\n\n process::exit(1);\n\n })\n\n}\n\n\n\n// TODO avoid code duplication (macros?)\n\n\n...
Rust
lib/engine-universal/src/unwind/windows_x64.rs
DumbMachine/wasmer
84727032e59bee88a4a5b8860cf593f7cfdd0baf
use loupe::{MemoryUsage, MemoryUsageTracker}; use std::collections::HashMap; use wasmer_compiler::CompiledFunctionUnwindInfo; use winapi::um::winnt; pub struct UnwindRegistry { functions: HashMap<usize, Vec<winnt::RUNTIME_FUNCTION>>, published: bool, } impl UnwindRegistry { pub fn new() -> Self { Self { functions: HashMap::new(), published: false, } } pub fn register( &mut self, base_address: usize, func_start: u32, func_len: u32, info: &CompiledFunctionUnwindInfo, ) -> Result<(), String> { if self.published { return Err("unwind registry has already been published".to_string()); } match info { CompiledFunctionUnwindInfo::WindowsX64(_) => {} _ => return Err("unsupported unwind information".to_string()), }; let mut entry = winnt::RUNTIME_FUNCTION::default(); entry.BeginAddress = func_start; entry.EndAddress = func_start + func_len; unsafe { *entry.u.UnwindInfoAddress_mut() = (entry.EndAddress + 3) & !3; } let entries = self .functions .entry(base_address) .or_insert_with(|| Vec::new()); entries.push(entry); Ok(()) } pub fn publish(&mut self, _eh_frame: Option<&[u8]>) -> Result<(), String> { if self.published { return Err("unwind registry has already been published".to_string()); } self.published = true; if !self.functions.is_empty() { for (base_address, functions) in self.functions.iter_mut() { assert_eq!( (functions.as_mut_ptr() as u64) % 4, 0, "function table allocation was not aligned" ); unsafe { if winnt::RtlAddFunctionTable( functions.as_mut_ptr(), functions.len() as u32, *base_address as u64, ) == 0 { return Err("failed to register function tables".to_string()); } } } } Ok(()) } } impl Drop for UnwindRegistry { fn drop(&mut self) { if self.published { unsafe { for functions in self.functions.values_mut() { winnt::RtlDeleteFunctionTable(functions.as_mut_ptr()); } } } } } impl MemoryUsage for UnwindRegistry { fn size_of_val(&self, tracker: &mut dyn MemoryUsageTracker) -> usize { self.functions .iter() .map(|(_, _)| std::mem::size_of::<u64>() * 3) .sum::<usize>() + self.published.size_of_val(tracker) } }
use loupe::{MemoryUsage, MemoryUsageTracker}; use std::collections::HashMap; use wasmer_compiler::CompiledFunctionUnwindInfo; use winapi::um::winnt; pub struct UnwindRegistry { functions: HashMap<usize, Vec<winnt::RUNTIME_FUNCTION>>, published: bool, } impl UnwindRegistry { pub fn new() -> Self { Self { functions: HashMap::new(), published: false, } } pub fn register( &mut self, base_address: usize, func_start: u32, func_len: u32, info: &CompiledFunctionUnwindInfo, ) -> Result<(), String> { if self.published { return Err("unwind registry has already been published".to_string()); } match info { CompiledFunctionUnwindInfo::WindowsX64(_) => {} _ => return Err("unsupported unwind information".to_string()), }; let mut entry = winnt::RUNTIME_FUNCTION::default(); entry.BeginAddress = func_start; entry.EndAddress = func_start + func_len; unsafe { *entry.u.UnwindInfoAddress_mut() = (entry.EndAddress + 3) & !3; } let entries = self .functions .entry(base_address) .or_insert_with(|| Vec::new()); entries.push(entry); Ok(()) } pub fn publish(&mut self, _eh_frame: Option<&[u8]>) -> Result<(), String> { if self.published { return Err("unwind registry has already been published".to_string()); } self.published = true; if !self.functions.is_empty() { for (base_address, functions) in self.functions.iter_mut() { assert_eq!( (functions.as_mut_ptr() as u64) % 4, 0, "function table allocation was not aligned" ); unsafe { if winnt::RtlAddFunctionTable( functions.as_mut_ptr(), functions.len() as u32, *base_address as u64, ) == 0 { return Err("failed to register function tables".to_string()); } } } } Ok(()) } } impl Drop for UnwindRegistry { fn drop(&mut self) { if self.published { unsafe { for functions in self.functions.values_mut() { winnt::RtlDeleteFunctionTable(functions.as_mut_ptr()); } } } } } impl MemoryUsage for UnwindRegistry {
}
fn size_of_val(&self, tracker: &mut dyn MemoryUsageTracker) -> usize { self.functions .iter() .map(|(_, _)| std::mem::size_of::<u64>() * 3) .sum::<usize>() + self.published.size_of_val(tracker) }
function_block-full_function
[ { "content": "pub fn get_emscripten_table_size(module: &Module) -> Result<(u32, Option<u32>), String> {\n\n if let Some(import) = module.imports().tables().next() {\n\n let ty = import.ty();\n\n Ok((ty.minimum, ty.maximum))\n\n } else {\n\n Err(\"Emscripten requires at least one impor...
Rust
gtk/src/flash.rs
system76/muf
a1561b32acad891424da8b6de8ae012f39f83d05
use atomic::Atomic; use dbus::arg::{OwnedFd, RefArg, Variant}; use dbus::blocking::{Connection, Proxy}; use dbus_udisks2::DiskDevice; use futures::executor; use libc; use popsicle::{Progress, Task}; use std::cell::Cell; use std::collections::HashMap; use std::fmt::{self, Debug, Display, Formatter}; use std::fs::File; use std::os::unix::io::FromRawFd; use std::str; use std::sync::atomic::Ordering; use std::sync::{Arc, Mutex}; use std::time::Duration; type UDisksOptions = HashMap<&'static str, Variant<Box<dyn RefArg>>>; #[derive(Clone, Copy, PartialEq)] pub enum FlashStatus { Inactive, Active, Killing, } pub struct FlashRequest { source: Option<File>, destinations: Vec<Arc<DiskDevice>>, status: Arc<Atomic<FlashStatus>>, progress: Arc<Vec<Atomic<u64>>>, finished: Arc<Vec<Atomic<bool>>>, } pub struct FlashTask { pub progress: Arc<Vec<Atomic<u64>>>, pub previous: Arc<Mutex<Vec<[u64; 7]>>>, pub finished: Arc<Vec<Atomic<bool>>>, } struct FlashProgress<'a> { request: &'a FlashRequest, id: usize, errors: &'a [Cell<Result<(), FlashError>>], } #[derive(Clone, Debug)] pub struct FlashError { kind: String, message: String, } impl Display for FlashError { fn fmt(&self, f: &mut Formatter) -> fmt::Result { write!(f, "{}: {}", self.kind, self.message) } } impl std::error::Error for FlashError {} impl<'a> Progress for FlashProgress<'a> { type Device = (); fn message(&mut self, _device: &(), kind: &str, message: &str) { self.errors[self.id] .set(Err(FlashError { kind: kind.to_string(), message: message.to_string() })); } fn finish(&mut self) { self.request.finished[self.id].store(true, Ordering::SeqCst); } fn set(&mut self, value: u64) { self.request.progress[self.id].store(value, Ordering::SeqCst); } } impl FlashRequest { pub fn new( source: File, destinations: Vec<Arc<DiskDevice>>, status: Arc<Atomic<FlashStatus>>, progress: Arc<Vec<Atomic<u64>>>, finished: Arc<Vec<Atomic<bool>>>, ) -> FlashRequest { FlashRequest { source: Some(source), destinations, status, progress, finished } } pub fn write(mut self) -> anyhow::Result<(anyhow::Result<()>, Vec<Result<(), FlashError>>)> { self.status.store(FlashStatus::Active, Ordering::SeqCst); let source = self.source.take().unwrap(); let res = self.write_inner(source); for atomic in self.finished.iter() { atomic.store(true, Ordering::SeqCst); } self.status.store(FlashStatus::Inactive, Ordering::SeqCst); res } fn write_inner<'a>( &'a self, source: File, ) -> anyhow::Result<(anyhow::Result<()>, Vec<Result<(), FlashError>>)> { for device in &self.destinations { let _ = udisks_unmount(&device.parent.path); for partition in &device.partitions { let _ = udisks_unmount(&partition.path); } } let mut files = Vec::new(); for device in &self.destinations { let file = udisks_open(&device.parent.path)?; files.push(file); } let mut errors = vec![Ok(()); files.len()]; let errors_cells = Cell::from_mut(&mut errors as &mut [_]).as_slice_of_cells(); let mut bucket = [0u8; 64 * 1024]; let mut task = Task::new(source.into(), false); for (i, file) in files.into_iter().enumerate() { let progress = FlashProgress { request: &self, errors: errors_cells, id: i }; task.subscribe(file.into(), (), progress); } let res = executor::block_on(task.process(&mut bucket)); Ok((res, errors)) } } fn udisks_unmount(dbus_path: &str) -> anyhow::Result<()> { let connection = Connection::new_system()?; let dbus_path = ::dbus::strings::Path::new(dbus_path).map_err(anyhow::Error::msg)?; let proxy = Proxy::new("org.freedesktop.UDisks2", dbus_path, Duration::new(25, 0), &connection); let mut options = UDisksOptions::new(); options.insert("force", Variant(Box::new(true))); let res: Result<(), _> = proxy.method_call("org.freedesktop.UDisks2.Filesystem", "Unmount", (options,)); if let Err(err) = res { if err.name() != Some("org.freedesktop.UDisks2.Error.NotMounted") { return Err(anyhow::Error::new(err)); } } Ok(()) } fn udisks_open(dbus_path: &str) -> anyhow::Result<File> { let connection = Connection::new_system()?; let dbus_path = ::dbus::strings::Path::new(dbus_path).map_err(anyhow::Error::msg)?; let proxy = Proxy::new("org.freedesktop.UDisks2", &dbus_path, Duration::new(25, 0), &connection); let mut options = UDisksOptions::new(); options.insert("flags", Variant(Box::new(libc::O_SYNC))); let res: (OwnedFd,) = proxy.method_call("org.freedesktop.UDisks2.Block", "OpenDevice", ("rw", options))?; Ok(unsafe { File::from_raw_fd(res.0.into_fd()) }) }
use atomic::Atomic; use dbus::arg::{OwnedFd, RefArg, Variant}; use dbus::blocking::{Connection, Proxy}; use dbus_udisks2::DiskDevice; use futures::executor; use libc; use popsicle::{Progress, Task}; use std::cell::Cell; use std::collections::HashMap; use std::fmt::{self, Debug, Display, Formatter}; use std::fs::File; use std::os::unix::io::FromRawFd; use std::str; use std::sync::atomic::Ordering; use std::sync::{Arc, Mutex}; use std::time::Duration; type UDisksOptions = HashMap<&'static str, Variant<Box<dyn RefArg>>>; #[derive(Clone, Copy, PartialEq)] pub enum FlashStatus { Inactive, Active, Killing, } pub struct FlashRequest { source: Option<File>, destinations: Vec<Arc<DiskDevice>>, status: Arc<Atomic<FlashStatus>>, progress: Arc<Vec<Atomic<u64>>>, finished: Arc<Vec<Atomic<bool>>>, } pub struct FlashTask { pub progress: Arc<Vec<Atomic<u64>>>, pub previous: Arc<Mutex<Vec<[u64; 7]>>>, pub finished: Arc<Vec<Atomic<bool>>>, } struct FlashProgress<'a> { request: &'a FlashRequest, id: usize, errors: &'a [Cell<Result<(), FlashError>>], } #[derive(Clone, Debug)] pub struct FlashError { kind: String, message: String, } impl Display for FlashError { fn fmt(&self, f: &mut Formatter) -> fmt::Result { write!(f, "{}: {}", self.kind, self.message) } } impl std::error::Error for FlashError {} impl<'a> Progress for FlashProgress<'a> { type Device = (); fn message(&mut self, _device: &(), kind: &str, message: &str) { self.errors[self.id] .set(Err(FlashError { kind: kind.to_string(), message: message.to_string() })); } fn finish(&mut self) { self.request.finished[self.id].store(true, Ordering::SeqCst); } fn set(&mut self, value: u64) { self.request.progress[self.id].store(value, Ordering::SeqCst); } } impl FlashRequest { pub fn new( source: File, destinations: Vec<Arc<DiskDevice>>, status: Arc<Atomic<FlashStatus>>, progress: Arc<Vec<Atomic<u64>>>, finished: Arc<Vec<Atomic<bool>>>, ) -> FlashRequest { FlashRequest { source: Some(source), destinations, status, progress, finished } } pub fn write(mut self) -> anyhow::Result<(anyhow::Result<()>, Vec<Result<(), FlashError>>)> { self.status.store(FlashStatus::Active, Ordering::SeqCst); let source = self.source.take().unwrap(); let res = self.write_inner(source); for atomic in self.finished.iter() { atomic.store(true, Ordering::SeqCst); } self.status.store(FlashStatus::Inactive, Ordering::SeqCst); res } fn write_inner<'a>( &'a self, source: File, ) -> anyhow::Result<(anyhow::Result<()>, Vec<Result<(), FlashError>>)> { for device in &self.destinations { let _ = udisks_unmount(&device.parent.path); for partition in &device.partitions { let _ = udisks_unmount(&partition.path); } } let mut files = Vec::new(); for device in &self.destinations { let file = udisks_open(&device.parent.path)?; files.push(file); } let mut errors = vec![Ok(()); files.len()]; let errors_cells = Cell::from_mut(&mut errors as &mut [_]).as_slice_of_cells(); let mut bucket = [0u8; 64 * 1024]; let mut task = Task::new(source.into(), false); for (i, file) in files.into_iter().enumerate() { let progress = FlashProgress { request: &self, errors: errors_cells, id: i }; task.subscribe(file.into(), (), progress); } let res = executor::block_on(task.process(&mut bucket)); Ok((res, errors)) } } fn udisks_unmount(dbus_path: &str) -> anyhow::Result<()> { let connection = Connection::new_system()?; let dbus_path = ::dbus::strings::Path::new(dbus_path).map_err(anyhow::Error::msg)?; let proxy = Proxy::new("org.freedesktop.UDisks2", dbus_path, Duration::new(25, 0), &connection); let mut options = UDisksOptions::new(); options.insert("force", Variant(Box::new(true))); let res: Result<(), _> = proxy.method_call("org.freedesktop.UDisks2.Filesystem", "Unmount", (options,)); if let Err(err) = res {
} Ok(()) } fn udisks_open(dbus_path: &str) -> anyhow::Result<File> { let connection = Connection::new_system()?; let dbus_path = ::dbus::strings::Path::new(dbus_path).map_err(anyhow::Error::msg)?; let proxy = Proxy::new("org.freedesktop.UDisks2", &dbus_path, Duration::new(25, 0), &connection); let mut options = UDisksOptions::new(); options.insert("flags", Variant(Box::new(libc::O_SYNC))); let res: (OwnedFd,) = proxy.method_call("org.freedesktop.UDisks2.Block", "OpenDevice", ("rw", options))?; Ok(unsafe { File::from_raw_fd(res.0.into_fd()) }) }
if err.name() != Some("org.freedesktop.UDisks2.Error.NotMounted") { return Err(anyhow::Error::new(err)); }
if_condition
[ { "content": "pub fn init() -> Result<(), glib::Error> {\n\n const GRESOURCE: &[u8] = include_bytes!(concat!(env!(\"OUT_DIR\"), \"/compiled.gresource\"));\n\n\n\n gio::resources_register(&gio::Resource::from_data(&glib::Bytes::from_static(GRESOURCE))?);\n\n\n\n let theme = gtk::IconTheme::default().unw...
Rust
rust/envop/src/main.rs
eagletmt/misc
cb4d3d3d19a00161ad7e87056d007ee043effed7
use std::io::Write as _; fn main() -> Result<(), Box<dyn std::error::Error>> { let mut args = std::env::args(); let me = args.next().unwrap(); let name = args.next().unwrap_or_else(|| { eprintln!("Usage: {} NAME PROG ARGS...", me); std::process::exit(1); }); let prog = args.next().unwrap_or_else(|| { eprintln!("Usage: {} NAME PROG ARGS...", me); std::process::exit(1); }); let tags = std::env::var("ENVOP_TAGS").unwrap_or_else(|_| "envop".to_owned()); let vault = std::env::var("ENVOP_VAULT").unwrap_or_else(|_| "Private".to_owned()); let output = std::process::Command::new("op") .arg("list") .arg("items") .arg("--vault") .arg(&vault) .arg("--categories") .arg("Secure Note") .arg("--tags") .arg(&tags) .output()?; if !output.status.success() { eprintln!("`op list items` failed"); std::io::stdout().write_all(&output.stdout)?; std::io::stderr().write_all(&output.stderr)?; std::process::exit(output.status.code().unwrap_or(1)); } let item_summaries: Vec<ItemSummary> = serde_json::from_slice(&output.stdout)?; let mut envs = Vec::new(); for item_summary in item_summaries .into_iter() .filter(|item_summary| item_summary.overview.title == name) { let output = std::process::Command::new("op") .arg("get") .arg("item") .arg("--vault") .arg(&vault) .arg(&item_summary.uuid) .output()?; if !output.status.success() { eprintln!("`op get item {}` failed", item_summary.uuid); std::io::stdout().write_all(&output.stdout)?; std::io::stderr().write_all(&output.stderr)?; std::process::exit(output.status.code().unwrap_or(1)); } let item: Item = serde_json::from_slice(&output.stdout)?; for section in item.details.sections.into_iter() { for field in section.fields.into_iter() { if field.k == "string" || field.k == "concealed" { envs.push((field.t, field.v)); } else { eprintln!( "{}: ignoring field {} in item {}", me, field.t, item_summary.uuid ); } } } } let mut cmd = std::process::Command::new(&prog); cmd.envs(envs).args(args); let status = exec(cmd)?; if !status.success() { std::process::exit(status.code().unwrap_or(1)); } Ok(()) } #[cfg(unix)] fn exec( mut cmd: std::process::Command, ) -> Result<std::process::ExitStatus, Box<dyn std::error::Error>> { use std::os::unix::process::CommandExt as _; Err(Box::new(cmd.exec())) } #[cfg(windows)] fn exec( mut cmd: std::process::Command, ) -> Result<std::process::ExitStatus, Box<dyn std::error::Error>> { Ok(cmd.status()?) } #[derive(Debug, serde::Deserialize)] struct ItemSummary { uuid: String, overview: ItemOverview, } #[derive(Debug, serde::Deserialize)] struct ItemOverview { title: String, } #[derive(Debug, serde::Deserialize)] struct Item { details: ItemDetails, } #[derive(Debug, serde::Deserialize)] struct ItemDetails { sections: Vec<ItemSection>, } #[derive(Debug, serde::Deserialize)] struct ItemSection { fields: Vec<ItemField>, } #[derive(Debug, serde::Deserialize)] struct ItemField { k: String, t: String, v: String, }
use std::io::Write as _; fn main() -> Result<(), Box<dyn std::error::Error>> { let mut args = std::env::args(); let me = args.next().unwrap(); let name = args.next().unwrap_or_else(|| { eprintln!("Usage: {} NAME PROG ARGS...", me); std::process::exit(1); }); let prog = args.next().unwrap_or_else(|| { eprintln!("Usage: {} NAME PROG ARGS...", me); std::process::exit(1); }); let tags = std::env::var("ENVOP_TAGS").unwrap_or_else(|_| "envop".to_owned()); let vault = std::env::var("ENVOP_VAULT").unwrap_or_else(|_| "Private".to_owned()); let output = std::process::Comm
tderr().write_all(&output.stderr)?; std::process::exit(output.status.code().unwrap_or(1)); } let item_summaries: Vec<ItemSummary> = serde_json::from_slice(&output.stdout)?; let mut envs = Vec::new(); for item_summary in item_summaries .into_iter() .filter(|item_summary| item_summary.overview.title == name) { let output = std::process::Command::new("op") .arg("get") .arg("item") .arg("--vault") .arg(&vault) .arg(&item_summary.uuid) .output()?; if !output.status.success() { eprintln!("`op get item {}` failed", item_summary.uuid); std::io::stdout().write_all(&output.stdout)?; std::io::stderr().write_all(&output.stderr)?; std::process::exit(output.status.code().unwrap_or(1)); } let item: Item = serde_json::from_slice(&output.stdout)?; for section in item.details.sections.into_iter() { for field in section.fields.into_iter() { if field.k == "string" || field.k == "concealed" { envs.push((field.t, field.v)); } else { eprintln!( "{}: ignoring field {} in item {}", me, field.t, item_summary.uuid ); } } } } let mut cmd = std::process::Command::new(&prog); cmd.envs(envs).args(args); let status = exec(cmd)?; if !status.success() { std::process::exit(status.code().unwrap_or(1)); } Ok(()) } #[cfg(unix)] fn exec( mut cmd: std::process::Command, ) -> Result<std::process::ExitStatus, Box<dyn std::error::Error>> { use std::os::unix::process::CommandExt as _; Err(Box::new(cmd.exec())) } #[cfg(windows)] fn exec( mut cmd: std::process::Command, ) -> Result<std::process::ExitStatus, Box<dyn std::error::Error>> { Ok(cmd.status()?) } #[derive(Debug, serde::Deserialize)] struct ItemSummary { uuid: String, overview: ItemOverview, } #[derive(Debug, serde::Deserialize)] struct ItemOverview { title: String, } #[derive(Debug, serde::Deserialize)] struct Item { details: ItemDetails, } #[derive(Debug, serde::Deserialize)] struct ItemDetails { sections: Vec<ItemSection>, } #[derive(Debug, serde::Deserialize)] struct ItemSection { fields: Vec<ItemField>, } #[derive(Debug, serde::Deserialize)] struct ItemField { k: String, t: String, v: String, }
and::new("op") .arg("list") .arg("items") .arg("--vault") .arg(&vault) .arg("--categories") .arg("Secure Note") .arg("--tags") .arg(&tags) .output()?; if !output.status.success() { eprintln!("`op list items` failed"); std::io::stdout().write_all(&output.stdout)?; std::io::s
random
[ { "content": "fn main() -> anyhow::Result<()> {\n\n env_logger::Builder::from_env(env_logger::Env::default().default_filter_or(\"info\")).init();\n\n\n\n for arg in std::env::args().skip(1) {\n\n unpack(&arg).with_context(|| format!(\"failed to unpack {}\", arg))?;\n\n }\n\n Ok(())\n\n}\n\n\n...
Rust
src/mbart/encoder.rs
eonm-abes/rust-bert
24fdb2dfb41e7cad6367f77e905570649bb7aefe
use crate::bart::{BartEncoderOutput, _expand_mask}; use crate::common::activations::TensorFunction; use crate::common::dropout::Dropout; use crate::mbart::attention::MBartAttention; use crate::mbart::embeddings::MBartLearnedPositionalEmbedding; use crate::mbart::MBartConfig; use crate::Activation; use std::borrow::{Borrow, BorrowMut}; use tch::{nn, Tensor}; pub struct MBartEncoderLayer { self_attention: MBartAttention, self_attention_layer_norm: nn::LayerNorm, dropout: Dropout, activation_dropout: Dropout, activation: TensorFunction, fc1: nn::Linear, fc2: nn::Linear, final_layer_norm: nn::LayerNorm, } impl MBartEncoderLayer { pub fn new<'p, P>(p: P, config: &MBartConfig) -> MBartEncoderLayer where P: Borrow<nn::Path<'p>>, { let p = p.borrow(); let layer_norm_config = nn::LayerNormConfig { eps: 1e-5, ..Default::default() }; let output_attention = config.output_attentions.unwrap_or(false); let self_attention = MBartAttention::new( p / "self_attn", config.d_model, config.encoder_attention_heads, config.attention_dropout, false, false, output_attention, ); let self_attention_layer_norm = nn::layer_norm( p / "self_attn_layer_norm", vec![config.d_model], layer_norm_config, ); let dropout = Dropout::new(config.dropout); let activation_dropout = Dropout::new(config.activation_dropout); let activation_function = match &config.activation_function { Some(act_function) => act_function, None => &Activation::gelu, }; let activation = activation_function.get_function(); let fc1 = nn::linear( p / "fc1", config.d_model, config.encoder_ffn_dim, Default::default(), ); let fc2 = nn::linear( p / "fc2", config.encoder_ffn_dim, config.d_model, Default::default(), ); let final_layer_norm = nn::layer_norm( p / "final_layer_norm", vec![config.d_model], layer_norm_config, ); MBartEncoderLayer { self_attention, self_attention_layer_norm, dropout, activation_dropout, activation, fc1, fc2, final_layer_norm, } } pub fn forward_t( &self, x: &Tensor, encoder_attention_mask: Option<&Tensor>, train: bool, ) -> (Tensor, Option<Tensor>) { let output = x.apply(&self.self_attention_layer_norm); let (output, attention_weights, _) = self.self_attention .forward_t(&output, None, encoder_attention_mask, None, train); let output: Tensor = output.apply_t(&self.dropout, train) + x; let residual = output.copy(); let output = output.apply(&self.final_layer_norm); let output = (self.activation.get_fn())(&output.apply(&self.fc1)); let output = output .apply_t(&self.activation_dropout, train) .apply(&self.fc2) .apply_t(&self.dropout, train); let output = output + residual; (output, attention_weights) } } pub struct MBartEncoder { dropout: Dropout, layer_norm_embedding: nn::LayerNorm, layer_norm: nn::LayerNorm, layers: Vec<MBartEncoderLayer>, embed_positions: MBartLearnedPositionalEmbedding, output_attentions: bool, output_hidden_states: bool, scale_embedding: f64, } impl MBartEncoder { pub fn new<'p, P>(p: P, config: &MBartConfig) -> MBartEncoder where P: Borrow<nn::Path<'p>>, { let p = p.borrow(); let output_attentions = config.output_attentions.unwrap_or(false); let output_hidden_states = config.output_hidden_states.unwrap_or(false); let scale_embedding = if let Some(scale_embeddings) = config.scale_embedding { if scale_embeddings { (config.d_model as f64).sqrt() } else { 1.0 } } else { 1.0 }; let dropout = Dropout::new(config.dropout); let layer_norm_embedding = nn::layer_norm( p / "layernorm_embedding", vec![config.d_model], Default::default(), ); let layer_norm = nn::layer_norm(p / "layer_norm", vec![config.d_model], Default::default()); let embed_positions = MBartLearnedPositionalEmbedding::new( p / "embed_positions", config.max_position_embeddings, config.d_model, ); let mut layers: Vec<MBartEncoderLayer> = vec![]; let p_layers = p / "layers"; for layer_index in 0..config.encoder_layers { layers.push(MBartEncoderLayer::new(&p_layers / layer_index, config)); } MBartEncoder { dropout, layer_norm_embedding, layer_norm, layers, embed_positions, output_attentions, output_hidden_states, scale_embedding, } } pub fn forward_t( &self, input_ids: &Tensor, attention_mask: Option<&Tensor>, embeddings: &nn::Embedding, train: bool, ) -> MBartEncoderOutput { let attention_mask = attention_mask.map(|mask| _expand_mask(mask, None)); let x = input_ids.apply(embeddings) * self.scale_embedding; let x = x + &self.embed_positions.forward(input_ids, 0); let mut hidden_state = x .apply(&self.layer_norm_embedding) .apply_t(&self.dropout, train); let mut all_hidden_states: Option<Vec<Tensor>> = if self.output_hidden_states { Some(vec![]) } else { None }; let mut all_attentions: Option<Vec<Tensor>> = if self.output_attentions { Some(vec![]) } else { None }; let mut attention_weights: Option<Tensor>; for layer in &self.layers { if let Some(hidden_states) = all_hidden_states.borrow_mut() { hidden_states.push(hidden_state.as_ref().copy()); }; let temp = layer.forward_t(&hidden_state, attention_mask.as_ref(), train); hidden_state = temp.0; attention_weights = temp.1; if let Some(attentions) = all_attentions.borrow_mut() { attentions.push(attention_weights.as_ref().unwrap().copy()); }; } if let Some(hidden_states) = all_hidden_states.borrow_mut() { hidden_states.push(hidden_state.as_ref().copy()); }; hidden_state = hidden_state.apply(&self.layer_norm); MBartEncoderOutput { hidden_state, all_hidden_states, all_attentions, } } } pub type MBartEncoderOutput = BartEncoderOutput;
use crate::bart::{BartEncoderOutput, _expand_mask}; use crate::common::activations::TensorFunction; use crate::common::dropout::Dropout; use crate::mbart::attention::MBartAttention; use crate::mbart::embeddings::MBartLearnedPositionalEmbedding; use crate::mbart::MBartConfig; use crate::Activation; use std::borrow::{Borrow, BorrowMut}; use tch::{nn, Tensor}; pub struct MBartEncoderLayer { self_attention: MBartAttention, self_attention_layer_norm: nn::LayerNorm, dropout: Dropout, activation_dropout: Dropout, activation: TensorFunction, fc1: nn::Linear, fc2: nn::Linear, final_layer_norm: nn::LayerNorm, } impl MBartEncoderLayer { pub fn new<'p, P>(p: P, config: &MBartConfig) -> MBartEncoderLayer where P: Borrow<nn::Path<'p>>, { let p = p.borrow(); let layer_norm_config = nn::LayerNormConfig { eps: 1e-5, ..Default::default() }; let output_attention = config.output_attentions.unwrap_or(false); let self_attention = MBartAttention::new( p / "self_attn", config.d_model, config.encoder_attention_heads, config.attention_dropout, false, false, output_attention, ); let self_attention_layer_norm = nn::layer_norm( p / "self_attn_layer_norm", vec![config.d_model], layer_norm_config, ); let dropout = Dropout::new(config.dropout); let activation_dropout = Dropout::new(config.activation_dropout); let activation_function = match &config.activation_function { Some(act_function) => act_function, None => &Activation::gelu, }; let activation = activation_function.get_function(); let fc1 = nn::linear( p / "fc1", config.d_model, config.encoder_ffn_dim, Default::default(), ); let fc2 = nn::linear( p / "fc2", config.encoder_ffn_dim, config.d_model, Default::default(), ); let final_layer_norm = nn::layer_norm( p / "final_layer_norm", vec![config.d_model], layer_norm_config, ); MBartEncoderLayer { self_attention, self_attention_layer_norm, dropout, activation_dropout, activation, fc1, fc2, final_layer_norm, } } pub fn forward_t( &self, x: &Tensor, encoder_attention_mask: Option<&Tensor>, train: bool, ) -> (Tensor, Option<Tensor>) { let output = x.apply(&self.self_attention_layer_norm); let (output, attention_weights, _) =
} pub struct MBartEncoder { dropout: Dropout, layer_norm_embedding: nn::LayerNorm, layer_norm: nn::LayerNorm, layers: Vec<MBartEncoderLayer>, embed_positions: MBartLearnedPositionalEmbedding, output_attentions: bool, output_hidden_states: bool, scale_embedding: f64, } impl MBartEncoder { pub fn new<'p, P>(p: P, config: &MBartConfig) -> MBartEncoder where P: Borrow<nn::Path<'p>>, { let p = p.borrow(); let output_attentions = config.output_attentions.unwrap_or(false); let output_hidden_states = config.output_hidden_states.unwrap_or(false); let scale_embedding = if let Some(scale_embeddings) = config.scale_embedding { if scale_embeddings { (config.d_model as f64).sqrt() } else { 1.0 } } else { 1.0 }; let dropout = Dropout::new(config.dropout); let layer_norm_embedding = nn::layer_norm( p / "layernorm_embedding", vec![config.d_model], Default::default(), ); let layer_norm = nn::layer_norm(p / "layer_norm", vec![config.d_model], Default::default()); let embed_positions = MBartLearnedPositionalEmbedding::new( p / "embed_positions", config.max_position_embeddings, config.d_model, ); let mut layers: Vec<MBartEncoderLayer> = vec![]; let p_layers = p / "layers"; for layer_index in 0..config.encoder_layers { layers.push(MBartEncoderLayer::new(&p_layers / layer_index, config)); } MBartEncoder { dropout, layer_norm_embedding, layer_norm, layers, embed_positions, output_attentions, output_hidden_states, scale_embedding, } } pub fn forward_t( &self, input_ids: &Tensor, attention_mask: Option<&Tensor>, embeddings: &nn::Embedding, train: bool, ) -> MBartEncoderOutput { let attention_mask = attention_mask.map(|mask| _expand_mask(mask, None)); let x = input_ids.apply(embeddings) * self.scale_embedding; let x = x + &self.embed_positions.forward(input_ids, 0); let mut hidden_state = x .apply(&self.layer_norm_embedding) .apply_t(&self.dropout, train); let mut all_hidden_states: Option<Vec<Tensor>> = if self.output_hidden_states { Some(vec![]) } else { None }; let mut all_attentions: Option<Vec<Tensor>> = if self.output_attentions { Some(vec![]) } else { None }; let mut attention_weights: Option<Tensor>; for layer in &self.layers { if let Some(hidden_states) = all_hidden_states.borrow_mut() { hidden_states.push(hidden_state.as_ref().copy()); }; let temp = layer.forward_t(&hidden_state, attention_mask.as_ref(), train); hidden_state = temp.0; attention_weights = temp.1; if let Some(attentions) = all_attentions.borrow_mut() { attentions.push(attention_weights.as_ref().unwrap().copy()); }; } if let Some(hidden_states) = all_hidden_states.borrow_mut() { hidden_states.push(hidden_state.as_ref().copy()); }; hidden_state = hidden_state.apply(&self.layer_norm); MBartEncoderOutput { hidden_state, all_hidden_states, all_attentions, } } } pub type MBartEncoderOutput = BartEncoderOutput;
self.self_attention .forward_t(&output, None, encoder_attention_mask, None, train); let output: Tensor = output.apply_t(&self.dropout, train) + x; let residual = output.copy(); let output = output.apply(&self.final_layer_norm); let output = (self.activation.get_fn())(&output.apply(&self.fc1)); let output = output .apply_t(&self.activation_dropout, train) .apply(&self.fc2) .apply_t(&self.dropout, train); let output = output + residual; (output, attention_weights) }
function_block-function_prefix_line
[ { "content": "pub fn _tanh(x: &Tensor) -> Tensor {\n\n x.tanh()\n\n}\n\n\n\npub struct TensorFunction(Box<fn(&Tensor) -> Tensor>);\n\n\n\nimpl TensorFunction {\n\n pub fn new(fun: Box<fn(&Tensor) -> Tensor>) -> Self {\n\n Self(fun)\n\n }\n\n\n\n pub fn get_fn(&self) -> &fn(&Tensor) -> Tensor ...
Rust
crates/rome_console/src/markup.rs
RustPhilly/tools
a5c89104e6623b2eb51e2fc1881ddc551fde34d2
use std::{ fmt::{self, Debug}, io, }; use termcolor::{Color, ColorSpec}; use crate::fmt::{Display, Formatter, MarkupElements, Write}; #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub enum MarkupElement { Emphasis, Dim, Italic, Underline, Error, Success, Warn, Info, } impl MarkupElement { pub(crate) fn update_color(&self, color: &mut ColorSpec) { match self { MarkupElement::Emphasis => { color.set_bold(true); } MarkupElement::Dim => { color.set_dimmed(true); } MarkupElement::Italic => { color.set_italic(true); } MarkupElement::Underline => { color.set_underline(true); } MarkupElement::Error => { color.set_fg(Some(Color::Red)); } MarkupElement::Success => { color.set_fg(Some(Color::Green)); } MarkupElement::Warn => { color.set_fg(Some(Color::Yellow)); } MarkupElement::Info => { #[cfg(windows)] const BLUE: Color = Color::Cyan; #[cfg(not(windows))] const BLUE: Color = Color::Blue; color.set_fg(Some(BLUE)); } } } } #[derive(Copy, Clone)] pub struct MarkupNode<'fmt> { pub elements: &'fmt [MarkupElement], pub content: &'fmt dyn Display, } #[derive(Clone, PartialEq, Eq)] pub struct MarkupNodeBuf { pub elements: Vec<MarkupElement>, pub content: String, } impl Debug for MarkupNodeBuf { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { for element in &self.elements { write!(fmt, "<{element:?}>")?; } write!(fmt, "{:?}", self.content)?; for element in self.elements.iter().rev() { write!(fmt, "</{element:?}>")?; } if fmt.alternate() && self.content.contains('\n') { writeln!(fmt)?; } Ok(()) } } #[derive(Copy, Clone)] pub struct Markup<'fmt>(pub &'fmt [MarkupNode<'fmt>]); impl<'fmt> Markup<'fmt> { pub fn to_owned(&self) -> MarkupBuf { let mut result = MarkupBuf(Vec::new()); Formatter::new(&mut result).write_markup(*self).unwrap(); result } } #[derive(Clone, Default, PartialEq, Eq)] pub struct MarkupBuf(pub Vec<MarkupNodeBuf>); impl MarkupBuf { pub(crate) fn is_empty(&self) -> bool { self.0.is_empty() } } impl Write for MarkupBuf { fn write_str(&mut self, elements: &MarkupElements, content: &str) -> io::Result<()> { let mut styles = Vec::new(); elements.for_each(&mut |elements| { styles.extend_from_slice(elements); }); if let Some(last) = self.0.last_mut() { if last.elements == styles { last.content.push_str(content); return Ok(()); } } self.0.push(MarkupNodeBuf { elements: styles, content: content.into(), }); Ok(()) } fn write_fmt(&mut self, elements: &MarkupElements, content: fmt::Arguments) -> io::Result<()> { let mut styles = Vec::new(); elements.for_each(&mut |elements| { styles.extend_from_slice(elements); }); if let Some(last) = self.0.last_mut() { if last.elements == styles { last.content.push_str(&content.to_string()); return Ok(()); } } self.0.push(MarkupNodeBuf { elements: styles, content: content.to_string(), }); Ok(()) } } impl Display for MarkupBuf { fn fmt(&self, fmt: &mut Formatter) -> io::Result<()> { let nodes: Vec<_> = self .0 .iter() .map(|node| MarkupNode { elements: &node.elements, content: &node.content, }) .collect(); fmt.write_markup(Markup(&nodes)) } } impl Debug for MarkupBuf { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { for node in &self.0 { write!(fmt, "{node:?}")?; } Ok(()) } }
use std::{ fmt::{self, Debug}, io, }; use termcolor::{Color, ColorSpec}; use crate::fmt::{Display, Formatter, MarkupElements, Write}; #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub enum MarkupElement { Emphasis, Dim, Italic, Underline, Error, Success, Warn, Info, } impl MarkupElement { pub(crate) fn update_color(&self, color: &mut ColorSpec) { match self { MarkupElement::Emphasis => { color.set_bold(true); } MarkupElement::Dim => { color.set_dimmed(true); } MarkupElement::Italic => { color.set_italic(true); } MarkupElement::Underline => { color.set_underline(true); } MarkupElement::Error => { color.set_fg(Some(Color::Red)); } MarkupElement::Success => { color.set_fg(Some(Color::Green)); } MarkupElement::Warn => { color.set_fg(Some(Color::Yellow)); } MarkupElement::Info => { #[cfg(windows)] const BLUE: Color = Color::Cyan; #[cfg(not(windows))] const BLUE: Color = Color::Blue; color.set_fg(Some(BLUE)); } } } } #[derive(Copy, Clone)] pub struct MarkupNode<'fmt> { pub elements: &'fmt [MarkupElement], pub content: &'fmt dyn Display, } #[derive(Clone, PartialEq, Eq)] pub struct MarkupNodeBuf { pub elements: Vec<MarkupElement>, pub content: String, } impl Debug for MarkupNodeBuf { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { for element in &self.elements {
} #[derive(Copy, Clone)] pub struct Markup<'fmt>(pub &'fmt [MarkupNode<'fmt>]); impl<'fmt> Markup<'fmt> { pub fn to_owned(&self) -> MarkupBuf { let mut result = MarkupBuf(Vec::new()); Formatter::new(&mut result).write_markup(*self).unwrap(); result } } #[derive(Clone, Default, PartialEq, Eq)] pub struct MarkupBuf(pub Vec<MarkupNodeBuf>); impl MarkupBuf { pub(crate) fn is_empty(&self) -> bool { self.0.is_empty() } } impl Write for MarkupBuf { fn write_str(&mut self, elements: &MarkupElements, content: &str) -> io::Result<()> { let mut styles = Vec::new(); elements.for_each(&mut |elements| { styles.extend_from_slice(elements); }); if let Some(last) = self.0.last_mut() { if last.elements == styles { last.content.push_str(content); return Ok(()); } } self.0.push(MarkupNodeBuf { elements: styles, content: content.into(), }); Ok(()) } fn write_fmt(&mut self, elements: &MarkupElements, content: fmt::Arguments) -> io::Result<()> { let mut styles = Vec::new(); elements.for_each(&mut |elements| { styles.extend_from_slice(elements); }); if let Some(last) = self.0.last_mut() { if last.elements == styles { last.content.push_str(&content.to_string()); return Ok(()); } } self.0.push(MarkupNodeBuf { elements: styles, content: content.to_string(), }); Ok(()) } } impl Display for MarkupBuf { fn fmt(&self, fmt: &mut Formatter) -> io::Result<()> { let nodes: Vec<_> = self .0 .iter() .map(|node| MarkupNode { elements: &node.elements, content: &node.content, }) .collect(); fmt.write_markup(Markup(&nodes)) } } impl Debug for MarkupBuf { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { for node in &self.0 { write!(fmt, "{node:?}")?; } Ok(()) } }
write!(fmt, "<{element:?}>")?; } write!(fmt, "{:?}", self.content)?; for element in self.elements.iter().rev() { write!(fmt, "</{element:?}>")?; } if fmt.alternate() && self.content.contains('\n') { writeln!(fmt)?; } Ok(()) }
function_block-function_prefix_line
[ { "content": "pub fn prepend_generated_preamble(content: impl Display) -> String {\n\n format!(\"//! {}\\n\\n{}\", PREAMBLE, content)\n\n}\n\n\n", "file_path": "xtask/src/lib.rs", "rank": 0, "score": 448341.5380411264 }, { "content": "pub trait Language: Sized + Clone + Copy + fmt::Debug ...
Rust
lib/shiika_core/src/names.rs
shiika-lang/shiika
1992ad906c4e7354f8eb7000a134898b68651883
use crate::ty; use crate::ty::*; use serde::{Deserialize, Serialize}; #[derive(Debug, PartialEq)] pub struct ClassFirstname(pub String); impl std::fmt::Display for ClassFirstname { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "{}", self.0) } } impl ClassFirstname { pub fn add_namespace(&self, namespace: &str) -> ClassFullname { if namespace.is_empty() { class_fullname(self.0.clone()) } else { class_fullname(namespace.to_string() + "::" + &self.0) } } } pub fn class_firstname(s: impl Into<String>) -> ClassFirstname { ClassFirstname(s.into()) } #[derive(Debug, PartialEq, Clone, Eq, Hash, Serialize, Deserialize)] pub struct ClassFullname(pub String); impl std::fmt::Display for ClassFullname { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "{}", self.0) } } pub fn class_fullname(s: impl Into<String>) -> ClassFullname { let name = s.into(); debug_assert!(name != "Meta:"); debug_assert!(!name.starts_with("::")); debug_assert!(!name.starts_with("Meta:Meta:")); ClassFullname(name) } pub fn metaclass_fullname(base_: impl Into<String>) -> ClassFullname { let base = base_.into(); debug_assert!(!base.is_empty()); if base == "Metaclass" || base.starts_with("Meta:") { class_fullname("Metaclass") } else { class_fullname(&("Meta:".to_string() + &base)) } } impl ClassFullname { pub fn new(s: impl Into<String>, is_meta: bool) -> ClassFullname { if is_meta { metaclass_fullname(s) } else { class_fullname(s) } } pub fn instance_ty(&self) -> TermTy { if self.0 == "Metaclass" { ty::new("Metaclass", Default::default(), true) } else if self.0.starts_with("Meta:") { ty::meta(&self.0.clone().split_off(5)) } else { ty::raw(&self.0) } } pub fn class_ty(&self) -> TermTy { ty::meta(&self.0) } pub fn is_meta(&self) -> bool { self.0.starts_with("Meta:") } pub fn is_the_class(&self) -> bool { self.0 == "Class" } pub fn to_ty(&self) -> TermTy { if self.is_meta() { let mut name = self.0.clone(); name.replace_range(0..=4, ""); ty::meta(&name) } else { self.instance_ty() } } pub fn meta_name(&self) -> ClassFullname { metaclass_fullname(&self.0) } pub fn method_fullname(&self, method_firstname: &MethodFirstname) -> MethodFullname { method_fullname(self, &method_firstname.0) } pub fn to_const_fullname(&self) -> ConstFullname { toplevel_const(&self.0) } } #[derive(Debug, PartialEq, Clone, Eq, Hash, Serialize, Deserialize)] pub struct MethodFirstname(pub String); impl std::fmt::Display for MethodFirstname { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "{}", self.0) } } pub fn method_firstname(s: impl Into<String>) -> MethodFirstname { MethodFirstname(s.into()) } impl MethodFirstname { pub fn append(&self, suffix: &str) -> MethodFirstname { MethodFirstname(self.0.clone() + suffix) } } #[derive(Debug, PartialEq, Clone, Eq, Hash, Serialize, Deserialize)] pub struct MethodFullname { pub full_name: String, pub first_name: MethodFirstname, } pub fn method_fullname( class_name: &ClassFullname, first_name_: impl Into<String>, ) -> MethodFullname { let first_name = first_name_.into(); debug_assert!(!first_name.is_empty()); MethodFullname { full_name: class_name.0.clone() + "#" + &first_name, first_name: MethodFirstname(first_name), } } pub fn method_fullname_raw(cls: impl Into<String>, method: impl Into<String>) -> MethodFullname { method_fullname(&class_fullname(cls), method) } impl std::fmt::Display for MethodFullname { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "{}", self.full_name) } } impl MethodFullname { pub fn is_class_method(&self) -> bool { self.full_name.starts_with("Meta:") } } #[derive(Debug, PartialEq, Clone, Eq, Hash, Serialize, Deserialize)] pub struct ConstFullname(pub String); impl std::fmt::Display for ConstFullname { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "{}", self.0) } } pub fn const_fullname(s_: impl Into<String>) -> ConstFullname { let s = s_.into(); debug_assert!(!s.starts_with("::")); ConstFullname(format!("::{}", &s)) } pub fn toplevel_const(first_name: &str) -> ConstFullname { debug_assert!(!first_name.starts_with("::")); ConstFullname(format!("::{}", first_name)) } #[derive(Debug, PartialEq, Clone)] pub struct Namespace(pub Vec<String>); impl std::fmt::Display for Namespace { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "::{}", &self.string()) } } impl Namespace { pub fn new(names: Vec<String>) -> Namespace { debug_assert!(names.iter().all(|x| !x.contains("::"))); Namespace(names) } pub fn root() -> Namespace { Namespace::new(vec![]) } pub fn add(&self, name: &ClassFirstname) -> Namespace { let mut v = self.0.clone(); v.push(name.0.clone()); Namespace::new(v) } pub fn class_fullname(&self, name: &ClassFirstname) -> ClassFullname { let n = self.string(); if n.is_empty() { class_fullname(&name.0) } else { class_fullname(format!("{}::{}", n, &name.0)) } } pub fn const_fullname(&self, name: &str) -> ConstFullname { let n = self.string(); if n.is_empty() { const_fullname(name) } else { const_fullname(format!("{}::{}", &n, name)) } } pub fn head(&self, n: usize) -> &[String] { &self.0[0..n] } pub fn size(&self) -> usize { self.0.len() } pub fn string(&self) -> String { self.0.join("::") } } #[derive(Debug, PartialEq, Clone)] pub struct ConstName { pub names: Vec<String>, pub args: Vec<ConstName>, } impl ConstName { pub fn resolved(&self) -> ResolvedConstName { debug_assert!(self.args.is_empty()); ResolvedConstName { names: self.names.clone(), args: vec![], } } pub fn has_type_args(&self) -> bool { !self.args.is_empty() } pub fn to_class_fullname(&self) -> ClassFullname { class_fullname(&self.string()) } pub fn fullname(&self) -> String { "::".to_string() + &self.string() } fn string(&self) -> String { let mut s = self.names.join("::"); if !self.args.is_empty() { s += "<"; let v = self.args.iter().map(|x| x.string()).collect::<Vec<_>>(); s += &v.join(","); s += ">"; } s } } pub fn const_name(names: Vec<String>) -> ConstName { ConstName { names, args: vec![], } } #[derive(Debug, PartialEq, Clone)] pub struct UnresolvedConstName(pub Vec<String>); #[derive(Debug, PartialEq)] pub struct ResolvedConstName { pub names: Vec<String>, pub args: Vec<ResolvedConstName>, } impl std::fmt::Display for ResolvedConstName { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "{}", &self.string()) } } impl ResolvedConstName { pub fn new(names: Vec<String>, args: Vec<ResolvedConstName>) -> ResolvedConstName { ResolvedConstName { names, args } } pub fn unsafe_create(s: String) -> ResolvedConstName { ResolvedConstName { names: vec![s], args: vec![], } } pub fn has_type_args(&self) -> bool { !self.args.is_empty() } pub fn base(&self) -> ResolvedConstName { ResolvedConstName { names: self.names.clone(), args: Default::default(), } } pub fn to_const_fullname(&self) -> ConstFullname { toplevel_const(&self.string()) } pub fn to_class_fullname(&self) -> ClassFullname { class_fullname(self.string()) } pub fn string(&self) -> String { let mut s = self.names.join("::"); if !self.args.is_empty() { s += "<"; let v = self.args.iter().map(|arg| arg.string()).collect::<Vec<_>>(); s += &v.join(","); s += ">"; } s } pub fn with_type_args(&self, args: Vec<ResolvedConstName>) -> ResolvedConstName { debug_assert!(self.args.is_empty()); ResolvedConstName { names: self.names.clone(), args, } } pub fn to_ty(&self, class_typarams: &[String], method_typarams: &[String]) -> TermTy { if self.args.is_empty() { let s = self.names.join("::"); if let Some(i) = class_typarams.iter().position(|name| *name == s) { ty::typaram(s, ty::TyParamKind::Class, i) } else if let Some(i) = method_typarams.iter().position(|name| *name == s) { ty::typaram(s, ty::TyParamKind::Method, i) } else { ty::raw(&self.names.join("::")) } } else { let type_args = self .args .iter() .map(|n| n.to_ty(class_typarams, method_typarams)) .collect(); ty::spe(&self.names.join("::"), type_args) } } } pub fn resolved_const_name(namespace: Namespace, names: Vec<String>) -> ResolvedConstName { let new_names = namespace .0 .into_iter() .chain(names.into_iter()) .collect::<Vec<String>>(); ResolvedConstName { names: new_names, args: vec![], } } pub fn typaram_as_resolved_const_name(name: impl Into<String>) -> ResolvedConstName { resolved_const_name(Namespace::root(), vec![name.into()]) }
use crate::ty; use crate::ty::*; use serde::{Deserialize, Serialize}; #[derive(Debug, PartialEq)] pub struct ClassFirstname(pub String); impl std::fmt::Display for ClassFirstname { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "{}", self.0) } } impl ClassFirstname { pub fn add_namespace(&self, namespace: &str) -> ClassFullname { if namespace.is_empty() { class_fullname(self.0.clone()) } else { class_fullname(namespace.to_string() + "::" + &self.0) } } } pub fn class_firstname(s: impl Into<String>) -> ClassFirstname { ClassFirstname(s.into()) } #[derive(Debug, PartialEq, Clone, Eq, Hash, Serialize, Deserialize)] pub struct ClassFullname(pub String); impl std::fmt::Display for ClassFullname { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "{}", self.0) } } pub fn class_fullname(s: impl Into<String>) -> ClassFullname { let name = s.into(); debug_assert!(name != "Meta:"); debug_assert!(!name.starts_with("::")); debug_assert!(!name.starts_with("Meta:Meta:")); ClassFullname(name) } pub fn metaclass_fullname(base_: impl Into<String>) -> ClassFullname { let base = base_.into(); debug_assert!(!base.is_empty()); if base == "Metaclass" || base.starts_with("Meta:") { class_fullname("Metaclass") } else { class_fullname(&("Meta:".to_string() + &base)) } } impl ClassFullname { pub fn new(s: impl Into<String>, is_meta: bool) -> ClassFullname { if is_meta { metaclass_fullname(s) } else { class_fullname(s) } } pub fn instance_ty(&self) -> TermTy { if self.0 == "Metaclass" { ty::new("Metaclass", Default::default(), true) } else if self.0.starts_with("Meta:") { ty::meta(&self.0.clone().split_off(5)) } else { ty::raw(&self.0) } } pub fn class_ty(&self) -> TermTy { ty::meta(&self.0) } pub fn is_meta(&self) -> bool { self.0.starts_with("Meta:") } pub fn is_the_class(&self) -> bool { self.0 == "Class" } pub fn to_ty(&self) -> TermTy { if self.is_meta() { l
pub fn meta_name(&self) -> ClassFullname { metaclass_fullname(&self.0) } pub fn method_fullname(&self, method_firstname: &MethodFirstname) -> MethodFullname { method_fullname(self, &method_firstname.0) } pub fn to_const_fullname(&self) -> ConstFullname { toplevel_const(&self.0) } } #[derive(Debug, PartialEq, Clone, Eq, Hash, Serialize, Deserialize)] pub struct MethodFirstname(pub String); impl std::fmt::Display for MethodFirstname { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "{}", self.0) } } pub fn method_firstname(s: impl Into<String>) -> MethodFirstname { MethodFirstname(s.into()) } impl MethodFirstname { pub fn append(&self, suffix: &str) -> MethodFirstname { MethodFirstname(self.0.clone() + suffix) } } #[derive(Debug, PartialEq, Clone, Eq, Hash, Serialize, Deserialize)] pub struct MethodFullname { pub full_name: String, pub first_name: MethodFirstname, } pub fn method_fullname( class_name: &ClassFullname, first_name_: impl Into<String>, ) -> MethodFullname { let first_name = first_name_.into(); debug_assert!(!first_name.is_empty()); MethodFullname { full_name: class_name.0.clone() + "#" + &first_name, first_name: MethodFirstname(first_name), } } pub fn method_fullname_raw(cls: impl Into<String>, method: impl Into<String>) -> MethodFullname { method_fullname(&class_fullname(cls), method) } impl std::fmt::Display for MethodFullname { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "{}", self.full_name) } } impl MethodFullname { pub fn is_class_method(&self) -> bool { self.full_name.starts_with("Meta:") } } #[derive(Debug, PartialEq, Clone, Eq, Hash, Serialize, Deserialize)] pub struct ConstFullname(pub String); impl std::fmt::Display for ConstFullname { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "{}", self.0) } } pub fn const_fullname(s_: impl Into<String>) -> ConstFullname { let s = s_.into(); debug_assert!(!s.starts_with("::")); ConstFullname(format!("::{}", &s)) } pub fn toplevel_const(first_name: &str) -> ConstFullname { debug_assert!(!first_name.starts_with("::")); ConstFullname(format!("::{}", first_name)) } #[derive(Debug, PartialEq, Clone)] pub struct Namespace(pub Vec<String>); impl std::fmt::Display for Namespace { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "::{}", &self.string()) } } impl Namespace { pub fn new(names: Vec<String>) -> Namespace { debug_assert!(names.iter().all(|x| !x.contains("::"))); Namespace(names) } pub fn root() -> Namespace { Namespace::new(vec![]) } pub fn add(&self, name: &ClassFirstname) -> Namespace { let mut v = self.0.clone(); v.push(name.0.clone()); Namespace::new(v) } pub fn class_fullname(&self, name: &ClassFirstname) -> ClassFullname { let n = self.string(); if n.is_empty() { class_fullname(&name.0) } else { class_fullname(format!("{}::{}", n, &name.0)) } } pub fn const_fullname(&self, name: &str) -> ConstFullname { let n = self.string(); if n.is_empty() { const_fullname(name) } else { const_fullname(format!("{}::{}", &n, name)) } } pub fn head(&self, n: usize) -> &[String] { &self.0[0..n] } pub fn size(&self) -> usize { self.0.len() } pub fn string(&self) -> String { self.0.join("::") } } #[derive(Debug, PartialEq, Clone)] pub struct ConstName { pub names: Vec<String>, pub args: Vec<ConstName>, } impl ConstName { pub fn resolved(&self) -> ResolvedConstName { debug_assert!(self.args.is_empty()); ResolvedConstName { names: self.names.clone(), args: vec![], } } pub fn has_type_args(&self) -> bool { !self.args.is_empty() } pub fn to_class_fullname(&self) -> ClassFullname { class_fullname(&self.string()) } pub fn fullname(&self) -> String { "::".to_string() + &self.string() } fn string(&self) -> String { let mut s = self.names.join("::"); if !self.args.is_empty() { s += "<"; let v = self.args.iter().map(|x| x.string()).collect::<Vec<_>>(); s += &v.join(","); s += ">"; } s } } pub fn const_name(names: Vec<String>) -> ConstName { ConstName { names, args: vec![], } } #[derive(Debug, PartialEq, Clone)] pub struct UnresolvedConstName(pub Vec<String>); #[derive(Debug, PartialEq)] pub struct ResolvedConstName { pub names: Vec<String>, pub args: Vec<ResolvedConstName>, } impl std::fmt::Display for ResolvedConstName { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "{}", &self.string()) } } impl ResolvedConstName { pub fn new(names: Vec<String>, args: Vec<ResolvedConstName>) -> ResolvedConstName { ResolvedConstName { names, args } } pub fn unsafe_create(s: String) -> ResolvedConstName { ResolvedConstName { names: vec![s], args: vec![], } } pub fn has_type_args(&self) -> bool { !self.args.is_empty() } pub fn base(&self) -> ResolvedConstName { ResolvedConstName { names: self.names.clone(), args: Default::default(), } } pub fn to_const_fullname(&self) -> ConstFullname { toplevel_const(&self.string()) } pub fn to_class_fullname(&self) -> ClassFullname { class_fullname(self.string()) } pub fn string(&self) -> String { let mut s = self.names.join("::"); if !self.args.is_empty() { s += "<"; let v = self.args.iter().map(|arg| arg.string()).collect::<Vec<_>>(); s += &v.join(","); s += ">"; } s } pub fn with_type_args(&self, args: Vec<ResolvedConstName>) -> ResolvedConstName { debug_assert!(self.args.is_empty()); ResolvedConstName { names: self.names.clone(), args, } } pub fn to_ty(&self, class_typarams: &[String], method_typarams: &[String]) -> TermTy { if self.args.is_empty() { let s = self.names.join("::"); if let Some(i) = class_typarams.iter().position(|name| *name == s) { ty::typaram(s, ty::TyParamKind::Class, i) } else if let Some(i) = method_typarams.iter().position(|name| *name == s) { ty::typaram(s, ty::TyParamKind::Method, i) } else { ty::raw(&self.names.join("::")) } } else { let type_args = self .args .iter() .map(|n| n.to_ty(class_typarams, method_typarams)) .collect(); ty::spe(&self.names.join("::"), type_args) } } } pub fn resolved_const_name(namespace: Namespace, names: Vec<String>) -> ResolvedConstName { let new_names = namespace .0 .into_iter() .chain(names.into_iter()) .collect::<Vec<String>>(); ResolvedConstName { names: new_names, args: vec![], } } pub fn typaram_as_resolved_const_name(name: impl Into<String>) -> ResolvedConstName { resolved_const_name(Namespace::root(), vec![name.into()]) }
et mut name = self.0.clone(); name.replace_range(0..=4, ""); ty::meta(&name) } else { self.instance_ty() } }
function_block-function_prefixed
[ { "content": "pub fn new(base_name_: impl Into<String>, type_args: Vec<TermTy>, is_meta: bool) -> TermTy {\n\n let base_name = base_name_.into();\n\n debug_assert!(!base_name.is_empty());\n\n debug_assert!(!base_name.starts_with(\"Meta:\"));\n\n debug_assert!(!base_name.contains('<'));\n\n let fu...
Rust
client/src/command_receiver.rs
amethyst/naia
791d5c90ce3435c254da1a6048064c2204ff538c
use std::collections::{HashMap, VecDeque}; use naia_shared::{ wrapping_diff, EntityType, ProtocolType, Ref, Replicate, SequenceBuffer, SequenceIterator, WorldMutType, }; use super::{entity_manager::EntityManager, event::OwnedEntity}; const COMMAND_HISTORY_SIZE: u16 = 64; #[derive(Debug)] pub struct CommandReceiver<P: ProtocolType, K: EntityType> { queued_incoming_commands: VecDeque<(u16, OwnedEntity<K>, Ref<dyn Replicate<P>>)>, command_history: HashMap<K, SequenceBuffer<Ref<dyn Replicate<P>>>>, queued_command_replays: VecDeque<(u16, OwnedEntity<K>, Ref<dyn Replicate<P>>)>, replay_trigger: HashMap<K, u16>, } impl<P: ProtocolType, K: EntityType> CommandReceiver<P, K> { pub fn new() -> Self { CommandReceiver { queued_incoming_commands: VecDeque::new(), command_history: HashMap::new(), queued_command_replays: VecDeque::new(), replay_trigger: HashMap::new(), } } pub fn pop_command(&mut self) -> Option<(u16, OwnedEntity<K>, Ref<dyn Replicate<P>>)> { self.queued_incoming_commands.pop_front() } pub fn pop_command_replay(&mut self) -> Option<(u16, OwnedEntity<K>, Ref<dyn Replicate<P>>)> { self.queued_command_replays.pop_front() } pub fn process_command_replay<W: WorldMutType<P, K>>( &mut self, world: &mut W, entity_manager: &mut EntityManager<P, K>, ) { for (world_entity, history_tick) in self.replay_trigger.iter() { if let Some(predicted_entity) = entity_manager.get_predicted_entity(world_entity) { entity_manager.prediction_reset_entity(world, world_entity); if let Some(command_buffer) = self.command_history.get_mut(&world_entity) { self.queued_incoming_commands.clear(); self.queued_command_replays.clear(); let current_tick = command_buffer.sequence_num(); for tick in *history_tick..=current_tick { if let Some(command) = command_buffer.get_mut(tick) { self.queued_command_replays.push_back(( tick, OwnedEntity::new(world_entity, &predicted_entity), command.clone(), )); } } } } } self.replay_trigger.clear(); } pub fn queue_command( &mut self, host_tick: u16, owned_entity: OwnedEntity<K>, command: Ref<dyn Replicate<P>>, ) { let world_entity = owned_entity.confirmed; self.queued_incoming_commands .push_back((host_tick, owned_entity, command.clone())); if let Some(command_buffer) = self.command_history.get_mut(&world_entity) { command_buffer.insert(host_tick, command); } } pub fn command_history_count(&self, owned_entity: &K) -> u8 { if let Some(command_buffer) = self.command_history.get(owned_entity) { return command_buffer.get_entries_count(); } return 0; } pub fn command_history_iter( &self, owned_entity: &K, reverse: bool, ) -> Option<SequenceIterator<Ref<dyn Replicate<P>>>> { if let Some(command_buffer) = self.command_history.get(owned_entity) { return Some(command_buffer.iter(reverse)); } return None; } pub fn replay_commands(&mut self, history_tick: u16, owned_entity: &K) { if let Some(tick) = self.replay_trigger.get_mut(owned_entity) { if wrapping_diff(*tick, history_tick) > 0 { *tick = history_tick; } } else { self.replay_trigger.insert(*owned_entity, history_tick); } } pub fn remove_history_until(&mut self, history_tick: u16, owned_entity: &K) { if let Some(command_buffer) = self.command_history.get_mut(owned_entity) { command_buffer.remove_until(history_tick); } } pub fn prediction_init(&mut self, owned_entity: &K) { self.command_history.insert( *owned_entity, SequenceBuffer::with_capacity(COMMAND_HISTORY_SIZE), ); } pub fn prediction_cleanup(&mut self, owned_entity: &K) { self.command_history.remove(owned_entity); } }
use std::collections::{HashMap, VecDeque}; use naia_shared::{ wrapping_diff, EntityType, ProtocolType, Ref, Replicate, SequenceBuffer, SequenceIterator, WorldMutType, }; use super::{entity_manager::EntityManager, event::OwnedEntity}; const COMMAND_HISTORY_SIZE: u16 = 64; #[derive(Debug)] pub struct CommandReceiver<P: ProtocolType, K: EntityType> { queued_incoming_commands: VecDeque<(u16, OwnedEntity<K>, Ref<dyn Replicate<P>>)>, command_history: HashMap<K, SequenceBuffer<Ref<dyn Replicate<P>>>>, queued_command_replays: VecDeque<(u16, OwnedEntity<K>, Ref<dyn Replicate<P>>)>, replay_trigger: HashMap<K, u16>, } impl<P: ProtocolType, K: EntityType> CommandReceiver<P, K> { pub fn new() -> Self { CommandReceiver { queued_incoming_commands: VecDeque::new(), command_history: HashMap::new(), queued_command_replays: VecDeque::new(), replay_trigger: HashMap::new(), } } pub fn pop_command(&mut self) -> Option<(u16, OwnedEntity<K>, Ref<dyn Replicate<P>>)> { self.queued_incoming_commands.pop_front() } pub fn pop_command_replay(&mut self) -> Option<(u16, OwnedEntity<K>, Ref<dyn Replicate<P>>)> { self.queued_command_replays.pop_front() } pub fn process_command_replay<W: WorldMutType<P, K>>( &mut self, world: &mut W, entity_manager: &mut EntityManager<P, K>, ) { for (world_entity, history_tick) in self.replay_trigger.iter() { if let Some(predicted_entity) = entity_manager.get_predicted_entity(world_entity) { entity_manager.prediction_reset_entity(world, world_entity); if let Some(command_buffer) = self.command_history.get_mut(&world_entity) { self.queued_incoming_commands.clear(); self.queued_command_replays.clear(); let current_tick = command_buffer.sequence_num(); for tick in *history_tick..=current_tick { if let Some(command) = command_buffer.get_mut(tick) { self.queued_command_replays.push_back(( tick, OwnedEntity::new(world_entity, &predicted_entity), command.clone(), )); } } } } } self.replay_trigger.clear(); } pub fn queue_command( &mut self, host_tick: u16, owned_entity: OwnedEntity<K>, command: Ref<dyn Replicate<P>>, ) { let world_entity = owned_entity.confirmed; self.queued_incoming_commands .push_back((host_tick, owned_entity, command.clone())); if let Some(command_buffer) = self.command_history.get_mut(&world_entity) { command_buffer.insert(host_tick, command); } } pub fn command_history_count(&self, owned_entity: &K) -> u8 { if let Some(command_buffer) = self.command_history.get(owned_entity) { return command_buffer.get_entries_count(); } return 0; } pub fn command_history_iter( &self, owned_entity: &K, reverse: bool, ) -> Option<SequenceIterator<Ref<dyn Replicate<P>>>> { if let Some(command_buffer) = self.command_history.get(owned_entity) { return Some(command_buffer.iter(reverse)); } return None; } pub fn replay_commands(&mut self, history_tick: u16, owned_entity: &K) { if let Some(tick) = self.replay_trigger.get_mut(owned_entity) { if wrapping_diff(*tick, history_tick) > 0 { *tick = history_tick; } } else { self.replay_trigger.insert(*owned_entity, history_tick); } } pub fn remove_history_until(&mut self, history_tick: u16, owned_entity: &K) {
owned_entity: &K) { self.command_history.insert( *owned_entity, SequenceBuffer::with_capacity(COMMAND_HISTORY_SIZE), ); } pub fn prediction_cleanup(&mut self, owned_entity: &K) { self.command_history.remove(owned_entity); } }
if let Some(command_buffer) = self.command_history.get_mut(owned_entity) { command_buffer.remove_until(history_tick); } } pub fn prediction_init(&mut self,
random
[ { "content": "pub fn before_receive_events(world: &mut World) {\n\n world.resource_scope(|world, mut client: Mut<Client<Entity>>| {\n\n\n\n // Host Component Updates\n\n let mut host_component_event_reader = world\n\n .get_resource_mut::<Events<HostSyncEvent>>()\n\n .unwra...
Rust
packages/moneymarket/src/testing.rs
1Zaitsev/money-market-mocks
d2c5d089e1a34735e9483f9e54afb647bb00c13d
use crate::mock_querier::mock_dependencies; use crate::oracle::PriceResponse; use crate::querier::{compute_tax, deduct_tax, query_price, query_tax_rate, TimeConstraints}; use crate::tokens::{Tokens, TokensHuman, TokensMath, TokensToRaw}; use cosmwasm_bignumber::{Decimal256, Uint256}; use cosmwasm_std::{Addr, Api, CanonicalAddr, Coin, Decimal, StdError, Uint128}; #[test] fn tax_rate_querier() { let mut deps = mock_dependencies(&[]); deps.querier.with_tax(Decimal::percent(1), &[]); assert_eq!( query_tax_rate(deps.as_ref()).unwrap(), Decimal256::percent(1), ); } #[test] fn test_compute_tax() { let mut deps = mock_dependencies(&[]); deps.querier.with_tax( Decimal::percent(1), &[(&"uusd".to_string(), &Uint128::from(1000000u128))], ); assert_eq!( compute_tax(deps.as_ref(), &Coin::new(10000000000u128, "uusd")).unwrap(), Uint256::from(1000000u64) ); assert_eq!( compute_tax(deps.as_ref(), &Coin::new(50000000u128, "uusd")).unwrap(), Uint256::from(495050u64) ); } #[test] fn test_deduct_tax() { let mut deps = mock_dependencies(&[]); deps.querier.with_tax( Decimal::percent(1), &[(&"uusd".to_string(), &Uint128::from(1000000u128))], ); assert_eq!( deduct_tax(deps.as_ref(), Coin::new(10000000000u128, "uusd")).unwrap(), Coin { denom: "uusd".to_string(), amount: Uint128::from(9999000000u128) } ); assert_eq!( deduct_tax(deps.as_ref(), Coin::new(50000000u128, "uusd")).unwrap(), Coin { denom: "uusd".to_string(), amount: Uint128::from(49504950u128) } ); } #[test] fn oracle_price_querier() { let mut deps = mock_dependencies(&[]); deps.querier.with_oracle_price(&[( &("terra123123".to_string(), "uusd".to_string()), &(Decimal256::from_ratio(131, 2), 123, 321), )]); let oracle_price = query_price( deps.as_ref(), Addr::unchecked("oracle"), "terra123123".to_string(), "uusd".to_string(), None, ) .unwrap(); assert_eq!( oracle_price, PriceResponse { rate: Decimal256::from_ratio(131, 2), last_updated_base: 123, last_updated_quote: 321, } ); query_price( deps.as_ref(), Addr::unchecked("oracle"), "terra123123".to_string(), "ukrw".to_string(), None, ) .unwrap_err(); let res = query_price( deps.as_ref(), Addr::unchecked("oracle"), "terra123123".to_string(), "uusd".to_string(), Some(TimeConstraints { block_time: 500u64, valid_timeframe: 60u64, }), ); match res { Err(StdError::GenericErr { msg, .. }) => assert_eq!(msg, "Price is too old"), _ => panic!("DO NOT ENTER HERE"), } } #[test] fn tokens_math() { let deps = mock_dependencies(&[]); let tokens_1: TokensHuman = vec![ ("token1".to_string(), Uint256::from(1000000u64)), ("token2".to_string(), Uint256::from(1000000u64)), ("token3".to_string(), Uint256::from(1000000u64)), ("token5".to_string(), Uint256::from(1000000u64)), ]; let tokens_2: TokensHuman = vec![ ("token1".to_string(), Uint256::from(1000000u64)), ("token4".to_string(), Uint256::from(1000000u64)), ]; let tokens_3: TokensHuman = vec![ ("token1".to_string(), Uint256::from(1000000u64)), ("token6".to_string(), Uint256::from(1000000u64)), ]; let tokens_4: TokensHuman = vec![ ("token1".to_string(), Uint256::from(1000000u64)), ("token2".to_string(), Uint256::from(1200000u64)), ]; let mut tokens_1_raw: Tokens = tokens_1.to_raw(deps.as_ref()).unwrap(); let tokens_2_raw: Tokens = tokens_2.to_raw(deps.as_ref()).unwrap(); let tokens_3_raw: Tokens = tokens_3.to_raw(deps.as_ref()).unwrap(); let tokens_4_raw: Tokens = tokens_4.to_raw(deps.as_ref()).unwrap(); assert!(tokens_1_raw.clone().sub(tokens_2_raw).is_err()); assert!(tokens_1_raw.clone().sub(tokens_3_raw).is_err()); assert!(tokens_1_raw.sub(tokens_4_raw).is_err()); } #[test] fn tokens_math_normal_add() { let deps = mock_dependencies(&[]); let acct1 = deps .api .addr_humanize(&CanonicalAddr::from(vec![ 1, 1, 1, 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, ])) .unwrap() .to_string(); let acct2 = deps .api .addr_humanize(&CanonicalAddr::from(vec![ 1, 1, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ])) .unwrap() .to_string(); let acct3 = deps .api .addr_humanize(&CanonicalAddr::from(vec![ 1, 1, 1, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ])) .unwrap() .to_string(); let acct4 = deps .api .addr_humanize(&CanonicalAddr::from(vec![ 1, 1, 1, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ])) .unwrap() .to_string(); let acct5 = deps .api .addr_humanize(&CanonicalAddr::from(vec![ 1, 1, 1, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ])) .unwrap() .to_string(); let tokens_1: TokensHuman = vec![ (acct1.clone(), Uint256::from(1000000u64)), (acct2, Uint256::from(1000000u64)), (acct3, Uint256::from(1000000u64)), (acct5, Uint256::from(1000000u64)), ]; let tokens_2: TokensHuman = vec![ (acct1, Uint256::from(1000000u64)), (acct4, Uint256::from(1000000u64)), ]; let mut tokens_1_raw: Tokens = tokens_1.to_raw(deps.as_ref()).unwrap(); let tokens_2_raw: Tokens = tokens_2.to_raw(deps.as_ref()).unwrap(); tokens_1_raw.add(tokens_2_raw); assert_eq!(tokens_1_raw[0].1, Uint256::from(2000000u64)); assert_eq!(tokens_1_raw.len(), 5); } #[test] fn token_math_zero_token() { let deps = mock_dependencies(&[]); let tokens_1: TokensHuman = vec![ ("token1".to_string(), Uint256::from(1000000u64)), ("token2".to_string(), Uint256::from(1000000u64)), ]; let tokens_2: TokensHuman = vec![ ("token1".to_string(), Uint256::from(1000000u64)), ("token2".to_string(), Uint256::from(1000000u64)), ]; let mut tokens_1_raw: Tokens = tokens_1.to_raw(deps.as_ref()).unwrap(); let tokens_2_raw: Tokens = tokens_2.to_raw(deps.as_ref()).unwrap(); tokens_1_raw.sub(tokens_2_raw).unwrap(); assert_eq!(tokens_1_raw.len(), 0); } #[test] #[should_panic] fn token_math_invalid_token() { let deps = mock_dependencies(&[]); let tokens_1: TokensHuman = vec![ ("token1".to_string(), Uint256::from(1000000u64)), ("token2".to_string(), Uint256::from(1000000u64)), ("token3".to_string(), Uint256::from(1000000u64)), ("token5".to_string(), Uint256::from(1000000u64)), ]; let tokens_2: TokensHuman = vec![ ("token1".to_string(), Uint256::from(1000000u64)), ("token1".to_string(), Uint256::from(1000000u64)), ("token3".to_string(), Uint256::from(1000000u64)), ]; let mut tokens_1_raw: Tokens = tokens_1.to_raw(deps.as_ref()).unwrap(); let tokens_2_raw: Tokens = tokens_2.to_raw(deps.as_ref()).unwrap(); let _ = tokens_1_raw.sub(tokens_2_raw); } #[test] #[should_panic] fn token_math_invalid_token_2() { let deps = mock_dependencies(&[]); let tokens_1: TokensHuman = vec![ ("token1".to_string(), Uint256::from(1000000u64)), ("token2".to_string(), Uint256::from(1000000u64)), ("token2".to_string(), Uint256::from(1000000u64)), ("token3".to_string(), Uint256::from(1000000u64)), ("token5".to_string(), Uint256::from(1000000u64)), ]; let tokens_2: TokensHuman = vec![ ("token1".to_string(), Uint256::from(1000000u64)), ("token2".to_string(), Uint256::from(1000000u64)), ("token3".to_string(), Uint256::from(1000000u64)), ]; let mut tokens_1_raw: Tokens = tokens_1.to_raw(deps.as_ref()).unwrap(); let tokens_2_raw: Tokens = tokens_2.to_raw(deps.as_ref()).unwrap(); let _ = tokens_1_raw.sub(tokens_2_raw); }
use crate::mock_querier::mock_dependencies; use crate::oracle::PriceResponse; use crate::querier::{compute_tax, deduct_tax, query_price, query_tax_rate, TimeConstraints}; use crate::tokens::{Tokens, TokensHuman, TokensMath, TokensToRaw}; use cosmwasm_bignumber::{Decimal256, Uint256}; use cosmwasm_std::{Addr, Api, CanonicalAddr, Coin, Decimal, StdError, Uint128}; #[test] fn tax_rate_querier() { let mut deps = mock_dependencies(&[]); deps.querier.with_tax(Decimal::percent(1), &[]); assert_eq!( query_tax_rate(deps.as_ref()).unwrap(), Decimal256::percent(1), ); } #[test] fn test_compute_tax() { let mut deps = mock_dependencies(&[]); deps.querier.with_tax( Decimal::percent(1), &[(&"uusd".to_string(), &Uint128::from(1000000u128))], ); assert_eq!( compute_tax(deps.as_ref(), &Coin::new(10000000000u128, "uusd")).unwrap(), Uint256::from(1000000u64) ); assert_eq!( compute_tax(deps.as_ref(), &Coin::new(50000000u128, "uusd")).unwrap(), Uint256::from(495050u64) ); } #[test] fn test_deduct_tax() { let mut deps = mock_dependencies(&[]); deps.querier.with_tax( Decimal::percent(1), &[(&"uusd".to_string(), &Uint128::from(1000000u128))], ); assert_eq!( deduct_tax(deps.as_ref(), Coin::new(10000000000u128, "uusd")).unwrap(), Coin { denom: "uusd".to_string(), amount: Uint128::from(9999000000u128) } ); assert_eq!( deduct_tax(deps.as_ref(), Coin::new(50000000u128, "uusd")).unwrap(), Coin { denom: "uusd".to_string(), amount: Uint128::from(49504950u128) } ); } #[test] fn oracle_price_querier() { let mut deps = mock_dependencies(&[]); deps.querier.with_oracle_price(&[( &("terra123123".to_string(), "uusd".to_string()), &(Decimal256::from_ratio(131, 2), 123, 321), )]); let oracle_price = query_price( deps.as_ref(), Addr::unchecked("oracle"), "terra123123".to_string(), "uusd".to_string(), None, ) .unwrap(); assert_eq!( oracle_price, PriceResponse { rate: Decimal256::f
fn token_math_invalid_token_2() { let deps = mock_dependencies(&[]); let tokens_1: TokensHuman = vec![ ("token1".to_string(), Uint256::from(1000000u64)), ("token2".to_string(), Uint256::from(1000000u64)), ("token2".to_string(), Uint256::from(1000000u64)), ("token3".to_string(), Uint256::from(1000000u64)), ("token5".to_string(), Uint256::from(1000000u64)), ]; let tokens_2: TokensHuman = vec![ ("token1".to_string(), Uint256::from(1000000u64)), ("token2".to_string(), Uint256::from(1000000u64)), ("token3".to_string(), Uint256::from(1000000u64)), ]; let mut tokens_1_raw: Tokens = tokens_1.to_raw(deps.as_ref()).unwrap(); let tokens_2_raw: Tokens = tokens_2.to_raw(deps.as_ref()).unwrap(); let _ = tokens_1_raw.sub(tokens_2_raw); }
rom_ratio(131, 2), last_updated_base: 123, last_updated_quote: 321, } ); query_price( deps.as_ref(), Addr::unchecked("oracle"), "terra123123".to_string(), "ukrw".to_string(), None, ) .unwrap_err(); let res = query_price( deps.as_ref(), Addr::unchecked("oracle"), "terra123123".to_string(), "uusd".to_string(), Some(TimeConstraints { block_time: 500u64, valid_timeframe: 60u64, }), ); match res { Err(StdError::GenericErr { msg, .. }) => assert_eq!(msg, "Price is too old"), _ => panic!("DO NOT ENTER HERE"), } } #[test] fn tokens_math() { let deps = mock_dependencies(&[]); let tokens_1: TokensHuman = vec![ ("token1".to_string(), Uint256::from(1000000u64)), ("token2".to_string(), Uint256::from(1000000u64)), ("token3".to_string(), Uint256::from(1000000u64)), ("token5".to_string(), Uint256::from(1000000u64)), ]; let tokens_2: TokensHuman = vec![ ("token1".to_string(), Uint256::from(1000000u64)), ("token4".to_string(), Uint256::from(1000000u64)), ]; let tokens_3: TokensHuman = vec![ ("token1".to_string(), Uint256::from(1000000u64)), ("token6".to_string(), Uint256::from(1000000u64)), ]; let tokens_4: TokensHuman = vec![ ("token1".to_string(), Uint256::from(1000000u64)), ("token2".to_string(), Uint256::from(1200000u64)), ]; let mut tokens_1_raw: Tokens = tokens_1.to_raw(deps.as_ref()).unwrap(); let tokens_2_raw: Tokens = tokens_2.to_raw(deps.as_ref()).unwrap(); let tokens_3_raw: Tokens = tokens_3.to_raw(deps.as_ref()).unwrap(); let tokens_4_raw: Tokens = tokens_4.to_raw(deps.as_ref()).unwrap(); assert!(tokens_1_raw.clone().sub(tokens_2_raw).is_err()); assert!(tokens_1_raw.clone().sub(tokens_3_raw).is_err()); assert!(tokens_1_raw.sub(tokens_4_raw).is_err()); } #[test] fn tokens_math_normal_add() { let deps = mock_dependencies(&[]); let acct1 = deps .api .addr_humanize(&CanonicalAddr::from(vec![ 1, 1, 1, 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, ])) .unwrap() .to_string(); let acct2 = deps .api .addr_humanize(&CanonicalAddr::from(vec![ 1, 1, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ])) .unwrap() .to_string(); let acct3 = deps .api .addr_humanize(&CanonicalAddr::from(vec![ 1, 1, 1, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ])) .unwrap() .to_string(); let acct4 = deps .api .addr_humanize(&CanonicalAddr::from(vec![ 1, 1, 1, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ])) .unwrap() .to_string(); let acct5 = deps .api .addr_humanize(&CanonicalAddr::from(vec![ 1, 1, 1, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ])) .unwrap() .to_string(); let tokens_1: TokensHuman = vec![ (acct1.clone(), Uint256::from(1000000u64)), (acct2, Uint256::from(1000000u64)), (acct3, Uint256::from(1000000u64)), (acct5, Uint256::from(1000000u64)), ]; let tokens_2: TokensHuman = vec![ (acct1, Uint256::from(1000000u64)), (acct4, Uint256::from(1000000u64)), ]; let mut tokens_1_raw: Tokens = tokens_1.to_raw(deps.as_ref()).unwrap(); let tokens_2_raw: Tokens = tokens_2.to_raw(deps.as_ref()).unwrap(); tokens_1_raw.add(tokens_2_raw); assert_eq!(tokens_1_raw[0].1, Uint256::from(2000000u64)); assert_eq!(tokens_1_raw.len(), 5); } #[test] fn token_math_zero_token() { let deps = mock_dependencies(&[]); let tokens_1: TokensHuman = vec![ ("token1".to_string(), Uint256::from(1000000u64)), ("token2".to_string(), Uint256::from(1000000u64)), ]; let tokens_2: TokensHuman = vec![ ("token1".to_string(), Uint256::from(1000000u64)), ("token2".to_string(), Uint256::from(1000000u64)), ]; let mut tokens_1_raw: Tokens = tokens_1.to_raw(deps.as_ref()).unwrap(); let tokens_2_raw: Tokens = tokens_2.to_raw(deps.as_ref()).unwrap(); tokens_1_raw.sub(tokens_2_raw).unwrap(); assert_eq!(tokens_1_raw.len(), 0); } #[test] #[should_panic] fn token_math_invalid_token() { let deps = mock_dependencies(&[]); let tokens_1: TokensHuman = vec![ ("token1".to_string(), Uint256::from(1000000u64)), ("token2".to_string(), Uint256::from(1000000u64)), ("token3".to_string(), Uint256::from(1000000u64)), ("token5".to_string(), Uint256::from(1000000u64)), ]; let tokens_2: TokensHuman = vec![ ("token1".to_string(), Uint256::from(1000000u64)), ("token1".to_string(), Uint256::from(1000000u64)), ("token3".to_string(), Uint256::from(1000000u64)), ]; let mut tokens_1_raw: Tokens = tokens_1.to_raw(deps.as_ref()).unwrap(); let tokens_2_raw: Tokens = tokens_2.to_raw(deps.as_ref()).unwrap(); let _ = tokens_1_raw.sub(tokens_2_raw); } #[test] #[should_panic]
random
[ { "content": "pub fn query_tax_rate_and_cap(deps: Deps, denom: String) -> StdResult<(Decimal256, Uint256)> {\n\n let terra_querier = TerraQuerier::new(&deps.querier);\n\n let rate = terra_querier.query_tax_rate()?.rate;\n\n let cap = terra_querier.query_tax_cap(denom)?.cap;\n\n Ok((rate.into(), cap....
Rust
micro-color-chooser/src/service/game_color_prefs.rs
CoinArcade/BUGOUT
ec01dc3dae54e1e248d540d442caa1731f2822e4
use crate::components::Repos; use crate::repo::*; use api::GameReady; use color_model::*; use core_model::*; pub fn by_session_id(session_id: &SessionId, repos: &Repos) -> Result<GameColorPref, FetchErr> { repos.game_ready.get(session_id).and_then(|sg| match sg { None => Ok(GameColorPref::NotReady), Some(game_ready) => { let first_pref = repos.prefs.get(&game_ready.sessions.0); let second_pref = repos.prefs.get(&game_ready.sessions.1); match (first_pref, second_pref) { (Ok(Some(first)), Ok(Some(second))) => Ok(GameColorPref::Complete { game_id: game_ready.game_id.clone(), prefs: (first, second), }), (Ok(Some(partial)), Ok(None)) => Ok(GameColorPref::Partial { game_id: game_ready.game_id.clone(), pref: partial, }), (Ok(None), Ok(Some(partial))) => Ok(GameColorPref::Partial { game_id: game_ready.game_id.clone(), pref: partial, }), (Ok(None), Ok(None)) => Ok(GameColorPref::NotReady), (Err(e), _) => Err(e), (_, Err(e)) => Err(e), } } }) } pub fn by_game_ready(game_ready: &GameReady, repos: &Repos) -> Result<GameColorPref, FetchErr> { let first_pref = repos.prefs.get(&game_ready.sessions.0)?; let second_pref = repos.prefs.get(&game_ready.sessions.1)?; Ok(match (first_pref, second_pref) { (Some(first), Some(second)) => GameColorPref::Complete { game_id: game_ready.game_id.clone(), prefs: (first, second), }, (Some(partial), None) => GameColorPref::Partial { game_id: game_ready.game_id.clone(), pref: partial, }, (None, Some(partial)) => GameColorPref::Partial { game_id: game_ready.game_id.clone(), pref: partial, }, _ => GameColorPref::NotReady, }) } #[cfg(test)] mod tests { use super::*; use std::rc::Rc; struct SGNotReady; struct SGReady(pub GameReady); struct PrefsNone; struct PrefsOne(pub SessionColorPref); struct PrefsTwo(pub SessionColorPref, pub SessionColorPref); impl GameReadyRepo for SGNotReady { fn get(&self, _: &SessionId) -> Result<Option<GameReady>, FetchErr> { Ok(None) } fn put(&self, _: GameReady) -> Result<(), WriteErr> { panic!() } } impl GameReadyRepo for SGReady { fn get(&self, session_id: &SessionId) -> Result<Option<GameReady>, FetchErr> { if session_id == &self.0.sessions.0 { Ok(Some(self.0.clone())) } else if session_id == &self.0.sessions.1 { Ok(Some(self.0.clone())) } else { Ok(None) } } fn put(&self, _: GameReady) -> Result<(), WriteErr> { panic!() } } impl PrefsRepo for PrefsNone { fn get(&self, _: &SessionId) -> Result<Option<SessionColorPref>, FetchErr> { Ok(None) } fn put(&self, _: &SessionColorPref) -> Result<(), WriteErr> { panic!() } } impl PrefsRepo for PrefsOne { fn get(&self, session_id: &SessionId) -> Result<Option<SessionColorPref>, FetchErr> { if session_id == &self.0.session_id { Ok(Some(self.0.clone())) } else { Ok(None) } } fn put(&self, _: &SessionColorPref) -> Result<(), WriteErr> { panic!() } } impl PrefsRepo for PrefsTwo { fn get(&self, session_id: &SessionId) -> Result<Option<SessionColorPref>, FetchErr> { if session_id == &self.0.session_id { Ok(Some(self.0.clone())) } else if session_id == &self.1.session_id { Ok(Some(self.1.clone())) } else { Ok(None) } } fn put(&self, _: &SessionColorPref) -> Result<(), WriteErr> { panic!() } } #[test] fn test_by_session_id_complete() { let sid = SessionId::new(); let cid = ClientId::new(); let gid = GameId::new(); let one_pref = SessionColorPref { session_id: sid.clone(), color_pref: ColorPref::Black, client_id: cid.clone(), }; let another_sid = SessionId::new(); let another_cid = ClientId::new(); let another_pref = SessionColorPref { session_id: another_sid.clone(), color_pref: ColorPref::Black, client_id: another_cid.clone(), }; let board_size = 9; let repos = Repos { prefs: Rc::new(PrefsTwo(one_pref.clone(), another_pref.clone())), game_ready: Rc::new(SGReady(GameReady { sessions: (sid.clone(), another_sid.clone()), game_id: gid.clone(), event_id: EventId::new(), board_size, })), }; let actual = by_session_id(&sid, &repos).expect("ok"); assert_eq!( actual, GameColorPref::Complete { game_id: gid, prefs: (one_pref, another_pref) } ) } #[test] fn test_by_session_id_partial() { let sid = SessionId::new(); let cid = ClientId::new(); let gid = GameId::new(); let pref = SessionColorPref { session_id: sid.clone(), color_pref: ColorPref::Black, client_id: cid.clone(), }; let board_size = 9; let repos = Repos { prefs: Rc::new(PrefsOne(pref.clone())), game_ready: Rc::new(SGReady(GameReady { sessions: (sid.clone(), SessionId::new()), game_id: gid.clone(), event_id: EventId::new(), board_size, })), }; let actual = by_session_id(&sid, &repos).expect("ok"); assert_eq!(actual, GameColorPref::Partial { game_id: gid, pref }) } #[test] fn test_by_session_id_not_ready() { let sid = SessionId::new(); let cid = ClientId::new(); let repos = Repos { prefs: Rc::new(PrefsOne(SessionColorPref { session_id: sid.clone(), color_pref: ColorPref::Black, client_id: cid.clone(), })), game_ready: Rc::new(SGNotReady), }; let actual = by_session_id(&sid, &repos).expect("ok"); assert_eq!(actual, GameColorPref::NotReady) } #[test] fn test_by_game_ready_two_prefs() { let sid = SessionId::new(); let gid = GameId::new(); let another_sid = SessionId::new(); let sessions = (sid.clone(), another_sid.clone()); let board_size = 9; let game_ready = GameReady { sessions: sessions.clone(), game_id: gid.clone(), event_id: EventId::new(), board_size, }; let first_pref = SessionColorPref { session_id: sid.clone(), color_pref: ColorPref::Black, client_id: ClientId::new(), }; let second_pref = SessionColorPref { session_id: another_sid.clone(), color_pref: ColorPref::Black, client_id: ClientId::new(), }; let repos = Repos { prefs: Rc::new(PrefsTwo(first_pref.clone(), second_pref.clone())), game_ready: Rc::new(SGReady(game_ready.clone())), }; let actual = by_game_ready(&game_ready, &repos).expect("ok"); assert_eq!( actual, GameColorPref::Complete { game_id: gid, prefs: (first_pref, second_pref) } ) } #[test] fn test_by_game_ready_one_pref() { let sid = SessionId::new(); let gid = GameId::new(); let sessions = (sid.clone(), SessionId::new()); let board_size = 9; let game_ready = GameReady { sessions: sessions.clone(), game_id: gid.clone(), event_id: EventId::new(), board_size, }; let pref = SessionColorPref { session_id: sid.clone(), color_pref: ColorPref::Black, client_id: ClientId::new(), }; let repos = Repos { prefs: Rc::new(PrefsOne(pref.clone())), game_ready: Rc::new(SGReady(game_ready.clone())), }; let actual = by_game_ready(&game_ready, &repos).expect("ok"); assert_eq!(actual, GameColorPref::Partial { game_id: gid, pref }) } #[test] fn test_by_game_ready_no_prefs() { let sid = SessionId::new(); let gid = GameId::new(); let sessions = (sid, SessionId::new()); let board_size = 9; let game_ready = GameReady { sessions: sessions.clone(), game_id: gid, event_id: EventId::new(), board_size, }; let repos = Repos { prefs: Rc::new(PrefsNone), game_ready: Rc::new(SGReady(game_ready.clone())), }; let actual = by_game_ready(&game_ready, &repos).expect("ok"); assert_eq!(actual, GameColorPref::NotReady) } }
use crate::components::Repos; use crate::repo::*; use api::GameReady; use color_model::*; use core_model::*; pub fn by_session_id(session_id: &SessionId, repos: &Repos) -> Result<GameColorPref, FetchErr> { repos.game_ready.get(session_id).and_then(|sg| match sg { None => Ok(GameColorPref::NotReady), Some(game_ready) => { let first_pref = repos.prefs.get(&game_ready.sessions.0); let second_pref = repos.prefs.get(&game_ready.sessions.1); match (first_pref, second_pref) { (Ok(Some(first)), Ok(Some(second))) => Ok(GameColorPref::Complete { game_id: game_ready.game_id.clone(), prefs: (first, second), }), (Ok(Some(partial)), Ok(None)) => Ok(GameColorPref::Partial { game_id: game_ready.game_id.clone(), pref: partial, }), (Ok(None), Ok(Some(partial))) => Ok(GameColorPref::Partial { game_id: game_ready.game_id.clone(), pref: partial, }), (Ok(None), Ok(None)) => Ok(GameColorPref::NotReady), (Err(e), _) => Err(e), (_, Err(e)) => Err(e), } } }) } pub fn by_game_ready(game_ready: &GameReady, repos: &Repos) -> Result<GameColorPref, FetchErr> { let first_pref = repos.prefs.get(&game_ready.sessions.0)?; let second_pref = repos.prefs.get(&game_ready.sessions.1)?; Ok(match (first_pref, second_pref) { (Some(first), Some(second)) => GameColorPref::Complete { game_id: game_ready.game_id.clone(), prefs: (first, second), }, (Some(partial), None) => GameColorPref::Partial { game_id: game_ready.game_id.clone(), pref: partial, }, (None, Some(partial)) => GameColorPref::Partial { game_id: game_ready.game_id.clone(), pref: partial, }, _ => GameColorPref::NotReady, }) } #[cfg(test)] mod tests { use super::*; use std::rc::Rc; struct SGNotReady; struct SGReady(pub GameReady); struct PrefsNone; struct PrefsOne(pub SessionColorPref); struct PrefsTwo(pub SessionColorPref, pub SessionColorPref); impl GameReadyRepo for SGNotReady { fn get(&self, _: &SessionId) -> Result<Option<GameReady>, FetchErr> { Ok(None) } fn put(&self, _: GameReady) -> Result<(), WriteErr> { panic!() } } impl GameReadyRepo for SGReady { fn get(&self, session_id: &SessionId) -> Result<Option<GameReady>, FetchErr> { if session_id == &self.0.sessions.0 { Ok(Some(self.0.clone())) } else if session_id == &self.0.sessions.1 { Ok(Some(self.0.clone())) } else { Ok(None) } } fn put(&self, _: GameReady) -> Result<(), WriteErr> { panic!() } } impl PrefsRepo for PrefsNone { fn get(&self, _: &SessionId) -> Result<Option<SessionColorPref>, FetchErr> { Ok(None) } fn put(&self, _: &SessionColorPref) -> Result<(), WriteErr> { panic!() } } impl PrefsRepo for PrefsOne { fn get(&self, session_id: &SessionId) -> Result<Option<SessionColorPref>, FetchErr> { if session_id == &self.0.session_id { Ok(Some(self.0.clone())) } else { Ok(None) } } fn put(&self, _: &SessionColorPref) -> Result<(), WriteErr> { panic!() } } impl PrefsRepo for PrefsTwo { fn get(&self, session_id: &SessionId) -> Result<Option<SessionColorPref>, FetchErr> { if session_id == &self.0.session_id { Ok(Some(self.0.clone())) } else if session_id == &self.1.session_id { Ok(Some(self.1.clone())) } else { Ok(None) } } fn put(&self, _: &SessionColorPref) -> Result<(), WriteErr> { panic!() } } #[test] fn test_by_session_id_complete() { let sid = SessionId::new(); let cid = ClientId::new(); let gid = GameId::new(); let one_pref = SessionColorPref { session_id: sid.clone(), color_pref: ColorPref::Black, client_id: cid.clone(), }; let another_sid = SessionId::new(); let another_cid = ClientId::new(); let another_pref = SessionColorPref { session_id: another_sid.clone(), color_pref: ColorPref::Black, client_id: another_cid.clone(), }; let board_size = 9; let repos = Repos { prefs: Rc::new(PrefsTwo(one_pref.clone(), another_pref.clone())), game_ready: Rc::new(SGReady(GameReady { sessions: (sid.clone(), another_sid.clone()), game_id: gid.clone(), event_id: EventId::new(), board_size, })), }; let actual = by_session_id(&sid, &repos).expect("ok"); assert_eq!( actual, GameColorPref::Complete { game_id: gid, prefs: (one_p
ert_eq!(actual, GameColorPref::NotReady) } }
ref, another_pref) } ) } #[test] fn test_by_session_id_partial() { let sid = SessionId::new(); let cid = ClientId::new(); let gid = GameId::new(); let pref = SessionColorPref { session_id: sid.clone(), color_pref: ColorPref::Black, client_id: cid.clone(), }; let board_size = 9; let repos = Repos { prefs: Rc::new(PrefsOne(pref.clone())), game_ready: Rc::new(SGReady(GameReady { sessions: (sid.clone(), SessionId::new()), game_id: gid.clone(), event_id: EventId::new(), board_size, })), }; let actual = by_session_id(&sid, &repos).expect("ok"); assert_eq!(actual, GameColorPref::Partial { game_id: gid, pref }) } #[test] fn test_by_session_id_not_ready() { let sid = SessionId::new(); let cid = ClientId::new(); let repos = Repos { prefs: Rc::new(PrefsOne(SessionColorPref { session_id: sid.clone(), color_pref: ColorPref::Black, client_id: cid.clone(), })), game_ready: Rc::new(SGNotReady), }; let actual = by_session_id(&sid, &repos).expect("ok"); assert_eq!(actual, GameColorPref::NotReady) } #[test] fn test_by_game_ready_two_prefs() { let sid = SessionId::new(); let gid = GameId::new(); let another_sid = SessionId::new(); let sessions = (sid.clone(), another_sid.clone()); let board_size = 9; let game_ready = GameReady { sessions: sessions.clone(), game_id: gid.clone(), event_id: EventId::new(), board_size, }; let first_pref = SessionColorPref { session_id: sid.clone(), color_pref: ColorPref::Black, client_id: ClientId::new(), }; let second_pref = SessionColorPref { session_id: another_sid.clone(), color_pref: ColorPref::Black, client_id: ClientId::new(), }; let repos = Repos { prefs: Rc::new(PrefsTwo(first_pref.clone(), second_pref.clone())), game_ready: Rc::new(SGReady(game_ready.clone())), }; let actual = by_game_ready(&game_ready, &repos).expect("ok"); assert_eq!( actual, GameColorPref::Complete { game_id: gid, prefs: (first_pref, second_pref) } ) } #[test] fn test_by_game_ready_one_pref() { let sid = SessionId::new(); let gid = GameId::new(); let sessions = (sid.clone(), SessionId::new()); let board_size = 9; let game_ready = GameReady { sessions: sessions.clone(), game_id: gid.clone(), event_id: EventId::new(), board_size, }; let pref = SessionColorPref { session_id: sid.clone(), color_pref: ColorPref::Black, client_id: ClientId::new(), }; let repos = Repos { prefs: Rc::new(PrefsOne(pref.clone())), game_ready: Rc::new(SGReady(game_ready.clone())), }; let actual = by_game_ready(&game_ready, &repos).expect("ok"); assert_eq!(actual, GameColorPref::Partial { game_id: gid, pref }) } #[test] fn test_by_game_ready_no_prefs() { let sid = SessionId::new(); let gid = GameId::new(); let sessions = (sid, SessionId::new()); let board_size = 9; let game_ready = GameReady { sessions: sessions.clone(), game_id: gid, event_id: EventId::new(), board_size, }; let repos = Repos { prefs: Rc::new(PrefsNone), game_ready: Rc::new(SGReady(game_ready.clone())), }; let actual = by_game_ready(&game_ready, &repos).expect("ok"); ass
random
[ { "content": "pub fn fetch(game_id: &GameId, components: &Components) -> Result<Option<GameState>, FetchErr> {\n\n let mut conn = components.client.get_connection().expect(\"fetch conn\");\n\n let key = components.redis_key_provider.game_states(&game_id);\n\n let bin_data: Option<Vec<u8>> = conn.get(&k...
Rust
src/util.rs
rantan/tapyrus-signer
bd8026460860469b15b2fca3ae158c801d15870f
use curv::{BigInt, GE}; use std::convert::TryFrom; use std::os::raw::c_int; use std::sync::atomic::AtomicUsize; use std::sync::Arc; pub fn sum_point(points: &Vec<GE>) -> GE { let mut iter = points.iter(); let head = iter.next().unwrap(); let tail = iter; tail.fold(head.clone(), |acc, x| acc + x) } pub fn jacobi(a: &BigInt, n: &BigInt) -> i8 { assert!(*n >= BigInt::from(3)); assert!(a < n); if a.is_zero() { return 0; } if *a == BigInt::from(1) { return 1; } let mut a1: BigInt = a.clone(); let mut e = 0; while a1.is_multiple_of(&BigInt::from(2)) { a1 = a1 >> 1; e += 1; } let mut s: i8 = if e & 1 == 0 || n.modulus(&BigInt::from(8)) == BigInt::from(1) || n.modulus(&BigInt::from(8)) == BigInt::from(7) { 1 } else if n.modulus(&BigInt::from(8)) == BigInt::from(3) || n.modulus(&BigInt::from(8)) == BigInt::from(5) { -1 } else { 0 }; if n.modulus(&BigInt::from(4)) == BigInt::from(3) && a1.modulus(&BigInt::from(4)) == BigInt::from(3) { s = -s } if a1 == BigInt::from(1) { s } else { s * jacobi(&(n % a1.clone()), &a1.clone()) } } const STOP_SIGNALS: [usize; 6] = [ signal_hook::SIGABRT as usize, signal_hook::SIGHUP as usize, signal_hook::SIGINT as usize, signal_hook::SIGQUIT as usize, signal_hook::SIGTERM as usize, signal_hook::SIGTRAP as usize, ]; pub fn set_stop_signal_handler() -> Result<Arc<AtomicUsize>, std::io::Error> { let handler = Arc::new(AtomicUsize::new(0)); for signal in &STOP_SIGNALS { signal_hook::flag::register_usize( *signal as c_int, Arc::clone(&handler), *signal as usize, )?; } Ok(handler) } pub fn signal_to_string(signal: usize) -> &'static str { let signal: u32 = TryFrom::try_from(signal).unwrap(); match signal as i32 { signal_hook::SIGABRT => "SIGABRT", signal_hook::SIGHUP => "SIGHUP", signal_hook::SIGINT => "SIGINT", signal_hook::SIGQUIT => "SIGQUIT", signal_hook::SIGTERM => "SIGTERM", signal_hook::SIGTRAP => "SIGTRAP", _ => unreachable!("unregistered signal received"), } } #[cfg(test)] mod tests { use super::*; use std::sync::atomic::Ordering; #[test] fn test_sum_point() { use curv::elliptic::curves::secp256_k1::*; use curv::elliptic::curves::traits::ECPoint; use curv::elliptic::curves::traits::ECScalar; use curv::BigInt; let s1 = ECScalar::from(&BigInt::from(1)); let s2 = ECScalar::from(&BigInt::from(2)); let s3 = ECScalar::from(&BigInt::from(3)); let p1 = GE::generator() * &s1; let p2 = GE::generator() * &s2; let p3 = GE::generator() * &s3; let sum = sum_point(&vec![p1, p2, p3]); let s6 = ECScalar::from(&BigInt::from(6)); let p6 = GE::generator() * &s6; assert_eq!(sum, p6); } #[test] fn test_jacobi() { assert_eq!(jacobi(&BigInt::from(158), &BigInt::from(235)), -1); assert_eq!(jacobi(&BigInt::from(5), &BigInt::from(12)), -1); assert_eq!(jacobi(&BigInt::from(16), &BigInt::from(60)), 1); } #[test] fn test_signals() { let handler = set_stop_signal_handler().unwrap(); unsafe { libc::raise(signal_hook::SIGINT); assert_eq!( handler.load(Ordering::Relaxed), signal_hook::SIGINT as usize ); libc::raise(signal_hook::SIGABRT); assert_eq!( handler.load(Ordering::Relaxed), signal_hook::SIGABRT as usize ); libc::raise(signal_hook::SIGHUP); assert_eq!( handler.load(Ordering::Relaxed), signal_hook::SIGHUP as usize ); libc::raise(signal_hook::SIGQUIT); assert_eq!( handler.load(Ordering::Relaxed), signal_hook::SIGQUIT as usize ); libc::raise(signal_hook::SIGTERM); assert_eq!( handler.load(Ordering::Relaxed), signal_hook::SIGTERM as usize ); libc::raise(signal_hook::SIGTRAP); assert_eq!( handler.load(Ordering::Relaxed), signal_hook::SIGTRAP as usize ); } } }
use curv::{BigInt, GE}; use std::convert::TryFrom; use std::os::raw::c_int; use std::sync::atomic::AtomicUsize; use std::sync::Arc; pub fn sum_point(points: &Vec<GE>) -> GE { let mut iter = points.iter(); let head = iter.next().unwrap(); let tail = iter; tail.fold(head.clone(), |acc, x| acc + x) } pub fn jacobi(a: &BigInt, n: &BigInt) -> i8 { assert!(*n >= BigInt::from(3)); assert!(a < n); if a.is_zero() { return 0; } if *a == BigInt::from(1) { return 1; } let mut a1: BigInt = a.clone(); let mut e = 0;
const STOP_SIGNALS: [usize; 6] = [ signal_hook::SIGABRT as usize, signal_hook::SIGHUP as usize, signal_hook::SIGINT as usize, signal_hook::SIGQUIT as usize, signal_hook::SIGTERM as usize, signal_hook::SIGTRAP as usize, ]; pub fn set_stop_signal_handler() -> Result<Arc<AtomicUsize>, std::io::Error> { let handler = Arc::new(AtomicUsize::new(0)); for signal in &STOP_SIGNALS { signal_hook::flag::register_usize( *signal as c_int, Arc::clone(&handler), *signal as usize, )?; } Ok(handler) } pub fn signal_to_string(signal: usize) -> &'static str { let signal: u32 = TryFrom::try_from(signal).unwrap(); match signal as i32 { signal_hook::SIGABRT => "SIGABRT", signal_hook::SIGHUP => "SIGHUP", signal_hook::SIGINT => "SIGINT", signal_hook::SIGQUIT => "SIGQUIT", signal_hook::SIGTERM => "SIGTERM", signal_hook::SIGTRAP => "SIGTRAP", _ => unreachable!("unregistered signal received"), } } #[cfg(test)] mod tests { use super::*; use std::sync::atomic::Ordering; #[test] fn test_sum_point() { use curv::elliptic::curves::secp256_k1::*; use curv::elliptic::curves::traits::ECPoint; use curv::elliptic::curves::traits::ECScalar; use curv::BigInt; let s1 = ECScalar::from(&BigInt::from(1)); let s2 = ECScalar::from(&BigInt::from(2)); let s3 = ECScalar::from(&BigInt::from(3)); let p1 = GE::generator() * &s1; let p2 = GE::generator() * &s2; let p3 = GE::generator() * &s3; let sum = sum_point(&vec![p1, p2, p3]); let s6 = ECScalar::from(&BigInt::from(6)); let p6 = GE::generator() * &s6; assert_eq!(sum, p6); } #[test] fn test_jacobi() { assert_eq!(jacobi(&BigInt::from(158), &BigInt::from(235)), -1); assert_eq!(jacobi(&BigInt::from(5), &BigInt::from(12)), -1); assert_eq!(jacobi(&BigInt::from(16), &BigInt::from(60)), 1); } #[test] fn test_signals() { let handler = set_stop_signal_handler().unwrap(); unsafe { libc::raise(signal_hook::SIGINT); assert_eq!( handler.load(Ordering::Relaxed), signal_hook::SIGINT as usize ); libc::raise(signal_hook::SIGABRT); assert_eq!( handler.load(Ordering::Relaxed), signal_hook::SIGABRT as usize ); libc::raise(signal_hook::SIGHUP); assert_eq!( handler.load(Ordering::Relaxed), signal_hook::SIGHUP as usize ); libc::raise(signal_hook::SIGQUIT); assert_eq!( handler.load(Ordering::Relaxed), signal_hook::SIGQUIT as usize ); libc::raise(signal_hook::SIGTERM); assert_eq!( handler.load(Ordering::Relaxed), signal_hook::SIGTERM as usize ); libc::raise(signal_hook::SIGTRAP); assert_eq!( handler.load(Ordering::Relaxed), signal_hook::SIGTRAP as usize ); } } }
while a1.is_multiple_of(&BigInt::from(2)) { a1 = a1 >> 1; e += 1; } let mut s: i8 = if e & 1 == 0 || n.modulus(&BigInt::from(8)) == BigInt::from(1) || n.modulus(&BigInt::from(8)) == BigInt::from(7) { 1 } else if n.modulus(&BigInt::from(8)) == BigInt::from(3) || n.modulus(&BigInt::from(8)) == BigInt::from(5) { -1 } else { 0 }; if n.modulus(&BigInt::from(4)) == BigInt::from(3) && a1.modulus(&BigInt::from(4)) == BigInt::from(3) { s = -s } if a1 == BigInt::from(1) { s } else { s * jacobi(&(n % a1.clone()), &a1.clone()) } }
function_block-function_prefix_line
[ { "content": "fn compute_e(r: &GE, y: &GE, message: &[u8]) -> FE {\n\n let mut hasher = Sha256::new();\n\n hasher.input(&r.get_element().serialize()[1..33]);\n\n hasher.input(&y.get_element().serialize()[..]);\n\n hasher.input(message);\n\n let e_bn = BigInt::from(&hasher.result()[..]);\n\n\n\n ...
Rust
iml-gui/crate/src/page/login.rs
intel-hpdd/-intel-manager-for-lustre
f8a6f61205b42cc62f4bbcb8d81214ad4f215cd6
use crate::{ auth, components::{ddn_logo, ddn_logo_lettering, whamcloud_logo}, generated::css_classes::C, GMsg, MergeAttrs, }; use core::fmt; use iml_wire_types::Branding; use seed::{browser::service::fetch, prelude::*, *}; #[derive(Clone, Default, serde::Serialize)] struct Form { username: String, password: String, } #[derive(Clone, Debug, Default, serde::Deserialize)] pub struct Errors { __all__: Option<String>, password: Option<Vec<String>>, username: Option<Vec<String>>, } #[derive(Default)] pub struct Model { errors: Option<Errors>, form: Form, logging_in: bool, } impl Model { fn disabled(&self) -> bool { self.form.username.is_empty() || self.form.password.is_empty() || self.logging_in } } #[allow(clippy::large_enum_variant)] #[derive(Clone)] pub enum Msg { UsernameChange(String), PasswordChange(String), SubmitResp(fetch::FetchObject<Errors>), Submit, } impl fmt::Debug for Msg { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::PasswordChange(_) => f.write_str("*****"), _ => write!(f, "{:?}", self), } } } async fn login(form: Form) -> Result<Msg, Msg> { auth::fetch_session() .method(fetch::Method::Post) .send_json(&form) .fetch_json(Msg::SubmitResp) .await } pub fn update(msg: Msg, model: &mut Model, orders: &mut impl Orders<Msg, GMsg>) { match msg { Msg::UsernameChange(x) => model.form.username = x, Msg::PasswordChange(x) => model.form.password = x, Msg::Submit => { model.logging_in = true; orders.perform_cmd(login(model.form.clone())); } Msg::SubmitResp(x) => { match x.result { Err(e) => error!("Response error {:?}", e), Ok(x) => { if x.status.code < 400 { orders.skip().send_g_msg(GMsg::AuthProxy(Box::new(auth::Msg::LoggedIn))); } else { model.logging_in = false; match x.data { Ok(x) => model.errors = Some(x), Err(e) => error!("DataError {:?}", e), } } } }; } } } fn err_item<T>(x: &str) -> Node<T> { p![class![C.text_red_500, C.text_xs, C.italic,], x] } pub fn view(model: &Model, branding: Branding, exa_version: &Option<String>) -> impl View<Msg> { let input_cls = class![ C.appearance_none, C.focus__outline_none, C.focus__shadow_outline, C.px_3, C.py_2, C.rounded_sm, C.text_gray_800, C.bg_gray_200, ]; let errs = Errors::default(); let errs = model.errors.as_ref().unwrap_or_else(|| &errs); let (border_color, text_color, logo) = match branding { Branding::Whamcloud => ( C.border_teal_500, C.text_teal_500, whamcloud_logo().merge_attrs(class![C.h_16, C.w_16]), ), Branding::DDN(_) => ( C.border_red_700, C.text_black, div![ class![C.w_32, C.flex, C.flex_col, C.items_center], ddn_logo().merge_attrs(class![C.w_24, C.mb_4]), ddn_logo_lettering().merge_attrs(class![C.w_24]), ], ), }; let exa_version = if let Some(version) = exa_version { p![class![C.mt_3], "Version ", version] } else { empty![] }; div![ class![ C.bg_gray_100, C.fade_in, C.flex, C.items_center, C.justify_center, C.min_h_screen, ], form![ class![C.bg_white, C.shadow_md, C.px_16, C.py_8, C.border_b_8, border_color], ev(Ev::Submit, move |event| { event.prevent_default(); Msg::Submit }), div![ class![ C.flex_col, C.flex, C.items_center, C.justify_center, C.mb_6 text_color, ], logo, exa_version ], match errs.__all__.as_ref() { Some(x) => err_item(x), None => empty![], }, div![ class![C.mb_4], input![ class![C.mt_2], input_ev(Ev::Input, Msg::UsernameChange), &input_cls, attrs! { At::AutoFocus => true.as_at_value(), At::Required => true.as_at_value(), At::Placeholder => "Username", At::AutoComplete => "username" }, ], match errs.username.as_ref() { Some(errs) => { errs.iter().map(|x| err_item(x)).collect() } None => vec![], } ], div![ class![C.mb_6], input![ class![C.mt_2, C.mb_2], input_ev(Ev::Input, Msg::PasswordChange), &input_cls, attrs! { At::Required => true, At::Type => "password", At::Placeholder => "Password", At::AutoComplete => "current-password" }, ], match errs.password.as_ref() { Some(errs) => { errs.iter().map(|x| err_item(x)).collect() } None => vec![], } ], div![ class![C.flex, C.items_center, C.justify_between], button![ class![ C.bg_gray_500 => model.disabled(), C.cursor_not_allowed => model.disabled(), C.bg_blue_500 => !model.disabled(), C.hover__bg_blue_700 => !model.disabled(), C.text_white, C.py_2, C.px_6, C.rounded_sm, C.focus__outline_none ], attrs! { At::Disabled => model.disabled().as_at_value() }, "Login", ], ], ] ] }
use crate::{ auth, components::{ddn_logo, ddn_logo_lettering, whamcloud_logo}, generated::css_classes::C, GMsg, MergeAttrs, }; use core::fmt; use iml_wire_types::Branding; use seed::{browser::service::fetch, prelude::*, *}; #[derive(Clone, Default, serde::Serialize)] struct Form { username: String, password: String, } #[derive(Clone, Debug, Default, serde::Deserialize)] pub struct Errors { __all__: Option<String>, password: Option<Vec<String>>, username: Option<Vec<String>>, } #[derive(Default)] pub struct Model { errors: Option<Errors>, form: Form, logging_in: bool, } impl Model { fn disabled(&self) -> bool { self.form.username.is_empty() || self.form.password.is_empty() || self.logging_in } } #[allow(clippy::large_enum_variant)] #[derive(Clone)] pub enum Msg { UsernameChange(String), PasswordChange(String), SubmitResp(fetch::FetchObject<Errors>), Submit, } impl fmt::Debug for Msg { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::PasswordChange(_) => f.write_str("*****"), _ => write!(f, "{:?}", self), } } } async fn login(form: Form) -> Result<Msg, Msg> { auth::fetch_session() .method(fetch::Method::Post) .send_json(&form) .fetch_json(Msg::SubmitResp) .await } pub fn update(msg: Msg, model: &mut Model, orders: &mut impl Orders<Msg, GMsg>) { match msg { Msg::UsernameChange(x) => model.form.username = x, Msg::PasswordChange(x) => model.form.password = x, Msg::Submit => { model.logging_in = true; orders.perform_cmd(login(model.form.clone())); } Msg::SubmitResp(x) => { match x.result { Err(e) => error!("Response error {:?}", e), Ok(x) => { if x.status.code < 400 { orders.skip().send_g_msg(GMsg::AuthProxy(Box::new(auth::Msg::LoggedIn))); } else { model.logging_in = false; match x.data { Ok(x) => model.errors = Some(x), Err(e) => error!("DataError {:?}", e), } } } }; } } } fn err_item<T>(x: &str) -> Node<T> { p![class![C.text_red_500, C.text_xs, C.italic,], x] } pub fn view(model: &Model, branding: Branding, exa_version: &Option<String>) -> impl View<Msg> { let input_cls = class![ C.appearance_none, C.focus__outline_none, C.focus__shadow_outline, C.px_3, C.py_2, C.rounded_sm, C.text_gray_800, C.bg_gray_200, ]; let errs = Errors::default(); let errs = model.errors.as_ref().unwrap_or_else(|| &errs); let (border_color, text_color, logo) = match branding { Branding::Whamcloud => ( C.border_teal_500, C.text_teal_500, whamcloud_logo().merge_attrs(class![C.h_16, C.w_16]), ), Branding::DDN(_) => ( C.border_red_700, C.text_black, div![ class![C.w_32, C.flex, C.flex_col, C.items_center], ddn_logo().merge_attrs(class![C.w_24, C.mb_4]), ddn_logo_lettering().merge_attrs(class![C.w_24]), ], ), }; let exa_version = if let Some(version) = exa_version { p![class![C.mt_3], "Version ", version] } else { empty![] }; div![ class![ C.bg_gray_100, C.fade_in, C.flex, C.items_center, C.justify_center, C.min_h_screen, ], form![ class![C.bg_white, C.shadow_md, C.px_16, C.py_8, C.border_b_8, border_color], ev(Ev::Submit, move |event| { event.prevent_default(); Msg::Submit }), div![ class![ C.flex_col, C.flex, C.items_center, C.justify_center, C.mb_6 text_color, ], logo, exa_version ], match errs.__all__.as_ref() { Some(x) => err_item(x), None => empty![], }, div![ class![C.mb_4], input![ class![C.mt_2], input_ev(Ev::Input, Msg::UsernameChange), &input_cls, attrs! { At::AutoFocus => true.as_at_value(), At::Required => true.as_at_value(), At::Placeholder => "Username", At::AutoComplete => "username" }, ], match errs.username.as_ref() { Some(errs) => { errs.iter().map(|x| err_item(x)).collect() } None => vec![], } ], div![ class![C.mb_6], input![ class![C.mt_2, C.mb_2], input_ev(Ev::Input, Msg::PasswordChange), &input_cls, attrs! { At::Required => true, At::Type => "passw
] ] }
ord", At::Placeholder => "Password", At::AutoComplete => "current-password" }, ], match errs.password.as_ref() { Some(errs) => { errs.iter().map(|x| err_item(x)).collect() } None => vec![], } ], div![ class![C.flex, C.items_center, C.justify_between], button![ class![ C.bg_gray_500 => model.disabled(), C.cursor_not_allowed => model.disabled(), C.bg_blue_500 => !model.disabled(), C.hover__bg_blue_700 => !model.disabled(), C.text_white, C.py_2, C.px_6, C.rounded_sm, C.focus__outline_none ], attrs! { At::Disabled => model.disabled().as_at_value() }, "Login", ], ],
random
[ { "content": "pub fn update(msg: Msg, model: &mut Model, orders: &mut impl Orders<Msg, GMsg>) {\n\n match msg {\n\n Msg::Fetch => {\n\n model.cancel = None;\n\n\n\n let request = fetch_session().controller(|controller| model.request_controller = Some(controller));\n\n\n\n ...
Rust
src/gossip/config.rs
devillove084/HierarchicalCache
0e6f95b758dbb9df274075d550e2b0dc8fd66699
#![allow(dead_code)] #[derive(Clone)] pub struct PeerSamplingConfig { push: bool, pull: bool, sampling_period: u64, sampling_deviation: u64, view_size: usize, healing_factor: usize, swapping_factor: usize, } impl PeerSamplingConfig { pub fn new(push: bool, pull: bool, sampling_period: u64, view_size: usize, healing_factor: usize, swapping_factor: usize) -> Self { PeerSamplingConfig { push, pull, sampling_period, sampling_deviation: 0, view_size, healing_factor, swapping_factor, } } pub fn new_with_deviation(push: bool, pull: bool, sampling_period: u64, sampling_deviation: u64, view_size: usize, healing_factor: usize, swapping_factor: usize) -> Self { PeerSamplingConfig { push, pull, sampling_period, sampling_deviation, view_size, healing_factor, swapping_factor, } } pub fn sampling_period(&self) -> u64 { self.sampling_period } pub fn sampling_deviation(&self) -> u64 { self.sampling_deviation } pub fn healing_factor(&self) -> usize { self.healing_factor } pub fn swapping_factor(&self) -> usize { self.swapping_factor } pub fn view_size(&self) -> usize { self.view_size } pub fn is_pull(&self) -> bool { self.pull } pub fn is_push(&self) -> bool { self.push } } impl Default for PeerSamplingConfig { fn default() -> Self { PeerSamplingConfig { push: true, pull: true, sampling_period: 60000, sampling_deviation: 0, view_size: 30, healing_factor: 3, swapping_factor: 12 } } } pub struct GossipConfig { push: bool, pull: bool, gossip_period: u64, gossip_deviation: u64, update_expiration: UpdateExpirationMode, } impl GossipConfig { pub fn new(push: bool, pull: bool, gossip_period: u64, update_expiration: UpdateExpirationMode) -> Self { GossipConfig { push, pull, gossip_period, gossip_deviation: 0, update_expiration, } } pub fn new_with_deviation(push: bool, pull: bool, gossip_period: u64, gossip_deviation: u64, update_expiration: UpdateExpirationMode) -> Self { GossipConfig { push, pull, gossip_period, gossip_deviation, update_expiration, } } pub fn is_push(&self) -> bool { self.push } pub fn is_pull(&self) -> bool { self.pull } pub fn gossip_period(&self) -> u64 { self.gossip_period } pub fn gossip_deviation(&self) -> u64 { self.gossip_deviation } pub fn update_expiration(&self) -> &UpdateExpirationMode { &self.update_expiration } } impl Default for GossipConfig { fn default() -> Self { GossipConfig { push: true, pull: true, gossip_period: 1000, gossip_deviation: 0, update_expiration: UpdateExpirationMode::None } } } #[derive(Debug, Clone)] pub enum UpdateExpirationMode { None, DurationMillis(u128), PushCount(u64), MostRecent(usize, f64), } pub enum UpdateExpirationValue { None, DurationMillis(std::time::Instant, u128), PushCount(u64), MostRecent(std::time::Instant), } impl UpdateExpirationValue { pub fn new(expiration_mode: UpdateExpirationMode) -> Self { match expiration_mode { UpdateExpirationMode::None => UpdateExpirationValue::None, UpdateExpirationMode::PushCount(count) => UpdateExpirationValue::PushCount(count), UpdateExpirationMode::DurationMillis(ms) => UpdateExpirationValue::DurationMillis(std::time::Instant::now(), ms), UpdateExpirationMode::MostRecent(_, _) => UpdateExpirationValue::MostRecent(std::time::Instant::now()), } } pub fn increase_push_count(&mut self) { match self { UpdateExpirationValue::PushCount(ref mut count) => { if *count > 0 { *count -= 1 } }, _ => (), } } pub fn has_expired(&self) -> bool { match self { UpdateExpirationValue::None => false, UpdateExpirationValue::PushCount(count) => *count == 0, UpdateExpirationValue::DurationMillis(start, ttl) => start.elapsed().as_millis() >= *ttl, UpdateExpirationValue::MostRecent(_) => false, } } }
#![allow(dead_code)] #[derive(Clone)] pub struct PeerSamplingConfig { push: bool, pull: bool, sampling_period: u64, sampling_deviation: u64, view_size: usize, healing_factor: usize, swapping_factor: usize, } impl PeerSamplingConfig { pub fn new(push: bool, pull: bool, sampling_period: u64, view_size: usize, healing_factor: usize, swapping_factor: usize) -> Self { PeerSamplingConfig { push, pull, sampling_period, sampling_deviation: 0, view_size, healing_factor, swapping_factor, } } pub fn new_with_deviation(push: bool, pull: bool, sampling_period: u64, sampling_deviation: u64, view_size: usize, healing_factor: usize, swapping_factor: usize) -> Self { PeerSamplingConfig { push, pull, sampling_period, sampling_deviation, view_size, healing_factor, swapping_factor, } } pub fn sampling_period(&self) -> u64 { self.sampling_period } pub fn sampling_deviation(&self) -> u64 { self.sampling_deviation } pub fn healing_factor(&self) -> usize { self.healing_factor } pub fn swapping_factor(&self) -> usize { self.swapping_factor } pub fn view_size(&self) -> usize { self.view_size } pub fn is_pull(&self) -> bool { self.pull } pub fn is_push(&self) -> bool { self.push } } impl Default for PeerSamplingConfig {
} pub struct GossipConfig { push: bool, pull: bool, gossip_period: u64, gossip_deviation: u64, update_expiration: UpdateExpirationMode, } impl GossipConfig { pub fn new(push: bool, pull: bool, gossip_period: u64, update_expiration: UpdateExpirationMode) -> Self { GossipConfig { push, pull, gossip_period, gossip_deviation: 0, update_expiration, } } pub fn new_with_deviation(push: bool, pull: bool, gossip_period: u64, gossip_deviation: u64, update_expiration: UpdateExpirationMode) -> Self { GossipConfig { push, pull, gossip_period, gossip_deviation, update_expiration, } } pub fn is_push(&self) -> bool { self.push } pub fn is_pull(&self) -> bool { self.pull } pub fn gossip_period(&self) -> u64 { self.gossip_period } pub fn gossip_deviation(&self) -> u64 { self.gossip_deviation } pub fn update_expiration(&self) -> &UpdateExpirationMode { &self.update_expiration } } impl Default for GossipConfig { fn default() -> Self { GossipConfig { push: true, pull: true, gossip_period: 1000, gossip_deviation: 0, update_expiration: UpdateExpirationMode::None } } } #[derive(Debug, Clone)] pub enum UpdateExpirationMode { None, DurationMillis(u128), PushCount(u64), MostRecent(usize, f64), } pub enum UpdateExpirationValue { None, DurationMillis(std::time::Instant, u128), PushCount(u64), MostRecent(std::time::Instant), } impl UpdateExpirationValue { pub fn new(expiration_mode: UpdateExpirationMode) -> Self { match expiration_mode { UpdateExpirationMode::None => UpdateExpirationValue::None, UpdateExpirationMode::PushCount(count) => UpdateExpirationValue::PushCount(count), UpdateExpirationMode::DurationMillis(ms) => UpdateExpirationValue::DurationMillis(std::time::Instant::now(), ms), UpdateExpirationMode::MostRecent(_, _) => UpdateExpirationValue::MostRecent(std::time::Instant::now()), } } pub fn increase_push_count(&mut self) { match self { UpdateExpirationValue::PushCount(ref mut count) => { if *count > 0 { *count -= 1 } }, _ => (), } } pub fn has_expired(&self) -> bool { match self { UpdateExpirationValue::None => false, UpdateExpirationValue::PushCount(count) => *count == 0, UpdateExpirationValue::DurationMillis(start, ttl) => start.elapsed().as_millis() >= *ttl, UpdateExpirationValue::MostRecent(_) => false, } } }
fn default() -> Self { PeerSamplingConfig { push: true, pull: true, sampling_period: 60000, sampling_deviation: 0, view_size: 30, healing_factor: 3, swapping_factor: 12 } }
function_block-full_function
[ { "content": "pub fn string_object_hash(object: &RobjPtr, seed: u64) -> usize {\n\n match object.borrow().encoding() {\n\n RobjEncoding::Raw =>\n\n murmur_hash64a(object.borrow().string(), seed) as usize,\n\n RobjEncoding::Int =>\n\n murmur_hash64a(object.borrow().integer(...
Rust
src/lib.rs
alec-deason/bevy_contrib_schedules
7029bf35f5c784ff4e8eba11152b072b54afc6d2
use bevy::{ app::stage, core::Time, ecs::{Schedule, ParallelExecutor, World, Resources, System, Entity}, utils::HashMap, }; #[derive(Debug)] pub enum ScheduleType { Always, Fixed(f64, f64), } pub struct PackedSchedule(pub ScheduleType, pub Schedule, ParallelExecutor); impl Default for PackedSchedule { fn default() -> Self { PackedSchedule( ScheduleType::Always, Default::default(), ParallelExecutor::without_tracker_clears(), ) } } impl PackedSchedule { fn run(&mut self, mut world: &mut World, mut resources: &mut Resources) { self.1.initialize(world, resources); match &mut self.0 { ScheduleType::Always => { self.2.run(&mut self.1, &mut world, &mut resources); }, ScheduleType::Fixed(rate, accumulator) => { match resources.get::<Time>() { Some(time) => { *accumulator += time.delta_seconds_f64; }, None => log::debug!("Time does not exist, Fixed Schedule cannot run!"), }; while accumulator >= rate { self.2.run(&mut self.1, &mut world, &mut resources); *accumulator -= *rate; } }, }; } } pub struct ScheduleRunner(pub PackedSchedule); impl Default for ScheduleRunner { fn default() -> Self { ScheduleRunner(PackedSchedule { 0: ScheduleType::Always , .. Default::default() }) .add_default_stages() } } impl ScheduleRunner { pub fn from_rate(rate: f64) -> Self { ScheduleRunner(PackedSchedule { 0: ScheduleType::Fixed(rate, 0.0) , .. Default::default() }) .add_default_stages() } pub fn from_rate_inv(rate: f64) -> Self { Self::from_rate(1.0 / rate) } pub fn add_default_stages(self) -> Self { self.add_stage(stage::FIRST) .add_stage(stage::PRE_UPDATE) .add_stage(stage::UPDATE) .add_stage(stage::POST_UPDATE) .add_stage(stage::LAST) } pub fn add_stage(mut self, stage_name: &'static str) -> Self { self.0.1.add_stage(stage_name); self } pub fn add_stage_after(mut self, target: &'static str, stage_name: &'static str) -> Self { self.0.1.add_stage_after(target, stage_name); self } pub fn add_stage_before( mut self, target: &'static str, stage_name: &'static str, ) -> Self { self.0.1.add_stage_before(target, stage_name); self } pub fn add_system(self, system: Box<dyn System>) -> Self { self.add_system_to_stage(stage::UPDATE, system) } pub fn add_systems(self, systems: Vec<Box<dyn System>>) -> Self { self.add_systems_to_stage(stage::UPDATE, systems) } pub fn add_system_to_stage( mut self, stage_name: &'static str, system: Box<dyn System>, ) -> Self { self.0.1.add_system_to_stage(stage_name, system); self } pub fn add_system_to_stage_front( mut self, stage_name: &'static str, system: Box<dyn System>, ) -> Self { self.0.1.add_system_to_stage_front(stage_name, system); self } pub fn add_systems_to_stage( mut self, stage_name: &'static str, systems: Vec<Box<dyn System>>, ) -> Self { for system in systems { self.0.1.add_system_to_stage(stage_name, system); } self } } pub fn schedule_runner_system(mut world: &mut World, mut resources: &mut Resources) { if resources.contains::<ScheduleRunner>() { let mut schedule = std::mem::take(&mut resources.get_mut::<ScheduleRunner>().unwrap().0); schedule.run(&mut world, &mut resources); resources.get_mut::<ScheduleRunner>().unwrap().0 = schedule; } let mut entity_map: HashMap<Entity, PackedSchedule> = world.query_mut::<(Entity, &mut ScheduleRunner)>() .iter() .map(|(entity, mut runner)| (entity, std::mem::take(&mut runner.0))) .collect(); for (_, schedule) in entity_map.iter_mut() { schedule.run(&mut world, &mut resources); } for (entity, mut runner) in &mut world.query_mut::<(Entity, &mut ScheduleRunner)>().iter() { runner.0 = entity_map.remove(&entity).unwrap(); } }
use bevy::{ app::stage, core::Time, ecs::{Schedule, ParallelExecutor, World, Resources, System, Entity}, utils::HashMap, }; #[derive(Debug)] pub enum ScheduleType { Always, Fixed(f64, f64), } pub struct PackedSchedule(pub ScheduleType, pub Schedule, ParallelExecutor); impl Default for PackedSchedule { fn default() -> Self { PackedSchedule( ScheduleType::Always, Default::default(), ParallelExecutor::without_tracker_clears(), ) } } impl PackedSchedule { fn run(&mut self, mut world: &mut World, mut resources: &mut Resources) { self.1.initialize(world, resources); match &mut self.0 { ScheduleType::Always => { self.2.run(&mut self.1, &mut world, &mut resources); }, ScheduleType::Fixed(rate, accumulator) => { match resources.get::<Time>() { Some(time) => { *accumulator += time.delta_seconds_f64; }, None => log::debug!("Time does not exist, Fixed Schedule cannot run!"), }; while accumulator >= rate { self.2.run(&mut self.1, &mut world, &mut resources); *accumulator -= *rate; } }, }; } } pub struct ScheduleRunner(pub PackedSchedule); impl Default for ScheduleRunner { fn default() -> Self { ScheduleRunner(PackedSchedule { 0: ScheduleType::Always , .. Default::default() }) .add_default_stages() } } impl ScheduleRunner { pub fn from_rate(rate: f64) -> Self { ScheduleRunner(PackedSchedule { 0: ScheduleType::Fixed(rate, 0.0) , .. Default::default() }) .add_default_stages() } pub fn from_rate_inv(rate: f64) -> Self { Self::from_rate(1.0 / rate) } pub fn add_default_stages(se
tage::POST_UPDATE) .add_stage(stage::LAST) } pub fn add_stage(mut self, stage_name: &'static str) -> Self { self.0.1.add_stage(stage_name); self } pub fn add_stage_after(mut self, target: &'static str, stage_name: &'static str) -> Self { self.0.1.add_stage_after(target, stage_name); self } pub fn add_stage_before( mut self, target: &'static str, stage_name: &'static str, ) -> Self { self.0.1.add_stage_before(target, stage_name); self } pub fn add_system(self, system: Box<dyn System>) -> Self { self.add_system_to_stage(stage::UPDATE, system) } pub fn add_systems(self, systems: Vec<Box<dyn System>>) -> Self { self.add_systems_to_stage(stage::UPDATE, systems) } pub fn add_system_to_stage( mut self, stage_name: &'static str, system: Box<dyn System>, ) -> Self { self.0.1.add_system_to_stage(stage_name, system); self } pub fn add_system_to_stage_front( mut self, stage_name: &'static str, system: Box<dyn System>, ) -> Self { self.0.1.add_system_to_stage_front(stage_name, system); self } pub fn add_systems_to_stage( mut self, stage_name: &'static str, systems: Vec<Box<dyn System>>, ) -> Self { for system in systems { self.0.1.add_system_to_stage(stage_name, system); } self } } pub fn schedule_runner_system(mut world: &mut World, mut resources: &mut Resources) { if resources.contains::<ScheduleRunner>() { let mut schedule = std::mem::take(&mut resources.get_mut::<ScheduleRunner>().unwrap().0); schedule.run(&mut world, &mut resources); resources.get_mut::<ScheduleRunner>().unwrap().0 = schedule; } let mut entity_map: HashMap<Entity, PackedSchedule> = world.query_mut::<(Entity, &mut ScheduleRunner)>() .iter() .map(|(entity, mut runner)| (entity, std::mem::take(&mut runner.0))) .collect(); for (_, schedule) in entity_map.iter_mut() { schedule.run(&mut world, &mut resources); } for (entity, mut runner) in &mut world.query_mut::<(Entity, &mut ScheduleRunner)>().iter() { runner.0 = entity_map.remove(&entity).unwrap(); } }
lf) -> Self { self.add_stage(stage::FIRST) .add_stage(stage::PRE_UPDATE) .add_stage(stage::UPDATE) .add_stage(s
function_block-random_span
[ { "content": "fn fixed_sys() {\n\n println!(\"game tick!\");\n\n}", "file_path": "examples/fixed_tick.rs", "rank": 1, "score": 37938.93565220559 }, { "content": "fn build(mut commands: Commands) {\n\n // TODO: Demonstrate how to later remove schedules conditionally\n\n // Spoiler: J...
Rust
crates/model/src/score/snapshots.rs
katandps/beatoraja_play_recommend
c7adf974cdab1b249c86c896aa1ba0a8fdd20819
use crate::score::score::ParamSnap; use crate::*; use chrono::Duration; use std::collections::BTreeSet; #[derive(Deserialize, Serialize, Debug, Clone, Default)] pub struct SnapShots(pub BTreeSet<SnapShot>); impl SnapShots { pub fn create_by_snaps(snapshots: Vec<SnapShot>) -> SnapShots { SnapShots(snapshots.iter().cloned().collect()) } pub fn add(&mut self, snapshot: SnapShot) { self.0.insert(snapshot); } pub fn snap(&self, date: &UpdatedAt) -> Option<&SnapShot> { self.0.iter().rev().find(|&s| s.updated_at.le(date)) } pub fn param_snap<T: ParamSnap>(&self, date: &UpdatedAt) -> Option<T> { match self.snap(date) { Some(last) => { let mut last_date = &last.updated_at; let mut one_day_before = None; for snap in self.0.iter().rev() { if T::cmp(snap, last) { last_date = &snap.updated_at; } else { one_day_before = self.snap(&(last_date - Duration::days(1))); break; } } Some(T::make(last, last_date.clone(), one_day_before)) } None => None, } } } #[cfg(test)] mod test { use super::*; use crate::score::score::ClearTypeSnap; #[test] pub fn test() { let shot1 = SnapShot::from_data(1, 2, 3, 4, 11); let shot2 = SnapShot::from_data(1, 2, 3, 4, 22); let shot3 = SnapShot::from_data(1, 2, 3, 4, 33); let shot4 = SnapShot::from_data(1, 2, 3, 4, 44); let shots = SnapShots::create_by_snaps(vec![ shot1.clone(), shot2.clone(), shot3.clone(), shot4.clone(), ]); assert_eq!(Some(&shot1), shots.snap(&UpdatedAt::from_timestamp(21))); assert_eq!(Some(&shot2), shots.snap(&UpdatedAt::from_timestamp(22))); assert_eq!(Some(&shot2), shots.snap(&UpdatedAt::from_timestamp(23))); assert_eq!(Some(&shot2), shots.snap(&UpdatedAt::from_timestamp(32))); assert_eq!(Some(&shot3), shots.snap(&UpdatedAt::from_timestamp(33))); } #[test] pub fn clear() { const DAY: i64 = 86400; fn asrt(snapshots: &SnapShots, current: ClearType, before: ClearType, timestamp: i64) { let snap = snapshots .param_snap::<ClearTypeSnap>(&UpdatedAt::from_timestamp(timestamp)) .unwrap_or_default(); assert_eq!(current.to_integer(), snap.current); assert_eq!(before.to_integer(), snap.before); } let shot_failed = SnapShot::from_data(1, 2, 3, 4, DAY * 10); let shot_failed2 = SnapShot::from_data(1, 2, 3, 4, DAY * 15); let shot_assist = SnapShot::from_data(2, 2, 3, 4, DAY * 17); let shot_la = SnapShot::from_data(3, 2, 3, 4, DAY * 17 + 1); let shot_la2 = SnapShot::from_data(3, 2, 3, 4, DAY * 20); let shot_easy = SnapShot::from_data(4, 2, 3, 4, DAY * 22); let shot_normal = SnapShot::from_data(5, 2, 3, 4, DAY * 25); let shot_hard = SnapShot::from_data(6, 2, 3, 4, DAY * 25 + DAY - 1); let shot_exhard = SnapShot::from_data(7, 2, 3, 4, DAY * 30); let shots = SnapShots::create_by_snaps(vec![ shot_failed.clone(), shot_failed2.clone(), shot_assist.clone(), shot_la.clone(), shot_la2.clone(), shot_easy.clone(), shot_normal.clone(), shot_hard.clone(), shot_exhard.clone(), ]); use ClearType::*; asrt(&shots, NoPlay, NoPlay, 0); asrt(&shots, NoPlay, NoPlay, DAY * 9); asrt(&shots, Failed, NoPlay, DAY * 10); asrt(&shots, Failed, NoPlay, DAY * 15); asrt(&shots, AssistEasy, Failed, DAY * 17); asrt(&shots, LightAssistEasy, Failed, DAY * 17 + 1); asrt(&shots, LightAssistEasy, Failed, DAY * 20); asrt(&shots, Easy, LightAssistEasy, DAY * 22); asrt(&shots, Normal, Easy, DAY * 25); asrt(&shots, Hard, Easy, DAY * 25 + DAY - 1); asrt(&shots, Hard, Easy, DAY * 26); asrt(&shots, ExHard, Hard, DAY * 30); } }
use crate::score::score::ParamSnap; use crate::*; use chrono::Duration; use std::collections::BTreeSet; #[derive(Deserialize, Serialize, Debug, Clone, Default)] pub struct SnapShots(pub BTreeSet<SnapShot>); impl SnapShots { pub fn create_by_snaps(snapshots: Vec<SnapShot>) -> SnapShots { SnapShots(snapshots.iter().cloned().collect()) } pub fn add(&mut self, snapshot: SnapShot) { self.0.insert(snapshot); } pub fn snap(&self, date: &UpdatedAt) -> Option<&SnapShot> { self.0.iter().rev().find(|&s| s.updated_at.le(date)) } pub fn param_snap<T: ParamSnap>(&self, date: &UpdatedAt) -> Option<T> { match self.snap(date) { Some(last) => { le
Some(T::make(last, last_date.clone(), one_day_before)) } None => None, } } } #[cfg(test)] mod test { use super::*; use crate::score::score::ClearTypeSnap; #[test] pub fn test() { let shot1 = SnapShot::from_data(1, 2, 3, 4, 11); let shot2 = SnapShot::from_data(1, 2, 3, 4, 22); let shot3 = SnapShot::from_data(1, 2, 3, 4, 33); let shot4 = SnapShot::from_data(1, 2, 3, 4, 44); let shots = SnapShots::create_by_snaps(vec![ shot1.clone(), shot2.clone(), shot3.clone(), shot4.clone(), ]); assert_eq!(Some(&shot1), shots.snap(&UpdatedAt::from_timestamp(21))); assert_eq!(Some(&shot2), shots.snap(&UpdatedAt::from_timestamp(22))); assert_eq!(Some(&shot2), shots.snap(&UpdatedAt::from_timestamp(23))); assert_eq!(Some(&shot2), shots.snap(&UpdatedAt::from_timestamp(32))); assert_eq!(Some(&shot3), shots.snap(&UpdatedAt::from_timestamp(33))); } #[test] pub fn clear() { const DAY: i64 = 86400; fn asrt(snapshots: &SnapShots, current: ClearType, before: ClearType, timestamp: i64) { let snap = snapshots .param_snap::<ClearTypeSnap>(&UpdatedAt::from_timestamp(timestamp)) .unwrap_or_default(); assert_eq!(current.to_integer(), snap.current); assert_eq!(before.to_integer(), snap.before); } let shot_failed = SnapShot::from_data(1, 2, 3, 4, DAY * 10); let shot_failed2 = SnapShot::from_data(1, 2, 3, 4, DAY * 15); let shot_assist = SnapShot::from_data(2, 2, 3, 4, DAY * 17); let shot_la = SnapShot::from_data(3, 2, 3, 4, DAY * 17 + 1); let shot_la2 = SnapShot::from_data(3, 2, 3, 4, DAY * 20); let shot_easy = SnapShot::from_data(4, 2, 3, 4, DAY * 22); let shot_normal = SnapShot::from_data(5, 2, 3, 4, DAY * 25); let shot_hard = SnapShot::from_data(6, 2, 3, 4, DAY * 25 + DAY - 1); let shot_exhard = SnapShot::from_data(7, 2, 3, 4, DAY * 30); let shots = SnapShots::create_by_snaps(vec![ shot_failed.clone(), shot_failed2.clone(), shot_assist.clone(), shot_la.clone(), shot_la2.clone(), shot_easy.clone(), shot_normal.clone(), shot_hard.clone(), shot_exhard.clone(), ]); use ClearType::*; asrt(&shots, NoPlay, NoPlay, 0); asrt(&shots, NoPlay, NoPlay, DAY * 9); asrt(&shots, Failed, NoPlay, DAY * 10); asrt(&shots, Failed, NoPlay, DAY * 15); asrt(&shots, AssistEasy, Failed, DAY * 17); asrt(&shots, LightAssistEasy, Failed, DAY * 17 + 1); asrt(&shots, LightAssistEasy, Failed, DAY * 20); asrt(&shots, Easy, LightAssistEasy, DAY * 22); asrt(&shots, Normal, Easy, DAY * 25); asrt(&shots, Hard, Easy, DAY * 25 + DAY - 1); asrt(&shots, Hard, Easy, DAY * 26); asrt(&shots, ExHard, Hard, DAY * 30); } }
t mut last_date = &last.updated_at; let mut one_day_before = None; for snap in self.0.iter().rev() { if T::cmp(snap, last) { last_date = &snap.updated_at; } else { one_day_before = self.snap(&(last_date - Duration::days(1))); break; } }
random
[ { "content": "pub fn changed_visibility_by_query() -> impl Filter<Extract = (bool,), Error = Rejection> + Clone {\n\n warp::body::json().and_then(get_changed_visibility_query)\n\n}\n\n\n\nasync fn get_changed_name_query(body: HashMap<String, String>) -> Result<String, Rejection> {\n\n let changed_name = b...
Rust
examples/dlint/config.rs
cdaringe/deno_lint
5ca58cd3f230ba95c75e261192414ee0bb9a758f
use anyhow::bail; use anyhow::Error as AnyError; use deno_lint::rules::{get_filtered_rules, LintRule}; use serde::Deserialize; use std::path::Path; use std::path::PathBuf; #[derive(Debug, Default, Deserialize)] #[serde(default)] pub struct RulesConfig { pub tags: Vec<String>, pub include: Vec<String>, pub exclude: Vec<String>, } #[derive(Debug, Default, Deserialize)] #[serde(default)] pub struct FilesConfig { pub include: Vec<String>, pub exclude: Vec<String>, } #[derive(Debug, Default, Deserialize)] #[serde(default)] pub struct Config { pub rules: RulesConfig, pub files: FilesConfig, } impl Config { pub fn get_rules(&self) -> Vec<Box<dyn LintRule>> { get_filtered_rules( Some(self.rules.tags.clone()), Some(self.rules.exclude.clone()), Some(self.rules.include.clone()), ) } pub fn get_files(&self) -> Result<Vec<PathBuf>, AnyError> { resolve_file_paths(&self.files) } } pub fn load_from_json(config_path: &Path) -> Result<Config, std::io::Error> { let json_str = std::fs::read_to_string(config_path)?; let config: Config = serde_json::from_str(&json_str)?; Ok(config) } fn resolve_file_paths(config: &FilesConfig) -> Result<Vec<PathBuf>, AnyError> { let mut file_patterns = get_file_patterns(config); let absolute_paths = take_absolute_paths(&mut file_patterns); let cwd = std::env::current_dir()?; let mut file_paths = glob(&cwd, &file_patterns)?; file_paths.extend(absolute_paths); return Ok(file_paths); fn get_file_patterns(config: &FilesConfig) -> Vec<String> { let mut file_patterns = Vec::new(); file_patterns.extend(config.include.clone()); file_patterns.extend(config.exclude.clone().into_iter().map(|exclude| { if exclude.starts_with('!') { exclude } else { format!("!{}", exclude) } })); for file_pattern in file_patterns.iter_mut() { if file_pattern.starts_with("./") { *file_pattern = String::from(&file_pattern[2..]); } if file_pattern.starts_with("!./") { *file_pattern = format!("!{}", &file_pattern[3..]); } } file_patterns } fn take_absolute_paths(file_patterns: &mut Vec<String>) -> Vec<PathBuf> { let len = file_patterns.len(); let mut file_paths = Vec::new(); for i in (0..len).rev() { if is_absolute_path(&file_patterns[i]) { file_paths.push(PathBuf::from(file_patterns.swap_remove(i))); } } file_paths } fn is_absolute_path(file_pattern: &str) -> bool { return !has_glob_chars(file_pattern) && PathBuf::from(file_pattern).is_absolute(); fn has_glob_chars(text: &str) -> bool { for c in text.chars() { match c { '*' | '{' | '}' | '[' | ']' | '!' => return true, _ => {} } } false } } } fn glob( base: &Path, file_patterns: &[String], ) -> Result<Vec<PathBuf>, AnyError> { let base = base.canonicalize()?; let walker = globwalk::GlobWalkerBuilder::from_patterns(base, file_patterns) .follow_links(false) .file_type(globwalk::FileType::FILE) .build(); let walker = match walker { Ok(walker) => walker, Err(err) => bail!("Error parsing file patterns: {}", err), }; let mut file_paths = Vec::new(); for result in walker.into_iter() { match result { Ok(result) => file_paths.push(result.into_path()), Err(err) => bail!("Error walking files: {}", err), } } Ok(file_paths) } #[cfg(test)] mod tests { use super::*; use deno_lint::rules::get_recommended_rules; use std::collections::HashSet; macro_rules! svec { ($( $elem:literal ),* $(,)?) => {{ vec![$( $elem.to_string() ),*] }} } macro_rules! set { ($( $elem:literal ),* $(,)?) => {{ vec![$( $elem ),*].into_iter().collect::<HashSet<&'static str>>() }} } fn into_codes(rules: Vec<Box<dyn LintRule>>) -> HashSet<&'static str> { rules.iter().map(|rule| rule.code()).collect() } #[test] fn test_get_rules() { let config = Config { rules: RulesConfig { tags: svec![], include: svec![], exclude: svec![], }, ..Default::default() }; assert!(config.get_rules().is_empty()); let config = Config { rules: RulesConfig { tags: svec!["recommended"], include: svec![], exclude: svec![], }, ..Default::default() }; let recommended_rules_codes = into_codes(get_recommended_rules()); assert_eq!(into_codes(config.get_rules()), recommended_rules_codes); let config = Config { rules: RulesConfig { tags: svec!["recommended"], include: svec!["no-empty"], exclude: svec![], }, ..Default::default() }; let recommended_rules_codes = into_codes(get_recommended_rules()); assert_eq!(into_codes(config.get_rules()), recommended_rules_codes); let config = Config { rules: RulesConfig { tags: svec![], include: svec!["eqeqeq"], exclude: svec!["eqeqeq"], }, ..Default::default() }; assert_eq!(into_codes(config.get_rules()), set!["eqeqeq"]); let config = Config { rules: RulesConfig { tags: svec![], include: svec!["this-is-a-totally-unknown-rule"], exclude: svec!["this-is-also-another-unknown-rule"], }, ..Default::default() }; assert_eq!(into_codes(config.get_rules()), set![]); } }
use anyhow::bail; use anyhow::Error as AnyError; use deno_lint::rules::{get_filtered_rules, LintRule}; use serde::Deserialize; use std::path::Path; use std::path::PathBuf; #[derive(Debug, Default, Deserialize)] #[serde(default)] pub struct RulesConfig { pub tags: Vec<String>, pub include: Vec<String>, pub exclude: Vec<String>, } #[derive(Debug, Default, Deserialize)] #[serde(default)] pub struct FilesConfig { pub include: Vec<String>, pub exclude: Vec<String>, } #[derive(Debug, Default, Deserialize)] #[serde(default)] pub struct Config { pub rules: RulesConfig, pub files: FilesConfig, } impl Config { pub fn get_rules(&self) -> Vec<Box<dyn LintRule>> { get_filtered_rules( Some(self.rules.tags.clone()), Some(self.rules.exclude.clone()), Some(self.rules.include.clone()), ) } pub fn get_files(&self) -> Result<Vec<PathBuf>, AnyError> { resolve_file_paths(&self.files) } } pub fn load_from_json(config_path: &Path) -> Result<Config, std::io::Error> { let json_str = std::fs::read_to_string(config_path)?; let config: Config = serde_json::from_str(&json_str)?; Ok(config) } fn resolve_file_paths(config: &FilesConfig) -> Result<Vec<PathBuf>, AnyError> { let mut file_patterns = get_file_patterns(config); let absolute_paths = take_absolute_paths(&mut file_patterns); let cwd = std::env::current_dir()?; let mut file_paths = glob(&cwd, &file_patterns)?; file_paths.extend(absolute_paths); return Ok(file_paths); fn get_file_patterns(config: &FilesConfig) -> Vec<String> { let mut file_patterns = Vec::new(); file_patterns.extend(config.include.clone()); file_patterns.extend(config.exclude.clone().into_iter().map(|exclude| { if exclude.starts_with('!') { exclude } else { format!("!{}", exclude) } })); for file_pattern in file_patterns.iter_mut() { if file_pattern.starts_with("./") { *file_pattern = String::from(&file_pattern[2..]); } if file_pattern.starts_with("!./") { *file_pattern = format!("!{}", &file_pattern[3..]); } } file_patterns } fn take_absolute_paths(file_patterns: &mut Vec<String>) -> Vec<PathBuf> { let len = file_patterns.len(); let mut file_paths = Vec::new(); for i in (0..len).rev() { if is_absolute_path(&file_patterns[i]) { file_paths.push(PathBuf::from(file_patterns.swap_remove(i))); } } file_paths } fn is_absolute_path(file_pattern: &str) -> bool { return !has_glob_chars(file_pattern) && PathBuf::from(file_pattern).is_absolute(); fn has_glob_chars(text: &str) -> bool { for c in text.chars() { match c { '*' | '{' | '}' | '[' | ']' | '!' => return true, _ => {} } } false } } } fn glob( base: &Path, file_patterns: &[String], ) -> Result<Vec<PathBuf>, AnyError> { let base = base.canonicalize()?; let walker = globwalk::GlobWalkerBuilder::from_patterns(base, file_patterns) .follow_links(false) .file_type(globwalk::FileType::FILE) .build();
let mut file_paths = Vec::new(); for result in walker.into_iter() { match result { Ok(result) => file_paths.push(result.into_path()), Err(err) => bail!("Error walking files: {}", err), } } Ok(file_paths) } #[cfg(test)] mod tests { use super::*; use deno_lint::rules::get_recommended_rules; use std::collections::HashSet; macro_rules! svec { ($( $elem:literal ),* $(,)?) => {{ vec![$( $elem.to_string() ),*] }} } macro_rules! set { ($( $elem:literal ),* $(,)?) => {{ vec![$( $elem ),*].into_iter().collect::<HashSet<&'static str>>() }} } fn into_codes(rules: Vec<Box<dyn LintRule>>) -> HashSet<&'static str> { rules.iter().map(|rule| rule.code()).collect() } #[test] fn test_get_rules() { let config = Config { rules: RulesConfig { tags: svec![], include: svec![], exclude: svec![], }, ..Default::default() }; assert!(config.get_rules().is_empty()); let config = Config { rules: RulesConfig { tags: svec!["recommended"], include: svec![], exclude: svec![], }, ..Default::default() }; let recommended_rules_codes = into_codes(get_recommended_rules()); assert_eq!(into_codes(config.get_rules()), recommended_rules_codes); let config = Config { rules: RulesConfig { tags: svec!["recommended"], include: svec!["no-empty"], exclude: svec![], }, ..Default::default() }; let recommended_rules_codes = into_codes(get_recommended_rules()); assert_eq!(into_codes(config.get_rules()), recommended_rules_codes); let config = Config { rules: RulesConfig { tags: svec![], include: svec!["eqeqeq"], exclude: svec!["eqeqeq"], }, ..Default::default() }; assert_eq!(into_codes(config.get_rules()), set!["eqeqeq"]); let config = Config { rules: RulesConfig { tags: svec![], include: svec!["this-is-a-totally-unknown-rule"], exclude: svec!["this-is-also-another-unknown-rule"], }, ..Default::default() }; assert_eq!(into_codes(config.get_rules()), set![]); } }
let walker = match walker { Ok(walker) => walker, Err(err) => bail!("Error parsing file patterns: {}", err), };
assignment_statement
[ { "content": "fn is_valid_typeof_string(str: &str) -> bool {\n\n matches!(\n\n str,\n\n \"undefined\"\n\n | \"object\"\n\n | \"boolean\"\n\n | \"number\"\n\n | \"string\"\n\n | \"function\"\n\n | \"symbol\"\n\n | \"bigint\"\n\n )\n\n}\n\n\n", "file_path": "src/rule...
Rust
src/config/freqency.rs
ywatanabee/libipt-rs
0efe4ff71d8e3236f4d3f691a16e714eb0c745bb
#[cfg(test)] mod test { use super::*; #[test] fn test_freq_props() { let mut freq = Frequency::new(1, 2, 3, 4); assert_eq!(freq.mtc(), 1); assert_eq!(freq.nom(), 2); assert_eq!(freq.ctc(), 3); assert_eq!(freq.tsc(), 4); freq.set_mtc(5); freq.set_nom(6); freq.set_ctc(7); freq.set_tsc(8); assert_eq!(freq.mtc(), 5); assert_eq!(freq.nom(), 6); assert_eq!(freq.ctc(), 7); assert_eq!(freq.tsc(), 8); } } #[derive(Clone, Copy, Default)] pub struct Frequency { pub(super) mtc: u8, pub(super) nom: u8, pub(super) ctc: u32, pub(super) tsc: u32 } impl Frequency { #[inline] pub fn new(mtc: u8, nom: u8, ctc: u32, tsc: u32) -> Self { Frequency {mtc, nom, ctc, tsc} } #[inline] pub fn mtc(self) -> u8 { self.mtc } #[inline] pub fn nom(self) -> u8 { self.nom } #[inline] pub fn ctc(self) -> u32 { self.ctc } #[inline] pub fn tsc(self) -> u32 { self.tsc } #[inline] pub fn set_mtc(&mut self, mtc: u8) { self.mtc = mtc } #[inline] pub fn set_nom(&mut self, nom: u8) { self.nom = nom } #[inline] pub fn set_ctc(&mut self, ctc: u32) { self.ctc = ctc } #[inline] pub fn set_tsc(&mut self, tsc: u32) { self.tsc = tsc } }
#[cfg(test)] mod test { use super::*; #[test] fn test_freq_props() {
} #[derive(Clone, Copy, Default)] pub struct Frequency { pub(super) mtc: u8, pub(super) nom: u8, pub(super) ctc: u32, pub(super) tsc: u32 } impl Frequency { #[inline] pub fn new(mtc: u8, nom: u8, ctc: u32, tsc: u32) -> Self { Frequency {mtc, nom, ctc, tsc} } #[inline] pub fn mtc(self) -> u8 { self.mtc } #[inline] pub fn nom(self) -> u8 { self.nom } #[inline] pub fn ctc(self) -> u32 { self.ctc } #[inline] pub fn tsc(self) -> u32 { self.tsc } #[inline] pub fn set_mtc(&mut self, mtc: u8) { self.mtc = mtc } #[inline] pub fn set_nom(&mut self, nom: u8) { self.nom = nom } #[inline] pub fn set_ctc(&mut self, ctc: u32) { self.ctc = ctc } #[inline] pub fn set_tsc(&mut self, tsc: u32) { self.tsc = tsc } }
let mut freq = Frequency::new(1, 2, 3, 4); assert_eq!(freq.mtc(), 1); assert_eq!(freq.nom(), 2); assert_eq!(freq.ctc(), 3); assert_eq!(freq.tsc(), 4); freq.set_mtc(5); freq.set_nom(6); freq.set_ctc(7); freq.set_tsc(8); assert_eq!(freq.mtc(), 5); assert_eq!(freq.nom(), 6); assert_eq!(freq.ctc(), 7); assert_eq!(freq.tsc(), 8); }
function_block-function_prefix_line
[ { "content": "#[test]\n\nfn test_encoder_all_packets() {\n\n let mut inp = [0; 132];\n\n let mut cfg = ConfigBuilder::new(&mut inp)\n\n .unwrap()\n\n .cpu(Cpu::intel(1, 2, 3))\n\n .finish();\n\n\n\n let mut enc = Encoder::new(&mut cfg).unwrap();\n\n\n\n let mut size: u32 = 0;\n\...
Rust
client/src/util.rs
fabaff/innernet
fd06b8054d007fcf86144c37c6eaf37f30719450
use crate::{ClientError, Error}; use colored::*; use indoc::eprintdoc; use log::{Level, LevelFilter}; use serde::{de::DeserializeOwned, Serialize}; use shared::{interface_config::ServerInfo, INNERNET_PUBKEY_HEADER}; use std::{io, time::Duration}; use ureq::{Agent, AgentBuilder}; static LOGGER: Logger = Logger; struct Logger; const BASE_MODULES: &[&str] = &["innernet", "shared"]; fn target_is_base(target: &str) -> bool { BASE_MODULES .iter() .any(|module| module == &target || target.starts_with(&format!("{}::", module))) } impl log::Log for Logger { fn enabled(&self, metadata: &log::Metadata) -> bool { metadata.level() <= log::max_level() && (log::max_level() == LevelFilter::Trace || target_is_base(metadata.target())) } fn log(&self, record: &log::Record) { if self.enabled(record.metadata()) { let level_str = match record.level() { Level::Error => "[E]".red(), Level::Warn => "[!]".yellow(), Level::Info => "[*]".dimmed(), Level::Debug => "[D]".blue(), Level::Trace => "[T]".purple(), }; if record.level() <= LevelFilter::Debug && !target_is_base(record.target()) { println!( "{} {} {}", level_str, format!("[{}]", record.target()).dimmed(), record.args() ); } else { println!("{} {}", level_str, record.args()); } } } fn flush(&self) {} } pub fn init_logger(verbosity: u64) { let level = match verbosity { 0 => log::LevelFilter::Info, 1 => log::LevelFilter::Debug, _ => log::LevelFilter::Trace, }; log::set_max_level(level); log::set_logger(&LOGGER).unwrap(); } pub fn human_duration(duration: Duration) -> String { match duration.as_secs() { n if n < 1 => "just now".cyan().to_string(), n if n < 60 => format!("{} {} ago", n, "seconds".cyan()), n if n < 60 * 60 => { let mins = n / 60; let secs = n % 60; format!( "{} {}, {} {} ago", mins, if mins == 1 { "minute" } else { "minutes" }.cyan(), secs, if secs == 1 { "second" } else { "seconds" }.cyan(), ) }, n => { let hours = n / (60 * 60); let mins = (n / 60) % 60; format!( "{} {}, {} {} ago", hours, if hours == 1 { "hour" } else { "hours" }.cyan(), mins, if mins == 1 { "minute" } else { "minutes" }.cyan(), ) }, } } pub fn human_size(bytes: u64) -> String { const KB: u64 = 1024; const MB: u64 = 1024 * KB; const GB: u64 = 1024 * MB; const TB: u64 = 1024 * GB; match bytes { n if n < 2 * KB => format!("{} {}", n, "B".cyan()), n if n < 2 * MB => format!("{:.2} {}", n as f64 / KB as f64, "KiB".cyan()), n if n < 2 * GB => format!("{:.2} {}", n as f64 / MB as f64, "MiB".cyan()), n if n < 2 * TB => format!("{:.2} {}", n as f64 / GB as f64, "GiB".cyan()), n => format!("{:.2} {}", n as f64 / TB as f64, "TiB".cyan()), } } pub fn permissions_helptext(e: &io::Error) { if e.raw_os_error() == Some(1) { let current_exe = std::env::current_exe() .ok() .map(|s| s.to_string_lossy().to_string()) .unwrap_or_else(|| "<innernet path>".into()); eprintdoc!( "{}: innernet can't access the device info. You either need to run innernet as root, or give innernet CAP_NET_ADMIN capabilities: sudo setcap cap_net_admin+eip {} ", "ERROR".bold().red(), current_exe ); } else if e.kind() == io::ErrorKind::PermissionDenied { eprintdoc!( "{}: innernet can't access its config/data folders. You either need to run innernet as root, or give the user/group running innernet permissions to access {config} and {data}. For non-root permissions, it's recommended to create an \"innernet\" group, and run for example: sudo chgrp -R innernet {config} {data} sudo chmod -R g+rwX {config} {data} ", "ERROR".bold().red(), config = shared::CLIENT_CONFIG_DIR.to_string_lossy(), data = shared::CLIENT_DATA_DIR.to_string_lossy(), ); } } pub struct Api<'a> { agent: Agent, server: &'a ServerInfo, } impl<'a> Api<'a> { pub fn new(server: &'a ServerInfo) -> Self { let agent = AgentBuilder::new() .timeout(Duration::from_secs(5)) .redirects(0) .build(); Self { agent, server } } pub fn http<T: DeserializeOwned>(&self, verb: &str, endpoint: &str) -> Result<T, Error> { self.request::<(), _>(verb, endpoint, None) } pub fn http_form<S: Serialize, T: DeserializeOwned>( &self, verb: &str, endpoint: &str, form: S, ) -> Result<T, Error> { self.request(verb, endpoint, Some(form)) } fn request<S: Serialize, T: DeserializeOwned>( &self, verb: &str, endpoint: &str, form: Option<S>, ) -> Result<T, Error> { let request = self .agent .request( verb, &format!("http://{}/v1{}", self.server.internal_endpoint, endpoint), ) .set(INNERNET_PUBKEY_HEADER, &self.server.public_key); let response = if let Some(form) = form { request.send_json(serde_json::to_value(form)?)? } else { request.call()? }; let mut response = response.into_string()?; if response.is_empty() { response = "null".into(); } Ok(serde_json::from_str(&response).map_err(|e| { ClientError(format!( "failed to deserialize JSON response from the server: {}, response={}", e, &response )) })?) } }
use crate::{ClientError, Error}; use colored::*; use indoc::eprintdoc; use log::{Level, LevelFilter}; use serde::{de::DeserializeOwned, Serialize}; use shared::{interface_config::ServerInfo, INNERNET_PUBKEY_HEADER}; use std::{io, time::Duration}; use ureq::{Agent, AgentBuilder}; static LOGGER: Logger = Logger; struct Logger; const BASE_MODULES: &[&str] = &["innernet", "shared"]; fn target_is_base(target: &str) -> bool { BASE_MODULES .iter() .any(|module| module == &target || target.starts_with(&format!("{}::", module))) } impl log::Log for Logger { fn enabled(&self, metadata: &log::Metadata) -> bool { metadata.level() <= log::max_level() && (log::max_level() == LevelFilter::Trace || target_is_base(metadata.target())) } fn log(&self, record: &log::Record) { if self.enabled(record.metadata()) { let level_str = match record.level() { Level::Error => "[E]".red(), Level::Warn => "[!]".yellow(), Level::Info => "[*]".dimmed(), Level::Debug => "[D]".blue(), Level::Trace => "[T]".purple(), }; if record.level() <= LevelFilter::Debug && !target_is_base(record.target()) { println!( "{} {} {}", level_str, format!("[{}]", record.target()).dimmed(), record.args() ); } else { println!("{} {}", level_str, record.args()); } } } fn flush(&self) {} } pub fn init_logger(verbosity: u64) { let level = match verbosity { 0 => log::LevelFilter::Info, 1 => log::LevelFilter::Debug, _ => log::LevelFilter::Trace, }; log::set_max_level(level); log::set_logger(&LOGGER).unwrap(); } pub fn human_duration(duration: Duration) -> String { match duration.as_secs() { n if n < 1 => "just now".cyan().to_string(), n if n < 60 => format!("{} {} ago", n, "seconds".cyan()), n if n < 60 * 60 => { let mins = n / 60; let secs = n % 60; format!( "{} {}, {} {} ago", mins, if mins == 1 { "minute" } else { "minutes" }.cyan(), secs, if secs == 1 { "second" } else { "seconds" }.cyan(), ) }, n => { let hours = n / (60 * 60); let mins = (n / 60) % 60;
pub fn human_size(bytes: u64) -> String { const KB: u64 = 1024; const MB: u64 = 1024 * KB; const GB: u64 = 1024 * MB; const TB: u64 = 1024 * GB; match bytes { n if n < 2 * KB => format!("{} {}", n, "B".cyan()), n if n < 2 * MB => format!("{:.2} {}", n as f64 / KB as f64, "KiB".cyan()), n if n < 2 * GB => format!("{:.2} {}", n as f64 / MB as f64, "MiB".cyan()), n if n < 2 * TB => format!("{:.2} {}", n as f64 / GB as f64, "GiB".cyan()), n => format!("{:.2} {}", n as f64 / TB as f64, "TiB".cyan()), } } pub fn permissions_helptext(e: &io::Error) { if e.raw_os_error() == Some(1) { let current_exe = std::env::current_exe() .ok() .map(|s| s.to_string_lossy().to_string()) .unwrap_or_else(|| "<innernet path>".into()); eprintdoc!( "{}: innernet can't access the device info. You either need to run innernet as root, or give innernet CAP_NET_ADMIN capabilities: sudo setcap cap_net_admin+eip {} ", "ERROR".bold().red(), current_exe ); } else if e.kind() == io::ErrorKind::PermissionDenied { eprintdoc!( "{}: innernet can't access its config/data folders. You either need to run innernet as root, or give the user/group running innernet permissions to access {config} and {data}. For non-root permissions, it's recommended to create an \"innernet\" group, and run for example: sudo chgrp -R innernet {config} {data} sudo chmod -R g+rwX {config} {data} ", "ERROR".bold().red(), config = shared::CLIENT_CONFIG_DIR.to_string_lossy(), data = shared::CLIENT_DATA_DIR.to_string_lossy(), ); } } pub struct Api<'a> { agent: Agent, server: &'a ServerInfo, } impl<'a> Api<'a> { pub fn new(server: &'a ServerInfo) -> Self { let agent = AgentBuilder::new() .timeout(Duration::from_secs(5)) .redirects(0) .build(); Self { agent, server } } pub fn http<T: DeserializeOwned>(&self, verb: &str, endpoint: &str) -> Result<T, Error> { self.request::<(), _>(verb, endpoint, None) } pub fn http_form<S: Serialize, T: DeserializeOwned>( &self, verb: &str, endpoint: &str, form: S, ) -> Result<T, Error> { self.request(verb, endpoint, Some(form)) } fn request<S: Serialize, T: DeserializeOwned>( &self, verb: &str, endpoint: &str, form: Option<S>, ) -> Result<T, Error> { let request = self .agent .request( verb, &format!("http://{}/v1{}", self.server.internal_endpoint, endpoint), ) .set(INNERNET_PUBKEY_HEADER, &self.server.public_key); let response = if let Some(form) = form { request.send_json(serde_json::to_value(form)?)? } else { request.call()? }; let mut response = response.into_string()?; if response.is_empty() { response = "null".into(); } Ok(serde_json::from_str(&response).map_err(|e| { ClientError(format!( "failed to deserialize JSON response from the server: {}, response={}", e, &response )) })?) } }
format!( "{} {}, {} {} ago", hours, if hours == 1 { "hour" } else { "hours" }.cyan(), mins, if mins == 1 { "minute" } else { "minutes" }.cyan(), ) }, } }
function_block-function_prefix_line
[ { "content": "pub fn confirm(prompt: &str) -> Result<bool, io::Error> {\n\n ensure_interactive(prompt)?;\n\n Confirm::with_theme(&*THEME)\n\n .wait_for_newline(true)\n\n .with_prompt(prompt)\n\n .default(false)\n\n .interact()\n\n}\n\n\n", "file_path": "shared/src/prompts.r...
Rust
qor-os/src/trap/context.rs
CarterTS/Qor
046616dc06179c158788c9003371441bc8a919d9
use core::usize; use super::TrapFrame; #[derive(Debug, Clone, Copy)] pub enum InterruptType { UserSoftwareInterrupt, SupervisorSoftwareInterrupt, MachineSoftwareInterrupt, UserTimeInterrupt, SupervisorTimerInterrupt, MachineTimerInterrupt, UserExternalInterrupt, SupervisorExternalInterrupt, MachineExternalInterrupt, InstructionAddressMisaligned, InstructionAccessFault, IllegalInstruction, Breakpoint, LoadAddressMisaligned, LoadAccessFault, StoreAddressMisaligned, StoreAccessFault, UserEnvironmentCall, SupervisorEnvironmentCall, MachineEnvironmentCall, InstructionPageFault, LoadPageFault, StorePageFault, UnknownSync(usize), UnknownAsync(usize) } pub struct InterruptContext { epc: usize, tval: usize, cause: InterruptType, hart: usize, status: usize, frame: *mut TrapFrame, async_trap: bool } impl InterruptContext { pub fn new(epc: usize, tval: usize, cause: usize, hart: usize, status: usize, frame: &'static mut TrapFrame) -> Self { let async_trap = cause >> 63 & 1 == 1 ; let interrupt_type = match (async_trap, cause & 0xfff) { (true, 0) => InterruptType::UserSoftwareInterrupt, (true, 1) => InterruptType::SupervisorSoftwareInterrupt, (true, 3) => InterruptType::MachineSoftwareInterrupt, (true, 4) => InterruptType::UserTimeInterrupt, (true, 5) => InterruptType::SupervisorTimerInterrupt, (true, 7) => InterruptType::MachineTimerInterrupt, (true, 8) => InterruptType::UserExternalInterrupt, (true, 9) => InterruptType::SupervisorExternalInterrupt, (true, 11) => InterruptType::MachineExternalInterrupt, (false, 0) => InterruptType::InstructionAddressMisaligned, (false, 1) => InterruptType::InstructionAccessFault, (false, 2) => InterruptType::IllegalInstruction, (false, 3) => InterruptType::Breakpoint, (false, 4) => InterruptType::LoadAddressMisaligned, (false, 5) => InterruptType::LoadAccessFault, (false, 6) => InterruptType::StoreAddressMisaligned, (false, 7) => InterruptType::StoreAccessFault, (false, 8) => InterruptType::UserEnvironmentCall, (false, 9) => InterruptType::SupervisorEnvironmentCall, (false, 11) => InterruptType::MachineEnvironmentCall, (false, 12) => InterruptType::InstructionPageFault, (false, 13) => InterruptType::LoadPageFault, (false, 15) => InterruptType::StorePageFault, (false, default) => InterruptType::UnknownSync(default), (true, default) => InterruptType::UnknownAsync(default), }; Self { epc, tval, cause: interrupt_type, hart, status, frame, async_trap } } pub fn instruction_address(&self) -> usize { self.epc } pub fn get_associated_value(&self) -> usize { self.tval } pub fn get_cause(&self) -> InterruptType { self.cause } pub fn get_hart(&self) -> usize { self.hart } pub fn get_status(&self) -> usize { self.status } pub fn get_frame(&self) -> *mut TrapFrame { self.frame } pub fn get_frame_mut(&self) -> &mut TrapFrame { unsafe { self.frame.as_mut() }.unwrap() } pub fn is_async(&self) -> bool { self.async_trap } } impl core::fmt::Display for InterruptContext { fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { writeln!(f, "Interrupt:")?; writeln!(f, " Cause: {:?}", self.cause)?; writeln!(f, " Instruction: 0x{:x}", self.epc)?; writeln!(f, " MTVAL: 0x{:x}", self.tval)?; writeln!(f, " HART: 0x{:x}", self.hart)?; writeln!(f, " Status: 0x{:x}", self.status)?; writeln!(f, " Frame Ptr: 0x{:x}", self.frame as *const TrapFrame as usize)?; Ok(()) } }
use core::usize; use super::TrapFrame; #[derive(Debug, Clone, Copy)] pub enum InterruptType { UserSoftwareInterrupt, SupervisorSoftwareInterrupt, MachineSoftwareInterrupt, UserTimeInterrupt, SupervisorTimerInterrupt, MachineTimerInterrupt, UserExternalInterrupt, SupervisorExternalInterrupt, MachineExternalInterrupt, InstructionAddressMisaligned, InstructionAccessFault, IllegalInstruction, Breakpoint, LoadAddressMisaligned, LoadAccessFault, StoreAddressMisaligned, StoreAccessFault, UserEnvironmentCall, SupervisorEnvironmentCall, MachineEnvironmentCall, InstructionPageFault, LoadPageF
:InstructionAddressMisaligned, (false, 1) => InterruptType::InstructionAccessFault, (false, 2) => InterruptType::IllegalInstruction, (false, 3) => InterruptType::Breakpoint, (false, 4) => InterruptType::LoadAddressMisaligned, (false, 5) => InterruptType::LoadAccessFault, (false, 6) => InterruptType::StoreAddressMisaligned, (false, 7) => InterruptType::StoreAccessFault, (false, 8) => InterruptType::UserEnvironmentCall, (false, 9) => InterruptType::SupervisorEnvironmentCall, (false, 11) => InterruptType::MachineEnvironmentCall, (false, 12) => InterruptType::InstructionPageFault, (false, 13) => InterruptType::LoadPageFault, (false, 15) => InterruptType::StorePageFault, (false, default) => InterruptType::UnknownSync(default), (true, default) => InterruptType::UnknownAsync(default), }; Self { epc, tval, cause: interrupt_type, hart, status, frame, async_trap } } pub fn instruction_address(&self) -> usize { self.epc } pub fn get_associated_value(&self) -> usize { self.tval } pub fn get_cause(&self) -> InterruptType { self.cause } pub fn get_hart(&self) -> usize { self.hart } pub fn get_status(&self) -> usize { self.status } pub fn get_frame(&self) -> *mut TrapFrame { self.frame } pub fn get_frame_mut(&self) -> &mut TrapFrame { unsafe { self.frame.as_mut() }.unwrap() } pub fn is_async(&self) -> bool { self.async_trap } } impl core::fmt::Display for InterruptContext { fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { writeln!(f, "Interrupt:")?; writeln!(f, " Cause: {:?}", self.cause)?; writeln!(f, " Instruction: 0x{:x}", self.epc)?; writeln!(f, " MTVAL: 0x{:x}", self.tval)?; writeln!(f, " HART: 0x{:x}", self.hart)?; writeln!(f, " Status: 0x{:x}", self.status)?; writeln!(f, " Frame Ptr: 0x{:x}", self.frame as *const TrapFrame as usize)?; Ok(()) } }
ault, StorePageFault, UnknownSync(usize), UnknownAsync(usize) } pub struct InterruptContext { epc: usize, tval: usize, cause: InterruptType, hart: usize, status: usize, frame: *mut TrapFrame, async_trap: bool } impl InterruptContext { pub fn new(epc: usize, tval: usize, cause: usize, hart: usize, status: usize, frame: &'static mut TrapFrame) -> Self { let async_trap = cause >> 63 & 1 == 1 ; let interrupt_type = match (async_trap, cause & 0xfff) { (true, 0) => InterruptType::UserSoftwareInterrupt, (true, 1) => InterruptType::SupervisorSoftwareInterrupt, (true, 3) => InterruptType::MachineSoftwareInterrupt, (true, 4) => InterruptType::UserTimeInterrupt, (true, 5) => InterruptType::SupervisorTimerInterrupt, (true, 7) => InterruptType::MachineTimerInterrupt, (true, 8) => InterruptType::UserExternalInterrupt, (true, 9) => InterruptType::SupervisorExternalInterrupt, (true, 11) => InterruptType::MachineExternalInterrupt, (false, 0) => InterruptType:
random
[ { "content": "#[test]\n\npub fn test_path_iterator()\n\n{\n\n use libutils::paths::OwnedPath;\n\n\n\n let path0 = OwnedPath::new(\"/usr/bin/ls\");\n\n let path1 = OwnedPath::new(\"bin/ls\");\n\n let path2 = OwnedPath::new(\"/\");\n\n let path3 = OwnedPath::new(\"./../../home/\");\n\n\n\n asser...
Rust
elasticsearch/src/error.rs
yaanhyy/elasticsearch-rs
740c3ebd41b391f954e9cf008209b39d89a75231
/* * Licensed to Elasticsearch B.V. under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch B.V. licenses this file to you 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. */ /* Error type based on the error type from es-rs: * * Copyright 2015-2018 Ben Ashford * * 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::http::{transport::BuildError, StatusCode}; use std::{error, fmt, io}; #[derive(Debug)] pub struct Error { kind: Kind, } #[cfg(feature = "tokio-feature")] #[derive(Debug)] enum Kind { Build(BuildError), Lib(String), Http(reqwest::Error), Io(io::Error), Json(serde_json::error::Error), } impl From<io::Error> for Error { fn from(err: io::Error) -> Error { Error { kind: Kind::Io(err), } } } #[cfg(feature = "tokio-feature")] impl From<reqwest::Error> for Error { fn from(err: reqwest::Error) -> Error { Error { kind: Kind::Http(err), } } } impl From<serde_json::error::Error> for Error { fn from(err: serde_json::error::Error) -> Error { Error { kind: Kind::Json(err), } } } impl From<url::ParseError> for Error { fn from(err: url::ParseError) -> Error { Error { kind: Kind::Lib(err.to_string()), } } } impl From<BuildError> for Error { fn from(err: BuildError) -> Error { Error { kind: Kind::Build(err), } } } pub(crate) fn lib(err: impl Into<String>) -> Error { Error { kind: Kind::Lib(err.into()), } } impl Error { pub fn status_code(&self) -> Option<StatusCode> { match &self.kind { Kind::Http(err) => err.status(), _ => None, } } pub fn is_timeout(&self) -> bool { match &self.kind { Kind::Http(err) => err.is_timeout(), _ => false, } } pub fn is_json(&self) -> bool { match &self.kind { Kind::Json(_) => true, _ => false, } } } impl error::Error for Error { fn source(&self) -> Option<&(dyn error::Error + 'static)> { match &self.kind { Kind::Build(err) => Some(err), Kind::Lib(_) => None, Kind::Http(err) => Some(err), Kind::Io(err) => Some(err), Kind::Json(err) => Some(err), } } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match &self.kind { Kind::Build(err) => err.fmt(f), Kind::Lib(err) => err.fmt(f), Kind::Http(err) => err.fmt(f), Kind::Io(err) => err.fmt(f), Kind::Json(err) => err.fmt(f), } } }
/* * Licensed to Elasticsearch B.V. under one or more contributor * license agreements. See the NOTICE file distributed with * this work for addition
type based on the error type from es-rs: * * Copyright 2015-2018 Ben Ashford * * 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::http::{transport::BuildError, StatusCode}; use std::{error, fmt, io}; #[derive(Debug)] pub struct Error { kind: Kind, } #[cfg(feature = "tokio-feature")] #[derive(Debug)] enum Kind { Build(BuildError), Lib(String), Http(reqwest::Error), Io(io::Error), Json(serde_json::error::Error), } impl From<io::Error> for Error { fn from(err: io::Error) -> Error { Error { kind: Kind::Io(err), } } } #[cfg(feature = "tokio-feature")] impl From<reqwest::Error> for Error { fn from(err: reqwest::Error) -> Error { Error { kind: Kind::Http(err), } } } impl From<serde_json::error::Error> for Error { fn from(err: serde_json::error::Error) -> Error { Error { kind: Kind::Json(err), } } } impl From<url::ParseError> for Error { fn from(err: url::ParseError) -> Error { Error { kind: Kind::Lib(err.to_string()), } } } impl From<BuildError> for Error { fn from(err: BuildError) -> Error { Error { kind: Kind::Build(err), } } } pub(crate) fn lib(err: impl Into<String>) -> Error { Error { kind: Kind::Lib(err.into()), } } impl Error { pub fn status_code(&self) -> Option<StatusCode> { match &self.kind { Kind::Http(err) => err.status(), _ => None, } } pub fn is_timeout(&self) -> bool { match &self.kind { Kind::Http(err) => err.is_timeout(), _ => false, } } pub fn is_json(&self) -> bool { match &self.kind { Kind::Json(_) => true, _ => false, } } } impl error::Error for Error { fn source(&self) -> Option<&(dyn error::Error + 'static)> { match &self.kind { Kind::Build(err) => Some(err), Kind::Lib(_) => None, Kind::Http(err) => Some(err), Kind::Io(err) => Some(err), Kind::Json(err) => Some(err), } } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match &self.kind { Kind::Build(err) => err.fmt(f), Kind::Lib(err) => err.fmt(f), Kind::Http(err) => err.fmt(f), Kind::Io(err) => err.fmt(f), Kind::Json(err) => err.fmt(f), } } }
al information regarding copyright * ownership. Elasticsearch B.V. licenses this file to you 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. */ /* Error
random
[ { "content": "pub fn create_default() -> Elasticsearch {\n\n create_for_url(cluster_addr().as_str())\n\n}\n\n\n", "file_path": "elasticsearch/tests/common/client.rs", "rank": 0, "score": 61105.408873425535 }, { "content": "fn create_client() -> Result<Elasticsearch, Error> {\n\n fn clu...
Rust
internal/wasmldr/src/workload.rs
rohankumardubey/enarx
27300ba494f463bf077fb1f8d326057412fa58ae
use log::{debug, info}; use wasmtime_wasi::sync::WasiCtxBuilder; #[allow(clippy::enum_variant_names)] #[derive(Debug)] pub enum Error { ConfigurationError, ExportNotFound, InstantiationFailed, CallFailed, IoError(std::io::Error), WASIError(wasmtime_wasi::Error), StringTableError, } impl From<std::io::Error> for Error { fn from(err: std::io::Error) -> Self { Self::IoError(err) } } impl From<wasmtime_wasi::Error> for Error { fn from(err: wasmtime_wasi::Error) -> Self { Self::WASIError(err) } } impl From<Error> for i32 { fn from(err: Error) -> Self { use Error::*; match err { ConfigurationError => 65, StringTableError => 65, InstantiationFailed => 65, ExportNotFound => 65, CallFailed => 65, WASIError(_) => 70, IoError(_) => 74, } } } pub type Result<T> = std::result::Result<T, Error>; pub fn run<T: AsRef<str>, U: AsRef<str>>( bytes: impl AsRef<[u8]>, args: impl IntoIterator<Item = T>, envs: impl IntoIterator<Item = (U, U)>, ) -> Result<Box<[wasmtime::Val]>> { debug!("configuring wasmtime engine"); let mut config = wasmtime::Config::new(); config.wasm_module_linking(true); config.wasm_multi_memory(true); config.static_memory_maximum_size(0); config.static_memory_guard_size(0); config.dynamic_memory_guard_size(0); config.dynamic_memory_reserved_for_growth(0); let engine = wasmtime::Engine::new(&config).or(Err(Error::ConfigurationError))?; debug!("instantiating wasmtime linker"); let mut linker = wasmtime::Linker::new(&engine); debug!("adding WASI to linker"); wasmtime_wasi::add_to_linker(&mut linker, |s| s)?; debug!("creating WASI context"); let mut wasi = WasiCtxBuilder::new(); for arg in args { wasi = wasi.arg(arg.as_ref()).or(Err(Error::StringTableError))?; } for kv in envs { wasi = wasi .env(kv.0.as_ref(), kv.1.as_ref()) .or(Err(Error::StringTableError))?; } info!("inheriting stdio from calling process"); wasi = wasi.inherit_stdio(); debug!("creating wasmtime Store"); let mut store = wasmtime::Store::new(&engine, wasi.build()); debug!("instantiating module from bytes"); let module = wasmtime::Module::from_binary(&engine, bytes.as_ref())?; debug!("adding module to store"); linker .module(&mut store, "", &module) .or(Err(Error::InstantiationFailed))?; debug!("getting module's default function"); let func = linker .get_default(&mut store, "") .or(Err(Error::ExportNotFound))?; debug!("calling function"); func.call(store, Default::default()) .or(Err(Error::CallFailed)) } #[cfg(test)] pub(crate) mod test { use crate::workload; use std::iter::empty; const NO_EXPORT_WAT: &'static str = r#"(module (memory (export "") 1) )"#; const RETURN_1_WAT: &'static str = r#"(module (func (export "") (result i32) i32.const 1) )"#; const WASI_COUNT_ARGS_WAT: &'static str = r#"(module (import "wasi_snapshot_preview1" "args_sizes_get" (func $__wasi_args_sizes_get (param i32 i32) (result i32))) (func (export "_start") (result i32) (i32.store (i32.const 0) (i32.const 0)) (i32.store (i32.const 4) (i32.const 0)) (call $__wasi_args_sizes_get (i32.const 0) (i32.const 4)) drop (i32.load (i32.const 0)) ) (memory 1) (export "memory" (memory 0)) )"#; const HELLO_WASI_WAT: &'static str = r#"(module (import "wasi_snapshot_preview1" "proc_exit" (func $__wasi_proc_exit (param i32))) (import "wasi_snapshot_preview1" "fd_write" (func $__wasi_fd_write (param i32 i32 i32 i32) (result i32))) (func $_start (i32.store (i32.const 24) (i32.const 14)) (i32.store (i32.const 20) (i32.const 0)) (block (br_if 0 (call $__wasi_fd_write (i32.const 1) (i32.const 20) (i32.const 1) (i32.const 16))) (br_if 0 (i32.ne (i32.load (i32.const 16)) (i32.const 14))) (br 1) ) (call $__wasi_proc_exit (i32.const 1)) ) (memory 1) (export "memory" (memory 0)) (export "_start" (func $_start)) (data (i32.const 0) "Hello, world!\0a") )"#; #[test] fn workload_run_return_1() { let bytes = wat::parse_str(RETURN_1_WAT).expect("error parsing wat"); let results: Vec<i32> = workload::run(&bytes, empty::<String>(), empty::<(String, String)>()) .unwrap() .iter() .map(|v| v.unwrap_i32()) .collect(); assert_eq!(results, vec![1]); } #[test] fn workload_run_no_export() { let bytes = wat::parse_str(NO_EXPORT_WAT).expect("error parsing wat"); match workload::run(&bytes, empty::<String>(), empty::<(String, String)>()) { Err(workload::Error::ExportNotFound) => {} _ => panic!("unexpected error"), }; } #[test] fn workload_run_wasi_count_args() { let bytes = wat::parse_str(WASI_COUNT_ARGS_WAT).expect("error parsing wat"); let results: Vec<i32> = workload::run( &bytes, vec!["a".to_string(), "b".to_string(), "c".to_string()], vec![("k", "v")], ) .unwrap() .iter() .map(|v| v.unwrap_i32()) .collect(); assert_eq!(results, vec![3]); } #[test] fn workload_run_hello_wasi() { let bytes = wat::parse_str(HELLO_WASI_WAT).expect("error parsing wat"); let args: Vec<String> = vec![]; let envs: Vec<(String, String)> = vec![]; let results = workload::run(&bytes, args, envs).unwrap(); assert_eq!(results.len(), 0); } }
use log::{debug, info}; use wasmtime_wasi::sync::WasiCtxBuilder; #[allow(clippy::enum_variant_names)] #[derive(Debug)] pub enum Error { ConfigurationError, ExportNotFound, InstantiationFailed, CallFailed, IoError(std::io::Error), WASIError(wasmtime_wasi::Error), StringTableError, } impl From<std::io::Error> for Error { fn from(err: std::io::Error) -> Self { Self::IoError(err) } } impl From<wasmtime_wasi::Error> for Error { fn from(err: wasmtime_wasi::Error) -> Self { Self::WASIError(err) } } impl From<Error> for i32 { fn from(err: Error) -> Self { use Error::*; match err { ConfigurationError => 65, StringTableError => 65, InstantiationFailed => 65, ExportNotFound => 65, CallFailed => 65, WASIError(_) => 70, IoError(_) => 74, } } } pub type Result<T> = std::result::Result<T, Error>; pub fn run<T: AsRef<str>, U: AsRef<str>>( bytes: impl AsRef<[u8]>, args: impl IntoIterator<Item = T>, envs: impl IntoIterator<Item = (U, U)>, ) -> Result<Box<[wasmtime::Val]>> { debug!("configuring wasmtime engine"); let mut config = wasmtime::Config::new(); config.wasm_module_linking(true); config.wasm_multi_memory(true); config.static_memory_maximum_size(0); config.static_memory_guard_size(0); config.dynamic_memory_guard_size(0); config.dynamic_memory_reserved_for_growth(0); let engine = wasmtime::Engine::new(&config).or(Err(Error::ConfigurationError))?; debug!("instantiating wasmtime linker"); let mut linker = wasmtime::Linker::new(&engine); debug!("adding WASI to linker"); wasmtime_wasi::add_to_linker(&mut linker, |s| s)?; debug!("creating WASI context"); let mut wasi = WasiCtxBuilder::new(); for arg in args { wasi = wasi.arg(arg.as_ref()).or(Err(Error::StringTableError))?; } for kv in envs { wasi = wasi .env(kv.0.as_ref(), kv.1.as_ref()) .or(Err(Error::StringTableError))?; } info!("inheriting stdio from calling process"); wasi = wasi.inherit_stdio(); debug!("creating wasmtime Store"); let mut store = wasmtime::Store::new(&engine, wasi.build()); debug!("instantiating module from bytes"); let module = wasmtime::Module::from_binary(&engine, bytes.as_ref())?; debug!("adding module to store"); linker .module(&mut store, "", &module) .or(Err(Error::InstantiationFailed))?; debug!("getting module's default function"); let func = linker .get_default(&mut store, "") .or(Err(Error::ExportNotFound))?; debug!("calling function"); func.call(store, Default::default()) .or(Err(Error::CallFailed)) } #[cfg(test)] pub(crate) mod test { use crate::workload; use std::iter::empty; const NO_EXPORT_WAT: &'static str = r#"(module (memory (export "") 1) )"#; const RETURN_1_WAT: &'static str = r#"(module (func (export "") (result i32) i32.const 1) )"#; const WASI_COUNT_ARGS_WAT: &'static str = r#"(module (import "wasi_snapshot_preview1" "args_sizes_get" (func $__wasi_args_sizes_get (param i32 i32) (result i32))) (func (export "_start") (result i32) (i32.store (i32.const 0) (i32.const 0)) (i32.store (i32.const 4) (i32.const 0)) (call $__wasi_args_sizes_get (i32.const 0) (i32.const 4)) drop (i32.load (i32.const 0)) ) (memory 1) (export "memory" (memory 0)) )"#; const HELLO_WASI_WAT: &'static str = r#"(module (import "wasi_snapshot_preview1" "proc_exit" (func $__wasi_proc_exit (param i32))) (import "wasi_snapshot_preview1" "fd_write" (func $__wasi_fd_write (param i32 i32 i32 i32) (result i32))) (func $_start (i32.store (i32.const 24) (i32.const 14)) (i32.store (i32.const 20) (i32.const 0)) (block (br_if 0 (call $__wasi_fd_write (i32.const 1) (i32.const 20) (i32.const 1) (i32.const 16))) (br_if 0 (i32.ne (i32.load (i32.const 16)) (i32.const 14))) (br 1) ) (call $__wasi_proc_exit (i32.const 1)) ) (memory 1) (export "memory" (memory 0)) (export "_start" (func $_start)) (data (i32.const 0) "Hello, world!\0a") )"#; #[test]
#[test] fn workload_run_no_export() { let bytes = wat::parse_str(NO_EXPORT_WAT).expect("error parsing wat"); match workload::run(&bytes, empty::<String>(), empty::<(String, String)>()) { Err(workload::Error::ExportNotFound) => {} _ => panic!("unexpected error"), }; } #[test] fn workload_run_wasi_count_args() { let bytes = wat::parse_str(WASI_COUNT_ARGS_WAT).expect("error parsing wat"); let results: Vec<i32> = workload::run( &bytes, vec!["a".to_string(), "b".to_string(), "c".to_string()], vec![("k", "v")], ) .unwrap() .iter() .map(|v| v.unwrap_i32()) .collect(); assert_eq!(results, vec![3]); } #[test] fn workload_run_hello_wasi() { let bytes = wat::parse_str(HELLO_WASI_WAT).expect("error parsing wat"); let args: Vec<String> = vec![]; let envs: Vec<(String, String)> = vec![]; let results = workload::run(&bytes, args, envs).unwrap(); assert_eq!(results.len(), 0); } }
fn workload_run_return_1() { let bytes = wat::parse_str(RETURN_1_WAT).expect("error parsing wat"); let results: Vec<i32> = workload::run(&bytes, empty::<String>(), empty::<(String, String)>()) .unwrap() .iter() .map(|v| v.unwrap_i32()) .collect(); assert_eq!(results, vec![1]); }
function_block-full_function
[ { "content": "#[cfg(feature = \"gdb\")]\n\npub fn handle_gdb(block: &mut Block, gdb_fd: &mut Option<std::net::TcpStream>, sockaddr: &str) {\n\n use gdbstub::Connection;\n\n\n\n let req = unsafe { block.msg.req };\n\n match req.num.into() {\n\n sallyport::syscall::SYS_ENARX_GDB_START => {\n\n ...
Rust
infra/src/shader.rs
MrShiposha/apriori-engine
faaf897fb72c093a8bc86498bf6f7e913ebc8f02
use { std::{ fs, io::prelude::*, path::{Path, PathBuf} }, shaderc::{ Compiler, CompileOptions, IncludeType, IncludeCallbackResult, ResolvedInclude }, convert_case::{Case, Casing}, pathdiff::diff_paths, crate::{ Result, Error, GENERATED_FILE_DIR, ffi::FOREIGN_FN_IFACE_DIR_NAME }, }; pub fn process_shader_srcs(src_path: &PathBuf, dir: &Path) -> Result<()> { const SHADER_DIR_NAME: &'static str = "gpu"; for entry in fs::read_dir(dir)? { let entry = entry?; let path = entry.path(); if path.is_file() { continue; } if let Some(dir_name) = path.components().last() { if dir_name.as_os_str().to_string_lossy() == SHADER_DIR_NAME { process_shader_dir(src_path, dir, &path)?; break; } } } Ok(()) } fn process_shader_dir(src_path: &PathBuf, top_shader_dir: &Path, dir: &Path) -> Result<()> { for entry in fs::read_dir(dir)? { let entry = entry?; let path = entry.path(); if path.is_dir() { process_shader_dir(src_path, top_shader_dir, &path)?; } else { compile_shader(src_path, top_shader_dir, &path)?; } } Ok(()) } fn compile_shader(src_path: &PathBuf, top_shader_dir: &Path, file_path: &Path) -> Result<()> { let mut options = CompileOptions::new() .ok_or(Error::Internal("shader compile options allocation failure".to_string()))?; options.set_include_callback(include_callback(src_path)); let source_language; if let Some(ext) = file_path.extension() { if ext == "glsl" { source_language = shaderc::SourceLanguage::GLSL; } else if ext == "hlsl" { source_language = shaderc::SourceLanguage::HLSL; } else { return Err( Error::ShaderFile( format!( "the shader {} has unknown extension {}", file_path.display(), ext.to_string_lossy() ) ) ) } } else { return Err( Error::ShaderFile( format!( "the shader {} has no extension", file_path.display() ) ) ) } options.set_source_language(source_language); options.add_macro_definition("___gpu___", None); let source_text = fs::read_to_string(file_path)?; let shader_kind = shaderc::ShaderKind::InferFromSource; let input_file_name = file_path.to_string_lossy(); let entry_point_name = "main"; let mut compiler = Compiler::new() .ok_or(Error::Internal("shader compiler allocation failure".to_string()))?; let spirv = compiler.compile_into_spirv( &source_text, shader_kind, &input_file_name, entry_point_name, Some(&options) )?; let binary_spirv = spirv.as_binary(); let binary_spirv_code_size = binary_spirv.len() * std::mem::size_of_val(&binary_spirv[0]); let file_name = file_path .file_stem() .expect("shader file name") .to_str() .expect("shader file name str"); let parent_dir = file_path.parent() .ok_or(Error::ShaderFile("unable to get shader parent dir".into()))?; let shader_relative_path = diff_paths( parent_dir, top_shader_dir ).ok_or(Error::ShaderFile("unable to get shader relative path".into()))?; let shader_ffi_dir = src_path .join(FOREIGN_FN_IFACE_DIR_NAME) .join(GENERATED_FILE_DIR) .join(shader_relative_path); let shader_ffi_base = shader_ffi_dir.join(file_name); if !shader_ffi_dir.exists() { fs::create_dir_all(shader_ffi_dir)?; } let mut shader_ffi_header = shader_ffi_base.clone(); shader_ffi_header.set_extension("h"); println!("cargo:rerun-if-changed={}", shader_ffi_header.display()); let do_not_modify_comment = format! { r#"// This file generated automatically. // DO NOT MODIFY IT MANUALLY! // Original shader source path: file:///{shader_source_path}"#, shader_source_path = file_path.display() }; let header_guard = format!( "___FFI_SHADER_HEADER_{}_H___", file_name.to_case(Case::UpperSnake) ); let shader_snake_name = file_name.to_case(Case::Snake); let shader_fn_decl = format!("uint32_t *{}()", shader_snake_name); let shader_code_size_fn_decl = format!("size_t {}_code_size()", shader_snake_name); let spirv_binary_hex = binary_spirv.iter() .map(|word| format!("{:#010X}", word)) .collect::<Vec<_>>() .join(",\n\t\t"); let shader_ffi_header_content = format! { r#"{do_not_modify_comment} #ifndef {header_guard} #define {header_guard} #include <stdint.h> {shader_fn_decl}; {shader_code_size_fn_decl}; #endif // {header_guard}"#, do_not_modify_comment = do_not_modify_comment, header_guard = header_guard, shader_fn_decl = shader_fn_decl, shader_code_size_fn_decl = shader_code_size_fn_decl, }; let shader_ffi_src_content = format! { r#"{do_not_modify_comment} #include "{header_file_path}" {shader_fn_decl} {{ static uint32_t shader_src[] = {{ {spirv_binary} }}; return shader_src; }} {shader_code_size_fn_decl} {{ return {shader_code_size}ULL; }} "#, do_not_modify_comment = do_not_modify_comment, header_file_path = shader_ffi_header.display(), shader_fn_decl = shader_fn_decl, spirv_binary = spirv_binary_hex, shader_code_size_fn_decl = shader_code_size_fn_decl, shader_code_size = binary_spirv_code_size }; let mut out = fs::OpenOptions::new() .create(true) .write(true) .truncate(true) .open(shader_ffi_header.clone())?; out.write_all(shader_ffi_header_content.as_bytes())?; let mut shader_ffi_src = shader_ffi_base.clone(); shader_ffi_src.set_extension("c"); println!("cargo:rerun-if-changed={}", shader_ffi_src.display()); let mut out = fs::OpenOptions::new() .create(true) .write(true) .truncate(true) .open(shader_ffi_src)?; out.write_all(shader_ffi_src_content.as_bytes())?; Ok(()) } fn include_callback(src_path: &PathBuf) -> impl Fn(&str, IncludeType, &str, usize) -> IncludeCallbackResult { let src_path = src_path.clone(); move |requested_source, include_type, requesting_source, _include_depth| { let header_path; let requested_source_path = Path::new(requested_source); let standard_path = src_path.join(requested_source_path); match include_type { IncludeType::Relative => { let requesting_source_path = Path::new(requesting_source); let requesting_dir_path = requesting_source_path.parent() .ok_or(format!("{}: expected parent path", requested_source_path.display()))?; let relative_path = requesting_dir_path.join(requested_source_path); if relative_path.is_file() { header_path = relative_path; } else if standard_path.is_file() { header_path = standard_path.clone(); } else { return Err("relative header path is not found".to_string()); } }, IncludeType::Standard => if standard_path.is_file() { header_path = standard_path.clone(); } else { return Err("standard header path is not found".to_string()); } } let header_content = fs::read_to_string(header_path) .map_err(|err| err.to_string())?; let resolved_include = ResolvedInclude { resolved_name: standard_path.to_string_lossy().to_string(), content: header_content }; Ok(resolved_include) } }
use { std::{ fs, io::prelude::*, path::{Path, PathBuf} }, shaderc::{ Compiler, CompileOptions, IncludeType, IncludeCallbackResult, ResolvedInclude }, convert_case::{Case, Casing}, pathdiff::diff_paths, crate::{ Result, Error, GENERATED_FILE_DIR, ffi::FOREIGN_FN_IFACE_DIR_NAME }, }; pub fn process_shader_srcs(src_path: &PathBuf, dir: &Path) -> Result<()> { const SHADER_DIR_NAME: &'static str = "gpu"; for entry in fs::read_dir(dir)? { let entry = entry?; let path =
shaderc::SourceLanguage::GLSL; } else if ext == "hlsl" { source_language = shaderc::SourceLanguage::HLSL; } else { return Err( Error::ShaderFile( format!( "the shader {} has unknown extension {}", file_path.display(), ext.to_string_lossy() ) ) ) } } else { return Err( Error::ShaderFile( format!( "the shader {} has no extension", file_path.display() ) ) ) } options.set_source_language(source_language); options.add_macro_definition("___gpu___", None); let source_text = fs::read_to_string(file_path)?; let shader_kind = shaderc::ShaderKind::InferFromSource; let input_file_name = file_path.to_string_lossy(); let entry_point_name = "main"; let mut compiler = Compiler::new() .ok_or(Error::Internal("shader compiler allocation failure".to_string()))?; let spirv = compiler.compile_into_spirv( &source_text, shader_kind, &input_file_name, entry_point_name, Some(&options) )?; let binary_spirv = spirv.as_binary(); let binary_spirv_code_size = binary_spirv.len() * std::mem::size_of_val(&binary_spirv[0]); let file_name = file_path .file_stem() .expect("shader file name") .to_str() .expect("shader file name str"); let parent_dir = file_path.parent() .ok_or(Error::ShaderFile("unable to get shader parent dir".into()))?; let shader_relative_path = diff_paths( parent_dir, top_shader_dir ).ok_or(Error::ShaderFile("unable to get shader relative path".into()))?; let shader_ffi_dir = src_path .join(FOREIGN_FN_IFACE_DIR_NAME) .join(GENERATED_FILE_DIR) .join(shader_relative_path); let shader_ffi_base = shader_ffi_dir.join(file_name); if !shader_ffi_dir.exists() { fs::create_dir_all(shader_ffi_dir)?; } let mut shader_ffi_header = shader_ffi_base.clone(); shader_ffi_header.set_extension("h"); println!("cargo:rerun-if-changed={}", shader_ffi_header.display()); let do_not_modify_comment = format! { r#"// This file generated automatically. // DO NOT MODIFY IT MANUALLY! // Original shader source path: file:///{shader_source_path}"#, shader_source_path = file_path.display() }; let header_guard = format!( "___FFI_SHADER_HEADER_{}_H___", file_name.to_case(Case::UpperSnake) ); let shader_snake_name = file_name.to_case(Case::Snake); let shader_fn_decl = format!("uint32_t *{}()", shader_snake_name); let shader_code_size_fn_decl = format!("size_t {}_code_size()", shader_snake_name); let spirv_binary_hex = binary_spirv.iter() .map(|word| format!("{:#010X}", word)) .collect::<Vec<_>>() .join(",\n\t\t"); let shader_ffi_header_content = format! { r#"{do_not_modify_comment} #ifndef {header_guard} #define {header_guard} #include <stdint.h> {shader_fn_decl}; {shader_code_size_fn_decl}; #endif // {header_guard}"#, do_not_modify_comment = do_not_modify_comment, header_guard = header_guard, shader_fn_decl = shader_fn_decl, shader_code_size_fn_decl = shader_code_size_fn_decl, }; let shader_ffi_src_content = format! { r#"{do_not_modify_comment} #include "{header_file_path}" {shader_fn_decl} {{ static uint32_t shader_src[] = {{ {spirv_binary} }}; return shader_src; }} {shader_code_size_fn_decl} {{ return {shader_code_size}ULL; }} "#, do_not_modify_comment = do_not_modify_comment, header_file_path = shader_ffi_header.display(), shader_fn_decl = shader_fn_decl, spirv_binary = spirv_binary_hex, shader_code_size_fn_decl = shader_code_size_fn_decl, shader_code_size = binary_spirv_code_size }; let mut out = fs::OpenOptions::new() .create(true) .write(true) .truncate(true) .open(shader_ffi_header.clone())?; out.write_all(shader_ffi_header_content.as_bytes())?; let mut shader_ffi_src = shader_ffi_base.clone(); shader_ffi_src.set_extension("c"); println!("cargo:rerun-if-changed={}", shader_ffi_src.display()); let mut out = fs::OpenOptions::new() .create(true) .write(true) .truncate(true) .open(shader_ffi_src)?; out.write_all(shader_ffi_src_content.as_bytes())?; Ok(()) } fn include_callback(src_path: &PathBuf) -> impl Fn(&str, IncludeType, &str, usize) -> IncludeCallbackResult { let src_path = src_path.clone(); move |requested_source, include_type, requesting_source, _include_depth| { let header_path; let requested_source_path = Path::new(requested_source); let standard_path = src_path.join(requested_source_path); match include_type { IncludeType::Relative => { let requesting_source_path = Path::new(requesting_source); let requesting_dir_path = requesting_source_path.parent() .ok_or(format!("{}: expected parent path", requested_source_path.display()))?; let relative_path = requesting_dir_path.join(requested_source_path); if relative_path.is_file() { header_path = relative_path; } else if standard_path.is_file() { header_path = standard_path.clone(); } else { return Err("relative header path is not found".to_string()); } }, IncludeType::Standard => if standard_path.is_file() { header_path = standard_path.clone(); } else { return Err("standard header path is not found".to_string()); } } let header_content = fs::read_to_string(header_path) .map_err(|err| err.to_string())?; let resolved_include = ResolvedInclude { resolved_name: standard_path.to_string_lossy().to_string(), content: header_content }; Ok(resolved_include) } }
entry.path(); if path.is_file() { continue; } if let Some(dir_name) = path.components().last() { if dir_name.as_os_str().to_string_lossy() == SHADER_DIR_NAME { process_shader_dir(src_path, dir, &path)?; break; } } } Ok(()) } fn process_shader_dir(src_path: &PathBuf, top_shader_dir: &Path, dir: &Path) -> Result<()> { for entry in fs::read_dir(dir)? { let entry = entry?; let path = entry.path(); if path.is_dir() { process_shader_dir(src_path, top_shader_dir, &path)?; } else { compile_shader(src_path, top_shader_dir, &path)?; } } Ok(()) } fn compile_shader(src_path: &PathBuf, top_shader_dir: &Path, file_path: &Path) -> Result<()> { let mut options = CompileOptions::new() .ok_or(Error::Internal("shader compile options allocation failure".to_string()))?; options.set_include_callback(include_callback(src_path)); let source_language; if let Some(ext) = file_path.extension() { if ext == "glsl" { source_language =
random
[ { "content": "pub fn process_c_srcs(dir: &Path, include_dirs: &Vec<PathBuf>, cc_build: &mut cc::Build) -> Result<()> {\n\n for entry in fs::read_dir(dir)? {\n\n let entry = entry?;\n\n let path = entry.path();\n\n\n\n if path.is_file() {\n\n continue;\n\n }\n\n\n\n ...
Rust
vendor/sgx_tstd/src/sys/rwlock.rs
mesainner/crates-io
b9e098e801cc7180d2d025cf495add70d9f7e9f5
use sgx_types::{SysError, sgx_thread_t, SGX_THREAD_T_NULL}; use sgx_trts::libc; use crate::thread; use crate::sync::SgxThreadMutex; use crate::sync::SgxThreadCondvar; use crate::sync::SgxThreadSpinlock; use core::cell::UnsafeCell; struct SgxThreadRwLockInner { readers_num: u32, writers_num: u32, busy: u32, writer_thread: sgx_thread_t, condvar: SgxThreadCondvar, mutex: SgxThreadMutex, spinlock: SgxThreadSpinlock, } impl SgxThreadRwLockInner { const fn new() -> Self { SgxThreadRwLockInner{ readers_num: 0, writers_num: 0, busy: 0, writer_thread: SGX_THREAD_T_NULL, condvar: SgxThreadCondvar::new(), mutex: SgxThreadMutex::new(), spinlock: SgxThreadSpinlock::new(), } } unsafe fn ref_busy(&mut self) -> SysError { let ret: SysError; self.spinlock.lock(); { if self.busy == u32::max_value() { ret = Err(libc::EAGAIN); } else { self.busy += 1; ret = Ok(()); } } self.spinlock.unlock(); ret } unsafe fn deref_busy(&mut self) -> SysError { let ret: SysError; self.spinlock.lock(); { if self.busy == 0 { ret = Err(libc::EAGAIN); } else { self.busy -= 1; ret = Ok(()); } } self.spinlock.unlock(); ret } unsafe fn read(&mut self) -> SysError { self.ref_busy()?; self.mutex.lock(); { if self.writer_thread == thread::rsgx_thread_self() { self.mutex.unlock(); self.deref_busy(); return Err(libc::EDEADLK); } if self.readers_num == u32::max_value() { self.mutex.unlock(); self.deref_busy(); return Err(libc::EAGAIN); } while self.writers_num > 0 { self.condvar.wait(&self.mutex); } self.readers_num += 1; } self.mutex.unlock(); self.deref_busy(); Ok(()) } unsafe fn try_read(&mut self) -> SysError { self.ref_busy()?; self.mutex.lock(); { let mut ret = Ok(()); if self.writer_thread == thread::rsgx_thread_self() { ret = Err(libc::EDEADLK); } else if self.readers_num == u32::max_value() { ret = Err(libc::EAGAIN); } else if self.writers_num > 0 { ret = Err(libc::EBUSY); } match ret { Ok(_) => {}, Err(e) => { self.mutex.unlock(); self.deref_busy(); return Err(e); } } self.readers_num += 1; } self.mutex.unlock(); self.deref_busy(); Ok(()) } unsafe fn write(&mut self) -> SysError { self.ref_busy()?; self.mutex.lock(); { if self.writer_thread == thread::rsgx_thread_self() { self.mutex.unlock(); self.deref_busy(); return Err(libc::EDEADLK); } if self.writers_num == u32::max_value() { self.mutex.unlock(); self.deref_busy(); return Err(libc::EAGAIN); } self.writers_num += 1; while self.readers_num > 0 { self.condvar.wait(&self.mutex); } while self.writer_thread != SGX_THREAD_T_NULL { self.condvar.wait(&self.mutex); } self.writer_thread = thread::rsgx_thread_self(); } self.mutex.unlock(); self.deref_busy(); Ok(()) } pub unsafe fn try_write(&mut self) -> SysError { self.ref_busy()?; self.mutex.lock(); { let mut ret = Ok(()); if self.writer_thread == thread::rsgx_thread_self() { ret = Err(libc::EDEADLK); } else if self.writers_num == u32::max_value() { ret = Err(libc::EAGAIN); } else if self.readers_num > 0 || self.writer_thread != SGX_THREAD_T_NULL { ret = Err(libc::EBUSY); } match ret { Ok(_) => {}, Err(e) => { self.mutex.unlock(); self.deref_busy(); return Err(e); } } self.writers_num += 1; self.writer_thread = thread::rsgx_thread_self(); } self.mutex.unlock(); self.deref_busy(); Ok(()) } unsafe fn read_unlock(&mut self) -> SysError { self.raw_unlock() } unsafe fn write_unlock(&mut self) -> SysError { self.raw_unlock() } unsafe fn raw_unlock(&mut self) -> SysError { self.mutex.lock(); { if self.readers_num > 0 { self.readers_num -= 1; if self.readers_num == 0 && self.writers_num > 0 { self.condvar.broadcast(); } } else { if self.writer_thread != thread::rsgx_thread_self() { self.mutex.unlock(); return Err(libc::EPERM); } self.writers_num -= 1; self.writer_thread = SGX_THREAD_T_NULL; if self.busy > 0 { self.condvar.broadcast(); } } } self.mutex.unlock(); Ok(()) } unsafe fn destroy(&mut self) -> SysError { self.mutex.lock(); { if self.readers_num > 0 || self.writers_num > 0 || self.busy > 0 { self.spinlock.unlock(); return Err(libc::EBUSY); } self.condvar.destroy(); self.mutex.destroy(); } self.spinlock.unlock(); Ok(()) } } pub struct SgxThreadRwLock { lock: UnsafeCell<SgxThreadRwLockInner>, } impl SgxThreadRwLock { pub const fn new() -> Self { SgxThreadRwLock { lock: UnsafeCell::new(SgxThreadRwLockInner::new()) } } #[inline] pub unsafe fn read(&self) -> SysError { let rwlock: &mut SgxThreadRwLockInner = &mut *self.lock.get(); rwlock.read() } #[inline] pub unsafe fn try_read(&self) -> SysError { let rwlock: &mut SgxThreadRwLockInner = &mut *self.lock.get(); rwlock.try_read() } #[inline] pub unsafe fn write(&self) -> SysError { let rwlock: &mut SgxThreadRwLockInner = &mut *self.lock.get(); rwlock.write() } #[inline] pub unsafe fn try_write(&self) -> SysError { let rwlock: &mut SgxThreadRwLockInner = &mut *self.lock.get(); rwlock.try_write() } #[inline] pub unsafe fn read_unlock(&self) -> SysError { let rwlock: &mut SgxThreadRwLockInner = &mut *self.lock.get(); rwlock.read_unlock() } #[inline] pub unsafe fn write_unlock(&self) -> SysError { let rwlock: &mut SgxThreadRwLockInner = &mut *self.lock.get(); rwlock.write_unlock() } #[inline] pub unsafe fn destroy(&self) -> SysError { let rwlock: &mut SgxThreadRwLockInner = &mut *self.lock.get(); rwlock.destroy() } }
use sgx_types::{SysError, sgx_thread_t, SGX_THREAD_T_NULL}; use sgx_trts::libc; use crate::thread; use crate::sync::SgxThreadMutex; use crate::sync::SgxThreadCondvar; use crate::sync::SgxThreadSpinlock; use core::cell::UnsafeCell; struct SgxThreadRwLockInner { readers_num: u32, writers_num: u32, busy: u32, writer_thread: sgx_thread_t, condvar: SgxThreadCondvar, mutex: SgxThreadMutex, spinlock: SgxThreadSpinlock, } impl SgxThreadRwLockInner { const fn new() -> Self { SgxThreadRwLockInner{ readers_num: 0, writers_num: 0, busy: 0, writer_thread: SGX_THREAD_T_NULL, condvar: SgxThreadCondvar::new(), mutex: SgxThreadMutex::new(), spinlock: SgxThreadSpinlock::new(), } } unsafe fn ref_busy(&mut self) -> SysError { let ret: SysError; self.spinlock.lock(); { if self.busy == u32::max_valu
unsafe fn deref_busy(&mut self) -> SysError { let ret: SysError; self.spinlock.lock(); { if self.busy == 0 { ret = Err(libc::EAGAIN); } else { self.busy -= 1; ret = Ok(()); } } self.spinlock.unlock(); ret } unsafe fn read(&mut self) -> SysError { self.ref_busy()?; self.mutex.lock(); { if self.writer_thread == thread::rsgx_thread_self() { self.mutex.unlock(); self.deref_busy(); return Err(libc::EDEADLK); } if self.readers_num == u32::max_value() { self.mutex.unlock(); self.deref_busy(); return Err(libc::EAGAIN); } while self.writers_num > 0 { self.condvar.wait(&self.mutex); } self.readers_num += 1; } self.mutex.unlock(); self.deref_busy(); Ok(()) } unsafe fn try_read(&mut self) -> SysError { self.ref_busy()?; self.mutex.lock(); { let mut ret = Ok(()); if self.writer_thread == thread::rsgx_thread_self() { ret = Err(libc::EDEADLK); } else if self.readers_num == u32::max_value() { ret = Err(libc::EAGAIN); } else if self.writers_num > 0 { ret = Err(libc::EBUSY); } match ret { Ok(_) => {}, Err(e) => { self.mutex.unlock(); self.deref_busy(); return Err(e); } } self.readers_num += 1; } self.mutex.unlock(); self.deref_busy(); Ok(()) } unsafe fn write(&mut self) -> SysError { self.ref_busy()?; self.mutex.lock(); { if self.writer_thread == thread::rsgx_thread_self() { self.mutex.unlock(); self.deref_busy(); return Err(libc::EDEADLK); } if self.writers_num == u32::max_value() { self.mutex.unlock(); self.deref_busy(); return Err(libc::EAGAIN); } self.writers_num += 1; while self.readers_num > 0 { self.condvar.wait(&self.mutex); } while self.writer_thread != SGX_THREAD_T_NULL { self.condvar.wait(&self.mutex); } self.writer_thread = thread::rsgx_thread_self(); } self.mutex.unlock(); self.deref_busy(); Ok(()) } pub unsafe fn try_write(&mut self) -> SysError { self.ref_busy()?; self.mutex.lock(); { let mut ret = Ok(()); if self.writer_thread == thread::rsgx_thread_self() { ret = Err(libc::EDEADLK); } else if self.writers_num == u32::max_value() { ret = Err(libc::EAGAIN); } else if self.readers_num > 0 || self.writer_thread != SGX_THREAD_T_NULL { ret = Err(libc::EBUSY); } match ret { Ok(_) => {}, Err(e) => { self.mutex.unlock(); self.deref_busy(); return Err(e); } } self.writers_num += 1; self.writer_thread = thread::rsgx_thread_self(); } self.mutex.unlock(); self.deref_busy(); Ok(()) } unsafe fn read_unlock(&mut self) -> SysError { self.raw_unlock() } unsafe fn write_unlock(&mut self) -> SysError { self.raw_unlock() } unsafe fn raw_unlock(&mut self) -> SysError { self.mutex.lock(); { if self.readers_num > 0 { self.readers_num -= 1; if self.readers_num == 0 && self.writers_num > 0 { self.condvar.broadcast(); } } else { if self.writer_thread != thread::rsgx_thread_self() { self.mutex.unlock(); return Err(libc::EPERM); } self.writers_num -= 1; self.writer_thread = SGX_THREAD_T_NULL; if self.busy > 0 { self.condvar.broadcast(); } } } self.mutex.unlock(); Ok(()) } unsafe fn destroy(&mut self) -> SysError { self.mutex.lock(); { if self.readers_num > 0 || self.writers_num > 0 || self.busy > 0 { self.spinlock.unlock(); return Err(libc::EBUSY); } self.condvar.destroy(); self.mutex.destroy(); } self.spinlock.unlock(); Ok(()) } } pub struct SgxThreadRwLock { lock: UnsafeCell<SgxThreadRwLockInner>, } impl SgxThreadRwLock { pub const fn new() -> Self { SgxThreadRwLock { lock: UnsafeCell::new(SgxThreadRwLockInner::new()) } } #[inline] pub unsafe fn read(&self) -> SysError { let rwlock: &mut SgxThreadRwLockInner = &mut *self.lock.get(); rwlock.read() } #[inline] pub unsafe fn try_read(&self) -> SysError { let rwlock: &mut SgxThreadRwLockInner = &mut *self.lock.get(); rwlock.try_read() } #[inline] pub unsafe fn write(&self) -> SysError { let rwlock: &mut SgxThreadRwLockInner = &mut *self.lock.get(); rwlock.write() } #[inline] pub unsafe fn try_write(&self) -> SysError { let rwlock: &mut SgxThreadRwLockInner = &mut *self.lock.get(); rwlock.try_write() } #[inline] pub unsafe fn read_unlock(&self) -> SysError { let rwlock: &mut SgxThreadRwLockInner = &mut *self.lock.get(); rwlock.read_unlock() } #[inline] pub unsafe fn write_unlock(&self) -> SysError { let rwlock: &mut SgxThreadRwLockInner = &mut *self.lock.get(); rwlock.write_unlock() } #[inline] pub unsafe fn destroy(&self) -> SysError { let rwlock: &mut SgxThreadRwLockInner = &mut *self.lock.get(); rwlock.destroy() } }
e() { ret = Err(libc::EAGAIN); } else { self.busy += 1; ret = Ok(()); } } self.spinlock.unlock(); ret }
function_block-function_prefixed
[]
Rust
planus-cli/src/util/sorted_map.rs
OliverEvans96/planus
c24182f57eafe15e416d240f805a9d30d652c056
#[derive(Debug, Clone, PartialOrd, Ord, PartialEq, Eq, Hash)] pub struct SortedMap<K, V>(pub Vec<(K, V)>); pub struct SortedSet<K>(SortedMap<K, ()>); impl<K, V> Default for SortedMap<K, V> { fn default() -> Self { Self::new() } } impl<K> Default for SortedSet<K> { fn default() -> Self { Self::new() } } impl<K, V> SortedMap<K, V> { pub fn new() -> Self { Self(Vec::new()) } pub fn clear(&mut self) { self.0.clear(); } pub fn len(&self) -> usize { self.0.len() } pub fn is_empty(&self) -> bool { self.0.len() == 0 } pub fn capacity(&self) -> usize { self.0.capacity() } pub fn iter(&self) -> impl Iterator<Item = &(K, V)> { self.0.iter() } pub fn values(&self) -> impl Iterator<Item = &V> { self.0.iter().map(|(_, v)| v) } pub fn values_mut(&mut self) -> impl Iterator<Item = &mut V> { self.0.iter_mut().map(|(_, v)| v) } pub fn first(&self) -> Option<&(K, V)> { self.0.first() } pub fn first_value(&self) -> Option<&V> { self.first().map(|(_k, v)| v) } pub fn last(&self) -> Option<&(K, V)> { self.0.last() } pub fn last_value(&self) -> Option<&V> { self.last().map(|(_k, v)| v) } } impl<K: Ord, V> SortedMap<K, V> { pub fn index_of(&self, k: &K) -> Option<usize> { self.0.binary_search_by_key(&k, |(k, _v)| k).ok() } pub fn get(&self, k: &K) -> Option<&V> { let index = self.0.binary_search_by_key(&k, |(k, _v)| k).ok()?; Some(&self.0[index].1) } pub fn insert(&mut self, key: K, value: V) -> Option<V> { match self.0.binary_search_by_key(&&key, |(k, _v)| k) { Ok(index) => Some(std::mem::replace(&mut self.0[index].1, value)), Err(index) => { self.0.insert(index, (key, value)); None } } } pub fn entry(&mut self, key: K) -> sorted_map::Entry<'_, K, V> { match self.0.binary_search_by_key(&&key, |(k, _v)| k) { Ok(index) => { sorted_map::Entry::Occupied(sorted_map::OccupiedEntry { map: self, index }) } Err(index) => sorted_map::Entry::Vacant(sorted_map::VacantEntry { map: self, key, index, }), } } } #[allow(clippy::module_inception)] pub mod sorted_map { pub enum Entry<'a, K: 'a, V: 'a> { Occupied(OccupiedEntry<'a, K, V>), Vacant(VacantEntry<'a, K, V>), } pub struct OccupiedEntry<'a, K: 'a, V: 'a> { pub(super) map: &'a mut super::SortedMap<K, V>, pub(super) index: usize, } pub struct VacantEntry<'a, K: 'a, V: 'a> { pub(super) map: &'a mut super::SortedMap<K, V>, pub(super) key: K, pub(super) index: usize, } impl<'a, K: 'a, V: 'a> Entry<'a, K, V> { #[inline] pub fn or_insert(self, default: V) -> &'a mut V { match self { Entry::Occupied(entry) => entry.into_mut(), Entry::Vacant(entry) => entry.insert(default), } } #[inline] pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V { match self { Entry::Occupied(entry) => entry.into_mut(), Entry::Vacant(entry) => entry.insert(default()), } } } impl<'a, K, V: Default> Entry<'a, K, V> { #[inline] pub fn or_default(self) -> &'a mut V { match self { Entry::Occupied(entry) => entry.into_mut(), Entry::Vacant(entry) => entry.insert(Default::default()), } } } impl<'a, K: 'a, V: 'a> OccupiedEntry<'a, K, V> { pub fn into_mut(self) -> &'a mut V { &mut self.map.0[self.index].1 } pub fn get_mut(&mut self) -> &mut V { &mut self.map.0[self.index].1 } } impl<'a, K: 'a, V: 'a> VacantEntry<'a, K, V> { pub fn insert(self, value: V) -> &'a mut V { self.map.0.insert(self.index, (self.key, value)); &mut self.map.0[self.index].1 } } } impl<K> SortedSet<K> { pub fn new() -> Self { Self(SortedMap::new()) } pub fn clear(&mut self) { self.0.clear(); } pub fn len(&self) -> usize { self.0.len() } pub fn is_empty(&self) -> bool { self.0.len() == 0 } pub fn capacity(&self) -> usize { self.0.capacity() } pub fn iter(&self) -> impl Iterator<Item = &K> { self.0.iter().map(|(k, ())| k) } pub fn first(&self) -> Option<&K> { self.0.first().map(|(k, ())| k) } pub fn last(&self) -> Option<&K> { self.0.last().map(|(k, ())| k) } } impl<K: Ord> SortedSet<K> { pub fn index_of(&self, k: &K) -> Option<usize> { self.0.index_of(k) } pub fn insert(&mut self, key: K) -> bool { self.0.insert(key, ()).is_none() } pub fn contains(&self, k: &K) -> bool { self.0.get(k).is_some() } }
#[derive(Debug, Clone, PartialOrd, Ord, PartialEq, Eq, Hash)] pub struct SortedMap<K, V>(pub Vec<(K, V)>); pub struct SortedSet<K>(SortedMap<K, ()>); impl<K, V> Default for SortedMap<K, V> { fn default() -> Self { Self::new() } } impl<K> Default for SortedSet<K> { fn default() -> Self { Self::new() } } impl<K, V> SortedMap<K, V> { pub fn new() -> Self { Self(Vec::new()) } pub fn clear(&mut self) { self.0.clear(); } pub fn len(&self) -> usize { self.0.len() } pub fn is_empty(&self) -> bool { self.0.len() == 0 } pub fn capacity(&self) -> usize { self.0.capacity() } pub fn iter(&self) -> impl Iterator<Item = &(K, V)> { self.0.iter() } pub fn values(&self) -> impl Iterator<Item = &V> { self.0.iter().map(|(_, v)| v) } pub fn values_mut(&mut self) -> impl Iterator<Item = &mut V> { self.0.iter_mut().map(|(_, v)| v) } pub fn first(&self) -> Option<&(K, V)> { self.0.first() } pub fn first_value(&self) -> Option<&V> { self.first().map(|(_k, v)| v) } pub fn last(&self) -> Option<&(K, V)> { self.0.last() } pub fn last_value(&self) -> Option<&V> { self.last().map(|(_k, v)| v) } } impl<K: Ord, V> SortedMap<K, V> { pub fn index_of(&self, k: &K) -> Option<usize> { self.0.binary_search_by_key(&k, |(k, _v)| k).ok() } pub fn get(&self, k: &K) -> Option<&V> { let index = self.0.binary_search_by_key(&k, |(k, _v)| k).ok()?; Some(&self.0[index].1) } pub fn insert(&mut self, key: K, value: V) -> Option<V> { match self.0.binary_search_by_key(&&key, |(k, _v)| k) { Ok(index) => Some(std::mem::replace(&mut self.0[index].1, value)), Err(index) => { self.0.insert(index, (key, value)); None } } } pub fn entry(&mut self, key: K) -> sorted_map::Entry<'_, K, V> { match self.0.binary_search_by_key(&&key, |(k, _v)| k) { Ok(index) => { sorted_map::Entry::Occupied(sorted_map::OccupiedEntry { map: self, index }) } Err(index) => sorted_map::Entry::Vacant(sorted_map::VacantEntry { map: self, key, index, }), } } } #[allow(clippy::module_inception)] pub mod sorted_map { pub enum Entry<'a, K: 'a, V: 'a> { Occupied(OccupiedEntry<'a, K, V>), Vacant(VacantEntry<'a, K, V>), } pub struct OccupiedEntry<'a, K: 'a, V: 'a> { pub(super) map: &'a mut super::SortedMap<K, V>, pub(super) index: usize, } pub struct VacantEntry<'a, K: 'a, V: 'a> { pub(super) map: &'a mut super::SortedMap<K, V>, pub(super) key: K, pub(super) index: usize, } impl<'a, K: 'a, V: 'a> Entry<'a, K, V> { #[inline] pub fn or_insert(self, default: V) -> &'a mut V { match self { Entry::Occupied(entry) => entry.into_mut(), Entry::Vacant(entry) => entry.insert(default), } } #[inline] pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V { match self { Entry::Occupied(entry) => entry.into_mut(), Entry::Vacant(entry) => entry.insert(default()), } } } impl<'a, K, V: Default> Entry<'a, K, V> { #[inline]
} impl<'a, K: 'a, V: 'a> OccupiedEntry<'a, K, V> { pub fn into_mut(self) -> &'a mut V { &mut self.map.0[self.index].1 } pub fn get_mut(&mut self) -> &mut V { &mut self.map.0[self.index].1 } } impl<'a, K: 'a, V: 'a> VacantEntry<'a, K, V> { pub fn insert(self, value: V) -> &'a mut V { self.map.0.insert(self.index, (self.key, value)); &mut self.map.0[self.index].1 } } } impl<K> SortedSet<K> { pub fn new() -> Self { Self(SortedMap::new()) } pub fn clear(&mut self) { self.0.clear(); } pub fn len(&self) -> usize { self.0.len() } pub fn is_empty(&self) -> bool { self.0.len() == 0 } pub fn capacity(&self) -> usize { self.0.capacity() } pub fn iter(&self) -> impl Iterator<Item = &K> { self.0.iter().map(|(k, ())| k) } pub fn first(&self) -> Option<&K> { self.0.first().map(|(k, ())| k) } pub fn last(&self) -> Option<&K> { self.0.last().map(|(k, ())| k) } } impl<K: Ord> SortedSet<K> { pub fn index_of(&self, k: &K) -> Option<usize> { self.0.index_of(k) } pub fn insert(&mut self, key: K) -> bool { self.0.insert(key, ()).is_none() } pub fn contains(&self, k: &K) -> bool { self.0.get(k).is_some() } }
pub fn or_default(self) -> &'a mut V { match self { Entry::Occupied(entry) => entry.into_mut(), Entry::Vacant(entry) => entry.insert(Default::default()), } }
function_block-full_function
[ { "content": "pub fn align_up(value: u32, alignment: u32) -> u32 {\n\n ((value + alignment - 1) / alignment) * alignment\n\n}\n", "file_path": "planus-cli/src/util/mod.rs", "rank": 0, "score": 163890.73865225195 }, { "content": "pub fn criterion_benchmark(c: &mut Criterion) {\n\n c.ben...
Rust
tokera/src/api/bag.rs
tokera-com/ate
42c4ce5a0c0aef47aeb4420cc6dc788ef6ee8804
#![allow(unused_imports)] use ate::prelude::*; use error_chain::bail; use fxhash::FxHashSet; use std::ops::Deref; use std::sync::Arc; use tracing::{debug, error, info, trace, warn}; use crate::api::TokApi; use crate::error::*; use crate::model::*; impl TokApi { pub(super) async fn __get_bag( &mut self, denomination: Denomination, ) -> Result<Option<DaoMut<BagOfCoins>>, WalletError> { let ret = self.wallet.as_mut().bags.get_mut(&denomination).await?; Ok(ret) } pub(super) async fn __get_or_create_bag( &mut self, denomination: Denomination, ) -> Result<DaoMut<BagOfCoins>, WalletError> { let ret = self .wallet .as_mut() .bags .get_or_default(denomination) .await?; Ok(ret) } pub async fn add_coin_to_wallet(&mut self, coin: CarvedCoin) -> Result<(), WalletError> { let lock = self.wallet.try_lock_with_timeout(self.lock_timeout).await?; if lock == false { bail!(WalletErrorKind::WalletLocked); } self.__add_coin_to_wallet(coin).await?; self.wallet.unlock().await?; Ok(()) } pub async fn add_coins_to_wallet( &mut self, coins: impl IntoIterator<Item = CarvedCoin>, ) -> Result<(), WalletError> { let lock = self.wallet.try_lock_with_timeout(self.lock_timeout).await?; if lock == false { bail!(WalletErrorKind::WalletLocked); } for coin in coins { self.__add_coin_to_wallet(coin).await?; } self.wallet.unlock().await?; Ok(()) } pub(super) async fn __add_coin_to_wallet( &mut self, coin: CarvedCoin, ) -> Result<(), WalletError> { let mut bag = self .__get_or_create_bag(Denomination { value: coin.value, currency: coin.currency, }) .await?; let mut active_bag = bag.as_mut(); if active_bag.coins.iter().any(|c| c.coin == coin.coin) { trace!( "ignoing coin (value={}{}) - already in wallet", coin.value, coin.currency ); return Ok(()); } trace!( "adding coin to wallet (value={}{})", coin.value, coin.currency ); active_bag.coins.push(coin); Ok(()) } pub async fn remove_coin_from_wallet( &mut self, denomination: Denomination, ) -> Result<(), WalletError> { let lock = self.wallet.try_lock_with_timeout(self.lock_timeout).await?; if lock == false { bail!(WalletErrorKind::WalletLocked); } self.__remove_coin_from_wallet(denomination).await?; self.wallet.unlock().await?; Ok(()) } pub(super) async fn __remove_coin_from_wallet( &mut self, denomination: Denomination, ) -> Result<Option<CarvedCoin>, WalletError> { let mut bag = match self.__get_bag(denomination).await? { Some(a) => a, None => { return Ok(None); } }; let mut bag = bag.as_mut(); let ret = bag.coins.pop(); Ok(ret) } }
#![allow(unused_imports)] use ate::prelude::*; use error_chain::bail; use fxhash::FxHashSet; use std::ops::Deref; use std::sync::Arc; use tracing::{debug, error, info, trace, warn}; use crate::api::TokApi; use crate::error::*; use crate::model::*; impl TokApi {
pub(super) async fn __get_or_create_bag( &mut self, denomination: Denomination, ) -> Result<DaoMut<BagOfCoins>, WalletError> { let ret = self .wallet .as_mut() .bags .get_or_default(denomination) .await?; Ok(ret) } pub async fn add_coin_to_wallet(&mut self, coin: CarvedCoin) -> Result<(), WalletError> { let lock = self.wallet.try_lock_with_timeout(self.lock_timeout).await?; if lock == false { bail!(WalletErrorKind::WalletLocked); } self.__add_coin_to_wallet(coin).await?; self.wallet.unlock().await?; Ok(()) } pub async fn add_coins_to_wallet( &mut self, coins: impl IntoIterator<Item = CarvedCoin>, ) -> Result<(), WalletError> { let lock = self.wallet.try_lock_with_timeout(self.lock_timeout).await?; if lock == false { bail!(WalletErrorKind::WalletLocked); } for coin in coins { self.__add_coin_to_wallet(coin).await?; } self.wallet.unlock().await?; Ok(()) } pub(super) async fn __add_coin_to_wallet( &mut self, coin: CarvedCoin, ) -> Result<(), WalletError> { let mut bag = self .__get_or_create_bag(Denomination { value: coin.value, currency: coin.currency, }) .await?; let mut active_bag = bag.as_mut(); if active_bag.coins.iter().any(|c| c.coin == coin.coin) { trace!( "ignoing coin (value={}{}) - already in wallet", coin.value, coin.currency ); return Ok(()); } trace!( "adding coin to wallet (value={}{})", coin.value, coin.currency ); active_bag.coins.push(coin); Ok(()) } pub async fn remove_coin_from_wallet( &mut self, denomination: Denomination, ) -> Result<(), WalletError> { let lock = self.wallet.try_lock_with_timeout(self.lock_timeout).await?; if lock == false { bail!(WalletErrorKind::WalletLocked); } self.__remove_coin_from_wallet(denomination).await?; self.wallet.unlock().await?; Ok(()) } pub(super) async fn __remove_coin_from_wallet( &mut self, denomination: Denomination, ) -> Result<Option<CarvedCoin>, WalletError> { let mut bag = match self.__get_bag(denomination).await? { Some(a) => a, None => { return Ok(None); } }; let mut bag = bag.as_mut(); let ret = bag.coins.pop(); Ok(ret) } }
pub(super) async fn __get_bag( &mut self, denomination: Denomination, ) -> Result<Option<DaoMut<BagOfCoins>>, WalletError> { let ret = self.wallet.as_mut().bags.get_mut(&denomination).await?; Ok(ret) }
function_block-full_function
[ { "content": "fn conv_err(err: FsError) -> Box<dyn std::error::Error> {\n\n error!(\"{}\", err);\n\n let err: std::io::Error = err.into();\n\n err.into()\n\n}\n", "file_path": "wasm-bus-fuse/examples/find.rs", "rank": 0, "score": 91894.57967854003 }, { "content": "fn main() -> Resul...
Rust
src/kernel/src/log.rs
ariadiamond/twizzler-Rust
5f5d01bac9127ca1d64bb8aa472a04f6634fc3a9
use core::{ fmt::Write, sync::atomic::{AtomicU64, Ordering}, }; use twizzler_abi::syscall::{ KernelConsoleReadBufferError, KernelConsoleReadError, KernelConsoleReadFlags, }; use crate::{interrupt, spinlock::Spinlock}; const KEC_BUFFER_LEN: usize = 4096; const MAX_SINGLE_WRITE: usize = KEC_BUFFER_LEN / 2; struct KernelConsoleInner { state: AtomicU64, buffer: core::cell::UnsafeCell<[u8; KEC_BUFFER_LEN]>, } unsafe impl Sync for KernelConsoleInner {} pub trait MessageLevel {} pub struct EmergencyMessage; impl MessageLevel for EmergencyMessage {} pub struct NormalMessage; impl MessageLevel for NormalMessage {} pub struct ConsoleWriteError; const INPUT_BUFFER_SIZE: usize = 1024; pub struct KernelConsoleReadBuffer { buf: [u8; INPUT_BUFFER_SIZE], pos: usize, } impl KernelConsoleReadBuffer { const fn new() -> Self { Self { buf: [0; INPUT_BUFFER_SIZE], pos: 0, } } pub fn push_input_byte(&mut self, byte: u8) { if self.pos == INPUT_BUFFER_SIZE { return; } self.buf[self.pos] = byte; self.pos += 1; } pub fn read_byte(&mut self) -> Option<u8> { if self.pos == 0 { return None; } let byte = self.buf[0]; self.buf.copy_within(1.., 0); self.pos -= 1; Some(byte) } } pub struct KernelConsole<T: KernelConsoleHardware, Level: MessageLevel> { inner: &'static KernelConsoleInner, hardware: T, lock: Spinlock<()>, read_lock: Spinlock<KernelConsoleReadBuffer>, _pd: core::marker::PhantomData<Level>, } unsafe impl<T: KernelConsoleHardware, Level: MessageLevel> Sync for KernelConsole<T, Level> {} static KERNEL_CONSOLE_MAIN: KernelConsoleInner = KernelConsoleInner { state: AtomicU64::new(0), buffer: core::cell::UnsafeCell::new([0; KEC_BUFFER_LEN]), }; pub trait KernelConsoleHardware { fn write(&self, data: &[u8], flags: KernelConsoleWriteFlags); } impl<T: KernelConsoleHardware> core::fmt::Write for KernelConsole<T, EmergencyMessage> { fn write_str(&mut self, s: &str) -> core::fmt::Result { let _ = self.write(s.as_bytes(), KernelConsoleWriteFlags::empty()); Ok(()) } } impl<T: KernelConsoleHardware> core::fmt::Write for KernelConsole<T, NormalMessage> { fn write_str(&mut self, s: &str) -> core::fmt::Result { let _ = self.write(s.as_bytes(), KernelConsoleWriteFlags::empty()); Ok(()) } } bitflags::bitflags! { pub struct KernelConsoleWriteFlags: u32 { const DISCARD_ON_FULL = 1; } } impl From<twizzler_abi::syscall::KernelConsoleWriteFlags> for KernelConsoleWriteFlags { fn from(x: twizzler_abi::syscall::KernelConsoleWriteFlags) -> Self { if x.contains(twizzler_abi::syscall::KernelConsoleWriteFlags::DISCARD_ON_FULL) { Self::DISCARD_ON_FULL } else { Self::empty() } } } fn write_head(s: u64) -> u64 { (s >> 32) & 0xffff } fn write_resv(s: u64) -> u64 { (s >> 16) & 0xffff } fn read_head(s: u64) -> u64 { s & 0xffff } fn new_state(rh: u64, wh: u64, wr: u64) -> u64 { ((rh % KEC_BUFFER_LEN as u64) & 0xffff) | (((wh % KEC_BUFFER_LEN as u64) & 0xffff) << 32) | (((wr % KEC_BUFFER_LEN as u64) & 0xffff) << 16) } fn did_pass(x: u64, y: u64, l: u64, n: u64) -> bool { assert!(l < n); let next_x = (x + l) % n; let did_wrap = next_x < x; if x < y { did_wrap || next_x >= y } else { next_x >= y && did_wrap } } fn reserve_write(state: u64, len: usize) -> u64 { let len = len as u64; let wr = write_resv(state); let mut wh = write_head(state); let mut rh = read_head(state); let passed_rh = did_pass(wr, rh, len, KEC_BUFFER_LEN as u64); let passed_wh = did_pass(wr, wh, len, KEC_BUFFER_LEN as u64); let wr = (wr + len) % KEC_BUFFER_LEN as u64; if passed_rh { rh = wr; } if passed_wh { wh = (wr - len) % KEC_BUFFER_LEN as u64; } new_state(rh, wh, wr) } fn commit_write(state: u64, len: usize) -> u64 { let wh = write_head(state); let wr = write_resv(state); new_state(read_head(state), wh + len as u64, wr) } fn reserve_space(state: u64, len: usize, toss: bool) -> (bool, u64, u64) { let new_state = reserve_write(state, len); ( read_head(state) == read_head(new_state) || !toss, new_state, write_head(state), ) } impl KernelConsoleInner { fn try_commit(&self, old: u64, new: u64) -> bool { self.state .compare_exchange(old, new, Ordering::SeqCst, Ordering::SeqCst) .is_ok() } fn write_buffer( &self, data: &[u8], flags: KernelConsoleWriteFlags, ) -> Result<(), ConsoleWriteError> { let data = &data[0..core::cmp::min(data.len(), MAX_SINGLE_WRITE)]; loop { let state = self.state.load(Ordering::SeqCst); let (ok, new_state, copy_offset) = reserve_space( state, data.len(), flags.contains(KernelConsoleWriteFlags::DISCARD_ON_FULL), ); if !ok { return Err(ConsoleWriteError {}); } if !self.try_commit(state, new_state) { continue; } let (first_len, second_len) = if copy_offset + data.len() as u64 > KEC_BUFFER_LEN as u64 { let first_len = KEC_BUFFER_LEN as u64 - copy_offset; (first_len, data.len() as u64 - first_len) } else { (data.len() as u64, 0) }; (&mut unsafe { *self.buffer.get() }) [copy_offset as usize..(copy_offset + first_len) as usize] .copy_from_slice(&data[0..first_len as usize]); (&mut unsafe { *self.buffer.get() })[0..second_len as usize] .copy_from_slice(&data[first_len as usize..(first_len + second_len) as usize]); let new_committed_state = commit_write(new_state, data.len()); if self.try_commit(new_state, new_committed_state) { break; } } Ok(()) } } impl<T: KernelConsoleHardware> KernelConsole<T, EmergencyMessage> { pub fn write( &self, data: &[u8], flags: KernelConsoleWriteFlags, ) -> Result<(), ConsoleWriteError> { self.hardware.write(data, flags); self.inner.write_buffer(data, flags) } } impl<T: KernelConsoleHardware> KernelConsole<T, NormalMessage> { pub fn write( &self, data: &[u8], flags: KernelConsoleWriteFlags, ) -> Result<(), ConsoleWriteError> { self.hardware.write(data, flags); self.inner.write_buffer(data, flags) } } impl<T: KernelConsoleHardware, M: MessageLevel> KernelConsole<T, M> { fn read_buffer_bytes(&self, _slice: &mut [u8]) -> Result<usize, KernelConsoleReadBufferError> { todo!() } fn read_bytes( &self, slice: &mut [u8], flags: KernelConsoleReadFlags, ) -> Result<usize, KernelConsoleReadError> { let mut i = 0; loop { if i == slice.len() { break; } let b = &mut slice[i]; if let Some(x) = self.read_lock.lock().read_byte() { *b = match x { 4 => return Ok(i), _ => x, }; i += 1; } else if flags.contains(KernelConsoleReadFlags::NONBLOCKING) || i > 0 { return Ok(i); } else { crate::sched::schedule(true); } } Ok(slice.len()) } } pub fn write_bytes(slice: &[u8], flags: KernelConsoleWriteFlags) -> Result<(), ConsoleWriteError> { unsafe { NORMAL_CONSOLE.write(slice, flags) } } pub fn read_bytes( slice: &mut [u8], flags: KernelConsoleReadFlags, ) -> Result<usize, KernelConsoleReadError> { unsafe { NORMAL_CONSOLE.read_bytes(slice, flags) } } pub fn read_buffer_bytes(slice: &mut [u8]) -> Result<usize, KernelConsoleReadBufferError> { unsafe { NORMAL_CONSOLE.read_buffer_bytes(slice) } } pub fn push_input_byte(byte: u8) { unsafe { let byte = match byte { 13 => 10, 127 => 8, x => x, }; NORMAL_CONSOLE.read_lock.lock().push_input_byte(byte); if byte == 8 { let _ = write_bytes(&[8, b' '], KernelConsoleWriteFlags::DISCARD_ON_FULL); } let _ = write_bytes(&[byte], KernelConsoleWriteFlags::DISCARD_ON_FULL); } } static mut EMERGENCY_CONSOLE: KernelConsole< crate::machine::MachineConsoleHardware, EmergencyMessage, > = KernelConsole { inner: &KERNEL_CONSOLE_MAIN, hardware: crate::machine::MachineConsoleHardware::new(), _pd: core::marker::PhantomData, lock: Spinlock::new(()), read_lock: Spinlock::new(KernelConsoleReadBuffer::new()), }; static mut NORMAL_CONSOLE: KernelConsole<crate::machine::MachineConsoleHardware, NormalMessage> = KernelConsole { inner: &KERNEL_CONSOLE_MAIN, hardware: crate::machine::MachineConsoleHardware::new(), _pd: core::marker::PhantomData, lock: Spinlock::new(()), read_lock: Spinlock::new(KernelConsoleReadBuffer::new()), }; #[doc(hidden)] pub fn _print_normal(args: ::core::fmt::Arguments) { let istate = interrupt::disable(); unsafe { let _guard = NORMAL_CONSOLE.lock.lock(); NORMAL_CONSOLE .write_fmt(args) .expect("printing to serial failed"); } interrupt::set(istate); } pub fn _print_emergency(args: ::core::fmt::Arguments) { unsafe { EMERGENCY_CONSOLE .write_fmt(args) .expect("printing to serial failed"); } } #[macro_export] macro_rules! log { ($($arg:tt)*) => { $crate::log::_print_normal(format_args!($($arg)*)) }; } #[macro_export] macro_rules! logln { () => { $crate::log!("\n") }; ($fmt:expr) => { $crate::log!(concat!($fmt, "\n")) }; ($fmt:expr, $($arg:tt)*) => { $crate::log!(concat!($fmt, "\n"), $($arg)*) }; } #[macro_export] macro_rules! emerglog { ($($arg:tt)*) => { $crate::log::_print_emergency(format_args!($($arg)*)) }; } #[macro_export] macro_rules! emerglogln { () => { $crate::emerglog!("\n") }; ($fmt:expr) => { $crate::emerglog!(concat!($fmt, "\n")) }; ($fmt:expr, $($arg:tt)*) => { $crate::emerglog!(concat!($fmt, "\n"), $($arg)*) }; }
use core::{ fmt::Write, sync::atomic::{AtomicU64, Ordering}, }; use twizzler_abi::syscall::{ KernelConsoleReadBufferError, KernelConsoleReadError, KernelConsoleReadFlags, }; use crate::{interrupt, spinlock::Spinlock}; const KEC_BUFFER_LEN: usize = 4096; const MAX_SINGLE_WRITE: usize = KEC_BUFFER_LEN / 2; struct KernelConsoleInner { state: AtomicU64, buffer: core::cell::UnsafeCell<[u8; KEC_BUFFER_LEN]>, } unsafe impl Sync for KernelConsoleInner {} pub trait MessageLevel {} pub struct EmergencyMessage; impl MessageLevel for EmergencyMessage {} pub struct NormalMessage; impl MessageLevel for NormalMessage {} pub struct ConsoleWriteError; const INPUT_BUFFER_SIZE: usize = 1024; pub struct KernelConsoleReadBuffer { buf: [u8; INPUT_BUFFER_SIZE], pos: usize, } impl KernelConsoleReadBuffer { const fn new() -> Self { Self { buf: [0; INPUT_BUFFER_SIZE], pos: 0, } } pub fn push_input_byte(&mut self, byte: u8) { if self.pos == INPUT_BUFFER_SIZE { return; } self.buf[self.pos] = byte; self.pos += 1; } pub fn read_byte(&mut self) -> Option<u8> { if self.pos == 0 { return None; } let byte = self.buf[0]; self.buf.copy_within(1.., 0); self.pos -= 1; Some(byte) } } pub struct KernelConsole<T: KernelConsoleHardware, Level: MessageLevel> { inner: &'static KernelConsoleInner, hardware: T, lock: Spinlock<()>, read_lock: Spinlock<KernelConsoleReadBuffer>, _pd: core::marker::PhantomData<Level>, } unsafe impl<T: KernelConsoleHardware, Level: MessageLevel> Sync for KernelConsole<T, Level> {} static KERNEL_CONSOLE_MAIN: KernelConsoleInner = KernelConsoleInner { state: AtomicU64::new(0), buffer: core::cell::UnsafeCell::new([0; KEC_BUFFER_LEN]), }; pub trait KernelConsoleHardware { fn write(&self, data: &[u8], flags: KernelConsoleWriteFlags); } impl<T: KernelConsoleHardware> core::fmt::Write for KernelConsole<T, EmergencyMessage> { fn write_str(&mut self, s: &str) -> core::fmt::Result { let _ = self.write(s.as_bytes(), KernelConsoleWriteFlags::empty()); Ok(()) } } impl<T: KernelConsoleHardware> core::fmt::Write for KernelConsole<T, NormalMessage> { fn write_str(&mut self, s: &str) -> core::fmt::Result { let _ = self.write(s.as_bytes(), KernelConsoleWriteFlags::empty()); Ok(()) } } bitflags::bitflags! { pub struct KernelConsoleWriteFlags: u32 { const DISCARD_ON_FULL = 1; } } impl From<twizzler_abi::syscall::KernelConsoleWriteFlags> for KernelConsoleWriteFlags {
} fn write_head(s: u64) -> u64 { (s >> 32) & 0xffff } fn write_resv(s: u64) -> u64 { (s >> 16) & 0xffff } fn read_head(s: u64) -> u64 { s & 0xffff } fn new_state(rh: u64, wh: u64, wr: u64) -> u64 { ((rh % KEC_BUFFER_LEN as u64) & 0xffff) | (((wh % KEC_BUFFER_LEN as u64) & 0xffff) << 32) | (((wr % KEC_BUFFER_LEN as u64) & 0xffff) << 16) } fn did_pass(x: u64, y: u64, l: u64, n: u64) -> bool { assert!(l < n); let next_x = (x + l) % n; let did_wrap = next_x < x; if x < y { did_wrap || next_x >= y } else { next_x >= y && did_wrap } } fn reserve_write(state: u64, len: usize) -> u64 { let len = len as u64; let wr = write_resv(state); let mut wh = write_head(state); let mut rh = read_head(state); let passed_rh = did_pass(wr, rh, len, KEC_BUFFER_LEN as u64); let passed_wh = did_pass(wr, wh, len, KEC_BUFFER_LEN as u64); let wr = (wr + len) % KEC_BUFFER_LEN as u64; if passed_rh { rh = wr; } if passed_wh { wh = (wr - len) % KEC_BUFFER_LEN as u64; } new_state(rh, wh, wr) } fn commit_write(state: u64, len: usize) -> u64 { let wh = write_head(state); let wr = write_resv(state); new_state(read_head(state), wh + len as u64, wr) } fn reserve_space(state: u64, len: usize, toss: bool) -> (bool, u64, u64) { let new_state = reserve_write(state, len); ( read_head(state) == read_head(new_state) || !toss, new_state, write_head(state), ) } impl KernelConsoleInner { fn try_commit(&self, old: u64, new: u64) -> bool { self.state .compare_exchange(old, new, Ordering::SeqCst, Ordering::SeqCst) .is_ok() } fn write_buffer( &self, data: &[u8], flags: KernelConsoleWriteFlags, ) -> Result<(), ConsoleWriteError> { let data = &data[0..core::cmp::min(data.len(), MAX_SINGLE_WRITE)]; loop { let state = self.state.load(Ordering::SeqCst); let (ok, new_state, copy_offset) = reserve_space( state, data.len(), flags.contains(KernelConsoleWriteFlags::DISCARD_ON_FULL), ); if !ok { return Err(ConsoleWriteError {}); } if !self.try_commit(state, new_state) { continue; } let (first_len, second_len) = if copy_offset + data.len() as u64 > KEC_BUFFER_LEN as u64 { let first_len = KEC_BUFFER_LEN as u64 - copy_offset; (first_len, data.len() as u64 - first_len) } else { (data.len() as u64, 0) }; (&mut unsafe { *self.buffer.get() }) [copy_offset as usize..(copy_offset + first_len) as usize] .copy_from_slice(&data[0..first_len as usize]); (&mut unsafe { *self.buffer.get() })[0..second_len as usize] .copy_from_slice(&data[first_len as usize..(first_len + second_len) as usize]); let new_committed_state = commit_write(new_state, data.len()); if self.try_commit(new_state, new_committed_state) { break; } } Ok(()) } } impl<T: KernelConsoleHardware> KernelConsole<T, EmergencyMessage> { pub fn write( &self, data: &[u8], flags: KernelConsoleWriteFlags, ) -> Result<(), ConsoleWriteError> { self.hardware.write(data, flags); self.inner.write_buffer(data, flags) } } impl<T: KernelConsoleHardware> KernelConsole<T, NormalMessage> { pub fn write( &self, data: &[u8], flags: KernelConsoleWriteFlags, ) -> Result<(), ConsoleWriteError> { self.hardware.write(data, flags); self.inner.write_buffer(data, flags) } } impl<T: KernelConsoleHardware, M: MessageLevel> KernelConsole<T, M> { fn read_buffer_bytes(&self, _slice: &mut [u8]) -> Result<usize, KernelConsoleReadBufferError> { todo!() } fn read_bytes( &self, slice: &mut [u8], flags: KernelConsoleReadFlags, ) -> Result<usize, KernelConsoleReadError> { let mut i = 0; loop { if i == slice.len() { break; } let b = &mut slice[i]; if let Some(x) = self.read_lock.lock().read_byte() { *b = match x { 4 => return Ok(i), _ => x, }; i += 1; } else if flags.contains(KernelConsoleReadFlags::NONBLOCKING) || i > 0 { return Ok(i); } else { crate::sched::schedule(true); } } Ok(slice.len()) } } pub fn write_bytes(slice: &[u8], flags: KernelConsoleWriteFlags) -> Result<(), ConsoleWriteError> { unsafe { NORMAL_CONSOLE.write(slice, flags) } } pub fn read_bytes( slice: &mut [u8], flags: KernelConsoleReadFlags, ) -> Result<usize, KernelConsoleReadError> { unsafe { NORMAL_CONSOLE.read_bytes(slice, flags) } } pub fn read_buffer_bytes(slice: &mut [u8]) -> Result<usize, KernelConsoleReadBufferError> { unsafe { NORMAL_CONSOLE.read_buffer_bytes(slice) } } pub fn push_input_byte(byte: u8) { unsafe { let byte = match byte { 13 => 10, 127 => 8, x => x, }; NORMAL_CONSOLE.read_lock.lock().push_input_byte(byte); if byte == 8 { let _ = write_bytes(&[8, b' '], KernelConsoleWriteFlags::DISCARD_ON_FULL); } let _ = write_bytes(&[byte], KernelConsoleWriteFlags::DISCARD_ON_FULL); } } static mut EMERGENCY_CONSOLE: KernelConsole< crate::machine::MachineConsoleHardware, EmergencyMessage, > = KernelConsole { inner: &KERNEL_CONSOLE_MAIN, hardware: crate::machine::MachineConsoleHardware::new(), _pd: core::marker::PhantomData, lock: Spinlock::new(()), read_lock: Spinlock::new(KernelConsoleReadBuffer::new()), }; static mut NORMAL_CONSOLE: KernelConsole<crate::machine::MachineConsoleHardware, NormalMessage> = KernelConsole { inner: &KERNEL_CONSOLE_MAIN, hardware: crate::machine::MachineConsoleHardware::new(), _pd: core::marker::PhantomData, lock: Spinlock::new(()), read_lock: Spinlock::new(KernelConsoleReadBuffer::new()), }; #[doc(hidden)] pub fn _print_normal(args: ::core::fmt::Arguments) { let istate = interrupt::disable(); unsafe { let _guard = NORMAL_CONSOLE.lock.lock(); NORMAL_CONSOLE .write_fmt(args) .expect("printing to serial failed"); } interrupt::set(istate); } pub fn _print_emergency(args: ::core::fmt::Arguments) { unsafe { EMERGENCY_CONSOLE .write_fmt(args) .expect("printing to serial failed"); } } #[macro_export] macro_rules! log { ($($arg:tt)*) => { $crate::log::_print_normal(format_args!($($arg)*)) }; } #[macro_export] macro_rules! logln { () => { $crate::log!("\n") }; ($fmt:expr) => { $crate::log!(concat!($fmt, "\n")) }; ($fmt:expr, $($arg:tt)*) => { $crate::log!(concat!($fmt, "\n"), $($arg)*) }; } #[macro_export] macro_rules! emerglog { ($($arg:tt)*) => { $crate::log::_print_emergency(format_args!($($arg)*)) }; } #[macro_export] macro_rules! emerglogln { () => { $crate::emerglog!("\n") }; ($fmt:expr) => { $crate::emerglog!(concat!($fmt, "\n")) }; ($fmt:expr, $($arg:tt)*) => { $crate::emerglog!(concat!($fmt, "\n"), $($arg)*) }; }
fn from(x: twizzler_abi::syscall::KernelConsoleWriteFlags) -> Self { if x.contains(twizzler_abi::syscall::KernelConsoleWriteFlags::DISCARD_ON_FULL) { Self::DISCARD_ON_FULL } else { Self::empty() } }
function_block-function_prefix_line
[]
Rust
src/main.rs
boylede/aoc2020
397cc12bb13b7cefb04a151ce87d992b6b7afb6d
use aoc2020::{Day, RunError, Session, SessionError}; use clap::Clap; #[clap(version = "0.1.0", author = "Daniel Boyle")] #[derive(Debug, Clone, Clap)] pub struct Config { #[clap(short = 'd', long = "day", default_value = "1")] pub day: i32, #[clap(short = 'a', long = "all")] pub all: bool, #[clap(short = 'o', long = "offline")] pub offline: bool, #[clap(short = 's', long = "session")] pub session: Option<String>, #[clap(short = 'i', long = "input")] pub input: Option<String>, #[clap(short = 'e', long = "examples")] pub examples: bool, #[clap(long = "accept")] pub accept: bool, #[clap(long = "validate")] pub validate: bool, #[clap(long = "clear-cache")] pub clear: bool, } fn main() { let config = Config::parse(); let days = aoc2020::DAYS; if config.all { for day in days { run_day(day, &config); } } else { let index = (config.day - 1) as usize; if index < days.len() { let day = &days[index]; run_day(day, &config); } else { println!("Invalid day selection: {}", config.day); } } } fn run_day(day: &Day, config: &Config) { if config.clear { println!("Clearing cache..."); day.clear_cache(); } if config.examples { println!("running examples for day {}...", day.index); match day.run_with_examples() { Ok(_) => (), Err(e) => {print_error(e)}, } } else if !config.offline && config.input.is_none() { let session = if let Some(session) = &config.session { Session::new(&session) } else { Session::from_file("session.txt") }; if let Ok(session) = session { let output = day.cache_input_and_run(&session); match output { Ok(result) => { let next_output = if config.validate { day.validate_result(result) } else if config.accept { day.cache_result(result) } else { Ok(()) }; if let Err(e) = next_output { print_error(e); } } Err(e) => print_error(e), } } else { println!("Please create a session.txt file or provide --session on the command line."); } } else if config.input.is_none() { let output = day.run_with_cached_input(); match output { Ok(result) => { let next_output = if config.validate { day.validate_result(result) } else if config.accept { day.cache_result(result) } else { Ok(()) }; if let Err(e) = next_output { print_error(e); } } Err(e) => print_error(e), } } else { let input_filename = config.input.as_ref().expect("unreachable"); let output = day.run_with_test_input(&input_filename); if let Err(e) = output { print_error(e); } } } fn print_error(err: RunError) { use RunError::*; use SessionError::*; match err { SessionFailed(TokenFormat) => println!("Session token was unreadable."), SessionFailed(IoError(desc)) => println!("{}", desc), SessionFailed(NetworkError) => println!("Network request failed."), SessionFailed(BufferError) => println!("An error occured while writing memory."), SessionFailed(DomError) => println!("Unable to parse DOM."), CacheInError => println!("No cached input available."), CacheOutError => println!("No cached result available."), InputError => println!("Couldn't open test input file."), DayError(reason) => println!("Errors with this Day: {}", reason), } }
use aoc2020::{Day, RunError, Session, SessionError}; use clap::Clap; #[clap(version = "0.1.0", author = "Daniel Boyle")] #[derive(Debug, Clone, Clap)] pub struct Config { #[clap(short = 'd', long = "day", default_value = "1")] pub day: i32, #[clap(short = 'a', long = "all")] pub all: bool, #[clap(short = 'o', long = "offline")] pub offline: bool, #[clap(short = 's', long = "session")] pub session: Option<String>, #[clap(short = 'i', long = "input")] pub input: Option<String>, #[clap(short = 'e', long = "examples")] pub examples: bool, #[clap(long = "accept")] pub accept: bool, #[clap(long = "validate")] pub validate: bool, #[clap(long = "clear-cache")] pub clear: bool, } fn main() { let config = Config::parse(); let days = aoc2020::DAYS; if config.all { for day in day
fn run_day(day: &Day, config: &Config) { if config.clear { println!("Clearing cache..."); day.clear_cache(); } if config.examples { println!("running examples for day {}...", day.index); match day.run_with_examples() { Ok(_) => (), Err(e) => {print_error(e)}, } } else if !config.offline && config.input.is_none() { let session = if let Some(session) = &config.session { Session::new(&session) } else { Session::from_file("session.txt") }; if let Ok(session) = session { let output = day.cache_input_and_run(&session); match output { Ok(result) => { let next_output = if config.validate { day.validate_result(result) } else if config.accept { day.cache_result(result) } else { Ok(()) }; if let Err(e) = next_output { print_error(e); } } Err(e) => print_error(e), } } else { println!("Please create a session.txt file or provide --session on the command line."); } } else if config.input.is_none() { let output = day.run_with_cached_input(); match output { Ok(result) => { let next_output = if config.validate { day.validate_result(result) } else if config.accept { day.cache_result(result) } else { Ok(()) }; if let Err(e) = next_output { print_error(e); } } Err(e) => print_error(e), } } else { let input_filename = config.input.as_ref().expect("unreachable"); let output = day.run_with_test_input(&input_filename); if let Err(e) = output { print_error(e); } } } fn print_error(err: RunError) { use RunError::*; use SessionError::*; match err { SessionFailed(TokenFormat) => println!("Session token was unreadable."), SessionFailed(IoError(desc)) => println!("{}", desc), SessionFailed(NetworkError) => println!("Network request failed."), SessionFailed(BufferError) => println!("An error occured while writing memory."), SessionFailed(DomError) => println!("Unable to parse DOM."), CacheInError => println!("No cached input available."), CacheOutError => println!("No cached result available."), InputError => println!("Couldn't open test input file."), DayError(reason) => println!("Errors with this Day: {}", reason), } }
s { run_day(day, &config); } } else { let index = (config.day - 1) as usize; if index < days.len() { let day = &days[index]; run_day(day, &config); } else { println!("Invalid day selection: {}", config.day); } } }
function_block-function_prefixed
[ { "content": "pub fn cache_input_for_day(day: i32, session: &Session) -> Result<Vec<String>, SessionError> {\n\n let file_path = input_cache_path(day);\n\n let file = fs::OpenOptions::new()\n\n .read(true)\n\n .write(false)\n\n .create(false)\n\n .open(&file_path);\n\n let l...
Rust
src/sdk/metrics/mod.rs
zoidbergwill/opentelemetry-rust
30e65af8942c5c7a635c86bd7a02001b833030d5
use crate::api; use crate::exporter::metrics::prometheus; use std::borrow::Cow; use std::collections::HashMap; pub type LabelSet = HashMap<Cow<'static, str>, Cow<'static, str>>; impl api::LabelSet for LabelSet {} #[allow(missing_debug_implementations)] pub struct Meter { registry: &'static prometheus::Registry, component: &'static str, } impl Meter { pub fn new(component: &'static str) -> Self { Meter { registry: prometheus::default_registry(), component, } } fn build_opts(&self, name: String, description: String) -> prometheus::Opts { let help = if !description.is_empty() { description } else { format!("{} metric", name) }; prometheus::Opts::new(name, help).namespace(format!("{}_", self.component)) } } impl api::Meter for Meter { type LabelSet = LabelSet; type I64Counter = prometheus::IntCounterVec; type F64Counter = prometheus::CounterVec; type I64Gauge = prometheus::IntGaugeVec; type F64Gauge = prometheus::GaugeVec; type I64Measure = prometheus::IntMeasure; type F64Measure = prometheus::HistogramVec; fn labels(&self, key_values: Vec<api::KeyValue>) -> Self::LabelSet { let mut label_set: Self::LabelSet = Default::default(); for api::KeyValue { key, value } in key_values.into_iter() { label_set.insert(key.into(), value.into()); } label_set } fn new_i64_counter<S: Into<String>>( &self, name: S, opts: api::MetricOptions, ) -> Self::I64Counter { let api::MetricOptions { description, unit: _unit, keys, alternate: _alternative, } = opts; let counter_opts = self.build_opts(name.into(), description); let labels = prometheus::convert_labels(&keys); let counter = prometheus::IntCounterVec::new(counter_opts, &labels).unwrap(); self.registry.register(Box::new(counter.clone())).unwrap(); counter } fn new_f64_counter<S: Into<String>>( &self, name: S, opts: api::MetricOptions, ) -> Self::F64Counter { let api::MetricOptions { description, unit: _unit, keys, alternate: _alternative, } = opts; let counter_opts = self.build_opts(name.into(), description); let labels = prometheus::convert_labels(&keys); let counter = prometheus::CounterVec::new(counter_opts, &labels).unwrap(); self.registry.register(Box::new(counter.clone())).unwrap(); counter } fn new_i64_gauge<S: Into<String>>(&self, name: S, opts: api::MetricOptions) -> Self::I64Gauge { let api::MetricOptions { description, unit: _unit, keys, alternate: _alternative, } = opts; let gauge_opts = self.build_opts(name.into(), description); let labels = prometheus::convert_labels(&keys); let gauge = prometheus::IntGaugeVec::new(gauge_opts, &labels).unwrap(); self.registry.register(Box::new(gauge.clone())).unwrap(); gauge } fn new_f64_gauge<S: Into<String>>(&self, name: S, opts: api::MetricOptions) -> Self::F64Gauge { let api::MetricOptions { description, unit: _unit, keys, alternate: _alternative, } = opts; let gauge_opts = self.build_opts(name.into(), description); let labels = prometheus::convert_labels(&keys); let gauge = prometheus::GaugeVec::new(gauge_opts, &labels).unwrap(); self.registry.register(Box::new(gauge.clone())).unwrap(); gauge } fn new_i64_measure<S: Into<String>>( &self, name: S, opts: api::MetricOptions, ) -> Self::I64Measure { let api::MetricOptions { description, unit: _unit, keys, alternate: _alternative, } = opts; let common_opts = self.build_opts(name.into(), description); let labels = prometheus::convert_labels(&keys); let histogram_opts = prometheus::HistogramOpts::from(common_opts); let histogram = prometheus::HistogramVec::new(histogram_opts, &labels).unwrap(); self.registry.register(Box::new(histogram.clone())).unwrap(); prometheus::IntMeasure::new(histogram) } fn new_f64_measure<S: Into<String>>( &self, name: S, opts: api::MetricOptions, ) -> Self::F64Measure { let api::MetricOptions { description, unit: _unit, keys, alternate: _alternative, } = opts; let common_opts = self.build_opts(name.into(), description); let labels = prometheus::convert_labels(&keys); let histogram_opts = prometheus::HistogramOpts::from(common_opts); let histogram = prometheus::HistogramVec::new(histogram_opts, &labels).unwrap(); self.registry.register(Box::new(histogram.clone())).unwrap(); histogram } fn record_batch<M: IntoIterator<Item = api::Measurement<Self::LabelSet>>>( &self, label_set: &Self::LabelSet, measurements: M, ) { for measure in measurements.into_iter() { let instrument = measure.instrument(); instrument.record_one(measure.into_value(), &label_set); } } }
use crate::api; use crate::exporter::metrics::prometheus; use std::borrow::Cow; use std::collections::HashMap; pub type LabelSet = HashMap<Cow<'static, str>, Cow<'static, str>>; impl api::LabelSet for LabelSet {} #[allow(missing_debug_implementations)] pub struct Meter { registry: &'static prometheus::Registry, component: &'static str, } impl Meter { pub fn new(component: &'static str) -> Self { Meter { registry: prometheus::default_registry(), component, } } fn build_opts(&self, name: String, description: String) -> prometheus::Opts { let help = if !description.is_empty() { description } else { format!("{} metric", name) }; prometheus::Opts::new(name, help).namespace(format!("{}_", self.component)) } } impl api::Meter for Meter { type LabelSet = LabelSet; type I64Counter = prometheus::IntCounterVec; type F64Counter = prometheus::CounterVec; type I64Gauge = prometheus::IntGaugeVec; type F64Gauge = prometheus::GaugeVec; type I64Measure = prometheus::IntMeasure; type F64Measure = prometheus::HistogramVec; fn labels(&self, key_values: Vec<api::KeyValue>) -> Self::LabelSet { let mut label_set: Self::LabelSet = Default::default(); for api::KeyValue { key, value } in key_values.into_iter() { label_set.insert(key.into(), value.into()); } label_set } fn new_i64_counter<S: Into<String>>( &self, name: S, opts: api::MetricOptions, ) -> Self::I64Counter { let api::MetricOptions { description, unit: _unit, keys, alternate: _alternative, } = opts; let counter_opts = self.build_opts(name.into(), description); let labels = prometheus::convert_labels(&keys); let counter = prometheus::IntCounterVec::new(counter_opts, &labels).unwrap(); self.registry.register(Box::new(counter.clone())).unwrap(); counter }
fn new_i64_gauge<S: Into<String>>(&self, name: S, opts: api::MetricOptions) -> Self::I64Gauge { let api::MetricOptions { description, unit: _unit, keys, alternate: _alternative, } = opts; let gauge_opts = self.build_opts(name.into(), description); let labels = prometheus::convert_labels(&keys); let gauge = prometheus::IntGaugeVec::new(gauge_opts, &labels).unwrap(); self.registry.register(Box::new(gauge.clone())).unwrap(); gauge } fn new_f64_gauge<S: Into<String>>(&self, name: S, opts: api::MetricOptions) -> Self::F64Gauge { let api::MetricOptions { description, unit: _unit, keys, alternate: _alternative, } = opts; let gauge_opts = self.build_opts(name.into(), description); let labels = prometheus::convert_labels(&keys); let gauge = prometheus::GaugeVec::new(gauge_opts, &labels).unwrap(); self.registry.register(Box::new(gauge.clone())).unwrap(); gauge } fn new_i64_measure<S: Into<String>>( &self, name: S, opts: api::MetricOptions, ) -> Self::I64Measure { let api::MetricOptions { description, unit: _unit, keys, alternate: _alternative, } = opts; let common_opts = self.build_opts(name.into(), description); let labels = prometheus::convert_labels(&keys); let histogram_opts = prometheus::HistogramOpts::from(common_opts); let histogram = prometheus::HistogramVec::new(histogram_opts, &labels).unwrap(); self.registry.register(Box::new(histogram.clone())).unwrap(); prometheus::IntMeasure::new(histogram) } fn new_f64_measure<S: Into<String>>( &self, name: S, opts: api::MetricOptions, ) -> Self::F64Measure { let api::MetricOptions { description, unit: _unit, keys, alternate: _alternative, } = opts; let common_opts = self.build_opts(name.into(), description); let labels = prometheus::convert_labels(&keys); let histogram_opts = prometheus::HistogramOpts::from(common_opts); let histogram = prometheus::HistogramVec::new(histogram_opts, &labels).unwrap(); self.registry.register(Box::new(histogram.clone())).unwrap(); histogram } fn record_batch<M: IntoIterator<Item = api::Measurement<Self::LabelSet>>>( &self, label_set: &Self::LabelSet, measurements: M, ) { for measure in measurements.into_iter() { let instrument = measure.instrument(); instrument.record_one(measure.into_value(), &label_set); } } }
fn new_f64_counter<S: Into<String>>( &self, name: S, opts: api::MetricOptions, ) -> Self::F64Counter { let api::MetricOptions { description, unit: _unit, keys, alternate: _alternative, } = opts; let counter_opts = self.build_opts(name.into(), description); let labels = prometheus::convert_labels(&keys); let counter = prometheus::CounterVec::new(counter_opts, &labels).unwrap(); self.registry.register(Box::new(counter.clone())).unwrap(); counter }
function_block-full_function
[ { "content": "/// Convert from `sdk::LabelSet` to `prometheus`' label format.\n\nfn convert_label_set(label_set: &sdk::LabelSet) -> HashMap<&str, &str> {\n\n label_set\n\n .iter()\n\n .map(|(key, value)| (key.as_ref(), value.as_ref()))\n\n .collect()\n\n}\n\n\n\n/// Convert from list of ...
Rust
examples/swdump.rs
a1ien/jaylink
09de031fb4cc3f76f24e4a361977ec6efb6838bd
use jaylink::{Interface, JayLink, SpeedConfig}; use log::trace; use std::{cmp, fmt}; use structopt::StructOpt; const IDLE_CYCLES_BEFORE_ACCESS: usize = 2; #[derive(StructOpt)] struct Opts { #[structopt(long = "serial")] serial: Option<String>, #[structopt(long = "speed")] speed: Option<u16>, } fn main() { env_logger::init(); let opts = Opts::from_args(); if let Err(e) = run(opts) { eprintln!("error: {}", e); std::process::exit(1); } } enum Port { Debug, #[allow(unused)] Access, } #[derive(Debug)] enum SwdError { Probe(jaylink::Error), Fault, NoResponse, Parity, } impl From<jaylink::Error> for SwdError { fn from(e: jaylink::Error) -> Self { SwdError::Probe(e) } } impl fmt::Display for SwdError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { SwdError::Probe(e) => e.fmt(f), SwdError::Fault => f.write_str("target returned FAULT response"), SwdError::NoResponse => f.write_str("no response from target chip"), SwdError::Parity => f.write_str("SWD parity error"), } } } enum Ack { Ok, Wait, Fault, } fn parse_ack(sl: &[bool]) -> Option<Ack> { assert_eq!(sl.len(), 3); trace!("ACK: {:?}", sl); Some(match (sl[0], sl[1], sl[2]) { (true, false, false) => Ack::Ok, (false, true, false) => Ack::Wait, (false, false, true) => Ack::Fault, _ => return None, }) } trait JayLinkExt { fn swj_seq(&mut self) -> jaylink::Result<()>; fn raw_read(&mut self, port: Port, a: u32) -> Result<u32, SwdError>; fn raw_write(&mut self, port: Port, a: u32, value: u32) -> Result<(), SwdError>; } impl JayLinkExt for JayLink { fn swj_seq(&mut self) -> jaylink::Result<()> { let mut dir = Vec::new(); let mut swdio = Vec::new(); swdio.resize(64, true); dir.resize(64, true); let mut seq = 0xE79E; for _ in 0..16 { swdio.push(seq & 0b1 != 0); seq >>= 1; } dir.resize(dir.len() + 16, true); swdio.resize(swdio.len() + 64, true); dir.resize(dir.len() + 64, true); swdio.resize(swdio.len() + 10, false); dir.resize(dir.len() + 10, true); self.swd_io(dir, swdio)?; Ok(()) } fn raw_read(&mut self, port: Port, a: u32) -> Result<u32, SwdError> { let mut dir = Vec::new(); let mut swdio = Vec::new(); swdio.resize(swdio.len() + IDLE_CYCLES_BEFORE_ACCESS, false); dir.resize(dir.len() + IDLE_CYCLES_BEFORE_ACCESS, true); let a2 = a & 0b0100 != 0; let a3 = a & 0b1000 != 0; swdio.push(true); swdio.push(match port { Port::Debug => false, Port::Access => true, }); swdio.push(true); swdio.push(a2); swdio.push(a3); let even_parity = (swdio.iter().filter(|b| **b).count() - 1) % 2 != 0; swdio.push(even_parity); swdio.push(false); swdio.push(true); dir.resize(dir.len() + 8, true); swdio.push(false); swdio.push(false); swdio.push(false); swdio.resize(swdio.len() + 32, false); swdio.push(false); dir.resize(dir.len() + 3 + 33, false); loop { let mut response = self.swd_io(dir.iter().copied(), swdio.iter().copied())?; response.split_off(IDLE_CYCLES_BEFORE_ACCESS + 8); trace!("response: {:?}", response); let ack = response.split_off(3).collect::<Vec<_>>(); let value = response.split_off(32).collect::<Vec<_>>(); let parity = response.next().unwrap(); if let Some(ack) = parse_ack(&ack) { match ack { Ack::Ok => { let value = value .iter() .fold(0u32, |accum, bit| (accum >> 1) | (u32::from(*bit) << 31)); trace!("value=0x{:08X}, parity={:?}", value, parity); let expected_parity = value.count_ones() % 2 != 0; if expected_parity == parity { return Ok(value); } else { return Err(SwdError::Parity); } } Ack::Wait => { trace!("WAIT - retrying read access"); continue; } Ack::Fault => { return Err(SwdError::Fault); } } } return Err(SwdError::NoResponse); } } fn raw_write(&mut self, port: Port, a: u32, value: u32) -> Result<(), SwdError> { let mut dir = Vec::new(); let mut swdio = Vec::new(); swdio.resize(swdio.len() + IDLE_CYCLES_BEFORE_ACCESS, false); dir.resize(dir.len() + IDLE_CYCLES_BEFORE_ACCESS, true); let a2 = a & 0b0100 != 0; let a3 = a & 0b1000 != 0; swdio.push(true); swdio.push(match port { Port::Debug => false, Port::Access => true, }); swdio.push(false); swdio.push(a2); swdio.push(a3); let even_parity = (swdio.iter().filter(|b| **b).count() - 1) % 2 != 0; swdio.push(even_parity); swdio.push(false); swdio.push(true); dir.resize(dir.len() + 8, true); swdio.push(false); swdio.push(false); swdio.push(false); dir.resize(dir.len() + 3, false); swdio.push(false); swdio.push(false); dir.resize(dir.len() + 2, false); { let mut value = value; for _ in 0..32 { swdio.push(value & 1 != 0); value >>= 1; } swdio.push(value.count_ones() % 2 != 0); dir.resize(dir.len() + 33, true); } loop { let mut response = self.swd_io(dir.iter().copied(), swdio.iter().copied())?; response.split_off(IDLE_CYCLES_BEFORE_ACCESS + 8); trace!("response: {:?}", response); let ack = response.split_off(3).collect::<Vec<_>>(); if let Some(ack) = parse_ack(&ack) { match ack { Ack::Ok => { return Ok(()); } Ack::Wait => { trace!("WAIT - retrying write access"); continue; } Ack::Fault => { return Err(SwdError::Fault); } } } return Err(SwdError::NoResponse); } } } fn run(opts: Opts) -> Result<(), SwdError> { let mut probe = JayLink::open_by_serial(opts.serial.as_deref())?; probe.select_interface(Interface::Swd)?; let speed = opts .speed .map(|khz| SpeedConfig::khz(cmp::min(khz, 0xfffe)).unwrap()) .unwrap_or(probe.read_speeds()?.max_speed_config()); println!("speed configuration: {}", speed); probe.set_speed(speed)?; probe.swj_seq()?; let dpidr = probe.raw_read(Port::Debug, 0b0000)?; println!("DPIDR=0x{:08X}", dpidr); probe.raw_write(Port::Debug, 0b0000, 0x1e)?; let errmask = 0b10100010; let ctrl_stat = probe.raw_read(Port::Debug, 0b0100)?; println!("CTRL/STAT=0x{:08X}", ctrl_stat); if ctrl_stat & errmask != 0 { eprintln!("errors bits set in CTRL/STAT"); } Ok(()) }
use jaylink::{Interface, JayLink, SpeedConfig}; use log::trace; use std::{cmp, fmt}; use structopt::StructOpt; const IDLE_CYCLES_BEFORE_ACCESS: usize = 2; #[derive(StructOpt)] struct Opts { #[structopt(long = "serial")] serial: Option<String>, #[structopt(long = "speed")] speed: Option<u16>, } fn main() { env_logger::init(); let opts = Opts::from_args(); if let Err(e) = run(opts) { eprintln!("error: {}", e); std::process::exit(1); } } enum Port { Debug, #[allow(unused)] Access, } #[derive(Debug)] enum SwdError { Probe(jaylink::Error), Fault, NoResponse, Parity, } impl From<jaylink::Error> for SwdError { fn from(e: jaylink::Error) -> Self { SwdError::Probe(e) } } impl fmt::Display for SwdError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { SwdError::Probe(e) => e.fmt(f), SwdError::Fault => f.write_str("target returned FAULT response"), SwdError::NoResponse => f.write_str("no response from target chip"), SwdError::Parity => f.write_str("SWD parity error"), } } } enum Ack { Ok, Wait, Fault, } fn parse_ack(sl: &[bool]) -> Option<Ack> { assert_eq!(sl.len(), 3); trace!("ACK: {:?}", sl);
} trait JayLinkExt { fn swj_seq(&mut self) -> jaylink::Result<()>; fn raw_read(&mut self, port: Port, a: u32) -> Result<u32, SwdError>; fn raw_write(&mut self, port: Port, a: u32, value: u32) -> Result<(), SwdError>; } impl JayLinkExt for JayLink { fn swj_seq(&mut self) -> jaylink::Result<()> { let mut dir = Vec::new(); let mut swdio = Vec::new(); swdio.resize(64, true); dir.resize(64, true); let mut seq = 0xE79E; for _ in 0..16 { swdio.push(seq & 0b1 != 0); seq >>= 1; } dir.resize(dir.len() + 16, true); swdio.resize(swdio.len() + 64, true); dir.resize(dir.len() + 64, true); swdio.resize(swdio.len() + 10, false); dir.resize(dir.len() + 10, true); self.swd_io(dir, swdio)?; Ok(()) } fn raw_read(&mut self, port: Port, a: u32) -> Result<u32, SwdError> { let mut dir = Vec::new(); let mut swdio = Vec::new(); swdio.resize(swdio.len() + IDLE_CYCLES_BEFORE_ACCESS, false); dir.resize(dir.len() + IDLE_CYCLES_BEFORE_ACCESS, true); let a2 = a & 0b0100 != 0; let a3 = a & 0b1000 != 0; swdio.push(true); swdio.push(match port { Port::Debug => false, Port::Access => true, }); swdio.push(true); swdio.push(a2); swdio.push(a3); let even_parity = (swdio.iter().filter(|b| **b).count() - 1) % 2 != 0; swdio.push(even_parity); swdio.push(false); swdio.push(true); dir.resize(dir.len() + 8, true); swdio.push(false); swdio.push(false); swdio.push(false); swdio.resize(swdio.len() + 32, false); swdio.push(false); dir.resize(dir.len() + 3 + 33, false); loop { let mut response = self.swd_io(dir.iter().copied(), swdio.iter().copied())?; response.split_off(IDLE_CYCLES_BEFORE_ACCESS + 8); trace!("response: {:?}", response); let ack = response.split_off(3).collect::<Vec<_>>(); let value = response.split_off(32).collect::<Vec<_>>(); let parity = response.next().unwrap(); if let Some(ack) = parse_ack(&ack) { match ack { Ack::Ok => { let value = value .iter() .fold(0u32, |accum, bit| (accum >> 1) | (u32::from(*bit) << 31)); trace!("value=0x{:08X}, parity={:?}", value, parity); let expected_parity = value.count_ones() % 2 != 0; if expected_parity == parity { return Ok(value); } else { return Err(SwdError::Parity); } } Ack::Wait => { trace!("WAIT - retrying read access"); continue; } Ack::Fault => { return Err(SwdError::Fault); } } } return Err(SwdError::NoResponse); } } fn raw_write(&mut self, port: Port, a: u32, value: u32) -> Result<(), SwdError> { let mut dir = Vec::new(); let mut swdio = Vec::new(); swdio.resize(swdio.len() + IDLE_CYCLES_BEFORE_ACCESS, false); dir.resize(dir.len() + IDLE_CYCLES_BEFORE_ACCESS, true); let a2 = a & 0b0100 != 0; let a3 = a & 0b1000 != 0; swdio.push(true); swdio.push(match port { Port::Debug => false, Port::Access => true, }); swdio.push(false); swdio.push(a2); swdio.push(a3); let even_parity = (swdio.iter().filter(|b| **b).count() - 1) % 2 != 0; swdio.push(even_parity); swdio.push(false); swdio.push(true); dir.resize(dir.len() + 8, true); swdio.push(false); swdio.push(false); swdio.push(false); dir.resize(dir.len() + 3, false); swdio.push(false); swdio.push(false); dir.resize(dir.len() + 2, false); { let mut value = value; for _ in 0..32 { swdio.push(value & 1 != 0); value >>= 1; } swdio.push(value.count_ones() % 2 != 0); dir.resize(dir.len() + 33, true); } loop { let mut response = self.swd_io(dir.iter().copied(), swdio.iter().copied())?; response.split_off(IDLE_CYCLES_BEFORE_ACCESS + 8); trace!("response: {:?}", response); let ack = response.split_off(3).collect::<Vec<_>>(); if let Some(ack) = parse_ack(&ack) { match ack { Ack::Ok => { return Ok(()); } Ack::Wait => { trace!("WAIT - retrying write access"); continue; } Ack::Fault => { return Err(SwdError::Fault); } } } return Err(SwdError::NoResponse); } } } fn run(opts: Opts) -> Result<(), SwdError> { let mut probe = JayLink::open_by_serial(opts.serial.as_deref())?; probe.select_interface(Interface::Swd)?; let speed = opts .speed .map(|khz| SpeedConfig::khz(cmp::min(khz, 0xfffe)).unwrap()) .unwrap_or(probe.read_speeds()?.max_speed_config()); println!("speed configuration: {}", speed); probe.set_speed(speed)?; probe.swj_seq()?; let dpidr = probe.raw_read(Port::Debug, 0b0000)?; println!("DPIDR=0x{:08X}", dpidr); probe.raw_write(Port::Debug, 0b0000, 0x1e)?; let errmask = 0b10100010; let ctrl_stat = probe.raw_read(Port::Debug, 0b0100)?; println!("CTRL/STAT=0x{:08X}", ctrl_stat); if ctrl_stat & errmask != 0 { eprintln!("errors bits set in CTRL/STAT"); } Ok(()) }
Some(match (sl[0], sl[1], sl[2]) { (true, false, false) => Ack::Ok, (false, true, false) => Ack::Wait, (false, false, true) => Ack::Fault, _ => return None, })
call_expression
[ { "content": "fn to_io_error(error: Error) -> io::Error {\n\n io::Error::new(io::ErrorKind::Other, error)\n\n}\n\n\n\nimpl<'a> Read for SwoStream<'a> {\n\n fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {\n\n if self.buf.position() == self.buf.get_ref().len() as u64 {\n\n // At ...
Rust
rust/arrow/benches/buffer_bit_ops.rs
jovany-wang/arrow
1f30466ac7042354de35cc69fd49ced1acd54b38
#[macro_use] extern crate criterion; use criterion::Criterion; extern crate arrow; use arrow::buffer::{Buffer, MutableBuffer}; use arrow::error::ArrowError; use arrow::error::Result; #[cfg(feature = "simd")] use arrow::util::bit_util; use std::borrow::BorrowMut; #[cfg(feature = "simd")] use std::slice::{from_raw_parts, from_raw_parts_mut}; fn create_buffer(size: usize) -> Buffer { let mut result = MutableBuffer::new(size).with_bitset(size, false); for i in 0..size { result.data_mut()[i] = 0b01010101; } result.freeze() } fn bench_and_current_impl(left: &Buffer, right: &Buffer) { criterion::black_box((left & right).unwrap()); } #[cfg(all(any(target_arch = "x86", target_arch = "x86_64"), feature = "simd"))] fn bench_and_packed_simd_chunked_exact(left: &Buffer, right: &Buffer) { criterion::black_box( bitwise_bin_op_simd_helper(&left, &right, |a, b| a & b).unwrap(), ); } fn bench_and_chunked_exact(left: &Buffer, right: &Buffer) { criterion::black_box( bitwise_bin_op_autovec_chunked_helper(&left, &right, |a, b| a & b).unwrap(), ); } fn bench_and_autovec(left: &Buffer, right: &Buffer) { criterion::black_box( bitwise_bin_op_autovec_helper(&left, &right, |a, b| a & b).unwrap(), ); } const AUTOVEC_LANES: usize = 64; fn bitwise_bin_op_autovec_chunked_helper<F>( left: &Buffer, right: &Buffer, op: F, ) -> Result<Buffer> where F: Fn(u8, u8) -> u8, { if left.len() != right.len() { return Err(ArrowError::ComputeError( "Buffers must be the same size to apply Bitwise AND.".to_string(), )); } let mut result = MutableBuffer::new(left.len()).with_bitset(left.len(), false); let mut left_chunks = left.data().chunks_exact(AUTOVEC_LANES); let mut right_chunks = right.data().chunks_exact(AUTOVEC_LANES); let mut result_chunks = result.data_mut().chunks_exact_mut(AUTOVEC_LANES); result_chunks .borrow_mut() .zip(left_chunks.borrow_mut().zip(right_chunks.borrow_mut())) .for_each(|(res, (left, right))| { for i in 0..AUTOVEC_LANES { res[i] = op(left[i], right[i]); } }); result_chunks .into_remainder() .iter_mut() .zip( left_chunks .remainder() .iter() .zip(right_chunks.remainder().iter()), ) .for_each(|(res, (left, right))| { *res = op(*left, *right); }); Ok(result.freeze()) } fn bitwise_bin_op_autovec_helper<F>( left: &Buffer, right: &Buffer, op: F, ) -> Result<Buffer> where F: Fn(u8, u8) -> u8, { if left.len() != right.len() { return Err(ArrowError::ComputeError( "Buffers must be the same size to apply Bitwise AND.".to_string(), )); } let mut result = MutableBuffer::new(left.len()).with_bitset(left.len(), false); result .data_mut() .iter_mut() .zip(left.data().iter().zip(right.data().iter())) .for_each(|(res, (left, right))| { *res = op(*left, *right); }); Ok(result.freeze()) } #[cfg(all(any(target_arch = "x86", target_arch = "x86_64"), feature = "simd"))] fn bitwise_bin_op_simd_helper<F>(left: &Buffer, right: &Buffer, op: F) -> Result<Buffer> where F: Fn(packed_simd::u8x64, packed_simd::u8x64) -> packed_simd::u8x64, { if left.len() != right.len() { return Err(ArrowError::ComputeError( "Buffers must be the same size to apply Bitwise AND.".to_string(), )); } let mut result = MutableBuffer::new(left.len()).with_bitset(left.len(), false); let lanes = packed_simd::u8x64::lanes(); for i in (0..left.len()).step_by(lanes) { let left_data = unsafe { from_raw_parts(left.raw_data().add(i), lanes) }; let right_data = unsafe { from_raw_parts(right.raw_data().add(i), lanes) }; let result_slice: &mut [u8] = unsafe { from_raw_parts_mut((result.data_mut().as_mut_ptr() as *mut u8).add(i), lanes) }; unsafe { bit_util::bitwise_bin_op_simd(&left_data, &right_data, result_slice, &op) }; } Ok(result.freeze()) } fn bit_ops_benchmark(c: &mut Criterion) { let left = create_buffer(512); let right = create_buffer(512); c.bench_function("buffer_bit_ops and current impl", |b| { b.iter(|| bench_and_current_impl(&left, &right)) }); #[cfg(all(any(target_arch = "x86", target_arch = "x86_64"), feature = "simd"))] c.bench_function("buffer_bit_ops and packed simd", |b| { b.iter(|| bench_and_packed_simd_chunked_exact(&left, &right)) }); c.bench_function("buffer_bit_ops and chunked autovec", |b| { b.iter(|| bench_and_chunked_exact(&left, &right)) }); c.bench_function("buffer_bit_ops and autovec", |b| { b.iter(|| bench_and_autovec(&left, &right)) }); } criterion_group!(benches, bit_ops_benchmark); criterion_main!(benches);
#[macro_use] extern crate criterion; use criterion::Criterion; extern crate arrow; use arrow::buffer::{Buffer, MutableBuffer}; use arrow::error::ArrowError; use arrow::error::Result; #[cfg(feature = "simd")] use arrow::util::bit_util; use std::borrow::BorrowMut; #[cfg(feature = "simd")] use std::slice::{from_raw_parts, from_raw_parts_mut}; fn create_buffer(size: usize) -> Buffer { let mut result = MutableBuffer::new(size).with_bitset(size, false); for i in 0..size { result.data_mut()[i] = 0b01010101; } result.freeze() } fn bench_and_current_impl(left: &Buffer, right: &Buffer) { criterion::black_box((left & right).unwrap()); } #[cfg(all(any(target_arch = "x86", target_arch = "x86_64"), feature = "simd"))] fn bench_and_packed_simd_chunked_exact(left: &Buffer, right: &Buffer) { criterion::black_box( bitwise_bin_op_simd_helper(&left, &right, |a, b| a & b).unwrap(), ); } fn bench_and_chunked_exact(left: &Buffer, right: &Buffer) { criterion::black_box( bitwise_bin_op_autovec_chunked_helper(&left, &right, |a, b| a & b).unwrap(), ); } fn bench_and_autovec(left: &Buffer, right: &Buffer) { criterion::black_box( bitwise_bin_op_autovec_helper(&left, &right, |a, b| a & b).unwrap(), ); } const AUTOVEC_LANES: usize = 64; fn bitwise_bin_op_autovec_chunked_helper<F>( left: &Buffer, right: &Buffer, op: F, ) -> Result<Buffer> where F: Fn(u8, u8) -> u8, { if left.len() != right.len() { return Err(ArrowError::ComputeError( "Buffers must be the same size to apply Bitwise AND.".to_string(), )); } let mut result = MutableBuffer::new(left.len()).with_bitset(left.len(), false); let mut left_chunks = left.data().chunks_exact(AUTOVEC_LANES); let mut right_chunks = right.data().chunks_exact(AUTOVEC_LANES); let mut result_chunks = result.data_mut().chunks_exact_mut(AUTOVEC_LANES); result_chunks .borrow_mut() .zip(left_chunks.borrow_mut().zip(right_chunks.borrow_mut())) .for_each(|(res, (left, right))| { for i in 0..AUTOVEC_LANES { res[i] = op(left[i], right[i]); } }); result_chunks .into_remainder() .iter_mut() .zip( left_chunks .remainder() .iter() .zip(right_chunks.remainder().iter()), ) .for_each(|(res, (left, right))| { *res = op(*left, *right); }); Ok(result.freeze()) } fn bitwise_bin_op_autovec_helper<F>( left: &Buffer, right: &Buffer, op: F, ) -> Result<Buffer> where F: Fn(u8, u8) -> u8, { if left.len() != right.len() { return Err(ArrowError::ComputeError( "Buffers must be the same size to apply Bitwise AND.".to_string(), )); } let mut result = MutableBuffer::new(left.len()).with_bitset(left.len(), false); result .data_mut() .iter_mut() .
#[cfg(all(any(target_arch = "x86", target_arch = "x86_64"), feature = "simd"))] fn bitwise_bin_op_simd_helper<F>(left: &Buffer, right: &Buffer, op: F) -> Result<Buffer> where F: Fn(packed_simd::u8x64, packed_simd::u8x64) -> packed_simd::u8x64, { if left.len() != right.len() { return Err(ArrowError::ComputeError( "Buffers must be the same size to apply Bitwise AND.".to_string(), )); } let mut result = MutableBuffer::new(left.len()).with_bitset(left.len(), false); let lanes = packed_simd::u8x64::lanes(); for i in (0..left.len()).step_by(lanes) { let left_data = unsafe { from_raw_parts(left.raw_data().add(i), lanes) }; let right_data = unsafe { from_raw_parts(right.raw_data().add(i), lanes) }; let result_slice: &mut [u8] = unsafe { from_raw_parts_mut((result.data_mut().as_mut_ptr() as *mut u8).add(i), lanes) }; unsafe { bit_util::bitwise_bin_op_simd(&left_data, &right_data, result_slice, &op) }; } Ok(result.freeze()) } fn bit_ops_benchmark(c: &mut Criterion) { let left = create_buffer(512); let right = create_buffer(512); c.bench_function("buffer_bit_ops and current impl", |b| { b.iter(|| bench_and_current_impl(&left, &right)) }); #[cfg(all(any(target_arch = "x86", target_arch = "x86_64"), feature = "simd"))] c.bench_function("buffer_bit_ops and packed simd", |b| { b.iter(|| bench_and_packed_simd_chunked_exact(&left, &right)) }); c.bench_function("buffer_bit_ops and chunked autovec", |b| { b.iter(|| bench_and_chunked_exact(&left, &right)) }); c.bench_function("buffer_bit_ops and autovec", |b| { b.iter(|| bench_and_autovec(&left, &right)) }); } criterion_group!(benches, bit_ops_benchmark); criterion_main!(benches);
zip(left.data().iter().zip(right.data().iter())) .for_each(|(res, (left, right))| { *res = op(*left, *right); }); Ok(result.freeze()) }
function_block-function_prefix_line
[]
Rust
src/main.rs
MichalGniadek/roguelike-tutorial-2021
69b1b7bac0ed939a25f06cdcaf791fe841a9e197
#![feature(iter_intersperse)] #![feature(option_result_contains)] mod bundles; mod dungeon_crawl; mod world_generation; mod world_map; use bevy::{app::AppExit, prelude::*}; use dungeon_crawl::TurnState; use world_map::Grid; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum AppState { MainMenu, WorldGeneration, DungeonCrawlEnter, DungeonCrawl(TurnState), DungeonCrawlExitToMenu, DungeonCrawlDescend, } #[cfg_attr(target_arch = "wasm32", global_allocator)] #[cfg(target_arch = "wasm32")] static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT; pub struct UiCamera; fn main() { #[cfg(target_arch = "wasm32")] console_error_panic_hook::set_once(); let mut app = App::build(); app.insert_resource(ClearColor(Color::hex("171717").unwrap())); app.insert_resource(WindowDescriptor { title: String::from("Roguelike"), #[cfg(target_arch = "wasm32")] canvas: Some(String::from("#canv")), ..Default::default() }); app.add_plugins(DefaultPlugins); app.insert_resource(Grid { cell_size: IVec2::new(512, 512), }) .add_startup_system( (|mut commands: Commands| { let mut orto = OrthographicCameraBundle::new_2d(); orto.orthographic_projection.scale = 8.0; commands.spawn_bundle(orto); commands .spawn_bundle(UiCameraBundle::default()) .insert(UiCamera); }) .system(), ); #[cfg(target_arch = "wasm32")] app.add_plugin(bevy_webgl2::WebGL2Plugin); app.add_state(AppState::MainMenu) .add_system_set( SystemSet::on_enter(AppState::MainMenu).with_system(main_menu_ui_create.system()), ) .add_system_set( SystemSet::on_update(AppState::MainMenu).with_system(main_menu_interaction.system()), ) .add_system_set( SystemSet::on_exit(AppState::MainMenu).with_system(main_menu_cleanup.system()), ) .add_plugin(dungeon_crawl::DungeonCrawlPlugin) .add_plugins(world_generation::WorldGenerationPlugins); app.run(); } pub struct MainMenuCanvas; pub enum MainMenuButton { Play, Quit, } pub fn main_menu_interaction( q: Query<(&Interaction, &MainMenuButton)>, mut app_state: ResMut<State<AppState>>, mut app_exit_events: EventWriter<AppExit>, ) { for (i, b) in q.iter() { match (i, b) { (Interaction::Clicked, MainMenuButton::Play) => { app_state.set(AppState::WorldGeneration).unwrap(); } (Interaction::Clicked, MainMenuButton::Quit) => app_exit_events.send(AppExit), _ => {} } } } pub fn main_menu_ui_create( mut commands: Commands, asset_server: Res<AssetServer>, mut materials: ResMut<Assets<ColorMaterial>>, ) { commands .spawn_bundle(NodeBundle { style: Style { size: Size::new(Val::Percent(100.0), Val::Percent(100.0)), align_items: AlignItems::Center, justify_content: JustifyContent::Center, flex_direction: FlexDirection::ColumnReverse, ..Default::default() }, material: materials.add(Color::hex("101010").unwrap().into()), ..Default::default() }) .insert(MainMenuCanvas) .with_children(|parent| { parent .spawn_bundle(ButtonBundle { style: Style { margin: Rect::all(Val::Px(50.0)), ..Default::default() }, material: materials.add(Color::hex("101010").unwrap().into()), ..Default::default() }) .insert(MainMenuButton::Play) .with_children(|parent| { parent.spawn_bundle(TextBundle { text: Text::with_section( "PLAY", TextStyle { font: asset_server.load("Roboto/Roboto-Regular.ttf"), font_size: 100.0, color: Color::WHITE, }, TextAlignment::default(), ), ..Default::default() }); }); parent .spawn_bundle(ButtonBundle { style: Style { margin: Rect::all(Val::Px(50.0)), ..Default::default() }, material: materials.add(Color::hex("101010").unwrap().into()), ..Default::default() }) .insert(MainMenuButton::Quit) .with_children(|parent| { parent.spawn_bundle(TextBundle { text: Text::with_section( "QUIT", TextStyle { font: asset_server.load("Roboto/Roboto-Regular.ttf"), font_size: 100.0, color: Color::WHITE, }, TextAlignment::default(), ), ..Default::default() }); }); }); } pub fn main_menu_cleanup(mut commands: Commands, q: Query<Entity, With<MainMenuCanvas>>) { commands.entity(q.single().unwrap()).despawn_recursive(); }
#![feature(iter_intersperse)] #![feature(option_result_contains)] mod bundles; mod dungeon_crawl; mod world_generation; mod world_map; use bevy::{app::AppExit, prelude::*}; use dungeon_crawl::TurnState; use world_map::Grid; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum AppState { MainMenu, WorldGeneration, DungeonCrawlEnter, DungeonCrawl(TurnState), DungeonCrawlExitToMenu, DungeonCrawlDescend, } #[cfg_attr(target_arch = "wasm32", global_allocator)] #[cfg(target_arch = "wasm32")] static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT; pub struct UiCamera; fn main() { #[cfg(target_arch = "wasm32")] console_error_panic_hook::set_once(); let mut app = App::build(); app.insert_resource(ClearColor(Color::hex("171717").unwrap())); app.insert_resource(WindowDescriptor { title: String::from("Roguelike"), #[cfg(target_arch = "wasm32")] canvas: Some(String::from("#canv")), ..Default::default() }); app.add_plugins(DefaultPlugins); app.insert_resource(Grid { cell_size: IVec2::new(512, 512), }) .add_startup_system( (|mut commands: Commands| { let mut orto = OrthographicCameraBundle::new
ttf"), font_size: 100.0, color: Color::WHITE, }, TextAlignment::default(), ), ..Default::default() }); }); parent .spawn_bundle(ButtonBundle { style: Style { margin: Rect::all(Val::Px(50.0)), ..Default::default() }, material: materials.add(Color::hex("101010").unwrap().into()), ..Default::default() }) .insert(MainMenuButton::Quit) .with_children(|parent| { parent.spawn_bundle(TextBundle { text: Text::with_section( "QUIT", TextStyle { font: asset_server.load("Roboto/Roboto-Regular.ttf"), font_size: 100.0, color: Color::WHITE, }, TextAlignment::default(), ), ..Default::default() }); }); }); } pub fn main_menu_cleanup(mut commands: Commands, q: Query<Entity, With<MainMenuCanvas>>) { commands.entity(q.single().unwrap()).despawn_recursive(); }
_2d(); orto.orthographic_projection.scale = 8.0; commands.spawn_bundle(orto); commands .spawn_bundle(UiCameraBundle::default()) .insert(UiCamera); }) .system(), ); #[cfg(target_arch = "wasm32")] app.add_plugin(bevy_webgl2::WebGL2Plugin); app.add_state(AppState::MainMenu) .add_system_set( SystemSet::on_enter(AppState::MainMenu).with_system(main_menu_ui_create.system()), ) .add_system_set( SystemSet::on_update(AppState::MainMenu).with_system(main_menu_interaction.system()), ) .add_system_set( SystemSet::on_exit(AppState::MainMenu).with_system(main_menu_cleanup.system()), ) .add_plugin(dungeon_crawl::DungeonCrawlPlugin) .add_plugins(world_generation::WorldGenerationPlugins); app.run(); } pub struct MainMenuCanvas; pub enum MainMenuButton { Play, Quit, } pub fn main_menu_interaction( q: Query<(&Interaction, &MainMenuButton)>, mut app_state: ResMut<State<AppState>>, mut app_exit_events: EventWriter<AppExit>, ) { for (i, b) in q.iter() { match (i, b) { (Interaction::Clicked, MainMenuButton::Play) => { app_state.set(AppState::WorldGeneration).unwrap(); } (Interaction::Clicked, MainMenuButton::Quit) => app_exit_events.send(AppExit), _ => {} } } } pub fn main_menu_ui_create( mut commands: Commands, asset_server: Res<AssetServer>, mut materials: ResMut<Assets<ColorMaterial>>, ) { commands .spawn_bundle(NodeBundle { style: Style { size: Size::new(Val::Percent(100.0), Val::Percent(100.0)), align_items: AlignItems::Center, justify_content: JustifyContent::Center, flex_direction: FlexDirection::ColumnReverse, ..Default::default() }, material: materials.add(Color::hex("101010").unwrap().into()), ..Default::default() }) .insert(MainMenuCanvas) .with_children(|parent| { parent .spawn_bundle(ButtonBundle { style: Style { margin: Rect::all(Val::Px(50.0)), ..Default::default() }, material: materials.add(Color::hex("101010").unwrap().into()), ..Default::default() }) .insert(MainMenuButton::Play) .with_children(|parent| { parent.spawn_bundle(TextBundle { text: Text::with_section( "PLAY", TextStyle { font: asset_server.load("Roboto/Roboto-Regular.
random
[ { "content": "pub fn cleanup_log_and_inventory(mut commands: Commands, inventory: Res<GameData>) {\n\n commands.insert_resource(Logs::default());\n\n for e in inventory.inventory.iter().filter_map(|i| *i) {\n\n commands.entity(e).despawn();\n\n }\n\n commands.insert_resource(GameData::default...
Rust
proxy/tests/discovery.rs
xiaods/conduit
bc16034fd6d3c88f20a4e7a6dc3f0baa0e3ce06f
mod support; use self::support::*; macro_rules! generate_tests { (server: $make_server:path, client: $make_client:path) => { use conduit_proxy_controller_grpc as pb; #[test] fn outbound_asks_controller_api() { let _ = env_logger::try_init(); let srv = $make_server().route("/", "hello").route("/bye", "bye").run(); let ctrl = controller::new() .destination("disco.test.svc.cluster.local", srv.addr) .run(); let proxy = proxy::new().controller(ctrl).outbound(srv).run(); let client = $make_client(proxy.outbound, "disco.test.svc.cluster.local"); assert_eq!(client.get("/"), "hello"); assert_eq!(client.get("/bye"), "bye"); } #[test] fn outbound_reconnects_if_controller_stream_ends() { let _ = env_logger::try_init(); let srv = $make_server().route("/recon", "nect").run(); let ctrl = controller::new() .destination_close("disco.test.svc.cluster.local") .destination("disco.test.svc.cluster.local", srv.addr) .run(); let proxy = proxy::new().controller(ctrl).outbound(srv).run(); let client = $make_client(proxy.outbound, "disco.test.svc.cluster.local"); assert_eq!(client.get("/recon"), "nect"); } #[test] #[cfg_attr(not(feature = "flaky_tests"), ignore)] fn outbound_destinations_reset_on_reconnect_followed_by_no_endpoints_exists() { outbound_destinations_reset_on_reconnect(move || { Some(controller::destination_exists_with_no_endpoints()) }) } #[test] #[cfg_attr(not(feature = "flaky_tests"), ignore)] fn outbound_destinations_reset_on_reconnect_followed_by_add_none() { outbound_destinations_reset_on_reconnect(move || { Some(controller::destination_add_none()) }) } #[test] #[cfg_attr(not(feature = "flaky_tests"), ignore)] fn outbound_destinations_reset_on_reconnect_followed_by_remove_none() { outbound_destinations_reset_on_reconnect(move || { Some(controller::destination_remove_none()) }) } fn outbound_destinations_reset_on_reconnect<F>(f: F) where F: Fn() -> Option<pb::destination::Update> + Send + 'static { use std::thread; let _ = env_logger::try_init(); let mut env = config::TestEnv::new(); env.put(config::ENV_BIND_TIMEOUT, "100".to_owned()); let srv = $make_server().route("/", "hello").run(); let ctrl = controller::new() .destination("initially-exists.ns.svc.cluster.local", srv.addr) .destination_close("trigger-close.ns.svc.cluster.local") .destination_fn("initially-exists.ns.svc.cluster.local", f) .run(); let proxy = proxy::new() .controller(ctrl) .outbound(srv) .run_with_test_env(env); let initially_exists = $make_client(proxy.outbound, "initially-exists.ns.svc.cluster.local"); assert_eq!(initially_exists.get("/"), "hello"); { let trigger_close = $make_client(proxy.outbound, "trigger-close.ns.svc.cluster.local"); let mut req = trigger_close.request_builder("/"); let rsp = trigger_close.request(req.method("GET")); assert_eq!(rsp.status(), http::StatusCode::INTERNAL_SERVER_ERROR); } thread::sleep(Duration::from_millis(1000)); let mut req = initially_exists.request_builder("/"); let rsp = initially_exists.request(req.method("GET")); assert_eq!(rsp.status(), http::StatusCode::INTERNAL_SERVER_ERROR); } #[test] #[cfg_attr(not(feature = "flaky_tests"), ignore)] fn outbound_times_out() { use std::thread; let _ = env_logger::try_init(); let mut env = config::TestEnv::new(); env.put(config::ENV_BIND_TIMEOUT, "100".to_owned()); let srv = $make_server().route("/hi", "hello").run(); let addr = srv.addr.clone(); let ctrl = controller::new() .destination_fn("disco.test.svc.cluster.local", move || { thread::sleep(Duration::from_millis(500)); Some(controller::destination_update(addr)) }) .run(); let proxy = proxy::new() .controller(ctrl) .outbound(srv) .run_with_test_env(env); let client = $make_client(proxy.outbound, "disco.test.svc.cluster.local"); let mut req = client.request_builder("/"); let rsp = client.request(req.method("GET")); assert_eq!(rsp.status(), http::StatusCode::INTERNAL_SERVER_ERROR); } #[test] fn outbound_uses_orig_dst_if_not_local_svc() { let _ = env_logger::try_init(); let srv = $make_server() .route("/", "hello") .route("/bye", "bye") .run(); let ctrl = controller::new() .run(); let proxy = proxy::new() .controller(ctrl) .outbound(srv) .run(); let client = $make_client(proxy.outbound, "versioncheck.conduit.io"); assert_eq!(client.get("/"), "hello"); assert_eq!(client.get("/bye"), "bye"); } #[test] fn outbound_asks_controller_without_orig_dst() { let _ = env_logger::try_init(); let srv = $make_server() .route("/", "hello") .route("/bye", "bye") .run(); let ctrl = controller::new() .destination("disco.test.svc.cluster.local", srv.addr) .run(); let proxy = proxy::new() .controller(ctrl) .run(); let client = $make_client(proxy.outbound, "disco.test.svc.cluster.local"); assert_eq!(client.get("/"), "hello"); assert_eq!(client.get("/bye"), "bye"); } } } mod http2 { use super::support::*; generate_tests! { server: server::new, client: client::new } } mod http1 { use super::support::*; generate_tests! { server: server::http1, client: client::http1 } mod absolute_uris { use super::super::support::*; generate_tests! { server: server::http1, client: client::http1_absolute_uris } } } #[test] fn outbound_updates_newer_services() { let _ = env_logger::try_init(); let srv = server::http1().route("/h1", "hello h1").run(); let ctrl = controller::new() .destination("disco.test.svc.cluster.local", srv.addr) .run(); let proxy = proxy::new().controller(ctrl).outbound(srv).run(); let client1 = client::http2(proxy.outbound, "disco.test.svc.cluster.local"); client1.get("/h2"); let client2 = client::http1(proxy.outbound, "disco.test.svc.cluster.local"); assert_eq!(client2.get("/h1"), "hello h1"); }
mod support; use self::support::*; macro_rules! generate_tests { (server: $make_server:path, client: $make_client:path) => { use conduit_proxy_controller_grpc as pb; #[test] fn outbound_asks_controller_api() { let _ = env_logger::try_init(); let srv = $make_server().route("/", "hello").route("/bye", "bye").run(); let ctrl = controller::new() .destination("disco.test.svc.cluster.local", srv.addr) .run(); let proxy = proxy::new().controller(ctrl).outbound(srv).run(); let client = $make_client(proxy.outbound, "disco.test.svc.cluster.local"); assert_eq!(client.get("/"), "hello"); assert_eq!(client.get("/bye"), "bye"); } #[test] fn outbound_reconnects_if_controller_stream_ends() { let _ = env_logger::try_init(); let srv = $make_server().route("/recon", "nect").run(); let ctrl = controller::new() .destination_close("disco.test.svc.cluster.local") .destination("disco.test.svc.cluster.local", srv.addr) .run(); let proxy = proxy::new().controller(ctrl).outbound(srv).run(); let client = $make_client(proxy.outbound, "disco.test.svc.cluster.local"); assert_eq!(client.get("/recon"), "nect"); } #[test] #[cfg_attr(not(feature = "flaky_tests"), ignore)] fn outbound_destinations_reset_on_reconnect_followed_by_no_endpoints_exists() { outbound_destinations_reset_on_reconnect(move || { Some(controller::destination_exists_with_no_endpoints()) }) } #[test] #[cfg_attr(not(feature = "flaky_tests"), ignore)] fn outbound_destinations_reset_on_reconnect_followed_by_add_none() { outbound_destinations_reset_on_reconnect(move || { Some(controller::destination_add_none()) }) } #[test] #[cfg_attr(not(feature = "flaky_tests"), ignore)] fn outbound_destinations_reset_on_reconnect_followed_by_remove_none() { outbound_destinations_reset_on_reconnect(move || { Some(controller::destination_remove_none()) }) } fn outbound_destinations_reset_on_reconnect<F>(f: F) where F: Fn() -> Option<pb::destination::Update> + Send + 'static { use std::thread; let _ = env_logger::try_init(); let mut env = config::TestEnv::new(); env.put(config::ENV_BIND_TIMEOUT, "100".to_owned()); let srv = $make_server().route("/", "hello").run(); let ctrl = controller::new() .destination("initially-exists.ns.svc.cluster.local", srv.addr) .destination_close("trigger-close.ns.svc.cluster.local") .destination_fn("initially-exists.ns.svc.cluster.local", f) .run(); let proxy = proxy::new() .controller(ctrl) .outbound(srv) .run_with_test_env(env); let initially_exists = $make_client(proxy.outbound, "initially-exists.ns.svc.cluster.local"); assert_eq!(initially_exists.get("/"), "hello"); { let trigger_close = $make_client(proxy.outbound, "trigger-close.ns.svc.cluster.local"); let mut req = trigger_close.request_builder("/"); let rsp = trigger_close.request(req.method("GET")); assert_eq!(rsp.status(), http::StatusCode::INTERNAL_SERVER_ERROR); } thread::sleep(Duration::from_millis(1000)); let mut req = initially_exists.request_builder("/"); let rsp = initially_exists.request(req.method("GET")); assert_eq!(rsp.status(), http::StatusCode::INTERNAL_SERVER_ERROR); } #[test] #[cfg_attr(not(feature = "flaky_tests"), ignore)] fn outbound_times_out() { use std::thread; let _ = env_logger::try_init(); let mut env = config::TestEnv::new(); env.put(config::ENV_BIND_TIMEOUT, "100".to_owned()); let srv = $make_server().route("/hi", "hello").run(); let addr = srv.addr.clone(); let ctrl = controller::new() .destination_fn("disco.test.svc.cluster.local", move || { thread::sleep(Duration::from_millis(500)); Some(controller::destination_update(addr)) }) .run(); let proxy = proxy::new() .controller(ctrl) .outbound(srv) .run_with_test_env(env); let client = $make_client(proxy.outbound, "disco.test.svc.cluster.local"); let mut req = client.request_builder("/"); let rsp = client.request(req.method("GET")); assert_eq!(rsp.status(), http::StatusCode::INTERNAL_SERVER_ERROR); } #[test] fn outbound_uses_orig_dst_if_not_local_svc() { let _ = env_logger::try_init(); let srv = $make_server() .route("/", "hello") .route("/bye", "bye") .run(); let ctrl = controller::new() .run(); let proxy = proxy::new() .controller(ctrl) .outbound(srv) .run(); let client = $make_client(proxy.outbound, "versioncheck.conduit.io"); assert_eq!(client.get("/"), "hello"); assert_eq!(client.get("/bye"), "bye"); } #[test] fn outbound_asks_controller_without_orig_dst() { let _ = env_logger::try_init(); let srv = $make_server() .route("/", "hello") .route("/bye", "bye") .run(); let ctrl = controller::new() .destination("disco.test.svc.cluster.local", srv.addr) .run(); let proxy = proxy::new() .controller(ctrl) .run(); let client = $make_client(proxy.outbound, "disco.test.svc.cluster.local"); assert_eq!(client.get("/"), "hello"); assert_eq!(client.get("/bye"), "bye"); } } } mod http2 { use super::support::*; generate_tests! { server: server::new, client: client::new } } mod http1 { use super::support::*; generate_tests! { server: server::http1, client: client::http1 } mod absolute_uris { use super::super::support::*; generate_tests! { server: server::http1, client: client::http1_absolute_uris } } } #[test] fn outbound_updates_newer_services() { let _ = env_logger::try_init(); let srv = server::http1().route("/h1", "hello h1").run(); let ctrl = controller::new() .destination("disco.test.svc.cluster.local", srv.addr) .run(); let proxy = proxy::new().controller(ctrl).outbound(srv).run(); let client1 = client::http2(proxy.outbound, "disco.test.svc.cluster.local"); client1.get("/h2");
let client2 = client::http1(proxy.outbound, "disco.test.svc.cluster.local"); assert_eq!(client2.get("/h1"), "hello h1"); }
function_block-function_prefix_line
[ { "content": "fn run(proxy: Proxy, mut env: config::TestEnv) -> Listening {\n\n use self::conduit_proxy::config;\n\n\n\n let controller = proxy.controller.expect(\"proxy controller missing\");\n\n let inbound = proxy.inbound;\n\n let outbound = proxy.outbound;\n\n let mut mock_orig_dst = DstInner...
Rust
src/rendering.rs
Ipotrick/eisen
fa86495574f3be99213e0ed98f0963db0f43614a
use std::{time::{SystemTime, Instant}}; use async_std::sync::Mutex; use wgpu::{util::{DeviceExt, RenderEncoder}, BindGroupDescriptor, RenderPipelineDescriptor}; use winit::{dpi::PhysicalSize, window::Window}; const QUADS_PER_BATCH: usize = 1024; #[repr(C)] #[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)] struct QuadDrawGlobals{ camera_translation: [f32; 2], camera_rotation: [f32; 2], camera_scale: [f32; 2], } #[repr(C)] #[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)] pub struct QuadDrawInfo{ pub color: [f32; 4], pub scale: [f32; 2], pub position: [f32; 2], pub orientation: [f32; 2], pub _pad: [f32; 2], } pub struct SharedRenderRessources { instance: wgpu::Instance, surface: wgpu::Surface, surf_size: PhysicalSize<u32>, surf_config: wgpu::SurfaceConfiguration, adapter: wgpu::Adapter, device: wgpu::Device, main_queue: wgpu::Queue, } pub trait RenderRoutine: Send + Sync { fn render(&mut self, shareed: &mut SharedRenderRessources); } pub enum RenderPass { Main, } pub struct RenderState { shared_ressources: SharedRenderRessources, main_pass_render_routines: Vec<Box<dyn RenderRoutine>>, rect_draw_buffers: Vec<(wgpu::Buffer, wgpu::BindGroup)>, last_buffer_index: usize, last_buffer_fill_len: usize, rect_index_buffer: wgpu::Buffer, rect_pipeline_binding_group_layout: wgpu::BindGroupLayout, rect_pipeline_globals_binding_group_layout: wgpu::BindGroupLayout, rect_globals_buffer: wgpu::Buffer, rect_pipeline_layout: wgpu::PipelineLayout, rect_pipeline: wgpu::RenderPipeline, globals: QuadDrawGlobals, } pub struct Renderer { state: Mutex<RenderState>, start_time: SystemTime, } impl Renderer { pub async fn new(window: &Window) -> Self { let instance = wgpu::Instance::new(wgpu::Backends::VULKAN); let surface = unsafe { instance.create_surface(window) }; let adapter = instance.request_adapter( &wgpu::RequestAdapterOptions { power_preference: wgpu::PowerPreference::HighPerformance, compatible_surface: Some(&surface), force_fallback_adapter: false, }, ).await.unwrap(); let (device, main_queue) = adapter.request_device( &wgpu::DeviceDescriptor{ features: wgpu::Features::empty(), limits: wgpu::Limits::default(), label: Some("main device"), }, None, ).await.unwrap(); let surf_size = window.inner_size(); let surf_config = wgpu::SurfaceConfiguration { usage: wgpu::TextureUsages::RENDER_ATTACHMENT, format: surface.get_preferred_format(&adapter).unwrap(), width: surf_size.width, height: surf_size.height, present_mode: wgpu::PresentMode::Immediate, }; surface.configure(&device, &surf_config); let mut indices = Vec::<u32>::new(); indices.reserve(QUADS_PER_BATCH*6); for i in (0 as u32..(QUADS_PER_BATCH*4) as u32).step_by(4) { indices.push(i + 2); indices.push(i + 0); indices.push(i + 1); indices.push(i + 2); indices.push(i + 1); indices.push(i + 3); } let batched_quad_index_buffer = device.create_buffer( &wgpu::BufferDescriptor{ label: Some("batched quad index buffer"), size: (std::mem::size_of::<u32>() * indices.len()) as u64, usage: wgpu::BufferUsages::INDEX | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false, } ); main_queue.write_buffer(&batched_quad_index_buffer, 0, bytemuck::cast_slice(&indices[..])); let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor{ entries: &[ wgpu::BindGroupLayoutEntry { binding: 0, visibility: wgpu::ShaderStages::VERTEX, ty: wgpu::BindingType::Buffer{ has_dynamic_offset: false, ty: wgpu::BufferBindingType::Uniform, min_binding_size: None, }, count: None, }, ], label: Some("quad render bind group layout"), }); let globals_bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor{ entries: &[ wgpu::BindGroupLayoutEntry { binding: 0, visibility: wgpu::ShaderStages::VERTEX | wgpu::ShaderStages::FRAGMENT, ty: wgpu::BindingType::Buffer{ has_dynamic_offset: false, ty: wgpu::BufferBindingType::Uniform, min_binding_size: None, }, count: None, }, ], label: Some("quad render global bind group layout"), }); let globals_buffer = device.create_buffer(&wgpu::BufferDescriptor{ label: Some("[quad renderer] globals"), size: std::mem::size_of::<QuadDrawGlobals>() as u64, usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false, }); let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor{ label: Some("quad render pipeline"), bind_group_layouts: &[&globals_bind_group_layout, &bind_group_layout], push_constant_ranges: &[], }); let shader_module = device.create_shader_module(&wgpu::ShaderModuleDescriptor{ label: Some("quad render shader"), source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed(include_str!("rendering/quad_shader.wgsl"))), }); let pipeline = device.create_render_pipeline(&RenderPipelineDescriptor{ vertex: wgpu::VertexState{ module: &shader_module, entry_point: "vs_main", buffers: &[], }, fragment: Some(wgpu::FragmentState{ module: &shader_module, entry_point: "fs_main", targets: &[ wgpu::ColorTargetState{ blend: None, format: surf_config.format, write_mask: wgpu::ColorWrites::ALL, } ], }), label: Some("quad render pipeline"), layout: Some(&pipeline_layout), primitive: wgpu::PrimitiveState{ topology: wgpu::PrimitiveTopology::TriangleList, strip_index_format: None, front_face: wgpu::FrontFace::Cw, cull_mode: None, unclipped_depth: false, polygon_mode: wgpu::PolygonMode::Fill, conservative: false, }, depth_stencil: None, multisample: wgpu::MultisampleState::default(), multiview: None, }); let shared = SharedRenderRessources{ instance, surface, surf_size, surf_config, adapter, device, main_queue, }; let state = Mutex::new(RenderState{ shared_ressources: shared, main_pass_render_routines: Vec::new(), rect_draw_buffers: Vec::new(), last_buffer_index: 0, last_buffer_fill_len: 0, rect_index_buffer: batched_quad_index_buffer, rect_pipeline_binding_group_layout: bind_group_layout, rect_pipeline_globals_binding_group_layout: globals_bind_group_layout, rect_globals_buffer: globals_buffer, rect_pipeline_layout: pipeline_layout, rect_pipeline: pipeline, globals: QuadDrawGlobals{ camera_translation: [0.0,0.0], camera_rotation: [1.0,0.0], camera_scale: [1.0,1.0], }, }); Self{ state, start_time: SystemTime::now(), } } pub async fn resize(&self, new_size: winit::dpi::PhysicalSize<u32>) { let mut state = self.state.lock().await; if new_size.width > 0 && new_size.height > 0 { state.shared_ressources.surf_size = new_size; state.shared_ressources.surf_config.width = new_size.width; state.shared_ressources.surf_config.height = new_size.height; state.shared_ressources.surface.configure(&state.shared_ressources.device, &state.shared_ressources.surf_config); println!("resized to: ({},{})", new_size.width, new_size.height); } } pub async fn add_render_routine(&self, routine: impl RenderRoutine + 'static, pass: RenderPass) { let mut state = self.state.lock().await; match pass { RenderPass::Main => state.main_pass_render_routines.push(Box::new(routine)), } } pub async fn push_quads(&self, quads: &[QuadDrawInfo]) { let mut state = self.state.lock().await; if quads.len() > 0 { state.last_buffer_index = (quads.len() - 1) / QUADS_PER_BATCH; state.last_buffer_fill_len = (quads.len() - 1) % QUADS_PER_BATCH + 1; while state.rect_draw_buffers.len() <= state.last_buffer_index { let buff = state.shared_ressources.device.create_buffer(&wgpu::BufferDescriptor{ label: Some("quad draw buffer"), mapped_at_creation: false, size: (QUADS_PER_BATCH * std::mem::size_of::<QuadDrawInfo>()) as u64, usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::UNIFORM }); let bind_group = state.shared_ressources.device.create_bind_group(&wgpu::BindGroupDescriptor{ label: Some("quad render pipeline bind group"), layout: &state.rect_pipeline_binding_group_layout, entries: &[ wgpu::BindGroupEntry{ binding: 0, resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding{ buffer: &buff, offset: 0, size: None, }), } ], }); state.rect_draw_buffers.push((buff, bind_group)); } for i in 0..state.last_buffer_index { let slice = bytemuck::cast_slice(&quads[i*QUADS_PER_BATCH..(i+1)*state.last_buffer_index]); state.shared_ressources.main_queue.write_buffer(&state.rect_draw_buffers[i].0, 0, slice); } let slice = bytemuck::cast_slice(&quads[state.last_buffer_index*QUADS_PER_BATCH..]); state.shared_ressources.main_queue.write_buffer(&state.rect_draw_buffers[state.last_buffer_index].0, 0, slice); } else { state.last_buffer_index = 0; state.last_buffer_fill_len = 0; } } pub async fn render(&self) -> Result<(), wgpu::SurfaceError> { let mut state = self.state.lock().await; let state = &mut*state; let output = state.shared_ressources.surface.get_current_texture()?; let view = output.texture.create_view(&wgpu::TextureViewDescriptor::default()); state.shared_ressources.main_queue.write_buffer(&state.rect_globals_buffer, 0, bytemuck::cast_slice(&[state.globals])); let mut encoder = state.shared_ressources.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("Rect Renderpass Encoder"), }); { let globals_bind_group = state.shared_ressources.device.create_bind_group(&wgpu::BindGroupDescriptor{ label: Some("[quad renderer] globals"), layout: &state.rect_pipeline_globals_binding_group_layout, entries: &[ wgpu::BindGroupEntry{ binding: 0, resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding{ buffer: &state.rect_globals_buffer, offset: 0, size: None, }), } ] }); let mut render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { label: Some("Render Pass"), color_attachments: &[wgpu::RenderPassColorAttachment { view: &view, resolve_target: None, ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color { r: 0.0, g: 0.0, b: 0.0, a: 1.0, }), store: true, }, }], depth_stencil_attachment: None, }); render_pass.set_bind_group(0, &globals_bind_group, &[]); render_pass.set_pipeline(&state.rect_pipeline); render_pass.set_index_buffer( state.rect_index_buffer.slice(..), wgpu::IndexFormat::Uint32, ); if state.last_buffer_fill_len > 0 { for i in 0..state.last_buffer_index { render_pass.set_bind_group(1, &state.rect_draw_buffers[i].1, &[]); render_pass.draw_indexed(0..(QUADS_PER_BATCH*6) as u32, 0, 0..1); } render_pass.set_bind_group(1, &state.rect_draw_buffers[state.last_buffer_index].1, &[]); render_pass.draw_indexed(0..(state.last_buffer_fill_len*6) as u32, 0, 0..1); } } let shared = &mut state.shared_ressources; for render_routine in &mut state.main_pass_render_routines { render_routine.render(shared); } state.shared_ressources.main_queue.submit(std::iter::once(encoder.finish())); output.present(); Ok(()) } }
use std::{time::{SystemTime, Instant}}; use async_std::sync::Mutex; use wgpu::{util::{DeviceExt, RenderEncoder}, BindGroupDescriptor, RenderPipelineDescriptor}; use winit::{dpi::PhysicalSize, window::Window}; const QUADS_PER_BATCH: usize = 1024; #[repr(C)] #[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)] struct QuadDrawGlobals{ camera_translation: [f32; 2], camera_rotation: [f32; 2], camera_scale: [f32; 2], } #[repr(C)] #[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)] pub struct QuadDrawInfo{ pub color: [f32; 4], pub scale: [f32; 2], pub position: [f32; 2], pub orientation: [f32; 2], pub _pad: [f32; 2], } pub struct SharedRenderRessources { instance: wgpu::Instance, surface: wgpu::Surface, surf_size: PhysicalSize<u32>, surf_config: wgpu::SurfaceConfiguration, adapter: wgpu::Adapter, device: wgpu::Device, main_queue: wgpu::Queue, } pub trait RenderRoutine: Send + Sync { fn render(&mut self, shareed: &mut SharedRenderRessources); } pub enum RenderPass { Main, } pub struct RenderState { shared_ressources: SharedRenderRessources, main_pass_render_routines: Vec<Box<dyn RenderRoutine>>, rect_draw_buffers: Vec<(wgpu::Buffer, wgpu::BindGroup)>, last_buffer_index: usize, last_buffer_fill_len: usize, rect_index_buffer: wgpu::Buffer, rect_pipeline_binding_group_layout: wgpu::BindGroupLayout, rect_pipeline_globals_binding_group_layout: wgpu::BindGroupLayout, rect_globals_buffer: wgpu::Buffer, rect_pipeline_layout: wgpu::PipelineLayout, rect_pipeline: wgpu::RenderPipeline, globals: QuadDrawGlobals, } pub struct Renderer { state: Mutex<RenderState>, start_time: SystemTime, } impl Renderer { pub async fn new(window: &Window) -> Self { let instance = wgpu::Instance::new(wgpu::Backends::VULKAN); let surface = unsafe { instance.create_surface(window) }; let adapter = instance.request_adapter( &wgpu::RequestAdapterOptions { power_preference: wgpu::PowerPreference::HighPerformance, compatible_surface: Some(&surface), force_fallback_adapter: false, }, ).await.unwrap(); let (device, main_queue) = adapter.request_device( &wgpu::DeviceDescriptor{ features: wgpu::Features::empty(), limits: wgpu::Limits::default(), label: Some("main device"), }, None, ).await.unwrap(); let surf_size = window.inner_size(); let surf_config = wgpu::SurfaceConfiguration { usage: wgpu::TextureUsages::RENDER_ATTACHMENT, format: surface.get_preferred_format(&adapter).unwrap(), width: surf_size.width, height: surf_size.height, present_mode: wgpu::PresentMode::Immediate, }; surface.configure(&device, &surf_config); let mut indices = Vec::<u32>::new(); indices.reserve(QUADS_PER_BATCH*6); for i in (0 as u32..(QUADS_PER_BATCH*4) as u32).step_by(4) { indices.push(i + 2); indices.push(i + 0); indices.push(i + 1); indices.push(i + 2); indices.push(i + 1); indices.push(i + 3); } let batched_quad_index_buffer = device.create_buffer( &wgpu::BufferDescriptor{ label: Some("batched quad index buffer"), size: (std::mem::size_of::<u32>() * indices.len()) as u64, usage: wgpu::BufferUsages::INDEX | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false, } ); main_queue.write_buffer(&batched_quad_index_buffer, 0, bytemuck::cast_slice(&indices[..])); let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor{ entries: &[ wgpu::BindGroupLayoutEntry { binding: 0, visibility: wgpu::ShaderStages::VERTEX, ty: wgpu::BindingType::Buffer{ has_dynamic_offset: false, ty: wgpu::BufferBindingType::Uniform, min_binding_size: None, }, count: None, }, ], label: Some("quad render bind group layout"), }); let globals_bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor{ entries: &[ wgpu::BindGroupLayoutEntry { binding: 0, visibility: wgpu::ShaderStages::VERTEX | wgpu::ShaderStages::FRAGMENT, ty: wgpu::BindingType::Buffer{ has_dynamic_offset: false, ty: wgpu::BufferBindingType::Uniform, min_binding_size: None, }, count: None, }, ], label: Some("quad render global bind group layout"), }); let globals_buffer = device.create_buffer(&wgpu::BufferDescriptor{ label: Some("[quad renderer] globals"), size: std::mem::size_of::<QuadDrawGlobals>() as u64, usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false, }); let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor{ label: Some("quad render pipeline"), bind_group_layouts: &[&globals_bind_group_layout, &bind_group_layout], push_constant_ranges: &[], }); let shader_module = device.create_shader_module(&wgpu::ShaderModuleDescriptor{ label: Some("quad render shader"), source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed(include_str!("rendering/quad_shader.wgsl"))), }); let pipeline = device.create_render_pipeline(&RenderPipelineDescriptor{ vertex: wgpu::VertexState{ module: &shader_module, entry_point: "vs_main", buffers: &[], }, fragment: Some(wgpu::FragmentState{ module: &shader_module, entry_point: "fs_main", targets: &[ wgpu::ColorTargetState{ blend: None, format: surf_config.format, write_mask: wgpu::ColorWrites::ALL, } ], }), label: Some("quad render pipeline"), layout: Some(&pipeline_layout), primitive: wgpu::PrimitiveState{ topology: wgpu::PrimitiveTopology::TriangleList, strip_index_format: None, front_face: wgpu::FrontFace::Cw, cull_mode: None, unclipped_depth: false, polygon_mode: wgpu::PolygonMode::Fill, conservative: false, }, depth_stencil: None, multisample: wgpu::MultisampleState::default(), multiview: None, }); let shared = SharedRenderRessources{ instance, surface, surf_size, surf_config, adapter, device, main_queue, }; let state = Mutex::new(RenderState{ shared_ressources: shared, main_pass_render_routines: Vec::new(), rect_draw_buffers: Vec::new(), last_buffer_index: 0, last_buffer_fill_len: 0, rect_index_buffer: batched_quad_index_buffer, rect_pipeline_binding_group_layout: bind_group_layout, rect_pipeline_globals_binding_group_layout: globals_bind_group_layout, rect_globals_buffer: globals_buffer, rect_pipeline_layout: pipeline_layout, rect_pipeline: pipeline, globals: QuadDrawGlobals{ camera_translation: [0.0,0.0], camera_rotation: [1.0,0.0], camera_scale: [1.0,1.0], }, }); Self{ state, start_time: SystemTime::now(), } } pub async fn resize(&self, new_size: winit::dpi::PhysicalSize<u32>) { let mut state = self.state.lock().await; if new_size.width > 0 && new_size.height > 0 { state.shared_ressources.surf_size = new_size; state.shared_ressources.surf_config.width = new_size.width; state.shared_ressources.surf_config.height = new_size.height; state.shared_ressources.surface.configure(&state.shared_ressources.device, &state.shared_ressources.surf_config); println!("resized to: ({},{})", new_size.width, new_size.height); } } pub async fn add_render_routine(&self, routine: impl RenderRoutine + 'static, pass: RenderPass) { let mut state = self.state.lock().await; match pass { RenderPass::Main => state.main_pass_render_routines.push(Box::new(routine)), } } pub async fn push_quads(&self, quads: &[QuadDrawInfo]) { let mut state = self.state.lock().await; if quads.len() > 0 { state.last_buffer_index = (quads.len() - 1) / QUADS_PER_BATCH; state.last_buffer_fill_len = (quads.len() - 1) % QUADS_PER_BATCH + 1; while state.rect_draw_buffers.len() <= state.last_buffer_index { let buff = state.shared_ressources.device.create_buffer(&wgpu::BufferDescriptor{ label: Some("quad draw buffer"), mapped_at_creation: false, size: (QUADS_PER_BATCH * std::mem::size_of::<QuadDrawInfo>()) as u64, usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::UNIFORM }); let bind_group = state.shared_ressources.device.create_bind_group(&wgpu::BindGroupDescriptor{ label: Some("quad render pipeline bind group"), layout: &state.rect_pipeline_binding_group_layout, entries: &[ wgpu::BindGroupEntry{ binding: 0, resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding{ buffer: &buff, offset: 0, size: None, }), } ], }); state.rect_draw_buffers.push((buff, bind_group)); }
pub async fn render(&self) -> Result<(), wgpu::SurfaceError> { let mut state = self.state.lock().await; let state = &mut*state; let output = state.shared_ressources.surface.get_current_texture()?; let view = output.texture.create_view(&wgpu::TextureViewDescriptor::default()); state.shared_ressources.main_queue.write_buffer(&state.rect_globals_buffer, 0, bytemuck::cast_slice(&[state.globals])); let mut encoder = state.shared_ressources.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("Rect Renderpass Encoder"), }); { let globals_bind_group = state.shared_ressources.device.create_bind_group(&wgpu::BindGroupDescriptor{ label: Some("[quad renderer] globals"), layout: &state.rect_pipeline_globals_binding_group_layout, entries: &[ wgpu::BindGroupEntry{ binding: 0, resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding{ buffer: &state.rect_globals_buffer, offset: 0, size: None, }), } ] }); let mut render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { label: Some("Render Pass"), color_attachments: &[wgpu::RenderPassColorAttachment { view: &view, resolve_target: None, ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color { r: 0.0, g: 0.0, b: 0.0, a: 1.0, }), store: true, }, }], depth_stencil_attachment: None, }); render_pass.set_bind_group(0, &globals_bind_group, &[]); render_pass.set_pipeline(&state.rect_pipeline); render_pass.set_index_buffer( state.rect_index_buffer.slice(..), wgpu::IndexFormat::Uint32, ); if state.last_buffer_fill_len > 0 { for i in 0..state.last_buffer_index { render_pass.set_bind_group(1, &state.rect_draw_buffers[i].1, &[]); render_pass.draw_indexed(0..(QUADS_PER_BATCH*6) as u32, 0, 0..1); } render_pass.set_bind_group(1, &state.rect_draw_buffers[state.last_buffer_index].1, &[]); render_pass.draw_indexed(0..(state.last_buffer_fill_len*6) as u32, 0, 0..1); } } let shared = &mut state.shared_ressources; for render_routine in &mut state.main_pass_render_routines { render_routine.render(shared); } state.shared_ressources.main_queue.submit(std::iter::once(encoder.finish())); output.present(); Ok(()) } }
for i in 0..state.last_buffer_index { let slice = bytemuck::cast_slice(&quads[i*QUADS_PER_BATCH..(i+1)*state.last_buffer_index]); state.shared_ressources.main_queue.write_buffer(&state.rect_draw_buffers[i].0, 0, slice); } let slice = bytemuck::cast_slice(&quads[state.last_buffer_index*QUADS_PER_BATCH..]); state.shared_ressources.main_queue.write_buffer(&state.rect_draw_buffers[state.last_buffer_index].0, 0, slice); } else { state.last_buffer_index = 0; state.last_buffer_fill_len = 0; } }
function_block-function_prefix_line
[ { "content": "#[allow(unused)]\n\npub fn block_on<Out>(mut future: impl Future<Output = Out>) -> Out {\n\n LOCAL_BLOCK_ON_DATA.with(\n\n |ref_cell| {\n\n let local_block_data = ref_cell.borrow_mut();\n\n let waker = waker_ref(&local_block_data.waker);\n\n let context =...
Rust
src/state.rs
peterschwarz/sawtooth-pbft
f9b5372fc028d5c47ad4f2a7c6947cbc77272a50
/* * Copyright 2018 Bitwise IO, 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. * ----------------------------------------------------------------------------- */ use std::fmt; use hex; use sawtooth_sdk::consensus::engine::{BlockId, PeerId}; use crate::config::PbftConfig; use crate::message_type::PbftMessageType; use crate::protos::pbft_message::PbftBlock; use crate::timing::Timeout; #[derive(Debug, PartialEq, Serialize, Deserialize)] enum PbftNodeRole { Primary, Secondary, } #[derive(Debug, PartialEq, PartialOrd, Clone, Serialize, Deserialize)] pub enum PbftPhase { NotStarted, PrePreparing, Preparing, Checking, Committing, Finished, } #[derive(Debug, PartialEq, Copy, Clone, Serialize, Deserialize)] pub enum PbftMode { Normal, ViewChanging, Checkpointing, } impl fmt::Display for PbftState { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let ast = if self.is_primary() { "*" } else { " " }; let mode = match self.mode { PbftMode::Normal => "N", PbftMode::Checkpointing => "C", PbftMode::ViewChanging => "V", }; let phase = match self.phase { PbftPhase::NotStarted => "NS", PbftPhase::PrePreparing => "PP", PbftPhase::Preparing => "Pr", PbftPhase::Checking => "Ch", PbftPhase::Committing => "Co", PbftPhase::Finished => "Fi", }; let wb = match self.working_block { WorkingBlockOption::WorkingBlock(ref block) => format!( "{}/{}", block.block_num, &hex::encode(block.get_block_id())[..6] ), WorkingBlockOption::TentativeWorkingBlock(ref block_id) => { String::from(&hex::encode(block_id)[..5]) + "~" } _ => String::from("~none~"), }; write!( f, "({} {} {}, seq {}, wb {}), Node {}{}", phase, mode, self.view, self.seq_num, wb, ast, &hex::encode(self.id.clone())[..6], ) } } #[derive(Debug, PartialEq, Clone, Serialize, Deserialize)] pub enum WorkingBlockOption { NoWorkingBlock, TentativeWorkingBlock(BlockId), WorkingBlock(PbftBlock), } impl WorkingBlockOption { pub fn is_none(&self) -> bool { self == &WorkingBlockOption::NoWorkingBlock } } #[derive(Debug, Serialize, Deserialize)] pub struct PbftState { pub id: PeerId, pub seq_num: u64, pub view: u64, pub phase: PbftPhase, role: PbftNodeRole, pub mode: PbftMode, pub pre_checkpoint_mode: PbftMode, pub peer_ids: Vec<PeerId>, pub f: u64, pub commit_timeout: Timeout, pub idle_timeout: Timeout, pub forced_view_change_period: u64, pub working_block: WorkingBlockOption, } impl PbftState { #[allow(clippy::needless_pass_by_value)] pub fn new(id: PeerId, head_block_num: u64, config: &PbftConfig) -> Self { let f = ((config.peers.len() - 1) / 3) as u64; if f == 0 { panic!("This network does not contain enough nodes to be fault tolerant"); } PbftState { id: id.clone(), seq_num: head_block_num + 1, view: 0, phase: PbftPhase::NotStarted, role: if config.peers[0] == id { PbftNodeRole::Primary } else { PbftNodeRole::Secondary }, mode: PbftMode::Normal, pre_checkpoint_mode: PbftMode::Normal, f, peer_ids: config.peers.clone(), commit_timeout: Timeout::new(config.commit_timeout), idle_timeout: Timeout::new(config.idle_timeout), forced_view_change_period: config.forced_view_change_period, working_block: WorkingBlockOption::NoWorkingBlock, } } pub fn peers(&self) -> &Vec<PeerId> { &self.peer_ids } pub fn check_msg_type(&self) -> PbftMessageType { match self.phase { PbftPhase::PrePreparing => PbftMessageType::PrePrepare, PbftPhase::Preparing => PbftMessageType::Prepare, PbftPhase::Checking => PbftMessageType::Prepare, PbftPhase::Committing => PbftMessageType::Commit, _ => PbftMessageType::Unset, } } pub fn get_primary_id(&self) -> PeerId { let primary_index = (self.view % (self.peer_ids.len() as u64)) as usize; self.peer_ids[primary_index].clone() } pub fn is_primary(&self) -> bool { self.role == PbftNodeRole::Primary } pub fn upgrade_role(&mut self) { self.role = PbftNodeRole::Primary; } pub fn downgrade_role(&mut self) { self.role = PbftNodeRole::Secondary; } pub fn switch_phase(&mut self, desired_phase: PbftPhase) -> Option<PbftPhase> { let next = match self.phase { PbftPhase::NotStarted => PbftPhase::PrePreparing, PbftPhase::PrePreparing => PbftPhase::Preparing, PbftPhase::Preparing => PbftPhase::Checking, PbftPhase::Checking => PbftPhase::Committing, PbftPhase::Committing => PbftPhase::Finished, PbftPhase::Finished => PbftPhase::NotStarted, }; if desired_phase == next { debug!("{}: Changing to {:?}", self, desired_phase); self.phase = desired_phase.clone(); Some(desired_phase) } else { debug!("{}: Didn't change to {:?}", self, desired_phase); None } } pub fn at_forced_view_change(&self) -> bool { self.seq_num > 0 && self.seq_num % self.forced_view_change_period == 0 } pub fn discard_current_block(&mut self) { warn!("PbftState::reset: {}", self); self.working_block = WorkingBlockOption::NoWorkingBlock; self.phase = PbftPhase::NotStarted; self.mode = PbftMode::Normal; self.commit_timeout.stop(); self.idle_timeout.start(); } } #[cfg(test)] mod tests { use super::*; use crate::config::mock_config; #[test] fn no_fault_tolerance() { let config = mock_config(1); let caught = ::std::panic::catch_unwind(|| { PbftState::new(vec![0], 0, &config); }) .is_err(); assert!(caught); } #[test] fn initial_config() { let config = mock_config(4); let state0 = PbftState::new(vec![0], 0, &config); let state1 = PbftState::new(vec![], 0, &config); assert!(state0.is_primary()); assert!(!state1.is_primary()); assert_eq!(state0.f, 1); assert_eq!(state1.f, 1); assert_eq!(state0.check_msg_type(), PbftMessageType::Unset); assert_eq!(state1.check_msg_type(), PbftMessageType::Unset); assert_eq!(state0.get_primary_id(), state0.peer_ids[0]); assert_eq!(state1.get_primary_id(), state1.peer_ids[0]); } #[test] fn role_changes() { let config = mock_config(4); let mut state = PbftState::new(vec![0], 0, &config); state.downgrade_role(); assert!(!state.is_primary()); state.upgrade_role(); assert!(state.is_primary()); } #[test] fn phase_changes() { let config = mock_config(4); let mut state = PbftState::new(vec![0], 0, &config); assert!(state.switch_phase(PbftPhase::PrePreparing).is_some()); assert!(state.switch_phase(PbftPhase::Preparing).is_some()); assert!(state.switch_phase(PbftPhase::Checking).is_some()); assert!(state.switch_phase(PbftPhase::Committing).is_some()); assert!(state.switch_phase(PbftPhase::Finished).is_some()); assert!(state.switch_phase(PbftPhase::NotStarted).is_some()); assert!(state.switch_phase(PbftPhase::Finished).is_none()); assert!(state.switch_phase(PbftPhase::Preparing).is_none()); } }
/* * Copyright 2018 Bitwise IO, 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. * ----------------------------------------------------------------------------- */ use std::fmt; use hex; use sawtooth_sdk::consensus::engine::{BlockId, PeerId}; use crate::config::PbftConfig; use crate::message_type::PbftMessageType; use crate::protos::pbft_message::PbftBlock; use crate::timing::Timeout; #[derive(Debug, PartialEq, Serialize, Deserialize)] enum PbftNodeRole { Primary, Secondary, } #[derive(Debug, PartialEq, PartialOrd, Clone, Serialize, Deserialize)] pub enum PbftPhase { NotStarted, PrePreparing, Preparing, Checking, Committing, Finished, } #[derive(Debug, PartialEq, Copy, Clone, Serialize, Deserialize)] pub enum PbftMode { Normal, ViewChanging, Checkpointing, } impl fmt::Display for PbftState { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let ast = if self.is_primary()
mary(&self) -> bool { self.role == PbftNodeRole::Primary } pub fn upgrade_role(&mut self) { self.role = PbftNodeRole::Primary; } pub fn downgrade_role(&mut self) { self.role = PbftNodeRole::Secondary; } pub fn switch_phase(&mut self, desired_phase: PbftPhase) -> Option<PbftPhase> { let next = match self.phase { PbftPhase::NotStarted => PbftPhase::PrePreparing, PbftPhase::PrePreparing => PbftPhase::Preparing, PbftPhase::Preparing => PbftPhase::Checking, PbftPhase::Checking => PbftPhase::Committing, PbftPhase::Committing => PbftPhase::Finished, PbftPhase::Finished => PbftPhase::NotStarted, }; if desired_phase == next { debug!("{}: Changing to {:?}", self, desired_phase); self.phase = desired_phase.clone(); Some(desired_phase) } else { debug!("{}: Didn't change to {:?}", self, desired_phase); None } } pub fn at_forced_view_change(&self) -> bool { self.seq_num > 0 && self.seq_num % self.forced_view_change_period == 0 } pub fn discard_current_block(&mut self) { warn!("PbftState::reset: {}", self); self.working_block = WorkingBlockOption::NoWorkingBlock; self.phase = PbftPhase::NotStarted; self.mode = PbftMode::Normal; self.commit_timeout.stop(); self.idle_timeout.start(); } } #[cfg(test)] mod tests { use super::*; use crate::config::mock_config; #[test] fn no_fault_tolerance() { let config = mock_config(1); let caught = ::std::panic::catch_unwind(|| { PbftState::new(vec![0], 0, &config); }) .is_err(); assert!(caught); } #[test] fn initial_config() { let config = mock_config(4); let state0 = PbftState::new(vec![0], 0, &config); let state1 = PbftState::new(vec![], 0, &config); assert!(state0.is_primary()); assert!(!state1.is_primary()); assert_eq!(state0.f, 1); assert_eq!(state1.f, 1); assert_eq!(state0.check_msg_type(), PbftMessageType::Unset); assert_eq!(state1.check_msg_type(), PbftMessageType::Unset); assert_eq!(state0.get_primary_id(), state0.peer_ids[0]); assert_eq!(state1.get_primary_id(), state1.peer_ids[0]); } #[test] fn role_changes() { let config = mock_config(4); let mut state = PbftState::new(vec![0], 0, &config); state.downgrade_role(); assert!(!state.is_primary()); state.upgrade_role(); assert!(state.is_primary()); } #[test] fn phase_changes() { let config = mock_config(4); let mut state = PbftState::new(vec![0], 0, &config); assert!(state.switch_phase(PbftPhase::PrePreparing).is_some()); assert!(state.switch_phase(PbftPhase::Preparing).is_some()); assert!(state.switch_phase(PbftPhase::Checking).is_some()); assert!(state.switch_phase(PbftPhase::Committing).is_some()); assert!(state.switch_phase(PbftPhase::Finished).is_some()); assert!(state.switch_phase(PbftPhase::NotStarted).is_some()); assert!(state.switch_phase(PbftPhase::Finished).is_none()); assert!(state.switch_phase(PbftPhase::Preparing).is_none()); } }
{ "*" } else { " " }; let mode = match self.mode { PbftMode::Normal => "N", PbftMode::Checkpointing => "C", PbftMode::ViewChanging => "V", }; let phase = match self.phase { PbftPhase::NotStarted => "NS", PbftPhase::PrePreparing => "PP", PbftPhase::Preparing => "Pr", PbftPhase::Checking => "Ch", PbftPhase::Committing => "Co", PbftPhase::Finished => "Fi", }; let wb = match self.working_block { WorkingBlockOption::WorkingBlock(ref block) => format!( "{}/{}", block.block_num, &hex::encode(block.get_block_id())[..6] ), WorkingBlockOption::TentativeWorkingBlock(ref block_id) => { String::from(&hex::encode(block_id)[..5]) + "~" } _ => String::from("~none~"), }; write!( f, "({} {} {}, seq {}, wb {}), Node {}{}", phase, mode, self.view, self.seq_num, wb, ast, &hex::encode(self.id.clone())[..6], ) } } #[derive(Debug, PartialEq, Clone, Serialize, Deserialize)] pub enum WorkingBlockOption { NoWorkingBlock, TentativeWorkingBlock(BlockId), WorkingBlock(PbftBlock), } impl WorkingBlockOption { pub fn is_none(&self) -> bool { self == &WorkingBlockOption::NoWorkingBlock } } #[derive(Debug, Serialize, Deserialize)] pub struct PbftState { pub id: PeerId, pub seq_num: u64, pub view: u64, pub phase: PbftPhase, role: PbftNodeRole, pub mode: PbftMode, pub pre_checkpoint_mode: PbftMode, pub peer_ids: Vec<PeerId>, pub f: u64, pub commit_timeout: Timeout, pub idle_timeout: Timeout, pub forced_view_change_period: u64, pub working_block: WorkingBlockOption, } impl PbftState { #[allow(clippy::needless_pass_by_value)] pub fn new(id: PeerId, head_block_num: u64, config: &PbftConfig) -> Self { let f = ((config.peers.len() - 1) / 3) as u64; if f == 0 { panic!("This network does not contain enough nodes to be fault tolerant"); } PbftState { id: id.clone(), seq_num: head_block_num + 1, view: 0, phase: PbftPhase::NotStarted, role: if config.peers[0] == id { PbftNodeRole::Primary } else { PbftNodeRole::Secondary }, mode: PbftMode::Normal, pre_checkpoint_mode: PbftMode::Normal, f, peer_ids: config.peers.clone(), commit_timeout: Timeout::new(config.commit_timeout), idle_timeout: Timeout::new(config.idle_timeout), forced_view_change_period: config.forced_view_change_period, working_block: WorkingBlockOption::NoWorkingBlock, } } pub fn peers(&self) -> &Vec<PeerId> { &self.peer_ids } pub fn check_msg_type(&self) -> PbftMessageType { match self.phase { PbftPhase::PrePreparing => PbftMessageType::PrePrepare, PbftPhase::Preparing => PbftMessageType::Prepare, PbftPhase::Checking => PbftMessageType::Prepare, PbftPhase::Committing => PbftMessageType::Commit, _ => PbftMessageType::Unset, } } pub fn get_primary_id(&self) -> PeerId { let primary_index = (self.view % (self.peer_ids.len() as u64)) as usize; self.peer_ids[primary_index].clone() } pub fn is_pri
random
[ { "content": "#[allow(clippy::ptr_arg)]\n\npub fn commit(\n\n state: &mut PbftState,\n\n service: &mut Service,\n\n message: &ParsedMessage,\n\n) -> Result<(), PbftError> {\n\n info!(\n\n \"{}: Committing block {:?}\",\n\n state,\n\n message.get_block().block_id.clone()\n\n )...
Rust
src/dclic/src/main.rs
alexcpsec/dcli
076a7e21a0bccc453722c9fb69b960d433666736
/* * Copyright 2021 Mike Chambers * https://github.com/mikechambers/dcli * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ use dcli::apiinterface::ApiInterface; use dcli::character::Characters; use dcli::enums::platform::Platform; use dcli::error::Error; use dcli::output::Output; use dcli::utils::EXIT_FAILURE; use dcli::utils::{print_error, print_verbose, repeat_str, TSV_DELIM, TSV_EOL}; use structopt::StructOpt; async fn retrieve_characters( member_id: String, platform: Platform, verbose: bool, ) -> Result<Option<Characters>, Error> { let interface = ApiInterface::new(verbose)?; let characters = interface.retrieve_characters(&member_id, &platform).await?; Ok(characters) } #[derive(StructOpt, Debug)] #[structopt(verbatim_doc_comment)] struct Opt { #[structopt(short = "m", long = "member-id", required = true)] member_id: String, #[structopt(short = "p", long = "platform", required = true)] platform: Platform, #[structopt(short = "v", long = "verbose")] verbose: bool, #[structopt( short = "O", long = "output-format", default_value = "default" )] output: Output, } #[tokio::main] async fn main() { let opt = Opt::from_args(); print_verbose(&format!("{:#?}", opt), opt.verbose); let chars: Characters = match retrieve_characters(opt.member_id, opt.platform, opt.verbose) .await { Ok(e) => match e { Some(e) => e, None => { println!("No Characters found for member."); return; } }, Err(e) => { print_error("Error retrieving characters from API.", e); std::process::exit(EXIT_FAILURE); } }; match opt.output { Output::Default => { print_default(&chars); } Output::Tsv => { print_tsv(&chars); } } } fn print_default(characters: &Characters) { let col_w = 12; let col_id = 24; println!( "{:<0col_w$}{:<0col_id$}{:<0col_w$}", "CLASS", "ID", "STATUS", col_w = col_w, col_id = col_id, ); println!("{}", repeat_str("-", col_w * 2 + col_id)); for p in characters.characters.iter() { let label = if p == characters.get_last_active_ref().unwrap() { "LAST ACTIVE" } else { "" }; println!( "{:<0col_w$}{:<0col_id$}{:<0col_w$}", p.class_type, p.id, label, col_w = col_w, col_id = col_id, ); } } fn print_tsv(characters: &Characters) { for p in characters.characters.iter() { let label = if p == characters.get_last_active_ref().unwrap() { "LAST ACTIVE" } else { "" }; print!( "{c}{delim}{i}{delim}{s}{eol}", c = p.class_type, i = p.id, s = label, delim = TSV_DELIM, eol = TSV_EOL ); } }
/* * Copyright 2021 Mike Chambers * https://github.com/mikechambers/dcli * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ use dcli::apiinterface::ApiInterface; use dcli::character::Characters; use dcli::enums::platform::Platform; use dcli::error::Error; use dcli::output::Output; use dcli::utils::EXIT_FAILURE; use dcli::utils::{print_error, print_verbose, repeat_str, TSV_DELIM, TSV_EOL}; use structopt::StructOpt; async fn retrieve_characters( member_id: String, platform: Platform, verbose: bool, ) -> Result<Option<Characters>, Error> { let interface = ApiInterface::new(verbose)?; let characters = interface.retrieve_characters(&member_id, &platform).await?; Ok(characters) } #[derive(StructOpt, Debug)] #[structopt(verbatim_doc_comment)] struct Opt { #[structopt(short = "m", long = "member-id", required = true)] member_id: String, #[structopt(short = "p", long = "platform", required = true)] platform: Platform, #[structopt(short = "v", long = "verbose")] verbose: bool, #[structopt( short = "O", long = "output-format", default_value = "default" )] output: Output, } #[tokio::main]
fn print_default(characters: &Characters) { let col_w = 12; let col_id = 24; println!( "{:<0col_w$}{:<0col_id$}{:<0col_w$}", "CLASS", "ID", "STATUS", col_w = col_w, col_id = col_id, ); println!("{}", repeat_str("-", col_w * 2 + col_id)); for p in characters.characters.iter() { let label = if p == characters.get_last_active_ref().unwrap() { "LAST ACTIVE" } else { "" }; println!( "{:<0col_w$}{:<0col_id$}{:<0col_w$}", p.class_type, p.id, label, col_w = col_w, col_id = col_id, ); } } fn print_tsv(characters: &Characters) { for p in characters.characters.iter() { let label = if p == characters.get_last_active_ref().unwrap() { "LAST ACTIVE" } else { "" }; print!( "{c}{delim}{i}{delim}{s}{eol}", c = p.class_type, i = p.id, s = label, delim = TSV_DELIM, eol = TSV_EOL ); } }
async fn main() { let opt = Opt::from_args(); print_verbose(&format!("{:#?}", opt), opt.verbose); let chars: Characters = match retrieve_characters(opt.member_id, opt.platform, opt.verbose) .await { Ok(e) => match e { Some(e) => e, None => { println!("No Characters found for member."); return; } }, Err(e) => { print_error("Error retrieving characters from API.", e); std::process::exit(EXIT_FAILURE); } }; match opt.output { Output::Default => { print_default(&chars); } Output::Tsv => { print_tsv(&chars); } } }
function_block-full_function
[ { "content": "/// Command line tool for retrieving and managing the Destiny 2 manifest database.\n\n///\n\n/// Manifest will be stored in the specified local directory with the file name:\n\n/// manifest.sqlite3, along with meta-data with information about the downloaded\n\n/// version. This is used to to deter...
Rust
tezos/context/src/serialize/mod.rs
tezedge/tezedge
b8e20d9886ad8b6876ad62375bacf1f6b7999e3b
use std::{ array::TryFromSliceError, convert::TryInto, io::Write, num::TryFromIntError, str::Utf8Error, string::FromUtf8Error, sync::Arc, }; use modular_bitfield::prelude::*; use tezos_timing::SerializeStats; use thiserror::Error; use crate::{ hash::HashingError, kv_store::HashId, persistent::DBError, working_tree::{ shape::DirectoryShapeError, storage::{DirEntryIdError, PointerToInode, Storage, StorageError}, string_interner::StringInterner, Object, }, ContextKeyValueStore, }; use self::persistent::AbsoluteOffset; pub mod in_memory; pub mod persistent; const COMPACT_HASH_ID_BIT: u64 = 1 << 31; const FULL_47_BITS: u64 = 0x7FFFFFFFFFFF; const FULL_31_BITS: u64 = 0x7FFFFFFF; pub type SerializeObjectSignature = fn( &Object, HashId, &mut Vec<u8>, &Storage, &StringInterner, &mut SerializeStats, &mut Vec<(HashId, Arc<[u8]>)>, &mut Vec<HashId>, &mut ContextKeyValueStore, Option<AbsoluteOffset>, ) -> Result<Option<AbsoluteOffset>, SerializationError>; #[derive(BitfieldSpecifier)] #[bits = 2] #[derive(Clone, Debug, Eq, PartialEq, Copy)] pub enum ObjectLength { OneByte, TwoBytes, FourBytes, } #[derive(BitfieldSpecifier)] #[bits = 3] #[derive(Clone, Debug, Eq, PartialEq, Copy)] pub enum ObjectTag { Directory, Blob, Commit, InodePointers, ShapedDirectory, } #[bitfield(bits = 8)] #[derive(Debug)] pub struct ObjectHeader { #[allow(dead_code)] tag: ObjectTag, length: ObjectLength, is_persistent: bool, #[skip] _unused: B2, } impl ObjectHeader { pub fn get_length(&self) -> ObjectLength { self.length() } pub fn get_persistent(&self) -> bool { self.is_persistent() } } #[derive(Copy, Clone, Default, Debug)] struct PointersHeader { bitfield: u32, } impl PointersHeader { fn set(&mut self, index: usize) { self.bitfield |= 1 << index; } fn get(&self, index: usize) -> bool { self.bitfield & 1 << index != 0 } fn to_bytes(self) -> [u8; 4] { self.bitfield.to_le_bytes() } fn iter(&self) -> PointersHeaderIterator { PointersHeaderIterator { bitfield: *self, current: 0, } } fn from_bytes(bytes: [u8; 4]) -> Self { Self { bitfield: u32::from_le_bytes(bytes), } } fn count(&self) -> u8 { self.bitfield.count_ones() as u8 } } impl From<&[Option<PointerToInode>; 32]> for PointersHeader { fn from(pointers: &[Option<PointerToInode>; 32]) -> Self { let mut bitfield = Self::default(); for (index, pointer) in pointers.iter().enumerate() { if pointer.is_some() { bitfield.set(index); } } bitfield } } struct PointersHeaderIterator { bitfield: PointersHeader, current: usize, } impl Iterator for PointersHeaderIterator { type Item = usize; fn next(&mut self) -> Option<Self::Item> { for index in self.current..32 { if self.bitfield.get(index) { self.current = index + 1; return Some(index); } } None } } #[derive(Debug, Error)] pub enum SerializationError { #[error("IOError {error}")] IOError { #[from] error: std::io::Error, }, #[error("Directory not found")] DirNotFound, #[error("Directory entry not found")] DirEntryNotFound, #[error("Blob not found")] BlobNotFound, #[error("Conversion from int failed: {error}")] TryFromIntError { #[from] error: TryFromIntError, }, #[error("StorageIdError: {error}")] StorageIdError { #[from] error: StorageError, }, #[error("HashId too big")] HashIdTooBig, #[error("Missing HashId")] MissingHashId, #[error("DBError: {error}")] DBError { #[from] error: DBError, }, #[error("Missing Offset")] MissingOffset, #[error("Hashing Error: {error}")] HashingError { #[from] error: HashingError, }, } #[derive(Debug, Error)] pub enum DeserializationError { #[error("Unexpected end of file")] UnexpectedEOF, #[error("Conversion from slice to an array failed")] TryFromSliceError { #[from] error: TryFromSliceError, }, #[error("Bytes are not valid utf-8: {error}")] Utf8Error { #[from] error: Utf8Error, }, #[error("UnknownID")] UnknownID, #[error("Vector is not valid utf-8: {error}")] FromUtf8Error { #[from] error: FromUtf8Error, }, #[error("Root hash is missing")] MissingRootHash, #[error("Hash is missing")] MissingHash, #[error("Offset is missing")] MissingOffset, #[error("DirEntryIdError: {error}")] DirEntryIdError { #[from] error: DirEntryIdError, }, #[error("StorageIdError: {error:?}")] StorageIdError { #[from] error: StorageError, }, #[error("Inode not found in repository")] InodeNotFoundInRepository, #[error("Inode empty in repository")] InodeEmptyInRepository, #[error("DBError: {error:?}")] DBError { #[from] error: Box<DBError>, }, #[error("Cannot find next shape")] CannotFindNextShape, #[error("Directory shape error: {error:?}")] DirectoryShapeError { #[from] error: DirectoryShapeError, }, #[error("IOError: {error:?}")] IOError { #[from] error: std::io::Error, }, } pub fn deserialize_hash_id(data: &[u8]) -> Result<(Option<HashId>, usize), DeserializationError> { use DeserializationError::*; let byte_hash_id = data.get(0).copied().ok_or(UnexpectedEOF)?; if byte_hash_id & 1 << 7 != 0 { let hash_id = data.get(0..4).ok_or(UnexpectedEOF)?; let hash_id = u32::from_be_bytes(hash_id.try_into()?); let hash_id = hash_id as u64; let hash_id = hash_id & (COMPACT_HASH_ID_BIT - 1); let hash_id = HashId::new(hash_id); Ok((hash_id, 4)) } else { let hash_id = data.get(0..6).ok_or(UnexpectedEOF)?; let hash_id = (hash_id[0] as u64) << 40 | (hash_id[1] as u64) << 32 | (hash_id[2] as u64) << 24 | (hash_id[3] as u64) << 16 | (hash_id[4] as u64) << 8 | (hash_id[5] as u64); let hash_id = HashId::new(hash_id); Ok((hash_id, 6)) } } pub fn serialize_hash_id_impl( hash_id: Option<HashId>, output: &mut Vec<u8>, repository: &mut ContextKeyValueStore, stats: &mut SerializeStats, ) -> Result<(), SerializationError> { let hash_id = match hash_id { Some(hash_id) => repository.make_hash_id_ready_for_commit(hash_id)?.as_u64(), None => 0, }; stats.highest_hash_id = stats.highest_hash_id.max(hash_id); if hash_id & FULL_31_BITS == hash_id { let hash_id: u64 = hash_id | COMPACT_HASH_ID_BIT; let hash_id: [u8; 8] = hash_id.to_be_bytes(); output.write_all(&hash_id[4..])?; stats.hash_ids_length = stats.hash_ids_length.saturating_add(4); Ok(()) } else if hash_id & FULL_47_BITS == hash_id { output.write_all(&hash_id.to_be_bytes()[2..])?; stats.hash_ids_length = stats.hash_ids_length.saturating_add(6); Ok(()) } else { Err(SerializationError::HashIdTooBig) } } pub fn serialize_hash_id<T>( hash_id: T, output: &mut Vec<u8>, repository: &mut ContextKeyValueStore, stats: &mut SerializeStats, ) -> Result<(), SerializationError> where T: Into<Option<HashId>>, { let hash_id: Option<HashId> = hash_id.into(); serialize_hash_id_impl(hash_id, output, repository, stats) }
use std::{ array::TryFromSliceError, convert::TryInto, io::Write, num::TryFromIntError, str::Utf8Error, string::FromUtf8Error, sync::Arc, }; use modular_bitfield::prelude::*; use tezos_timing::SerializeStats; use thiserror::Error; use crate::{ hash::HashingError, kv_store::HashId, persistent::DBError, working_tree::{ shape::DirectoryShapeError, storage::{DirEntryIdError, PointerToInode, Storage, StorageError}, string_interner::StringInterner, Object, }, ContextKeyValueStore, }; use self::persistent::AbsoluteOffset; pub mod in_memory; pub mod persistent; const COMPACT_HASH_ID_BIT: u64 = 1 << 31; const FULL_47_BITS: u64 = 0x7FFFFFFFFFFF; const FULL_31_BITS: u64 = 0x7FFFFFFF; pub type SerializeObjectSignature = fn( &Object, HashId, &mut Vec<u8>, &Storage, &StringInterner, &mut SerializeStats, &mut Vec<(HashId, Arc<[u8]>)>, &mut Vec<HashId>, &mut ContextKeyValueStore, Option<AbsoluteOffset>, ) -> Result<Option<AbsoluteOffset>, SerializationError>; #[derive(BitfieldSpecifier)] #[bits = 2] #[derive(Clone, Debug, Eq, PartialEq, Copy)] pub enum ObjectLength { OneByte, TwoBytes, FourBytes, } #[derive(BitfieldSpecifier)] #[bits = 3] #[derive(Clone, Debug, Eq, PartialEq, Copy)] pub enum ObjectTag { Directory, Blob, Commit, InodePointers, ShapedDirectory, } #[bitfield(bits = 8)] #[derive(Debug)] pub struct ObjectHeader { #[allow(dead_code)] tag: ObjectTag, length: ObjectLength, is_persistent: bool, #[skip] _unused: B2, } impl ObjectHeader { pub fn get_length(&self) -> ObjectLength { self.length() } pub fn get_persistent(&self) -> bool { self.is_persistent() } } #[derive(Copy, Clone, Default, Debug)] struct PointersHeader { bitfield: u32, } impl PointersHeader { fn set(&mut self, index: usize) { self.bitfield |= 1 << index; } fn get(&self, index: usize) -> bool { self.bitfield & 1 << index != 0 } fn to_bytes(self) -> [u8; 4] { self.bitfield.to_le_bytes() } fn iter(&self) -> PointersHeaderIterator { PointersHeaderIterator { bitfield: *self, current: 0, } } fn from_bytes(bytes: [u8; 4]) -> Self { Self { bitfield: u32::from_le_bytes(bytes), } } fn count(&self) -> u8 { self.bitfield.count_ones() as u8 } } impl From<&[Option<PointerToInode>; 32]> for PointersHeader { fn from(pointers: &[Option<PointerToInode>; 32]) -> Self { let mut bitfield = Self::default(); for (index, pointer) in pointers.iter().enumerate() { if pointer.is_some() { bitfield.set(index); } } bitfield } } struct PointersHeaderIterator { bitfield: PointersHeader, current: usize, } impl Iterator for PointersHeaderIterator { type Item = usize; fn next(&mut self) -> Option<Self::Item> { for index in self.current..32 { if self.bitfield.get(index) { self.current = index + 1; return Some(index); } } None } } #[derive(Debug, Error)] pub enum SerializationError { #[error("IOError {error}")] IOError { #[from] error: std::io::Error, }, #[error("Directory not found")] DirNotFound, #[error("Directory entry not found")] DirEntryNotFound, #[error("Blob not found")] BlobNotFound, #[error("Conversion from int failed: {error}")] TryFromIntError { #[from] error: TryFromIntError, }, #[error("StorageIdError: {error}")] StorageIdError { #[from] error: StorageError, }, #[error("HashId too big")] HashIdTooBig, #[error("Missing HashId")] MissingHashId, #[error("DBError: {error}")] DBError { #[from] error: DBError, }, #[error("Missing Offset")] MissingOffset, #[error("Hashing Error: {error}")] HashingError { #[from] error: HashingError, }, } #[derive(Debug, Error)] pub enum DeserializationError { #[error("Unexpected end of file")] UnexpectedEOF, #[error("Conversion from slice to an array failed")] TryFromSliceError { #[from] error: TryFromSliceError, }, #[error("Bytes are not valid utf-8: {error}")] Utf8Error { #[from] error: Utf8Error, }, #[error("UnknownID")] UnknownID, #[error("Vector is not valid utf-8: {error}")] FromUtf8Error { #[from] error: FromUtf8Error, }, #[error("Root hash is missing")] MissingRootHash, #[error("Hash is missing")] MissingHash, #[error("Offset is missing")] MissingOffset, #[error("DirEntryIdError: {error}")] DirEntryIdError { #[from] error: DirEntryIdError, }, #[error("StorageIdError: {error:?}")] StorageIdError { #[from] error: StorageError, }, #[error("Inode not found in repository")] InodeNotFoundInRepository, #[error("Inode empty in repository")] InodeEmptyInRepository, #[error("DBError: {error:?}")] DBError { #[from] error: Box<DBError>, }, #[error("Cannot find next shape")] CannotFindNextShape, #[error("Directory shape error: {error:?}")] DirectoryShapeError { #[from] error: DirectoryShapeError, }, #[error("IOError: {error:?}")] IOError { #[from] error: std::io::Error, }, } pub fn deserialize_hash_id(data: &[u8]) -> Result<(Option<HashId>, usize), DeserializationError> { use DeserializationError::*; let byte_hash_id = data.get(0).copied().ok_or(UnexpectedEOF)?; if byte_hash_id & 1 << 7 != 0 { let hash_id = data.get(0..4).ok_or(UnexpectedEOF)?; let hash_id = u3
pub fn serialize_hash_id_impl( hash_id: Option<HashId>, output: &mut Vec<u8>, repository: &mut ContextKeyValueStore, stats: &mut SerializeStats, ) -> Result<(), SerializationError> { let hash_id = match hash_id { Some(hash_id) => repository.make_hash_id_ready_for_commit(hash_id)?.as_u64(), None => 0, }; stats.highest_hash_id = stats.highest_hash_id.max(hash_id); if hash_id & FULL_31_BITS == hash_id { let hash_id: u64 = hash_id | COMPACT_HASH_ID_BIT; let hash_id: [u8; 8] = hash_id.to_be_bytes(); output.write_all(&hash_id[4..])?; stats.hash_ids_length = stats.hash_ids_length.saturating_add(4); Ok(()) } else if hash_id & FULL_47_BITS == hash_id { output.write_all(&hash_id.to_be_bytes()[2..])?; stats.hash_ids_length = stats.hash_ids_length.saturating_add(6); Ok(()) } else { Err(SerializationError::HashIdTooBig) } } pub fn serialize_hash_id<T>( hash_id: T, output: &mut Vec<u8>, repository: &mut ContextKeyValueStore, stats: &mut SerializeStats, ) -> Result<(), SerializationError> where T: Into<Option<HashId>>, { let hash_id: Option<HashId> = hash_id.into(); serialize_hash_id_impl(hash_id, output, repository, stats) }
2::from_be_bytes(hash_id.try_into()?); let hash_id = hash_id as u64; let hash_id = hash_id & (COMPACT_HASH_ID_BIT - 1); let hash_id = HashId::new(hash_id); Ok((hash_id, 4)) } else { let hash_id = data.get(0..6).ok_or(UnexpectedEOF)?; let hash_id = (hash_id[0] as u64) << 40 | (hash_id[1] as u64) << 32 | (hash_id[2] as u64) << 24 | (hash_id[3] as u64) << 16 | (hash_id[4] as u64) << 8 | (hash_id[5] as u64); let hash_id = HashId::new(hash_id); Ok((hash_id, 6)) } }
function_block-function_prefixed
[ { "content": "fn write_object_header(output: &mut Vec<u8>, start: usize, tag: ObjectTag) {\n\n let length = output.len() - start;\n\n\n\n if length <= 0xFF {\n\n let header: [u8; 1] = ObjectHeader::new()\n\n .with_tag(tag)\n\n .with_length(ObjectLength::OneByte)\n\n ...
Rust
vendor/pulldown-cmark/src/simd.rs
47565647456/evtx
fbb2a713d335f5208bb6675f4f158babd6f2f389
use crate::parse::{LookupTable, LoopInstruction, Options}; use core::arch::x86_64::*; pub(crate) const VECTOR_SIZE: usize = std::mem::size_of::<__m128i>(); pub(crate) fn compute_lookup(options: &Options) -> [u8; 16] { let mut lookup = [0u8; 16]; let standard_bytes = [ b'\n', b'\r', b'*', b'_', b'&', b'\\', b'[', b']', b'<', b'!', b'`', ]; for &byte in &standard_bytes { add_lookup_byte(&mut lookup, byte); } if options.contains(Options::ENABLE_TABLES) { add_lookup_byte(&mut lookup, b'|'); } if options.contains(Options::ENABLE_STRIKETHROUGH) { add_lookup_byte(&mut lookup, b'~'); } if options.contains(Options::ENABLE_SMART_PUNCTUATION) { for &byte in &[b'.', b'-', b'"', b'\''] { add_lookup_byte(&mut lookup, byte); } } lookup } fn add_lookup_byte(lookup: &mut [u8; 16], byte: u8) { lookup[(byte & 0x0f) as usize] |= 1 << (byte >> 4); } #[target_feature(enable = "ssse3")] #[inline] unsafe fn compute_mask(lut: &[u8; 16], bytes: &[u8], ix: usize) -> i32 { debug_assert!(bytes.len() >= ix + VECTOR_SIZE); let bitmap = _mm_loadu_si128(lut.as_ptr() as *const __m128i); let bitmask_lookup = _mm_setr_epi8(1, 2, 4, 8, 16, 32, 64, -128, -1, -1, -1, -1, -1, -1, -1, -1); let raw_ptr = bytes.as_ptr().add(ix) as *const __m128i; let input = _mm_loadu_si128(raw_ptr); let bitset = _mm_shuffle_epi8(bitmap, input); let higher_nibbles = _mm_and_si128(_mm_srli_epi16(input, 4), _mm_set1_epi8(0x0f)); let bitmask = _mm_shuffle_epi8(bitmask_lookup, higher_nibbles); let tmp = _mm_and_si128(bitset, bitmask); let result = _mm_cmpeq_epi8(tmp, bitmask); _mm_movemask_epi8(result) } pub(crate) fn iterate_special_bytes<F, T>( lut: &LookupTable, bytes: &[u8], ix: usize, callback: F, ) -> (usize, Option<T>) where F: FnMut(usize, u8) -> LoopInstruction<Option<T>>, { if is_x86_feature_detected!("ssse3") && bytes.len() >= VECTOR_SIZE { unsafe { simd_iterate_special_bytes(&lut.simd, bytes, ix, callback) } } else { crate::parse::scalar_iterate_special_bytes(&lut.scalar, bytes, ix, callback) } } unsafe fn process_mask<F, T>( mut mask: i32, bytes: &[u8], mut offset: usize, callback: &mut F, ) -> Result<usize, (usize, Option<T>)> where F: FnMut(usize, u8) -> LoopInstruction<Option<T>>, { while mask != 0 { let mask_ix = mask.trailing_zeros() as usize; offset += mask_ix; match callback(offset, *bytes.get_unchecked(offset)) { LoopInstruction::ContinueAndSkip(skip) => { offset += skip + 1; mask >>= skip + 1 + mask_ix; } LoopInstruction::BreakAtWith(ix, val) => return Err((ix, val)), } } Ok(offset) } #[target_feature(enable = "ssse3")] unsafe fn simd_iterate_special_bytes<F, T>( lut: &[u8; 16], bytes: &[u8], mut ix: usize, mut callback: F, ) -> (usize, Option<T>) where F: FnMut(usize, u8) -> LoopInstruction<Option<T>>, { debug_assert!(bytes.len() >= VECTOR_SIZE); let upperbound = bytes.len() - VECTOR_SIZE; while ix < upperbound { let mask = compute_mask(lut, bytes, ix); let block_start = ix; ix = match process_mask(mask, bytes, ix, &mut callback) { Ok(ix) => std::cmp::max(ix, VECTOR_SIZE + block_start), Err((end_ix, val)) => return (end_ix, val), }; } if bytes.len() > ix { let mask = compute_mask(lut, bytes, upperbound) >> ix - upperbound; if let Err((end_ix, val)) = process_mask(mask, bytes, ix, &mut callback) { return (end_ix, val); } } (bytes.len(), None) } #[cfg(test)] mod simd_test { use super::{iterate_special_bytes, LoopInstruction}; use crate::Options; fn check_expected_indices(bytes: &[u8], expected: &[usize], skip: usize) { let mut opts = Options::empty(); opts.insert(Options::ENABLE_TABLES); opts.insert(Options::ENABLE_FOOTNOTES); opts.insert(Options::ENABLE_STRIKETHROUGH); opts.insert(Options::ENABLE_TASKLISTS); let lut = crate::parse::create_lut(&opts); let mut indices = vec![]; iterate_special_bytes::<_, i32>(&lut, bytes, 0, |ix, _byte_ty| { indices.push(ix); LoopInstruction::ContinueAndSkip(skip) }); assert_eq!(&indices[..], expected); } #[test] fn simple_no_match() { check_expected_indices("abcdef0123456789".as_bytes(), &[], 0); } #[test] fn simple_match() { check_expected_indices("*bcd&f0123456789".as_bytes(), &[0, 4], 0); } #[test] fn single_open_fish() { check_expected_indices("<".as_bytes(), &[0], 0); } #[test] fn long_match() { check_expected_indices("0123456789abcde~*bcd&f0".as_bytes(), &[15, 16, 20], 0); } #[test] fn border_skip() { check_expected_indices("0123456789abcde~~~~d&f0".as_bytes(), &[15, 20], 3); } #[test] fn exhaustive_search() { let chars = [ b'\n', b'\r', b'*', b'_', b'~', b'|', b'&', b'\\', b'[', b']', b'<', b'!', b'`', ]; for &c in &chars { for i in 0u8..=255 { if !chars.contains(&i) { let mut buf = [i; 18]; buf[3] = c; buf[6] = c; check_expected_indices(&buf[..], &[3, 6], 0); } } } } }
use crate::parse::{LookupTable, LoopInstruction, Options}; use core::arch::x86_64::*; pub(crate) const VECTOR_SIZE: usize = std::mem::size_of::<__m128i>(); pub(crate) fn compute_lookup(options: &Options) -> [u8; 16] { let mut lookup = [0u8; 16]; let standard_bytes = [ b'\n', b'\r', b'*', b'_', b'&', b'\\', b'[', b']', b'<', b'!', b'`', ]; for &byte in &standard_bytes { add_lookup_byte(&mut lookup, byte); } if options.contains(Options::ENABLE_TABLES) { add_lookup_byte(&mut lookup, b'|'); } if options.contains(Options::ENABLE_STRIKETHROUGH) { add_lookup_byte(&mut lookup, b'~'); } if options.contains(Options::ENABLE_SMART_PUNCTUATION) { for &byte in &[b'.', b'-', b'"', b'\''] { add_lookup_byte(&mut lookup, byte); } } lookup } fn add_lookup_byte(lookup: &mut [u8; 16], byte: u8) { lookup[(byte & 0x0f) as usize] |= 1 << (byte >> 4); } #[target_feature(enable = "ssse3")] #[inline] unsafe fn compute_mask(lut: &[u8; 16], bytes: &[u8], ix: usize) -> i32 { debug_assert!(bytes.len() >= ix + VECTOR_SIZE); let bitmap = _mm_loadu_si128(lut.as_ptr() as *const __m128i); let bitmask_lookup = _mm_setr_epi8(1, 2, 4, 8, 16, 32, 64, -128, -1, -1, -1, -1, -1, -1, -1, -1); let raw_ptr = bytes.as_ptr().add(ix) as *const __m128i; let input = _mm_loadu_si128(raw_ptr); let bitset = _mm_shuffle_epi8(bitmap, input); let higher_nibbles = _mm_and_si128(_mm_srli_epi16(input, 4), _mm_set1_epi8(0x0f)); let bitmask = _mm_shuffle_epi8(bitmask_lookup, higher_nibbles); let tmp = _mm_and_si128(bitset, bitmask); let result = _mm_cmpeq_epi8(tmp, bitmask); _mm_movemask_epi8(result) } pub(crate) fn iterate_special_bytes<F, T>( lut: &LookupTable, bytes: &[u8], ix: usize, callback: F, ) -> (usize, Option<T>) where F: FnMut(usize, u8) -> LoopInstruction<Option<T>>, { if is_x86_feature_detected!("ssse3") && bytes.len() >= VECTOR_SIZE { unsafe { simd_iterate_special_bytes(&lut.simd, bytes, ix, callback) } } else { crate::parse::scalar_iterate_special_bytes(&lut.scalar, bytes, ix, callback) } } unsafe fn process_mask<F, T>( mut mask: i32, bytes: &[u8], mut offset: usize, callback: &mut F, ) -> Result<usize, (usize, Option<T>)> where F: FnMut(usize, u8) -> LoopInstruction<Option<T>>, { while mask != 0 { let mask_ix = mask.trailing_zeros() as usize; offset += mask_ix; match callback(offset, *bytes.get_unchecked(offset)) { LoopInstruction::ContinueAndSkip(skip) => { offset += skip + 1; mask >>= skip + 1 + mask_ix; } LoopInstruction::BreakAtWith(ix, val) => return Err((ix, val)), } } Ok(offset) } #[target_feature(enable = "ssse3")] unsafe fn simd_iterate_special_bytes<F, T>( lut: &[u8; 16], bytes: &[u8], mut ix: usize, mut callback: F, ) -> (usize, Option<T>) where F: FnMut(usize, u8) -> LoopInstruction<Option<T>>, { debug_assert!(bytes.len() >= VECTOR_SIZE); let upperbound = bytes.len() - VECTOR_SIZE; while ix < upperbound { let mask = compute_mask(lut, bytes, ix); let block_start = ix; ix = match process_mask(mask, bytes, ix, &mut callback) { Ok(ix) => std::cmp::max(ix, VECTOR_SIZE + block_start), Err((end_ix, val)) => return (end_ix, val), }; } if bytes.len() > ix { let mask = compute_mask(lut, bytes, upperbound) >> ix - upperbound; if let Err((end_ix, val)) = process_mask(mask, bytes, ix, &mut callback) { return (end_ix, val); } } (bytes.len(), None) } #[cfg(test)] mod simd_test { use super::{iterate_special_bytes, LoopIn
pts = Options::empty(); opts.insert(Options::ENABLE_TABLES); opts.insert(Options::ENABLE_FOOTNOTES); opts.insert(Options::ENABLE_STRIKETHROUGH); opts.insert(Options::ENABLE_TASKLISTS); let lut = crate::parse::create_lut(&opts); let mut indices = vec![]; iterate_special_bytes::<_, i32>(&lut, bytes, 0, |ix, _byte_ty| { indices.push(ix); LoopInstruction::ContinueAndSkip(skip) }); assert_eq!(&indices[..], expected); } #[test] fn simple_no_match() { check_expected_indices("abcdef0123456789".as_bytes(), &[], 0); } #[test] fn simple_match() { check_expected_indices("*bcd&f0123456789".as_bytes(), &[0, 4], 0); } #[test] fn single_open_fish() { check_expected_indices("<".as_bytes(), &[0], 0); } #[test] fn long_match() { check_expected_indices("0123456789abcde~*bcd&f0".as_bytes(), &[15, 16, 20], 0); } #[test] fn border_skip() { check_expected_indices("0123456789abcde~~~~d&f0".as_bytes(), &[15, 20], 3); } #[test] fn exhaustive_search() { let chars = [ b'\n', b'\r', b'*', b'_', b'~', b'|', b'&', b'\\', b'[', b']', b'<', b'!', b'`', ]; for &c in &chars { for i in 0u8..=255 { if !chars.contains(&i) { let mut buf = [i; 18]; buf[3] = c; buf[6] = c; check_expected_indices(&buf[..], &[3, 6], 0); } } } } }
struction}; use crate::Options; fn check_expected_indices(bytes: &[u8], expected: &[usize], skip: usize) { let mut o
random
[ { "content": "pub fn read_attribute(cursor: &mut Cursor<&[u8]>) -> Result<BinXMLAttribute> {\n\n trace!(\"Offset `0x{:08x}` - Attribute\", cursor.position());\n\n let name = BinXmlNameRef::from_stream(cursor)?;\n\n\n\n Ok(BinXMLAttribute { name })\n\n}\n\n\n", "file_path": "src/binxml/tokens.rs", ...
Rust
src/creeps/lrh.rs
snorrwe/xenos
2b625daf8edea133949a70dcf1579dddc65a3668
use super::{ approach_target_room, gofer, harvester, update_scout_info, upgrader, CreepState, HOME_ROOM, LOADING, TARGET, TASK, }; use crate::prelude::*; use crate::state::RoomIFF; use num::FromPrimitive; use screeps::prelude::*; const HARVEST_TARGET_ROOM: &'static str = "harvest_target_room"; #[derive(Debug, Clone, Copy, FromPrimitive, ToPrimitive)] #[repr(u8)] enum LrhState { Idle = 0, Loading = 1, Unloading = 2, } pub fn run<'a>(state: &mut CreepState) -> ExecutionResult { let last_task = state.creep_memory_i64(TASK).unwrap_or(0); let last_task = LrhState::from_u32(last_task as u32).unwrap_or(LrhState::Idle); let mut priorities = [0; 3]; priorities[last_task as usize] += 1; let mut tasks = [ Task::new(|state| load(state)) .with_name("Load") .with_state_save(LrhState::Loading) .with_priority(priorities[LrhState::Loading as usize]) .with_required_bucket(2000), Task::new(|state| unload(state)) .with_name("Unload") .with_state_save(LrhState::Unloading) .with_priority(priorities[LrhState::Unloading as usize]), Task::new(|state| harvester::unload(state)) .with_name("Harvester unload") .with_priority(-1), Task::new(|state| upgrader::attempt_upgrade(state)).with_priority(-2), ]; sorted_by_priority(&mut tasks); sequence(state, tasks.iter()) } fn load<'a>(state: &mut CreepState) -> ExecutionResult { trace!("Loading"); if !state.creep_memory_bool(LOADING).unwrap_or(false) { Err("not loading")?; } let creep = state.creep(); if creep.carry_total() == creep.carry_capacity() { state.creep_memory_set(LOADING.into(), false); state.creep_memory_remove(TARGET); Err("full")?; } let tasks = [ Task::new(|state| approach_target_room(state, HARVEST_TARGET_ROOM)) .with_name("Approach target room"), Task::new(|state| set_target_room(state)).with_name("Set target room"), Task::new(|state| { update_scout_info(state)?; Err("continue")? }) .with_name("Update scout info"), Task::new(|state| harvester::attempt_harvest(state, Some(TARGET))) .with_name("Attempt harvest"), ]; sequence(state, tasks.iter()) } fn set_target_room<'a>(state: &'a mut CreepState) -> ExecutionResult { { let target = state.creep_memory_string(HARVEST_TARGET_ROOM); if target.is_some() { Err("Already has a target")?; } } let room = { let creep = state.creep(); creep.room() }; let room = WorldPosition::from(room); let neighbours = room.neighbours_in_vectors(); let target = { let gs: &mut GameState = unsafe { &mut *state.mut_game_state() }; let counts: &mut _ = gs .long_range_harvesters .entry(room) .or_insert([0; 4]); let scout_intel = &gs.scout_intel; let (i, target) = neighbours .iter() .enumerate() .filter(|(_, wp)| { scout_intel .get(&wp) .map(|int| match int.iff { RoomIFF::Unknown | RoomIFF::Neutral => true, _ => false, }) .unwrap_or(true) }) .min_by_key(|(i, _)| counts[*i]) .ok_or_else(|| { warn!( "Failed to find target room of LRH {:?} in room {:?}", state.creep().name(), state.creep().room().name() ); "Failed to find a target room" })?; counts[i] += 1; target }; state.creep_memory_set(HARVEST_TARGET_ROOM.into(), target.to_string().as_str()); Ok(()) } fn unload<'a>(state: &mut CreepState) -> ExecutionResult { trace!("Unloading"); if state.creep_memory_bool(LOADING).unwrap_or(false) { Err("loading")?; } if state.creep().carry_total() == 0 { state.creep_memory_set(LOADING.into(), true); state.creep_memory_remove(TARGET); Err("empty")?; } let tasks = [ Task::new(|state| approach_target_room(state, HOME_ROOM)).with_name("Approach target room"), Task::new(|state| gofer::attempt_unload(state)).with_name("Attempt unload"), ]; sequence(state, tasks.iter()) }
use super::{ approach_target_room, gofer, harvester, update_scout_info, upgrader, CreepState, HOME_ROOM, LOADING, TARGET, TASK, }; use crate::prelude::*; use crate::state::RoomIFF; use num::FromPrimitive; use screeps::prelude::*; const HARVEST_TARGET_ROOM: &'static str = "harvest_target_room"; #[derive(Debug, Clone, Copy, FromPrimitive, ToPrimitive)] #[repr(u8)] enum LrhState { Idle = 0, Loading = 1, Unloading = 2, } pub fn run<'a>(state: &mut CreepState) -> ExecutionResult { let last_task = state.creep_memory_i64(TASK).unwrap_or(0); let last_task = LrhState::from_u32(last_task as u32).unwrap_or(LrhState::Idle); let mut priorities = [0; 3]; priorities[last_task as usize] += 1; let mut tasks = [ Task::new(|state| load(state)) .with_name("Load") .with_state_save(LrhState::Loading) .with_priority(priorities[LrhState::Loading as usize]) .with_required_bucket(2000), Task::new(|state| unload(state)) .with_name("Unload") .with_state_save(LrhState::Unloading) .with_priority(priorities[LrhState::Unloading as usize]), Task::new(|state| harvester::unload(state)) .with_name("Harvester unload") .with_priority(-1), Task::new(|state| upgrader::attempt_upgrade(state)).with_priority(-2), ]; sorted_by_priority(&mut tasks); sequence(state, tasks.iter()) } fn load<'a>(state: &mut CreepState) -> ExecutionResult { trace!("Loading"); if !state.creep_memory_bool(LOADING).unwrap_or(false) { Err("not loading")?; } let creep = state.creep(); if creep.carry_total() == creep.carry_capacity() { state.creep_memory_set(LOADING.into(), false); state.creep_memory_remove(TARGET); Err("full")?; } let tasks = [ Task::new(|state| approach_target_room(state, HARVEST_TARGET_ROOM)) .with_name("Approach target room"), Task::new(|state| set_target_room(state)).with_name("Set target room"), Task::new(|state| { update_scout_info(state)?; Err("continue")? }) .with_name("Update scout info"), Task::new(|state| harvester::attempt_harvest(state, Some(TARGET))) .with_name("Attempt harvest"), ]; sequence(state, tasks.iter()) } fn set_target_room<'a>(state: &'a mut CreepState) -> ExecutionResult { { let target = state.creep_memory_string(HARVEST_TARGET_ROOM); if target.is_some() { Err("Already has a target")?; } } let room = { let creep = state.creep(); creep.room() }; let room = WorldPosition::from(room); let neighbours = room.neighbours_in_vectors(); let target = { let gs: &mut GameState = unsafe
() .enumerate() .filter(|(_, wp)| { scout_intel .get(&wp) .map(|int| match int.iff { RoomIFF::Unknown | RoomIFF::Neutral => true, _ => false, }) .unwrap_or(true) }) .min_by_key(|(i, _)| counts[*i]) .ok_or_else(|| { warn!( "Failed to find target room of LRH {:?} in room {:?}", state.creep().name(), state.creep().room().name() ); "Failed to find a target room" })?; counts[i] += 1; target }; state.creep_memory_set(HARVEST_TARGET_ROOM.into(), target.to_string().as_str()); Ok(()) } fn unload<'a>(state: &mut CreepState) -> ExecutionResult { trace!("Unloading"); if state.creep_memory_bool(LOADING).unwrap_or(false) { Err("loading")?; } if state.creep().carry_total() == 0 { state.creep_memory_set(LOADING.into(), true); state.creep_memory_remove(TARGET); Err("empty")?; } let tasks = [ Task::new(|state| approach_target_room(state, HOME_ROOM)).with_name("Approach target room"), Task::new(|state| gofer::attempt_unload(state)).with_name("Attempt unload"), ]; sequence(state, tasks.iter()) }
{ &mut *state.mut_game_state() }; let counts: &mut _ = gs .long_range_harvesters .entry(room) .or_insert([0; 4]); let scout_intel = &gs.scout_intel; let (i, target) = neighbours .iter
function_block-random_span
[ { "content": "/// target_key is a memory entry key\n\npub fn approach_target_room(state: &mut CreepState, target_key: &str) -> ExecutionResult {\n\n let target = state.creep_memory_string(target_key).ok_or(\"no target\")?;\n\n\n\n let creep = state.creep();\n\n\n\n let room = creep.room();\n\n let r...
Rust
libeir_ir/src/algo/equality.rs
lumen/eir
37e790f388d13a836991f8a6220eb322269d509e
use std::collections::{BTreeMap, VecDeque}; use snafu::Snafu; use crate::Function; use crate::ValueKind; use crate::{Block, Const, PrimOp, Value}; #[derive(Snafu, Debug, PartialEq, Eq)] pub enum EqualityFail { BlockArity { left: Block, right: Block }, BlockOp { left: Block, right: Block }, BlockReadsLength { left: Block, right: Block }, MismatchingValue { left: Value, right: Value }, PrimReadsLength { left: PrimOp, right: PrimOp }, MismatchingConst { left: Const, right: Const }, } struct EqCtx<'a> { lf: &'a Function, rf: &'a Function, to_walk: VecDeque<(Block, Block)>, to_check: Vec<(Value, Value)>, map: BTreeMap<Value, Value>, } impl Function { pub fn graph_eq( &self, lhs_block: Block, rhs: &Function, rhs_block: Block, ) -> Result<(), EqualityFail> { let mut ctx = EqCtx { lf: self, rf: rhs, map: BTreeMap::new(), to_walk: VecDeque::new(), to_check: Vec::new(), }; ctx.to_walk.push_back((lhs_block, rhs_block)); ctx.map .insert(ctx.lf.block_value(lhs_block), ctx.rf.block_value(rhs_block)); while let Some((l_b, r_b)) = ctx.to_walk.pop_front() { let l_block_val = ctx.lf.block_value(l_b); let r_block_val = ctx.rf.block_value(r_b); debug_assert_eq!(ctx.map.get(&l_block_val), Some(&r_block_val)); let l_args = ctx.lf.block_args(l_b); let r_args = ctx.rf.block_args(r_b); if l_args.len() != r_args.len() { return Result::Err(EqualityFail::BlockArity { left: l_b, right: r_b, }); } for (l, r) in l_args.iter().zip(r_args.iter()) { ctx.map.insert(*l, *r); } if !ctx.lf.block_op_eq(l_b, &ctx.rf, r_b) { return Result::Err(EqualityFail::BlockOp { left: l_b, right: r_b, }); } let l_reads = ctx.lf.block_reads(l_b); let r_reads = ctx.rf.block_reads(r_b); if l_reads.len() != r_reads.len() { return Result::Err(EqualityFail::BlockReadsLength { left: l_b, right: r_b, }); } for (l, r) in l_reads.iter().zip(r_reads.iter()) { traverse_value(&mut ctx, *l, *r)?; } } for (l, r) in ctx.to_check.iter() { if ctx.map.get(l) != Some(r) { return Result::Err(EqualityFail::MismatchingValue { left: *l, right: *r, }); } } Ok(()) } } fn traverse_value<'a>(ctx: &mut EqCtx<'a>, l: Value, r: Value) -> Result<(), EqualityFail> { if let Some(nr) = ctx.map.get(&l) { if *nr == r { return Ok(()); } else { return Err(EqualityFail::MismatchingValue { left: l, right: r }); } } match (ctx.lf.value_kind(l), ctx.rf.value_kind(r)) { (ValueKind::Block(lb), ValueKind::Block(rb)) => { ctx.map.insert(l, r); ctx.to_walk.push_back((lb, rb)); Ok(()) } (ValueKind::Argument(_, _), ValueKind::Argument(_, _)) => { ctx.to_check.push((l, r)); Ok(()) } (ValueKind::Const(lc), ValueKind::Const(rc)) => { if !ctx.lf.cons().eq_other(lc, ctx.rf.cons(), rc) { return Err(EqualityFail::MismatchingConst { left: lc, right: rc, }); } Ok(()) } (ValueKind::PrimOp(lp), ValueKind::PrimOp(rp)) => { let l_reads = ctx.lf.primop_reads(lp); let r_reads = ctx.rf.primop_reads(rp); if l_reads.len() != r_reads.len() { return Err(EqualityFail::PrimReadsLength { left: lp, right: rp, }); } for (l, r) in l_reads.iter().zip(r_reads.iter()) { traverse_value(ctx, *l, *r)?; } Ok(()) } _ => Err(EqualityFail::MismatchingValue { left: l, right: r }), } } #[cfg(test)] mod tests { use crate::parse_function_unwrap; #[test] fn basic_equality() { let ir1 = parse_function_unwrap( " a'foo':a'bar'/1 { entry(%ret, %thr, %arg1): block2(%arg1); block2(%b): block3(%b); block3(%a): %ret(%a); } ", ); let ir2 = parse_function_unwrap( " a'a':a'b'/1 { entry(%ret, %thr, %arg1): block2(%arg1); block3(%a): %ret(%a); block2(%b): block3(%b); } ", ); assert!(ir1 .graph_eq(ir1.block_entry(), &ir2, ir2.block_entry()) .is_ok()); } #[test] fn args_length_inequality() { let ir1 = parse_function_unwrap( " a'foo':a'bar'/2 { entry(%ret, %thr, %arg1, %arg2): %ret(%arg1); } ", ); let ir2 = parse_function_unwrap( " a'foo':a'bar'/1 { entry(%ret, %thr, %arg1): %ret(%arg1); } ", ); assert!(ir1 .graph_eq(ir1.block_entry(), &ir2, ir2.block_entry()) .is_err()); } #[test] fn args_read_inequality() { let ir1 = parse_function_unwrap( " a'foo':a'bar'/2 { entry(%ret, %thr, %arg1, %arg2): %ret(%arg1); } ", ); let ir2 = parse_function_unwrap( " a'foo':a'bar'/2 { entry(%ret, %thr, %arg1, %arg2): %ret(%arg2); } ", ); assert!(ir1 .graph_eq(ir1.block_entry(), &ir2, ir2.block_entry()) .is_err()); } #[test] fn args_read_const_equality() { let ir1 = parse_function_unwrap( " a'foo':a'bar'/2 { entry(%ret, %thr, %arg1, %arg2): %ret(a'a'); } ", ); let ir2 = parse_function_unwrap( " a'foo':a'bar'/2 { entry(%ret, %thr, %arg1, %arg2): %ret(a'a'); } ", ); assert!(ir1 .graph_eq(ir1.block_entry(), &ir2, ir2.block_entry()) .is_ok()); } #[test] fn args_read_const_inequality() { let ir1 = parse_function_unwrap( " a'foo':a'bar'/2 { entry(%ret, %thr, %arg1, %arg2): %ret(a'a'); } ", ); let ir2 = parse_function_unwrap( " a'foo':a'bar'/2 { entry(%ret, %thr, %arg1, %arg2): %ret(a'b'); } ", ); assert!(ir1 .graph_eq(ir1.block_entry(), &ir2, ir2.block_entry()) .is_err()); } #[test] fn args_prim_inequality() { let ir1 = parse_function_unwrap( " a'foo':a'bar'/1 { entry(%ret, %thr, %arg1): %fun = a'a':a'a'/1; %fun(%ret, %thr, %arg1); } ", ); let ir2 = parse_function_unwrap( " a'foo':a'bar'/1 { entry(%ret, %thr, %arg1): %fun = a'a':a'b'/1; %fun(%ret, %thr, %arg1); } ", ); assert!(ir1 .graph_eq(ir1.block_entry(), &ir2, ir2.block_entry()) .is_err()); } }
use std::collections::{BTreeMap, VecDeque}; use snafu::Snafu; use crate::Function; use crate::ValueKind; use crate::{Block, Const, PrimOp, Value}; #[derive(Snafu, Debug, PartialEq, Eq)] pub enum EqualityFail { BlockArity { left: Block, right: Block }, BlockOp { left: Block, right: Block }, BlockReadsLength { left: Block, right: Block }, MismatchingValue { left: Value, right: Value }, PrimReadsLength { left: PrimOp, right: PrimOp }, MismatchingConst { left: Const, right: Const }, } struct EqCtx<'a> { lf: &'a Function, rf: &'a Function, to_walk: VecDeque<(Block, Block)>, to_check: Vec<(Value, Value)>, map: BTreeMap<Value, Value>, } impl Function { pub fn graph_eq( &self, lhs_block: Block, rhs: &Function, rhs_block: Block, ) -> Result<(), EqualityFail> { let mut ctx = EqCtx { lf: self, rf: rhs, map: BTreeMap::new(), to_walk: VecDeque::new(), to_check: Vec::new(), }; ctx.to_walk.push_back((lhs_block, rhs_block)); ctx.map .insert(ctx.lf.block_value(lhs_block), ctx.rf.block_value(rhs_block)); while let Some((l_b, r_b)) = ctx.to_walk.pop_front() { let l_block_val = ctx.lf.block_value(l_b); let r_block_val = ctx.rf.block_value(r_b); debug_assert_eq!(ctx.map.get(&l_block_val), Some(&r_block_val)); let l_args = ctx.lf.block_args(l_b); let r_args = ctx.rf.block_args(r_b); if l_args.len() != r_args.len() { return Result::Err(EqualityFail::BlockArity { left: l_b, right: r_b, }); } for (l, r) in l_args.iter().zip(r_args.iter()) { ctx.map.insert(*l, *r); } if !ctx.lf.block_op_eq(l_b, &ctx.rf, r_b) { return Result::Err(EqualityFail::BlockOp { left: l_b, right: r_b, }); } let l_reads = ctx.lf.block_reads(l_b); let r_reads = ctx.rf.block_reads(r_b); if l_reads.len() != r_reads.len() { return Result::Err(EqualityFail::BlockReadsLength { left: l_b, right: r_b, }); } for (l, r) in l_reads.iter().zip(r_reads.iter()) { traverse_value(&mut ctx, *l, *r)?; } } for (l, r) in ctx.to_check.iter() { if ctx.map.get(l) != Some(r) { return Result::Err(EqualityFail::MismatchingValue { left: *l, right: *r, }); } } Ok(()) } } fn traverse_value<'a>(ctx: &mut EqCtx<'a>, l: Value, r: Value) -> Result<(), EqualityFail> { if let Some(nr) = ctx.map.get(&l) { if *nr == r { return Ok(()); } else { return Err(EqualityFail::MismatchingValue { left: l, right: r }); } } match (ctx.lf.value_kind(l), ctx.rf.value_kind(r)) { (ValueKind::Block(lb), ValueKind::Block(rb)) => { ctx.map.insert(l, r); ctx.to_walk.push_back((lb, rb)); Ok(()) } (ValueKind::Argument(_, _), ValueKind::Argument(_, _)) => { ctx.to_check.push((l, r)); Ok(()) } (ValueKind::Const(lc), ValueKind::Const(rc)) => {
Ok(()) } (ValueKind::PrimOp(lp), ValueKind::PrimOp(rp)) => { let l_reads = ctx.lf.primop_reads(lp); let r_reads = ctx.rf.primop_reads(rp); if l_reads.len() != r_reads.len() { return Err(EqualityFail::PrimReadsLength { left: lp, right: rp, }); } for (l, r) in l_reads.iter().zip(r_reads.iter()) { traverse_value(ctx, *l, *r)?; } Ok(()) } _ => Err(EqualityFail::MismatchingValue { left: l, right: r }), } } #[cfg(test)] mod tests { use crate::parse_function_unwrap; #[test] fn basic_equality() { let ir1 = parse_function_unwrap( " a'foo':a'bar'/1 { entry(%ret, %thr, %arg1): block2(%arg1); block2(%b): block3(%b); block3(%a): %ret(%a); } ", ); let ir2 = parse_function_unwrap( " a'a':a'b'/1 { entry(%ret, %thr, %arg1): block2(%arg1); block3(%a): %ret(%a); block2(%b): block3(%b); } ", ); assert!(ir1 .graph_eq(ir1.block_entry(), &ir2, ir2.block_entry()) .is_ok()); } #[test] fn args_length_inequality() { let ir1 = parse_function_unwrap( " a'foo':a'bar'/2 { entry(%ret, %thr, %arg1, %arg2): %ret(%arg1); } ", ); let ir2 = parse_function_unwrap( " a'foo':a'bar'/1 { entry(%ret, %thr, %arg1): %ret(%arg1); } ", ); assert!(ir1 .graph_eq(ir1.block_entry(), &ir2, ir2.block_entry()) .is_err()); } #[test] fn args_read_inequality() { let ir1 = parse_function_unwrap( " a'foo':a'bar'/2 { entry(%ret, %thr, %arg1, %arg2): %ret(%arg1); } ", ); let ir2 = parse_function_unwrap( " a'foo':a'bar'/2 { entry(%ret, %thr, %arg1, %arg2): %ret(%arg2); } ", ); assert!(ir1 .graph_eq(ir1.block_entry(), &ir2, ir2.block_entry()) .is_err()); } #[test] fn args_read_const_equality() { let ir1 = parse_function_unwrap( " a'foo':a'bar'/2 { entry(%ret, %thr, %arg1, %arg2): %ret(a'a'); } ", ); let ir2 = parse_function_unwrap( " a'foo':a'bar'/2 { entry(%ret, %thr, %arg1, %arg2): %ret(a'a'); } ", ); assert!(ir1 .graph_eq(ir1.block_entry(), &ir2, ir2.block_entry()) .is_ok()); } #[test] fn args_read_const_inequality() { let ir1 = parse_function_unwrap( " a'foo':a'bar'/2 { entry(%ret, %thr, %arg1, %arg2): %ret(a'a'); } ", ); let ir2 = parse_function_unwrap( " a'foo':a'bar'/2 { entry(%ret, %thr, %arg1, %arg2): %ret(a'b'); } ", ); assert!(ir1 .graph_eq(ir1.block_entry(), &ir2, ir2.block_entry()) .is_err()); } #[test] fn args_prim_inequality() { let ir1 = parse_function_unwrap( " a'foo':a'bar'/1 { entry(%ret, %thr, %arg1): %fun = a'a':a'a'/1; %fun(%ret, %thr, %arg1); } ", ); let ir2 = parse_function_unwrap( " a'foo':a'bar'/1 { entry(%ret, %thr, %arg1): %fun = a'a':a'b'/1; %fun(%ret, %thr, %arg1); } ", ); assert!(ir1 .graph_eq(ir1.block_entry(), &ir2, ir2.block_entry()) .is_err()); } }
if !ctx.lf.cons().eq_other(lc, ctx.rf.cons(), rc) { return Err(EqualityFail::MismatchingConst { left: lc, right: rc, }); }
if_condition
[ { "content": "fn lower_function(ctx: &mut LowerCtx, b: &mut FunctionBuilder, fun: &Function) -> IrBlock {\n\n let entry = b.block_insert_with_span(Some(fun.span()));\n\n\n\n match fun {\n\n Function::Named(_named) => unimplemented!(),\n\n Function::Unnamed(lambda) => {\n\n ctx.fun...
Rust
src/firmware/types.rs
tfanelli-rh/sev
e0e17aac9249b00b0cb3e24a2780ca814d229a11
use crate::certs::sev; use crate::Version; use std::marker::PhantomData; pub struct PlatformReset; bitflags::bitflags! { #[derive(Default)] pub struct PlatformStatusFlags: u32 { const OWNED = 1 << 0; const ENCRYPTED_STATE = 1 << 8; } } #[derive(Default)] #[repr(C, packed)] pub struct PlatformStatus { pub version: Version, pub state: u8, pub flags: PlatformStatusFlags, pub build: u8, pub guest_count: u32, } pub struct PekGen; #[repr(C, packed)] pub struct PekCsr<'a> { addr: u64, len: u32, _phantom: PhantomData<&'a ()>, } impl<'a> PekCsr<'a> { pub fn new(cert: &'a mut sev::Certificate) -> Self { Self { addr: cert as *mut _ as _, len: std::mem::size_of_val(cert) as _, _phantom: PhantomData, } } } #[repr(C, packed)] pub struct PekCertImport<'a> { pek_addr: u64, pek_len: u32, oca_addr: u64, oca_len: u32, _phantom: PhantomData<&'a ()>, } impl<'a> PekCertImport<'a> { pub fn new(pek: &'a sev::Certificate, oca: &'a sev::Certificate) -> Self { Self { pek_addr: pek as *const _ as _, pek_len: std::mem::size_of_val(pek) as _, oca_addr: oca as *const _ as _, oca_len: std::mem::size_of_val(oca) as _, _phantom: PhantomData, } } } pub struct PdhGen; #[repr(C, packed)] pub struct PdhCertExport<'a> { pdh_addr: u64, pdh_len: u32, certs_addr: u64, certs_len: u32, _phantom: PhantomData<&'a ()>, } impl<'a> PdhCertExport<'a> { pub fn new(pdh: &'a mut sev::Certificate, certs: &'a mut [sev::Certificate; 3]) -> Self { Self { pdh_addr: pdh as *mut _ as _, pdh_len: std::mem::size_of_val(pdh) as _, certs_addr: certs.as_mut_ptr() as _, certs_len: std::mem::size_of_val(certs) as _, _phantom: PhantomData, } } } #[repr(C, packed)] pub struct GetId<'a> { id_addr: u64, id_len: u32, _phantom: PhantomData<&'a ()>, } impl<'a> GetId<'a> { pub fn new(id: &'a mut [u8; 64]) -> Self { Self { id_addr: id.as_mut_ptr() as _, id_len: id.len() as _, _phantom: PhantomData, } } pub fn as_slice(&self) -> &[u8] { unsafe { std::slice::from_raw_parts(self.id_addr as *const u8, self.id_len as _) } } } #[derive(Default)] #[repr(C, packed)] pub struct SnpPlatformStatus { pub version: Version, pub state: u8, pub build_id: u32, pub guest_count: u32, pub tcb_version: u64, }
use crate::certs::sev; use crate::Version; use std::marker::PhantomData; pub struct PlatformReset; bitflags::bitflags! { #[derive(Default)] pub struct PlatformStatusFlags: u32 { const OWNED = 1 << 0; const ENCRYPTED_STATE = 1 << 8; } } #[derive(Default)] #[repr(C, packed)] pub struct PlatformStatus { pub version: Version, pub state: u8, pub flags: PlatformStatusFlags, pub build: u8, pub guest_count: u32, } pub struct PekGen; #[repr(C, packed)] pub struct PekCsr<'a> { addr: u64, len: u32, _phantom: PhantomData<&'a ()>, } impl<'a> PekCsr<'a> { pub fn new(cert: &'a mut sev::Certificate)
*const u8, self.id_len as _) } } } #[derive(Default)] #[repr(C, packed)] pub struct SnpPlatformStatus { pub version: Version, pub state: u8, pub build_id: u32, pub guest_count: u32, pub tcb_version: u64, }
-> Self { Self { addr: cert as *mut _ as _, len: std::mem::size_of_val(cert) as _, _phantom: PhantomData, } } } #[repr(C, packed)] pub struct PekCertImport<'a> { pek_addr: u64, pek_len: u32, oca_addr: u64, oca_len: u32, _phantom: PhantomData<&'a ()>, } impl<'a> PekCertImport<'a> { pub fn new(pek: &'a sev::Certificate, oca: &'a sev::Certificate) -> Self { Self { pek_addr: pek as *const _ as _, pek_len: std::mem::size_of_val(pek) as _, oca_addr: oca as *const _ as _, oca_len: std::mem::size_of_val(oca) as _, _phantom: PhantomData, } } } pub struct PdhGen; #[repr(C, packed)] pub struct PdhCertExport<'a> { pdh_addr: u64, pdh_len: u32, certs_addr: u64, certs_len: u32, _phantom: PhantomData<&'a ()>, } impl<'a> PdhCertExport<'a> { pub fn new(pdh: &'a mut sev::Certificate, certs: &'a mut [sev::Certificate; 3]) -> Self { Self { pdh_addr: pdh as *mut _ as _, pdh_len: std::mem::size_of_val(pdh) as _, certs_addr: certs.as_mut_ptr() as _, certs_len: std::mem::size_of_val(certs) as _, _phantom: PhantomData, } } } #[repr(C, packed)] pub struct GetId<'a> { id_addr: u64, id_len: u32, _phantom: PhantomData<&'a ()>, } impl<'a> GetId<'a> { pub fn new(id: &'a mut [u8; 64]) -> Self { Self { id_addr: id.as_mut_ptr() as _, id_len: id.len() as _, _phantom: PhantomData, } } pub fn as_slice(&self) -> &[u8] { unsafe { std::slice::from_raw_parts(self.id_addr as
random
[]
Rust
apps/fifteen_min/src/bus.rs
lucasccdias/abstreet
cf88a2a13396d1872f5165f54189c753b9686d21
use abstutil::prettyprint_usize; use geom::Duration; use map_gui::tools::{InputWaypoints, WaypointID}; use map_model::connectivity::WalkingOptions; use synthpop::{TripEndpoint, TripMode}; use widgetry::mapspace::{ObjectID, World, WorldOutcome}; use widgetry::{ Color, EventCtx, GfxCtx, HorizontalAlignment, Key, Line, Outcome, Panel, State, Text, Transition, VerticalAlignment, Widget, }; use crate::isochrone::{Isochrone, MovementOptions, Options}; use crate::App; pub struct BusExperiment { panel: Panel, waypoints: InputWaypoints, world: World<ID>, } #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] enum ID { Waypoint(WaypointID), BusRoute(usize), } impl ObjectID for ID {} impl BusExperiment { pub fn new_state(ctx: &mut EventCtx, app: &App) -> Box<dyn State<App>> { let mut state = BusExperiment { panel: Panel::empty(ctx), waypoints: InputWaypoints::new(app), world: World::unbounded(), }; state.recalculate_everything(ctx, app); Box::new(state) } fn recalculate_everything(&mut self, ctx: &mut EventCtx, app: &App) { let map = &app.map; let mut world = World::bounded(map.get_bounds()); self.waypoints .rebuild_world(ctx, &mut world, ID::Waypoint, 1); for (idx, pair) in self.waypoints.get_waypoints().windows(2).enumerate() { if let Some(path) = TripEndpoint::path_req(pair[0], pair[1], TripMode::Drive, map) .and_then(|req| map.pathfind(req).ok()) { let duration = path.estimate_duration(map, None); if let Ok(hitbox) = path.trace_v2(map) { world .add(ID::BusRoute(idx)) .hitbox(hitbox) .zorder(0) .draw_color(self.waypoints.get_waypoint_color(idx)) .hover_alpha(0.8) .tooltip(Text::from(Line(format!("Freeflow time is {duration}")))) .build(ctx); } } } let stops = self .waypoints .get_waypoints() .into_iter() .filter_map(|endpt| match endpt { TripEndpoint::Building(b) => Some(b), _ => None, }) .collect::<Vec<_>>(); let isochrone = Isochrone::new( ctx, app, stops, Options { movement: MovementOptions::Walking(WalkingOptions::default()), thresholds: vec![(Duration::minutes(15), Color::grey(0.3).alpha(0.5))], /*thresholds: vec![ (Duration::minutes(5), Color::grey(0.3).alpha(0.5)), (Duration::minutes(10), Color::grey(0.3).alpha(0.3)), (Duration::minutes(15), Color::grey(0.3).alpha(0.2)), ],*/ }, ); world.draw_master_batch_built(isochrone.draw); world.initialize_hover(ctx); world.rebuilt_during_drag(&self.world); self.world = world; self.panel = Panel::new_builder(Widget::col(vec![ map_gui::tools::app_header(ctx, app, "Bus planner"), ctx.style() .btn_back("15-minute neighborhoods") .hotkey(Key::Escape) .build_def(ctx), Text::from_multiline(vec![ Line("Within a 15 min walk of all stops:"), Line(format!( "Population: {}", prettyprint_usize(isochrone.population) )), Line(format!( "Shops: {}", prettyprint_usize( isochrone .amenities_reachable .borrow() .values() .map(|x| x.len()) .sum() ) )), ]) .into_widget(ctx), self.waypoints.get_panel_widget(ctx), ])) .aligned(HorizontalAlignment::Left, VerticalAlignment::Top) .ignore_initial_events() .build(ctx); } } impl State<App> for BusExperiment { fn event(&mut self, ctx: &mut EventCtx, app: &mut App) -> Transition<App> { let panel_outcome = self.panel.event(ctx); if let Outcome::Clicked(ref x) = panel_outcome { if x == "15-minute neighborhoods" { return Transition::Pop; } } let world_outcome = self.world.event(ctx); let world_outcome_for_waypoints = world_outcome .maybe_map_id(|id| match id { ID::Waypoint(id) => Some(id), _ => None, }) .unwrap_or(WorldOutcome::Nothing); if self .waypoints .event(app, panel_outcome, world_outcome_for_waypoints) { self.recalculate_everything(ctx, app); } Transition::Keep } fn draw(&self, g: &mut GfxCtx, _: &App) { self.panel.draw(g); self.world.draw(g); } }
use abstutil::prettyprint_usize; use geom::Duration; use map_gui::tools::{InputWaypoints, WaypointID}; use map_model::connectivity::WalkingOptions; use synthpop::{TripEndpoint, TripMode}; use widgetry::mapspace::{ObjectID, World, WorldOutcome}; use widgetry::{ Color, EventCtx, GfxCtx, HorizontalAlignment, Key, Line, Outcome, Panel, State, Text, Transition, VerticalAlignment, Widget, }; use crate::isochrone::{Isochrone, MovementOptions, Options}; use crate::App; pub struct BusExperiment { panel: Panel, waypoints: InputWaypoints, world: World<ID>, } #[derive(Clone, Copy, Debug, Partia
lAlignment::Left, VerticalAlignment::Top) .ignore_initial_events() .build(ctx); } } impl State<App> for BusExperiment { fn event(&mut self, ctx: &mut EventCtx, app: &mut App) -> Transition<App> { let panel_outcome = self.panel.event(ctx); if let Outcome::Clicked(ref x) = panel_outcome { if x == "15-minute neighborhoods" { return Transition::Pop; } } let world_outcome = self.world.event(ctx); let world_outcome_for_waypoints = world_outcome .maybe_map_id(|id| match id { ID::Waypoint(id) => Some(id), _ => None, }) .unwrap_or(WorldOutcome::Nothing); if self .waypoints .event(app, panel_outcome, world_outcome_for_waypoints) { self.recalculate_everything(ctx, app); } Transition::Keep } fn draw(&self, g: &mut GfxCtx, _: &App) { self.panel.draw(g); self.world.draw(g); } }
lEq, Eq, Hash)] enum ID { Waypoint(WaypointID), BusRoute(usize), } impl ObjectID for ID {} impl BusExperiment { pub fn new_state(ctx: &mut EventCtx, app: &App) -> Box<dyn State<App>> { let mut state = BusExperiment { panel: Panel::empty(ctx), waypoints: InputWaypoints::new(app), world: World::unbounded(), }; state.recalculate_everything(ctx, app); Box::new(state) } fn recalculate_everything(&mut self, ctx: &mut EventCtx, app: &App) { let map = &app.map; let mut world = World::bounded(map.get_bounds()); self.waypoints .rebuild_world(ctx, &mut world, ID::Waypoint, 1); for (idx, pair) in self.waypoints.get_waypoints().windows(2).enumerate() { if let Some(path) = TripEndpoint::path_req(pair[0], pair[1], TripMode::Drive, map) .and_then(|req| map.pathfind(req).ok()) { let duration = path.estimate_duration(map, None); if let Ok(hitbox) = path.trace_v2(map) { world .add(ID::BusRoute(idx)) .hitbox(hitbox) .zorder(0) .draw_color(self.waypoints.get_waypoint_color(idx)) .hover_alpha(0.8) .tooltip(Text::from(Line(format!("Freeflow time is {duration}")))) .build(ctx); } } } let stops = self .waypoints .get_waypoints() .into_iter() .filter_map(|endpt| match endpt { TripEndpoint::Building(b) => Some(b), _ => None, }) .collect::<Vec<_>>(); let isochrone = Isochrone::new( ctx, app, stops, Options { movement: MovementOptions::Walking(WalkingOptions::default()), thresholds: vec![(Duration::minutes(15), Color::grey(0.3).alpha(0.5))], /*thresholds: vec![ (Duration::minutes(5), Color::grey(0.3).alpha(0.5)), (Duration::minutes(10), Color::grey(0.3).alpha(0.3)), (Duration::minutes(15), Color::grey(0.3).alpha(0.2)), ],*/ }, ); world.draw_master_batch_built(isochrone.draw); world.initialize_hover(ctx); world.rebuilt_during_drag(&self.world); self.world = world; self.panel = Panel::new_builder(Widget::col(vec![ map_gui::tools::app_header(ctx, app, "Bus planner"), ctx.style() .btn_back("15-minute neighborhoods") .hotkey(Key::Escape) .build_def(ctx), Text::from_multiline(vec![ Line("Within a 15 min walk of all stops:"), Line(format!( "Population: {}", prettyprint_usize(isochrone.population) )), Line(format!( "Shops: {}", prettyprint_usize( isochrone .amenities_reachable .borrow() .values() .map(|x| x.len()) .sum() ) )), ]) .into_widget(ctx), self.waypoints.get_panel_widget(ctx), ])) .aligned(Horizonta
random
[ { "content": "pub fn custom_bar(ctx: &mut EventCtx, filled_color: Color, pct_full: f64, txt: Text) -> Widget {\n\n let total_width = 300.0;\n\n let height = 32.0;\n\n let radius = 4.0;\n\n\n\n let mut batch = GeomBatch::new();\n\n // Background\n\n batch.push(\n\n Color::hex(\"#666666\"...
Rust
tests/expectations/tests/issue-648-derive-debug-with-padding.rs
rust-lang-nursery/rust-bindgen
5a01c551993e56d20240ef64d0ec78cd4195855d
#![allow( dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals )] #[repr(C)] #[repr(align(64))] #[derive(Copy, Clone)] pub struct NoDebug { pub c: ::std::os::raw::c_char, } #[test] fn bindgen_test_layout_NoDebug() { assert_eq!( ::std::mem::size_of::<NoDebug>(), 64usize, concat!("Size of: ", stringify!(NoDebug)) ); assert_eq!( ::std::mem::align_of::<NoDebug>(), 64usize, concat!("Alignment of ", stringify!(NoDebug)) ); assert_eq!( unsafe { let uninit = ::std::mem::MaybeUninit::<NoDebug>::uninit(); let ptr = uninit.as_ptr(); ::std::ptr::addr_of!((*ptr).c) as usize - ptr as usize }, 0usize, concat!( "Offset of field: ", stringify!(NoDebug), "::", stringify!(c) ) ); } impl Default for NoDebug { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::<Self>::uninit(); unsafe { ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); s.assume_init() } } } impl ::std::cmp::PartialEq for NoDebug { fn eq(&self, other: &NoDebug) -> bool { self.c == other.c } } #[repr(C)] #[repr(align(64))] #[derive(Copy, Clone)] pub struct ShouldDeriveDebugButDoesNot { pub c: [::std::os::raw::c_char; 32usize], pub d: ::std::os::raw::c_char, } #[test] fn bindgen_test_layout_ShouldDeriveDebugButDoesNot() { assert_eq!( ::std::mem::size_of::<ShouldDeriveDebugButDoesNot>(), 64usize, concat!("Size of: ", stringify!(ShouldDeriveDebugButDoesNot)) ); assert_eq!( ::std::mem::align_of::<ShouldDeriveDebugButDoesNot>(), 64usize, concat!("Alignment of ", stringify!(ShouldDeriveDebugButDoesNot)) ); assert_eq!( unsafe { let uninit = ::std::mem::MaybeUninit::<ShouldDeriveDebugButDoesNot>::uninit( ); let ptr = uninit.as_ptr(); ::std::ptr::addr_of!((*ptr).c) as usize - ptr as usize }, 0usize, concat!( "Offset of field: ", stringify!(ShouldDeriveDebugButDoesNot), "::", stringify!(c) ) ); assert_eq!( unsafe { let uninit = ::std::mem::MaybeUninit::<ShouldDeriveDebugButDoesNot>::uninit( ); let ptr = uninit.as_ptr(); ::std::ptr::addr_of!((*ptr).d) as usize - ptr as usize }, 32usize, concat!( "Offset of field: ", stringify!(ShouldDeriveDebugButDoesNot), "::", stringify!(d) ) ); } impl Default for ShouldDeriveDebugButDoesNot { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::<Self>::uninit(); unsafe { ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); s.assume_init() } } } impl ::std::cmp::PartialEq for ShouldDeriveDebugButDoesNot { fn eq(&self, other: &ShouldDeriveDebugButDoesNot) -> bool { self.c == other.c && self.d == other.d } }
#![allow( dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals )] #[repr(C)] #[repr(align(64))] #[derive(Copy, Clone)] pub struct NoDebug { pub c: ::std::os::raw::c_char, } #[test] fn bindgen_test_layout_NoDebug() { assert_eq!( ::std::mem::size_of::<NoDebug>(), 64usize, concat!("Size of: ", stringify!(NoDebug)) ); assert_eq!( ::std::mem::align_of::<NoDebug>(), 64usize, concat!("Alignment of ", stringify!(NoDebug)) ); assert_eq!( unsafe { let uninit = ::std::mem::MaybeUninit::<NoDebug>::uninit(); let ptr = uninit.as_ptr(); ::std::ptr::addr_of!((*ptr).c) as usize - ptr as usize }, 0usize, concat!( "Offset of field: ", stringify!(NoDebug), "::", stringify!(c) ) ); } impl Default for NoDebug { fn default() -> Self { l
} impl ::std::cmp::PartialEq for NoDebug { fn eq(&self, other: &NoDebug) -> bool { self.c == other.c } } #[repr(C)] #[repr(align(64))] #[derive(Copy, Clone)] pub struct ShouldDeriveDebugButDoesNot { pub c: [::std::os::raw::c_char; 32usize], pub d: ::std::os::raw::c_char, } #[test] fn bindgen_test_layout_ShouldDeriveDebugButDoesNot() { assert_eq!( ::std::mem::size_of::<ShouldDeriveDebugButDoesNot>(), 64usize, concat!("Size of: ", stringify!(ShouldDeriveDebugButDoesNot)) ); assert_eq!( ::std::mem::align_of::<ShouldDeriveDebugButDoesNot>(), 64usize, concat!("Alignment of ", stringify!(ShouldDeriveDebugButDoesNot)) ); assert_eq!( unsafe { let uninit = ::std::mem::MaybeUninit::<ShouldDeriveDebugButDoesNot>::uninit( ); let ptr = uninit.as_ptr(); ::std::ptr::addr_of!((*ptr).c) as usize - ptr as usize }, 0usize, concat!( "Offset of field: ", stringify!(ShouldDeriveDebugButDoesNot), "::", stringify!(c) ) ); assert_eq!( unsafe { let uninit = ::std::mem::MaybeUninit::<ShouldDeriveDebugButDoesNot>::uninit( ); let ptr = uninit.as_ptr(); ::std::ptr::addr_of!((*ptr).d) as usize - ptr as usize }, 32usize, concat!( "Offset of field: ", stringify!(ShouldDeriveDebugButDoesNot), "::", stringify!(d) ) ); } impl Default for ShouldDeriveDebugButDoesNot { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::<Self>::uninit(); unsafe { ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); s.assume_init() } } } impl ::std::cmp::PartialEq for ShouldDeriveDebugButDoesNot { fn eq(&self, other: &ShouldDeriveDebugButDoesNot) -> bool { self.c == other.c && self.d == other.d } }
et mut s = ::std::mem::MaybeUninit::<Self>::uninit(); unsafe { ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); s.assume_init() } }
function_block-function_prefixed
[ { "content": "#[test]\n\nfn bindgen_test_layout_ShouldImplClone() {\n\n assert_eq!(\n\n ::std::mem::size_of::<ShouldImplClone>(),\n\n 132usize,\n\n concat!(\"Size of: \", stringify!(ShouldImplClone))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<ShouldImplClone>(),\n\n ...
Rust
src/modules/centerdevice/auth.rs
dschneller/ceres
9449011264d17fdd4b03a262930d8fe19ff9dc8f
use clams::prelude::{Config as ClamsConfig}; use clap::{App, Arg, ArgMatches, SubCommand}; use centerdevice::{CenterDevice, Client, ClientCredentials, Token}; use centerdevice::client::AuthorizedClient; use centerdevice::client::auth::{Code, CodeProvider, IntoUrl}; use centerdevice::errors::{Result as CenterDeviceResult}; use failure::Fail; use std::io; use std::io::Write; use std::convert::TryInto; use config::{CeresConfig as Config, CenterDevice as CenterDeviceConfig, Profile}; use run_config::RunConfig; use modules::{Result as ModuleResult, Error as ModuleError, ErrorKind as ModuleErrorKind, Module}; use modules::centerdevice::errors::*; pub const NAME: &str = "auth"; pub struct SubModule; impl Module for SubModule { fn build_sub_cli() -> App<'static, 'static> { SubCommand::with_name(NAME) .about("Authenticate with CenterDevice") .arg( Arg::with_name("refresh") .short("r") .long("refresh") .help("Just refresh token without re-authentication"), ) .arg( Arg::with_name("show") .short("s") .long("show") .required_unless("save") .help("On successful authentication, print the received token to stdout"), ) .arg( Arg::with_name("save") .short("S") .long("save") .required_unless("show") .help("On successful authentication, save the received token to configuration file"), ) } fn call(cli_args: Option<&ArgMatches>, run_config: &RunConfig, config: &Config) -> ModuleResult<()> { let args = cli_args.unwrap(); do_call(args, run_config, config) .map_err(|e| ModuleError::with_chain(e, ModuleErrorKind::ModuleFailed(NAME.to_owned()))) } } struct CliCodeProvider {} impl CodeProvider for CliCodeProvider { fn get_code<T: IntoUrl>(&self, auth_url: T) -> CenterDeviceResult<Code> { let auth_url = auth_url.into_url().expect("Failed to parse auth url"); println!("Please authenticate at the following URL, wait for the redirect, enter the code into the terminal, and then press return ..."); println!("\n\t{}\n", auth_url); print!("Authentication code: "); let _ = std::io::stdout().flush(); let mut input = String::new(); let _ = io::stdin().read_line(&mut input); let code = input.trim(); let code = Code::new(code.to_string()); Ok(code) } } fn do_call(args: &ArgMatches, run_config: &RunConfig, config: &Config) -> Result<()> { let profile = match run_config.active_profile.as_ref() { "default" => config.get_default_profile(), s => config.get_profile(s), }.chain_err(|| ErrorKind::FailedToParseCmd("profile".to_string()))?; let centerdevice = profile.centerdevice.as_ref().ok_or( Error::from_kind(ErrorKind::NoCenterDeviceInProfile) )?; let token = if args.is_present("refresh") { refresh_token(&centerdevice)? } else { get_token(&centerdevice)? }; debug!("{:#?}", token); if args.is_present("show") { println!("{:#?}", token); } if args.is_present("save") { save_token(run_config, config, &token) .chain_err(|| ErrorKind::FailedToSaveToken)?; } Ok(()) } fn get_token(centerdevice: &CenterDeviceConfig) -> Result<Token> { let client_credentials = ClientCredentials::new( &centerdevice.client_id, &centerdevice.client_secret, ); let code_provider = CliCodeProvider {}; info!("Authenticating with CenterDevice at {}", centerdevice.base_domain); let client = Client::new(&centerdevice.base_domain, client_credentials) .authorize_with_code_flow(&centerdevice.redirect_uri, &code_provider) .map_err(|e| Error::with_chain(e.compat(), ErrorKind::FailedToAccessCenterDeviceApi))?; info!("Successfully authenticated."); Ok(client.token().clone()) } fn refresh_token(centerdevice: &CenterDeviceConfig) -> Result<Token> { info!("Refreshing token with CenterDevice at {}", centerdevice.base_domain); let client: AuthorizedClient = centerdevice.try_into()?; let token = client.refresh_access_token() .map_err(|e| Error::with_chain(e.compat(), ErrorKind::FailedToAccessCenterDeviceApi))?; info!("Successfully re-energized."); Ok(token) } fn save_token(run_config: &RunConfig, config: &Config, token: &Token) -> Result<()> { let new_config = update_config(run_config, config, token)?; new_config.save(run_config.active_config) .chain_err(|| ErrorKind::FailedToSaveConfig)?; Ok(()) } fn update_config(run_config: &RunConfig, config: &Config, token: &Token) -> Result<Config> { let profile = match run_config.active_profile.as_ref() { "default" => config.get_default_profile(), s => config.get_profile(s), }.chain_err(|| ErrorKind::FailedToParseCmd("profile".to_string()))?; let centerdevice = profile.centerdevice.as_ref().ok_or( Error::from_kind(ErrorKind::NoCenterDeviceInProfile) )?; let centerdevice = CenterDeviceConfig { access_token: Some(token.access_token().to_string()), refresh_token: Some(token.refresh_token().to_string()), ..(*centerdevice).clone() }; let profile = Profile { centerdevice: Some(centerdevice), ..(*profile).clone() }; let profile_name = match run_config.active_profile.as_ref() { "default" => config.default_profile.clone(), s => s.to_string(), }; let mut profiles = config.profiles.clone(); profiles.insert(profile_name, profile); let new_config = Config { profiles, ..(*config).clone() }; Ok(new_config) }
use clams::prelude::{Config as ClamsConfig}; use clap::{App, Arg, ArgMatches, SubCommand}; use centerdevice::{CenterDevice, Client, ClientCredentials, Token}; use centerdevice::client::AuthorizedClient; use centerdevice::client::auth::{Code, CodeProvider, IntoUrl}; use centerdevice::errors::{Result as CenterDeviceResult}; use failure::Fail; use std::io; use std::io::Write; use std::convert::TryInto; use config::{CeresConfig as Config, CenterDevice as CenterDeviceConfig, Profile}; use run_config::RunConfig; use modules::{Result as ModuleResult, Error as ModuleError, ErrorKind as ModuleErrorKind, Module}; use modules::centerdevice::errors::*; pub const NAME: &str = "auth"; pub struct SubModule; impl Module for SubModule { fn build_sub_cli() -> App<'static, 'static> { SubCommand::with_name(NAME) .about("Authenticate with CenterDevice") .arg( Arg::with_name("refresh") .short("r") .long("refresh") .help("Just refresh token without re-authentication"), ) .arg( Arg::with_name("show") .short("s") .long("show") .required_unless("save") .help("On successful authentication, print the received token to stdout"), ) .arg( Arg::with_name("save") .short("S") .long("save") .required_unless("show") .help("On successful authentication, save the received token to configuration file"), ) } fn call(cli_args: Option<&ArgMatches>, run_config: &RunConfig, config: &Config) -> ModuleResult<()> { let args = cli_args.unwrap(); do_call(args, run_config, config) .map_err(|e| ModuleError::with_chain(e, ModuleErrorKind::ModuleFailed(NAME.to_owned()))) } } struct CliCodeProvider {} impl CodeProvider for CliCodeProvider { fn get_code<T: IntoUrl>(&self, auth_url: T) -> CenterDeviceResult<Code> { let auth_url = auth_url.into_url().expect("Failed to parse auth url"); println!("Please authenticate at the following URL, wait for the redirect, enter the code into the terminal, and then press return ..."); println!("\n\t{}\n", auth_url); print!("Authentication code: "); let _ = std::io::stdout().flush(); let mut input = String::new(); let _ = io::stdin().read_line(&mut input); let code = input.trim(); let code = Code::new(code.to_string()); Ok(code) } } fn do_call(args: &ArgMatches, run_config: &RunConfig, config: &Config) -> Result<()> { let profile = match run_config.active_profile.as_ref() { "default" => config.get_default_profile(), s => config.get_profile(s), }.chain_err(|| ErrorKind::FailedToParseCmd("profile".to_string()))?; let centerdevice = profile.centerdevice.as_ref().ok_or( Error::from_kind(ErrorKind::NoCenterDeviceInProfile) )?; let token = if args.is_present("refresh") { refresh_token(&centerdevice)? } else { get_token(&centerdevice)? }; debug!("{:#?}", token); if args.is_present("show") { println!("{:#?}", token); }
Ok(()) } fn get_token(centerdevice: &CenterDeviceConfig) -> Result<Token> { let client_credentials = ClientCredentials::new( &centerdevice.client_id, &centerdevice.client_secret, ); let code_provider = CliCodeProvider {}; info!("Authenticating with CenterDevice at {}", centerdevice.base_domain); let client = Client::new(&centerdevice.base_domain, client_credentials) .authorize_with_code_flow(&centerdevice.redirect_uri, &code_provider) .map_err(|e| Error::with_chain(e.compat(), ErrorKind::FailedToAccessCenterDeviceApi))?; info!("Successfully authenticated."); Ok(client.token().clone()) } fn refresh_token(centerdevice: &CenterDeviceConfig) -> Result<Token> { info!("Refreshing token with CenterDevice at {}", centerdevice.base_domain); let client: AuthorizedClient = centerdevice.try_into()?; let token = client.refresh_access_token() .map_err(|e| Error::with_chain(e.compat(), ErrorKind::FailedToAccessCenterDeviceApi))?; info!("Successfully re-energized."); Ok(token) } fn save_token(run_config: &RunConfig, config: &Config, token: &Token) -> Result<()> { let new_config = update_config(run_config, config, token)?; new_config.save(run_config.active_config) .chain_err(|| ErrorKind::FailedToSaveConfig)?; Ok(()) } fn update_config(run_config: &RunConfig, config: &Config, token: &Token) -> Result<Config> { let profile = match run_config.active_profile.as_ref() { "default" => config.get_default_profile(), s => config.get_profile(s), }.chain_err(|| ErrorKind::FailedToParseCmd("profile".to_string()))?; let centerdevice = profile.centerdevice.as_ref().ok_or( Error::from_kind(ErrorKind::NoCenterDeviceInProfile) )?; let centerdevice = CenterDeviceConfig { access_token: Some(token.access_token().to_string()), refresh_token: Some(token.refresh_token().to_string()), ..(*centerdevice).clone() }; let profile = Profile { centerdevice: Some(centerdevice), ..(*profile).clone() }; let profile_name = match run_config.active_profile.as_ref() { "default" => config.default_profile.clone(), s => s.to_string(), }; let mut profiles = config.profiles.clone(); profiles.insert(profile_name, profile); let new_config = Config { profiles, ..(*config).clone() }; Ok(new_config) }
if args.is_present("save") { save_token(run_config, config, &token) .chain_err(|| ErrorKind::FailedToSaveToken)?; }
if_condition
[ { "content": "fn query_health(client: &ReqwestClient, name: &'static str, url: &str) -> impl Future<Item = HealthCheck, Error = Error> {\n\n trace!(\"Quering health for {}\", url);\n\n client\n\n .get(url)\n\n .header(Connection::close())\n\n .send()\n\n .map_err(|e| Error::with_chain(e,...
Rust
src/cli/doc_get.rs
couchbaselabs/couchbase-shell
28498991f17c7383e255cceb05eb71e543ae9d6e
use super::util::convert_json_value_to_nu_value; use crate::state::State; use crate::cli::doc_upsert::{build_batched_kv_items, prime_manifest_if_required}; use crate::cli::util::cluster_identifiers_from; use crate::client::KeyValueRequest; use futures::stream::FuturesUnordered; use futures::StreamExt; use log::debug; use nu_engine::{CommandArgs, Example}; use nu_errors::ShellError; use nu_protocol::{ MaybeOwned, Primitive, Signature, SyntaxShape, TaggedDictBuilder, UntaggedValue, }; use nu_source::Tag; use nu_stream::OutputStream; use std::ops::Add; use std::sync::{Arc, Mutex}; use tokio::runtime::Runtime; use tokio::time::Instant; pub struct DocGet { state: Arc<Mutex<State>>, } impl DocGet { pub fn new(state: Arc<Mutex<State>>) -> Self { Self { state } } } impl nu_engine::WholeStreamCommand for DocGet { fn name(&self) -> &str { "doc get" } fn signature(&self) -> Signature { Signature::build("doc get") .optional("id", SyntaxShape::String, "the document id") .named( "id-column", SyntaxShape::String, "the name of the id column if used with an input stream", None, ) .named( "bucket", SyntaxShape::String, "the name of the bucket", None, ) .named("scope", SyntaxShape::String, "the name of the scope", None) .named( "collection", SyntaxShape::String, "the name of the collection", None, ) .named( "clusters", SyntaxShape::String, "the clusters which should be contacted", None, ) .named( "batch-size", SyntaxShape::Number, "the maximum number of items to batch send at a time", None, ) } fn usage(&self) -> &str { "Fetches a document through the data service" } fn run(&self, args: CommandArgs) -> Result<OutputStream, ShellError> { run_get(self.state.clone(), args) } fn examples(&self) -> Vec<Example> { vec![ Example { description: "Fetches a single document with the ID as an argument", example: "doc get my_doc_id", result: None, }, Example { description: "Fetches multiple documents with IDs from the previous command", example: "echo [[id]; [airline_10] [airline_11]] | doc get", result: None, }, ] } } fn run_get(state: Arc<Mutex<State>>, mut args: CommandArgs) -> Result<OutputStream, ShellError> { let ctrl_c = args.ctrl_c(); let cluster_identifiers = cluster_identifiers_from(&state, &args, true)?; let batch_size: Option<i32> = args.get_flag("batch-size")?; let id_column: String = args.get_flag("id-column")?.unwrap_or_else(|| "id".into()); let ids = ids_from_input(&mut args, id_column.clone())?; let mut workers = FuturesUnordered::new(); let guard = state.lock().unwrap(); let mut all_ids: Vec<Vec<String>> = vec![]; if let Some(size) = batch_size { all_ids = build_batched_kv_items(size as u32, ids.clone()); } let mut results = vec![]; for identifier in cluster_identifiers { let active_cluster = match guard.clusters().get(&identifier) { Some(c) => c, None => { return Err(ShellError::unexpected("Cluster not found")); } }; let bucket = match args .get_flag("bucket")? .or_else(|| active_cluster.active_bucket()) { Some(v) => Ok(v), None => Err(ShellError::unexpected( "Could not auto-select a bucket - please use --bucket instead".to_string(), )), }?; let scope = match args.get_flag("scope")? { Some(s) => s, None => match active_cluster.active_scope() { Some(s) => s, None => "".into(), }, }; let collection = match args.get_flag("collection")? { Some(c) => c, None => match active_cluster.active_collection() { Some(c) => c, None => "".into(), }, }; if all_ids.is_empty() { all_ids = build_batched_kv_items(active_cluster.kv_batch_size(), ids.clone()); } debug!("Running kv get for docs {:?}", &ids); let rt = Runtime::new().unwrap(); let deadline = Instant::now().add(active_cluster.timeouts().data_timeout()); let mut client = rt.block_on(active_cluster.cluster().key_value_client( bucket.clone(), deadline, ctrl_c.clone(), ))?; prime_manifest_if_required( &rt, scope.clone(), collection.clone(), ctrl_c.clone(), Instant::now().add(active_cluster.timeouts().data_timeout()), &mut client, )?; let client = Arc::new(client); for ids in all_ids.clone() { for id in ids { let deadline = Instant::now().add(active_cluster.timeouts().data_timeout()); let scope = scope.clone(); let collection = collection.clone(); let ctrl_c = ctrl_c.clone(); let id = id.clone(); let client = client.clone(); workers.push(async move { client .request( KeyValueRequest::Get { key: id }, scope, collection, deadline, ctrl_c, ) .await }); } rt.block_on(async { while let Some(response) = workers.next().await { match response { Ok(mut res) => { let tag = Tag::default(); let mut collected = TaggedDictBuilder::new(&tag); collected.insert_value(&id_column, res.key()); collected.insert_value( "cas", UntaggedValue::int(res.cas() as i64).into_untagged_value(), ); let content = res.content().unwrap(); match convert_json_value_to_nu_value(&content, Tag::default()) { Ok(c) => { collected.insert_value("content", c); collected.insert_value("error", "".to_string()); } Err(e) => { collected.insert_value("content", "".to_string()); collected.insert_value("error", e.to_string()); } } collected.insert_value("cluster", identifier.clone()); results.push(collected.into_value()); } Err(e) => { let tag = Tag::default(); let mut collected = TaggedDictBuilder::new(&tag); collected.insert_value( &id_column, e.key().unwrap_or_else(|| "".to_string()), ); collected.insert_value("cas", "".to_string()); collected.insert_value("content", "".to_string()); collected.insert_value("error", e.to_string()); collected.insert_value("cluster", identifier.clone()); results.push(collected.into_value()); } } } }); } } Ok(OutputStream::from(results)) } pub(crate) fn ids_from_input( args: &mut CommandArgs, id_column: String, ) -> Result<Vec<String>, ShellError> { let mut ids = vec![]; for item in &mut args.input { let untagged = item.into(); match untagged { UntaggedValue::Primitive(Primitive::String(s)) => ids.push(s.clone()), UntaggedValue::Row(d) => { if let MaybeOwned::Borrowed(d) = d.get_data(id_column.as_ref()) { let untagged = &d.value; if let UntaggedValue::Primitive(Primitive::String(s)) = untagged { ids.push(s.clone()) } } } _ => {} } } if let Some(id) = args.opt(0)? { ids.push(id); } Ok(ids) }
use super::util::convert_json_value_to_nu_value; use crate::state::State; use crate::cli::doc_upsert::{build_batched_kv_items, prime_manifest_if_required}; use crate::cli::util::cluster_identifiers_from; use crate::client::KeyValueRequest; use futures::stream::FuturesUnordered; use futures::StreamExt; use log::debug; use nu_engine::{CommandArgs, Example}; use nu_errors::ShellError; use nu_protocol::{ MaybeOwned, Primitive, Signature, SyntaxShape, TaggedDictBuilder, UntaggedValue, }; use nu_source::Tag; use nu_stream::OutputStream; use std::ops::Add; use std::sync::{Arc, Mutex}; use tokio::runtime::Runtime; use tokio::time::Instant; pub struct DocGet { state: Arc<Mutex<State>>, } impl DocGet { pub fn new(state: Arc<Mutex<State>>) -> Self { Self { state } } } impl nu_engine::WholeStreamCommand for DocGet { fn name(&self) -> &str { "doc get" } fn signature(&self) -> Signature { Signature::build("doc get") .optional("id", SyntaxShape::String, "the document id") .named( "id-column", SyntaxShape::String, "the name of the id column if used with an input stream", None, ) .named( "bucket", SyntaxShape::String, "the name of the bucket", None, ) .named("scope", SyntaxShape::String, "the name of the scope", None) .named( "collection", SyntaxShape::String, "the name of the collection", None, ) .named( "clusters", SyntaxShape::String, "the clusters which should be contacted", None, ) .named( "batch-size", SyntaxShape::Number, "the maximum number of items to batch send at a time", None, ) } fn usage(&self) -> &str { "Fetches a document through the data service" } fn run(&self, args: CommandArgs) -> Result<OutputStream, ShellError> { run_get(self.state.clone(), args) } fn examples(&self) -> Vec<Example> { vec![ Example { description: "Fetches a single document with the ID as an argument", example: "doc get my_doc_id", result: None, }, Example { description: "Fetches multiple documents with IDs from the previous com
} fn run_get(state: Arc<Mutex<State>>, mut args: CommandArgs) -> Result<OutputStream, ShellError> { let ctrl_c = args.ctrl_c(); let cluster_identifiers = cluster_identifiers_from(&state, &args, true)?; let batch_size: Option<i32> = args.get_flag("batch-size")?; let id_column: String = args.get_flag("id-column")?.unwrap_or_else(|| "id".into()); let ids = ids_from_input(&mut args, id_column.clone())?; let mut workers = FuturesUnordered::new(); let guard = state.lock().unwrap(); let mut all_ids: Vec<Vec<String>> = vec![]; if let Some(size) = batch_size { all_ids = build_batched_kv_items(size as u32, ids.clone()); } let mut results = vec![]; for identifier in cluster_identifiers { let active_cluster = match guard.clusters().get(&identifier) { Some(c) => c, None => { return Err(ShellError::unexpected("Cluster not found")); } }; let bucket = match args .get_flag("bucket")? .or_else(|| active_cluster.active_bucket()) { Some(v) => Ok(v), None => Err(ShellError::unexpected( "Could not auto-select a bucket - please use --bucket instead".to_string(), )), }?; let scope = match args.get_flag("scope")? { Some(s) => s, None => match active_cluster.active_scope() { Some(s) => s, None => "".into(), }, }; let collection = match args.get_flag("collection")? { Some(c) => c, None => match active_cluster.active_collection() { Some(c) => c, None => "".into(), }, }; if all_ids.is_empty() { all_ids = build_batched_kv_items(active_cluster.kv_batch_size(), ids.clone()); } debug!("Running kv get for docs {:?}", &ids); let rt = Runtime::new().unwrap(); let deadline = Instant::now().add(active_cluster.timeouts().data_timeout()); let mut client = rt.block_on(active_cluster.cluster().key_value_client( bucket.clone(), deadline, ctrl_c.clone(), ))?; prime_manifest_if_required( &rt, scope.clone(), collection.clone(), ctrl_c.clone(), Instant::now().add(active_cluster.timeouts().data_timeout()), &mut client, )?; let client = Arc::new(client); for ids in all_ids.clone() { for id in ids { let deadline = Instant::now().add(active_cluster.timeouts().data_timeout()); let scope = scope.clone(); let collection = collection.clone(); let ctrl_c = ctrl_c.clone(); let id = id.clone(); let client = client.clone(); workers.push(async move { client .request( KeyValueRequest::Get { key: id }, scope, collection, deadline, ctrl_c, ) .await }); } rt.block_on(async { while let Some(response) = workers.next().await { match response { Ok(mut res) => { let tag = Tag::default(); let mut collected = TaggedDictBuilder::new(&tag); collected.insert_value(&id_column, res.key()); collected.insert_value( "cas", UntaggedValue::int(res.cas() as i64).into_untagged_value(), ); let content = res.content().unwrap(); match convert_json_value_to_nu_value(&content, Tag::default()) { Ok(c) => { collected.insert_value("content", c); collected.insert_value("error", "".to_string()); } Err(e) => { collected.insert_value("content", "".to_string()); collected.insert_value("error", e.to_string()); } } collected.insert_value("cluster", identifier.clone()); results.push(collected.into_value()); } Err(e) => { let tag = Tag::default(); let mut collected = TaggedDictBuilder::new(&tag); collected.insert_value( &id_column, e.key().unwrap_or_else(|| "".to_string()), ); collected.insert_value("cas", "".to_string()); collected.insert_value("content", "".to_string()); collected.insert_value("error", e.to_string()); collected.insert_value("cluster", identifier.clone()); results.push(collected.into_value()); } } } }); } } Ok(OutputStream::from(results)) } pub(crate) fn ids_from_input( args: &mut CommandArgs, id_column: String, ) -> Result<Vec<String>, ShellError> { let mut ids = vec![]; for item in &mut args.input { let untagged = item.into(); match untagged { UntaggedValue::Primitive(Primitive::String(s)) => ids.push(s.clone()), UntaggedValue::Row(d) => { if let MaybeOwned::Borrowed(d) = d.get_data(id_column.as_ref()) { let untagged = &d.value; if let UntaggedValue::Primitive(Primitive::String(s)) = untagged { ids.push(s.clone()) } } } _ => {} } } if let Some(id) = args.opt(0)? { ids.push(id); } Ok(ids) }
mand", example: "echo [[id]; [airline_10] [airline_11]] | doc get", result: None, }, ] }
function_block-function_prefixed
[ { "content": "fn buckets_get(state: Arc<Mutex<State>>, args: CommandArgs) -> Result<OutputStream, ShellError> {\n\n let ctrl_c = args.ctrl_c();\n\n\n\n let cluster_identifiers = cluster_identifiers_from(&state, &args, true)?;\n\n let bucket: String = args.req(0)?;\n\n\n\n debug!(\"Running buckets ge...
Rust
crates/interledger-settlement-engines/src/stores/redis_ethereum_ledger/store.rs
pensivej/interledger-rs
f86937f11ee4557887b66c2a7dc935a6475bbd3a
use futures::{ future::{err, ok}, Future, }; use ethereum_tx_sign::web3::types::{Address as EthAddress, H256, U256}; use interledger_service::Account as AccountTrait; use std::collections::HashMap; use crate::engines::ethereum_ledger::{EthereumAccount, EthereumAddresses, EthereumStore}; use redis::{self, cmd, r#async::SharedConnection, ConnectionInfo, PipelineCommands, Value}; use log::{debug, error}; use crate::stores::redis_store_common::{EngineRedisStore, EngineRedisStoreBuilder}; static RECENTLY_OBSERVED_BLOCK_KEY: &str = "recently_observed_block"; static SAVED_TRANSACTIONS_KEY: &str = "transactions"; static SETTLEMENT_ENGINES_KEY: &str = "settlement"; static LEDGER_KEY: &str = "ledger"; static ETHEREUM_KEY: &str = "eth"; #[derive(Clone, Debug, Serialize)] pub struct Account { pub(crate) id: u64, pub(crate) own_address: EthAddress, pub(crate) token_address: Option<EthAddress>, } impl AccountTrait for Account { type AccountId = u64; fn id(&self) -> Self::AccountId { self.id } } fn ethereum_transactions_key(tx_hash: H256) -> String { format!( "{}:{}:{}:{}", ETHEREUM_KEY, LEDGER_KEY, SAVED_TRANSACTIONS_KEY, tx_hash, ) } fn ethereum_ledger_key(account_id: u64) -> String { format!( "{}:{}:{}:{}", ETHEREUM_KEY, LEDGER_KEY, SETTLEMENT_ENGINES_KEY, account_id ) } impl EthereumAccount for Account { fn token_address(&self) -> Option<EthAddress> { self.token_address } fn own_address(&self) -> EthAddress { self.own_address } } pub struct EthereumLedgerRedisStoreBuilder { redis_store_builder: EngineRedisStoreBuilder, } impl EthereumLedgerRedisStoreBuilder { pub fn new(redis_uri: ConnectionInfo) -> Self { EthereumLedgerRedisStoreBuilder { redis_store_builder: EngineRedisStoreBuilder::new(redis_uri), } } pub fn connect(&self) -> impl Future<Item = EthereumLedgerRedisStore, Error = ()> { self.redis_store_builder .connect() .and_then(move |redis_store| { let connection = redis_store.connection.clone(); Ok(EthereumLedgerRedisStore { redis_store, connection, }) }) } } #[derive(Clone)] pub struct EthereumLedgerRedisStore { redis_store: EngineRedisStore, connection: SharedConnection, } impl EthereumLedgerRedisStore { pub fn new(redis_store: EngineRedisStore) -> Self { let connection = redis_store.connection.clone(); EthereumLedgerRedisStore { redis_store, connection, } } } impl EthereumStore for EthereumLedgerRedisStore { type Account = Account; fn load_account_addresses( &self, account_ids: Vec<<Self::Account as AccountTrait>::AccountId>, ) -> Box<dyn Future<Item = Vec<EthereumAddresses>, Error = ()> + Send> { debug!("Loading account addresses {:?}", account_ids); let mut pipe = redis::pipe(); for account_id in account_ids.iter() { pipe.hgetall(ethereum_ledger_key(*account_id)); } Box::new( pipe.query_async(self.connection.clone()) .map_err(move |err| { error!( "Error the addresses for accounts: {:?} {:?}", account_ids, err ) }) .and_then( move |(_conn, addresses): (_, Vec<HashMap<String, Vec<u8>>>)| { debug!("Loaded account addresses {:?}", addresses); let mut ret = Vec::with_capacity(addresses.len()); for addr in &addresses { let own_address = if let Some(own_address) = addr.get("own_address") { own_address } else { return err(()); }; let own_address = EthAddress::from(&own_address[..]); let token_address = if let Some(token_address) = addr.get("token_address") { token_address } else { return err(()); }; let token_address = if token_address.len() == 20 { Some(EthAddress::from(&token_address[..])) } else { None }; ret.push(EthereumAddresses { own_address, token_address, }); } ok(ret) }, ), ) } fn save_account_addresses( &self, data: HashMap<<Self::Account as AccountTrait>::AccountId, EthereumAddresses>, ) -> Box<dyn Future<Item = (), Error = ()> + Send> { let mut pipe = redis::pipe(); for (account_id, d) in data { let token_address = if let Some(token_address) = d.token_address { token_address.to_vec() } else { vec![] }; let acc_id = ethereum_ledger_key(account_id); let addrs = &[ ("own_address", d.own_address.to_vec()), ("token_address", token_address), ]; pipe.hset_multiple(acc_id, addrs).ignore(); pipe.set(addrs_to_key(d), account_id).ignore(); } Box::new( pipe.query_async(self.connection.clone()) .map_err(move |err| error!("Error saving account data: {:?}", err)) .and_then(move |(_conn, _ret): (_, Value)| Ok(())), ) } fn save_recently_observed_block( &self, block: U256, ) -> Box<dyn Future<Item = (), Error = ()> + Send> { let mut pipe = redis::pipe(); pipe.set(RECENTLY_OBSERVED_BLOCK_KEY, block.low_u64()) .ignore(); Box::new( pipe.query_async(self.connection.clone()) .map_err(move |err| { error!("Error saving last observed block {:?}: {:?}", block, err) }) .and_then(move |(_conn, _ret): (_, Value)| Ok(())), ) } fn load_recently_observed_block(&self) -> Box<dyn Future<Item = U256, Error = ()> + Send> { let mut pipe = redis::pipe(); pipe.get(RECENTLY_OBSERVED_BLOCK_KEY); Box::new( pipe.query_async(self.connection.clone()) .map_err(move |err| error!("Error loading last observed block: {:?}", err)) .and_then(move |(_conn, block): (_, Vec<u64>)| { if !block.is_empty() { let block = U256::from(block[0]); ok(block) } else { ok(U256::from(0)) } }), ) } fn load_account_id_from_address( &self, eth_address: EthereumAddresses, ) -> Box<dyn Future<Item = <Self::Account as AccountTrait>::AccountId, Error = ()> + Send> { let mut pipe = redis::pipe(); pipe.get(addrs_to_key(eth_address)); Box::new( pipe.query_async(self.connection.clone()) .map_err(move |err| error!("Error loading account data: {:?}", err)) .and_then(move |(_conn, account_id): (_, Vec<u64>)| ok(account_id[0])), ) } fn check_if_tx_processed( &self, tx_hash: H256, ) -> Box<dyn Future<Item = bool, Error = ()> + Send> { Box::new( cmd("EXISTS") .arg(ethereum_transactions_key(tx_hash)) .query_async(self.connection.clone()) .map_err(move |err| error!("Error loading account data: {:?}", err)) .and_then(move |(_conn, ret): (_, bool)| Ok(ret)), ) } fn mark_tx_processed(&self, tx_hash: H256) -> Box<dyn Future<Item = (), Error = ()> + Send> { Box::new( cmd("SETNX") .arg(ethereum_transactions_key(tx_hash)) .arg(true) .query_async(self.connection.clone()) .map_err(move |err| error!("Error loading account data: {:?}", err)) .and_then( move |(_conn, ret): (_, bool)| { if ret { ok(()) } else { err(()) } }, ), ) } } fn addrs_to_key(address: EthereumAddresses) -> String { let token_address = if let Some(token_address) = address.token_address { token_address.to_string() } else { "null".to_string() }; format!( "account:{}:{}", address.own_address.to_string(), token_address ) } #[cfg(test)] mod tests { use super::super::super::test_helpers::store_helpers::{ block_on, test_eth_store as test_store, }; use super::*; use std::iter::FromIterator; use std::str::FromStr; #[test] fn saves_and_loads_ethereum_addreses_properly() { block_on(test_store().and_then(|(store, context)| { let account_ids = vec![30, 42]; let account_addresses = vec![ EthereumAddresses { own_address: EthAddress::from_str("3cdb3d9e1b74692bb1e3bb5fc81938151ca64b02") .unwrap(), token_address: Some( EthAddress::from_str("c92be489639a9c61f517bd3b955840fa19bc9b7c").unwrap(), ), }, EthereumAddresses { own_address: EthAddress::from_str("2fcd07047c209c46a767f8338cb0b14955826826") .unwrap(), token_address: None, }, ]; let input = HashMap::from_iter(vec![ (account_ids[0], account_addresses[0]), (account_ids[1], account_addresses[1]), ]); store .save_account_addresses(input) .map_err(|err| eprintln!("Redis error: {:?}", err)) .and_then(move |_| { store .load_account_addresses(account_ids.clone()) .map_err(|err| eprintln!("Redis error: {:?}", err)) .and_then(move |data| { assert_eq!(data[0], account_addresses[0]); assert_eq!(data[1], account_addresses[1]); let _ = context; store .load_account_id_from_address(account_addresses[0]) .map_err(|err| eprintln!("Redis error: {:?}", err)) .and_then(move |acc_id| { assert_eq!(acc_id, account_ids[0]); let _ = context; store .load_account_id_from_address(account_addresses[1]) .map_err(|err| eprintln!("Redis error: {:?}", err)) .and_then(move |acc_id| { assert_eq!(acc_id, account_ids[1]); let _ = context; Ok(()) }) }) }) }) })) .unwrap() } #[test] fn saves_and_loads_last_observed_data_properly() { block_on(test_store().and_then(|(store, context)| { let block = U256::from(2); store .save_recently_observed_block(block) .map_err(|err| eprintln!("Redis error: {:?}", err)) .and_then(move |_| { store .load_recently_observed_block() .map_err(|err| eprintln!("Redis error: {:?}", err)) .and_then(move |data| { assert_eq!(data, block); let _ = context; Ok(()) }) }) })) .unwrap() } #[test] fn saves_tx_hashes_properly() { block_on(test_store().and_then(|(store, context)| { let tx_hash = H256::from("0xb28675771f555adf614f1401838b9fffb43bc285387679bcbd313a8dc5bdc00e"); store .mark_tx_processed(tx_hash) .map_err(|err| eprintln!("Redis error: {:?}", err)) .and_then(move |_| { store .check_if_tx_processed(tx_hash) .map_err(|err| eprintln!("Redis error: {:?}", err)) .and_then(move |seen2| { assert_eq!(seen2, true); let _ = context; Ok(()) }) }) })) .unwrap() } }
use futures::{ future::{err, ok}, Future, }; use ethereum_tx_sign::web3::types::{Address as EthAddress, H256, U256}; use interledger_service::Account as AccountTrait; use std::collections::HashMap; use crate::engines::ethereum_ledger::{EthereumAccount, EthereumAddresses, EthereumStore}; use redis::{self, cmd, r#async::SharedConnection, ConnectionInfo, PipelineCommands, Value}; use log::{debug, error}; use crate::stores::redis_store_common::{EngineRedisStore, EngineRedisStoreBuilder}; static RECENTLY_OBSERVED_BLOCK_KEY: &str = "recently_observed_block"; static SAVED_TRANSACTIONS_KEY: &str = "transactions"; static SETTLEMENT_ENGINES_KEY: &str = "settlement"; static LEDGER_KEY: &str = "ledger"; static ETHEREUM_KEY: &str = "eth"; #[derive(Clone, Debug, Serialize)] pub struct Account { pub(crate) id: u64, pub(crate) own_address: EthAddress, pub(crate) token_address: Option<EthAddress>, } impl AccountTrait for Account { type AccountId = u64; fn id(&self) -> Self::AccountId { self.id } } fn ethereum_transactions_key(tx_hash: H256) -> String { format!( "{}:{}:{}:{}", ETHEREUM_KEY, LEDGER_KEY, SAVED_TRANSACTIONS_KEY, tx_hash, ) } fn ethereum_ledger_key(account_id: u64) -> String { format!( "{}:{}:{}:{}", ETHEREUM_KEY, LEDGER_KEY, SETTLEMENT_ENGINES_KEY, account_id ) } impl EthereumAccount for Account { fn token_address(&self) -> Option<EthAddress> { self.token_address } fn own_address(&self) -> EthAddress { self.own_address } } pub struct EthereumLedgerRedisStoreBuilder { redis_store_builder: EngineRedisStoreBuilder, } impl EthereumLedgerRedisStoreBuilder { pub fn new(redis_uri: ConnectionInfo) -> Self { EthereumLedgerRedisStoreBuilder { redis_store_builder: EngineRedisStoreBuilder::new(redis_uri), } } pub fn connect(&self) -> impl Future<Item = EthereumLedgerRedisStore, Error = ()> { self.redis_store_builder .connect() .and_then(move |redis_store| { let connection = redis_store.connection.clone(); Ok(EthereumLedgerRedisStore { redis_store, connection, }) }) } } #[derive(Clone)] pub struct EthereumLedgerRedisStore { redis_store: EngineRedisStore, connection: SharedConnection, } impl EthereumLedgerRedisStore { pub fn new(redis_store: EngineRedisStore) -> Self { let connection = redis_store.connection.clone(); EthereumLedgerRedisStore { redis_store, connection, } } } impl EthereumStore for EthereumLedgerRedisStore { type Account = Account; fn load_account_addresses( &self, account_ids: Vec<<Self::Account as AccountTrait>::AccountId>, ) -> Box<dyn Future<Item = Vec<EthereumAddresses>, Error = ()> + Send> { debug!("Loading account addresses {:?}", account_ids); let mut pipe = redis::pipe(); for account_id in account_ids.iter() { pipe.hgetall(ethereum_ledger_key(*account_id)); } Box::new( pipe.query_async(self.connection.clone()) .map_err(move |err| { error!( "Error the addresses for accounts: {:?} {:?}", account_ids, err ) }) .and_then( move |(_conn, addresses): (_, Vec<HashMap<String, Vec<u8>>>)| { debug!("Loaded account addresses {:?}", addresses); let mut ret = Vec::with_capacity(addresses.len()); for addr in &addresses { let own_address = if let Some(own_address) = addr.get("own_address") { own_address } else { return err(()); }; let own_address = EthAddress::from(&own_address[..]); let token_address = if let Some(token_address) = addr.get("token_address") { token_address } else { return err(()); }; let token_address = if token_address.len() == 20 { Some(EthAddress::from(&token_address[..])) } else { None }; ret.push(EthereumAddresses { own_address, token_address, }); } ok(ret) }, ), ) } fn save_account_addresses( &self, data: HashMap<<Self::Account as AccountTrait>::AccountId, EthereumAddresses>, ) -> Box<dyn Future<Item = (), Error = ()> + Send> { let mut pipe = redis::pipe(); for (account_id, d) in data { let token_address = if let Some(token_address) = d.token_address { token_address.to_vec() } else { vec![] }; let acc_id = ethereum_ledger_key(account_id); let addrs = &[ ("own_address", d.own_address.to_vec()), ("token_address", token_address), ]; pipe.hset_multiple(acc_id, addrs).ignore(); pipe.set(addrs_to_key(d), account_id).ignore(); } Box::new( pipe.query_async(self.connection.clone()) .map_err(move |err| error!("Error saving account data: {:?}", err)) .and_then(move |(_conn, _ret): (_, Value)| Ok(())), ) } fn save_recently_observed_block( &self, block: U256, ) -> Box<dyn Future<Item = (), Error = ()> + Send> { let mut pipe = redis::pipe(); pipe.set(RECENTLY_OBSERVED_BLOCK_KEY, block.low_u64()) .ignore(); Box::new( pipe.query_async(self.connection.clone()) .map_err(move |err| { error!("Error saving last observed block {:?}: {:?}", block, err) }) .and_then(move |(_conn, _ret): (_, Value)| Ok(())), ) } fn load_recently_observed_block(&self) -> Box<dyn Future<Item = U256, Error = ()> + Send> { let mut pipe = redis::pipe(); pipe.get(RECENTLY_OBSERVED_BLOCK_KEY); Box::new( pipe.query_async(self.connection.clone()) .map_err(move |err| error!("Error loading last observed block: {:?}", err)) .and_then(move |(_conn, block): (_, Vec<u64>)| { if !block.is_empty() { let block = U256::from(block[0]); ok(block) } else { ok(U256::from(0)) } }), ) } fn load_account_id_from_address( &self, eth_address: EthereumAddresses, ) -> Box<dyn Future<Item = <Self::Account as AccountTrait>::AccountId, Error = ()> + Send> { let mut pipe = redis::pipe(); pipe.get(addrs_to_key(eth_address)); Box::new( pipe.query_async(self.connection.clone()) .map_err(move |err| error!("Error loading account data: {:?}", err)) .and_then(move |(_conn, account_id): (_, Vec<u64>)| ok(account_id[0])), ) } fn check_if_tx_processed( &self, tx_hash: H256, ) -> Box<dyn Future<Item = bool, Error = ()> + Send> { Box::new( cmd("EXISTS") .arg(ethereum_transactions_key(tx_hash)) .query_async(self.connection.clone()) .map_err(move |err| error!("Error loading account data: {:?}", err)) .and_then(move |(_conn, ret): (_, bool)| Ok(ret)), ) } fn mark_tx_processed(&self, tx_hash: H256) -> Box<dyn Future<Item = (), Error = ()> + Send> { Box::new( cmd("SETNX") .arg(ethereum_transactions_key(tx_hash)) .arg(true) .query_async(self.connection.clone()) .map_err(move |err| error!("Error loading account data: {:?}", err)) .and_then( move |(_conn, ret): (_, bool)| { if ret { ok(()) } else { err(()) } }, ), ) } } fn addrs_to_key(address: EthereumAddresses) -> String { let token_address = if let Some(token_address) = address.token_address { token_address.to_string() } else { "null".to_string() }; format!( "account:{}:{}", address.own_address.to_string(), token_address ) } #[cfg(test)] mod tests { use super::super::super::test_helpers::store_helpers::{ block_on, test_eth_store as test_store, }; use super::*; use std::iter::FromIterator; use std::str::FromStr; #[test] fn saves_and_loads_ethereum_addreses_properly() {
.unwrap() } #[test] fn saves_and_loads_last_observed_data_properly() { block_on(test_store().and_then(|(store, context)| { let block = U256::from(2); store .save_recently_observed_block(block) .map_err(|err| eprintln!("Redis error: {:?}", err)) .and_then(move |_| { store .load_recently_observed_block() .map_err(|err| eprintln!("Redis error: {:?}", err)) .and_then(move |data| { assert_eq!(data, block); let _ = context; Ok(()) }) }) })) .unwrap() } #[test] fn saves_tx_hashes_properly() { block_on(test_store().and_then(|(store, context)| { let tx_hash = H256::from("0xb28675771f555adf614f1401838b9fffb43bc285387679bcbd313a8dc5bdc00e"); store .mark_tx_processed(tx_hash) .map_err(|err| eprintln!("Redis error: {:?}", err)) .and_then(move |_| { store .check_if_tx_processed(tx_hash) .map_err(|err| eprintln!("Redis error: {:?}", err)) .and_then(move |seen2| { assert_eq!(seen2, true); let _ = context; Ok(()) }) }) })) .unwrap() } }
block_on(test_store().and_then(|(store, context)| { let account_ids = vec![30, 42]; let account_addresses = vec![ EthereumAddresses { own_address: EthAddress::from_str("3cdb3d9e1b74692bb1e3bb5fc81938151ca64b02") .unwrap(), token_address: Some( EthAddress::from_str("c92be489639a9c61f517bd3b955840fa19bc9b7c").unwrap(), ), }, EthereumAddresses { own_address: EthAddress::from_str("2fcd07047c209c46a767f8338cb0b14955826826") .unwrap(), token_address: None, }, ]; let input = HashMap::from_iter(vec![ (account_ids[0], account_addresses[0]), (account_ids[1], account_addresses[1]), ]); store .save_account_addresses(input) .map_err(|err| eprintln!("Redis error: {:?}", err)) .and_then(move |_| { store .load_account_addresses(account_ids.clone()) .map_err(|err| eprintln!("Redis error: {:?}", err)) .and_then(move |data| { assert_eq!(data[0], account_addresses[0]); assert_eq!(data[1], account_addresses[1]); let _ = context; store .load_account_id_from_address(account_addresses[0]) .map_err(|err| eprintln!("Redis error: {:?}", err)) .and_then(move |acc_id| { assert_eq!(acc_id, account_ids[0]); let _ = context; store .load_account_id_from_address(account_addresses[1]) .map_err(|err| eprintln!("Redis error: {:?}", err)) .and_then(move |acc_id| { assert_eq!(acc_id, account_ids[1]); let _ = context; Ok(()) }) }) }) }) }))
call_expression
[ { "content": "pub fn delay(ms: u64) -> impl Future<Item = (), Error = ()> {\n\n Delay::new(Instant::now() + Duration::from_millis(ms)).map_err(|err| panic!(err))\n\n}\n\n\n", "file_path": "crates/interledger-settlement-engines/tests/redis_helpers.rs", "rank": 0, "score": 401299.29343494965 }, ...
Rust
kernel-hal/src/bare/arch/riscv/vm.rs
SummerVibes/zCore
09c69b2adc920b6edc78a7d45d9237bfd8b43d40
use core::fmt::{Debug, Formatter, Result}; use core::slice; use riscv::{asm, register::satp}; use spin::Mutex; use crate::addr::{align_down, align_up}; use crate::utils::page_table::{GenericPTE, PageTableImpl, PageTableLevel3}; use crate::{mem::phys_to_virt, MMUFlags, PhysAddr, VirtAddr, KCONFIG, PAGE_SIZE}; lazy_static! { static ref KERNEL_PT: Mutex<PageTable> = Mutex::new(init_kernel_page_table().unwrap()); } fn init_kernel_page_table() -> PagingResult<PageTable> { extern "C" { fn stext(); fn etext(); fn srodata(); fn erodata(); fn sdata(); fn edata(); fn sbss(); fn ebss(); fn bootstack(); fn bootstacktop(); fn end(); } let mut pt = PageTable::new(); let mut map_range = |start: VirtAddr, end: VirtAddr, flags: MMUFlags| -> PagingResult { pt.map_cont( start, crate::addr::align_up(end - start), start - KCONFIG.phys_to_virt_offset, flags | MMUFlags::HUGE_PAGE, ) }; map_range( stext as usize, etext as usize, MMUFlags::READ | MMUFlags::EXECUTE, )?; map_range(srodata as usize, erodata as usize, MMUFlags::READ)?; map_range( sdata as usize, edata as usize, MMUFlags::READ | MMUFlags::WRITE, )?; map_range( sbss as usize, ebss as usize, MMUFlags::READ | MMUFlags::WRITE, )?; map_range( bootstack as usize, bootstacktop as usize, MMUFlags::READ | MMUFlags::WRITE, )?; map_range( align_up(end as usize + PAGE_SIZE), phys_to_virt(align_down(KCONFIG.phys_mem_end)), MMUFlags::READ | MMUFlags::WRITE, )?; info!("initialized kernel page table @ {:#x}", pt.table_phys()); Ok(pt) } pub(super) fn kernel_page_table() -> &'static Mutex<PageTable> { &KERNEL_PT } pub(super) fn init() { unsafe { KERNEL_PT.lock().activate() }; } hal_fn_impl! { impl mod crate::hal_fn::vm { fn activate_paging(vmtoken: PhysAddr) { let old_token = current_vmtoken(); if old_token != vmtoken { #[cfg(target_arch = "riscv64")] let mode = satp::Mode::Sv39; debug!("switch table {:x?} -> {:x?}", old_token, vmtoken); unsafe { satp::set(mode, 0, vmtoken >> 12); asm::sfence_vma_all(); } } } fn current_vmtoken() -> PhysAddr { satp::read().ppn() << 12 } fn flush_tlb(vaddr: Option<VirtAddr>) { unsafe { if let Some(vaddr) = vaddr { asm::sfence_vma(0, vaddr) } else { asm::sfence_vma_all(); } } } fn pt_clone_kernel_space(dst_pt_root: PhysAddr, src_pt_root: PhysAddr) { let entry_range = 0x100..0x200; let dst_table = unsafe { slice::from_raw_parts_mut(phys_to_virt(dst_pt_root) as *mut Rv64PTE, 512) }; let src_table = unsafe { slice::from_raw_parts(phys_to_virt(src_pt_root) as *const Rv64PTE, 512) }; for i in entry_range { dst_table[i] = src_table[i]; if !dst_table[i].is_unused() { dst_table[i].0 |= PTF::GLOBAL.bits() as u64; } } } } } bitflags::bitflags! { pub struct PTF: usize { const VALID = 1 << 0; const READABLE = 1 << 1; const WRITABLE = 1 << 2; const EXECUTABLE = 1 << 3; const USER = 1 << 4; const GLOBAL = 1 << 5; const ACCESSED = 1 << 6; const DIRTY = 1 << 7; const RESERVED1 = 1 << 8; const RESERVED2 = 1 << 9; } } impl From<MMUFlags> for PTF { fn from(f: MMUFlags) -> Self { if f.is_empty() { return PTF::empty(); } let mut flags = PTF::VALID; if f.contains(MMUFlags::READ) { flags |= PTF::READABLE; } if f.contains(MMUFlags::WRITE) { flags |= PTF::READABLE | PTF::WRITABLE; } if f.contains(MMUFlags::EXECUTE) { flags |= PTF::EXECUTABLE; } if f.contains(MMUFlags::USER) { flags |= PTF::USER; } flags } } impl From<PTF> for MMUFlags { fn from(f: PTF) -> Self { let mut ret = Self::empty(); if f.contains(PTF::READABLE) { ret |= Self::READ; } if f.contains(PTF::WRITABLE) { ret |= Self::WRITE; } if f.contains(PTF::EXECUTABLE) { ret |= Self::EXECUTE; } if f.contains(PTF::USER) { ret |= Self::USER; } ret } } const PHYS_ADDR_MASK: u64 = 0x003f_ffff_ffff_fc00; #[derive(Clone, Copy)] #[repr(transparent)] pub struct Rv64PTE(u64); impl GenericPTE for Rv64PTE { fn addr(&self) -> PhysAddr { ((self.0 & PHYS_ADDR_MASK) << 2) as _ } fn flags(&self) -> MMUFlags { PTF::from_bits_truncate(self.0 as usize).into() } fn is_unused(&self) -> bool { self.0 == 0 } fn is_present(&self) -> bool { PTF::from_bits_truncate(self.0 as usize).contains(PTF::VALID) } fn is_leaf(&self) -> bool { PTF::from_bits_truncate(self.0 as usize).intersects(PTF::READABLE | PTF::EXECUTABLE) } fn set_addr(&mut self, paddr: PhysAddr) { self.0 = (self.0 & !PHYS_ADDR_MASK) | ((paddr as u64 >> 2) & PHYS_ADDR_MASK); } fn set_flags(&mut self, flags: MMUFlags, _is_huge: bool) { let flags = PTF::from(flags) | PTF::ACCESSED | PTF::DIRTY; debug_assert!(flags.contains(PTF::READABLE | PTF::EXECUTABLE)); self.0 = (self.0 & PHYS_ADDR_MASK) | flags.bits() as u64; } fn set_table(&mut self, paddr: PhysAddr) { self.0 = ((paddr as u64 >> 2) & PHYS_ADDR_MASK) | PTF::VALID.bits() as u64; } fn clear(&mut self) { self.0 = 0 } } impl Debug for Rv64PTE { fn fmt(&self, f: &mut Formatter) -> Result { let mut f = f.debug_struct("Rv64PTE"); f.field("raw", &self.0); f.field("addr", &self.addr()); f.field("flags", &self.flags()); f.finish() } } pub type PageTable = PageTableImpl<PageTableLevel3, Rv64PTE>;
use core::fmt::{Debug, Formatter, Result}; use core::slice; use riscv::{asm, register::satp}; use spin::Mutex; use crate::addr::{align_down, align_up}; use crate::utils::page_table::{GenericPTE, PageTableImpl, PageTableLevel3}; use crate::{mem::phys_to_virt, MMUFlags, PhysAddr, VirtAddr, KCONFIG, PAGE_SIZE}; lazy_static! { static ref KERNEL_PT: Mutex<PageTable> = Mutex::new(init_kernel_page_table().unwrap()); } fn init_kernel_page_table() -> PagingResult<PageTable> { extern "C" { fn stext(); fn etext(); fn srodata(); fn erodata(); fn sdata(); fn edata(); fn sbss(); fn ebss(); fn bootstack(); fn bootstacktop(); fn end(); } let mut pt = PageTable::new(); let mut map_range = |start: VirtAddr, end: VirtAddr, flags: MMUFlags| -> PagingResult { pt.map_cont( start, crate::addr::align_up(end - start), start - KCONFIG.phys_to_virt_offset, flags | MMUFlags::HUGE_PAGE, ) }; map_range( stext as usize, etext as usize, MMUFlags::READ | MMUFlags::EXECUTE, )?; map_range(srodata as usize, erodata as usize, MMUFlags::READ)?; map_range( sdata as usize, edata as usize, MMUFlags::READ | MMUFlags::WRITE, )?; map_range( sbss as usize, ebss as usize, MMUFlags::READ | MMUFlags::WRITE, )?; map_range( bootstack as usize, bootstacktop as usize, MMUFlags::READ | MMUFlags::WRITE, )?; map_range( align_up(end as usize + PAGE_SIZE), phys_to_virt(align_down(KCONFIG.phys_mem_end)), MMUFlags::READ | MMUFlags::WRITE, )?; info!("initialized kernel page table @ {:#x}", pt.table_phys()); Ok(pt) } pub(super) fn kernel_page_table() -> &'static Mutex<PageTable> { &KERNEL_PT } pub(super) fn init() { unsafe { KERNEL_PT.lock().activate() }; } hal_fn_impl! { impl mod crate::hal_fn::vm { fn activate_paging(vmtoken: PhysAddr) { let old_token = current_vmtoken(); if old_token != vmtoken { #[cfg(target_arch = "riscv64")] let mode = satp::Mode::Sv39; debug!("switch table {:x?} -> {:x?}", old_token, vmtoken); unsafe { satp::set(mode, 0, vmtoken >> 12); asm::sfence_vma_all(); } } } fn current_vmtoken() -> PhysAddr { satp::read().ppn() << 12 } fn flush_tlb(vaddr: Option<VirtAddr>) { unsafe { if let Some(vaddr) = vaddr { asm::sfence_vma(0, vaddr) } else { asm::sfence_vma_all(); } } } fn pt_clone_kernel_space(dst_pt_root: PhysAddr, src_pt_root: PhysAddr) { let entry_range = 0x100..0x200; let dst_table = unsafe { slice::from_raw_parts_mut(phys_to_virt(dst_pt_root) as *mut Rv64PTE, 512) }; let src_table = unsafe { slice::from_raw_parts(phys_to_virt(src_pt_root) as *const Rv64PTE, 512) }; for i in entry_range { dst_table[i] = src_table[i]; if !dst_table[i].is_unused() { dst_table[i].0 |= PTF::GLOBAL.bits() as u64; } } } } } bitflags::bitflags! { pub struct PTF: usize { const VALID = 1 << 0; const READABLE = 1 << 1; const WRITABLE = 1 << 2; const EXECUTABLE = 1 << 3; const USER = 1 << 4; const GLOBAL = 1 << 5; const ACCESSED = 1 << 6; const DIRTY = 1 << 7; const RESERVED1 = 1 << 8; const RESERVED2 = 1 << 9; } } impl From<MMUFlags> for PTF { fn from(
} impl From<PTF> for MMUFlags { fn from(f: PTF) -> Self { let mut ret = Self::empty(); if f.contains(PTF::READABLE) { ret |= Self::READ; } if f.contains(PTF::WRITABLE) { ret |= Self::WRITE; } if f.contains(PTF::EXECUTABLE) { ret |= Self::EXECUTE; } if f.contains(PTF::USER) { ret |= Self::USER; } ret } } const PHYS_ADDR_MASK: u64 = 0x003f_ffff_ffff_fc00; #[derive(Clone, Copy)] #[repr(transparent)] pub struct Rv64PTE(u64); impl GenericPTE for Rv64PTE { fn addr(&self) -> PhysAddr { ((self.0 & PHYS_ADDR_MASK) << 2) as _ } fn flags(&self) -> MMUFlags { PTF::from_bits_truncate(self.0 as usize).into() } fn is_unused(&self) -> bool { self.0 == 0 } fn is_present(&self) -> bool { PTF::from_bits_truncate(self.0 as usize).contains(PTF::VALID) } fn is_leaf(&self) -> bool { PTF::from_bits_truncate(self.0 as usize).intersects(PTF::READABLE | PTF::EXECUTABLE) } fn set_addr(&mut self, paddr: PhysAddr) { self.0 = (self.0 & !PHYS_ADDR_MASK) | ((paddr as u64 >> 2) & PHYS_ADDR_MASK); } fn set_flags(&mut self, flags: MMUFlags, _is_huge: bool) { let flags = PTF::from(flags) | PTF::ACCESSED | PTF::DIRTY; debug_assert!(flags.contains(PTF::READABLE | PTF::EXECUTABLE)); self.0 = (self.0 & PHYS_ADDR_MASK) | flags.bits() as u64; } fn set_table(&mut self, paddr: PhysAddr) { self.0 = ((paddr as u64 >> 2) & PHYS_ADDR_MASK) | PTF::VALID.bits() as u64; } fn clear(&mut self) { self.0 = 0 } } impl Debug for Rv64PTE { fn fmt(&self, f: &mut Formatter) -> Result { let mut f = f.debug_struct("Rv64PTE"); f.field("raw", &self.0); f.field("addr", &self.addr()); f.field("flags", &self.flags()); f.finish() } } pub type PageTable = PageTableImpl<PageTableLevel3, Rv64PTE>;
f: MMUFlags) -> Self { if f.is_empty() { return PTF::empty(); } let mut flags = PTF::VALID; if f.contains(MMUFlags::READ) { flags |= PTF::READABLE; } if f.contains(MMUFlags::WRITE) { flags |= PTF::READABLE | PTF::WRITABLE; } if f.contains(MMUFlags::EXECUTE) { flags |= PTF::EXECUTABLE; } if f.contains(MMUFlags::USER) { flags |= PTF::USER; } flags }
function_block-function_prefixed
[]
Rust
build/main.rs
cdecompilador/rust-xcb
d83de0035743766c4503b9e699fb22cc1a6d2986
extern crate quick_xml; mod ast; mod codegen; mod output; mod parse; use std::env; use std::fs; use std::path::{Path, PathBuf}; use ast::{Event, ExtInfo, OpCopy, OpCopyMap}; use codegen::{CodeGen, DepInfo}; use output::Output; use parse::{Parser, Result}; fn xcb_mod_map(name: &str) -> &str { match name { "bigreq" => "big_requests", "ge" => "genericevent", "xselinux" => "selinux", "xprint" => "x_print", "xtest" => "test", _ => name, } } fn is_always(name: &str) -> bool { matches!(name, "xproto" | "big_requests" | "xc_misc") } fn has_feature(name: &str) -> bool { env::var(format!("CARGO_FEATURE_{}", name.to_ascii_uppercase())).is_ok() } fn main() { let root = env::var("CARGO_MANIFEST_DIR").unwrap_or_else(|_| ".".to_string()); let xml_dir = Path::new(&root).join("xml"); let out_dir = env::var("OUT_DIR").unwrap_or_else(|_| "./gen/current".to_string()); let out_dir = Path::new(&out_dir); let rustfmt = env::var("RXCB_RUSTFMT").ok().and_then(|var| { if var == "1" || var == "y" || var == "Y" { find_exe("rustfmt") } else { None } }); let gen_all = env::var("RXCB_GENALL").is_ok(); let mut dep_info = Vec::new(); for xml_file in iter_xml(&xml_dir) { if xml_file.file_stem().unwrap().to_str().unwrap() == "xinput" { continue; } process_xcb_gen(&xml_file, out_dir, &rustfmt, gen_all, &mut dep_info).unwrap_or_else( |err| { panic!( "Error during processing of {}: {:?}", xml_file.display(), err ) }, ); } #[cfg(target_os = "freebsd")] println!("cargo:rustc-link-search=/usr/local/lib"); } fn iter_xml(xml_dir: &Path) -> impl Iterator<Item = PathBuf> { fs::read_dir(xml_dir) .unwrap() .map(|e| e.unwrap().path()) .filter(|p| match p.extension() { Some(e) => e == "xml", _ => false, }) } fn find_exe<P>(exe_name: P) -> Option<PathBuf> where P: AsRef<Path>, { env::var_os("PATH").and_then(|paths| { env::split_paths(&paths) .filter_map(|dir| { let full_path = dir.join(&exe_name); if full_path.is_file() { Some(full_path) } else { None } }) .next() }) } fn process_xcb_gen( xml_file: &Path, out_dir: &Path, rustfmt: &Option<PathBuf>, gen_all: bool, dep_info: &mut Vec<DepInfo>, ) -> Result<()> { let xcb_mod = xml_file.file_stem().unwrap(); let xcb_mod = xcb_mod.to_str().unwrap(); let xcb_mod = xcb_mod_map(xcb_mod); if dep_info.iter().any(|di| di.xcb_mod == xcb_mod) { return Ok(()); } if !gen_all && !is_always(xcb_mod) && !has_feature(xcb_mod) { return Ok(()); } let ffi_file = out_dir.join("ffi").join(&xcb_mod).with_extension("rs"); let rs_file = out_dir.join(&xcb_mod).with_extension("rs"); let ffi = Output::new(rustfmt, &ffi_file) .unwrap_or_else(|_| panic!("cannot create FFI output file: {}", ffi_file.display())); let rs = Output::new(rustfmt, &rs_file) .unwrap_or_else(|_| panic!("cannot create Rust output file: {}", rs_file.display())); let mut parser = Parser::from_file(xml_file); let mut imports = Vec::new(); let mut events = Vec::new(); let mut evcopies: OpCopyMap = OpCopyMap::new(); let mut info: Option<(String, Option<ExtInfo>)> = None; for e in &mut parser { match e? { Event::Ignore => {} Event::Info(mod_name, ext_info) => { info = Some((mod_name, ext_info)); } Event::Import(imp) => imports.push(imp), Event::Event { number, stru, no_seq_number, xge, } => { evcopies.insert(stru.name.clone(), Vec::new()); events.push(Event::Event { number, stru, no_seq_number, xge, }); } Event::EventCopy { name, number, ref_ } => { if let Some(copies) = evcopies.get_mut(&ref_) { copies.push(OpCopy { name, number }); } else { events.push(Event::EventCopy { name, number, ref_ }); } } ev => { events.push(ev); } } } let info = info.expect("no xcb protocol opening"); let deps = { let mut deps = Vec::new(); for i in imports.iter() { let xml_file = xml_file.with_file_name(&format!("{}.xml", i)); process_xcb_gen(&xml_file, out_dir, rustfmt, gen_all, dep_info).unwrap_or_else(|err| { panic!( "Error during processing of {}: {:?}", xml_file.display(), err ) }); let i = xcb_mod_map(i); deps.push( dep_info .iter() .find(|di| di.xcb_mod == i) .unwrap_or_else(|| panic!("can't find dependency {} of {}", i, xcb_mod)) .clone(), ); } deps }; let mut cg = CodeGen::new(xcb_mod, ffi, rs, deps, evcopies); cg.prologue(imports, &info.1)?; for ev in events { cg.event(ev)?; } cg.epilogue()?; dep_info.push(cg.into_depinfo()); Ok(()) }
extern crate quick_xml; mod ast; mod codegen; mod output; mod parse; use std::env; use std::fs; use std::path::{Path, PathBuf}; use ast::{Event, ExtInfo, OpCopy, OpCopyMap}; use codegen::{CodeGen, DepInfo}; use output::Output; use parse::{Parser, Result}; fn xcb_mod_map(name: &str) -> &str {
} fn is_always(name: &str) -> bool { matches!(name, "xproto" | "big_requests" | "xc_misc") } fn has_feature(name: &str) -> bool { env::var(format!("CARGO_FEATURE_{}", name.to_ascii_uppercase())).is_ok() } fn main() { let root = env::var("CARGO_MANIFEST_DIR").unwrap_or_else(|_| ".".to_string()); let xml_dir = Path::new(&root).join("xml"); let out_dir = env::var("OUT_DIR").unwrap_or_else(|_| "./gen/current".to_string()); let out_dir = Path::new(&out_dir); let rustfmt = env::var("RXCB_RUSTFMT").ok().and_then(|var| { if var == "1" || var == "y" || var == "Y" { find_exe("rustfmt") } else { None } }); let gen_all = env::var("RXCB_GENALL").is_ok(); let mut dep_info = Vec::new(); for xml_file in iter_xml(&xml_dir) { if xml_file.file_stem().unwrap().to_str().unwrap() == "xinput" { continue; } process_xcb_gen(&xml_file, out_dir, &rustfmt, gen_all, &mut dep_info).unwrap_or_else( |err| { panic!( "Error during processing of {}: {:?}", xml_file.display(), err ) }, ); } #[cfg(target_os = "freebsd")] println!("cargo:rustc-link-search=/usr/local/lib"); } fn iter_xml(xml_dir: &Path) -> impl Iterator<Item = PathBuf> { fs::read_dir(xml_dir) .unwrap() .map(|e| e.unwrap().path()) .filter(|p| match p.extension() { Some(e) => e == "xml", _ => false, }) } fn find_exe<P>(exe_name: P) -> Option<PathBuf> where P: AsRef<Path>, { env::var_os("PATH").and_then(|paths| { env::split_paths(&paths) .filter_map(|dir| { let full_path = dir.join(&exe_name); if full_path.is_file() { Some(full_path) } else { None } }) .next() }) } fn process_xcb_gen( xml_file: &Path, out_dir: &Path, rustfmt: &Option<PathBuf>, gen_all: bool, dep_info: &mut Vec<DepInfo>, ) -> Result<()> { let xcb_mod = xml_file.file_stem().unwrap(); let xcb_mod = xcb_mod.to_str().unwrap(); let xcb_mod = xcb_mod_map(xcb_mod); if dep_info.iter().any(|di| di.xcb_mod == xcb_mod) { return Ok(()); } if !gen_all && !is_always(xcb_mod) && !has_feature(xcb_mod) { return Ok(()); } let ffi_file = out_dir.join("ffi").join(&xcb_mod).with_extension("rs"); let rs_file = out_dir.join(&xcb_mod).with_extension("rs"); let ffi = Output::new(rustfmt, &ffi_file) .unwrap_or_else(|_| panic!("cannot create FFI output file: {}", ffi_file.display())); let rs = Output::new(rustfmt, &rs_file) .unwrap_or_else(|_| panic!("cannot create Rust output file: {}", rs_file.display())); let mut parser = Parser::from_file(xml_file); let mut imports = Vec::new(); let mut events = Vec::new(); let mut evcopies: OpCopyMap = OpCopyMap::new(); let mut info: Option<(String, Option<ExtInfo>)> = None; for e in &mut parser { match e? { Event::Ignore => {} Event::Info(mod_name, ext_info) => { info = Some((mod_name, ext_info)); } Event::Import(imp) => imports.push(imp), Event::Event { number, stru, no_seq_number, xge, } => { evcopies.insert(stru.name.clone(), Vec::new()); events.push(Event::Event { number, stru, no_seq_number, xge, }); } Event::EventCopy { name, number, ref_ } => { if let Some(copies) = evcopies.get_mut(&ref_) { copies.push(OpCopy { name, number }); } else { events.push(Event::EventCopy { name, number, ref_ }); } } ev => { events.push(ev); } } } let info = info.expect("no xcb protocol opening"); let deps = { let mut deps = Vec::new(); for i in imports.iter() { let xml_file = xml_file.with_file_name(&format!("{}.xml", i)); process_xcb_gen(&xml_file, out_dir, rustfmt, gen_all, dep_info).unwrap_or_else(|err| { panic!( "Error during processing of {}: {:?}", xml_file.display(), err ) }); let i = xcb_mod_map(i); deps.push( dep_info .iter() .find(|di| di.xcb_mod == i) .unwrap_or_else(|| panic!("can't find dependency {} of {}", i, xcb_mod)) .clone(), ); } deps }; let mut cg = CodeGen::new(xcb_mod, ffi, rs, deps, evcopies); cg.prologue(imports, &info.1)?; for ev in events { cg.event(ev)?; } cg.epilogue()?; dep_info.push(cg.into_depinfo()); Ok(()) }
match name { "bigreq" => "big_requests", "ge" => "genericevent", "xselinux" => "selinux", "xprint" => "x_print", "xtest" => "test", _ => name, }
if_condition
[ { "content": "fn main() {\n\n let dpy = \":0\";\n\n if let Ok((_, _)) = xcb::Connection::connect(Some(&dpy)) {\n\n println!(\"Connected to X on display \\\"{}\\\"!\", dpy);\n\n } else {\n\n println!(\"Could not connect to X!\");\n\n }\n\n}\n", "file_path": "examples/connect_str.rs"...