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/an_ok_binary_tree/src/lib.rs
shen-jinhao/Rust-With-Linked-Lists
924b6fe896192d1e3fc4757080027ae12baad28a
use an_ok_stack::List as Stack; use an_unsafe_queue::List as Queue; use std::fmt::Debug; #[derive(Clone)] pub struct BinaryTree<T> { root: Link<T>, } type Link<T> = Option<Box<Node<T>>>; #[derive(Eq, PartialEq, Clone)] struct Node<T> { elem: T, left: Link<T>, right: Link<T>, } impl<T> Node<T> { pub fn new(elem: T) -> Self { Self { elem, left: None, right: None, } } } impl<T: Debug + PartialEq + Clone> BinaryTree<T> { pub fn new(val: &[T], invalid: T) -> Self { let mut index: usize = 0; Self { root: Self::create(val, &invalid, &mut index) } } fn create(val: &[T], invalid: &T, index: &mut usize) -> Link<T> { let mut new_root: Link<T> = None; let cur = *index; if val[cur] != *invalid { new_root = Some(Box::new(Node::new(val[cur].clone()))); *index += 1; if let Some(node) = new_root.as_mut() { node.left = Self::create(val, invalid, index); } *index += 1; if let Some(node) = new_root.as_mut() { node.right = Self::create(val, invalid, index); } } new_root } pub fn prev_orer(&self) -> Vec<T>{ let mut res = Vec::new(); Self::prev_order_help(&self.root, &mut res); res } fn prev_order_help(root: &Link<T>, res: &mut Vec<T>){ if root.is_none() { return; } let node = root.as_ref().unwrap(); res.push(node.elem.clone()); Self::prev_order_help(&node.left, res); Self::prev_order_help(&node.right, res); } pub fn prev_order_no_r(&self) -> Vec<T>{ let mut res = Vec::new(); let mut stack = Stack::new(); let mut cur = self.root.as_ref(); while cur.is_some() || !stack.is_empty() { while cur.is_some() { let node = cur.unwrap(); res.push(node.elem.clone()); stack.push(node); cur = node.left.as_ref(); } cur = stack.pop().and_then(|node| { node.right.as_ref() }) } res } pub fn in_order(&self) -> Vec<T> { let mut res = Vec::new(); Self::in_order_help(&self.root, &mut res); res } fn in_order_help(root: &Link<T>, res: &mut Vec<T>) { if root.is_none() { return; } let node = root.as_ref().unwrap(); Self::in_order_help(&node.left, res); res.push(node.elem.clone()); Self::in_order_help(&node.right, res); } pub fn in_order_no_r(&self) -> Vec<T>{ let mut res = Vec::new(); let mut stack = Stack::new(); let mut cur = self.root.as_ref(); while cur.is_some() || !stack.is_empty() { while cur.is_some() { let node = cur.unwrap(); stack.push(node); cur = node.left.as_ref(); } cur = stack.pop().and_then(|node| { res.push(node.elem.clone()); node.right.as_ref() }) } res } pub fn post_order(&self) -> Vec<T>{ let mut res = Vec::new(); Self::post_order_help(&self.root, &mut res); res } fn post_order_help(root: &Link<T>, res: &mut Vec<T>) { if root.is_none() { return; } let node = root.as_ref().unwrap(); Self::post_order_help(&node.left, res); Self::post_order_help(&node.right, res); res.push(node.elem.clone()); } pub fn post_order_no_r(&self) -> Vec<T>{ let mut res = Vec::new(); let mut stack = Stack::new(); let mut cur = self.root.as_ref(); let mut prev: Option<&Box<Node<T>>> = None; while cur.is_some() || !stack.is_empty() { while cur.is_some() { let node = cur.unwrap(); stack.push(node); cur = node.left.as_ref(); } let top = stack.peek().unwrap(); if top.right.is_none() || top.right.as_ref() == prev { res.push(top.elem.clone()); prev = Some(top); let _ = stack.pop(); } else { cur = top.right.as_ref(); } } res } pub fn level_order(&self) -> Vec<T>{ let mut res = Vec::new(); let mut queue = Queue::new(); if self.root.is_some() { queue.push(self.root.as_ref().unwrap()); } while !queue.is_empty() { if let Some(node) = queue.pop() { res.push(node.elem.clone()); if node.left.is_some() { queue.push(node.left.as_ref().unwrap()); } if node.right.is_some() { queue.push(node.right.as_ref().unwrap()); } } } res } pub fn tree_node_size(&self) -> usize { let mut size: usize = 0; Self::tree_node_size_help(&self.root, &mut size); size } fn tree_node_size_help(root: &Link<T>, size: &mut usize) { if root.is_none() { return; } Self::tree_node_size_help(&root.as_ref().unwrap().left, size); *size += 1; Self::tree_node_size_help(&root.as_ref().unwrap().right, size); } pub fn tree_leaf_size(&self) -> usize { Self::tree_leaf_size_help(&self.root) } fn tree_leaf_size_help(root: &Link<T>) -> usize{ if root.is_none() { return 0; } if root.as_ref().unwrap().left.is_none() && root.as_ref().unwrap().right.is_none() { return 1; } let left = &root.as_ref().unwrap().left; let right = &root.as_ref().unwrap().right; Self::tree_leaf_size_help(left) + Self::tree_leaf_size_help(right) } pub fn tree_height(&self) -> usize { Self::tree_height_help(&self.root) } fn tree_height_help(root: &Link<T>) -> usize { if root.is_none() { return 0; } let left_height = Self::tree_height_help(&root.as_ref().unwrap().left); let right_height = Self::tree_height_help(&root.as_ref().unwrap().right); return if left_height > right_height { left_height + 1 } else { right_height + 1 } } pub fn get_level_node_size(&self, level: usize) -> Option<usize> { let height = self.tree_height(); if level > height || level == 0 { return None; } Some(Self::get_level_node_size_help(&self.root, level)) } fn get_level_node_size_help(root: &Link<T>, level: usize) -> usize{ if root.is_none() { return 0; } if level == 1 { return 1; } let left = &root.as_ref().unwrap().left; let right = &root.as_ref().unwrap().right; Self::get_level_node_size_help(left, level - 1) + Self::get_level_node_size_help(right, level - 1) } pub fn find(&self, key: T) -> bool { Self::find_help(&self.root, key) } fn find_help(root: &Link<T>, key: T) -> bool { if root.is_none() { return false; } if root.as_ref().unwrap().elem == key { return true; } let left = &root.as_ref().unwrap().left; let right = &root.as_ref().unwrap().right; let res = Self::find_help(left, key.clone()) || Self::find_help(right, key.clone()); if res { return res; } false } pub fn is_complete_tree(&self) -> bool { let mut queue = Queue::new(); if self.root.is_some() { queue.push(self.root.as_ref().unwrap()); } let mut flag = true; while !queue.is_empty() { let head = queue.pop().unwrap(); if head.left.is_some() { if !flag { return false; } queue.push(head.left.as_ref().unwrap()); } else { flag = false; } if head.right.is_some() { if !flag { return false; } queue.push(head.right.as_ref().unwrap()); } else { flag = false; } } true } pub fn destroy_tree(self) { Self::destroy_tree_help(self.root); } fn destroy_tree_help(root: Link<T>) { if root.is_none() { return; } let cur = root.unwrap(); Self::destroy_tree_help(cur.left); Self::destroy_tree_help(cur.right); } } #[cfg(test)] mod tests { use crate::BinaryTree; #[test] fn basic() { let array = ['A', 'B', '#', 'D', '#', '#', 'C' ,'#', '#']; let tree = BinaryTree::new(&array, '#'); assert_eq!(tree.prev_orer(), vec!['A', 'B', 'D', 'C']); assert_eq!(tree.prev_order_no_r(), vec!['A', 'B', 'D', 'C']); assert_eq!(tree.in_order(), vec!['B', 'D', 'A', 'C']); assert_eq!(tree.in_order_no_r(), vec!['B', 'D', 'A', 'C']); assert_eq!(tree.post_order(), vec!['D', 'B', 'C', 'A']); assert_eq!(tree.post_order_no_r(), vec!['D', 'B', 'C', 'A']); assert_eq!(tree.level_order(), vec!['A', 'B', 'C', 'D']); let array = ["Alian".to_string(), "Bob".to_string(), "no".to_string() , "David".to_string(), "no".to_string(), "no".to_string(), "Clion".to_string() ,"no".to_string(), "no".to_string()]; let tree = BinaryTree::new(&array, "no".to_string()); assert_eq!(tree.prev_orer(), vec!["Alian", "Bob", "David", "Clion"]); assert_eq!(tree.prev_order_no_r(), vec!["Alian", "Bob", "David", "Clion"]); assert_eq!(tree.in_order(), vec!["Bob", "David", "Alian", "Clion"]); assert_eq!(tree.in_order_no_r(), vec!["Bob", "David", "Alian", "Clion"]); assert_eq!(tree.post_order(), vec!["David", "Bob", "Clion", "Alian"]); assert_eq!(tree.post_order_no_r(), vec!["David", "Bob", "Clion", "Alian"]); assert_eq!(tree.level_order(), vec!["Alian", "Bob", "Clion", "David"]); } /* 1 / \ 2 3 / / \ 4 5 6 */ #[test] fn size_test() { let array = [1, 2, 4,i32::MIN, i32::MIN, i32::MIN ,3, 5, i32::MIN, i32::MIN, 6, i32::MIN, i32::MIN]; let tree = BinaryTree::new(&array, i32::MIN); assert_eq!(tree.prev_order_no_r(), vec![1, 2, 4, 3, 5, 6]); assert_eq!(tree.in_order_no_r(), vec![4,2,1,5,3,6]); assert_eq!(tree.post_order_no_r(), vec![4,2,5,6,3,1]); assert_eq!(tree.level_order(), vec![1,2,3,4,5,6]); assert_eq!(tree.tree_node_size(), 6); assert_eq!(tree.tree_leaf_size(), 3); assert_eq!(tree.tree_height(), 3); assert_eq!(tree.get_level_node_size(0), None); assert_eq!(tree.get_level_node_size(1), Some(1)); assert_eq!(tree.get_level_node_size(2), Some(2)); assert_eq!(tree.get_level_node_size(3), Some(3)); assert_eq!(tree.get_level_node_size(4), None); assert_eq!(tree.find(0), false); assert_eq!(tree.find(1), true); assert_eq!(tree.find(2), true); assert_eq!(tree.find(3), true); assert_eq!(tree.find(4), true); assert_eq!(tree.find(5), true); assert_eq!(tree.find(6), true); assert_eq!(tree.find(7), false); assert_eq!(tree.is_complete_tree(), false); } #[test] fn is_complete_test() { let array = [1, 2, 4,i32::MIN, i32::MIN, 5, i32::MIN, i32::MIN ,3, 6, i32::MIN, i32::MIN, 7, i32::MIN, i32::MIN]; let tree = BinaryTree::new(&array, i32::MIN); assert_eq!(tree.is_complete_tree(), true); tree.destroy_tree(); } }
use an_ok_stack::List as Stack; use an_unsafe_queue::List as Queue; use std::fmt::Debug; #[derive(Clone)] pub struct BinaryTree<T> { root: Link<T>, } type Link<T> = Option<Box<Node<T>>>; #[derive(Eq, PartialEq, Clone)] struct Node<T> { elem: T, left: Link<T>, right: Link<T>, } impl<T> Node<
()); } let mut flag = true; while !queue.is_empty() { let head = queue.pop().unwrap(); if head.left.is_some() { if !flag { return false; } queue.push(head.left.as_ref().unwrap()); } else { flag = false; } if head.right.is_some() { if !flag { return false; } queue.push(head.right.as_ref().unwrap()); } else { flag = false; } } true } pub fn destroy_tree(self) { Self::destroy_tree_help(self.root); } fn destroy_tree_help(root: Link<T>) { if root.is_none() { return; } let cur = root.unwrap(); Self::destroy_tree_help(cur.left); Self::destroy_tree_help(cur.right); } } #[cfg(test)] mod tests { use crate::BinaryTree; #[test] fn basic() { let array = ['A', 'B', '#', 'D', '#', '#', 'C' ,'#', '#']; let tree = BinaryTree::new(&array, '#'); assert_eq!(tree.prev_orer(), vec!['A', 'B', 'D', 'C']); assert_eq!(tree.prev_order_no_r(), vec!['A', 'B', 'D', 'C']); assert_eq!(tree.in_order(), vec!['B', 'D', 'A', 'C']); assert_eq!(tree.in_order_no_r(), vec!['B', 'D', 'A', 'C']); assert_eq!(tree.post_order(), vec!['D', 'B', 'C', 'A']); assert_eq!(tree.post_order_no_r(), vec!['D', 'B', 'C', 'A']); assert_eq!(tree.level_order(), vec!['A', 'B', 'C', 'D']); let array = ["Alian".to_string(), "Bob".to_string(), "no".to_string() , "David".to_string(), "no".to_string(), "no".to_string(), "Clion".to_string() ,"no".to_string(), "no".to_string()]; let tree = BinaryTree::new(&array, "no".to_string()); assert_eq!(tree.prev_orer(), vec!["Alian", "Bob", "David", "Clion"]); assert_eq!(tree.prev_order_no_r(), vec!["Alian", "Bob", "David", "Clion"]); assert_eq!(tree.in_order(), vec!["Bob", "David", "Alian", "Clion"]); assert_eq!(tree.in_order_no_r(), vec!["Bob", "David", "Alian", "Clion"]); assert_eq!(tree.post_order(), vec!["David", "Bob", "Clion", "Alian"]); assert_eq!(tree.post_order_no_r(), vec!["David", "Bob", "Clion", "Alian"]); assert_eq!(tree.level_order(), vec!["Alian", "Bob", "Clion", "David"]); } /* 1 / \ 2 3 / / \ 4 5 6 */ #[test] fn size_test() { let array = [1, 2, 4,i32::MIN, i32::MIN, i32::MIN ,3, 5, i32::MIN, i32::MIN, 6, i32::MIN, i32::MIN]; let tree = BinaryTree::new(&array, i32::MIN); assert_eq!(tree.prev_order_no_r(), vec![1, 2, 4, 3, 5, 6]); assert_eq!(tree.in_order_no_r(), vec![4,2,1,5,3,6]); assert_eq!(tree.post_order_no_r(), vec![4,2,5,6,3,1]); assert_eq!(tree.level_order(), vec![1,2,3,4,5,6]); assert_eq!(tree.tree_node_size(), 6); assert_eq!(tree.tree_leaf_size(), 3); assert_eq!(tree.tree_height(), 3); assert_eq!(tree.get_level_node_size(0), None); assert_eq!(tree.get_level_node_size(1), Some(1)); assert_eq!(tree.get_level_node_size(2), Some(2)); assert_eq!(tree.get_level_node_size(3), Some(3)); assert_eq!(tree.get_level_node_size(4), None); assert_eq!(tree.find(0), false); assert_eq!(tree.find(1), true); assert_eq!(tree.find(2), true); assert_eq!(tree.find(3), true); assert_eq!(tree.find(4), true); assert_eq!(tree.find(5), true); assert_eq!(tree.find(6), true); assert_eq!(tree.find(7), false); assert_eq!(tree.is_complete_tree(), false); } #[test] fn is_complete_test() { let array = [1, 2, 4,i32::MIN, i32::MIN, 5, i32::MIN, i32::MIN ,3, 6, i32::MIN, i32::MIN, 7, i32::MIN, i32::MIN]; let tree = BinaryTree::new(&array, i32::MIN); assert_eq!(tree.is_complete_tree(), true); tree.destroy_tree(); } }
T> { pub fn new(elem: T) -> Self { Self { elem, left: None, right: None, } } } impl<T: Debug + PartialEq + Clone> BinaryTree<T> { pub fn new(val: &[T], invalid: T) -> Self { let mut index: usize = 0; Self { root: Self::create(val, &invalid, &mut index) } } fn create(val: &[T], invalid: &T, index: &mut usize) -> Link<T> { let mut new_root: Link<T> = None; let cur = *index; if val[cur] != *invalid { new_root = Some(Box::new(Node::new(val[cur].clone()))); *index += 1; if let Some(node) = new_root.as_mut() { node.left = Self::create(val, invalid, index); } *index += 1; if let Some(node) = new_root.as_mut() { node.right = Self::create(val, invalid, index); } } new_root } pub fn prev_orer(&self) -> Vec<T>{ let mut res = Vec::new(); Self::prev_order_help(&self.root, &mut res); res } fn prev_order_help(root: &Link<T>, res: &mut Vec<T>){ if root.is_none() { return; } let node = root.as_ref().unwrap(); res.push(node.elem.clone()); Self::prev_order_help(&node.left, res); Self::prev_order_help(&node.right, res); } pub fn prev_order_no_r(&self) -> Vec<T>{ let mut res = Vec::new(); let mut stack = Stack::new(); let mut cur = self.root.as_ref(); while cur.is_some() || !stack.is_empty() { while cur.is_some() { let node = cur.unwrap(); res.push(node.elem.clone()); stack.push(node); cur = node.left.as_ref(); } cur = stack.pop().and_then(|node| { node.right.as_ref() }) } res } pub fn in_order(&self) -> Vec<T> { let mut res = Vec::new(); Self::in_order_help(&self.root, &mut res); res } fn in_order_help(root: &Link<T>, res: &mut Vec<T>) { if root.is_none() { return; } let node = root.as_ref().unwrap(); Self::in_order_help(&node.left, res); res.push(node.elem.clone()); Self::in_order_help(&node.right, res); } pub fn in_order_no_r(&self) -> Vec<T>{ let mut res = Vec::new(); let mut stack = Stack::new(); let mut cur = self.root.as_ref(); while cur.is_some() || !stack.is_empty() { while cur.is_some() { let node = cur.unwrap(); stack.push(node); cur = node.left.as_ref(); } cur = stack.pop().and_then(|node| { res.push(node.elem.clone()); node.right.as_ref() }) } res } pub fn post_order(&self) -> Vec<T>{ let mut res = Vec::new(); Self::post_order_help(&self.root, &mut res); res } fn post_order_help(root: &Link<T>, res: &mut Vec<T>) { if root.is_none() { return; } let node = root.as_ref().unwrap(); Self::post_order_help(&node.left, res); Self::post_order_help(&node.right, res); res.push(node.elem.clone()); } pub fn post_order_no_r(&self) -> Vec<T>{ let mut res = Vec::new(); let mut stack = Stack::new(); let mut cur = self.root.as_ref(); let mut prev: Option<&Box<Node<T>>> = None; while cur.is_some() || !stack.is_empty() { while cur.is_some() { let node = cur.unwrap(); stack.push(node); cur = node.left.as_ref(); } let top = stack.peek().unwrap(); if top.right.is_none() || top.right.as_ref() == prev { res.push(top.elem.clone()); prev = Some(top); let _ = stack.pop(); } else { cur = top.right.as_ref(); } } res } pub fn level_order(&self) -> Vec<T>{ let mut res = Vec::new(); let mut queue = Queue::new(); if self.root.is_some() { queue.push(self.root.as_ref().unwrap()); } while !queue.is_empty() { if let Some(node) = queue.pop() { res.push(node.elem.clone()); if node.left.is_some() { queue.push(node.left.as_ref().unwrap()); } if node.right.is_some() { queue.push(node.right.as_ref().unwrap()); } } } res } pub fn tree_node_size(&self) -> usize { let mut size: usize = 0; Self::tree_node_size_help(&self.root, &mut size); size } fn tree_node_size_help(root: &Link<T>, size: &mut usize) { if root.is_none() { return; } Self::tree_node_size_help(&root.as_ref().unwrap().left, size); *size += 1; Self::tree_node_size_help(&root.as_ref().unwrap().right, size); } pub fn tree_leaf_size(&self) -> usize { Self::tree_leaf_size_help(&self.root) } fn tree_leaf_size_help(root: &Link<T>) -> usize{ if root.is_none() { return 0; } if root.as_ref().unwrap().left.is_none() && root.as_ref().unwrap().right.is_none() { return 1; } let left = &root.as_ref().unwrap().left; let right = &root.as_ref().unwrap().right; Self::tree_leaf_size_help(left) + Self::tree_leaf_size_help(right) } pub fn tree_height(&self) -> usize { Self::tree_height_help(&self.root) } fn tree_height_help(root: &Link<T>) -> usize { if root.is_none() { return 0; } let left_height = Self::tree_height_help(&root.as_ref().unwrap().left); let right_height = Self::tree_height_help(&root.as_ref().unwrap().right); return if left_height > right_height { left_height + 1 } else { right_height + 1 } } pub fn get_level_node_size(&self, level: usize) -> Option<usize> { let height = self.tree_height(); if level > height || level == 0 { return None; } Some(Self::get_level_node_size_help(&self.root, level)) } fn get_level_node_size_help(root: &Link<T>, level: usize) -> usize{ if root.is_none() { return 0; } if level == 1 { return 1; } let left = &root.as_ref().unwrap().left; let right = &root.as_ref().unwrap().right; Self::get_level_node_size_help(left, level - 1) + Self::get_level_node_size_help(right, level - 1) } pub fn find(&self, key: T) -> bool { Self::find_help(&self.root, key) } fn find_help(root: &Link<T>, key: T) -> bool { if root.is_none() { return false; } if root.as_ref().unwrap().elem == key { return true; } let left = &root.as_ref().unwrap().left; let right = &root.as_ref().unwrap().right; let res = Self::find_help(left, key.clone()) || Self::find_help(right, key.clone()); if res { return res; } false } pub fn is_complete_tree(&self) -> bool { let mut queue = Queue::new(); if self.root.is_some() { queue.push(self.root.as_ref().unwrap
random
[ { "content": "struct Node {\n\n elem: i32,\n\n next: Link,\n\n}\n\n\n", "file_path": "src/a_bad_stack/src/lib.rs", "rank": 0, "score": 126590.78467837354 }, { "content": "struct Node<T> {\n\n elem: T,\n\n next: Link<T>,\n\n}\n\n\n\nimpl<T> List<T> {\n\n pub fn new() -> Self {\...
Rust
server/prisma-rs/query-engine/native-bridge/src/error.rs
otrebu/prisma
298be5c919119847bb8d102d6b16672edd06b2c5
use crate::protobuf; use connector::error::{ConnectorError, NodeSelectorInfo}; use failure::{Error, Fail}; use prisma_models::DomainError; use prost::DecodeError; use serde_json; #[derive(Debug, Fail)] pub enum BridgeError { #[fail(display = "Error in connector.")] ConnectorError(ConnectorError), #[fail(display = "Error in domain logic.")] DomainError(DomainError), #[fail(display = "Error decoding Protobuf input.")] ProtobufDecodeError(Error), #[fail(display = "Error decoding JSON input.")] JsonDecodeError(Error), #[fail(display = "Error decoding JSON input.")] InvalidConnectionArguments(&'static str), } impl From<ConnectorError> for BridgeError { fn from(e: ConnectorError) -> BridgeError { BridgeError::ConnectorError(e) } } impl From<DomainError> for BridgeError { fn from(e: DomainError) -> BridgeError { BridgeError::DomainError(e) } } impl From<DecodeError> for BridgeError { fn from(e: DecodeError) -> BridgeError { BridgeError::ProtobufDecodeError(e.into()) } } impl From<serde_json::error::Error> for BridgeError { fn from(e: serde_json::error::Error) -> BridgeError { BridgeError::JsonDecodeError(e.into()) } } impl From<NodeSelectorInfo> for protobuf::prisma::NodeSelector { fn from(info: NodeSelectorInfo) -> Self { Self { model_name: info.model, field_name: info.field, value: info.value.into(), } } } impl From<BridgeError> for protobuf::prisma::error::Value { fn from(error: BridgeError) -> protobuf::prisma::error::Value { match error { BridgeError::ConnectorError(e @ ConnectorError::ConnectionError(_)) => { protobuf::prisma::error::Value::ConnectionError(format!("{}", e)) } BridgeError::ConnectorError(e @ ConnectorError::QueryError(_)) => { protobuf::prisma::error::Value::QueryError(format!("{}", e)) } BridgeError::ConnectorError(e @ ConnectorError::InvalidConnectionArguments) => { protobuf::prisma::error::Value::QueryError(format!("{}", e)) } BridgeError::ConnectorError(ConnectorError::FieldCannotBeNull { field }) => { protobuf::prisma::error::Value::FieldCannotBeNull(field) } BridgeError::ConnectorError(ConnectorError::UniqueConstraintViolation { field_name }) => { protobuf::prisma::error::Value::UniqueConstraintViolation(field_name) } BridgeError::ConnectorError(ConnectorError::RelationViolation { relation_name, model_a_name, model_b_name, }) => { let error = protobuf::prisma::RelationViolationError { relation_name, model_a_name, model_b_name, }; protobuf::prisma::error::Value::RelationViolation(error) } BridgeError::ConnectorError(ConnectorError::NodeNotFoundForWhere(info)) => { let node_selector = protobuf::prisma::NodeSelector { model_name: info.model, field_name: info.field, value: info.value.into(), }; protobuf::prisma::error::Value::NodeNotFoundForWhere(node_selector) } BridgeError::ConnectorError(ConnectorError::NodesNotConnected { relation_name, parent_name, parent_where, child_name, child_where, }) => { let error = protobuf::prisma::NodesNotConnectedError { relation_name: relation_name, parent_name: parent_name, parent_where: parent_where.map(protobuf::prisma::NodeSelector::from), child_name: child_name, child_where: child_where.map(protobuf::prisma::NodeSelector::from), }; protobuf::prisma::error::Value::NodesNotConnected(error) } e @ BridgeError::ProtobufDecodeError(_) => { protobuf::prisma::error::Value::ProtobufDecodeError(format!("{}", e)) } e @ BridgeError::JsonDecodeError(_) => protobuf::prisma::error::Value::JsonDecodeError(format!("{}", e)), e @ BridgeError::DomainError(_) => protobuf::prisma::error::Value::InvalidInputError(format!("{}", e)), e => protobuf::prisma::error::Value::InvalidInputError(format!("{}", e)), } } }
use crate::protobuf; use connector::error::{ConnectorError, NodeSelectorInfo}; use failure::{Error, Fail}; use prisma_models::DomainError; use prost::DecodeError; use serde_json; #[derive(Debug, Fail)] pub enum BridgeError { #[fail(display = "Error in connector.")] ConnectorError(ConnectorError), #[fail(display = "Error in domain logic.")] DomainError(DomainError), #[fail(display = "Error decoding Protobuf input.")] ProtobufDecodeError(Error), #[fail(display = "Error decoding JSON input.")] JsonDecodeError(Error), #[fail(display = "Error decoding JSON input.")] InvalidConnectionArguments(&'static str), } impl From<ConnectorError> for BridgeError { fn from(e: ConnectorError) -> BridgeError { BridgeError::ConnectorError(e) } } impl From<DomainError> for BridgeError { fn from(e: DomainError) -> BridgeError { BridgeError::DomainError(e) } } impl From<DecodeError> for BridgeError { fn from(e: DecodeError) -> BridgeError { BridgeError::ProtobufDecodeError(e.into()) } } impl From<serde_json::error::Error> for BridgeError { fn from(e: serde_json::error::Error) -> BridgeError { BridgeError::JsonDecodeError(e.into()) } } impl From<NodeSelectorInfo> for protobuf::prisma::NodeSelector { fn from(info: NodeSelectorInfo) -> Self { Self { model_name: info.model, field_name: info.field, value: info.value.into(), } } } impl From<BridgeError> for protobuf::prisma::error::Value { fn from(error: BridgeError) -> protobuf::prisma::error::Value { match error { BridgeError::ConnectorError(e @ ConnectorError::ConnectionError(_)) => { protobuf::prisma::error::Value::ConnectionError(format!("{}", e)) } BridgeError::ConnectorError(e @ ConnectorError::QueryError(_)) => { protobuf::prisma::error::Value::QueryError(format!("{}", e)) } BridgeError::ConnectorError(e @ ConnectorError::InvalidConnectionArguments) => { protobuf::prisma::error::Value::QueryError(format!("{}", e)) } BridgeError::ConnectorError(ConnectorError::FieldCannotBeNull { field }) => { protobuf::prisma::error::Value::FieldCannotBeNull(field) } BridgeError::ConnectorError(ConnectorError::UniqueConstraintViolation { field_name }) => { protobuf::prisma::error::Value::UniqueConstraintViolation(field_name) } BridgeError::ConnectorError(ConnectorError::RelationViolation { relation_name, model_a_name, model_b_name, }) => { let error = protobuf::prisma::RelationViolationError { relation_name, model_a_name, model_b_name, }; protobuf::prisma::error::Value::RelationViolation(error) } BridgeError::ConnectorError(ConnectorError::NodeNotFoundForWhere(info)) => {
protobuf::prisma::error::Value::NodeNotFoundForWhere(node_selector) } BridgeError::ConnectorError(ConnectorError::NodesNotConnected { relation_name, parent_name, parent_where, child_name, child_where, }) => { let error = protobuf::prisma::NodesNotConnectedError { relation_name: relation_name, parent_name: parent_name, parent_where: parent_where.map(protobuf::prisma::NodeSelector::from), child_name: child_name, child_where: child_where.map(protobuf::prisma::NodeSelector::from), }; protobuf::prisma::error::Value::NodesNotConnected(error) } e @ BridgeError::ProtobufDecodeError(_) => { protobuf::prisma::error::Value::ProtobufDecodeError(format!("{}", e)) } e @ BridgeError::JsonDecodeError(_) => protobuf::prisma::error::Value::JsonDecodeError(format!("{}", e)), e @ BridgeError::DomainError(_) => protobuf::prisma::error::Value::InvalidInputError(format!("{}", e)), e => protobuf::prisma::error::Value::InvalidInputError(format!("{}", e)), } } }
let node_selector = protobuf::prisma::NodeSelector { model_name: info.model, field_name: info.field, value: info.value.into(), };
assignment_statement
[ { "content": "pub fn parse_and_validate(input: &str) -> dml::Schema {\n\n let ast = datamodel::parser::parse(&String::from(input)).expect(\"Unable to parse datamodel.\");\n\n let validator = datamodel::validator::Validator::new();\n\n validator.validate(&ast).expect(\"Validation error\")\n\n}\n", "...
Rust
main/src/devices/stepper.rs
Alexander89/Stepper-Feedback-Driver
4e698750d75d79ec77b9845374cc9ebf741c4422
use atsamd_hal::{ delay::Delay, gpio::v2::{Pin, PushPullOutput, PA04, PA10, PA11}, prelude::_atsamd_hal_embedded_hal_digital_v2_OutputPin, }; use embedded_hal::digital::v2::PinState; use utils::time::{Microseconds, U32Ext}; use crate::settings::{DT_MIN_U32, STEPS_PER_RESOLUTION_I16, STEPS_PER_RESOLUTION_I16_HALF}; pub enum Direction { CW, CCW, } pub enum NextStepperAction { Idle, DirectionChanged(Direction), StepRequired(i8), } pub struct Stepper { enable: Pin<PA04, PushPullOutput>, direction: Pin<PA10, PushPullOutput>, step: Pin<PA11, PushPullOutput>, state: PinState, turn_cw: bool, current_direction_cw: bool, target_step: i32, current_step: i32, real_step: i32, last_mag_val: i16, filtered_dt_per_step: u32, } impl Stepper { pub fn init( enable: Pin<PA04, PushPullOutput>, direction: Pin<PA10, PushPullOutput>, step: Pin<PA11, PushPullOutput>, ) -> Self { let mut motor = Self { enable, direction, step, state: PinState::Low, turn_cw: true, current_direction_cw: true, target_step: 0, current_step: 0, real_step: 0, last_mag_val: 0, filtered_dt_per_step: 0, }; motor.direction.set_high(); motor.disable(); motor.cw(); motor } pub fn enable(&mut self) { self.enable.set_low(); } pub fn disable(&mut self) { self.enable.set_high(); } pub fn cw(&mut self) { self.turn_cw = true; } pub fn ccw(&mut self) { self.turn_cw = false; } pub fn do_step(&mut self) { if self.turn_cw { self.target_step += 1; } else { self.target_step -= 1; } } pub fn init_stepper(&mut self, start_value: i16) { self.last_mag_val = start_value; } pub fn poll_next_action(&mut self) -> NextStepperAction { if self.current_step == self.target_step { NextStepperAction::Idle } else if self.current_step > self.target_step && self.current_direction_cw { NextStepperAction::DirectionChanged(Direction::CCW) } else if self.current_step < self.target_step && !self.current_direction_cw { NextStepperAction::DirectionChanged(Direction::CW) } else { if self.current_direction_cw { NextStepperAction::StepRequired(1) } else { NextStepperAction::StepRequired(-1) } } } pub fn execute(&mut self, req: NextStepperAction) -> bool { match req { NextStepperAction::Idle => false, NextStepperAction::DirectionChanged(Direction::CW) => { self.direction.set_high(); self.current_direction_cw = true; true } NextStepperAction::DirectionChanged(Direction::CCW) => { self.direction.set_low(); self.current_direction_cw = false; true } NextStepperAction::StepRequired(i) => { self.current_step += i as i32; self.state = !self.state; self.step.set_high(); cortex_m::asm::nop(); cortex_m::asm::nop(); cortex_m::asm::nop(); cortex_m::asm::nop(); cortex_m::asm::nop(); self.step.set_low(); (self.current_step - self.real_step).abs() < 3 } } } pub fn update_angle( &mut self, mag_val: i16, dt: Microseconds, motor_dt: Microseconds, ) -> Option<Microseconds> { let mmove = STEPS_PER_RESOLUTION_I16_HALF - self.last_mag_val; let mut new_val = mag_val + mmove; if new_val < 0 { new_val += STEPS_PER_RESOLUTION_I16; } else if new_val > STEPS_PER_RESOLUTION_I16 { new_val -= STEPS_PER_RESOLUTION_I16; } let mut dif: i32 = (STEPS_PER_RESOLUTION_I16_HALF - new_val) as i32; self.real_step -= dif; let dt_per_step = if dif == 0 { DT_MIN_U32 } else { (dt.0 / dif.abs() as u32).min(DT_MIN_U32) }; self.filtered_dt_per_step = ((self.filtered_dt_per_step + dt_per_step) / 2).min(DT_MIN_U32); let stuck = motor_dt.0 < self.filtered_dt_per_step - 1280; let dif = self.current_step - self.real_step; match dif.abs() { 1 => { } x if x > 1 => self.current_step -= (dif) / 2, _ => (), } self.last_mag_val = mag_val; if stuck { Some(self.filtered_dt_per_step.us()) } else { None } } }
use atsamd_hal::{ delay::Delay, gpio::v2::{Pin, PushPullOutput, PA04, PA10, PA11}, prelude::_atsamd_hal_embedded_hal_digital_v2_OutputPin, }; use embedded_hal::digital::v2::PinState; use utils::time::{Microseconds, U32Ext}; use crate::settings::{DT_MIN_U32, STEPS_PER_RESOLUTION_I16, STEPS_PER_RESOLUTION_I16_HALF}; pub enum Direction { CW, CCW, } pub enum NextStepperAction { Idle, DirectionChanged(Direction), StepRequired(i8), } pub struct Stepper { enable: Pin<PA04, PushPullOutput>, direction: Pin<PA10, PushPullOutput>, step: Pin<PA11, PushPullOutput>, state: PinState, turn_cw: bool, current_direction_cw: bool, target_step: i32, current_step: i32, real_step: i32, last_mag_val: i16, filtered_dt_per_step: u32, } impl Stepper { pub fn init( enable: Pin<PA04, PushPullOutput>, direction: Pin<PA10, PushPullOutput>, step: Pin<PA11, PushPullOutput>, ) -> Self { let mut motor = Self { enable, direction, step, state: PinState::Low, turn_cw: true, current_direction_cw: true, target_step: 0, current_step: 0, real_step: 0, last_mag_val: 0, filtered_dt_per_step: 0, }; motor.direction.set_high(); motor.disable(); motor.cw(); motor } pub fn enable(&mut self) { self.enable.set_low(); } pub fn disable(&mut self) { self.enable.set_high(); } pub fn cw(&mut self) { self.turn_cw = true; } pub fn ccw(&mut self) { self.turn_cw = false; } pub fn do_step(&mut self) { if self.turn_cw { self.target_step += 1; } else { self.target_step -= 1; } } pub fn init_stepper(&mut self, start_value: i16) { self.last_mag_val = start_value; } pub fn poll_next_action(&mut self) -> NextStepperAction { if self.current_step == self.target_step { NextStepperAction::Idle } else if self.current_step > self.target_step && self.current_direction_cw { NextStepperAction::DirectionChanged(Direction::CCW) } else if self.current_step < self.target_step && !self.current_direction_cw { NextStepperAction::DirectionChanged(Direction::CW) } else { if self.current_direction_cw { NextStepperAction::StepRequired(1) } else { NextStepperAction::StepRequired(-1) } } } pub fn execute(&mut self, req: NextStepperAction) -> bool { match req { NextStepperAction::Idle => false, NextStepperAction::DirectionChanged(Direction::CW) => { self.direction.set_high(); self.current_direction_cw = true; true } NextStepperAction::DirectionChanged(Direction::CCW) => { self.direction.set_low(); self.current_direction_cw = false; true } NextStepperAction::StepRequired(i) => { self.current_step += i as i32; self.state = !self.state; self.step.set_high(); cortex_m::asm::nop(); cortex_m::asm::nop(); cortex_m::asm::nop(); cortex_m::asm::nop(); cortex_m::asm::nop(); self.step.set_low(); (self.current_step - self.real_step).abs() < 3 } } } pub fn update_angle( &mut self, mag_val: i16, dt: Microseconds, motor_dt: Microseconds, ) -> Option<Microseconds> { let mmove = STEPS_PER_RESOLUTION_I16_HALF - self.last_mag_val; let mut new_val = mag_val + mmove; if new_val < 0 { new_val += STEPS_PER_RESOLUTION_I16; } else if new_val > STEPS_PER_RESOLUTION_I16 { new_val -= STEPS_PER_RESOLUTION_I16; } let mut dif: i32 = (STEPS_PER_RESOLUTION_I16_HALF - new_val) as i32; self.real_step -= dif;
self.filtered_dt_per_step = ((self.filtered_dt_per_step + dt_per_step) / 2).min(DT_MIN_U32); let stuck = motor_dt.0 < self.filtered_dt_per_step - 1280; let dif = self.current_step - self.real_step; match dif.abs() { 1 => { } x if x > 1 => self.current_step -= (dif) / 2, _ => (), } self.last_mag_val = mag_val; if stuck { Some(self.filtered_dt_per_step.us()) } else { None } } }
let dt_per_step = if dif == 0 { DT_MIN_U32 } else { (dt.0 / dif.abs() as u32).min(DT_MIN_U32) };
assignment_statement
[ { "content": "fn enabled_changed(state: bool) {\n\n unsafe { HARDWARE.as_mut() }.map(|hw| {\n\n if state {\n\n hw.stepper_enable();\n\n hw.led1.on()\n\n } else {\n\n hw.stepper_disable();\n\n hw.led1.off()\n\n }\n\n });\n\n}\n", "file_pa...
Rust
fruity_core/fruity_ecs/src/entity/entity_query/serialized/mod.rs
DoYouRockBaby/fruity_game_engine
299a8fe641efb142a551640f6d1aa4868e1ad670
use crate::entity::archetype::Archetype; use crate::entity::archetype::ArchetypeArcRwLock; use crate::entity::entity_query::serialized::params::With; use crate::entity::entity_query::serialized::params::WithEnabled; use crate::entity::entity_query::serialized::params::WithEntity; use crate::entity::entity_query::serialized::params::WithId; use crate::entity::entity_query::serialized::params::WithName; use crate::entity::entity_query::serialized::params::WithOptional; use crate::entity::entity_reference::EntityReference; use fruity_any::*; use fruity_core::convert::FruityInto; use fruity_core::introspect::FieldInfo; use fruity_core::introspect::IntrospectObject; use fruity_core::introspect::MethodCaller; use fruity_core::introspect::MethodInfo; use fruity_core::serialize::serialized::Callback; use fruity_core::serialize::serialized::SerializableObject; use fruity_core::serialize::serialized::Serialized; use fruity_core::utils::introspect::cast_introspect_mut; use fruity_core::utils::introspect::ArgumentCaster; use fruity_core::RwLock; use itertools::Itertools; use std::fmt::Debug; use std::sync::Arc; pub(crate) mod params; pub trait SerializedQueryParam: FruityAny { fn duplicate(&self) -> Box<dyn SerializedQueryParam>; fn filter_archetype(&self, archetype: &Archetype) -> bool; fn get_entity_components(&self, entity_reference: EntityReference) -> Vec<Serialized>; } #[derive(FruityAny)] pub(crate) struct SerializedQuery { pub archetypes: Arc<RwLock<Vec<ArchetypeArcRwLock>>>, pub params: Vec<Box<dyn SerializedQueryParam>>, } impl Clone for SerializedQuery { fn clone(&self) -> Self { Self { archetypes: self.archetypes.clone(), params: self .params .iter() .map(|param| param.duplicate()) .collect::<Vec<_>>(), } } } impl Debug for SerializedQuery { fn fmt( &self, _formatter: &mut std::fmt::Formatter<'_>, ) -> std::result::Result<(), std::fmt::Error> { Ok(()) } } impl SerializedQuery { pub fn with_entity(&mut self) { self.params.push(Box::new(WithEntity {})); } pub fn with_id(&mut self) { self.params.push(Box::new(WithId {})); } pub fn with_name(&mut self) { self.params.push(Box::new(WithName {})); } pub fn with_enabled(&mut self) { self.params.push(Box::new(WithEnabled {})); } pub fn with(&mut self, component_identifier: &str) { self.params.push(Box::new(With { identifier: component_identifier.to_string(), })); } pub fn with_optional(&mut self, component_identifier: &str) { self.params.push(Box::new(WithOptional { identifier: component_identifier.to_string(), })); } pub fn for_each(&self, callback: impl Fn(&[Serialized]) + Send + Sync) { let archetypes = self.archetypes.read(); let mut archetype_iter: Box<dyn Iterator<Item = &ArchetypeArcRwLock>> = Box::new(archetypes.iter()); for param in self.params.iter() { archetype_iter = Box::new( archetype_iter.filter(|archetype| param.filter_archetype(&archetype.read())), ); } let entities = archetype_iter .map(|archetype| archetype.iter(false)) .flatten() .collect::<Vec<_>>(); entities .into_iter() /*.par_bridge()*/ .for_each(|entity| { let serialized_params = self .params .iter() .map(|param| param.get_entity_components(entity.clone())) .multi_cartesian_product(); serialized_params.for_each(|params| callback(&params)) }); } } impl FruityInto<Serialized> for SerializedQuery { fn fruity_into(self) -> Serialized { Serialized::NativeObject(Box::new(self)) } } impl SerializableObject for SerializedQuery { fn duplicate(&self) -> Box<dyn SerializableObject> { Box::new(self.clone()) } } impl IntrospectObject for SerializedQuery { fn get_class_name(&self) -> String { "Query".to_string() } fn get_method_infos(&self) -> Vec<MethodInfo> { vec![ MethodInfo { name: "with_entity".to_string(), call: MethodCaller::Mut(Arc::new(|this, _args| { let this = cast_introspect_mut::<SerializedQuery>(this); this.with_entity(); Ok(Some(Serialized::NativeObject(this.duplicate()))) })), }, MethodInfo { name: "with_id".to_string(), call: MethodCaller::Mut(Arc::new(|this, _args| { let this = cast_introspect_mut::<SerializedQuery>(this); this.with_id(); Ok(Some(Serialized::NativeObject(this.duplicate()))) })), }, MethodInfo { name: "with_name".to_string(), call: MethodCaller::Mut(Arc::new(|this, _args| { let this = cast_introspect_mut::<SerializedQuery>(this); this.with_name(); Ok(Some(Serialized::NativeObject(this.duplicate()))) })), }, MethodInfo { name: "with_enabled".to_string(), call: MethodCaller::Mut(Arc::new(|this, _args| { let this = cast_introspect_mut::<SerializedQuery>(this); this.with_enabled(); Ok(Some(Serialized::NativeObject(this.duplicate()))) })), }, MethodInfo { name: "with".to_string(), call: MethodCaller::Mut(Arc::new(|this, args| { let this = cast_introspect_mut::<SerializedQuery>(this); let mut caster = ArgumentCaster::new("with", args); let arg1 = caster.cast_next::<String>()?; this.with(&arg1); Ok(Some(Serialized::NativeObject(this.duplicate()))) })), }, MethodInfo { name: "with_optional".to_string(), call: MethodCaller::Mut(Arc::new(|this, args| { let this = cast_introspect_mut::<SerializedQuery>(this); let mut caster = ArgumentCaster::new("with_optional", args); let arg1 = caster.cast_next::<String>()?; this.with_optional(&arg1); Ok(Some(Serialized::NativeObject(this.duplicate()))) })), }, MethodInfo { name: "for_each".to_string(), call: MethodCaller::Mut(Arc::new(|this, args| { let this = cast_introspect_mut::<SerializedQuery>(this); let mut caster = ArgumentCaster::new("for_each", args); let arg1 = caster.cast_next::<Callback>()?; let callback = arg1.callback; this.for_each(|args| { callback(args.to_vec()).ok(); }); Ok(None) })), }, ] } fn get_field_infos(&self) -> Vec<FieldInfo> { vec![] } }
use crate::entity::archetype::Archetype; use crate::entity::archetype::ArchetypeArcRwLock; use crate::entity::entity_query::serialized::params::With; use crate::entity::entity_query::serialized::params::WithEnabled; use crate::entity::entity_query::serialized::params::WithEntity; use crate::entity::entity_query::serialized::params::WithId; use crate::entity::entity_query::serialized::params::WithName; use crate::entity::entity_query::serialized::params::WithOptional; use crate::entity::entity_reference::EntityReference; use fruity_any::*; use fruity_core::convert::FruityInto; use fruity_core::introspect::FieldInfo; use fruity_core::introspect::IntrospectObject; use fruity_core::introspect::MethodCaller; use fruity_core::introspect::MethodInfo; use fruity_core::serialize::serialized::Callback; use fruity_core::serialize::serialized::SerializableObject; use fruity_core::serialize::serialized::Serialized; use fruity_core::utils::introspect::cast_introspect_mut; use fruity_core::utils::introspect::ArgumentCaster; use fruity_core::RwLock; use itertools::Itertools; use std::fmt::Debug; use std::sync::Arc; pub(crate) mod params; pub trait SerializedQueryParam: FruityAny { fn duplicate(&self) -> Box<dyn SerializedQueryParam>; fn filter_archetype(&self, archetype: &Archetype) -> bool; fn get_entity_components(&self, entity_reference: EntityReference) -> Vec<Serialized>; } #[derive(FruityAny)] pub(crate) struct SerializedQuery { pub archetypes: Arc<RwLock<Vec<ArchetypeArcRwLock>>>, pub params: Vec<Box<dyn SerializedQueryParam>>, } impl Clone for SerializedQuery { fn clone(&self) -> Self { Self { archetypes: self.archetypes.clone(), params: self .params .iter() .map(|param| param.duplicate()) .collect::<Vec<_>>(), } } } impl Debug for SerializedQuery { fn fmt( &self, _formatter: &mut std::fmt::Formatter<'_>, ) -> std::result::Result<(), std::fmt::Error> { Ok(()) } } impl SerializedQuery { pub fn with_entity(&mut self) { self.params.push(Box::new(WithEntity {})); } pub fn with_id(&mut self) { self.params.push(Box::new(WithId {})); } pub fn with_name(&mut self) { self.params.push(Box::new(WithName {})); } pub fn with_enabled(&mut self) { self.params.push(Box::new(WithEnabled {})); } pub fn with(&mut self, component_identifier: &str) { self.params.push(Box::new(With { identifier: component_identifier.to_string(), })); } pub fn with_optional(&mut self, component_identifier: &str) { self.params.push(Box::new(WithOptional { identifier: component_identifier.to_string(), })); } pub fn for_each(&self, callback: impl Fn(&[Serialized]) + Send + Sync) { let archetypes = self.archetypes.read(); let mut archetype_iter: Box<dyn Iterator<Item = &ArchetypeArcRwLock>> = Box::new(archetypes.iter()); for param in self.params.iter() { archetype_iter = Box::new( archetype_iter.filter(|archetype| param.filter_archetype(&archetype.read())), ); } let entities = archetype_iter .map(|archetype| archetype.iter(false)) .flatten() .collect::<Vec<_>>(); entities .into_iter() /*.par_bridge()*/ .for_each(|entity| { let serialized_params = self .params .iter() .map(|param| param.get_entity_components(entity.clone())) .multi_cartesian_product(); serialized_params.for_each(|params| callback(&params)) }); } } impl FruityInto<Serialized> for SerializedQuery { fn fruity_into(self) -> Serialized { Serialized::NativeObject(Box::new(self)) } } impl SerializableObject for SerializedQuery { fn duplicate(&self) -> Box<dyn SerializableObject> { Box::new(self.clone()) } } impl IntrospectObject for SerializedQuery { fn get_class_name(&self) -> String { "Query".to_string() }
fn get_field_infos(&self) -> Vec<FieldInfo> { vec![] } }
fn get_method_infos(&self) -> Vec<MethodInfo> { vec![ MethodInfo { name: "with_entity".to_string(), call: MethodCaller::Mut(Arc::new(|this, _args| { let this = cast_introspect_mut::<SerializedQuery>(this); this.with_entity(); Ok(Some(Serialized::NativeObject(this.duplicate()))) })), }, MethodInfo { name: "with_id".to_string(), call: MethodCaller::Mut(Arc::new(|this, _args| { let this = cast_introspect_mut::<SerializedQuery>(this); this.with_id(); Ok(Some(Serialized::NativeObject(this.duplicate()))) })), }, MethodInfo { name: "with_name".to_string(), call: MethodCaller::Mut(Arc::new(|this, _args| { let this = cast_introspect_mut::<SerializedQuery>(this); this.with_name(); Ok(Some(Serialized::NativeObject(this.duplicate()))) })), }, MethodInfo { name: "with_enabled".to_string(), call: MethodCaller::Mut(Arc::new(|this, _args| { let this = cast_introspect_mut::<SerializedQuery>(this); this.with_enabled(); Ok(Some(Serialized::NativeObject(this.duplicate()))) })), }, MethodInfo { name: "with".to_string(), call: MethodCaller::Mut(Arc::new(|this, args| { let this = cast_introspect_mut::<SerializedQuery>(this); let mut caster = ArgumentCaster::new("with", args); let arg1 = caster.cast_next::<String>()?; this.with(&arg1); Ok(Some(Serialized::NativeObject(this.duplicate()))) })), }, MethodInfo { name: "with_optional".to_string(), call: MethodCaller::Mut(Arc::new(|this, args| { let this = cast_introspect_mut::<SerializedQuery>(this); let mut caster = ArgumentCaster::new("with_optional", args); let arg1 = caster.cast_next::<String>()?; this.with_optional(&arg1); Ok(Some(Serialized::NativeObject(this.duplicate()))) })), }, MethodInfo { name: "for_each".to_string(), call: MethodCaller::Mut(Arc::new(|this, args| { let this = cast_introspect_mut::<SerializedQuery>(this); let mut caster = ArgumentCaster::new("for_each", args); let arg1 = caster.cast_next::<Callback>()?; let callback = arg1.callback; this.for_each(|args| { callback(args.to_vec()).ok(); }); Ok(None) })), }, ] }
function_block-full_function
[ { "content": "pub fn use_global<'a, T: Send + Sync + 'static>() -> &'a mut T {\n\n let mut globals = GLOBALS.lock();\n\n let globals = globals.get_mut(&TypeId::of::<T>()).unwrap().deref_mut();\n\n let result = globals.downcast_mut::<T>().unwrap();\n\n\n\n // TODO: Try to find a way to remove that\n\...
Rust
src/beatmap/mod.rs
LunarCoffee/osurate
06684a4ddef5a579903e794245d98cea5d9883c8
use std::io::BufRead; pub use crate::beatmap::parser::ParseError; use crate::beatmap::parser::Parser; mod parser; #[derive(Clone, Debug)] pub struct Beatmap { pub general_info: GeneralInfo, pub editor_info: EditorInfo, pub metadata: Metadata, pub difficulty: DifficultyInfo, pub events: Events, pub timing_points: Vec<TimingPoint>, pub colors: Option<Colors>, pub hit_objects: Vec<HitObject>, } impl Beatmap { pub fn parse(reader: impl BufRead) -> parser::Result<Beatmap> { Parser::new(reader).parse() } pub fn change_rate(&mut self, rate: f64) -> bool { let transform_f64 = |n| n / rate + 75.; let transform = |n| transform_f64(n as f64) as i32; let preview = self.general_info.preview_time; self.general_info.preview_time = if preview >= 0 { transform(preview) } else { preview }; self.metadata.diff_name += &format!(" ({}x)", rate); for mut point in &mut self.timing_points { point.time = transform_f64(point.time); if point.beat_len.is_sign_positive() { point.beat_len /= rate; } } for mut object in &mut self.hit_objects { object.time = transform(object.time); match object.params { HitObjectParams::Spinner(end_time) => object.params = HitObjectParams::Spinner(transform(end_time)), HitObjectParams::LongNote(end_time) => { let rest = match object.rest_parts[2].split_once(':') { Some((_, rest)) => rest, _ => return false, }; object.rest_parts[2] = transform(end_time).to_string() + ":" + rest; } _ => {} } } true } pub fn into_string(self) -> String { format!( "osu file format v14\n\n{}\n{}\n{}\n{}\n{}\n[TimingPoints]\n{}\n\n{}\n[HitObjects]\n{}", self.general_info.into_string(), self.editor_info.into_string(), self.metadata.into_string(), self.difficulty.into_string(), self.events.into_string(), self.timing_points.into_iter().map(|p| p.into_string()).collect::<Vec<_>>().join("\n"), self.colors.map(|c| c.into_string()).unwrap_or(String::new()), self.hit_objects.into_iter().map(|p| p.into_string()).collect::<Vec<_>>().join("\n"), ) } } #[derive(Clone, Debug)] pub struct GeneralInfo { pub audio_file: String, pub preview_time: i32, rest: String, } impl GeneralInfo { fn into_string(self) -> String { format!("[General]\nAudioFilename: {}\nPreviewTime: {}\n{}", self.audio_file, self.preview_time, self.rest) } } #[derive(Clone, Debug)] pub struct EditorInfo(String); impl EditorInfo { fn into_string(self) -> String { format!("[Editor]\n{}", self.0) } } #[derive(Clone, Debug)] pub struct Metadata { pub diff_name: String, rest: String, } impl Metadata { fn into_string(self) -> String { format!("[Metadata]\nVersion:{}\n{}", self.diff_name, self.rest) } } #[derive(Clone, Debug)] pub struct DifficultyInfo(String); impl DifficultyInfo { fn into_string(self) -> String { format!("[Difficulty]\n{}", self.0) } } #[derive(Clone, Debug)] pub struct Events(String); impl Events { fn into_string(self) -> String { format!("[Events]\n{}", self.0) } } #[derive(Clone, Debug)] pub struct TimingPoint { pub time: f64, pub beat_len: f64, rest: String, } impl TimingPoint { fn into_string(self) -> String { format!("{},{},{}", self.time as i32, self.beat_len, self.rest) } } #[derive(Clone, Debug)] pub struct Colors(String); impl Colors { fn into_string(self) -> String { format!("[Colours]\n{}", self.0) } } #[derive(Clone, Debug)] pub struct HitObject { pub time: i32, pub params: HitObjectParams, rest_parts: Vec<String>, } impl HitObject { fn into_string(self) -> String { format!( "{},{},{}{}{}", self.rest_parts[0], self.time, self.rest_parts[1], self.params.into_string(), self.rest_parts[2], ) } } #[derive(Clone, Debug)] pub enum HitObjectParams { NoneUseful, Spinner(i32), LongNote(i32), } impl HitObjectParams { fn into_string(self) -> String { match self { HitObjectParams::NoneUseful | HitObjectParams::LongNote(_) => ",".to_string(), HitObjectParams::Spinner(end_time) => format!(",{},", end_time), } } }
use std::io::BufRead; pub use crate::beatmap::parser::ParseError; use crate::beatmap::parser::Parser; mod parser; #[derive(Clone, Debug)] pub struct Beatmap { pub general_info: GeneralInfo, pub editor_info: EditorInfo, pub metadata: Metadata, pub difficulty: DifficultyInfo, pub events: Events, pub timing_points: Vec<TimingPoint>, pub colors: Option<Colors>, pub hit_objects: Vec<HitObject>, } impl Beatmap { pub fn parse(reader: impl BufRead) -> parser::Result<Beatmap> { Parser::new(reader).parse() }
pub fn into_string(self) -> String { format!( "osu file format v14\n\n{}\n{}\n{}\n{}\n{}\n[TimingPoints]\n{}\n\n{}\n[HitObjects]\n{}", self.general_info.into_string(), self.editor_info.into_string(), self.metadata.into_string(), self.difficulty.into_string(), self.events.into_string(), self.timing_points.into_iter().map(|p| p.into_string()).collect::<Vec<_>>().join("\n"), self.colors.map(|c| c.into_string()).unwrap_or(String::new()), self.hit_objects.into_iter().map(|p| p.into_string()).collect::<Vec<_>>().join("\n"), ) } } #[derive(Clone, Debug)] pub struct GeneralInfo { pub audio_file: String, pub preview_time: i32, rest: String, } impl GeneralInfo { fn into_string(self) -> String { format!("[General]\nAudioFilename: {}\nPreviewTime: {}\n{}", self.audio_file, self.preview_time, self.rest) } } #[derive(Clone, Debug)] pub struct EditorInfo(String); impl EditorInfo { fn into_string(self) -> String { format!("[Editor]\n{}", self.0) } } #[derive(Clone, Debug)] pub struct Metadata { pub diff_name: String, rest: String, } impl Metadata { fn into_string(self) -> String { format!("[Metadata]\nVersion:{}\n{}", self.diff_name, self.rest) } } #[derive(Clone, Debug)] pub struct DifficultyInfo(String); impl DifficultyInfo { fn into_string(self) -> String { format!("[Difficulty]\n{}", self.0) } } #[derive(Clone, Debug)] pub struct Events(String); impl Events { fn into_string(self) -> String { format!("[Events]\n{}", self.0) } } #[derive(Clone, Debug)] pub struct TimingPoint { pub time: f64, pub beat_len: f64, rest: String, } impl TimingPoint { fn into_string(self) -> String { format!("{},{},{}", self.time as i32, self.beat_len, self.rest) } } #[derive(Clone, Debug)] pub struct Colors(String); impl Colors { fn into_string(self) -> String { format!("[Colours]\n{}", self.0) } } #[derive(Clone, Debug)] pub struct HitObject { pub time: i32, pub params: HitObjectParams, rest_parts: Vec<String>, } impl HitObject { fn into_string(self) -> String { format!( "{},{},{}{}{}", self.rest_parts[0], self.time, self.rest_parts[1], self.params.into_string(), self.rest_parts[2], ) } } #[derive(Clone, Debug)] pub enum HitObjectParams { NoneUseful, Spinner(i32), LongNote(i32), } impl HitObjectParams { fn into_string(self) -> String { match self { HitObjectParams::NoneUseful | HitObjectParams::LongNote(_) => ",".to_string(), HitObjectParams::Spinner(end_time) => format!(",{},", end_time), } } }
pub fn change_rate(&mut self, rate: f64) -> bool { let transform_f64 = |n| n / rate + 75.; let transform = |n| transform_f64(n as f64) as i32; let preview = self.general_info.preview_time; self.general_info.preview_time = if preview >= 0 { transform(preview) } else { preview }; self.metadata.diff_name += &format!(" ({}x)", rate); for mut point in &mut self.timing_points { point.time = transform_f64(point.time); if point.beat_len.is_sign_positive() { point.beat_len /= rate; } } for mut object in &mut self.hit_objects { object.time = transform(object.time); match object.params { HitObjectParams::Spinner(end_time) => object.params = HitObjectParams::Spinner(transform(end_time)), HitObjectParams::LongNote(end_time) => { let rest = match object.rest_parts[2].split_once(':') { Some((_, rest)) => rest, _ => return false, }; object.rest_parts[2] = transform(end_time).to_string() + ":" + rest; } _ => {} } } true }
function_block-full_function
[ { "content": "// Stretches the audio associated with the given `map` by a factor of `rate`, updating metadata.\n\npub fn stretch_beatmap_audio(map: &mut Beatmap, dir: &Path, rate: f64) -> Result<()> {\n\n let old_path = dir.join(&map.general_info.audio_file);\n\n let old_audio = File::open(&old_path).or(E...
Rust
all-is-cubes/benches/space_bench.rs
kpreid/all-is-cubes
81e0fb8fbd5a0557f0f9002085f4160bce37174a
use criterion::{ black_box, criterion_group, criterion_main, BatchSize, BenchmarkId, Criterion, Throughput, }; use all_is_cubes::content::make_some_blocks; use all_is_cubes::space::{Grid, Space, SpaceTransaction}; use all_is_cubes::transaction::Transaction; pub fn space_bulk_mutation(c: &mut Criterion) { let mut group = c.benchmark_group("space-bulk-mutation"); for &mutation_size in &[1, 4, 64] { let grid = Grid::new([0, 0, 0], [mutation_size, mutation_size, mutation_size]); let bigger_grid = grid.multiply(2); let size_description = format!("{}×{}×{}", mutation_size, mutation_size, mutation_size); let mutation_volume = grid.volume(); group.throughput(Throughput::Elements(mutation_volume as u64)); group.bench_function( BenchmarkId::new("fill() entire space", &size_description), |b| { let [block] = make_some_blocks(); b.iter_batched( || Space::empty(grid), |mut space| { space.fill(space.grid(), |_| Some(&block)).unwrap(); }, BatchSize::SmallInput, ) }, ); group.bench_function( BenchmarkId::new("fill() part of space", &size_description), |b| { let [block] = make_some_blocks(); b.iter_batched( || Space::empty(bigger_grid), |mut space| { space.fill(grid, |_| Some(&block)).unwrap(); }, BatchSize::SmallInput, ) }, ); group.bench_function( BenchmarkId::new("fill_uniform() entire space", &size_description), |b| { let [block] = make_some_blocks(); b.iter_batched( || Space::empty(grid), |mut space| { space.fill_uniform(space.grid(), &block).unwrap(); }, BatchSize::SmallInput, ) }, ); group.bench_function( BenchmarkId::new("fill_uniform() part of space", &size_description), |b| { let [block] = make_some_blocks(); b.iter_batched( || Space::empty(bigger_grid), |mut space| { space.fill_uniform(grid, &block).unwrap(); }, BatchSize::SmallInput, ) }, ); group.bench_function( BenchmarkId::new("set() entire space", &size_description), |b| { let [block] = make_some_blocks(); b.iter_batched( || Space::empty(grid), |mut space| { for x in 0..mutation_size { for y in 0..mutation_size { for z in 0..mutation_size { space.set([x, y, z], &block).unwrap(); } } } }, BatchSize::SmallInput, ) }, ); group.bench_function( BenchmarkId::new("transaction entire space", &size_description), |b| { let [block] = make_some_blocks(); b.iter_batched( || Space::empty(grid), |mut space| { let mut txn = SpaceTransaction::default(); for x in 0..mutation_size { for y in 0..mutation_size { for z in 0..mutation_size { txn.set([x, y, z], None, Some(block.clone())).unwrap(); } } } txn.execute(&mut space).unwrap(); }, BatchSize::SmallInput, ) }, ); } group.finish(); } pub fn grid_bench(c: &mut Criterion) { let mut group = c.benchmark_group("Grid"); let grid = Grid::new([0, 0, 0], [256, 256, 256]); group.throughput(Throughput::Elements(grid.volume() as u64)); group.bench_function("Grid::interior_iter", |b| { b.iter(|| { for cube in grid.interior_iter() { black_box(cube); } }) }); group.finish(); } criterion_group!(benches, space_bulk_mutation, grid_bench); criterion_main!(benches);
use criterion::{ black_box, criterion_group, criterion_main, BatchSize, BenchmarkId, Criterion, Throughput, }; use all_is_cubes::content::make_some_blocks; use all_is_cubes::space::{Grid, Space, SpaceTransaction}; use all_is_cubes::transac
function( BenchmarkId::new("fill_uniform() entire space", &size_description), |b| { let [block] = make_some_blocks(); b.iter_batched( || Space::empty(grid), |mut space| { space.fill_uniform(space.grid(), &block).unwrap(); }, BatchSize::SmallInput, ) }, ); group.bench_function( BenchmarkId::new("fill_uniform() part of space", &size_description), |b| { let [block] = make_some_blocks(); b.iter_batched( || Space::empty(bigger_grid), |mut space| { space.fill_uniform(grid, &block).unwrap(); }, BatchSize::SmallInput, ) }, ); group.bench_function( BenchmarkId::new("set() entire space", &size_description), |b| { let [block] = make_some_blocks(); b.iter_batched( || Space::empty(grid), |mut space| { for x in 0..mutation_size { for y in 0..mutation_size { for z in 0..mutation_size { space.set([x, y, z], &block).unwrap(); } } } }, BatchSize::SmallInput, ) }, ); group.bench_function( BenchmarkId::new("transaction entire space", &size_description), |b| { let [block] = make_some_blocks(); b.iter_batched( || Space::empty(grid), |mut space| { let mut txn = SpaceTransaction::default(); for x in 0..mutation_size { for y in 0..mutation_size { for z in 0..mutation_size { txn.set([x, y, z], None, Some(block.clone())).unwrap(); } } } txn.execute(&mut space).unwrap(); }, BatchSize::SmallInput, ) }, ); } group.finish(); } pub fn grid_bench(c: &mut Criterion) { let mut group = c.benchmark_group("Grid"); let grid = Grid::new([0, 0, 0], [256, 256, 256]); group.throughput(Throughput::Elements(grid.volume() as u64)); group.bench_function("Grid::interior_iter", |b| { b.iter(|| { for cube in grid.interior_iter() { black_box(cube); } }) }); group.finish(); } criterion_group!(benches, space_bulk_mutation, grid_bench); criterion_main!(benches);
tion::Transaction; pub fn space_bulk_mutation(c: &mut Criterion) { let mut group = c.benchmark_group("space-bulk-mutation"); for &mutation_size in &[1, 4, 64] { let grid = Grid::new([0, 0, 0], [mutation_size, mutation_size, mutation_size]); let bigger_grid = grid.multiply(2); let size_description = format!("{}×{}×{}", mutation_size, mutation_size, mutation_size); let mutation_volume = grid.volume(); group.throughput(Throughput::Elements(mutation_volume as u64)); group.bench_function( BenchmarkId::new("fill() entire space", &size_description), |b| { let [block] = make_some_blocks(); b.iter_batched( || Space::empty(grid), |mut space| { space.fill(space.grid(), |_| Some(&block)).unwrap(); }, BatchSize::SmallInput, ) }, ); group.bench_function( BenchmarkId::new("fill() part of space", &size_description), |b| { let [block] = make_some_blocks(); b.iter_batched( || Space::empty(bigger_grid), |mut space| { space.fill(grid, |_| Some(&block)).unwrap(); }, BatchSize::SmallInput, ) }, ); group.bench_
random
[]
Rust
Katalon_OrangeHRMS/Object Repository/Header_Menu/Performance/a_Manage Reviews.rs
girishbhangale416/Katalon_Docker
a3f8ada90afac9e0b71454366ca93ff8a09dffe4
<?xml version="1.0" encoding="UTF-8"?> <WebElementEntity> <description></description> <name>a_Manage Reviews</name> <tag></tag> <elementGuidId>a9d86c40-dd16-4349-9cf7-4fb26ece97a5</elementGuidId> <selectorCollection> <entry> <key>XPATH</key> <value> </entry> </selectorCollection> <selectorMethod>XPATH</selectorMethod> <useRalativeImagePath>false</useRalativeImagePath> <webElementProperties> <isSelected>false</isSelected> <matchCondition>equals</matchCondition> <name>tag</name> <type>Main</type> <value>a</value> </webElementProperties> <webElementProperties> <isSelected>true</isSelected> <matchCondition>equals</matchCondition> <name>href</name> <type>Main</type> <value>#</value> </webElementProperties> <webElementProperties> <isSelected>true</isSelected> <matchCondition>equals</matchCondition> <name>id</name> <type>Main</type> <value>menu_performance_ManageReviews</value> </webElementProperties> <webElementProperties> <isSelected>false</isSelected> <matchCondition>equals</matchCondition> <name>class</name> <type>Main</type> <value>arrow</value> </webElementProperties> <webElementProperties> <isSelected>true</isSelected> <matchCondition>equals</matchCondition> <name>text</name> <type>Main</type> <value>Manage Reviews</value> </webElementProperties> <webElementProperties> <isSelected>false</isSelected> <matchCondition>equals</matchCondition> <name>xpath</name> <type>Main</type> <value>id(&quot;menu_performance_ManageReviews&quot;)</value> </webElementProperties> <webElementXpaths> <isSelected>true</isSelected> <matchCondition>equals</matchCondition> <name>xpath:attributes</name> <type>Main</type> <value> </webElementXpaths> <webElementXpaths> <isSelected>false</isSelected> <matchCondition>equals</matchCondition> <name>xpath:idRelative</name> <type>Main</type> <value> </webElementXpaths> <webElementXpaths> <isSelected>false</isSelected> <matchCondition>equals</matchCondition> <name>xpath:link</name> <type>Main</type> <value> </webElementXpaths> <webElementXpaths> <isSelected>false</isSelected> <matchCondition>equals</matchCondition> <name>xpath:neighbor</name> <type>Main</type> <value>(. </webElementXpaths> <webElementXpaths> <isSelected>false</isSelected> <matchCondition>equals</matchCondition> <name>xpath:neighbor</name> <type>Main</type> <value>(. </webElementXpaths> <webElementXpaths> <isSelected>false</isSelected> <matchCondition>equals</matchCondition> <name>xpath:neighbor</name> <type>Main</type> <value>(. </webElementXpaths> <webElementXpaths> <isSelected>false</isSelected> <matchCondition>equals</matchCondition> <name>xpath:neighbor</name> <type>Main</type> <value>(. </webElementXpaths> <webElementXpaths> <isSelected>false</isSelected> <matchCondition>equals</matchCondition> <name>xpath:href</name> <type>Main</type> <value>( </webElementXpaths> <webElementXpaths> <isSelected>false</isSelected> <matchCondition>equals</matchCondition> <name>xpath:position</name> <type>Main</type> <value> </webElementXpaths> </WebElementEntity>
<?xml version="1.0" encoding="UTF-8"?> <WebElementEntity> <description></description> <name>a_Manage Reviews</name> <tag></tag> <elementGuidId>a9d86c40-dd16-4349-9cf7-4fb26ece97a5</elementGuidId> <selectorCollection> <entry> <key>XPATH</key> <value> </entry> </selectorCollection> <selectorMethod>XPATH</selectorMethod> <useRalativeImagePath>false</useRalativeImagePath> <webElementProperties> <isSelected>false</isSelected> <matchCondition>equals</matchCondition> <name
ondition>equals</matchCondition> <name>xpath:neighbor</name> <type>Main</type> <value>(. </webElementXpaths> <webElementXpaths> <isSelected>false</isSelected> <matchCondition>equals</matchCondition> <name>xpath:href</name> <type>Main</type> <value>( </webElementXpaths> <webElementXpaths> <isSelected>false</isSelected> <matchCondition>equals</matchCondition> <name>xpath:position</name> <type>Main</type> <value> </webElementXpaths> </WebElementEntity>
>tag</name> <type>Main</type> <value>a</value> </webElementProperties> <webElementProperties> <isSelected>true</isSelected> <matchCondition>equals</matchCondition> <name>href</name> <type>Main</type> <value>#</value> </webElementProperties> <webElementProperties> <isSelected>true</isSelected> <matchCondition>equals</matchCondition> <name>id</name> <type>Main</type> <value>menu_performance_ManageReviews</value> </webElementProperties> <webElementProperties> <isSelected>false</isSelected> <matchCondition>equals</matchCondition> <name>class</name> <type>Main</type> <value>arrow</value> </webElementProperties> <webElementProperties> <isSelected>true</isSelected> <matchCondition>equals</matchCondition> <name>text</name> <type>Main</type> <value>Manage Reviews</value> </webElementProperties> <webElementProperties> <isSelected>false</isSelected> <matchCondition>equals</matchCondition> <name>xpath</name> <type>Main</type> <value>id(&quot;menu_performance_ManageReviews&quot;)</value> </webElementProperties> <webElementXpaths> <isSelected>true</isSelected> <matchCondition>equals</matchCondition> <name>xpath:attributes</name> <type>Main</type> <value> </webElementXpaths> <webElementXpaths> <isSelected>false</isSelected> <matchCondition>equals</matchCondition> <name>xpath:idRelative</name> <type>Main</type> <value> </webElementXpaths> <webElementXpaths> <isSelected>false</isSelected> <matchCondition>equals</matchCondition> <name>xpath:link</name> <type>Main</type> <value> </webElementXpaths> <webElementXpaths> <isSelected>false</isSelected> <matchCondition>equals</matchCondition> <name>xpath:neighbor</name> <type>Main</type> <value>(. </webElementXpaths> <webElementXpaths> <isSelected>false</isSelected> <matchCondition>equals</matchCondition> <name>xpath:neighbor</name> <type>Main</type> <value>(. </webElementXpaths> <webElementXpaths> <isSelected>false</isSelected> <matchCondition>equals</matchCondition> <name>xpath:neighbor</name> <type>Main</type> <value>(. </webElementXpaths> <webElementXpaths> <isSelected>false</isSelected> <matchC
random
[ { "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\n<WebElementEntity>\n\n <description></description>\n\n <name>input_Middle Name_middleName</name>\n\n <tag></tag>\n\n <elementGuidId>a02d298f-e2ee-48f3-8efe-dc1f9953b202</elementGuidId>\n\n <selectorCollection>\n\n <entry>\n\n <ke...
Rust
unsafe_collection/src/bytes/uninit.rs
HFQR/xitca-web
ee2d4fa9e88b2be149c9ca3454bc14d90f8f9ca2
use std::{io::IoSlice, mem::MaybeUninit}; use bytes_crate::{buf::Chain, Buf, Bytes}; use crate::uninit; use super::buf_list::{BufList, EitherBuf}; mod sealed { pub trait Sealed {} } pub trait ChunkVectoredUninit: sealed::Sealed { unsafe fn chunks_vectored_uninit<'a>(&'a self, dst: &mut [MaybeUninit<IoSlice<'a>>]) -> usize; } impl<T, U> sealed::Sealed for Chain<T, U> where T: sealed::Sealed, U: sealed::Sealed, { } impl<T, U> ChunkVectoredUninit for Chain<T, U> where T: ChunkVectoredUninit, U: ChunkVectoredUninit, { unsafe fn chunks_vectored_uninit<'a>(&'a self, dst: &mut [MaybeUninit<IoSlice<'a>>]) -> usize { let mut n = self.first_ref().chunks_vectored_uninit(dst); n += self.last_ref().chunks_vectored_uninit(&mut dst[n..]); n } } impl<B, const LEN: usize> sealed::Sealed for BufList<B, LEN> where B: ChunkVectoredUninit {} impl<B: ChunkVectoredUninit, const LEN: usize> ChunkVectoredUninit for BufList<B, LEN> { #[inline] unsafe fn chunks_vectored_uninit<'a>(&'a self, dst: &mut [MaybeUninit<IoSlice<'a>>]) -> usize { assert!(!dst.is_empty()); let mut vecs = 0; for buf in self.bufs.iter() { vecs += buf.chunks_vectored_uninit(&mut dst[vecs..]); if vecs == dst.len() { break; } } vecs } } impl<B: ChunkVectoredUninit, const LEN: usize> BufList<B, LEN> { pub fn chunks_vectored_uninit_into_init<'a, 's>( &'a self, dst: &'s mut [MaybeUninit<IoSlice<'a>>], ) -> &'s mut [IoSlice<'a>] { unsafe { let len = self.chunks_vectored_uninit(dst); uninit::slice_assume_init_mut(&mut dst[..len]) } } } impl<L, R> sealed::Sealed for EitherBuf<L, R> where L: ChunkVectoredUninit, R: ChunkVectoredUninit, { } impl<L, R> ChunkVectoredUninit for EitherBuf<L, R> where L: ChunkVectoredUninit, R: ChunkVectoredUninit, { unsafe fn chunks_vectored_uninit<'a>(&'a self, dst: &mut [MaybeUninit<IoSlice<'a>>]) -> usize { match *self { Self::Left(ref buf) => buf.chunks_vectored_uninit(dst), Self::Right(ref buf) => buf.chunks_vectored_uninit(dst), } } } impl sealed::Sealed for Bytes {} impl ChunkVectoredUninit for Bytes { unsafe fn chunks_vectored_uninit<'a>(&'a self, dst: &mut [MaybeUninit<IoSlice<'a>>]) -> usize { if dst.is_empty() { return 0; } if self.has_remaining() { dst[0].write(IoSlice::new(self.chunk())); 1 } else { 0 } } } impl sealed::Sealed for &'_ [u8] {} impl ChunkVectoredUninit for &'_ [u8] { unsafe fn chunks_vectored_uninit<'a>(&'a self, dst: &mut [MaybeUninit<IoSlice<'a>>]) -> usize { if dst.is_empty() { return 0; } if self.has_remaining() { dst[0].write(IoSlice::new(self)); 1 } else { 0 } } } #[cfg(test)] mod test { use super::*; use crate::uninit::uninit_array; #[test] fn either_buf() { let mut lst = BufList::<_, 2>::new(); let mut buf = uninit_array::<_, 4>(); lst.push(EitherBuf::Left(&b"left"[..])); lst.push(EitherBuf::Right(&b"right"[..])); let slice = lst.chunks_vectored_uninit_into_init(&mut buf); assert_eq!(slice.len(), 2); assert_eq!(slice[0].as_ref(), b"left"); assert_eq!(slice[1].as_ref(), b"right"); } #[test] fn either_chain() { let mut lst = BufList::<_, 3>::new(); let mut buf = uninit_array::<_, 5>(); lst.push(EitherBuf::Left((&b"1"[..]).chain(&b"2"[..]))); lst.push(EitherBuf::Right(&b"3"[..])); let slice = lst.chunks_vectored_uninit_into_init(&mut buf); assert_eq!(slice.len(), 3); assert_eq!(slice[0].as_ref(), b"1"); assert_eq!(slice[1].as_ref(), b"2"); assert_eq!(slice[2].as_ref(), b"3"); } }
use std::{io::IoSlice, mem::MaybeUninit}; use bytes_crate::{buf::Chain, Buf, Bytes}; use crate::uninit; use super::buf_list::{BufList, EitherBuf}; mod sealed { pub trait Sealed {} } pub trait ChunkVectoredUninit: sealed::Sealed { unsafe fn chunks_vectored_uninit<'a>(&'a self, dst: &mut [MaybeUninit<IoSlice<'a>>]) -> usize; } impl<T, U> sealed::Sealed for Chain<T, U> where T: sealed::Sealed, U: sealed::Sealed, { } impl<T, U> ChunkVectoredUninit for Chain<T, U> where T: ChunkVectoredUninit, U: ChunkVectoredUninit, { unsafe fn chunks_vectored_uninit<'a>(&'a self, dst: &mut [MaybeUninit<IoSlice<'a>>]) -> usize { let mut n = self.first_ref().chunks_vectored_uninit(dst); n += self.last_ref().chunks_vectored_uninit(&mut dst[n..]); n } } impl<B, const LEN: usize> sealed::Sealed for BufList<B, LEN> where B: ChunkVectoredUninit {} impl<B: ChunkVectoredUninit, const LEN: usize> ChunkVectoredUninit for BufList<B, LEN> { #[inline] unsafe fn chunks_vectored_uninit<'a>(&'a self, dst: &mut [MaybeUninit<IoSlice<'a>>]) -> usize { assert!(!dst.is_empty()); let mut vecs = 0; for buf in self.bufs.iter() { vecs += buf.chunks_vectored_uninit(&mut dst[vecs..]); if vecs == dst.len() { break; } } vecs } } impl<B: ChunkVectoredUninit, const LEN: usize> BufList<B, LEN> { pub fn chunks_vectored_uninit_into_init<'a, 's>( &'a sel
} impl<L, R> sealed::Sealed for EitherBuf<L, R> where L: ChunkVectoredUninit, R: ChunkVectoredUninit, { } impl<L, R> ChunkVectoredUninit for EitherBuf<L, R> where L: ChunkVectoredUninit, R: ChunkVectoredUninit, { unsafe fn chunks_vectored_uninit<'a>(&'a self, dst: &mut [MaybeUninit<IoSlice<'a>>]) -> usize { match *self { Self::Left(ref buf) => buf.chunks_vectored_uninit(dst), Self::Right(ref buf) => buf.chunks_vectored_uninit(dst), } } } impl sealed::Sealed for Bytes {} impl ChunkVectoredUninit for Bytes { unsafe fn chunks_vectored_uninit<'a>(&'a self, dst: &mut [MaybeUninit<IoSlice<'a>>]) -> usize { if dst.is_empty() { return 0; } if self.has_remaining() { dst[0].write(IoSlice::new(self.chunk())); 1 } else { 0 } } } impl sealed::Sealed for &'_ [u8] {} impl ChunkVectoredUninit for &'_ [u8] { unsafe fn chunks_vectored_uninit<'a>(&'a self, dst: &mut [MaybeUninit<IoSlice<'a>>]) -> usize { if dst.is_empty() { return 0; } if self.has_remaining() { dst[0].write(IoSlice::new(self)); 1 } else { 0 } } } #[cfg(test)] mod test { use super::*; use crate::uninit::uninit_array; #[test] fn either_buf() { let mut lst = BufList::<_, 2>::new(); let mut buf = uninit_array::<_, 4>(); lst.push(EitherBuf::Left(&b"left"[..])); lst.push(EitherBuf::Right(&b"right"[..])); let slice = lst.chunks_vectored_uninit_into_init(&mut buf); assert_eq!(slice.len(), 2); assert_eq!(slice[0].as_ref(), b"left"); assert_eq!(slice[1].as_ref(), b"right"); } #[test] fn either_chain() { let mut lst = BufList::<_, 3>::new(); let mut buf = uninit_array::<_, 5>(); lst.push(EitherBuf::Left((&b"1"[..]).chain(&b"2"[..]))); lst.push(EitherBuf::Right(&b"3"[..])); let slice = lst.chunks_vectored_uninit_into_init(&mut buf); assert_eq!(slice.len(), 3); assert_eq!(slice[0].as_ref(), b"1"); assert_eq!(slice[1].as_ref(), b"2"); assert_eq!(slice[2].as_ref(), b"3"); } }
f, dst: &'s mut [MaybeUninit<IoSlice<'a>>], ) -> &'s mut [IoSlice<'a>] { unsafe { let len = self.chunks_vectored_uninit(dst); uninit::slice_assume_init_mut(&mut dst[..len]) } }
function_block-function_prefixed
[ { "content": " pub trait Sealed {}\n\n}\n\n\n\nimpl<T> sealed::Sealed for &mut [MaybeUninit<T>] {}\n\n\n", "file_path": "unsafe_collection/src/uninit.rs", "rank": 2, "score": 266279.3679360628 }, { "content": "/// Trait for safely initialize an unit slice.\n\npub trait PartialInit: sealed...
Rust
mayastor/tests/reconfigure.rs
gahag/MayaStor
0a2f01b04d75203e5ec19b3037703ee8967ec9e7
#![feature(async_await)] #![allow(clippy::cognitive_complexity)] use mayastor::{ bdev::{ nexus::nexus_bdev::{nexus_create, nexus_lookup}, Bdev, }, descriptor::Descriptor, mayastor_start, spdk_stop, }; use std::process::Command; static DISKNAME1: &str = "/tmp/disk1.img"; static BDEVNAME1: &str = "aio:///tmp/disk1.img?blk_size=512"; static DISKNAME2: &str = "/tmp/disk2.img"; static BDEVNAME2: &str = "aio:///tmp/disk2.img?blk_size=512"; #[test] fn reconfigure() { let log = mayastor::spdklog::SpdkLog::new(); let _ = log.init(); mayastor::CPS_INIT!(); let args = vec!["-c", "../etc/test.conf"]; let output = Command::new("truncate") .args(&["-s", "64m", DISKNAME1]) .output() .expect("failed exec truncate"); assert_eq!(output.status.success(), true); let output = Command::new("truncate") .args(&["-s", "64m", DISKNAME2]) .output() .expect("failed exec truncate"); assert_eq!(output.status.success(), true); let rc = mayastor_start("test", args, || { mayastor::executor::spawn(works()); }); assert_eq!(rc, 0); let output = Command::new("rm") .args(&["-rf", DISKNAME1, DISKNAME2]) .output() .expect("failed delete test file"); assert_eq!(output.status.success(), true); } fn buf_compare(first: &[u8], second: &[u8]) { for i in 0 .. first.len() { assert_eq!(first[i], second[i]); } } async fn stats_compare(first: &Bdev, second: &Bdev) { let stats1 = first.stats().await.unwrap(); let stats2 = second.stats().await.unwrap(); assert_eq!(stats1.num_write_ops, stats2.num_write_ops); } async fn works() { let child1 = BDEVNAME1.to_string(); let child2 = BDEVNAME2.to_string(); let children = vec![child1.clone(), child2.clone()]; nexus_create("hello", 512, 131_072, None, &children) .await .unwrap(); let nexus = nexus_lookup("hello").unwrap(); let nd = Descriptor::open("hello", true).expect("failed open bdev"); let cd1 = Descriptor::open(&child1, false).expect("failed open bdev"); let cd2 = Descriptor::open(&child2, false).expect("failed open bdev"); let bdev1 = cd1.get_bdev(); let bdev2 = cd2.get_bdev(); let mut buf = nd.dma_zmalloc(4096).expect("failed to allocate buffer"); buf.fill(0xff); let mut buf1 = cd1.dma_zmalloc(4096).unwrap(); let mut buf2 = cd2.dma_zmalloc(4096).unwrap(); for i in 0 .. 10 { nd.write_at(i * 4096, &buf).await.unwrap(); } stats_compare(&bdev1, &bdev2).await; for i in 0 .. 10 { cd1.read_at((i * 4096) + (10240 * 512), &mut buf1) .await .unwrap(); cd2.read_at((i * 4096) + (10240 * 512), &mut buf2) .await .unwrap(); buf_compare(buf1.as_slice(), buf2.as_slice()); } buf.fill(0xF0); nexus.offline_child(&child2).await.unwrap(); for i in 0 .. 10 { nd.write_at(i * 4096, &buf).await.unwrap(); } for i in 0 .. 10 { buf1.fill(0x0); buf2.fill(0x0); cd1.read_at((i * 4096) + (10240 * 512), &mut buf1) .await .unwrap(); cd2.read_at((i * 4096) + (10240 * 512), &mut buf2) .await .unwrap(); buf1.as_slice() .iter() .map(|b| assert_eq!(*b, 0xf0)) .for_each(drop); buf2.as_slice() .iter() .map(|b| assert_eq!(*b, 0xff)) .for_each(drop); } nexus.online_child(&child2).await.unwrap(); buf.fill(0xAA); for i in 0 .. 10 { nd.write_at(i * 4096, &buf).await.unwrap(); } for i in 0 .. 10 { buf1.fill(0x0); buf2.fill(0x0); cd1.read_at((i * 4096) + (10240 * 512), &mut buf1) .await .unwrap(); cd2.read_at((i * 4096) + (10240 * 512), &mut buf2) .await .unwrap(); buf1.as_slice() .iter() .map(|b| assert_eq!(*b, 0xAA)) .for_each(drop); buf2.as_slice() .iter() .map(|b| assert_eq!(*b, 0xAA)) .for_each(drop); } cd1.close(); cd2.close(); nd.close(); spdk_stop(0); }
#![feature(async_await)] #![allow(clippy::cognitive_complexity)] use mayastor::{ bdev::{ nexus::nexus_bdev::{nexus_create, nexus_lookup}, Bdev, }, descriptor::Descriptor, mayastor_start, spdk_stop, }; use std::process::Command; static DISKNAME1: &str = "/tmp/disk1.img"; static BDEVNAME1: &str = "aio:///tmp/disk1.img?blk_size=512"; static DISKNAME2: &str = "/tmp/disk2.img"; static BDEVNAME2: &str = "aio:///tmp/disk2.img?blk_size=512"; #[test] fn reconfigure() { let log = mayastor::spdklog::SpdkLog::new(); let _ = log.init(); mayastor::CPS_INIT!(); let args = vec!["-c", "../etc/test.conf"]; let output = Command::new("truncate") .args(&["-s", "64m", DISKNAME1]) .output() .expect("failed exec truncate"); assert_eq!(output.status.success(), true); let output = Command::new("truncate") .args(&["-s", "64m", DISKNAME2]) .output() .expect("failed exec truncate"); assert_eq!(output.status.success(), true); let rc = mayastor_start("test", args, || { mayastor::executor::spawn(works()); }); ass
let stats1 = first.stats().await.unwrap(); let stats2 = second.stats().await.unwrap(); assert_eq!(stats1.num_write_ops, stats2.num_write_ops); } async fn works() { let child1 = BDEVNAME1.to_string(); let child2 = BDEVNAME2.to_string(); let children = vec![child1.clone(), child2.clone()]; nexus_create("hello", 512, 131_072, None, &children) .await .unwrap(); let nexus = nexus_lookup("hello").unwrap(); let nd = Descriptor::open("hello", true).expect("failed open bdev"); let cd1 = Descriptor::open(&child1, false).expect("failed open bdev"); let cd2 = Descriptor::open(&child2, false).expect("failed open bdev"); let bdev1 = cd1.get_bdev(); let bdev2 = cd2.get_bdev(); let mut buf = nd.dma_zmalloc(4096).expect("failed to allocate buffer"); buf.fill(0xff); let mut buf1 = cd1.dma_zmalloc(4096).unwrap(); let mut buf2 = cd2.dma_zmalloc(4096).unwrap(); for i in 0 .. 10 { nd.write_at(i * 4096, &buf).await.unwrap(); } stats_compare(&bdev1, &bdev2).await; for i in 0 .. 10 { cd1.read_at((i * 4096) + (10240 * 512), &mut buf1) .await .unwrap(); cd2.read_at((i * 4096) + (10240 * 512), &mut buf2) .await .unwrap(); buf_compare(buf1.as_slice(), buf2.as_slice()); } buf.fill(0xF0); nexus.offline_child(&child2).await.unwrap(); for i in 0 .. 10 { nd.write_at(i * 4096, &buf).await.unwrap(); } for i in 0 .. 10 { buf1.fill(0x0); buf2.fill(0x0); cd1.read_at((i * 4096) + (10240 * 512), &mut buf1) .await .unwrap(); cd2.read_at((i * 4096) + (10240 * 512), &mut buf2) .await .unwrap(); buf1.as_slice() .iter() .map(|b| assert_eq!(*b, 0xf0)) .for_each(drop); buf2.as_slice() .iter() .map(|b| assert_eq!(*b, 0xff)) .for_each(drop); } nexus.online_child(&child2).await.unwrap(); buf.fill(0xAA); for i in 0 .. 10 { nd.write_at(i * 4096, &buf).await.unwrap(); } for i in 0 .. 10 { buf1.fill(0x0); buf2.fill(0x0); cd1.read_at((i * 4096) + (10240 * 512), &mut buf1) .await .unwrap(); cd2.read_at((i * 4096) + (10240 * 512), &mut buf2) .await .unwrap(); buf1.as_slice() .iter() .map(|b| assert_eq!(*b, 0xAA)) .for_each(drop); buf2.as_slice() .iter() .map(|b| assert_eq!(*b, 0xAA)) .for_each(drop); } cd1.close(); cd2.close(); nd.close(); spdk_stop(0); }
ert_eq!(rc, 0); let output = Command::new("rm") .args(&["-rf", DISKNAME1, DISKNAME2]) .output() .expect("failed delete test file"); assert_eq!(output.status.success(), true); } fn buf_compare(first: &[u8], second: &[u8]) { for i in 0 .. first.len() { assert_eq!(first[i], second[i]); } } async fn stats_compare(first: &Bdev, second: &Bdev) {
random
[ { "content": "/// lookup a bdev by its name or one of its alias\n\npub fn bdev_lookup_by_name(name: &str) -> Option<Bdev> {\n\n let name = std::ffi::CString::new(name.to_string()).unwrap();\n\n unsafe {\n\n let b = spdk_sys::spdk_bdev_get_by_name(name.as_ptr());\n\n if b.is_null() {\n\n ...
Rust
src/main.rs
falzberger/ddlog_bench
261fc5598353c648708088eb3b36d1e2082fd869
use clap::{App, Arg, ArgMatches}; use csv::{ReaderBuilder, StringRecord}; use ordered_float::OrderedFloat; use std::fs::File; use std::io::prelude::*; use query_ddlog::api::HDDlog; use query_ddlog::relid2name; use query_ddlog::typedefs::*; use query_ddlog::Relations; use differential_datalog::ddval::{DDValConvert, DDValue}; use differential_datalog::program::RelId; use differential_datalog::program::Update; use differential_datalog::DeltaMap; use differential_datalog::{DDlog, DDlogDynamic}; fn relation_str_to_enum(relation: &str) -> Relations { match relation { "edge" | "Edge" => Relations::Edge, _ => panic!("Unknown input relation: {}", relation), } } fn parse_tuple_for_relation(tuple: StringRecord, offset: usize, relation: Relations) -> DDValue { match relation { Relations::Edge => Edge { parent: tuple[offset + 0].to_string(), child: tuple[offset + 1].to_string(), weight: OrderedFloat::from(tuple[offset + 2].parse::<f32>().unwrap()), } .into_ddvalue(), _ => panic!("Unsupported input relation: {:?}", relation), } } fn get_cli_arg_matches<'a>() -> ArgMatches<'a> { App::new("DDlog Benchmark CLI") .arg( Arg::with_name("input") .short("i") .help("Specifies a CSV input file for a relation. We expect CSVs to have headers.") .takes_value(true) .number_of_values(2) .value_names(&["relation", "csv"]) .multiple(true) .required(true), ) .arg( Arg::with_name("updates") .short("u") .help("Specifies a CSV file for updates to the computation. We expect CSVs to have headers.\ The first column of the CSV should be either -1 or 1, indicating whether to add or remove a tuple.\ The second column must be the name of the relation, followed by the relation attributes.") .takes_value(true) .value_names(&["csv"]) .multiple(true) .required(false), ) .get_matches() } fn main() -> Result<(), String> { let matches = get_cli_arg_matches(); println!("Instantiating DDlog program..."); let start = std::time::Instant::now(); let (hddlog, init_state) = HDDlog::run(1, false)?; println!( "Instantiating program took {} µs", start.elapsed().as_micros() ); dump_delta(&init_state); let initial_start = std::time::Instant::now(); println!("Adding inputs to the dataflow with multiple transactions"); let inputs: Vec<_> = matches.values_of("input").unwrap().collect(); for i in (0..inputs.len()).step_by(2) { let (input_relation, csv_file) = (relation_str_to_enum(inputs[i]), inputs[i + 1]); let file = File::open(csv_file).expect(&*format!("Could not open file {}", csv_file)); let mut rdr = ReaderBuilder::new().has_headers(true).from_reader(file); let max_batch_size = 1000; let mut batch = Vec::with_capacity(max_batch_size); start_transaction(&hddlog); for tuple in rdr.records().flatten() { batch.push(Update::Insert { relid: input_relation as RelId, v: parse_tuple_for_relation(tuple, 0, input_relation), }); if batch.len() >= max_batch_size { hddlog.apply_updates(&mut batch.drain(..).into_iter())?; } } hddlog.apply_updates(&mut batch.into_iter())?; commit_transaction(&hddlog); } println!( "Initial computation took {} µs to complete", initial_start.elapsed().as_micros() ); let updates: Vec<_> = matches .values_of("updates") .map_or_else(Vec::new, |values| values.collect()); for file_name in updates { let start = std::time::Instant::now(); println!("Adding updates from file {} to the dataflow", file_name); let file = File::open(file_name).expect(&*format!("Could not open file {}", file_name)); let mut rdr = ReaderBuilder::new().has_headers(true).from_reader(file); start_transaction(&hddlog); let mut updates = vec![]; for tuple in rdr.records().flatten() { let add_or_remove = tuple.get(0).expect("Empty rows are not valid"); let relation = relation_str_to_enum(tuple.get(1).expect("Each row must contain a relation")); if add_or_remove == "1" { updates.push(Update::Insert { relid: relation as RelId, v: parse_tuple_for_relation(tuple, 2, relation), }); } else if add_or_remove == "-1" { updates.push(Update::DeleteValue { relid: relation as RelId, v: parse_tuple_for_relation(tuple, 2, relation), }); } else { panic!( "First column must either be 1 or -1 but was: {:?}", add_or_remove ) } } hddlog.apply_updates(&mut updates.into_iter())?; println!( "Finished adding updates after {} µs.", start.elapsed().as_micros() ); commit_transaction(&hddlog); } hddlog.stop().unwrap(); Ok(()) } fn start_transaction(hddlog: &HDDlog) { println!("Starting transaction..."); hddlog.transaction_start().unwrap(); } fn commit_transaction(hddlog: &HDDlog) { let start = std::time::Instant::now(); let delta = hddlog.transaction_commit_dump_changes().unwrap(); println!( "Committing transaction took {} µs", start.elapsed().as_micros() ); dump_delta(&delta); } fn dump_delta(delta: &DeltaMap<DDValue>) { for (rel, changes) in delta.iter() { let mut file = std::fs::OpenOptions::new() .append(true) .create(true) .open(format!("{}.out", relid2name(*rel).unwrap())) .expect(&*format!( "Could not open file for writing exported relation: {:?}.out", relid2name(*rel) )); for (val, weight) in changes.iter() { let _ = writeln!(file, "{:+}, ({})", weight, val); } } }
use clap::{App, Arg, ArgMatches}; use csv::{ReaderBuilder, StringRecord}; use ordered_float::OrderedFloat; use std::fs::File; use std::io::prelude::*; use query_ddlog::api::HDDlog; use query_ddlog::relid2name; use query_ddlog::typedefs::*; use query_ddlog::Relations; use differential_datalog::ddval::{DDValConvert, DDValue}; use differential_datalog::program::RelId; use differential_datalog::program::Update; use differential_datalog::DeltaMap; use differential_datalog::{DDlog, DDlogDynamic}; fn relation_str_to_enum(relation: &str) -> Relations { match relation { "edge" | "Edge" => Relations::Edge, _ => panic!("Unknown input relation: {}", relation), } } fn parse_tuple_for_relation(tuple: StringRecord, offset: usize, relation: Relations) -> DDValue { match relation { Relations::Edge => Edge { parent: tuple[offset + 0].to_string(), child: tuple[offset + 1].to_string(), weight: OrderedFloat::from(tuple[offset + 2].parse::<f32>().unwrap()), } .into_ddvalue(), _ => panic!("Unsupported input relation: {:?}", relation), } }
fn main() -> Result<(), String> { let matches = get_cli_arg_matches(); println!("Instantiating DDlog program..."); let start = std::time::Instant::now(); let (hddlog, init_state) = HDDlog::run(1, false)?; println!( "Instantiating program took {} µs", start.elapsed().as_micros() ); dump_delta(&init_state); let initial_start = std::time::Instant::now(); println!("Adding inputs to the dataflow with multiple transactions"); let inputs: Vec<_> = matches.values_of("input").unwrap().collect(); for i in (0..inputs.len()).step_by(2) { let (input_relation, csv_file) = (relation_str_to_enum(inputs[i]), inputs[i + 1]); let file = File::open(csv_file).expect(&*format!("Could not open file {}", csv_file)); let mut rdr = ReaderBuilder::new().has_headers(true).from_reader(file); let max_batch_size = 1000; let mut batch = Vec::with_capacity(max_batch_size); start_transaction(&hddlog); for tuple in rdr.records().flatten() { batch.push(Update::Insert { relid: input_relation as RelId, v: parse_tuple_for_relation(tuple, 0, input_relation), }); if batch.len() >= max_batch_size { hddlog.apply_updates(&mut batch.drain(..).into_iter())?; } } hddlog.apply_updates(&mut batch.into_iter())?; commit_transaction(&hddlog); } println!( "Initial computation took {} µs to complete", initial_start.elapsed().as_micros() ); let updates: Vec<_> = matches .values_of("updates") .map_or_else(Vec::new, |values| values.collect()); for file_name in updates { let start = std::time::Instant::now(); println!("Adding updates from file {} to the dataflow", file_name); let file = File::open(file_name).expect(&*format!("Could not open file {}", file_name)); let mut rdr = ReaderBuilder::new().has_headers(true).from_reader(file); start_transaction(&hddlog); let mut updates = vec![]; for tuple in rdr.records().flatten() { let add_or_remove = tuple.get(0).expect("Empty rows are not valid"); let relation = relation_str_to_enum(tuple.get(1).expect("Each row must contain a relation")); if add_or_remove == "1" { updates.push(Update::Insert { relid: relation as RelId, v: parse_tuple_for_relation(tuple, 2, relation), }); } else if add_or_remove == "-1" { updates.push(Update::DeleteValue { relid: relation as RelId, v: parse_tuple_for_relation(tuple, 2, relation), }); } else { panic!( "First column must either be 1 or -1 but was: {:?}", add_or_remove ) } } hddlog.apply_updates(&mut updates.into_iter())?; println!( "Finished adding updates after {} µs.", start.elapsed().as_micros() ); commit_transaction(&hddlog); } hddlog.stop().unwrap(); Ok(()) } fn start_transaction(hddlog: &HDDlog) { println!("Starting transaction..."); hddlog.transaction_start().unwrap(); } fn commit_transaction(hddlog: &HDDlog) { let start = std::time::Instant::now(); let delta = hddlog.transaction_commit_dump_changes().unwrap(); println!( "Committing transaction took {} µs", start.elapsed().as_micros() ); dump_delta(&delta); } fn dump_delta(delta: &DeltaMap<DDValue>) { for (rel, changes) in delta.iter() { let mut file = std::fs::OpenOptions::new() .append(true) .create(true) .open(format!("{}.out", relid2name(*rel).unwrap())) .expect(&*format!( "Could not open file for writing exported relation: {:?}.out", relid2name(*rel) )); for (val, weight) in changes.iter() { let _ = writeln!(file, "{:+}, ({})", weight, val); } } }
fn get_cli_arg_matches<'a>() -> ArgMatches<'a> { App::new("DDlog Benchmark CLI") .arg( Arg::with_name("input") .short("i") .help("Specifies a CSV input file for a relation. We expect CSVs to have headers.") .takes_value(true) .number_of_values(2) .value_names(&["relation", "csv"]) .multiple(true) .required(true), ) .arg( Arg::with_name("updates") .short("u") .help("Specifies a CSV file for updates to the computation. We expect CSVs to have headers.\ The first column of the CSV should be either -1 or 1, indicating whether to add or remove a tuple.\ The second column must be the name of the relation, followed by the relation attributes.") .takes_value(true) .value_names(&["csv"]) .multiple(true) .required(false), ) .get_matches() }
function_block-full_function
[ { "content": "def to_entity_str(entity_id: int):\n", "file_path": "generator.py", "rank": 7, "score": 12004.358802751458 }, { "content": "# Differential Datalog Benchmarks\n\n\n\nThis repository contains some simple benchmarks based on artificially generated datasets for\n\nthe [Differential...
Rust
src/main.rs
caperaven/svg-to-js
07a2f5962d878d183c4aac2fd5e75f91e78982cc
mod path_to_path; extern crate lyon; extern crate glob; use std::env; use glob::glob; use std::fs; use lyon::tessellation::{FillOptions, FillTessellator, StrokeTessellator, StrokeOptions}; use lyon::path::math::{Point}; use lyon::path::Path; use lyon::tessellation::geometry_builder::{VertexBuffers, simple_builder}; type PolyBuffer = VertexBuffers<Point, u16>; fn ensure_result_folder(folder: &str) { fs::create_dir_all(folder).ok(); } fn get_svg_in_folder() -> (glob::Paths, String) { let executable = env::current_exe().unwrap(); let path = match executable.parent() { Some(name) => name, _ => panic!() }; let folder = path.display(); let folder_str = format!("{}", folder); let target_folder = format!("{}/result", folder); ensure_result_folder(&target_folder); let glob_query = format!("{}/*.svg", folder_str); let glob_query_str = glob_query.as_str(); return (glob(glob_query_str).expect("Failed to read glob pattern"), target_folder); } fn process_file(filename: &str) -> (PolyBuffer, PolyBuffer) { let opt = usvg::Options::default(); let file_data = std::fs::read(filename).unwrap(); let rtree = usvg::Tree::from_data(&file_data, &opt.to_ref()).unwrap(); let mut fill_builder = lyon::path::Path::builder(); let mut stroke_builder = lyon::path::Path::builder(); for node in rtree.root().descendants() { if let usvg::NodeKind::Path(ref p) = *node.borrow() { if let Some(_) = p.fill { path_to_path::to_path(&p.data, &mut fill_builder); } if let Some(_) = p.stroke { path_to_path::to_path(&p.data, &mut stroke_builder); } } } let fill_buffer = create_fill(&fill_builder.build()); let stroke_buffer = create_stroke(&stroke_builder.build(), 5.0); return (fill_buffer, stroke_buffer); } pub fn create_fill(path: &Path) -> PolyBuffer { let mut buffer: PolyBuffer = VertexBuffers::new(); { let mut vertex_builder = simple_builder(&mut buffer); let mut tessellator = FillTessellator::new(); tessellator .tessellate_path(path, &FillOptions::default(), &mut vertex_builder) .ok(); } return buffer; } pub fn create_stroke(path: &Path, line_width: f32) -> PolyBuffer { let mut buffer: PolyBuffer = VertexBuffers::new(); { let mut vertex_builder = simple_builder(&mut buffer); let mut tessellator = StrokeTessellator::new(); let options = StrokeOptions::default().with_tolerance(0.01).with_line_width(line_width); tessellator.tessellate_path ( path, &options, &mut vertex_builder ).ok(); } return buffer; } pub fn save_buffer(path: &str, buffer: PolyBuffer, target_folder: &String) { let mut vertices = Vec::new(); let mut indices = Vec::new(); for point in buffer.vertices.iter() { vertices.push(point.x.to_string()); vertices.push(point.y.to_string()); vertices.push(String::from("0.0")); } for i in buffer.indices.iter() { indices.push(i.to_string()); } let v_code = vertices.join(","); let i_code = indices.join(","); let file_name = path.split("/").last().unwrap().replace(".svg", "").replace(" ", ""); let target_file = format!("{}/{}.js", target_folder, file_name); let className = format!("{}Data", file_name); let code = vec![ String::from("export const "), className, String::from(" = {vertices: ["), v_code, String::from("], indices: ["), i_code, String::from("]};") ].join(""); std::fs::write(target_file, code).ok(); println!("saving: {}", file_name); } fn main() { let (files, target_folder) = get_svg_in_folder(); for entry in files { match entry { Ok(path) => { let file_name = format!("{}", path.display()); let (fill_buffer, _stroke_buffer) = process_file(&file_name); save_buffer(&file_name, fill_buffer, &target_folder); }, Err(e) => println!("{:?}", e) } } }
mod path_to_path; extern crate lyon; extern crate glob; use std::env; use glob::glob; use std::fs; use lyon::tessellation::{FillOptions, FillTessellator, StrokeTessellator, StrokeOptions}; use lyon::path::math::{Point}; use lyon::path::Path; use lyon::tessellation::geometry_builder::{VertexBuffers, simple_builder}; type PolyBuffer = VertexBuffers<Point, u16>; fn ensure_result_folder(folder: &str) { fs::create_dir_all(folder).ok(); } fn get_svg_in_folder() -> (glob::Paths, String) { let executable = env::current_exe().unwrap(); let path = match executable.parent() { Some(name) => name, _ => panic!() }; let folder = path.display(); let folder_str = format!("{}", folder); let target_folder = format!("{}/result", folder); ensure_result_folder(&target_folder); let glob_query = format!("{}/*.svg", folder_str); let glob_query_str = glob_query.as_str(); return (glob(glob_query_str).expect("Failed to read glob pattern"), target_folder); } fn process_file(filename: &str) -> (PolyBuffer, PolyBuffer) { let opt = usvg::Options::default(); let file_data = std::fs::read(filename).unwrap(); let rtree = usvg::Tree::from_data(&file_data, &opt.to_ref()).unwrap(); let mut fill_builder = lyon::path::Path::builder(); let mut stroke_builder = lyon::path::Path::builder(); for node in rtree.root().descendants() { if let usvg::NodeKind::Path(ref p) = *node.borrow() { if let Some(_) = p.fill { path_to_path::to_path(&p.data, &mut fill_builder); } if let Some(_) = p.stroke { path_to_path::to_path(&p.data, &mut stroke_builder); } } } let fill_buffer = create_fill(&fill_builder.build()); let stroke_buffer = create_stroke(&stroke_builder.build(), 5.0); return (fill_buffer, stroke_buffer); } pub fn create_fill(path: &Path) -> PolyBuffer { let mut buffer: PolyBuffer = VertexBuffers::new(); { let mut vertex_builder = simple_builder(&mut buffer); let mut tessellator = FillTessellator::new(); tessellator .tessellate_path(path, &FillOptions::default(), &mut vertex_builder) .ok(); } return buffer; } pub fn create_stroke(path: &Path, line_width: f32) -> PolyBuffer { let mut buffer: PolyBuffer = VertexBuffers::new(); { let mut vertex_builder = simple_builder(&mut buffer); let mut tessellator = StrokeTessellator::new(); let options = StrokeOptions::default().with_tolerance(0.01).with_line_width(line_width); tessellator.tessellate_path ( path, &options, &mut vertex_builder ).ok(); } return buffer; } pub fn save_buffer(path: &str, buffer: PolyBuffer, target_folder: &String) { let mut vertices = Vec::new(); let mut indices = Vec::new(); for point in buffer.vertices.iter() { vertices.push(point.x.to_string()); vertices.push(point.y.to_string()); vertices.push(String::from("0.0")); } for i in buffer.indices.iter() { indices.push(i.to_string()); } let v_code = vertices.join(","); let i_code = indices.join(","); let file_name = path.split("/").last().unwrap().replace(".svg", "").replace(" ", ""); let target_file = format!("{}/{}.js", target_folder, file_name); let className = format!("{}Data", file_name); let code = vec![ String::from("export const "), className, String::from(" = {vertices: ["), v_code, String::from("], indices: ["), i_code, String::from("]};") ].join(""); std::fs::write(target_file, code).ok(); println!("saving: {}", file_name); }
fn main() { let (files, target_folder) = get_svg_in_folder(); for entry in files { match entry { Ok(path) => { let file_name = format!("{}", path.display()); let (fill_buffer, _stroke_buffer) = process_file(&file_name); save_buffer(&file_name, fill_buffer, &target_folder); }, Err(e) => println!("{:?}", e) } } }
function_block-full_function
[]
Rust
utils/test-env/src/utils.rs
hboshnak/casper-nft-cep47
09b40b0caf4cfc6f73d1e5f7d5b9c868228f7621
use std::path::PathBuf; use casper_engine_test_support::{ DeployItemBuilder, ExecuteRequestBuilder, InMemoryWasmTestBuilder, ARG_AMOUNT, DEFAULT_ACCOUNT_ADDR, DEFAULT_PAYMENT, }; use casper_execution_engine::core::engine_state::ExecuteRequest; use casper_types::{ account::AccountHash, bytesrepr::FromBytes, runtime_args, system::mint, CLTyped, ContractHash, Key, RuntimeArgs, StoredValue, U512, }; pub fn query<T: FromBytes + CLTyped>( builder: &InMemoryWasmTestBuilder, base: Key, path: &[String], ) -> T { builder .query(None, base, path) .expect("should be stored value.") .as_cl_value() .expect("should be cl value.") .clone() .into_t() .expect("Wrong type in query result.") } pub fn fund_account(account: &AccountHash) -> ExecuteRequest { let deploy_item = DeployItemBuilder::new() .with_address(*DEFAULT_ACCOUNT_ADDR) .with_authorization_keys(&[*DEFAULT_ACCOUNT_ADDR]) .with_empty_payment_bytes(runtime_args! {ARG_AMOUNT => *DEFAULT_PAYMENT}) .with_transfer_args(runtime_args! { mint::ARG_AMOUNT => U512::from(30_000_000_000_000_u64), mint::ARG_TARGET => *account, mint::ARG_ID => <Option::<u64>>::None }) .with_deploy_hash([1; 32]) .build(); ExecuteRequestBuilder::from_deploy_item(deploy_item).build() } pub enum DeploySource { Code(PathBuf), ByHash { hash: ContractHash, method: String }, } pub fn deploy( builder: &mut InMemoryWasmTestBuilder, deployer: &AccountHash, source: &DeploySource, args: RuntimeArgs, success: bool, block_time: Option<u64>, ) { let mut deploy_builder = DeployItemBuilder::new() .with_empty_payment_bytes(runtime_args! {ARG_AMOUNT => *DEFAULT_PAYMENT}) .with_address(*deployer) .with_authorization_keys(&[*deployer]); deploy_builder = match source { DeploySource::Code(path) => deploy_builder.with_session_code(path, args), DeploySource::ByHash { hash, method } => { deploy_builder.with_stored_session_hash(*hash, method, args) } }; let mut execute_request_builder = ExecuteRequestBuilder::from_deploy_item(deploy_builder.build()); if let Some(ustamp) = block_time { execute_request_builder = execute_request_builder.with_block_time(ustamp) } let exec = builder.exec(execute_request_builder.build()); if success { exec.expect_success() } else { exec.expect_failure() } .commit(); } pub fn query_dictionary_item( builder: &InMemoryWasmTestBuilder, key: Key, dictionary_name: Option<String>, dictionary_item_key: String, ) -> Result<StoredValue, String> { let empty_path = vec![]; let dictionary_key_bytes = dictionary_item_key.as_bytes(); let address = match key { Key::Account(_) | Key::Hash(_) => { if let Some(name) = dictionary_name { let stored_value = builder.query(None, key, &[])?; let named_keys = match &stored_value { StoredValue::Account(account) => account.named_keys(), StoredValue::Contract(contract) => contract.named_keys(), _ => { return Err( "Provided base key is nether an account or a contract".to_string() ) } }; let dictionary_uref = named_keys .get(&name) .and_then(Key::as_uref) .ok_or_else(|| "No dictionary uref was found in named keys".to_string())?; Key::dictionary(*dictionary_uref, dictionary_key_bytes) } else { return Err("No dictionary name was provided".to_string()); } } Key::URef(uref) => Key::dictionary(uref, dictionary_key_bytes), Key::Dictionary(address) => Key::Dictionary(address), _ => return Err("Unsupported key type for a query to a dictionary item".to_string()), }; builder.query(None, address, &empty_path) }
use std::path::PathBuf; use casper_engine_test_support::{ DeployItemBuilder, ExecuteRequestBuilder, InMemoryWasmTestBuilder, ARG_AMOUNT, DEFAULT_ACCOUNT_ADDR, DEFAULT_PAYMENT, }; use casper_execution_engine::core::engine_state::ExecuteRequest; use casper_types::{ account::AccountHash, bytesrepr::FromBytes, runtime_args, system::mint, CLTyped, ContractHash, Key, RuntimeArgs, StoredValue, U512, }; pub fn query<T: FromBytes + CLTyped>( builder: &InMemoryWasmTestBuilder, base: Key, path: &[String], ) -> T { builder .query(None, base, path) .expect("should be stored value.") .as_cl_value() .expect("should be cl value.") .clone() .into_t() .expect("Wrong type in query result.") } pub fn fund_account(account: &AccountHash) -> ExecuteRequest { let deploy_item = DeployItemBuilder::new() .with_address(*DEFAULT_ACCOUNT_ADDR) .with_authorization_keys(&[*DEFAULT_ACCOUNT_ADDR]) .with_empty_payment_bytes(runtime_args! {ARG_AMOUNT => *DEFAULT_PAYMENT}) .with_transfer_args(runtime_args! { mint::ARG_AMOUNT => U512::from(30_000_000_000_000_u64), mint::ARG_TARGET => *account, mint::ARG_ID => <Option::<u64>>::None }) .with_deploy_hash([1; 32]) .build(); ExecuteRequestBuilder::from_deploy_item(deploy_item).build() } pub enum DeploySource { Code(PathBuf), ByHash { hash: ContractHash, method: String }, } pub fn deploy( builder: &mut InMemoryWasmTestBuilder, deployer: &AccountHash, source: &DeploySource, args: RuntimeArgs, success: bool, block_time: Option<u64>, ) { let mut deploy_builder = DeployItemBuilder::new() .with_empty_payment_bytes(runtime_args! {ARG_AMOUNT => *DEFAULT_PAYMENT}) .with_address(*deployer) .with_authorization_keys(&[*deployer]); deploy_builder = match source { DeploySource::Code(path) => deploy_builder.with_session_code(path, args), DeploySource::ByHash { hash, method } => { deploy_builder.with_stored_session_hash(*hash, method, args) } }; let mut execute_request_builder = ExecuteRequestBuilder::from_deploy_item(deploy_builder.build()); if let Some(ustamp) = block_time { execute_request_builder = execute_request_builder.with_block_time(ustamp) } let exec = builder.exec(execute_request_builder.build()); if success { exec.expect_success() } else { exec.expect_failure() } .commit(); } pub fn query_dictionary_item( builder: &InMemoryWasmTestBuilder, key: Key, dictionary_name: Option<String>, dictionary_item_key: String, ) -> Result<StoredValue, String> { let empty_path = vec![]; let dictionary_key_bytes = dictionary_item_key.as_bytes(); let address = match key { Key::Account(_) | Key::Hash(_) => { if let Some(name) = dictionary_name { let stored_value = builder.query(None, key, &[])?;
let named_keys = match &stored_value { StoredValue::Account(account) => account.named_keys(), StoredValue::Contract(contract) => contract.named_keys(), _ => { return Err( "Provided base key is nether an account or a contract".to_string() ) } }; let dictionary_uref = named_keys .get(&name) .and_then(Key::as_uref) .ok_or_else(|| "No dictionary uref was found in named keys".to_string())?; Key::dictionary(*dictionary_uref, dictionary_key_bytes) } else { return Err("No dictionary name was provided".to_string()); } } Key::URef(uref) => Key::dictionary(uref, dictionary_key_bytes), Key::Dictionary(address) => Key::Dictionary(address), _ => return Err("Unsupported key type for a query to a dictionary item".to_string()), }; builder.query(None, address, &empty_path) }
function_block-function_prefix_line
[ { "content": "pub fn key_and_value_to_str<T: CLTyped + ToBytes>(key: &Key, value: &T) -> String {\n\n let mut bytes_a = key.to_bytes().unwrap_or_revert();\n\n let mut bytes_b = value.to_bytes().unwrap_or_revert();\n\n\n\n bytes_a.append(&mut bytes_b);\n\n\n\n let bytes = runtime::blake2b(bytes_a);\n...
Rust
src/main.rs
rcarmo/rrss2imap
1fff615262bcf5f98ae74bfacec6f902f732b9de
extern crate structopt; #[macro_use] extern crate log; extern crate serde; #[macro_use] extern crate serde_derive; extern crate serde_json; extern crate flexi_logger; extern crate treexml; extern crate chrono; extern crate rfc822_sanitizer; extern crate unidecode; extern crate tera; #[macro_use] extern crate lazy_static; #[macro_use] extern crate human_panic; extern crate kuchiki; extern crate imap; extern crate native_tls; extern crate base64; extern crate atom_syndication; extern crate reqwest; extern crate rss; extern crate xhtmlchardet; extern crate url; extern crate tree_magic; extern crate emailmessage; extern crate openssl_probe; extern crate regex; extern crate custom_error; extern crate async_std; extern crate tokio; extern crate futures; use flexi_logger::Logger; use std::path::PathBuf; use structopt::StructOpt; use std::error::Error; mod config; mod export; mod feed_errors; mod feed_reader; mod feed_utils; mod feed; mod image_to_data; mod import; mod message; mod settings; mod store; mod syndication; #[derive(Debug, StructOpt)] #[structopt(author=env!("CARGO_PKG_AUTHORS"))] struct RRSS2IMAP { #[structopt(short, long, parse(from_occurrences))] verbose: u8, #[structopt(subcommand)] cmd: Command } #[derive(Debug, StructOpt)] enum Command { #[structopt(name = "new")] New { email: String, }, #[structopt(name = "email")] Email { email: String }, #[structopt(name = "run")] Run, #[structopt(name = "add")] Add { #[structopt(short = "u", long = "url")] url:Option<String>, #[structopt(short = "e", long = "email")] email:Option<String>, #[structopt(short = "d", long = "destination")] destination:Option<String>, #[structopt(short = "i", long = "inline-mages")] inline_images:bool, #[structopt(short = "x", long = "do-not-inline-mages")] do_not_inline_images:bool, parameters: Vec<String>, }, #[structopt(name = "list")] List, #[structopt(name = "reset")] Reset, #[structopt(name = "delete")] Delete { feed: u32, }, #[structopt(name = "export")] Export { #[structopt(parse(from_os_str))] output: Option<PathBuf>, }, #[structopt(name = "import")] Import { #[structopt(parse(from_os_str))] input: Option<PathBuf>, }, } #[tokio::main] async fn main() -> Result<(), Box<dyn Error>> { if !cfg!(debug_assertions) { setup_panic!(); } let opt = RRSS2IMAP::from_args(); Logger::try_with_env_or_str( match opt.verbose { 0 => "warn", 1 => "warn, rrss2imap = info", 2 => "warn, rrss2imap = info", _ => "trace", }) .unwrap_or_else(|e| panic!("Logger initialization failed with {}", e)) .format(match opt.verbose { 0 => flexi_logger::colored_default_format, 1 => flexi_logger::colored_default_format, 2 => flexi_logger::colored_detailed_format, _ => flexi_logger::colored_with_thread, }) .start() .unwrap_or_else(|e| panic!("Logger initialization failed with {}", e)); openssl_probe::init_ssl_cert_env_vars(); let store_path = store::find_store(); let store_result = store::Store::load(&store_path); match store_result { Ok(mut store) => { match opt.cmd { Command::New { email } => store.init_config(email), Command::Email { email } => store.set_email(email), Command::List => store.list(), Command::Add { url, email, destination, inline_images, do_not_inline_images, parameters } => store.add(url, email, destination, store.settings.config.inline(inline_images, do_not_inline_images), parameters), Command::Delete { feed } => store.delete(feed), Command::Reset => store.reset(), Command::Run => { let handle = tokio::spawn(async move { store.run().await }); let _res = handle.await; } Command::Export { output } => store.export(output), Command::Import { input } => store.import(input), } }, Err(e) => { error!("Impossible to open store {}\n{}", store_path.to_string_lossy(), e); } } Ok(()) }
extern crate structopt; #[macro_use] extern crate log; extern crate serde; #[macro_use] extern crate serde_derive; extern crate serde_json; extern crate flexi_logger; extern crate treexml; extern crate chrono; extern crate rfc822_sanitizer; extern crate unidecode; extern crate tera; #[macro_use] extern crate lazy_static; #[macro_use] extern crate human_panic; extern crate kuchiki; extern crate imap; extern crate native_tls; extern crate base64; extern crate atom_syndication; extern crate reqwest; extern crate rss; extern crate xhtmlchardet; extern crate url; extern crate tree_magic; extern crate emailmessage; extern crate openssl_probe; extern crate regex; extern crate custom_error; extern crate async_std; extern crate tokio; extern crate futures; use flexi_logger::Logger; use std::path::PathBuf; use structopt::StructOpt; use std::error::Error; mod config; mod export; mod feed_errors; mod feed_reader; mod feed_utils; mod feed; mod image_to_data; mod import; mod message; mod settings; mod store; mod syndication; #[derive(Debug, StructOpt)] #[structopt(author=env!("CARGO_PKG_AUTHORS"))] struct RRSS2IMAP { #[structopt(short, long, parse(from_occurrences))] verbose: u8, #[structopt(subcommand)] cmd: Command } #[derive(Debug, StructOpt)] enum Command { #[structopt(name = "new")] New { email: String, }, #[structopt(name = "email")] Email { email: String }, #[structopt(name = "run")] Run, #[structopt(name = "add")] Add { #[structopt(short = "u", long = "url")] url:Option<String>, #[structopt(short = "e", long = "email")] email:Option<String>, #[structopt(short = "d", long = "destination")] destination:Option<String>, #[structopt(short = "i", long = "inline-mages")] inline_images:bool, #[structopt(short = "x", long = "do-not-inline-mages")] do_not_inline_images:bool, parameters: Vec<String>, }, #[structopt(name = "list")] List, #[structopt(name = "reset")] Reset, #[structopt(name = "delete")] Delete { feed: u32, }, #[structopt(name = "export")] Export { #[structopt(parse(from_os_str))] output: Option<PathBuf>, }, #[structopt(name = "import")] Import { #[structopt(parse(from_os_str))] input: Option<PathBuf>, }, } #[tokio::main] async fn main() -> Result<(), Box<dyn Error>> { if !cfg!(debug_assertions) { setup_panic!(); } let opt = RRSS2IMAP::from_args(); Logger::try_with_env_or_str( match opt.verbose { 0 => "warn", 1 => "warn, rrss2imap = info", 2 => "warn, rrss2imap = info", _ => "trace", }) .unwrap_or_else(|e| panic!("Logger initialization failed with {}", e)) .format(match opt.verbose { 0 => flexi_logger::colored_default_format, 1 => flexi_logger::colored_default_format, 2 => flexi_logger::colored_detailed_format, _ =>
flexi_logger::colored_with_thread, }) .start() .unwrap_or_else(|e| panic!("Logger initialization failed with {}", e)); openssl_probe::init_ssl_cert_env_vars(); let store_path = store::find_store(); let store_result = store::Store::load(&store_path); match store_result { Ok(mut store) => { match opt.cmd { Command::New { email } => store.init_config(email), Command::Email { email } => store.set_email(email), Command::List => store.list(), Command::Add { url, email, destination, inline_images, do_not_inline_images, parameters } => store.add(url, email, destination, store.settings.config.inline(inline_images, do_not_inline_images), parameters), Command::Delete { feed } => store.delete(feed), Command::Reset => store.reset(), Command::Run => { let handle = tokio::spawn(async move { store.run().await }); let _res = handle.await; } Command::Export { output } => store.export(output), Command::Import { input } => store.import(input), } }, Err(e) => { error!("Impossible to open store {}\n{}", store_path.to_string_lossy(), e); } } Ok(()) }
function_block-function_prefix_line
[ { "content": "fn group_feeds(to_store: &Store) -> HashMap<String, Vec<Feed>> {\n\n to_store.feeds.iter().fold(HashMap::new(), |mut map, feed| {\n\n let feed = feed.clone();\n\n let folder = feed.config.get_folder(&to_store.settings.config);\n\n if !map.contains_key(&folder) {\n\n ...
Rust
src/loading/util.rs
zmbush/budgetron
3403a020abbea635e156d2245226120ee87843c6
use { crate::loading::{ alliant, generic::{Genericize, Transaction}, logix, mint, }, budgetronlib::error::{BResult, BudgetError}, csv::Reader, log::info, serde::de::DeserializeOwned, std::{ cmp::min, fmt::Display, fs::File, io::{self, Read, Seek, Stdin, StdinLock}, path::Path, }, }; fn from_reader<TransactionType, R>(file: &mut R) -> BResult<Vec<Transaction>> where TransactionType: Genericize + DeserializeOwned, R: io::Read, { let mut transactions = Vec::new(); for record in Reader::from_reader(file).deserialize() { let record: TransactionType = record?; transactions.push(record.genericize()?); } Ok(transactions) } struct StdinSource<'a> { buf: Vec<u8>, loc: usize, stdin: StdinLock<'a>, } impl<'a> StdinSource<'a> { fn new(stdin: &'a Stdin) -> StdinSource<'a> { StdinSource { buf: Vec::new(), loc: 0, stdin: stdin.lock(), } } } enum Source<'a> { File(File), Stdin(StdinSource<'a>), } impl<'a> Seek for Source<'a> { fn seek(&mut self, pos: io::SeekFrom) -> io::Result<u64> { match *self { Source::File(ref mut f) => f.seek(pos), Source::Stdin(ref mut source) => match pos { io::SeekFrom::Start(loc) => { source.loc = loc as usize; Ok(source.loc as u64) } io::SeekFrom::Current(diff) => { if diff >= 0 { source.loc += diff as usize; } else { source.loc -= (-diff) as usize; } if source.loc >= source.buf.len() { Err(io::Error::new( io::ErrorKind::UnexpectedEof, "Tried to seek past internal buffer", )) } else { Ok(source.loc as u64) } } io::SeekFrom::End(_) => Err(io::Error::new( io::ErrorKind::InvalidInput, "Stdin has no end", )), }, } } } impl<'a> Read for Source<'a> { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { match *self { Source::File(ref mut f) => f.read(buf), Source::Stdin(ref mut source) => { if source.loc >= source.buf.len() { let ret = source.stdin.read(buf); if let Ok(size) = ret { source.buf.extend_from_slice(&buf[..size]); source.loc += size; Ok(size) } else { ret } } else { let len = buf.len(); let start = source.loc; let end = min(start + len, source.buf.len()); let readlen = end - start; buf[..readlen].copy_from_slice(&source.buf[start..end]); source.loc = end; Ok(readlen) } } } } } fn from_file_inferred<P: AsRef<Path> + Copy>(filename: P) -> BResult<Vec<Transaction>> { let stdin = io::stdin(); let mut reader = match filename.as_ref().to_str() { Some("-") => Source::Stdin(StdinSource::new(&stdin)), _ => Source::File(File::open(filename)?), }; let mut errors = Vec::new(); macro_rules! parse_exports { ($($type:path),*) => ($(match from_reader::<$type, _>(&mut reader) { Ok(result) => return Ok(result), Err(e) => { errors.push(e); reader.seek(io::SeekFrom::Start(0))?; } })*) } parse_exports!( Transaction, mint::MintExport, logix::LogixExport, alliant::AlliantExport ); Err(BudgetError::Multi(errors)) } pub fn load_from_files<P: AsRef<Path> + Display, Files: Iterator<Item = P>>( filenames: Files, ) -> BResult<Vec<Transaction>> { let mut transactions = Vec::new(); for filename in filenames { info!("Opening file: {}", filename); transactions.append(&mut from_file_inferred(&filename)?); } transactions.sort_by(|a, b| a.date.cmp(&b.date)); Ok(transactions) }
use { crate::loading::{ alliant, generic::{Genericize, Transaction}, logix, mint, }, budgetronlib::error::{BResu
read(buf), Source::Stdin(ref mut source) => { if source.loc >= source.buf.len() { let ret = source.stdin.read(buf); if let Ok(size) = ret { source.buf.extend_from_slice(&buf[..size]); source.loc += size; Ok(size) } else { ret } } else { let len = buf.len(); let start = source.loc; let end = min(start + len, source.buf.len()); let readlen = end - start; buf[..readlen].copy_from_slice(&source.buf[start..end]); source.loc = end; Ok(readlen) } } } } } fn from_file_inferred<P: AsRef<Path> + Copy>(filename: P) -> BResult<Vec<Transaction>> { let stdin = io::stdin(); let mut reader = match filename.as_ref().to_str() { Some("-") => Source::Stdin(StdinSource::new(&stdin)), _ => Source::File(File::open(filename)?), }; let mut errors = Vec::new(); macro_rules! parse_exports { ($($type:path),*) => ($(match from_reader::<$type, _>(&mut reader) { Ok(result) => return Ok(result), Err(e) => { errors.push(e); reader.seek(io::SeekFrom::Start(0))?; } })*) } parse_exports!( Transaction, mint::MintExport, logix::LogixExport, alliant::AlliantExport ); Err(BudgetError::Multi(errors)) } pub fn load_from_files<P: AsRef<Path> + Display, Files: Iterator<Item = P>>( filenames: Files, ) -> BResult<Vec<Transaction>> { let mut transactions = Vec::new(); for filename in filenames { info!("Opening file: {}", filename); transactions.append(&mut from_file_inferred(&filename)?); } transactions.sort_by(|a, b| a.date.cmp(&b.date)); Ok(transactions) }
lt, BudgetError}, csv::Reader, log::info, serde::de::DeserializeOwned, std::{ cmp::min, fmt::Display, fs::File, io::{self, Read, Seek, Stdin, StdinLock}, path::Path, }, }; fn from_reader<TransactionType, R>(file: &mut R) -> BResult<Vec<Transaction>> where TransactionType: Genericize + DeserializeOwned, R: io::Read, { let mut transactions = Vec::new(); for record in Reader::from_reader(file).deserialize() { let record: TransactionType = record?; transactions.push(record.genericize()?); } Ok(transactions) } struct StdinSource<'a> { buf: Vec<u8>, loc: usize, stdin: StdinLock<'a>, } impl<'a> StdinSource<'a> { fn new(stdin: &'a Stdin) -> StdinSource<'a> { StdinSource { buf: Vec::new(), loc: 0, stdin: stdin.lock(), } } } enum Source<'a> { File(File), Stdin(StdinSource<'a>), } impl<'a> Seek for Source<'a> { fn seek(&mut self, pos: io::SeekFrom) -> io::Result<u64> { match *self { Source::File(ref mut f) => f.seek(pos), Source::Stdin(ref mut source) => match pos { io::SeekFrom::Start(loc) => { source.loc = loc as usize; Ok(source.loc as u64) } io::SeekFrom::Current(diff) => { if diff >= 0 { source.loc += diff as usize; } else { source.loc -= (-diff) as usize; } if source.loc >= source.buf.len() { Err(io::Error::new( io::ErrorKind::UnexpectedEof, "Tried to seek past internal buffer", )) } else { Ok(source.loc as u64) } } io::SeekFrom::End(_) => Err(io::Error::new( io::ErrorKind::InvalidInput, "Stdin has no end", )), }, } } } impl<'a> Read for Source<'a> { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { match *self { Source::File(ref mut f) => f.
random
[ { "content": "CREATE TABLE transactions (\n\n id SERIAL PRIMARY KEY,\n\n date DATE NOT NULL,\n\n person VARCHAR NOT NULL,\n\n description VARCHAR NOT NULL,\n\n original_description VARCHAR,\n\n amount DOUBLE PRECISION NOT NULL,\n\n transaction_type VARCHAR NOT NULL,\n\n category VARCHAR NOT NULL,\n\n o...
Rust
guacamole-runner/src/map.rs
EllenNyan/guacamole-runner
aa17fdaf763e415ff9531e42ae946b503f9cbfb9
use crate::{ shipyard::{ *, }, consts::{ *, }, tetra::{ math::{ Vec3, Vec2, }, graphics::{ Color, }, }, }; use vermarine_lib::{ rendering::{ draw_buffer::{ DrawBuffer, DrawCommand, }, Drawables, }, }; use rand::SeedableRng; use rand::Rng; use rand::rngs::StdRng; pub struct HexTileData { pub ground_height: u8, pub wall_height: u8, pub is_tilled: bool, pub is_grown: bool, } impl HexTileData { pub fn new(height: u8) -> HexTileData { HexTileData { ground_height: height, wall_height: height, is_tilled: false, is_grown: false, } } } pub struct HexMap { pub tiles: Vec<HexTileData>, pub width: usize, pub height: usize, pub position: Vec2<f32>, pub tallest: u8, } impl HexMap { pub fn new(width: usize, height: usize) -> Self { let mut rand = StdRng::from_entropy(); let mut tiles = Vec::<HexTileData>::with_capacity(width * height); let mut tallest = 0; for _ in 0..width * height { let value = rand.gen_range(0, MAX_FLOOR_HEIGHT + 1); let tile = HexTileData::new(value); tiles.push(tile); if value > tallest { tallest = value; } } for _ in 0..5 { for section in 0..(width / 10) { let col = rand.gen_range(0, height + 1); let mut total = 0; for _ in 0..5 { total += rand.gen_range(3, 7 + 1); } total /= 5; for offset in 0..total { if let Some(tile) = tiles.get_mut((col * width) + (section * 10) + offset) { tile.is_tilled = true; } } } } let height_px = { height as f32 * FLOOR_VERT_STEP }; let position = Vec2::new( 0., 360. - height_px, ); HexMap { tiles, width, height, position, tallest, } } pub fn pixel_to_hex_raw(&mut self, pos: Vec2<f32>, height_offset: f32) -> (f32, f32) { let mut pos = pos; pos -= Vec2::new(18., 18.); pos.x -= self.position.x; pos.y -= self.position.y; pos.y += height_offset; let size_x = FLOOR_WIDTH / f32::sqrt(3.0); let size_y = 18.66666666666666666; let pos = Vec2::new( pos.x / size_x, pos.y / size_y, ); let b0 = f32::sqrt(3.0) / 3.0; let b1 = -1.0 / 3.0; let b2 = 0.0; let b3 = 2.0 / 3.0; let q: f32 = b0 * pos.x + b1 * pos.y; let r: f32 = b2 * pos.x + b3 * pos.y; (q, r) } #[allow(dead_code)] pub fn pixel_to_hex(&mut self, pos: Vec2<f32>) -> Option<(i32, i32)> { let mut tallest_height: Option<(u8, i32, i32)> = None; for height in 0..=self.tallest { let height_offset = height as f32 * FLOOR_DEPTH_STEP; let (q, r) = self.pixel_to_hex_raw(pos.clone(), height_offset); let (q, r, s) = (q, r, -r -q); let (x, y, _) = cube_round(q, r, s); if x < 0 || x >= self.width as i32 || y < 0 || y >= self.height as i32 { continue; } let tile = &self.tiles[self.width * y as usize + x as usize]; let tile_height = tile.wall_height; if tile_height != height { continue; } if tallest_height.is_none() || tile_height > tallest_height.unwrap().0 { tallest_height = Some((tile_height, x, y)); } } if let Some((_, x, y)) = tallest_height { return Some((x, y)); } None } #[allow(dead_code)] pub fn axial_to_pixel(&mut self, q: i32, r: i32) -> (f32, f32) { let (q, r) = (q as f32, r as f32); let size_x = FLOOR_WIDTH / f32::sqrt(3.0); let size_y = 18.66666666666666666; let x = size_x * (f32::sqrt(3.0) * q + f32::sqrt(3.0) / 2.0 * r); let y = size_y * (3.0 / 2.0 * r); ( x + 18. + self.position.x, y + 18. + self.position.y, ) } } #[allow(dead_code)] pub fn cube_to_offset(q: i32, r: i32) -> (i32, i32) { let col = q + (r - (r & 1)) / 2; let row = r; (col, row) } #[allow(dead_code)] pub fn offset_to_cube(off_x: i32, off_y: i32) -> (i32, i32, i32) { let x = off_x - (off_y - (off_y as i32 & 1)) / 2; let z = off_y; let y = -x-z; (x, y, z) } pub fn cube_round(q: f32, r: f32, s: f32) -> (i32, i32, i32) { let mut qi = q.round() as i32; let mut ri = r.round() as i32; let mut si = s.round() as i32; let q_diff = f64::abs(qi as f64 - q as f64); let r_diff = f64::abs(ri as f64 - r as f64); let s_diff = f64::abs(si as f64 - s as f64); if q_diff > r_diff && q_diff > s_diff { qi = -ri - si; } else if r_diff > s_diff { ri = -qi - si; } else { si = -qi - ri; } (qi, ri, si) } pub fn render_hex_map(mut draw_buffer: UniqueViewMut<DrawBuffer>, drawables: NonSendSync<UniqueViewMut<Drawables>>, mut map: UniqueViewMut<HexMap>) { draw_buffer.new_command_pool(true); let command_pool = draw_buffer.get_command_pool(); let (q, r) = map.pixel_to_hex_raw(Vec2::zero(), 0.); let startx = (q - 40.0) .max(0.0).min(map.width as f32 - 1.0) as usize; let endx = (q + 40.0) .max(0.0).min(map.width as f32 - 1.0) as usize; let starty = (r - 20.0) .max(0.0).min(map.height as f32 - 1.0) as usize; let endy = (r + 20.0) .max(0.0).min(map.height as f32 - 1.0) as usize; let (top_tex, wall_tex, brick_tex, brick_floor_tex, grown_tex, tilled_tex) = ( drawables.alias[textures::FLOOR], drawables.alias[textures::WALL], drawables.alias[textures::WALL_BRICK], drawables.alias[textures::FLOOR_BRICK], drawables.alias[textures::FLOOR_GROWN], drawables.alias[textures::FLOOR_TILLED], ); for height in 0..=MAX_BRICK_HEIGHT { let mut wall_buffer: Vec<DrawCommand> = Vec::with_capacity(1024); let mut wall_brick_buffer: Vec<DrawCommand> = Vec::with_capacity(1024); let mut top_buffer: Vec<DrawCommand> = Vec::with_capacity(1024); let mut top_brick_buffer: Vec<DrawCommand> = Vec::with_capacity(1024); let mut top_tilled_buffer: Vec<DrawCommand> = Vec::with_capacity(1024); let mut top_grown_buffer: Vec<DrawCommand> = Vec::with_capacity(1024); for y in starty..=endy { for x in startx..=endx { let tile = &map.tiles[map.width * y + x]; if tile.wall_height < height { continue; } let (draw_x, draw_y) = { let offset_x = (FLOOR_WIDTH / 2.0) * y as f32; let mut x = FLOOR_WIDTH * x as f32; x += offset_x; ( x, (y as i32) as f32 * (FLOOR_VERT_STEP) ) }; let (draw_x, draw_y) = ( draw_x + map.position.x, draw_y + map.position.y, ); if height <= tile.ground_height && height != 0 { render_hex_walls(&mut wall_buffer, draw_x, draw_y, height, wall_tex); } else if height > tile.ground_height && height <= tile.wall_height { render_hex_bricks(&mut wall_brick_buffer, draw_x, draw_y, height, brick_tex); } if tile.is_grown && height == tile.ground_height { render_hex_top(&mut top_grown_buffer, draw_x, draw_y, tile.ground_height, grown_tex, Color::WHITE); } else if tile.is_tilled && height == tile.ground_height { render_hex_top(&mut top_tilled_buffer, draw_x, draw_y, tile.ground_height, tilled_tex, Color::WHITE); } else if height == tile.ground_height && height == tile.wall_height { render_hex_top(&mut top_buffer, draw_x, draw_y, tile.ground_height, top_tex, Color::WHITE); } else if height == tile.wall_height && height != tile.ground_height { render_hex_brick_top(&mut top_brick_buffer, draw_x, draw_y, tile.wall_height, brick_floor_tex, Color::WHITE); } } } command_pool.commands.extend(&wall_buffer); command_pool.commands.extend(&wall_brick_buffer); command_pool.commands.extend(&top_buffer); command_pool.commands.extend(&top_brick_buffer); command_pool.commands.extend(&top_tilled_buffer); command_pool.commands.extend(&top_grown_buffer); } /*let marker_tex = drawables.alias[textures::MARKER]; for y_tile in starty..=endy { for x_tile in startx..=endx { let (x, y) = map.axial_to_pixel(x_tile as i32, y_tile as i32); let tile = &map.tiles[map.width * y_tile + x_tile]; draw_buffer.draw( DrawCommand::new(marker_tex) .position(Vec3::new( x - 2.0, y - 2.0, tile.wall_height as f32 * FLOOR_DEPTH_STEP )) .draw_iso(true) ); } }*/ draw_buffer.end_command_pool(); } pub fn render_hex_top(draw_buffer: &mut Vec<DrawCommand>, x: f32, y: f32, height: u8, texture: u64, color: Color) { let mut draw_command = create_floor_draw_cmd(x, y, height as f32 * FLOOR_DEPTH_STEP, height, texture); if color != Color::WHITE { draw_command = draw_command.color(color); } draw_buffer.push(draw_command); } fn create_floor_draw_cmd(x: f32, y: f32, height: f32, color: u8, texture: u64) -> DrawCommand { let color = if color == 0 { let v = 0.55; Color::rgba(v, v, v, 1.0) } else if color == 1 { let v = 0.8; Color::rgba(v, v, v, 1.0) } else { let v = 0.95; Color::rgba(v, v, v, 1.0) }; DrawCommand::new(texture) .position(Vec3::new(x, y, height)) .draw_layer(draw_layers::FLOOR) .draw_iso(true) .color(color) } pub fn render_hex_brick_top(draw_buffer: &mut Vec<DrawCommand>, x: f32, y: f32, height: u8, texture: u64, color: Color) { let mut draw_command = create_brick_floor_draw_cmd(x, y, height as f32 * FLOOR_DEPTH_STEP, height, texture); if color != Color::WHITE { draw_command = draw_command.color(color); } draw_buffer.push(draw_command); } fn create_brick_floor_draw_cmd(x: f32, y: f32, height: f32, color: u8, texture: u64) -> DrawCommand { let color = if color == 1 { let v = 0.65; Color::rgba(v, v, v, 1.0) } else if color == 2 { let v = 0.8; Color::rgba(v, v, v, 1.0) } else if color == 3 { let v = 0.9; Color::rgba(v, v, v, 1.0) } else { let v = 1.0; Color::rgba(v, v, v, 1.0) }; DrawCommand::new(texture) .position(Vec3::new(x, y, height)) .draw_layer(draw_layers::FLOOR) .draw_iso(true) .color(color) } pub fn render_hex_walls(draw_buffer: &mut Vec<DrawCommand>, x: f32, y: f32, height: u8, wall_tex: u64) { let start_height = height as f32 * FLOOR_DEPTH_STEP - WALL_VERT_OFFSET; let color = if height % 2 == 1 { 1 } else { 2 }; draw_buffer.push( create_wall_draw_cmd(x, y, start_height, color, wall_tex) ); } fn create_wall_draw_cmd(x: f32, y: f32, height: f32, color: u8, texture: u64) -> DrawCommand { let color = if color == 1 { let v = 0.5; Color::rgba(v, v, v, 1.0) } else if color == 2{ let v = 0.7; Color::rgba(v, v, v, 1.0) } else { let v = 1.0; Color::rgba(v, v, v, 1.0) }; DrawCommand::new(texture) .position(Vec3::new(x, y, height)) .draw_layer(draw_layers::WALL) .draw_iso(true) .color(color) } pub fn render_hex_bricks(draw_buffer: &mut Vec<DrawCommand>, x: f32, y: f32, height: u8, brick_tex: u64) { let start_height = height as f32 * FLOOR_DEPTH_STEP - WALL_VERT_STEP; draw_buffer.push( create_wall_brick_draw_cmd(x, y, start_height, height, brick_tex) ); } fn create_wall_brick_draw_cmd(x: f32, y: f32, height: f32, color: u8, texture: u64) -> DrawCommand { let color = if color == 1 { let v = 0.3; Color::rgba(v, v, v, 1.0) } else if color == 2 { let v = 0.55; Color::rgba(v, v, v, 1.0) } else if color == 3 { let v = 0.7; Color::rgba(v, v, v, 1.0) } else { let v = 0.80; Color::rgba(v, v, v, 1.0) }; DrawCommand::new(texture) .position(Vec3::new(x, y, height)) .draw_layer(draw_layers::WALL) .draw_iso(true) .color(color) }
use crate::{ shipyard::{ *, }, consts::{ *, }, tetra::{ math::{ Vec3, Vec2, }, graphics::{ Color, }, }, }; use vermarine_lib::{ rendering::{ draw_buffer::{ DrawBuffer, DrawCommand, }, Drawables, }, }; use rand::SeedableRng; use rand::Rng; use rand::rngs::StdRng; pub struct HexTileData { pub ground_height: u8, pub wall_height: u8, pub is_tilled: bool, pub is_grown: bool, } impl HexTileData { pub fn new(height: u8) -> HexTileData { HexTileData { ground_height: height, wall_height: height, is_tilled: false, is_grown: false, } } } pub struct HexMap { pub tiles: Vec<HexTileData>, pub width: usize, pub height: usize, pub position: Vec2<f32>, pub tallest: u8, } impl HexMap { pub fn new(width: usize, height: usize) -> Self { let mut rand = StdRng::from_entropy(); let mut tiles = Vec::<HexTileData>::with_capacity(width * height); let mut tallest = 0; for _ in 0..width * height { let value = rand.gen_range(0, MAX_FLOOR_HEIGHT + 1); let tile = HexTileData::new(value); tiles.push(tile); if value > tallest { tallest = value; } } for _ in 0..5 { for section in 0..(width / 10) { let col = rand.gen_range(0, height + 1); let mut total = 0; for _ in 0..5 { total += rand.gen_range(3, 7 + 1); } total /= 5; for offset in 0..total { if let Some(tile) = tiles.get_mut((col * width) + (section * 10) + offset) { tile.is_tilled = true; } } } } let height_px = { height as f32 * FLOOR_VERT_STEP }; let position = Vec2::new( 0., 360. - height_px, ); HexMap { tiles, width, height, position, tallest, } } pub fn pixel_to_hex_raw(&mut self, pos: Vec2<f32>, height_offset: f32) -> (f32, f32) { let mut pos = pos; pos -= Vec2::new(18., 18.); pos.x -= self.position.x; pos.y -= self.position.y; pos.y += height_offset; let size_x = FLOOR_WIDTH / f32::sqrt(3.0); let size_y = 18.66666666666666666; let pos = Vec2::new( pos.x / size_x, pos.y / size_y, ); let b0 = f32::sqrt(3.0) / 3.0; let b1 = -1.0 / 3.0; let b2 = 0.0; let b3 = 2.0 / 3.0; let q: f32 = b0 * pos.x + b1 * pos.y; let r: f32 = b2 * pos.x + b3 * pos.y; (q, r) } #[allow(dead_code)] pub fn pixel_to_hex(&mut self, pos: Vec2<f32>) -> Option<(i32, i32)> { let mut tallest_height: Option<(u8, i32, i32)> = None; for height in 0..=self.tallest { let height_offset = height as f32 * FLOOR_DEPTH_STEP; let (q, r) = self.pixel_to_hex_raw(pos.clone(), height_offset); let (q, r, s) = (q, r, -r -q); let (x, y, _) = cube_round(q, r, s); if x < 0 || x >= self.width as i32 || y < 0 || y >= self.height as i32 { continue; } let tile = &self.tiles[self.width * y as usize + x as usize]; let tile_height = tile.wall_height; if tile_height != height { continue; } if tallest_height.is_none() || tile_height > tallest_height.unwrap().0 { tallest_height = Some((tile_height, x, y)); } } if let Some((_, x, y)) = tallest_height { return Some((x, y)); } None } #[allow(dead_code)] pub fn axial_to_pixel(&mut self, q: i32, r: i32) -> (f32, f32) { let (q, r) = (q as f32, r as f32); let size_x = FLOOR_WIDTH / f32::sqrt(3.0); let size_y = 18.66666666666666666; let x = size_x * (f32::sqrt(3.0) * q + f32::sqrt(3.0) / 2.0 * r); let y = size_y * (3.0 / 2.0 * r); ( x + 18. + self.position.x, y + 18. + self.position.y, ) } } #[allow(dead_code)] pub fn cube_to_offset(q: i32, r: i32) -> (i32, i32) { let col = q + (r - (r & 1)) / 2; let row = r; (col, row) } #[allow(dead_code)] pub fn offset_to_cube(off_x: i32, off_y: i32) -> (i32, i32, i32) { let x = off_x - (off_y - (off_y as i32 & 1)) / 2; let z = off_y; let y = -x-z; (x, y, z) } pub fn cube_round(q: f32, r: f32, s: f32) -> (i32, i32, i32) { let
pub fn render_hex_map(mut draw_buffer: UniqueViewMut<DrawBuffer>, drawables: NonSendSync<UniqueViewMut<Drawables>>, mut map: UniqueViewMut<HexMap>) { draw_buffer.new_command_pool(true); let command_pool = draw_buffer.get_command_pool(); let (q, r) = map.pixel_to_hex_raw(Vec2::zero(), 0.); let startx = (q - 40.0) .max(0.0).min(map.width as f32 - 1.0) as usize; let endx = (q + 40.0) .max(0.0).min(map.width as f32 - 1.0) as usize; let starty = (r - 20.0) .max(0.0).min(map.height as f32 - 1.0) as usize; let endy = (r + 20.0) .max(0.0).min(map.height as f32 - 1.0) as usize; let (top_tex, wall_tex, brick_tex, brick_floor_tex, grown_tex, tilled_tex) = ( drawables.alias[textures::FLOOR], drawables.alias[textures::WALL], drawables.alias[textures::WALL_BRICK], drawables.alias[textures::FLOOR_BRICK], drawables.alias[textures::FLOOR_GROWN], drawables.alias[textures::FLOOR_TILLED], ); for height in 0..=MAX_BRICK_HEIGHT { let mut wall_buffer: Vec<DrawCommand> = Vec::with_capacity(1024); let mut wall_brick_buffer: Vec<DrawCommand> = Vec::with_capacity(1024); let mut top_buffer: Vec<DrawCommand> = Vec::with_capacity(1024); let mut top_brick_buffer: Vec<DrawCommand> = Vec::with_capacity(1024); let mut top_tilled_buffer: Vec<DrawCommand> = Vec::with_capacity(1024); let mut top_grown_buffer: Vec<DrawCommand> = Vec::with_capacity(1024); for y in starty..=endy { for x in startx..=endx { let tile = &map.tiles[map.width * y + x]; if tile.wall_height < height { continue; } let (draw_x, draw_y) = { let offset_x = (FLOOR_WIDTH / 2.0) * y as f32; let mut x = FLOOR_WIDTH * x as f32; x += offset_x; ( x, (y as i32) as f32 * (FLOOR_VERT_STEP) ) }; let (draw_x, draw_y) = ( draw_x + map.position.x, draw_y + map.position.y, ); if height <= tile.ground_height && height != 0 { render_hex_walls(&mut wall_buffer, draw_x, draw_y, height, wall_tex); } else if height > tile.ground_height && height <= tile.wall_height { render_hex_bricks(&mut wall_brick_buffer, draw_x, draw_y, height, brick_tex); } if tile.is_grown && height == tile.ground_height { render_hex_top(&mut top_grown_buffer, draw_x, draw_y, tile.ground_height, grown_tex, Color::WHITE); } else if tile.is_tilled && height == tile.ground_height { render_hex_top(&mut top_tilled_buffer, draw_x, draw_y, tile.ground_height, tilled_tex, Color::WHITE); } else if height == tile.ground_height && height == tile.wall_height { render_hex_top(&mut top_buffer, draw_x, draw_y, tile.ground_height, top_tex, Color::WHITE); } else if height == tile.wall_height && height != tile.ground_height { render_hex_brick_top(&mut top_brick_buffer, draw_x, draw_y, tile.wall_height, brick_floor_tex, Color::WHITE); } } } command_pool.commands.extend(&wall_buffer); command_pool.commands.extend(&wall_brick_buffer); command_pool.commands.extend(&top_buffer); command_pool.commands.extend(&top_brick_buffer); command_pool.commands.extend(&top_tilled_buffer); command_pool.commands.extend(&top_grown_buffer); } /*let marker_tex = drawables.alias[textures::MARKER]; for y_tile in starty..=endy { for x_tile in startx..=endx { let (x, y) = map.axial_to_pixel(x_tile as i32, y_tile as i32); let tile = &map.tiles[map.width * y_tile + x_tile]; draw_buffer.draw( DrawCommand::new(marker_tex) .position(Vec3::new( x - 2.0, y - 2.0, tile.wall_height as f32 * FLOOR_DEPTH_STEP )) .draw_iso(true) ); } }*/ draw_buffer.end_command_pool(); } pub fn render_hex_top(draw_buffer: &mut Vec<DrawCommand>, x: f32, y: f32, height: u8, texture: u64, color: Color) { let mut draw_command = create_floor_draw_cmd(x, y, height as f32 * FLOOR_DEPTH_STEP, height, texture); if color != Color::WHITE { draw_command = draw_command.color(color); } draw_buffer.push(draw_command); } fn create_floor_draw_cmd(x: f32, y: f32, height: f32, color: u8, texture: u64) -> DrawCommand { let color = if color == 0 { let v = 0.55; Color::rgba(v, v, v, 1.0) } else if color == 1 { let v = 0.8; Color::rgba(v, v, v, 1.0) } else { let v = 0.95; Color::rgba(v, v, v, 1.0) }; DrawCommand::new(texture) .position(Vec3::new(x, y, height)) .draw_layer(draw_layers::FLOOR) .draw_iso(true) .color(color) } pub fn render_hex_brick_top(draw_buffer: &mut Vec<DrawCommand>, x: f32, y: f32, height: u8, texture: u64, color: Color) { let mut draw_command = create_brick_floor_draw_cmd(x, y, height as f32 * FLOOR_DEPTH_STEP, height, texture); if color != Color::WHITE { draw_command = draw_command.color(color); } draw_buffer.push(draw_command); } fn create_brick_floor_draw_cmd(x: f32, y: f32, height: f32, color: u8, texture: u64) -> DrawCommand { let color = if color == 1 { let v = 0.65; Color::rgba(v, v, v, 1.0) } else if color == 2 { let v = 0.8; Color::rgba(v, v, v, 1.0) } else if color == 3 { let v = 0.9; Color::rgba(v, v, v, 1.0) } else { let v = 1.0; Color::rgba(v, v, v, 1.0) }; DrawCommand::new(texture) .position(Vec3::new(x, y, height)) .draw_layer(draw_layers::FLOOR) .draw_iso(true) .color(color) } pub fn render_hex_walls(draw_buffer: &mut Vec<DrawCommand>, x: f32, y: f32, height: u8, wall_tex: u64) { let start_height = height as f32 * FLOOR_DEPTH_STEP - WALL_VERT_OFFSET; let color = if height % 2 == 1 { 1 } else { 2 }; draw_buffer.push( create_wall_draw_cmd(x, y, start_height, color, wall_tex) ); } fn create_wall_draw_cmd(x: f32, y: f32, height: f32, color: u8, texture: u64) -> DrawCommand { let color = if color == 1 { let v = 0.5; Color::rgba(v, v, v, 1.0) } else if color == 2{ let v = 0.7; Color::rgba(v, v, v, 1.0) } else { let v = 1.0; Color::rgba(v, v, v, 1.0) }; DrawCommand::new(texture) .position(Vec3::new(x, y, height)) .draw_layer(draw_layers::WALL) .draw_iso(true) .color(color) } pub fn render_hex_bricks(draw_buffer: &mut Vec<DrawCommand>, x: f32, y: f32, height: u8, brick_tex: u64) { let start_height = height as f32 * FLOOR_DEPTH_STEP - WALL_VERT_STEP; draw_buffer.push( create_wall_brick_draw_cmd(x, y, start_height, height, brick_tex) ); } fn create_wall_brick_draw_cmd(x: f32, y: f32, height: f32, color: u8, texture: u64) -> DrawCommand { let color = if color == 1 { let v = 0.3; Color::rgba(v, v, v, 1.0) } else if color == 2 { let v = 0.55; Color::rgba(v, v, v, 1.0) } else if color == 3 { let v = 0.7; Color::rgba(v, v, v, 1.0) } else { let v = 0.80; Color::rgba(v, v, v, 1.0) }; DrawCommand::new(texture) .position(Vec3::new(x, y, height)) .draw_layer(draw_layers::WALL) .draw_iso(true) .color(color) }
mut qi = q.round() as i32; let mut ri = r.round() as i32; let mut si = s.round() as i32; let q_diff = f64::abs(qi as f64 - q as f64); let r_diff = f64::abs(ri as f64 - r as f64); let s_diff = f64::abs(si as f64 - s as f64); if q_diff > r_diff && q_diff > s_diff { qi = -ri - si; } else if r_diff > s_diff { ri = -qi - si; } else { si = -qi - ri; } (qi, ri, si) }
function_block-function_prefixed
[ { "content": "pub fn player_height_visualiser(player: View<Player>, height: View<Height>, mut sprite: ViewMut<Sprite>) {\n\n let (_, height, sprite) = (&player, &height, &mut sprite).iter().next().unwrap();\n\n let mut percent = height.0 / START_HEIGHT;\n\n percent *= percent;\n\n let start = 1.;\n\...
Rust
src/grammar/grammar.rs
zuyumi/compiler-course-helper
093b0d37073703d8e87e29e140a7bec29008c93b
use std::collections::{HashMap, HashSet}; #[derive(Debug, Clone)] pub struct NonTerminal { pub index: usize, pub name: String, pub first: HashSet<usize>, pub follow: HashSet<usize>, pub nullable: bool, pub productions: Vec<Vec<usize>>, } impl NonTerminal { pub fn new(index: usize, name: String) -> Self { Self { index, name, first: HashSet::new(), follow: HashSet::new(), nullable: false, productions: Vec::new(), } } } #[derive(Debug, Clone)] pub enum Symbol { NonTerminal(NonTerminal), Terminal(String), } impl Symbol { pub fn non_terminal(&self) -> Option<&NonTerminal> { match self { Symbol::NonTerminal(e) => Some(e), Symbol::Terminal(_) => None, } } pub fn mut_non_terminal(&mut self) -> Option<&mut NonTerminal> { match self { Symbol::NonTerminal(e) => Some(e), Symbol::Terminal(_) => None, } } } #[derive(Debug, Clone)] pub struct Grammar { valid_nullable_first_follow: bool, pub symbols: Vec<Symbol>, pub symbol_table: HashMap<String, usize>, pub start_symbol: Option<usize>, } impl Grammar { pub fn new() -> Self { let mut g = Self { valid_nullable_first_follow: false, symbols: Vec::new(), symbol_table: HashMap::new(), start_symbol: None, }; let e_idx = g.add_non_terminal(super::EPSILON); g.symbols[e_idx].mut_non_terminal().unwrap().nullable = true; g.symbol_table.insert("ε".to_string(), e_idx); g.add_terminal(super::END_MARK.to_string()); g } pub fn get_symbol_by_name(&self, name: &str) -> &Symbol { &self.symbols[self.symbol_table[name]] } pub fn terminal_iter(&self) -> impl Iterator<Item = &String> { self.symbols.iter().filter_map(|s| { if let Symbol::Terminal(name) = s { Some(name) } else { None } }) } pub fn non_terminal_iter(&self) -> impl Iterator<Item = &NonTerminal> { self.symbols.iter().filter_map(|s| s.non_terminal()).skip(1) } pub fn non_terminal_iter_mut(&mut self) -> impl Iterator<Item = &mut NonTerminal> { self.symbols .iter_mut() .filter_map(|s| s.mut_non_terminal()) .skip(1) } pub fn get_symbol_index(&self, name: &str) -> Option<usize> { self.symbol_table.get(name).cloned() } pub fn add_non_terminal(&mut self, name: &str) -> usize { let idx = self.symbols.len(); self.symbols .push(Symbol::NonTerminal(NonTerminal::new(idx, name.to_string()))); self.symbol_table.insert(name.to_string(), idx); idx } pub fn add_terminal(&mut self, name: String) -> usize { let idx = self.symbols.len(); self.symbols.push(Symbol::Terminal(name.clone())); self.symbol_table.insert(name, idx); idx } pub fn add_production(&mut self, left: usize, right: Vec<usize>) { self.symbols[left] .mut_non_terminal() .unwrap() .productions .push(right); } pub fn get_symbol_name(&self, index: usize) -> &str { match &self.symbols[index] { Symbol::NonTerminal(e) => e.name.as_str(), Symbol::Terminal(e) => e.as_str(), } } pub fn get_symbol_prime_name(&self, mut name: String) -> String { while self.symbol_table.contains_key(&name) { name.push('\''); } name } pub fn invalidate_nullable_first_follow(&mut self) { self.valid_nullable_first_follow = false; self.reset_nullable_first_follow(); } pub fn is_nullable_first_follow_valid(&self) -> bool { self.valid_nullable_first_follow } pub fn validate_nullable_first_follow(&mut self) { self.valid_nullable_first_follow = true; } pub fn production_to_vec_str(&self, production: &Vec<usize>) -> Vec<&str> { production .iter() .map(|idx| self.get_symbol_name(*idx)) .collect() } }
use std::collections::{HashMap, HashSet}; #[derive(Debug, Clone)] pub struct NonTerminal { pub index: usize, pub name: String, pub first: HashSet<usize>, pub follow: HashSet<usize>, pub nullable: bool, pub productions: Vec<Vec<usize>>, } impl NonTerminal { pub fn new(index: usize, name: String) -> Self { Self { index, name, first: HashSet::new(), follow: HashSet::new(), nullable: false, productions: Vec::new(), } } } #[derive(Debug, Clone)] pub enum Symbol { NonTerminal(NonTerminal), Terminal(String), } impl Symbol { pub fn non_terminal(&self) -> Option<&NonTerminal> { match self { Symbol::NonTerminal(e) => Some(e), Symbol::Terminal(_) => None, } } pub fn mut_non_terminal(&mut self) -> Option<&mut NonTerminal> { match self { Symbol::NonTerminal(e) => Some(e), Symbol::Terminal(_) => None, } } } #[derive(Debug, Clone)] pub struct Grammar { valid_nullable_first_follow: bool, pub symbols: Vec<Symbol>, pub symbol_table: HashMap<String, usize>, pub start_symbol: Option<usize>, } impl Grammar { pub fn new() -> Self { let mut g = Self { valid_nullable_first_follow: false, symbols: Vec::new(), symbol_table: HashMap::new(), start_symbol: None, }; let e_idx = g.add_non_terminal(super::EPSILON); g.symbols[e_idx].mut_non_terminal().unwrap().nullable = true; g.symbol_table.insert("ε".to_string(), e_idx); g.add_terminal(super::END_MARK.to_string()); g } pub fn get_symbol_by_name(&self, name: &str) -> &Symbol { &self.symbols[self.symbol_table[name]] } pub fn terminal_iter(&self) -> impl Iterator<Item = &String> { self.symbols.iter().filter_map(|s| { if let Symbol::Terminal(name) = s { Some(name) } else { None } }) } pub fn non_terminal_iter(&self) -> impl Iterator<Item = &NonTerminal> { self.symbols.iter().filter_map(|s| s.non_terminal()).skip(1) } pub fn non_terminal_iter_mut(&mut self) -> impl Iterator<Item = &mut NonTerminal> { self.symbols .iter_mut() .filter_map(|s| s.mut_non_terminal()) .skip(1) } pub fn get_symbol_index(&self, name: &str) -> Option<usize> { self.symbol_table.get(name).cloned() } pub fn add_non_terminal(&mut self, name: &str) -> usize { let idx = self.symbols.len(); self.symbols .push(Symbol::NonTerminal(NonTerminal::new(idx, name.to_string()))); self.symbol_table.insert(name.to_string(), idx); idx } pub fn add_terminal(&mut self, name: String) -> usize { let idx = self.symbols.len(); self.symbols.push(Symbol::Terminal(name.clone())); self.symbol_table.insert(name, idx); idx } pub fn add_production(&mut self, left: usize, right: Vec<usize>) { self.symbols[left] .mut_non_terminal() .unwrap() .productions .push(right); } pub fn get_symbol_name(&self, index: usize) -> &str { match &self.symbols[index] { Symbol::NonTerminal(e) => e.name.as_str(), Symbol::Terminal(e) => e.as_str(), } } pub fn get_symbol_prime_name(&self, mut name: String) -> String { while self.symbol_table.contains_key(&name) { name.push('\''); } name } pub fn invalidate_nullable_first_follow(&mut self) { self.valid_nullable_first_follow = false; self.reset_nullable_first_follow(); } pub fn is_nullable_first_follow_valid(&self) -> bool { self.valid_nullable_first_follow } pub fn validate_nullable_first_follow(&mut self) { self.valid_nullable_first_follow = true; }
}
pub fn production_to_vec_str(&self, production: &Vec<usize>) -> Vec<&str> { production .iter() .map(|idx| self.get_symbol_name(*idx)) .collect() }
function_block-full_function
[ { "content": "#[wasm_bindgen]\n\npub fn wasm_grammar_to_output(json: &str) -> String {\n\n let args: WasmArgs = serde_json::from_str(json).unwrap();\n\n let result = grammar_to_output(&args.grammar, &args.actions, &args.outputs);\n\n serde_json::to_string(&result).unwrap()\n\n}\n\n\n\n#[derive(Clone, C...
Rust
src/services/paste.rs
zeroqn/pastebin-actix
269693f99be1d9a7cc010bf7e4392f61909659b8
use std::time::SystemTime; use actix::prelude::*; use diesel::{self, prelude::*}; use crate::common::error::ServerError; use crate::models::{ executor::DatabaseExecutor as DbExecutor, paste::{NewPaste, Paste}, }; pub struct CreatePasteMsg { pub title: String, pub body: String, pub created_at: SystemTime, } impl Message for CreatePasteMsg { type Result = Result<Paste, ServerError>; } impl Handler<CreatePasteMsg> for DbExecutor { type Result = Result<Paste, ServerError>; fn handle(&mut self, msg: CreatePasteMsg, _: &mut Self::Context) -> Self::Result { use crate::models::schema::pastes::dsl::*; let new_paste = NewPaste { title: &msg.title, body: &msg.body, created_at: &msg.created_at, modified_at: &msg.created_at, }; diesel::insert_into(pastes) .values(&new_paste) .get_result(&self.0.get().map_err(ServerError::R2d2)?) .map_err(ServerError::Database) } } pub struct UpdatePasteMsg { pub id: i64, pub title: String, pub body: String, pub modified_at: SystemTime, } impl Message for UpdatePasteMsg { type Result = Result<Paste, ServerError>; } impl Handler<UpdatePasteMsg> for DbExecutor { type Result = Result<Paste, ServerError>; fn handle(&mut self, msg: UpdatePasteMsg, _: &mut Self::Context) -> Self::Result { use crate::models::schema::pastes::dsl::*; diesel::update(pastes.find(msg.id)) .set(( title.eq(msg.title), body.eq(msg.body), modified_at.eq(msg.modified_at), )).get_result(&self.0.get().map_err(ServerError::R2d2)?) .map_err(ServerError::Database) } } pub struct GetPasteByIdMsg { pub id: i64, } impl Message for GetPasteByIdMsg { type Result = Result<Paste, ServerError>; } impl Handler<GetPasteByIdMsg> for DbExecutor { type Result = Result<Paste, ServerError>; fn handle(&mut self, msg: GetPasteByIdMsg, _: &mut Self::Context) -> Self::Result { use crate::models::schema::pastes::dsl::*; pastes .find(msg.id) .get_result(&self.0.get().map_err(ServerError::R2d2)?) .map_err(ServerError::Database) } } #[derive(Debug)] pub enum Item { Title, Body, CreatedAt, ModifiedAt, } #[derive(Debug)] pub enum Order { Ascend, Decrease, } #[derive(Debug)] pub enum CmpOp { GT, EQ, LT, GE, LE, } #[derive(Debug)] pub struct Orderby { pub item: Item, pub order: Order, } #[derive(Debug)] pub struct TimeCondition { pub op: CmpOp, pub time: SystemTime, } macro_rules! cmp { ($query:expr, $column:expr, $cmp:expr, $cond:expr) => { match $cmp { CmpOp::GT => $query.filter($column.gt($cond)), CmpOp::EQ => $query.filter($column.eq($cond)), CmpOp::LT => $query.filter($column.lt($cond)), CmpOp::GE => $query.filter($column.ge($cond)), CmpOp::LE => $query.filter($column.le($cond)), } }; } macro_rules! order { ($query:expr, $column:expr, $order:expr) => { match $order { Order::Ascend => $query.order($column.asc()), Order::Decrease => $query.order($column.desc()), } }; } macro_rules! orderby { ($query:expr, $column:expr, $order:expr) => { match $column { Item::Title => order!($query, title, $order), Item::Body => order!($query, body, $order), Item::CreatedAt => order!($query, created_at, $order), Item::ModifiedAt => order!($query, modified_at, $order), } }; } pub struct GetPasteListMsg { pub title_pat: Option<String>, pub body_pat: Option<String>, pub created_at: Option<TimeCondition>, pub modified_at: Option<TimeCondition>, pub orderby_list: Option<Vec<Orderby>>, pub limit: Option<i64>, pub offset: Option<i64>, } impl Default for GetPasteListMsg { fn default() -> Self { GetPasteListMsg { title_pat: None, body_pat: None, created_at: None, modified_at: None, orderby_list: None, limit: Some(20), offset: Some(0), } } } impl Message for GetPasteListMsg { type Result = Result<Vec<Paste>, ServerError>; } impl Handler<GetPasteListMsg> for DbExecutor { type Result = Result<Vec<Paste>, ServerError>; fn handle(&mut self, msg: GetPasteListMsg, _: &mut Self::Context) -> Self::Result { use crate::models::schema::pastes::dsl::*; let mut query = pastes.into_boxed(); if let Some(title_pat) = msg.title_pat { query = query.filter(title.ilike(title_pat.to_owned() + "%")); } if let Some(body_pat) = msg.body_pat { query = query.filter(body.ilike(body_pat.to_owned() + "%")); } if let Some(cond) = msg.created_at { query = cmp!(query, created_at, cond.op, cond.time); } if let Some(cond) = msg.modified_at { query = cmp!(query, modified_at, cond.op, cond.time); } if let Some(orderby_list) = msg.orderby_list { for orderby in orderby_list { query = orderby!(query, orderby.item, orderby.order); } } if let Some(limit) = msg.limit { query = query.limit(limit); } if let Some(offset) = msg.offset { query = query.offset(offset); } query .load::<Paste>(&self.0.get().map_err(ServerError::R2d2)?) .map_err(ServerError::Database) } } pub struct DelPasteByIdMsg { pub id: i64, } impl Message for DelPasteByIdMsg { type Result = Result<usize, ServerError>; } impl Handler<DelPasteByIdMsg> for DbExecutor { type Result = Result<usize, ServerError>; fn handle(&mut self, msg: DelPasteByIdMsg, _: &mut Self::Context) -> Self::Result { use crate::models::schema::pastes::dsl::*; diesel::delete(pastes) .filter(id.eq(msg.id)) .execute(&self.0.get().map_err(ServerError::R2d2)?) .map_err(ServerError::Database) } }
use std::time::SystemTime; use actix::prelude::*; use diesel::{self, prelude::*}; use crate::common::error::ServerError; use crate::models::{ executor::DatabaseExecutor as DbExecutor, paste::{NewPaste, Paste}, }; pub struct CreatePasteMsg { pub title: String, pub body: String, pub created_at: SystemTime, } impl Message for CreatePasteMsg { type Result = Result<Paste, ServerError>; } impl Handler<CreatePasteMsg> for DbExecutor { type Result = Result<Paste, ServerError>; fn handle(&mut self, msg: CreatePasteMsg, _: &mut Self::Context) -> Self::Result { use crate::models::schema::pastes::dsl::*; let new_paste = NewPaste { title: &msg.title, body: &msg.body, created_at: &msg.created_at, modified_at: &msg.created_at, }; diesel::insert_into(pastes) .values(&new_paste) .get_result(&self.0.get().map_err(ServerError::R2d2)?) .map_err(ServerError::Database) } } pub struct UpdatePasteMsg { pub id: i64, pub title: String, pub body: String, pub modified_at: SystemTime, } impl Message for UpdatePasteMsg { type Result = Result<Paste, ServerError>; } impl Handler<UpdatePasteMsg> for DbExecutor { type Result = Result<Paste, ServerError>; fn handle(&mut self, msg: UpdatePasteMsg, _: &mut Self::Context) -> Self::Result { use crate::models::schema::pastes::dsl::*; diesel::update(pastes.find(msg.id)) .set(( title.eq(msg.title), body.eq(msg.body), modified_at.eq(msg.modified_at), )).get_result(&self.0.get().map_err(ServerError::R2d2)?) .map_err(ServerError::Database) } } pub struct GetPasteByIdMsg { pub id: i64, } impl Message for GetPasteByIdMsg { type Result = Result<Paste, ServerError>; } impl Handler<GetPasteByIdMsg> for DbExecutor { type Result = Result<Paste, ServerError>; fn handle(&mut self, msg: GetPasteByIdMsg, _: &mut Self::Context) -> Self::Result { use crate::models::schema::pastes::dsl::*; pastes .find(msg.id) .get_result(&self.0.get().map_err(ServerError::R2d2)?) .map_err(ServerError::Database) } } #[derive(Debug)] pub enum Item { Title, Body, CreatedAt, ModifiedAt, } #[derive(Debug)] pub enum Order { Ascend, Decrease, } #[derive(Debug)] pub enum CmpOp { GT, EQ, LT, GE, LE, } #[derive(Debug)] pub struct Orderby { pub item: Item, pub order: Order, } #[derive(Debug)] pub struct TimeCondition { pub op: CmpOp, pub time: SystemTime, } macro_rules! cmp { ($query:expr, $column:expr, $cmp:expr, $cond:expr) => { match $cmp { CmpOp::GT => $query.filter($column.gt($cond)), CmpOp::EQ => $query.filter($column.eq($cond)), CmpOp::LT => $query.filter($column.lt($cond)), CmpOp::GE => $query.filter($column.ge($cond)), CmpOp::LE => $query.filter($column.le($cond)), } }; } macro_rules! order { ($query:expr, $column:expr, $order:expr) => { match $order { Order::Ascend => $query.order($column.asc()), Order::Decrease => $query.order($column.desc()), } }; } macro_rules! orderby { ($query:expr, $column:expr, $order:expr) => { match $column { Item::Title => order!($query, title, $order), Item::Body => order!($query, body, $order), Item::CreatedAt => order!($query, created_at, $order), Item::ModifiedAt => order!($query, modified_at, $order), } }; } pub struct GetPasteListMsg { pub title_pat: Option<String>, pub body_pat: Option<String>, pub created_at: Option<TimeCondition>, pub modified_at: Option<TimeCondition>, pub orderby_list: Option<Vec<Orderby>>, pub limit: Option<i64>, pub offset: Option<i64>, } impl Default for GetPasteListMsg { fn default() -> Self { GetPasteListMsg { title_pat: None, body_pat: None, created_at: None, modified_at: None, orderby_list: None, limit: Some(20), offset: Some(0), } } } impl Message for GetPasteListMsg { type Result = Result<Vec<Paste>, ServerError>; } impl Handler<GetPasteListMsg> for DbExecutor { type Result = Result<Vec<Paste>, ServerError>;
} pub struct DelPasteByIdMsg { pub id: i64, } impl Message for DelPasteByIdMsg { type Result = Result<usize, ServerError>; } impl Handler<DelPasteByIdMsg> for DbExecutor { type Result = Result<usize, ServerError>; fn handle(&mut self, msg: DelPasteByIdMsg, _: &mut Self::Context) -> Self::Result { use crate::models::schema::pastes::dsl::*; diesel::delete(pastes) .filter(id.eq(msg.id)) .execute(&self.0.get().map_err(ServerError::R2d2)?) .map_err(ServerError::Database) } }
fn handle(&mut self, msg: GetPasteListMsg, _: &mut Self::Context) -> Self::Result { use crate::models::schema::pastes::dsl::*; let mut query = pastes.into_boxed(); if let Some(title_pat) = msg.title_pat { query = query.filter(title.ilike(title_pat.to_owned() + "%")); } if let Some(body_pat) = msg.body_pat { query = query.filter(body.ilike(body_pat.to_owned() + "%")); } if let Some(cond) = msg.created_at { query = cmp!(query, created_at, cond.op, cond.time); } if let Some(cond) = msg.modified_at { query = cmp!(query, modified_at, cond.op, cond.time); } if let Some(orderby_list) = msg.orderby_list { for orderby in orderby_list { query = orderby!(query, orderby.item, orderby.order); } } if let Some(limit) = msg.limit { query = query.limit(limit); } if let Some(offset) = msg.offset { query = query.offset(offset); } query .load::<Paste>(&self.0.get().map_err(ServerError::R2d2)?) .map_err(ServerError::Database) }
function_block-full_function
[ { "content": "pub fn get_paste_list(\n\n (req, conds): (HttpRequest<State>, Query<GetPasteListConds>),\n\n) -> FutureJsonResponse {\n\n let db_chan = req.state().db_chan.clone();\n\n let created_at = conds\n\n .cmp_created_at\n\n .to_owned()\n\n .map_or(Ok(None), |cmp_created_at| {...
Rust
day-21/src/main.rs
Shriram-Balaji/rust-advent-of-code-2020
a1002a2f50d12eff744f7cb0db1f7271b9020c3a
#[macro_use] extern crate lazy_static; use regex::Regex; use std::{ collections::{BTreeMap, HashMap, HashSet}, env, fs, }; #[derive(Debug)] struct Food<'a> { ingredients: HashSet<&'a str>, allergens: Vec<&'a str>, } fn process_food(food: &str) -> Food { lazy_static! { static ref FOOD_REGEX: Regex = Regex::new(r"(\w.*)\(contains\s+(\w+.*)\)").unwrap(); } let food = food.trim(); let captures = match FOOD_REGEX.captures(food) { Some(captures) => captures, None => panic!("Invalid food item {}", food), }; let ingredients: HashSet<&str> = captures .get(1) .unwrap() .as_str() .split_ascii_whitespace() .collect(); let allergens: Vec<&str> = captures.get(2).unwrap().as_str().split(", ").collect(); Food { ingredients, allergens, } } struct Processed<'a> { ingredients_without_allergens: HashMap<&'a str, u32>, ingredients_with_allergens: Vec<&'a str>, } fn process_food_items(input: &str) -> Processed { let lines: Vec<&str> = input .lines() .filter(|x| !x.is_empty()) .map(|x| x.trim()) .collect(); let mut foods: Vec<Food> = lines.iter().map(|x| process_food(*x)).collect(); let mut unknown_allergens: HashSet<&str> = foods .iter() .map(|f| f.allergens.iter()) .flatten() .cloned() .collect(); let mut known_allergens: BTreeMap<&str, &str> = BTreeMap::new(); 'outer: loop { for allergen in &unknown_allergens.clone() { let foods_with_allergen: Vec<&Food> = foods .iter() .filter(|f| f.allergens.contains(&allergen)) .collect(); let init: HashSet<&str> = foods_with_allergen[0].ingredients.clone(); let candidate_ingredients: HashSet<&str> = foods_with_allergen.iter().fold(init.to_owned(), |i, f| { i.intersection(&f.ingredients).cloned().collect() }); if candidate_ingredients.len() == 1 { let ingredient = candidate_ingredients.iter().next().unwrap(); for f in foods.iter_mut() { f.ingredients.remove(ingredient); } known_allergens.insert(allergen, ingredient); unknown_allergens.remove(allergen); } if unknown_allergens.is_empty() { break 'outer; } } } let ingredients_without_allergens: HashMap<&str, u32> = foods .iter() .map(|f| f.ingredients.clone()) .flatten() .fold(HashMap::new(), |mut acc, value| { acc.entry(value).and_modify(|e| *e += 1).or_insert(1); acc }); let danger_list: Vec<&str> = known_allergens.values().cloned().collect(); Processed { ingredients_with_allergens: danger_list, ingredients_without_allergens, } } fn main() { let args: Vec<String> = env::args().collect::<Vec<String>>(); let filepath = args.get(1).expect("Input filepath cannot be empty!"); let input = fs::read_to_string(filepath).expect("Something went wrong while reading the input file"); let Processed { ingredients_without_allergens, ingredients_with_allergens, } = process_food_items(&input); let sum: u32 = ingredients_without_allergens .values() .map(|x| x.to_owned()) .sum(); println!("Sum of ingredients without allergens: {}", sum); println!( "Canonical Dangerous List: {:?}", ingredients_with_allergens.join(",") ); } #[cfg(test)] mod tests { use super::*; #[test] fn should_process_food() { process_food("mxmxvkd kfcds sqjhc nhms (contains dairy, fish)"); } #[test] fn should_process_food_items_list() { let input = r#"mxmxvkd kfcds sqjhc nhms (contains dairy, fish) trh fvjkl sbzzf mxmxvkd (contains dairy) sqjhc fvjkl (contains soy) sqjhc mxmxvkd sbzzf (contains fish)"#; process_food_items(input); } }
#[macro_use] extern crate lazy_static; use regex::Regex; use std::{ collections::{BTreeMap, HashMap, HashSet}, env, fs, }; #[derive(Debug)] struct Food<'a> { ingredients: HashSet<&'a str>, allergens: Vec<&'a str>, } fn process_food(food: &str) -> Food { lazy_static! { static ref FOOD_REGEX: Regex = Regex::new(r"(\w.*)\(contains\s+(\w+.*)\)").unwrap(); } let food = food.trim(); let captures = match FOOD_REGEX.captures(food) { Some(captures) => captures, None => panic!("Invalid food item {}", food), }; let ingredients: HashSet<&str> = captures .get(1) .unwrap() .as_str() .split_ascii_whitespace() .collect(); let allergens: Vec<&str> = captures.get(2).unwrap().as_str().split(", ").collect(); Food { ingredients, allergens, } } struct Processed<'a> { ingredients_without_allergens: HashMap<&'a str, u32>, ingredients_with_allergens: Vec<&'a str>, } fn process_food_items(input: &str) -> Processed { let lines: Vec<&str> = input .lines() .filter(|x| !x.is_empty()) .map(|x| x.trim()) .collect(); let mut foods: Vec<Food> = lines.iter().map(|x| process_food(*x)).collect(); let mut unknown_allergens: HashSet<&str> = foods .iter() .map(|f| f.allergens.iter()) .flatten() .cloned() .collect(); let mut known_allergens: BTreeMap<&str, &str> = BTreeMap::new(); 'outer: loop { for allergen in &unknown_allergens.clone() { let foods_with_allergen: Vec<&Food> = foods .iter() .filter(|f| f.allergens.contains(&allergen)) .collect(); let init: HashSet<&str> = foods_with_allergen[0].ingredients.clone(); let candidate_ingredients: HashSet<&str> = foods_with_allergen.iter().fold(init.to_owned(), |i, f| { i.intersection(&f.ingredients).cloned().collect() }); if candidate_ingredients.len() == 1 { let ingredient = candidate_ingredients.iter().next().unwrap(); for f in foods.iter_mut() { f.ingredients.remove(ingredient); } known_allergens.insert(allergen, ingredient); unknown_allergens.remove(allergen); } if unknown_allergens.is_empty() { break 'outer; } } } let ingredients_without_allergens: HashMap<&str, u32> = foods .iter() .map(|f| f.ingredients.clone()) .flatten() .fold(HashMap::new(), |mut acc, value| { acc.entry(value).and_modify(|e| *e += 1).or_insert(1); acc }); let danger_list: Vec<&str> = known_allergens.values().cloned().collect(); Processed { ingredients_with_allergens: danger_list, ingredients_without_allergens, } } fn main() { let args: Vec<String> = env::args().collect::<Vec<String>>(); let filepath = args.get(1).expect("Input filepath cannot be empty!"); let input = fs::read_to_string(filepath).expect("Something went wrong while reading the input file"); let Processed { ingredients_without_allergens, ingredients_with_allergens, } = process_food_items(&input); let sum: u32 = ingredients_without_allergens .values() .map(|x| x.to_owned()) .sum(); println!("Sum of ingredients without allergens: {}", sum); println!( "Canonical Dangerous List: {:?}", ingredients_with_allergens.join(",") ); } #[cfg(test)] mod tests { use super::*; #[test] fn should_process_food() { process_food("mxmxvkd kfcds sqjhc nhms (contains dairy, fish)"); } #[test]
}
fn should_process_food_items_list() { let input = r#"mxmxvkd kfcds sqjhc nhms (contains dairy, fish) trh fvjkl sbzzf mxmxvkd (contains dairy) sqjhc fvjkl (contains soy) sqjhc mxmxvkd sbzzf (contains fish)"#; process_food_items(input); }
function_block-full_function
[ { "content": "fn process(input: &str) -> (u64, Vec<&str>) {\n\n let notes: Vec<&str> = input.split('\\n').collect();\n\n let timestamp = notes[0].parse::<u64>().expect(\"Invalid timestamp\");\n\n let bus_ids: Vec<&str> = notes[1].split(',').collect();\n\n (timestamp, bus_ids)\n\n}\n\n\n", "file_...
Rust
src/macos/aarch64/vcpu.rs
RWTH-OS/uhyve
14e8ea129a82910c13e5a12b7893cd1badb5f380
#![allow(non_snake_case)] #![allow(clippy::identity_op)] use crate::aarch64::{ mair, tcr_size, MT_DEVICE_nGnRE, MT_DEVICE_nGnRnE, MT_DEVICE_GRE, MT_NORMAL, MT_NORMAL_NC, PSR, TCR_FLAGS, TCR_TG1_4K, VA_BITS, }; use crate::consts::*; use crate::vm::HypervisorResult; use crate::vm::SysExit; use crate::vm::VcpuStopReason; use crate::vm::VirtualCPU; use log::debug; use std::ffi::OsString; use std::path::Path; use std::path::PathBuf; use xhypervisor; use xhypervisor::{Register, SystemRegister, VirtualCpuExitReason}; pub struct UhyveCPU { id: u32, kernel_path: PathBuf, args: Vec<OsString>, vcpu: xhypervisor::VirtualCpu, vm_start: usize, } impl UhyveCPU { pub fn new(id: u32, kernel_path: PathBuf, args: Vec<OsString>, vm_start: usize) -> UhyveCPU { Self { id, kernel_path, args, vcpu: xhypervisor::VirtualCpu::new().unwrap(), vm_start, } } } impl VirtualCPU for UhyveCPU { fn init(&mut self, entry_point: u64) -> HypervisorResult<()> { debug!("Initialize VirtualCPU"); /* pstate = all interrupts masked */ let pstate: PSR = PSR::D_BIT | PSR::A_BIT | PSR::I_BIT | PSR::F_BIT | PSR::MODE_EL1H; self.vcpu.write_register(Register::CPSR, pstate.bits())?; self.vcpu.write_register(Register::PC, entry_point)?; self.vcpu.write_register(Register::X0, BOOT_INFO_ADDR)?; /* * Setup memory attribute type tables * * Memory regioin attributes for LPAE: * * n = AttrIndx[2:0] * n MAIR * DEVICE_nGnRnE 000 00000000 (0x00) * DEVICE_nGnRE 001 00000100 (0x04) * DEVICE_GRE 010 00001100 (0x0c) * NORMAL_NC 011 01000100 (0x44) * NORMAL 100 11111111 (0xff) */ let mair_el1 = mair(0x00, MT_DEVICE_nGnRnE) | mair(0x04, MT_DEVICE_nGnRE) | mair(0x0c, MT_DEVICE_GRE) | mair(0x44, MT_NORMAL_NC) | mair(0xff, MT_NORMAL); self.vcpu .write_system_register(SystemRegister::MAIR_EL1, mair_el1)?; /* * Setup translation control register (TCR) */ let aa64mmfr0_el1 = self .vcpu .read_system_register(SystemRegister::ID_AA64MMFR0_EL1)?; let tcr = ((aa64mmfr0_el1 & 0xF) << 32) | (tcr_size(VA_BITS) | TCR_TG1_4K | TCR_FLAGS); let tcr_el1 = (tcr & 0xFFFFFFF0FFFFFFFFu64) | ((aa64mmfr0_el1 & 0xFu64) << 32); self.vcpu .write_system_register(SystemRegister::TCR_EL1, tcr_el1)?; /* * Enable FP/ASIMD in Architectural Feature Access Control Register, */ let cpacr_el1 = self.vcpu.read_system_register(SystemRegister::CPACR_EL1)? | (3 << 20); self.vcpu .write_system_register(SystemRegister::CPACR_EL1, cpacr_el1)?; /* * Reset debug control register */ self.vcpu .write_system_register(SystemRegister::MDSCR_EL1, 0)?; self.vcpu .write_system_register(SystemRegister::TTBR1_EL1, 0)?; self.vcpu .write_system_register(SystemRegister::TTBR0_EL1, BOOT_PGT)?; /* * Prepare system control register (SCTRL) * Todo: - Verify if all of these bits actually should be explicitly set - Link origin of this documentation and check to which instruction set versions it applies (if applicable) - Fill in the missing Documentation for some of the bits and verify if we care about them or if loading and not setting them would be the appropriate action. */ let sctrl_el1: u64 = 0 | (1 << 26) /* UCI Enables EL0 access in AArch64 for DC CVAU, DC CIVAC, DC CVAC and IC IVAU instructions */ | (0 << 25) /* EE Explicit data accesses at EL1 and Stage 1 translation table walks at EL1 & EL0 are little-endian */ | (0 << 24) /* EOE Explicit data accesses at EL0 are little-endian */ | (1 << 23) | (1 << 22) | (1 << 20) | (0 << 19) /* WXN Regions with write permission are not forced to XN */ | (1 << 18) /* nTWE WFE instructions are executed as normal */ | (0 << 17) | (1 << 16) /* nTWI WFI instructions are executed as normal */ | (1 << 15) /* UCT Enables EL0 access in AArch64 to the CTR_EL0 register */ | (1 << 14) /* DZE Execution of the DC ZVA instruction is allowed at EL0 */ | (0 << 13) | (1 << 12) /* I Instruction caches enabled at EL0 and EL1 */ | (1 << 11) | (0 << 10) | (0 << 9) /* UMA Disable access to the interrupt masks from EL0 */ | (1 << 8) /* SED The SETEND instruction is available */ | (0 << 7) /* ITD The IT instruction functionality is available */ | (0 << 6) /* THEE ThumbEE is disabled */ | (0 << 5) /* CP15BEN CP15 barrier operations disabled */ | (1 << 4) /* SA0 Stack Alignment check for EL0 enabled */ | (1 << 3) /* SA Stack Alignment check enabled */ | (1 << 2) /* C Data and unified enabled */ | (0 << 1) /* A Alignment fault checking disabled */ | (1 << 0) /* M MMU enable */ ; self.vcpu .write_system_register(SystemRegister::SCTLR_EL1, sctrl_el1)?; Ok(()) } fn kernel_path(&self) -> &Path { self.kernel_path.as_path() } fn args(&self) -> &[OsString] { self.args.as_slice() } fn host_address(&self, addr: usize) -> usize { addr + self.vm_start } fn virt_to_phys(&self, _addr: usize) -> usize { 0 } fn r#continue(&mut self) -> HypervisorResult<VcpuStopReason> { loop { self.vcpu.run()?; let reason = self.vcpu.exit_reason(); match reason { VirtualCpuExitReason::Exception { exception } => { let ec = (exception.syndrome >> 26) & 0x3f; if ec == 0b100100u64 || ec == 0b100101u64 { let addr: u16 = exception.physical_address.try_into().unwrap(); let pc = self.vcpu.read_register(Register::PC)?; match addr { UHYVE_UART_PORT => { let x8 = (self.vcpu.read_register(Register::X8)? & 0xFF) as u8; self.uart(&[x8]).unwrap(); self.vcpu.write_register(Register::PC, pc + 4)?; } UHYVE_PORT_EXIT => { let data_addr = self.vcpu.read_register(Register::X8)?; let sysexit = unsafe { &*(self.host_address(data_addr as usize) as *const SysExit) }; return Ok(VcpuStopReason::Exit(self.exit(sysexit))); } _ => { error!("Unable to handle exception {:?}", exception); self.print_registers(); return Err(xhypervisor::Error::Error); } } } else { error!("Unsupported exception class: 0x{:x}", ec); self.print_registers(); return Err(xhypervisor::Error::Error); } } _ => { error!("Unknown exit reason: {:?}", reason); return Err(xhypervisor::Error::Error); } } } } fn run(&mut self) -> HypervisorResult<Option<i32>> { match self.r#continue()? { VcpuStopReason::Debug(_) => { unreachable!("reached debug exit without running in debugging mode") } VcpuStopReason::Exit(code) => Ok(Some(code)), VcpuStopReason::Kick => Ok(None), } } fn print_registers(&self) { println!("\nDump state of CPU {}", self.id); let pc = self.vcpu.read_register(Register::PC).unwrap(); let cpsr = self.vcpu.read_register(Register::CPSR).unwrap(); let sp = self .vcpu .read_system_register(SystemRegister::SP_EL1) .unwrap(); let sctlr = self .vcpu .read_system_register(SystemRegister::SCTLR_EL1) .unwrap(); let ttbr0 = self .vcpu .read_system_register(SystemRegister::TTBR0_EL1) .unwrap(); let lr = self.vcpu.read_register(Register::LR).unwrap(); let x0 = self.vcpu.read_register(Register::X0).unwrap(); let x1 = self.vcpu.read_register(Register::X1).unwrap(); let x2 = self.vcpu.read_register(Register::X2).unwrap(); let x3 = self.vcpu.read_register(Register::X3).unwrap(); let x4 = self.vcpu.read_register(Register::X4).unwrap(); let x5 = self.vcpu.read_register(Register::X5).unwrap(); let x6 = self.vcpu.read_register(Register::X6).unwrap(); let x7 = self.vcpu.read_register(Register::X7).unwrap(); let x8 = self.vcpu.read_register(Register::X8).unwrap(); let x9 = self.vcpu.read_register(Register::X9).unwrap(); let x10 = self.vcpu.read_register(Register::X10).unwrap(); let x11 = self.vcpu.read_register(Register::X11).unwrap(); let x12 = self.vcpu.read_register(Register::X12).unwrap(); let x13 = self.vcpu.read_register(Register::X13).unwrap(); let x14 = self.vcpu.read_register(Register::X14).unwrap(); let x15 = self.vcpu.read_register(Register::X15).unwrap(); let x16 = self.vcpu.read_register(Register::X16).unwrap(); let x17 = self.vcpu.read_register(Register::X17).unwrap(); let x18 = self.vcpu.read_register(Register::X18).unwrap(); let x19 = self.vcpu.read_register(Register::X19).unwrap(); let x20 = self.vcpu.read_register(Register::X20).unwrap(); let x21 = self.vcpu.read_register(Register::X21).unwrap(); let x22 = self.vcpu.read_register(Register::X22).unwrap(); let x23 = self.vcpu.read_register(Register::X23).unwrap(); let x24 = self.vcpu.read_register(Register::X24).unwrap(); let x25 = self.vcpu.read_register(Register::X25).unwrap(); let x26 = self.vcpu.read_register(Register::X26).unwrap(); let x27 = self.vcpu.read_register(Register::X27).unwrap(); let x28 = self.vcpu.read_register(Register::X28).unwrap(); let x29 = self.vcpu.read_register(Register::X29).unwrap(); println!("\nRegisters:"); println!("----------"); println!( "PC : {:016x} LR : {:016x} CPSR : {:016x}\n\ SP : {:016x} SCTLR : {:016x} TTBR0 : {:016x}", pc, lr, cpsr, sp, sctlr, ttbr0, ); print!( "x0 : {:016x} x1 : {:016x} x2 : {:016x}\n\ x3 : {:016x} x4 : {:016x} x5 : {:016x}\n\ x6 : {:016x} x7 : {:016x} x8 : {:016x}\n\ x9 : {:016x} x10 : {:016x} x11 : {:016x}\n\ x12 : {:016x} x13 : {:016x} x14 : {:016x}\n\ x15 : {:016x} x16 : {:016x} x17 : {:016x}\n\ x18 : {:016x} x19 : {:016x} x20 : {:016x}\n\ x21 : {:016x} x22 : {:016x} x23 : {:016x}\n\ x24 : {:016x} x25 : {:016x} x26 : {:016x}\n\ x27 : {:016x} x28 : {:016x} x29 : {:016x}\n", x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16, x17, x18, x19, x20, x21, x22, x23, x24, x25, x26, x27, x28, x29, ); } } impl Drop for UhyveCPU { fn drop(&mut self) { debug!("Drop virtual CPU {}", self.id); let _ = self.vcpu.destroy(); } }
#![allow(non_snake_case)] #![allow(clippy::identity_op)] use crate::aarch64::{ mair, tcr_size, MT_DEVICE_nGnRE, MT_DEVICE_nGnRnE, MT_DEVICE_GRE, MT_NORMAL, MT_NORMAL_NC, PSR, TCR_FLAGS, TCR_TG1_4K, VA_BITS, }; use crate::consts::*; use crate::vm::HypervisorResult; use crate::vm::SysExit; use crate::vm::VcpuStopReason; use crate::vm::VirtualCPU; use log::debug; use std::ffi::OsString; use std::path::Path; use std::path::PathBuf; use xhypervisor; use xhypervisor::{Register, SystemRegister, VirtualCpuExitReason}; pub struct UhyveCPU { id: u32, kernel_path: PathBuf, args: Vec<OsString>, vcpu: xhypervisor::VirtualCpu, vm_start: usize, } impl UhyveCPU {
} impl VirtualCPU for UhyveCPU { fn init(&mut self, entry_point: u64) -> HypervisorResult<()> { debug!("Initialize VirtualCPU"); /* pstate = all interrupts masked */ let pstate: PSR = PSR::D_BIT | PSR::A_BIT | PSR::I_BIT | PSR::F_BIT | PSR::MODE_EL1H; self.vcpu.write_register(Register::CPSR, pstate.bits())?; self.vcpu.write_register(Register::PC, entry_point)?; self.vcpu.write_register(Register::X0, BOOT_INFO_ADDR)?; /* * Setup memory attribute type tables * * Memory regioin attributes for LPAE: * * n = AttrIndx[2:0] * n MAIR * DEVICE_nGnRnE 000 00000000 (0x00) * DEVICE_nGnRE 001 00000100 (0x04) * DEVICE_GRE 010 00001100 (0x0c) * NORMAL_NC 011 01000100 (0x44) * NORMAL 100 11111111 (0xff) */ let mair_el1 = mair(0x00, MT_DEVICE_nGnRnE) | mair(0x04, MT_DEVICE_nGnRE) | mair(0x0c, MT_DEVICE_GRE) | mair(0x44, MT_NORMAL_NC) | mair(0xff, MT_NORMAL); self.vcpu .write_system_register(SystemRegister::MAIR_EL1, mair_el1)?; /* * Setup translation control register (TCR) */ let aa64mmfr0_el1 = self .vcpu .read_system_register(SystemRegister::ID_AA64MMFR0_EL1)?; let tcr = ((aa64mmfr0_el1 & 0xF) << 32) | (tcr_size(VA_BITS) | TCR_TG1_4K | TCR_FLAGS); let tcr_el1 = (tcr & 0xFFFFFFF0FFFFFFFFu64) | ((aa64mmfr0_el1 & 0xFu64) << 32); self.vcpu .write_system_register(SystemRegister::TCR_EL1, tcr_el1)?; /* * Enable FP/ASIMD in Architectural Feature Access Control Register, */ let cpacr_el1 = self.vcpu.read_system_register(SystemRegister::CPACR_EL1)? | (3 << 20); self.vcpu .write_system_register(SystemRegister::CPACR_EL1, cpacr_el1)?; /* * Reset debug control register */ self.vcpu .write_system_register(SystemRegister::MDSCR_EL1, 0)?; self.vcpu .write_system_register(SystemRegister::TTBR1_EL1, 0)?; self.vcpu .write_system_register(SystemRegister::TTBR0_EL1, BOOT_PGT)?; /* * Prepare system control register (SCTRL) * Todo: - Verify if all of these bits actually should be explicitly set - Link origin of this documentation and check to which instruction set versions it applies (if applicable) - Fill in the missing Documentation for some of the bits and verify if we care about them or if loading and not setting them would be the appropriate action. */ let sctrl_el1: u64 = 0 | (1 << 26) /* UCI Enables EL0 access in AArch64 for DC CVAU, DC CIVAC, DC CVAC and IC IVAU instructions */ | (0 << 25) /* EE Explicit data accesses at EL1 and Stage 1 translation table walks at EL1 & EL0 are little-endian */ | (0 << 24) /* EOE Explicit data accesses at EL0 are little-endian */ | (1 << 23) | (1 << 22) | (1 << 20) | (0 << 19) /* WXN Regions with write permission are not forced to XN */ | (1 << 18) /* nTWE WFE instructions are executed as normal */ | (0 << 17) | (1 << 16) /* nTWI WFI instructions are executed as normal */ | (1 << 15) /* UCT Enables EL0 access in AArch64 to the CTR_EL0 register */ | (1 << 14) /* DZE Execution of the DC ZVA instruction is allowed at EL0 */ | (0 << 13) | (1 << 12) /* I Instruction caches enabled at EL0 and EL1 */ | (1 << 11) | (0 << 10) | (0 << 9) /* UMA Disable access to the interrupt masks from EL0 */ | (1 << 8) /* SED The SETEND instruction is available */ | (0 << 7) /* ITD The IT instruction functionality is available */ | (0 << 6) /* THEE ThumbEE is disabled */ | (0 << 5) /* CP15BEN CP15 barrier operations disabled */ | (1 << 4) /* SA0 Stack Alignment check for EL0 enabled */ | (1 << 3) /* SA Stack Alignment check enabled */ | (1 << 2) /* C Data and unified enabled */ | (0 << 1) /* A Alignment fault checking disabled */ | (1 << 0) /* M MMU enable */ ; self.vcpu .write_system_register(SystemRegister::SCTLR_EL1, sctrl_el1)?; Ok(()) } fn kernel_path(&self) -> &Path { self.kernel_path.as_path() } fn args(&self) -> &[OsString] { self.args.as_slice() } fn host_address(&self, addr: usize) -> usize { addr + self.vm_start } fn virt_to_phys(&self, _addr: usize) -> usize { 0 } fn r#continue(&mut self) -> HypervisorResult<VcpuStopReason> { loop { self.vcpu.run()?; let reason = self.vcpu.exit_reason(); match reason { VirtualCpuExitReason::Exception { exception } => { let ec = (exception.syndrome >> 26) & 0x3f; if ec == 0b100100u64 || ec == 0b100101u64 { let addr: u16 = exception.physical_address.try_into().unwrap(); let pc = self.vcpu.read_register(Register::PC)?; match addr { UHYVE_UART_PORT => { let x8 = (self.vcpu.read_register(Register::X8)? & 0xFF) as u8; self.uart(&[x8]).unwrap(); self.vcpu.write_register(Register::PC, pc + 4)?; } UHYVE_PORT_EXIT => { let data_addr = self.vcpu.read_register(Register::X8)?; let sysexit = unsafe { &*(self.host_address(data_addr as usize) as *const SysExit) }; return Ok(VcpuStopReason::Exit(self.exit(sysexit))); } _ => { error!("Unable to handle exception {:?}", exception); self.print_registers(); return Err(xhypervisor::Error::Error); } } } else { error!("Unsupported exception class: 0x{:x}", ec); self.print_registers(); return Err(xhypervisor::Error::Error); } } _ => { error!("Unknown exit reason: {:?}", reason); return Err(xhypervisor::Error::Error); } } } } fn run(&mut self) -> HypervisorResult<Option<i32>> { match self.r#continue()? { VcpuStopReason::Debug(_) => { unreachable!("reached debug exit without running in debugging mode") } VcpuStopReason::Exit(code) => Ok(Some(code)), VcpuStopReason::Kick => Ok(None), } } fn print_registers(&self) { println!("\nDump state of CPU {}", self.id); let pc = self.vcpu.read_register(Register::PC).unwrap(); let cpsr = self.vcpu.read_register(Register::CPSR).unwrap(); let sp = self .vcpu .read_system_register(SystemRegister::SP_EL1) .unwrap(); let sctlr = self .vcpu .read_system_register(SystemRegister::SCTLR_EL1) .unwrap(); let ttbr0 = self .vcpu .read_system_register(SystemRegister::TTBR0_EL1) .unwrap(); let lr = self.vcpu.read_register(Register::LR).unwrap(); let x0 = self.vcpu.read_register(Register::X0).unwrap(); let x1 = self.vcpu.read_register(Register::X1).unwrap(); let x2 = self.vcpu.read_register(Register::X2).unwrap(); let x3 = self.vcpu.read_register(Register::X3).unwrap(); let x4 = self.vcpu.read_register(Register::X4).unwrap(); let x5 = self.vcpu.read_register(Register::X5).unwrap(); let x6 = self.vcpu.read_register(Register::X6).unwrap(); let x7 = self.vcpu.read_register(Register::X7).unwrap(); let x8 = self.vcpu.read_register(Register::X8).unwrap(); let x9 = self.vcpu.read_register(Register::X9).unwrap(); let x10 = self.vcpu.read_register(Register::X10).unwrap(); let x11 = self.vcpu.read_register(Register::X11).unwrap(); let x12 = self.vcpu.read_register(Register::X12).unwrap(); let x13 = self.vcpu.read_register(Register::X13).unwrap(); let x14 = self.vcpu.read_register(Register::X14).unwrap(); let x15 = self.vcpu.read_register(Register::X15).unwrap(); let x16 = self.vcpu.read_register(Register::X16).unwrap(); let x17 = self.vcpu.read_register(Register::X17).unwrap(); let x18 = self.vcpu.read_register(Register::X18).unwrap(); let x19 = self.vcpu.read_register(Register::X19).unwrap(); let x20 = self.vcpu.read_register(Register::X20).unwrap(); let x21 = self.vcpu.read_register(Register::X21).unwrap(); let x22 = self.vcpu.read_register(Register::X22).unwrap(); let x23 = self.vcpu.read_register(Register::X23).unwrap(); let x24 = self.vcpu.read_register(Register::X24).unwrap(); let x25 = self.vcpu.read_register(Register::X25).unwrap(); let x26 = self.vcpu.read_register(Register::X26).unwrap(); let x27 = self.vcpu.read_register(Register::X27).unwrap(); let x28 = self.vcpu.read_register(Register::X28).unwrap(); let x29 = self.vcpu.read_register(Register::X29).unwrap(); println!("\nRegisters:"); println!("----------"); println!( "PC : {:016x} LR : {:016x} CPSR : {:016x}\n\ SP : {:016x} SCTLR : {:016x} TTBR0 : {:016x}", pc, lr, cpsr, sp, sctlr, ttbr0, ); print!( "x0 : {:016x} x1 : {:016x} x2 : {:016x}\n\ x3 : {:016x} x4 : {:016x} x5 : {:016x}\n\ x6 : {:016x} x7 : {:016x} x8 : {:016x}\n\ x9 : {:016x} x10 : {:016x} x11 : {:016x}\n\ x12 : {:016x} x13 : {:016x} x14 : {:016x}\n\ x15 : {:016x} x16 : {:016x} x17 : {:016x}\n\ x18 : {:016x} x19 : {:016x} x20 : {:016x}\n\ x21 : {:016x} x22 : {:016x} x23 : {:016x}\n\ x24 : {:016x} x25 : {:016x} x26 : {:016x}\n\ x27 : {:016x} x28 : {:016x} x29 : {:016x}\n", x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16, x17, x18, x19, x20, x21, x22, x23, x24, x25, x26, x27, x28, x29, ); } } impl Drop for UhyveCPU { fn drop(&mut self) { debug!("Drop virtual CPU {}", self.id); let _ = self.vcpu.destroy(); } }
pub fn new(id: u32, kernel_path: PathBuf, args: Vec<OsString>, vm_start: usize) -> UhyveCPU { Self { id, kernel_path, args, vcpu: xhypervisor::VirtualCpu::new().unwrap(), vm_start, } }
function_block-full_function
[ { "content": "/// Uses Cargo to build a kernel in the `tests/test-kernels` directory.\n\n/// Returns a path to the build binary.\n\npub fn build_hermit_bin(kernel: impl AsRef<Path>) -> PathBuf {\n\n\tlet kernel = kernel.as_ref();\n\n\tprintln!(\"Building Kernel {}\", kernel.display());\n\n\tlet kernel_src_path ...
Rust
gcode/src/words.rs
Michael-F-Bryan/gcode-rs
3cfd2fe1787fcd234bf135bbc7250aa1b5b67ca6
use crate::{ lexer::{Lexer, Token, TokenType}, Comment, Span, }; use core::fmt::{self, Display, Formatter}; #[derive(Debug, Copy, Clone, PartialEq)] #[cfg_attr( feature = "serde-1", derive(serde_derive::Serialize, serde_derive::Deserialize) )] #[repr(C)] pub struct Word { pub letter: char, pub value: f32, pub span: Span, } impl Word { pub fn new(letter: char, value: f32, span: Span) -> Self { Word { letter, value, span, } } } impl Display for Word { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { write!(f, "{}{}", self.letter, self.value) } } #[derive(Debug, Copy, Clone, PartialEq)] pub(crate) enum Atom<'input> { Word(Word), Comment(Comment<'input>), BrokenWord(Token<'input>), Unknown(Token<'input>), } impl<'input> Atom<'input> { pub(crate) fn span(&self) -> Span { match self { Atom::Word(word) => word.span, Atom::Comment(comment) => comment.span, Atom::Unknown(token) | Atom::BrokenWord(token) => token.span, } } } #[derive(Debug, Clone, PartialEq)] pub(crate) struct WordsOrComments<'input, I> { tokens: I, last_letter: Option<Token<'input>>, } impl<'input, I> WordsOrComments<'input, I> where I: Iterator<Item = Token<'input>>, { pub(crate) fn new(tokens: I) -> Self { WordsOrComments { tokens, last_letter: None, } } } impl<'input, I> Iterator for WordsOrComments<'input, I> where I: Iterator<Item = Token<'input>>, { type Item = Atom<'input>; fn next(&mut self) -> Option<Self::Item> { while let Some(token) = self.tokens.next() { let Token { kind, value, span } = token; match kind { TokenType::Unknown => return Some(Atom::Unknown(token)), TokenType::Comment => { return Some(Atom::Comment(Comment { value, span })) }, TokenType::Letter if self.last_letter.is_none() => { self.last_letter = Some(token); }, TokenType::Number if self.last_letter.is_some() => { let letter_token = self.last_letter.take().unwrap(); let span = letter_token.span.merge(span); debug_assert_eq!(letter_token.value.len(), 1); let letter = letter_token.value.chars().next().unwrap(); let value = value.parse().expect(""); return Some(Atom::Word(Word { letter, value, span, })); }, _ => return Some(Atom::BrokenWord(token)), } } self.last_letter.take().map(Atom::BrokenWord) } } impl<'input> From<&'input str> for WordsOrComments<'input, Lexer<'input>> { fn from(other: &'input str) -> WordsOrComments<'input, Lexer<'input>> { WordsOrComments::new(Lexer::new(other)) } } #[cfg(test)] mod tests { use super::*; use crate::lexer::Lexer; #[test] fn pass_comments_through() { let mut words = WordsOrComments::new(Lexer::new("(this is a comment) 3.14")); let got = words.next().unwrap(); let comment = "(this is a comment)"; let expected = Atom::Comment(Comment { value: comment, span: Span { start: 0, end: comment.len(), line: 0, }, }); assert_eq!(got, expected); } #[test] fn pass_garbage_through() { let text = "!@#$ *"; let mut words = WordsOrComments::new(Lexer::new(text)); let got = words.next().unwrap(); let expected = Atom::Unknown(Token { value: text, kind: TokenType::Unknown, span: Span { start: 0, end: text.len(), line: 0, }, }); assert_eq!(got, expected); } #[test] fn numbers_are_garbage_if_they_dont_have_a_letter_in_front() { let text = "3.14 ()"; let mut words = WordsOrComments::new(Lexer::new(text)); let got = words.next().unwrap(); let expected = Atom::BrokenWord(Token { value: "3.14", kind: TokenType::Number, span: Span { start: 0, end: 4, line: 0, }, }); assert_eq!(got, expected); } #[test] fn recognise_a_valid_word() { let text = "G90"; let mut words = WordsOrComments::new(Lexer::new(text)); let got = words.next().unwrap(); let expected = Atom::Word(Word { letter: 'G', value: 90.0, span: Span { start: 0, end: text.len(), line: 0, }, }); assert_eq!(got, expected); } }
use crate::{ lexer::{Lexer, Token, TokenType}, Comment, Span, }; use core::fmt::{self, Display, Formatter}; #[derive(Debug, Copy, Clone, PartialEq)] #[cfg_attr( feature = "serde-1", derive(serde_derive::Serialize, serde_derive::Deserialize) )] #[repr(C)] pub struct Word { pub letter: char, pub value: f32, pub span: Span, } impl Word { pub fn new(letter: char, value: f32, span: Span) -> Self { Word { letter, value, span, } } } impl Display for Word { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { write!(f, "{}{}", self.letter, self.value) } } #[derive(Debug, Copy, Clone, PartialEq)] pub(crate) enum Atom<'input> { Word(Word), Comment(Comment<'input>), BrokenWord(Token<'input>), Unknown(Token<'input>), } impl<'input> Atom<'input> { pub(crate) fn span(&self) -> Span { match self { Atom::Word(word) => word.span, Atom::Comment(comment) => comment.span, Atom::Unknown(token) | Atom::BrokenWord(token) => token.span, } } } #[derive(Debug, Clone, PartialEq)] pub(crate) struct WordsOrComments<'input, I> { tokens: I, last_letter: Option<Token<'input>>, } impl<'input, I> WordsOrComments<'input, I> where I: Iterator<Item = Token<'input>>, { pub(crate) fn new(tokens: I) -> Self { WordsOrComments { tokens, last_letter: None, } } } impl<'input, I> Iterator for WordsOrComments<'input, I> where I: Iterator<Item = Token<'input>>, { type Item = Atom<'input>;
() { let mut words = WordsOrComments::new(Lexer::new("(this is a comment) 3.14")); let got = words.next().unwrap(); let comment = "(this is a comment)"; let expected = Atom::Comment(Comment { value: comment, span: Span { start: 0, end: comment.len(), line: 0, }, }); assert_eq!(got, expected); } #[test] fn pass_garbage_through() { let text = "!@#$ *"; let mut words = WordsOrComments::new(Lexer::new(text)); let got = words.next().unwrap(); let expected = Atom::Unknown(Token { value: text, kind: TokenType::Unknown, span: Span { start: 0, end: text.len(), line: 0, }, }); assert_eq!(got, expected); } #[test] fn numbers_are_garbage_if_they_dont_have_a_letter_in_front() { let text = "3.14 ()"; let mut words = WordsOrComments::new(Lexer::new(text)); let got = words.next().unwrap(); let expected = Atom::BrokenWord(Token { value: "3.14", kind: TokenType::Number, span: Span { start: 0, end: 4, line: 0, }, }); assert_eq!(got, expected); } #[test] fn recognise_a_valid_word() { let text = "G90"; let mut words = WordsOrComments::new(Lexer::new(text)); let got = words.next().unwrap(); let expected = Atom::Word(Word { letter: 'G', value: 90.0, span: Span { start: 0, end: text.len(), line: 0, }, }); assert_eq!(got, expected); } }
fn next(&mut self) -> Option<Self::Item> { while let Some(token) = self.tokens.next() { let Token { kind, value, span } = token; match kind { TokenType::Unknown => return Some(Atom::Unknown(token)), TokenType::Comment => { return Some(Atom::Comment(Comment { value, span })) }, TokenType::Letter if self.last_letter.is_none() => { self.last_letter = Some(token); }, TokenType::Number if self.last_letter.is_some() => { let letter_token = self.last_letter.take().unwrap(); let span = letter_token.span.merge(span); debug_assert_eq!(letter_token.value.len(), 1); let letter = letter_token.value.chars().next().unwrap(); let value = value.parse().expect(""); return Some(Atom::Word(Word { letter, value, span, })); }, _ => return Some(Atom::BrokenWord(token)), } } self.last_letter.take().map(Atom::BrokenWord) } } impl<'input> From<&'input str> for WordsOrComments<'input, Lexer<'input>> { fn from(other: &'input str) -> WordsOrComments<'input, Lexer<'input>> { WordsOrComments::new(Lexer::new(other)) } } #[cfg(test)] mod tests { use super::*; use crate::lexer::Lexer; #[test] fn pass_comments_through
random
[ { "content": "/// Parse each [`GCode`] in some text, ignoring any errors that may occur or\n\n/// [`Comment`]s that are found.\n\n///\n\n/// This function is probably what you are looking for if you just want to read\n\n/// the [`GCode`] commands in a program. If more detailed information is needed,\n\n/// have...
Rust
src/lib.rs
JIghtuse/rs-release
e96f2441c02ed1d54ee939856fca87c9bc2b7459
#![deny(missing_docs)] use std::collections::HashMap; use std::convert::From; use std::error::Error; use std::fmt; use std::fs::File; use std::io::{BufReader, BufRead}; use std::path::Path; use std::borrow::Cow; const PATHS: [&'static str; 2] = ["/etc/os-release", "/usr/lib/os-release"]; const QUOTES: [&'static str; 2] = ["\"", "'"]; const COMMON_KEYS: [&'static str; 16] = ["ANSI_COLOR", "BUG_REPORT_URL", "BUILD_ID", "CPE_NAME", "HOME_URL", "ID", "ID_LIKE", "NAME", "PRETTY_NAME", "PRIVACY_POLICY_URL", "SUPPORT_URL", "VARIANT", "VARIANT_ID", "VERSION", "VERSION_CODENAME", "VERSION_ID"]; #[derive(Debug)] pub enum OsReleaseError { Io(std::io::Error), NoFile, ParseError, } impl PartialEq for OsReleaseError { fn eq(&self, other: &OsReleaseError) -> bool { match (self, other) { (&OsReleaseError::Io(_), &OsReleaseError::Io(_)) | (&OsReleaseError::NoFile, &OsReleaseError::NoFile) | (&OsReleaseError::ParseError, &OsReleaseError::ParseError) => true, _ => false, } } } impl fmt::Display for OsReleaseError { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { match *self { OsReleaseError::Io(ref inner) => inner.fmt(fmt), OsReleaseError::NoFile => write!(fmt, "{}", self.description()), OsReleaseError::ParseError => write!(fmt, "{}", self.description()), } } } impl Error for OsReleaseError { fn description(&self) -> &str { match *self { OsReleaseError::Io(ref err) => err.description(), OsReleaseError::NoFile => "Failed to find os-release file", OsReleaseError::ParseError => "File is malformed", } } fn cause(&self) -> Option<&Error> { match *self { OsReleaseError::Io(ref err) => Some(err), OsReleaseError::NoFile | OsReleaseError::ParseError => None, } } } impl From<std::io::Error> for OsReleaseError { fn from(err: std::io::Error) -> OsReleaseError { OsReleaseError::Io(err) } } pub type Result<T> = std::result::Result<T, OsReleaseError>; fn trim_quotes(s: &str) -> &str { if QUOTES.iter().any(|q| s.starts_with(q) && s.ends_with(q)) { &s[1..s.len() - 1] } else { s } } fn extract_variable_and_value(s: &str) -> Result<(Cow<'static, str>, String)> { if let Some(equal) = s.chars().position(|c| c == '=') { let var = &s[..equal]; let var = var.trim(); let val = &s[equal + 1..]; let val = trim_quotes(val.trim()).to_string(); if let Some(key) = COMMON_KEYS.iter().find(|&k| *k == var) { Ok((Cow::Borrowed(key), val)) } else { Ok((Cow::Owned(var.to_string()), val)) } } else { Err(OsReleaseError::ParseError) } } pub fn parse_os_release<P: AsRef<Path>>(path: P) -> Result<HashMap<Cow<'static, str>, String>> { let mut os_release = HashMap::new(); let file = try!(File::open(path)); let reader = BufReader::new(file); for line in reader.lines() { let line = try!(line); let line = line.trim(); if line.starts_with('#') || line.is_empty() { continue; } let var_val = try!(extract_variable_and_value(line)); os_release.insert(var_val.0, var_val.1); } Ok(os_release) } pub fn parse_os_release_str(data: &str) -> Result<HashMap<Cow<'static, str>, String>> { let mut os_release = HashMap::new(); for line in data.split('\n') { let line = line.trim(); if line.starts_with('#') || line.is_empty() { continue; } let var_val = try!(extract_variable_and_value(line)); os_release.insert(var_val.0, var_val.1); } Ok(os_release) } pub fn get_os_release() -> Result<HashMap<Cow<'static, str>, String>> { for file in &PATHS { if let Ok(os_release) = parse_os_release(file) { return Ok(os_release); } } Err(OsReleaseError::NoFile) }
#![deny(missing_docs)] use std::collections::HashMap; use std::convert::From; use std::error::Error; use std::fmt; use std::fs::File; use std::io::{BufReader, BufRead}; use std::path::Path; use std::borrow::Cow; const PATHS: [&'static str; 2] = ["/etc/os-release", "/usr/lib/os-release"]; const QUOTES: [&'static str; 2] = ["\"", "'"]; const COMMON_KEYS: [&'static str; 16] = ["ANSI_COLOR", "BUG_REPORT_URL", "BUILD_ID", "CPE_NAME", "HOME_URL", "ID", "ID_LIKE", "NAME", "PRETTY_NAME", "PRIVACY_POLICY_URL", "SUPPORT_URL", "VARIANT", "VARIANT_ID", "VERSION", "VERSION_CODENAME", "VERSION_ID"]; #[derive(Debug)] pub enum OsReleaseError { Io(std::io::Error), NoFile, ParseError, } impl PartialEq for OsReleaseError { fn eq(&self, other: &OsReleaseError) -> bool { match (self, other) { (&OsReleaseError::Io(_), &OsReleaseError::Io(_)) | (&OsReleaseError::NoFile, &OsReleaseError::NoFile) | (&OsReleaseError::ParseError, &OsReleaseError::ParseError) => true, _ => false, } } } impl fmt::Display for OsReleaseError { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { match *self { OsReleaseError::Io(ref inner) => inner.fmt(fmt), OsReleaseError::NoFile => write!(fmt, "{}", self.description()), OsReleaseError::ParseError => write!(fmt, "{}", self.description()), } } } impl Error for OsReleaseError { fn description(&self) -> &str { match *self { OsReleaseError::Io(ref err) => err.description(), OsReleaseError::NoFile => "Failed to find os-release file", OsReleaseError::ParseError => "File is malformed", } } fn cause(&self) -> Option<&Error> { match *self { OsReleaseError::Io(ref err) => Some(err), OsReleaseError::NoFile | OsReleaseError::ParseError => None, } } } impl From<std::io::Error> for OsReleaseError { fn from(err: std::io::Error) -> OsReleaseError { OsReleaseError::Io(err) } } pub type Result<T> = std::result::Result<T, OsReleaseError>;
fn extract_variable_and_value(s: &str) -> Result<(Cow<'static, str>, String)> { if let Some(equal) = s.chars().position(|c| c == '=') { let var = &s[..equal]; let var = var.trim(); let val = &s[equal + 1..]; let val = trim_quotes(val.trim()).to_string(); if let Some(key) = COMMON_KEYS.iter().find(|&k| *k == var) { Ok((Cow::Borrowed(key), val)) } else { Ok((Cow::Owned(var.to_string()), val)) } } else { Err(OsReleaseError::ParseError) } } pub fn parse_os_release<P: AsRef<Path>>(path: P) -> Result<HashMap<Cow<'static, str>, String>> { let mut os_release = HashMap::new(); let file = try!(File::open(path)); let reader = BufReader::new(file); for line in reader.lines() { let line = try!(line); let line = line.trim(); if line.starts_with('#') || line.is_empty() { continue; } let var_val = try!(extract_variable_and_value(line)); os_release.insert(var_val.0, var_val.1); } Ok(os_release) } pub fn parse_os_release_str(data: &str) -> Result<HashMap<Cow<'static, str>, String>> { let mut os_release = HashMap::new(); for line in data.split('\n') { let line = line.trim(); if line.starts_with('#') || line.is_empty() { continue; } let var_val = try!(extract_variable_and_value(line)); os_release.insert(var_val.0, var_val.1); } Ok(os_release) } pub fn get_os_release() -> Result<HashMap<Cow<'static, str>, String>> { for file in &PATHS { if let Ok(os_release) = parse_os_release(file) { return Ok(os_release); } } Err(OsReleaseError::NoFile) }
fn trim_quotes(s: &str) -> &str { if QUOTES.iter().any(|q| s.starts_with(q) && s.ends_with(q)) { &s[1..s.len() - 1] } else { s } }
function_block-full_function
[ { "content": "#[derive(Debug)]\n\nenum Error {\n\n UnknownOs,\n\n ReadError,\n\n}\n\n\n", "file_path": "examples/who_eats_my_hard_drive.rs", "rank": 5, "score": 70185.70182749387 }, { "content": "fn get_os_id() -> Result<String, Error> {\n\n match rs_release::get_os_release() {\n\n ...
Rust
crates/tm4c129x/src/emac0/vlantg.rs
m-labs/ti2svd
30145706b658136c35c90290701de3f02a4b8ef2
#[doc = "Reader of register VLANTG"] pub type R = crate::R<u32, super::VLANTG>; #[doc = "Writer for register VLANTG"] pub type W = crate::W<u32, super::VLANTG>; #[doc = "Register VLANTG `reset()`'s with value 0"] impl crate::ResetValue for super::VLANTG { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `VL`"] pub type VL_R = crate::R<u16, u16>; #[doc = "Write proxy for field `VL`"] pub struct VL_W<'a> { w: &'a mut W, } impl<'a> VL_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u16) -> &'a mut W { self.w.bits = (self.w.bits & !0xffff) | ((value as u32) & 0xffff); self.w } } #[doc = "Reader of field `ETV`"] pub type ETV_R = crate::R<bool, bool>; #[doc = "Write proxy for field `ETV`"] pub struct ETV_W<'a> { w: &'a mut W, } impl<'a> ETV_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 16)) | (((value as u32) & 0x01) << 16); self.w } } #[doc = "Reader of field `VTIM`"] pub type VTIM_R = crate::R<bool, bool>; #[doc = "Write proxy for field `VTIM`"] pub struct VTIM_W<'a> { w: &'a mut W, } impl<'a> VTIM_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 17)) | (((value as u32) & 0x01) << 17); self.w } } #[doc = "Reader of field `ESVL`"] pub type ESVL_R = crate::R<bool, bool>; #[doc = "Write proxy for field `ESVL`"] pub struct ESVL_W<'a> { w: &'a mut W, } impl<'a> ESVL_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 18)) | (((value as u32) & 0x01) << 18); self.w } } #[doc = "Reader of field `VTHM`"] pub type VTHM_R = crate::R<bool, bool>; #[doc = "Write proxy for field `VTHM`"] pub struct VTHM_W<'a> { w: &'a mut W, } impl<'a> VTHM_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 19)) | (((value as u32) & 0x01) << 19); self.w } } impl R { #[doc = "Bits 0:15 - VLAN Tag Identifier for Receive Frames"] #[inline(always)] pub fn vl(&self) -> VL_R { VL_R::new((self.bits & 0xffff) as u16) } #[doc = "Bit 16 - Enable 12-Bit VLAN Tag Comparison"] #[inline(always)] pub fn etv(&self) -> ETV_R { ETV_R::new(((self.bits >> 16) & 0x01) != 0) } #[doc = "Bit 17 - VLAN Tag Inverse Match Enable"] #[inline(always)] pub fn vtim(&self) -> VTIM_R { VTIM_R::new(((self.bits >> 17) & 0x01) != 0) } #[doc = "Bit 18 - Enable S-VLAN"] #[inline(always)] pub fn esvl(&self) -> ESVL_R { ESVL_R::new(((self.bits >> 18) & 0x01) != 0) } #[doc = "Bit 19 - VLAN Tag Hash Table Match Enable"] #[inline(always)] pub fn vthm(&self) -> VTHM_R { VTHM_R::new(((self.bits >> 19) & 0x01) != 0) } } impl W { #[doc = "Bits 0:15 - VLAN Tag Identifier for Receive Frames"] #[inline(always)] pub fn vl(&mut self) -> VL_W { VL_W { w: self } } #[doc = "Bit 16 - Enable 12-Bit VLAN Tag Comparison"] #[inline(always)] pub fn etv(&mut self) -> ETV_W { ETV_W { w: self } } #[doc = "Bit 17 - VLAN Tag Inverse Match Enable"] #[inline(always)] pub fn vtim(&mut self) -> VTIM_W { VTIM_W { w: self } } #[doc = "Bit 18 - Enable S-VLAN"] #[inline(always)] pub fn esvl(&mut self) -> ESVL_W { ESVL_W { w: self } } #[doc = "Bit 19 - VLAN Tag Hash Table Match Enable"] #[inline(always)] pub fn vthm(&mut self) -> VTHM_W { VTHM_W { w: self } } }
#[doc = "Reader of register VLANTG"] pub type R = crate::R<u32, super::VLANTG>; #[doc = "Writer for register VLANTG"] pub type W = crate::W<u32, super::VLANTG>; #[doc = "Register VLANTG `reset()`'s with value 0"] impl crate::ResetValue for super::VLANTG { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `VL`"] pub type VL_R = crate::R<u16, u16>; #[doc = "Write proxy for field `VL`"] pub struct VL_W<'a> { w: &'a mut W, } impl<'a> VL_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u16) -> &'a mut W { self.w.bits = (self.w.bits & !0xffff) | ((value as u32) & 0xffff); self.w } } #[doc = "Reader of field `ETV`"] pub type ETV_R = crate::R<bool, bool>; #[doc = "Write proxy for field `ETV`"] pub struct ETV_W<'a> { w: &'a mut W, } impl<'a> ETV_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 16)) | (((value as u32) & 0x01) << 16); self.w } } #[doc = "Reader of field `VTIM`"] pub type VTIM_R = crate::R<bool, bool>; #[doc = "Write proxy for field `VTIM`"] pub struct VTIM_W<'a> { w: &'a mut W, } impl<'a> VTIM_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 17)) | (((value as u32) & 0x01) << 17); self.w } } #[doc = "Reader of field `ESVL`"] pub type ESVL_R = crate::R<bool, bool>; #[doc = "Write proxy for field `ESVL`"] pub struct ESVL_W<'a> { w: &'a mut W, } impl<'a> ESVL_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(alway
elf) -> ETV_R { ETV_R::new(((self.bits >> 16) & 0x01) != 0) } #[doc = "Bit 17 - VLAN Tag Inverse Match Enable"] #[inline(always)] pub fn vtim(&self) -> VTIM_R { VTIM_R::new(((self.bits >> 17) & 0x01) != 0) } #[doc = "Bit 18 - Enable S-VLAN"] #[inline(always)] pub fn esvl(&self) -> ESVL_R { ESVL_R::new(((self.bits >> 18) & 0x01) != 0) } #[doc = "Bit 19 - VLAN Tag Hash Table Match Enable"] #[inline(always)] pub fn vthm(&self) -> VTHM_R { VTHM_R::new(((self.bits >> 19) & 0x01) != 0) } } impl W { #[doc = "Bits 0:15 - VLAN Tag Identifier for Receive Frames"] #[inline(always)] pub fn vl(&mut self) -> VL_W { VL_W { w: self } } #[doc = "Bit 16 - Enable 12-Bit VLAN Tag Comparison"] #[inline(always)] pub fn etv(&mut self) -> ETV_W { ETV_W { w: self } } #[doc = "Bit 17 - VLAN Tag Inverse Match Enable"] #[inline(always)] pub fn vtim(&mut self) -> VTIM_W { VTIM_W { w: self } } #[doc = "Bit 18 - Enable S-VLAN"] #[inline(always)] pub fn esvl(&mut self) -> ESVL_W { ESVL_W { w: self } } #[doc = "Bit 19 - VLAN Tag Hash Table Match Enable"] #[inline(always)] pub fn vthm(&mut self) -> VTHM_W { VTHM_W { w: self } } }
s)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 18)) | (((value as u32) & 0x01) << 18); self.w } } #[doc = "Reader of field `VTHM`"] pub type VTHM_R = crate::R<bool, bool>; #[doc = "Write proxy for field `VTHM`"] pub struct VTHM_W<'a> { w: &'a mut W, } impl<'a> VTHM_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 19)) | (((value as u32) & 0x01) << 19); self.w } } impl R { #[doc = "Bits 0:15 - VLAN Tag Identifier for Receive Frames"] #[inline(always)] pub fn vl(&self) -> VL_R { VL_R::new((self.bits & 0xffff) as u16) } #[doc = "Bit 16 - Enable 12-Bit VLAN Tag Comparison"] #[inline(always)] pub fn etv(&s
random
[ { "content": "#[doc = \"Reset value of the register\"]\n\n#[doc = \"\"]\n\n#[doc = \"This value is initial value for `write` method.\"]\n\n#[doc = \"It can be also directly writed to register by `reset` method.\"]\n\npub trait ResetValue {\n\n #[doc = \"Register size\"]\n\n type Type;\n\n #[doc = \"Res...
Rust
crates/core/src/graph/mod.rs
rustatian/rock
664825fe85b3649de669d5e498f64267c7676e79
#![warn(missing_debug_implementations)] #![allow(dead_code)] use crate::profile::line::Line; use crate::profile::Profile; use crate::profile::{self}; use std::{collections::HashMap, vec}; use std::{ hash::{Hash, Hasher}, path::PathBuf, }; #[cfg(target_os = "windows")] const SEPARATOR: &str = "\\"; #[cfg(target_os = "linux")] const SEPARATOR: &str = "/"; type EdgeMap = HashMap<Node, Edge>; type TagMap = HashMap<String, Tag>; type Nodes = Vec<Node>; type NodeMap = HashMap<NodeInfo, Node>; type NodeSet = HashMap<NodeInfo, bool>; #[derive(Clone, Debug)] struct Graph<'a> { nodes: Vec<&'a Node>, } impl<'a> Graph<'a> { pub fn new() -> Self { Graph { nodes: vec![] } } fn init_graph<T: Fn(&[i64]) -> i64, U: Fn(i64, String) -> String>( &self, prof: Profile, o: Options<T, U>, ) -> Self { Graph { nodes: vec![] } } fn create_nodes<T: Fn(&[i64]) -> i64, U: Fn(i64, String) -> String>( prof: &Profile, o: Options<T, U>, ) -> Option<(Nodes, HashMap<u64, Nodes>)> { let mut locations: HashMap<u64, Nodes> = HashMap::new(); let nm = NodeMap::new(); for l in prof.location.iter() { let lines: &Vec<Line> = &l.line; let mut nodes: Vec<Node> = vec![Node::default(); lines.len()]; for ln in 0..lines.len() { nodes.insert(ln, Node::default()); } locations.insert(l.id, nodes); } Some(( nm.iter().map(|x| x.1.clone()).collect::<Vec<Node>>(), locations, )) } fn find_or_insert_node(nm: &mut NodeMap, info: NodeInfo, kept: NodeSet) -> Option<Node> { None } fn find_or_insert_line<T: Fn(&[i64]) -> i64, U: Fn(i64, String) -> String>( nm: &NodeMap, l: &profile::location::Location, line: profile::line::Line, o: &Options<T, U>, ) -> Option<Node> { let mut objfile = String::new(); if let Some(m) = &l.mapping { if !m.filename.is_empty() { objfile = m.filename.clone(); } } let mut node_info = Graph::node_info(l, line, objfile, o); None } fn node_info<T: Fn(&[i64]) -> i64, U: Fn(i64, String) -> String>( l: &profile::location::Location, line: profile::line::Line, objfile: String, o: &Options<T, U>, ) -> NodeInfo { if line.function == profile::function::Function::default() { return NodeInfo { address: l.address, objfile, ..Default::default() }; } let mut ni = NodeInfo { address: l.address, lineno: line.line, name: line.function.name, ..Default::default() }; if !line.function.filename.is_empty() { let mut buf = PathBuf::from(line.function.filename); buf.clear(); ni.file = buf.to_str().unwrap().to_string(); } if o.orig_fn_names { ni.orig_name = line.function.system_name; } if o.obj_names || (ni.name.is_empty() && ni.orig_name.is_empty()) { ni.objfile = objfile; ni.start_line = line.function.start_line; } ni } } #[derive(Debug)] struct Options<T, U> where T: Fn(&[i64]) -> i64, U: Fn(i64, String) -> String, { sample_value: T, sample_mean_divisor: T, format_tag: U, obj_names: bool, orig_fn_names: bool, call_tree: bool, drop_negative: bool, kept_nodes: HashMap<NodeInfo, bool>, } #[derive(Clone, Debug, Eq, Default)] struct Node { info: NodeInfo, function: Box<Node>, flat: i64, flat_div: i64, cum: i64, cum_div: i64, r#in: HashMap<Node, Edge>, out: HashMap<Node, Edge>, label_tags: HashMap<String, Tag>, numeric_tags: HashMap<String, HashMap<String, Tag>>, } impl Hash for Node { fn hash<H: Hasher>(&self, state: &mut H) { self.info.hash(state); self.function.hash(state); self.flat.hash(state); self.flat_div.hash(state); self.cum.hash(state); self.cum_div.hash(state); } } impl PartialEq for Node { fn eq(&self, other: &Self) -> bool { self.flat == other.flat && self.info == other.info && self.function == other.function && self.flat_div == other.flat_div && self.cum == other.cum && self.cum_div == other.cum_div && self.r#in == other.r#in && self.out == other.out && self.label_tags == other.label_tags && self.numeric_tags == other.numeric_tags } } impl Node { pub fn new() -> Self { Node::default() } pub fn flat_value(&self) -> i64 { if self.flat_div == 0 { return self.flat; } self.flat / self.flat_div } pub fn cum_value(&self) -> i64 { if self.cum_div == 0 { return self.cum; } self.cum / self.cum_div } pub fn add_to_edge(&mut self, to: &mut Node, v: i64, residual: bool, inline: bool) { self.add_to_edge_div(to, 0, v, residual, inline); } pub fn add_to_edge_div( &mut self, to: &mut Node, dv: i64, v: i64, residual: bool, inline: bool, ) { if let Some(node1) = self.r#in.get(to) { if let Some(node2) = self.out.get(self) { if node1 != node2 { panic!("asymmetric edges {:?} {:?}", self, to); } } } if let Some(e) = self.r#in.get_mut(to) { e.weight_div += dv; e.weight += v; if residual { e.residual = true; } if !inline { e.inline = false; } return; } let info = Edge { src: self.clone(), dest: to.clone(), weight_div: dv, weight: v, residual, inline, }; self.out.insert(to.clone(), info.clone()); to.r#in.insert(self.clone(), info); } } #[derive(Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Default)] struct NodeInfo { name: String, orig_name: String, address: u64, file: String, start_line: i64, lineno: i64, objfile: String, } impl NodeInfo { pub fn printable_name(&self) -> String { self.name_components().join(" ") } pub fn name_components(&self) -> Vec<String> { let mut name = vec![]; if self.address != 0 { name.push(format!("{:x}", self.address)); } if !self.name.is_empty() { name.push(self.name.to_string()); } if self.lineno != 0 { name.push(format!("{}:{}", self.file, self.lineno)); } if !self.file.is_empty() { name.push(self.file.to_string()); } if !self.name.is_empty() { name.push(self.name.to_string()); } if !self.objfile.is_empty() { name.push(format!("[{}]", get_basename(&self.objfile, SEPARATOR))); } if name.is_empty() { name.push("<unknown>".to_string()); } name } } fn get_basename<'a>(path: &'a str, pat: &'a str) -> String { let mut parts = path.rsplit(pat); match parts.next() { None => "".into(), Some(path) => path.into(), } } #[derive(Clone, Debug, Hash, Eq, PartialEq)] struct Edge { src: Node, dest: Node, weight: i64, weight_div: i64, residual: bool, inline: bool, } impl Edge { pub fn weight_value(&self) -> i64 { if self.weight_div == 0 { return self.weight; } self.weight / self.weight_div } } #[derive(Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Default)] struct Tag { name: String, unit: String, value: i64, flat: i64, flat_div: i64, cum: i64, cum_div: i64, } impl Tag { pub fn cum_value(&self) -> i64 { if self.cum_div == 0 { return self.cum; } self.cum / self.cum_div } pub fn flat_value(&self) -> i64 { if self.flat_div == 0 { return self.flat; } self.flat / self.flat_div } } #[cfg(test)] mod tests { use crate::graph::{get_basename, SEPARATOR}; #[test] fn test_get_basename() { assert_eq!(get_basename("/usr/data", SEPARATOR), "data"); assert_eq!(get_basename("/", SEPARATOR), ""); assert_eq!(get_basename("/root", SEPARATOR), "root"); } }
#![warn(missing_debug_implementations)] #![allow(dead_code)] use crate::profile::line::Line; use crate::profile::Profile; use crate::profile::{self}; use std::{collections::HashMap, vec}; use std::{ hash::{Hash, Hasher}, path::PathBuf, }; #[cfg(target_os = "windows")] const SEPARATOR: &str = "\\"; #[cfg(target_os = "linux")] const SEPARATOR: &str = "/"; type EdgeMap = HashMap<Node, Edge>; type TagMap = HashMap<String, Tag>; type Nodes = Vec<Node>; type NodeMap = HashMap<NodeInfo, Node>; type NodeSet = HashMap<NodeInfo, bool>; #[derive(Clone, Debug)] struct Graph<'a> { nodes: Vec<&'a Node>, } impl<'a> Graph<'a> { pub fn new() -> Self { Graph { nodes: vec![] } }
fn create_nodes<T: Fn(&[i64]) -> i64, U: Fn(i64, String) -> String>( prof: &Profile, o: Options<T, U>, ) -> Option<(Nodes, HashMap<u64, Nodes>)> { let mut locations: HashMap<u64, Nodes> = HashMap::new(); let nm = NodeMap::new(); for l in prof.location.iter() { let lines: &Vec<Line> = &l.line; let mut nodes: Vec<Node> = vec![Node::default(); lines.len()]; for ln in 0..lines.len() { nodes.insert(ln, Node::default()); } locations.insert(l.id, nodes); } Some(( nm.iter().map(|x| x.1.clone()).collect::<Vec<Node>>(), locations, )) } fn find_or_insert_node(nm: &mut NodeMap, info: NodeInfo, kept: NodeSet) -> Option<Node> { None } fn find_or_insert_line<T: Fn(&[i64]) -> i64, U: Fn(i64, String) -> String>( nm: &NodeMap, l: &profile::location::Location, line: profile::line::Line, o: &Options<T, U>, ) -> Option<Node> { let mut objfile = String::new(); if let Some(m) = &l.mapping { if !m.filename.is_empty() { objfile = m.filename.clone(); } } let mut node_info = Graph::node_info(l, line, objfile, o); None } fn node_info<T: Fn(&[i64]) -> i64, U: Fn(i64, String) -> String>( l: &profile::location::Location, line: profile::line::Line, objfile: String, o: &Options<T, U>, ) -> NodeInfo { if line.function == profile::function::Function::default() { return NodeInfo { address: l.address, objfile, ..Default::default() }; } let mut ni = NodeInfo { address: l.address, lineno: line.line, name: line.function.name, ..Default::default() }; if !line.function.filename.is_empty() { let mut buf = PathBuf::from(line.function.filename); buf.clear(); ni.file = buf.to_str().unwrap().to_string(); } if o.orig_fn_names { ni.orig_name = line.function.system_name; } if o.obj_names || (ni.name.is_empty() && ni.orig_name.is_empty()) { ni.objfile = objfile; ni.start_line = line.function.start_line; } ni } } #[derive(Debug)] struct Options<T, U> where T: Fn(&[i64]) -> i64, U: Fn(i64, String) -> String, { sample_value: T, sample_mean_divisor: T, format_tag: U, obj_names: bool, orig_fn_names: bool, call_tree: bool, drop_negative: bool, kept_nodes: HashMap<NodeInfo, bool>, } #[derive(Clone, Debug, Eq, Default)] struct Node { info: NodeInfo, function: Box<Node>, flat: i64, flat_div: i64, cum: i64, cum_div: i64, r#in: HashMap<Node, Edge>, out: HashMap<Node, Edge>, label_tags: HashMap<String, Tag>, numeric_tags: HashMap<String, HashMap<String, Tag>>, } impl Hash for Node { fn hash<H: Hasher>(&self, state: &mut H) { self.info.hash(state); self.function.hash(state); self.flat.hash(state); self.flat_div.hash(state); self.cum.hash(state); self.cum_div.hash(state); } } impl PartialEq for Node { fn eq(&self, other: &Self) -> bool { self.flat == other.flat && self.info == other.info && self.function == other.function && self.flat_div == other.flat_div && self.cum == other.cum && self.cum_div == other.cum_div && self.r#in == other.r#in && self.out == other.out && self.label_tags == other.label_tags && self.numeric_tags == other.numeric_tags } } impl Node { pub fn new() -> Self { Node::default() } pub fn flat_value(&self) -> i64 { if self.flat_div == 0 { return self.flat; } self.flat / self.flat_div } pub fn cum_value(&self) -> i64 { if self.cum_div == 0 { return self.cum; } self.cum / self.cum_div } pub fn add_to_edge(&mut self, to: &mut Node, v: i64, residual: bool, inline: bool) { self.add_to_edge_div(to, 0, v, residual, inline); } pub fn add_to_edge_div( &mut self, to: &mut Node, dv: i64, v: i64, residual: bool, inline: bool, ) { if let Some(node1) = self.r#in.get(to) { if let Some(node2) = self.out.get(self) { if node1 != node2 { panic!("asymmetric edges {:?} {:?}", self, to); } } } if let Some(e) = self.r#in.get_mut(to) { e.weight_div += dv; e.weight += v; if residual { e.residual = true; } if !inline { e.inline = false; } return; } let info = Edge { src: self.clone(), dest: to.clone(), weight_div: dv, weight: v, residual, inline, }; self.out.insert(to.clone(), info.clone()); to.r#in.insert(self.clone(), info); } } #[derive(Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Default)] struct NodeInfo { name: String, orig_name: String, address: u64, file: String, start_line: i64, lineno: i64, objfile: String, } impl NodeInfo { pub fn printable_name(&self) -> String { self.name_components().join(" ") } pub fn name_components(&self) -> Vec<String> { let mut name = vec![]; if self.address != 0 { name.push(format!("{:x}", self.address)); } if !self.name.is_empty() { name.push(self.name.to_string()); } if self.lineno != 0 { name.push(format!("{}:{}", self.file, self.lineno)); } if !self.file.is_empty() { name.push(self.file.to_string()); } if !self.name.is_empty() { name.push(self.name.to_string()); } if !self.objfile.is_empty() { name.push(format!("[{}]", get_basename(&self.objfile, SEPARATOR))); } if name.is_empty() { name.push("<unknown>".to_string()); } name } } fn get_basename<'a>(path: &'a str, pat: &'a str) -> String { let mut parts = path.rsplit(pat); match parts.next() { None => "".into(), Some(path) => path.into(), } } #[derive(Clone, Debug, Hash, Eq, PartialEq)] struct Edge { src: Node, dest: Node, weight: i64, weight_div: i64, residual: bool, inline: bool, } impl Edge { pub fn weight_value(&self) -> i64 { if self.weight_div == 0 { return self.weight; } self.weight / self.weight_div } } #[derive(Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Default)] struct Tag { name: String, unit: String, value: i64, flat: i64, flat_div: i64, cum: i64, cum_div: i64, } impl Tag { pub fn cum_value(&self) -> i64 { if self.cum_div == 0 { return self.cum; } self.cum / self.cum_div } pub fn flat_value(&self) -> i64 { if self.flat_div == 0 { return self.flat; } self.flat / self.flat_div } } #[cfg(test)] mod tests { use crate::graph::{get_basename, SEPARATOR}; #[test] fn test_get_basename() { assert_eq!(get_basename("/usr/data", SEPARATOR), "data"); assert_eq!(get_basename("/", SEPARATOR), ""); assert_eq!(get_basename("/root", SEPARATOR), "root"); } }
fn init_graph<T: Fn(&[i64]) -> i64, U: Fn(i64, String) -> String>( &self, prof: Profile, o: Options<T, U>, ) -> Self { Graph { nodes: vec![] } }
function_block-full_function
[ { "content": "#[inline]\n\n#[allow(unused_assignments)]\n\npub fn decode_field(buf: &mut Buffer, data: &mut Vec<u8>) -> Result<Vec<u8>, RockError> {\n\n let result = decode_varint(data);\n\n match result {\n\n Ok(varint) => {\n\n // decode\n\n // 90 -> 1011010\n\n /...
Rust
src/args.rs
anthraxx/dfrs
ea645d6a9d36510005a08dc6729884e1171cc068
#![allow(clippy::use_self)] use structopt::clap::{AppSettings, Shell}; use structopt::StructOpt; use std::io::stdout; use anyhow::Result; use lazy_static::lazy_static; use std::path::PathBuf; use strum::VariantNames; use strum_macros::{EnumString, EnumVariantNames, ToString}; #[derive(Debug, StructOpt)] #[structopt(about="Display file system space usage using graphs and colors.", global_settings = &[AppSettings::ColoredHelp, AppSettings::DeriveDisplayOrder])] pub struct Args { #[structopt(short = "a", group = "display_group", parse(from_occurrences))] pub display: u8, #[structopt(long, group = "display_group")] pub more: bool, #[structopt(long, group = "display_group")] pub all: bool, #[structopt(long, group = "color_group", possible_values=&ColorOpt::VARIANTS)] pub color: Option<ColorOpt>, #[structopt(short = "c", group = "color_group")] pub color_always: bool, #[structopt(short, long)] pub inodes: bool, #[structopt(short = "h", long = "human-readable", group = "number_format")] pub base2: bool, #[structopt(short = "H", long = "si", group = "number_format")] pub base10: bool, #[structopt(long)] pub total: bool, #[structopt(short, long)] pub local: bool, #[structopt(long)] pub no_aliases: bool, #[structopt(long, parse(from_os_str), default_value = "/proc/self/mounts")] pub mounts: PathBuf, #[structopt(short)] pub verbose: bool, #[structopt(parse(from_os_str))] pub paths: Vec<PathBuf>, #[structopt(long, use_delimiter = true, possible_values = &ColumnType::VARIANTS, default_value = &COLUMNS_OPT_DEFAULT_VALUE)] pub columns: Vec<ColumnType>, #[structopt(subcommand)] pub subcommand: Option<SubCommand>, } #[derive(Debug, StructOpt)] pub enum SubCommand { #[structopt(name = "completions")] Completions(Completions), } #[derive(Debug, StructOpt, ToString, EnumString, EnumVariantNames)] #[strum(serialize_all = "lowercase")] pub enum ColorOpt { Auto, Always, Never, } #[derive(Debug, StructOpt, EnumString)] #[strum(serialize_all = "lowercase")] pub enum DisplayFilter { Minimal, More, All, } impl DisplayFilter { pub const fn from_u8(n: u8) -> Self { match n { 0 => Self::Minimal, 1 => Self::More, _ => Self::All, } } pub fn get_mnt_fsname_filter(&self) -> Vec<&'static str> { match self { Self::Minimal => vec!["/dev*", "storage"], Self::More => vec!["dev", "run", "tmpfs", "/dev*", "storage"], Self::All => vec!["*"], } } } #[derive(Debug, StructOpt)] pub enum NumberFormat { Base10, Base2, } impl NumberFormat { pub const fn get_powers_of(&self) -> f64 { match self { Self::Base10 => 1000_f64, Self::Base2 => 1024_f64, } } } #[derive(Debug, StructOpt, ToString, EnumString, EnumVariantNames)] #[strum(serialize_all = "snake_case")] pub enum ColumnType { Filesystem, Type, Bar, Used, UsedPercentage, Available, AvailablePercentage, Capacity, MountedOn, } impl ColumnType { pub const fn label(&self, inodes_mode: bool) -> &str { match self { Self::Filesystem => "Filesystem", Self::Type => "Type", Self::Bar => "", Self::Used => "Used", Self::UsedPercentage => "Used%", Self::Available => "Avail", Self::AvailablePercentage => "Avail%", Self::Capacity => { if inodes_mode { "Inodes" } else { "Size" } } Self::MountedOn => "Mounted on", } } } lazy_static! { static ref COLUMNS_OPT_DEFAULT_VALUE: String = vec![ ColumnType::Filesystem, ColumnType::Type, ColumnType::Bar, ColumnType::UsedPercentage, ColumnType::Available, ColumnType::Used, ColumnType::Capacity, ColumnType::MountedOn ] .iter() .map(|e| e.to_string()) .collect::<Vec<String>>() .join(","); } #[derive(Debug, StructOpt)] pub struct Completions { #[structopt(possible_values=&Shell::variants())] pub shell: Shell, } pub fn gen_completions(args: &Completions) -> Result<()> { Args::clap().gen_completions_to("dfrs", args.shell, &mut stdout()); Ok(()) }
#![allow(clippy::use_self)] use structopt::clap::{AppSettings, Shell}; use structopt::StructOpt; use std::io::stdout; use anyhow::Result; use lazy_static::lazy_static; use std::path::PathBuf; use strum::VariantNames; use strum_macros::{EnumString, EnumVariantNames, ToString}; #[derive(Debug, StructOpt)] #[structopt(about="Display file system space usage using graphs and colors.", global_settings = &[AppSettings::ColoredHelp, AppSettings::DeriveDisplayOrder])] pub struct Args { #[structopt(short = "a", group = "display_group", parse(from_occurrences))] pub display: u8, #[structopt(long, group = "display_group")] pub more: bool, #[structopt(long, group = "display_group")] pub all: bool, #[structopt(long, group = "color_group", possible_values=&ColorOpt::VARIANTS)] pub color: Option<ColorOpt>, #[structopt(short = "c", group = "color_group")] pub color_always: bool, #[structopt(short, long)] pub inodes: bool, #[structopt(short = "h", long = "human-readable", group = "number_format")] pub base2: bool, #[structopt(short = "H", long = "si", group = "number_format")] pub base10: bool, #[structopt(long)] pub total: bool, #[structopt(short, long)] pub local: bool, #[structopt(long)] pub no_aliases: bool, #[structopt(long, parse(from_os_str), default_value = "/proc/self/mounts")] pub mounts: PathBuf, #[structopt(short)] pub verbose: bool, #[structopt(parse(from_os_str))] pub paths: Vec<PathBuf>, #[structopt(long, use_delimiter = true, possible_values = &ColumnType::VARIANTS, default_value = &COLUMNS_OPT_DEFAULT_VALUE)] pub columns: Vec<ColumnType>, #[structopt(subcommand)] pub subcommand: Option<SubCommand>, } #[derive(Debug, StructOpt)] pub enum SubCommand { #[structopt(name = "completions")] Completions(Completions), } #[derive(Debug, StructOpt, ToString, EnumString, EnumVariantNames)] #[strum(serialize_all = "lowercase")] pub enum ColorOpt { Auto, Always, Never, } #[derive(Debug, StructOpt, EnumString)] #[strum(serialize_all = "lowercase")] pub enum DisplayFilter { Minimal, More, All, } impl DisplayFilter { pub const fn from_u8(n: u8) -> Self { match n { 0 => Self::Minimal, 1 => Self::More, _ => Self::All, } } pub fn get_mnt_fsname_filter(&self) -> Vec<&'static str> { match self { Self::Minimal => vec!["/dev*", "storage"], Self::More => vec!["dev", "run", "tmpfs", "/dev*", "storage"], Self::All => vec!["*"], } } } #[derive(Debug, StructOpt)] pub enum NumberFormat { Base10, Base2, } impl NumberFormat { pub const fn get_powers_of(&self) -> f64 { m
ble_values=&Shell::variants())] pub shell: Shell, } pub fn gen_completions(args: &Completions) -> Result<()> { Args::clap().gen_completions_to("dfrs", args.shell, &mut stdout()); Ok(()) }
atch self { Self::Base10 => 1000_f64, Self::Base2 => 1024_f64, } } } #[derive(Debug, StructOpt, ToString, EnumString, EnumVariantNames)] #[strum(serialize_all = "snake_case")] pub enum ColumnType { Filesystem, Type, Bar, Used, UsedPercentage, Available, AvailablePercentage, Capacity, MountedOn, } impl ColumnType { pub const fn label(&self, inodes_mode: bool) -> &str { match self { Self::Filesystem => "Filesystem", Self::Type => "Type", Self::Bar => "", Self::Used => "Used", Self::UsedPercentage => "Used%", Self::Available => "Avail", Self::AvailablePercentage => "Avail%", Self::Capacity => { if inodes_mode { "Inodes" } else { "Size" } } Self::MountedOn => "Mounted on", } } } lazy_static! { static ref COLUMNS_OPT_DEFAULT_VALUE: String = vec![ ColumnType::Filesystem, ColumnType::Type, ColumnType::Bar, ColumnType::UsedPercentage, ColumnType::Available, ColumnType::Used, ColumnType::Capacity, ColumnType::MountedOn ] .iter() .map(|e| e.to_string()) .collect::<Vec<String>>() .join(","); } #[derive(Debug, StructOpt)] pub struct Completions { #[structopt(possi
random
[ { "content": "pub fn parse_mounts(f: File) -> Result<Vec<Mount>> {\n\n BufReader::new(f)\n\n .lines()\n\n .map(|line| {\n\n parse_mount_line(&line?)\n\n .context(\"Failed to parse mount line\")\n\n .map_err(Error::from)\n\n })\n\n .collect:...
Rust
rust/k210-shared/src/soc/sysctl/pll_compute.rs
egcd32/k210-sdk-stuff
ab95e18ba81e011f721237472b1f5434506fd7fb
use core::convert::TryInto; use libm::F64Ext; /** PLL configuration */ #[derive(Debug, PartialEq, Eq)] pub struct Params { pub clkr: u8, pub clkf: u8, pub clkod: u8, pub bwadj: u8, } /* constants for PLL frequency computation */ const VCO_MIN: f64 = 3.5e+08; const VCO_MAX: f64 = 1.75e+09; const REF_MIN: f64 = 1.36719e+07; const REF_MAX: f64 = 1.75e+09; const NR_MIN: i32 = 1; const NR_MAX: i32 = 16; const NF_MIN: i32 = 1; const NF_MAX: i32 = 64; const NO_MIN: i32 = 1; const NO_MAX: i32 = 16; const NB_MIN: i32 = 1; const NB_MAX: i32 = 64; const MAX_VCO: bool = true; const REF_RNG: bool = true; /* * Calculate PLL registers' value by finding closest matching parameters * NOTE: this uses floating point math ... this is horrible for something so critical :-( * TODO: implement this without fp ops */ pub fn compute_params(freq_in: u32, freq_out: u32) -> Option<Params> { let fin: f64 = freq_in.into(); let fout: f64 = freq_out.into(); let val: f64 = fout / fin; let terr: f64 = 0.5 / ((NF_MAX / 2) as f64); let mut merr: f64 = terr; let mut x_nrx: i32 = 0; let mut x_no: i32 = 0; let mut found: Option<Params> = None; for nfi in (val as i32)..NF_MAX { let nr: i32 = ((nfi as f64) / val).round() as i32; if nr == 0 { continue; } if REF_RNG && (nr < NR_MIN) { continue; } if fin / (nr as f64) > REF_MAX { continue; } let mut nrx: i32 = nr; let mut nf: i32 = nfi; let mut nfx: i64 = nfi.into(); let nval: f64 = (nfx as f64) / (nr as f64); if nf == 0 { nf = 1; } let err: f64 = 1.0 - nval / val; if (err.abs() < merr * (1.0 + 1e-6)) || (err.abs() < 1e-16) { let mut not: i32 = (VCO_MAX / fout).floor() as i32; let mut no: i32 = if not > NO_MAX { NO_MAX } else { not }; while no > NO_MIN { if (REF_RNG) && ((nr / no) < NR_MIN) { no -= 1; continue; } if (nr % no) == 0 { break; } no -= 1; } if (nr % no) != 0 { continue; } let mut nor: i32 = (if not > NO_MAX { NO_MAX } else { not }) / no; let mut nore: i32 = NF_MAX / nf; if nor > nore { nor = nore; } let noe: i32 = (VCO_MIN / fout).ceil() as i32; if !MAX_VCO { nore = (noe - 1) / no + 1; nor = nore; not = 0; /* force next if to fail */ } if (((no * nor) < (not >> 1)) || ((no * nor) < noe)) && ((no * nor) < (NF_MAX / nf)) { no = NF_MAX / nf; if no > NO_MAX { no = NO_MAX; } if no > not { no = not; } nfx *= no as i64; nf *= no; if (no > 1) && !found.is_none() { continue; } /* wait for larger nf in later iterations */ } else { nrx /= no; nfx *= nor as i64; nf *= nor; no *= nor; if no > NO_MAX { continue; } if (nor > 1) && !found.is_none() { continue; } /* wait for larger nf in later iterations */ } let mut nb: i32 = nfx as i32; if nb < NB_MIN { nb = NB_MIN; } if nb > NB_MAX { continue; } let fvco: f64 = fin / (nrx as f64) * (nfx as f64); if fvco < VCO_MIN { continue; } if fvco > VCO_MAX { continue; } if nf < NF_MIN { continue; } if REF_RNG && (fin / (nrx as f64) < REF_MIN) { continue; } if REF_RNG && (nrx > NR_MAX) { continue; } if found.is_some() { if !((err.abs() < merr * (1.0 - 1e-6)) || (MAX_VCO && (no > x_no))) { continue; } if nrx > x_nrx { continue; } } found = Some(Params { clkr: (nrx - 1).try_into().unwrap(), clkf: (nfx - 1).try_into().unwrap(), clkod: (no - 1).try_into().unwrap(), bwadj: (nb - 1).try_into().unwrap(), }); merr = err.abs(); x_no = no; x_nrx = nrx; } } if merr >= terr * (1.0 - 1e-6) { None } else { found } } #[cfg(test)] mod tests { use super::*; #[test] fn test_ompute_params() { /* check against output of C implementation */ assert_eq!(compute_params(26_000_000, 1_500_000_000), Some(Params { clkr: 0, clkf: 57, clkod: 0, bwadj: 57 })); assert_eq!(compute_params(26_000_000, 1_000_000_000), Some(Params { clkr: 0, clkf: 37, clkod: 0, bwadj: 37 })); assert_eq!(compute_params(26_000_000, 800_000_000), Some(Params { clkr: 0, clkf: 61, clkod: 1, bwadj: 61 })); assert_eq!(compute_params(26_000_000, 700_000_000), Some(Params { clkr: 0, clkf: 53, clkod: 1, bwadj: 53 })); assert_eq!(compute_params(26_000_000, 300_000_000), Some(Params { clkr: 0, clkf: 45, clkod: 3, bwadj: 45 })); assert_eq!(compute_params(26_000_000, 45_158_400), Some(Params { clkr: 0, clkf: 25, clkod: 14, bwadj: 25 })); } }
use core::convert::TryInto; use libm::F64Ext; /** PLL configuration */ #[derive(Debug, PartialEq, Eq)] pub struct Params { pub clkr: u8, pub clkf: u8, pub clkod: u8, pub bwadj: u8, } /* constants for PLL frequency computation */ const VCO_MIN: f64 = 3.5e+08; const VCO_MAX: f64 = 1.75e+09; const REF_MIN: f64 = 1.36719e+07; const REF_MAX: f64 = 1.75e+09; const NR_MIN: i32 = 1; const NR_MAX: i32 = 16; const NF_MIN: i32 = 1; const NF_MAX: i32 = 64; const NO_MIN: i32 = 1; const NO_MAX: i32 = 16; const NB_MIN: i32 = 1; const NB_MAX: i32 = 64; const MAX_VCO: bool = true; const REF_RNG: bool = true; /* * Calculate PLL registers' value by finding closest matching parameters * NOTE: this uses floating point math ... this is horrible for something so critical :-( * TODO: implement this without fp ops */ pub fn compute_params(freq_in: u32, freq_out: u32) -> Option<Params> { let fin: f64 = freq_in.into(); let fout: f64 = freq_out.into(); let val: f64 = fout / fin; let terr: f64 = 0.5 / ((NF_MAX / 2) as f64); let mut merr: f64 = terr; let mut x_nrx: i32 = 0; let mut x_no: i32 = 0; let mut found: Option<Params> = None; for nfi in (val as i32)..NF_MAX { let nr: i32 = ((nfi as f64) / val).round() as i32; if nr == 0 { continue; } if REF_RNG && (nr < NR_MIN) { continue; } if fin / (nr as f64) > REF_MAX { continue; } let mut nrx: i32 = nr; let mut nf: i32 = nfi; let mut nfx: i64 = nfi.into(); let nval: f64 = (nfx as f64) / (nr as f64); if nf == 0 { nf = 1; } let err: f64 = 1.0 - nval / val; if (err.abs() < merr * (1.0 + 1e-6)) || (err.abs() < 1e-16) { let mut not: i32 = (VCO_MAX / fout).floor() as i32; let mut no: i32 = if not > NO_MAX { NO_MAX } else { not }; while no > NO_MIN { if (REF_RNG) && ((nr / no) < NR_MIN) { no -= 1; continue; } if (nr % no) == 0 { break; } no -= 1; } if (nr % no) != 0 { continue; } let mut nor: i32 = (if not > NO_MAX { NO_MAX } else { not }) / no; let mut nore: i32 = NF_MAX / nf; if nor > nore { nor = nore; } let noe: i32 = (VCO_MIN / fout).ceil() as i32; if !MAX_VCO { nore = (noe - 1) / no + 1; nor = nore; not = 0; /* force next if to fail */ } if (((no * nor) < (not >> 1)) || ((no * nor) < noe)) && ((no * nor) < (NF_MAX / nf)) { no = NF_MAX / nf; if no > NO_MAX { no = NO_MAX; } if no > not { no = not; } nfx *= no as i64; nf *= no; if (no > 1) && !found.is_none() { continue; } /* wait for larger nf in later iterations */ } else { nrx /= no; nfx *= nor as i64; nf *= nor; no *= nor; if no > NO_MAX { continue; } if (nor > 1) && !found.is_none() { continue; } /* wait for larger nf in later iterations */ } let mut nb: i32 = nfx as i32; if nb < NB_MIN { nb = NB_MIN; } if nb > NB_MAX { continue; } let fvco: f64 = fin / (nrx as f64) * (nfx as f64); if fvco < VCO_MIN { continue; } if fvco > VCO_MAX { continue; } if nf < NF_MIN { continue; } if REF_RNG && (fin / (nrx as f64) < REF_MIN) { continue; } if REF_RNG && (nrx > NR_MAX) { continue; } if found.is_some() { if !((err.abs() < merr * (1.0 - 1e-6)) || (MAX_VCO && (no > x_no))) { continue; } if nrx > x_nrx { continue; } } found = Some(Params { clkr: (nrx - 1).try_into().unwrap(), clkf: (nfx - 1).try_into().unwrap(), clkod: (no - 1).try_into().unwrap(), bwadj: (nb - 1).try_into().unwrap(), }); merr = err.abs(); x_no = no; x_nrx = nrx; } } if merr >= terr * (1.0 - 1e-6) { None } else { found } } #[cfg(test)] mod tests { use super::*; #[test]
}
fn test_ompute_params() { /* check against output of C implementation */ assert_eq!(compute_params(26_000_000, 1_500_000_000), Some(Params { clkr: 0, clkf: 57, clkod: 0, bwadj: 57 })); assert_eq!(compute_params(26_000_000, 1_000_000_000), Some(Params { clkr: 0, clkf: 37, clkod: 0, bwadj: 37 })); assert_eq!(compute_params(26_000_000, 800_000_000), Some(Params { clkr: 0, clkf: 61, clkod: 1, bwadj: 61 })); assert_eq!(compute_params(26_000_000, 700_000_000), Some(Params { clkr: 0, clkf: 53, clkod: 1, bwadj: 53 })); assert_eq!(compute_params(26_000_000, 300_000_000), Some(Params { clkr: 0, clkf: 45, clkod: 3, bwadj: 45 })); assert_eq!(compute_params(26_000_000, 45_158_400), Some(Params { clkr: 0, clkf: 25, clkod: 14, bwadj: 25 })); }
function_block-full_function
[ { "content": "pub fn set_bit(inval: u32, bit: u8, state: bool) -> u32 {\n\n if state {\n\n inval | (1 << u32::from(bit))\n\n } else {\n\n inval & !(1 << u32::from(bit))\n\n }\n\n}\n\n\n", "file_path": "rust/k210-shared/src/soc/utils.rs", "rank": 1, "score": 305117.4159386919 ...
Rust
src/support/mod.rs
Twinklebear/tobj_viewer
c6f59993eb4bf0a7b1262602fec17884ec48c1f3
#![allow(dead_code)] extern crate clock_ticks; extern crate tobj; use glium::vertex::VertexBufferAny; use glium::{self, Display}; use std::f32; use std::path::Path; use std::thread; use std::time::{Duration, Instant}; pub mod camera; pub enum Action { Stop, Continue, } pub fn start_loop<F>(mut callback: F) where F: FnMut() -> Action, { let mut accumulator = Duration::new(0, 0); let mut previous_clock = Instant::now(); loop { match callback() { Action::Stop => break, Action::Continue => (), }; let now = Instant::now(); accumulator += now - previous_clock; previous_clock = now; let fixed_time_stamp = Duration::new(0, 16666667); while accumulator >= fixed_time_stamp { accumulator -= fixed_time_stamp; } thread::sleep(fixed_time_stamp - accumulator); } } pub fn load_wavefront(display: &Display, path: &Path) -> (VertexBufferAny, f32) { #[derive(Copy, Clone)] struct Vertex { position: [f32; 3], normal: [f32; 3], color_diffuse: [f32; 3], color_specular: [f32; 4], } implement_vertex!(Vertex, position, normal, color_diffuse, color_specular); let mut min_pos = [f32::INFINITY; 3]; let mut max_pos = [f32::NEG_INFINITY; 3]; let mut vertex_data = Vec::new(); match tobj::load_obj(path) { Ok((models, mats)) => { for model in &models { let mesh = &model.mesh; println!("Uploading model: {}", model.name); for idx in &mesh.indices { let i = *idx as usize; let pos = [ mesh.positions[3 * i], mesh.positions[3 * i + 1], mesh.positions[3 * i + 2], ]; let normal = if !mesh.normals.is_empty() { [ mesh.normals[3 * i], mesh.normals[3 * i + 1], mesh.normals[3 * i + 2], ] } else { [0.0, 0.0, 0.0] }; let (color_diffuse, color_specular) = match mesh.material_id { Some(i) => ( mats[i].diffuse, [ mats[i].specular[0], mats[i].specular[1], mats[i].specular[2], mats[i].shininess, ], ), None => ([0.8, 0.8, 0.8], [0.15, 0.15, 0.15, 15.0]), }; vertex_data.push(Vertex { position: pos, normal: normal, color_diffuse: color_diffuse, color_specular: color_specular, }); for i in 0..3 { min_pos[i] = f32::min(min_pos[i], pos[i]); max_pos[i] = f32::max(max_pos[i], pos[i]); } } } } Err(e) => panic!("Loading of {:?} failed due to {:?}", path, e), } let diagonal_len = 6.0; let current_len = f32::powf(max_pos[0] - min_pos[0], 2.0) + f32::powf(max_pos[1] - min_pos[1], 2.0) + f32::powf(max_pos[2] - min_pos[2], 2.0); let scale = f32::sqrt(diagonal_len / current_len); println!("Model scaled by {} to fit", scale); ( glium::vertex::VertexBuffer::new(display, &vertex_data) .unwrap() .into_vertex_buffer_any(), scale, ) }
#![allow(dead_code)] extern crate clock_ticks; extern crate tobj; use glium::vertex::VertexBufferAny; use glium::{self, Display}; use std::f32; use std::path::Path; use std::thread; use std::time::{Duration, Instant}; pub mod camera; pub enum Action { Stop, Continue, } pub fn start_loop<F>(mut callback: F) where F: FnMut() -> Action, { let mut accumulator = Duration::new(0, 0); let mut previous_clock = Instant::now(); loop { match callback() { Action::Stop => break, Action::Continue => (), }; let now = Instant::now(); accumulator += now - previous_clock; previous_clock = now; let fixed_time_stamp = Duration::new(0, 16666667); while accumulator >= fixed_time_stamp { accumulator -= fixed_time_stamp; } thread::sleep(fixed_time_stamp - accumulator); } } pub fn load_wavefront(display: &Display, path: &Path) -> (VertexBufferAny, f32) { #[derive(Copy, Clone)] struct Vertex { position: [f32; 3], normal: [f32; 3], color_diffuse: [f32; 3], color_specular: [f32; 4], } implement_vertex!(Vertex, position, normal, color_diffuse, color_specular); let mut min_pos = [f32::INFINITY; 3]; let mut max_pos = [f32::NEG_INFINITY; 3]; let mut vertex_data = Vec::new(); match tobj::load_obj(path) { Ok((models, mats)) => { for model in &models { let mesh = &model.mesh; println!("Uploading model: {}", model.name); for idx in &mesh.indices { let i = *idx as usize; let pos = [ mesh.positions[3 * i], mesh.positions[3 * i + 1], mesh.positions[3 * i + 2], ]; let normal = if !mesh.normals.is_empty() { [ mesh.normals[3 * i], mesh.normals[3 * i + 1], mesh.normals[3 * i + 2], ] } else { [0.0, 0.0, 0.0] }; let (color_diffuse, color_specular) = match mesh.material_id { Some(i) => ( mats[i].diffuse, [ mats[i].specular[0], mats[i].specular[1], mats[i].specular[2], mats[i].shininess, ], ), None => ([0.8, 0.8, 0.8], [0.15, 0.15, 0.15, 15.0]), }; vertex_data.push(Vertex { position: pos, normal: normal, color_diffuse: color_diffuse, color_specular: color_specular, }); for i in 0..3 { min_pos[i] = f32::min(min_pos[i], pos[i]); max_pos[i] = f32::max(max_pos[i], pos[i]); } } } } Err(e) => panic!("Loading of {:?} failed due to {:?}", path, e), } let diagonal_len = 6.0; let current_len = f32::powf(max_pos[0] - min_pos[0], 2.0) +
f32::powf(max_pos[1] - min_pos[1], 2.0) + f32::powf(max_pos[2] - min_pos[2], 2.0); let scale = f32::sqrt(diagonal_len / current_len); println!("Model scaled by {} to fit", scale); ( glium::vertex::VertexBuffer::new(display, &vertex_data) .unwrap() .into_vertex_buffer_any(), scale, ) }
function_block-function_prefix_line
[ { "content": "fn show_test_window<'a>(ui: &Ui<'a>, state: &mut State, opened: &mut bool) {\n\n if state.show_app_metrics {\n\n ui.show_metrics_window(&mut state.show_app_metrics);\n\n }\n\n if state.show_app_main_menu_bar { show_example_app_main_menu_bar(ui, state) }\n\n if state.show_app_aut...
Rust
src/ast/pp_visitor.rs
ffwff/iro
2e92ab30bee7f3ab9036726e383edd8ec788fdd9
use crate::ast::*; use crate::compiler::sources; use bit_set::BitSet; use std::path::PathBuf; pub struct PreprocessState { imported: BitSet<u32>, total_imported_statements: Vec<NodeBox>, prelude: Option<PathBuf>, } impl PreprocessState { pub fn new(prelude: Option<PathBuf>) -> Self { Self { imported: BitSet::new(), total_imported_statements: vec![], prelude, } } } pub struct PreprocessVisitor<'a> { file: sources::FileIndex, working_path: Option<PathBuf>, state: Option<&'a RefCell<PreprocessState>>, sources: &'a mut sources::Sources, } impl<'a> PreprocessVisitor<'a> { pub fn postprocess( program: &mut Program, file: sources::FileIndex, working_path: Option<PathBuf>, state: Option<&'a RefCell<PreprocessState>>, sources: &'a mut sources::Sources, ) -> VisitorResult { let mut visitor = Self { file, working_path, state, sources, }; visitor.visit_program(program) } fn fill_box(&self, boxed: &NodeBox) { boxed.span_ref().update(|mut span| { span.file = self.file; span }); } fn ungenerate_retvar(b: &NodeBox) { b.generate_retvar.set(false); } fn import(&mut self, working_path: PathBuf) -> VisitorResult { if let Some(mut state) = self.state.as_ref().map(|x| x.borrow_mut()) { let sources = &mut self.sources; let (index, _) = sources .read(&working_path) .map_err(|error| compiler::Error::io_error(error))?; if state.imported.insert(index) { std::mem::drop(state); let ast = compiler::parse_file_to_ast( index, working_path, sources, self.state.clone().unwrap(), ) .map_err(|err| { err.span.map(|mut span| { span.file = index; span }); err })?; let mut state = self.state.as_ref().unwrap().borrow_mut(); state .total_imported_statements .extend(ast.exprs.into_iter().filter(|ast| ast.can_import())); } } Ok(()) } } impl<'a> Visitor for PreprocessVisitor<'a> { fn visit_program(&mut self, n: &mut Program) -> VisitorResult { for node in &n.exprs { Self::ungenerate_retvar(node); node.visit(self)?; } if self.file == 0 { if let Some(state_cell) = self.state { { let state = state_cell.borrow(); if let Some(prelude) = &state.prelude { let mut working_path = std::env::current_dir() .map_err(|error| compiler::Error::io_error(error))?; working_path.push(prelude); working_path = std::fs::canonicalize(working_path) .map_err(|error| compiler::Error::io_error(error))?; std::mem::drop(state); self.import(working_path)?; } } let mut state = state_cell.borrow_mut(); n.exprs.extend(std::mem::replace( &mut state.total_imported_statements, vec![], )); } } Ok(()) } fn visit_import(&mut self, n: &ImportStatement, b: &NodeBox) -> VisitorResult { self.fill_box(b); let mut working_path = self.working_path.clone().unwrap(); working_path.pop(); working_path.push(&n.path); working_path.set_extension("iro"); working_path = std::fs::canonicalize(working_path) .map_err(|error| compiler::Error::io_error(error))?; self.import(working_path)?; Ok(()) } fn visit_class(&mut self, _n: &ClassStatement, b: &NodeBox) -> VisitorResult { self.fill_box(b); Ok(()) } fn visit_class_init(&mut self, n: &ClassInitExpr, b: &NodeBox) -> VisitorResult { self.fill_box(b); for (_, boxed) in &n.inits { boxed.visit(self)?; } Ok(()) } fn visit_modstmt(&mut self, n: &ModStatement, b: &NodeBox) -> VisitorResult { self.fill_box(b); for expr in &n.exprs { expr.visit(self)?; } Ok(()) } fn visit_defstmt(&mut self, n: &DefStatement, b: &NodeBox) -> VisitorResult { self.fill_box(b); let last_idx = n.exprs.len().wrapping_sub(1); for (idx, expr) in n.exprs.iter().enumerate() { if idx != last_idx { Self::ungenerate_retvar(expr); } expr.visit(self)?; } Ok(()) } fn visit_return(&mut self, n: &ReturnExpr, b: &NodeBox) -> VisitorResult { self.fill_box(b); n.expr.visit(self)?; Ok(()) } fn visit_whileexpr(&mut self, n: &WhileExpr, b: &NodeBox) -> VisitorResult { self.fill_box(b); n.cond.visit(self)?; let last_idx = n.exprs.len().wrapping_sub(1); for (idx, expr) in n.exprs.iter().enumerate() { if idx != last_idx { Self::ungenerate_retvar(expr); } expr.visit(self)?; } Ok(()) } fn visit_ifexpr(&mut self, n: &IfExpr, b: &NodeBox) -> VisitorResult { self.fill_box(b); n.cond.visit(self)?; let last_idx = n.exprs.len().wrapping_sub(1); for (idx, expr) in n.exprs.iter().enumerate() { if idx != last_idx && !b.generate_retvar.get() { Self::ungenerate_retvar(expr); } expr.visit(self)?; } let last_idx = n.elses.len().wrapping_sub(1); for (idx, expr) in n.elses.iter().enumerate() { if idx != last_idx && !b.generate_retvar.get() { Self::ungenerate_retvar(expr); } expr.visit(self)?; } Ok(()) } fn visit_callexpr(&mut self, n: &CallExpr, b: &NodeBox) -> VisitorResult { self.fill_box(b); for expr in &n.args { expr.visit(self)?; } Ok(()) } fn visit_letexpr(&mut self, n: &LetExpr, b: &NodeBox) -> VisitorResult { self.fill_box(b); n.left.visit(self)?; n.right.visit(self)?; Ok(()) } fn visit_binexpr(&mut self, n: &BinExpr, b: &NodeBox) -> VisitorResult { self.fill_box(b); n.left.visit(self)?; n.right.visit(self)?; Ok(()) } fn visit_asexpr(&mut self, n: &AsExpr, b: &NodeBox) -> VisitorResult { self.fill_box(b); n.left.visit(self)?; Ok(()) } fn visit_member_expr(&mut self, n: &MemberExpr, b: &NodeBox) -> VisitorResult { self.fill_box(b); n.left.visit(self)?; for arm in &n.right { if let MemberExprArm::Index(boxed) = arm { boxed.visit(self)?; } } Ok(()) } fn visit_value(&mut self, n: &Value, b: &NodeBox) -> VisitorResult { self.fill_box(b); if let Value::Slice(vec) = &n { for expr in vec { expr.visit(self)?; } } Ok(()) } fn visit_typeid(&mut self, _n: &TypeId, b: &NodeBox) -> VisitorResult { self.fill_box(b); Ok(()) } fn visit_break(&mut self, _n: &BreakExpr, b: &NodeBox) -> VisitorResult { self.fill_box(b); Ok(()) } fn visit_borrow(&mut self, n: &BorrowExpr, b: &NodeBox) -> VisitorResult { self.fill_box(b); n.expr.visit(self)?; Ok(()) } fn visit_deref(&mut self, n: &DerefExpr, b: &NodeBox) -> VisitorResult { self.fill_box(b); n.expr.visit(self)?; Ok(()) } fn visit_unary(&mut self, n: &UnaryExpr, b: &NodeBox) -> VisitorResult { self.fill_box(b); n.expr.visit(self)?; Ok(()) } fn visit_path(&mut self, _n: &PathExpr, b: &NodeBox) -> VisitorResult { self.fill_box(b); Ok(()) } }
use crate::ast::*; use crate::compiler::sources; use bit_set::BitSet; use std::path::PathBuf; pub struct PreprocessState { imported: BitSet<u32>, total_imported_statements: Vec<NodeBox>, prelude: Option<PathBuf>, } impl PreprocessState { pub fn new(prelude: Option<PathBuf>) -> Self { Self { imported: BitSet::new(), total_imported_statements: vec![], prelude, } } } pub struct PreprocessVisitor<'a> { file: sources::FileIndex, working_path: Option<PathBuf>, state: Option<&'a RefCell<PreprocessState>>, sources: &'a mut sources::Sources, } impl<'a> PreprocessVisitor<'a> { pub fn postprocess( program: &mut Program, file: sources::FileIndex, working_path: Option<PathBuf>, state: Option<&'a RefCell<PreprocessState>>, sources: &'a mut sources::Sources, ) -> VisitorResult { let mut visitor = Self { file, working_path, state, sources, }; visitor.visit_program(program) } fn fill_box(&self, boxed: &NodeBox) { boxed.span_ref().update(|mut span| { span.file = self.file; span }); } fn ungenerate_retvar(b: &NodeBox) { b.generate_retvar.set(false); }
} impl<'a> Visitor for PreprocessVisitor<'a> { fn visit_program(&mut self, n: &mut Program) -> VisitorResult { for node in &n.exprs { Self::ungenerate_retvar(node); node.visit(self)?; } if self.file == 0 { if let Some(state_cell) = self.state { { let state = state_cell.borrow(); if let Some(prelude) = &state.prelude { let mut working_path = std::env::current_dir() .map_err(|error| compiler::Error::io_error(error))?; working_path.push(prelude); working_path = std::fs::canonicalize(working_path) .map_err(|error| compiler::Error::io_error(error))?; std::mem::drop(state); self.import(working_path)?; } } let mut state = state_cell.borrow_mut(); n.exprs.extend(std::mem::replace( &mut state.total_imported_statements, vec![], )); } } Ok(()) } fn visit_import(&mut self, n: &ImportStatement, b: &NodeBox) -> VisitorResult { self.fill_box(b); let mut working_path = self.working_path.clone().unwrap(); working_path.pop(); working_path.push(&n.path); working_path.set_extension("iro"); working_path = std::fs::canonicalize(working_path) .map_err(|error| compiler::Error::io_error(error))?; self.import(working_path)?; Ok(()) } fn visit_class(&mut self, _n: &ClassStatement, b: &NodeBox) -> VisitorResult { self.fill_box(b); Ok(()) } fn visit_class_init(&mut self, n: &ClassInitExpr, b: &NodeBox) -> VisitorResult { self.fill_box(b); for (_, boxed) in &n.inits { boxed.visit(self)?; } Ok(()) } fn visit_modstmt(&mut self, n: &ModStatement, b: &NodeBox) -> VisitorResult { self.fill_box(b); for expr in &n.exprs { expr.visit(self)?; } Ok(()) } fn visit_defstmt(&mut self, n: &DefStatement, b: &NodeBox) -> VisitorResult { self.fill_box(b); let last_idx = n.exprs.len().wrapping_sub(1); for (idx, expr) in n.exprs.iter().enumerate() { if idx != last_idx { Self::ungenerate_retvar(expr); } expr.visit(self)?; } Ok(()) } fn visit_return(&mut self, n: &ReturnExpr, b: &NodeBox) -> VisitorResult { self.fill_box(b); n.expr.visit(self)?; Ok(()) } fn visit_whileexpr(&mut self, n: &WhileExpr, b: &NodeBox) -> VisitorResult { self.fill_box(b); n.cond.visit(self)?; let last_idx = n.exprs.len().wrapping_sub(1); for (idx, expr) in n.exprs.iter().enumerate() { if idx != last_idx { Self::ungenerate_retvar(expr); } expr.visit(self)?; } Ok(()) } fn visit_ifexpr(&mut self, n: &IfExpr, b: &NodeBox) -> VisitorResult { self.fill_box(b); n.cond.visit(self)?; let last_idx = n.exprs.len().wrapping_sub(1); for (idx, expr) in n.exprs.iter().enumerate() { if idx != last_idx && !b.generate_retvar.get() { Self::ungenerate_retvar(expr); } expr.visit(self)?; } let last_idx = n.elses.len().wrapping_sub(1); for (idx, expr) in n.elses.iter().enumerate() { if idx != last_idx && !b.generate_retvar.get() { Self::ungenerate_retvar(expr); } expr.visit(self)?; } Ok(()) } fn visit_callexpr(&mut self, n: &CallExpr, b: &NodeBox) -> VisitorResult { self.fill_box(b); for expr in &n.args { expr.visit(self)?; } Ok(()) } fn visit_letexpr(&mut self, n: &LetExpr, b: &NodeBox) -> VisitorResult { self.fill_box(b); n.left.visit(self)?; n.right.visit(self)?; Ok(()) } fn visit_binexpr(&mut self, n: &BinExpr, b: &NodeBox) -> VisitorResult { self.fill_box(b); n.left.visit(self)?; n.right.visit(self)?; Ok(()) } fn visit_asexpr(&mut self, n: &AsExpr, b: &NodeBox) -> VisitorResult { self.fill_box(b); n.left.visit(self)?; Ok(()) } fn visit_member_expr(&mut self, n: &MemberExpr, b: &NodeBox) -> VisitorResult { self.fill_box(b); n.left.visit(self)?; for arm in &n.right { if let MemberExprArm::Index(boxed) = arm { boxed.visit(self)?; } } Ok(()) } fn visit_value(&mut self, n: &Value, b: &NodeBox) -> VisitorResult { self.fill_box(b); if let Value::Slice(vec) = &n { for expr in vec { expr.visit(self)?; } } Ok(()) } fn visit_typeid(&mut self, _n: &TypeId, b: &NodeBox) -> VisitorResult { self.fill_box(b); Ok(()) } fn visit_break(&mut self, _n: &BreakExpr, b: &NodeBox) -> VisitorResult { self.fill_box(b); Ok(()) } fn visit_borrow(&mut self, n: &BorrowExpr, b: &NodeBox) -> VisitorResult { self.fill_box(b); n.expr.visit(self)?; Ok(()) } fn visit_deref(&mut self, n: &DerefExpr, b: &NodeBox) -> VisitorResult { self.fill_box(b); n.expr.visit(self)?; Ok(()) } fn visit_unary(&mut self, n: &UnaryExpr, b: &NodeBox) -> VisitorResult { self.fill_box(b); n.expr.visit(self)?; Ok(()) } fn visit_path(&mut self, _n: &PathExpr, b: &NodeBox) -> VisitorResult { self.fill_box(b); Ok(()) } }
fn import(&mut self, working_path: PathBuf) -> VisitorResult { if let Some(mut state) = self.state.as_ref().map(|x| x.borrow_mut()) { let sources = &mut self.sources; let (index, _) = sources .read(&working_path) .map_err(|error| compiler::Error::io_error(error))?; if state.imported.insert(index) { std::mem::drop(state); let ast = compiler::parse_file_to_ast( index, working_path, sources, self.state.clone().unwrap(), ) .map_err(|err| { err.span.map(|mut span| { span.file = index; span }); err })?; let mut state = self.state.as_ref().unwrap().borrow_mut(); state .total_imported_statements .extend(ast.exprs.into_iter().filter(|ast| ast.can_import())); } } Ok(()) }
function_block-full_function
[ { "content": "pub fn mangle_string(source: &str, dest: &mut String) {\n\n for ch in source.chars() {\n\n assert!((0x20..0x7e).contains(&(ch as _)));\n\n dest.push(ch);\n\n }\n\n}\n\n\n", "file_path": "src/codegen/mangler.rs", "rank": 0, "score": 158156.51224327856 }, { "c...
Rust
contracts/pylon/gov/src/executions/mod.rs
kyscott18/interest_split
e24541f6ecfb228ab1397a1f058bb45149c413a9
use cosmwasm_std::{ from_binary, to_binary, CanonicalAddr, CosmosMsg, Decimal, DepsMut, Env, MessageInfo, Order, Response, Uint128, WasmMsg, }; use cosmwasm_storage::{ReadonlyBucket, ReadonlySingleton}; use cw20::Cw20ReceiveMsg; use pylon_token::gov_msg::{ AirdropMsg, Cw20HookMsg, ExecuteMsg, InstantiateMsg, MigrateMsg, StakingMsg, }; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use crate::error::ContractError; use crate::state::config::Config; use crate::state::poll::{ExecuteData, Poll, PollCategory, PollStatus}; use crate::state::state::State; pub type ExecuteResult = Result<Response, ContractError>; pub mod airdrop; pub mod poll; pub mod staking; pub fn instantiate( deps: DepsMut, _env: Env, info: MessageInfo, msg: InstantiateMsg, ) -> ExecuteResult { let response = Response::default().add_attribute("action", "instantiate"); let config = Config { pylon_token: deps.api.addr_canonicalize(msg.voting_token.as_str())?, owner: deps.api.addr_canonicalize(info.sender.as_str())?, quorum: msg.quorum, threshold: msg.threshold, voting_period: msg.voting_period, timelock_period: msg.timelock_period, expiration_period: 0u64, proposal_deposit: msg.proposal_deposit, snapshot_period: msg.snapshot_period, }; config.validate()?; let state = State { poll_count: 0, total_share: Uint128::zero(), total_deposit: Uint128::zero(), total_airdrop_count: 0, airdrop_update_candidates: vec![], }; Config::save(deps.storage, &config)?; State::save(deps.storage, &state)?; Ok(response) } pub fn receive( deps: DepsMut, env: Env, info: MessageInfo, cw20_msg: Cw20ReceiveMsg, ) -> ExecuteResult { let config = Config::load(deps.storage)?; if config.pylon_token != deps.api.addr_canonicalize(info.sender.as_str())? { return Err(ContractError::Unauthorized {}); } match from_binary(&cw20_msg.msg) { Ok(Cw20HookMsg::Stake {}) => Ok(Response::new() .add_message(CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: env.contract.address.to_string(), msg: to_binary(&ExecuteMsg::Airdrop(AirdropMsg::Update { target: Some(cw20_msg.sender.to_string()), }))?, funds: vec![], })) .add_message(CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: env.contract.address.to_string(), msg: to_binary(&ExecuteMsg::Staking(StakingMsg::StakeInternal { sender: cw20_msg.sender.to_string(), amount: cw20_msg.amount, }))?, funds: vec![], }))), Ok(Cw20HookMsg::CreatePoll { title, category, description, link, execute_msgs, }) => poll::create( deps, env, cw20_msg.sender, cw20_msg.amount, title, category.into(), description, link, execute_msgs, ), _ => Err(ContractError::DataShouldBeGiven {}), } } #[allow(clippy::too_many_arguments)] pub fn update_config( deps: DepsMut, info: MessageInfo, owner: Option<String>, quorum: Option<Decimal>, threshold: Option<Decimal>, voting_period: Option<u64>, timelock_period: Option<u64>, proposal_deposit: Option<Uint128>, snapshot_period: Option<u64>, ) -> ExecuteResult { let response = Response::new().add_attribute("action", "update_config"); let api = deps.api; let mut config = Config::load(deps.storage)?; if config.owner != api.addr_canonicalize(info.sender.as_str())? { return Err(ContractError::Unauthorized {}); } if let Some(owner) = owner { config.owner = api.addr_canonicalize(&owner)?; } if let Some(quorum) = quorum { config.quorum = quorum; } if let Some(threshold) = threshold { config.threshold = threshold; } if let Some(voting_period) = voting_period { config.voting_period = voting_period; } if let Some(timelock_period) = timelock_period { config.timelock_period = timelock_period; } if let Some(proposal_deposit) = proposal_deposit { config.proposal_deposit = proposal_deposit; } if let Some(period) = snapshot_period { config.snapshot_period = period; } Config::save(deps.storage, &config)?; Ok(response) } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct LegacyState { pub poll_count: u64, pub total_share: Uint128, pub total_deposit: Uint128, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct LegacyPoll { pub id: u64, pub creator: CanonicalAddr, pub status: PollStatus, pub yes_votes: Uint128, pub no_votes: Uint128, pub end_height: u64, pub title: String, pub description: String, pub link: Option<String>, pub execute_data: Option<Vec<ExecuteData>>, pub deposit_amount: Uint128, pub total_balance_at_end_poll: Option<Uint128>, pub staked_amount: Option<Uint128>, } pub fn migrate(deps: DepsMut, _env: Env, msg: MigrateMsg) -> ExecuteResult { match msg { MigrateMsg::State {} => { let state: LegacyState = ReadonlySingleton::new(deps.storage, b"state") .load() .unwrap(); State::save( deps.storage, &State { poll_count: state.poll_count, total_share: state.total_share, total_deposit: state.total_deposit, total_airdrop_count: 0, airdrop_update_candidates: vec![], }, ) .unwrap(); let legacy_poll_store: ReadonlyBucket<LegacyPoll> = ReadonlyBucket::new(deps.storage, b"poll"); let legacy_polls: Vec<LegacyPoll> = legacy_poll_store .range(None, None, Order::Descending) .take(100) .map(|item| -> LegacyPoll { let (_, v) = item.unwrap(); v }) .collect(); for poll in legacy_polls.iter() { Poll::save( deps.storage, &poll.id, &Poll { id: poll.id, creator: poll.creator.clone(), status: poll.status.clone(), yes_votes: poll.yes_votes, no_votes: poll.no_votes, end_height: poll.end_height, title: poll.title.clone(), category: PollCategory::None, description: poll.description.clone(), link: poll.link.clone(), execute_data: poll.execute_data.clone(), deposit_amount: poll.deposit_amount, total_balance_at_end_poll: poll.total_balance_at_end_poll, staked_amount: poll.staked_amount, }, )?; } } MigrateMsg::General {} => {} } Ok(Response::default()) }
use cosmwasm_std::{ from_binary, to_binary, CanonicalAddr, CosmosMsg, Decimal, DepsMut, Env, MessageInfo, Order, Response, Uint128, WasmMsg, }; use cosmwasm_storage::{ReadonlyBucket, ReadonlySingleton}; use cw20::Cw20ReceiveMsg; use pylon_token::gov_msg::{ AirdropMsg, Cw20HookMsg, ExecuteMsg, InstantiateMsg, MigrateMsg, StakingMsg, }; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use crate::error::ContractError; use crate::state::config::Config; use crate::state::poll::{ExecuteData, Poll, PollCategory, PollStatus}; use crate::state::state::State; pub type ExecuteResult = Result<Response, ContractError>; pub mod airdrop; pub mod poll; pub mod staking; pub fn instantiate( deps: DepsMut, _env: Env, info: MessageInfo, msg: InstantiateMsg, ) -> ExecuteResult { let response = Response::default().add_attribute("action", "instantiate"); let config = Config { pylon_token: deps.api.addr_canonicalize(msg.voting_token.as_str())?, owner: deps.api.addr_canonicalize(info.sender.as_str())?, quorum: msg.quorum, threshold: msg.threshold, voting_period: msg.voting_period, timelock_period: msg.timelock_period, expiration_period: 0u64, proposal_deposit: msg.proposal_deposit, snapshot_period: msg.snapshot_period, }; config.validate()?; let state = State { poll_count: 0, total_share: Uint128::zero(), total_deposit: Uint128::zero(), total_airdrop_count: 0, airdrop_update_candidates: vec![], }; Config::save(deps.storage, &config)?; State::save(deps.storage, &state)?; Ok(response) } pub fn receive( deps: DepsMut, env: Env, info: MessageInfo, cw20_msg: Cw20ReceiveMsg, ) -> ExecuteResult { let config = Config::load(deps.storage)?; if config.pylon_token != deps.api.addr_canonicalize(info.sender.as_str())? { return Err(ContractError::Unauthorized {}); } match from_binary(&cw20_msg.msg) { Ok(Cw20HookMsg::Stake {}) => Ok(Response::new() .add_message(CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: env.contract.address.to_string(), msg: to_binary(&ExecuteMsg::Airdrop(AirdropMsg::Update { target: Some(cw20_msg.sender.to_string()), }))?, funds: vec![], })) .add_message(CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: env.contract.address.to_string(), msg: to_binary(&ExecuteMsg::Staking(StakingMsg::StakeInternal { sender: cw20_msg.sender.to_string(), amount: cw20_msg.amount, }))?, funds: vec![], }))), Ok(Cw20HookMsg::CreatePoll { title, category, description, link, execute_msgs, }) => poll::create( deps, env, cw20_msg.sender, cw20_msg.amount, title, category.into(), description, link, execute_msgs, ), _ => Err(ContractError::DataShouldBeGiven {}), } } #[allow(clippy::too_many_arguments)] pub fn update_config( deps: DepsMut, info: MessageInfo, owner: Option<String>, quorum: Option<Decimal>, threshold: Option<Decimal>, voting_period: Option<u64>, timelock_period: Option<u64>, proposal_deposit: Option<Uint128>, snapshot_period: Option<u64>, ) -> ExecuteResult { let response = Response::new().add_attribute("action", "update_config"); let api = deps.api; let mut config = Config::load(deps.storage)?; if config.owner != api.addr_canonicalize(info.sender.as_str())? { return Err(ContractError::Unauthorized {}); } if let Some(owner) = owner { config.owner = api.addr_canonicalize(&owner)?; } if let Some(quorum) = quorum { config.quorum = quorum; } if let Some(threshold) = threshold { config.threshold = threshold; } if let Some(voting_period) = voting_period { config.voting_period = voting_period; } if let Some(timelock_period) = timelock_period { config.timelock_period = timelock_period; } if let Some(proposal_deposit) = proposal_deposit { config.proposal_deposit = proposal_deposit; } if let Some(period) = snapshot_period { config.snapshot_period = period; } Config::save(deps.storage, &config)?; Ok(response) } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct LegacyState { pub poll_count: u64, pub total_share: Uint128, pub total_deposit: Uint128, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct LegacyPoll { pub id: u64, pub creator: CanonicalAddr, pub status: PollStatus, pub yes_votes: Uint128, pub no_votes: Uint128, pub end_height: u64, pub title: String, pub description: String, pub link: Option<String>, pub execute_data: Option<Vec<ExecuteData>>, pub deposit_amount: Uint128, pub total_balance_at_end_poll: Option<Uint128>, pub staked_amount: Option<Uint128>, }
pub fn migrate(deps: DepsMut, _env: Env, msg: MigrateMsg) -> ExecuteResult { match msg { MigrateMsg::State {} => { let state: LegacyState = ReadonlySingleton::new(deps.storage, b"state") .load() .unwrap(); State::save( deps.storage, &State { poll_count: state.poll_count, total_share: state.total_share, total_deposit: state.total_deposit, total_airdrop_count: 0, airdrop_update_candidates: vec![], }, ) .unwrap(); let legacy_poll_store: ReadonlyBucket<LegacyPoll> = ReadonlyBucket::new(deps.storage, b"poll"); let legacy_polls: Vec<LegacyPoll> = legacy_poll_store .range(None, None, Order::Descending) .take(100) .map(|item| -> LegacyPoll { let (_, v) = item.unwrap(); v }) .collect(); for poll in legacy_polls.iter() { Poll::save( deps.storage, &poll.id, &Poll { id: poll.id, creator: poll.creator.clone(), status: poll.status.clone(), yes_votes: poll.yes_votes, no_votes: poll.no_votes, end_height: poll.end_height, title: poll.title.clone(), category: PollCategory::None, description: poll.description.clone(), link: poll.link.clone(), execute_data: poll.execute_data.clone(), deposit_amount: poll.deposit_amount, total_balance_at_end_poll: poll.total_balance_at_end_poll, staked_amount: poll.staked_amount, }, )?; } } MigrateMsg::General {} => {} } Ok(Response::default()) }
function_block-full_function
[ { "content": "pub fn claim(deps: DepsMut, env: Env, info: MessageInfo, sender: Option<String>) -> ExecuteResult {\n\n let sender = sender\n\n .map(|x| deps.api.addr_validate(x.as_str()).unwrap())\n\n .unwrap_or(info.sender);\n\n\n\n let state = State::load(deps.storage).unwrap();\n\n let ...
Rust
src/util/conversions.rs
paigereeves/mmtk-core
d45c5155d3f20bdc4f667c3b08a78f641507966c
use crate::util::constants::*; use crate::util::heap::layout::vm_layout_constants::*; use crate::util::Address; /* Alignment */ pub fn is_address_aligned(addr: Address) -> bool { addr.is_aligned_to(BYTES_IN_ADDRESS) } pub fn page_align_down(address: Address) -> Address { address.align_down(BYTES_IN_PAGE) } pub fn is_page_aligned(address: Address) -> bool { address.is_aligned_to(BYTES_IN_PAGE) } pub const fn chunk_align_up(addr: Address) -> Address { addr.align_up(BYTES_IN_CHUNK) } pub const fn chunk_align_down(addr: Address) -> Address { addr.align_down(BYTES_IN_CHUNK) } pub const fn mmap_chunk_align_up(addr: Address) -> Address { addr.align_up(MMAP_CHUNK_BYTES) } pub const fn mmap_chunk_align_down(addr: Address) -> Address { addr.align_down(MMAP_CHUNK_BYTES) } pub fn bytes_to_chunks_up(bytes: usize) -> usize { (bytes + BYTES_IN_CHUNK - 1) >> LOG_BYTES_IN_CHUNK } pub fn address_to_chunk_index(addr: Address) -> usize { addr >> LOG_BYTES_IN_CHUNK } pub fn chunk_index_to_address(chunk: usize) -> Address { unsafe { Address::from_usize(chunk << LOG_BYTES_IN_CHUNK) } } pub const fn raw_align_up(val: usize, align: usize) -> usize { val.wrapping_add(align).wrapping_sub(1) & !align.wrapping_sub(1) } pub const fn raw_align_down(val: usize, align: usize) -> usize { val & !align.wrapping_sub(1) } pub const fn raw_is_aligned(val: usize, align: usize) -> bool { val & align.wrapping_sub(1) == 0 } /* Conversion */ pub fn pages_to_bytes(pages: usize) -> usize { pages << LOG_BYTES_IN_PAGE } pub fn bytes_to_pages_up(bytes: usize) -> usize { (bytes + BYTES_IN_PAGE - 1) >> LOG_BYTES_IN_PAGE } pub fn bytes_to_pages(bytes: usize) -> usize { let pages = bytes_to_pages_up(bytes); if cfg!(debug = "true") { let computed_extent = pages << LOG_BYTES_IN_PAGE; let bytes_match_pages = computed_extent == bytes; assert!( bytes_match_pages, "ERROR: number of bytes computed from pages must match original byte amount!\ bytes = {}\ pages = {}\ bytes computed from pages = {}", bytes, pages, computed_extent ); } pages } pub fn bytes_to_formatted_string(bytes: usize) -> String { const UNITS: [&str; 6] = ["B", "KiB", "MiB", "GiB", "TiB", "PiB"]; let mut i = 0; let mut num = bytes; while i < UNITS.len() - 1 { let new_num = num >> 10; if new_num == 0 { return format!("{}{}", num, UNITS[i]); } num = new_num; i += 1; } return format!("{}{}", num, UNITS.last().unwrap()); } #[cfg(test)] mod tests { use crate::util::conversions::*; use crate::util::Address; #[test] fn test_page_align() { let addr = unsafe { Address::from_usize(0x2345_6789) }; assert_eq!(page_align_down(addr), unsafe { Address::from_usize(0x2345_6000) }); assert!(!is_page_aligned(addr)); assert!(is_page_aligned(page_align_down(addr))); } #[test] fn test_chunk_align() { let addr = unsafe { Address::from_usize(0x2345_6789) }; assert_eq!(chunk_align_down(addr), unsafe { Address::from_usize(0x2340_0000) }); assert_eq!(chunk_align_up(addr), unsafe { Address::from_usize(0x2380_0000) }); } #[test] fn test_bytes_to_formatted_string() { assert_eq!(bytes_to_formatted_string(0), "0B"); assert_eq!(bytes_to_formatted_string(1023), "1023B"); assert_eq!(bytes_to_formatted_string(1024), "1KiB"); assert_eq!(bytes_to_formatted_string(1025), "1KiB"); assert_eq!(bytes_to_formatted_string(1 << 20), "1MiB"); assert_eq!(bytes_to_formatted_string(1 << 30), "1GiB"); #[cfg(target_pointer_width = "64")] { assert_eq!(bytes_to_formatted_string(1 << 40), "1TiB"); assert_eq!(bytes_to_formatted_string(1 << 50), "1PiB"); assert_eq!(bytes_to_formatted_string(1 << 60), "1024PiB"); assert_eq!(bytes_to_formatted_string(1 << 63), "8192PiB"); } } }
use crate::util::constants::*; use crate::util::heap::layout::vm_layout_constants::*; use crate::util::Address; /* Alignment */ pub fn is_address_aligned(addr: Address) -> bool { addr.is_aligned_to(BYTES_IN_ADDRESS) } pub fn page_align_down(ad
o_chunk_index(addr: Address) -> usize { addr >> LOG_BYTES_IN_CHUNK } pub fn chunk_index_to_address(chunk: usize) -> Address { unsafe { Address::from_usize(chunk << LOG_BYTES_IN_CHUNK) } } pub const fn raw_align_up(val: usize, align: usize) -> usize { val.wrapping_add(align).wrapping_sub(1) & !align.wrapping_sub(1) } pub const fn raw_align_down(val: usize, align: usize) -> usize { val & !align.wrapping_sub(1) } pub const fn raw_is_aligned(val: usize, align: usize) -> bool { val & align.wrapping_sub(1) == 0 } /* Conversion */ pub fn pages_to_bytes(pages: usize) -> usize { pages << LOG_BYTES_IN_PAGE } pub fn bytes_to_pages_up(bytes: usize) -> usize { (bytes + BYTES_IN_PAGE - 1) >> LOG_BYTES_IN_PAGE } pub fn bytes_to_pages(bytes: usize) -> usize { let pages = bytes_to_pages_up(bytes); if cfg!(debug = "true") { let computed_extent = pages << LOG_BYTES_IN_PAGE; let bytes_match_pages = computed_extent == bytes; assert!( bytes_match_pages, "ERROR: number of bytes computed from pages must match original byte amount!\ bytes = {}\ pages = {}\ bytes computed from pages = {}", bytes, pages, computed_extent ); } pages } pub fn bytes_to_formatted_string(bytes: usize) -> String { const UNITS: [&str; 6] = ["B", "KiB", "MiB", "GiB", "TiB", "PiB"]; let mut i = 0; let mut num = bytes; while i < UNITS.len() - 1 { let new_num = num >> 10; if new_num == 0 { return format!("{}{}", num, UNITS[i]); } num = new_num; i += 1; } return format!("{}{}", num, UNITS.last().unwrap()); } #[cfg(test)] mod tests { use crate::util::conversions::*; use crate::util::Address; #[test] fn test_page_align() { let addr = unsafe { Address::from_usize(0x2345_6789) }; assert_eq!(page_align_down(addr), unsafe { Address::from_usize(0x2345_6000) }); assert!(!is_page_aligned(addr)); assert!(is_page_aligned(page_align_down(addr))); } #[test] fn test_chunk_align() { let addr = unsafe { Address::from_usize(0x2345_6789) }; assert_eq!(chunk_align_down(addr), unsafe { Address::from_usize(0x2340_0000) }); assert_eq!(chunk_align_up(addr), unsafe { Address::from_usize(0x2380_0000) }); } #[test] fn test_bytes_to_formatted_string() { assert_eq!(bytes_to_formatted_string(0), "0B"); assert_eq!(bytes_to_formatted_string(1023), "1023B"); assert_eq!(bytes_to_formatted_string(1024), "1KiB"); assert_eq!(bytes_to_formatted_string(1025), "1KiB"); assert_eq!(bytes_to_formatted_string(1 << 20), "1MiB"); assert_eq!(bytes_to_formatted_string(1 << 30), "1GiB"); #[cfg(target_pointer_width = "64")] { assert_eq!(bytes_to_formatted_string(1 << 40), "1TiB"); assert_eq!(bytes_to_formatted_string(1 << 50), "1PiB"); assert_eq!(bytes_to_formatted_string(1 << 60), "1024PiB"); assert_eq!(bytes_to_formatted_string(1 << 63), "8192PiB"); } } }
dress: Address) -> Address { address.align_down(BYTES_IN_PAGE) } pub fn is_page_aligned(address: Address) -> bool { address.is_aligned_to(BYTES_IN_PAGE) } pub const fn chunk_align_up(addr: Address) -> Address { addr.align_up(BYTES_IN_CHUNK) } pub const fn chunk_align_down(addr: Address) -> Address { addr.align_down(BYTES_IN_CHUNK) } pub const fn mmap_chunk_align_up(addr: Address) -> Address { addr.align_up(MMAP_CHUNK_BYTES) } pub const fn mmap_chunk_align_down(addr: Address) -> Address { addr.align_down(MMAP_CHUNK_BYTES) } pub fn bytes_to_chunks_up(bytes: usize) -> usize { (bytes + BYTES_IN_CHUNK - 1) >> LOG_BYTES_IN_CHUNK } pub fn address_t
random
[ { "content": "/// Is the address in the mapped memory? The runtime can use this function to check\n\n/// if an address is mapped by MMTk. Note that this is different than is_mapped_object().\n\n/// For malloc spaces, MMTk does not map those addresses (malloc does the mmap), so\n\n/// this function will return f...
Rust
src/threaded.rs
jneem/dfa-runner
b3e926f79274e0254ecc61c86ec7d8b9874948b9
use Engine; use prefix::{Prefix, PrefixSearcher}; use program::{Program, Instructions}; use std::mem; use std::cell::RefCell; use std::ops::DerefMut; #[derive(Clone, Debug, PartialEq)] struct Thread { state: usize, start_idx: usize, } #[derive(Clone, Debug, PartialEq)] struct Threads { threads: Vec<Thread>, states: Vec<u8>, } impl Threads { fn with_capacity(n: usize) -> Threads { Threads { threads: Vec::with_capacity(n), states: vec![0; n], } } fn add(&mut self, state: usize, start_idx: usize) { if self.states[state] == 0 { self.states[state] = 1; self.threads.push(Thread { state: state, start_idx: start_idx }); } } fn starts_after(&self, start_idx: usize) -> bool { self.threads.is_empty() || self.threads[0].start_idx >= start_idx } } #[derive(Clone, Debug, PartialEq)] struct ProgThreads { cur: Threads, next: Threads, } impl ProgThreads { fn with_capacity(n: usize) -> ProgThreads { ProgThreads { cur: Threads::with_capacity(n), next: Threads::with_capacity(n), } } fn swap(&mut self) { mem::swap(&mut self.cur, &mut self.next); self.next.threads.clear(); } fn clear(&mut self) { self.cur.threads.clear(); self.next.threads.clear(); for s in &mut self.cur.states { *s = 0; } for s in &mut self.next.states { *s = 0; } } } #[derive(Clone, Debug)] pub struct ThreadedEngine<Insts: Instructions> { prog: Program<Insts>, threads: RefCell<ProgThreads>, prefix: Prefix, } impl<Insts: Instructions> ThreadedEngine<Insts> { pub fn new(prog: Program<Insts>, pref: Prefix) -> ThreadedEngine<Insts> { let len = prog.num_states(); ThreadedEngine { prog: prog, threads: RefCell::new(ProgThreads::with_capacity(len)), prefix: pref, } } fn advance_thread(&self, threads: &mut ProgThreads, acc: &mut Option<(usize, usize)>, i: usize, input: &[u8], pos: usize) { let state = threads.cur.threads[i].state; let start_idx = threads.cur.threads[i].start_idx; threads.cur.states[state] = 0; let (next_state, accept) = self.prog.step(state, &input[pos..]); if let Some(bytes_ago) = accept { let acc_idx = start_idx.saturating_sub(bytes_ago as usize); if acc.is_none() || acc_idx < acc.unwrap().0 { *acc = Some((acc_idx, pos)); } } if let Some(next_state) = next_state { threads.next.add(next_state, start_idx); } } fn shortest_match_from_searcher<'a>(&'a self, s: &[u8], skip: &mut PrefixSearcher) -> Option<(usize, usize)> { let mut acc: Option<(usize, usize)> = None; let mut pos = match skip.search() { Some(x) => x.start_pos, None => return None, }; let mut threads_guard = self.threads.borrow_mut(); let threads = threads_guard.deref_mut(); threads.clear(); threads.cur.threads.push(Thread { state: 0, start_idx: pos }); while pos < s.len() { for i in 0..threads.cur.threads.len() { self.advance_thread(threads, &mut acc, i, s, pos); } threads.swap(); if acc.is_some() && threads.cur.starts_after(acc.unwrap().0) { return acc; } pos += 1; if threads.cur.threads.is_empty() { skip.skip_to(pos); if let Some(search_result) = skip.search() { pos = search_result.start_pos; threads.cur.add(0, pos); } else { return None } } else { threads.cur.add(0, pos); } } for th in &threads.cur.threads { if let Some(bytes_ago) = self.prog.check_eoi(th.state) { return Some((th.start_idx, s.len().saturating_sub(bytes_ago))); } } None } } impl<I: Instructions + 'static> Engine for ThreadedEngine<I> { fn shortest_match(&self, s: &str) -> Option<(usize, usize)> { if self.prog.num_states() == 0 { return None; } let s = s.as_bytes(); let mut searcher = self.prefix.make_searcher(s); self.shortest_match_from_searcher(s, &mut *searcher) } fn clone_box(&self) -> Box<Engine> { Box::new(self.clone()) } }
use Engine; use prefix::{Prefix, PrefixSearcher}; use program::{Program, Instructions}; use std::mem; use std::cell::RefCell; use std::ops::DerefMut; #[derive(Clone, Debug, PartialEq)] struct Thread { state: usize, start_idx: usize, } #[derive(Clone, Debug, PartialEq)] struct Threads { threads: Vec<Thread>, states: Vec<u8>, } impl Threads { fn with_capacity(n: usize) -> Threads { Threads { threads: Vec::with_capacity(n), states: vec![0; n], } } fn add(&mut self, state: usize, start_idx: usize) { if self.states[state] == 0 { self.states[state] = 1; self.threads.push(Thread { state: state, start_idx: start_idx }); } } fn starts_after(&self, start_idx: usize) -> bool { self.threads.is_empty() || self.threads[0].start_idx >= start_idx } } #[derive(Clone, Debug, PartialEq)] struct ProgThreads { cur: Threads, next: Threads, } impl ProgThreads { fn with_capacity(n: usize) -> ProgThreads { ProgThreads { cur: Threads::with_capacity(n), next: Threads::with_capacity(n), } } fn swap(&mut self) { mem::swap(&mut self.cur, &mut self.next); self.next.threads.clear(); } fn clear(&mut self) { self.cur.threads.clear(); self.next.threads.clear(); for s in &mut self.cur.states { *s = 0; } for s in &mut self.next.states { *s = 0; } } } #[derive(Clone, Debug)] pub struct ThreadedEngine<Insts: Instructions> { prog: Program<Insts>, threads: RefCell<ProgThreads>, prefix: Prefix, } impl<Insts: Instructions> ThreadedEngine<Insts> { pub fn new(prog: Program<Insts>, pref: Prefix) -> ThreadedEngine<Insts> { let len = prog.num_states(); ThreadedEngine { prog: prog, threads: RefCell::new(ProgThreads::with_capacity(len)), prefix: pref, } } fn advance_thread(&self, threads: &mut ProgThreads, acc: &mut Option<(usize, usize)>, i: usize, input: &[u8], pos: usize) { let state = thre
_bytes(); let mut searcher = self.prefix.make_searcher(s); self.shortest_match_from_searcher(s, &mut *searcher) } fn clone_box(&self) -> Box<Engine> { Box::new(self.clone()) } }
ads.cur.threads[i].state; let start_idx = threads.cur.threads[i].start_idx; threads.cur.states[state] = 0; let (next_state, accept) = self.prog.step(state, &input[pos..]); if let Some(bytes_ago) = accept { let acc_idx = start_idx.saturating_sub(bytes_ago as usize); if acc.is_none() || acc_idx < acc.unwrap().0 { *acc = Some((acc_idx, pos)); } } if let Some(next_state) = next_state { threads.next.add(next_state, start_idx); } } fn shortest_match_from_searcher<'a>(&'a self, s: &[u8], skip: &mut PrefixSearcher) -> Option<(usize, usize)> { let mut acc: Option<(usize, usize)> = None; let mut pos = match skip.search() { Some(x) => x.start_pos, None => return None, }; let mut threads_guard = self.threads.borrow_mut(); let threads = threads_guard.deref_mut(); threads.clear(); threads.cur.threads.push(Thread { state: 0, start_idx: pos }); while pos < s.len() { for i in 0..threads.cur.threads.len() { self.advance_thread(threads, &mut acc, i, s, pos); } threads.swap(); if acc.is_some() && threads.cur.starts_after(acc.unwrap().0) { return acc; } pos += 1; if threads.cur.threads.is_empty() { skip.skip_to(pos); if let Some(search_result) = skip.search() { pos = search_result.start_pos; threads.cur.add(0, pos); } else { return None } } else { threads.cur.add(0, pos); } } for th in &threads.cur.threads { if let Some(bytes_ago) = self.prog.check_eoi(th.state) { return Some((th.start_idx, s.len().saturating_sub(bytes_ago))); } } None } } impl<I: Instructions + 'static> Engine for ThreadedEngine<I> { fn shortest_match(&self, s: &str) -> Option<(usize, usize)> { if self.prog.num_states() == 0 { return None; } let s = s.as
random
[ { "content": "fn loop_searcher<'i, 'lo>(loop_while: &'lo [bool], input: &'i [u8])\n\n-> SimpleSearcher<'i, LoopWhile<'lo>> {\n\n SimpleSearcher {\n\n skip_fn: LoopWhile(loop_while),\n\n input: input,\n\n pos: 0,\n\n }\n\n}\n\n\n\nimpl<'a, Sk: SkipFn> PrefixSearcher for SimpleSearcher<...
Rust
src/graph/stage/source/refreshable.rs
dmrolfs/proctor
9b2fac5e80e4a8874906a85302af7b34b4433f46
use std::fmt::{self, Debug}; use std::future::Future; use async_trait::async_trait; use cast_trait_object::dyn_upcast; use tokio::sync::mpsc; use crate::graph::shape::SourceShape; use crate::graph::{stage, Outlet, Port, Stage, PORT_DATA}; use crate::{AppData, ProctorResult, SharedString}; pub struct RefreshableSource<Ctrl, Out, A, F> where A: Fn(Option<Ctrl>) -> F, F: Future<Output = Option<Out>>, { name: SharedString, action: A, rx_control: mpsc::Receiver<Ctrl>, outlet: Outlet<Out>, } impl<Ctrl, Out, A, F> RefreshableSource<Ctrl, Out, A, F> where A: Fn(Option<Ctrl>) -> F, F: Future<Output = Option<Out>>, { pub fn new<S: Into<SharedString>>(name: S, action: A, rx_control: mpsc::Receiver<Ctrl>) -> Self { let name = name.into(); let outlet = Outlet::new(name.clone(), PORT_DATA); Self { name, action, rx_control, outlet } } } impl<Ctrl, Out, A, F> SourceShape for RefreshableSource<Ctrl, Out, A, F> where A: Fn(Option<Ctrl>) -> F, F: Future<Output = Option<Out>>, { type Out = Out; #[inline] fn outlet(&self) -> Outlet<Self::Out> { self.outlet.clone() } } #[dyn_upcast] #[async_trait] impl<Ctrl, Out, A, F> Stage for RefreshableSource<Ctrl, Out, A, F> where Ctrl: AppData + Copy + Into<i32>, Out: AppData, A: Fn(Option<Ctrl>) -> F + Send + Sync + 'static, F: Future<Output = Option<Out>> + Send + 'static, { #[inline] fn name(&self) -> SharedString { self.name.clone() } #[tracing::instrument(level = "info", skip(self))] async fn check(&self) -> ProctorResult<()> { self.outlet.check_attachment().await?; Ok(()) } #[tracing::instrument(level = "info", name = "run refreshable source", skip(self))] async fn run(&mut self) -> ProctorResult<()> { let mut done = false; let op = &self.action; let operation = op(None); tokio::pin!(operation); let outlet = &self.outlet; let rx = &mut self.rx_control; loop { let _timer = stage::start_stage_eval_time(self.name.as_ref()); tokio::select! { result = &mut operation, if !done => { let op_span = tracing::info_span!("evaluate operation", ?result); let _op_span_guard = op_span.enter(); done = true; if let Some(r) = result { tracing::info!("Completed with result = {:?}", r); let _ = outlet.send(r).await; break; } } Some(control_signal) = rx.recv() => { let ctrl_span = tracing::info_span!("control check", ?control_signal); let _ctrl_span_guard = ctrl_span.enter(); if control_signal.into() % 2 == 0 { tracing::info!("setting operation with control signal.."); operation.set(op(Some(control_signal))); done = false; } } } } Ok(()) } async fn close(mut self: Box<Self>) -> ProctorResult<()> { tracing::info!("closing refreshable source outlet."); self.outlet.close().await; Ok(()) } } impl<Ctrl, Out, A, F> Debug for RefreshableSource<Ctrl, Out, A, F> where A: Fn(Option<Ctrl>) -> F, F: Future<Output = Option<Out>>, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("RefreshableSource") .field("name", &self.name) .field("outlet", &self.outlet) .finish() } }
use std::fmt::{self, Debug}; use std::future::Future; use async_trait::async_trait; use cast_trait_object::dyn_upcast; use tokio::sync::mpsc; use crate::graph::shape::SourceShape; use crate::graph::{stage, Outlet, Port, Stage, PORT_DATA}; use crate::{AppData, ProctorResult, SharedString}; pub struct RefreshableSource<Ctrl, Out, A, F> where A: Fn(Option<Ctrl>) -> F, F: Future<Output = Option<Out>>, { name: SharedString, action: A, rx_control: mpsc::Receiver<Ctrl>, outlet: Outlet<Out>, } impl<Ctrl, Out, A, F> RefreshableSource<Ctrl, Out, A, F> where A: Fn(Option<Ctrl>) -> F, F: Future<Output = Option<Out>>, { pub fn new<S: Into<SharedString>>(name: S, action: A, rx_control: mpsc::Receiver<Ctrl>) -> Self { let name = name.into(); let outlet = Outlet::new(name.clone(), PORT_DATA); Self { name, action, rx_control, outlet } } } impl<Ctrl, Out, A, F> SourceShape for RefreshableSource<Ctrl, Out, A, F> where A: Fn(Option<Ctrl>) -> F, F: Future<Output = Option<Out>>, { type Out = Out; #[inline] fn outlet(&self) -> Outlet<Self::Out> { self.outlet.clone() } } #[dyn_upcast] #[async_trait] impl<Ctrl, Out, A, F> Stage for RefreshableSource<Ctrl, Out, A, F> where Ctrl: AppData + Copy + Into<i32>, Out: AppData, A: Fn(Option<Ctrl>) -> F + Send + Sync + 'static, F: Future<Output = Option<Out>> + Send + 'static, { #[inline] fn name(&self) -> SharedString { self.name.clone() } #[tracing::instrument(level = "info", skip(self))] async fn check(&self) -> ProctorResult<()> { self.outlet.check_attachment().await?; Ok(()) } #[tracing::instrument(level = "info", name = "run refreshable source", skip(self))]
async fn close(mut self: Box<Self>) -> ProctorResult<()> { tracing::info!("closing refreshable source outlet."); self.outlet.close().await; Ok(()) } } impl<Ctrl, Out, A, F> Debug for RefreshableSource<Ctrl, Out, A, F> where A: Fn(Option<Ctrl>) -> F, F: Future<Output = Option<Out>>, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("RefreshableSource") .field("name", &self.name) .field("outlet", &self.outlet) .finish() } }
async fn run(&mut self) -> ProctorResult<()> { let mut done = false; let op = &self.action; let operation = op(None); tokio::pin!(operation); let outlet = &self.outlet; let rx = &mut self.rx_control; loop { let _timer = stage::start_stage_eval_time(self.name.as_ref()); tokio::select! { result = &mut operation, if !done => { let op_span = tracing::info_span!("evaluate operation", ?result); let _op_span_guard = op_span.enter(); done = true; if let Some(r) = result { tracing::info!("Completed with result = {:?}", r); let _ = outlet.send(r).await; break; } } Some(control_signal) = rx.recv() => { let ctrl_span = tracing::info_span!("control check", ?control_signal); let _ctrl_span_guard = ctrl_span.enter(); if control_signal.into() % 2 == 0 { tracing::info!("setting operation with control signal.."); operation.set(op(Some(control_signal))); done = false; } } } } Ok(()) }
function_block-full_function
[ { "content": "#[dyn_upcast]\n\n#[async_trait]\n\npub trait Stage: fmt::Debug + Send + Sync {\n\n fn name(&self) -> SharedString;\n\n async fn check(&self) -> ProctorResult<()>;\n\n async fn run(&mut self) -> ProctorResult<()>;\n\n async fn close(self: Box<Self>) -> ProctorResult<()>;\n\n}\n\n\n", ...
Rust
logpack-derive/src/encode_derive.rs
da-x/logpack
4c95c05a415a94d41ff562cde38d77b3e55516c1
use std::collections::HashSet; use proc_macro2::{TokenStream as Tokens, Span}; use syn::{Data, DeriveInput, Fields, DataEnum, Ident}; use quote::quote; pub fn derive(input: &DeriveInput) -> Tokens { let name = &input.ident; let generics = super::add_trait_bounds( input.generics.clone(), &HashSet::new(), &[quote!{ logpack::Encoder }], ); let (impl_generics, ty_generics, where_clause) = generics.split_for_impl(); let encoder_fields = match &input.data { Data::Enum(data) => encoder_for_enum(name, data, false), Data::Struct(variant_data) => encoder_for_struct(&variant_data.fields, false), Data::Union{..} => { panic!() } }; let sizer_fields = match &input.data { Data::Enum(data) => encoder_for_enum(name, &data, true), Data::Struct(variant_data) => encoder_for_struct(&variant_data.fields, true), Data::Union{..} => { panic!() } }; let result = quote! { impl #impl_generics logpack::Encoder for #name #ty_generics #where_clause { fn logpack_encode(&self, _buf: &mut logpack::buffers::BufEncoder) -> Result<(), (usize, usize)> { #encoder_fields; Ok(()) } fn logpack_sizer(&self) -> usize { #sizer_fields } } }; result } fn encoder_for_struct(fields: &Fields, sized: bool) -> Tokens { match fields { Fields::Named(ref fields) => { let fields : Vec<_> = fields.named.iter().collect(); encoder_for_struct_kind(Some(&fields[..]), true, sized) }, Fields::Unnamed(ref fields) => { let fields : Vec<_> = fields.unnamed.iter().collect(); encoder_for_struct_kind(Some(&fields[..]), false, sized) }, Fields::Unit => { encoder_for_struct_kind(None, false, sized) }, } } fn encoder_for_enum_struct<'a>(name: &Ident, ident: &Ident, fields: Vec<FieldExt<'a>>, prefix: Tokens, named: bool, sizer: bool, header_size: usize) -> Tokens { let one_ref = fields.iter().map(|v| { let ident = &v.get_match_ident(); quote! { ref #ident } }); let fields_match = match named { false => quote!(( #(#one_ref),* )), true => quote!({ #(#one_ref),* }), }; let body = if sizer { let body_impls = fields.iter().map(|v| { let ident = &v.get_match_ident(); quote! { size += #ident.logpack_sizer(); } }); quote!(let mut size: usize = #header_size; #(#body_impls);*; size ) } else { let body_impls = fields.iter().map(|v| { let ident = &v.get_match_ident(); quote! { #ident.logpack_encode(_buf)? } }); quote!(#(#body_impls);*; Ok(()) ) }; quote! { &#name::#ident #fields_match => { #prefix #body } } } fn encoder_for_enum(name: &Ident, data_enum: &DataEnum, sizer: bool) -> Tokens { let variants = &data_enum.variants; if variants.len() == 0 { if sizer { quote!(0) } else { quote!() } } else { let mut idx : u32 = 0; let (idx_type, header_size) = if variants.len() < 0x100 { ("u8", 1) } else if variants.len() < 0x10000 { ("u16", 2) } else { ("u32", 4) }; let idx_type = Ident::new(idx_type, Span::call_site()); let impls = variants.iter().map(|v| { let ident = &v.ident; let prefix = if sizer { quote! {} } else { quote! { let idx : #idx_type = #idx as #idx_type; idx.logpack_encode(_buf)?; } }; idx += 1; match v.fields { Fields::Named(ref fields) => { let fields: Vec<_> = fields.named.iter().enumerate().map(|(i, f)| FieldExt::new(f, i, true)).collect(); encoder_for_enum_struct(name, ident, fields, prefix, true, sizer, header_size) }, Fields::Unnamed(ref fields) => { let fields: Vec<_> = fields.unnamed.iter().enumerate().map(|(i, f)| FieldExt::new(f, i, false)).collect(); encoder_for_enum_struct(name, ident, fields, prefix, false, sizer, header_size) }, Fields::Unit => { if sizer { quote! { &#name::#ident => { #header_size } } } else { quote! { &#name::#ident => { #prefix Ok(()) } } } }, } }); if sizer { quote!( match self { #(#impls),* } ) } else { quote!( match self { #(#impls),* }? ) } } } fn encoder_for_struct_kind(fields: Option<&[&syn::Field]>, named: bool, sizer: bool) -> Tokens { let unit = fields.is_none(); let fields: Vec<_> = fields.unwrap_or(&[]).iter() .enumerate().map(|(i, f)| FieldExt::new(f, i, named)).collect(); if unit { if sizer { quote![ 0 ] } else { quote![ ] } } else { let fields = fields.iter().map(|f| { let field_expr = &f.access_expr(); if sizer { quote!(size += #field_expr.logpack_sizer();) } else { quote!(#field_expr.logpack_encode(_buf)?) } }); if sizer { quote!{ let mut size : usize = 0; #(#fields);*; size } } else { quote!{ #(#fields);* } } } } struct FieldExt<'a> { field: &'a syn::Field, idx: usize, named: bool, } impl<'a> FieldExt<'a> { fn new(field: &'a syn::Field, idx: usize, named: bool) -> FieldExt<'a> { FieldExt { field, idx, named } } fn access_expr(&self) -> Tokens { if self.named { let ident = &self.field.ident; quote! { self.#ident } } else { let idx = syn::Index::from(self.idx); quote! { self.#idx } } } fn get_match_ident(&self) -> Ident { if self.named { self.field.ident.clone().unwrap() } else { Ident::new(&format!("f{}", self.idx), Span::call_site()) } } }
use std::collections::HashSet; use proc_macro2::{TokenStream as Tokens, Span}; use syn::{Data, DeriveInput, Fields, DataEnum, Ident}; use quote::quote; pub fn derive(input: &DeriveInput) -> Tokens { let name = &input.ident; let generics = super::add_trait_bounds( input.generics.clone(), &HashSet::new(), &[quote!{ logpack::Encoder }], ); let (impl_generics, ty_generics, where_clause) = generics.split_for_impl(); let encoder_fields = match &input.data { Data::Enum(data) => encoder_for_enum(name, data, false), Data::Struct(variant_data) => encoder_for_struct(&variant_data.fields, false), Data::Union{..} => { panic!() } }; let sizer_fields = match &input.data { Data::Enum(data) => encoder_for_enum(name, &data, true), Data::Struct(variant_data) => encoder_for_struct(&variant_data.fields, true), Data::Union{..} => { panic!() } }; let result = quote! { impl #impl_generics logpack::Encoder for #name #ty_generics #where_clause { fn logpack_encode(&self, _buf: &mut logpack::buffers::BufEncoder) -> Result<(), (usize, usize)> { #encoder_fields; Ok(()) } fn logpack_sizer(&self) -> usize { #sizer_fields } } }; result } fn encoder_for_struct(fields: &Fields, sized: bool) -> Tokens { match fields { Fields::Named(ref fields) => { let fields : Vec<_> = fields.named.iter().collect(); encoder_for_struct_kind(Some(&fields[..]), true, sized) }, Fields::Unnamed(ref fields) => { let fields : Vec<_> = fields.unnamed.iter().collect(); encoder_for_struct_kind(Some(&fields[..]), false, sized) }, Fields::Unit => { encoder_for_struct_kind(None, false, sized) }, } } fn encoder_for_enum_struct<'a>(name: &Ident, ident: &Ident, fields: Vec<FieldExt<'a>>, prefix: Tokens, named: bool, sizer: bool, header_size: usize) -> Tokens { let one_ref = fields.iter().map(|v| { let ident = &v.get_match_ident(); quote! { ref #ident } }); let fields_match = match named { false => quote!(( #(#one_ref),* )), true => quote!({ #(#one_ref),* }), }; let body = if sizer { let body_impls = fields.iter().map(|v| { let ident = &v.get_match_ident(); quote! { size += #ident.logpack_sizer(); } }); quote!(let mut size: usize = #header_size; #(#body_impls);*; size ) } else { let body_impls = fields.iter().map(|v| { let ident = &v.get_match_ident(); quote! { #ident.logpack_encode(_buf)? } }); quote!(#(#body_impls);*; Ok(()) ) }; quote! { &#name::#ident #fields_match => { #prefix #body } } } fn encoder_for_enum(name: &Ident, data_enum: &DataEnum, sizer: bool) -> Tokens { let variants = &data_enum.variants; if variants.len() == 0 { if sizer { quote!(0) } else { quote!() } } else { let mut idx : u32 = 0; let (idx_type, header_size) = if variants.len() < 0x100 { ("u8", 1) } else if variants.len() < 0x10000 { ("u16", 2) } else { ("u32", 4) }; let idx_type = Ident::new(idx_type, Span::call_site()); let impls = variants.iter().map(|v| { let ident = &v.iden
fn encoder_for_struct_kind(fields: Option<&[&syn::Field]>, named: bool, sizer: bool) -> Tokens { let unit = fields.is_none(); let fields: Vec<_> = fields.unwrap_or(&[]).iter() .enumerate().map(|(i, f)| FieldExt::new(f, i, named)).collect(); if unit { if sizer { quote![ 0 ] } else { quote![ ] } } else { let fields = fields.iter().map(|f| { let field_expr = &f.access_expr(); if sizer { quote!(size += #field_expr.logpack_sizer();) } else { quote!(#field_expr.logpack_encode(_buf)?) } }); if sizer { quote!{ let mut size : usize = 0; #(#fields);*; size } } else { quote!{ #(#fields);* } } } } struct FieldExt<'a> { field: &'a syn::Field, idx: usize, named: bool, } impl<'a> FieldExt<'a> { fn new(field: &'a syn::Field, idx: usize, named: bool) -> FieldExt<'a> { FieldExt { field, idx, named } } fn access_expr(&self) -> Tokens { if self.named { let ident = &self.field.ident; quote! { self.#ident } } else { let idx = syn::Index::from(self.idx); quote! { self.#idx } } } fn get_match_ident(&self) -> Ident { if self.named { self.field.ident.clone().unwrap() } else { Ident::new(&format!("f{}", self.idx), Span::call_site()) } } }
t; let prefix = if sizer { quote! {} } else { quote! { let idx : #idx_type = #idx as #idx_type; idx.logpack_encode(_buf)?; } }; idx += 1; match v.fields { Fields::Named(ref fields) => { let fields: Vec<_> = fields.named.iter().enumerate().map(|(i, f)| FieldExt::new(f, i, true)).collect(); encoder_for_enum_struct(name, ident, fields, prefix, true, sizer, header_size) }, Fields::Unnamed(ref fields) => { let fields: Vec<_> = fields.unnamed.iter().enumerate().map(|(i, f)| FieldExt::new(f, i, false)).collect(); encoder_for_enum_struct(name, ident, fields, prefix, false, sizer, header_size) }, Fields::Unit => { if sizer { quote! { &#name::#ident => { #header_size } } } else { quote! { &#name::#ident => { #prefix Ok(()) } } } }, } }); if sizer { quote!( match self { #(#impls),* } ) } else { quote!( match self { #(#impls),* }? ) } } }
function_block-function_prefixed
[ { "content": "fn bintype_for_enum(data_enum: &DataEnum) -> Tokens {\n\n let impls = data_enum.variants.iter().map(|v| {\n\n let fields = bintype_for_struct(&v.fields);\n\n let ident = &v.ident;\n\n quote! { (stringify!(#ident), #fields) }\n\n });\n\n\n\n quote!(vec![#(#impls),*])\n...
Rust
src/main.rs
icefoxen/otter
518de550ea792ce1c16f7cf353b8dd97bcd4ff57
extern crate pencil; #[macro_use] extern crate log; extern crate env_logger; extern crate hoedown; extern crate git2; use std::collections::BTreeMap; use std::fs; use std::io; use std::io::Read; use pencil::helpers; use pencil::{Pencil, Request, Response, PencilResult, PencilError}; use pencil::http_errors; use git2::Repository; use hoedown::Render; static PAGE_PATH: &'static str = "pages/"; fn page_path(page: &str) -> String { let mut pagepath = PAGE_PATH.to_string(); pagepath += page; pagepath += ".md"; pagepath } use std::convert::From; fn git_to_http_error(_err: git2::Error) -> PencilError { let err = http_errors::InternalServerError; PencilError::PenHTTPError(err) } fn load_page_file(pagename: &str) -> Result<String, PencilError> { let r = Repository::init(PAGE_PATH).map_err(git_to_http_error); let pagepath = page_path(pagename); match fs::File::open(pagepath) { Ok(mut file) => { let mut s = String::new(); let _ = file.read_to_string(&mut s).unwrap(); Ok(s) } Err(e) => { let status = match e.kind() { io::ErrorKind::NotFound => http_errors::NotFound, io::ErrorKind::PermissionDenied => http_errors::Forbidden, _ => http_errors::InternalServerError, }; let err = PencilError::PenHTTPError(status); return Err(err) } } } fn index_redirect(_request: &mut Request) -> PencilResult { helpers::redirect("/index", 308) } fn page_get(request: &mut Request) -> PencilResult { let page = request.view_args.get("page").unwrap(); let contents = load_page_file(page)?; let md = hoedown::Markdown::from(contents.as_bytes()); let mut html = hoedown::Html::new(hoedown::renderer::html::Flags::empty(), 0); let buffer = html.render(&md); let rendered_markdown = buffer.to_str().unwrap(); let mut ctx = BTreeMap::new(); ctx.insert("pagename".to_string(), page.to_string()); ctx.insert("page".to_string(), rendered_markdown.to_string()); request.app.render_template("page.html", &ctx) } fn page_edit_get(request: &mut Request) -> PencilResult { let page = request.view_args.get("page").unwrap(); let contents = load_page_file(page)?; let mut ctx = BTreeMap::new(); ctx.insert("title".to_string(), page.to_string()); ctx.insert("page".to_string(), contents.to_string()); request.app.render_template("edit.html", &ctx) } fn page_edit_post(request: &mut Request) -> PencilResult { println!("Edit posted thing"); let newpage = request.form().get("submission").unwrap(); let response = format!("Posted editing page: {}", newpage); Ok(Response::from(response)) } fn setup_app() -> Pencil { let mut app = Pencil::new("."); app.set_debug(true); app.enable_static_file_handling(); app.register_template("page.html"); app.register_template("edit.html"); app.get("/", "index", index_redirect); app.get("/<page:string>", "page_get", page_get); app.get("/edit/<page:string>", "page_edit_get", page_edit_get); app.post("/edit/<page:string>", "page_edit_post", page_edit_post); app } static ADDRESS: &'static str = "localhost:5000"; fn main() { let app = setup_app(); app.run(ADDRESS); } mod test { /* fn start_test_server() -> Child { let child = Command::new("cargo") .arg("run") .spawn() .unwrap(); child } fn curl(url: &str) -> Child { let child = Command::new("curl") .arg(url) .spawn() .unwrap(); child } */ /* #[test] fn it_works() { let mut c = start_test_server(); //c.wait().unwrap(); let mut curl = curl("http://localhost:5000/start"); curl.wait().unwrap(); // Goodness, no TERM signal? How violent. c.kill().unwrap(); } */ }
extern crate pencil; #[macro_use] extern crate log; extern crate env_logger; extern crate hoedown; extern crate git2; use std::collections::BTreeMap; use std::fs; use std::io; use std::io::Read; use pencil::helpers; use pencil::{Pencil, Request, Response, PencilResult, PencilError}; use pencil::http_errors; use git2::Repository; use hoedown::Render; static PAGE_PATH: &'static str = "pages/"; fn page_path(page: &str) -> String { let mut pagepath = PAGE_PATH.to_string(); pagepath += page; pagepath += ".md"; pagepath } use std::convert::From; fn git_to_http_error(_err: git2::Error) -> PencilError { let err = http_errors::InternalServerError; PencilError::PenHTTPError(err) } fn load_page_file(pagename: &str) -> Result<String, PencilError> { let r = Repository::init(PAGE_PATH).map_err(git_to_http_error); let pagepath = page_path(pagename); match fs::File::open(pagepath) { Ok(mut file) => { let mut s = String::new(); let _ = file.read_to_string(&mut s).unwrap(); Ok(s) } Err(e) => { let status = match e.kind() { io::ErrorKind::NotFound => http_errors::NotFound, io::ErrorKind::PermissionDenied => http_errors::Forbidden, _ => http_errors::InternalServerError, }; let err = PencilError::PenHTTPError(status); return Err(err) } } } fn index_redirect(_request: &mut Request) -> PencilResult { helpers::redirect("/index", 308) } fn page_get(request: &mut Request) -> PencilResult {
::from(contents.as_bytes()); let mut html = hoedown::Html::new(hoedown::renderer::html::Flags::empty(), 0); let buffer = html.render(&md); let rendered_markdown = buffer.to_str().unwrap(); let mut ctx = BTreeMap::new(); ctx.insert("pagename".to_string(), page.to_string()); ctx.insert("page".to_string(), rendered_markdown.to_string()); request.app.render_template("page.html", &ctx) } fn page_edit_get(request: &mut Request) -> PencilResult { let page = request.view_args.get("page").unwrap(); let contents = load_page_file(page)?; let mut ctx = BTreeMap::new(); ctx.insert("title".to_string(), page.to_string()); ctx.insert("page".to_string(), contents.to_string()); request.app.render_template("edit.html", &ctx) } fn page_edit_post(request: &mut Request) -> PencilResult { println!("Edit posted thing"); let newpage = request.form().get("submission").unwrap(); let response = format!("Posted editing page: {}", newpage); Ok(Response::from(response)) } fn setup_app() -> Pencil { let mut app = Pencil::new("."); app.set_debug(true); app.enable_static_file_handling(); app.register_template("page.html"); app.register_template("edit.html"); app.get("/", "index", index_redirect); app.get("/<page:string>", "page_get", page_get); app.get("/edit/<page:string>", "page_edit_get", page_edit_get); app.post("/edit/<page:string>", "page_edit_post", page_edit_post); app } static ADDRESS: &'static str = "localhost:5000"; fn main() { let app = setup_app(); app.run(ADDRESS); } mod test { /* fn start_test_server() -> Child { let child = Command::new("cargo") .arg("run") .spawn() .unwrap(); child } fn curl(url: &str) -> Child { let child = Command::new("curl") .arg(url) .spawn() .unwrap(); child } */ /* #[test] fn it_works() { let mut c = start_test_server(); //c.wait().unwrap(); let mut curl = curl("http://localhost:5000/start"); curl.wait().unwrap(); // Goodness, no TERM signal? How violent. c.kill().unwrap(); } */ }
let page = request.view_args.get("page").unwrap(); let contents = load_page_file(page)?; let md = hoedown::Markdown
function_block-random_span
[ { "content": "pub fn clone(repo_url: &str, into_directory: &str) -> Result<String, Error> {\n\n let output = try!(Command::new(\"git\")\n\n .arg(\"clone\")\n\n .arg(repo_url)\n\n .arg(into_directory)\n\n .outp...
Rust
sw/linalg/src/im4.rs
yupferris/xenowing
0762908cba96bdd695c9af07f494bf34736b3288
use crate::fixed::*; use crate::iv4::*; use trig::*; use core::ops::{Mul, MulAssign}; #[derive(Clone, Copy)] pub struct Im4<const FRACT_BITS: u32> { pub columns: [Iv4<FRACT_BITS>; 4], } impl<const FRACT_BITS: u32> Im4<FRACT_BITS> { pub fn identity() -> Self { Self { columns: [ Iv4::new(1.0, 0.0, 0.0, 0.0), Iv4::new(0.0, 1.0, 0.0, 0.0), Iv4::new(0.0, 0.0, 1.0, 0.0), Iv4::new(0.0, 0.0, 0.0, 1.0), ], } } pub fn translation( x: impl Into<Fixed<FRACT_BITS>>, y: impl Into<Fixed<FRACT_BITS>>, z: impl Into<Fixed<FRACT_BITS>>, ) -> Self { Self { columns: [ Iv4::new(1.0, 0.0, 0.0, 0.0), Iv4::new(0.0, 1.0, 0.0, 0.0), Iv4::new(0.0, 0.0, 1.0, 0.0), Iv4::new(x, y, z, 1.0), ], } } pub fn rotation_x(radians: f32) -> Self { let s = sin(radians); let c = cos(radians); Self { columns: [ Iv4::new(1.0, 0.0, 0.0, 0.0), Iv4::new(0.0, c, s, 0.0), Iv4::new(0.0, -s, c, 0.0), Iv4::new(0.0, 0.0, 0.0, 1.0), ] } } pub fn rotation_y(radians: f32) -> Self { let s = sin(radians); let c = cos(radians); Self { columns: [ Iv4::new(c, 0.0, -s, 0.0), Iv4::new(0.0, 1.0, 0.0, 0.0), Iv4::new(s, 0.0, c, 0.0), Iv4::new(0.0, 0.0, 0.0, 1.0), ] } } pub fn rotation_z(radians: f32) -> Self { let s = sin(radians); let c = cos(radians); Self { columns: [ Iv4::new(c, s, 0.0, 0.0), Iv4::new(-s, c, 0.0, 0.0), Iv4::new(0.0, 0.0, 1.0, 0.0), Iv4::new(0.0, 0.0, 0.0, 1.0), ] } } pub fn scale( x: impl Into<Fixed<FRACT_BITS>>, y: impl Into<Fixed<FRACT_BITS>>, z: impl Into<Fixed<FRACT_BITS>>, ) -> Self { Self { columns: [ Iv4::new(x, 0.0, 0.0, 0.0), Iv4::new(0.0, y, 0.0, 0.0), Iv4::new(0.0, 0.0, z, 0.0), Iv4::new(0.0, 0.0, 0.0, 1.0), ] } } pub fn ortho(left: f32, right: f32, bottom: f32, top: f32, z_near: f32, z_far: f32) -> Self { let tx = -(right + left) / (right - left); let ty = -(top + bottom) / (top - bottom); let tz = -(z_far + z_near) / (z_far - z_near); Self { columns: [ Iv4::new(2.0 / (right - left), 0.0, 0.0, 0.0), Iv4::new(0.0, 2.0 / (top - bottom), 0.0, 0.0), Iv4::new(0.0, 0.0, -2.0 / (z_far - z_near), 0.0), Iv4::new(tx, ty, tz, 1.0), ] } } pub fn perspective(fov_degrees: f32, aspect: f32, z_near: f32, z_far: f32) -> Self { let fov_radians = fov_degrees.to_radians(); let top = z_near * tan(fov_radians / 2.0); let right = top * aspect; let z_range = z_far - z_near; Self { columns: [ Iv4::new(z_near / right, 0.0, 0.0, 0.0), Iv4::new(0.0, z_near / top, 0.0, 0.0), Iv4::new(0.0, 0.0, -(z_near + z_far) / z_range, -1.0), Iv4::new(0.0, 0.0, -2.0 * z_near * z_far / z_range, 0.0), ] } } fn rows(&self) -> [Iv4<FRACT_BITS>; 4] { [ Iv4::new(self.columns[0].x, self.columns[1].x, self.columns[2].x, self.columns[3].x), Iv4::new(self.columns[0].y, self.columns[1].y, self.columns[2].y, self.columns[3].y), Iv4::new(self.columns[0].z, self.columns[1].z, self.columns[2].z, self.columns[3].z), Iv4::new(self.columns[0].w, self.columns[1].w, self.columns[2].w, self.columns[3].w), ] } } impl<const FRACT_BITS: u32> Mul for Im4<FRACT_BITS> { type Output = Self; fn mul(self, other: Self) -> Self { &self * &other } } impl<'a, const FRACT_BITS: u32> Mul<&'a Self> for Im4<FRACT_BITS> { type Output = Self; fn mul(self, other: &'a Self) -> Self { &self * other } } impl<'a, const FRACT_BITS: u32> Mul<Im4<FRACT_BITS>> for &'a Im4<FRACT_BITS> { type Output = Im4<FRACT_BITS>; fn mul(self, other: Im4<FRACT_BITS>) -> Im4<FRACT_BITS> { self * &other } } impl<'a, 'b, const FRACT_BITS: u32> Mul<&'a Im4<FRACT_BITS>> for &'b Im4<FRACT_BITS> { type Output = Im4<FRACT_BITS>; fn mul(self, other: &'a Im4<FRACT_BITS>) -> Im4<FRACT_BITS> { let rows = self.rows(); Im4 { columns: [ Iv4::new( rows[0].dot(other.columns[0]), rows[1].dot(other.columns[0]), rows[2].dot(other.columns[0]), rows[3].dot(other.columns[0]), ), Iv4::new( rows[0].dot(other.columns[1]), rows[1].dot(other.columns[1]), rows[2].dot(other.columns[1]), rows[3].dot(other.columns[1]), ), Iv4::new( rows[0].dot(other.columns[2]), rows[1].dot(other.columns[2]), rows[2].dot(other.columns[2]), rows[3].dot(other.columns[2]), ), Iv4::new( rows[0].dot(other.columns[3]), rows[1].dot(other.columns[3]), rows[2].dot(other.columns[3]), rows[3].dot(other.columns[3]), ), ], } } } impl<const FRACT_BITS: u32> Mul<Iv4<FRACT_BITS>> for Im4<FRACT_BITS> { type Output = Iv4<FRACT_BITS>; fn mul(self, other: Iv4<FRACT_BITS>) -> Iv4<FRACT_BITS> { let rows = self.rows(); Iv4::new( rows[0].dot(other), rows[1].dot(other), rows[2].dot(other), rows[3].dot(other), ) } } impl<const FRACT_BITS: u32> MulAssign for Im4<FRACT_BITS> { fn mul_assign(&mut self, other: Self) { *self = *self * other } }
use crate::fixed::*; use crate::iv4::*; use trig::*; use core::ops::{Mul, MulAssign}; #[derive(Clone, Copy)] pub struct Im4<const FRACT_BITS: u32> { pub columns: [Iv4<FRACT_BITS>; 4], } impl<const FRACT_BITS: u32> Im4<FRACT_BITS> { pub fn identity() -> Self { Self { columns: [ Iv4::new(1.0, 0.0, 0.0, 0.0), Iv4::new(0.0, 1.0, 0.0, 0.0), Iv4::new(0.0, 0.0, 1.0, 0.0), Iv4::new(0.0, 0.0, 0.0, 1.0), ], } } pub fn translation( x: impl Into<Fixed<FRACT_BITS>>, y: impl Into<Fixed<FRACT_BITS>>, z: impl Into<Fixed<FRACT_BITS>>, ) -> Self { Self { columns: [ Iv4::new(1.0, 0.0, 0.0, 0.0), Iv4::new(0.0, 1.0, 0.0, 0.0), Iv4::new(0.0, 0.0, 1.0, 0.0), Iv4::new(x, y, z, 1.0), ], } } pub fn rotation_x(radians: f32) -> Self { let s = sin(radians); let c = cos(radians); Self { columns: [ Iv4::new(1.0, 0.0, 0.0, 0.0), Iv4::new(0.0, c, s, 0.0), Iv4::new(0.0, -s, c, 0.0), Iv4::new(0.0, 0.0, 0.0, 1.0), ] } } pub fn rotation_y(radians: f32) -> Self { let s = sin(radians); let c = cos(radians); Self { columns: [ Iv4::new(c, 0.0, -s, 0.0), Iv4::new(0.0, 1.0, 0.0, 0.0), Iv4::new(s, 0.0, c, 0.0), Iv4::new(0.0, 0.0, 0.0, 1.0), ] } } pub fn rotation_z(radians: f32) -> Self { let s = sin(radians); let c = cos(radians); Self { columns: [ Iv4::new(c, s, 0.0, 0.0), Iv4::new(-s, c, 0.0, 0.0), Iv4::new(0.0, 0.0, 1.0, 0.0), Iv4::new(0.0, 0.0, 0.0, 1.0), ] } } pub fn scale( x: impl Into<Fixed<FRACT_BITS>>, y: impl Into<Fixed<FRACT_BITS>>, z: impl Into<Fixed<FRACT_BITS>>, ) -> Self { Self { columns: [ Iv4::new(x, 0.0, 0.0, 0.0), Iv4::new(0.0, y, 0.0, 0.0), Iv4::new(0.0, 0.0, z, 0.0), Iv4::new(0.0, 0.0, 0.0, 1.0), ] } } pub fn ortho(left: f32, right: f32, bottom: f32, top: f32, z_near: f32, z_far: f32) -> Self { let tx = -(right + left) / (right - left); let ty = -(top + bottom) / (top - bottom); let tz = -(z_far + z_near) / (z_far - z_near); Self { columns:
( rows[0].dot(other.columns[0]), rows[1].dot(other.columns[0]), rows[2].dot(other.columns[0]), rows[3].dot(other.columns[0]), ), Iv4::new( rows[0].dot(other.columns[1]), rows[1].dot(other.columns[1]), rows[2].dot(other.columns[1]), rows[3].dot(other.columns[1]), ), Iv4::new( rows[0].dot(other.columns[2]), rows[1].dot(other.columns[2]), rows[2].dot(other.columns[2]), rows[3].dot(other.columns[2]), ), Iv4::new( rows[0].dot(other.columns[3]), rows[1].dot(other.columns[3]), rows[2].dot(other.columns[3]), rows[3].dot(other.columns[3]), ), ], } } } impl<const FRACT_BITS: u32> Mul<Iv4<FRACT_BITS>> for Im4<FRACT_BITS> { type Output = Iv4<FRACT_BITS>; fn mul(self, other: Iv4<FRACT_BITS>) -> Iv4<FRACT_BITS> { let rows = self.rows(); Iv4::new( rows[0].dot(other), rows[1].dot(other), rows[2].dot(other), rows[3].dot(other), ) } } impl<const FRACT_BITS: u32> MulAssign for Im4<FRACT_BITS> { fn mul_assign(&mut self, other: Self) { *self = *self * other } }
[ Iv4::new(2.0 / (right - left), 0.0, 0.0, 0.0), Iv4::new(0.0, 2.0 / (top - bottom), 0.0, 0.0), Iv4::new(0.0, 0.0, -2.0 / (z_far - z_near), 0.0), Iv4::new(tx, ty, tz, 1.0), ] } } pub fn perspective(fov_degrees: f32, aspect: f32, z_near: f32, z_far: f32) -> Self { let fov_radians = fov_degrees.to_radians(); let top = z_near * tan(fov_radians / 2.0); let right = top * aspect; let z_range = z_far - z_near; Self { columns: [ Iv4::new(z_near / right, 0.0, 0.0, 0.0), Iv4::new(0.0, z_near / top, 0.0, 0.0), Iv4::new(0.0, 0.0, -(z_near + z_far) / z_range, -1.0), Iv4::new(0.0, 0.0, -2.0 * z_near * z_far / z_range, 0.0), ] } } fn rows(&self) -> [Iv4<FRACT_BITS>; 4] { [ Iv4::new(self.columns[0].x, self.columns[1].x, self.columns[2].x, self.columns[3].x), Iv4::new(self.columns[0].y, self.columns[1].y, self.columns[2].y, self.columns[3].y), Iv4::new(self.columns[0].z, self.columns[1].z, self.columns[2].z, self.columns[3].z), Iv4::new(self.columns[0].w, self.columns[1].w, self.columns[2].w, self.columns[3].w), ] } } impl<const FRACT_BITS: u32> Mul for Im4<FRACT_BITS> { type Output = Self; fn mul(self, other: Self) -> Self { &self * &other } } impl<'a, const FRACT_BITS: u32> Mul<&'a Self> for Im4<FRACT_BITS> { type Output = Self; fn mul(self, other: &'a Self) -> Self { &self * other } } impl<'a, const FRACT_BITS: u32> Mul<Im4<FRACT_BITS>> for &'a Im4<FRACT_BITS> { type Output = Im4<FRACT_BITS>; fn mul(self, other: Im4<FRACT_BITS>) -> Im4<FRACT_BITS> { self * &other } } impl<'a, 'b, const FRACT_BITS: u32> Mul<&'a Im4<FRACT_BITS>> for &'b Im4<FRACT_BITS> { type Output = Im4<FRACT_BITS>; fn mul(self, other: &'a Im4<FRACT_BITS>) -> Im4<FRACT_BITS> { let rows = self.rows(); Im4 { columns: [ Iv4::new
random
[ { "content": "pub fn sin(x: f32) -> f32 {\n\n let phase_scale = 1.0 / core::f32::consts::TAU;\n\n let phase = x * phase_scale;\n\n let phase = phase - unsafe { intrinsics::floorf32(phase) };\n\n let phase_with_offset = phase + 1.0;\n\n let bits = phase_with_offset.to_bits();\n\n const NUM_SIGN...
Rust
memscanner/src/signature/mod.rs
garlond/memscanner
dcc322a6c83133dcc494472933b6be410ca46583
mod parser; use super::MemReader; use failure::{format_err, Error}; #[derive(Clone, Debug, PartialEq, Eq)] enum Match { Any, Position, Literal(u8), } #[derive(Clone, Debug, PartialEq, Eq)] enum Op { Asm(Vec<Match>), Ptr(i32), } #[derive(Clone, Debug, PartialEq, Eq)] pub struct Signature { ops: Vec<Op>, } impl Signature { pub fn new(ops: &Vec<String>) -> Result<Signature, Error> { let mut sig = Signature { ops: vec![] }; for op_str in ops { let (_, op) = parser::parse_op(op_str).map_err(|_| format_err!("Can't parse op: {}", op_str))?; sig.ops.push(op); } Ok(sig) } pub fn resolve(&self, mem: &dyn MemReader, start_addr: u64, end_addr: u64) -> Option<u64> { let mut addr = start_addr; for op in &self.ops { addr = match &op { Op::Asm(p) => resolve_asm(mem, start_addr, end_addr, &p)?, Op::Ptr(o) => resolve_ptr(mem, addr, *o)?, }; } Some(addr) } } fn offset_addr(addr: u64, offset: i32) -> u64 { if offset < 0 { addr - (-offset) as u64 } else { addr + offset as u64 } } fn check_pattern( mem: &dyn MemReader, start_addr: u64, end_addr: u64, pattern: &[Match], ) -> Option<u64> { if end_addr - start_addr < pattern.len() as u64 { println!("Not enough room for pattern"); return None; } let mut mem_contents = vec![0x0; pattern.len()]; let mem_read = mem.read(&mut mem_contents, start_addr, pattern.len()); if mem_read != pattern.len() { println!("incomplete read"); return None; } let mut offset: Option<u64> = None; for i in 0..pattern.len() { match &pattern[i] { Match::Position => { if offset == None { offset = Some(i as u64); } } Match::Any => {} Match::Literal(val) => { if mem_contents[i] != *val { return None; } } }; } match offset { None => Some(pattern.len() as u64), Some(_) => offset, } } fn resolve_match( mem: &dyn MemReader, start_addr: u64, end_addr: u64, pattern: &[Match], ) -> Option<u64> { let mem_len = end_addr - start_addr; for i in 0..=(mem_len as usize - pattern.len()) { if let Some(offset) = check_pattern(mem, start_addr + i as u64, end_addr, pattern) { return Some(start_addr + offset + i as u64); } } None } fn resolve_asm( mem: &dyn MemReader, start_addr: u64, end_addr: u64, pattern: &[Match], ) -> Option<u64> { let match_addr = resolve_match(mem, start_addr, end_addr, pattern)?; let offset = mem.read_i32(match_addr)?; let addr = offset_addr(match_addr, offset) + 4; Some(addr) } fn resolve_ptr(mem: &dyn MemReader, addr: u64, offset: i32) -> Option<u64> { let addr = (addr as i64 + offset as i64) as u64; let addr = mem.read_u64(addr)?; Some(addr) } #[cfg(test)] mod tests { use super::super::test::TestMemReader; use super::*; #[test] fn single_lea() { #[rustfmt::skip] let mem = TestMemReader { mem: vec![ 0xff, 0xff, 0xff, 0xff, 0x00, 0x11, 0x22, 0x33, 0x04, 0x00, 0x00, 0x00, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, ], start_addr: 0x1000, }; let sig = Signature::new(&vec!["asm(00112233^^^^^^^^********)".to_string()]).unwrap(); println!("{:?}", sig); let offset = sig .resolve(&mem, mem.start_addr, mem.start_addr + mem.mem.len() as u64) .unwrap(); assert_eq!(offset, 0x1010); assert_eq!(mem.read_u64(offset).unwrap(), 0xffeeddccbbaa9988); } }
mod parser; use super::MemReader; use failure::{format_err, Error}; #[derive(Clone, Debug, PartialEq, Eq)] enum Match { Any, Position, Literal(u8), } #[derive(Clone, Debug, PartialEq, Eq)] enum Op { Asm(Vec<Match>), Ptr(i32), } #[derive(Clone, Debug, PartialEq, Eq)] pub struct Signature { ops: Vec<Op>, } impl Signature { pub fn new(ops: &Vec<String>) -> Result<Signature, Error> { let mut sig = Signature { ops: vec![] }; for op_str in ops { let (_, op) = parser::parse_op(op_str).map_err(|_| format_err!("Can't parse op: {}", op_str))?; sig.ops.push(op); } Ok(sig) } pub fn resolve(&self, mem: &dyn MemReader, start_addr: u64, end_addr: u64) -> Option<u64> { let mut addr = start_addr; for op in &self.ops { addr = match &op { Op::Asm(p) => resolve_asm(mem, start_addr, end_addr, &p)?, Op::Ptr(o) => resolve_ptr(mem, addr, *o)?, }; } Some(addr) } } fn offset_addr(addr: u64, offset: i32) -> u64 { if offset < 0 { addr - (-offset) as u64 } else { addr + offset as u64 } } fn check_pattern( mem: &dyn MemReader, start_addr: u64, end_addr: u64, pattern: &[Match], ) -> Option<u64> { if end_addr - start_addr < pattern.len() as u64 { println!("Not enough room for pattern"); return None; } let mut mem_contents = vec![0x0; pattern.len()]; let mem_read = mem.read(&mut mem_contents, start_addr, pattern.len()); if mem_read != pattern.len() { println!("incomplete read"); return None; } let mut offset: Option<u64> = None; for i in 0..pattern.len() { match &pattern[i] { Match::Position => { if offset == None { offset = Some(i as u64); } } Match::Any => {} Match::Literal(val) => { if mem_contents[i] != *val { return None; } } }; } match offset { None => Some(pattern.len() as u64), Some(_) => offset, } } fn resolve_match( mem: &dyn MemReader, start_addr: u64, end_addr: u64, pattern: &[Match], ) -> Option<u64> { let mem_len = end_addr - start_addr; for i in 0..=(mem_len as usize - pattern.len()) { if let Some(offset) = check_pattern(mem, start_addr + i as u64, end_addr, pattern) { return Some(start_addr + offset + i as u64); } } None } fn resolve_asm( mem: &dyn MemReader, start_addr: u64, end_addr: u64, pattern: &[Match], ) -> Option<u64> { let match_addr = resolve_match(mem, start_addr, end_addr, pattern)?; let offset = mem.read_i32(match_addr)?; let addr = offset_addr(match_addr, offset) + 4; Some(addr) } fn resolve_ptr(mem: &dyn MemReader, addr: u64, offset: i32) -> Option<u64> { let addr = (addr as i64 + offset as i64) as u64; let addr = mem.read_u64(addr)?; Some(addr) } #[cfg(test)] mod tests { use super::super::test::TestMemReader; use super::*; #[test]
}
fn single_lea() { #[rustfmt::skip] let mem = TestMemReader { mem: vec![ 0xff, 0xff, 0xff, 0xff, 0x00, 0x11, 0x22, 0x33, 0x04, 0x00, 0x00, 0x00, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, ], start_addr: 0x1000, }; let sig = Signature::new(&vec!["asm(00112233^^^^^^^^********)".to_string()]).unwrap(); println!("{:?}", sig); let offset = sig .resolve(&mem, mem.start_addr, mem.start_addr + mem.mem.len() as u64) .unwrap(); assert_eq!(offset, 0x1010); assert_eq!(mem.read_u64(offset).unwrap(), 0xffeeddccbbaa9988); }
function_block-full_function
[ { "content": "fn parse_position(input: &str) -> IResult<&str, Match> {\n\n value(Match::Position, tag(\"^^\"))(input)\n\n}\n\n\n", "file_path": "memscanner/src/signature/parser.rs", "rank": 6, "score": 111181.45690729145 }, { "content": "fn parse_i32(input: &str) -> IResult<&str, i32> {\n...
Rust
src/utils.rs
ruoshui-git/mks66-w11_animation
2324fb210b1b88c44e712d7a5a9790b975223069
use std::fs::File; use std::path::Path; use indicatif::ProgressStyle; use crate::{ canvas::Canvas, light::{self, LightProps}, }; pub(crate) fn create_file(filepath: &str) -> File { let path = Path::new(filepath); let display = path.display(); match File::create(&path) { Err(why) => panic!("Could not create {}: {}", display, why), Ok(file) => file, } } pub(crate) fn polar_to_xy(mag: f64, angle_degrees: f64) -> (f64, f64) { let (dy, dx) = angle_degrees.to_radians().sin_cos(); (dx * mag, dy * mag) } pub(crate) fn compute_bezier3_coef(p0: f64, p1: f64, p2: f64, p3: f64) -> (f64, f64, f64, f64) { ( -p0 + 3.0 * (p1 - p2) + p3, 3.0 * p0 - 6.0 * p1 + 3.0 * p2, 3.0 * (-p0 + p1), p0, ) } pub(crate) fn compute_hermite3_coef(p0: f64, p1: f64, r0: f64, r1: f64) -> (f64, f64, f64, f64) { ( 2.0 * (p0 - p1) + r0 + r1, 3.0 * (-p0 + p1) - 2.0 * r0 - r1, r0, p0, ) } use crate::{Matrix, PPMImg}; use std::{fs, process::Command}; use super::RGB; pub(crate) fn display_ppm(img: &PPMImg) { let tmpfile_name = "tmp.ppm"; img.write_binary(tmpfile_name) .expect("Error writing to file"); let mut cmd = Command::new(if cfg!(windows) { "imdisplay" } else { "display" }); let mut display = cmd .arg(tmpfile_name) .spawn() .unwrap(); let _result = display.wait().unwrap(); fs::remove_file(tmpfile_name).expect("Error removing tmp file"); } pub(crate) fn display_edge_matrix(m: &Matrix, ndc: bool, color: RGB) { let mut img = PPMImg::new(500, 500, 225); if ndc { img.render_ndc_edges_n1to1(m, color); } else { img.render_edge_matrix(m, color); } display_ppm(&img); } pub(crate) fn display_polygon_matrix(m: &Matrix, ndc: bool) { let mut img = PPMImg::with_bg(500, 500, 225, RGB::BLACK); if ndc { unimplemented!("Displaying polygon matrix in ndc is not implemented."); } else { img.render_polygon_matrix(m, &LightProps::DEFAULT_PROPS, &light::default_lights()); } display_ppm(&img); } pub fn mapper(instart: f64, inend: f64, outstart: f64, outend: f64) -> impl Fn(f64) -> f64 { let slope = (outend - outstart) / (inend - instart); move |x| outstart + slope * (x - instart) } pub fn shark_spinner_style() -> ProgressStyle { ProgressStyle::default_spinner() .template("\t[{elapsed}] {spinner:.green} {wide_msg}") .tick_strings(&[ "▐|\\____________▌", "▐_|\\___________▌", "▐__|\\__________▌", "▐___|\\_________▌", "▐____|\\________▌", "▐_____|\\_______▌", "▐______|\\______▌", "▐_______|\\_____▌", "▐________|\\____▌", "▐_________|\\___▌", "▐__________|\\__▌", "▐___________|\\_▌", "▐____________|\\▌", "▐____________/|▌", "▐___________/|_▌", "▐__________/|__▌", "▐_________/|___▌", "▐________/|____▌", "▐_______/|_____▌", "▐______/|______▌", "▐_____/|_______▌", "▐____/|________▌", "▐___/|_________▌", "▐__/|__________▌", "▐_/|___________▌", "▐/|____________▌", ]) }
use std::fs::File; use std::path::Path; use indicatif::ProgressStyle; use crate::{ canvas::Canvas, light::{self, LightProps}, }; pub(crate) fn create_file(filepath: &str) -> File { let path = Path::new(filepath); let display = path.display(); match File::create(&path) { Err(why) => panic!("Could not create {}: {}", display, why), Ok(file) => file, } } pub(crate) fn polar_to_xy(mag: f64, angle_degrees: f64) -> (f64, f64) { let (dy, dx) = angle_degrees.to_radians().sin_cos(); (dx * mag, dy * mag) } pub(crate) fn compute_bezier3_coef(p0: f64, p1: f64, p2: f64, p3: f64) -> (f64, f64, f64, f64) { ( -p0 + 3.0 * (p1 - p2) + p3, 3.0 * p0 - 6.0 * p1 + 3.0 * p2, 3.0 * (-p0 + p1), p0, ) } pub(crate) fn compute_hermite3_coef(p0: f64, p1: f64, r0: f64, r1: f64) -> (f64, f64, f64, f64) { ( 2.0 * (p0 - p1) + r0 + r1, 3.0 * (-p0 + p1) - 2.0 * r0 - r1, r0, p0, ) } use crate::{Matrix, PPMImg}; use std::{fs, process::Command}; use super::RGB; pub(crate) fn display_ppm(img: &PPMImg) { let tmpfile_name = "tmp.ppm"; img.write_binary(tmpfile_name) .expect("Error writing to file"); let mut cmd = Command::new(if cfg!(windows) { "imdisplay" } else { "display" }); let mut display = cmd .arg(tmpfile_name) .spawn() .unwrap(); let _result = display.wait().unwrap(); fs::remove_file(tmpfile_name).expect("Error removing tmp file"); } pub(crate) fn display_edge_matrix(m: &Matrix, ndc: bool, color: RGB) { let mut img = PPMImg::new(500, 500, 225); if ndc {
]) }
img.render_ndc_edges_n1to1(m, color); } else { img.render_edge_matrix(m, color); } display_ppm(&img); } pub(crate) fn display_polygon_matrix(m: &Matrix, ndc: bool) { let mut img = PPMImg::with_bg(500, 500, 225, RGB::BLACK); if ndc { unimplemented!("Displaying polygon matrix in ndc is not implemented."); } else { img.render_polygon_matrix(m, &LightProps::DEFAULT_PROPS, &light::default_lights()); } display_ppm(&img); } pub fn mapper(instart: f64, inend: f64, outstart: f64, outend: f64) -> impl Fn(f64) -> f64 { let slope = (outend - outstart) / (inend - instart); move |x| outstart + slope * (x - instart) } pub fn shark_spinner_style() -> ProgressStyle { ProgressStyle::default_spinner() .template("\t[{elapsed}] {spinner:.green} {wide_msg}") .tick_strings(&[ "▐|\\____________▌", "▐_|\\___________▌", "▐__|\\__________▌", "▐___|\\_________▌", "▐____|\\________▌", "▐_____|\\_______▌", "▐______|\\______▌", "▐_______|\\_____▌", "▐________|\\____▌", "▐_________|\\___▌", "▐__________|\\__▌", "▐___________|\\_▌", "▐____________|\\▌", "▐____________/|▌", "▐___________/|_▌", "▐__________/|__▌", "▐_________/|___▌", "▐________/|____▌", "▐_______/|_____▌", "▐______/|______▌", "▐_____/|_______▌", "▐____/|________▌", "▐___/|_________▌", "▐__/|__________▌", "▐_/|___________▌", "▐/|____________▌",
random
[ { "content": "// generate transformation matrices\n\n/// Generate a translation matrix with (dx, dy, dz)\n\npub fn mv(dx: f64, dy: f64, dz: f64) -> Matrix {\n\n let mut m = Matrix::ident(4);\n\n\n\n m.set(3, 0, dx);\n\n m.set(3, 1, dy);\n\n m.set(3, 2, dz);\n\n m\n\n}\n\n\n", "file_path": "sr...
Rust
src/cluster/cluster.rs
MilesBreslin/Chunky-Bits
2338a32b9fd8fbae75173c4e667b4b509128dad3
use std::{ convert::TryInto, path::Path, }; use futures::stream::Stream; use serde::{ Deserialize, Serialize, }; use tokio::{ io, io::AsyncRead, }; use crate::{ cluster::{ ClusterNodes, ClusterProfile, ClusterProfiles, Destination, DestinationInner, FileOrDirectory, MetadataFormat, MetadataTypes, Tunables, }, error::{ ClusterError, LocationParseError, MetadataReadError, }, file::{ new_profiler, FileReference, FileWriteBuilder, Location, ProfileReport, ProfileReporter, }, }; #[derive(Clone, Serialize, Deserialize)] pub struct Cluster { #[serde(alias = "destination")] #[serde(alias = "nodes")] #[serde(alias = "node")] pub destinations: ClusterNodes, #[serde(alias = "metadata")] pub metadata: MetadataTypes, pub profiles: ClusterProfiles, #[serde(default)] #[serde(alias = "tunable")] #[serde(alias = "tuning")] pub tunables: Tunables, } impl Cluster { pub async fn from_location( location: impl TryInto<Location, Error = impl Into<LocationParseError>>, ) -> Result<Cluster, MetadataReadError> { MetadataFormat::Yaml.from_location(location).await } pub fn get_file_writer(&self, profile: &ClusterProfile) -> FileWriteBuilder<Destination> { let destination = self.get_destination(profile); FileReference::write_builder() .destination(destination) .chunk_size((1_usize) << profile.get_chunk_size()) .data_chunks(profile.get_data_chunks()) } pub async fn write_file_ref( &self, path: impl AsRef<Path>, file_ref: &FileReference, ) -> Result<(), ClusterError> { self.metadata.write(path, &file_ref).await?; Ok(()) } pub async fn write_file<R>( &self, path: impl AsRef<Path>, reader: &mut R, profile: &ClusterProfile, content_type: Option<String>, ) -> Result<(), ClusterError> where R: AsyncRead + Unpin, { let mut file_ref = self.get_file_writer(profile).write(reader).await?; file_ref.content_type = content_type; self.metadata.write(path, &file_ref).await.unwrap(); Ok(()) } pub async fn write_file_with_report<R>( &self, path: impl AsRef<Path>, reader: &mut R, profile: &ClusterProfile, content_type: Option<String>, ) -> (ProfileReport, Result<(), ClusterError>) where R: AsyncRead + Unpin, { let (reporter, destination) = self.get_destination_with_profiler(profile); let result = FileReference::write_builder() .destination(destination) .chunk_size((1_usize) << profile.get_chunk_size()) .data_chunks(profile.get_data_chunks()) .parity_chunks(profile.get_parity_chunks()) .write(reader) .await; match result { Ok(mut file_ref) => { file_ref.content_type = content_type; self.metadata.write(path, &file_ref).await.unwrap(); (reporter.profile().await, Ok(())) }, Err(err) => (reporter.profile().await, Err(err.into())), } } pub async fn get_file_ref( &self, path: impl AsRef<Path>, ) -> Result<FileReference, MetadataReadError> { self.metadata.read(path).await } pub async fn read_file( &self, path: impl AsRef<Path>, ) -> Result<impl AsyncRead + Unpin, MetadataReadError> { let file_ref = self.get_file_ref(path).await?; let reader = file_ref.read_builder_owned().reader_owned(); Ok(reader) } pub fn get_destination(&self, profile: &ClusterProfile) -> Destination { let inner = DestinationInner { nodes: self.destinations.clone(), location_context: self.tunables.as_ref().clone(), profile: profile.clone(), }; Destination(inner.into()) } pub fn get_destination_with_profiler( &self, profile: &ClusterProfile, ) -> (ProfileReporter, Destination) { let (profiler, reporter) = new_profiler(); let location_context = self .tunables .generate_location_context_builder() .profiler(profiler) .build(); ( reporter, Destination( DestinationInner { nodes: self.destinations.clone(), location_context, profile: profile.clone(), } .into(), ), ) } pub fn get_profile<'a>( &self, profile: impl Into<Option<&'a str>>, ) -> Option<&'_ ClusterProfile> { self.profiles.get(profile) } pub async fn list_files( &self, path: &Path, ) -> Result<impl Stream<Item = io::Result<FileOrDirectory>> + 'static, MetadataReadError> { self.metadata.list(path).await } }
use std::{ convert::TryInto, path::Path, }; use futures::stream::Stream; use serde::{ Deserialize, Serialize, }; use tokio::{ io, io::AsyncRead, }; use crate::{ cluster::{ ClusterNodes, ClusterProfile, ClusterProfiles, Destination, DestinationInner, FileOrDirectory, MetadataFormat, MetadataTypes, Tunables, }, error::{ ClusterError, LocationParseError, MetadataReadError, }, file::{ new_profiler, FileReference, FileWriteBuilder, Location, ProfileReport, ProfileReporter, }, }; #[derive(Clone, Serialize, Deserialize)] pub struct Cluster { #[serde(alias = "destination")] #[serde(alias = "nodes")] #[serde(alias = "node")] pub destinations: ClusterNodes, #[serde(alias = "metadata")] pub metadata: MetadataTypes, pub profiles: ClusterProfiles, #[serde(default)] #[serde(alias = "tunable")] #[serde(alias = "tuning")] pub tunables: Tunables, } impl Cluster { pub async
parity_chunks(profile.get_parity_chunks()) .write(reader) .await; match result { Ok(mut file_ref) => { file_ref.content_type = content_type; self.metadata.write(path, &file_ref).await.unwrap(); (reporter.profile().await, Ok(())) }, Err(err) => (reporter.profile().await, Err(err.into())), } } pub async fn get_file_ref( &self, path: impl AsRef<Path>, ) -> Result<FileReference, MetadataReadError> { self.metadata.read(path).await } pub async fn read_file( &self, path: impl AsRef<Path>, ) -> Result<impl AsyncRead + Unpin, MetadataReadError> { let file_ref = self.get_file_ref(path).await?; let reader = file_ref.read_builder_owned().reader_owned(); Ok(reader) } pub fn get_destination(&self, profile: &ClusterProfile) -> Destination { let inner = DestinationInner { nodes: self.destinations.clone(), location_context: self.tunables.as_ref().clone(), profile: profile.clone(), }; Destination(inner.into()) } pub fn get_destination_with_profiler( &self, profile: &ClusterProfile, ) -> (ProfileReporter, Destination) { let (profiler, reporter) = new_profiler(); let location_context = self .tunables .generate_location_context_builder() .profiler(profiler) .build(); ( reporter, Destination( DestinationInner { nodes: self.destinations.clone(), location_context, profile: profile.clone(), } .into(), ), ) } pub fn get_profile<'a>( &self, profile: impl Into<Option<&'a str>>, ) -> Option<&'_ ClusterProfile> { self.profiles.get(profile) } pub async fn list_files( &self, path: &Path, ) -> Result<impl Stream<Item = io::Result<FileOrDirectory>> + 'static, MetadataReadError> { self.metadata.list(path).await } }
fn from_location( location: impl TryInto<Location, Error = impl Into<LocationParseError>>, ) -> Result<Cluster, MetadataReadError> { MetadataFormat::Yaml.from_location(location).await } pub fn get_file_writer(&self, profile: &ClusterProfile) -> FileWriteBuilder<Destination> { let destination = self.get_destination(profile); FileReference::write_builder() .destination(destination) .chunk_size((1_usize) << profile.get_chunk_size()) .data_chunks(profile.get_data_chunks()) } pub async fn write_file_ref( &self, path: impl AsRef<Path>, file_ref: &FileReference, ) -> Result<(), ClusterError> { self.metadata.write(path, &file_ref).await?; Ok(()) } pub async fn write_file<R>( &self, path: impl AsRef<Path>, reader: &mut R, profile: &ClusterProfile, content_type: Option<String>, ) -> Result<(), ClusterError> where R: AsyncRead + Unpin, { let mut file_ref = self.get_file_writer(profile).write(reader).await?; file_ref.content_type = content_type; self.metadata.write(path, &file_ref).await.unwrap(); Ok(()) } pub async fn write_file_with_report<R>( &self, path: impl AsRef<Path>, reader: &mut R, profile: &ClusterProfile, content_type: Option<String>, ) -> (ProfileReport, Result<(), ClusterError>) where R: AsyncRead + Unpin, { let (reporter, destination) = self.get_destination_with_profiler(profile); let result = FileReference::write_builder() .destination(destination) .chunk_size((1_usize) << profile.get_chunk_size()) .data_chunks(profile.get_data_chunks()) .
random
[ { "content": "#[derive(Serialize, Deserialize)]\n\nstruct MetadataGitSerde {\n\n #[serde(default)]\n\n pub format: MetadataFormat,\n\n pub path: PathBuf,\n\n}\n\n\n\nimpl From<MetadataGitSerde> for MetadataGit {\n\n fn from(meta: MetadataGitSerde) -> Self {\n\n let MetadataGitSerde { format, ...
Rust
azul-layout/src/style.rs
dignifiedquire/azul
de204bf2770286866c4da5d049827e04dab22347
use crate::geometry::{Offsets, Size}; use crate::number::Number; use azul_css::PixelValue; #[derive(Copy, Clone, PartialEq, Debug)] pub enum AlignItems { FlexStart, FlexEnd, Center, Baseline, Stretch, } impl Default for AlignItems { fn default() -> AlignItems { AlignItems::Stretch } } #[derive(Copy, Clone, PartialEq, Debug)] pub enum AlignSelf { Auto, FlexStart, FlexEnd, Center, Baseline, Stretch, } impl Default for AlignSelf { fn default() -> AlignSelf { AlignSelf::Auto } } #[derive(Copy, Clone, PartialEq, Debug)] pub enum AlignContent { FlexStart, FlexEnd, Center, Stretch, SpaceBetween, SpaceAround, } impl Default for AlignContent { fn default() -> AlignContent { AlignContent::Stretch } } #[derive(Copy, Clone, PartialEq, Debug)] pub enum Direction { Inherit, LTR, RTL, } impl Default for Direction { fn default() -> Direction { Direction::Inherit } } #[derive(Copy, Clone, PartialEq, Debug)] pub enum Display { Flex, Inline, None, } impl Default for Display { fn default() -> Display { Display::Flex } } #[derive(Copy, Clone, PartialEq, Debug)] pub enum FlexDirection { Row, Column, RowReverse, ColumnReverse, } impl Default for FlexDirection { fn default() -> FlexDirection { FlexDirection::Row } } impl FlexDirection { pub(crate) fn is_row(self) -> bool { self == FlexDirection::Row || self == FlexDirection::RowReverse } pub(crate) fn is_column(self) -> bool { self == FlexDirection::Column || self == FlexDirection::ColumnReverse } pub(crate) fn is_reverse(self) -> bool { self == FlexDirection::RowReverse || self == FlexDirection::ColumnReverse } } #[derive(Copy, Clone, PartialEq, Debug)] pub enum JustifyContent { FlexStart, FlexEnd, Center, SpaceBetween, SpaceAround, SpaceEvenly, } impl Default for JustifyContent { fn default() -> JustifyContent { JustifyContent::FlexStart } } #[derive(Copy, Clone, PartialEq, Debug)] pub enum Overflow { Visible, Hidden, Scroll, } impl Default for Overflow { fn default() -> Overflow { Overflow::Visible } } #[derive(Copy, Clone, PartialEq, Debug)] pub enum PositionType { Relative, Absolute, } impl Default for PositionType { fn default() -> PositionType { PositionType::Relative } } #[derive(Copy, Clone, PartialEq, Debug)] pub enum FlexWrap { NoWrap, Wrap, WrapReverse, } impl Default for FlexWrap { fn default() -> FlexWrap { FlexWrap::NoWrap } } #[derive(Copy, Clone, PartialEq, Debug)] pub enum Dimension { Undefined, Auto, Pixels(f32), Percent(f32), } impl Default for Dimension { fn default() -> Dimension { Dimension::Undefined } } impl Dimension { pub(crate) fn resolve(self, parent_width: Number) -> Number { match self { Dimension::Pixels(pixels) => Number::Defined(pixels), Dimension::Percent(percent) => parent_width * (percent / 100.0), _ => Number::Undefined, } } pub(crate) fn is_defined(self) -> bool { match self { Dimension::Pixels(_) => true, Dimension::Percent(_) => true, _ => false, } } } impl Default for Offsets<Dimension> { fn default() -> Offsets<Dimension> { Offsets { right: Default::default(), left: Default::default(), top: Default::default(), bottom: Default::default(), } } } impl Default for Size<Dimension> { fn default() -> Size<Dimension> { Size { width: Dimension::Auto, height: Dimension::Auto, } } } #[derive(Copy, Clone, PartialEq, Debug)] pub enum BoxSizing { ContentBox, BorderBox, } impl Default for BoxSizing { fn default() -> BoxSizing { BoxSizing::ContentBox } } #[derive(Copy, Clone, Debug)] pub struct Style { pub display: Display, pub box_sizing: BoxSizing, pub position_type: PositionType, pub direction: Direction, pub flex_direction: FlexDirection, pub flex_wrap: FlexWrap, pub overflow: Overflow, pub align_items: AlignItems, pub align_self: AlignSelf, pub align_content: AlignContent, pub justify_content: JustifyContent, pub position: Offsets<Dimension>, pub margin: Offsets<Dimension>, pub padding: Offsets<Dimension>, pub border: Offsets<Dimension>, pub flex_grow: f32, pub flex_shrink: f32, pub flex_basis: Dimension, pub size: Size<Dimension>, pub min_size: Size<Dimension>, pub max_size: Size<Dimension>, pub aspect_ratio: Number, pub font_size_px: PixelValue, pub letter_spacing: Option<PixelValue>, pub word_spacing: Option<PixelValue>, pub line_height: Option<f32>, pub tab_width: Option<f32>, } impl Default for Style { fn default() -> Style { Style { display: Default::default(), box_sizing: Default::default(), position_type: Default::default(), direction: Default::default(), flex_direction: Default::default(), flex_wrap: Default::default(), overflow: Default::default(), align_items: Default::default(), align_self: Default::default(), align_content: Default::default(), justify_content: Default::default(), position: Default::default(), margin: Default::default(), padding: Default::default(), border: Default::default(), flex_grow: 0.0, flex_shrink: 1.0, flex_basis: Dimension::Auto, size: Default::default(), min_size: Default::default(), max_size: Default::default(), aspect_ratio: Default::default(), font_size_px: PixelValue::const_px(10), letter_spacing: None, line_height: None, word_spacing: None, tab_width: None, } } } impl Style { pub(crate) fn min_main_size(&self, direction: FlexDirection) -> Dimension { match direction { FlexDirection::Row | FlexDirection::RowReverse => self.min_size.width, FlexDirection::Column | FlexDirection::ColumnReverse => self.min_size.height, } } pub(crate) fn max_main_size(&self, direction: FlexDirection) -> Dimension { match direction { FlexDirection::Row | FlexDirection::RowReverse => self.max_size.width, FlexDirection::Column | FlexDirection::ColumnReverse => self.max_size.height, } } pub(crate) fn main_margin_start(&self, direction: FlexDirection) -> Dimension { match direction { FlexDirection::Row | FlexDirection::RowReverse => self.margin.left, FlexDirection::Column | FlexDirection::ColumnReverse => self.margin.top, } } pub(crate) fn main_margin_end(&self, direction: FlexDirection) -> Dimension { match direction { FlexDirection::Row | FlexDirection::RowReverse => self.margin.right, FlexDirection::Column | FlexDirection::ColumnReverse => self.margin.bottom, } } pub(crate) fn cross_size(&self, direction: FlexDirection) -> Dimension { match direction { FlexDirection::Row | FlexDirection::RowReverse => self.size.height, FlexDirection::Column | FlexDirection::ColumnReverse => self.size.width, } } pub(crate) fn min_cross_size(&self, direction: FlexDirection) -> Dimension { match direction { FlexDirection::Row | FlexDirection::RowReverse => self.min_size.height, FlexDirection::Column | FlexDirection::ColumnReverse => self.min_size.width, } } pub(crate) fn max_cross_size(&self, direction: FlexDirection) -> Dimension { match direction { FlexDirection::Row | FlexDirection::RowReverse => self.max_size.height, FlexDirection::Column | FlexDirection::ColumnReverse => self.max_size.width, } } pub(crate) fn cross_margin_start(&self, direction: FlexDirection) -> Dimension { match direction { FlexDirection::Row | FlexDirection::RowReverse => self.margin.top, FlexDirection::Column | FlexDirection::ColumnReverse => self.margin.left, } } pub(crate) fn cross_margin_end(&self, direction: FlexDirection) -> Dimension { match direction { FlexDirection::Row | FlexDirection::RowReverse => self.margin.bottom, FlexDirection::Column | FlexDirection::ColumnReverse => self.margin.right, } } pub(crate) fn align_self(&self, parent: &Style) -> AlignSelf { if self.align_self == AlignSelf::Auto { match parent.align_items { AlignItems::FlexStart => AlignSelf::FlexStart, AlignItems::FlexEnd => AlignSelf::FlexEnd, AlignItems::Center => AlignSelf::Center, AlignItems::Baseline => AlignSelf::Baseline, AlignItems::Stretch => AlignSelf::Stretch, } } else { self.align_self } } }
use crate::geometry::{Offsets, Size}; use crate::number::Number; use azul_css::PixelValue; #[derive(Copy, Clone, PartialEq, Debug)] pub enum AlignItems { FlexStart, FlexEnd, Center, Baseline, Stretch, } impl Default for AlignItems { fn default() -> AlignItems { AlignItems::Stretch } } #[derive(Copy, Clone, PartialEq, Debug)] pub enum AlignSelf { Auto, FlexStart, FlexEnd, Center, Baseline, Stretch, } impl Default for AlignSelf { fn default() -> AlignSelf { AlignSelf::Auto } } #[derive(Copy, Clone, PartialEq, Debug)] pub enum AlignContent { FlexStart, FlexEnd, Center, Stretch, SpaceBetween, SpaceAround, } impl Default for AlignContent { fn default() -> AlignContent { AlignContent::Stretch } } #[derive(Copy, Clone, PartialEq, Debug)] pub enum Direction { Inherit, LTR, RTL, } impl Default for Direction { fn default() -> Direction { Direction::Inherit } } #[derive(Copy, Clone, PartialEq, Debug)] pub enum Display { Flex, Inline, None, } impl Default for Display { fn default() -> Display { Display::Flex } } #[derive(Copy, Clone, PartialEq, Debug)] pub enum FlexDirection { Row, Column, RowReverse, ColumnReverse, } impl Default for FlexDirection { fn default() -> FlexDirection { FlexDirection::Row } } impl FlexDirection { pub(crate) fn is_row(self) -> bool { self == FlexDirection::Row || self == FlexDirection::RowReverse } pub(crate) fn is_column(self) -> bool { self == FlexDirection::Column || self == FlexDirection::ColumnReverse } pub(crate) fn is_reverse(self) -> bool { self == FlexDirection::RowReverse || self == FlexDirection::ColumnReverse } } #[derive(Copy, Clone, PartialEq, Debug)] pub enum JustifyContent { FlexStart, FlexEnd, Center, SpaceBetween, SpaceAround, SpaceEvenly, } impl Default for JustifyContent { fn default() -> JustifyContent { JustifyContent::FlexStart } } #[derive(Copy, Clone, PartialEq, Debug)] pub enum Overflow { Visible, Hidden, Scroll, } impl Default for Overflow { fn default() -> Overflow { Overflow::Visible } } #[derive(Copy, Clone, PartialEq, Debug)] pub enum PositionType { Relative, Absolute, } impl Default for PositionType { fn default() -> PositionType { PositionType::Relative } } #[derive(Copy, Clone, PartialEq, Debug)] pub enum FlexWrap { NoWrap, Wrap, WrapReverse, } impl Default for FlexWrap { fn default() -> FlexWrap { FlexWrap::NoWrap } } #[derive(Copy, Clone, PartialEq, Debug)] pub enum Dimension { Undefined, Auto, Pixels(f32), Percent(f32), } impl Default for Dimension { fn default() -> Dimension { Dimension::Undefined } } impl Dimension { pub(crate) fn resolve(self, parent_width: Number) -> Number { match self { Dimension::Pixels(pixels) => Number::Defined(pixels), Dimension::Percent(percent) => parent_width * (percent / 100.0), _ => Number::Undefined, } } pub(crate) fn is_defined(self) -> bool { match self { Dimension::Pixels(_) => true, Dimension::Percent(_) => true, _ => false, } } } impl Default for Offsets<Dimension> { fn default() -> Offsets<Dimension> { Offsets { right: Default::default(), left: Default::default(), top: Default::default(), bottom: Default::default(), } } } impl Default for Size<Dimension> { fn default() -> Size<Dimension> { Size { width: Dimension::Auto, height: Dimension::Auto, } } } #[derive(Copy, Clone, PartialEq, Debug)] pub enum BoxSizing { ContentBox, BorderBox, } impl Default for BoxSizing { fn default() -> BoxSizing { BoxSizing::ContentBox } } #[derive(Copy, Clone, Debug)] pub struct Style { pub display: Display, pub box_sizing: BoxSizing, pub position_type: PositionType, pub direction: Direction, pub flex_direction: FlexDirection, pub flex_wrap: FlexWrap, pub overflow: Overflow, pub align_items: AlignItems, pub align_self: AlignSelf, pub align_content: AlignContent, pub justify_content: JustifyContent, pub position: Offsets<Dimension>, pub margin: Offsets<Dimension>, pub padding: Offsets<Dimension>, pub border: Offsets<Dimension>, pub flex_grow: f32, pub flex_shrink: f32, pub flex_basis: Dimension, pub size: Size<Dimension>, pub min_size: Size<Dimension>, pub max_size: Size<Dimension>, pub aspect_ratio: Number, pub font_size_px: PixelValue, pub letter_spacing: Option<PixelValue>, pub word_spacing: Option<PixelValue>, pub line_height: Option<f32>, pub tab_width: Option<f32>, } impl Default for Style { fn default() -> Style { Style { display: Default::default(), box_sizing: Default::default(), position_type: Default::default(), direction: Default::default(), flex_direction: Default::default(), flex_wrap: Default::default(), overflow: Default::default(), align_items: Default::default(), align_self: Default::default(), align_content: Default::default(), justify_content: Default::default(), position: Default::default(), margin: Default::default(), padding: Default::default(), border: Default::default(), flex_grow: 0.0, flex_shrink: 1.0, flex_basis: Dimension::Auto, size: Default::default(), min_size: Default::default(), max_size: Default::default(), aspect_ratio: Default::default(), font_size_px: PixelValue::const_px(10), letter_spacing: None, line_height: None, word_spacing: None, tab_width: None, } } } impl Style { pub(crate) fn min_main_size(&self, direction: FlexDirection) -> Dimension { match direction { FlexDirection::Row | FlexDirection::RowReverse => self.min_size.width, FlexDirection::Column | FlexDirection::ColumnReverse => self.min_size.height, } } pub(crate) fn max_main_size(&self, direction: FlexDirection) -> Dimension { match direction { FlexDirection::Row | FlexDirection::RowReverse => self.max_size.width, FlexDirection::Column | FlexDirection::ColumnReverse => self.max_size.height, } } pub(crate) fn main_margin_start(&self, direction: FlexDirection) -> Dimension { match direction { FlexDirection::Row | FlexDirection::RowReverse => self.margin.left, FlexDirection::Column | FlexDirection::ColumnReverse => self.margin.top, } } pub(crate) fn main_margin_end(&self, direction: FlexDirection) -> Dimension { match direction { FlexDirection::Row | FlexDirection::RowReverse => self.margin.right, FlexDirection::Column | FlexDirection::ColumnReverse => self.margin.bottom, } } pub(crate) fn cross_size(&self, direction: FlexDirection) -> Dimension { match direction { FlexDirection::Row | FlexDirection::RowReverse => self.size.height, FlexDirection::Column | FlexDirection::ColumnReverse => self.size.width, } } pub(crate) fn min_cross_size(&self, direction: FlexDirection) -> Dimension { match direction { FlexDirection::Row | FlexDirection::RowReverse => self.min_size.height, FlexDirection::Column | FlexDirection::ColumnReverse => self.min_size.width, } } pub(crate) fn max_cross_size(&self, direction: FlexDirection) -> Dimension { match direction { FlexDirection::Row | FlexDirection::RowReverse => self.max_size.height, FlexDirection::Column | FlexDirection::ColumnReverse => self.max_size.width, } }
pub(crate) fn cross_margin_end(&self, direction: FlexDirection) -> Dimension { match direction { FlexDirection::Row | FlexDirection::RowReverse => self.margin.bottom, FlexDirection::Column | FlexDirection::ColumnReverse => self.margin.right, } } pub(crate) fn align_self(&self, parent: &Style) -> AlignSelf { if self.align_self == AlignSelf::Auto { match parent.align_items { AlignItems::FlexStart => AlignSelf::FlexStart, AlignItems::FlexEnd => AlignSelf::FlexEnd, AlignItems::Center => AlignSelf::Center, AlignItems::Baseline => AlignSelf::Baseline, AlignItems::Stretch => AlignSelf::Stretch, } } else { self.align_self } } }
pub(crate) fn cross_margin_start(&self, direction: FlexDirection) -> Dimension { match direction { FlexDirection::Row | FlexDirection::RowReverse => self.margin.top, FlexDirection::Column | FlexDirection::ColumnReverse => self.margin.left, } }
function_block-full_function
[ { "content": "/// For a given line number (**NOTE: 0-indexed!**), calculates the Y\n\n/// position of the bottom left corner\n\npub fn get_line_y_position(line_number: usize, font_size_px: f32, line_height_px: f32) -> f32 {\n\n ((font_size_px + line_height_px) * line_number as f32) + font_size_px\n\n}\n\n\n"...
Rust
polars/polars-arrow/src/builder.rs
Spirans/polars
7774f419fdbf79bc4c4ec3bd6f0f72d87b32a70c
use crate::bit_util; use crate::vec::AlignedVec; pub use arrow::array::LargeStringBuilder; use arrow::array::{ ArrayBuilder, ArrayData, ArrayRef, BooleanArray, LargeStringArray, PrimitiveArray, }; use arrow::buffer::{Buffer, MutableBuffer}; use arrow::datatypes::{ArrowPrimitiveType, DataType}; use std::any::Any; use std::mem; use std::sync::Arc; #[derive(Debug)] pub struct BooleanBufferBuilder { buffer: MutableBuffer, len: usize, } impl BooleanBufferBuilder { #[inline] pub fn new(capacity: usize) -> Self { let byte_capacity = bit_util::ceil(capacity, 8); let buffer = MutableBuffer::from_len_zeroed(byte_capacity); Self { buffer, len: 0 } } pub fn len(&self) -> usize { self.len } pub fn is_empty(&self) -> bool { self.len == 0 } pub fn capacity(&self) -> usize { self.buffer.capacity() * 8 } #[inline] pub fn advance(&mut self, additional: usize) { let new_len = self.len + additional; let new_len_bytes = bit_util::ceil(new_len, 8); if new_len_bytes > self.buffer.len() { self.buffer.resize(new_len_bytes, 0); } self.len = new_len; } #[inline] pub fn reserve(&mut self, additional: usize) { let capacity = self.len + additional; if capacity > self.capacity() { let additional = bit_util::ceil(capacity, 8) - self.buffer.len(); self.buffer.reserve(additional); } } #[inline] pub fn append(&mut self, v: bool) { self.advance(1); if v { unsafe { bit_util::set_bit_raw(self.buffer.as_mut_ptr(), self.len - 1) }; } } #[inline] pub fn append_n(&mut self, additional: usize, v: bool) { self.advance(additional); if additional > 0 && v { let offset = self.len() - additional; (0..additional).for_each(|i| unsafe { bit_util::set_bit_raw(self.buffer.as_mut_ptr(), offset + i) }) } } #[inline] pub fn append_slice(&mut self, slice: &[bool]) { let additional = slice.len(); self.advance(additional); let offset = self.len() - additional; for (i, v) in slice.iter().enumerate() { if *v { unsafe { bit_util::set_bit_raw(self.buffer.as_mut_ptr(), offset + i) } } } } pub fn shrink_to_fit(&mut self) { let byte_len = bit_util::ceil(self.len(), 8); self.buffer.resize(byte_len, 0) } #[inline] pub fn finish(&mut self) -> Buffer { let buf = std::mem::replace(&mut self.buffer, MutableBuffer::new(0)); self.len = 0; buf.into() } } #[derive(Debug)] pub struct BooleanArrayBuilder { values_builder: BooleanBufferBuilder, bitmap_builder: BooleanBufferBuilder, } impl BooleanArrayBuilder { pub fn new(capacity: usize) -> Self { Self { values_builder: BooleanBufferBuilder::new(capacity), bitmap_builder: BooleanBufferBuilder::new(capacity), } } pub fn new_no_nulls(capacity: usize) -> Self { Self { values_builder: BooleanBufferBuilder::new(capacity), bitmap_builder: BooleanBufferBuilder::new(0), } } pub fn capacity(&self) -> usize { self.values_builder.capacity() } pub fn append_value(&mut self, v: bool) { self.bitmap_builder.append(true); self.values_builder.append(v); } pub fn append_null(&mut self) { self.bitmap_builder.append(false); self.values_builder.advance(1); } pub fn append_option(&mut self, v: Option<bool>) { match v { None => self.append_null(), Some(v) => self.append_value(v), }; } pub fn append_slice(&mut self, v: &[bool]) { self.bitmap_builder.append_n(v.len(), true); self.values_builder.append_slice(v); } pub fn append_values(&mut self, values: &[bool], is_valid: &[bool]) { assert_eq!(values.len(), is_valid.len()); self.bitmap_builder.append_slice(is_valid); self.values_builder.append_slice(values); } pub fn shrink_to_fit(&mut self) { self.values_builder.shrink_to_fit(); self.bitmap_builder.shrink_to_fit(); } pub fn finish_with_null_buffer(&mut self, buffer: Buffer) -> BooleanArray { self.shrink_to_fit(); let len = self.len(); let data = ArrayData::builder(DataType::Boolean) .len(len) .add_buffer(self.values_builder.finish()) .null_bit_buffer(buffer) .build(); BooleanArray::from(data) } pub fn finish(&mut self) -> BooleanArray { self.shrink_to_fit(); let len = self.len(); let null_bit_buffer = self.bitmap_builder.finish(); let null_count = len - null_bit_buffer.count_set_bits(); let mut builder = ArrayData::builder(DataType::Boolean) .len(len) .add_buffer(self.values_builder.finish()); if null_count > 0 { builder = builder.null_bit_buffer(null_bit_buffer); } let data = builder.build(); BooleanArray::from(data) } } impl ArrayBuilder for BooleanArrayBuilder { fn as_any(&self) -> &dyn Any { self } fn as_any_mut(&mut self) -> &mut dyn Any { self } fn into_box_any(self: Box<Self>) -> Box<dyn Any> { self } fn len(&self) -> usize { self.values_builder.len() } fn is_empty(&self) -> bool { self.values_builder.is_empty() } fn finish(&mut self) -> ArrayRef { Arc::new(self.finish()) } } pub struct PrimitiveArrayBuilder<T> where T: ArrowPrimitiveType, T::Native: Default, { values: AlignedVec<T::Native>, bitmap_builder: BooleanBufferBuilder, null_count: usize, } impl<T> PrimitiveArrayBuilder<T> where T: ArrowPrimitiveType, T::Native: Default, { pub fn new(capacity: usize) -> Self { let values = AlignedVec::<T::Native>::with_capacity_aligned(capacity); let bitmap_builder = BooleanBufferBuilder::new(capacity); Self { values, bitmap_builder, null_count: 0, } } pub fn new_no_nulls(capacity: usize) -> Self { let values = AlignedVec::<T::Native>::with_capacity_aligned(capacity); let bitmap_builder = BooleanBufferBuilder::new(0); Self { values, bitmap_builder, null_count: 0, } } #[inline] pub fn append_value(&mut self, v: T::Native) { self.values.push(v); self.bitmap_builder.append(true); } #[inline] pub fn append_slice(&mut self, other: &[T::Native]) { self.values.extend_from_slice(other) } #[inline] pub fn append_null(&mut self) { self.bitmap_builder.append(false); self.values.push(Default::default()); self.null_count += 1; } pub fn shrink_to_fit(&mut self) { self.values.shrink_to_fit(); self.bitmap_builder.shrink_to_fit(); } pub fn finish_with_null_buffer(&mut self, buffer: Buffer) -> PrimitiveArray<T> { self.shrink_to_fit(); let values = mem::take(&mut self.values); values.into_primitive_array(Some(buffer)) } pub fn finish(&mut self) -> PrimitiveArray<T> { self.shrink_to_fit(); let values = mem::take(&mut self.values); let null_bit_buffer = self.bitmap_builder.finish(); let buf = if self.null_count == 0 { None } else { Some(null_bit_buffer) }; values.into_primitive_array(buf) } } impl<T> ArrayBuilder for PrimitiveArrayBuilder<T> where T: ArrowPrimitiveType, { fn len(&self) -> usize { self.values.len() } fn is_empty(&self) -> bool { self.values.is_empty() } fn finish(&mut self) -> ArrayRef { Arc::new(PrimitiveArrayBuilder::finish(self)) } fn as_any(&self) -> &dyn Any { self } fn as_any_mut(&mut self) -> &mut dyn Any { self } fn into_box_any(self: Box<Self>) -> Box<dyn Any> { self } } #[derive(Debug)] pub struct NoNullLargeStringBuilder { values: AlignedVec<u8>, offsets: AlignedVec<i64>, } impl NoNullLargeStringBuilder { pub fn with_capacity(values_capacity: usize, list_capacity: usize) -> Self { let mut offsets = AlignedVec::with_capacity_aligned(list_capacity + 1); offsets.push(0); Self { values: AlignedVec::with_capacity_aligned(values_capacity), offsets, } } pub fn extend_from_slices(&mut self, values: &[u8], offsets: &[i64]) { self.values.extend_from_slice(values); self.offsets.extend_from_slice(offsets); } #[inline] pub fn append_value(&mut self, value: &str) { self.values.extend_from_slice(value.as_bytes()); self.offsets.push(self.values.len() as i64); } pub fn finish(&mut self) -> LargeStringArray { let values = mem::take(&mut self.values); let offsets = mem::take(&mut self.offsets); let offsets_len = offsets.len() - 1; let buf_offsets = offsets.into_arrow_buffer(); let buf_values = values.into_arrow_buffer(); assert_eq!(buf_values.len(), buf_values.capacity()); assert_eq!(buf_offsets.len(), buf_offsets.capacity()); let arraydata = ArrayData::builder(DataType::LargeUtf8) .len(offsets_len) .add_buffer(buf_offsets) .add_buffer(buf_values) .build(); LargeStringArray::from(arraydata) } } #[cfg(test)] mod test { use super::*; use arrow::array::Array; use arrow::datatypes::UInt32Type; #[test] fn test_primitive_builder() { let mut builder = PrimitiveArrayBuilder::<UInt32Type>::new(10); builder.append_value(0); builder.append_null(); let out = builder.finish(); assert_eq!(out.len(), 2); assert_eq!(out.null_count(), 1); dbg!(out); } #[test] fn test_string_builder() { let mut builder = LargeStringBuilder::with_capacity(1, 3); builder.append_value("foo").unwrap(); builder.append_null().unwrap(); builder.append_value("bar").unwrap(); let out = builder.finish(); let vals = out.iter().collect::<Vec<_>>(); assert_eq!(vals, &[Some("foo"), None, Some("bar")]); } }
use crate::bit_util; use crate::vec::AlignedVec; pub use arrow::array::LargeStringBuilder; use arrow::array::{ ArrayBuilder, ArrayData, ArrayRef, BooleanArray, LargeStringArray, PrimitiveArray, }; use arrow::buffer::{Buffer, MutableBuffer}; use arrow::datatypes::{ArrowPrimitiveType, DataType}; use std::any::Any; use std::mem; use std::sync::Arc; #[derive(Debug)] pub struct BooleanBufferBuilder { buffer: MutableBuffer, len: usize, } impl BooleanBufferBuilder { #[inline] pub fn new(capacity: usize) -> Self { let byte_capacity = bit_util::ceil(capacity, 8); let buffer = MutableBuffer::from_len_zeroed(byte_capacity); Self { buffer, len: 0 } } pub fn len(&self) -> usize { self.len } pub fn is_empty(&self) -> bool { self.len == 0 } pub fn capacity(&self) -> usize { self.buffer.capacity() * 8 } #[inline] pub fn advance(&mut self, additional: usize) { let new_len = self.len + additional; let new_len_bytes = bit_util::ceil(new_len, 8); if new_len_bytes > self.buffer.len() { self.buffer.resize(new_len_bytes, 0); } self.len = new_len; } #[inline] pub fn reserve(&mut self, additional: usize) { let capacity = self.len + additional; if capacity > self.capacity() { let additional = bit_util::ceil(capacity, 8) - self.buffer.len(); self.buffer.reserve(additional); } } #[inline] pub fn append(&mut self, v: bool) { self.advance(1); if v { unsafe { bit_util::set_bit_raw(self.buffer.as_mut_ptr(), self.len - 1) }; } } #[inline] pub fn append_n(&mut self, additional: usize, v: bool) { self.advance(additional); if additional > 0 && v { let offset = self.len() - additional; (0..additional).for_each(|i| unsafe { bit_util::set_bit_raw(self.buffer.as_mut_ptr(), offset + i) }) } } #[inline] pub fn append_slice(&mut self, slice: &[bool]) { let additional = slice.len(); self.advance(additional); let offset = self.len() - additional; for (i, v) in slice.iter().enumerate() { if *v { unsafe { bit_util::set_bit_raw(self.buffer.as_mut_ptr(), offset + i) } } } } pub fn shrink_to_fit(&mut self) { let byte_len = bit_util::ceil(self.len(), 8); self.buffer.resize(byte_len, 0) } #[inline] pub fn finish(&mut self) -> Buffer { let buf = std::mem::replace(&mut self.buffer, MutableBuffer::new(0)); self.len = 0; buf.into() } } #[derive(Debug)] pub struct BooleanArrayBuilder { values_builder: BooleanBufferBuilder, bitmap_builder: BooleanBufferBuilder, } impl BooleanArrayBuilder { pub fn new(capacity: usize) -> Self { Self { values_builder: BooleanBufferBuilder::new(capacity), bitmap_builder: BooleanBufferBuilder::new(capacity), } } pub fn new_no_nulls(capacity: usize) -> Self { Self { values_builder: BooleanBufferBuilder::new(capacity), bitmap_builder: BooleanBufferBuilder::new(0), } } pub fn capacity(&self) -> usize { self.values_builder.capacity() } pub fn append_value(&mut self, v: bool) { self.bitmap_builder.append(true); self.values_builder.append(v); } pub fn append_null(&mut self) { self.bitmap_builder.append(false); self.values_builder.advance(1); } pub fn append_option(&mut self, v: Option<bool>) { match v { None => self.append_null(), Some(v) => self.append_value(v), }; } pub fn append_slice(&mut self, v: &[bool]) { self.bitmap_builder.append_n(v.len(), true); self.values_builder.append_slice(v); } pub fn append_values(&mut self, values: &[bool], is_valid: &[bool]) { assert_eq!(values.len(), is_valid.len()); self.bitmap_builder.append_slice(is_valid); self.values_builder.append_slice(values); } pub fn shrink_to_fit(&mut self) { self.values_builder.shrink_to_fit(); self.bitmap_builder.shrink_to_fit(); } pub fn finish_with_null_buffer(&mut self, buffer: Buffer) -> BooleanArray { self.shrink_to_fit(); let len = self.len(); let data = ArrayData::builder(DataType::Boolean) .len(len) .add_buffer(self.values_builder.finish()) .null_bit_buffer(buffer) .build(); BooleanArray::from(data) } pub fn finish(&mut self) -> BooleanArray { self.shrink_to_fit(); let len = self.len(); let null_bit_buffer = self.bitmap_builder.finish(); let null_count = len - null_bit_buffer.count_set_bits(); let mut builder = ArrayData::builder(DataType::Boolean) .len(len) .add_buffer(self.values_builder.finish()); if null_count > 0 { builder = builder.null_bit_buffer(null_bit_buffer); } let data = builder.build(); BooleanArray::from(data) } } impl ArrayBuilder for BooleanArrayBuilder { fn as_any(&self) -> &dyn Any { self } fn as_any_mut(&mut self) -> &mut dyn Any { self } fn into_box_any(self: Box<Self>) -> Box<dyn Any> { self } fn len(&self) -> usize { self.values_builder.len() } fn is_empt
extend_from_slice(values); self.offsets.extend_from_slice(offsets); } #[inline] pub fn append_value(&mut self, value: &str) { self.values.extend_from_slice(value.as_bytes()); self.offsets.push(self.values.len() as i64); } pub fn finish(&mut self) -> LargeStringArray { let values = mem::take(&mut self.values); let offsets = mem::take(&mut self.offsets); let offsets_len = offsets.len() - 1; let buf_offsets = offsets.into_arrow_buffer(); let buf_values = values.into_arrow_buffer(); assert_eq!(buf_values.len(), buf_values.capacity()); assert_eq!(buf_offsets.len(), buf_offsets.capacity()); let arraydata = ArrayData::builder(DataType::LargeUtf8) .len(offsets_len) .add_buffer(buf_offsets) .add_buffer(buf_values) .build(); LargeStringArray::from(arraydata) } } #[cfg(test)] mod test { use super::*; use arrow::array::Array; use arrow::datatypes::UInt32Type; #[test] fn test_primitive_builder() { let mut builder = PrimitiveArrayBuilder::<UInt32Type>::new(10); builder.append_value(0); builder.append_null(); let out = builder.finish(); assert_eq!(out.len(), 2); assert_eq!(out.null_count(), 1); dbg!(out); } #[test] fn test_string_builder() { let mut builder = LargeStringBuilder::with_capacity(1, 3); builder.append_value("foo").unwrap(); builder.append_null().unwrap(); builder.append_value("bar").unwrap(); let out = builder.finish(); let vals = out.iter().collect::<Vec<_>>(); assert_eq!(vals, &[Some("foo"), None, Some("bar")]); } }
y(&self) -> bool { self.values_builder.is_empty() } fn finish(&mut self) -> ArrayRef { Arc::new(self.finish()) } } pub struct PrimitiveArrayBuilder<T> where T: ArrowPrimitiveType, T::Native: Default, { values: AlignedVec<T::Native>, bitmap_builder: BooleanBufferBuilder, null_count: usize, } impl<T> PrimitiveArrayBuilder<T> where T: ArrowPrimitiveType, T::Native: Default, { pub fn new(capacity: usize) -> Self { let values = AlignedVec::<T::Native>::with_capacity_aligned(capacity); let bitmap_builder = BooleanBufferBuilder::new(capacity); Self { values, bitmap_builder, null_count: 0, } } pub fn new_no_nulls(capacity: usize) -> Self { let values = AlignedVec::<T::Native>::with_capacity_aligned(capacity); let bitmap_builder = BooleanBufferBuilder::new(0); Self { values, bitmap_builder, null_count: 0, } } #[inline] pub fn append_value(&mut self, v: T::Native) { self.values.push(v); self.bitmap_builder.append(true); } #[inline] pub fn append_slice(&mut self, other: &[T::Native]) { self.values.extend_from_slice(other) } #[inline] pub fn append_null(&mut self) { self.bitmap_builder.append(false); self.values.push(Default::default()); self.null_count += 1; } pub fn shrink_to_fit(&mut self) { self.values.shrink_to_fit(); self.bitmap_builder.shrink_to_fit(); } pub fn finish_with_null_buffer(&mut self, buffer: Buffer) -> PrimitiveArray<T> { self.shrink_to_fit(); let values = mem::take(&mut self.values); values.into_primitive_array(Some(buffer)) } pub fn finish(&mut self) -> PrimitiveArray<T> { self.shrink_to_fit(); let values = mem::take(&mut self.values); let null_bit_buffer = self.bitmap_builder.finish(); let buf = if self.null_count == 0 { None } else { Some(null_bit_buffer) }; values.into_primitive_array(buf) } } impl<T> ArrayBuilder for PrimitiveArrayBuilder<T> where T: ArrowPrimitiveType, { fn len(&self) -> usize { self.values.len() } fn is_empty(&self) -> bool { self.values.is_empty() } fn finish(&mut self) -> ArrayRef { Arc::new(PrimitiveArrayBuilder::finish(self)) } fn as_any(&self) -> &dyn Any { self } fn as_any_mut(&mut self) -> &mut dyn Any { self } fn into_box_any(self: Box<Self>) -> Box<dyn Any> { self } } #[derive(Debug)] pub struct NoNullLargeStringBuilder { values: AlignedVec<u8>, offsets: AlignedVec<i64>, } impl NoNullLargeStringBuilder { pub fn with_capacity(values_capacity: usize, list_capacity: usize) -> Self { let mut offsets = AlignedVec::with_capacity_aligned(list_capacity + 1); offsets.push(0); Self { values: AlignedVec::with_capacity_aligned(values_capacity), offsets, } } pub fn extend_from_slices(&mut self, values: &[u8], offsets: &[i64]) { self.values.
random
[ { "content": "#[inline]\n\npub fn slice_offsets(offset: i64, length: usize, array_len: usize) -> (usize, usize) {\n\n let abs_offset = offset.abs() as usize;\n\n\n\n // The offset counted from the start of the array\n\n // negative index\n\n if offset < 0 {\n\n if abs_offset <= array_len {\n\...
Rust
crates/holochain/tests/authored_test/mod.rs
MCYBA/holochain
74a9ac250285d38985fad9d41de3955646549606
use std::convert::TryFrom; use std::convert::TryInto; use std::time::Duration; use holo_hash::AnyDhtHash; use holo_hash::EntryHash; use holochain_state::prelude::fresh_reader_test; use holochain_wasm_test_utils::TestWasm; use holochain_zome_types::Entry; use holochain::test_utils::conductor_setup::ConductorTestData; use holochain::test_utils::host_fn_caller::*; use holochain::test_utils::wait_for_integration; use rusqlite::named_params; #[tokio::test(flavor = "multi_thread")] async fn authored_test() { observability::test_run().ok(); let num_attempts = 100; let delay_per_attempt = Duration::from_millis(100); let zomes = vec![TestWasm::Create]; let mut conductor_test = ConductorTestData::two_agents(zomes, true).await; let handle = conductor_test.handle(); let alice_call_data = conductor_test.alice_call_data(); let bob_call_data = conductor_test.bob_call_data().unwrap(); let entry = Post("Hi there".into()); let entry_hash = EntryHash::with_data_sync(&Entry::try_from(entry.clone()).unwrap()); alice_call_data .get_api(TestWasm::Create) .commit_entry(entry.clone().try_into().unwrap(), POST_ID) .await; let triggers = handle.get_cell_triggers(&alice_call_data.cell_id).unwrap(); triggers.publish_dht_ops.trigger(); fresh_reader_test(alice_call_data.authored_env.clone(), |txn| { let basis: AnyDhtHash = entry_hash.clone().into(); let has_authored_entry: bool = txn .query_row( "SELECT EXISTS(SELECT 1 FROM DhtOp JOIN Header ON DhtOp.header_hash = Header.hash WHERE basis_hash = :hash AND Header.author = :author)", named_params! { ":hash": basis, ":author": alice_call_data.cell_id.agent_pubkey(), }, |row| row.get(0), ) .unwrap(); assert!(has_authored_entry); }); let expected_count = 3 + 14; wait_for_integration( &bob_call_data.dht_env, expected_count, num_attempts, delay_per_attempt.clone(), ) .await; fresh_reader_test(bob_call_data.authored_env.clone(), |txn| { let basis: AnyDhtHash = entry_hash.clone().into(); let has_authored_entry: bool = txn .query_row( "SELECT EXISTS(SELECT 1 FROM DhtOp JOIN Header ON DhtOp.header_hash = Header.hash WHERE basis_hash = :hash AND Header.author = :author)", named_params! { ":hash": basis, ":author": bob_call_data.cell_id.agent_pubkey(), }, |row| row.get(0), ) .unwrap(); assert!(!has_authored_entry); }); fresh_reader_test(bob_call_data.dht_env.clone(), |txn| { let basis: AnyDhtHash = entry_hash.clone().into(); let has_integrated_entry: bool = txn .query_row( "SELECT EXISTS(SELECT 1 FROM DhtOp WHERE basis_hash = :hash)", named_params! { ":hash": basis, }, |row| row.get(0), ) .unwrap(); assert!(has_integrated_entry); }); bob_call_data .get_api(TestWasm::Create) .commit_entry(entry.clone().try_into().unwrap(), POST_ID) .await; let triggers = handle.get_cell_triggers(&bob_call_data.cell_id).unwrap(); triggers.publish_dht_ops.trigger(); fresh_reader_test(bob_call_data.authored_env.clone(), |txn| { let basis: AnyDhtHash = entry_hash.clone().into(); let has_authored_entry: bool = txn .query_row( "SELECT EXISTS(SELECT 1 FROM DhtOp JOIN Header ON DhtOp.header_hash = Header.hash WHERE basis_hash = :hash AND Header.author = :author)", named_params! { ":hash": basis, ":author": bob_call_data.cell_id.agent_pubkey(), }, |row| row.get(0), ) .unwrap(); assert!(has_authored_entry); }); conductor_test.shutdown_conductor().await; }
use std::convert::TryFrom; use std::convert::TryInto; use std::time::Duration; use holo_hash::AnyDhtHash; use holo_hash::EntryHash; use holochain_state::prelude::fresh_reader_test; use holochain_wasm_test_utils::TestWasm; use holochain_zome_types::Entry; use holochain::test_utils::conductor_setup::ConductorTestData; use holochain::test_utils::host_fn_caller::*; use holochain::test_utils::wait_for_integration; use rusqlite::named_params; #[tokio::test(flavor = "multi_thread")] async fn authored_test() { observability::test_run().ok(); let num_attempts = 100; let delay_per_attempt = Duration::from_millis(100); let zomes = vec![TestWasm::Create]; let mut conductor_test = ConductorT
.await; let triggers = handle.get_cell_triggers(&alice_call_data.cell_id).unwrap(); triggers.publish_dht_ops.trigger(); fresh_reader_test(alice_call_data.authored_env.clone(), |txn| { let basis: AnyDhtHash = entry_hash.clone().into(); let has_authored_entry: bool = txn .query_row( "SELECT EXISTS(SELECT 1 FROM DhtOp JOIN Header ON DhtOp.header_hash = Header.hash WHERE basis_hash = :hash AND Header.author = :author)", named_params! { ":hash": basis, ":author": alice_call_data.cell_id.agent_pubkey(), }, |row| row.get(0), ) .unwrap(); assert!(has_authored_entry); }); let expected_count = 3 + 14; wait_for_integration( &bob_call_data.dht_env, expected_count, num_attempts, delay_per_attempt.clone(), ) .await; fresh_reader_test(bob_call_data.authored_env.clone(), |txn| { let basis: AnyDhtHash = entry_hash.clone().into(); let has_authored_entry: bool = txn .query_row( "SELECT EXISTS(SELECT 1 FROM DhtOp JOIN Header ON DhtOp.header_hash = Header.hash WHERE basis_hash = :hash AND Header.author = :author)", named_params! { ":hash": basis, ":author": bob_call_data.cell_id.agent_pubkey(), }, |row| row.get(0), ) .unwrap(); assert!(!has_authored_entry); }); fresh_reader_test(bob_call_data.dht_env.clone(), |txn| { let basis: AnyDhtHash = entry_hash.clone().into(); let has_integrated_entry: bool = txn .query_row( "SELECT EXISTS(SELECT 1 FROM DhtOp WHERE basis_hash = :hash)", named_params! { ":hash": basis, }, |row| row.get(0), ) .unwrap(); assert!(has_integrated_entry); }); bob_call_data .get_api(TestWasm::Create) .commit_entry(entry.clone().try_into().unwrap(), POST_ID) .await; let triggers = handle.get_cell_triggers(&bob_call_data.cell_id).unwrap(); triggers.publish_dht_ops.trigger(); fresh_reader_test(bob_call_data.authored_env.clone(), |txn| { let basis: AnyDhtHash = entry_hash.clone().into(); let has_authored_entry: bool = txn .query_row( "SELECT EXISTS(SELECT 1 FROM DhtOp JOIN Header ON DhtOp.header_hash = Header.hash WHERE basis_hash = :hash AND Header.author = :author)", named_params! { ":hash": basis, ":author": bob_call_data.cell_id.agent_pubkey(), }, |row| row.get(0), ) .unwrap(); assert!(has_authored_entry); }); conductor_test.shutdown_conductor().await; }
estData::two_agents(zomes, true).await; let handle = conductor_test.handle(); let alice_call_data = conductor_test.alice_call_data(); let bob_call_data = conductor_test.bob_call_data().unwrap(); let entry = Post("Hi there".into()); let entry_hash = EntryHash::with_data_sync(&Entry::try_from(entry.clone()).unwrap()); alice_call_data .get_api(TestWasm::Create) .commit_entry(entry.clone().try_into().unwrap(), POST_ID)
random
[ { "content": "fn consistency(bench: &mut Criterion) {\n\n observability::test_run().ok();\n\n let mut group = bench.benchmark_group(\"consistency\");\n\n group.sample_size(\n\n std::env::var_os(\"BENCH_SAMPLE_SIZE\")\n\n .and_then(|s| s.to_string_lossy().parse::<usize>().ok())\n\n ...
Rust
src/soft_f32/soft_f32_add.rs
Inokinoki/softfpu-rs
152f71f131d5d38a4112bf5d2e2c2975af2c1e15
use super::util::{ f32_shift_right_jam, f32_norm_round_and_pack, f32_round_and_pack, f32_pack_raw, f32_pack, f32_propagate_nan, f32_sign, f32_exp, f32_frac, }; use crate::soft_f32::f32_sub; pub fn f32_add(a: u32, b: u32) -> u32 { let mut a_sign = f32_sign(a); let mut b_sign = f32_sign(b); let mut r_sign; if a_sign != b_sign { return f32_sub(a, b); } let mut a_exp = f32_exp(a); let mut b_exp = f32_exp(b); let mut r_exp; let mut a_frac = f32_frac(a); let mut b_frac = f32_frac(b); let mut r_frac; let diff_exp = a_exp - b_exp; if diff_exp == 0 { if a_exp == 0 { r_sign = a_sign; r_exp = a_exp; r_frac = a_frac + b_frac; return f32_pack_raw(r_sign, r_exp, r_frac); } if a_exp == 0xFF { if (a_frac | b_frac) != 0 { return f32_propagate_nan(a, b); } else { r_sign = a_sign; r_exp = a_exp; r_frac = a_frac + b_frac; return f32_pack_raw(r_sign, r_exp, r_frac); } } r_sign = a_sign; r_exp = a_exp; r_frac = 0x01000000 + a_frac + b_frac; if (r_frac & 0x01) == 0 && r_exp < 0xFE { return f32_pack_raw(r_sign, r_exp, r_frac >> 1); } r_frac <<= 6; } else { r_sign = a_sign; a_frac <<= 6; b_frac <<= 6; if diff_exp < 0 { if b_exp == 0xFF { if b_sign != 0 { return f32_propagate_nan(a, b); } else { return f32_pack_raw(r_sign, 0xFF, 0); } } r_exp = b_exp; if a_exp != 0 { a_frac += 0x20000000; } else { a_frac += a_frac; } a_frac = f32_shift_right_jam(a_frac, -diff_exp); } else { if a_exp == 0xFF { if a_sign != 0 { return f32_propagate_nan(a, b); } else { return f32_pack_raw(a_sign, a_exp, a_frac); } } r_exp = a_exp; if b_exp != 0 { b_frac += 0x20000000; } else { b_frac += b_frac; } b_frac = f32_shift_right_jam(b_frac, diff_exp); } r_frac = 0x20000000 + a_frac + b_frac; if r_frac < 0x40000000 { r_exp -= 1; r_frac <<= 1; } } f32_round_and_pack(r_sign, r_exp, r_frac) } #[cfg(test)] mod tests { #[test] fn test_f32_add() { assert_eq!(crate::soft_f32::f32_add(0x3DCCCCCD, 0x3E4CCCCD), 0x3E99999A); assert_eq!(crate::soft_f32::f32_add(0xBDCCCCCD, 0xBE4CCCCD), 0xBE99999A); assert_eq!(crate::soft_f32::f32_add(0x4640E400, 0x47849900), 0x479CB580); assert_eq!(crate::soft_f32::f32_add(0xC640E400, 0xC7849900), 0xC79CB580); assert_eq!(crate::soft_f32::f32_add(0x3B03126F, 0x3B03126F), 0x3B83126F); assert_eq!(crate::soft_f32::f32_add(0xBB03126F, 0xBB03126F), 0xBB83126F); assert_eq!(crate::soft_f32::f32_add(0xBDCCCCCD, 0x3E4CCCCD), 0x3DCCCCCD); assert_eq!(crate::soft_f32::f32_add(0x3DCCCCCD, 0xBE4CCCCD), 0xBDCCCCCD); } #[test] fn test_f32_add_inf_nan() { assert_eq!(crate::soft_f32::f32_add(0x7F800000, 0x3F800000), 0x7F800000); assert_eq!(crate::soft_f32::f32_add(0xFF800000, 0x3F800000), 0xFF800000); assert_eq!(crate::soft_f32::f32_is_nan(crate::soft_f32::f32_add(0xFF800000, 0x7F800000)), true); assert_eq!(crate::soft_f32::f32_add(0x7F800000, 0x3F800000), 0x7F800000); assert_eq!(crate::soft_f32::f32_add(0xFF800000, 0x3F800000), 0xFF800000); assert_eq!(crate::soft_f32::f32_add(0xFFFFFFFF, 0x3F800000), 0xFFFFFFFF); assert_eq!(crate::soft_f32::f32_is_nan(crate::soft_f32::f32_add(0xFFFFFFFF, 0x3F800000)), true); assert_eq!(crate::soft_f32::f32_is_nan(crate::soft_f32::f32_add(0xFFFFFFFF, 0x7F800000)), true); assert_eq!(crate::soft_f32::f32_is_nan(crate::soft_f32::f32_add(0xFFFFFFFF, 0xFF800000)), true); assert_eq!(crate::soft_f32::f32_add(0x0, 0xBDCCCCCE), 0xBDCCCCCE); assert_eq!(crate::soft_f32::f32_add(0x0, 0x3DCCCCCE), 0x3DCCCCCE); assert_eq!(crate::soft_f32::f32_add(0x80000000, 0xBDCCCCCE), 0xBDCCCCCE); assert_eq!(crate::soft_f32::f32_add(0x0, 0x0), 0x0); assert_eq!(crate::soft_f32::f32_add(0x0, 0x80000000), 0x0); } }
use super::util::{ f32_shift_right_jam, f32_norm_round_and_pack, f32_round_and_pack, f32_pack_raw, f32_pack, f32_propagate_nan, f32_sign, f32_exp, f32_frac, }; use crate::soft_f32::f32_sub; pub fn f32_add(a: u32, b: u32) -> u32 { let mut a_sign = f32_sign(a); let mut b_sign = f32_sign(b); let mut r_sign; if a_sign != b_sign { return f32_sub(a, b); } let mut a_exp = f32_exp(a); let mut b_exp = f32_exp(b); let mut r_exp; let mut a_frac = f32_frac(a); let mut b_frac = f32_frac(b); let mut r_frac; let diff_exp = a_exp - b_exp; if diff_exp == 0 { if a_exp == 0 { r_sign = a_sign; r_exp = a_exp; r_frac = a_frac + b_frac; return f32_pack_raw(r_sign, r_exp, r_frac); } if a_exp == 0xFF { if (a_frac | b_frac) != 0 { return f32_propagate_nan(a, b); } else { r_sign = a_sign; r_exp = a_exp; r_frac = a_frac + b_frac; return f32_pack_raw(r_sign, r_exp, r_frac); } } r_sign = a_sign; r_exp = a_exp; r_frac = 0x01000000 + a_frac + b_frac; if (r_frac & 0x01) == 0 && r_exp < 0xFE { return f32_pack_raw(r_sign, r_exp, r_frac >> 1); } r_frac <<= 6; } else { r_sign = a_sign; a_frac <<= 6; b_frac <<= 6; if diff_exp < 0 { if b_exp == 0xFF { if b_sign != 0 { return f32_propagate_nan(a, b); } else { return f32_pack_raw(r_sign, 0xFF, 0); } } r_exp = b_exp; if a_exp != 0 { a_frac += 0x20000000; } else { a_frac += a_frac; } a_frac = f32_shift_right_jam(a_frac, -diff_exp); } else { if a_exp == 0xFF { if a_sign != 0 { return f32_propagate_nan(a, b); } else { return f32_pack_raw(a_sign, a_exp, a_frac); } } r_exp = a_exp; if b_exp != 0 { b_frac += 0x20000000; } else { b_frac += b_frac; } b_frac = f32_shift_right_jam(b_frac, diff_exp); } r_frac = 0x20000000 + a_frac + b_frac; if r_frac < 0x40000000 { r_exp -= 1; r_frac <<= 1; } } f32_round_and_pack(r_sign, r_exp, r_frac) } #[cfg(test)] mod tests { #[test] fn test_f32_add() { assert_eq!(crate::soft_f32::f32_add(0x3DCCCCCD, 0x3E4CCCCD), 0x3E99999A); assert_eq!(crate::soft_f32::f32_add(0xBDCCCCCD, 0xBE4CCCCD), 0xBE99999A); assert_eq!(crate::soft_f32::f32_add(0x4640E400, 0x47849900), 0x479CB580); assert_eq!(crate::soft_f32::f32_add(0xC640E400, 0xC7849900), 0xC79CB580); assert_eq!(crate::soft_f32::f32_add(0x3B03126F, 0x3B03126F), 0x3B83126F); assert_eq!(crate::soft_f32::f32_add(0xBB03126F, 0xBB03126F), 0xBB83126F); assert_eq!(crate::soft_f32::f32_add(0xBDCCCCCD, 0x3E4CCCCD), 0x3DCCCCCD); assert_eq!(crate::soft_f32::f32_add(0x3DCCCCCD, 0xBE4CCCCD), 0xBDCCCCCD); } #[test]
}
fn test_f32_add_inf_nan() { assert_eq!(crate::soft_f32::f32_add(0x7F800000, 0x3F800000), 0x7F800000); assert_eq!(crate::soft_f32::f32_add(0xFF800000, 0x3F800000), 0xFF800000); assert_eq!(crate::soft_f32::f32_is_nan(crate::soft_f32::f32_add(0xFF800000, 0x7F800000)), true); assert_eq!(crate::soft_f32::f32_add(0x7F800000, 0x3F800000), 0x7F800000); assert_eq!(crate::soft_f32::f32_add(0xFF800000, 0x3F800000), 0xFF800000); assert_eq!(crate::soft_f32::f32_add(0xFFFFFFFF, 0x3F800000), 0xFFFFFFFF); assert_eq!(crate::soft_f32::f32_is_nan(crate::soft_f32::f32_add(0xFFFFFFFF, 0x3F800000)), true); assert_eq!(crate::soft_f32::f32_is_nan(crate::soft_f32::f32_add(0xFFFFFFFF, 0x7F800000)), true); assert_eq!(crate::soft_f32::f32_is_nan(crate::soft_f32::f32_add(0xFFFFFFFF, 0xFF800000)), true); assert_eq!(crate::soft_f32::f32_add(0x0, 0xBDCCCCCE), 0xBDCCCCCE); assert_eq!(crate::soft_f32::f32_add(0x0, 0x3DCCCCCE), 0x3DCCCCCE); assert_eq!(crate::soft_f32::f32_add(0x80000000, 0xBDCCCCCE), 0xBDCCCCCE); assert_eq!(crate::soft_f32::f32_add(0x0, 0x0), 0x0); assert_eq!(crate::soft_f32::f32_add(0x0, 0x80000000), 0x0); }
function_block-full_function
[ { "content": "pub fn f32_div(a: u32, b: u32) -> u32 {\n\n // Sign\n\n let mut a_sign = f32_sign(a);\n\n let mut b_sign = f32_sign(b);\n\n let mut r_sign = a_sign ^ b_sign;\n\n\n\n // Exp\n\n let mut a_exp = f32_exp(a);\n\n let mut b_exp = f32_exp(b);\n\n let mut r_exp;\n\n\n\n // Frac...
Rust
third_party/rust_crates/vendor/tokio-executor/src/park.rs
casey/fuchsia
2b965e9a1e8f2ea346db540f3611a5be16bb4d6b
use std::marker::PhantomData; use std::rc::Rc; use std::sync::Arc; use std::time::Duration; use crossbeam_utils::sync::{Parker, Unparker}; pub trait Park { type Unpark: Unpark; type Error; fn unpark(&self) -> Self::Unpark; fn park(&mut self) -> Result<(), Self::Error>; fn park_timeout(&mut self, duration: Duration) -> Result<(), Self::Error>; } pub trait Unpark: Sync + Send + 'static { fn unpark(&self); } impl Unpark for Box<dyn Unpark> { fn unpark(&self) { (**self).unpark() } } impl Unpark for Arc<dyn Unpark> { fn unpark(&self) { (**self).unpark() } } #[derive(Debug)] pub struct ParkThread { _anchor: PhantomData<Rc<()>>, } #[derive(Debug)] pub struct ParkError { _p: (), } #[derive(Clone, Debug)] pub struct UnparkThread { inner: Unparker, } thread_local! { static CURRENT_PARKER: Parker = Parker::new(); } impl ParkThread { pub fn new() -> ParkThread { ParkThread { _anchor: PhantomData, } } fn with_current<F, R>(&self, f: F) -> R where F: FnOnce(&Parker) -> R, { CURRENT_PARKER.with(|inner| f(inner)) } } impl Park for ParkThread { type Unpark = UnparkThread; type Error = ParkError; fn unpark(&self) -> Self::Unpark { let inner = self.with_current(|inner| inner.unparker().clone()); UnparkThread { inner } } fn park(&mut self) -> Result<(), Self::Error> { self.with_current(|inner| inner.park()); Ok(()) } fn park_timeout(&mut self, duration: Duration) -> Result<(), Self::Error> { self.with_current(|inner| inner.park_timeout(duration)); Ok(()) } } impl Unpark for UnparkThread { fn unpark(&self) { self.inner.unpark(); } }
use std::marker::PhantomData; use std::rc::Rc; use std::sync::Arc; use std::time::Duration; use crossbeam_utils::sync::{Parker, Unparker}; pub trait Park { type Unpark: Unpark; type Error; fn unpark(&self) -> Self::Unpark; fn park(&mut self) -> Result<(), Self::Error>; fn park_timeout(&mut self, duration: Duration) -> Result<(), Self::Error>; } pub trait Unpark: Sync + Send + 'static { fn unpark(&self); } impl Unpark for Box<dyn Unpark> { fn unpark(&self) { (**self).unpark() } } impl Unpark for Arc<dyn Unpark> { fn unpark(&self) { (**self).unpark() } } #[derive(Debug)] pub struct ParkThread { _anchor: PhantomData<Rc<()>>, } #[derive(Debug)] pub struct ParkError { _p: (), } #[derive(Clone, Debug)] pub struct UnparkThread { inner: Unparker, } thread_local! { static CURRENT_PARKER: Parker = Parker::new(); } impl ParkThread { pub fn new() -> ParkThread { ParkThread { _anchor: PhantomData, } }
} impl Park for ParkThread { type Unpark = UnparkThread; type Error = ParkError; fn unpark(&self) -> Self::Unpark { let inner = self.with_current(|inner| inner.unparker().clone()); UnparkThread { inner } } fn park(&mut self) -> Result<(), Self::Error> { self.with_current(|inner| inner.park()); Ok(()) } fn park_timeout(&mut self, duration: Duration) -> Result<(), Self::Error> { self.with_current(|inner| inner.park_timeout(duration)); Ok(()) } } impl Unpark for UnparkThread { fn unpark(&self) { self.inner.unpark(); } }
fn with_current<F, R>(&self, f: F) -> R where F: FnOnce(&Parker) -> R, { CURRENT_PARKER.with(|inner| f(inner)) }
function_block-function_prefix_line
[]
Rust
src/db.rs
lovesh/merkle_trees
0db6b68bbfb219d584a96d503e2d6e4e4c7147a6
use crate::errors::{MerkleTreeError, MerkleTreeErrorKind}; use num_bigint::BigUint; use std::collections::HashMap; use std::iter::FromIterator; pub trait HashValueDb<H, V: Clone> { fn put(&mut self, hash: H, value: V) -> Result<(), MerkleTreeError>; fn get(&self, hash: &H) -> Result<V, MerkleTreeError>; } #[derive(Clone, Debug)] pub struct InMemoryHashValueDb<V: Clone> { db: HashMap<Vec<u8>, V>, } impl<V: Clone> HashValueDb<Vec<u8>, V> for InMemoryHashValueDb<V> { fn put(&mut self, hash: Vec<u8>, value: V) -> Result<(), MerkleTreeError> { self.db.insert(hash, value); Ok(()) } fn get(&self, hash: &Vec<u8>) -> Result<V, MerkleTreeError> { match self.db.get(hash) { Some(val) => Ok(val.clone()), None => Err(MerkleTreeErrorKind::HashNotFoundInDB { hash: hash.to_vec(), } .into()), } } } impl<T: Clone> InMemoryHashValueDb<T> { pub fn new() -> Self { let db = HashMap::<Vec<u8>, T>::new(); Self { db } } } #[derive(Clone, Debug)] pub struct InMemoryBigUintHashDb<V: Clone> { db: HashMap<Vec<u8>, V>, } impl<V: Clone> HashValueDb<BigUint, V> for InMemoryBigUintHashDb<V> { fn put(&mut self, hash: BigUint, value: V) -> Result<(), MerkleTreeError> { self.db.insert(hash.to_bytes_be(), value); Ok(()) } fn get(&self, hash: &BigUint) -> Result<V, MerkleTreeError> { let b = hash.to_bytes_be(); match self.db.get(&b) { Some(val) => Ok(val.clone()), None => Err(MerkleTreeErrorKind::HashNotFoundInDB { hash: b }.into()), } } } impl<T: Clone> InMemoryBigUintHashDb<T> { pub fn new() -> Self { let db = HashMap::<Vec<u8>, T>::new(); Self { db } } } #[cfg(test)] pub mod unqlite_db { use super::{HashValueDb, MerkleTreeError, MerkleTreeErrorKind}; extern crate unqlite; use unqlite::{Config, Cursor, UnQLite, KV}; pub struct UnqliteHashValueDb { db_name: String, db: UnQLite, } impl UnqliteHashValueDb { pub fn new(db_name: String) -> Self { let db = UnQLite::create(&db_name); Self { db_name, db } } } impl HashValueDb<Vec<u8>, Vec<u8>> for UnqliteHashValueDb { fn put(&mut self, hash: Vec<u8>, value: Vec<u8>) -> Result<(), MerkleTreeError> { self.db.kv_store(&hash, &value).unwrap(); Ok(()) } fn get(&self, hash: &Vec<u8>) -> Result<Vec<u8>, MerkleTreeError> { self.db.kv_fetch(hash).map_err(|_| { MerkleTreeError::from_kind(MerkleTreeErrorKind::HashNotFoundInDB { hash: hash.to_vec(), }) }) } } } #[cfg(test)] pub mod rusqlite_db { use super::{HashValueDb, MerkleTreeError, MerkleTreeErrorKind}; extern crate rusqlite; use rusqlite::{params, Connection, NO_PARAMS}; pub struct RusqliteHashValueDb { db_path: String, pub table_name: String, pub db_conn: Connection, } impl RusqliteHashValueDb { pub fn new(db_path: String, table_name: String) -> Self { let db_conn = Connection::open(&db_path).unwrap(); let sql = format!( "create table if not exists {} (key string primary key, value blob not null)", table_name ); db_conn.execute(&sql, NO_PARAMS).unwrap(); Self { db_path, table_name, db_conn, } } pub fn hash_to_hex(hash: &Vec<u8>) -> String { format!("{:x?}", hash) .replace(", ", "") .replace("[", "") .replace("]", "") } } impl HashValueDb<Vec<u8>, Vec<u8>> for RusqliteHashValueDb { fn put(&mut self, hash: Vec<u8>, value: Vec<u8>) -> Result<(), MerkleTreeError> { let hash_hex = Self::hash_to_hex(&hash); let sql = format!( "insert into {} (key, value) values (?1, ?2)", self.table_name ); self.db_conn .execute(&sql, params![hash_hex, value]) .unwrap(); Ok(()) } fn get(&self, hash: &Vec<u8>) -> Result<Vec<u8>, MerkleTreeError> { let sql = format!( "select value from {} where key='{}'", self.table_name, Self::hash_to_hex(hash) ); self.db_conn .query_row(&sql, NO_PARAMS, |row| row.get(0)) .map_err(|_| { MerkleTreeError::from_kind(MerkleTreeErrorKind::HashNotFoundInDB { hash: hash.to_vec(), }) }) } } } #[cfg(test)] pub mod sled_db { use super::{HashValueDb, MerkleTreeError, MerkleTreeErrorKind}; extern crate sled; use self::sled::{Config, Db}; use crate::sha2::{Digest, Sha256}; use std::marker::PhantomData; pub struct SledHashDb { config: Config, db: Db, } impl SledHashDb { pub fn new() -> Self { let config = Config::new().temporary(true); let db = config.open().unwrap(); Self { config, db } } } impl HashValueDb<Vec<u8>, Vec<u8>> for SledHashDb { fn put(&mut self, hash: Vec<u8>, value: Vec<u8>) -> Result<(), MerkleTreeError> { self.db.insert(hash, value); Ok(()) } fn get(&self, hash: &Vec<u8>) -> Result<Vec<u8>, MerkleTreeError> { match self.db.get(hash) { Ok(Some(ivec)) => Ok(ivec.to_vec()), _ => Err(MerkleTreeErrorKind::HashNotFoundInDB { hash: hash.to_vec(), } .into()), } } } } #[cfg(test)] mod tests { use super::*; use crate::sha2::{Digest, Sha256}; use std::fs; fn check_db_put_get(db: &mut HashValueDb<Vec<u8>, Vec<u8>>) { let data_1 = "Hello world!".as_bytes().to_vec(); let mut hasher = Sha256::new(); hasher.input(&data_1); let hash_1 = hasher.result().to_vec(); db.put(hash_1.clone(), data_1.clone()).unwrap(); assert_eq!(db.get(&hash_1).unwrap(), data_1); let data_2 = "Byte!".as_bytes().to_vec(); let mut hasher = Sha256::new(); hasher.input(&data_2); let hash_2 = hasher.result().to_vec(); assert!(db.get(&hash_2).is_err()); db.put(hash_2.clone(), data_2.clone()).unwrap(); assert_eq!(db.get(&hash_2).unwrap(), data_2); } #[test] fn test_in_memory_db_string_val() { let mut db = InMemoryHashValueDb::<String>::new(); let data_1 = String::from("Hello world!"); let mut hasher = Sha256::new(); hasher.input(data_1.as_bytes()); let hash_1 = hasher.result().to_vec(); db.put(hash_1.clone(), data_1.clone()).unwrap(); assert_eq!(db.get(&hash_1).unwrap(), data_1); let data_2 = String::from("Byte!"); let mut hasher = Sha256::new(); hasher.input(data_2.as_bytes()); let hash_2 = hasher.result().to_vec(); assert!(db.get(&hash_2).is_err()); db.put(hash_2.clone(), data_2.clone()).unwrap(); assert_eq!(db.get(&hash_2).unwrap(), data_2); } #[test] fn test_unqlite_db_string_val() { let db_name = "unqlite_test.db"; fs::remove_file(db_name); let mut db = unqlite_db::UnqliteHashValueDb::new(String::from(db_name)); check_db_put_get(&mut db); } #[test] fn test_rusqlite_db_string_val() { let db_path = "./rusqlite_test.db"; fs::remove_file(db_path); let mut db = rusqlite_db::RusqliteHashValueDb::new(String::from(db_path), String::from("kv_table")); check_db_put_get(&mut db); } #[test] fn test_sled_db_string_val() { let mut db = sled_db::SledHashDb::new(); check_db_put_get(&mut db); } }
use crate::errors::{MerkleTreeError, MerkleTreeErrorKind}; use num_bigint::BigUint; use std::collections::HashMap; use std::iter::FromIterator; pub trait HashValueDb<H, V: Clone> { fn put(&mut self, hash: H, value: V) -> Result<(), MerkleTreeError>; fn get(&self, hash: &H) -> Result<V, MerkleTreeError>; } #[derive(Clone, Debug)] pub struct InMemoryHashValueDb<V: Clone> { db: HashMap<Vec<u8>, V>, } impl<V: Clone> HashValueDb<Vec<u8>, V> for InMemoryHashValueDb<V> { fn put(&mut self, hash: Vec<u8>, value: V) -> Result<(), MerkleTreeError> { self.db.insert(hash, value); Ok(()) } fn get(&self, hash: &Vec<u8>) -> Result<V, MerkleTreeError> { match self.db.get(hash) { Some(val) => Ok(val.clone()), None => Err(MerkleTreeErrorKind::HashNotFoundInDB { hash: hash.to_vec(), } .into()), } } } impl<T: Clone> InMemoryHashValueDb<T> { pub fn new() -> Self { let db = HashMap::<Vec<u8>, T>::new(); Self { db } } } #[derive(Clone, Debug)] pub struct InMemoryBigUintHashDb<V: Clone> { db: HashMap<Vec<u8>, V>, } impl<V: Clone> HashValueDb<BigUint, V> for InMemoryBigUintHashDb<V> { fn put(&mut self, hash: BigUint, value: V) -> Result<(), MerkleTreeError> { self.db.insert(hash.to_bytes_be(), value); Ok(()) }
} impl<T: Clone> InMemoryBigUintHashDb<T> { pub fn new() -> Self { let db = HashMap::<Vec<u8>, T>::new(); Self { db } } } #[cfg(test)] pub mod unqlite_db { use super::{HashValueDb, MerkleTreeError, MerkleTreeErrorKind}; extern crate unqlite; use unqlite::{Config, Cursor, UnQLite, KV}; pub struct UnqliteHashValueDb { db_name: String, db: UnQLite, } impl UnqliteHashValueDb { pub fn new(db_name: String) -> Self { let db = UnQLite::create(&db_name); Self { db_name, db } } } impl HashValueDb<Vec<u8>, Vec<u8>> for UnqliteHashValueDb { fn put(&mut self, hash: Vec<u8>, value: Vec<u8>) -> Result<(), MerkleTreeError> { self.db.kv_store(&hash, &value).unwrap(); Ok(()) } fn get(&self, hash: &Vec<u8>) -> Result<Vec<u8>, MerkleTreeError> { self.db.kv_fetch(hash).map_err(|_| { MerkleTreeError::from_kind(MerkleTreeErrorKind::HashNotFoundInDB { hash: hash.to_vec(), }) }) } } } #[cfg(test)] pub mod rusqlite_db { use super::{HashValueDb, MerkleTreeError, MerkleTreeErrorKind}; extern crate rusqlite; use rusqlite::{params, Connection, NO_PARAMS}; pub struct RusqliteHashValueDb { db_path: String, pub table_name: String, pub db_conn: Connection, } impl RusqliteHashValueDb { pub fn new(db_path: String, table_name: String) -> Self { let db_conn = Connection::open(&db_path).unwrap(); let sql = format!( "create table if not exists {} (key string primary key, value blob not null)", table_name ); db_conn.execute(&sql, NO_PARAMS).unwrap(); Self { db_path, table_name, db_conn, } } pub fn hash_to_hex(hash: &Vec<u8>) -> String { format!("{:x?}", hash) .replace(", ", "") .replace("[", "") .replace("]", "") } } impl HashValueDb<Vec<u8>, Vec<u8>> for RusqliteHashValueDb { fn put(&mut self, hash: Vec<u8>, value: Vec<u8>) -> Result<(), MerkleTreeError> { let hash_hex = Self::hash_to_hex(&hash); let sql = format!( "insert into {} (key, value) values (?1, ?2)", self.table_name ); self.db_conn .execute(&sql, params![hash_hex, value]) .unwrap(); Ok(()) } fn get(&self, hash: &Vec<u8>) -> Result<Vec<u8>, MerkleTreeError> { let sql = format!( "select value from {} where key='{}'", self.table_name, Self::hash_to_hex(hash) ); self.db_conn .query_row(&sql, NO_PARAMS, |row| row.get(0)) .map_err(|_| { MerkleTreeError::from_kind(MerkleTreeErrorKind::HashNotFoundInDB { hash: hash.to_vec(), }) }) } } } #[cfg(test)] pub mod sled_db { use super::{HashValueDb, MerkleTreeError, MerkleTreeErrorKind}; extern crate sled; use self::sled::{Config, Db}; use crate::sha2::{Digest, Sha256}; use std::marker::PhantomData; pub struct SledHashDb { config: Config, db: Db, } impl SledHashDb { pub fn new() -> Self { let config = Config::new().temporary(true); let db = config.open().unwrap(); Self { config, db } } } impl HashValueDb<Vec<u8>, Vec<u8>> for SledHashDb { fn put(&mut self, hash: Vec<u8>, value: Vec<u8>) -> Result<(), MerkleTreeError> { self.db.insert(hash, value); Ok(()) } fn get(&self, hash: &Vec<u8>) -> Result<Vec<u8>, MerkleTreeError> { match self.db.get(hash) { Ok(Some(ivec)) => Ok(ivec.to_vec()), _ => Err(MerkleTreeErrorKind::HashNotFoundInDB { hash: hash.to_vec(), } .into()), } } } } #[cfg(test)] mod tests { use super::*; use crate::sha2::{Digest, Sha256}; use std::fs; fn check_db_put_get(db: &mut HashValueDb<Vec<u8>, Vec<u8>>) { let data_1 = "Hello world!".as_bytes().to_vec(); let mut hasher = Sha256::new(); hasher.input(&data_1); let hash_1 = hasher.result().to_vec(); db.put(hash_1.clone(), data_1.clone()).unwrap(); assert_eq!(db.get(&hash_1).unwrap(), data_1); let data_2 = "Byte!".as_bytes().to_vec(); let mut hasher = Sha256::new(); hasher.input(&data_2); let hash_2 = hasher.result().to_vec(); assert!(db.get(&hash_2).is_err()); db.put(hash_2.clone(), data_2.clone()).unwrap(); assert_eq!(db.get(&hash_2).unwrap(), data_2); } #[test] fn test_in_memory_db_string_val() { let mut db = InMemoryHashValueDb::<String>::new(); let data_1 = String::from("Hello world!"); let mut hasher = Sha256::new(); hasher.input(data_1.as_bytes()); let hash_1 = hasher.result().to_vec(); db.put(hash_1.clone(), data_1.clone()).unwrap(); assert_eq!(db.get(&hash_1).unwrap(), data_1); let data_2 = String::from("Byte!"); let mut hasher = Sha256::new(); hasher.input(data_2.as_bytes()); let hash_2 = hasher.result().to_vec(); assert!(db.get(&hash_2).is_err()); db.put(hash_2.clone(), data_2.clone()).unwrap(); assert_eq!(db.get(&hash_2).unwrap(), data_2); } #[test] fn test_unqlite_db_string_val() { let db_name = "unqlite_test.db"; fs::remove_file(db_name); let mut db = unqlite_db::UnqliteHashValueDb::new(String::from(db_name)); check_db_put_get(&mut db); } #[test] fn test_rusqlite_db_string_val() { let db_path = "./rusqlite_test.db"; fs::remove_file(db_path); let mut db = rusqlite_db::RusqliteHashValueDb::new(String::from(db_path), String::from("kv_table")); check_db_put_get(&mut db); } #[test] fn test_sled_db_string_val() { let mut db = sled_db::SledHashDb::new(); check_db_put_get(&mut db); } }
fn get(&self, hash: &BigUint) -> Result<V, MerkleTreeError> { let b = hash.to_bytes_be(); match self.db.get(&b) { Some(val) => Ok(val.clone()), None => Err(MerkleTreeErrorKind::HashNotFoundInDB { hash: b }.into()), } }
function_block-full_function
[ { "content": "/// Interface for the database used to store the leaf and node hashes\n\npub trait HashDb<H> {\n\n /// The database stores all leaves\n\n fn add_leaf(&mut self, leaf_hash: H) -> Result<(), MerkleTreeError>;\n\n\n\n /// The database stores roots of all full subtrees of the datbase\n\n f...
Rust
crates/volta-core/src/tool/node/resolve.rs
gregjopa/volta
18f6b061d9fe5205010291f586518b93533a2f6f
use std::fs::File; use std::io::Write; use std::str::FromStr; use std::time::{Duration, SystemTime}; use super::super::registry_fetch_error; use super::metadata::{NodeEntry, NodeIndex, RawNodeIndex}; use crate::error::{Context, ErrorKind, Fallible}; use crate::fs::{create_staging_file, read_file}; use crate::hook::ToolHooks; use crate::layout::volta_home; use crate::session::Session; use crate::style::progress_spinner; use crate::tool::Node; use crate::version::{VersionSpec, VersionTag}; use attohttpc::Response; use cfg_if::cfg_if; use fs_utils::ensure_containing_dir_exists; use hyperx::header::{CacheControl, CacheDirective, Expires, HttpDate, TypedHeaders}; use log::debug; use semver::{Version, VersionReq}; cfg_if! { if #[cfg(feature = "mock-network")] { fn public_node_version_index() -> String { format!("{}/node-dist/index.json", mockito::SERVER_URL) } } else { fn public_node_version_index() -> String { "https://nodejs.org/dist/index.json".to_string() } } } pub fn resolve(matching: VersionSpec, session: &mut Session) -> Fallible<Version> { let hooks = session.hooks()?.node(); match matching { VersionSpec::Semver(requirement) => resolve_semver(requirement, hooks), VersionSpec::Exact(version) => Ok(version), VersionSpec::None | VersionSpec::Tag(VersionTag::Lts) => resolve_lts(hooks), VersionSpec::Tag(VersionTag::Latest) => resolve_latest(hooks), VersionSpec::Tag(VersionTag::LtsRequirement(req)) => resolve_lts_semver(req, hooks), VersionSpec::Tag(VersionTag::Custom(tag)) => { Err(ErrorKind::NodeVersionNotFound { matching: tag }.into()) } } } fn resolve_latest(hooks: Option<&ToolHooks<Node>>) -> Fallible<Version> { let url = match hooks { Some(&ToolHooks { latest: Some(ref hook), .. }) => { debug!("Using node.latest hook to determine node index URL"); hook.resolve("index.json")? } _ => public_node_version_index(), }; let version_opt = match_node_version(&url, |_| true)?; match version_opt { Some(version) => { debug!("Found latest node version ({}) from {}", version, url); Ok(version) } None => Err(ErrorKind::NodeVersionNotFound { matching: "latest".into(), } .into()), } } fn resolve_lts(hooks: Option<&ToolHooks<Node>>) -> Fallible<Version> { let url = match hooks { Some(&ToolHooks { index: Some(ref hook), .. }) => { debug!("Using node.index hook to determine node index URL"); hook.resolve("index.json")? } _ => public_node_version_index(), }; let version_opt = match_node_version(&url, |&NodeEntry { lts, .. }| lts)?; match version_opt { Some(version) => { debug!("Found newest LTS node version ({}) from {}", version, url); Ok(version) } None => Err(ErrorKind::NodeVersionNotFound { matching: "lts".into(), } .into()), } } fn resolve_semver(matching: VersionReq, hooks: Option<&ToolHooks<Node>>) -> Fallible<Version> { let url = match hooks { Some(&ToolHooks { index: Some(ref hook), .. }) => { debug!("Using node.index hook to determine node index URL"); hook.resolve("index.json")? } _ => public_node_version_index(), }; let version_opt = match_node_version(&url, |NodeEntry { version, .. }| matching.matches(version))?; match version_opt { Some(version) => { debug!( "Found node@{} matching requirement '{}' from {}", version, matching, url ); Ok(version) } None => Err(ErrorKind::NodeVersionNotFound { matching: matching.to_string(), } .into()), } } fn resolve_lts_semver(matching: VersionReq, hooks: Option<&ToolHooks<Node>>) -> Fallible<Version> { let url = match hooks { Some(&ToolHooks { index: Some(ref hook), .. }) => { debug!("Using node.index hook to determine node index URL"); hook.resolve("index.json")? } _ => public_node_version_index(), }; let first_pass = match_node_version( &url, |&NodeEntry { ref version, lts, .. }| { lts && matching.matches(version) }, )?; match first_pass { Some(version) => { debug!( "Found LTS node@{} matching requirement '{}' from {}", version, matching, url ); return Ok(version); } None => debug!( "No LTS version found matching requirement '{}', checking for non-LTS", matching ), }; match match_node_version(&url, |NodeEntry { version, .. }| matching.matches(version))? { Some(version) => { debug!( "Found non-LTS node@{} matching requirement '{}' from {}", version, matching, url ); Ok(version) } None => Err(ErrorKind::NodeVersionNotFound { matching: matching.to_string(), } .into()), } } fn match_node_version( url: &str, predicate: impl Fn(&NodeEntry) -> bool, ) -> Fallible<Option<Version>> { let index: NodeIndex = resolve_node_versions(url)?.into(); let mut entries = index.entries.into_iter(); Ok(entries .find(predicate) .map(|NodeEntry { version, .. }| version)) } fn read_cached_opt(url: &str) -> Fallible<Option<RawNodeIndex>> { let expiry_file = volta_home()?.node_index_expiry_file(); let expiry = read_file(&expiry_file).with_context(|| ErrorKind::ReadNodeIndexExpiryError { file: expiry_file.to_owned(), })?; if let Some(date) = expiry { let expiry_date = HttpDate::from_str(&date).with_context(|| ErrorKind::ParseNodeIndexExpiryError)?; let current_date = HttpDate::from(SystemTime::now()); if current_date < expiry_date { let index_file = volta_home()?.node_index_file(); let cached = read_file(&index_file).with_context(|| ErrorKind::ReadNodeIndexCacheError { file: index_file.to_owned(), })?; if let Some(content) = cached { if content.starts_with(url) { return serde_json::de::from_str(&content[url.len()..]) .with_context(|| ErrorKind::ParseNodeIndexCacheError); } } } } Ok(None) } fn max_age(headers: &attohttpc::header::HeaderMap) -> u32 { if let Ok(cache_control_header) = headers.decode::<CacheControl>() { for cache_directive in cache_control_header.iter() { if let CacheDirective::MaxAge(max_age) = cache_directive { return *max_age; } } } 4 * 60 * 60 } fn resolve_node_versions(url: &str) -> Fallible<RawNodeIndex> { match read_cached_opt(url)? { Some(serial) => { debug!("Found valid cache of Node version index"); Ok(serial) } None => { debug!("Node index cache was not found or was invalid"); let spinner = progress_spinner(&format!("Fetching public registry: {}", url)); let (_, headers, response) = attohttpc::get(url) .send() .and_then(Response::error_for_status) .with_context(registry_fetch_error("Node", url))? .split(); let response_text = response .text() .with_context(registry_fetch_error("Node", url))?; let index: RawNodeIndex = serde_json::de::from_str(&response_text).with_context(|| { ErrorKind::ParseNodeIndexError { from_url: url.to_string(), } })?; let cached = create_staging_file()?; let mut cached_file: &File = cached.as_file(); writeln!(cached_file, "{}", url) .and_then(|_| cached_file.write(response_text.as_bytes())) .with_context(|| ErrorKind::WriteNodeIndexCacheError { file: cached.path().to_path_buf(), })?; let index_cache_file = volta_home()?.node_index_file(); ensure_containing_dir_exists(&index_cache_file).with_context(|| { ErrorKind::ContainingDirError { path: index_cache_file.to_owned(), } })?; cached.persist(&index_cache_file).with_context(|| { ErrorKind::WriteNodeIndexCacheError { file: index_cache_file.to_owned(), } })?; let expiry = create_staging_file()?; let mut expiry_file: &File = expiry.as_file(); let result = if let Ok(expires_header) = headers.decode::<Expires>() { write!(expiry_file, "{}", expires_header) } else { let expiry_date = SystemTime::now() + Duration::from_secs(max_age(&headers).into()); write!(expiry_file, "{}", HttpDate::from(expiry_date)) }; result.with_context(|| ErrorKind::WriteNodeIndexExpiryError { file: expiry.path().to_path_buf(), })?; let index_expiry_file = volta_home()?.node_index_expiry_file(); ensure_containing_dir_exists(&index_expiry_file).with_context(|| { ErrorKind::ContainingDirError { path: index_expiry_file.to_owned(), } })?; expiry.persist(&index_expiry_file).with_context(|| { ErrorKind::WriteNodeIndexExpiryError { file: index_expiry_file.to_owned(), } })?; spinner.finish_and_clear(); Ok(index) } } }
use std::fs::File; use std::io::Write; use std::str::FromStr; use std::time::{Duration, SystemTime}; use super::super::registry_fetch_error; use super::metadata::{NodeEntry, NodeIndex, RawNodeIndex}; use crate::error::{Context, ErrorKind, Fallible}; use crate::fs::{create_staging_file, read_file}; use crate::hook::ToolHooks; use crate::layout::volta_home; use crate::session::Session; use crate::style::progress_spinner; use crate::tool::Node; use crate::version::{VersionSpec, VersionTag}; use attohttpc::Response; use cfg_if::cfg_if; use fs_utils::ensure_containing_dir_exists; use hyperx::header::{CacheControl, CacheDirective, Expires, HttpDate, TypedHeaders}; use log::debug; use semver::{Version, VersionReq}; cfg_if! { if #[cfg(feature = "mock-network")] { fn public_node_version_index() -> String { format!("{}/node-dist/index.json", mockit
let index: NodeIndex = resolve_node_versions(url)?.into(); let mut entries = index.entries.into_iter(); Ok(entries .find(predicate) .map(|NodeEntry { version, .. }| version)) } fn read_cached_opt(url: &str) -> Fallible<Option<RawNodeIndex>> { let expiry_file = volta_home()?.node_index_expiry_file(); let expiry = read_file(&expiry_file).with_context(|| ErrorKind::ReadNodeIndexExpiryError { file: expiry_file.to_owned(), })?; if let Some(date) = expiry { let expiry_date = HttpDate::from_str(&date).with_context(|| ErrorKind::ParseNodeIndexExpiryError)?; let current_date = HttpDate::from(SystemTime::now()); if current_date < expiry_date { let index_file = volta_home()?.node_index_file(); let cached = read_file(&index_file).with_context(|| ErrorKind::ReadNodeIndexCacheError { file: index_file.to_owned(), })?; if let Some(content) = cached { if content.starts_with(url) { return serde_json::de::from_str(&content[url.len()..]) .with_context(|| ErrorKind::ParseNodeIndexCacheError); } } } } Ok(None) } fn max_age(headers: &attohttpc::header::HeaderMap) -> u32 { if let Ok(cache_control_header) = headers.decode::<CacheControl>() { for cache_directive in cache_control_header.iter() { if let CacheDirective::MaxAge(max_age) = cache_directive { return *max_age; } } } 4 * 60 * 60 } fn resolve_node_versions(url: &str) -> Fallible<RawNodeIndex> { match read_cached_opt(url)? { Some(serial) => { debug!("Found valid cache of Node version index"); Ok(serial) } None => { debug!("Node index cache was not found or was invalid"); let spinner = progress_spinner(&format!("Fetching public registry: {}", url)); let (_, headers, response) = attohttpc::get(url) .send() .and_then(Response::error_for_status) .with_context(registry_fetch_error("Node", url))? .split(); let response_text = response .text() .with_context(registry_fetch_error("Node", url))?; let index: RawNodeIndex = serde_json::de::from_str(&response_text).with_context(|| { ErrorKind::ParseNodeIndexError { from_url: url.to_string(), } })?; let cached = create_staging_file()?; let mut cached_file: &File = cached.as_file(); writeln!(cached_file, "{}", url) .and_then(|_| cached_file.write(response_text.as_bytes())) .with_context(|| ErrorKind::WriteNodeIndexCacheError { file: cached.path().to_path_buf(), })?; let index_cache_file = volta_home()?.node_index_file(); ensure_containing_dir_exists(&index_cache_file).with_context(|| { ErrorKind::ContainingDirError { path: index_cache_file.to_owned(), } })?; cached.persist(&index_cache_file).with_context(|| { ErrorKind::WriteNodeIndexCacheError { file: index_cache_file.to_owned(), } })?; let expiry = create_staging_file()?; let mut expiry_file: &File = expiry.as_file(); let result = if let Ok(expires_header) = headers.decode::<Expires>() { write!(expiry_file, "{}", expires_header) } else { let expiry_date = SystemTime::now() + Duration::from_secs(max_age(&headers).into()); write!(expiry_file, "{}", HttpDate::from(expiry_date)) }; result.with_context(|| ErrorKind::WriteNodeIndexExpiryError { file: expiry.path().to_path_buf(), })?; let index_expiry_file = volta_home()?.node_index_expiry_file(); ensure_containing_dir_exists(&index_expiry_file).with_context(|| { ErrorKind::ContainingDirError { path: index_expiry_file.to_owned(), } })?; expiry.persist(&index_expiry_file).with_context(|| { ErrorKind::WriteNodeIndexExpiryError { file: index_expiry_file.to_owned(), } })?; spinner.finish_and_clear(); Ok(index) } } }
o::SERVER_URL) } } else { fn public_node_version_index() -> String { "https://nodejs.org/dist/index.json".to_string() } } } pub fn resolve(matching: VersionSpec, session: &mut Session) -> Fallible<Version> { let hooks = session.hooks()?.node(); match matching { VersionSpec::Semver(requirement) => resolve_semver(requirement, hooks), VersionSpec::Exact(version) => Ok(version), VersionSpec::None | VersionSpec::Tag(VersionTag::Lts) => resolve_lts(hooks), VersionSpec::Tag(VersionTag::Latest) => resolve_latest(hooks), VersionSpec::Tag(VersionTag::LtsRequirement(req)) => resolve_lts_semver(req, hooks), VersionSpec::Tag(VersionTag::Custom(tag)) => { Err(ErrorKind::NodeVersionNotFound { matching: tag }.into()) } } } fn resolve_latest(hooks: Option<&ToolHooks<Node>>) -> Fallible<Version> { let url = match hooks { Some(&ToolHooks { latest: Some(ref hook), .. }) => { debug!("Using node.latest hook to determine node index URL"); hook.resolve("index.json")? } _ => public_node_version_index(), }; let version_opt = match_node_version(&url, |_| true)?; match version_opt { Some(version) => { debug!("Found latest node version ({}) from {}", version, url); Ok(version) } None => Err(ErrorKind::NodeVersionNotFound { matching: "latest".into(), } .into()), } } fn resolve_lts(hooks: Option<&ToolHooks<Node>>) -> Fallible<Version> { let url = match hooks { Some(&ToolHooks { index: Some(ref hook), .. }) => { debug!("Using node.index hook to determine node index URL"); hook.resolve("index.json")? } _ => public_node_version_index(), }; let version_opt = match_node_version(&url, |&NodeEntry { lts, .. }| lts)?; match version_opt { Some(version) => { debug!("Found newest LTS node version ({}) from {}", version, url); Ok(version) } None => Err(ErrorKind::NodeVersionNotFound { matching: "lts".into(), } .into()), } } fn resolve_semver(matching: VersionReq, hooks: Option<&ToolHooks<Node>>) -> Fallible<Version> { let url = match hooks { Some(&ToolHooks { index: Some(ref hook), .. }) => { debug!("Using node.index hook to determine node index URL"); hook.resolve("index.json")? } _ => public_node_version_index(), }; let version_opt = match_node_version(&url, |NodeEntry { version, .. }| matching.matches(version))?; match version_opt { Some(version) => { debug!( "Found node@{} matching requirement '{}' from {}", version, matching, url ); Ok(version) } None => Err(ErrorKind::NodeVersionNotFound { matching: matching.to_string(), } .into()), } } fn resolve_lts_semver(matching: VersionReq, hooks: Option<&ToolHooks<Node>>) -> Fallible<Version> { let url = match hooks { Some(&ToolHooks { index: Some(ref hook), .. }) => { debug!("Using node.index hook to determine node index URL"); hook.resolve("index.json")? } _ => public_node_version_index(), }; let first_pass = match_node_version( &url, |&NodeEntry { ref version, lts, .. }| { lts && matching.matches(version) }, )?; match first_pass { Some(version) => { debug!( "Found LTS node@{} matching requirement '{}' from {}", version, matching, url ); return Ok(version); } None => debug!( "No LTS version found matching requirement '{}', checking for non-LTS", matching ), }; match match_node_version(&url, |NodeEntry { version, .. }| matching.matches(version))? { Some(version) => { debug!( "Found non-LTS node@{} matching requirement '{}' from {}", version, matching, url ); Ok(version) } None => Err(ErrorKind::NodeVersionNotFound { matching: matching.to_string(), } .into()), } } fn match_node_version( url: &str, predicate: impl Fn(&NodeEntry) -> bool, ) -> Fallible<Option<Version>> {
random
[ { "content": "fn resolve_semver_legacy(matching: VersionReq, url: String) -> Fallible<Version> {\n\n let spinner = progress_spinner(&format!(\"Fetching public registry: {}\", url));\n\n let releases: RawYarnIndex = attohttpc::get(&url)\n\n .send()\n\n .and_then(Response::error_for_status)\n\...
Rust
ethers-solc/src/hh.rs
alxiong/ethers-rs
133c32d64a53a8ae38e0c8c8a10753e423127782
use crate::{ artifacts::{ Bytecode, BytecodeObject, CompactContract, CompactContractBytecode, Contract, ContractBytecode, DeployedBytecode, LosslessAbi, Offsets, }, ArtifactOutput, }; use serde::{Deserialize, Serialize}; use std::collections::btree_map::BTreeMap; const HH_ARTIFACT_VERSION: &str = "hh-sol-artifact-1"; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct HardhatArtifact { #[serde(rename = "_format")] pub format: String, pub contract_name: String, pub source_name: String, pub abi: LosslessAbi, pub bytecode: Option<BytecodeObject>, pub deployed_bytecode: Option<BytecodeObject>, #[serde(default)] pub link_references: BTreeMap<String, BTreeMap<String, Vec<Offsets>>>, #[serde(default)] pub deployed_link_references: BTreeMap<String, BTreeMap<String, Vec<Offsets>>>, } impl From<HardhatArtifact> for CompactContract { fn from(artifact: HardhatArtifact) -> Self { CompactContract { abi: Some(artifact.abi.abi), bin: artifact.bytecode, bin_runtime: artifact.deployed_bytecode, } } } impl From<HardhatArtifact> for ContractBytecode { fn from(artifact: HardhatArtifact) -> Self { let bytecode: Option<Bytecode> = artifact.bytecode.as_ref().map(|t| { let mut bcode: Bytecode = t.clone().into(); bcode.link_references = artifact.link_references.clone(); bcode }); let deployed_bytecode: Option<DeployedBytecode> = artifact.bytecode.as_ref().map(|t| { let mut bcode: Bytecode = t.clone().into(); bcode.link_references = artifact.deployed_link_references.clone(); bcode.into() }); ContractBytecode { abi: Some(artifact.abi.abi), bytecode, deployed_bytecode } } } impl From<HardhatArtifact> for CompactContractBytecode { fn from(artifact: HardhatArtifact) -> Self { let c: ContractBytecode = artifact.into(); c.into() } } #[derive(Debug, Copy, Clone, Eq, PartialEq, Default)] pub struct HardhatArtifacts { _priv: (), } impl ArtifactOutput for HardhatArtifacts { type Artifact = HardhatArtifact; fn contract_to_artifact(&self, file: &str, name: &str, contract: Contract) -> Self::Artifact { let (bytecode, link_references, deployed_bytecode, deployed_link_references) = if let Some(evm) = contract.evm { let (deployed_bytecode, deployed_link_references) = if let Some(code) = evm.deployed_bytecode.and_then(|code| code.bytecode) { (Some(code.object), code.link_references) } else { (None, Default::default()) }; let (bytecode, link_ref) = if let Some(bc) = evm.bytecode { (Some(bc.object), bc.link_references) } else { (None, Default::default()) }; (bytecode, link_ref, deployed_bytecode, deployed_link_references) } else { (Default::default(), Default::default(), None, Default::default()) }; HardhatArtifact { format: HH_ARTIFACT_VERSION.to_string(), contract_name: name.to_string(), source_name: file.to_string(), abi: contract.abi.unwrap_or_default(), bytecode, deployed_bytecode, link_references, deployed_link_references, } } } #[cfg(test)] mod tests { use super::*; use crate::Artifact; #[test] fn can_parse_hh_artifact() { let s = include_str!("../test-data/hh-greeter-artifact.json"); let artifact = serde_json::from_str::<HardhatArtifact>(s).unwrap(); let compact = artifact.into_compact_contract(); assert!(compact.abi.is_some()); assert!(compact.bin.is_some()); assert!(compact.bin_runtime.is_some()); } }
use crate::{ artifacts::{ Bytecode, BytecodeObject, CompactContract, CompactContractBytecode, Contract, ContractBytecode, DeployedBytecode, LosslessAbi, Offsets, }, ArtifactOutput, }; use serde::{Deserialize, Serialize}; use std::collections::btree_map::BTreeMap; const HH_ARTIFACT_VERSION: &str = "hh-sol-artifact-1"; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct HardhatArtifact { #[serde(rename = "_format")] pub format: String, pub contract_name: String, pub source_name: String, pub abi: LosslessAbi, pub bytecode: Option<BytecodeObject>, pub deployed_bytecode: Option<BytecodeObject>, #[serde(default)] pub link_references: BTreeMap<String, BTreeMap<String, Vec<Offsets>>>, #[serde(default)] pub deployed_link_references: BTreeMap<String, BTreeMap<String, Vec<Offsets>>>, } impl From<HardhatArtifact> for CompactContract { fn from(artifact: HardhatArtifact) -> Self { CompactContract { abi: Some(artifact.abi.abi), bin: artifact.bytecode, bin_runtime: artifact.deployed_bytecode, } } } impl From<HardhatArtifact> for ContractBytecode { fn from(artifact: HardhatArtifact) -> Self { let bytecode: Option<Bytecode> = artifact.bytecode.as_ref().map(|t| { let mut bcode: Bytecode = t.clone().into(); bcode.link_references = artifact.link_references.clone(); bcode }); let deployed_bytecode: Option<DeployedBytecode> = artifact.bytecode.as_ref().map(|t| { let mut bcode: Bytecode = t.clone().into(); bcode.link_references = artifact.deployed_link_references.clone(); bcode.into() }); ContractBytecode { abi: Some(artifact.abi.abi), bytecode, deployed_bytecode } } } impl From<HardhatArtifact> for CompactContractBytecode { fn from(artifact: HardhatArtifact) -> Self { let c: ContractBytecode = artifact.into(); c.into() } } #[derive(Debug, Copy, Clone, Eq, PartialEq, Default)] pub struct HardhatArtifacts { _priv: (), } impl ArtifactOutput for HardhatArtifacts { type Artifact = HardhatArtifact;
} #[cfg(test)] mod tests { use super::*; use crate::Artifact; #[test] fn can_parse_hh_artifact() { let s = include_str!("../test-data/hh-greeter-artifact.json"); let artifact = serde_json::from_str::<HardhatArtifact>(s).unwrap(); let compact = artifact.into_compact_contract(); assert!(compact.abi.is_some()); assert!(compact.bin.is_some()); assert!(compact.bin_runtime.is_some()); } }
fn contract_to_artifact(&self, file: &str, name: &str, contract: Contract) -> Self::Artifact { let (bytecode, link_references, deployed_bytecode, deployed_link_references) = if let Some(evm) = contract.evm { let (deployed_bytecode, deployed_link_references) = if let Some(code) = evm.deployed_bytecode.and_then(|code| code.bytecode) { (Some(code.object), code.link_references) } else { (None, Default::default()) }; let (bytecode, link_ref) = if let Some(bc) = evm.bytecode { (Some(bc.object), bc.link_references) } else { (None, Default::default()) }; (bytecode, link_ref, deployed_bytecode, deployed_link_references) } else { (Default::default(), Default::default(), None, Default::default()) }; HardhatArtifact { format: HH_ARTIFACT_VERSION.to_string(), contract_name: name.to_string(), source_name: file.to_string(), abi: contract.abi.unwrap_or_default(), bytecode, deployed_bytecode, link_references, deployed_link_references, } }
function_block-full_function
[ { "content": "/// Strips the identifier of field declaration from the input and returns it\n\nfn strip_field_identifier(input: &mut &str) -> Result<String> {\n\n let mut iter = input.trim_end().rsplitn(2, is_whitespace);\n\n let name = iter\n\n .next()\n\n .ok_or_else(|| format_err!(\"Expect...
Rust
language/bytecode-verifier/src/abstract_state.rs
meenxio/libra
da94f03225f93709f18d614a72337e41ba54b3fd
use crate::{ absint::{AbstractDomain, JoinResult}, borrow_graph::BorrowGraph, nonce::Nonce, }; use mirai_annotations::{checked_postcondition, checked_precondition, checked_verify}; use std::collections::{BTreeMap, BTreeSet}; use vm::{ file_format::{ CompiledModule, FieldDefinitionIndex, Kind, LocalIndex, SignatureToken, StructDefinitionIndex, }, views::{FunctionDefinitionView, ViewInternals}, }; #[derive(Clone, Debug, Eq, PartialEq)] pub struct TypedAbstractValue { pub signature: SignatureToken, pub value: AbstractValue, } #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum AbstractValue { Reference(Nonce), Value(Kind), } impl AbstractValue { pub fn is_reference(&self) -> bool { match self { AbstractValue::Reference(_) => true, AbstractValue::Value(_) => false, } } pub fn is_value(&self) -> bool { !self.is_reference() } pub fn is_unrestricted_value(&self) -> bool { match self { AbstractValue::Reference(_) => false, AbstractValue::Value(Kind::Unrestricted) => true, AbstractValue::Value(Kind::All) | AbstractValue::Value(Kind::Resource) => false, } } pub fn extract_nonce(&self) -> Option<Nonce> { match self { AbstractValue::Reference(nonce) => Some(*nonce), AbstractValue::Value(_) => None, } } } #[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)] pub enum LabelElem { Local(LocalIndex), Global(StructDefinitionIndex), Field(FieldDefinitionIndex), } impl Default for LabelElem { fn default() -> Self { LabelElem::Local(0) } } #[derive(Clone, Debug, Default, Eq, PartialEq)] pub struct AbstractState { locals: BTreeMap<LocalIndex, TypedAbstractValue>, borrow_graph: BorrowGraph<LabelElem>, frame_root: Nonce, next_id: usize, } impl AbstractState { pub fn new(function_definition_view: FunctionDefinitionView<CompiledModule>) -> Self { let function_signature_view = function_definition_view.signature(); let mut locals = BTreeMap::new(); let mut borrow_graph = BorrowGraph::new(); for (arg_idx, arg_type_view) in function_signature_view.arg_tokens().enumerate() { if arg_type_view.is_reference() { let nonce = Nonce::new(arg_idx); borrow_graph.add_nonce(nonce); locals.insert( arg_idx as LocalIndex, TypedAbstractValue { signature: arg_type_view.as_inner().clone(), value: AbstractValue::Reference(nonce), }, ); } else { let arg_kind = arg_type_view .kind(&function_definition_view.signature().as_inner().type_formals); locals.insert( arg_idx as LocalIndex, TypedAbstractValue { signature: arg_type_view.as_inner().clone(), value: AbstractValue::Value(arg_kind), }, ); } } let frame_root = Nonce::new(function_definition_view.locals_signature().len()); borrow_graph.add_nonce(frame_root); let next_id = frame_root.inner() + 1; AbstractState { locals, borrow_graph, frame_root, next_id, } } pub fn is_available(&self, idx: LocalIndex) -> bool { self.locals.contains_key(&idx) } pub fn local(&self, idx: LocalIndex) -> &TypedAbstractValue { &self.locals[&idx] } pub fn remove_local(&mut self, idx: LocalIndex) -> TypedAbstractValue { self.locals.remove(&idx).unwrap() } pub fn insert_local(&mut self, idx: LocalIndex, abs_type: TypedAbstractValue) { self.locals.insert(idx, abs_type); } pub fn is_local_safe_to_destroy(&self, idx: LocalIndex) -> bool { match self.locals[&idx].value { AbstractValue::Reference(_) => true, AbstractValue::Value(Kind::All) | AbstractValue::Value(Kind::Resource) => false, AbstractValue::Value(Kind::Unrestricted) => !self.is_local_borrowed(idx), } } pub fn is_frame_safe_to_destroy(&self) -> bool { self.locals .values() .all(|x| x.value.is_unrestricted_value()) && !self.is_nonce_borrowed(self.frame_root) } pub fn destroy_local(&mut self, idx: LocalIndex) { checked_precondition!(self.is_local_safe_to_destroy(idx)); let local = self.locals.remove(&idx).unwrap(); match local.value { AbstractValue::Reference(nonce) => self.remove_nonce(nonce), AbstractValue::Value(kind) => { checked_verify!(kind == Kind::Unrestricted); } } } pub fn add_nonce(&mut self) -> Nonce { let nonce = Nonce::new(self.next_id); self.borrow_graph.add_nonce(nonce); self.next_id += 1; nonce } pub fn remove_nonce(&mut self, nonce: Nonce) { self.borrow_graph.remove_nonce(nonce); } pub fn is_nonce_borrowed(&self, nonce: Nonce) -> bool { !self.borrow_graph.all_borrows(nonce).is_empty() } pub fn is_local_borrowed(&self, idx: LocalIndex) -> bool { !self .borrow_graph .consistent_borrows(self.frame_root, LabelElem::Local(idx)) .is_empty() } pub fn is_global_borrowed(&self, idx: StructDefinitionIndex) -> bool { !self .borrow_graph .consistent_borrows(self.frame_root, LabelElem::Global(idx)) .is_empty() } pub fn is_nonce_freezable(&self, nonce: Nonce) -> bool { let borrows = self.borrow_graph.all_borrows(nonce); self.all_nonces_immutable(borrows) } pub fn borrow_global_value(&mut self, mut_: bool, idx: StructDefinitionIndex) -> Option<Nonce> { if mut_ { if self.is_global_borrowed(idx) { return None; } } else { let borrowed_nonces = self .borrow_graph .consistent_borrows(self.frame_root, LabelElem::Global(idx)); if !self.all_nonces_immutable(borrowed_nonces) { return None; } } let new_nonce = self.add_nonce(); self.borrow_graph .add_weak_edge(self.frame_root, vec![LabelElem::Global(idx)], new_nonce); Some(new_nonce) } pub fn borrow_field_from_nonce( &mut self, operand: &TypedAbstractValue, mut_: bool, idx: FieldDefinitionIndex, ) -> Option<Nonce> { let nonce = operand.value.extract_nonce().unwrap(); if mut_ { if !self.borrow_graph.nil_borrows(nonce).is_empty() { return None; } } else if operand.signature.is_mutable_reference() { let borrowed_nonces = self .borrow_graph .consistent_borrows(nonce, LabelElem::Field(idx)); if !self.all_nonces_immutable(borrowed_nonces) { return None; } } let new_nonce = self.add_nonce(); self.borrow_graph .add_strong_edge(nonce, vec![LabelElem::Field(idx)], new_nonce); Some(new_nonce) } pub fn borrow_local_value(&mut self, mut_: bool, idx: LocalIndex) -> Option<Nonce> { checked_precondition!(self.locals[&idx].value.is_value()); if !mut_ { let borrowed_nonces = self .borrow_graph .consistent_borrows(self.frame_root, LabelElem::Local(idx)); if !self.all_nonces_immutable(borrowed_nonces) { return None; } } let new_nonce = self.add_nonce(); self.borrow_graph .add_strong_edge(self.frame_root, vec![LabelElem::Local(idx)], new_nonce); Some(new_nonce) } pub fn borrow_from_local_reference(&mut self, idx: LocalIndex) -> Nonce { checked_precondition!(self.locals[&idx].value.is_reference()); let new_nonce = self.add_nonce(); self.borrow_graph.add_strong_edge( self.locals[&idx].value.extract_nonce().unwrap(), vec![], new_nonce, ); new_nonce } pub fn borrow_from_nonces(&mut self, to_borrow_from: &BTreeSet<Nonce>) -> Nonce { let new_nonce = self.add_nonce(); for nonce in to_borrow_from { self.borrow_graph.add_weak_edge(*nonce, vec![], new_nonce); } new_nonce } pub fn construct_canonical_state(&self) -> Self { let mut new_locals = BTreeMap::new(); let mut nonce_map = BTreeMap::new(); for (idx, abs_type) in &self.locals { if let AbstractValue::Reference(nonce) = abs_type.value { let new_nonce = Nonce::new(*idx as usize); new_locals.insert( *idx, TypedAbstractValue { signature: abs_type.signature.clone(), value: AbstractValue::Reference(new_nonce), }, ); nonce_map.insert(nonce, new_nonce); } else { new_locals.insert(*idx, abs_type.clone()); } } nonce_map.insert(self.frame_root, self.frame_root); let canonical_state = AbstractState { locals: new_locals, borrow_graph: self.borrow_graph.rename_nonces(nonce_map), frame_root: self.frame_root, next_id: self.frame_root.inner() + 1, }; checked_postcondition!(canonical_state.is_canonical()); canonical_state } fn all_nonces_immutable(&self, borrows: BTreeSet<Nonce>) -> bool { !self.locals.values().any(|abs_type| { abs_type.signature.is_mutable_reference() && borrows.contains(&abs_type.value.extract_nonce().unwrap()) }) } fn is_canonical(&self) -> bool { self.locals.iter().all(|(x, y)| { !y.value.is_reference() || Nonce::new(*x as usize) == y.value.extract_nonce().unwrap() }) } fn borrowed_value_unavailable(state1: &AbstractState, state2: &AbstractState) -> bool { state1.locals.keys().any(|idx| { state1.locals[idx].value.is_value() && state1.is_local_borrowed(*idx) && !state2.locals.contains_key(idx) }) } fn split_locals( locals: &BTreeMap<LocalIndex, TypedAbstractValue>, values: &mut BTreeMap<LocalIndex, Kind>, references: &mut BTreeMap<LocalIndex, Nonce>, ) { for (idx, abs_type) in locals { match abs_type.value { AbstractValue::Reference(nonce) => { references.insert(idx.clone(), nonce); } AbstractValue::Value(kind) => { values.insert(idx.clone(), kind); } } } } } impl AbstractDomain for AbstractState { fn join(&mut self, state: &AbstractState) -> JoinResult { checked_precondition!(self.is_canonical() && state.is_canonical()); if self .locals .keys() .filter(|idx| !self.locals[idx].value.is_unrestricted_value()) .collect::<BTreeSet<_>>() != state .locals .keys() .filter(|idx| !state.locals[idx].value.is_unrestricted_value()) .collect::<BTreeSet<_>>() { return JoinResult::Error; } if Self::borrowed_value_unavailable(self, state) || Self::borrowed_value_unavailable(state, self) { return JoinResult::Error; } let mut values1 = BTreeMap::new(); let mut references1 = BTreeMap::new(); Self::split_locals(&self.locals, &mut values1, &mut references1); let mut values2 = BTreeMap::new(); let mut references2 = BTreeMap::new(); Self::split_locals(&state.locals, &mut values2, &mut references2); checked_verify!(references1 == references2); let mut locals = BTreeMap::new(); for (idx, nonce) in &references1 { locals.insert( idx.clone(), TypedAbstractValue { signature: self.locals[idx].signature.clone(), value: AbstractValue::Reference(*nonce), }, ); } for (idx, kind1) in &values1 { if let Some(kind2) = values2.get(idx) { checked_verify!(kind1 == kind2); locals.insert( idx.clone(), TypedAbstractValue { signature: self.locals[idx].signature.clone(), value: AbstractValue::Value(*kind1), }, ); } } let locals_unchanged = self.locals.keys().all(|idx| locals.contains_key(idx)); let borrow_graph_unchanged = self.borrow_graph.abstracts(&state.borrow_graph); if locals_unchanged && borrow_graph_unchanged { JoinResult::Unchanged } else { self.locals = locals; self.borrow_graph.join(&state.borrow_graph); JoinResult::Changed } } }
use crate::{ absint::{AbstractDomain, JoinResult}, borrow_graph::BorrowGraph, nonce::Nonce, }; use mirai_annotations::{checked_postcondition, checked_precondition, checked_verify}; use std::collections::{BTreeMap, BTreeSet}; use vm::{ file_format::{ CompiledModule, FieldDefinitionIndex, Kind, LocalIndex, SignatureToken, StructDefinitionIndex, }, views::{FunctionDefinitionView, ViewInternals}, }; #[derive(Clone, Debug, Eq, PartialEq)] pub struct TypedAbstractValue { pub signature: SignatureToken, pub value: AbstractValue, } #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum AbstractValue { Reference(Nonce), Value(Kind), } impl AbstractValue { pub fn is_reference(&self) -> bool { match self { AbstractValue::Reference(_) => true, AbstractValue::Value(_) => false, } } pub fn is_value(&self) -> bool { !self.is_reference() } pub fn is_unrestricted_value(&self) -> bool { match self { AbstractValue::Reference(_) => false, AbstractValue::Value(Kind::Unrestricted) => true, AbstractValue::Value(Kind::All) | AbstractValue::Value(Kind::Resource) => false, } } pub fn extract_nonce(&self) -> Option<Nonce> { match self { AbstractValue::Reference(nonce) => Some(*nonce), AbstractValue::Value(_) => None, } } } #[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)] pub enum LabelElem { Local(LocalIndex), Global(StructDefinitionIndex), Field(FieldDefinitionIndex), } impl Default for LabelElem { fn default() -> Self { LabelElem::Local(0) } } #[derive(Clone, Debug, Default, Eq, PartialEq)] pub struct AbstractState { locals: BTreeMap<LocalIndex, TypedAbstractValue>, borrow_graph: BorrowGraph<LabelElem>, frame_root: Nonce, next_id: usize, } impl AbstractState { pub fn new(function_definition_view: FunctionDefinitionView<CompiledModule>) -> Self { let function_signature_view = function_definition_view.signature(); let mut locals = BTreeMap::new(); let mut borrow_graph = BorrowGraph::new(); for (arg_idx, arg_type_view) in function_signature_view.arg_tokens().enumerate() { if arg_type_view.is_reference() { let nonce = Nonce::new(arg_idx); borrow_graph.add_nonce(nonce); locals.insert( arg_idx as LocalIndex, TypedAbstractValue { signature: arg_type_view.as_inner().clone(), value: AbstractValue::Reference(nonce), }, ); } else { let arg_kind = arg_type_view .kind(&function_definition_view.signature().as_inner().type_formals); locals.insert( arg_idx as LocalIndex, TypedAbstractValue { signature: arg_type_view.as_inner().clone(), value: AbstractValue::Value(arg_kind), }, ); } } let frame_root = Nonce::new(function_definition_view.locals_signature().len()); borrow_graph.add_nonce(frame_root); let next_id = frame_root.inner() + 1; AbstractState { locals, borrow_graph, frame_root, next_id, } } pub fn is_available(&self, idx: LocalIndex) -> bool { self.locals.contains_key(&idx) } pub fn local(&self, idx: LocalIndex) -> &TypedAbstractValue { &self.locals[&idx] } pub fn remove_local(&mut self, idx: LocalIndex) -> TypedAbstractValue { self.locals.remove(&idx).unwrap() } pub fn insert_local(&mut self, idx: LocalIndex, abs_type: TypedAbstractValue) { self.locals.insert(idx, abs_type); } pub fn is_local_safe_to_destroy(&self, idx: LocalIndex) -> bool { match self.locals[&idx].value { AbstractValue::Reference(_) => true, AbstractValue::Value(Kind::All) | AbstractValue::Value(Kind::Resource) => false, AbstractValue::Value(Kind::Unrestricted) => !self.is_local_borrowed(idx), } } pub fn is_frame_safe_to_destroy(&self) -> bool { self.locals .values() .all(|x| x.value.is_unrestricted_value()) && !self.is_nonce_borrowed(self.frame_root) } pub fn destroy_local(&mut self, idx: LocalIndex) { checked_precondition!(self.is_local_safe_to_destroy(idx)); let local = self.locals.remove(&idx).unwrap(); match local.value { AbstractValue::Reference(nonce) => self.remove_nonce(nonce), AbstractValue::Value(kind) => { checked_verify!(kind == Kind::Unrestricted); } } } pub fn add_nonce(&mut self) -> Nonce { let nonce = Nonce::new(self.next_id); self.borrow_graph.add_nonce(nonce); self.next_id += 1; nonce } pub fn remove_nonce(&mut self, nonce: Nonce) { self.borrow_graph.remove_nonce(nonce); } pub fn is_nonce_borrowed(&self, nonce: Nonce) -> bool { !self.borrow_graph.all_borrows(nonce).is_empty() } pub fn is_local_borrowed(&self, idx: LocalIndex) -> bool { !self .borrow_graph .consistent_borrows(self.frame_root, LabelElem::Local(idx)) .is_empty() } pub fn is_global_borrowed(&self, idx: StructDefinitionIndex) -> bool { !self .borrow_graph .consistent_borrows(self.frame_root, LabelElem::Global(idx)) .is_empty() } pub fn is_nonce_freezable(&self, nonce: Nonce) -> bool { let borrows = self.borrow_graph.all_borrows(nonce); self.all_nonces_immutable(borrows) } pub fn borrow_global_value(&mut self, mut_: bool, idx: StructDefinitionIndex) -> Option<Nonce> { if mut_ { if self.is_global_borrowed(idx) { return None; } } else { let borrowed_nonces = self .borrow_graph .consistent_borrows(self.frame_root, LabelElem::Global(idx)); if !self.all_nonces_immutable(borrowed_nonces) { return None; } } let new_nonce = self.add_nonce(); self.borrow_graph .add_weak_edge(self.frame_root, vec![LabelElem::Global(idx)], new_nonce); Some(new_nonce) } pub fn borrow_field_from_nonce( &mut self, operand: &TypedAbstractValue, mut_: bool, idx: FieldDefinitionIndex, ) -> Option<Nonce> { let nonce = operand.value.extract_nonce().unwrap(); if mut_ { if !self.borrow_graph.nil_borrows(nonce).is_empty() { return None; } } else if operand.signature.is_mutable_reference() { let borrowed_nonces = self .borrow_graph .consistent_borrows(nonce, LabelElem::Field(idx)); if !self.all_nonces_immutable(borrowed_nonces) { return None; } } let new_nonce = self.add_nonce(); self.borrow_graph .add_strong_edge(nonce, vec![LabelElem::Field(idx)], new_nonce); Some(new_nonce) } pub fn borrow_local_value(&mut self, mut_: bool, idx: LocalIndex) -> Option<Nonce> { checked_precondition!(self.locals[&idx].value.is_value()); if !mut_ { let borrowed_nonces = self .borrow_graph .consistent_borrows(self.frame_root, LabelElem::Local(idx)); if !self.all_nonces_immutable(borrowed_nonces) { return None; } } let new_nonce = self.add_nonce(); self.borrow_graph .add_strong_edge(self.frame_root, vec![LabelElem::Local(idx)], new_nonce); Some(new_nonce) } pub fn borrow_from_local_reference(&mut self, idx: LocalIndex) -> Nonce { checked_precondition!(self.locals[&idx].value.is_reference()); let new_nonce = self.add_nonce(); self.borrow_graph.add_strong_edge( self.locals[&idx].value.extract_nonce().unwrap(), vec![], new_nonce, ); new_nonce } pub fn borrow_from_nonces(&mut self, to_borrow_from: &BTreeSet<Nonce>) -> Nonce { let new_nonce = self.add_nonce(); for nonce in to_borrow_from { self.borrow_graph.add_weak_edge(*nonce, vec![], new_nonce); } new_nonce } pub fn construct_canonical_state(&self) -> Self { let mut new_locals = BTreeMap::new(); let mut nonce_map = BTreeMap::new(); for (idx, abs_type) in &self.locals { if let AbstractValue::Reference(nonce) = abs_type.value { let new_nonce = Nonce::new(*idx as usize); new_locals.insert( *idx, TypedAbstractValue { signature: abs_type.signature.clone(), value: AbstractValue::Reference(new_nonce), }, ); nonce_map.insert(nonce, new_nonce); } else { new_locals.insert(*idx, abs_type.clone()); } } nonce_map.insert(self.frame_root, self.frame_root); let canonical_state = AbstractState { locals: new_locals, borrow_graph: self.borrow_graph.rename_nonces(nonce_map), frame_root: self.frame_root, next_id: self.frame_root.inner() + 1, }; checked_postcondition!(canonical_state.is_canonical()); canonical_state } fn all_nonces_immutable(&self, borrows: BTreeSet<Nonce>) -> bool { !self.locals.values().any(|abs_type| { abs_type.signature.is_mutable_reference() && borrows.contains(&abs_type.value.extract_nonce().unwrap()) }) } fn is_canonical(&self) -> bool { self.locals.iter().all(|(x, y)| { !y.value.is_reference() || Nonce::new(*x as usize) == y.value.extract_nonce().unwrap() }) } fn borrowed_value_unavailable(state1: &AbstractState, state2: &AbstractState) -> bool {
fn split_locals( locals: &BTreeMap<LocalIndex, TypedAbstractValue>, values: &mut BTreeMap<LocalIndex, Kind>, references: &mut BTreeMap<LocalIndex, Nonce>, ) { for (idx, abs_type) in locals { match abs_type.value { AbstractValue::Reference(nonce) => { references.insert(idx.clone(), nonce); } AbstractValue::Value(kind) => { values.insert(idx.clone(), kind); } } } } } impl AbstractDomain for AbstractState { fn join(&mut self, state: &AbstractState) -> JoinResult { checked_precondition!(self.is_canonical() && state.is_canonical()); if self .locals .keys() .filter(|idx| !self.locals[idx].value.is_unrestricted_value()) .collect::<BTreeSet<_>>() != state .locals .keys() .filter(|idx| !state.locals[idx].value.is_unrestricted_value()) .collect::<BTreeSet<_>>() { return JoinResult::Error; } if Self::borrowed_value_unavailable(self, state) || Self::borrowed_value_unavailable(state, self) { return JoinResult::Error; } let mut values1 = BTreeMap::new(); let mut references1 = BTreeMap::new(); Self::split_locals(&self.locals, &mut values1, &mut references1); let mut values2 = BTreeMap::new(); let mut references2 = BTreeMap::new(); Self::split_locals(&state.locals, &mut values2, &mut references2); checked_verify!(references1 == references2); let mut locals = BTreeMap::new(); for (idx, nonce) in &references1 { locals.insert( idx.clone(), TypedAbstractValue { signature: self.locals[idx].signature.clone(), value: AbstractValue::Reference(*nonce), }, ); } for (idx, kind1) in &values1 { if let Some(kind2) = values2.get(idx) { checked_verify!(kind1 == kind2); locals.insert( idx.clone(), TypedAbstractValue { signature: self.locals[idx].signature.clone(), value: AbstractValue::Value(*kind1), }, ); } } let locals_unchanged = self.locals.keys().all(|idx| locals.contains_key(idx)); let borrow_graph_unchanged = self.borrow_graph.abstracts(&state.borrow_graph); if locals_unchanged && borrow_graph_unchanged { JoinResult::Unchanged } else { self.locals = locals; self.borrow_graph.join(&state.borrow_graph); JoinResult::Changed } } }
state1.locals.keys().any(|idx| { state1.locals[idx].value.is_value() && state1.is_local_borrowed(*idx) && !state2.locals.contains_key(idx) }) }
function_block-function_prefix_line
[ { "content": "/// Get the StructTag for a StructDefinition defined in a published module.\n\npub fn resource_storage_key(module: &impl ModuleAccess, idx: StructDefinitionIndex) -> StructTag {\n\n let resource = module.struct_def_at(idx);\n\n let res_handle = module.struct_handle_at(resource.struct_handle)...
Rust
dynomite/src/ext.rs
sbruton/dynomite
0f3e5a045a0bbd6fd5ae6b1f83c66ccbb0ac6376
use crate::dynamodb::{ AttributeValue, BackupSummary, DynamoDb, ListBackupsError, ListBackupsInput, ListTablesError, ListTablesInput, QueryError, QueryInput, ScanError, ScanInput, }; use futures::{stream, Stream, TryStreamExt}; #[cfg(feature = "default")] use rusoto_core_default::RusotoError; #[cfg(feature = "rustls")] use rusoto_core_rustls::RusotoError; use std::{collections::HashMap, pin::Pin}; type DynomiteStream<I, E> = Pin<Box<dyn Stream<Item = Result<I, RusotoError<E>>> + Send>>; type DynomiteUserStream<I, E> = Pin<Box<dyn Stream<Item = Result<I, E>> + Send>>; pub trait DynamoDbExt { fn list_backups_pages( self, input: ListBackupsInput, ) -> DynomiteStream<BackupSummary, ListBackupsError>; fn list_tables_pages( self, input: ListTablesInput, ) -> DynomiteStream<String, ListTablesError>; fn query_pages( self, input: QueryInput, ) -> DynomiteStream<HashMap<String, AttributeValue>, QueryError>; fn scan_pages<E: From<RusotoError<ScanError>> + Sized + Sync + Send>( self, input: ScanInput, ) -> DynomiteUserStream<HashMap<String, AttributeValue>, E>; } impl<D> DynamoDbExt for D where D: DynamoDb + Clone + Send + Sync + 'static, { fn list_backups_pages( self, input: ListBackupsInput, ) -> DynomiteStream<BackupSummary, ListBackupsError> { enum PageState { Next(Option<String>, ListBackupsInput), End, } Box::pin( stream::try_unfold( PageState::Next(input.exclusive_start_backup_arn.clone(), input), move |state| { let clone = self.clone(); async move { let (exclusive_start_backup_arn, input) = match state { PageState::Next(start, input) => (start, input), PageState::End => { return Ok(None) as Result<_, RusotoError<ListBackupsError>> } }; let resp = clone .list_backups(ListBackupsInput { exclusive_start_backup_arn, ..input.clone() }) .await?; let next_state = match resp .last_evaluated_backup_arn .filter(|next| !next.is_empty()) { Some(next) => PageState::Next(Some(next), input), _ => PageState::End, }; Ok(Some(( stream::iter( resp.backup_summaries .unwrap_or_default() .into_iter() .map(Ok), ), next_state, ))) } }, ) .try_flatten(), ) } fn list_tables_pages( self, input: ListTablesInput, ) -> DynomiteStream<String, ListTablesError> { enum PageState { Next(Option<String>, ListTablesInput), End, } Box::pin( stream::try_unfold( PageState::Next(input.exclusive_start_table_name.clone(), input), move |state| { let clone = self.clone(); async move { let (exclusive_start_table_name, input) = match state { PageState::Next(start, input) => (start, input), PageState::End => { return Ok(None) as Result<_, RusotoError<ListTablesError>> } }; let resp = clone .list_tables(ListTablesInput { exclusive_start_table_name, ..input.clone() }) .await?; let next_state = match resp .last_evaluated_table_name .filter(|next| !next.is_empty()) { Some(next) => PageState::Next(Some(next), input), _ => PageState::End, }; Ok(Some(( stream::iter(resp.table_names.unwrap_or_default().into_iter().map(Ok)), next_state, ))) } }, ) .try_flatten(), ) } fn query_pages( self, input: QueryInput, ) -> DynomiteStream<HashMap<String, AttributeValue>, QueryError> { #[allow(clippy::large_enum_variant)] enum PageState { Next(Option<HashMap<String, AttributeValue>>, QueryInput), End, } Box::pin( stream::try_unfold( PageState::Next(input.exclusive_start_key.clone(), input), move |state| { let clone = self.clone(); async move { let (exclusive_start_key, input) = match state { PageState::Next(start, input) => (start, input), PageState::End => { return Ok(None) as Result<_, RusotoError<QueryError>> } }; let resp = clone .query(QueryInput { exclusive_start_key, ..input.clone() }) .await?; let next_state = match resp.last_evaluated_key.filter(|next| !next.is_empty()) { Some(next) => PageState::Next(Some(next), input), _ => PageState::End, }; Ok(Some(( stream::iter(resp.items.unwrap_or_default().into_iter().map(Ok)), next_state, ))) } }, ) .try_flatten(), ) } fn scan_pages<E>( self, input: ScanInput, ) -> DynomiteUserStream<HashMap<String, AttributeValue>, E> where E: From<RusotoError<ScanError>> + Sized + Sync + Send, { #[allow(clippy::large_enum_variant)] enum PageState { Next(Option<HashMap<String, AttributeValue>>, ScanInput), End, } Box::pin( stream::try_unfold( PageState::Next(input.exclusive_start_key.clone(), input), move |state| { let clone = self.clone(); async move { let (exclusive_start_key, input) = match state { PageState::Next(start, input) => (start, input), PageState::End => return Ok(None) as Result<_, E>, }; let resp = clone .scan(ScanInput { exclusive_start_key, ..input.clone() }) .await?; let next_state = match resp.last_evaluated_key.filter(|next| !next.is_empty()) { Some(next) => PageState::Next(Some(next), input), _ => PageState::End, }; Ok(Some(( stream::iter(resp.items.unwrap_or_default().into_iter().map(Ok)), next_state, ))) } }, ) .try_flatten(), ) } }
use crate::dynamodb::{ AttributeValue, BackupSummary, DynamoDb, ListBackupsError, ListBackupsInput, ListTablesError, ListTablesInput, QueryError, QueryInput, ScanError, ScanInput, }; use futures::{stream, Stream, TryStreamExt}; #[cfg(feature = "default")] use rusoto_core_default::RusotoError; #[cfg(feature = "rustls")] use rusoto_core_rustls::RusotoError; use std::{collections::HashMap, pin::Pin}; type DynomiteStream<I, E> = Pin<Box<dyn Stream<Item = Result<I, RusotoError<E>>> + Send>>; type DynomiteUserStream<I, E> = Pin<Box<dyn Stream<Item = Result<I, E>> + Send>>; pub trait DynamoDbExt { fn list_backups_pages( self, input: ListBackupsInput, ) -> DynomiteStream<BackupSummary, ListBackupsError>; fn list_tables_pages( self, input: ListTablesInput, ) -> DynomiteStream<String, ListTablesError>; fn query_pages( self, input: QueryInput, ) -> DynomiteStream<HashMap<String, AttributeValue>, QueryError>; fn scan_pages<E: From<RusotoError<ScanError>> + Sized + Sync + Send>( self, input: ScanInput, ) -> DynomiteUserStream<HashMap<String, AttributeValue>, E>; } impl<D> DynamoDbExt for D where D: DynamoDb + Clone + Send + Sync + 'static, { fn list_backups_pages( self, input: ListBackupsInput, ) -> DynomiteStream<BackupSummary, ListBackupsError> { enum PageState { Next(Option<String>, ListBackupsInput), End, } Box::pin( stream::try_unfold( PageState::Next(input.exclusive_start_backup_arn.clone(), input), move |state| { let clone = self.clone(); async move { let (exclusive_start_backup_arn, input) = match state { PageState::Next(start, input) => (start, input), PageState::End => { return Ok(None) as Result<_, RusotoError<ListBackupsError>> } }; let resp = clone .list_backups(ListBackupsInput { exclusive_start_backup_arn, ..input.clone() }) .await?; let next_state = match resp .last_evaluated_backup_arn .filter(|next| !next.is_empty()) { Some(next) => PageState::Next(Some(next), input), _ => PageState::End, }; Ok(Some(( stream::iter( resp.backup_summaries .unwrap_or_default() .into_iter() .map(Ok), ), next_state, ))) } }, ) .try_flatten(), ) } fn list_tables_pages( self, input: ListTablesInput, ) -> DynomiteStream<String, ListTablesError> { enum PageState { Next(Option<String>, ListTablesInput), End, } Box::pin( stream::try_unfold( PageState::Next(input.exclusive_start_table_name.clone(), input), move |state| { let clone = self.clone(); async move { let (exclusive_start_table_name, input) = match state { PageState::Next(start, input) => (start, input), PageState::End => { return Ok(None) as Result<_, RusotoError<ListTablesError>> } }; let resp = clone .list_tables(ListTablesInput { exclusive_start_table_name, ..input.clone() }) .await?; let next_state = match resp .last_evaluated_table_name .filter(|next| !next.is_empty()) { Some(next) => PageState::Next(Some(next), input), _ => PageState::End, }; Ok(Some(( stream::iter(resp.table_names.unwrap_or_default().into_iter().map(Ok)), next_state, ))) } }, ) .try_flatten(), ) } fn query_pages( self, input: QueryInput, ) -> DynomiteStream<HashMap<String, AttributeValue>, QueryError> { #[allow(clippy::large_enum_variant)] enum PageState { Next(Option<HashMap<String, AttributeValue>>, QueryInput), End, } Box::pin( stream::try_unfold( PageState::Next(input.exclusive_start_key.clone(), input), move |state| { let clone = self.clone(); async move { let (exclusive_start_key, input) = match state { PageState::Next(start, input) => (start, input), PageState::End => { return Ok(None) as Result<_, RusotoError<QueryError>> } }; let resp = clone .query(QueryInput { exclusive_start_key, ..input.clone() }) .await?; let next_state = match resp.last_evaluated_key.filter(|next| !next.is_empty()) { Some(next) => PageState::Next(Some(next), input), _ => PageState::End, }; Ok(Some(( stream::iter(resp.items.unwrap_or_default().into_iter().map(Ok)), next_state, ))) } }, ) .try_flatten(), ) } fn scan_pages<E>( self, input: ScanInput, ) -> DynomiteUserStream<HashMap<String, AttributeValue>, E> where E: From<RusotoError<ScanError>> + Sized + Sync + Send, { #[allow(clippy::large_enum_variant)] enum PageState { Next(Option<HashMap<String, AttributeValue>>, ScanInput), End, } Box::pin( stream::try_unfold( PageState::Next(input.exclusive_start_key.clone(), input), move |state| { let clone = self.clone(); async move { let (exclusive_start_key, input) = match state { PageState::Next(start, input) => (start, input), PageState::End => return Ok(None) as Result<_, E>, }; let resp = clone .scan(ScanInput { exclusive_start_key, ..input.clone() }) .await?; let next_state =
; Ok(Some(( stream::iter(resp.items.unwrap_or_default().into_iter().map(Ok)), next_state, ))) } }, ) .try_flatten(), ) } }
match resp.last_evaluated_key.filter(|next| !next.is_empty()) { Some(next) => PageState::Next(Some(next), input), _ => PageState::End, }
if_condition
[ { "content": "#[proc_macro_error::proc_macro_error]\n\n#[proc_macro_derive(Attributes, attributes(dynomite))]\n\npub fn derive_attributes(input: TokenStream) -> TokenStream {\n\n let ast = syn::parse_macro_input!(input);\n\n\n\n let gen = match expand_attributes(ast) {\n\n Ok(g) => g,\n\n Er...
Rust
language/bytecode-verifier/src/control_flow.rs
GreyHyphen/dijets
8c94c5c079fd025929dbd0455fc0e76d62e418c2
use move_binary_format::{ errors::{PartialVMError, PartialVMResult}, file_format::{Bytecode, CodeOffset, CodeUnit, FunctionDefinitionIndex}, }; use move_core_types::vm_status::StatusCode; use std::{collections::HashSet, convert::TryInto}; pub fn verify( current_function_opt: Option<FunctionDefinitionIndex>, code: &CodeUnit, ) -> PartialVMResult<()> { let current_function = current_function_opt.unwrap_or(FunctionDefinitionIndex(0)); match code.code.last() { None => return Err(PartialVMError::new(StatusCode::EMPTY_CODE_UNIT)), Some(last) if !last.is_unconditional_branch() => { return Err(PartialVMError::new(StatusCode::INVALID_FALL_THROUGH) .at_code_offset(current_function, (code.code.len() - 1) as CodeOffset)) } Some(_) => (), } let context = &ControlFlowVerifier { current_function, code: &code.code, }; let labels = instruction_labels(context); check_jumps(context, labels) } #[derive(Clone, Copy)] enum Label { Loop { last_continue: u16 }, Code, } struct ControlFlowVerifier<'a> { current_function: FunctionDefinitionIndex, code: &'a Vec<Bytecode>, } impl<'a> ControlFlowVerifier<'a> { fn code(&self) -> impl Iterator<Item = (CodeOffset, &'a Bytecode)> { self.code .iter() .enumerate() .map(|(idx, instr)| (idx.try_into().unwrap(), instr)) } fn labeled_code<'b: 'a>( &self, labels: &'b [Label], ) -> impl Iterator<Item = (CodeOffset, &'a Bytecode, &'b Label)> { self.code() .zip(labels) .map(|((i, instr), lbl)| (i, instr, lbl)) } fn error(&self, status: StatusCode, offset: CodeOffset) -> PartialVMError { PartialVMError::new(status).at_code_offset(self.current_function, offset) } } fn instruction_labels(context: &ControlFlowVerifier) -> Vec<Label> { let mut labels: Vec<Label> = (0..context.code.len()).map(|_| Label::Code).collect(); let mut loop_continue = |loop_idx: CodeOffset, last_continue: CodeOffset| { labels[loop_idx as usize] = Label::Loop { last_continue } }; for (i, instr) in context.code() { match instr { Bytecode::Branch(prev) | Bytecode::BrTrue(prev) | Bytecode::BrFalse(prev) if *prev <= i => { loop_continue(*prev, i) } _ => (), } } labels } fn check_jumps(context: &ControlFlowVerifier, labels: Vec<Label>) -> PartialVMResult<()> { check_continues(context, &labels)?; check_breaks(context, &labels)?; check_no_loop_splits(context, &labels) } fn check_code< F: FnMut(&Vec<(CodeOffset, CodeOffset)>, CodeOffset, &Bytecode) -> PartialVMResult<()>, >( context: &ControlFlowVerifier, labels: &[Label], mut check: F, ) -> PartialVMResult<()> { let mut loop_stack: Vec<(CodeOffset, CodeOffset)> = vec![]; for (i, instr, label) in context.labeled_code(labels) { if let Label::Loop { last_continue } = label { loop_stack.push((i, *last_continue)); } check(&loop_stack, i, instr)?; match instr { Bytecode::Branch(j) | Bytecode::BrTrue(j) | Bytecode::BrFalse(j) if *j <= i => { let (_cur_loop, last_continue) = loop_stack.last().unwrap(); if i == *last_continue { loop_stack.pop(); } } _ => (), } } Ok(()) } fn check_continues(context: &ControlFlowVerifier, labels: &[Label]) -> PartialVMResult<()> { check_code(context, labels, |loop_stack, i, instr| { match instr { Bytecode::Branch(j) | Bytecode::BrTrue(j) | Bytecode::BrFalse(j) if *j <= i => { let (cur_loop, _last_continue) = loop_stack.last().unwrap(); let is_continue = *j <= i; if is_continue && j != cur_loop { Err(context.error(StatusCode::INVALID_LOOP_CONTINUE, i)) } else { Ok(()) } } _ => Ok(()), } }) } fn check_breaks(context: &ControlFlowVerifier, labels: &[Label]) -> PartialVMResult<()> { check_code(context, labels, |loop_stack, i, instr| { match instr { Bytecode::Branch(j) | Bytecode::BrTrue(j) | Bytecode::BrFalse(j) if *j > i => { match loop_stack.last() { Some((_cur_loop, last_continue)) if j > last_continue && *j != last_continue + 1 => { Err(context.error(StatusCode::INVALID_LOOP_BREAK, i)) } _ => Ok(()), } } _ => Ok(()), } }) } fn check_no_loop_splits(context: &ControlFlowVerifier, labels: &[Label]) -> PartialVMResult<()> { let is_break = |loop_stack: &Vec<(CodeOffset, CodeOffset)>, jump_target: CodeOffset| -> bool { match loop_stack.last() { None => false, Some((_cur_loop, last_continue)) => jump_target > *last_continue, } }; let loop_depth = count_loop_depth(labels); check_code(context, labels, |loop_stack, i, instr| { match instr { Bytecode::Branch(j) | Bytecode::BrTrue(j) | Bytecode::BrFalse(j) if *j > i && !is_break(loop_stack, *j) => { let j = *j; let before_depth = loop_depth[i as usize]; let after_depth = match &labels[j as usize] { Label::Loop { .. } => loop_depth[j as usize] - 1, Label::Code => loop_depth[j as usize], }; if before_depth != after_depth { Err(context.error(StatusCode::INVALID_LOOP_SPLIT, i)) } else { Ok(()) } } _ => Ok(()), } }) } fn count_loop_depth(labels: &[Label]) -> Vec<usize> { let last_continues: HashSet<CodeOffset> = labels .iter() .filter_map(|label| match label { Label::Loop { last_continue } => Some(*last_continue), Label::Code => None, }) .collect(); let mut count = 0; let mut counts = vec![]; for (idx, label) in labels.iter().enumerate() { if let Label::Loop { .. } = label { count += 1 } counts.push(count); if last_continues.contains(&idx.try_into().unwrap()) { count -= 1; } } counts }
use move_binary_format::{ errors::{PartialVMError, PartialVMResult}, file_format::{Bytecode, CodeOffset, CodeUnit, FunctionDefinitionIndex}, }; use move_core_types::vm_status::StatusCode; use std::{collections::HashSet, convert::TryInto}; pub fn verify( current_function_opt: Option<FunctionDefinitionIndex>, code: &CodeUnit, ) -> PartialVMResult<()> { let current_function = current_function_opt.unwrap_or(FunctionDefinitionIndex(0)); match code.code.last() { None => return Err(PartialVMError::new(StatusCode::EMPTY_CODE_UNIT)), Some(last) if !last.is_unconditional_branch() => { return Err(PartialVMError::new(StatusCode::INVALID_FALL_THROUGH) .at_code_offset(current_function, (code.code.len() - 1) as CodeOffset)) } Some(_) => (), } let context = &ControlFlowVerifier { current_function, code: &code.code, }; let labels = instruction_labels(context); check_jumps(context, labels) } #[derive(Clone, Copy)] enum Label { Loop { last_continue: u16 }, Code, } struct ControlFlowVerifier<'a> { current_function: FunctionDefinitionIndex, code: &'a Vec<Bytecode>, } impl<'a> ControlFlowVerifier<'a> { fn code(&self) -> impl Iterator<Item = (CodeOffset, &'a Bytecode)> { self.code .iter() .enumerate() .map(|(idx, instr)| (idx.try_into().unwrap(), instr)) } fn labeled_code<'b: 'a>( &self, labels: &'b [Label], ) -> impl Iterator<Item = (CodeOffset, &'a Bytecode, &'b Label)> { self.code() .zip(labels) .map(|((i, instr), lbl)| (i, instr, lbl)) } fn error(&self, status: StatusCode, offset: CodeOffset) -> PartialVMError { PartialVMError::new(status).at_code_offset(self.current_function, offset) } } fn instruction_labels(context: &ControlFlowVerifier) -> Vec<Label> { let mut labels: Vec<Label> = (0..context.code.len()).map(|_| Label::Code).collect(); let mut loop_continue = |loop_idx: CodeOffset, last_continue: CodeOffset| { labels[loop_idx as usize] = Label::Loop { last_continue } }; for (i, instr) in context.code() { match instr { Bytecode::Branch(prev) | Bytecode::BrTrue(prev) | Bytecode::BrFalse(prev) if *prev <= i => { loop_continue(*prev, i) } _ => (), } } labels } fn check_jumps(context: &ControlFlowVerifier, labels: Vec<Label>) -> PartialVMResult<()> { check_continues(context, &labels)?; check_breaks(context, &labels)?; check_no_loop_splits(context, &labels) } fn check_code< F: FnMut(&Vec<(CodeOffset, CodeOffset)>, CodeOffset, &Bytecode) -> PartialVMResult<()>, >( context: &ControlFlowVerifier, labels: &[Label], mut check: F, ) -> PartialVMResult<()> { let mut loop_stack: Vec<(CodeOffset, CodeOffset)> = vec![]; for (i, instr, label) in context.labeled_code(labels) { if let Label::Loop { last_continue } = label { loop_stack.push((i, *last_continue)); } check(&loop_stack, i, instr)?; match instr { Bytecode::Branch(j) | Bytecode::BrTrue(j) | Bytecode::BrFalse(j) if *j <= i => { let (_cur_loop, last_continue) = loop_stack.last().unwrap(); if i == *last_continue { loop_stack.pop(); } } _ => (), } } Ok(()) } fn check_continues(context: &ControlFlowVerifier, labels: &[Label]) -> PartialVMResult<()> { check_code(context, labels, |loop_stack, i, instr| { match instr { Bytecode::Branch(j) | Bytecode::BrTrue(j) | Bytecode::BrFalse(j) if *j <= i => { let (cur_loop, _last_continue) = loop_stack.last().unwrap(); let is_continue = *j <= i; if is_continue && j != cur_loop { Err(context.error(StatusCode::INVALID_LOOP_CONTINUE, i)) } else { Ok(()) } } _ => Ok(()), } }) } fn check_breaks(context: &ControlFlowVerifier, labels: &[Label]) -> PartialVMResult<()> { check_code(context, labels, |lo
Err(context.error(StatusCode::INVALID_LOOP_BREAK, i)) } _ => Ok(()), } } _ => Ok(()), } }) } fn check_no_loop_splits(context: &ControlFlowVerifier, labels: &[Label]) -> PartialVMResult<()> { let is_break = |loop_stack: &Vec<(CodeOffset, CodeOffset)>, jump_target: CodeOffset| -> bool { match loop_stack.last() { None => false, Some((_cur_loop, last_continue)) => jump_target > *last_continue, } }; let loop_depth = count_loop_depth(labels); check_code(context, labels, |loop_stack, i, instr| { match instr { Bytecode::Branch(j) | Bytecode::BrTrue(j) | Bytecode::BrFalse(j) if *j > i && !is_break(loop_stack, *j) => { let j = *j; let before_depth = loop_depth[i as usize]; let after_depth = match &labels[j as usize] { Label::Loop { .. } => loop_depth[j as usize] - 1, Label::Code => loop_depth[j as usize], }; if before_depth != after_depth { Err(context.error(StatusCode::INVALID_LOOP_SPLIT, i)) } else { Ok(()) } } _ => Ok(()), } }) } fn count_loop_depth(labels: &[Label]) -> Vec<usize> { let last_continues: HashSet<CodeOffset> = labels .iter() .filter_map(|label| match label { Label::Loop { last_continue } => Some(*last_continue), Label::Code => None, }) .collect(); let mut count = 0; let mut counts = vec![]; for (idx, label) in labels.iter().enumerate() { if let Label::Loop { .. } = label { count += 1 } counts.push(count); if last_continues.contains(&idx.try_into().unwrap()) { count -= 1; } } counts }
op_stack, i, instr| { match instr { Bytecode::Branch(j) | Bytecode::BrTrue(j) | Bytecode::BrFalse(j) if *j > i => { match loop_stack.last() { Some((_cur_loop, last_continue)) if j > last_continue && *j != last_continue + 1 => {
function_block-random_span
[ { "content": "fn remap_branch_offsets(code: &mut Vec<Bytecode>, fake_to_actual: &HashMap<u16, u16>) {\n\n for instr in code {\n\n match instr {\n\n Bytecode::BrTrue(offset) | Bytecode::BrFalse(offset) | Bytecode::Branch(offset) => {\n\n *offset = fake_to_actual[offset]\n\n ...
Rust
src/systems/collision.rs
Jazarro/evoli
fe817899c4381bc98b294ae124f12301a711c664
use amethyst::renderer::{debug_drawing::DebugLinesComponent, palette::Srgba}; use amethyst::shrev::{EventChannel, ReaderId}; use amethyst::{core::math::Point3, core::Transform, ecs::prelude::*}; use log::info; use std::f32; #[cfg(feature = "profiler")] use thread_profiler::profile_scope; use crate::components::collider; use crate::components::creatures; use crate::resources::world_bounds::*; pub struct EnforceBoundsSystem; impl<'s> System<'s> for EnforceBoundsSystem { type SystemData = ( WriteStorage<'s, Transform>, ReadStorage<'s, creatures::CreatureTag>, ReadExpect<'s, WorldBounds>, ); fn run(&mut self, (mut locals, tags, bounds): Self::SystemData) { for (local, _) in (&mut locals, &tags).join() { let pos = local.translation().clone(); if pos.x > bounds.right { local.translation_mut().x = bounds.right; } else if pos.x < bounds.left { local.translation_mut().x = bounds.left; } if pos.y > bounds.top { local.translation_mut().y = bounds.top; } else if pos.y < bounds.bottom { local.translation_mut().y = bounds.bottom; } } } } #[derive(Debug, Clone)] pub struct CollisionEvent { pub entity_a: Entity, pub entity_b: Entity, } impl CollisionEvent { pub fn new(entity_a: Entity, entity_b: Entity) -> CollisionEvent { CollisionEvent { entity_a, entity_b } } } pub struct CollisionSystem; impl<'s> System<'s> for CollisionSystem { type SystemData = ( ReadStorage<'s, collider::Circle>, WriteStorage<'s, creatures::Movement>, WriteStorage<'s, Transform>, Entities<'s>, Write<'s, EventChannel<CollisionEvent>>, ); fn run( &mut self, (circles, mut movements, locals, entities, mut collision_events): Self::SystemData, ) { #[cfg(feature = "profiler")] profile_scope!("collision_system"); for (circle_a, movement, local_a, entity_a) in (&circles, &mut movements, &locals, &entities).join() { for (circle_b, local_b, entity_b) in (&circles, &locals, &entities).join() { if entity_a == entity_b { continue; } let allowed_distance = circle_a.radius + circle_b.radius; let direction = local_a.translation() - local_b.translation(); if direction.magnitude_squared() < allowed_distance * allowed_distance { collision_events.single_write(CollisionEvent::new(entity_a, entity_b)); if direction.magnitude() < f32::EPSILON { movement.velocity = -movement.velocity; } else { let norm_direction = direction.normalize(); movement.velocity = norm_direction * movement.velocity.magnitude(); } } } } } } pub struct DebugColliderSystem; impl<'s> System<'s> for DebugColliderSystem { type SystemData = ( ReadStorage<'s, collider::Circle>, ReadStorage<'s, Transform>, WriteStorage<'s, DebugLinesComponent>, ); fn run(&mut self, (circles, locals, mut debug_lines_comps): Self::SystemData) { for (circle, local, db_comp) in (&circles, &locals, &mut debug_lines_comps).join() { let mut position = local.global_matrix().column(3).xyz(); position[2] += 1.0; db_comp.add_circle_2d( Point3::from(position), circle.radius, 16, Srgba::new(1.0, 0.5, 0.5, 1.0), ); } } } #[derive(Default)] pub struct DebugCollisionEventSystem { event_reader: Option<ReaderId<CollisionEvent>>, } impl<'s> System<'s> for DebugCollisionEventSystem { type SystemData = (Write<'s, EventChannel<CollisionEvent>>,); fn run(&mut self, (collision_events,): Self::SystemData) { let event_reader = self .event_reader .as_mut() .expect("`DebugCollisionEventSystem::setup` was not called before `DebugCollisionEventSystem::run`"); for event in collision_events.read(event_reader) { info!("Received collision event {:?}", event) } } fn setup(&mut self, world: &mut World) { <Self as System<'_>>::SystemData::setup(world); self.event_reader = Some( world .fetch_mut::<EventChannel<CollisionEvent>>() .register_reader(), ); } }
use amethyst::renderer::{debug_drawing::DebugLinesComponent, palette::Srgba}; use amethyst::shrev::{EventChannel, ReaderId}; use amethyst::{core::math::Point3, core::Transform, ecs::prelude::*}; use log::info; use std::f32; #[cfg(feature = "profiler")] use thread_profiler::profile_scope; use crate::components::collider; use crate::components::creatures; use crate::resources::world_bounds::*; pub struct EnforceBoundsSystem; impl<'s> System<'s> for EnforceBoundsSystem { type SystemData = ( WriteStorage<'s, Transform>, ReadStorage<'s, creatures::CreatureTag>, ReadExpect<'s, WorldBounds>, ); fn run(&mut self, (mut locals, tags, bounds): Self::SystemData) { for (local, _) in (&mut locals, &tags).join() { let pos = loc
if pos.y > bounds.top { local.translation_mut().y = bounds.top; } else if pos.y < bounds.bottom { local.translation_mut().y = bounds.bottom; } } } } #[derive(Debug, Clone)] pub struct CollisionEvent { pub entity_a: Entity, pub entity_b: Entity, } impl CollisionEvent { pub fn new(entity_a: Entity, entity_b: Entity) -> CollisionEvent { CollisionEvent { entity_a, entity_b } } } pub struct CollisionSystem; impl<'s> System<'s> for CollisionSystem { type SystemData = ( ReadStorage<'s, collider::Circle>, WriteStorage<'s, creatures::Movement>, WriteStorage<'s, Transform>, Entities<'s>, Write<'s, EventChannel<CollisionEvent>>, ); fn run( &mut self, (circles, mut movements, locals, entities, mut collision_events): Self::SystemData, ) { #[cfg(feature = "profiler")] profile_scope!("collision_system"); for (circle_a, movement, local_a, entity_a) in (&circles, &mut movements, &locals, &entities).join() { for (circle_b, local_b, entity_b) in (&circles, &locals, &entities).join() { if entity_a == entity_b { continue; } let allowed_distance = circle_a.radius + circle_b.radius; let direction = local_a.translation() - local_b.translation(); if direction.magnitude_squared() < allowed_distance * allowed_distance { collision_events.single_write(CollisionEvent::new(entity_a, entity_b)); if direction.magnitude() < f32::EPSILON { movement.velocity = -movement.velocity; } else { let norm_direction = direction.normalize(); movement.velocity = norm_direction * movement.velocity.magnitude(); } } } } } } pub struct DebugColliderSystem; impl<'s> System<'s> for DebugColliderSystem { type SystemData = ( ReadStorage<'s, collider::Circle>, ReadStorage<'s, Transform>, WriteStorage<'s, DebugLinesComponent>, ); fn run(&mut self, (circles, locals, mut debug_lines_comps): Self::SystemData) { for (circle, local, db_comp) in (&circles, &locals, &mut debug_lines_comps).join() { let mut position = local.global_matrix().column(3).xyz(); position[2] += 1.0; db_comp.add_circle_2d( Point3::from(position), circle.radius, 16, Srgba::new(1.0, 0.5, 0.5, 1.0), ); } } } #[derive(Default)] pub struct DebugCollisionEventSystem { event_reader: Option<ReaderId<CollisionEvent>>, } impl<'s> System<'s> for DebugCollisionEventSystem { type SystemData = (Write<'s, EventChannel<CollisionEvent>>,); fn run(&mut self, (collision_events,): Self::SystemData) { let event_reader = self .event_reader .as_mut() .expect("`DebugCollisionEventSystem::setup` was not called before `DebugCollisionEventSystem::run`"); for event in collision_events.read(event_reader) { info!("Received collision event {:?}", event) } } fn setup(&mut self, world: &mut World) { <Self as System<'_>>::SystemData::setup(world); self.event_reader = Some( world .fetch_mut::<EventChannel<CollisionEvent>>() .register_reader(), ); } }
al.translation().clone(); if pos.x > bounds.right { local.translation_mut().x = bounds.right; } else if pos.x < bounds.left { local.translation_mut().x = bounds.left; }
function_block-random_span
[ { "content": "// Once the prefabs are loaded, this function is called to update the ekeys in the CreaturePrefabs struct.\n\n// We use the Named component of the entity to determine which key to use.\n\npub fn update_prefabs(world: &mut World) {\n\n let updated_prefabs = {\n\n let creature_prefabs = wo...
Rust
src/operation/aggregate/change_stream.rs
moy2010/mongo-rust-driver
dc085119dac3943773115bf4a0f923d17156dd06
use crate::{ bson::{doc, Document}, change_stream::{event::ResumeToken, ChangeStreamData, WatchArgs}, cmap::{Command, RawCommandResponse, StreamDescription}, cursor::CursorSpecification, error::Result, operation::{append_options, Operation, Retryability}, options::{ChangeStreamOptions, SelectionCriteria, WriteConcern}, }; use super::Aggregate; pub(crate) struct ChangeStreamAggregate { inner: Aggregate, args: WatchArgs, resume_data: Option<ChangeStreamData>, } impl ChangeStreamAggregate { pub(crate) fn new(args: &WatchArgs, resume_data: Option<ChangeStreamData>) -> Result<Self> { Ok(Self { inner: Self::build_inner(args)?, args: args.clone(), resume_data, }) } fn build_inner(args: &WatchArgs) -> Result<Aggregate> { let mut bson_options = Document::new(); append_options(&mut bson_options, args.options.as_ref())?; let mut agg_pipeline = vec![doc! { "$changeStream": bson_options }]; agg_pipeline.extend(args.pipeline.iter().cloned()); Ok(Aggregate::new( args.target.clone(), agg_pipeline, args.options.as_ref().map(|o| o.aggregate_options()), )) } } impl Operation for ChangeStreamAggregate { type O = (CursorSpecification, ChangeStreamData); type Command = Document; const NAME: &'static str = "aggregate"; fn build(&mut self, description: &StreamDescription) -> Result<Command> { if let Some(data) = &mut self.resume_data { let mut new_opts = self.args.options.clone().unwrap_or_default(); if let Some(token) = data.resume_token.take() { if new_opts.start_after.is_some() && !data.document_returned { new_opts.start_after = Some(token); new_opts.start_at_operation_time = None; } else { new_opts.resume_after = Some(token); new_opts.start_after = None; new_opts.start_at_operation_time = None; } } else { let saved_time = new_opts .start_at_operation_time .as_ref() .or_else(|| data.initial_operation_time.as_ref()); if saved_time.is_some() && description.max_wire_version.map_or(false, |v| v >= 7) { new_opts.start_at_operation_time = saved_time.cloned(); } } self.inner = Self::build_inner(&WatchArgs { options: Some(new_opts), ..self.args.clone() })?; } self.inner.build(description) } fn extract_at_cluster_time( &self, response: &bson::RawDocument, ) -> Result<Option<bson::Timestamp>> { self.inner.extract_at_cluster_time(response) } fn handle_response( &self, response: RawCommandResponse, description: &StreamDescription, ) -> Result<Self::O> { let op_time = response .raw_body() .get("operationTime")? .and_then(bson::RawBsonRef::as_timestamp); let spec = self.inner.handle_response(response, description)?; let mut data = ChangeStreamData { resume_token: ResumeToken::initial(self.args.options.as_ref(), &spec), ..ChangeStreamData::default() }; let has_no_time = |o: &ChangeStreamOptions| { o.start_at_operation_time.is_none() && o.resume_after.is_none() && o.start_after.is_none() }; if self.args.options.as_ref().map_or(true, has_no_time) && description.max_wire_version.map_or(false, |v| v >= 7) && spec.initial_buffer.is_empty() && spec.post_batch_resume_token.is_none() { data.initial_operation_time = op_time; } Ok((spec, data)) } fn selection_criteria(&self) -> Option<&SelectionCriteria> { self.inner.selection_criteria() } fn supports_read_concern(&self, description: &StreamDescription) -> bool { self.inner.supports_read_concern(description) } fn write_concern(&self) -> Option<&WriteConcern> { self.inner.write_concern() } fn retryability(&self) -> Retryability { self.inner.retryability() } }
use crate::{ bson::{doc, Document}, change_stream::{event::ResumeToken, ChangeStreamData, WatchArgs}, cmap::{Command, RawCommandResponse, StreamDescription}, cursor::CursorSpecification, error::Result, operation::{append_options, Operation, Retryability}, options::{ChangeStreamOptions, SelectionCriteria, WriteConcern}, }; use super::Aggregate; pub(crate) struct ChangeStreamAggregate { inner: Aggregate, args: WatchArgs, resume_data: Option<ChangeStreamData>, } impl ChangeStreamAggregate { pub(crate) fn new(args: &WatchArgs, resume_data: Option<ChangeStreamData>) -> Result<Self> { Ok(Self { inner: Self::build_inner(args)?, args: args.clone(), resume_data, }) } fn build_inner(args: &WatchArgs) -> Result<Aggregate> { let mut bson_options = Document::new(); append_options(&mut bson_options, args.options.as_ref())?; let mut agg_pipeline = vec![doc! { "$changeStream": bson_options }]; agg_pipeline.extend(args.pipeline.iter().cloned()); Ok(Aggregate::new( args.target.clone(), agg_pipeline, args.options.as_ref().map(|o| o.aggregate_options()), )) } } impl Operation for ChangeStreamAggregate { type O = (CursorSpecification, ChangeStreamData); type Command = Document; const NAME: &'static str = "aggregate"; fn build(&mut self, description: &StreamDescription) -> Result<Command> { if let Some(data) = &mut self.resume_data { let mut new_opts = self.args.options.clone().unwrap_or_default(); if let Some(token) = data.resume_token.take() { if new_opts.start_after.is_some() && !data.document_returned { new_opts.start_after = Some(token); new_opts.start_at_operation_time = None; } else { new_opts.resume_after = Some(token); new_opts.start_after = None; new_opts.start_at_operation_time = None; } } else { let saved_time = new_opts .start_at_operation_time .as_ref() .or_else(|| data.initial_operation_time.as_ref()); if saved_time.is_some() && description.max_wire_version.map_or(false, |v| v >= 7) { new_opts.start_at_operation_time = saved_time.cloned(); } } self.inner = Self::build_inner(&WatchArgs { options: Some(new_opts), ..self.args.clone() })?; } self.inner.build(description) }
fn handle_response( &self, response: RawCommandResponse, description: &StreamDescription, ) -> Result<Self::O> { let op_time = response .raw_body() .get("operationTime")? .and_then(bson::RawBsonRef::as_timestamp); let spec = self.inner.handle_response(response, description)?; let mut data = ChangeStreamData { resume_token: ResumeToken::initial(self.args.options.as_ref(), &spec), ..ChangeStreamData::default() }; let has_no_time = |o: &ChangeStreamOptions| { o.start_at_operation_time.is_none() && o.resume_after.is_none() && o.start_after.is_none() }; if self.args.options.as_ref().map_or(true, has_no_time) && description.max_wire_version.map_or(false, |v| v >= 7) && spec.initial_buffer.is_empty() && spec.post_batch_resume_token.is_none() { data.initial_operation_time = op_time; } Ok((spec, data)) } fn selection_criteria(&self) -> Option<&SelectionCriteria> { self.inner.selection_criteria() } fn supports_read_concern(&self, description: &StreamDescription) -> bool { self.inner.supports_read_concern(description) } fn write_concern(&self) -> Option<&WriteConcern> { self.inner.write_concern() } fn retryability(&self) -> Retryability { self.inner.retryability() } }
fn extract_at_cluster_time( &self, response: &bson::RawDocument, ) -> Result<Option<bson::Timestamp>> { self.inner.extract_at_cluster_time(response) }
function_block-full_function
[ { "content": "fn build_test(db_name: &str, mut list_collections: ListCollections, mut expected_body: Document) {\n\n let mut cmd = list_collections\n\n .build(&StreamDescription::new_testing())\n\n .expect(\"build should succeed\");\n\n assert_eq!(cmd.name, \"listCollections\");\n\n asser...
Rust
sync/src/synchronizer/headers_process.rs
Taem42/ckb
9d43dee13a350fe75f62b75915c3c932f129a3f5
use crate::block_status::BlockStatus; use crate::synchronizer::Synchronizer; use crate::types::{ActiveChain, SyncShared}; use crate::{Status, StatusCode, MAX_HEADERS_LEN}; use ckb_error::{Error, ErrorKind}; use ckb_logger::{debug, log_enabled, warn, Level}; use ckb_network::{CKBProtocolContext, PeerIndex}; use ckb_traits::BlockMedianTimeContext; use ckb_types::{ core::{self, BlockNumber}, packed::{self, Byte32}, prelude::*, }; use ckb_verification::{HeaderError, HeaderErrorKind, HeaderResolver, HeaderVerifier, Verifier}; pub struct HeadersProcess<'a> { message: packed::SendHeadersReader<'a>, synchronizer: &'a Synchronizer, peer: PeerIndex, nc: &'a dyn CKBProtocolContext, active_chain: ActiveChain, } pub struct VerifierResolver<'a> { shared: &'a SyncShared, header: &'a core::HeaderView, parent: Option<&'a core::HeaderView>, } impl<'a> VerifierResolver<'a> { pub fn new( parent: Option<&'a core::HeaderView>, header: &'a core::HeaderView, shared: &'a SyncShared, ) -> Self { VerifierResolver { parent, header, shared, } } } impl<'a> ::std::clone::Clone for VerifierResolver<'a> { fn clone(&self) -> Self { VerifierResolver { parent: self.parent, header: self.header, shared: self.shared, } } } impl<'a> BlockMedianTimeContext for VerifierResolver<'a> { fn median_block_count(&self) -> u64 { self.shared.consensus().median_time_block_count() as u64 } fn timestamp_and_parent(&self, block_hash: &Byte32) -> (u64, BlockNumber, Byte32) { let header = self .shared .get_header(&block_hash) .expect("[VerifierResolver] blocks used for median time exist"); ( header.timestamp(), header.number(), header.data().raw().parent_hash(), ) } } impl<'a> HeaderResolver for VerifierResolver<'a> { fn header(&self) -> &core::HeaderView { self.header } fn parent(&self) -> Option<&core::HeaderView> { self.parent } } impl<'a> HeadersProcess<'a> { pub fn new( message: packed::SendHeadersReader<'a>, synchronizer: &'a Synchronizer, peer: PeerIndex, nc: &'a dyn CKBProtocolContext, ) -> Self { let active_chain = synchronizer.shared.active_chain(); HeadersProcess { message, nc, synchronizer, peer, active_chain, } } fn is_continuous(&self, headers: &[core::HeaderView]) -> bool { for window in headers.windows(2) { if let [parent, header] = &window { if header.data().raw().parent_hash() != parent.hash() { debug!( "header.parent_hash {} parent.hash {}", header.parent_hash(), parent.hash() ); return false; } } } true } pub fn accept_first(&self, first: &core::HeaderView) -> ValidationResult { let shared = self.synchronizer.shared(); let parent = shared.get_header(&first.data().raw().parent_hash()); let resolver = VerifierResolver::new(parent.as_ref(), &first, &shared); let verifier = HeaderVerifier::new(&resolver, &shared.consensus()); let acceptor = HeaderAcceptor::new( first, self.peer, resolver.clone(), verifier, self.active_chain.clone(), ); acceptor.accept() } pub fn execute(self) -> Status { debug!("HeadersProcess begin"); let shared = self.synchronizer.shared(); let headers = self .message .headers() .to_entity() .into_iter() .map(packed::Header::into_view) .collect::<Vec<_>>(); if headers.len() > MAX_HEADERS_LEN { shared.state().misbehavior(self.peer, 20); warn!("HeadersProcess is_oversize"); return Status::ok(); } if headers.is_empty() { self.synchronizer .peers() .state .write() .get_mut(&self.peer) .expect("Peer must exists") .headers_sync_timeout = None; debug!("HeadersProcess is_empty (synchronized)"); return Status::ok(); } if !self.is_continuous(&headers) { shared.state().misbehavior(self.peer, 20); debug!("HeadersProcess is not continuous"); return Status::ok(); } let result = self.accept_first(&headers[0]); if !result.is_valid() { if result.misbehavior > 0 { shared.state().misbehavior(self.peer, result.misbehavior); } debug!( "HeadersProcess accept_first is_valid {:?} headers = {:?}", result, headers[0] ); return Status::ok(); } for window in headers.windows(2) { if let [parent, header] = &window { let resolver = VerifierResolver::new(Some(&parent), &header, &shared); let verifier = HeaderVerifier::new(&resolver, &shared.consensus()); let acceptor = HeaderAcceptor::new( &header, self.peer, resolver.clone(), verifier, self.active_chain.clone(), ); let result = acceptor.accept(); if !result.is_valid() { if result.misbehavior > 0 { shared.state().misbehavior(self.peer, result.misbehavior); } debug!("HeadersProcess accept is invalid {:?}", result); return Status::ok(); } } } if log_enabled!(Level::Debug) { let shared_best_known = self.synchronizer.shared.state().shared_best_header(); let peer_best_known = self.synchronizer.peers().get_best_known_header(self.peer); debug!( "chain: num={}, diff={:#x};", self.active_chain.tip_number(), self.active_chain.total_difficulty() ); debug!( "shared best_known_header: num={}, diff={:#x}, hash={};", shared_best_known.number(), shared_best_known.total_difficulty(), shared_best_known.hash(), ); if let Some(header) = peer_best_known { debug!( "peer's best_known_header: peer: {}, num={}; diff={:#x}, hash={};", self.peer, header.number(), header.total_difficulty(), header.hash() ); } else { debug!("state: null;"); } debug!("peer: {}", self.peer); } if headers.len() == MAX_HEADERS_LEN { let start = headers.last().expect("empty checked"); self.active_chain .send_getheaders_to_peer(self.nc, self.peer, start); } let peer_flags = self .synchronizer .peers() .state .read() .get(&self.peer) .map(|state| state.peer_flags) .unwrap_or_default(); if self.active_chain.is_initial_block_download() && headers.len() != MAX_HEADERS_LEN && (!peer_flags.is_protect && !peer_flags.is_whitelist && peer_flags.is_outbound) { debug!("Disconnect peer({}) is unprotected outbound", self.peer); if let Err(err) = self .nc .disconnect(self.peer, "useless outbound peer in IBD") { return StatusCode::Network.with_context(format!("Disconnect error: {:?}", err)); } } Status::ok() } } #[derive(Clone)] pub struct HeaderAcceptor<'a, V: Verifier> { header: &'a core::HeaderView, active_chain: ActiveChain, peer: PeerIndex, resolver: V::Target, verifier: V, } impl<'a, V> HeaderAcceptor<'a, V> where V: Verifier<Target = VerifierResolver<'a>>, { pub fn new( header: &'a core::HeaderView, peer: PeerIndex, resolver: VerifierResolver<'a>, verifier: V, active_chain: ActiveChain, ) -> Self { HeaderAcceptor { header, peer, resolver, verifier, active_chain, } } pub fn prev_block_check(&self, state: &mut ValidationResult) -> Result<(), ()> { if self.active_chain.contains_block_status( &self.header.data().raw().parent_hash(), BlockStatus::BLOCK_INVALID, ) { state.dos(Some(ValidationError::InvalidParent), 100); return Err(()); } Ok(()) } pub fn non_contextual_check(&self, state: &mut ValidationResult) -> Result<(), ()> { self.verifier.verify(&self.resolver).map_err(|error| { debug!( "HeadersProcess accept {:?} error {:?}", self.header.number(), error ); if error.kind() == &ErrorKind::Header { let header_error = error .downcast_ref::<HeaderError>() .expect("error kind checked"); match header_error.kind() { HeaderErrorKind::Pow => state.dos(Some(ValidationError::Verify(error)), 100), HeaderErrorKind::Epoch => state.dos(Some(ValidationError::Verify(error)), 50), _ => state.invalid(Some(ValidationError::Verify(error))), } } else { state.invalid(Some(ValidationError::Verify(error))); } }) } pub fn version_check(&self, state: &mut ValidationResult) -> Result<(), ()> { if self.header.version() != 0 { state.invalid(Some(ValidationError::Version)); Err(()) } else { Ok(()) } } pub fn accept(&self) -> ValidationResult { let mut result = ValidationResult::default(); let shared = self.active_chain.shared(); let state = shared.state(); if self .active_chain .contains_block_status(&self.header.hash(), BlockStatus::HEADER_VALID) { let header_view = shared .get_header_view(&self.header.hash()) .expect("header with HEADER_VALID should exist"); state.peers().new_header_received(self.peer, &header_view); return result; } if self.prev_block_check(&mut result).is_err() { debug!( "HeadersProcess reject invalid-parent header: {} {}", self.header.number(), self.header.hash(), ); state.insert_block_status(self.header.hash(), BlockStatus::BLOCK_INVALID); return result; } if self.non_contextual_check(&mut result).is_err() { debug!( "HeadersProcess reject non-contextual header: {} {}", self.header.number(), self.header.hash(), ); state.insert_block_status(self.header.hash(), BlockStatus::BLOCK_INVALID); return result; } if self.version_check(&mut result).is_err() { debug!( "HeadersProcess reject invalid-version header {} {}", self.header.number(), self.header.hash(), ); state.insert_block_status(self.header.hash(), BlockStatus::BLOCK_INVALID); return result; } shared.insert_valid_header(self.peer, &self.header); result } } #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub enum ValidationState { VALID, INVALID, } impl Default for ValidationState { fn default() -> Self { ValidationState::VALID } } #[derive(Debug)] pub enum ValidationError { Verify(Error), Version, InvalidParent, } #[derive(Debug, Default)] pub struct ValidationResult { pub error: Option<ValidationError>, pub misbehavior: u32, pub state: ValidationState, } impl ValidationResult { pub fn invalid(&mut self, error: Option<ValidationError>) { self.dos(error, 0); } pub fn dos(&mut self, error: Option<ValidationError>, misbehavior: u32) { self.error = error; self.misbehavior += misbehavior; self.state = ValidationState::INVALID; } pub fn is_valid(&self) -> bool { self.state == ValidationState::VALID } }
use crate::block_status::BlockStatus; use crate::synchronizer::Synchronizer; use crate::types::{ActiveChain, SyncShared}; use crate::{Status, StatusCode, MAX_HEADERS_LEN}; use ckb_error::{Error, ErrorKind}; use ckb_logger::{debug, log_enabled, warn, Level}; use ckb_network::{CKBProtocolContext, PeerIndex}; use ckb_traits::BlockMedianTimeContext; use ckb_types::{ core::{self, BlockNumber}, packed::{self, Byte32}, prelude::*, }; use ckb_verification::{HeaderError, HeaderErrorKind, HeaderResolver, HeaderVerifier, Verifier}; pub struct HeadersProcess<'a> { message: packed::SendHeadersReader<'a>, synchronizer: &'a Synchronizer, peer: PeerIndex, nc: &'a dyn CKBProtocolContext, active_chain: ActiveChain, } pub struct VerifierResolver<'a> { shared: &'a SyncShared, header: &'a core::HeaderView, parent: Option<&'a core::HeaderView>, } impl<'a> VerifierResolver<'a> { pub fn new( parent: Option<&'a core::HeaderView>, header: &'a core::HeaderView, shared: &'a SyncShared, ) -> Self { VerifierResolver { parent, header, shared, } } } impl<'a> ::std::clone::Clone for VerifierResolver<'a> { fn clone(&self) -> Self { VerifierResolver { parent: self.parent, header: self.header, shared: self.shared, } } } impl<'a> BlockMedianTimeContext for VerifierResolver<'a> { fn median_block_count(&self) -> u64 { self.shared.consensus().median_time_block_count() as u64 } fn timestamp_and_parent(&self, block_hash: &Byte32) -> (u64, BlockNumber, Byte32) { let header = self .shared .get_header(&block_hash) .expect("[VerifierResolver] blocks used for median time exist"); ( header.timestamp(), header.number(), header.data().raw().parent_hash(), ) } } impl<'a> HeaderResolver for VerifierResolver<'a> { fn header(&self) -> &core::HeaderView { self.header } fn parent(&self) -> Option<&core::HeaderView> { self.parent } } impl<'a> HeadersProcess<'a> { pub fn new( message: packed::SendHeadersReader<'a>, synchronizer: &'a Synchronizer, peer: PeerIndex, nc: &'a dyn CKBProtocolContext, ) -> Self { let active_chain = synchronizer.shared.active_chain(); HeadersProcess { message, nc, synchronizer, peer, active_chain, } } fn is_continuous(&self, headers: &[core::HeaderView]) -> bool { for window in headers.windows(2) { if let [parent, header] = &window { if header.data().raw().parent_hash() != parent.hash() { debug!( "header.parent_hash {} parent.hash {}", header.parent_hash(), parent.hash() ); return false; } } } true } pub fn accept_first(&self, first: &core::HeaderView) -> ValidationResult { let shared = self.synchronizer.shared(); let parent = shared.get_header(&first.data().raw().parent_hash()); let resolver = VerifierResolver::new(parent.as_ref(), &first, &shared); let verifier = HeaderVerifier::new(&resolver, &shared.consensus()); let acceptor = HeaderAcceptor::new( first, self.peer, resolver.clone(), verifier, self.active_chain.clone(), ); acceptor.accept() } pub fn execute(self) -> Status { debug!("HeadersProcess begin"); let shared = self.synchronizer.shared(); let headers = self .message .headers() .to_entity() .into_iter() .map(packed::Header::into_view) .collect::<Vec<_>>(); if headers.len() > MAX_HEADERS_LE
.nc .disconnect(self.peer, "useless outbound peer in IBD") { return StatusCode::Network.with_context(format!("Disconnect error: {:?}", err)); } } Status::ok() } } #[derive(Clone)] pub struct HeaderAcceptor<'a, V: Verifier> { header: &'a core::HeaderView, active_chain: ActiveChain, peer: PeerIndex, resolver: V::Target, verifier: V, } impl<'a, V> HeaderAcceptor<'a, V> where V: Verifier<Target = VerifierResolver<'a>>, { pub fn new( header: &'a core::HeaderView, peer: PeerIndex, resolver: VerifierResolver<'a>, verifier: V, active_chain: ActiveChain, ) -> Self { HeaderAcceptor { header, peer, resolver, verifier, active_chain, } } pub fn prev_block_check(&self, state: &mut ValidationResult) -> Result<(), ()> { if self.active_chain.contains_block_status( &self.header.data().raw().parent_hash(), BlockStatus::BLOCK_INVALID, ) { state.dos(Some(ValidationError::InvalidParent), 100); return Err(()); } Ok(()) } pub fn non_contextual_check(&self, state: &mut ValidationResult) -> Result<(), ()> { self.verifier.verify(&self.resolver).map_err(|error| { debug!( "HeadersProcess accept {:?} error {:?}", self.header.number(), error ); if error.kind() == &ErrorKind::Header { let header_error = error .downcast_ref::<HeaderError>() .expect("error kind checked"); match header_error.kind() { HeaderErrorKind::Pow => state.dos(Some(ValidationError::Verify(error)), 100), HeaderErrorKind::Epoch => state.dos(Some(ValidationError::Verify(error)), 50), _ => state.invalid(Some(ValidationError::Verify(error))), } } else { state.invalid(Some(ValidationError::Verify(error))); } }) } pub fn version_check(&self, state: &mut ValidationResult) -> Result<(), ()> { if self.header.version() != 0 { state.invalid(Some(ValidationError::Version)); Err(()) } else { Ok(()) } } pub fn accept(&self) -> ValidationResult { let mut result = ValidationResult::default(); let shared = self.active_chain.shared(); let state = shared.state(); if self .active_chain .contains_block_status(&self.header.hash(), BlockStatus::HEADER_VALID) { let header_view = shared .get_header_view(&self.header.hash()) .expect("header with HEADER_VALID should exist"); state.peers().new_header_received(self.peer, &header_view); return result; } if self.prev_block_check(&mut result).is_err() { debug!( "HeadersProcess reject invalid-parent header: {} {}", self.header.number(), self.header.hash(), ); state.insert_block_status(self.header.hash(), BlockStatus::BLOCK_INVALID); return result; } if self.non_contextual_check(&mut result).is_err() { debug!( "HeadersProcess reject non-contextual header: {} {}", self.header.number(), self.header.hash(), ); state.insert_block_status(self.header.hash(), BlockStatus::BLOCK_INVALID); return result; } if self.version_check(&mut result).is_err() { debug!( "HeadersProcess reject invalid-version header {} {}", self.header.number(), self.header.hash(), ); state.insert_block_status(self.header.hash(), BlockStatus::BLOCK_INVALID); return result; } shared.insert_valid_header(self.peer, &self.header); result } } #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub enum ValidationState { VALID, INVALID, } impl Default for ValidationState { fn default() -> Self { ValidationState::VALID } } #[derive(Debug)] pub enum ValidationError { Verify(Error), Version, InvalidParent, } #[derive(Debug, Default)] pub struct ValidationResult { pub error: Option<ValidationError>, pub misbehavior: u32, pub state: ValidationState, } impl ValidationResult { pub fn invalid(&mut self, error: Option<ValidationError>) { self.dos(error, 0); } pub fn dos(&mut self, error: Option<ValidationError>, misbehavior: u32) { self.error = error; self.misbehavior += misbehavior; self.state = ValidationState::INVALID; } pub fn is_valid(&self) -> bool { self.state == ValidationState::VALID } }
N { shared.state().misbehavior(self.peer, 20); warn!("HeadersProcess is_oversize"); return Status::ok(); } if headers.is_empty() { self.synchronizer .peers() .state .write() .get_mut(&self.peer) .expect("Peer must exists") .headers_sync_timeout = None; debug!("HeadersProcess is_empty (synchronized)"); return Status::ok(); } if !self.is_continuous(&headers) { shared.state().misbehavior(self.peer, 20); debug!("HeadersProcess is not continuous"); return Status::ok(); } let result = self.accept_first(&headers[0]); if !result.is_valid() { if result.misbehavior > 0 { shared.state().misbehavior(self.peer, result.misbehavior); } debug!( "HeadersProcess accept_first is_valid {:?} headers = {:?}", result, headers[0] ); return Status::ok(); } for window in headers.windows(2) { if let [parent, header] = &window { let resolver = VerifierResolver::new(Some(&parent), &header, &shared); let verifier = HeaderVerifier::new(&resolver, &shared.consensus()); let acceptor = HeaderAcceptor::new( &header, self.peer, resolver.clone(), verifier, self.active_chain.clone(), ); let result = acceptor.accept(); if !result.is_valid() { if result.misbehavior > 0 { shared.state().misbehavior(self.peer, result.misbehavior); } debug!("HeadersProcess accept is invalid {:?}", result); return Status::ok(); } } } if log_enabled!(Level::Debug) { let shared_best_known = self.synchronizer.shared.state().shared_best_header(); let peer_best_known = self.synchronizer.peers().get_best_known_header(self.peer); debug!( "chain: num={}, diff={:#x};", self.active_chain.tip_number(), self.active_chain.total_difficulty() ); debug!( "shared best_known_header: num={}, diff={:#x}, hash={};", shared_best_known.number(), shared_best_known.total_difficulty(), shared_best_known.hash(), ); if let Some(header) = peer_best_known { debug!( "peer's best_known_header: peer: {}, num={}; diff={:#x}, hash={};", self.peer, header.number(), header.total_difficulty(), header.hash() ); } else { debug!("state: null;"); } debug!("peer: {}", self.peer); } if headers.len() == MAX_HEADERS_LEN { let start = headers.last().expect("empty checked"); self.active_chain .send_getheaders_to_peer(self.nc, self.peer, start); } let peer_flags = self .synchronizer .peers() .state .read() .get(&self.peer) .map(|state| state.peer_flags) .unwrap_or_default(); if self.active_chain.is_initial_block_download() && headers.len() != MAX_HEADERS_LEN && (!peer_flags.is_protect && !peer_flags.is_whitelist && peer_flags.is_outbound) { debug!("Disconnect peer({}) is unprotected outbound", self.peer); if let Err(err) = self
random
[ { "content": "pub fn inherit_block(shared: &Shared, parent_hash: &Byte32) -> BlockBuilder {\n\n let snapshot = shared.snapshot();\n\n let parent = snapshot.get_block(parent_hash).unwrap();\n\n let parent_epoch = snapshot.get_block_epoch(parent_hash).unwrap();\n\n let parent_number = parent.header()....
Rust
src/linux/mod.rs
8176135/InputBot
e54b3a04cccbcdead0141a42688d2cf7e89fd6d4
use crate::{common::*, linux::inputs::*, public::*}; use input::{ event::{ keyboard::{ KeyState, {KeyboardEvent, KeyboardEventTrait}, }, pointer::{ButtonState, PointerEvent::*}, Event::{self, *}, }, Libinput, LibinputInterface, }; use nix::{ fcntl::{open, OFlag}, sys::stat::Mode, unistd::close, }; use std::{ os::unix::io::RawFd, path::Path, thread::sleep, time::Duration, ptr::null, mem::MaybeUninit, }; use uinput::event::{controller::{Controller, Mouse}, Event as UinputEvent, relative::Position}; use x11::xlib::*; use once_cell::sync::Lazy; mod inputs; type ButtonStatesMap = HashMap<MouseButton, bool>; type KeyStatesMap = HashMap<KeybdKey, bool>; static BUTTON_STATES: Lazy<Mutex<ButtonStatesMap>> = Lazy::new(|| Mutex::new(ButtonStatesMap::new())); static KEY_STATES: Lazy<Mutex<KeyStatesMap>> = Lazy::new(|| Mutex::new(KeyStatesMap::new())); static SEND_DISPLAY: Lazy<AtomicPtr<Display>> = Lazy::new(|| { unsafe { XInitThreads() }; AtomicPtr::new(unsafe { XOpenDisplay(null()) }) }); static FAKE_DEVICE: Lazy<Mutex<uinput::Device>> = Lazy::new(|| { Mutex::new( uinput::default() .unwrap() .name("inputbot") .unwrap() .event(uinput::event::Keyboard::All) .unwrap() .event(UinputEvent::Controller(Controller::Mouse(Mouse::Left))) .unwrap() .event(UinputEvent::Controller(Controller::Mouse(Mouse::Right))) .unwrap() .event(UinputEvent::Controller(Controller::Mouse(Mouse::Middle))) .unwrap() .event(UinputEvent::Controller(Controller::Mouse(Mouse::Side))) .unwrap() .event(UinputEvent::Controller(Controller::Mouse(Mouse::Extra))) .unwrap() .event(UinputEvent::Controller(Controller::Mouse(Mouse::Forward))) .unwrap() .event(UinputEvent::Controller(Controller::Mouse(Mouse::Back))) .unwrap() .event(UinputEvent::Controller(Controller::Mouse(Mouse::Task))) .unwrap() .event(Position::X) .unwrap() .event(Position::Y) .unwrap() .create() .unwrap(), ) }); pub fn init_device() { FAKE_DEVICE.lock().unwrap(); } impl KeybdKey { pub fn is_pressed(self) -> bool { *KEY_STATES.lock().unwrap().entry(self).or_insert(false) } pub fn press(self) { let mut device = FAKE_DEVICE.lock().unwrap(); device .write(0x01, key_to_scan_code(self), 1) .unwrap(); device.synchronize().unwrap(); } pub fn release(self) { let mut device = FAKE_DEVICE.lock().unwrap(); device .write(0x01, key_to_scan_code(self), 0) .unwrap(); device.synchronize().unwrap(); } pub fn is_toggled(self) -> bool { if let Some(key) = match self { KeybdKey::ScrollLockKey => Some(4), KeybdKey::NumLockKey => Some(2), KeybdKey::CapsLockKey => Some(1), _ => None, } { let mut state: XKeyboardState = unsafe { MaybeUninit::zeroed().assume_init() }; SEND_DISPLAY.with(|display| unsafe { XGetKeyboardControl(display, &mut state); }); state.led_mask & key != 0 } else { false } } } impl MouseButton { pub fn is_pressed(self) -> bool { *BUTTON_STATES.lock().unwrap().entry(self).or_insert(false) } pub fn press(self) { let mut device = FAKE_DEVICE.lock().unwrap(); device.press(&Controller::Mouse(Mouse::from(self))).unwrap(); device.synchronize().unwrap(); } pub fn release(self) { let mut device = FAKE_DEVICE.lock().unwrap(); device.release(&Controller::Mouse(Mouse::from(self))).unwrap(); device.synchronize().unwrap(); } } impl MouseCursor { pub fn move_rel(x: i32, y: i32) { SEND_DISPLAY.with(|display| unsafe { XWarpPointer(display, 0, 0, 0, 0, 0, 0, x, y); }); } pub fn move_abs(x: i32, y: i32) { SEND_DISPLAY.with(|display| unsafe { XWarpPointer(display, 0, XRootWindow(display, XDefaultScreen(display)), 0, 0, 0, 0, x, y); }); } } impl MouseWheel { pub fn scroll_ver(y: i32) { if y < 0 { MouseButton::OtherButton(4).press(); MouseButton::OtherButton(4).release(); } else { MouseButton::OtherButton(5).press(); MouseButton::OtherButton(5).release(); } } pub fn scroll_hor(x: i32) { if x < 0 { MouseButton::OtherButton(6).press(); MouseButton::OtherButton(6).release(); } else { MouseButton::OtherButton(7).press(); MouseButton::OtherButton(7).release(); } } } struct LibinputInterfaceRaw; impl LibinputInterfaceRaw { fn seat(&self) -> String { String::from("seat0") } } impl LibinputInterface for LibinputInterfaceRaw { fn open_restricted(&mut self, path: &Path, flags: i32) -> std::result::Result<RawFd, i32> { if let Ok(fd) = open(path, OFlag::from_bits_truncate(flags), Mode::empty()) { Ok(fd) } else { Err(1) } } fn close_restricted(&mut self, fd: RawFd) { let _ = close(fd); } } pub fn handle_input_events() { let mut libinput_context = Libinput::new_with_udev(LibinputInterfaceRaw); libinput_context .udev_assign_seat(&LibinputInterfaceRaw.seat()) .unwrap(); while !MOUSE_BINDS.lock().unwrap().is_empty() || !KEYBD_BINDS.lock().unwrap().is_empty() { libinput_context.dispatch().unwrap(); while let Some(event) = libinput_context.next() { handle_input_event(event); } sleep(Duration::from_millis(10)); } } fn handle_input_event(event: Event) { match event { Keyboard(keyboard_event) => { let KeyboardEvent::Key(keyboard_key_event) = keyboard_event; let key = keyboard_key_event.key(); if let Some(keybd_key) = scan_code_to_key(key) { if keyboard_key_event.key_state() == KeyState::Pressed { KEY_STATES.lock().unwrap().insert(keybd_key, true); if let Some(Bind::NormalBind(cb)) = KEYBD_BINDS.lock().unwrap().get(&keybd_key) { let cb = Arc::clone(cb); spawn(move || cb()); }; } else { KEY_STATES.lock().unwrap().insert(keybd_key, false); } } } Pointer(pointer_event) => { if let Button(button_event) = pointer_event { let button = button_event.button(); if let Some(mouse_button) = match button { 272 => Some(MouseButton::LeftButton), 273 => Some(MouseButton::RightButton), 274 => Some(MouseButton::MiddleButton), 275 => Some(MouseButton::X1Button), 276 => Some(MouseButton::X2Button), _ => None, } { if button_event.button_state() == ButtonState::Pressed { BUTTON_STATES.lock().unwrap().insert(mouse_button, true); if let Some(Bind::NormalBind(cb)) = MOUSE_BINDS.lock().unwrap().get(&mouse_button) { let cb = Arc::clone(cb); spawn(move || cb()); }; } else { BUTTON_STATES.lock().unwrap().insert(mouse_button, false); } } } } _ => {} } } trait DisplayAcquirable { fn with<F, Z>(&self, cb: F) -> Z where F: FnOnce(*mut Display) -> Z; } impl DisplayAcquirable for AtomicPtr<Display> { fn with<F, Z>(&self, cb: F) -> Z where F: FnOnce(*mut Display) -> Z, { let display = self.load(Ordering::Relaxed); unsafe { XLockDisplay(display); }; let cb_result = cb(display); unsafe { XFlush(display); XUnlockDisplay(display); }; cb_result } }
use crate::{common::*, linux::inputs::*, public::*}; use input::{ event::{ keyboard::{ KeyState, {KeyboardEvent, KeyboardEventTrait}, }, pointer::{ButtonState, PointerEvent::*}, Event::{self, *}, }, Libinput, LibinputInterface, }; use nix::{ fcntl::{open, OFlag}, sys::stat::Mode, unistd::close, }; use std::{ os::unix::io::RawFd, path::Path, thread::sleep, time::Duration, ptr::null, mem::MaybeUninit, }; use uinput::event::{controller::{Controller, Mouse}, Event as UinputEvent, relative::Position}; use x11::xlib::*; use once_cell::sync::Lazy; mod inputs; type ButtonStatesMap = HashMap<MouseButton, bool>; type KeyStatesMap = HashMap<KeybdKey, bool>; static BUTTON_STATES: Lazy<Mutex<ButtonStatesMap>> = Lazy::new(|| Mutex::new(ButtonStatesMap::new())); static KEY_STATES: Lazy<Mutex<KeyStatesMap>> = Lazy::new(|| Mutex::new(KeyStatesMap::new())); static SEND_DISPLAY: Lazy<AtomicPtr<Display>> = Lazy::new(|| { unsafe { XInitThreads() }; AtomicPtr::new(unsafe { XOpenDisplay(null()) }) }); static FAKE_DEVICE: Lazy<Mutex<uinput::Device>> = Lazy::new(|| { Mutex::new( uinput::default() .unwrap() .name("inputbot") .unwrap() .event(uinput::event::Keyboard::All) .unwrap() .event(UinputEvent::Controller(Controller::Mouse(Mouse::Left))) .unwrap() .event(UinputEvent::Controller(Controller::Mouse(Mouse::Right))) .unwrap() .event(UinputEvent::Controller(Controller::Mouse(Mouse::Middle))) .unwrap() .event(UinputEvent::Controller(Controller::Mouse(Mouse::Side))) .unwrap() .event(UinputEvent::Controller(Controller::Mouse(Mouse::Extra))) .unwrap() .event(UinputEvent::Controller(Controller::Mouse(Mouse::Forward))) .unwrap() .event(UinputEvent::Controller(Controller::Mouse(Mouse::Back))) .unwrap() .event(UinputEvent::Controller(Controller::Mouse(Mouse::Task))) .unwrap() .event(Position::X) .unwrap() .event(Position::Y) .unwrap() .create() .unwrap(), ) }); pub fn init_device() { FAKE_DEVICE.lock().unwrap(); } impl KeybdKey { pub fn is_pressed(self) -> bool { *KEY_STATES.lock().unwrap().entry(self).or_insert(false) } pub fn pre
&LibinputInterfaceRaw.seat()) .unwrap(); while !MOUSE_BINDS.lock().unwrap().is_empty() || !KEYBD_BINDS.lock().unwrap().is_empty() { libinput_context.dispatch().unwrap(); while let Some(event) = libinput_context.next() { handle_input_event(event); } sleep(Duration::from_millis(10)); } } fn handle_input_event(event: Event) { match event { Keyboard(keyboard_event) => { let KeyboardEvent::Key(keyboard_key_event) = keyboard_event; let key = keyboard_key_event.key(); if let Some(keybd_key) = scan_code_to_key(key) { if keyboard_key_event.key_state() == KeyState::Pressed { KEY_STATES.lock().unwrap().insert(keybd_key, true); if let Some(Bind::NormalBind(cb)) = KEYBD_BINDS.lock().unwrap().get(&keybd_key) { let cb = Arc::clone(cb); spawn(move || cb()); }; } else { KEY_STATES.lock().unwrap().insert(keybd_key, false); } } } Pointer(pointer_event) => { if let Button(button_event) = pointer_event { let button = button_event.button(); if let Some(mouse_button) = match button { 272 => Some(MouseButton::LeftButton), 273 => Some(MouseButton::RightButton), 274 => Some(MouseButton::MiddleButton), 275 => Some(MouseButton::X1Button), 276 => Some(MouseButton::X2Button), _ => None, } { if button_event.button_state() == ButtonState::Pressed { BUTTON_STATES.lock().unwrap().insert(mouse_button, true); if let Some(Bind::NormalBind(cb)) = MOUSE_BINDS.lock().unwrap().get(&mouse_button) { let cb = Arc::clone(cb); spawn(move || cb()); }; } else { BUTTON_STATES.lock().unwrap().insert(mouse_button, false); } } } } _ => {} } } trait DisplayAcquirable { fn with<F, Z>(&self, cb: F) -> Z where F: FnOnce(*mut Display) -> Z; } impl DisplayAcquirable for AtomicPtr<Display> { fn with<F, Z>(&self, cb: F) -> Z where F: FnOnce(*mut Display) -> Z, { let display = self.load(Ordering::Relaxed); unsafe { XLockDisplay(display); }; let cb_result = cb(display); unsafe { XFlush(display); XUnlockDisplay(display); }; cb_result } }
ss(self) { let mut device = FAKE_DEVICE.lock().unwrap(); device .write(0x01, key_to_scan_code(self), 1) .unwrap(); device.synchronize().unwrap(); } pub fn release(self) { let mut device = FAKE_DEVICE.lock().unwrap(); device .write(0x01, key_to_scan_code(self), 0) .unwrap(); device.synchronize().unwrap(); } pub fn is_toggled(self) -> bool { if let Some(key) = match self { KeybdKey::ScrollLockKey => Some(4), KeybdKey::NumLockKey => Some(2), KeybdKey::CapsLockKey => Some(1), _ => None, } { let mut state: XKeyboardState = unsafe { MaybeUninit::zeroed().assume_init() }; SEND_DISPLAY.with(|display| unsafe { XGetKeyboardControl(display, &mut state); }); state.led_mask & key != 0 } else { false } } } impl MouseButton { pub fn is_pressed(self) -> bool { *BUTTON_STATES.lock().unwrap().entry(self).or_insert(false) } pub fn press(self) { let mut device = FAKE_DEVICE.lock().unwrap(); device.press(&Controller::Mouse(Mouse::from(self))).unwrap(); device.synchronize().unwrap(); } pub fn release(self) { let mut device = FAKE_DEVICE.lock().unwrap(); device.release(&Controller::Mouse(Mouse::from(self))).unwrap(); device.synchronize().unwrap(); } } impl MouseCursor { pub fn move_rel(x: i32, y: i32) { SEND_DISPLAY.with(|display| unsafe { XWarpPointer(display, 0, 0, 0, 0, 0, 0, x, y); }); } pub fn move_abs(x: i32, y: i32) { SEND_DISPLAY.with(|display| unsafe { XWarpPointer(display, 0, XRootWindow(display, XDefaultScreen(display)), 0, 0, 0, 0, x, y); }); } } impl MouseWheel { pub fn scroll_ver(y: i32) { if y < 0 { MouseButton::OtherButton(4).press(); MouseButton::OtherButton(4).release(); } else { MouseButton::OtherButton(5).press(); MouseButton::OtherButton(5).release(); } } pub fn scroll_hor(x: i32) { if x < 0 { MouseButton::OtherButton(6).press(); MouseButton::OtherButton(6).release(); } else { MouseButton::OtherButton(7).press(); MouseButton::OtherButton(7).release(); } } } struct LibinputInterfaceRaw; impl LibinputInterfaceRaw { fn seat(&self) -> String { String::from("seat0") } } impl LibinputInterface for LibinputInterfaceRaw { fn open_restricted(&mut self, path: &Path, flags: i32) -> std::result::Result<RawFd, i32> { if let Ok(fd) = open(path, OFlag::from_bits_truncate(flags), Mode::empty()) { Ok(fd) } else { Err(1) } } fn close_restricted(&mut self, fd: RawFd) { let _ = close(fd); } } pub fn handle_input_events() { let mut libinput_context = Libinput::new_with_udev(LibinputInterfaceRaw); libinput_context .udev_assign_seat(
random
[ { "content": "pub fn handle_input_events() {\n\n if !MOUSE_BINDS.lock().unwrap().is_empty() {\n\n set_hook(WH_MOUSE_LL, &*MOUSE_HHOOK, mouse_proc);\n\n };\n\n if !KEYBD_BINDS.lock().unwrap().is_empty() {\n\n set_hook(WH_KEYBOARD_LL, &*KEYBD_HHOOK, keybd_proc);\n\n };\n\n let mut msg...
Rust
src/wayland/output/xdg.rs
rano-oss/smithay
a06e8b231e305cda37f68c63f872d468d673d598
use std::{ ops::Deref as _, sync::{Arc, Mutex}, }; use slog::{o, trace}; use wayland_protocols::unstable::xdg_output::v1::server::{ zxdg_output_manager_v1::{self, ZxdgOutputManagerV1}, zxdg_output_v1::ZxdgOutputV1, }; use wayland_server::{protocol::wl_output::WlOutput, Display, Filter, Global, Main}; use crate::utils::{Logical, Physical, Point, Size}; use super::{Mode, Output}; #[derive(Debug)] struct Inner { name: String, description: String, logical_position: Point<i32, Logical>, physical_size: Option<Size<i32, Physical>>, scale: i32, instances: Vec<ZxdgOutputV1>, _log: ::slog::Logger, } #[derive(Debug, Clone)] pub(super) struct XdgOutput { inner: Arc<Mutex<Inner>>, } impl XdgOutput { fn new(output: &super::Inner, log: ::slog::Logger) -> Self { trace!(log, "Creating new xdg_output"; "name" => &output.name); let description = format!( "{} - {} - {}", output.physical.make, output.physical.model, output.name ); let physical_size = output.current_mode.map(|mode| mode.size); Self { inner: Arc::new(Mutex::new(Inner { name: output.name.clone(), description, logical_position: output.location, physical_size, scale: output.scale, instances: Vec::new(), _log: log, })), } } fn add_instance(&self, xdg_output: Main<ZxdgOutputV1>, wl_output: &WlOutput) { let mut inner = self.inner.lock().unwrap(); xdg_output.logical_position(inner.logical_position.x, inner.logical_position.y); if let Some(size) = inner.physical_size { let logical_size = size.to_logical(inner.scale); xdg_output.logical_size(logical_size.w, logical_size.h); } if xdg_output.as_ref().version() >= 2 { xdg_output.name(inner.name.clone()); xdg_output.description(inner.description.clone()); } if xdg_output.as_ref().version() < 3 { xdg_output.done(); } wl_output.done(); xdg_output.quick_assign(|_, _, _| {}); xdg_output.assign_destructor(Filter::new(|xdg_output: ZxdgOutputV1, _, _| { let inner = &xdg_output.as_ref().user_data().get::<XdgOutput>().unwrap().inner; inner .lock() .unwrap() .instances .retain(|o| !o.as_ref().equals(xdg_output.as_ref())); })); xdg_output.as_ref().user_data().set_threadsafe({ let xdg_output = self.clone(); move || xdg_output }); inner.instances.push(xdg_output.deref().clone()); } pub(super) fn change_current_state( &self, new_mode: Option<Mode>, new_scale: Option<i32>, new_location: Option<Point<i32, Logical>>, ) { let mut output = self.inner.lock().unwrap(); if let Some(new_mode) = new_mode { output.physical_size = Some(new_mode.size); } if let Some(new_scale) = new_scale { output.scale = new_scale; } if let Some(new_location) = new_location { output.logical_position = new_location; } for instance in output.instances.iter() { if new_mode.is_some() | new_scale.is_some() { if let Some(size) = output.physical_size { let logical_size = size.to_logical(output.scale); instance.logical_size(logical_size.w, logical_size.h); } } if new_location.is_some() { instance.logical_position(output.logical_position.x, output.logical_position.y); } if instance.as_ref().version() < 3 { instance.done(); } } } } pub fn init_xdg_output_manager<L>(display: &mut Display, logger: L) -> Global<ZxdgOutputManagerV1> where L: Into<Option<::slog::Logger>>, { let log = crate::slog_or_fallback(logger).new(o!("smithay_module" => "xdg_output_handler")); display.create_global( 3, Filter::new(move |(manager, _version): (Main<ZxdgOutputManagerV1>, _), _, _| { let log = log.clone(); manager.quick_assign(move |_, req, _| match req { zxdg_output_manager_v1::Request::GetXdgOutput { id, output: wl_output, } => { let output = Output::from_resource(&wl_output).unwrap(); let mut inner = output.inner.0.lock().unwrap(); if inner.xdg_output.is_none() { inner.xdg_output = Some(XdgOutput::new(&inner, log.clone())); } inner.xdg_output.as_ref().unwrap().add_instance(id, &wl_output); } zxdg_output_manager_v1::Request::Destroy => { } _ => {} }); }), ) }
use std::{ ops::Deref as _, sync::{Arc, Mutex}, }; use slog::{o, trace}; use wayland_protocols::unstable::xdg_output::v1::server::{ zxdg_output_manager_v1::{self, ZxdgOutputManagerV1}, zxdg_output_v1::ZxdgOutputV1, }; use wayland_server::{protocol::wl_output::WlOutput, Display, Filter, Global, Main}; use crate::utils::{Logical, Physical, Point, Size}; use super::{Mode, Output}; #[derive(Debug)] struct Inner { name: String, description: String, logical_position: Point<i32, Logical>, physical_size: Option<Size<i32, Physical>>, scale: i32, instances: Vec<ZxdgOutputV1>, _log: ::slog::Logger, } #[derive(Debug, Clone)] pub(super) struct XdgOutput { inner: Arc<Mutex<Inner>>, } impl XdgOutput { fn new(output: &super::Inner, log: ::slog::Logger) -> Self { trace!(log, "Creating new xdg_output"; "name" => &output.name); let description = format!( "{} - {} - {}", output.physical.make, output.physical.model, output.name ); let physical_size = output.current_mode.map(|mode| mode.size); Self { inner: Arc::new(Mutex::new(Inner { name: output.name.clone(), description, logical_position: output.location, physical_size, scale: output.scale, instances: Vec::new(), _log: log, })), } } fn add_instance(&self, xdg_output: Main<ZxdgOutputV1>, wl_output: &WlOutput) { let mut inner = self.inner.lock().unwrap(); xdg_output.logical_position(inner.logical_position.x, inner.logical_position.y); if let Some(size) = inner.physical_size { let logical_size = size.to_logical(inner.scale); xdg_output.logical_size(logical_size.w, logical_size.h); } if xdg_output.as_ref().version() >= 2 { xdg_output.name(inner.name.clone()); xdg_output.description(inner.description.clone()); } if xdg_output.as_ref().version() < 3 { xdg_output.done(); } wl_output.done(); xdg_output.quick_assign(|_, _, _| {}); xdg_output.assign_destructor(Filter::new(|xdg_output: ZxdgOutputV1, _, _| { let inner = &xdg_output.as_ref().user_data().get::<XdgOutput>().unwrap().inner; inner .lock() .unwrap() .instances .retain(|o| !o.as_ref().equals(xdg_output.as_ref())); })); xdg_output.as_ref().user_data().set_threadsafe({ let xdg_output = self.clone(); move || xdg_output }); inner.instances.push(xdg_output.deref().clone()); } pub(super) fn change_current_state( &self, new_mode: Option<Mode>, new_scale: Option<i32>, new_location: Option<Point<i32, Logical>>, ) { let mut output = self.inner.lock().unwrap(); if let Some(new_mode) = new_mode { output.physical_size = Some(new_mode.size); } if let Some(new_scale) = new_scale { output.scale = new_scale; } if let Some(new_location) = new_location { output.logical_position = new_location; } for instance in output.instances.iter() { if new_mode.is_some() | new_scale.is_some() { if let Some(size) = output.physical_size { let logical_size = size.to_logical(output.scale); instance.logical_size(logical_size.w, logical_size.h); } } if new_location.is_some() { instance.logical_position(output.logical_position.x, output.logical_position.y); } if instance.as_ref().version() < 3 { instance.done(); } } } } pub fn init_xdg_output_manager<L>(display: &mut Display, logger: L) -> Global<ZxdgOutputManagerV1> where
L: Into<Option<::slog::Logger>>, { let log = crate::slog_or_fallback(logger).new(o!("smithay_module" => "xdg_output_handler")); display.create_global( 3, Filter::new(move |(manager, _version): (Main<ZxdgOutputManagerV1>, _), _, _| { let log = log.clone(); manager.quick_assign(move |_, req, _| match req { zxdg_output_manager_v1::Request::GetXdgOutput { id, output: wl_output, } => { let output = Output::from_resource(&wl_output).unwrap(); let mut inner = output.inner.0.lock().unwrap(); if inner.xdg_output.is_none() { inner.xdg_output = Some(XdgOutput::new(&inner, log.clone())); } inner.xdg_output.as_ref().unwrap().add_instance(id, &wl_output); } zxdg_output_manager_v1::Request::Destroy => { } _ => {} }); }), ) }
function_block-function_prefix_line
[ { "content": "/// Initialize a tablet manager global.\n\npub fn init_tablet_manager_global(display: &mut Display) -> Global<ZwpTabletManagerV2> {\n\n display.create_global::<ZwpTabletManagerV2, _>(\n\n MANAGER_VERSION,\n\n Filter::new(\n\n move |(manager, _version): (Main<ZwpTabletMa...
Rust
src/list.rs
mantono/giss
867d2143196e631a875207684c5be45abb3feae7
use crate::search::{GraphQLQuery, SearchIssues, SearchQuery, Type}; use crate::{ api::ApiError, cfg::Config, issue::{Issue, Root}, project::Project, sort::Sorting, AppErr, }; use crate::{user::Username, Target}; use core::fmt; use std::{ sync::mpsc::{SendError, SyncSender}, time::Instant, }; #[derive(Debug)] pub struct FilterConfig { assigned_only: bool, pull_requests: bool, review_requests: bool, issues: bool, labels: Vec<String>, project: Option<Project>, sorting: Sorting, search: Option<String>, state: StateFilter, limit: u32, } impl FilterConfig { pub fn types(&self) -> Vec<Type> { let mut types: Vec<Type> = Vec::with_capacity(3); if self.issues { types.push(Type::Issue) } if self.pull_requests { types.push(Type::PullRequest) } if self.review_requests { types.push(Type::ReviewRequest) } types } } impl From<&Config> for FilterConfig { fn from(cfg: &Config) -> Self { FilterConfig { assigned_only: cfg.assigned_only(), pull_requests: cfg.pulls(), review_requests: cfg.reviews(), labels: cfg.label(), project: cfg.project(), sorting: cfg.sorting(), search: cfg.search(), issues: cfg.issues(), state: cfg.state(), limit: cfg.limit(), } } } #[derive(Eq, PartialEq, Debug, Copy, Clone)] pub enum StateFilter { Open, Closed, All, } impl std::fmt::Display for StateFilter { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let output = match self { StateFilter::Open => "open", StateFilter::Closed => "closed", StateFilter::All => "all", }; write!(f, "{}", output) } } pub async fn list_issues( channel: SyncSender<Issue>, user: &Option<Username>, targets: &[Target], token: &str, config: &FilterConfig, ) -> Result<(), AppErr> { let user: Option<String> = user.clone().map(|u| u.0); log::debug!("Filter config: {:?}", config); let start = Instant::now(); let issues = async { if config.issues { req_and_send(Type::Issue, &channel, &user, targets, token, config).await?; } Ok::<(), AppErr>(()) }; let pulls = async { if config.pull_requests { req_and_send(Type::PullRequest, &channel, &user, targets, token, config).await?; } Ok::<(), AppErr>(()) }; let reviews = async { if config.review_requests { req_and_send(Type::ReviewRequest, &channel, &user, targets, token, config).await?; } Ok::<(), AppErr>(()) }; futures::try_join!(issues, pulls, reviews)?; let end = Instant::now(); let elapsed = end.duration_since(start); log::debug!("API execution took {:?}", elapsed); Ok(()) } async fn req_and_send( kind: Type, channel: &SyncSender<Issue>, user: &Option<String>, targets: &[Target], token: &str, config: &FilterConfig, ) -> Result<(), AppErr> { let query: SearchIssues = create_query(kind, &user, targets, config); let issues: Vec<Issue> = api_request(query, token).await?; for issue in issues { channel.send(issue)?; } Ok(()) } fn create_query(kind: Type, user: &Option<String>, targets: &[Target], config: &FilterConfig) -> SearchIssues { let assignee: Option<String> = match config.assigned_only { false => None, true => match kind { Type::Issue | Type::PullRequest => user.clone(), Type::ReviewRequest => None, }, }; let review_requested: Option<String> = match config.review_requests { false => None, true => match kind { Type::ReviewRequest => user.clone(), Type::Issue | Type::PullRequest => None, }, }; SearchIssues { archived: false, assignee, resource_type: Some(kind), review_requested, sort: config.sorting, state: config.state, labels: config.labels.clone(), project: config.project.clone(), targets: targets.to_vec(), search: config.search.clone(), limit: config.limit, } } impl From<SendError<Issue>> for AppErr { fn from(_: SendError<Issue>) -> Self { AppErr::ChannelError } } impl From<ApiError> for AppErr { fn from(err: ApiError) -> Self { log::error!("{:?}", err); match err { ApiError::NoResponse(_) => AppErr::ApiError, ApiError::Response(code) => match code { 429 => AppErr::RateLimited, _ => AppErr::ApiError, }, } } } async fn api_request(search: SearchIssues, token: &str) -> Result<Vec<Issue>, ApiError> { let query: GraphQLQuery = search.build(); let issues: Root = crate::api::v4::request(token, query).await?; let issues: Vec<Issue> = issues.data.search.edges.into_iter().map(|n| n.node).collect(); Ok(issues) }
use crate::search::{GraphQLQuery, SearchIssues, SearchQuery, Type}; use crate::{ api::ApiError, cfg::Config, issue::{Issue, Root}, project::Project, sort::Sorting, AppErr, }; use crate::{user::Username, Target}; use core::fmt; use std::{ sync::mpsc::{SendError, SyncSender}, time::Instant, }; #[derive(Debug)] pub struct FilterConfig { assigned_only: bool, pull_requests: bool, review_requests: bool, issues: bool, labels: Vec<String>, project: Option<Project>, sorting: Sorting, search: Option<String>, state: StateFilter, limit: u32, } impl FilterConfig { pub fn types(&self) -> Vec<Type> { let mut types: Vec<Type> = Vec::with_capacity(3); if self.issues { types.push(Type::Issue) } if self.pull_requests { types.push(Type::PullRequest) } if self.review_requests { types.push(Type::ReviewRequest) } types } } impl From<&Config> for FilterConfig { fn from(cfg: &Config) -> Self { FilterConfig { assigned_only: cfg.assigned_only(), pull_requests: cfg.pulls(), review_requests: cfg.reviews(), labels: cfg.label(), project: cfg.project(), sorting: cfg.sorting(), search: cfg.search(), issues: cfg.issues(), state: cfg.state(), limit: cfg.limit(), } } } #[derive(Eq, PartialEq, Debug, Copy, Clone)] pub enum StateFilter { Open, Closed, All, } impl std::fmt::Display for StateFilter { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let output = match self { StateFilter::Open => "open", StateFilter::Closed => "closed", StateFilter::All => "all", }; write!(f, "{}", output) } } pub async fn list_issues( channel: SyncSender<Issue>, user: &Option<Username>, targets: &[Target], token: &str, config: &FilterConfig, ) -> Result<(), AppErr> { let user: Option<String> = user.clone().map(|u| u.0); log::debug!("Filter config: {:?}", config); let start = Instant::now(); let issues = async { if config.issues { req_and_send(Type::Issue, &channel, &user, targets, token, config).await?; } Ok::<(), AppErr>(()) }; let pulls = async { if config.pull_requests { req_and_send(Type::PullRequest, &channel, &user, targets, token, config).await?; } Ok::<(), AppErr>(()) }; let reviews = async { if config.review_requests { req_and_send(Type::ReviewRequest, &channel, &user, targets, token, config).await?; } Ok::<(), AppErr>(()) }; futures::try_join!(issues, pulls, reviews)?; let end = Instant::now(); let elapsed = end.duration_since(start); log::debug!("API execution took {:?}", elapsed); Ok(()) } async fn req_and_send( kind: Type, channel: &SyncSender<Issue>, user: &Option<String>, targets: &[Target], token: &str, config: &FilterConfig, ) -> Result<(), AppErr> { let query: SearchIssues = create_query(kind, &user, targets, config); let issues: Vec<Issue> = api_request(query, token).await?; for issue in issues { channel.send(issue)?; } Ok(()) }
impl From<SendError<Issue>> for AppErr { fn from(_: SendError<Issue>) -> Self { AppErr::ChannelError } } impl From<ApiError> for AppErr { fn from(err: ApiError) -> Self { log::error!("{:?}", err); match err { ApiError::NoResponse(_) => AppErr::ApiError, ApiError::Response(code) => match code { 429 => AppErr::RateLimited, _ => AppErr::ApiError, }, } } } async fn api_request(search: SearchIssues, token: &str) -> Result<Vec<Issue>, ApiError> { let query: GraphQLQuery = search.build(); let issues: Root = crate::api::v4::request(token, query).await?; let issues: Vec<Issue> = issues.data.search.edges.into_iter().map(|n| n.node).collect(); Ok(issues) }
fn create_query(kind: Type, user: &Option<String>, targets: &[Target], config: &FilterConfig) -> SearchIssues { let assignee: Option<String> = match config.assigned_only { false => None, true => match kind { Type::Issue | Type::PullRequest => user.clone(), Type::ReviewRequest => None, }, }; let review_requested: Option<String> = match config.review_requests { false => None, true => match kind { Type::ReviewRequest => user.clone(), Type::Issue | Type::PullRequest => None, }, }; SearchIssues { archived: false, assignee, resource_type: Some(kind), review_requested, sort: config.sorting, state: config.state, labels: config.labels.clone(), project: config.project.clone(), targets: targets.to_vec(), search: config.search.clone(), limit: config.limit, } }
function_block-full_function
[ { "content": "fn save_username(token: &str, username: &str) -> Result<(), std::io::Error> {\n\n let token_hash: String = hash_token(token);\n\n let mut path: PathBuf = get_users_dir();\n\n std::fs::create_dir_all(&path)?;\n\n path.push(token_hash);\n\n let mut file: File = File::create(&path)?;\n...
Rust
osm2lanes/src/transform/tags_to_lanes/counts.rs
a-b-street/osm2lanes
e24d9762dc50f8d83b57f0a0737e2626823133a4
use super::{Infer, Oneway}; use crate::locale::Locale; use crate::tag::{Highway, TagKey, Tags}; use crate::transform::tags_to_lanes::modes::BusLaneCount; use crate::transform::{RoadWarnings, TagsToLanesMsg}; #[derive(Debug)] pub enum Counts { One, Directional { forward: Infer<usize>, backward: Infer<usize>, centre_turn_lane: Infer<bool>, }, } impl Counts { #[allow( clippy::integer_arithmetic, clippy::integer_division, clippy::too_many_lines )] pub(super) fn new( tags: &Tags, oneway: Oneway, highway: &Highway, centre_turn_lane: &CentreTurnLaneScheme, bus: &BusLaneCount, locale: &Locale, warnings: &mut RoadWarnings, ) -> Self { let lanes = LanesDirectionScheme::from_tags(tags, oneway, locale, warnings); let centre_turn_lane = match (lanes.both_ways, centre_turn_lane.some()) { (Some(()), None | Some(true)) => Infer::Direct(true), (None, Some(true)) => Infer::Calculated(true), (None, Some(false)) => Infer::Calculated(false), (None, None) => Infer::Default(false), (Some(()), Some(false)) => { warnings.push(TagsToLanesMsg::ambiguous_tags( tags.subset(&[LANES + "both_ways", CENTRE_TURN_LANE]), )); Infer::Default(true) }, }; let both_ways: usize = if centre_turn_lane.some().unwrap_or(false) { 1 } else { 0 }; if oneway.into() { if lanes.both_ways.is_some() || lanes.backward.is_some() { warnings.push(TagsToLanesMsg::ambiguous_tags(tags.subset(&[ "oneway", "lanes:both_ways", "lanes:backward", ]))); } if let Some(total) = lanes.total { let forward = total - both_ways - bus.backward; let result = Self::Directional { forward: Infer::Calculated(forward), backward: Infer::Calculated(bus.backward), centre_turn_lane, }; if lanes.forward.map_or(false, |direct| direct != forward) { warnings.push(TagsToLanesMsg::ambiguous_tags(tags.subset(&[ "oneway", "lanes", "lanes:forward", ]))); } result } else if let Some(f) = lanes.forward { Self::Directional { forward: Infer::Direct(f), backward: Infer::Default(0), centre_turn_lane, } } else { let assumed_forward = 1; Self::Directional { forward: Infer::Default(assumed_forward + bus.forward), backward: Infer::Default(0), centre_turn_lane, } } } else { match (lanes.total, lanes.forward, lanes.backward) { (Some(l), Some(f), Some(b)) => { if l != f + b + both_ways { warnings.push(TagsToLanesMsg::ambiguous_tags(tags.subset(&[ "lanes", "lanes:forward", "lanes:backward", "lanes:both_ways", "center_turn_lanes", ]))); } Self::Directional { forward: Infer::Direct(f), backward: Infer::Direct(b), centre_turn_lane, } }, (None, Some(f), Some(b)) => Self::Directional { forward: Infer::Direct(f), backward: Infer::Direct(b), centre_turn_lane, }, (Some(l), Some(f), None) => Self::Directional { forward: Infer::Direct(f), backward: Infer::Calculated(l - f - both_ways), centre_turn_lane, }, (Some(l), None, Some(b)) => Self::Directional { forward: Infer::Calculated(l - b - both_ways), backward: Infer::Direct(b), centre_turn_lane, }, (Some(1), None, None) => Self::One, (Some(l), None, None) => { if l % 2 == 0 && centre_turn_lane.some().unwrap_or(false) { Self::Directional { forward: Infer::Default(l / 2), backward: Infer::Default(l / 2), centre_turn_lane, } } else { let remaining_lanes = l - both_ways - bus.forward - bus.backward; if remaining_lanes % 2 != 0 { warnings.push(TagsToLanesMsg::ambiguous_str("Total lane count cannot be evenly divided between the forward and backward")); } let half = (remaining_lanes + 1) / 2; Self::Directional { forward: Infer::Default(half + bus.forward), backward: Infer::Default( remaining_lanes - half - both_ways + bus.backward, ), centre_turn_lane, } } }, (None, None, None) => { if locale.has_split_lanes(highway.r#type()) || bus.forward > 0 || bus.backward > 0 { Self::Directional { forward: Infer::Default(1 + bus.forward), backward: Infer::Default(1 + bus.backward), centre_turn_lane, } } else { Self::One } }, (None, _, _) => { if locale.has_split_lanes(highway.r#type()) { let forward = Infer::from(lanes.forward).or_default(1 + bus.forward); let backward = Infer::from(lanes.backward).or_default(1 + bus.forward); Self::Directional { forward, backward, centre_turn_lane, } } else { Self::One } }, } } } } const LANES: TagKey = TagKey::from("lanes"); pub(in crate::transform::tags_to_lanes) struct LanesDirectionScheme { total: Option<usize>, forward: Option<usize>, backward: Option<usize>, both_ways: Option<()>, } impl LanesDirectionScheme { pub fn from_tags( tags: &Tags, _oneway: Oneway, _locale: &Locale, warnings: &mut RoadWarnings, ) -> Self { let both_ways = tags .get_parsed(LANES + "both_ways", warnings) .filter(|&v: &usize| { if v == 1 { true } else { warnings.push(TagsToLanesMsg::unsupported( "lanes:both_ways must be 1", tags.subset(&[LANES + "both_ways"]), )); false } }) .map(|_v| {}); Self { total: tags.get_parsed(LANES, warnings), forward: tags.get_parsed(LANES + "forward", warnings), backward: tags.get_parsed(LANES + "backward", warnings), both_ways, } } } const CENTRE_TURN_LANE: TagKey = TagKey::from("centre_turn_lane"); pub(in crate::transform::tags_to_lanes) struct CentreTurnLaneScheme(pub Option<bool>); impl CentreTurnLaneScheme { pub fn from_tags( tags: &Tags, _oneway: Oneway, _locale: &Locale, warnings: &mut RoadWarnings, ) -> Self { if let Some(v) = tags.get(CENTRE_TURN_LANE) { warnings.push(TagsToLanesMsg::deprecated_tags( tags.subset(&[CENTRE_TURN_LANE]), )); match v { "yes" => Self(Some(true)), "no" => Self(Some(false)), _ => { warnings.push(TagsToLanesMsg::unsupported_tags( tags.subset(&[CENTRE_TURN_LANE]), )); Self(None) }, } } else { Self(None) } } pub fn some(&self) -> Option<bool> { self.0 } }
use super::{Infer, Oneway}; use crate::locale::Locale; use crate::tag::{Highway, TagKey, Tags}; use crate::transform::tags_to_lanes::modes::BusLaneCount; use crate::transform::{RoadWarnings, TagsToLanesMsg}; #[derive(Debug)] pub enum Counts { One, Directional { forward: Infer<usize>, backward: Infer<usize>, centre_turn_lane: Infer<bool>, }, } impl Counts { #[allow( clippy::integer_arithmetic, clippy::integer_division, clippy::too_many_lines )] pub(super) fn new( tags: &Tags, oneway: Oneway, highway: &Highway, centre_turn_lane: &CentreTurnLaneScheme, bus: &BusLaneCount, locale: &Locale, warnings: &mut RoadWarnings, ) -> Self { let lanes = LanesDirectionScheme::from_tags(tags, oneway, locale, warnings); let centre_turn_lane = match (lanes.both_ways, centre_turn_lane.some()) { (Some(()), None | Some(true)) => Infer::Direct(true), (None, Some(true)) => Infer::Calculated(true), (None, Some(false)) => Infer::Calculated(false), (None, None) => Infer::Default(false), (Some(()), Some(false)) => { warnings.push(TagsToLanesMsg::ambiguous_tags( tags.subset(&[LANES + "both_ways", CENTRE_TURN_LANE]), )); Infer::Default(true) }, }; let both_ways: usize = if centre_turn_lane.some().unwrap_or(false) { 1 } else { 0 }; if oneway.into() { if lanes.both_ways.is_some() || lanes.backward.is_some() { warnings.push(TagsToLanesMsg::ambiguous_tags(tags.subset(&[ "oneway",
l / 2), centre_turn_lane, } } else { let remaining_lanes = l - both_ways - bus.forward - bus.backward; if remaining_lanes % 2 != 0 { warnings.push(TagsToLanesMsg::ambiguous_str("Total lane count cannot be evenly divided between the forward and backward")); } let half = (remaining_lanes + 1) / 2; Self::Directional { forward: Infer::Default(half + bus.forward), backward: Infer::Default( remaining_lanes - half - both_ways + bus.backward, ), centre_turn_lane, } } }, (None, None, None) => { if locale.has_split_lanes(highway.r#type()) || bus.forward > 0 || bus.backward > 0 { Self::Directional { forward: Infer::Default(1 + bus.forward), backward: Infer::Default(1 + bus.backward), centre_turn_lane, } } else { Self::One } }, (None, _, _) => { if locale.has_split_lanes(highway.r#type()) { let forward = Infer::from(lanes.forward).or_default(1 + bus.forward); let backward = Infer::from(lanes.backward).or_default(1 + bus.forward); Self::Directional { forward, backward, centre_turn_lane, } } else { Self::One } }, } } } } const LANES: TagKey = TagKey::from("lanes"); pub(in crate::transform::tags_to_lanes) struct LanesDirectionScheme { total: Option<usize>, forward: Option<usize>, backward: Option<usize>, both_ways: Option<()>, } impl LanesDirectionScheme { pub fn from_tags( tags: &Tags, _oneway: Oneway, _locale: &Locale, warnings: &mut RoadWarnings, ) -> Self { let both_ways = tags .get_parsed(LANES + "both_ways", warnings) .filter(|&v: &usize| { if v == 1 { true } else { warnings.push(TagsToLanesMsg::unsupported( "lanes:both_ways must be 1", tags.subset(&[LANES + "both_ways"]), )); false } }) .map(|_v| {}); Self { total: tags.get_parsed(LANES, warnings), forward: tags.get_parsed(LANES + "forward", warnings), backward: tags.get_parsed(LANES + "backward", warnings), both_ways, } } } const CENTRE_TURN_LANE: TagKey = TagKey::from("centre_turn_lane"); pub(in crate::transform::tags_to_lanes) struct CentreTurnLaneScheme(pub Option<bool>); impl CentreTurnLaneScheme { pub fn from_tags( tags: &Tags, _oneway: Oneway, _locale: &Locale, warnings: &mut RoadWarnings, ) -> Self { if let Some(v) = tags.get(CENTRE_TURN_LANE) { warnings.push(TagsToLanesMsg::deprecated_tags( tags.subset(&[CENTRE_TURN_LANE]), )); match v { "yes" => Self(Some(true)), "no" => Self(Some(false)), _ => { warnings.push(TagsToLanesMsg::unsupported_tags( tags.subset(&[CENTRE_TURN_LANE]), )); Self(None) }, } } else { Self(None) } } pub fn some(&self) -> Option<bool> { self.0 } }
"lanes:both_ways", "lanes:backward", ]))); } if let Some(total) = lanes.total { let forward = total - both_ways - bus.backward; let result = Self::Directional { forward: Infer::Calculated(forward), backward: Infer::Calculated(bus.backward), centre_turn_lane, }; if lanes.forward.map_or(false, |direct| direct != forward) { warnings.push(TagsToLanesMsg::ambiguous_tags(tags.subset(&[ "oneway", "lanes", "lanes:forward", ]))); } result } else if let Some(f) = lanes.forward { Self::Directional { forward: Infer::Direct(f), backward: Infer::Default(0), centre_turn_lane, } } else { let assumed_forward = 1; Self::Directional { forward: Infer::Default(assumed_forward + bus.forward), backward: Infer::Default(0), centre_turn_lane, } } } else { match (lanes.total, lanes.forward, lanes.backward) { (Some(l), Some(f), Some(b)) => { if l != f + b + both_ways { warnings.push(TagsToLanesMsg::ambiguous_tags(tags.subset(&[ "lanes", "lanes:forward", "lanes:backward", "lanes:both_ways", "center_turn_lanes", ]))); } Self::Directional { forward: Infer::Direct(f), backward: Infer::Direct(b), centre_turn_lane, } }, (None, Some(f), Some(b)) => Self::Directional { forward: Infer::Direct(f), backward: Infer::Direct(b), centre_turn_lane, }, (Some(l), Some(f), None) => Self::Directional { forward: Infer::Direct(f), backward: Infer::Calculated(l - f - both_ways), centre_turn_lane, }, (Some(l), None, Some(b)) => Self::Directional { forward: Infer::Calculated(l - b - both_ways), backward: Infer::Direct(b), centre_turn_lane, }, (Some(1), None, None) => Self::One, (Some(l), None, None) => { if l % 2 == 0 && centre_turn_lane.some().unwrap_or(false) { Self::Directional { forward: Infer::Default(l / 2), backward: Infer::Default(
random
[ { "content": "fn set_cycleway(lanes: &[Lane], tags: &mut Tags, oneway: bool) -> Result<(), LanesToTagsMsg> {\n\n let left_cycle_lane: Option<Direction> = lanes\n\n .iter()\n\n .take_while(|lane| !lane.is_motor())\n\n .find(|lane| lane.is_bicycle())\n\n .and_then(Lane::direction);\...
Rust
src/options.rs
sunsided/realsense-rust
6908a3d6ca172b8d7f388c10434b1800ceefafbe
use crate::{ common::*, error::{ErrorChecker, Result as RsResult}, kind::Rs2Option, }; pub trait ToOptions { fn to_options(&self) -> RsResult<HashMap<Rs2Option, OptionHandle>> { let options_ptr = self.get_options_ptr(); unsafe { let list_ptr = { let mut checker = ErrorChecker::new(); let list_ptr = realsense_sys::rs2_get_options_list( options_ptr.as_ptr(), checker.inner_mut_ptr(), ); checker.check()?; list_ptr }; let len = { let mut checker = ErrorChecker::new(); let len = realsense_sys::rs2_get_options_list_size(list_ptr, checker.inner_mut_ptr()); checker.check()?; len }; let handles = (0..len) .map(|index| { let mut checker = ErrorChecker::new(); let val = realsense_sys::rs2_get_option_from_list( list_ptr, index, checker.inner_mut_ptr(), ); checker.check()?; let option = Rs2Option::from_u32(val).unwrap(); let handle = OptionHandle { ptr: options_ptr, option, }; RsResult::Ok((option, handle)) }) .collect::<RsResult<HashMap<_, _>>>()?; Ok(handles) } } fn get_options_ptr(&self) -> NonNull<realsense_sys::rs2_options>; } #[derive(Debug, Clone)] pub struct OptionHandle { ptr: NonNull<realsense_sys::rs2_options>, option: Rs2Option, } impl OptionHandle { pub fn get_value(&self) -> RsResult<f32> { unsafe { let mut checker = ErrorChecker::new(); let val = realsense_sys::rs2_get_option( self.ptr.as_ptr(), self.option as realsense_sys::rs2_option, checker.inner_mut_ptr(), ); checker.check()?; Ok(val) } } pub fn set_value(&self, value: f32) -> RsResult<()> { unsafe { let mut checker = ErrorChecker::new(); realsense_sys::rs2_set_option( self.ptr.as_ptr(), self.option as realsense_sys::rs2_option, value, checker.inner_mut_ptr(), ); checker.check()?; Ok(()) } } pub fn is_read_only(&self) -> RsResult<bool> { unsafe { let mut checker = ErrorChecker::new(); let val = realsense_sys::rs2_is_option_read_only( self.ptr.as_ptr(), self.option as realsense_sys::rs2_option, checker.inner_mut_ptr(), ); checker.check()?; Ok(val != 0) } } pub fn name<'a>(&'a self) -> RsResult<&'a str> { unsafe { let mut checker = ErrorChecker::new(); let ptr = realsense_sys::rs2_get_option_name( self.ptr.as_ptr(), self.option as realsense_sys::rs2_option, checker.inner_mut_ptr(), ); checker.check()?; let desc = CStr::from_ptr(ptr).to_str().unwrap(); Ok(desc) } } pub fn option_description<'a>(&'a self) -> RsResult<&'a str> { unsafe { let mut checker = ErrorChecker::new(); let ptr = realsense_sys::rs2_get_option_description( self.ptr.as_ptr(), self.option as realsense_sys::rs2_option, checker.inner_mut_ptr(), ); checker.check()?; let desc = CStr::from_ptr(ptr).to_str().unwrap(); Ok(desc) } } pub fn value_description<'a>(&'a self, value: f32) -> RsResult<&'a str> { unsafe { let mut checker = ErrorChecker::new(); let ptr = realsense_sys::rs2_get_option_value_description( self.ptr.as_ptr(), self.option as realsense_sys::rs2_option, value, checker.inner_mut_ptr(), ); checker.check()?; let desc = CStr::from_ptr(ptr).to_str().unwrap(); Ok(desc) } } }
use crate::{ common::*, error::{ErrorChecker, Result as RsResult}, kind::Rs2Option, }; pub trait ToOptions { fn to_options(&self) -> RsResult<HashMap<Rs2Option, OptionHandle>> { let options_ptr = self.get_options_ptr(); unsafe { let list_ptr = { let mut checker = ErrorChecker::new(); let list_ptr = realsense_sys::rs2_get_options_list( options_ptr.as_ptr(), checker.inner_mut_ptr(), ); checker.check()?; list_ptr }; let len = { let mut checker = ErrorChecker::new(); let le
let mut checker = ErrorChecker::new(); let val = realsense_sys::rs2_is_option_read_only( self.ptr.as_ptr(), self.option as realsense_sys::rs2_option, checker.inner_mut_ptr(), ); checker.check()?; Ok(val != 0) } } pub fn name<'a>(&'a self) -> RsResult<&'a str> { unsafe { let mut checker = ErrorChecker::new(); let ptr = realsense_sys::rs2_get_option_name( self.ptr.as_ptr(), self.option as realsense_sys::rs2_option, checker.inner_mut_ptr(), ); checker.check()?; let desc = CStr::from_ptr(ptr).to_str().unwrap(); Ok(desc) } } pub fn option_description<'a>(&'a self) -> RsResult<&'a str> { unsafe { let mut checker = ErrorChecker::new(); let ptr = realsense_sys::rs2_get_option_description( self.ptr.as_ptr(), self.option as realsense_sys::rs2_option, checker.inner_mut_ptr(), ); checker.check()?; let desc = CStr::from_ptr(ptr).to_str().unwrap(); Ok(desc) } } pub fn value_description<'a>(&'a self, value: f32) -> RsResult<&'a str> { unsafe { let mut checker = ErrorChecker::new(); let ptr = realsense_sys::rs2_get_option_value_description( self.ptr.as_ptr(), self.option as realsense_sys::rs2_option, value, checker.inner_mut_ptr(), ); checker.check()?; let desc = CStr::from_ptr(ptr).to_str().unwrap(); Ok(desc) } } }
n = realsense_sys::rs2_get_options_list_size(list_ptr, checker.inner_mut_ptr()); checker.check()?; len }; let handles = (0..len) .map(|index| { let mut checker = ErrorChecker::new(); let val = realsense_sys::rs2_get_option_from_list( list_ptr, index, checker.inner_mut_ptr(), ); checker.check()?; let option = Rs2Option::from_u32(val).unwrap(); let handle = OptionHandle { ptr: options_ptr, option, }; RsResult::Ok((option, handle)) }) .collect::<RsResult<HashMap<_, _>>>()?; Ok(handles) } } fn get_options_ptr(&self) -> NonNull<realsense_sys::rs2_options>; } #[derive(Debug, Clone)] pub struct OptionHandle { ptr: NonNull<realsense_sys::rs2_options>, option: Rs2Option, } impl OptionHandle { pub fn get_value(&self) -> RsResult<f32> { unsafe { let mut checker = ErrorChecker::new(); let val = realsense_sys::rs2_get_option( self.ptr.as_ptr(), self.option as realsense_sys::rs2_option, checker.inner_mut_ptr(), ); checker.check()?; Ok(val) } } pub fn set_value(&self, value: f32) -> RsResult<()> { unsafe { let mut checker = ErrorChecker::new(); realsense_sys::rs2_set_option( self.ptr.as_ptr(), self.option as realsense_sys::rs2_option, value, checker.inner_mut_ptr(), ); checker.check()?; Ok(()) } } pub fn is_read_only(&self) -> RsResult<bool> { unsafe {
random
[ { "content": "#[cfg(all(feature = \"with-image\", feature = \"with-nalgebra\"))]\n\nfn main() -> Result<()> {\n\n example::main()\n\n}\n\n\n", "file_path": "examples/capture_images.rs", "rank": 1, "score": 91129.60982840325 }, { "content": "fn main() -> Result<()> {\n\n println!(\"Look...
Rust
src/main.rs
mbaumfalk/scheme
a00669a59d127d24b7bab87c5abe369f7a2a8ddf
extern crate nom; use nom::{ branch::alt, bytes::streaming::{tag, take_until, take_while1}, character::streaming::{ anychar, char, digit1, hex_digit1, line_ending, multispace0, none_of, oct_digit1, }, combinator::opt, error::{Error, ErrorKind::Char}, multi::{many0, many1}, sequence::{delimited, preceded, terminated}, Err::{self, Incomplete}, IResult, }; use std::{ fmt, io::{self, BufRead, Write}, ops::Neg, }; #[derive(Debug)] enum LispData { Nil, Bool(bool), Num(i64), Symbol(String), LispString(String), Vector(Vec<LispData>), Cons(Box<LispData>, Box<LispData>), } use LispData::*; fn write_cdr(data: &LispData, f: &mut fmt::Formatter<'_>) -> fmt::Result { match data { Nil => Ok(()), Cons(a, b) => { write!(f, " {}", a)?; write_cdr(b, f) } _ => write!(f, " . {}", data), } } impl fmt::Display for LispData { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Nil => write!(f, "()"), Bool(b) => write!(f, "#{}", if *b { 't' } else { 'f' }), Num(n) => n.fmt(f), Symbol(s) => s.fmt(f), LispString(s) => write!(f, "{:?}", s), Vector(v) => { write!(f, "#(")?; if let Some(val) = v.get(0) { val.fmt(f)?; } for val in v.iter().skip(1) { write!(f, " {}", val)?; } write!(f, ")") } Cons(a, b) => { write!(f, "({}", a)?; write_cdr(&b, f)?; write!(f, ")") } } } } fn lisptoken(input: &str) -> IResult<&str, char> { none_of("'()# \"\r\n")(input) } fn cons(input: &str) -> IResult<&str, LispData> { let (input, _) = char('(')(input)?; let (input, _) = multispace0(input)?; let (input, middle) = many0(terminated(lisp_data, multispace0))(input)?; let (input, dot) = opt(preceded( terminated(char('.'), multispace0), terminated(lisp_data, multispace0), ))(input)?; let (input, _) = char(')')(input)?; Ok(( input, middle .into_iter() .rev() .fold(dot.unwrap_or(Nil), |a, b| Cons(Box::new(b), Box::new(a))), )) } fn quote(input: &str) -> IResult<&str, LispData> { let (input, _) = char('\'')(input)?; let (input, data) = lisp_data(input)?; Ok(( input, Cons( Box::new(Symbol("quote".to_string())), Box::new(Cons(Box::new(data), Box::new(Nil))), ), )) } fn symbol(input: &str) -> IResult<&str, LispData> { let (input, a) = many1(lisptoken)(input)?; let b: String = a.into_iter().collect(); match b.as_str() { "." => Err(Err::Error(Error::new("dot", Char))), _ => Ok((input, Symbol(b))), } } fn parse_num<'a>( f: fn(&'a str) -> IResult<&'a str, &'a str>, input: &'a str, radix: u32, ) -> IResult<&'a str, LispData> { let (input, negate) = opt(char('-'))(input)?; let (input, data) = f(input)?; match i64::from_str_radix(data, radix) { Ok(n) => Ok((input, Num(if negate.is_some() { n.neg() } else { n }))), Err(_) => Err(Err::Error(Error::new("parseint", Char))), } } fn num(input: &str) -> IResult<&str, LispData> { parse_num(digit1, input, 10) } fn bin_digit1(input: &str) -> IResult<&str, &str> { take_while1(|a| a == '0' || a == '1')(input) } fn sharp(input: &str) -> IResult<&str, LispData> { let (input, _) = char('#')(input)?; let (input, c) = anychar(input)?; match c.to_lowercase().next().unwrap() { 'f' => Ok((input, Bool(false))), 't' => Ok((input, Bool(true))), 'b' => parse_num(bin_digit1, input, 2), 'o' => parse_num(oct_digit1, input, 8), 'd' => num(input), 'x' => parse_num(hex_digit1, input, 16), '(' => { let (input, _) = multispace0(input)?; let (input, vals) = many0(terminated(lisp_data, multispace0))(input)?; let (input, _) = char(')')(input)?; Ok((input, Vector(vals))) } _ => Err(Err::Error(Error::new("#", Char))), } } fn block_comment(input: &str) -> IResult<&str, ()> { let (input, _) = delimited(tag("#|"), take_until("|#"), tag("|#"))(input)?; Ok((input, ())) } fn line_comment(input: &str) -> IResult<&str, ()> { let (input, _) = delimited(char(';'), take_until("\n"), line_ending)(input)?; Ok((input, ())) } fn datum_comment(input: &str) -> IResult<&str, ()> { let (input, _) = preceded(tag("#;"), lisp_data)(input)?; Ok((input, ())) } fn comment(input: &str) -> IResult<&str, LispData> { let (input, _) = alt((block_comment, line_comment, datum_comment))(input)?; lisp_data(input) } fn escaped_char(input: &str) -> IResult<&str, char> { let (input, _) = char('\\')(input)?; let (input, seq) = anychar(input)?; let c = match seq { 'a' => '\x07', 'b' => '\x08', 'n' => '\n', 'r' => '\r', 't' => '\t', '"' => '\"', '\\' => '\\', '|' => '|', _ => return Err(Err::Error(Error::new("escape", Char))), }; Ok((input, c)) } fn string(input: &str) -> IResult<&str, LispData> { let (input, data) = delimited( char('"'), many0(alt((none_of("\\\""), escaped_char))), char('"'), )(input)?; Ok((input, LispString(data.into_iter().collect()))) } fn lisp_data(input: &str) -> IResult<&str, LispData> { let (input, _) = multispace0(input)?; alt((quote, cons, comment, sharp, num, string, symbol))(input) } fn main() -> io::Result<()> { let stdin = io::stdin(); let mut stdin = stdin.lock(); let mut buffer = String::new(); let mut stdout = io::stdout(); loop { if buffer.is_empty() { print!("> "); stdout.flush()?; } match lisp_data(&buffer) { Ok((rest, val)) => { buffer = rest.to_string(); println!("{}", val); print!("> "); stdout.flush()?; } Err(Incomplete(_)) => { if stdin.read_line(&mut buffer)? == 0 { println!(""); return Ok(()); } } err => { println!("{:?}", err); buffer.clear() } } } }
extern crate nom; use nom::{ branch::alt, bytes::streaming::{tag, take_until, take_while1}, character::streaming::{ anychar, char, digit1, hex_digit1, line_ending, multispace0, none_of, oct_digit1, }, combinator::opt, error::{Error, ErrorKind::Char}, multi::{many0, many1}, sequence::{delimited, preceded, terminated}, Err::{self, Incomplete}, IResult, }; use std::{ fmt, io::{self, BufRead, Write}, ops::Neg, }; #[derive(Debug)] enum LispData { Nil, Bool(bool), Num(i64), Symbol(String), LispString(String), Vector(Vec<LispData>), Cons(Box<LispData>, Box<LispData>), } use LispData::*; fn write_cdr(data: &LispData, f: &mut fmt::Formatter<'_>) -> fmt::Result { match data { Nil => Ok(()), Cons(a, b) => { write!(f, " {}", a)?; write_cdr(b, f) } _ => write!(f, " . {}", data), } } impl fmt::Display for LispData { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Nil => write!(f, "()"), Bool(b) => write!(f, "#{}", if *b { 't' } else { 'f' }), Num(n) => n.fmt(f), Symbol(s) => s.fmt(f), LispString(s) => write!(f, "{:?}", s), Vector(v) => { write!(f, "#(")?; if let Some(val) = v.get(0) { val.fmt(f)?; } for val in v.iter().skip(1) { write!(f, " {}", val)?; } write!(f, ")") } Cons(
} fn lisptoken(input: &str) -> IResult<&str, char> { none_of("'()# \"\r\n")(input) } fn cons(input: &str) -> IResult<&str, LispData> { let (input, _) = char('(')(input)?; let (input, _) = multispace0(input)?; let (input, middle) = many0(terminated(lisp_data, multispace0))(input)?; let (input, dot) = opt(preceded( terminated(char('.'), multispace0), terminated(lisp_data, multispace0), ))(input)?; let (input, _) = char(')')(input)?; Ok(( input, middle .into_iter() .rev() .fold(dot.unwrap_or(Nil), |a, b| Cons(Box::new(b), Box::new(a))), )) } fn quote(input: &str) -> IResult<&str, LispData> { let (input, _) = char('\'')(input)?; let (input, data) = lisp_data(input)?; Ok(( input, Cons( Box::new(Symbol("quote".to_string())), Box::new(Cons(Box::new(data), Box::new(Nil))), ), )) } fn symbol(input: &str) -> IResult<&str, LispData> { let (input, a) = many1(lisptoken)(input)?; let b: String = a.into_iter().collect(); match b.as_str() { "." => Err(Err::Error(Error::new("dot", Char))), _ => Ok((input, Symbol(b))), } } fn parse_num<'a>( f: fn(&'a str) -> IResult<&'a str, &'a str>, input: &'a str, radix: u32, ) -> IResult<&'a str, LispData> { let (input, negate) = opt(char('-'))(input)?; let (input, data) = f(input)?; match i64::from_str_radix(data, radix) { Ok(n) => Ok((input, Num(if negate.is_some() { n.neg() } else { n }))), Err(_) => Err(Err::Error(Error::new("parseint", Char))), } } fn num(input: &str) -> IResult<&str, LispData> { parse_num(digit1, input, 10) } fn bin_digit1(input: &str) -> IResult<&str, &str> { take_while1(|a| a == '0' || a == '1')(input) } fn sharp(input: &str) -> IResult<&str, LispData> { let (input, _) = char('#')(input)?; let (input, c) = anychar(input)?; match c.to_lowercase().next().unwrap() { 'f' => Ok((input, Bool(false))), 't' => Ok((input, Bool(true))), 'b' => parse_num(bin_digit1, input, 2), 'o' => parse_num(oct_digit1, input, 8), 'd' => num(input), 'x' => parse_num(hex_digit1, input, 16), '(' => { let (input, _) = multispace0(input)?; let (input, vals) = many0(terminated(lisp_data, multispace0))(input)?; let (input, _) = char(')')(input)?; Ok((input, Vector(vals))) } _ => Err(Err::Error(Error::new("#", Char))), } } fn block_comment(input: &str) -> IResult<&str, ()> { let (input, _) = delimited(tag("#|"), take_until("|#"), tag("|#"))(input)?; Ok((input, ())) } fn line_comment(input: &str) -> IResult<&str, ()> { let (input, _) = delimited(char(';'), take_until("\n"), line_ending)(input)?; Ok((input, ())) } fn datum_comment(input: &str) -> IResult<&str, ()> { let (input, _) = preceded(tag("#;"), lisp_data)(input)?; Ok((input, ())) } fn comment(input: &str) -> IResult<&str, LispData> { let (input, _) = alt((block_comment, line_comment, datum_comment))(input)?; lisp_data(input) } fn escaped_char(input: &str) -> IResult<&str, char> { let (input, _) = char('\\')(input)?; let (input, seq) = anychar(input)?; let c = match seq { 'a' => '\x07', 'b' => '\x08', 'n' => '\n', 'r' => '\r', 't' => '\t', '"' => '\"', '\\' => '\\', '|' => '|', _ => return Err(Err::Error(Error::new("escape", Char))), }; Ok((input, c)) } fn string(input: &str) -> IResult<&str, LispData> { let (input, data) = delimited( char('"'), many0(alt((none_of("\\\""), escaped_char))), char('"'), )(input)?; Ok((input, LispString(data.into_iter().collect()))) } fn lisp_data(input: &str) -> IResult<&str, LispData> { let (input, _) = multispace0(input)?; alt((quote, cons, comment, sharp, num, string, symbol))(input) } fn main() -> io::Result<()> { let stdin = io::stdin(); let mut stdin = stdin.lock(); let mut buffer = String::new(); let mut stdout = io::stdout(); loop { if buffer.is_empty() { print!("> "); stdout.flush()?; } match lisp_data(&buffer) { Ok((rest, val)) => { buffer = rest.to_string(); println!("{}", val); print!("> "); stdout.flush()?; } Err(Incomplete(_)) => { if stdin.read_line(&mut buffer)? == 0 { println!(""); return Ok(()); } } err => { println!("{:?}", err); buffer.clear() } } } }
a, b) => { write!(f, "({}", a)?; write_cdr(&b, f)?; write!(f, ")") } } }
function_block-function_prefixed
[]
Rust
day-12/src/main.rs
kecors/AoC-2018
dd213e9087639ace4788c94daa4a85fedc635162
use pom::parser::*; use pom::Error; use std::collections::HashMap; use std::collections::VecDeque; use std::io::{stdin, Read}; #[derive(Debug)] struct Pot { number: i32, plant: bool, } #[derive(Debug)] struct Note { neighbors: Vec<bool>, next_generation: bool, } #[derive(Debug)] struct Engine { pots: VecDeque<Pot>, note_hm: HashMap<Vec<bool>, bool>, } impl Engine { fn new(initial_state: Vec<bool>, notes: Vec<Note>) -> Engine { let mut pots = VecDeque::new(); for (n, plant) in initial_state.into_iter().enumerate() { pots.push_back(Pot { number: n as i32, plant, }); } let mut note_hm = HashMap::new(); for note in notes { note_hm.insert(note.neighbors, note.next_generation); } Engine { pots, note_hm } } fn next_generation(&mut self) { let front_number = if let Some(pot) = self.pots.front() { pot.number } else { unreachable!("Impossible if any plants remain"); }; let back_number = if let Some(pot) = self.pots.back() { pot.number } else { unreachable!("Impossible if any plants remain"); }; for x in 1..=4 { self.pots.push_front(Pot { number: front_number - x, plant: false, }); self.pots.push_back(Pot { number: back_number + x, plant: false, }); } let mut new_pots = VecDeque::new(); for j in 0..self.pots.len() - 4 { let mut neighbor_key = Vec::new(); for k in 0..5 { neighbor_key.push(self.pots[j + k].plant); } let plant = if let Some(plant) = self.note_hm.get(&neighbor_key) { *plant } else { false }; new_pots.push_back(Pot { number: self.pots[j + 2].number, plant, }); } let pot_to_restore = loop { if let Some(pot) = new_pots.pop_front() { if pot.plant { break pot; } } }; new_pots.push_front(pot_to_restore); let pot_to_restore = loop { if let Some(pot) = new_pots.pop_back() { if pot.plant { break pot; } } }; new_pots.push_back(pot_to_restore); self.pots = new_pots; } fn sum(&self) -> i32 { let mut sum = 0; for pot in self.pots.iter() { if pot.plant { sum += pot.number; } } sum } fn range(&self) -> (i32, i32) { let front_number = if let Some(pot) = self.pots.front() { pot.number } else { unreachable!("Impossible if any plants remain"); }; let back_number = if let Some(pot) = self.pots.back() { pot.number } else { unreachable!("Impossible if any plants remain"); }; (front_number, back_number) } fn pattern(&self) -> String { let mut pattern = String::new(); for pot in self.pots.iter() { pattern.push(if pot.plant { '#' } else { '.' }); } pattern } #[allow(dead_code)] fn display(&self) { for pot in self.pots.iter() { print!("{} ", pot.number); } println!(); for pot in self.pots.iter() { print!("{}", if pot.plant { "#" } else { "." }); } println!(); } } fn space<'a>() -> Parser<'a, u8, ()> { one_of(b" \t\r\n").repeat(0..).discard() } fn plant<'a>() -> Parser<'a, u8, bool> { sym(b'#').map(|_| true) | sym(b'.').map(|_| false) } fn initial_state<'a>() -> Parser<'a, u8, Vec<bool>> { let prefix = seq(b"initial state: ").discard(); let plants = plant().repeat(1..); prefix * plants } fn note<'a>() -> Parser<'a, u8, Note> { (plant().repeat(5) + skip(4) * plant()).map(|(neighbors, next_generation)| Note { neighbors, next_generation, }) } fn engine<'a>() -> Parser<'a, u8, Engine> { let notes = (space() * note()).repeat(1..); (initial_state() + notes).map(|(initial_state, notes)| Engine::new(initial_state, notes)) } fn main() -> Result<(), Error> { let mut input = String::new(); stdin().read_to_string(&mut input).unwrap(); let mut engine_p1 = engine().parse(input.as_bytes())?; for _ in 0..20 { engine_p1.next_generation(); } let part1 = engine_p1.sum(); println!( "Part 1: After 20 generations, the sum of the numbers of all pots which contain a plant is {}", part1 ); let mut engine_p2 = engine().parse(input.as_bytes())?; let mut patterns = HashMap::new(); for x in 0..200 { if x > 157 { let p = patterns.entry(engine_p2.pattern()).or_insert_with(Vec::new); p.push((x, engine_p2.range(), engine_p2.sum())); } engine_p2.next_generation(); println!("[{}] sum = {}", x, engine_p2.sum()); engine_p2.display(); println!(); } println!("patterns = {:#?}", patterns); let part2: u64 = (50_000_000_000 - 158) * 86 + 16002; println!( "Part 2: After fifty billion generations, the sum of the numbers of all pots which contain a plant is {}", part2 ); Ok(()) }
use pom::parser::*; use pom::Error; use std::collections::HashMap; use std::collections::VecDeque; use std::io::{stdin, Read}; #[derive(Debug)] struct Pot { number: i32, plant: bool, } #[derive(Debug)] struct Note { neighbors: Vec<bool>, next_generation: bool, } #[derive(Debug)] struct Engine { pots: VecDeque<Pot>, note_hm: HashMap<Vec<bool>, bool>, } impl Engine { fn new(initial_state: Vec<bool>, notes: Vec<Note>) -> Engine { let mut pots = VecDeque::new(); for (n, plant) in initial_state.into_iter().enumerate() { pots.push_back(Pot { number: n as i32, plant, }); } let mut note_hm = HashMap::new(); for note in notes { note_hm.insert(note.neighbors, note.next_generation); } Engine { pots, note_hm } } fn next_generation(&mut self) { let front_number = if let Some(pot) = self.pots.front() { pot.number } else { unreachable!("Impossible if any plants remain"); }; let back_number = if let Some(pot) = self.pots.back() { pot.number } else { unreachable!("Impossible if any plants remain"); }; for x in 1..=4 { self.pots.push_front(Pot {
engine_p2.next_generation(); println!("[{}] sum = {}", x, engine_p2.sum()); engine_p2.display(); println!(); } println!("patterns = {:#?}", patterns); let part2: u64 = (50_000_000_000 - 158) * 86 + 16002; println!( "Part 2: After fifty billion generations, the sum of the numbers of all pots which contain a plant is {}", part2 ); Ok(()) }
number: front_number - x, plant: false, }); self.pots.push_back(Pot { number: back_number + x, plant: false, }); } let mut new_pots = VecDeque::new(); for j in 0..self.pots.len() - 4 { let mut neighbor_key = Vec::new(); for k in 0..5 { neighbor_key.push(self.pots[j + k].plant); } let plant = if let Some(plant) = self.note_hm.get(&neighbor_key) { *plant } else { false }; new_pots.push_back(Pot { number: self.pots[j + 2].number, plant, }); } let pot_to_restore = loop { if let Some(pot) = new_pots.pop_front() { if pot.plant { break pot; } } }; new_pots.push_front(pot_to_restore); let pot_to_restore = loop { if let Some(pot) = new_pots.pop_back() { if pot.plant { break pot; } } }; new_pots.push_back(pot_to_restore); self.pots = new_pots; } fn sum(&self) -> i32 { let mut sum = 0; for pot in self.pots.iter() { if pot.plant { sum += pot.number; } } sum } fn range(&self) -> (i32, i32) { let front_number = if let Some(pot) = self.pots.front() { pot.number } else { unreachable!("Impossible if any plants remain"); }; let back_number = if let Some(pot) = self.pots.back() { pot.number } else { unreachable!("Impossible if any plants remain"); }; (front_number, back_number) } fn pattern(&self) -> String { let mut pattern = String::new(); for pot in self.pots.iter() { pattern.push(if pot.plant { '#' } else { '.' }); } pattern } #[allow(dead_code)] fn display(&self) { for pot in self.pots.iter() { print!("{} ", pot.number); } println!(); for pot in self.pots.iter() { print!("{}", if pot.plant { "#" } else { "." }); } println!(); } } fn space<'a>() -> Parser<'a, u8, ()> { one_of(b" \t\r\n").repeat(0..).discard() } fn plant<'a>() -> Parser<'a, u8, bool> { sym(b'#').map(|_| true) | sym(b'.').map(|_| false) } fn initial_state<'a>() -> Parser<'a, u8, Vec<bool>> { let prefix = seq(b"initial state: ").discard(); let plants = plant().repeat(1..); prefix * plants } fn note<'a>() -> Parser<'a, u8, Note> { (plant().repeat(5) + skip(4) * plant()).map(|(neighbors, next_generation)| Note { neighbors, next_generation, }) } fn engine<'a>() -> Parser<'a, u8, Engine> { let notes = (space() * note()).repeat(1..); (initial_state() + notes).map(|(initial_state, notes)| Engine::new(initial_state, notes)) } fn main() -> Result<(), Error> { let mut input = String::new(); stdin().read_to_string(&mut input).unwrap(); let mut engine_p1 = engine().parse(input.as_bytes())?; for _ in 0..20 { engine_p1.next_generation(); } let part1 = engine_p1.sum(); println!( "Part 1: After 20 generations, the sum of the numbers of all pots which contain a plant is {}", part1 ); let mut engine_p2 = engine().parse(input.as_bytes())?; let mut patterns = HashMap::new(); for x in 0..200 { if x > 157 { let p = patterns.entry(engine_p2.pattern()).or_insert_with(Vec::new); p.push((x, engine_p2.range(), engine_p2.sum())); }
random
[ { "content": "fn number<'a>() -> Parser<'a, u8, i32> {\n\n let integer = (one_of(b\"123456789\") - one_of(b\"0123456789\").repeat(0..)) | sym(b'0');\n\n let number = sym(b'-').opt() + integer;\n\n number\n\n .collect()\n\n .convert(str::from_utf8)\n\n .convert(|s| i32::from_str_rad...
Rust
ruma-events/tests/pdu.rs
ignatenkobrain/ruma
1c47963befcf241f1dbd0e9ad12ab3dfd7ef54cc
#![cfg(not(feature = "unstable-pre-spec"))] use std::{ collections::BTreeMap, time::{Duration, SystemTime}, }; use ruma_events::{ pdu::{EventHash, Pdu, RoomV1Pdu, RoomV3Pdu}, EventType, }; use ruma_identifiers::{event_id, room_id, server_name, server_signing_key_id, user_id}; use serde_json::{from_value as from_json_value, json, to_value as to_json_value}; #[test] fn serialize_pdu_as_v1() { let mut signatures = BTreeMap::new(); let mut inner_signature = BTreeMap::new(); inner_signature.insert( server_signing_key_id!("ed25519:key_version"), "86BytesOfSignatureOfTheRedactedEvent".into(), ); signatures.insert(server_name!("example.com"), inner_signature); let mut unsigned = BTreeMap::new(); unsigned.insert("somekey".into(), json!({"a": 456})); let v1_pdu = RoomV1Pdu { room_id: room_id!("!n8f893n9:example.com"), event_id: event_id!("$somejoinevent:matrix.org"), sender: user_id!("@sender:example.com"), origin: "matrix.org".into(), origin_server_ts: SystemTime::UNIX_EPOCH + Duration::from_millis(1_592_050_773_658), kind: EventType::RoomPowerLevels, content: json!({"testing": 123}), state_key: Some("state".into()), prev_events: vec![( event_id!("$previousevent:matrix.org"), EventHash { sha256: "123567".into() }, )], depth: 2_u32.into(), auth_events: vec![( event_id!("$someauthevent:matrix.org"), EventHash { sha256: "21389CFEDABC".into() }, )], redacts: Some(event_id!("$9654:matrix.org")), unsigned, hashes: EventHash { sha256: "1233543bABACDEF".into() }, signatures, }; let pdu = Pdu::RoomV1Pdu(v1_pdu); let json = json!({ "room_id": "!n8f893n9:example.com", "event_id": "$somejoinevent:matrix.org", "sender": "@sender:example.com", "origin": "matrix.org", "origin_server_ts": 1_592_050_773_658usize, "type": "m.room.power_levels", "content": { "testing": 123 }, "state_key": "state", "prev_events": [ [ "$previousevent:matrix.org", {"sha256": "123567"} ] ], "depth": 2, "auth_events": [ ["$someauthevent:matrix.org", {"sha256": "21389CFEDABC"}] ], "redacts": "$9654:matrix.org", "unsigned": { "somekey": { "a": 456 } }, "hashes": { "sha256": "1233543bABACDEF" }, "signatures": { "example.com": { "ed25519:key_version":"86BytesOfSignatureOfTheRedactedEvent" } } }); assert_eq!(to_json_value(&pdu).unwrap(), json); } #[test] fn serialize_pdu_as_v3() { let mut signatures = BTreeMap::new(); let mut inner_signature = BTreeMap::new(); inner_signature.insert( server_signing_key_id!("ed25519:key_version"), "86BytesOfSignatureOfTheRedactedEvent".into(), ); signatures.insert(server_name!("example.com"), inner_signature); let mut unsigned = BTreeMap::new(); unsigned.insert("somekey".into(), json!({"a": 456})); let v3_pdu = RoomV3Pdu { room_id: room_id!("!n8f893n9:example.com"), sender: user_id!("@sender:example.com"), origin: "matrix.org".into(), origin_server_ts: SystemTime::UNIX_EPOCH + Duration::from_millis(1_592_050_773_658), kind: EventType::RoomPowerLevels, content: json!({"testing": 123}), state_key: Some("state".into()), prev_events: vec![event_id!("$previousevent:matrix.org")], depth: 2_u32.into(), auth_events: vec![event_id!("$someauthevent:matrix.org")], redacts: Some(event_id!("$9654:matrix.org")), unsigned, hashes: EventHash { sha256: "1233543bABACDEF".into() }, signatures, }; let pdu_stub = Pdu::RoomV3Pdu(v3_pdu); let json = json!({ "room_id": "!n8f893n9:example.com", "sender": "@sender:example.com", "origin": "matrix.org", "origin_server_ts": 1_592_050_773_658usize, "type": "m.room.power_levels", "content": { "testing": 123 }, "state_key": "state", "prev_events": [ "$previousevent:matrix.org" ], "depth": 2, "auth_events": ["$someauthevent:matrix.org" ], "redacts": "$9654:matrix.org", "unsigned": { "somekey": { "a": 456 } }, "hashes": { "sha256": "1233543bABACDEF" }, "signatures": { "example.com": { "ed25519:key_version":"86BytesOfSignatureOfTheRedactedEvent" } } }); assert_eq!(to_json_value(&pdu_stub).unwrap(), json); } #[test] fn deserialize_pdu_as_v1() { let json = json!({ "room_id": "!n8f893n9:example.com", "event_id": "$somejoinevent:matrix.org", "auth_events": [ [ "$abc123:matrix.org", { "sha256": "Base64EncodedSha256HashesShouldBe43BytesLong" } ] ], "content": { "key": "value" }, "depth": 12, "event_id": "$a4ecee13e2accdadf56c1025:example.com", "hashes": { "sha256": "ThisHashCoversAllFieldsInCaseThisIsRedacted" }, "origin": "matrix.org", "origin_server_ts": 1_234_567_890, "prev_events": [ [ "$abc123:matrix.org", { "sha256": "Base64EncodedSha256HashesShouldBe43BytesLong" } ] ], "redacts": "$def456:matrix.org", "room_id": "!abc123:matrix.org", "sender": "@someone:matrix.org", "signatures": { "example.com": { "ed25519:key_version": "86BytesOfSignatureOfTheRedactedEvent" } }, "state_key": "my_key", "type": "m.room.message", "unsigned": { "key": "value" } }); let parsed = from_json_value::<Pdu>(json).unwrap(); match parsed { Pdu::RoomV1Pdu(v1_pdu) => { assert_eq!(v1_pdu.auth_events.first().unwrap().0, event_id!("$abc123:matrix.org")); assert_eq!( v1_pdu.auth_events.first().unwrap().1.sha256, "Base64EncodedSha256HashesShouldBe43BytesLong" ); } Pdu::RoomV3Pdu(_) => panic!("Matched V3 PDU"), } } #[cfg(not(feature = "unstable-pre-spec"))] #[test] fn deserialize_pdu_as_v3() { let json = json!({ "room_id": "!n8f893n9:example.com", "auth_events": [ "$abc123:matrix.org" ], "content": { "key": "value" }, "depth": 12, "event_id": "$a4ecee13e2accdadf56c1025:example.com", "hashes": { "sha256": "ThisHashCoversAllFieldsInCaseThisIsRedacted" }, "origin": "matrix.org", "origin_server_ts": 1_234_567_890, "prev_events": [ "$abc123:matrix.org" ], "redacts": "$def456:matrix.org", "room_id": "!abc123:matrix.org", "sender": "@someone:matrix.org", "signatures": { "example.com": { "ed25519:key_version": "86BytesOfSignatureOfTheRedactedEvent" } }, "state_key": "my_key", "type": "m.room.message", "unsigned": { "key": "value" } }); let parsed = from_json_value::<Pdu>(json).unwrap(); match parsed { Pdu::RoomV1Pdu(_) => panic!("Matched V1 PDU"), Pdu::RoomV3Pdu(v3_pdu) => { assert_eq!(v3_pdu.auth_events.first().unwrap(), &event_id!("$abc123:matrix.org")); } } }
#![cfg(not(feature = "unstable-pre-spec"))] use std::{ collections::BTreeMap, time::{Duration, SystemTime}, }; use ruma_events::{ pdu::{EventHash, Pdu, RoomV1Pdu, RoomV3Pdu}, EventType, }; use ruma_identifiers::{event_id, room_id, server_name, server_signing_key_id, user_id}; use serde_json::{from_value as from_json_value, json, to_value as to_json_value}; #[test] fn serialize_pdu_as_v1() { let mut signatures = BTreeMap::new(); let mut inner_signature = BTreeMap::new(); inner_signature.insert( server_signing_key_id!("ed25519:key_version"), "86BytesOfSignatureOfTheRedactedEvent".into(), ); signatures.insert(server_name!("example.com"), inner_signature); let mut unsigned = BTreeMap::new(); unsigned.insert("somekey".into(), json!({"a": 456})); let v1_pdu = RoomV1Pdu { room_id: room_id!("!n8f893n9:example.com"), event_id: event_id!("$somejoinevent:matrix.org"), sender: user_id!("@sender:example.com"), origin: "matrix.org".into(), origin_server_ts: SystemTime::UNIX_EPOCH + Duration::from_millis(1_592_050_773_658), kind: EventType::RoomPowerLevels, content: json!({"testing": 123}), state_key: Some("state".into()), prev_events: vec![( event_id!("$previousevent:matrix.org"), EventHash { sha256: "123567".into() }, )], depth:
rg")), unsigned, hashes: EventHash { sha256: "1233543bABACDEF".into() }, signatures, }; let pdu_stub = Pdu::RoomV3Pdu(v3_pdu); let json = json!({ "room_id": "!n8f893n9:example.com", "sender": "@sender:example.com", "origin": "matrix.org", "origin_server_ts": 1_592_050_773_658usize, "type": "m.room.power_levels", "content": { "testing": 123 }, "state_key": "state", "prev_events": [ "$previousevent:matrix.org" ], "depth": 2, "auth_events": ["$someauthevent:matrix.org" ], "redacts": "$9654:matrix.org", "unsigned": { "somekey": { "a": 456 } }, "hashes": { "sha256": "1233543bABACDEF" }, "signatures": { "example.com": { "ed25519:key_version":"86BytesOfSignatureOfTheRedactedEvent" } } }); assert_eq!(to_json_value(&pdu_stub).unwrap(), json); } #[test] fn deserialize_pdu_as_v1() { let json = json!({ "room_id": "!n8f893n9:example.com", "event_id": "$somejoinevent:matrix.org", "auth_events": [ [ "$abc123:matrix.org", { "sha256": "Base64EncodedSha256HashesShouldBe43BytesLong" } ] ], "content": { "key": "value" }, "depth": 12, "event_id": "$a4ecee13e2accdadf56c1025:example.com", "hashes": { "sha256": "ThisHashCoversAllFieldsInCaseThisIsRedacted" }, "origin": "matrix.org", "origin_server_ts": 1_234_567_890, "prev_events": [ [ "$abc123:matrix.org", { "sha256": "Base64EncodedSha256HashesShouldBe43BytesLong" } ] ], "redacts": "$def456:matrix.org", "room_id": "!abc123:matrix.org", "sender": "@someone:matrix.org", "signatures": { "example.com": { "ed25519:key_version": "86BytesOfSignatureOfTheRedactedEvent" } }, "state_key": "my_key", "type": "m.room.message", "unsigned": { "key": "value" } }); let parsed = from_json_value::<Pdu>(json).unwrap(); match parsed { Pdu::RoomV1Pdu(v1_pdu) => { assert_eq!(v1_pdu.auth_events.first().unwrap().0, event_id!("$abc123:matrix.org")); assert_eq!( v1_pdu.auth_events.first().unwrap().1.sha256, "Base64EncodedSha256HashesShouldBe43BytesLong" ); } Pdu::RoomV3Pdu(_) => panic!("Matched V3 PDU"), } } #[cfg(not(feature = "unstable-pre-spec"))] #[test] fn deserialize_pdu_as_v3() { let json = json!({ "room_id": "!n8f893n9:example.com", "auth_events": [ "$abc123:matrix.org" ], "content": { "key": "value" }, "depth": 12, "event_id": "$a4ecee13e2accdadf56c1025:example.com", "hashes": { "sha256": "ThisHashCoversAllFieldsInCaseThisIsRedacted" }, "origin": "matrix.org", "origin_server_ts": 1_234_567_890, "prev_events": [ "$abc123:matrix.org" ], "redacts": "$def456:matrix.org", "room_id": "!abc123:matrix.org", "sender": "@someone:matrix.org", "signatures": { "example.com": { "ed25519:key_version": "86BytesOfSignatureOfTheRedactedEvent" } }, "state_key": "my_key", "type": "m.room.message", "unsigned": { "key": "value" } }); let parsed = from_json_value::<Pdu>(json).unwrap(); match parsed { Pdu::RoomV1Pdu(_) => panic!("Matched V1 PDU"), Pdu::RoomV3Pdu(v3_pdu) => { assert_eq!(v3_pdu.auth_events.first().unwrap(), &event_id!("$abc123:matrix.org")); } } }
2_u32.into(), auth_events: vec![( event_id!("$someauthevent:matrix.org"), EventHash { sha256: "21389CFEDABC".into() }, )], redacts: Some(event_id!("$9654:matrix.org")), unsigned, hashes: EventHash { sha256: "1233543bABACDEF".into() }, signatures, }; let pdu = Pdu::RoomV1Pdu(v1_pdu); let json = json!({ "room_id": "!n8f893n9:example.com", "event_id": "$somejoinevent:matrix.org", "sender": "@sender:example.com", "origin": "matrix.org", "origin_server_ts": 1_592_050_773_658usize, "type": "m.room.power_levels", "content": { "testing": 123 }, "state_key": "state", "prev_events": [ [ "$previousevent:matrix.org", {"sha256": "123567"} ] ], "depth": 2, "auth_events": [ ["$someauthevent:matrix.org", {"sha256": "21389CFEDABC"}] ], "redacts": "$9654:matrix.org", "unsigned": { "somekey": { "a": 456 } }, "hashes": { "sha256": "1233543bABACDEF" }, "signatures": { "example.com": { "ed25519:key_version":"86BytesOfSignatureOfTheRedactedEvent" } } }); assert_eq!(to_json_value(&pdu).unwrap(), json); } #[test] fn serialize_pdu_as_v3() { let mut signatures = BTreeMap::new(); let mut inner_signature = BTreeMap::new(); inner_signature.insert( server_signing_key_id!("ed25519:key_version"), "86BytesOfSignatureOfTheRedactedEvent".into(), ); signatures.insert(server_name!("example.com"), inner_signature); let mut unsigned = BTreeMap::new(); unsigned.insert("somekey".into(), json!({"a": 456})); let v3_pdu = RoomV3Pdu { room_id: room_id!("!n8f893n9:example.com"), sender: user_id!("@sender:example.com"), origin: "matrix.org".into(), origin_server_ts: SystemTime::UNIX_EPOCH + Duration::from_millis(1_592_050_773_658), kind: EventType::RoomPowerLevels, content: json!({"testing": 123}), state_key: Some("state".into()), prev_events: vec![event_id!("$previousevent:matrix.org")], depth: 2_u32.into(), auth_events: vec![event_id!("$someauthevent:matrix.org")], redacts: Some(event_id!("$9654:matrix.o
random
[ { "content": "fn aliases_event_with_prev_content() -> JsonValue {\n\n json!({\n\n \"content\": {\n\n \"aliases\": [ \"#somewhere:localhost\" ]\n\n },\n\n \"event_id\": \"$h29iv0s8:example.com\",\n\n \"origin_server_ts\": 1,\n\n \"prev_content\": {\n\n ...
Rust
src/graphics/shader.rs
mooman219/glpaly
7731c705614ee2de8bc8685dc28361caa050a0af
use crate::graphics::{ graphics, resource, std140::Std140Struct, Buffer, DrawMode, Texture, Uniform, VertexDescriptor, }; use crate::{App, Context}; use alloc::format; use core::iter::IntoIterator; use core::marker::PhantomData; pub trait ShaderDescriptor<const TEXTURES: usize> { const VERTEX_SHADER: &'static str; const FRAGMENT_SHADER: &'static str; const TEXTURE_NAMES: [&'static str; TEXTURES]; const VERTEX_UNIFORM_NAME: &'static str; type VertexUniformType: Std140Struct; type VertexDescriptor: VertexDescriptor + Copy; } pub struct Shader<T: ShaderDescriptor<TEXTURES>, const TEXTURES: usize> { _unsend: core::marker::PhantomData<*const ()>, program: resource::Program, vertex_uniform_location: u32, texture_locations: [resource::UniformLocation; TEXTURES], phantom: PhantomData<T>, } impl<T: ShaderDescriptor<TEXTURES>, const TEXTURES: usize> Shader<T, TEXTURES> { pub fn new(_ctx: &Context<impl App>) -> Shader<T, TEXTURES> { let gl = graphics().gl(); let program = gl.shader_program(T::VERTEX_SHADER, T::FRAGMENT_SHADER); let vertex_uniform_location = gl.get_uniform_block_index(program, T::VERTEX_UNIFORM_NAME).expect( &format!("Failed to find uniform block named '{}' in vertex shader.", T::VERTEX_UNIFORM_NAME), ); gl.uniform_block_binding(program, vertex_uniform_location, 0); let texture_locations = T::TEXTURE_NAMES.map(|name| { gl.get_uniform_location(program, name) .expect(&format!("Failed to find texture named '{}' in fragment shader.", name)) }); Shader { _unsend: core::marker::PhantomData, program, vertex_uniform_location, texture_locations, phantom: PhantomData, } } fn bind(&self, uniform: &Uniform<T::VertexUniformType>, textures: [&Texture; TEXTURES]) { let gl = graphics().gl(); gl.use_program(Some(self.program)); uniform.bind(0); for i in 0..TEXTURES { textures[i].bind(i as u32); gl.uniform_1_i32(Some(&self.texture_locations[i]), i as i32); } } pub fn draw<'a, Item, Iter>( &self, mode: DrawMode, uniform: &Uniform<T::VertexUniformType>, textures: [&Texture; TEXTURES], buffers: Iter, ) where Item: AsRef<Buffer<T::VertexDescriptor>> + 'a, Iter: IntoIterator<Item = &'a Item>, { let instancing = T::VertexDescriptor::INSTANCING; if instancing.is_instanced() { self.draw_instanced(mode, uniform, textures, buffers, instancing.count); } else { self.draw_non_instanced(mode, uniform, textures, buffers); } } fn draw_instanced<'a, Item, Iter>( &self, mode: DrawMode, uniform: &Uniform<T::VertexUniformType>, textures: [&Texture; TEXTURES], buffers: Iter, count: i32, ) where Item: AsRef<Buffer<T::VertexDescriptor>> + 'a, Iter: IntoIterator<Item = &'a Item>, { self.bind(uniform, textures); for buffer in buffers { let buffer = buffer.as_ref(); if buffer.len() > 0 { buffer.bind(); graphics().gl().draw_arrays_instanced(mode, 0, count, buffer.len() as i32); } } } fn draw_non_instanced<'a, Item, Iter>( &self, mode: DrawMode, uniform: &Uniform<T::VertexUniformType>, textures: [&Texture; TEXTURES], buffers: Iter, ) where Item: AsRef<Buffer<T::VertexDescriptor>> + 'a, Iter: IntoIterator<Item = &'a Item>, { self.bind(uniform, textures); for buffer in buffers { let buffer = buffer.as_ref(); if buffer.len() > 0 { buffer.bind(); graphics().gl().draw_arrays(mode, 0, buffer.len() as i32); } } } } impl<T: ShaderDescriptor<TEXTURES>, const TEXTURES: usize> Drop for Shader<T, TEXTURES> { fn drop(&mut self) { let gl = graphics().gl(); gl.delete_program(self.program); } }
use crate::graphics::{ graphics, resource, std140::Std140Struct, Buffer, DrawMode, Texture, Uniform, VertexDescriptor, }; use crate::{App, Context}; use alloc::format; use core::iter::IntoIterator; use core::marker::PhantomData; pub trait ShaderDescriptor<const TEXTURES: usize> { const VERTEX_SHADER: &'static str; const FRAGMENT_SHADER: &'static str; const TEXTURE_NAMES: [&'static str; TEXTURES]; const VERTEX_UNIFORM_NAME: &'static str; type VertexUniformType: Std140Struct; type VertexDescriptor: VertexDescriptor + Copy; } pub struct Shader<T: ShaderDescriptor<TEXTURES>, const TEXTURES: usize> { _unsend: core::marker::PhantomData<*const ()>, program: resource::Program, vertex_uniform_location: u32, texture_locations: [resource::UniformLocation; TEXTURES], phantom: PhantomData<T>, } impl<T: ShaderDescriptor<TEXTURES>, const TEXTURES: usize> Shader<T, TEXTURES> { pub fn new(_ctx: &Context<impl App>) -> Shader<T, TEXTURES> { let gl = graphics().gl(); let program = gl.shader_program(T::VERTEX_SHADER, T::FRAGMENT_SHADER); let vertex_uniform_location = gl.get_uniform_block_index(program, T::VERTEX_UNIFORM_NAME).expect( &format!("Failed to find uniform block named '{}' in vertex shader.", T::VERTEX_UNIFORM_NAME), ); gl.uniform_block_binding(program, vertex_uniform_location, 0); let texture_locations = T::TEXTURE_NAMES.map(|name| { gl.get_uniform_location(program, name) .expect(&format!("Failed to find texture named '{}' in fragment shader.", name)) }); Shader { _unsend: core::marker::PhantomData, program, vertex_uniform_location, texture_locations, phantom: PhantomData, } } fn bind(&self, uniform: &Uniform<T::VertexUniformType>, textures: [&Texture; TEXTURES]) { let gl = graphics().gl(); gl.use_program(Some(self.program)); uniform.bind(0); for i in 0..TEXTURES { textures[i].bind(i as u32); gl.uniform_1_i32(Some(&self.texture_locations[i]), i as i32); } } pub fn draw<'a, Item, Iter>( &self, mode: DrawMode, uniform: &Uniform<T::VertexUniformType>, textures: [&Texture; TEXTURES], buffers: Iter, ) where Item: AsRef<Buffer<T::VertexDescriptor>> + 'a, Iter: IntoIterator<Item = &'a Item>, {
fn draw_instanced<'a, Item, Iter>( &self, mode: DrawMode, uniform: &Uniform<T::VertexUniformType>, textures: [&Texture; TEXTURES], buffers: Iter, count: i32, ) where Item: AsRef<Buffer<T::VertexDescriptor>> + 'a, Iter: IntoIterator<Item = &'a Item>, { self.bind(uniform, textures); for buffer in buffers { let buffer = buffer.as_ref(); if buffer.len() > 0 { buffer.bind(); graphics().gl().draw_arrays_instanced(mode, 0, count, buffer.len() as i32); } } } fn draw_non_instanced<'a, Item, Iter>( &self, mode: DrawMode, uniform: &Uniform<T::VertexUniformType>, textures: [&Texture; TEXTURES], buffers: Iter, ) where Item: AsRef<Buffer<T::VertexDescriptor>> + 'a, Iter: IntoIterator<Item = &'a Item>, { self.bind(uniform, textures); for buffer in buffers { let buffer = buffer.as_ref(); if buffer.len() > 0 { buffer.bind(); graphics().gl().draw_arrays(mode, 0, buffer.len() as i32); } } } } impl<T: ShaderDescriptor<TEXTURES>, const TEXTURES: usize> Drop for Shader<T, TEXTURES> { fn drop(&mut self) { let gl = graphics().gl(); gl.delete_program(self.program); } }
let instancing = T::VertexDescriptor::INSTANCING; if instancing.is_instanced() { self.draw_instanced(mode, uniform, textures, buffers, instancing.count); } else { self.draw_non_instanced(mode, uniform, textures, buffers); } }
function_block-function_prefix_line
[ { "content": "/// Type that holds all of your application state and handles events.\n\npub trait App: 'static + Sized {\n\n /// Function to create the app from a context.\n\n /// # Arguments\n\n ///\n\n /// * `ctx` - The engine context. This can be used to call various API functions.\n\n fn new(_...
Rust
src/find.rs
jqnatividad/csvlens
5d9f82e4e17145f0df324dfff39b29a257aab6bd
use crate::csv; use anyhow::Result; use regex::Regex; use std::cmp::min; use std::sync::{Arc, Mutex, MutexGuard}; use std::thread::{self}; use std::time::Instant; pub struct Finder { internal: Arc<Mutex<FinderInternalState>>, cursor: Option<usize>, row_hint: usize, target: Regex, } #[derive(Clone, Debug)] pub struct FoundRecord { pub row_index: usize, column_indices: Vec<usize>, } impl FoundRecord { pub fn row_index(&self) -> usize { self.row_index } pub fn column_indices(&self) -> &Vec<usize> { &self.column_indices } pub fn first_column(&self) -> usize { *self.column_indices.first().unwrap() } } impl Finder { pub fn new(config: Arc<csv::CsvConfig>, target: Regex) -> Result<Self> { let internal = FinderInternalState::init( config, target.clone() ); let finder = Finder { internal, cursor: None, row_hint: 0, target, }; Ok(finder) } pub fn count(&self) -> usize { (self.internal.lock().unwrap()).count } pub fn done(&self) -> bool { (self.internal.lock().unwrap()).done } pub fn cursor(&self) -> Option<usize> { self.cursor } pub fn cursor_row_index(&self) -> Option<usize> { let m_guard = self.internal.lock().unwrap(); self.get_found_record_at_cursor(m_guard) .map(|x| x.row_index()) } pub fn target(&self) -> Regex { self.target.clone() } pub fn reset_cursor(&mut self) { self.cursor = None; } pub fn set_row_hint(&mut self, row_hint: usize) { self.row_hint = row_hint; } pub fn next(&mut self) -> Option<FoundRecord> { let m_guard = self.internal.lock().unwrap(); let count = m_guard.count; if let Some(n) = self.cursor { if n + 1 < count { self.cursor = Some(n + 1); } } else if count > 0 { self.cursor = Some(m_guard.next_from(self.row_hint)); } self.get_found_record_at_cursor(m_guard) } pub fn prev(&mut self) -> Option<FoundRecord> { let m_guard = self.internal.lock().unwrap(); if let Some(n) = self.cursor { self.cursor = Some(n.saturating_sub(1)); } else { let count = m_guard.count; if count > 0 { self.cursor = Some(m_guard.prev_from(self.row_hint)); } } self.get_found_record_at_cursor(m_guard) } pub fn current(&self) -> Option<FoundRecord> { let m_guard = self.internal.lock().unwrap(); self.get_found_record_at_cursor(m_guard) } fn get_found_record_at_cursor( &self, m_guard: MutexGuard<FinderInternalState>, ) -> Option<FoundRecord> { if let Some(n) = self.cursor { let res = m_guard.founds.get(n); res.cloned() } else { None } } fn terminate(&self) { let mut m_guard = self.internal.lock().unwrap(); m_guard.terminate(); } pub fn elapsed(&self) -> Option<u128> { let m_guard = self.internal.lock().unwrap(); m_guard.elapsed() } pub fn get_subset_found(&self, offset: usize, num_rows: usize) -> Vec<u64> { let m_guard = self.internal.lock().unwrap(); let founds = &m_guard.founds; let start = min(offset, founds.len().saturating_sub(1)); let end = start.saturating_add(num_rows); let end = min(end, founds.len()); let indices: Vec<u64> = founds[start..end] .iter() .map(|x| x.row_index() as u64) .collect(); indices } } impl Drop for Finder { fn drop(&mut self) { self.terminate(); } } struct FinderInternalState { count: usize, founds: Vec<FoundRecord>, done: bool, should_terminate: bool, elapsed: Option<u128>, } impl FinderInternalState { pub fn init(config: Arc<csv::CsvConfig>, target: Regex) -> Arc<Mutex<FinderInternalState>> { let internal = FinderInternalState { count: 0, founds: vec![], done: false, should_terminate: false, elapsed: None, }; let m_state = Arc::new(Mutex::new(internal)); let _m = m_state.clone(); let _filename = config.filename().to_owned(); let _handle = thread::spawn(move || { let mut bg_reader = config.new_reader().unwrap(); let records = bg_reader.records(); let start = Instant::now(); for (row_index, r) in records.enumerate() { let mut column_indices = vec![]; if let Ok(valid_record) = r { for (column_index, field) in valid_record.iter().enumerate() { if target.is_match(field) { column_indices.push(column_index); } } } if !column_indices.is_empty() { let found = FoundRecord { row_index, column_indices, }; let mut m = _m.lock().unwrap(); (*m).found_one(found); } let m = _m.lock().unwrap(); if m.should_terminate { break; } } let mut m = _m.lock().unwrap(); (*m).done = true; (*m).elapsed = Some(start.elapsed().as_micros()); }); m_state } fn found_one(&mut self, found: FoundRecord) { self.founds.push(found); self.count += 1; } fn next_from(&self, row_hint: usize) -> usize { let mut index = self.founds.partition_point(|r| r.row_index() < row_hint); if index >= self.founds.len() { index -= 1; } index } fn prev_from(&self, row_hint: usize) -> usize { let next = self.next_from(row_hint); if next > 0 { next - 1 } else { next } } fn terminate(&mut self) { self.should_terminate = true; } fn elapsed(&self) -> Option<u128> { self.elapsed } }
use crate::csv; use anyhow::Result; use regex::Regex; use std::cmp::min; use std::sync::{Arc, Mutex, MutexGuard}; use std::thread::{self}; use std::time::Instant; pub struct Finder { internal: Arc<Mutex<FinderInternalState>>, cursor: Option<usize>, row_hint: usize, target: Regex, } #[derive(Clone, Debug)] pub struct FoundRecord { pub row_index: usize, column_indices: Vec<usize>, } impl FoundRecord { pub fn row_index(&self) -> usize { self.row_index } pub fn column_indices(&self) -> &Vec<usize> { &self.column_indices } pub fn first_column(&self) -> usize { *self.column_indices.first().unwrap() } } impl Finder { pub fn new(config: Arc<csv::CsvConfig>, target: Regex) -> Result<Self> { let internal = FinderInternalState::init( config, target.clone() ); let finder = Finder { internal, cursor: None, row_hint: 0, target, }; Ok(finder) } pub fn count(&self) -> usize { (self.internal.lock().unwrap()).count } pub fn done(&self) -> bool { (self.internal.lock().unwrap()).done } pub fn cursor(&self) -> Option<usize> { self.cursor } pub fn cursor_row_index(&self) -> Option<usize> { let m_guard = self.internal.lock().unwrap(); self.get_found_record_at_cursor(m_guard) .map(|x| x.row_index()) } pub fn target(&self) -> Regex { self.target.clone() } pub fn reset_cursor(&mut self) { self.cursor = None; } pub fn set_row_hint(&mut self, row_hint: usize) { self.row_hint = row_hint; } pub fn next(&mut self) -> Option<FoundRecord> {
pub fn prev(&mut self) -> Option<FoundRecord> { let m_guard = self.internal.lock().unwrap(); if let Some(n) = self.cursor { self.cursor = Some(n.saturating_sub(1)); } else { let count = m_guard.count; if count > 0 { self.cursor = Some(m_guard.prev_from(self.row_hint)); } } self.get_found_record_at_cursor(m_guard) } pub fn current(&self) -> Option<FoundRecord> { let m_guard = self.internal.lock().unwrap(); self.get_found_record_at_cursor(m_guard) } fn get_found_record_at_cursor( &self, m_guard: MutexGuard<FinderInternalState>, ) -> Option<FoundRecord> { if let Some(n) = self.cursor { let res = m_guard.founds.get(n); res.cloned() } else { None } } fn terminate(&self) { let mut m_guard = self.internal.lock().unwrap(); m_guard.terminate(); } pub fn elapsed(&self) -> Option<u128> { let m_guard = self.internal.lock().unwrap(); m_guard.elapsed() } pub fn get_subset_found(&self, offset: usize, num_rows: usize) -> Vec<u64> { let m_guard = self.internal.lock().unwrap(); let founds = &m_guard.founds; let start = min(offset, founds.len().saturating_sub(1)); let end = start.saturating_add(num_rows); let end = min(end, founds.len()); let indices: Vec<u64> = founds[start..end] .iter() .map(|x| x.row_index() as u64) .collect(); indices } } impl Drop for Finder { fn drop(&mut self) { self.terminate(); } } struct FinderInternalState { count: usize, founds: Vec<FoundRecord>, done: bool, should_terminate: bool, elapsed: Option<u128>, } impl FinderInternalState { pub fn init(config: Arc<csv::CsvConfig>, target: Regex) -> Arc<Mutex<FinderInternalState>> { let internal = FinderInternalState { count: 0, founds: vec![], done: false, should_terminate: false, elapsed: None, }; let m_state = Arc::new(Mutex::new(internal)); let _m = m_state.clone(); let _filename = config.filename().to_owned(); let _handle = thread::spawn(move || { let mut bg_reader = config.new_reader().unwrap(); let records = bg_reader.records(); let start = Instant::now(); for (row_index, r) in records.enumerate() { let mut column_indices = vec![]; if let Ok(valid_record) = r { for (column_index, field) in valid_record.iter().enumerate() { if target.is_match(field) { column_indices.push(column_index); } } } if !column_indices.is_empty() { let found = FoundRecord { row_index, column_indices, }; let mut m = _m.lock().unwrap(); (*m).found_one(found); } let m = _m.lock().unwrap(); if m.should_terminate { break; } } let mut m = _m.lock().unwrap(); (*m).done = true; (*m).elapsed = Some(start.elapsed().as_micros()); }); m_state } fn found_one(&mut self, found: FoundRecord) { self.founds.push(found); self.count += 1; } fn next_from(&self, row_hint: usize) -> usize { let mut index = self.founds.partition_point(|r| r.row_index() < row_hint); if index >= self.founds.len() { index -= 1; } index } fn prev_from(&self, row_hint: usize) -> usize { let next = self.next_from(row_hint); if next > 0 { next - 1 } else { next } } fn terminate(&mut self) { self.should_terminate = true; } fn elapsed(&self) -> Option<u128> { self.elapsed } }
let m_guard = self.internal.lock().unwrap(); let count = m_guard.count; if let Some(n) = self.cursor { if n + 1 < count { self.cursor = Some(n + 1); } } else if count > 0 { self.cursor = Some(m_guard.next_from(self.row_hint)); } self.get_found_record_at_cursor(m_guard) }
function_block-function_prefix_line
[ { "content": "struct ReaderInternalState {\n\n total_line_number: Option<usize>,\n\n total_line_number_approx: Option<usize>,\n\n pos_table: Vec<Position>,\n\n done: bool,\n\n}\n\n\n\nimpl ReaderInternalState {\n\n fn init_internal(config: Arc<CsvConfig>) -> (Arc<Mutex<ReaderInternalState>>, Join...
Rust
arrow/src/buffer/ops.rs
zhaox1n/arrow-rs
d2cec2ccef6adf92754883bd58a7fdd4858c02a9
#[cfg(feature = "simd")] use crate::util::bit_util; #[cfg(feature = "simd")] use packed_simd::u8x64; #[cfg(feature = "avx512")] use crate::arch::avx512::*; use crate::util::bit_util::ceil; #[cfg(any(feature = "simd", feature = "avx512"))] use std::borrow::BorrowMut; use super::{Buffer, MutableBuffer}; #[cfg(feature = "simd")] pub fn bitwise_bin_op_simd_helper<F_SIMD, F_SCALAR>( left: &Buffer, left_offset: usize, right: &Buffer, right_offset: usize, len: usize, simd_op: F_SIMD, scalar_op: F_SCALAR, ) -> Buffer where F_SIMD: Fn(u8x64, u8x64) -> u8x64, F_SCALAR: Fn(u8, u8) -> u8, { let mut result = MutableBuffer::new(len).with_bitset(len, false); let lanes = u8x64::lanes(); let mut left_chunks = left.as_slice()[left_offset..].chunks_exact(lanes); let mut right_chunks = right.as_slice()[right_offset..].chunks_exact(lanes); let mut result_chunks = result.as_slice_mut().chunks_exact_mut(lanes); result_chunks .borrow_mut() .zip(left_chunks.borrow_mut().zip(right_chunks.borrow_mut())) .for_each(|(res, (left, right))| { unsafe { bit_util::bitwise_bin_op_simd(&left, &right, res, &simd_op) }; }); result_chunks .into_remainder() .iter_mut() .zip( left_chunks .remainder() .iter() .zip(right_chunks.remainder().iter()), ) .for_each(|(res, (left, right))| { *res = scalar_op(*left, *right); }); result.into() } #[cfg(feature = "simd")] pub fn bitwise_unary_op_simd_helper<F_SIMD, F_SCALAR>( left: &Buffer, left_offset: usize, len: usize, simd_op: F_SIMD, scalar_op: F_SCALAR, ) -> Buffer where F_SIMD: Fn(u8x64) -> u8x64, F_SCALAR: Fn(u8) -> u8, { let mut result = MutableBuffer::new(len).with_bitset(len, false); let lanes = u8x64::lanes(); let mut left_chunks = left.as_slice()[left_offset..].chunks_exact(lanes); let mut result_chunks = result.as_slice_mut().chunks_exact_mut(lanes); result_chunks .borrow_mut() .zip(left_chunks.borrow_mut()) .for_each(|(res, left)| unsafe { let data_simd = u8x64::from_slice_unaligned_unchecked(left); let simd_result = simd_op(data_simd); simd_result.write_to_slice_unaligned_unchecked(res); }); result_chunks .into_remainder() .iter_mut() .zip(left_chunks.remainder().iter()) .for_each(|(res, left)| { *res = scalar_op(*left); }); result.into() } pub fn bitwise_bin_op_helper<F>( left: &Buffer, left_offset_in_bits: usize, right: &Buffer, right_offset_in_bits: usize, len_in_bits: usize, op: F, ) -> Buffer where F: Fn(u64, u64) -> u64, { let left_chunks = left.bit_chunks(left_offset_in_bits, len_in_bits); let right_chunks = right.bit_chunks(right_offset_in_bits, len_in_bits); let chunks = left_chunks .iter() .zip(right_chunks.iter()) .map(|(left, right)| op(left, right)); let mut buffer = unsafe { MutableBuffer::from_trusted_len_iter(chunks) }; let remainder_bytes = ceil(left_chunks.remainder_len(), 8); let rem = op(left_chunks.remainder_bits(), right_chunks.remainder_bits()); let rem = &rem.to_le_bytes()[0..remainder_bytes]; buffer.extend_from_slice(rem); buffer.into() } pub fn bitwise_unary_op_helper<F>( left: &Buffer, offset_in_bits: usize, len_in_bits: usize, op: F, ) -> Buffer where F: Fn(u64) -> u64, { let mut result = MutableBuffer::new(ceil(len_in_bits, 8)).with_bitset(len_in_bits / 64 * 8, false); let left_chunks = left.bit_chunks(offset_in_bits, len_in_bits); let result_chunks = result.typed_data_mut::<u64>().iter_mut(); result_chunks .zip(left_chunks.iter()) .for_each(|(res, left)| { *res = op(left); }); let remainder_bytes = ceil(left_chunks.remainder_len(), 8); let rem = op(left_chunks.remainder_bits()); let rem = &rem.to_le_bytes()[0..remainder_bytes]; result.extend_from_slice(rem); result.into() } #[cfg(all(target_arch = "x86_64", feature = "avx512"))] pub fn buffer_bin_and( left: &Buffer, left_offset_in_bits: usize, right: &Buffer, right_offset_in_bits: usize, len_in_bits: usize, ) -> Buffer { if left_offset_in_bits % 8 == 0 && right_offset_in_bits % 8 == 0 && len_in_bits % 8 == 0 { let len = len_in_bits / 8; let left_offset = left_offset_in_bits / 8; let right_offset = right_offset_in_bits / 8; let mut result = MutableBuffer::new(len).with_bitset(len, false); let mut left_chunks = left.as_slice()[left_offset..].chunks_exact(AVX512_U8X64_LANES); let mut right_chunks = right.as_slice()[right_offset..].chunks_exact(AVX512_U8X64_LANES); let mut result_chunks = result.as_slice_mut().chunks_exact_mut(AVX512_U8X64_LANES); result_chunks .borrow_mut() .zip(left_chunks.borrow_mut().zip(right_chunks.borrow_mut())) .for_each(|(res, (left, right))| unsafe { avx512_bin_and(left, right, res); }); result_chunks .into_remainder() .iter_mut() .zip( left_chunks .remainder() .iter() .zip(right_chunks.remainder().iter()), ) .for_each(|(res, (left, right))| { *res = *left & *right; }); result.into() } else { bitwise_bin_op_helper( &left, left_offset_in_bits, right, right_offset_in_bits, len_in_bits, |a, b| a & b, ) } } #[cfg(all(feature = "simd", not(feature = "avx512")))] pub fn buffer_bin_and( left: &Buffer, left_offset_in_bits: usize, right: &Buffer, right_offset_in_bits: usize, len_in_bits: usize, ) -> Buffer { if left_offset_in_bits % 8 == 0 && right_offset_in_bits % 8 == 0 && len_in_bits % 8 == 0 { bitwise_bin_op_simd_helper( &left, left_offset_in_bits / 8, &right, right_offset_in_bits / 8, len_in_bits / 8, |a, b| a & b, |a, b| a & b, ) } else { bitwise_bin_op_helper( &left, left_offset_in_bits, right, right_offset_in_bits, len_in_bits, |a, b| a & b, ) } } #[cfg(all(not(any(feature = "simd", feature = "avx512"))))] pub fn buffer_bin_and( left: &Buffer, left_offset_in_bits: usize, right: &Buffer, right_offset_in_bits: usize, len_in_bits: usize, ) -> Buffer { bitwise_bin_op_helper( left, left_offset_in_bits, right, right_offset_in_bits, len_in_bits, |a, b| a & b, ) } #[cfg(all(target_arch = "x86_64", feature = "avx512"))] pub fn buffer_bin_or( left: &Buffer, left_offset_in_bits: usize, right: &Buffer, right_offset_in_bits: usize, len_in_bits: usize, ) -> Buffer { if left_offset_in_bits % 8 == 0 && right_offset_in_bits % 8 == 0 && len_in_bits % 8 == 0 { let len = len_in_bits / 8; let left_offset = left_offset_in_bits / 8; let right_offset = right_offset_in_bits / 8; let mut result = MutableBuffer::new(len).with_bitset(len, false); let mut left_chunks = left.as_slice()[left_offset..].chunks_exact(AVX512_U8X64_LANES); let mut right_chunks = right.as_slice()[right_offset..].chunks_exact(AVX512_U8X64_LANES); let mut result_chunks = result.as_slice_mut().chunks_exact_mut(AVX512_U8X64_LANES); result_chunks .borrow_mut() .zip(left_chunks.borrow_mut().zip(right_chunks.borrow_mut())) .for_each(|(res, (left, right))| unsafe { avx512_bin_or(left, right, res); }); result_chunks .into_remainder() .iter_mut() .zip( left_chunks .remainder() .iter() .zip(right_chunks.remainder().iter()), ) .for_each(|(res, (left, right))| { *res = *left | *right; }); result.into() } else { bitwise_bin_op_helper( &left, left_offset_in_bits, right, right_offset_in_bits, len_in_bits, |a, b| a | b, ) } } #[cfg(all(feature = "simd", not(feature = "avx512")))] pub fn buffer_bin_or( left: &Buffer, left_offset_in_bits: usize, right: &Buffer, right_offset_in_bits: usize, len_in_bits: usize, ) -> Buffer { if left_offset_in_bits % 8 == 0 && right_offset_in_bits % 8 == 0 && len_in_bits % 8 == 0 { bitwise_bin_op_simd_helper( &left, left_offset_in_bits / 8, &right, right_offset_in_bits / 8, len_in_bits / 8, |a, b| a | b, |a, b| a | b, ) } else { bitwise_bin_op_helper( &left, left_offset_in_bits, right, right_offset_in_bits, len_in_bits, |a, b| a | b, ) } } #[cfg(all(not(any(feature = "simd", feature = "avx512"))))] pub fn buffer_bin_or( left: &Buffer, left_offset_in_bits: usize, right: &Buffer, right_offset_in_bits: usize, len_in_bits: usize, ) -> Buffer { bitwise_bin_op_helper( left, left_offset_in_bits, right, right_offset_in_bits, len_in_bits, |a, b| a | b, ) } pub fn buffer_unary_not( left: &Buffer, offset_in_bits: usize, len_in_bits: usize, ) -> Buffer { #[cfg(feature = "simd")] if offset_in_bits % 8 == 0 && len_in_bits % 8 == 0 { return bitwise_unary_op_simd_helper( &left, offset_in_bits / 8, len_in_bits / 8, |a| !a, |a| !a, ); } #[allow(unreachable_code)] { bitwise_unary_op_helper(left, offset_in_bits, len_in_bits, |a| !a) } }
#[cfg(feature = "simd")] use crate::util::bit_util; #[cfg(feature = "simd")] use packed_simd::u8x64; #[cfg(feature = "avx512")] use crate::arch::avx512::*; use crate::util::bit_util::ceil; #[cfg(any(feature = "simd", feature = "avx512"))] use std::borrow::BorrowMut; use super::{Buffer, MutableBuffer}; #[cfg(feature = "simd")] pub fn bitwise_bin_op_simd_helper<F_SIMD, F_SCALAR>( left: &Buffer, left_offset: usize, right: &Buffer, right_offset: usize, len: usize, simd_op: F_SIMD, scalar_op: F_SCALAR, ) -> Buffer where F_SIMD: Fn(u8x64, u8x64) -> u8x64, F_SCALAR: Fn(u8, u8) -> u8, { let mut result = MutableBuffer::new(len).with_bitset(len, false); let lanes = u8x64::lanes(); let mut left_chunks = left.as_slice()[left_offset..].chunks_exact(lanes); let mut right_chunks = right.as_slice()[right_offset..].chunks_exact(lanes); let mut result_chunks = result.as_slice_mut().chunks_exact_mut(lanes); result_chunks .borrow_mut() .zip(left_chunks.borrow_mut().zip(right_chunks.borrow_mut())) .for_each(|(res, (left, right))| { unsafe { bit_util::bitwise_bin_op_simd(&left, &right, res, &simd_op) }; }); result_chunks .into_remainder() .iter_mut() .zip( left_chunks .remainder() .iter() .zip(right_chunks.remainder().iter()), ) .for_each(|(res, (left, right))| { *res = scalar_op(*left, *right); }); result.into() } #[cfg(feature = "simd")] pub fn bitwise_unary_op_simd_helper<F_SIMD, F_SCALAR>( left: &Buffer, left_offset: usize, len: usize, simd_op: F_SIMD, scalar_op: F_SCALAR, ) -> Buffer where F_SIMD: Fn(u8x64) -> u8x64, F_SCALAR: Fn(u8) -> u8, { let mut result = MutableBuffer::new(len).with_bitset(len, false); let lanes = u8x64::lanes(); let mut left_chunks = left.as_slice()[left_offset..].chunks_exact(lanes); let mut result_chunks = result.as_slice_mut().chunks_exact_mut(lanes); result_chunks .borrow_mut() .zip(left_chunks.borrow_mut()) .for_each(|(res, left)| unsafe { let data_simd = u8x64::from_slice_unaligned_unchecked(left); let simd_result = simd_op(data_simd); simd_result.write_to_slice_unaligned_unchecked(res); }); result_chunks .into_remainder() .iter_mut() .zip(left_chunks.remainder().iter()) .for_each(|(res, left)| { *res = scalar_op(*left); }); result.into() } pub fn bitwise_bin_op_helper<F>( left: &Buffer, left_offset_in_bits: usize, right: &Buffer, right_offset_in_bits: usize, len_in_bits: usize, op: F, ) -> Buffer where F: Fn(u64, u64) -> u64, { let left_chunks = left.bit_chunks(left_offset_in_bits, len_in_bits); let right_chunks = right.bit_chunks(right_offset_in_bits, len_in_bits); let chunks = left_chunks .iter() .zip(right_chunks.iter()) .map(|(left, right)| op(left, right)); let mut buffer = unsafe { MutableBuffer::from_trusted_len_iter(chunks) }; let remainder_bytes = ceil(left_chunks.remainder_len(), 8); let rem = op(left_chunks.remainder_bits(), right_chunks.remainder_bits()); let rem = &rem.to_le_bytes()[0..remainder_bytes]; buffer.extend_from_slice(rem); buffer.into() }
#[cfg(all(target_arch = "x86_64", feature = "avx512"))] pub fn buffer_bin_and( left: &Buffer, left_offset_in_bits: usize, right: &Buffer, right_offset_in_bits: usize, len_in_bits: usize, ) -> Buffer { if left_offset_in_bits % 8 == 0 && right_offset_in_bits % 8 == 0 && len_in_bits % 8 == 0 { let len = len_in_bits / 8; let left_offset = left_offset_in_bits / 8; let right_offset = right_offset_in_bits / 8; let mut result = MutableBuffer::new(len).with_bitset(len, false); let mut left_chunks = left.as_slice()[left_offset..].chunks_exact(AVX512_U8X64_LANES); let mut right_chunks = right.as_slice()[right_offset..].chunks_exact(AVX512_U8X64_LANES); let mut result_chunks = result.as_slice_mut().chunks_exact_mut(AVX512_U8X64_LANES); result_chunks .borrow_mut() .zip(left_chunks.borrow_mut().zip(right_chunks.borrow_mut())) .for_each(|(res, (left, right))| unsafe { avx512_bin_and(left, right, res); }); result_chunks .into_remainder() .iter_mut() .zip( left_chunks .remainder() .iter() .zip(right_chunks.remainder().iter()), ) .for_each(|(res, (left, right))| { *res = *left & *right; }); result.into() } else { bitwise_bin_op_helper( &left, left_offset_in_bits, right, right_offset_in_bits, len_in_bits, |a, b| a & b, ) } } #[cfg(all(feature = "simd", not(feature = "avx512")))] pub fn buffer_bin_and( left: &Buffer, left_offset_in_bits: usize, right: &Buffer, right_offset_in_bits: usize, len_in_bits: usize, ) -> Buffer { if left_offset_in_bits % 8 == 0 && right_offset_in_bits % 8 == 0 && len_in_bits % 8 == 0 { bitwise_bin_op_simd_helper( &left, left_offset_in_bits / 8, &right, right_offset_in_bits / 8, len_in_bits / 8, |a, b| a & b, |a, b| a & b, ) } else { bitwise_bin_op_helper( &left, left_offset_in_bits, right, right_offset_in_bits, len_in_bits, |a, b| a & b, ) } } #[cfg(all(not(any(feature = "simd", feature = "avx512"))))] pub fn buffer_bin_and( left: &Buffer, left_offset_in_bits: usize, right: &Buffer, right_offset_in_bits: usize, len_in_bits: usize, ) -> Buffer { bitwise_bin_op_helper( left, left_offset_in_bits, right, right_offset_in_bits, len_in_bits, |a, b| a & b, ) } #[cfg(all(target_arch = "x86_64", feature = "avx512"))] pub fn buffer_bin_or( left: &Buffer, left_offset_in_bits: usize, right: &Buffer, right_offset_in_bits: usize, len_in_bits: usize, ) -> Buffer { if left_offset_in_bits % 8 == 0 && right_offset_in_bits % 8 == 0 && len_in_bits % 8 == 0 { let len = len_in_bits / 8; let left_offset = left_offset_in_bits / 8; let right_offset = right_offset_in_bits / 8; let mut result = MutableBuffer::new(len).with_bitset(len, false); let mut left_chunks = left.as_slice()[left_offset..].chunks_exact(AVX512_U8X64_LANES); let mut right_chunks = right.as_slice()[right_offset..].chunks_exact(AVX512_U8X64_LANES); let mut result_chunks = result.as_slice_mut().chunks_exact_mut(AVX512_U8X64_LANES); result_chunks .borrow_mut() .zip(left_chunks.borrow_mut().zip(right_chunks.borrow_mut())) .for_each(|(res, (left, right))| unsafe { avx512_bin_or(left, right, res); }); result_chunks .into_remainder() .iter_mut() .zip( left_chunks .remainder() .iter() .zip(right_chunks.remainder().iter()), ) .for_each(|(res, (left, right))| { *res = *left | *right; }); result.into() } else { bitwise_bin_op_helper( &left, left_offset_in_bits, right, right_offset_in_bits, len_in_bits, |a, b| a | b, ) } } #[cfg(all(feature = "simd", not(feature = "avx512")))] pub fn buffer_bin_or( left: &Buffer, left_offset_in_bits: usize, right: &Buffer, right_offset_in_bits: usize, len_in_bits: usize, ) -> Buffer { if left_offset_in_bits % 8 == 0 && right_offset_in_bits % 8 == 0 && len_in_bits % 8 == 0 { bitwise_bin_op_simd_helper( &left, left_offset_in_bits / 8, &right, right_offset_in_bits / 8, len_in_bits / 8, |a, b| a | b, |a, b| a | b, ) } else { bitwise_bin_op_helper( &left, left_offset_in_bits, right, right_offset_in_bits, len_in_bits, |a, b| a | b, ) } } #[cfg(all(not(any(feature = "simd", feature = "avx512"))))] pub fn buffer_bin_or( left: &Buffer, left_offset_in_bits: usize, right: &Buffer, right_offset_in_bits: usize, len_in_bits: usize, ) -> Buffer { bitwise_bin_op_helper( left, left_offset_in_bits, right, right_offset_in_bits, len_in_bits, |a, b| a | b, ) } pub fn buffer_unary_not( left: &Buffer, offset_in_bits: usize, len_in_bits: usize, ) -> Buffer { #[cfg(feature = "simd")] if offset_in_bits % 8 == 0 && len_in_bits % 8 == 0 { return bitwise_unary_op_simd_helper( &left, offset_in_bits / 8, len_in_bits / 8, |a| !a, |a| !a, ); } #[allow(unreachable_code)] { bitwise_unary_op_helper(left, offset_in_bits, len_in_bits, |a| !a) } }
pub fn bitwise_unary_op_helper<F>( left: &Buffer, offset_in_bits: usize, len_in_bits: usize, op: F, ) -> Buffer where F: Fn(u64) -> u64, { let mut result = MutableBuffer::new(ceil(len_in_bits, 8)).with_bitset(len_in_bits / 64 * 8, false); let left_chunks = left.bit_chunks(offset_in_bits, len_in_bits); let result_chunks = result.typed_data_mut::<u64>().iter_mut(); result_chunks .zip(left_chunks.iter()) .for_each(|(res, left)| { *res = op(left); }); let remainder_bytes = ceil(left_chunks.remainder_len(), 8); let rem = op(left_chunks.remainder_bits()); let rem = &rem.to_le_bytes()[0..remainder_bytes]; result.extend_from_slice(rem); result.into() }
function_block-full_function
[ { "content": "fn bench_buffer_and(left: &Buffer, right: &Buffer) {\n\n criterion::black_box((left & right).unwrap());\n\n}\n\n\n", "file_path": "arrow/benches/buffer_bit_ops.rs", "rank": 2, "score": 380009.3854061781 }, { "content": "fn bench_buffer_or(left: &Buffer, right: &Buffer) {\n\n...
Rust
sdk/program/src/entrypoint_deprecated.rs
rob-ti/SAFE
315d06c27d3923472ef8f94f04be4bfe762dd91a
extern crate alloc; use crate::{account_info::AccountInfo, program_error::ProgramError, pubkey::Pubkey}; use alloc::vec::Vec; use std::{ cell::RefCell, mem::size_of, rc::Rc, result::Result as ResultGeneric, slice::{from_raw_parts, from_raw_parts_mut}, }; pub type ProgramResult = ResultGeneric<(), ProgramError>; pub type ProcessInstruction = fn(program_id: &Pubkey, accounts: &[AccountInfo], instruction_data: &[u8]) -> ProgramResult; pub const SUCCESS: u64 = 0; #[macro_export] macro_rules! entrypoint_deprecated { ($process_instruction:ident) => { #[no_mangle] pub unsafe extern "C" fn entrypoint(input: *mut u8) -> u64 { let (program_id, accounts, instruction_data) = unsafe { $crate::entrypoint_deprecated::deserialize(input) }; match $process_instruction(&program_id, &accounts, &instruction_data) { Ok(()) => $crate::entrypoint_deprecated::SUCCESS, Err(error) => error.into(), } } }; } #[allow(clippy::type_complexity)] pub unsafe fn deserialize<'a>(input: *mut u8) -> (&'a Pubkey, Vec<AccountInfo<'a>>, &'a [u8]) { let mut offset: usize = 0; #[allow(clippy::cast_ptr_alignment)] let num_accounts = *(input.add(offset) as *const u64) as usize; offset += size_of::<u64>(); let mut accounts = Vec::with_capacity(num_accounts); for _ in 0..num_accounts { let dup_info = *(input.add(offset) as *const u8); offset += size_of::<u8>(); if dup_info == std::u8::MAX { #[allow(clippy::cast_ptr_alignment)] let is_signer = *(input.add(offset) as *const u8) != 0; offset += size_of::<u8>(); #[allow(clippy::cast_ptr_alignment)] let is_writable = *(input.add(offset) as *const u8) != 0; offset += size_of::<u8>(); let key: &Pubkey = &*(input.add(offset) as *const Pubkey); offset += size_of::<Pubkey>(); #[allow(clippy::cast_ptr_alignment)] let lamports = Rc::new(RefCell::new(&mut *(input.add(offset) as *mut u64))); offset += size_of::<u64>(); #[allow(clippy::cast_ptr_alignment)] let data_len = *(input.add(offset) as *const u64) as usize; offset += size_of::<u64>(); let data = Rc::new(RefCell::new({ from_raw_parts_mut(input.add(offset), data_len) })); offset += data_len; let owner: &Pubkey = &*(input.add(offset) as *const Pubkey); offset += size_of::<Pubkey>(); #[allow(clippy::cast_ptr_alignment)] let executable = *(input.add(offset) as *const u8) != 0; offset += size_of::<u8>(); #[allow(clippy::cast_ptr_alignment)] let rent_epoch = *(input.add(offset) as *const u64); offset += size_of::<u64>(); accounts.push(AccountInfo { is_signer, is_writable, key, lamports, data, owner, executable, rent_epoch, }); } else { accounts.push(accounts[dup_info as usize].clone()); } } #[allow(clippy::cast_ptr_alignment)] let instruction_data_len = *(input.add(offset) as *const u64) as usize; offset += size_of::<u64>(); let instruction_data = { from_raw_parts(input.add(offset), instruction_data_len) }; offset += instruction_data_len; let program_id: &Pubkey = &*(input.add(offset) as *const Pubkey); (program_id, accounts, instruction_data) }
extern crate alloc; use crate::{account_info::AccountInfo, program_error::ProgramError, pubkey::Pubkey}; use alloc::vec::Vec; use std::{ cell::RefCell, mem::size_of, rc::Rc, result::Result as ResultGeneric, slice::{from_raw_parts, from_raw_parts_mut}, }; pub type ProgramResult = ResultGeneric<(), ProgramError>; pub type ProcessInstruction = fn(program_id: &Pubkey, accounts: &[AccountInfo], instruction_data: &[u8]) -> ProgramResult; pub const SUCCESS: u64 = 0; #[macro_export] macro_rules! entrypoint_deprecated { ($process_instruction:ident) => { #[no_mangle] pub unsafe extern "C" fn entrypoint(input: *mut u8) -> u64 { let (program_id, accounts, instruction_data) = unsafe { $crate::entrypoint_deprecated::deserialize(input) }; match $process_instruction(&program_id, &accounts, &instruction_data) { Ok(()) => $crate::entrypoint_deprecated::SUCCESS, Err(error) => error.into(), } } }; } #[allow(clippy::type_complexity)] pub unsafe fn deserialize<'a>(input: *mut u8) -> (&'a Pubkey, Vec<AccountInfo<'a>>, &'a [u8]) { let mut offset: usize = 0; #[allow(clippy::cast_ptr_alignment)] let num_accounts = *(input.add(offset) as *const u64) as usize; offset += size_of::<u64>();
let mut accounts = Vec::with_capacity(num_accounts); for _ in 0..num_accounts { let dup_info = *(input.add(offset) as *const u8); offset += size_of::<u8>(); if dup_info == std::u8::MAX { #[allow(clippy::cast_ptr_alignment)] let is_signer = *(input.add(offset) as *const u8) != 0; offset += size_of::<u8>(); #[allow(clippy::cast_ptr_alignment)] let is_writable = *(input.add(offset) as *const u8) != 0; offset += size_of::<u8>(); let key: &Pubkey = &*(input.add(offset) as *const Pubkey); offset += size_of::<Pubkey>(); #[allow(clippy::cast_ptr_alignment)] let lamports = Rc::new(RefCell::new(&mut *(input.add(offset) as *mut u64))); offset += size_of::<u64>(); #[allow(clippy::cast_ptr_alignment)] let data_len = *(input.add(offset) as *const u64) as usize; offset += size_of::<u64>(); let data = Rc::new(RefCell::new({ from_raw_parts_mut(input.add(offset), data_len) })); offset += data_len; let owner: &Pubkey = &*(input.add(offset) as *const Pubkey); offset += size_of::<Pubkey>(); #[allow(clippy::cast_ptr_alignment)] let executable = *(input.add(offset) as *const u8) != 0; offset += size_of::<u8>(); #[allow(clippy::cast_ptr_alignment)] let rent_epoch = *(input.add(offset) as *const u64); offset += size_of::<u64>(); accounts.push(AccountInfo { is_signer, is_writable, key, lamports, data, owner, executable, rent_epoch, }); } else { accounts.push(accounts[dup_info as usize].clone()); } } #[allow(clippy::cast_ptr_alignment)] let instruction_data_len = *(input.add(offset) as *const u64) as usize; offset += size_of::<u64>(); let instruction_data = { from_raw_parts(input.add(offset), instruction_data_len) }; offset += instruction_data_len; let program_id: &Pubkey = &*(input.add(offset) as *const Pubkey); (program_id, accounts, instruction_data) }
function_block-function_prefix_line
[ { "content": "/// Create `AccountInfo`s\n\npub fn create_account_infos(accounts: &mut [(Pubkey, Account)]) -> Vec<AccountInfo> {\n\n accounts.iter_mut().map(Into::into).collect()\n\n}\n\n\n", "file_path": "sdk/src/account.rs", "rank": 0, "score": 425486.5331603654 }, { "content": "pub fn ...
Rust
src/config.rs
AmaranthineCodices/whimsy
e46684a0e66277a18694324268e8635cdc22f054
use std::default::Default; use std::path::{Path, PathBuf}; use crate::keybind; lazy_static::lazy_static! { pub static ref DEFAULT_CONFIG_PATH: PathBuf = { let mut cfg_dir = dirs::config_dir().expect("Could not find user configuration directory."); cfg_dir.push("whimsy"); cfg_dir.push("whimsy.yaml"); cfg_dir }; } #[derive(Debug, thiserror::Error)] pub enum ConfigReadError { #[error("could not read config file: {0}")] IoError(std::io::Error), #[error("could not deserialize config file contents: {0}")] DeserializeError(serde_yaml::Error), } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize)] #[serde(default)] pub struct ConfigDirectives { #[serde(rename = "live-reload")] pub live_reload_configuration: bool, } impl Default for ConfigDirectives { fn default() -> Self { ConfigDirectives { live_reload_configuration: false, } } } #[derive(Debug, Copy, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "kebab-case")] pub enum Direction { Up, Left, Right, Down, } #[derive(Debug, Copy, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "kebab-case")] pub enum Metric { Percent(f32), Absolute(f32), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "kebab-case")] pub enum Action { Push { direction: Direction, fraction: f32, }, Nudge { direction: Direction, distance: Metric, }, } #[derive(Debug, serde::Serialize, serde::Deserialize)] pub struct Binding { pub key: keybind::Key, pub modifiers: Vec<keybind::Modifier>, pub action: Action, } #[derive(Debug, serde::Serialize, serde::Deserialize)] #[serde(default)] pub struct Config { pub directives: ConfigDirectives, pub bindings: Vec<Binding>, } impl Default for Config { fn default() -> Self { Config { directives: ConfigDirectives::default(), bindings: vec![ Binding { key: keybind::Key::Left, modifiers: vec![keybind::Modifier::Super, keybind::Modifier::Shift], action: Action::Push { direction: Direction::Left, fraction: 2.0, }, }, Binding { key: keybind::Key::Left, modifiers: vec![ keybind::Modifier::Super, keybind::Modifier::Shift, keybind::Modifier::Alt, ], action: Action::Nudge { direction: Direction::Left, distance: Metric::Absolute(100.0), }, }, ], } } } pub fn read_config_from_file(path: &dyn AsRef<Path>) -> Result<Option<Config>, ConfigReadError> { if !path.as_ref().exists() { return Ok(None); } let config_string = std::fs::read_to_string(path).map_err(|e| ConfigReadError::IoError(e))?; serde_yaml::from_str(&config_string).map_err(|e| ConfigReadError::DeserializeError(e)) } pub fn create_default_config() -> std::io::Result<()> { let default_config = Config::default(); let default_path: &PathBuf = &DEFAULT_CONFIG_PATH; let config_string = serde_yaml::to_string(&default_config).unwrap(); std::fs::create_dir_all(&default_path.parent().unwrap())?; std::fs::write(&default_path, &config_string)?; Ok(()) }
use std::default::Default; use std::path::{Path, PathBuf}; use crate::keybind; lazy_static::lazy_static! { pub static ref DEFAULT_CONFIG_PATH: PathBuf = { let mut cfg_dir = dirs::config_dir().expect("Could not find user configuration directory."); cfg_dir.push("whimsy"); cfg_dir.push("whimsy.yaml"); cfg_dir }; } #[derive(Debug, thiserror::Error)] pub enum ConfigReadError { #[error("could not read config file: {0}")] IoError(std::io::Error), #[error("could not deserialize config file contents: {0}")] DeserializeError(serde_yaml::Error), } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize)] #[serde(default)] pub struct ConfigDirectives { #[serde(rename = "live-reload")] pub live_reload_configuration: bool, } impl Default for ConfigDirectives { fn default() -> Self { ConfigDirectives { live_reload_configuration: false, } } } #[derive(Debug, Copy, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "kebab-case")] pub enum Direction { Up, Left, Right, Down, } #[derive(Debug, Copy, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "kebab-case")] pub enum Metric { Percent(f32), Absolute(f32), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "kebab-case")] pub enum Action { Push { direction: Direction, fraction: f32, }, Nudge { direction: Direction, distance: Metric, }, } #[derive(Debug, serde::Serialize, serde::Deserialize)] pub struct Binding { pub key: keybind::Key, pub modifiers: Vec<keybind::Modifier>, pub action: Action, } #[derive(Debug, serde::Serialize, serde::Deserialize)] #[serde(default)] pub struct Config { pub directives: ConfigDirectives, pub bindings: Vec<Binding>, } impl Default for Config {
} pub fn read_config_from_file(path: &dyn AsRef<Path>) -> Result<Option<Config>, ConfigReadError> { if !path.as_ref().exists() { return Ok(None); } let config_string = std::fs::read_to_string(path).map_err(|e| ConfigReadError::IoError(e))?; serde_yaml::from_str(&config_string).map_err(|e| ConfigReadError::DeserializeError(e)) } pub fn create_default_config() -> std::io::Result<()> { let default_config = Config::default(); let default_path: &PathBuf = &DEFAULT_CONFIG_PATH; let config_string = serde_yaml::to_string(&default_config).unwrap(); std::fs::create_dir_all(&default_path.parent().unwrap())?; std::fs::write(&default_path, &config_string)?; Ok(()) }
fn default() -> Self { Config { directives: ConfigDirectives::default(), bindings: vec![ Binding { key: keybind::Key::Left, modifiers: vec![keybind::Modifier::Super, keybind::Modifier::Shift], action: Action::Push { direction: Direction::Left, fraction: 2.0, }, }, Binding { key: keybind::Key::Left, modifiers: vec![ keybind::Modifier::Super, keybind::Modifier::Shift, keybind::Modifier::Alt, ], action: Action::Nudge { direction: Direction::Left, distance: Metric::Absolute(100.0), }, }, ], } }
function_block-full_function
[ { "content": "fn modifier_to_flag_code(modifier: &Modifier) -> isize {\n\n match modifier {\n\n Modifier::Control => winuser::MOD_CONTROL,\n\n Modifier::Alt => winuser::MOD_ALT,\n\n Modifier::Shift => winuser::MOD_SHIFT,\n\n Modifier::Super => winuser::MOD_WIN,\n\n }\n\n}\n\n\n...
Rust
src/codegen.rs
tamaroning/ironcc
c75f6dfc300ee44154cd68b5d7f3801bfeb40279
extern crate llvm_sys as llvm; use self::llvm::core::*; use self::llvm::prelude::*; use crate::node; use crate::types; /* use self::llvm::execution_engine; use self::llvm::target::*; use llvm::execution_engine::LLVMCreateExecutionEngineForModule; use llvm::execution_engine::LLVMDisposeExecutionEngine; use llvm::execution_engine::LLVMGetFunctionAddress; use llvm::execution_engine::LLVMLinkInMCJIT; use std::mem; */ use node::{BinaryOps, UnaryOps, AST}; use std::collections::HashMap; use std::ffi::CString; use std::ptr; use types::Type; #[derive(Debug)] pub struct VarInfo { ty: Type, llvm_val: LLVMValueRef, } impl VarInfo { pub fn new(ty: Type, llvm_val: LLVMValueRef) -> VarInfo { VarInfo { ty: ty, llvm_val: llvm_val, } } } pub struct Codegen { context: LLVMContextRef, module: LLVMModuleRef, builder: LLVMBuilderRef, cur_func: Option<LLVMValueRef>, local_varmap: Vec<HashMap<String, VarInfo>>, } pub unsafe fn cstr(s: &'static str) -> CString { CString::new(s).unwrap() } pub unsafe fn is_exist_terminator(builder: LLVMBuilderRef) -> bool { LLVMIsATerminatorInst(LLVMGetLastInstruction(LLVMGetInsertBlock(builder))) != ptr::null_mut() } pub unsafe fn inside_load(ast: &AST) -> &AST { match ast { AST::Load(node) => node, _ => panic!("Error: ast load"), } } impl Codegen { pub unsafe fn new(mod_name: &str) -> Codegen { let c_mod_name = CString::new(mod_name).unwrap(); Codegen { context: LLVMContextCreate(), module: LLVMModuleCreateWithNameInContext(c_mod_name.as_ptr(), LLVMContextCreate()), builder: LLVMCreateBuilderInContext(LLVMContextCreate()), cur_func: None, local_varmap: Vec::new(), } } pub unsafe fn typecast(&mut self, val: LLVMValueRef, to: LLVMTypeRef) -> LLVMValueRef { let from = LLVMTypeOf(val); match LLVMGetTypeKind(from) { llvm::LLVMTypeKind::LLVMPointerTypeKind => match LLVMGetTypeKind(to) { llvm::LLVMTypeKind::LLVMIntegerTypeKind => { return LLVMBuildPtrToInt(self.builder, val, to, cstr("cast").as_ptr()); } _ => panic!(), }, _ => val, } } pub unsafe fn type_to_llvmty(&self, ty: &Type) -> LLVMTypeRef { match &ty { Type::Int => LLVMInt32Type(), Type::Ptr(basety) => LLVMPointerType(self.type_to_llvmty(&*basety), 0), Type::Func(ret_type, param_types, _) => LLVMFunctionType( self.type_to_llvmty(ret_type), || -> *mut LLVMTypeRef { let mut param_llvm_types: Vec<LLVMTypeRef> = Vec::new(); for param_type in param_types { param_llvm_types.push(self.type_to_llvmty(param_type)); } param_llvm_types.as_mut_slice().as_mut_ptr() }(), param_types.len() as u32, 0, ), _ => panic!("Unsupported type"), } } pub unsafe fn dump_module(&self) { LLVMDumpModule(self.module); } pub unsafe fn write_llvm_bc(&mut self) { llvm::bit_writer::LLVMWriteBitcodeToFile(self.module, cstr("a.bc").as_ptr()); } pub unsafe fn gen_program(&mut self, program: Vec<AST>) { for top_level in program { match top_level { AST::FuncDef(func_ty, func_name, body) => { self.gen_func_def(func_ty, func_name, body); } _ => panic!("Unsupported node type"), } } LLVMDisposeBuilder(self.builder); /* //JIT exec // build engine let mut ee = mem::uninitialized(); let mut out = mem::zeroed(); //LLVMLinkInMCJIT(); LLVM_InitializeNativeTarget(); LLVM_InitializeNativeAsmParser(); LLVM_InitializeNativeAsmParser(); //LLVMInitializeX LLVMCreateExecutionEngineForModule(&mut ee, self.module, &mut out); let addr = LLVMGetFunctionAddress(ee, b"main\0".as_ptr() as *const _); let f: extern "C" fn() -> i32 = mem::transmute(addr); println!("ret = {}", f()); LLVMDisposeExecutionEngine(ee); LLVMContextDispose(self.context); */ } pub unsafe fn gen_func_def(&mut self, func_ty: Box<Type>, func_name: String, body: Box<AST>) { let func_ty = self.type_to_llvmty(&func_ty); let func = LLVMAddFunction(self.module, CString::new(func_name.as_str()).unwrap().as_ptr(), func_ty); let bb_entry = LLVMAppendBasicBlock(func, cstr("entry").as_ptr()); LLVMPositionBuilderAtEnd(self.builder, bb_entry); self.cur_func = Some(func); self.local_varmap.push(HashMap::new()); self.gen(&*body); if !is_exist_terminator(self.builder) { LLVMBuildRet(self.builder, self.make_int(0, false).unwrap().0); } self.local_varmap.pop(); } pub unsafe fn gen(&mut self, ast: &AST) -> Option<(LLVMValueRef, Option<Type>)> { match &ast { AST::Block(ref block) => self.gen_block(block), AST::UnaryOp(ref ast, ref op) => self.gen_unary_op(&**ast, &*op), AST::BinaryOp(ref lhs, ref rhs, ref op) => self.gen_binary_op(&**lhs, &**rhs, &*op), AST::Int(ref n) => self.make_int(*n as u64, false), AST::If(ref cond, ref then, ref els) => self.gen_if(&**cond, &**then, &**els), AST::For(ref init, ref cond, ref step, ref body) => self.gen_for(&**init, &**cond, &**step, &**body), AST::Return(None) => Some((LLVMBuildRetVoid(self.builder), None)), AST::Return(Some(ref val)) => self.gen_return(val), AST::Load(ref expr) => self.gen_load(expr), AST::Variable(ref name) => self.gen_var(name), AST::VariableDecl(ref ty, ref name, ref init_opt) => { self.gen_local_var_decl(ty, name, init_opt) } _ => None, } } pub unsafe fn gen_block(&mut self, block: &Vec<AST>) -> Option<(LLVMValueRef, Option<Type>)> { for ast in block { self.gen(ast); } None } pub unsafe fn gen_local_var_decl( &mut self, ty: &Type, name: &String, init_opt: &Option<Box<AST>>, ) -> Option<(LLVMValueRef, Option<Type>)> { let func = self.cur_func.unwrap(); let builder = LLVMCreateBuilderInContext(self.context); let entry_bb = LLVMGetEntryBasicBlock(func); let first_inst = LLVMGetFirstInstruction(entry_bb); if first_inst == ptr::null_mut() { LLVMPositionBuilderAtEnd(builder, entry_bb); } else { LLVMPositionBuilderBefore(builder, first_inst); } let llvm_ty = self.type_to_llvmty(ty); let var = LLVMBuildAlloca(builder, llvm_ty, CString::new(name.as_str()).unwrap().as_ptr()); self.local_varmap .last_mut() .unwrap() .insert(name.clone(), VarInfo::new(ty.clone(), var)); if let Some(init) = init_opt { self.gen_assign(&AST::Variable(name.clone()), &init); } None } pub unsafe fn gen_unary_op( &mut self, ast: &AST, op: &UnaryOps, ) -> Option<(LLVMValueRef, Option<Type>)> { let res = match op { UnaryOps::Plus => self.gen(ast), UnaryOps::Minus => { let val = self.gen(ast).unwrap().0; let neg = LLVMBuildNeg(self.builder, val, cstr("neg").as_ptr()); Some((neg, Some(Type::Int))) } UnaryOps::Addr => self.gen(inside_load(ast)), UnaryOps::Deref => self.gen_load(ast), _ => panic!("Unsupported unary op"), }; res } pub unsafe fn gen_binary_op( &mut self, lhs: &AST, rhs: &AST, op: &BinaryOps, ) -> Option<(LLVMValueRef, Option<Type>)> { if let BinaryOps::Assign = op { return self.gen_assign(&inside_load(lhs), rhs); } let (lhs_val, lhs_ty) = self.gen(&*lhs).unwrap(); let (rhs_val, rhs_ty) = self.gen(&*rhs).unwrap(); let lhs_ty = lhs_ty.unwrap(); let rhs_ty = rhs_ty.unwrap(); if matches!(&lhs_ty, Type::Ptr(_)) { return self.gen_ptr_binary_op(lhs_val, rhs_val, lhs_ty, op); } else if matches!(&rhs_ty, Type::Ptr(_)) { return self.gen_ptr_binary_op(lhs_val, rhs_val, rhs_ty, op); } self.gen_int_binary_op(&lhs_val, &rhs_val, lhs_ty, op) } pub unsafe fn gen_ptr_binary_op( &mut self, lhs_val: LLVMValueRef, rhs_val: LLVMValueRef, ty: Type, op: &BinaryOps, ) -> Option<(LLVMValueRef, Option<Type>)> { let mut numidx = vec![match *op { BinaryOps::Add => rhs_val, BinaryOps::Sub => LLVMBuildSub( self.builder, self.make_int(0, true).unwrap().0, rhs_val, cstr("sub").as_ptr(), ), _ => panic!(), }]; let ret = LLVMBuildGEP( self.builder, lhs_val, numidx.as_mut_slice().as_mut_ptr(), 1, cstr("add").as_ptr(), ); Some((ret, Some(ty))) } pub unsafe fn gen_int_binary_op( &mut self, lhs_val: &LLVMValueRef, rhs_val: &LLVMValueRef, ty: Type, op: &BinaryOps, ) -> Option<(LLVMValueRef, Option<Type>)> { let res = match op { BinaryOps::Add => LLVMBuildAdd(self.builder, *lhs_val, *rhs_val, cstr("add").as_ptr()), BinaryOps::Sub => LLVMBuildSub(self.builder, *lhs_val, *rhs_val, cstr("sub").as_ptr()), BinaryOps::Mul => LLVMBuildMul(self.builder, *lhs_val, *rhs_val, cstr("mul").as_ptr()), BinaryOps::Div => LLVMBuildSDiv(self.builder, *lhs_val, *rhs_val, cstr("sdiv").as_ptr()), BinaryOps::Eq => LLVMBuildICmp( self.builder, llvm::LLVMIntPredicate::LLVMIntEQ, *lhs_val, *rhs_val, cstr("eql").as_ptr(), ), BinaryOps::Ne => LLVMBuildICmp( self.builder, llvm::LLVMIntPredicate::LLVMIntNE, *lhs_val, *rhs_val, cstr("ne").as_ptr(), ), BinaryOps::Lt => LLVMBuildICmp( self.builder, llvm::LLVMIntPredicate::LLVMIntSLT, *lhs_val, *rhs_val, cstr("lt").as_ptr(), ), BinaryOps::Le => LLVMBuildICmp( self.builder, llvm::LLVMIntPredicate::LLVMIntSLE, *lhs_val, *rhs_val, cstr("le").as_ptr(), ), _ => panic!("Unsupported bianry op"), }; Some((res, Some(ty))) } pub unsafe fn gen_load(&mut self, ast: &AST) -> Option<(LLVMValueRef, Option<Type>)> { match ast { AST::Variable(ref name) => { let (val, ty) = self.gen(ast).unwrap(); let ty = ty.unwrap(); let ret = LLVMBuildLoad(self.builder, val, cstr("var").as_ptr()); match ty { Type::Ptr(origin_ty) => Some((ret, Some(*origin_ty))), _ => panic!(), } }, _ => { let (val, ty) = self.gen(ast).unwrap(); let ret = LLVMBuildLoad(self.builder, val, cstr("var").as_ptr()); Some((ret, Some(Type::Ptr(Box::new(ty.unwrap()))))) }, } } pub unsafe fn gen_var(&mut self, name: &String) -> Option<(LLVMValueRef, Option<Type>)> { if self.local_varmap.is_empty() { panic!(); } let mut i = (self.local_varmap.len() - 1) as isize; while i >= 0 { let var_info_opt = self.local_varmap[i as usize].get(name); match var_info_opt { Some(ref var_info) => { return Some(( var_info.llvm_val, Some(Type::Ptr(Box::new(var_info.ty.clone()))), )); } _ => (), } i -= 1; } panic!("local variable not found"); } pub unsafe fn gen_assign( &mut self, lhs: &AST, rhs: &AST, ) -> Option<(LLVMValueRef, Option<Type>)> { let (rhs_val, ty) = self.gen(rhs).unwrap(); let (dst, dst_ty) = self.gen(lhs).unwrap(); LLVMBuildStore(self.builder, rhs_val, dst); let load = LLVMBuildLoad(self.builder, dst, cstr("load").as_ptr()); Some((load, dst_ty)) } pub unsafe fn gen_if(&mut self, cond: &AST, then: &AST, els: &AST) -> Option<(LLVMValueRef, Option<Type>)> { let cond_val = self.gen(cond).unwrap().0; let func = self.cur_func.unwrap(); let bb_then = LLVMAppendBasicBlock(func, cstr("then").as_ptr()); let bb_else = LLVMAppendBasicBlock(func, cstr("else").as_ptr()); let bb_endif = LLVMAppendBasicBlock(func, cstr("endif").as_ptr()); LLVMBuildCondBr(self.builder, cond_val, bb_then, bb_else); LLVMPositionBuilderAtEnd(self.builder, bb_then); self.gen(then); if !is_exist_terminator(self.builder) { LLVMBuildBr(self.builder, bb_endif); } LLVMPositionBuilderAtEnd(self.builder, bb_else); self.gen(els); if !is_exist_terminator(self.builder) { LLVMBuildBr(self.builder, bb_endif); } LLVMPositionBuilderAtEnd(self.builder, bb_endif); None } pub unsafe fn gen_for(&mut self, init: &AST, cond: &AST, step: &AST, body: &AST) -> Option<(LLVMValueRef, Option<Type>)> { self.gen(init); let func = self.cur_func.unwrap(); let bb_begin = LLVMAppendBasicBlock(func, cstr("begin").as_ptr()); let bb_body = LLVMAppendBasicBlock(func, cstr("body").as_ptr()); let bb_update = LLVMAppendBasicBlock(func, cstr("update").as_ptr()); let bb_end = LLVMAppendBasicBlock(func, cstr("end").as_ptr()); LLVMBuildBr(self.builder, bb_begin); LLVMPositionBuilderAtEnd(self.builder, bb_begin); let cond_val = self.gen(cond).unwrap().0; LLVMBuildCondBr(self.builder, cond_val, bb_body, bb_end); LLVMPositionBuilderAtEnd(self.builder, bb_body); self.gen(body); if !is_exist_terminator(self.builder) { LLVMBuildBr(self.builder, bb_update); } LLVMPositionBuilderAtEnd(self.builder, bb_update); self.gen(step); if !is_exist_terminator(self.builder) { LLVMBuildBr(self.builder, bb_begin); } LLVMPositionBuilderAtEnd(self.builder, bb_end); None } pub unsafe fn gen_return(&mut self, ast: &AST) -> Option<(LLVMValueRef, Option<Type>)> { let ret_val = self.gen(ast); LLVMBuildRet(self.builder, ret_val.unwrap().0); None } pub unsafe fn make_int( &mut self, n: u64, is_unsigned: bool, ) -> Option<(LLVMValueRef, Option<Type>)> { Some(( LLVMConstInt(LLVMInt32Type(), n, if is_unsigned { 1 } else { 0 }), Some(Type::Int), )) } }
extern crate llvm_sys as llvm; use self::llvm::core::*; use self::llvm::prelude::*; use crate::node; use crate::types; /* use self::llvm::execution_engine; use self::llvm::target::*; use llvm::execution_engine::LLVMCreateExecutionEngineForModule; use llvm::execution_engine::LLVMDisposeExecutionEngine; use llvm::execution_engine::LLVMGetFunctionAddress; use llvm::execution_engine::LLVMLinkInMCJIT; use std::mem; */ use node::{BinaryOps, UnaryOps, AST}; use std::collections::HashMap; use std::ffi::CString; use std::ptr; use types::Type; #[derive(Debug)] pub struct VarInfo { ty: Type, llvm_val: LLVMValueRef, } impl VarInfo { pub fn new(ty: Type, llvm_val: LLVMValueRef) -> VarInfo { VarInfo { ty: ty, llvm_val: llvm_val, } } } pub struct Codegen { context: LLVMContextRef, module: LLVMModuleRef, builder: LLVMBuilderRef, cur_func: Option<LLVMValueRef>, local_varmap: Vec<HashMap<String, VarInfo>>, } pub unsafe fn cstr(s: &'static str) -> CString { CString::new(s).unwrap() } pub unsafe fn is_exist_terminator(builder: LLVMBuilderRef) -> bool { LLVMIsATerminatorInst(LLVMGetLastInstruction(LLVMGetInsertBlock(builder))) != ptr::null_mut() } pub unsafe fn inside_load(ast: &AST) -> &AST { match ast { AST::Load(node) => node, _ => panic!("Error: ast load"), } } impl Codegen { pub unsafe fn new(mod_name: &str) -> Codegen { let c_mod_name = CString::new(mod_name).unwrap(); Codegen { context: LLVMContextCreate(), module: LLVMModuleCreateWithNameInContext(c_mod_name.as_ptr(), LLVMContextCreate()), builder: LLVMCreateBuilderInContext(LLVMContextCreate()), cur_func: None, local_varmap: Vec::new(), } } pub unsafe fn typecast(&mut self, val: LLVMValueRef, to: LLVMTypeRef) -> LLVMValueRef { let from = LLVMTypeOf(val); match LLVMGetTypeKind(from) { llvm::LLVMTypeKind::LLVMPointerTypeKind => match LLVMGetTypeKind(to) { llvm::LLVMTypeKind::LLVMIntegerTypeKind => { return LLVMBuildPtrToInt(self.builder, val, to, cstr("cast").as_ptr()); } _ => panic!(), }, _ => val, } } pub unsafe fn type_to_llvmty(&self, ty: &Type) -> LLVMTypeRef { match &ty { Type::Int => LLVMInt32Type(), Type::Ptr(basety) => LLVMPointerType(self.type_to_llvmty(&*basety), 0), Type::Func(ret_type, param_types, _) => LLVMFunctionType( self.type_to_llvmty(ret_type), || -> *mut LLVMTypeRef { let mut param_llvm_types: Vec<LLVMTypeRef> = Vec::new(); for param_type in param_types { param_llvm_types.push(self.type_to_llvmty(param_type)); } param_llvm_types.as_mut_slice().as_mut_ptr() }(), param_types.len() as u32, 0, ), _ => panic!("Unsupported type"), } } pub unsafe fn dump_module(&self) { LLVMDumpModule(self.module); } pub unsafe fn write_llvm_bc(&mut self) { llvm::bit_writer::LLVMWriteBitcodeToFile(self.module, cstr("a.bc").as_ptr()); } pub unsafe fn gen_program(&mut self, program: Vec<AST>) { for top_level in program { match top_level { AST::FuncDef(func_ty, func_name, body) => { self.gen_func_def(func_ty, func_name, body); } _ => panic!("Unsupported node type"), } } LLVMDisposeBuilder(self.builder); /* //JIT exec // build engine let mut ee = mem::uninitialized(); let mut out = mem::zeroed(); //LLVMLinkInMCJIT(); LLVM_InitializeNativeTarget(); LLVM_InitializeNativeAsmParser(); LLVM_InitializeNativeAsmParser(); //LLVMInitializeX LLVMCreateExecutionEngineForModule(&mut ee, self.module, &mut out); let addr = LLVMGetFunctionAddress(ee, b"main\0".as_ptr() as *const _); let f: extern "C" fn() -> i32 = mem::transmute(addr); println!("ret = {}", f()); LLVMDisposeExecutionEngine(ee); LLVMContextDispose(self.context); */ } pub unsafe fn gen_func_def(&mut self, func_ty: Box<Type>, func_name: String, body: Box<AST>) { let func_ty = self.type_to_llvmty(&func_ty); let func = LLVMAddFunction(self.module, CString::new(func_name.as_str()).unwrap().as_ptr(), func_ty); let bb_entry = LLVMAppendBasicBlock(func, cstr("entry").as_ptr()); LLVMPositionBuilderAtEnd(self.builder, bb_entry); self.cur_func = Some(func); self.local_varmap.push(HashMap::new()); self.gen(&*body); if !is_exist_terminator(self.builder) { LLVMBuildRet(self.builder, self.make_int(0, false).unwrap().0); } self.local_varmap.pop(); } pub unsafe fn gen(&mut self, ast: &AST) -> Option<(LLVMValueRef, Option<Type>)> { match &ast { AST::Block(ref block) => self.gen_block(block), AST::UnaryOp(ref ast, ref op) => self.gen_unary_op(&**ast, &*op), AST::BinaryOp(ref lhs, ref rhs, ref op) => self.gen_binary_op(&**lhs, &**rhs, &*op), AST::Int(ref n) => self.make_int(*n as u64, false), AST::If(ref cond, ref then, ref els) => self.gen_if(&**cond, &**then, &**els), AST::For(ref init, ref cond, ref step, ref body) => self.gen_for(&**init, &**cond, &**step, &**body), AST::Return(None) => Some((LLVMBuildRetVoid(self.builder), None)), AST::Return(Some(ref val)) => self.gen_return(val), AST::Load(ref expr) => self.gen_load(expr), AST::Variable(ref name) => self.gen_var(name), AST::VariableDecl(ref ty, ref name, ref init_opt) => { self.gen_local_var_decl(ty, name, init_opt) } _ => None, } } pub unsafe fn gen_block(&mut self, block: &Vec<AST>) -> Option<(LLVMValueRef, Option<Type>)> { for ast in block { self.gen(ast); } None } pub unsafe fn gen_local_var_decl( &mut self, ty: &Type, name: &String, init_opt: &Option<Box<AST>>, ) -> Option<(LLVMValueRef, Option<Type>)> { let func = self.cur_func.unwrap(); let builder = LLVMCreateBuilderInContext(self.context); let entry_bb = LLVMGetEntryBasicBlock(func); let first_inst = LLVMGetFirstInstruction(entry_bb); if first_inst == ptr::null_mut() { LLVMPositionBuilderAtEnd(builder, entry_bb); } else { LLVMPositionBuilderBefore(builder, first_inst); } let llvm_ty = self.type_to_llvmty(ty); let var = LLVMBuildAlloca(builder, llvm_ty, CString::new(name.as_str()).unwrap().as_ptr()); self.local_varmap .last_mut() .unwrap() .insert(name.clone(), VarInfo::new(ty.clone(), var)); if let Some(init) = init_opt { self.gen_assign(&AST::Variable(name.clone()), &init); } None } pub unsafe fn gen_unary_op( &mut self, ast: &AST, op: &UnaryOps, ) -> Option<(LLVMValueRef, Option<Type>)> { let res = match op { UnaryOps::Plus => self.gen(ast), UnaryOps::Minus => { let val = self.gen(ast).unwrap().0; let neg = LLVMBuildNeg(self.builder, val, cstr("neg").as_ptr()); Some((neg, Some(Type::Int))) } UnaryOps::Addr => self.gen(inside_load(ast)), UnaryOps::Deref => self.gen_load(ast), _ => panic!("Unsupported unary op"), }; res } pub unsafe fn gen_binary_op( &mut self, lhs: &AST, rhs: &AST, op: &BinaryOps, ) -> Option<(LLVMValueRef, Option<Type>)> { if let BinaryOps::Assign = op { return self.gen_assign(&inside_load(lhs), rhs); } let (lhs_val, lhs_ty) = self.gen(&*lhs).unwrap(); let (rhs_val, rhs_ty) = self.gen(&*rhs).unwrap(); let lhs_ty = lhs_ty.unwrap(); let rhs_ty = rhs_ty.unwrap(); if matches!(&lhs_ty, Type::Ptr(_)) { return self.gen_ptr_binary_op(lhs_val, rhs_val, lhs_ty, op); } else if matches!(&rhs_ty, Type::Ptr(_)) { return self.gen_ptr_binary_op(lhs_val, rhs_val, rhs_ty, op); } self.gen_int_binary_op(&lhs_val, &rhs_val, lhs_ty, op) } pub unsafe fn gen_ptr_binary_op( &mut self, lhs_val: LLVMValueRef, rhs_val: LLVMValueRef, ty: Type, op: &BinaryOps, ) -> Option<(LLVMValueRef, Option<Type>)> { let mut numidx = vec![match *op { BinaryOps::Add => rhs_val, BinaryOps::Sub => LLVMBuildSub( self.builder, self.make_int(0, true).unwrap().0, rhs_val, cstr("sub").as_ptr(), ), _ => panic!(), }]; let ret = LLVMBuildGEP( self.builder, lhs_val, numidx.as_mut_slice().as_mut_ptr(), 1, cstr("add").as_ptr(), ); Some((ret, Some(ty))) } pub unsafe fn gen_int_binary_op( &mut self, lhs_val: &LLVMValueRef, rhs_val: &LLVMValueRef, ty: Type, op: &BinaryOps, ) -> Option<(LLVMValueRef, Option<Type>)> { let res = match op { BinaryOps::Add => LLVMBuildAdd(self.builder, *lhs_val, *rhs_val, cstr("add").as_ptr()), BinaryOps::Sub => LLVMBuildSub(self.builder, *lhs_val, *rhs_val, cstr("sub").as_ptr()), BinaryOps::Mul => LLVMBuildMul(self.builder, *lhs_val, *rhs_val, cstr("mul").as_ptr()), BinaryOps::Div => LLVMBuildSDiv(self.builder, *lhs_val, *rhs_val, cstr("sdiv").as_ptr()), BinaryOps::Eq => LLVMBuildICmp( self.builder, llvm::LLVMIntPredicate::LLVMIntEQ, *lhs_val, *rhs_val, cstr("eql").as_ptr(), ), BinaryOps::Ne => LLVMBuildICmp( self.builder, llvm::LLVMIntPredicate::LLVMIntNE, *lhs_val, *rhs_val,
pub unsafe fn gen_load(&mut self, ast: &AST) -> Option<(LLVMValueRef, Option<Type>)> { match ast { AST::Variable(ref name) => { let (val, ty) = self.gen(ast).unwrap(); let ty = ty.unwrap(); let ret = LLVMBuildLoad(self.builder, val, cstr("var").as_ptr()); match ty { Type::Ptr(origin_ty) => Some((ret, Some(*origin_ty))), _ => panic!(), } }, _ => { let (val, ty) = self.gen(ast).unwrap(); let ret = LLVMBuildLoad(self.builder, val, cstr("var").as_ptr()); Some((ret, Some(Type::Ptr(Box::new(ty.unwrap()))))) }, } } pub unsafe fn gen_var(&mut self, name: &String) -> Option<(LLVMValueRef, Option<Type>)> { if self.local_varmap.is_empty() { panic!(); } let mut i = (self.local_varmap.len() - 1) as isize; while i >= 0 { let var_info_opt = self.local_varmap[i as usize].get(name); match var_info_opt { Some(ref var_info) => { return Some(( var_info.llvm_val, Some(Type::Ptr(Box::new(var_info.ty.clone()))), )); } _ => (), } i -= 1; } panic!("local variable not found"); } pub unsafe fn gen_assign( &mut self, lhs: &AST, rhs: &AST, ) -> Option<(LLVMValueRef, Option<Type>)> { let (rhs_val, ty) = self.gen(rhs).unwrap(); let (dst, dst_ty) = self.gen(lhs).unwrap(); LLVMBuildStore(self.builder, rhs_val, dst); let load = LLVMBuildLoad(self.builder, dst, cstr("load").as_ptr()); Some((load, dst_ty)) } pub unsafe fn gen_if(&mut self, cond: &AST, then: &AST, els: &AST) -> Option<(LLVMValueRef, Option<Type>)> { let cond_val = self.gen(cond).unwrap().0; let func = self.cur_func.unwrap(); let bb_then = LLVMAppendBasicBlock(func, cstr("then").as_ptr()); let bb_else = LLVMAppendBasicBlock(func, cstr("else").as_ptr()); let bb_endif = LLVMAppendBasicBlock(func, cstr("endif").as_ptr()); LLVMBuildCondBr(self.builder, cond_val, bb_then, bb_else); LLVMPositionBuilderAtEnd(self.builder, bb_then); self.gen(then); if !is_exist_terminator(self.builder) { LLVMBuildBr(self.builder, bb_endif); } LLVMPositionBuilderAtEnd(self.builder, bb_else); self.gen(els); if !is_exist_terminator(self.builder) { LLVMBuildBr(self.builder, bb_endif); } LLVMPositionBuilderAtEnd(self.builder, bb_endif); None } pub unsafe fn gen_for(&mut self, init: &AST, cond: &AST, step: &AST, body: &AST) -> Option<(LLVMValueRef, Option<Type>)> { self.gen(init); let func = self.cur_func.unwrap(); let bb_begin = LLVMAppendBasicBlock(func, cstr("begin").as_ptr()); let bb_body = LLVMAppendBasicBlock(func, cstr("body").as_ptr()); let bb_update = LLVMAppendBasicBlock(func, cstr("update").as_ptr()); let bb_end = LLVMAppendBasicBlock(func, cstr("end").as_ptr()); LLVMBuildBr(self.builder, bb_begin); LLVMPositionBuilderAtEnd(self.builder, bb_begin); let cond_val = self.gen(cond).unwrap().0; LLVMBuildCondBr(self.builder, cond_val, bb_body, bb_end); LLVMPositionBuilderAtEnd(self.builder, bb_body); self.gen(body); if !is_exist_terminator(self.builder) { LLVMBuildBr(self.builder, bb_update); } LLVMPositionBuilderAtEnd(self.builder, bb_update); self.gen(step); if !is_exist_terminator(self.builder) { LLVMBuildBr(self.builder, bb_begin); } LLVMPositionBuilderAtEnd(self.builder, bb_end); None } pub unsafe fn gen_return(&mut self, ast: &AST) -> Option<(LLVMValueRef, Option<Type>)> { let ret_val = self.gen(ast); LLVMBuildRet(self.builder, ret_val.unwrap().0); None } pub unsafe fn make_int( &mut self, n: u64, is_unsigned: bool, ) -> Option<(LLVMValueRef, Option<Type>)> { Some(( LLVMConstInt(LLVMInt32Type(), n, if is_unsigned { 1 } else { 0 }), Some(Type::Int), )) } }
cstr("ne").as_ptr(), ), BinaryOps::Lt => LLVMBuildICmp( self.builder, llvm::LLVMIntPredicate::LLVMIntSLT, *lhs_val, *rhs_val, cstr("lt").as_ptr(), ), BinaryOps::Le => LLVMBuildICmp( self.builder, llvm::LLVMIntPredicate::LLVMIntSLE, *lhs_val, *rhs_val, cstr("le").as_ptr(), ), _ => panic!("Unsupported bianry op"), }; Some((res, Some(ty))) }
function_block-function_prefix_line
[ { "content": "pub fn error(line: u32, msg: &str) {\n\n println!(\" Error: line:{} {}\", line, msg);\n\n process::exit(-1);\n\n}", "file_path": "src/error.rs", "rank": 0, "score": 81268.38232700378 }, { "content": "pub fn run(filepath: String, tokens: Vec<Token>) -> Vec<AST> {\n\n le...
Rust
day07/src/main.rs
pkusensei/adventofcode2020
116b462afa8f5d05d221d312644a7b870954fc92
use std::{collections::HashMap, str::FromStr}; fn main() { let input = tools::read_input("input.txt").unwrap(); let rules = parse_rules(&input); println!("To Shiny gold: {}", count_shiny_gold(&rules)); println!( "Shiny gold contains: {}", count_contained(&rules, "shiny gold") - 1 ) } fn count_shiny_gold(rules: &HashMap<&str, Vec<(u32, &str)>>) -> usize { rules .keys() .filter(|k| contains_color(rules, k, "shiny gold")) .count() } fn count_contained(rules: &HashMap<&str, Vec<(u32, &str)>>, start: &str) -> usize { match rules.get(&start) { Some(ncpairs) => { if ncpairs.is_empty() { 1 } else { 1 + ncpairs .iter() .map(|(num, color)| (*num as usize) * count_contained(rules, color)) .sum::<usize>() } } _ => 0, } } fn contains_color(rules: &HashMap<&str, Vec<(u32, &str)>>, start: &str, target: &str) -> bool { match rules.get(&start) { Some(colors) => { if colors.iter().map(|(_, color)| color).any(|&c| c == target) { true } else { colors .iter() .map(|(_, color)| contains_color(rules, color, target)) .fold(false, |acc, i| acc || i) } } _ => false, } } fn parse_rules(lines: &[String]) -> HashMap<&str, Vec<(u32, &str)>> { lines .into_iter() .map(|s| { let mut kvpair = s.split("bags contain"); let key = kvpair.next().unwrap().trim(); let value = kvpair.next().unwrap().trim(); (key, parse_contained(value)) }) .collect() } fn parse_contained(line: &str) -> Vec<(u32, &str)> { if line.starts_with("no other") { vec![] } else { line.split(',') .map(|s| { let mut num_color_pair = s.trim().splitn(2, ' '); let num = u32::from_str(num_color_pair.next().unwrap()).unwrap(); let color = num_color_pair .next() .unwrap() .rsplitn(2, ' ') .skip(1) .next() .unwrap(); (num, color) }) .collect() } } #[cfg(test)] mod tests { use super::*; fn sample() -> Vec<String> { r#"light red bags contain 1 bright white bag, 2 muted yellow bags. dark orange bags contain 3 bright white bags, 4 muted yellow bags. bright white bags contain 1 shiny gold bag. muted yellow bags contain 2 shiny gold bags, 9 faded blue bags. shiny gold bags contain 1 dark olive bag, 2 vibrant plum bags. dark olive bags contain 3 faded blue bags, 4 dotted black bags. vibrant plum bags contain 5 faded blue bags, 6 dotted black bags. faded blue bags contain no other bags. dotted black bags contain no other bags."# .split('\n') .map(|s| s.trim().to_owned()) .collect() } #[test] fn test_count_shiny_gold() { let lines = sample(); let rules = parse_rules(&lines); assert_eq!(4, count_shiny_gold(&rules)) } #[test] fn test_count_contained() { { let lines = sample(); let rules = parse_rules(&lines); assert_eq!(32, count_contained(&rules, "shiny gold") - 1); } { let lines: Vec<_> = r#"shiny gold bags contain 2 dark red bags. dark red bags contain 2 dark orange bags. dark orange bags contain 2 dark yellow bags. dark yellow bags contain 2 dark green bags. dark green bags contain 2 dark blue bags. dark blue bags contain 2 dark violet bags. dark violet bags contain no other bags."# .split('\n') .map(|s| s.trim().to_owned()) .collect(); let rules = parse_rules(&lines); assert_eq!(126, count_contained(&rules, "shiny gold") - 1); } } }
use std::{collections::HashMap, str::FromStr}; fn main() { let input = tools::read_input("input.txt").unwrap(); let rules = parse_rules(&input); println!("To Shiny gold: {}", count_shiny_gold(&rules)); println!( "Shiny gold contains: {}", count_contained(&rules, "shiny gold") - 1 ) } fn count_shiny_gold(rules: &HashMap<&str, Vec<(u32, &str)>>) -> usize { rules .keys() .filter(|k| contains_color(rules, k, "shiny gold")) .count() } fn count_contained(rules: &HashMap<&str, Vec<(u32, &str)>>, start: &str) -> usize { match rules.get(&start) { Some(ncpairs) => { if ncpairs.is_empty() { 1 } else { 1 + ncpairs .iter() .map(|(num, color)| (*num as usize) * count_contained(rules, color)) .sum::<usize>() } } _ => 0, } } fn contains_color(rules: &HashMap<&str, Vec<(u32, &str)>>, start: &str, target: &str) -> bool { match rules.get(&start) { Some(colors) => { if colors.iter().map(|(_, color)| color).any(|&c| c == target) { true } else { colors .iter() .map(|(_, color)| contains_color(rules, color, target)) .fold(false, |acc, i| acc || i) } } _ => false, } } fn parse_rules(lines: &[String]) -> HashMap<&str, Vec<(u32, &str)>> { lines .into_iter() .map(|s| { let mut kvpair = s.split("bags contain"); let key = kvpair.next().unwrap().trim(); let value = kvpair.next().unwrap().trim(); (key, parse_contained(value)) }) .collect() } fn parse_contained(line: &str) -> Vec<(u32, &str)> { if line.starts_with("no other") { vec![] } else { line.split(',') .map(|s| { let mut num_color_pair = s.trim().splitn(2, ' '); let num = u32::from_str(num_color_pair.next().unwrap()).unwrap(); let color = num_color_pair .next() .unwrap() .rsplitn(2, ' ') .skip(1) .next() .unwrap(); (num, color) }) .collect() } } #[cfg(test)] mod tests { use super::*; fn sample() -> Vec<String> { r#"light red bags contain 1 bright white bag, 2 muted yellow bags. dark orange bags contain 3 bright white bags, 4 muted yellow bags. bright white bags contain 1 shiny gold bag. muted yellow bags contain 2 shiny gold bags, 9 faded blue bags. shiny gold bags contain 1 dark olive bag, 2 vibrant plum bags. dark olive bags contain 3 faded blue bags, 4 dotted black bags. vibrant plum bags contain 5 faded blue bags, 6 dotted black bags. faded blue bags contain no other bags. dotted black bags contain no other bags."# .split('\n') .map(|s| s.trim().to_owned()) .collect() } #[test] fn test_count_shiny_gold() { let lines = sample(); let rules = parse_rules(&lines); assert_eq!(4, count_shiny_gold(&rules)) } #[test] fn test_count_contained() { { let lines = sample(); let rules = parse_rules(&lines); assert_eq!(32, count_contained(&rules, "shiny gold") - 1); } { let lines: Vec<_> = r#"shiny gold bags contain 2 dark red bags. dark red bags c
s); assert_eq!(126, count_contained(&rules, "shiny gold") - 1); } } }
ontain 2 dark orange bags. dark orange bags contain 2 dark yellow bags. dark yellow bags contain 2 dark green bags. dark green bags contain 2 dark blue bags. dark blue bags contain 2 dark violet bags. dark violet bags contain no other bags."# .split('\n') .map(|s| s.trim().to_owned()) .collect(); let rules = parse_rules(&line
function_block-random_span
[ { "content": "fn group_answers(lines: &[String]) -> Vec<Vec<&str>> {\n\n let mut groups = vec![];\n\n let mut one_group = vec![];\n\n for line in lines {\n\n if line.trim().is_empty() {\n\n groups.push(one_group.clone());\n\n one_group.clear()\n\n } else {\n\n ...
Rust
azure_sdk_cosmos/src/resource_quota.rs
guywaldman/azure-sdk-for-rust
638d0322d1f397be253b609963cc1961324bdf04
use crate::errors::TokenParsingError; #[derive(Debug, Clone, PartialEq, PartialOrd)] pub enum ResourceQuota { Databases(u64), StoredProcedures(u64), Collections(u64), DocumentSize(u64), DocumentsSize(u64), DocumentsCount(i64), CollectionSize(u64), Users(u64), Permissions(u64), Triggers(u64), Functions(u64), ClientEncryptionKeys(u64), } const DATABASES: &str = "databases="; const STORED_PROCEDURES: &str = "storedProcedures="; const COLLECTIONS: &str = "collections="; const DOCUMENT_SIZE: &str = "documentSize="; const DOCUMENTS_SIZE: &str = "documentsSize="; const DOCUMENTS_COUNT: &str = "documentsCount="; const COLLECTION_SIZE: &str = "collectionSize="; const USERS: &str = "users="; const PERMISSIONS: &str = "permissions="; const TRIGGERS: &str = "triggers="; const FUNCTIONS: &str = "functions="; const CLIENT_ENCRYPTION_KEYS: &str = "clientEncryptionKeys="; pub(crate) fn resource_quotas_from_str(s: &str) -> Result<Vec<ResourceQuota>, failure::Error> { debug!("resource_quotas_from_str(\"{}\") called", s); let tokens: Vec<&str> = s.split(';').collect(); let mut v = Vec::with_capacity(tokens.len()); for token in tokens.into_iter().filter(|token| !token.is_empty()) { debug!("processing token == {}", token); if token.starts_with(DATABASES) { v.push(ResourceQuota::Databases(str::parse( &token[DATABASES.len()..], )?)); } else if token.starts_with(STORED_PROCEDURES) { v.push(ResourceQuota::StoredProcedures(str::parse( &token[STORED_PROCEDURES.len()..], )?)); } else if token.starts_with(COLLECTIONS) { v.push(ResourceQuota::Collections(str::parse( &token[COLLECTIONS.len()..], )?)); } else if token.starts_with(DOCUMENT_SIZE) { v.push(ResourceQuota::DocumentSize(str::parse( &token[DOCUMENT_SIZE.len()..], )?)); } else if token.starts_with(DOCUMENTS_SIZE) { v.push(ResourceQuota::DocumentsSize(str::parse( &token[DOCUMENTS_SIZE.len()..], )?)); } else if token.starts_with(DOCUMENTS_COUNT) { v.push(ResourceQuota::DocumentsCount(str::parse( &token[DOCUMENTS_COUNT.len()..], )?)); } else if token.starts_with(COLLECTION_SIZE) { v.push(ResourceQuota::CollectionSize(str::parse( &token[COLLECTION_SIZE.len()..], )?)); } else if token.starts_with(USERS) { v.push(ResourceQuota::Users(str::parse(&token[USERS.len()..])?)); } else if token.starts_with(PERMISSIONS) { v.push(ResourceQuota::Permissions(str::parse( &token[PERMISSIONS.len()..], )?)); } else if token.starts_with(TRIGGERS) { v.push(ResourceQuota::Triggers(str::parse( &token[TRIGGERS.len()..], )?)); } else if token.starts_with(FUNCTIONS) { v.push(ResourceQuota::Functions(str::parse( &token[FUNCTIONS.len()..], )?)); } else if token.starts_with(CLIENT_ENCRYPTION_KEYS) { v.push(ResourceQuota::ClientEncryptionKeys(str::parse( &token[CLIENT_ENCRYPTION_KEYS.len()..], )?)); } else { return Err(TokenParsingError::UnsupportedToken { token: token.to_string(), s: s.to_owned(), } .into()); } debug!("v == {:#?}", v); } Ok(v) } #[cfg(test)] mod tests { use super::*; #[test] fn parse_resource_quota() { let resource_quota = resource_quotas_from_str("storedProcedures=25;").unwrap(); assert_eq!(resource_quota, vec![ResourceQuota::StoredProcedures(25)]); let resource_quota = resource_quotas_from_str( "databases=100;collections=5000;users=500000;permissions=2000000;clientEncryptionKeys=13;", ) .unwrap(); assert_eq!( resource_quota, vec![ ResourceQuota::Databases(100), ResourceQuota::Collections(5000), ResourceQuota::Users(500000), ResourceQuota::Permissions(2000000), ResourceQuota::ClientEncryptionKeys(13) ] ); let resource_quota = resource_quotas_from_str("collections=27;").unwrap(); assert_eq!(resource_quota, vec![ResourceQuota::Collections(27)]); let resource_quota = resource_quotas_from_str("documentSize=0;documentsSize=2;collectionSize=3;").unwrap(); assert_eq!( resource_quota, vec![ ResourceQuota::DocumentSize(0), ResourceQuota::DocumentsSize(2), ResourceQuota::CollectionSize(3) ] ); let resource_quota = resource_quotas_from_str("users=500000;").unwrap(); assert_eq!(resource_quota, vec![ResourceQuota::Users(500000)]); let resource_quota = resource_quotas_from_str("permissions=2000000;").unwrap(); assert_eq!(resource_quota, vec![ResourceQuota::Permissions(2000000)]); let resource_quota = resource_quotas_from_str("triggers=25;").unwrap(); assert_eq!(resource_quota, vec![ResourceQuota::Triggers(25)]); let resource_quota = resource_quotas_from_str("functions=26;").unwrap(); assert_eq!(resource_quota, vec![ResourceQuota::Functions(26)]); let resource_quota = resource_quotas_from_str("clientEncryptionKeys=13;").unwrap(); assert_eq!(resource_quota, vec![ResourceQuota::ClientEncryptionKeys(13)]); } }
use crate::errors::TokenParsingError; #[derive(Debug, Clone, PartialEq, PartialOrd)] pub enum ResourceQuota { Databases(u64), StoredProcedures(u64), Collections(u64), DocumentSize(u64), DocumentsSize(u64), DocumentsCount(i64), CollectionSize(u64), Users(u64), Permissions(u64), Triggers(u64), Functions(u64), ClientEncryptionKeys(u64), } const DATABASES: &str = "databases="; const STORED_PROCEDURES: &str = "storedProcedures="; const COLLECTIONS: &str = "collections="; const DOCUMENT_SIZE: &str = "documentSize="; const DOCUMENTS_SIZE: &str = "documentsSize="; const DOCUMENTS_COUNT: &str = "documentsCount="; const COLLECTION_SIZE: &str = "collectionSize="; const USERS: &str = "users="; const PERMISSIONS: &str = "permissions="; const TRIGGERS: &str = "triggers="; const FUNCTIONS: &str = "functions="; const CLIENT_ENCRYPTION_KEYS: &str = "clientEncryptionKeys="; pub(crate) fn resource_quotas_from_str(s: &str) -> Result<Vec<ResourceQuota>, failure::Error> { debug!("resource_quotas_from_str(\"{}\") called", s); let tokens: Vec<&str> = s.split(';').collect(); let mut v = Vec::with_capacity(tokens.len()); for token in tokens.into_iter().filter(|token| !token.is_empty()) { debug!("processing token == {}", token); if token.starts_with(DATABASES) { v.push(ResourceQuota::Databases(str::parse( &token[DATABASES.len()..], )?)); } else if token.starts_with(STORED_PROCEDURES) { v.push(ResourceQuota::StoredProcedures(str::parse( &token[STORED_PROCEDURES.len()..], )?)); } else if token.starts_with(COLLECTIONS) { v.push(ResourceQuota::Collections(str::parse( &token[COLLECTIONS.len()..], )?)); } else if token.starts_with(DOCUMENT_SIZE) { v.push(ResourceQuota::DocumentSize(str::parse( &token[DOCUMENT_SIZE.len()..], )?)); } else if token.starts_with(DOCUMENTS_SIZE) { v.push(ResourceQuota::DocumentsSize(str::parse( &token[DOCUMENTS_SIZE.len()..], )?)); } else if token.starts_with(DOCUMENTS_COUNT) { v.push(ResourceQuota::DocumentsCount(str::parse( &token[DOCUMENTS_COUNT.len()..], )?)); } else if token.starts_with(COLLECTION_SIZE) { v.push(ResourceQuota::CollectionSize(str::parse( &token[COLLECTION_SIZE.len()..], )?)); } else if token.starts_with(USERS) { v.push(ResourceQuota::Users(str::parse(&token[USERS.len()..])?)); } else if token.starts_with(PERMISSIONS) { v.push(ResourceQuota::Permissions(str::parse( &token[PERMISSIONS.len()..], )?)); } else if token.starts_with(TRIGGERS) { v.push(ResourceQuota::Triggers(str::parse( &token[TRIGGERS.len()..], )?)); } else if token.starts_with(FUNCTIONS) { v.push(ResourceQuota::Functions(str::parse( &token[FUNCTIONS.len()..], )?)); } else if token.starts_with(CLIENT_ENCRYPTION_KEYS) { v.push(ResourceQuota::ClientEncryptionKeys(str::parse( &token[CLIENT_ENCRYPTION_KEYS.len()..], )?)); } else { return Err(TokenParsingError::UnsupportedToken { token: token.to_string(), s: s.to_owned(), } .into()); } debug!("v == {:#?}", v); } Ok(v) } #[cfg(test)] mod tests { use super::*; #[test]
}
fn parse_resource_quota() { let resource_quota = resource_quotas_from_str("storedProcedures=25;").unwrap(); assert_eq!(resource_quota, vec![ResourceQuota::StoredProcedures(25)]); let resource_quota = resource_quotas_from_str( "databases=100;collections=5000;users=500000;permissions=2000000;clientEncryptionKeys=13;", ) .unwrap(); assert_eq!( resource_quota, vec![ ResourceQuota::Databases(100), ResourceQuota::Collections(5000), ResourceQuota::Users(500000), ResourceQuota::Permissions(2000000), ResourceQuota::ClientEncryptionKeys(13) ] ); let resource_quota = resource_quotas_from_str("collections=27;").unwrap(); assert_eq!(resource_quota, vec![ResourceQuota::Collections(27)]); let resource_quota = resource_quotas_from_str("documentSize=0;documentsSize=2;collectionSize=3;").unwrap(); assert_eq!( resource_quota, vec![ ResourceQuota::DocumentSize(0), ResourceQuota::DocumentsSize(2), ResourceQuota::CollectionSize(3) ] ); let resource_quota = resource_quotas_from_str("users=500000;").unwrap(); assert_eq!(resource_quota, vec![ResourceQuota::Users(500000)]); let resource_quota = resource_quotas_from_str("permissions=2000000;").unwrap(); assert_eq!(resource_quota, vec![ResourceQuota::Permissions(2000000)]); let resource_quota = resource_quotas_from_str("triggers=25;").unwrap(); assert_eq!(resource_quota, vec![ResourceQuota::Triggers(25)]); let resource_quota = resource_quotas_from_str("functions=26;").unwrap(); assert_eq!(resource_quota, vec![ResourceQuota::Functions(26)]); let resource_quota = resource_quotas_from_str("clientEncryptionKeys=13;").unwrap(); assert_eq!(resource_quota, vec![ResourceQuota::ClientEncryptionKeys(13)]); }
function_block-full_function
[ { "content": "pub fn with_azure_sas(account: &str, sas_token: &str) -> KeyClient {\n\n let client = hyper::Client::builder().build(HttpsConnector::new());\n\n let params = get_sas_token_parms(sas_token);\n\n\n\n KeyClient::new(\n\n account.to_owned(),\n\n String::new(),\n\n Some(pa...
Rust
eir-fmm/src/entry_functions.rs
ein-lang/eir
70d59589efeb1f6a7e881abb28ce7aebb862018f
use super::error::CompileError; use crate::{closures, expressions, reference_count, types}; use std::collections::HashMap; const CLOSURE_NAME: &str = "_closure"; pub fn compile( module_builder: &fmm::build::ModuleBuilder, definition: &eir::ir::Definition, variables: &HashMap<String, fmm::build::TypedExpression>, types: &HashMap<String, eir::types::RecordBody>, ) -> Result<fmm::build::TypedExpression, CompileError> { Ok(if definition.is_thunk() { compile_thunk(module_builder, definition, variables, types)? } else { compile_non_thunk(module_builder, definition, variables, types)? }) } fn compile_non_thunk( module_builder: &fmm::build::ModuleBuilder, definition: &eir::ir::Definition, variables: &HashMap<String, fmm::build::TypedExpression>, types: &HashMap<String, eir::types::RecordBody>, ) -> Result<fmm::build::TypedExpression, CompileError> { module_builder.define_anonymous_function( compile_arguments(definition, types), |instruction_builder| { Ok(instruction_builder.return_(compile_body( module_builder, &instruction_builder, definition, variables, types, )?)) }, types::compile(definition.result_type(), types), fmm::types::CallingConvention::Source, ) } fn compile_thunk( module_builder: &fmm::build::ModuleBuilder, definition: &eir::ir::Definition, variables: &HashMap<String, fmm::build::TypedExpression>, types: &HashMap<String, eir::types::RecordBody>, ) -> Result<fmm::build::TypedExpression, CompileError> { compile_initial_thunk_entry( module_builder, definition, compile_normal_thunk_entry(module_builder, definition, types)?, compile_locked_thunk_entry(module_builder, definition, types)?, variables, types, ) } fn compile_body( module_builder: &fmm::build::ModuleBuilder, instruction_builder: &fmm::build::InstructionBuilder, definition: &eir::ir::Definition, variables: &HashMap<String, fmm::build::TypedExpression>, types: &HashMap<String, eir::types::RecordBody>, ) -> Result<fmm::build::TypedExpression, CompileError> { let payload_pointer = compile_payload_pointer(definition, types)?; let environment_pointer = if definition.is_thunk() { fmm::build::union_address(payload_pointer, 0)?.into() } else { payload_pointer }; expressions::compile( module_builder, instruction_builder, definition.body(), &variables .clone() .into_iter() .chain( definition .environment() .iter() .enumerate() .map(|(index, free_variable)| -> Result<_, CompileError> { let value = instruction_builder.load(fmm::build::record_address( environment_pointer.clone(), index, )?)?; reference_count::clone_expression( instruction_builder, &value, free_variable.type_(), types, )?; Ok((free_variable.name().into(), value)) }) .collect::<Result<Vec<_>, _>>()?, ) .chain(vec![( definition.name().into(), compile_closure_pointer(definition.type_(), types)?, )]) .chain(definition.arguments().iter().map(|argument| { ( argument.name().into(), fmm::build::variable(argument.name(), types::compile(argument.type_(), types)), ) })) .collect(), types, ) } fn compile_initial_thunk_entry( module_builder: &fmm::build::ModuleBuilder, definition: &eir::ir::Definition, normal_entry_function: fmm::build::TypedExpression, lock_entry_function: fmm::build::TypedExpression, variables: &HashMap<String, fmm::build::TypedExpression>, types: &HashMap<String, eir::types::RecordBody>, ) -> Result<fmm::build::TypedExpression, CompileError> { let entry_function_name = module_builder.generate_name(); let entry_function_type = types::compile_entry_function(definition, types); let arguments = compile_arguments(definition, types); module_builder.define_function( &entry_function_name, arguments.clone(), |instruction_builder| { let entry_function_pointer = compile_entry_function_pointer(definition, types)?; instruction_builder.if_( instruction_builder.compare_and_swap( entry_function_pointer.clone(), fmm::build::variable(&entry_function_name, entry_function_type.clone()), lock_entry_function.clone(), fmm::ir::AtomicOrdering::Acquire, fmm::ir::AtomicOrdering::Relaxed, ), |instruction_builder| -> Result<_, CompileError> { let value = compile_body( module_builder, &instruction_builder, definition, variables, types, )?; reference_count::clone_expression( &instruction_builder, &value, definition.result_type(), types, )?; instruction_builder.store( value.clone(), compile_thunk_value_pointer(definition, types)?, ); instruction_builder.store( closures::compile_normal_thunk_drop_function( module_builder, definition, types, )?, compile_drop_function_pointer(definition, types)?, ); instruction_builder.atomic_store( normal_entry_function.clone(), entry_function_pointer.clone(), fmm::ir::AtomicOrdering::Release, ); Ok(instruction_builder.return_(value)) }, |instruction_builder| { Ok(instruction_builder.return_( instruction_builder.call( instruction_builder.atomic_load( compile_entry_function_pointer(definition, types)?, fmm::ir::AtomicOrdering::Acquire, )?, arguments .iter() .map(|argument| { fmm::build::variable(argument.name(), argument.type_().clone()) }) .collect(), )?, )) }, )?; Ok(instruction_builder.unreachable()) }, types::compile(definition.result_type(), types), fmm::types::CallingConvention::Source, fmm::ir::Linkage::Internal, ) } fn compile_normal_thunk_entry( module_builder: &fmm::build::ModuleBuilder, definition: &eir::ir::Definition, types: &HashMap<String, eir::types::RecordBody>, ) -> Result<fmm::build::TypedExpression, CompileError> { module_builder.define_anonymous_function( compile_arguments(definition, types), |instruction_builder| compile_normal_body(&instruction_builder, definition, types), types::compile(definition.result_type(), types), fmm::types::CallingConvention::Source, ) } fn compile_locked_thunk_entry( module_builder: &fmm::build::ModuleBuilder, definition: &eir::ir::Definition, types: &HashMap<String, eir::types::RecordBody>, ) -> Result<fmm::build::TypedExpression, CompileError> { let entry_function_name = module_builder.generate_name(); module_builder.define_function( &entry_function_name, compile_arguments(definition, types), |instruction_builder| { instruction_builder.if_( fmm::build::comparison_operation( fmm::ir::ComparisonOperator::Equal, fmm::build::bit_cast( fmm::types::Primitive::PointerInteger, instruction_builder.atomic_load( compile_entry_function_pointer(definition, types)?, fmm::ir::AtomicOrdering::Acquire, )?, ), fmm::build::bit_cast( fmm::types::Primitive::PointerInteger, fmm::build::variable( &entry_function_name, types::compile_entry_function(definition, types), ), ), )?, |instruction_builder| Ok(instruction_builder.unreachable()), |instruction_builder| compile_normal_body(&instruction_builder, definition, types), )?; Ok(instruction_builder.unreachable()) }, types::compile(definition.result_type(), types), fmm::types::CallingConvention::Source, fmm::ir::Linkage::Internal, ) } fn compile_normal_body( instruction_builder: &fmm::build::InstructionBuilder, definition: &eir::ir::Definition, types: &HashMap<String, eir::types::RecordBody>, ) -> Result<fmm::ir::Block, CompileError> { let value = instruction_builder.load(compile_thunk_value_pointer(definition, types)?)?; reference_count::clone_expression( instruction_builder, &value, definition.result_type(), types, )?; Ok(instruction_builder.return_(value)) } fn compile_entry_function_pointer( definition: &eir::ir::Definition, types: &HashMap<String, eir::types::RecordBody>, ) -> Result<fmm::build::TypedExpression, CompileError> { Ok(fmm::build::bit_cast( fmm::types::Pointer::new(types::compile_entry_function(definition, types)), closures::compile_entry_function_pointer(compile_closure_pointer( definition.type_(), types, )?)?, ) .into()) } fn compile_drop_function_pointer( definition: &eir::ir::Definition, types: &HashMap<String, eir::types::RecordBody>, ) -> Result<fmm::build::TypedExpression, CompileError> { closures::compile_drop_function_pointer(compile_closure_pointer(definition.type_(), types)?) } fn compile_arguments( definition: &eir::ir::Definition, types: &HashMap<String, eir::types::RecordBody>, ) -> Vec<fmm::ir::Argument> { vec![fmm::ir::Argument::new( CLOSURE_NAME, types::compile_untyped_closure_pointer(), )] .into_iter() .chain(definition.arguments().iter().map(|argument| { fmm::ir::Argument::new(argument.name(), types::compile(argument.type_(), types)) })) .collect() } fn compile_thunk_value_pointer( definition: &eir::ir::Definition, types: &HashMap<String, eir::types::RecordBody>, ) -> Result<fmm::build::TypedExpression, CompileError> { Ok(fmm::build::union_address(compile_payload_pointer(definition, types)?, 1)?.into()) } fn compile_payload_pointer( definition: &eir::ir::Definition, types: &HashMap<String, eir::types::RecordBody>, ) -> Result<fmm::build::TypedExpression, CompileError> { closures::compile_environment_pointer(fmm::build::bit_cast( fmm::types::Pointer::new(types::compile_sized_closure(definition, types)), compile_untyped_closure_pointer(), )) } fn compile_closure_pointer( function_type: &eir::types::Function, types: &HashMap<String, eir::types::RecordBody>, ) -> Result<fmm::build::TypedExpression, fmm::build::BuildError> { Ok(fmm::build::bit_cast( fmm::types::Pointer::new(types::compile_unsized_closure(function_type, types)), compile_untyped_closure_pointer(), ) .into()) } fn compile_untyped_closure_pointer() -> fmm::build::TypedExpression { fmm::build::variable(CLOSURE_NAME, types::compile_untyped_closure_pointer()) }
use super::error::CompileError; use crate::{closures, expressions, reference_count, types}; use std::collections::HashMap; const CLOSURE_NAME: &str = "_closure"; pub fn compile( module_builder: &fmm::build::ModuleBuilder, definition: &eir::ir::Definition, variables: &HashMap<String, fmm::build::TypedExpression>, types: &HashMap<String, eir::types::RecordBody>, ) -> Result<fmm::build::TypedExpression, CompileError> { Ok(if definition.is_thunk() { compile_thunk(module_builder, definition, variables, types)? } else { compile_non_thunk(module_builder, definition, variables, types)? }) } fn compile_non_thunk( module_builder: &fmm::build::ModuleBuilder, definition: &eir::ir::Definition, variables: &HashMap<String, fmm::build::TypedExpression>, types: &HashMap<String, eir::types::RecordBody>, ) -> Result<fmm::build::TypedExpression, CompileError> { module_builder.define_anonymous_function( compile_arguments(definition, types), |instruction_builder| { Ok(instruction_builder.return_(compile_body( module_builder, &instruction_builder, definition, variables, types, )?)) }, types::compile(definition.result_type(), types), fmm::types::CallingConvention::Source, ) } fn compile_thunk( module_builder: &fmm::build::ModuleBuilder, definition: &eir::ir::Definition, variables: &HashMap<String, fmm::build::TypedExpression>, types: &HashMap<String, eir::types::RecordBody>, ) -> Result<fmm::build::TypedExpression, CompileError> { compile_initial_thunk_entry( module_builder, definition, compile_normal_thunk_entry(module_builder, definition, types)?, compile_locked_thunk_entry(module_builder, definition, types)?, variables, types, ) } fn compile_body( module_builder: &fmm::build::ModuleBuilder, instruction_builder: &fmm::build::InstructionBuilder, definition: &eir::ir::Definition, variables: &HashMap<String, fmm::build::TypedExpression>, types: &HashMap<String, eir::types::RecordBody>, ) -> Result<fmm::build::TypedExpression, CompileError> { let payload_pointer = compile_payload_pointer(definition, types)?; let environment_pointer = if definition.is_thunk() { fmm::build::union_address(payload_pointer, 0)?.into() } else { payload_pointer }; expressions::compile( module_builder, instruction_builder, definition.body(), &variables .clone() .into_iter() .chain( definition .environment() .iter() .enumerate() .map(|(index, free_variable)| -> Result<_, CompileError> { let value = instruction_builder.load(fmm::build::record_address( environment_pointer.clone(), index, )?)?; reference_count::clone_expression( instruction_builder, &value, free_variable.type_(), types, )?; Ok((free_variable.name().into(), value)) }) .collect::<Result<Vec<_>, _>>()?, ) .chain(vec![( definition.name().into(), compile_closure_pointer(definition.type_(), types)?, )]) .chain(definition.arguments().iter().map(|argument| { ( argument.name().into(), fmm::build::variable(argument.name(), types::compile(argument.type_(), types)), ) })) .collect(), types, ) } fn compile_initial_thunk_entry( module_builder: &fmm::build::ModuleBuilder, definition: &eir::ir::Definition, normal_entry_function: fmm::build::TypedExpression, lock_entry_function: fmm::build::TypedExpression, variables: &HashMap<String, fmm::build::TypedExpression>, types: &HashMap<String, eir::types::RecordBody>, ) -> Result<fmm::build::TypedExpression, CompileError> { let entry_function_name = module_builder.generate_name(); let entry_function_type = types::compile_entry_function(definition, types); let arguments = compile_arguments(definition, types); module_builder.define_function( &entry_function_name, arguments.clone(), |instruction_builder| { let entry_function_pointer = compile_entry_function_pointer(definition, types)?; instruction_builder.if_( instruction_builder.compare_and_swap( entry_function_pointer.clone(), fmm::build::variable(&entry_function_name, entry_function_type.clone()), lock_entry_function.clone(), fmm::ir::AtomicOrdering::Acquire, fmm::ir::AtomicOrdering::Relaxed, ), |instruction_builder| -> Result<_, CompileError> { let value = compile_body( module_builder, &instruction_builder, definition, variables, types, )?; reference_count::clone_expression( &instruction_builder, &value, definition.result_type(), types, )?; instruction_builder.store( value.clone(), compile_thunk_value_pointer(definition, types)?, ); instruction_builder.store( closures::compile_normal_thunk_drop_function( module_builder, definition, types, )?, compile_drop_function_pointer(definition, types)?, ); instruction_builder.atomic_store( normal_entry_function.clone(), entry_function_pointer.clone(), fmm::ir::AtomicOrdering::Release, ); Ok(instruction_builder.return_(value)) }, |instruction_builder| {
}, )?; Ok(instruction_builder.unreachable()) }, types::compile(definition.result_type(), types), fmm::types::CallingConvention::Source, fmm::ir::Linkage::Internal, ) } fn compile_normal_thunk_entry( module_builder: &fmm::build::ModuleBuilder, definition: &eir::ir::Definition, types: &HashMap<String, eir::types::RecordBody>, ) -> Result<fmm::build::TypedExpression, CompileError> { module_builder.define_anonymous_function( compile_arguments(definition, types), |instruction_builder| compile_normal_body(&instruction_builder, definition, types), types::compile(definition.result_type(), types), fmm::types::CallingConvention::Source, ) } fn compile_locked_thunk_entry( module_builder: &fmm::build::ModuleBuilder, definition: &eir::ir::Definition, types: &HashMap<String, eir::types::RecordBody>, ) -> Result<fmm::build::TypedExpression, CompileError> { let entry_function_name = module_builder.generate_name(); module_builder.define_function( &entry_function_name, compile_arguments(definition, types), |instruction_builder| { instruction_builder.if_( fmm::build::comparison_operation( fmm::ir::ComparisonOperator::Equal, fmm::build::bit_cast( fmm::types::Primitive::PointerInteger, instruction_builder.atomic_load( compile_entry_function_pointer(definition, types)?, fmm::ir::AtomicOrdering::Acquire, )?, ), fmm::build::bit_cast( fmm::types::Primitive::PointerInteger, fmm::build::variable( &entry_function_name, types::compile_entry_function(definition, types), ), ), )?, |instruction_builder| Ok(instruction_builder.unreachable()), |instruction_builder| compile_normal_body(&instruction_builder, definition, types), )?; Ok(instruction_builder.unreachable()) }, types::compile(definition.result_type(), types), fmm::types::CallingConvention::Source, fmm::ir::Linkage::Internal, ) } fn compile_normal_body( instruction_builder: &fmm::build::InstructionBuilder, definition: &eir::ir::Definition, types: &HashMap<String, eir::types::RecordBody>, ) -> Result<fmm::ir::Block, CompileError> { let value = instruction_builder.load(compile_thunk_value_pointer(definition, types)?)?; reference_count::clone_expression( instruction_builder, &value, definition.result_type(), types, )?; Ok(instruction_builder.return_(value)) } fn compile_entry_function_pointer( definition: &eir::ir::Definition, types: &HashMap<String, eir::types::RecordBody>, ) -> Result<fmm::build::TypedExpression, CompileError> { Ok(fmm::build::bit_cast( fmm::types::Pointer::new(types::compile_entry_function(definition, types)), closures::compile_entry_function_pointer(compile_closure_pointer( definition.type_(), types, )?)?, ) .into()) } fn compile_drop_function_pointer( definition: &eir::ir::Definition, types: &HashMap<String, eir::types::RecordBody>, ) -> Result<fmm::build::TypedExpression, CompileError> { closures::compile_drop_function_pointer(compile_closure_pointer(definition.type_(), types)?) } fn compile_arguments( definition: &eir::ir::Definition, types: &HashMap<String, eir::types::RecordBody>, ) -> Vec<fmm::ir::Argument> { vec![fmm::ir::Argument::new( CLOSURE_NAME, types::compile_untyped_closure_pointer(), )] .into_iter() .chain(definition.arguments().iter().map(|argument| { fmm::ir::Argument::new(argument.name(), types::compile(argument.type_(), types)) })) .collect() } fn compile_thunk_value_pointer( definition: &eir::ir::Definition, types: &HashMap<String, eir::types::RecordBody>, ) -> Result<fmm::build::TypedExpression, CompileError> { Ok(fmm::build::union_address(compile_payload_pointer(definition, types)?, 1)?.into()) } fn compile_payload_pointer( definition: &eir::ir::Definition, types: &HashMap<String, eir::types::RecordBody>, ) -> Result<fmm::build::TypedExpression, CompileError> { closures::compile_environment_pointer(fmm::build::bit_cast( fmm::types::Pointer::new(types::compile_sized_closure(definition, types)), compile_untyped_closure_pointer(), )) } fn compile_closure_pointer( function_type: &eir::types::Function, types: &HashMap<String, eir::types::RecordBody>, ) -> Result<fmm::build::TypedExpression, fmm::build::BuildError> { Ok(fmm::build::bit_cast( fmm::types::Pointer::new(types::compile_unsized_closure(function_type, types)), compile_untyped_closure_pointer(), ) .into()) } fn compile_untyped_closure_pointer() -> fmm::build::TypedExpression { fmm::build::variable(CLOSURE_NAME, types::compile_untyped_closure_pointer()) }
Ok(instruction_builder.return_( instruction_builder.call( instruction_builder.atomic_load( compile_entry_function_pointer(definition, types)?, fmm::ir::AtomicOrdering::Acquire, )?, arguments .iter() .map(|argument| { fmm::build::variable(argument.name(), argument.type_().clone()) }) .collect(), )?, ))
call_expression
[ { "content": "fn infer_in_let(let_: &Let, variables: &HashMap<String, Type>) -> Let {\n\n Let::new(\n\n let_.name(),\n\n let_.type_().clone(),\n\n infer_in_expression(let_.bound_expression(), variables),\n\n infer_in_expression(\n\n let_.expression(),\n\n &va...
Rust
src/kgen/src/ast/functions/mod.rs
capra314cabra/kaprino
7b4ce32631194955e9a9cd4e206edadbc5110da4
use inkwell::types::BasicTypeEnum; use inkwell::types::FunctionType; use inkwell::values::FunctionValue; use crate::ast::CodeGen; use crate::ast::functions::expr_function::ExprFunction; use crate::ast::functions::external_function::ExternalFunction; use crate::ast::functions::statement_function::StatementFunction; use crate::error::error_token::{ ErrorToken, FilePosition }; use crate::resolvers::parameter_resolver::KParameter; #[derive(Debug,PartialEq)] pub enum FunctionObject { ExprFunction(Box<ExprFunction>), ExternalFunction(Box<ExternalFunction>), StatementFunction(Box<StatementFunction>) } impl<'ctx> FunctionObject { pub fn codegen(&self, gen: &CodeGen<'ctx>) -> Result<(), ErrorToken> { match self { FunctionObject::ExprFunction(obj) => obj.codegen(gen), FunctionObject::ExternalFunction(obj) => obj.codegen(gen), FunctionObject::StatementFunction(obj) => obj.codegen(gen) } } } #[derive(Debug,PartialEq)] pub struct FunctionInfo { pub name: String, pub args: Vec<String>, pub types: Vec<String>, pub ret_type: String } impl FunctionInfo { pub fn new(name: String, args: Vec<String>, types: Vec<String>, ret_type: String) -> Self { FunctionInfo{ name, args, types, ret_type } } } pub trait FunctionObjectTrait { fn get_info(&self) -> &FunctionInfo; fn get_arg_types<'ctx>(&self, gen: &CodeGen<'ctx>, pos: FilePosition) -> Result<Vec<BasicTypeEnum<'ctx>>, ErrorToken> { let mut vec: Vec<BasicTypeEnum<'ctx>> = Vec::new(); let mut error_message: Option<String> = None; let type_resolver = gen.type_resolver.borrow(); for arg_type_name in self.get_info().types.iter() { let arg_type = type_resolver.find(arg_type_name); match arg_type { Some(arg_type) => { let arg_type = arg_type.get_type(gen); vec.push(arg_type); }, None => { error_message = Some(format!( "Unknown types {0} were used in declaration of arguments of the function named {1}.", arg_type_name, self.get_info().name )); break; } }; }; match error_message { Some(error_message) => { Err(ErrorToken::error(pos, error_message)) }, None => { Ok(vec) } } } fn get_ret_type<'ctx>(&self, gen: &CodeGen<'ctx>, pos: FilePosition) -> Result<BasicTypeEnum<'ctx>, ErrorToken> { let type_resolver = gen.type_resolver.borrow(); let ret_type = type_resolver .find(&self.get_info().ret_type) .ok_or(ErrorToken::error( pos, format!( "Unknown types were used in declaration of return value of the function named {}.", self.get_info().name ) ))?; Ok(ret_type.get_type(gen)) } fn get_func_type<'ctx>(&self, gen: &CodeGen<'ctx>, pos: FilePosition) -> Result<FunctionType<'ctx>, ErrorToken> { let arg_types = self.get_arg_types(gen, pos.clone())?; let ret_type = self.get_ret_type(gen, pos)?; let ret_type = match ret_type { BasicTypeEnum::ArrayType(val) => val.fn_type(arg_types.as_slice(), false), BasicTypeEnum::FloatType(val) => val.fn_type(arg_types.as_slice(), false), BasicTypeEnum::IntType(val) => val.fn_type(arg_types.as_slice(), false), BasicTypeEnum::PointerType(val) => val.fn_type(arg_types.as_slice(), false), BasicTypeEnum::StructType(val) => val.fn_type(arg_types.as_slice(), false), BasicTypeEnum::VectorType(val) => val.fn_type(arg_types.as_slice(), false) }; Ok(ret_type) } fn assign_args<'ctx>(&self, gen: &CodeGen<'ctx>, func: &FunctionValue<'ctx>) { let mut param_resolver = gen.param_resolver.borrow_mut(); param_resolver.add_scope(&self.get_info().name); let params = func.get_params(); for (idx, param_name) in self.get_info().args.iter().enumerate() { let allocated = gen.builder.build_alloca(params[idx].get_type(), ""); gen.builder.build_store(allocated, params[idx]); let param = KParameter::new( self.get_info().args[idx].clone(), allocated.into() ); param_resolver.add(param_name, param); }; } } pub mod expr_function; pub mod external_function; pub mod statement_function;
use inkwell::types::BasicTypeEnum; use inkwell::types::FunctionType; use inkwell::values::FunctionValue; use crate::ast::CodeGen; use crate::ast::functions::expr_function::ExprFunction; use crate::ast::functions::external_function::ExternalFunction; use crate::ast::functions::statement_function::StatementFunction; use crate::error::error_token::{ ErrorToken, FilePosition }; use crate::resolvers::parameter_resolver::KParameter; #[derive(Debug,PartialEq)] pub enum FunctionObject { ExprFunction(Box<ExprFunction>), ExternalFunction(Box<ExternalFunction>), StatementFunction(Box<StatementFunction>) } impl<'ctx> FunctionObject { pub fn codegen(&self, gen: &CodeGen<'ctx>) -> Result<(), ErrorToken> { match self { FunctionObject::ExprFunction(obj) => obj.codegen(gen), FunctionObject::ExternalFunction(obj) => obj.codegen(gen), FunctionObject::StatementFunction(obj) => obj.codegen(gen) } } } #[derive(Debug,PartialEq)] pub struct FunctionInfo { pub name: String, pub args: Vec<String>, pub types: Vec<String>, pub ret_type: String } impl FunctionInfo { pub fn new(name: String, args: Vec<String>, types: Vec<String>, ret_type: String) -> Self { FunctionInfo{ name, args, types, ret_type } } } pub trait FunctionObjectTrait { fn get_info(&self) -> &FunctionInfo; fn get_arg_types<'ctx>(&self, gen: &CodeGen<'ctx>, pos: FilePosition) -> Result<Vec<BasicTypeEnum<'ctx>>, ErrorToken> { let mut vec: Vec<BasicTypeEnum<'ctx>> = Vec::new(); let mut error_message: Option<String> = None; let type_resolver = gen.type_resolver.borrow(); for arg_type_name in self.get_info().types.iter() { let arg_type = type_resolver.find(arg_type_name); match arg_type { Some(arg_type) => { let arg_type = arg_type.get_type(gen); vec.push(arg_type); }, None => { error_message = Some(format!( "Unknown types {0} were used in declaration of arguments of the function named {1}.", arg_type_name, self.get_info().name )); break; } }; }; match error_message { Some(error_message) => { Err(ErrorToken::error(pos, error_message)) }, None => { Ok(vec) } } } fn get_ret_type<'ctx>(&self, gen: &CodeGen<'ctx>, pos: FilePosition) -> Result<BasicTypeEnum<'ctx>, ErrorToken> { let type_resolver = gen.type_resolver.borrow(); let ret_type = type_resolver .find(&self.get_info().ret_type) .ok_or(ErrorToken::error( pos, format!( "Unknown types w
fn get_func_type<'ctx>(&self, gen: &CodeGen<'ctx>, pos: FilePosition) -> Result<FunctionType<'ctx>, ErrorToken> { let arg_types = self.get_arg_types(gen, pos.clone())?; let ret_type = self.get_ret_type(gen, pos)?; let ret_type = match ret_type { BasicTypeEnum::ArrayType(val) => val.fn_type(arg_types.as_slice(), false), BasicTypeEnum::FloatType(val) => val.fn_type(arg_types.as_slice(), false), BasicTypeEnum::IntType(val) => val.fn_type(arg_types.as_slice(), false), BasicTypeEnum::PointerType(val) => val.fn_type(arg_types.as_slice(), false), BasicTypeEnum::StructType(val) => val.fn_type(arg_types.as_slice(), false), BasicTypeEnum::VectorType(val) => val.fn_type(arg_types.as_slice(), false) }; Ok(ret_type) } fn assign_args<'ctx>(&self, gen: &CodeGen<'ctx>, func: &FunctionValue<'ctx>) { let mut param_resolver = gen.param_resolver.borrow_mut(); param_resolver.add_scope(&self.get_info().name); let params = func.get_params(); for (idx, param_name) in self.get_info().args.iter().enumerate() { let allocated = gen.builder.build_alloca(params[idx].get_type(), ""); gen.builder.build_store(allocated, params[idx]); let param = KParameter::new( self.get_info().args[idx].clone(), allocated.into() ); param_resolver.add(param_name, param); }; } } pub mod expr_function; pub mod external_function; pub mod statement_function;
ere used in declaration of return value of the function named {}.", self.get_info().name ) ))?; Ok(ret_type.get_type(gen)) }
function_block-function_prefixed
[ { "content": "///\n\n/// Execute a function Just In Time.\n\n///\n\npub fn execute_function(text: &str, func_name: &str, arg: u32) -> Result<u32, ()> {\n\n type TestFunc = unsafe extern \"C\" fn(u32) -> u32;\n\n\n\n let context = &Context::create();\n\n let gen = CodeGen::new(context, \"test\");\n\n\n\...
Rust
async-coap/src/message/write.rs
Luro02/rust-async-coap
6a7b592a23de0c9d86ca399bf40ecfbf0bff6e62
use super::*; pub trait MessageWrite: OptionInsert { fn set_msg_type(&mut self, tt: MsgType); fn set_msg_id(&mut self, msg_id: MsgId); fn set_msg_code(&mut self, code: MsgCode); fn set_msg_token(&mut self, token: MsgToken); fn append_payload_bytes(&mut self, body: &[u8]) -> Result<(), Error>; fn append_payload_string(&mut self, body: &str) -> Result<(), Error> { self.append_payload_bytes(body.as_bytes()) } fn append_payload_u8(&mut self, b: u8) -> Result<(), Error> { self.append_payload_bytes(&[b]) } fn append_payload_char(&mut self, c: char) -> Result<(), Error> { self.append_payload_string(c.encode_utf8(&mut [0; 4])) } fn clear(&mut self); } impl<'a> core::fmt::Write for dyn MessageWrite + 'a { fn write_str(&mut self, s: &str) -> Result<(), core::fmt::Error> { self.append_payload_string(s)?; Ok(()) } fn write_char(&mut self, c: char) -> Result<(), core::fmt::Error> { self.append_payload_char(c)?; Ok(()) } } impl<'a> std::io::Write for dyn MessageWrite + 'a { fn write(&mut self, buf: &[u8]) -> Result<usize, std::io::Error> { self.append_payload_bytes(buf) .map(|_| buf.len()) .map_err(|_| std::io::ErrorKind::Other.into()) } fn flush(&mut self) -> Result<(), std::io::Error> { Ok(()) } fn write_all(&mut self, buf: &[u8]) -> Result<(), std::io::Error> { self.append_payload_bytes(buf) .map_err(|_| std::io::ErrorKind::Other.into()) } } impl<'a> std::io::Write for BufferMessageEncoder<'a> { fn write(&mut self, buf: &[u8]) -> Result<usize, std::io::Error> { self.append_payload_bytes(buf) .map(|_| buf.len()) .map_err(|_| std::io::ErrorKind::Other.into()) } fn flush(&mut self) -> Result<(), std::io::Error> { Ok(()) } fn write_all(&mut self, buf: &[u8]) -> Result<(), std::io::Error> { self.append_payload_bytes(buf) .map_err(|_| std::io::ErrorKind::Other.into()) } } impl std::io::Write for VecMessageEncoder { fn write(&mut self, buf: &[u8]) -> Result<usize, std::io::Error> { self.append_payload_bytes(buf) .map(|_| buf.len()) .map_err(|_| std::io::ErrorKind::Other.into()) } fn flush(&mut self) -> Result<(), std::io::Error> { Ok(()) } fn write_all(&mut self, buf: &[u8]) -> Result<(), std::io::Error> { self.append_payload_bytes(buf) .map_err(|_| std::io::ErrorKind::Other.into()) } }
use super::*; pub trait MessageWrite: OptionInsert { fn set_msg_type(&mut self, tt: MsgType); fn set_msg_id(&mut self, msg_id: MsgId); fn set_msg_code(&mut self, code: MsgCode); fn set_msg_token(&mut self, token: MsgToken); fn append_payload_bytes(&mut self, body: &[u8]) -> Result<(), Error>; fn append_payload_string(&mut self, body: &str) -> Result<(), Error> { self.append_payload_bytes(body
Ok(()) } fn write_char(&mut self, c: char) -> Result<(), core::fmt::Error> { self.append_payload_char(c)?; Ok(()) } } impl<'a> std::io::Write for dyn MessageWrite + 'a { fn write(&mut self, buf: &[u8]) -> Result<usize, std::io::Error> { self.append_payload_bytes(buf) .map(|_| buf.len()) .map_err(|_| std::io::ErrorKind::Other.into()) } fn flush(&mut self) -> Result<(), std::io::Error> { Ok(()) } fn write_all(&mut self, buf: &[u8]) -> Result<(), std::io::Error> { self.append_payload_bytes(buf) .map_err(|_| std::io::ErrorKind::Other.into()) } } impl<'a> std::io::Write for BufferMessageEncoder<'a> { fn write(&mut self, buf: &[u8]) -> Result<usize, std::io::Error> { self.append_payload_bytes(buf) .map(|_| buf.len()) .map_err(|_| std::io::ErrorKind::Other.into()) } fn flush(&mut self) -> Result<(), std::io::Error> { Ok(()) } fn write_all(&mut self, buf: &[u8]) -> Result<(), std::io::Error> { self.append_payload_bytes(buf) .map_err(|_| std::io::ErrorKind::Other.into()) } } impl std::io::Write for VecMessageEncoder { fn write(&mut self, buf: &[u8]) -> Result<usize, std::io::Error> { self.append_payload_bytes(buf) .map(|_| buf.len()) .map_err(|_| std::io::ErrorKind::Other.into()) } fn flush(&mut self) -> Result<(), std::io::Error> { Ok(()) } fn write_all(&mut self, buf: &[u8]) -> Result<(), std::io::Error> { self.append_payload_bytes(buf) .map_err(|_| std::io::ErrorKind::Other.into()) } }
.as_bytes()) } fn append_payload_u8(&mut self, b: u8) -> Result<(), Error> { self.append_payload_bytes(&[b]) } fn append_payload_char(&mut self, c: char) -> Result<(), Error> { self.append_payload_string(c.encode_utf8(&mut [0; 4])) } fn clear(&mut self); } impl<'a> core::fmt::Write for dyn MessageWrite + 'a { fn write_str(&mut self, s: &str) -> Result<(), core::fmt::Error> { self.append_payload_string(s)?;
random
[ { "content": "/// Extension trait for option iterators that provide additional convenient accessors.\n\npub trait OptionIteratorExt<'a>: Iterator<Item = Result<(OptionNumber, &'a [u8]), Error>> {\n\n /// Moves the iterator forward until it finds a matching key or the\n\n /// spot where it should have been...
Rust
src/client.rs
shichaoyuan/mini-redis
cefca5377af54520904c55764d16fc7c0a291902
use crate::cmd::{Get, Publish, Set, Subscribe, Unsubscribe}; use crate::{Connection, Frame}; use async_stream::try_stream; use bytes::Bytes; use std::io::{Error, ErrorKind}; use std::time::Duration; use tokio::net::{TcpStream, ToSocketAddrs}; use tokio::stream::Stream; use tracing::{debug, instrument}; pub struct Client { connection: Connection, } pub struct Subscriber { client: Client, subscribed_channels: Vec<String>, } #[derive(Debug, Clone)] pub struct Message { pub channel: String, pub content: Bytes, } pub async fn connect<T: ToSocketAddrs>(addr: T) -> crate::Result<Client> { let socket = TcpStream::connect(addr).await?; let connection = Connection::new(socket); Ok(Client { connection }) } impl Client { #[instrument(skip(self))] pub async fn get(&mut self, key: &str) -> crate::Result<Option<Bytes>> { let frame = Get::new(key).into_frame(); debug!(request = ?frame); self.connection.write_frame(&frame).await?; match self.read_response().await? { Frame::Simple(value) => Ok(Some(value.into())), Frame::Bulk(value) => Ok(Some(value)), Frame::Null => Ok(None), frame => Err(frame.to_error()), } } #[instrument(skip(self))] pub async fn set(&mut self, key: &str, value: Bytes) -> crate::Result<()> { self.set_cmd(Set::new(key, value, None)).await } #[instrument(skip(self))] pub async fn set_expires( &mut self, key: &str, value: Bytes, expiration: Duration, ) -> crate::Result<()> { self.set_cmd(Set::new(key, value, Some(expiration))).await } async fn set_cmd(&mut self, cmd: Set) -> crate::Result<()> { let frame = cmd.into_frame(); debug!(request = ?frame); self.connection.write_frame(&frame).await?; match self.read_response().await? { Frame::Simple(response) if response == "OK" => Ok(()), frame => Err(frame.to_error()), } } #[instrument(skip(self))] pub async fn publish(&mut self, channel: &str, message: Bytes) -> crate::Result<u64> { let frame = Publish::new(channel, message).into_frame(); debug!(request = ?frame); self.connection.write_frame(&frame).await?; match self.read_response().await? { Frame::Integer(response) => Ok(response), frame => Err(frame.to_error()), } } #[instrument(skip(self))] pub async fn subscribe(mut self, channels: Vec<String>) -> crate::Result<Subscriber> { self.subscribe_cmd(&channels).await?; Ok(Subscriber { client: self, subscribed_channels: channels, }) } async fn subscribe_cmd(&mut self, channels: &[String]) -> crate::Result<()> { let frame = Subscribe::new(&channels).into_frame(); debug!(request = ?frame); self.connection.write_frame(&frame).await?; for channel in channels { let response = self.read_response().await?; match response { Frame::Array(ref frame) => match frame.as_slice() { [subscribe, schannel, ..] if *subscribe == "subscribe" && *schannel == channel => {} _ => return Err(response.to_error()), }, frame => return Err(frame.to_error()), }; } Ok(()) } async fn read_response(&mut self) -> crate::Result<Frame> { let response = self.connection.read_frame().await?; debug!(?response); match response { Some(Frame::Error(msg)) => Err(msg.into()), Some(frame) => Ok(frame), None => { let err = Error::new(ErrorKind::ConnectionReset, "connection reset by server"); Err(err.into()) } } } } impl Subscriber { pub fn get_subscribed(&self) -> &[String] { &self.subscribed_channels } pub async fn next_message(&mut self) -> crate::Result<Option<Message>> { match self.client.connection.read_frame().await? { Some(mframe) => { debug!(?mframe); match mframe { Frame::Array(ref frame) => match frame.as_slice() { [message, channel, content] if *message == "message" => Ok(Some(Message { channel: channel.to_string(), content: Bytes::from(content.to_string()), })), _ => Err(mframe.to_error()), }, frame => Err(frame.to_error()), } } None => Ok(None), } } pub fn into_stream(mut self) -> impl Stream<Item = crate::Result<Message>> { try_stream! { while let Some(message) = self.next_message().await? { yield message; } } } #[instrument(skip(self))] pub async fn subscribe(&mut self, channels: &[String]) -> crate::Result<()> { self.client.subscribe_cmd(channels).await?; self.subscribed_channels .extend(channels.iter().map(Clone::clone)); Ok(()) } #[instrument(skip(self))] pub async fn unsubscribe(&mut self, channels: &[String]) -> crate::Result<()> { let frame = Unsubscribe::new(&channels).into_frame(); debug!(request = ?frame); self.client.connection.write_frame(&frame).await?; let num = if channels.is_empty() { self.subscribed_channels.len() } else { channels.len() }; for _ in 0..num { let response = self.client.read_response().await?; match response { Frame::Array(ref frame) => match frame.as_slice() { [unsubscribe, channel, ..] if *unsubscribe == "unsubscribe" => { let len = self.subscribed_channels.len(); if len == 0 { return Err(response.to_error()); } self.subscribed_channels.retain(|c| *channel != &c[..]); if self.subscribed_channels.len() != len - 1 { return Err(response.to_error()); } } _ => return Err(response.to_error()), }, frame => return Err(frame.to_error()), }; } Ok(()) } }
use crate::cmd::{Get, Publish, Set, Subscribe, Unsubscribe}; use crate::{Connection, Frame}; use async_stream::try_stream; use bytes::Bytes; use std::io::{Error, ErrorKind}; use std::time::Duration; use tokio::net::{TcpStream, ToSocketAddrs}; use tokio::stream::Stream; use tracing::{debug, instrument}; pub struct Client { connection: Connection, } pub struct Subscriber { client: Client, subscribed_channels: Vec<String>, } #[derive(Debug, Clone)] pub struct Message { pub channel: String, pub content: Bytes, } pub async fn connect<T: ToSocketAddrs>(addr: T) -> crate::Result<Client> { let socket = TcpStream::connect(addr).await?; let connection = Connection::new(socket); Ok(Client { connection }) } impl Client { #[instrument(skip(self))] pub async fn get(&mut self, key: &str) -> crate::Result<Option<Bytes>> { let frame = Get::new(key).into_frame(); debug!(request = ?frame); self.connection.write_frame(&frame).await?; match self.read_response().await? { Frame::Simple(value) => Ok(Some(value.into())), Frame::Bulk(value) => Ok(Some(value)), Frame::Null => Ok(None), frame => Err(frame.to_error()), } } #[instrument(skip(self))] pub async fn set(&mut self, key: &str, value: Bytes) -> crate::Result<()> { self.set_cmd(Set::new(key, value, None)).await } #[instrument(skip(self))] pub async fn set_expires( &mut self, key: &str, value: Bytes, expiration: Duration, ) -> crate::Result<()> { self.set_cmd(Set::new(key, value, Some(expiration))).await } async fn set_cmd(&mut self, cmd: Set) -> crate::Result<()> { let frame = cmd.into_frame(); debug!(request = ?frame); self.connection.write_frame(&frame).await?; match self.read_response().await? { Frame::Simple(response) if response == "OK" => Ok(()), frame => Err(frame.to_error()), } } #[instrument(skip(self))] pub async fn publish(&mut self, channel: &str, message: Bytes) -> crate::Result<u64> { let frame = Publish::new(channel, message).into_frame(); debug!(request = ?frame); self.connection.write_frame(&frame).await?; match self.read_response().await? { Frame::Integer(response) => Ok(response), frame => Err(frame.to_error()), } } #[instrument(skip(self))] pub async fn subscribe(mut self, channels: Vec<String>) -> crate::Result<Subscriber> { self.subscribe_cmd(&channels).await?; Ok(Subscriber { client: self, subscribed_channels: channels, }) } async fn subscribe_cmd(&mut self, channels: &[String]) -> crate::Result<()> { let frame = Subscribe::new(&channels).into_frame(); debug!(request = ?frame); self.connection.write_frame(&frame).await?; for channel in channels { let response = self.read_response().await?; match response { Frame::Array(ref frame) => match frame.as_slice() { [subscribe, schannel, ..] if *subscribe == "subscribe" && *schannel == channel => {} _ => return Err(response.to_error()), }, frame => return Err(frame.to_error()), }; } Ok(()) } async fn read_response(&mut self) -> crate::Result<Frame> { let response = self.connection.read_frame().await?; debug!(?response); match response { Some(Frame::Error(msg)) => Err(msg.into()), Some(frame) => Ok(frame), None => { let err = Error::new(ErrorKind::ConnectionReset, "connection reset by server"); Err(err.into()) } } } } impl Subscriber { pub fn get_subscribed(&self) -> &[String] { &self.subscribed_channels } pub async fn next_message(&mut self) -> crate::Result<Option<Message>> { match self.client.connection.read_frame().await? { Some(mframe) => { debug!(?mframe); match mframe { Frame::Array(ref frame) => match frame.as_slice() { [message, channel, content] if *message == "message" => Ok(Some(Message { channel: channel.to_string(), content: Bytes::from(content.to_string()), })), _ => Err(mframe.to_error()), }, frame => Err(frame.to_error()), } } None => Ok(None), } } pub fn into_stream(mut self) -> impl Stream<Item = crate::Result<Message>> { try_stream! { while let Some(message) = self.next_message().await? { yield message; } } } #[instrument(skip(self))] pub async fn subscribe(&mut self, channels: &[String]) -> crate::Result<()> { self.client.subscribe_cmd(channels).awai
#[instrument(skip(self))] pub async fn unsubscribe(&mut self, channels: &[String]) -> crate::Result<()> { let frame = Unsubscribe::new(&channels).into_frame(); debug!(request = ?frame); self.client.connection.write_frame(&frame).await?; let num = if channels.is_empty() { self.subscribed_channels.len() } else { channels.len() }; for _ in 0..num { let response = self.client.read_response().await?; match response { Frame::Array(ref frame) => match frame.as_slice() { [unsubscribe, channel, ..] if *unsubscribe == "unsubscribe" => { let len = self.subscribed_channels.len(); if len == 0 { return Err(response.to_error()); } self.subscribed_channels.retain(|c| *channel != &c[..]); if self.subscribed_channels.len() != len - 1 { return Err(response.to_error()); } } _ => return Err(response.to_error()), }, frame => return Err(frame.to_error()), }; } Ok(()) } }
t?; self.subscribed_channels .extend(channels.iter().map(Clone::clone)); Ok(()) }
function_block-function_prefixed
[ { "content": "/// Creates a message informing the client about a new message on a channel that\n\n/// the client subscribes to.\n\nfn make_message_frame(channel_name: String, msg: Bytes) -> Frame {\n\n let mut response = Frame::array();\n\n response.push_bulk(Bytes::from_static(b\"message\"));\n\n resp...
Rust
crates/nomination/src/lib.rs
gregdhill/interbtc
88e53a7d46c437fdd58ef232973388469186ecf9
#![deny(warnings)] #![cfg_attr(test, feature(proc_macro_hygiene))] #![cfg_attr(not(feature = "std"), no_std)] #[cfg(test)] mod mock; #[cfg(test)] mod tests; mod ext; mod types; mod default_weights; use ext::vault_registry::{DefaultVault, SlashingError, TryDepositCollateral, TryWithdrawCollateral}; use frame_support::{ dispatch::{DispatchError, DispatchResult}, ensure, transactional, weights::Weight, }; use frame_system::{ensure_root, ensure_signed}; use reward::RewardPool; use sp_runtime::{ traits::{CheckedAdd, CheckedDiv, CheckedSub, One, Zero}, FixedPointNumber, }; use sp_std::convert::TryInto; pub use types::Nominator; use types::{ BalanceOf, Collateral, DefaultNominator, RichNominator, SignedFixedPoint, SignedInner, UnsignedFixedPoint, }; pub trait WeightInfo { fn set_nomination_enabled() -> Weight; fn opt_in_to_nomination() -> Weight; fn opt_out_of_nomination() -> Weight; fn deposit_collateral() -> Weight; fn withdraw_collateral() -> Weight; } pub use pallet::*; #[frame_support::pallet] pub mod pallet { use super::*; use frame_support::pallet_prelude::*; use frame_system::pallet_prelude::*; #[pallet::config] pub trait Config: frame_system::Config + security::Config + vault_registry::Config + fee::Config<UnsignedFixedPoint = UnsignedFixedPoint<Self>, UnsignedInner = BalanceOf<Self>> { type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>; type WeightInfo: WeightInfo; type VaultRewards: reward::Rewards<Self::AccountId, SignedFixedPoint = SignedFixedPoint<Self>>; } #[pallet::event] #[pallet::generate_deposit(pub(super) fn deposit_event)] #[pallet::metadata(T::AccountId = "AccountId", Collateral<T> = "Collateral")] pub enum Event<T: Config> { NominationOptIn(T::AccountId), NominationOptOut(T::AccountId), DepositCollateral(T::AccountId, T::AccountId, Collateral<T>), WithdrawCollateral(T::AccountId, T::AccountId, Collateral<T>), } #[pallet::error] pub enum Error<T> { InsufficientFunds, ArithmeticOverflow, ArithmeticUnderflow, NominatorNotFound, VaultAlreadyOptedInToNomination, VaultNotOptedInToNomination, VaultNotFound, TryIntoIntError, InsufficientCollateral, VaultNominationDisabled, DepositViolatesMaxNominationRatio, HasNominatedCollateral, } impl<T: Config> From<SlashingError> for Error<T> { fn from(err: SlashingError) -> Self { match err { SlashingError::ArithmeticOverflow => Error::<T>::ArithmeticOverflow, SlashingError::ArithmeticUnderflow => Error::<T>::ArithmeticUnderflow, SlashingError::TryIntoIntError => Error::<T>::TryIntoIntError, SlashingError::InsufficientFunds => Error::<T>::InsufficientCollateral, } } } #[pallet::hooks] impl<T: Config> Hooks<T::BlockNumber> for Pallet<T> {} #[pallet::storage] #[pallet::getter(fn is_nomination_enabled)] pub type NominationEnabled<T: Config> = StorageValue<_, bool, ValueQuery>; #[pallet::storage] pub(super) type Vaults<T: Config> = StorageMap<_, Blake2_128Concat, T::AccountId, bool, ValueQuery>; #[pallet::storage] pub(super) type Nominators<T: Config> = StorageDoubleMap< _, Blake2_128Concat, T::AccountId, Blake2_128Concat, T::AccountId, Nominator<T::AccountId, Collateral<T>, SignedFixedPoint<T>>, ValueQuery, >; #[pallet::genesis_config] pub struct GenesisConfig { pub is_nomination_enabled: bool, } #[cfg(feature = "std")] impl Default for GenesisConfig { fn default() -> Self { Self { is_nomination_enabled: Default::default(), } } } #[pallet::genesis_build] impl<T: Config> GenesisBuild<T> for GenesisConfig { fn build(&self) { { NominationEnabled::<T>::put(self.is_nomination_enabled); } } } #[pallet::pallet] pub struct Pallet<T>(_); #[pallet::call] impl<T: Config> Pallet<T> { #[pallet::weight(<T as Config>::WeightInfo::set_nomination_enabled())] #[transactional] pub fn set_nomination_enabled(origin: OriginFor<T>, enabled: bool) -> DispatchResultWithPostInfo { ensure_root(origin)?; <NominationEnabled<T>>::set(enabled); Ok(().into()) } #[pallet::weight(<T as Config>::WeightInfo::opt_in_to_nomination())] #[transactional] pub fn opt_in_to_nomination(origin: OriginFor<T>) -> DispatchResultWithPostInfo { ext::security::ensure_parachain_status_running::<T>()?; Self::_opt_in_to_nomination(&ensure_signed(origin)?)?; Ok(().into()) } #[pallet::weight(<T as Config>::WeightInfo::opt_out_of_nomination())] #[transactional] pub fn opt_out_of_nomination(origin: OriginFor<T>) -> DispatchResultWithPostInfo { Self::_opt_out_of_nomination(&ensure_signed(origin)?)?; Ok(().into()) } #[pallet::weight(<T as Config>::WeightInfo::deposit_collateral())] #[transactional] pub fn deposit_collateral( origin: OriginFor<T>, vault_id: T::AccountId, amount: Collateral<T>, ) -> DispatchResultWithPostInfo { let sender = ensure_signed(origin)?; ext::security::ensure_parachain_status_running::<T>()?; Self::_deposit_collateral(sender, vault_id, amount)?; Ok(().into()) } #[pallet::weight(<T as Config>::WeightInfo::withdraw_collateral())] #[transactional] pub fn withdraw_collateral( origin: OriginFor<T>, vault_id: T::AccountId, amount: Collateral<T>, ) -> DispatchResultWithPostInfo { let sender = ensure_signed(origin)?; ext::security::ensure_parachain_status_running::<T>()?; Self::_withdraw_collateral(sender, vault_id, amount)?; Ok(().into()) } } } impl<T: Config> Pallet<T> { pub fn _withdraw_collateral( nominator_id: T::AccountId, vault_id: T::AccountId, amount: Collateral<T>, ) -> DispatchResult { ensure!(Self::is_nomination_enabled(), Error::<T>::VaultNominationDisabled); ensure!( Self::is_nominatable(&vault_id)?, Error::<T>::VaultNotOptedInToNomination ); ensure!( ext::vault_registry::is_allowed_to_withdraw_collateral::<T>(&vault_id, amount)?, Error::<T>::InsufficientCollateral ); ext::fee::withdraw_all_vault_rewards::<T>(&vault_id)?; Self::withdraw_pool_stake::<<T as pallet::Config>::VaultRewards>(&nominator_id, &vault_id, amount)?; let mut nominator: RichNominator<T> = Self::get_nominator(&nominator_id, &vault_id)?.into(); nominator.try_withdraw_collateral(amount)?; ext::collateral::unlock_and_transfer::<T>(&vault_id, &nominator_id, amount)?; Self::deposit_event(Event::<T>::WithdrawCollateral(nominator_id, vault_id, amount)); Ok(()) } pub fn _deposit_collateral( nominator_id: T::AccountId, vault_id: T::AccountId, amount: Collateral<T>, ) -> DispatchResult { ensure!(Self::is_nomination_enabled(), Error::<T>::VaultNominationDisabled); ensure!( Self::is_nominatable(&vault_id)?, Error::<T>::VaultNotOptedInToNomination ); let vault_backing_collateral = ext::vault_registry::get_backing_collateral::<T>(&vault_id)?; let total_nominated_collateral = Self::get_total_nominated_collateral(&vault_id)?; let new_nominated_collateral = total_nominated_collateral .checked_add(&amount) .ok_or(Error::<T>::ArithmeticOverflow)?; ensure!( new_nominated_collateral <= Self::get_max_nominatable_collateral(vault_backing_collateral)?, Error::<T>::DepositViolatesMaxNominationRatio ); ext::fee::withdraw_all_vault_rewards::<T>(&vault_id)?; Self::deposit_pool_stake::<<T as pallet::Config>::VaultRewards>(&nominator_id, &vault_id, amount)?; let mut nominator: RichNominator<T> = Self::register_or_get_nominator(&nominator_id, &vault_id)?.into(); nominator .try_deposit_collateral(amount) .map_err(|e| Error::<T>::from(e))?; ext::collateral::transfer_and_lock::<T>(&nominator_id, &vault_id, amount)?; Self::deposit_event(Event::<T>::DepositCollateral(nominator_id, vault_id, amount)); Ok(()) } pub fn _opt_in_to_nomination(vault_id: &T::AccountId) -> DispatchResult { ensure!(Self::is_nomination_enabled(), Error::<T>::VaultNominationDisabled); ensure!( ext::vault_registry::vault_exists::<T>(&vault_id), Error::<T>::VaultNotFound ); ensure!( !<Vaults<T>>::contains_key(vault_id), Error::<T>::VaultAlreadyOptedInToNomination ); <Vaults<T>>::insert(vault_id, true); Self::deposit_event(Event::<T>::NominationOptIn(vault_id.clone())); Ok(()) } pub fn _opt_out_of_nomination(vault_id: &T::AccountId) -> DispatchResult { ensure!( Self::get_total_nominated_collateral(vault_id)?.is_zero(), Error::<T>::HasNominatedCollateral ); <Vaults<T>>::remove(vault_id); Self::deposit_event(Event::<T>::NominationOptOut(vault_id.clone())); Ok(()) } pub fn is_nominatable(vault_id: &T::AccountId) -> Result<bool, DispatchError> { Ok(<Vaults<T>>::contains_key(&vault_id)) } pub fn is_nominator(nominator_id: &T::AccountId, vault_id: &T::AccountId) -> Result<bool, DispatchError> { Ok(<Nominators<T>>::contains_key(&nominator_id, &vault_id)) } pub fn get_total_nominated_collateral(vault_id: &T::AccountId) -> Result<Collateral<T>, DispatchError> { let vault: DefaultVault<T> = ext::vault_registry::get_vault_from_id::<T>(vault_id)?; let vault_actual_collateral = ext::vault_registry::compute_collateral::<T>(vault_id)?; Ok(vault .backing_collateral .checked_sub(&vault_actual_collateral) .ok_or(Error::<T>::ArithmeticUnderflow)?) } pub fn get_max_nomination_ratio() -> Result<UnsignedFixedPoint<T>, DispatchError> { let secure_collateral_threshold = ext::vault_registry::get_secure_collateral_threshold::<T>(); let premium_redeem_threshold = ext::vault_registry::get_premium_redeem_threshold::<T>(); Ok(secure_collateral_threshold .checked_div(&premium_redeem_threshold) .ok_or(Error::<T>::ArithmeticUnderflow)? .checked_sub(&UnsignedFixedPoint::<T>::one()) .ok_or(Error::<T>::ArithmeticUnderflow)?) } pub fn get_nominator( nominator_id: &T::AccountId, vault_id: &T::AccountId, ) -> Result<DefaultNominator<T>, DispatchError> { ensure!( Self::is_nominator(&nominator_id, &vault_id)?, Error::<T>::NominatorNotFound ); Ok(<Nominators<T>>::get(nominator_id, vault_id)) } pub fn get_rich_nominator( nominator_id: &T::AccountId, vault_id: &T::AccountId, ) -> Result<RichNominator<T>, DispatchError> { Ok(Self::get_nominator(&nominator_id, &vault_id)?.into()) } pub fn get_nominator_collateral( nominator_id: &T::AccountId, vault_id: &T::AccountId, ) -> Result<Collateral<T>, DispatchError> { let nominator = Self::get_rich_nominator(nominator_id, vault_id)?; Ok(nominator.compute_collateral()?) } pub fn register_or_get_nominator( nominator_id: &T::AccountId, vault_id: &T::AccountId, ) -> Result<DefaultNominator<T>, DispatchError> { if !Self::is_nominator(&nominator_id, &vault_id)? { let nominator = Nominator::new(nominator_id.clone(), vault_id.clone()); <Nominators<T>>::insert(nominator_id, vault_id, nominator.clone()); Ok(nominator) } else { Ok(<Nominators<T>>::get(&nominator_id, &vault_id)) } } pub fn get_max_nominatable_collateral(vault_collateral: Collateral<T>) -> Result<Collateral<T>, DispatchError> { ext::fee::collateral_for::<T>(vault_collateral, Self::get_max_nomination_ratio()?) } fn collateral_to_fixed(x: Collateral<T>) -> Result<SignedFixedPoint<T>, DispatchError> { let signed_inner = TryInto::<SignedInner<T>>::try_into(x).map_err(|_| Error::<T>::TryIntoIntError)?; let signed_fixed_point = SignedFixedPoint::<T>::checked_from_integer(signed_inner).ok_or(Error::<T>::TryIntoIntError)?; Ok(signed_fixed_point) } fn withdraw_pool_stake<R: reward::Rewards<T::AccountId, SignedFixedPoint = SignedFixedPoint<T>>>( account_id: &T::AccountId, vault_id: &T::AccountId, amount: Collateral<T>, ) -> Result<(), DispatchError> { let amount_fixed = Self::collateral_to_fixed(amount)?; if amount_fixed > SignedFixedPoint::<T>::zero() { R::withdraw_stake(RewardPool::Local(vault_id.clone()), account_id, amount_fixed)?; } Ok(()) } fn deposit_pool_stake<R: reward::Rewards<T::AccountId, SignedFixedPoint = SignedFixedPoint<T>>>( account_id: &T::AccountId, vault_id: &T::AccountId, amount: Collateral<T>, ) -> Result<(), DispatchError> { let amount_fixed = Self::collateral_to_fixed(amount)?; R::deposit_stake(RewardPool::Local(vault_id.clone()), account_id, amount_fixed)?; Ok(()) } }
#![deny(warnings)] #![cfg_attr(test, feature(proc_macro_hygiene))] #![cfg_attr(not(feature = "std"), no_std)] #[cfg(test)] mod mock; #[cfg(test)] mod tests; mod ext; mod types; mod default_weights; use ext::vault_registry::{DefaultVault, SlashingError, TryDepositCollateral, TryWithdrawCollateral}; use frame_support::{ dispatch::{DispatchError, DispatchResult}, ensure, transactional, weights::Weight, }; use frame_system::{ensure_root, ensure_signed}; use reward::RewardPool; use sp_runtime::{ traits::{CheckedAdd, CheckedDiv, CheckedSub, One, Zero}, FixedPointNumber, }; use sp_std::convert::TryInto; pub use types::Nominator; use types::{ BalanceOf, Collateral, DefaultNominator, RichNominator, SignedFixedPoint, SignedInner, UnsignedFixedPoint, }; pub trait WeightInfo { fn set_nomination_enabled() -> Weight; fn opt_in_to_nomination() -> Weight; fn opt_out_of_nomination() -> Weight; fn deposit_collateral() -> Weight; fn withdraw_collateral() -> Weight; } pub use pallet::*; #[frame_support::pallet] pub mod pallet { use super::*; use frame_support::pallet_prelude::*; use frame_system::pallet_prelude::*; #[pallet::config] pub trait Config: frame_system::Config + security::Config + vault_registry::Config + fee::Config<UnsignedFixedPoint = UnsignedFixedPoint<Self>, UnsignedInner = BalanceOf<Self>> { type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>; type WeightInfo: WeightInfo; type VaultRewards: reward::Rewards<Self::AccountId, SignedFixedPoint = SignedFixedPoint<Self>>; } #[pallet::event] #[pallet::generate_deposit(pub(super) fn deposit_event)] #[pallet::metadata(T::AccountId = "AccountId", Collateral<T> = "Collateral")] pub enum Event<T: Config> { NominationOptIn(T::AccountId), NominationOptOut(T::AccountId), DepositCollateral(T::AccountId, T::AccountId, Collateral<T>), WithdrawCollateral(T::AccountId, T::AccountId, Collateral<T>), } #[pallet::error] pub enum Error<T> { InsufficientFunds, ArithmeticOverflow, ArithmeticUnderflow, NominatorNotFound, VaultAlreadyOptedInToNomination, VaultNotOptedInToNomination, VaultNotFound, TryIntoIntError, InsufficientCollateral, VaultNominationDisabled, DepositViolatesMaxNominationRatio, HasNominatedCollateral, } impl<T: Config> From<SlashingError> for Error<T> { fn from(err: SlashingError) -> Self { match err { SlashingError::ArithmeticOverflow => Error::<T>::ArithmeticOverflow, SlashingError::ArithmeticUnderflow => Error::<T>::ArithmeticUnderflow, SlashingError::TryIntoIntError => Error::<T>::TryIntoIntError, SlashingError::InsufficientFunds => Error::<T>::InsufficientCollateral, } } } #[pallet::hooks] impl<T: Config> Hooks<T::BlockNumber> for Pallet<T> {} #[pallet::storage] #[pallet::getter(fn is_nomination_enabled)] pub type NominationEnabled<T: Config> = StorageValue<_, bool, ValueQuery>; #[pallet::storage] pub(super) type Vaults<T: Config> = StorageMap<_, Blake2_128Concat, T::AccountId, bool, ValueQuery>; #[pallet::storage] pub(super) type Nominators<T: Config> = StorageDoubleMap< _, Blake2_128Concat, T::AccountId, Blake2_128Concat, T::AccountId, Nominator<T::AccountId, Collateral<T>, SignedFixedPoint<T>>, ValueQuery, >; #[pallet::genesis_config] pub struct GenesisConfig { pub is_nomination_enabled: bool, } #[cfg(feature = "std")] impl Default for GenesisConfig { fn default() -> Self { Self { is_nomination_enabled: Default::default(), } } } #[pallet::genesis_build] impl<T: Config> GenesisBuild<T> for GenesisConfig { fn build(&self) { { NominationEnabled::<T>::put(self.is_nomination_enabled); } } } #[pallet::pallet] pub struct Pallet<T>(_); #[pallet::call] impl<T: Config> Pallet<T> { #[pallet::weight(<T as Config>::WeightInfo::set_nomination_enabled())] #[transactional] pub fn set_nomination_enabled(origin: OriginFor<T>, enabled: bool) -> DispatchResultWithPostInfo { ensure_root(origin)?; <NominationEnabled<T>>::set(enabled); Ok(().into()) } #[pallet::weight(<T as Config>::WeightInfo::opt_in_to_nomination())] #[transactional] pub fn opt_in_to_nomination(origin: OriginFor<T>) -> DispatchResultWithPostInfo { ext::security::ensure_parachain_status_running::<T>()?; Self::_opt_in_to_nomination(&ensure_signed(origin)?)?; Ok(().into()) } #[pallet::weight(<T as Config>::WeightInfo::opt_out_of_nomination())] #[transactional] pub fn opt_out_of_nomination(origin: OriginFor<T>) -> DispatchResultWithPostInfo { Self::_opt_out_of_nomination(&ensure_signed(origin)?)?; Ok(().into()) } #[pallet::weight(<T as Config>::WeightInfo::deposit_collateral())] #[transactional] pub fn deposit_collateral( origin: OriginFor<T>, vault_id: T::AccountId, amount: Collateral<T>, ) -> DispatchResultWithPostInfo { let sender = ensure_signed(origin)?; ext::security::ensure_parachain_status_running::<T>()?; Self::_deposit_collateral(sender, vault_id, amount)?; Ok(().into()) } #[pallet::weight(<T as Config>::WeightInfo::withdraw_collateral())] #[transactional] pub fn withdraw_collateral( origin: OriginFor<T>, vault_id: T::AccountId, amount: Collateral<T>, ) -> DispatchResultWithPostInfo { let sender = ensure_signed(origin)?; ext::security::ensure_parachain_status_running::<T>()?; Self::_withdraw_collateral(sender, vault_id, amount)?; Ok(().into()) } } } impl<T: Config> Pallet<T> { pub fn _withdraw_collateral( nominator_id: T::AccountId, vault_id: T::AccountId, amount: Collateral<T>, ) -> DispatchResult { ensure!(Self::is_nomination_enabled(), Error::<T>::VaultNominationDisabled); ensure!( Self::is_nominatable(&vault_id)?, Error::<T>::VaultNotOptedInToNomination ); ensure!( ext::vault_registry::is_allowed_to_withdraw_collateral::<T>(&vault_id, amount)?, Error::<T>::InsufficientCollateral ); ext::fee::withdraw_all_vault_rewards::<T>(&vault_id)?; Self::withdraw_pool_stake::<<T as pallet::Config>::VaultRewards>(&nominator_id, &vault_id, amount)?; let mut nominator: RichNominator<T> = Self::get_nominator(&nominator_id, &vault_id)?.into(); nominator.try_withdraw_collateral(amount)?; ext::collateral::unlock_and_transfer::<T>(&vault_id, &nominator_id, amount)?; Self::deposit_event(Event::<T>::WithdrawCollateral(nominator_id, vault_id, amount)); Ok(()) } pub fn _deposit_collateral( nominator_id: T::AccountId, vault_id: T::AccountId, amount: Collateral<T>, ) -> DispatchResult { ensure!(Self::is_nomination_enabled(), Error::<T>::VaultNominationDisabled); ensure!( Self::is_nominatable(&vault_id)?, Error::<T>::VaultNotOptedInToNomination ); let vault_backing_collateral = ext::vault_registry::get_backing_collateral::<T>(&vault_id)?; let total_nominated_collateral = Self::get_total_nominated_collateral(&vault_id)?; let new_nominated_collateral = total_nominated_collateral .checked_add(&amount) .ok_or(Error::<T>::ArithmeticOverflow)?; ensur
pub fn _opt_in_to_nomination(vault_id: &T::AccountId) -> DispatchResult { ensure!(Self::is_nomination_enabled(), Error::<T>::VaultNominationDisabled); ensure!( ext::vault_registry::vault_exists::<T>(&vault_id), Error::<T>::VaultNotFound ); ensure!( !<Vaults<T>>::contains_key(vault_id), Error::<T>::VaultAlreadyOptedInToNomination ); <Vaults<T>>::insert(vault_id, true); Self::deposit_event(Event::<T>::NominationOptIn(vault_id.clone())); Ok(()) } pub fn _opt_out_of_nomination(vault_id: &T::AccountId) -> DispatchResult { ensure!( Self::get_total_nominated_collateral(vault_id)?.is_zero(), Error::<T>::HasNominatedCollateral ); <Vaults<T>>::remove(vault_id); Self::deposit_event(Event::<T>::NominationOptOut(vault_id.clone())); Ok(()) } pub fn is_nominatable(vault_id: &T::AccountId) -> Result<bool, DispatchError> { Ok(<Vaults<T>>::contains_key(&vault_id)) } pub fn is_nominator(nominator_id: &T::AccountId, vault_id: &T::AccountId) -> Result<bool, DispatchError> { Ok(<Nominators<T>>::contains_key(&nominator_id, &vault_id)) } pub fn get_total_nominated_collateral(vault_id: &T::AccountId) -> Result<Collateral<T>, DispatchError> { let vault: DefaultVault<T> = ext::vault_registry::get_vault_from_id::<T>(vault_id)?; let vault_actual_collateral = ext::vault_registry::compute_collateral::<T>(vault_id)?; Ok(vault .backing_collateral .checked_sub(&vault_actual_collateral) .ok_or(Error::<T>::ArithmeticUnderflow)?) } pub fn get_max_nomination_ratio() -> Result<UnsignedFixedPoint<T>, DispatchError> { let secure_collateral_threshold = ext::vault_registry::get_secure_collateral_threshold::<T>(); let premium_redeem_threshold = ext::vault_registry::get_premium_redeem_threshold::<T>(); Ok(secure_collateral_threshold .checked_div(&premium_redeem_threshold) .ok_or(Error::<T>::ArithmeticUnderflow)? .checked_sub(&UnsignedFixedPoint::<T>::one()) .ok_or(Error::<T>::ArithmeticUnderflow)?) } pub fn get_nominator( nominator_id: &T::AccountId, vault_id: &T::AccountId, ) -> Result<DefaultNominator<T>, DispatchError> { ensure!( Self::is_nominator(&nominator_id, &vault_id)?, Error::<T>::NominatorNotFound ); Ok(<Nominators<T>>::get(nominator_id, vault_id)) } pub fn get_rich_nominator( nominator_id: &T::AccountId, vault_id: &T::AccountId, ) -> Result<RichNominator<T>, DispatchError> { Ok(Self::get_nominator(&nominator_id, &vault_id)?.into()) } pub fn get_nominator_collateral( nominator_id: &T::AccountId, vault_id: &T::AccountId, ) -> Result<Collateral<T>, DispatchError> { let nominator = Self::get_rich_nominator(nominator_id, vault_id)?; Ok(nominator.compute_collateral()?) } pub fn register_or_get_nominator( nominator_id: &T::AccountId, vault_id: &T::AccountId, ) -> Result<DefaultNominator<T>, DispatchError> { if !Self::is_nominator(&nominator_id, &vault_id)? { let nominator = Nominator::new(nominator_id.clone(), vault_id.clone()); <Nominators<T>>::insert(nominator_id, vault_id, nominator.clone()); Ok(nominator) } else { Ok(<Nominators<T>>::get(&nominator_id, &vault_id)) } } pub fn get_max_nominatable_collateral(vault_collateral: Collateral<T>) -> Result<Collateral<T>, DispatchError> { ext::fee::collateral_for::<T>(vault_collateral, Self::get_max_nomination_ratio()?) } fn collateral_to_fixed(x: Collateral<T>) -> Result<SignedFixedPoint<T>, DispatchError> { let signed_inner = TryInto::<SignedInner<T>>::try_into(x).map_err(|_| Error::<T>::TryIntoIntError)?; let signed_fixed_point = SignedFixedPoint::<T>::checked_from_integer(signed_inner).ok_or(Error::<T>::TryIntoIntError)?; Ok(signed_fixed_point) } fn withdraw_pool_stake<R: reward::Rewards<T::AccountId, SignedFixedPoint = SignedFixedPoint<T>>>( account_id: &T::AccountId, vault_id: &T::AccountId, amount: Collateral<T>, ) -> Result<(), DispatchError> { let amount_fixed = Self::collateral_to_fixed(amount)?; if amount_fixed > SignedFixedPoint::<T>::zero() { R::withdraw_stake(RewardPool::Local(vault_id.clone()), account_id, amount_fixed)?; } Ok(()) } fn deposit_pool_stake<R: reward::Rewards<T::AccountId, SignedFixedPoint = SignedFixedPoint<T>>>( account_id: &T::AccountId, vault_id: &T::AccountId, amount: Collateral<T>, ) -> Result<(), DispatchError> { let amount_fixed = Self::collateral_to_fixed(amount)?; R::deposit_stake(RewardPool::Local(vault_id.clone()), account_id, amount_fixed)?; Ok(()) } }
e!( new_nominated_collateral <= Self::get_max_nominatable_collateral(vault_backing_collateral)?, Error::<T>::DepositViolatesMaxNominationRatio ); ext::fee::withdraw_all_vault_rewards::<T>(&vault_id)?; Self::deposit_pool_stake::<<T as pallet::Config>::VaultRewards>(&nominator_id, &vault_id, amount)?; let mut nominator: RichNominator<T> = Self::register_or_get_nominator(&nominator_id, &vault_id)?.into(); nominator .try_deposit_collateral(amount) .map_err(|e| Error::<T>::from(e))?; ext::collateral::transfer_and_lock::<T>(&nominator_id, &vault_id, amount)?; Self::deposit_event(Event::<T>::DepositCollateral(nominator_id, vault_id, amount)); Ok(()) }
function_block-function_prefixed
[ { "content": "pub fn origin_of(account_id: AccountId) -> <Runtime as frame_system::Config>::Origin {\n\n <Runtime as frame_system::Config>::Origin::signed(account_id)\n\n}\n\n\n", "file_path": "parachain/runtime/tests/mock/mod.rs", "rank": 0, "score": 354341.9938808502 }, { "content": "pu...
Rust
adafruit-feather-nrf52840-express/examples/feather-express-listener.rs
blueluna/nrf52840-dk-experiments
bbe34a24b9002f9f446e949d7b8013d2e8dae484
#![no_main] #![no_std] use panic_itm as _; use cortex_m::{iprintln, peripheral::ITM}; use rtic::app; use bbqueue::{self, BBBuffer}; use nrf52840_hal::{clocks, gpio, uarte}; use nrf52840_pac as pac; use psila_nrf52::radio::{Radio, MAX_PACKET_LENGHT}; const PACKET_BUFFER_SIZE: usize = 2048; static PKT_BUFFER: BBBuffer<PACKET_BUFFER_SIZE> = BBBuffer::new(); #[app(device = nrf52840_pac, peripherals = true)] const APP: () = { struct Resources { radio: Radio, itm: ITM, uart: uarte::Uarte<pac::UARTE0>, rx_producer: bbqueue::Producer<'static, PACKET_BUFFER_SIZE>, rx_consumer: bbqueue::Consumer<'static, PACKET_BUFFER_SIZE>, } #[init] fn init(cx: init::Context) -> init::LateResources { let port0 = gpio::p0::Parts::new(cx.device.P0); let _clocks = clocks::Clocks::new(cx.device.CLOCK) .enable_ext_hfosc() .set_lfclk_src_external(clocks::LfOscConfiguration::NoExternalNoBypass) .start_lfclk(); let uarte0 = uarte::Uarte::new( cx.device.UARTE0, uarte::Pins { txd: port0 .p0_06 .into_push_pull_output(gpio::Level::High) .degrade(), rxd: port0.p0_08.into_floating_input().degrade(), cts: Some(port0.p0_07.into_floating_input().degrade()), rts: Some( port0 .p0_05 .into_push_pull_output(gpio::Level::High) .degrade(), ), }, uarte::Parity::EXCLUDED, uarte::Baudrate::BAUD115200, ); let (q_producer, q_consumer) = PKT_BUFFER.try_split().unwrap(); let mut radio = Radio::new(cx.device.RADIO); radio.set_channel(15); radio.set_transmission_power(8); radio.receive_prepare(); init::LateResources { radio, itm: cx.core.ITM, uart: uarte0, rx_producer: q_producer, rx_consumer: q_consumer, } } #[task(binds = RADIO, resources = [radio, rx_producer],)] fn radio(cx: radio::Context) { let radio = cx.resources.radio; let queue = cx.resources.rx_producer; match queue.grant_exact(MAX_PACKET_LENGHT) { Ok(mut grant) => { if grant.buf().len() < MAX_PACKET_LENGHT { grant.commit(0); } else { if let Ok(packet_len) = radio.receive_slice(grant.buf()) { grant.commit(packet_len); } else { grant.commit(0); } } } Err(_) => { let mut buffer = [0u8; MAX_PACKET_LENGHT]; let _ = radio.receive(&mut buffer); } } } #[idle(resources = [rx_consumer, uart, itm])] fn idle(cx: idle::Context) -> ! { let mut host_packet = [0u8; MAX_PACKET_LENGHT * 2]; let queue = cx.resources.rx_consumer; let uarte = cx.resources.uart; let itm_port = &mut cx.resources.itm.stim[0]; iprintln!(itm_port, "~ listening ~"); loop { if let Ok(grant) = queue.read() { let packet_length = grant[0] as usize; match esercom::com_encode( esercom::MessageType::RadioReceive, &grant[1..packet_length], &mut host_packet, ) { Ok(written) => { uarte.write(&host_packet[..written]).unwrap(); } Err(_) => { iprintln!(itm_port, "Failed to encode packet"); } } grant.release(packet_length); } } } };
#![no_main] #![no_std] use panic_itm as _; use cortex_m::{iprintln, peripheral::ITM}; use rtic::app; use bbqueue::{self, BBBuffer}; use nrf52840_hal::{clocks, gpio, uarte}; use nrf52840_pac as pac; use psila_nrf52::radio::{Radio, MAX_PACKET_LENGHT}; const PACKET_BUFFER_SIZE: usize = 2048; static PKT_BUFFER: BBBuffer<PACKET_BUFFER_SIZE> = BBBuffer::new(); #[app(device = nrf52840_pac, peripherals = true)] const APP: () = { struct Resources { radio: Radio, itm: ITM, uart: uarte::Uarte<pac::UARTE0>, rx_producer: bbqueue::Producer<'static, PACKET_BUFFER_SIZE>, rx_consumer: bbqueue::Consumer<'static, PACKET_BUFFER_SIZE>, } #[init] fn init(cx: init::Context) -> init::LateResources { let port0 = gpio::p0::Parts::new(cx.device.P0); let _clocks = clocks::Clocks::new(cx.device.CLOCK) .enable_ext_hfosc() .set_lfclk_src_external(clocks::LfOscConfiguration::NoExternalNoBypass) .start_lfclk(); let uarte0 = uarte::Uarte::new( cx.device.UARTE0, uarte::Pins { txd: port0 .p0_06 .into_push_pull_output(gpio::Level::High) .degrade(), rxd: port0.p0_08.into_floating_input().degrade(), cts: Some(port0.p0_07.into_floating_input().degrade()), rts: Some( port0 .p0_05 .into_push_pull_output(gpio::Level::High) .degrade(), ), }, uarte::Parity::EXCLUDED, uarte::Baudrate::BAUD115200, ); let (q_producer, q_consumer) = PKT_BUFFER.try_split().unwrap(); let mut radio = Radio::new(cx.device.RADIO); radio.set_channel(15); radio.set_transmission_power(8); radio.receive_prepare(); init::LateResources { radio, itm: cx.core.ITM, uart: uarte0, rx_producer: q_producer, rx_consumer: q_consumer, } } #[task(binds = RADIO, resources = [radio, rx_producer],)] fn radio(cx: radio::Context) { let radio = cx.resources.radio; let queue
let mut buffer = [0u8; MAX_PACKET_LENGHT]; let _ = radio.receive(&mut buffer); } } } #[idle(resources = [rx_consumer, uart, itm])] fn idle(cx: idle::Context) -> ! { let mut host_packet = [0u8; MAX_PACKET_LENGHT * 2]; let queue = cx.resources.rx_consumer; let uarte = cx.resources.uart; let itm_port = &mut cx.resources.itm.stim[0]; iprintln!(itm_port, "~ listening ~"); loop { if let Ok(grant) = queue.read() { let packet_length = grant[0] as usize; match esercom::com_encode( esercom::MessageType::RadioReceive, &grant[1..packet_length], &mut host_packet, ) { Ok(written) => { uarte.write(&host_packet[..written]).unwrap(); } Err(_) => { iprintln!(itm_port, "Failed to encode packet"); } } grant.release(packet_length); } } } };
= cx.resources.rx_producer; match queue.grant_exact(MAX_PACKET_LENGHT) { Ok(mut grant) => { if grant.buf().len() < MAX_PACKET_LENGHT { grant.commit(0); } else { if let Ok(packet_len) = radio.receive_slice(grant.buf()) { grant.commit(packet_len); } else { grant.commit(0); } } } Err(_) => {
function_block-random_span
[ { "content": "fn clear(slice: &mut [u8]) {\n\n for v in slice.iter_mut() {\n\n *v = 0;\n\n }\n\n}\n\n\n\n#[derive(Clone, Debug, PartialEq)]\n\npub enum EncryptDecrypt {\n\n /// Encryp operation\n\n Encrypt = 0,\n\n /// Decryp operation\n\n Decrypt = 1,\n\n}\n\n\n\n/// Block cipher key t...
Rust
src/elastic/src/types/string/macros.rs
reinfer/elastic
78191a70d3774295ba66e1cf35f72e216e9fbf2a
macro_rules! impl_string_type { ($wrapper_ty:ident, $mapping_ty:ident, $field_type:ident) => { impl<TMapping> $field_type<TMapping> for $wrapper_ty<TMapping> where TMapping: $mapping_ty {} impl_mapping_type!(String, $wrapper_ty, $mapping_ty); impl<'a, TMapping> From<$wrapper_ty<TMapping>> for String where TMapping: $mapping_ty, { fn from(wrapper: $wrapper_ty<TMapping>) -> Self { wrapper.value } } impl<'a, TMapping> From<&'a $wrapper_ty<TMapping>> for std::borrow::Cow<'a, str> where TMapping: $mapping_ty, { fn from(wrapper: &'a $wrapper_ty<TMapping>) -> Self { wrapper.as_ref().into() } } impl<'a, TMapping> From<&'a $wrapper_ty<TMapping>> for &'a str where TMapping: $mapping_ty, { fn from(wrapper: &'a $wrapper_ty<TMapping>) -> Self { wrapper.as_ref() } } impl<'a, TMapping> From<$wrapper_ty<TMapping>> for std::borrow::Cow<'a, str> where TMapping: $mapping_ty, { fn from(wrapper: $wrapper_ty<TMapping>) -> Self { String::from(wrapper).into() } } impl<TMapping> AsRef<str> for $wrapper_ty<TMapping> where TMapping: $mapping_ty, { fn as_ref(&self) -> &str { &self.value } } impl<'a, TMapping> PartialEq<&'a str> for $wrapper_ty<TMapping> where TMapping: $mapping_ty, { fn eq(&self, other: &&'a str) -> bool { PartialEq::eq(&self.value, *other) } } impl<'a, TMapping> PartialEq<$wrapper_ty<TMapping>> for &'a str where TMapping: $mapping_ty, { fn eq(&self, other: &$wrapper_ty<TMapping>) -> bool { PartialEq::eq(*self, &other.value) } } impl<TMapping> Serialize for $wrapper_ty<TMapping> where TMapping: $mapping_ty, { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { serializer.serialize_str(&self.value) } } impl<'de, TMapping> Deserialize<'de> for $wrapper_ty<TMapping> where TMapping: $mapping_ty, { fn deserialize<D>(deserializer: D) -> Result<$wrapper_ty<TMapping>, D::Error> where D: Deserializer<'de>, { struct StringVisitor<TMapping> { _m: PhantomData<TMapping>, } impl<'de, TMapping> Visitor<'de> for StringVisitor<TMapping> where TMapping: $mapping_ty, { type Value = $wrapper_ty<TMapping>; fn expecting( &self, formatter: &mut ::std::fmt::Formatter, ) -> ::std::fmt::Result { write!(formatter, "a json string") } fn visit_str<E>(self, v: &str) -> Result<$wrapper_ty<TMapping>, E> where E: Error, { Ok($wrapper_ty::new(v)) } } deserializer.deserialize_any(StringVisitor { _m: PhantomData }) } } }; }
macro_rules! impl_string_type { ($wrapper_ty:ident, $mapping_ty:ident, $field_type:ident) => { impl<TMapping> $field_type<TMapping> for $wrapper_ty<TMapping> where TMapping: $mapping_ty {} impl_mapping_type!(String, $wrapper_ty, $mapping_ty); impl<'a, TMapping> From<$wrapper_ty<TMapping>> for String where TMapping: $mapping_ty, { fn from(wrapper: $wrapper
orrow::Cow<'a, str> where TMapping: $mapping_ty, { fn from(wrapper: &'a $wrapper_ty<TMapping>) -> Self { wrapper.as_ref().into() } } impl<'a, TMapping> From<&'a $wrapper_ty<TMapping>> for &'a str where TMapping: $mapping_ty, { fn from(wrapper: &'a $wrapper_ty<TMapping>) -> Self { wrapper.as_ref() } } impl<'a, TMapping> From<$wrapper_ty<TMapping>> for std::borrow::Cow<'a, str> where TMapping: $mapping_ty, { fn from(wrapper: $wrapper_ty<TMapping>) -> Self { String::from(wrapper).into() } } impl<TMapping> AsRef<str> for $wrapper_ty<TMapping> where TMapping: $mapping_ty, { fn as_ref(&self) -> &str { &self.value } } impl<'a, TMapping> PartialEq<&'a str> for $wrapper_ty<TMapping> where TMapping: $mapping_ty, { fn eq(&self, other: &&'a str) -> bool { PartialEq::eq(&self.value, *other) } } impl<'a, TMapping> PartialEq<$wrapper_ty<TMapping>> for &'a str where TMapping: $mapping_ty, { fn eq(&self, other: &$wrapper_ty<TMapping>) -> bool { PartialEq::eq(*self, &other.value) } } impl<TMapping> Serialize for $wrapper_ty<TMapping> where TMapping: $mapping_ty, { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { serializer.serialize_str(&self.value) } } impl<'de, TMapping> Deserialize<'de> for $wrapper_ty<TMapping> where TMapping: $mapping_ty, { fn deserialize<D>(deserializer: D) -> Result<$wrapper_ty<TMapping>, D::Error> where D: Deserializer<'de>, { struct StringVisitor<TMapping> { _m: PhantomData<TMapping>, } impl<'de, TMapping> Visitor<'de> for StringVisitor<TMapping> where TMapping: $mapping_ty, { type Value = $wrapper_ty<TMapping>; fn expecting( &self, formatter: &mut ::std::fmt::Formatter, ) -> ::std::fmt::Result { write!(formatter, "a json string") } fn visit_str<E>(self, v: &str) -> Result<$wrapper_ty<TMapping>, E> where E: Error, { Ok($wrapper_ty::new(v)) } } deserializer.deserialize_any(StringVisitor { _m: PhantomData }) } } }; }
_ty<TMapping>) -> Self { wrapper.value } } impl<'a, TMapping> From<&'a $wrapper_ty<TMapping>> for std::b
random
[ { "content": "fn dedup_urls(endpoint: (String, Endpoint)) -> (String, Endpoint) {\n\n let (name, mut endpoint) = endpoint;\n\n\n\n let mut deduped_paths = BTreeMap::new();\n\n\n\n for path in endpoint.url.paths {\n\n let key = path.params().join(\"\");\n\n\n\n deduped_paths.insert(key, pa...
Rust
examples/src/bin/orientable_subclass.rs
elmarco/gtk4-rs
a1f7bcc611584c542308bd062ceda0103f96a69a
use std::cell::RefCell; use std::env; use gtk::glib; use gtk::prelude::*; use gtk::subclass::prelude::ObjectSubclass; mod imp { use super::*; use gtk::{glib::translate::ToGlib, subclass::prelude::*}; #[derive(Debug)] pub struct CustomOrientable { first_label: RefCell<Option<gtk::Widget>>, second_label: RefCell<Option<gtk::Widget>>, orientation: RefCell<gtk::Orientation>, } #[glib::object_subclass] impl ObjectSubclass for CustomOrientable { const NAME: &'static str = "ExCustomOrientable"; type Type = super::CustomOrientable; type ParentType = gtk::Widget; type Interfaces = (gtk::Orientable,); fn class_init(klass: &mut Self::Class) { klass.set_layout_manager_type::<gtk::BoxLayout>(); } fn new() -> Self { Self { first_label: RefCell::new(None), second_label: RefCell::new(None), orientation: RefCell::new(gtk::Orientation::Horizontal), } } } impl ObjectImpl for CustomOrientable { fn constructed(&self, obj: &Self::Type) { self.parent_constructed(obj); let first_label = gtk::Label::new(Some("Hello")); let second_label = gtk::Label::new(Some("World!")); let layout_manager = obj .get_layout_manager() .unwrap() .downcast::<gtk::BoxLayout>() .unwrap(); layout_manager.set_spacing(6); first_label.set_parent(obj); second_label.set_parent(obj); self.first_label .replace(Some(first_label.upcast::<gtk::Widget>())); self.second_label .replace(Some(second_label.upcast::<gtk::Widget>())); } fn dispose(&self, _obj: &Self::Type) { if let Some(child) = self.first_label.borrow_mut().take() { child.unparent(); } if let Some(child) = self.second_label.borrow_mut().take() { child.unparent(); } } fn properties() -> &'static [glib::ParamSpec] { use once_cell::sync::Lazy; static PROPERTIES: Lazy<Vec<glib::ParamSpec>> = Lazy::new(|| { vec![glib::ParamSpec::enum_( "orientation", "orientation", "Orientation", gtk::Orientation::static_type(), gtk::Orientation::Horizontal.to_glib(), glib::ParamFlags::READWRITE | glib::ParamFlags::CONSTRUCT, )] }); PROPERTIES.as_ref() } fn set_property( &self, obj: &Self::Type, _id: usize, value: &glib::Value, pspec: &glib::ParamSpec, ) { match pspec.get_name() { "orientation" => { let orientation = value.get().unwrap().unwrap(); self.orientation.replace(orientation); let layout_manager = obj .get_layout_manager() .unwrap() .downcast::<gtk::BoxLayout>() .unwrap(); layout_manager.set_orientation(orientation); } _ => unimplemented!(), } } fn get_property( &self, _obj: &Self::Type, _id: usize, pspec: &glib::ParamSpec, ) -> glib::Value { match pspec.get_name() { "orientation" => self.orientation.borrow().to_value(), _ => unimplemented!(), } } } impl WidgetImpl for CustomOrientable {} impl OrientableImpl for CustomOrientable {} } glib::wrapper! { pub struct CustomOrientable(ObjectSubclass<imp::CustomOrientable>) @extends gtk::Widget, @implements gtk::Orientable; } impl CustomOrientable { pub fn new() -> Self { glib::Object::new(&[]).expect("Failed to create CustomOrientable") } } fn main() { let application = gtk::Application::new( Some("com.github.gtk-rs.examples.orientable_subclass"), Default::default(), ) .expect("Initialization failed..."); application.connect_activate(|app| { let window = gtk::ApplicationWindow::new(app); let bx = gtk::Box::new(gtk::Orientation::Vertical, 6); let orientable = CustomOrientable::new(); let button = gtk::Button::with_label("Switch orientation"); button.connect_clicked(glib::clone!(@weak orientable => move |_| { match orientable.get_orientation() { gtk::Orientation::Horizontal => orientable.set_orientation(gtk::Orientation::Vertical), gtk::Orientation::Vertical => orientable.set_orientation(gtk::Orientation::Horizontal), _ => unreachable!(), }; })); orientable.set_halign(gtk::Align::Center); bx.append(&orientable); bx.append(&button); bx.set_margin_top(18); bx.set_margin_bottom(18); bx.set_margin_start(18); bx.set_margin_end(18); window.set_child(Some(&bx)); window.show(); }); application.run(&env::args().collect::<Vec<_>>()); }
use std::cell::RefCell; use std::env; use gtk::glib; use gtk::prelude::*; use gtk::subclass::prelude::ObjectSubclass; mod imp { use super::*; use gtk::{glib::translate::ToGlib, subclass::prelude::*}; #[derive(Debug)] pub struct CustomOrientable { first_label: RefCell<Option<gtk::Widget>>, second_label: RefCell<Option<gtk::Widget>>, orientation: RefCell<gtk::Orientation>, } #[glib::object_subclass] impl ObjectSubclass for CustomOrientable { const NAME: &'static str = "ExCustomOrientable"; type Type = super::CustomOrientable; type ParentType = gtk::Widget; type Interfaces = (gtk::Orientable,); fn class_init(klass: &mut Self::Class) { klass.set_layout_manager_type::<gtk::BoxLayout>(); } fn new() -> Self { Self { first_label: RefCell::new(None), second_label: RefCell::new(None), orientation: RefCell::new(gtk::Orientation::Horizontal), } } } impl ObjectImpl for CustomOrientable { fn constructed(&self, obj: &Self::Type) { self.parent_constructed(obj); let first_label = gtk::Label::new(Some("Hello")); let second_label = gtk::Label::new(Some("World!")); let layout_manager = obj .get_layout_manager() .unwrap() .downcast::<gtk::BoxLayout>() .unwrap(); layout_manager.set_spacing(6); first_label.set_parent(obj); second_label.set_parent(obj); self.first_label .replace(Some(first_label.upcast::<gtk::Widget>())); self.second_label .replace(Some(second_label.upcast::<gtk::Widget>())); } fn dispose(&self, _obj: &Self::Type) { if let Some(child) = self.first_label.borrow_mut().take() { child.unparent(); } if let Some(child) = self.second_label.borrow_mut().take() { child.unparent(); } } fn properties() -> &'static [glib::ParamSpec] { use once_cell::sync::Lazy; static PROPERTIES: Lazy<Vec<glib::ParamSpec>> = Lazy::new(|| { vec![glib::ParamSpec::enum_( "orientation", "orientation", "Orientation", gtk::Orientation::static_type(), gtk::Orientation::Horizontal.to_glib(), glib::ParamFlags::READWRITE | glib::ParamFlags::CONSTRUCT, )] }); PROPERTIES.as_ref() } fn set_property( &self, obj: &Self::Type, _id: usize, value: &glib::Value, pspec: &glib::ParamSpec, ) { match pspec.get_name() { "orientation" => { let orientation = value.get().unwrap().unwrap(); self.orientation.replace(orientation); let layout_manager = obj .get_layout_manager() .unwrap() .downcast::<gtk::BoxLayout>() .unwrap(); layout_manager.set_orientation(orientation); } _ => unimplemented!(), } } fn get_property( &self, _obj: &Self::Type, _id: usize, pspec: &glib::ParamSpec, ) -> glib::Value { match pspec.get_name() { "orientation" => self.orientation.borrow().to_value(), _ => unimplemented!(), } } } impl WidgetImpl for CustomOrientable {} impl OrientableImpl for CustomOrientable {} } glib::wrapper! { pub struct CustomOrientable(ObjectSubclass<imp::CustomOrientable>) @extends gtk::Widget, @implements gtk::Orientable; } impl CustomOrientable { pub fn new() -> Self { glib::Object::new(&[]).expect("Failed to create CustomOrientable") } } fn main() { let application = gtk::Application::new( Some("com.github.gtk-rs.examples.orientable_subclass"), Default::default(), ) .expect("Initialization failed..."); application.connect_activate(|app| { let window = gtk::ApplicationWindow::new(app); let bx = gtk::Box::new(gtk::Orientation::Vertical, 6); let orientable = CustomOrientable::new(); let button = gtk::Button::with_label("Switch orientation");
bx.append(&orientable); bx.append(&button); bx.set_margin_top(18); bx.set_margin_bottom(18); bx.set_margin_start(18); bx.set_margin_end(18); window.set_child(Some(&bx)); window.show(); }); application.run(&env::args().collect::<Vec<_>>()); }
button.connect_clicked(glib::clone!(@weak orientable => move |_| { match orientable.get_orientation() { gtk::Orientation::Horizontal => orientable.set_orientation(gtk::Orientation::Vertical), gtk::Orientation::Vertical => orientable.set_orientation(gtk::Orientation::Horizontal), _ => unreachable!(), }; })); orientable.set_halign(gtk::Align::Center);
function_block-random_span
[ { "content": "pub trait ApplicationWindowImpl: WindowImpl + 'static {}\n\n\n\nunsafe impl<T: ApplicationWindowImpl> IsSubclassable<T> for ApplicationWindow {\n\n fn class_init(class: &mut glib::Class<Self>) {\n\n <Window as IsSubclassable<T>>::class_init(class);\n\n }\n\n\n\n fn instance_init(in...
Rust
packages/vm/src/middleware/deterministic.rs
slave5vw/cosmwasm
220e39c8977eb0f0391a429c146872ad59b16426
use wasmer::wasmparser::Operator; use wasmer::{ FunctionMiddleware, LocalFunctionIndex, MiddlewareError, MiddlewareReaderState, ModuleMiddleware, }; #[derive(Debug)] pub struct Deterministic {} impl Deterministic { pub fn new() -> Self { Self {} } } impl ModuleMiddleware for Deterministic { fn generate_function_middleware(&self, _: LocalFunctionIndex) -> Box<dyn FunctionMiddleware> { Box::new(FunctionDeterministic {}) } } #[derive(Debug)] pub struct FunctionDeterministic {} impl FunctionMiddleware for FunctionDeterministic { fn feed<'a>( &mut self, operator: Operator<'a>, state: &mut MiddlewareReaderState<'a>, ) -> Result<(), MiddlewareError> { match operator { Operator::Unreachable | Operator::Nop | Operator::Block { .. } | Operator::Loop { .. } | Operator::If { .. } | Operator::Else | Operator::End | Operator::Br { .. } | Operator::BrIf { .. } | Operator::BrTable { .. } | Operator::Return | Operator::Call { .. } | Operator::CallIndirect { .. } | Operator::Drop | Operator::Select | Operator::LocalGet { .. } | Operator::LocalSet { .. } | Operator::LocalTee { .. } | Operator::GlobalGet { .. } | Operator::GlobalSet { .. } | Operator::I32Load { .. } | Operator::I64Load { .. } | Operator::I32Load8S { .. } | Operator::I32Load8U { .. } | Operator::I32Load16S { .. } | Operator::I32Load16U { .. } | Operator::I64Load8S { .. } | Operator::I64Load8U { .. } | Operator::I64Load16S { .. } | Operator::I64Load16U { .. } | Operator::I64Load32S { .. } | Operator::I64Load32U { .. } | Operator::I32Store { .. } | Operator::I64Store { .. } | Operator::I32Store8 { .. } | Operator::I32Store16 { .. } | Operator::I64Store8 { .. } | Operator::I64Store16 { .. } | Operator::I64Store32 { .. } | Operator::MemorySize { .. } | Operator::MemoryGrow { .. } | Operator::I32Const { .. } | Operator::I64Const { .. } | Operator::I32Eqz | Operator::I32Eq | Operator::I32Ne | Operator::I32LtS | Operator::I32LtU | Operator::I32GtS | Operator::I32GtU | Operator::I32LeS | Operator::I32LeU | Operator::I32GeS | Operator::I32GeU | Operator::I64Eqz | Operator::I64Eq | Operator::I64Ne | Operator::I64LtS | Operator::I64LtU | Operator::I64GtS | Operator::I64GtU | Operator::I64LeS | Operator::I64LeU | Operator::I64GeS | Operator::I64GeU | Operator::I32Clz | Operator::I32Ctz | Operator::I32Popcnt | Operator::I32Add | Operator::I32Sub | Operator::I32Mul | Operator::I32DivS | Operator::I32DivU | Operator::I32RemS | Operator::I32RemU | Operator::I32And | Operator::I32Or | Operator::I32Xor | Operator::I32Shl | Operator::I32ShrS | Operator::I32ShrU | Operator::I32Rotl | Operator::I32Rotr | Operator::I64Clz | Operator::I64Ctz | Operator::I64Popcnt | Operator::I64Add | Operator::I64Sub | Operator::I64Mul | Operator::I64DivS | Operator::I64DivU | Operator::I64RemS | Operator::I64RemU | Operator::I64And | Operator::I64Or | Operator::I64Xor | Operator::I64Shl | Operator::I64ShrS | Operator::I64ShrU | Operator::I64Rotl | Operator::I64Rotr | Operator::I32WrapI64 | Operator::I32Extend8S | Operator::I32Extend16S | Operator::I64Extend8S | Operator::I64Extend16S | Operator::I64ExtendI32S | Operator::I64ExtendI32U => { state.push_operator(operator); Ok(()) } _ => { let msg = format!("Non-determinstic operator detected: {:?}", operator); Err(MiddlewareError::new("Deterministic", msg)) } } } } #[cfg(test)] mod tests { use super::*; use std::sync::Arc; use wasmer::{CompilerConfig, Cranelift, Module, Store, JIT}; #[test] fn valid_wasm_instance_sanity() { let wasm = wat::parse_str( r#" (module (func (export "sum") (param i32 i32) (result i32) get_local 0 get_local 1 i32.add )) "#, ) .unwrap(); let deterministic = Arc::new(Deterministic::new()); let mut compiler_config = Cranelift::default(); compiler_config.push_middleware(deterministic); let store = Store::new(&JIT::new(compiler_config).engine()); let result = Module::new(&store, &wasm); assert!(result.is_ok()); } #[test] fn parser_floats_are_not_supported() { let wasm = wat::parse_str( r#" (module (func $to_float (param i32) (result f32) get_local 0 f32.convert_u/i32 )) "#, ) .unwrap(); let deterministic = Arc::new(Deterministic::new()); let mut compiler_config = Cranelift::default(); compiler_config.push_middleware(deterministic); let store = Store::new(&JIT::new(compiler_config).engine()); let result = Module::new(&store, &wasm); assert!(result.is_err()); } }
use wasmer::wasmparser::Operator; use wasmer::{ FunctionMiddleware, LocalFunctionIndex, MiddlewareError, MiddlewareReaderState, ModuleMiddleware, }; #[derive(Debug)] pub struct Deterministic {} impl Deterministic { pub fn new() -> Self { Self {} } } impl ModuleMiddleware for Deterministic { fn generate_function_middleware(&self, _: LocalFunctionIndex) -> Box<dyn FunctionMiddleware> { Box::new(FunctionDeterministic {}) } } #[derive(Debug)] pub struct FunctionDeterministic {} impl FunctionMiddleware for FunctionDeterministic { fn feed<'a>( &mut self, operator: Operator<'a>, state: &mut MiddlewareReaderState<'a>, ) -> Result<(), MiddlewareError> { match operator { Operator::Unreachable | Operator::Nop | Operator::Block { .. } | Operator::Loop { .. } | Operator::If { .. } | Operator::Else | Operator::End | Operator::Br { .. } | Operator::BrIf { .. } | Operator::BrTable { .. } | Operator::Return | Operator::Call { .. } | Operator::CallIndirect { .. } | Operator::Drop | Operator::Select | Operator::LocalGet { .. } | Operator::LocalSet { .. } | Operator::LocalTee { .. } | Operator::GlobalGet { .. } | Operator::GlobalSet { .. } | Operator::I32Load { .. } | Operator::I64Load { .. } | Operator::I32Load8S { .. } | Operator::I32Load8U { .. } | Operator::I32Load16S { .. } | Operator::I32Load16U { .. } | Operator::I64Load8S { .. } | Operator::I64Load8U { .. } | Operator::I64Load16S { .. } | Operator::I64Load16U { .. } | Operator::I64Load32S { .. } | Operator::I64Load32U { .. } | Operator::I32Store { .. } | Operator::I64Store { .. } | Operator::I32Store8 { .. } | Operator::I32Store16 { .. } | Operator::I64Store8 { .. } | Operator::I64Store16 { .. } | Operator::I64Store32 { .. } | Operator::MemorySize { .. } | Operator::MemoryGrow { .. } | Operator::I32Const { .. } | Operator::I64Const { .. } | Operator::I32Eqz | Operator::I32Eq | Operator::I32Ne | Operator::I32LtS | Operator::I32LtU | Operator::I32GtS | Operator::I32GtU | Operator::I32LeS | Operator::I32LeU | Operator::I32GeS | Operator::I32GeU | Operator::I64Eqz | Operator::I64Eq | Operator::I64Ne | Operator::I64LtS | Operator::I64LtU | Operator::I64GtS | Operator::I64GtU | Operator::I64LeS | Operator::I64LeU | Operator::I64GeS | Operator::I64GeU | Operator::I32Clz | Operator::I32Ctz | Operator::I32Popcnt | Operator::I32Add | Operator::I32Sub | Operator::I32Mul | Operator::I32DivS | Operator::I32DivU | Operator::I32RemS | Operator::I32RemU | Operator::I32And | Operator::I32Or | Operator::I32Xor | Operator::I32Shl | Operator::I32ShrS | Operator::I32ShrU | Operator::I32Rotl | Operator::I32Rotr | Operator::I64Clz | Operator::I64Ctz | Operator::I64Popcnt | Operator::I64Add | Operator::I64Sub | Operator::I64Mul | Operator::I64DivS | Operator::I64DivU | Operator::I64RemS | Operator::I64RemU | Operator::I64And | Operator::I64Or | Operator::I64Xor | Operator::I64Shl | Operator::I64ShrS | Operator::I64ShrU | Operator::I64Rotl | Operator::I64Rotr | Operator::I32WrapI64 | Operator::I32Extend8S | Operator::I32Extend16S | Operator::I64Extend8S | Operator::I64Extend16S | Operator::I64ExtendI32S | Operator::I64ExtendI32U => { state.push_operator(operator); Ok(()) } _ => { let msg = format!("Non-determinstic operator detected: {:?}", operator); Err(MiddlewareError::new("Deterministic", msg)) } } } } #[cfg(test)] mod tests { use super::*; use std::sync::Arc; use wasmer::{CompilerConfig, Cranelift, Module, Store, JIT}; #[test] fn valid_wasm_instance_sanity() {
let deterministic = Arc::new(Deterministic::new()); let mut compiler_config = Cranelift::default(); compiler_config.push_middleware(deterministic); let store = Store::new(&JIT::new(compiler_config).engine()); let result = Module::new(&store, &wasm); assert!(result.is_ok()); } #[test] fn parser_floats_are_not_supported() { let wasm = wat::parse_str( r#" (module (func $to_float (param i32) (result f32) get_local 0 f32.convert_u/i32 )) "#, ) .unwrap(); let deterministic = Arc::new(Deterministic::new()); let mut compiler_config = Cranelift::default(); compiler_config.push_middleware(deterministic); let store = Store::new(&JIT::new(compiler_config).engine()); let result = Module::new(&store, &wasm); assert!(result.is_err()); } }
let wasm = wat::parse_str( r#" (module (func (export "sum") (param i32 i32) (result i32) get_local 0 get_local 1 i32.add )) "#, ) .unwrap();
assignment_statement
[ { "content": "pub fn config(storage: &mut dyn Storage) -> Singleton<State> {\n\n singleton(storage, CONFIG_KEY)\n\n}\n\n\n", "file_path": "contracts/reflect/src/state.rs", "rank": 0, "score": 281227.80228281906 }, { "content": "#[entry_point]\n\npub fn init(deps: DepsMut, _env: Env, info:...
Rust
strum_macros/src/macros/enum_iter.rs
orenbenkiki/strum
d5f660a3737ca0db3a5d8384a772e2b92e4ec0ed
use proc_macro2::{Span, TokenStream}; use quote::quote; use syn::{Data, DeriveInput, Fields, Ident}; use crate::helpers::{non_enum_error, HasStrumVariantProperties, HasTypeProperties}; pub fn enum_iter_inner(ast: &DeriveInput) -> syn::Result<TokenStream> { let name = &ast.ident; let gen = &ast.generics; let (impl_generics, ty_generics, where_clause) = gen.split_for_impl(); let vis = &ast.vis; let type_properties = ast.get_type_properties()?; let strum_module_path = type_properties.crate_module_path(); if gen.lifetimes().count() > 0 { return Err(syn::Error::new( Span::call_site(), "This macro doesn't support enums with lifetimes. \ The resulting enums would be unbounded.", )); } let phantom_data = if gen.type_params().count() > 0 { let g = gen.type_params().map(|param| &param.ident); quote! { < ( #(#g),* ) > } } else { quote! { < () > } }; let variants = match &ast.data { Data::Enum(v) => &v.variants, _ => return Err(non_enum_error()), }; let mut arms = Vec::new(); let mut idx = 0usize; for variant in variants { if variant.get_variant_properties()?.disabled.is_some() { continue; } let ident = &variant.ident; let params = match &variant.fields { Fields::Unit => quote! {}, Fields::Unnamed(fields) => { let defaults = ::core::iter::repeat(quote!(::core::default::Default::default())) .take(fields.unnamed.len()); quote! { (#(#defaults),*) } } Fields::Named(fields) => { let fields = fields .named .iter() .map(|field| field.ident.as_ref().unwrap()); quote! { {#(#fields: ::core::default::Default::default()),*} } } }; arms.push(quote! {#idx => ::core::option::Option::Some(#name::#ident #params)}); idx += 1; } let variant_count = arms.len(); arms.push(quote! { _ => ::core::option::Option::None }); let iter_name = syn::parse_str::<Ident>(&format!("{}Iter", name)).unwrap(); Ok(quote! { #[doc = "An iterator over the variants of [Self]"] #vis struct #iter_name #ty_generics { idx: usize, back_idx: usize, marker: ::core::marker::PhantomData #phantom_data, } impl #impl_generics #iter_name #ty_generics #where_clause { fn get(&self, idx: usize) -> Option<#name #ty_generics> { match idx { #(#arms),* } } } impl #impl_generics #strum_module_path::IntoEnumIterator for #name #ty_generics #where_clause { type Iterator = #iter_name #ty_generics; fn iter() -> #iter_name #ty_generics { #iter_name { idx: 0, back_idx: 0, marker: ::core::marker::PhantomData, } } } impl #impl_generics Iterator for #iter_name #ty_generics #where_clause { type Item = #name #ty_generics; fn next(&mut self) -> Option<<Self as Iterator>::Item> { self.nth(0) } fn size_hint(&self) -> (usize, Option<usize>) { let t = if self.idx + self.back_idx >= #variant_count { 0 } else { #variant_count - self.idx - self.back_idx }; (t, Some(t)) } fn nth(&mut self, n: usize) -> Option<<Self as Iterator>::Item> { let idx = self.idx + n + 1; if idx + self.back_idx > #variant_count { self.idx = #variant_count; None } else { self.idx = idx; self.get(idx - 1) } } } impl #impl_generics ExactSizeIterator for #iter_name #ty_generics #where_clause { fn len(&self) -> usize { self.size_hint().0 } } impl #impl_generics DoubleEndedIterator for #iter_name #ty_generics #where_clause { fn next_back(&mut self) -> Option<<Self as Iterator>::Item> { let back_idx = self.back_idx + 1; if self.idx + back_idx > #variant_count { self.back_idx = #variant_count; None } else { self.back_idx = back_idx; self.get(#variant_count - self.back_idx) } } } impl #impl_generics Clone for #iter_name #ty_generics #where_clause { fn clone(&self) -> #iter_name #ty_generics { #iter_name { idx: self.idx, back_idx: self.back_idx, marker: self.marker.clone(), } } } }) }
use proc_macro2::{Span, TokenStream}; use quote::quote; use syn::{Data, DeriveInput, Fields, Ident}; use crate::helpers::{non_enum_error, HasStrumVariantProperties, HasTypeProperties};
pub fn enum_iter_inner(ast: &DeriveInput) -> syn::Result<TokenStream> { let name = &ast.ident; let gen = &ast.generics; let (impl_generics, ty_generics, where_clause) = gen.split_for_impl(); let vis = &ast.vis; let type_properties = ast.get_type_properties()?; let strum_module_path = type_properties.crate_module_path(); if gen.lifetimes().count() > 0 { return Err(syn::Error::new( Span::call_site(), "This macro doesn't support enums with lifetimes. \ The resulting enums would be unbounded.", )); } let phantom_data = if gen.type_params().count() > 0 { let g = gen.type_params().map(|param| &param.ident); quote! { < ( #(#g),* ) > } } else { quote! { < () > } }; let variants = match &ast.data { Data::Enum(v) => &v.variants, _ => return Err(non_enum_error()), }; let mut arms = Vec::new(); let mut idx = 0usize; for variant in variants { if variant.get_variant_properties()?.disabled.is_some() { continue; } let ident = &variant.ident; let params = match &variant.fields { Fields::Unit => quote! {}, Fields::Unnamed(fields) => { let defaults = ::core::iter::repeat(quote!(::core::default::Default::default())) .take(fields.unnamed.len()); quote! { (#(#defaults),*) } } Fields::Named(fields) => { let fields = fields .named .iter() .map(|field| field.ident.as_ref().unwrap()); quote! { {#(#fields: ::core::default::Default::default()),*} } } }; arms.push(quote! {#idx => ::core::option::Option::Some(#name::#ident #params)}); idx += 1; } let variant_count = arms.len(); arms.push(quote! { _ => ::core::option::Option::None }); let iter_name = syn::parse_str::<Ident>(&format!("{}Iter", name)).unwrap(); Ok(quote! { #[doc = "An iterator over the variants of [Self]"] #vis struct #iter_name #ty_generics { idx: usize, back_idx: usize, marker: ::core::marker::PhantomData #phantom_data, } impl #impl_generics #iter_name #ty_generics #where_clause { fn get(&self, idx: usize) -> Option<#name #ty_generics> { match idx { #(#arms),* } } } impl #impl_generics #strum_module_path::IntoEnumIterator for #name #ty_generics #where_clause { type Iterator = #iter_name #ty_generics; fn iter() -> #iter_name #ty_generics { #iter_name { idx: 0, back_idx: 0, marker: ::core::marker::PhantomData, } } } impl #impl_generics Iterator for #iter_name #ty_generics #where_clause { type Item = #name #ty_generics; fn next(&mut self) -> Option<<Self as Iterator>::Item> { self.nth(0) } fn size_hint(&self) -> (usize, Option<usize>) { let t = if self.idx + self.back_idx >= #variant_count { 0 } else { #variant_count - self.idx - self.back_idx }; (t, Some(t)) } fn nth(&mut self, n: usize) -> Option<<Self as Iterator>::Item> { let idx = self.idx + n + 1; if idx + self.back_idx > #variant_count { self.idx = #variant_count; None } else { self.idx = idx; self.get(idx - 1) } } } impl #impl_generics ExactSizeIterator for #iter_name #ty_generics #where_clause { fn len(&self) -> usize { self.size_hint().0 } } impl #impl_generics DoubleEndedIterator for #iter_name #ty_generics #where_clause { fn next_back(&mut self) -> Option<<Self as Iterator>::Item> { let back_idx = self.back_idx + 1; if self.idx + back_idx > #variant_count { self.back_idx = #variant_count; None } else { self.back_idx = back_idx; self.get(#variant_count - self.back_idx) } } } impl #impl_generics Clone for #iter_name #ty_generics #where_clause { fn clone(&self) -> #iter_name #ty_generics { #iter_name { idx: self.idx, back_idx: self.back_idx, marker: self.marker.clone(), } } } }) }
function_block-full_function
[ { "content": "struct Prop(Ident, LitStr);\n\n\n\nimpl Parse for Prop {\n\n fn parse(input: ParseStream) -> syn::Result<Self> {\n\n use syn::ext::IdentExt;\n\n\n\n let k = Ident::parse_any(input)?;\n\n let _: Token![=] = input.parse()?;\n\n let v = input.parse()?;\n\n\n\n Ok...
Rust
cargo-spatial/src/download.rs
randomPoison/spatialos-sdk-rs
6a0149a21a7de40fd4ff127820d6f04f87173454
#[cfg(target_os = "linux")] pub use self::linux::*; #[cfg(target_os = "macos")] pub use self::macos::*; #[cfg(target_os = "windows")] pub use self::windows::*; use crate::{config::Config, opt::DownloadSdk}; use log::*; use reqwest::get; use std::fs::File; use std::io::copy; use std::{ fs, path::{Path, PathBuf}, process, }; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] enum SpatialWorkerSdkPackage { CHeaders, CApiWin, CApiMac, CApiLinux, } impl SpatialWorkerSdkPackage { fn package_name(self) -> &'static str { match self { SpatialWorkerSdkPackage::CHeaders => "c_headers", SpatialWorkerSdkPackage::CApiWin => "c-static-x86_64-vc140_mt-win32", SpatialWorkerSdkPackage::CApiMac => "c-static-x86_64-clang-macos", SpatialWorkerSdkPackage::CApiLinux => "c-static-x86_64-gcc510_pic-linux", } } fn relative_target_directory(self) -> &'static str { match self { SpatialWorkerSdkPackage::CHeaders => "headers", SpatialWorkerSdkPackage::CApiWin => "win", SpatialWorkerSdkPackage::CApiMac => "macos", SpatialWorkerSdkPackage::CApiLinux => "linux", } } } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] enum SpatialToolsPackage { SchemaCompilerWin, SchemaCompilerMac, SchemaCompilerLinux, SnapshotConverterWin, SnapshotConverterMac, SnapshotConverterLinux, } impl SpatialToolsPackage { fn package_name(self) -> &'static str { match self { SpatialToolsPackage::SchemaCompilerWin => "schema_compiler-x86_64-win32", SpatialToolsPackage::SchemaCompilerMac => "schema_compiler-x86_64-macos", SpatialToolsPackage::SchemaCompilerLinux => "schema_compiler-x86_64-linux", SpatialToolsPackage::SnapshotConverterWin => "snapshot_converter-x86_64-win32", SpatialToolsPackage::SnapshotConverterMac => "snapshot_converter-x86_64-macos", SpatialToolsPackage::SnapshotConverterLinux => "snapshot_converter-x86_64-linux", } } fn relative_target_directory(self) -> &'static str { match self { SpatialToolsPackage::SchemaCompilerWin | SpatialToolsPackage::SchemaCompilerMac | SpatialToolsPackage::SchemaCompilerLinux => "schema-compiler", SpatialToolsPackage::SnapshotConverterWin | SpatialToolsPackage::SnapshotConverterMac | SpatialToolsPackage::SnapshotConverterLinux => "snapshot-converter", } } } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] enum SpatialSchemaPackage { StandardLibrary, ExhaustiveTestSchema, } impl SpatialSchemaPackage { fn package_name(self) -> &'static str { match self { SpatialSchemaPackage::StandardLibrary => "standard_library", SpatialSchemaPackage::ExhaustiveTestSchema => "test_schema_library", } } fn relative_target_directory(self) -> &'static str { match self { SpatialSchemaPackage::StandardLibrary => "std-lib", SpatialSchemaPackage::ExhaustiveTestSchema => "test-schema", } } } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] enum SpatialPackageSource { WorkerSdk(SpatialWorkerSdkPackage), Tools(SpatialToolsPackage), Schema(SpatialSchemaPackage), } impl SpatialPackageSource { fn package_name(self) -> Vec<&'static str> { match self { SpatialPackageSource::WorkerSdk(package) => vec!["worker_sdk", package.package_name()], SpatialPackageSource::Tools(package) => vec!["tools", package.package_name()], SpatialPackageSource::Schema(package) => vec!["schema", package.package_name()], } } fn relative_target_directory(self) -> &'static str { match self { SpatialPackageSource::WorkerSdk(package) => package.relative_target_directory(), SpatialPackageSource::Tools(package) => package.relative_target_directory(), SpatialPackageSource::Schema(package) => package.relative_target_directory(), } } } static COMMON_PACKAGES: &[SpatialPackageSource] = &[ SpatialPackageSource::WorkerSdk(SpatialWorkerSdkPackage::CHeaders), SpatialPackageSource::WorkerSdk(SpatialWorkerSdkPackage::CApiLinux), SpatialPackageSource::WorkerSdk(SpatialWorkerSdkPackage::CApiWin), SpatialPackageSource::WorkerSdk(SpatialWorkerSdkPackage::CApiMac), SpatialPackageSource::Schema(SpatialSchemaPackage::StandardLibrary), ]; #[cfg(target_os = "linux")] static PLATFORM_PACKAGES: &[SpatialPackageSource] = &[ SpatialPackageSource::Tools(SpatialToolsPackage::SchemaCompilerLinux), SpatialPackageSource::Tools(SpatialToolsPackage::SnapshotConverterLinux), ]; #[cfg(target_os = "windows")] static PLATFORM_PACKAGES: &[SpatialPackageSource] = &[ SpatialPackageSource::Tools(SpatialToolsPackage::SchemaCompilerWin), SpatialPackageSource::Tools(SpatialToolsPackage::SnapshotConverterWin), ]; #[cfg(target_os = "macos")] static PLATFORM_PACKAGES: &[SpatialPackageSource] = &[ SpatialPackageSource::Tools(SpatialToolsPackage::SchemaCompilerMac), SpatialPackageSource::Tools(SpatialToolsPackage::SnapshotConverterMac), ]; pub fn download_sdk( config: Result<Config, Box<dyn std::error::Error>>, options: &DownloadSdk, ) -> Result<(), Box<dyn std::error::Error>> { let spatial_lib_dir = match config { Ok(ref config) => config.spatial_lib_dir().ok_or("spatial_lib_dir value must be set in the config, or the SPATIAL_LIB_DIR environment variable must be set")?, Err(_) => ::std::env::var("SPATIAL_LIB_DIR")? }; let spatial_sdk_version = match options.sdk_version { Some(ref version) => version.clone(), None => config?.spatial_sdk_version, }; info!("Downloading packages into: {}", spatial_lib_dir); if Path::new(&spatial_lib_dir).exists() { fs::remove_dir_all(&spatial_lib_dir)?; } fs::create_dir_all(&spatial_lib_dir)?; trace!("Spatial lib directory cleaned."); for package in COMMON_PACKAGES { download_package(*package, &spatial_sdk_version, &spatial_lib_dir)?; } for package in PLATFORM_PACKAGES { download_package(*package, &spatial_sdk_version, &spatial_lib_dir)?; } if options.with_test_schema { download_package( SpatialPackageSource::Schema(SpatialSchemaPackage::ExhaustiveTestSchema), &spatial_sdk_version, &spatial_lib_dir, )?; } Ok(()) } fn download_package( package_source: SpatialPackageSource, sdk_version: &str, spatial_lib_dir: &str, ) -> Result<(), Box<dyn std::error::Error>> { info!("Downloading {}", package_source.package_name().join(" ")); let mut output_path = PathBuf::new(); output_path.push(spatial_lib_dir); output_path.push(package_source.relative_target_directory()); let mut args = vec!["package", "retrieve"]; args.extend(package_source.package_name()); args.push(sdk_version); args.push(output_path.to_str().unwrap()); args.push("--unzip"); trace!("Running spatial command with arguments: {:?}", args); let process = process::Command::new("spatial").args(args).output()?; if !process.status.success() { let stdout = String::from_utf8(process.stdout)?; let stderr = String::from_utf8(process.stderr)?; trace!("{}", stdout); trace!("{}", stderr); return Err("Failed to download package.".into()); } Ok(()) } fn get_installer( download_url: &str, directory: &Path, ) -> Result<PathBuf, Box<dyn std::error::Error>> { trace!("GET request to {}", download_url); let mut response = get(download_url)?; let (mut dest, path) = { let fname = response .url() .path_segments() .and_then(::std::iter::Iterator::last) .and_then(|name| if name.is_empty() { None } else { Some(name) }) .unwrap_or("tmp.bin"); trace!("Downloading {}", fname); let fname = directory.join(fname); trace!("Creating temporary file at: {:?}", fname); (File::create(fname.clone())?, fname) }; copy(&mut response, &mut dest)?; Ok(path) } #[cfg(target_os = "linux")] mod linux { pub fn download_cli() -> Result<(), Box<dyn std::error::Error>> { Err("Linux installer is unsupported. Follow the instructions here to install the Spatial CLI: https://docs.improbable.io/reference/latest/shared/setup/linux".to_owned().into()) } } #[cfg(target_os = "windows")] mod windows { use log::info; use std::process; use tempfile; const DOWNLOAD_LOCATION: &str = "https://console.improbable.io/installer/download/stable/latest/win"; pub fn download_cli() -> Result<(), Box<dyn std::error::Error>> { let tmp_dir = tempfile::TempDir::new()?; info!("Downloading installer."); let installer_path = super::get_installer(DOWNLOAD_LOCATION, tmp_dir.path())?; info!("Executing installer."); let result = process::Command::new(installer_path).status(); match result { Ok(status) => { if !status.success() { return Err("Installer returned a non-zero exit code.".to_owned().into()); } Ok(()) } Err(e) => { if let Some(code) = e.raw_os_error() { if code == 740 { return Err("Installer requires elevated permissions to run. Please rerun in a terminal with elevated permissions.".to_owned().into()); } } Err(e.into()) } } } } #[cfg(target_os = "macos")] mod macos { use log::info; use std::process; use tempfile; const DOWNLOAD_LOCATION: &str = "https://console.improbable.io/installer/download/stable/latest/mac"; pub fn download_cli() -> Result<(), Box<dyn std::error::Error>> { let tmp_dir = tempfile::TempDir::new()?; info!("Downloading installer."); let installer_path = super::get_installer(DOWNLOAD_LOCATION, tmp_dir.path())?; info!("Executing installer."); let status = process::Command::new("installer") .arg("-pkg") .arg(installer_path) .args(&["-target", "/"]) .status()?; if !status.success() { return Err("Installer returned a non-zero exit code.".to_owned().into()); } Ok(()) } }
#[cfg(target_os = "linux")] pub use self::linux::*; #[cfg(target_os = "macos")] pub use self::macos::*; #[cfg(target_os = "windows")] pub use self::windows::*; use crate::{config::Config, opt::DownloadSdk}; use log::*; use reqwest::get; use std::fs::File; use std::io::copy; use std::{ fs, path::{Path, PathBuf}, process, }; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] enum SpatialWorkerSdkPackage { CHeaders, CApiWin, CApiMac, CApiLinux, } impl SpatialWorkerSdkPackage { fn package_name(self) -> &'static str { match self { SpatialWorkerSdkPackage::CHeaders => "c_headers", SpatialWorkerSdkPackage::CApiWin => "c-static-x86_64-vc140_mt-win32", SpatialWorkerSdkPackage::CApiMac => "c-static-x86_64-clang-macos", SpatialWorkerSdkPackage::CApiLinux => "c-static-x86_64-gcc510_pic-linux", } } fn relative_target_directory(self) -> &'static str { match self { SpatialWorkerSdkPackage::CHeaders => "headers", SpatialWorkerSdkPackage::CApiWin => "win", SpatialWorkerSdkPackage::CApiMac => "macos", SpatialWorkerSdkPackage::CApiLinux => "linux", } } } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] enum SpatialToolsPackage { SchemaCompilerWin, SchemaCompilerMac, SchemaCompilerLinux, SnapshotConverterWin, SnapshotConverterMac, SnapshotConverterLinux, } impl SpatialToolsPackage { fn package_name(self) -> &'static str { match self { SpatialToolsPackage::SchemaCompilerWin => "schema_compiler-x86_64-win32", SpatialToolsPackage::SchemaCompilerMac => "schema_compiler-x86_64-macos", SpatialToolsPackage::SchemaCompilerLinux => "schema_compiler-x86_64-linux", SpatialToolsPackage::SnapshotConverterWin => "snapshot_converter-x86_64-win32", SpatialToolsPackage::SnapshotConverterMac => "snapshot_converter-x86_64-macos", SpatialToolsPackage::SnapshotConverterLinux => "snapshot_converter-x86_64-linux", } } fn relative_target_directory(self) -> &'static str { match self { SpatialToolsPackage::SchemaCompilerWin | SpatialToolsPackage::SchemaCompilerMac | SpatialToolsPackage::SchemaCompilerLinux => "schema-compiler", SpatialToolsPackage::SnapshotConverterWin | SpatialToolsPackage::SnapshotConverterMac | SpatialToolsPackage::SnapshotConverterLinux => "snapshot-converter", } } } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] enum SpatialSchemaPackage { StandardLibrary, ExhaustiveTestSchema, } impl SpatialSchemaPackage { fn package_name(self) -> &'static str { match self { SpatialSchemaPackage::StandardLibrary => "standard_library", SpatialSchemaPackage::ExhaustiveTestSchema => "test_schema_library", } } fn rel
} #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] enum SpatialPackageSource { WorkerSdk(SpatialWorkerSdkPackage), Tools(SpatialToolsPackage), Schema(SpatialSchemaPackage), } impl SpatialPackageSource { fn package_name(self) -> Vec<&'static str> { match self { SpatialPackageSource::WorkerSdk(package) => vec!["worker_sdk", package.package_name()], SpatialPackageSource::Tools(package) => vec!["tools", package.package_name()], SpatialPackageSource::Schema(package) => vec!["schema", package.package_name()], } } fn relative_target_directory(self) -> &'static str { match self { SpatialPackageSource::WorkerSdk(package) => package.relative_target_directory(), SpatialPackageSource::Tools(package) => package.relative_target_directory(), SpatialPackageSource::Schema(package) => package.relative_target_directory(), } } } static COMMON_PACKAGES: &[SpatialPackageSource] = &[ SpatialPackageSource::WorkerSdk(SpatialWorkerSdkPackage::CHeaders), SpatialPackageSource::WorkerSdk(SpatialWorkerSdkPackage::CApiLinux), SpatialPackageSource::WorkerSdk(SpatialWorkerSdkPackage::CApiWin), SpatialPackageSource::WorkerSdk(SpatialWorkerSdkPackage::CApiMac), SpatialPackageSource::Schema(SpatialSchemaPackage::StandardLibrary), ]; #[cfg(target_os = "linux")] static PLATFORM_PACKAGES: &[SpatialPackageSource] = &[ SpatialPackageSource::Tools(SpatialToolsPackage::SchemaCompilerLinux), SpatialPackageSource::Tools(SpatialToolsPackage::SnapshotConverterLinux), ]; #[cfg(target_os = "windows")] static PLATFORM_PACKAGES: &[SpatialPackageSource] = &[ SpatialPackageSource::Tools(SpatialToolsPackage::SchemaCompilerWin), SpatialPackageSource::Tools(SpatialToolsPackage::SnapshotConverterWin), ]; #[cfg(target_os = "macos")] static PLATFORM_PACKAGES: &[SpatialPackageSource] = &[ SpatialPackageSource::Tools(SpatialToolsPackage::SchemaCompilerMac), SpatialPackageSource::Tools(SpatialToolsPackage::SnapshotConverterMac), ]; pub fn download_sdk( config: Result<Config, Box<dyn std::error::Error>>, options: &DownloadSdk, ) -> Result<(), Box<dyn std::error::Error>> { let spatial_lib_dir = match config { Ok(ref config) => config.spatial_lib_dir().ok_or("spatial_lib_dir value must be set in the config, or the SPATIAL_LIB_DIR environment variable must be set")?, Err(_) => ::std::env::var("SPATIAL_LIB_DIR")? }; let spatial_sdk_version = match options.sdk_version { Some(ref version) => version.clone(), None => config?.spatial_sdk_version, }; info!("Downloading packages into: {}", spatial_lib_dir); if Path::new(&spatial_lib_dir).exists() { fs::remove_dir_all(&spatial_lib_dir)?; } fs::create_dir_all(&spatial_lib_dir)?; trace!("Spatial lib directory cleaned."); for package in COMMON_PACKAGES { download_package(*package, &spatial_sdk_version, &spatial_lib_dir)?; } for package in PLATFORM_PACKAGES { download_package(*package, &spatial_sdk_version, &spatial_lib_dir)?; } if options.with_test_schema { download_package( SpatialPackageSource::Schema(SpatialSchemaPackage::ExhaustiveTestSchema), &spatial_sdk_version, &spatial_lib_dir, )?; } Ok(()) } fn download_package( package_source: SpatialPackageSource, sdk_version: &str, spatial_lib_dir: &str, ) -> Result<(), Box<dyn std::error::Error>> { info!("Downloading {}", package_source.package_name().join(" ")); let mut output_path = PathBuf::new(); output_path.push(spatial_lib_dir); output_path.push(package_source.relative_target_directory()); let mut args = vec!["package", "retrieve"]; args.extend(package_source.package_name()); args.push(sdk_version); args.push(output_path.to_str().unwrap()); args.push("--unzip"); trace!("Running spatial command with arguments: {:?}", args); let process = process::Command::new("spatial").args(args).output()?; if !process.status.success() { let stdout = String::from_utf8(process.stdout)?; let stderr = String::from_utf8(process.stderr)?; trace!("{}", stdout); trace!("{}", stderr); return Err("Failed to download package.".into()); } Ok(()) } fn get_installer( download_url: &str, directory: &Path, ) -> Result<PathBuf, Box<dyn std::error::Error>> { trace!("GET request to {}", download_url); let mut response = get(download_url)?; let (mut dest, path) = { let fname = response .url() .path_segments() .and_then(::std::iter::Iterator::last) .and_then(|name| if name.is_empty() { None } else { Some(name) }) .unwrap_or("tmp.bin"); trace!("Downloading {}", fname); let fname = directory.join(fname); trace!("Creating temporary file at: {:?}", fname); (File::create(fname.clone())?, fname) }; copy(&mut response, &mut dest)?; Ok(path) } #[cfg(target_os = "linux")] mod linux { pub fn download_cli() -> Result<(), Box<dyn std::error::Error>> { Err("Linux installer is unsupported. Follow the instructions here to install the Spatial CLI: https://docs.improbable.io/reference/latest/shared/setup/linux".to_owned().into()) } } #[cfg(target_os = "windows")] mod windows { use log::info; use std::process; use tempfile; const DOWNLOAD_LOCATION: &str = "https://console.improbable.io/installer/download/stable/latest/win"; pub fn download_cli() -> Result<(), Box<dyn std::error::Error>> { let tmp_dir = tempfile::TempDir::new()?; info!("Downloading installer."); let installer_path = super::get_installer(DOWNLOAD_LOCATION, tmp_dir.path())?; info!("Executing installer."); let result = process::Command::new(installer_path).status(); match result { Ok(status) => { if !status.success() { return Err("Installer returned a non-zero exit code.".to_owned().into()); } Ok(()) } Err(e) => { if let Some(code) = e.raw_os_error() { if code == 740 { return Err("Installer requires elevated permissions to run. Please rerun in a terminal with elevated permissions.".to_owned().into()); } } Err(e.into()) } } } } #[cfg(target_os = "macos")] mod macos { use log::info; use std::process; use tempfile; const DOWNLOAD_LOCATION: &str = "https://console.improbable.io/installer/download/stable/latest/mac"; pub fn download_cli() -> Result<(), Box<dyn std::error::Error>> { let tmp_dir = tempfile::TempDir::new()?; info!("Downloading installer."); let installer_path = super::get_installer(DOWNLOAD_LOCATION, tmp_dir.path())?; info!("Executing installer."); let status = process::Command::new("installer") .arg("-pkg") .arg(installer_path) .args(&["-target", "/"]) .status()?; if !status.success() { return Err("Installer returned a non-zero exit code.".to_owned().into()); } Ok(()) } }
ative_target_directory(self) -> &'static str { match self { SpatialSchemaPackage::StandardLibrary => "std-lib", SpatialSchemaPackage::ExhaustiveTestSchema => "test-schema", } }
function_block-function_prefixed
[ { "content": "/// Formats an key-value pair into an argument string.\n\npub fn format_arg<S: AsRef<OsStr>>(prefix: &str, value: S) -> OsString {\n\n let mut arg = OsString::from(format!(\"--{}=\", prefix));\n\n arg.push(value.as_ref());\n\n arg\n\n}\n", "file_path": "cargo-spatial/src/lib.rs", ...
Rust
rg3d-ui/src/check_box.rs
vigdail/rg3d
b65bfdab350f8c1d48bcc288a8449cc74653ef51
use crate::grid::{Column, GridBuilder, Row}; use crate::message::MessageDirection; use crate::vector_image::{Primitive, VectorImageBuilder}; use crate::{ border::BorderBuilder, brush::Brush, core::{color::Color, pool::Handle}, message::{CheckBoxMessage, UiMessage, UiMessageData, WidgetMessage}, widget::{Widget, WidgetBuilder}, BuildContext, Control, HorizontalAlignment, NodeHandleMapping, Thickness, UiNode, UserInterface, VerticalAlignment, BRUSH_BRIGHT, BRUSH_DARK, BRUSH_LIGHT, BRUSH_TEXT, }; use rg3d_core::algebra::Vector2; use std::any::Any; use std::ops::{Deref, DerefMut}; #[derive(Clone)] pub struct CheckBox { pub widget: Widget, pub checked: Option<bool>, pub check_mark: Handle<UiNode>, pub uncheck_mark: Handle<UiNode>, pub undefined_mark: Handle<UiNode>, } crate::define_widget_deref!(CheckBox); impl Control for CheckBox { fn as_any(&self) -> &dyn Any { self } fn as_any_mut(&mut self) -> &mut dyn Any { self } fn clone_boxed(&self) -> Box<dyn Control> { Box::new(self.clone()) } fn resolve(&mut self, node_map: &NodeHandleMapping) { node_map.resolve(&mut self.check_mark); node_map.resolve(&mut self.uncheck_mark); node_map.resolve(&mut self.undefined_mark); } fn handle_routed_message(&mut self, ui: &mut UserInterface, message: &mut UiMessage) { self.widget.handle_routed_message(ui, message); match message.data() { UiMessageData::Widget(ref msg) => { match msg { WidgetMessage::MouseDown { .. } => { if message.destination() == self.handle() || self.widget.has_descendant(message.destination(), ui) { ui.capture_mouse(self.handle()); } } WidgetMessage::MouseUp { .. } => { if message.destination() == self.handle() || self.widget.has_descendant(message.destination(), ui) { ui.release_mouse_capture(); if let Some(value) = self.checked { ui.send_message(CheckBoxMessage::checked( self.handle(), MessageDirection::ToWidget, Some(!value), )); } else { ui.send_message(CheckBoxMessage::checked( self.handle(), MessageDirection::ToWidget, Some(true), )); } } } _ => (), } } &UiMessageData::CheckBox(CheckBoxMessage::Check(value)) if message.direction() == MessageDirection::ToWidget && message.destination() == self.handle() => { if self.checked != value { self.checked = value; ui.send_message(message.reverse()); if self.check_mark.is_some() { match value { None => { ui.send_message(WidgetMessage::visibility( self.check_mark, MessageDirection::ToWidget, false, )); ui.send_message(WidgetMessage::visibility( self.uncheck_mark, MessageDirection::ToWidget, false, )); ui.send_message(WidgetMessage::visibility( self.undefined_mark, MessageDirection::ToWidget, true, )); } Some(value) => { ui.send_message(WidgetMessage::visibility( self.check_mark, MessageDirection::ToWidget, value, )); ui.send_message(WidgetMessage::visibility( self.uncheck_mark, MessageDirection::ToWidget, !value, )); ui.send_message(WidgetMessage::visibility( self.undefined_mark, MessageDirection::ToWidget, false, )); } } } } } _ => {} } } fn remove_ref(&mut self, handle: Handle<UiNode>) { if self.check_mark == handle { self.check_mark = Handle::NONE; } if self.uncheck_mark == handle { self.uncheck_mark = Handle::NONE; } if self.undefined_mark == handle { self.undefined_mark = Handle::NONE; } } } pub struct CheckBoxBuilder { widget_builder: WidgetBuilder, checked: Option<bool>, check_mark: Option<Handle<UiNode>>, uncheck_mark: Option<Handle<UiNode>>, undefined_mark: Option<Handle<UiNode>>, content: Handle<UiNode>, } impl CheckBoxBuilder { pub fn new(widget_builder: WidgetBuilder) -> Self { Self { widget_builder, checked: Some(false), check_mark: None, uncheck_mark: None, undefined_mark: None, content: Handle::NONE, } } pub fn checked(mut self, value: Option<bool>) -> Self { self.checked = value; self } pub fn with_check_mark(mut self, check_mark: Handle<UiNode>) -> Self { self.check_mark = Some(check_mark); self } pub fn with_uncheck_mark(mut self, uncheck_mark: Handle<UiNode>) -> Self { self.uncheck_mark = Some(uncheck_mark); self } pub fn with_undefined_mark(mut self, undefined_mark: Handle<UiNode>) -> Self { self.undefined_mark = Some(undefined_mark); self } pub fn with_content(mut self, content: Handle<UiNode>) -> Self { self.content = content; self } pub fn build(self, ctx: &mut BuildContext) -> Handle<UiNode> { let check_mark = self.check_mark.unwrap_or_else(|| { VectorImageBuilder::new( WidgetBuilder::new() .with_vertical_alignment(VerticalAlignment::Center) .with_horizontal_alignment(HorizontalAlignment::Center) .with_foreground(BRUSH_TEXT), ) .with_primitives(vec![ Primitive::Line { begin: Vector2::new(0.0, 6.0), end: Vector2::new(6.0, 12.0), thickness: 2.0, }, Primitive::Line { begin: Vector2::new(6.0, 12.0), end: Vector2::new(12.0, 0.0), thickness: 2.0, }, ]) .build(ctx) }); ctx[check_mark].set_visibility(self.checked.unwrap_or(false)); let uncheck_mark = self.uncheck_mark.unwrap_or_else(|| { BorderBuilder::new( WidgetBuilder::new() .with_background(Brush::Solid(Color::TRANSPARENT)) .with_foreground(Brush::Solid(Color::TRANSPARENT)), ) .build(ctx) }); ctx[uncheck_mark].set_visibility(!self.checked.unwrap_or(true)); let undefined_mark = self.undefined_mark.unwrap_or_else(|| { BorderBuilder::new( WidgetBuilder::new() .with_margin(Thickness::uniform(1.0)) .with_background(BRUSH_BRIGHT) .with_foreground(Brush::Solid(Color::TRANSPARENT)), ) .build(ctx) }); ctx[undefined_mark].set_visibility(self.checked.is_none()); if self.content.is_some() { ctx[self.content].set_row(0).set_column(1); } let grid = GridBuilder::new( WidgetBuilder::new() .with_child( BorderBuilder::new( WidgetBuilder::new() .with_child(check_mark) .with_child(uncheck_mark) .with_child(undefined_mark) .with_background(BRUSH_DARK) .with_foreground(BRUSH_LIGHT), ) .with_stroke_thickness(Thickness::uniform(1.0)) .build(ctx), ) .with_child(self.content), ) .add_row(Row::stretch()) .add_column(Column::strict(20.0)) .add_column(Column::stretch()) .build(ctx); let cb = CheckBox { widget: self.widget_builder.with_child(grid).build(), checked: self.checked, check_mark, uncheck_mark, undefined_mark, }; ctx.add_node(UiNode::new(cb)) } } #[cfg(test)] mod test { use crate::{ check_box::CheckBoxBuilder, core::algebra::Vector2, message::{CheckBoxMessage, MessageDirection}, widget::WidgetBuilder, UserInterface, }; #[test] fn check_box() { let mut ui = UserInterface::new(Vector2::new(1000.0, 1000.0)); assert_eq!(ui.poll_message(), None); let check_box = CheckBoxBuilder::new(WidgetBuilder::new()).build(&mut ui.build_ctx()); assert_eq!(ui.poll_message(), None); let input_message = CheckBoxMessage::checked(check_box, MessageDirection::ToWidget, Some(true)); ui.send_message(input_message.clone()); assert_eq!(ui.poll_message(), Some(input_message.clone())); assert_eq!(ui.poll_message(), Some(input_message.reverse())); } }
use crate::grid::{Column, GridBuilder, Row}; use crate::message::MessageDirection; use crate::vector_image::{Primitive, VectorImageBuilder}; use crate::{ border::BorderBuilder, brush::Brush, core::{color::Color, pool::Handle}, message::{CheckBoxMessage, UiMessage, UiMessageData, WidgetMessage}, widget::{Widget, WidgetBuilder}, BuildContext, Control, HorizontalAlignment, NodeHandleMapping, Thickness, UiNode, UserInterface, VerticalAlignment, BRUSH_BRIGHT, BRUSH_DARK, BRUSH_LIGHT, BRUSH_TEXT, }; use rg3d_core::algebra::Vector2; use std::any::Any; use std::ops::{Deref, DerefMut}; #[derive(Clone)] pub struct CheckBox { pub widget: Widget, pub checked: Option<bool>, pub check_mark: Handle<UiNode>, pub uncheck_mark: Handle<UiNode>, pub undefined_mark: Handle<UiNode>, } crate::define_widget_deref!(CheckBox); impl Control for CheckBox { fn as_any(&self) -> &dyn Any { self } fn as_any_mut(&mut self) -> &mut dyn Any { self } fn clone_boxed(&self) -> Box<dyn Control> { Box::new(self.clone()) } fn resolve(&mut self, node_map: &NodeHandleMapping) { node_map.resolve(&mut self.check_mark); node_map.resolve(&mut self.uncheck_mark); node_map.resolve(&mut self.undefined_mark); } fn handle_routed_message(&mut self, ui: &mut UserInterface, message: &mut UiMessage) { self.widget.handle_routed_message(ui, message); match message.data() { UiMessageData::Widget(ref msg) => { match msg { WidgetMessage::MouseDown { .. } => { if message.destination() == self.handle() || self.widget.has_descendant(message.destination(), ui) { ui.capture_mouse(self.handle()); } } WidgetMessage::MouseUp { .. } => { if message.destination() == self.handle() || self.widget.has_descendant(message.destination(), ui) { ui.release_mouse_capture(); if let Some(value) = self.checked { ui.send_message(CheckBoxMessage::checked( self.handle(), MessageDirection::ToWidget, Some(!value), )); } else { ui.send_message(CheckBoxMessage::checked( self.handle(), MessageDirection::ToWidget, Some(true), )); } } } _ => (), } } &UiMessageData::CheckBox(CheckBoxMessage::Check(value)) if message.direction() == MessageDirection::ToWidget && message.destination() == self.handle() => { if self.checked != value { self.checked = value; ui.send_message(message.reverse()); if self.check_mark.is_some() { match value { None => { ui.send_message(WidgetMessage::visibility( self.check_mark, MessageDirection::ToWidget, false, )); ui.send_message(WidgetMessage::visibility( self.uncheck_mark, MessageDirection::ToWidget, false, )); ui.send_message(WidgetMessage::visibility( self.undefined_mark, MessageDirection::ToWidget, true, )); } Some(value) => { ui.send_message(WidgetMessage::visibility( self.check_mark, MessageDirection::ToWidget, value, )); ui.send_message(WidgetMessage::visibility( self.uncheck_mark, MessageDirection::ToWidget, !value, )); ui.send_message(WidgetMessage::visibility( self.undefined_mark, MessageDirection::ToWidget, false, )); } } } } } _ => {} } } fn remove_ref(&mut self, handle: Handle<UiNode>) { if self.check_mark == handle { self.check_mark = Handle::NONE; } if self.uncheck_mark == handle { self.uncheck_mark = Handle::NONE; } if self.undefined_mark == handle { self.undefined_mark = Handle::NONE; } } } pub struct CheckBoxBuilder { widget_builder: WidgetBuilder, checked: Option<bool>, check_mark: Option<Handle<UiNode>>, uncheck_mark: Option<Handle<UiNode>>, undefined_mark: Option<Handle<UiNode>>, content: Handle<UiNode>, } impl CheckBoxBuilder { pub fn new(widget_builder: WidgetBuilder) -> Self { Self { widget_builder, checked: Some(false), check_mark: None, uncheck_mark: None, undefined_mark: None, content: Handle::NONE, } } pub fn checked(mut self, value: Option<bool>) -> Self { self.checked = value; self } pub fn with_check_mark(mut self, check_mark: Handle<UiNode>) -> Self { self.check_mark = Some(check_mark); self } pub fn with_uncheck_mark(mut self, uncheck_mark: Handle<UiNode>) -> Self { self.uncheck_mark = Some(uncheck_mark); self } pub fn with_undefined_mark(mut self, undefined_mark: Handle<UiNode>) -> Self { self.undefined_mark = Some(undefined_mark); self } pub fn with_content(mut self, content: Handle<UiNode>) -> Self { self.content = content; self }
} #[cfg(test)] mod test { use crate::{ check_box::CheckBoxBuilder, core::algebra::Vector2, message::{CheckBoxMessage, MessageDirection}, widget::WidgetBuilder, UserInterface, }; #[test] fn check_box() { let mut ui = UserInterface::new(Vector2::new(1000.0, 1000.0)); assert_eq!(ui.poll_message(), None); let check_box = CheckBoxBuilder::new(WidgetBuilder::new()).build(&mut ui.build_ctx()); assert_eq!(ui.poll_message(), None); let input_message = CheckBoxMessage::checked(check_box, MessageDirection::ToWidget, Some(true)); ui.send_message(input_message.clone()); assert_eq!(ui.poll_message(), Some(input_message.clone())); assert_eq!(ui.poll_message(), Some(input_message.reverse())); } }
pub fn build(self, ctx: &mut BuildContext) -> Handle<UiNode> { let check_mark = self.check_mark.unwrap_or_else(|| { VectorImageBuilder::new( WidgetBuilder::new() .with_vertical_alignment(VerticalAlignment::Center) .with_horizontal_alignment(HorizontalAlignment::Center) .with_foreground(BRUSH_TEXT), ) .with_primitives(vec![ Primitive::Line { begin: Vector2::new(0.0, 6.0), end: Vector2::new(6.0, 12.0), thickness: 2.0, }, Primitive::Line { begin: Vector2::new(6.0, 12.0), end: Vector2::new(12.0, 0.0), thickness: 2.0, }, ]) .build(ctx) }); ctx[check_mark].set_visibility(self.checked.unwrap_or(false)); let uncheck_mark = self.uncheck_mark.unwrap_or_else(|| { BorderBuilder::new( WidgetBuilder::new() .with_background(Brush::Solid(Color::TRANSPARENT)) .with_foreground(Brush::Solid(Color::TRANSPARENT)), ) .build(ctx) }); ctx[uncheck_mark].set_visibility(!self.checked.unwrap_or(true)); let undefined_mark = self.undefined_mark.unwrap_or_else(|| { BorderBuilder::new( WidgetBuilder::new() .with_margin(Thickness::uniform(1.0)) .with_background(BRUSH_BRIGHT) .with_foreground(Brush::Solid(Color::TRANSPARENT)), ) .build(ctx) }); ctx[undefined_mark].set_visibility(self.checked.is_none()); if self.content.is_some() { ctx[self.content].set_row(0).set_column(1); } let grid = GridBuilder::new( WidgetBuilder::new() .with_child( BorderBuilder::new( WidgetBuilder::new() .with_child(check_mark) .with_child(uncheck_mark) .with_child(undefined_mark) .with_background(BRUSH_DARK) .with_foreground(BRUSH_LIGHT), ) .with_stroke_thickness(Thickness::uniform(1.0)) .build(ctx), ) .with_child(self.content), ) .add_row(Row::stretch()) .add_column(Column::strict(20.0)) .add_column(Column::stretch()) .build(ctx); let cb = CheckBox { widget: self.widget_builder.with_child(grid).build(), checked: self.checked, check_mark, uncheck_mark, undefined_mark, }; ctx.add_node(UiNode::new(cb)) }
function_block-full_function
[ { "content": "pub fn make_default_anchor(ctx: &mut BuildContext, row: usize, column: usize) -> Handle<UiNode> {\n\n let default_anchor_size = 30.0;\n\n BorderBuilder::new(\n\n WidgetBuilder::new()\n\n .with_width(default_anchor_size)\n\n .with_height(default_anchor_size)\n\n ...
Rust
src/resource/model.rs
Jytesh/rg3d
5cc1017f9a9b3e5d461fbb6247675bf0df4d6d00
#![warn(missing_docs)] use crate::{ animation::Animation, core::{ pool::Handle, visitor::{Visit, VisitError, VisitResult, Visitor}, }, engine::resource_manager::ResourceManager, resource::{ fbx::{self, error::FbxError}, Resource, ResourceData, }, scene::{node::Node, Scene}, utils::log::{Log, MessageKind}, }; use std::{ borrow::Cow, path::{Path, PathBuf}, }; #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] #[repr(u32)] pub(in crate) enum NodeMapping { UseNames = 0, UseHandles = 1, } #[derive(Debug)] pub struct ModelData { pub(in crate) path: PathBuf, pub(in crate) mapping: NodeMapping, scene: Scene, } pub type Model = Resource<ModelData, ModelLoadError>; impl Model { pub fn instantiate_geometry(&self, dest_scene: &mut Scene) -> Handle<Node> { let data = self.data_ref(); let (root, old_to_new) = data.scene.graph.copy_node( data.scene.graph.get_root(), &mut dest_scene.graph, &mut |_, _| true, ); dest_scene.graph[root].is_resource_instance_root = true; let mut stack = vec![root]; while let Some(node_handle) = stack.pop() { let node = &mut dest_scene.graph[node_handle]; node.resource = Some(self.clone()); stack.extend_from_slice(node.children()); } for navmesh in data.scene.navmeshes.iter() { dest_scene.navmeshes.add(navmesh.clone()); } std::mem::drop(data); dest_scene.physics.embed_resource( &mut dest_scene.physics_binder, &dest_scene.graph, old_to_new, self.clone(), ); root } pub fn instantiate(&self, dest_scene: &mut Scene) -> ModelInstance { let root = self.instantiate_geometry(dest_scene); ModelInstance { root, animations: self.retarget_animations(root, dest_scene), } } pub fn retarget_animations( &self, root: Handle<Node>, dest_scene: &mut Scene, ) -> Vec<Handle<Animation>> { let data = self.data_ref(); let mut animation_handles = Vec::new(); for ref_anim in data.scene.animations.iter() { let mut anim_copy = ref_anim.clone(); anim_copy.resource = Some(self.clone()); for (i, ref_track) in ref_anim.get_tracks().iter().enumerate() { let ref_node = &data.scene.graph[ref_track.get_node()]; let instance_node = dest_scene.graph.find_by_name(root, ref_node.name()); if instance_node.is_none() { Log::writeln( MessageKind::Error, format!( "Failed to retarget animation {:?} for node {}", data.path(), ref_node.name() ), ); } anim_copy.get_tracks_mut()[i].set_node(instance_node); } animation_handles.push(dest_scene.animations.add(anim_copy)); } animation_handles } } impl ResourceData for ModelData { fn path(&self) -> Cow<Path> { Cow::Borrowed(&self.path) } } impl Default for ModelData { fn default() -> Self { Self { path: PathBuf::new(), mapping: NodeMapping::UseNames, scene: Scene::new(), } } } impl Visit for ModelData { fn visit(&mut self, name: &str, visitor: &mut Visitor) -> VisitResult { visitor.enter_region(name)?; self.path.visit("Path", visitor)?; visitor.leave_region() } } pub struct ModelInstance { pub root: Handle<Node>, pub animations: Vec<Handle<Animation>>, } #[derive(Debug)] pub enum ModelLoadError { Visit(VisitError), NotSupported(String), Fbx(FbxError), } impl From<FbxError> for ModelLoadError { fn from(fbx: FbxError) -> Self { ModelLoadError::Fbx(fbx) } } impl From<VisitError> for ModelLoadError { fn from(e: VisitError) -> Self { ModelLoadError::Visit(e) } } impl ModelData { pub(in crate) async fn load<P: AsRef<Path>>( path: P, resource_manager: ResourceManager, ) -> Result<Self, ModelLoadError> { let extension = path .as_ref() .extension() .unwrap_or_default() .to_string_lossy() .as_ref() .to_lowercase(); let (scene, mapping) = match extension.as_ref() { "fbx" => { let mut scene = Scene::new(); if let Some(filename) = path.as_ref().file_name() { let root = scene.graph.get_root(); scene.graph[root].set_name(filename.to_string_lossy().to_string()); } fbx::load_to_scene(&mut scene, resource_manager, path.as_ref())?; (scene, NodeMapping::UseNames) } "rgs" => ( Scene::from_file(path.as_ref(), resource_manager).await?, NodeMapping::UseHandles, ), _ => { return Err(ModelLoadError::NotSupported(format!( "Unsupported model resource format: {}", extension ))) } }; Ok(Self { path: path.as_ref().to_owned(), scene, mapping, }) } pub fn get_scene(&self) -> &Scene { &self.scene } pub fn find_node_by_name(&self, name: &str) -> Handle<Node> { self.scene.graph.find_by_name_from_root(name) } }
#![warn(missing_docs)] use crate::{ animation::Animation, core::{ pool::Handle, visitor::{Visit, VisitError, VisitResult, Visitor}, }, engine::resource_manager::ResourceManager, resource::{ fbx::{self, error::FbxError}, Resource, ResourceData, }, scene::{node::Node, Scene}, utils::log::{Log, MessageKind}, }; use std::{ borrow::Cow, path::{Path, PathBuf}, }; #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] #[repr(u32)] pub(in crate) enum NodeMapping { UseNames = 0, UseHandles = 1, } #[derive(Debug)] pub struct ModelData { pub(in crate) path: PathBuf, pub(in crate) mapping: NodeMapping, scene: Scene, } pub type Model = Resource<ModelData, ModelLoadError>; impl Model { pub fn instantiate_geometry(&self, dest_scene: &mut Scene) -> Handle<Node> { let d
xtension = path .as_ref() .extension() .unwrap_or_default() .to_string_lossy() .as_ref() .to_lowercase(); let (scene, mapping) = match extension.as_ref() { "fbx" => { let mut scene = Scene::new(); if let Some(filename) = path.as_ref().file_name() { let root = scene.graph.get_root(); scene.graph[root].set_name(filename.to_string_lossy().to_string()); } fbx::load_to_scene(&mut scene, resource_manager, path.as_ref())?; (scene, NodeMapping::UseNames) } "rgs" => ( Scene::from_file(path.as_ref(), resource_manager).await?, NodeMapping::UseHandles, ), _ => { return Err(ModelLoadError::NotSupported(format!( "Unsupported model resource format: {}", extension ))) } }; Ok(Self { path: path.as_ref().to_owned(), scene, mapping, }) } pub fn get_scene(&self) -> &Scene { &self.scene } pub fn find_node_by_name(&self, name: &str) -> Handle<Node> { self.scene.graph.find_by_name_from_root(name) } }
ata = self.data_ref(); let (root, old_to_new) = data.scene.graph.copy_node( data.scene.graph.get_root(), &mut dest_scene.graph, &mut |_, _| true, ); dest_scene.graph[root].is_resource_instance_root = true; let mut stack = vec![root]; while let Some(node_handle) = stack.pop() { let node = &mut dest_scene.graph[node_handle]; node.resource = Some(self.clone()); stack.extend_from_slice(node.children()); } for navmesh in data.scene.navmeshes.iter() { dest_scene.navmeshes.add(navmesh.clone()); } std::mem::drop(data); dest_scene.physics.embed_resource( &mut dest_scene.physics_binder, &dest_scene.graph, old_to_new, self.clone(), ); root } pub fn instantiate(&self, dest_scene: &mut Scene) -> ModelInstance { let root = self.instantiate_geometry(dest_scene); ModelInstance { root, animations: self.retarget_animations(root, dest_scene), } } pub fn retarget_animations( &self, root: Handle<Node>, dest_scene: &mut Scene, ) -> Vec<Handle<Animation>> { let data = self.data_ref(); let mut animation_handles = Vec::new(); for ref_anim in data.scene.animations.iter() { let mut anim_copy = ref_anim.clone(); anim_copy.resource = Some(self.clone()); for (i, ref_track) in ref_anim.get_tracks().iter().enumerate() { let ref_node = &data.scene.graph[ref_track.get_node()]; let instance_node = dest_scene.graph.find_by_name(root, ref_node.name()); if instance_node.is_none() { Log::writeln( MessageKind::Error, format!( "Failed to retarget animation {:?} for node {}", data.path(), ref_node.name() ), ); } anim_copy.get_tracks_mut()[i].set_node(instance_node); } animation_handles.push(dest_scene.animations.add(anim_copy)); } animation_handles } } impl ResourceData for ModelData { fn path(&self) -> Cow<Path> { Cow::Borrowed(&self.path) } } impl Default for ModelData { fn default() -> Self { Self { path: PathBuf::new(), mapping: NodeMapping::UseNames, scene: Scene::new(), } } } impl Visit for ModelData { fn visit(&mut self, name: &str, visitor: &mut Visitor) -> VisitResult { visitor.enter_region(name)?; self.path.visit("Path", visitor)?; visitor.leave_region() } } pub struct ModelInstance { pub root: Handle<Node>, pub animations: Vec<Handle<Animation>>, } #[derive(Debug)] pub enum ModelLoadError { Visit(VisitError), NotSupported(String), Fbx(FbxError), } impl From<FbxError> for ModelLoadError { fn from(fbx: FbxError) -> Self { ModelLoadError::Fbx(fbx) } } impl From<VisitError> for ModelLoadError { fn from(e: VisitError) -> Self { ModelLoadError::Visit(e) } } impl ModelData { pub(in crate) async fn load<P: AsRef<Path>>( path: P, resource_manager: ResourceManager, ) -> Result<Self, ModelLoadError> { let e
random
[ { "content": "/// Tries to load and convert FBX from given path.\n\n///\n\n/// Normally you should never use this method, use resource manager to load models.\n\npub fn load_to_scene<P: AsRef<Path>>(\n\n scene: &mut Scene,\n\n resource_manager: ResourceManager,\n\n path: P,\n\n) -> Result<(), FbxError>...
Rust
packages/sycamore-macro/src/component/mod.rs
alsuren/sycamore
df16d18ad29933316aa666185e7e2dd7002eb662
use proc_macro2::TokenStream; use quote::{quote, ToTokens}; use syn::parse::{Parse, ParseStream}; use syn::{ Attribute, Block, FnArg, GenericParam, Generics, Ident, Item, ItemFn, Result, ReturnType, Type, Visibility, }; pub struct ComponentFunctionName { pub component_name: Ident, pub generics: Generics, } impl Parse for ComponentFunctionName { fn parse(input: ParseStream) -> Result<Self> { if input.is_empty() { Err(input.error("expected an identifier for the component")) } else { let component_name: Ident = input.parse()?; let generics: Generics = input.parse()?; if let Some(lifetime) = generics.lifetimes().next() { return Err(syn::Error::new_spanned( lifetime, "unexpected lifetime param; put lifetime params on function instead", )); } if let Some(const_param) = generics.const_params().next() { return Err(syn::Error::new_spanned( const_param, "unexpected const generic param; put const generic params on function instead", )); } if generics.type_params().count() != 1 { return Err(syn::Error::new_spanned( generics, "expected a single type param", )); } if !generics .type_params() .next() .unwrap() .bounds .empty_or_trailing() { return Err(syn::Error::new_spanned( generics, "unexpected type bound in generic type", )); } Ok(Self { component_name, generics, }) } } } pub struct ComponentFunction { pub block: Box<Block>, pub props_type: Box<Type>, pub arg: FnArg, pub generics: Generics, pub vis: Visibility, pub attrs: Vec<Attribute>, pub name: Ident, pub return_type: Box<Type>, } impl Parse for ComponentFunction { fn parse(input: ParseStream) -> Result<Self> { let parsed: Item = input.parse()?; match parsed { Item::Fn(func) => { let ItemFn { attrs, vis, sig, block, } = func; if sig.asyncness.is_some() { return Err(syn::Error::new_spanned( sig.asyncness, "async functions can't be components", )); } if sig.constness.is_some() { return Err(syn::Error::new_spanned( sig.constness, "const functions can't be components", )); } if sig.abi.is_some() { return Err(syn::Error::new_spanned( sig.abi, "extern functions can't be components", )); } let return_type = match sig.output { ReturnType::Default => { return Err(syn::Error::new_spanned( sig, "function must return `sycamore::view::View`", )) } ReturnType::Type(_, ty) => ty, }; let mut inputs = sig.inputs.into_iter(); let arg: FnArg = inputs.next().unwrap_or_else(|| syn::parse_quote! { _: () }); let props_type = match &arg { FnArg::Typed(arg) => arg.ty.clone(), FnArg::Receiver(arg) => { return Err(syn::Error::new_spanned( arg, "function components can't accept a receiver", )) } }; if inputs.len() > 0 { let params: TokenStream = inputs.map(|it| it.to_token_stream()).collect(); return Err(syn::Error::new_spanned( params, "function should accept at most one parameter for the prop", )); } Ok(Self { block, props_type, arg, generics: sig.generics, vis, attrs, name: sig.ident, return_type, }) } item => Err(syn::Error::new_spanned( item, "`component` attribute can only be applied to functions", )), } } } pub fn component_impl( attr: ComponentFunctionName, component: ComponentFunction, ) -> Result<TokenStream> { let ComponentFunctionName { component_name, generics: generic_node_ty, } = attr; let component_name_str = component_name.to_string(); let generic_node_ty = generic_node_ty.type_params().next().unwrap(); let generic_node: GenericParam = syn::parse_quote! { #generic_node_ty: ::sycamore::generic_node::Html }; let ComponentFunction { block, props_type: _, arg, mut generics, vis, attrs, name, return_type, } = component; let prop_ty = match &arg { FnArg::Receiver(_) => unreachable!(), FnArg::Typed(pat_ty) => &pat_ty.ty, }; let first_generic_param_index = generics .params .iter() .enumerate() .find(|(_, param)| matches!(param, GenericParam::Type(_) | GenericParam::Const(_))) .map(|(i, _)| i); if let Some(first_generic_param_index) = first_generic_param_index { generics .params .insert(first_generic_param_index, generic_node); } else { generics.params.push(generic_node); } let (impl_generics, ty_generics, where_clause) = generics.split_for_impl(); let phantom_generics = ty_generics .clone() .into_token_stream() .into_iter() .collect::<Vec<_>>(); let phantom_generics_len = phantom_generics.len(); let phantom_generics = phantom_generics .into_iter() .take(phantom_generics_len.saturating_sub(1)) .skip(1) .collect::<TokenStream>(); if name == component_name { return Err(syn::Error::new_spanned( component_name, "the component must not have the same name as the function", )); } let quoted = quote! { #(#attrs)* #vis struct #component_name#generics { #[doc(hidden)] _marker: ::std::marker::PhantomData<(#phantom_generics)>, } impl#impl_generics ::sycamore::component::Component::<#generic_node_ty> for #component_name#ty_generics #where_clause { #[cfg(debug_assertions)] const NAME: &'static ::std::primitive::str = #component_name_str; type Props = #prop_ty; fn __create_component(#arg) -> #return_type{ #block } } }; Ok(quoted) }
use proc_macro2::TokenStream; use quote::{quote, ToTokens}; use syn::parse::{Parse, ParseStream}; use syn::{ Attribute, Block, FnArg, GenericParam, Generics, Ident, Item, ItemFn, Result, ReturnType, Type, Visibility, }; pub struct ComponentFunctionName { pub component_name: Ident, pub generics: Generics, } impl Parse for ComponentFunctionName { fn parse(input: ParseStream) -> Result<Self> { if input.is_empty() { Err(input.error("expected an identifier for the component")) } else { let component_name: Ident = input.parse()?; let generics: Generics = input.parse()?; if let Some(lifetime) = generics.lifetimes().next() { return Err(syn::Error::new_spanned( lifetime, "unexpected lifetime param; put lifetime params on function instead", )); } if let Some(const_param) = generics.const_params().next() { return Err(syn::Error::new_spanned( const_param, "unexpected const generic param; put const generic params on function instead", )); } if generics.type_params().count() != 1 { return Err(syn::Error::new_spanned( generics, "expected a single type param", )); } if !generics .type_params() .next() .unwrap() .bounds .empty_or_trailing() { return Err(syn::Error::new_spanned( generics, "unexpected type bound in generic type", )); } Ok(Self { component_name, generics, }) } } } pub struct ComponentFunction { pub block: Box<Block>, pub props_type: Box<Type>, pub arg: FnArg, pub generics: Generics, pub vis: Visibility, pub attrs: Vec<Attribute>, pub name: Ident, pub return_type: Box<Type>, } impl Parse for ComponentFunction { fn parse(input: ParseStream) -> Result<Self> { let parsed: Item = input.parse()?; match parsed { Item::Fn(func) => { let ItemFn { attrs, vis, sig, block, } = func; if sig.asyncness.is_some() { return Err(syn::Error::new_spanned( sig.asyncness, "async functions can't be components", )); } if sig.constness.is_some() { return Err(syn::Error::new_spanned( sig.constness, "const functions can't be components", )); } if sig.abi.is_some() { return Err(syn::Error::new_spanned( sig.abi, "extern functions can't be components", )); } let return_type = match sig.output { ReturnType::Default => { return Err(syn::Error::new_spanned( sig, "function must return `sycamore::view::View`", )) } ReturnType::Type(_, ty) => ty, }; let mut inputs = sig.inputs.into_iter(); let arg: FnArg = inputs.next().unwrap_or_else(|| syn::parse_quote! { _: () }); let props_type = match &arg { FnArg::Typed(arg) => arg.ty.clone(), FnArg::Receiver(arg) => { return Err(syn::Error::new_spanned( arg, "function components can't accept a receiver", )) } }; if inputs.len() > 0 { let params: TokenStream = inputs.map(|it| it.to_token_stream()).collect(); return Err(syn::Error::new_spanned( params, "function should accept at most one parameter for the prop", )); } Ok(Self { block, props_type, arg, generics: sig.generics, vis, attrs, name: sig.ident, return_type, }) } item => Err(syn::Error::new_spanned( item, "`component` attribute can only be applied to functions", )), } } }
pub fn component_impl( attr: ComponentFunctionName, component: ComponentFunction, ) -> Result<TokenStream> { let ComponentFunctionName { component_name, generics: generic_node_ty, } = attr; let component_name_str = component_name.to_string(); let generic_node_ty = generic_node_ty.type_params().next().unwrap(); let generic_node: GenericParam = syn::parse_quote! { #generic_node_ty: ::sycamore::generic_node::Html }; let ComponentFunction { block, props_type: _, arg, mut generics, vis, attrs, name, return_type, } = component; let prop_ty = match &arg { FnArg::Receiver(_) => unreachable!(), FnArg::Typed(pat_ty) => &pat_ty.ty, }; let first_generic_param_index = generics .params .iter() .enumerate() .find(|(_, param)| matches!(param, GenericParam::Type(_) | GenericParam::Const(_))) .map(|(i, _)| i); if let Some(first_generic_param_index) = first_generic_param_index { generics .params .insert(first_generic_param_index, generic_node); } else { generics.params.push(generic_node); } let (impl_generics, ty_generics, where_clause) = generics.split_for_impl(); let phantom_generics = ty_generics .clone() .into_token_stream() .into_iter() .collect::<Vec<_>>(); let phantom_generics_len = phantom_generics.len(); let phantom_generics = phantom_generics .into_iter() .take(phantom_generics_len.saturating_sub(1)) .skip(1) .collect::<TokenStream>(); if name == component_name { return Err(syn::Error::new_spanned( component_name, "the component must not have the same name as the function", )); } let quoted = quote! { #(#attrs)* #vis struct #component_name#generics { #[doc(hidden)] _marker: ::std::marker::PhantomData<(#phantom_generics)>, } impl#impl_generics ::sycamore::component::Component::<#generic_node_ty> for #component_name#ty_generics #where_clause { #[cfg(debug_assertions)] const NAME: &'static ::std::primitive::str = #component_name_str; type Props = #prop_ty; fn __create_component(#arg) -> #return_type{ #block } } }; Ok(quoted) }
function_block-full_function
[ { "content": "pub fn route_impl(input: DeriveInput) -> syn::Result<TokenStream> {\n\n let mut quoted = TokenStream::new();\n\n let mut err_quoted = TokenStream::new();\n\n let mut has_error_handler = false;\n\n\n\n match &input.data {\n\n syn::Data::Enum(de) => {\n\n let ty_name = ...
Rust
starky/src/constraint_consumer.rs
mfaulk/plonky2
2cedd1b02a718d19115560647ba1f741eab83260
use std::marker::PhantomData; use plonky2::field::extension_field::Extendable; use plonky2::field::packed_field::PackedField; use plonky2::hash::hash_types::RichField; use plonky2::iop::ext_target::ExtensionTarget; use plonky2::iop::target::Target; use plonky2::plonk::circuit_builder::CircuitBuilder; pub struct ConstraintConsumer<P: PackedField> { alphas: Vec<P::Scalar>, pub constraint_accs: Vec<P>, z_last: P, lagrange_basis_first: P, lagrange_basis_last: P, } impl<P: PackedField> ConstraintConsumer<P> { pub fn new( alphas: Vec<P::Scalar>, z_last: P, lagrange_basis_first: P, lagrange_basis_last: P, ) -> Self { Self { constraint_accs: vec![P::ZEROS; alphas.len()], alphas, z_last, lagrange_basis_first, lagrange_basis_last, } } pub fn accumulators(self) -> Vec<P::Scalar> { self.constraint_accs .into_iter() .map(|acc| acc.as_slice()[0]) .collect() } pub fn constraint_transition(&mut self, constraint: P) { self.constraint(constraint * self.z_last); } pub fn constraint(&mut self, constraint: P) { for (&alpha, acc) in self.alphas.iter().zip(&mut self.constraint_accs) { *acc *= alpha; *acc += constraint; } } pub fn constraint_first_row(&mut self, constraint: P) { self.constraint(constraint * self.lagrange_basis_first); } pub fn constraint_last_row(&mut self, constraint: P) { self.constraint(constraint * self.lagrange_basis_last); } } pub struct RecursiveConstraintConsumer<F: RichField + Extendable<D>, const D: usize> { alphas: Vec<Target>, constraint_accs: Vec<ExtensionTarget<D>>, z_last: ExtensionTarget<D>, lagrange_basis_first: ExtensionTarget<D>, lagrange_basis_last: ExtensionTarget<D>, _phantom: PhantomData<F>, } impl<F: RichField + Extendable<D>, const D: usize> RecursiveConstraintConsumer<F, D> { pub fn new( zero: ExtensionTarget<D>, alphas: Vec<Target>, z_last: ExtensionTarget<D>, lagrange_basis_first: ExtensionTarget<D>, lagrange_basis_last: ExtensionTarget<D>, ) -> Self { Self { constraint_accs: vec![zero; alphas.len()], alphas, z_last, lagrange_basis_first, lagrange_basis_last, _phantom: Default::default(), } } pub fn accumulators(self) -> Vec<ExtensionTarget<D>> { self.constraint_accs } pub fn constraint_transition( &mut self, builder: &mut CircuitBuilder<F, D>, constraint: ExtensionTarget<D>, ) { let filtered_constraint = builder.mul_extension(constraint, self.z_last); self.constraint(builder, filtered_constraint); } pub fn constraint( &mut self, builder: &mut CircuitBuilder<F, D>, constraint: ExtensionTarget<D>, ) { for (&alpha, acc) in self.alphas.iter().zip(&mut self.constraint_accs) { *acc = builder.scalar_mul_add_extension(alpha, *acc, constraint); } } pub fn constraint_first_row( &mut self, builder: &mut CircuitBuilder<F, D>, constraint: ExtensionTarget<D>, ) { let filtered_constraint = builder.mul_extension(constraint, self.lagrange_basis_first); self.constraint(builder, filtered_constraint); } pub fn constraint_last_row( &mut self, builder: &mut CircuitBuilder<F, D>, constraint: ExtensionTarget<D>, ) { let filtered_constraint = builder.mul_extension(constraint, self.lagrange_basis_last); self.constraint(builder, filtered_constraint); } }
use std::marker::PhantomData; use plonky2::field::extension_field::Extendable; use plonky2::field::packed_field::PackedField; use plonky2::hash::hash_types::RichField; use plonky2::iop::ext_target::ExtensionTarget; use plonky2::iop::target::Target; use plonky2::plonk::circuit_builder::CircuitBuilder; pub struct ConstraintConsumer<P: PackedField> { alphas: Vec<P::Scalar>, pub constraint_accs: Vec<P>, z_last: P, lagrange_basis_first: P, lagrange_basis_last: P, } impl<P: PackedField> ConstraintConsumer<P> { pub fn new( alphas: Vec<P::Scalar>, z_last: P, lagrange_basis_first: P, lagrange_basis_last: P, ) -> Self { Self { constraint_accs: vec![P::ZEROS; alphas.len()], alphas, z_last, lagrange_basis_first, lagrange_basis_last, } } pub fn accumulators(self) -> Vec<P::Scalar> { self.constraint_accs .into_iter() .map(|acc| acc.as_slice()[0]) .collect() } pub fn constraint_transition(&mut self, constraint: P) { self.constraint(constraint * self.z_last); } pub fn c
pub fn constraint_first_row(&mut self, constraint: P) { self.constraint(constraint * self.lagrange_basis_first); } pub fn constraint_last_row(&mut self, constraint: P) { self.constraint(constraint * self.lagrange_basis_last); } } pub struct RecursiveConstraintConsumer<F: RichField + Extendable<D>, const D: usize> { alphas: Vec<Target>, constraint_accs: Vec<ExtensionTarget<D>>, z_last: ExtensionTarget<D>, lagrange_basis_first: ExtensionTarget<D>, lagrange_basis_last: ExtensionTarget<D>, _phantom: PhantomData<F>, } impl<F: RichField + Extendable<D>, const D: usize> RecursiveConstraintConsumer<F, D> { pub fn new( zero: ExtensionTarget<D>, alphas: Vec<Target>, z_last: ExtensionTarget<D>, lagrange_basis_first: ExtensionTarget<D>, lagrange_basis_last: ExtensionTarget<D>, ) -> Self { Self { constraint_accs: vec![zero; alphas.len()], alphas, z_last, lagrange_basis_first, lagrange_basis_last, _phantom: Default::default(), } } pub fn accumulators(self) -> Vec<ExtensionTarget<D>> { self.constraint_accs } pub fn constraint_transition( &mut self, builder: &mut CircuitBuilder<F, D>, constraint: ExtensionTarget<D>, ) { let filtered_constraint = builder.mul_extension(constraint, self.z_last); self.constraint(builder, filtered_constraint); } pub fn constraint( &mut self, builder: &mut CircuitBuilder<F, D>, constraint: ExtensionTarget<D>, ) { for (&alpha, acc) in self.alphas.iter().zip(&mut self.constraint_accs) { *acc = builder.scalar_mul_add_extension(alpha, *acc, constraint); } } pub fn constraint_first_row( &mut self, builder: &mut CircuitBuilder<F, D>, constraint: ExtensionTarget<D>, ) { let filtered_constraint = builder.mul_extension(constraint, self.lagrange_basis_first); self.constraint(builder, filtered_constraint); } pub fn constraint_last_row( &mut self, builder: &mut CircuitBuilder<F, D>, constraint: ExtensionTarget<D>, ) { let filtered_constraint = builder.mul_extension(constraint, self.lagrange_basis_last); self.constraint(builder, filtered_constraint); } }
onstraint(&mut self, constraint: P) { for (&alpha, acc) in self.alphas.iter().zip(&mut self.constraint_accs) { *acc *= alpha; *acc += constraint; } }
function_block-function_prefixed
[]
Rust
starchart/src/action/result.rs
starlite-project/starchart
c0f8cd6774596d45bf9a603aa3a37aa5dcde5d3a
use std::{ fmt::{Debug, Display, Formatter, Result as FmtResult}, hint::unreachable_unchecked, iter::FromIterator, }; use crate::Entry; #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] #[must_use = "an ActionResult should be asserted"] pub enum ActionResult<R> { Create, SingleRead(Option<R>), MultiRead(Vec<R>), Update, Delete(bool), } impl<R> ActionResult<R> { pub const fn is_create(&self) -> bool { matches!(self, Self::Create) } pub const fn is_single_read(&self) -> bool { matches!(self, Self::SingleRead(_)) } pub const fn is_multi_read(&self) -> bool { matches!(self, Self::MultiRead(_)) } pub const fn is_read(&self) -> bool { self.is_single_read() || self.is_multi_read() } pub const fn is_update(&self) -> bool { matches!(self, Self::Update) } pub const fn is_delete(&self) -> bool { matches!(self, Self::Delete(_)) } } impl<R: Entry> ActionResult<R> { #[track_caller] #[inline] pub fn unwrap_create(self) { assert!( self.is_create(), "called `ActionResult::create` on a `{}` value", self ); } #[inline] #[track_caller] pub unsafe fn unwrap_create_unchecked(self) { debug_assert!(self.is_create()); if let Self::Create = self { } else { unreachable_unchecked() } } #[track_caller] #[inline] pub fn unwrap_single_read(self) -> Option<R> { if let Self::SingleRead(v) = self { v } else { panic!("called `ActionResult::single_read` on a `{}` value", self); } } #[track_caller] #[inline] pub unsafe fn unwrap_single_read_unchecked(self) -> Option<R> { debug_assert!(self.is_single_read()); if let Self::SingleRead(v) = self { v } else { unreachable_unchecked() } } #[track_caller] #[inline] pub fn unwrap_multi_read<I: FromIterator<R>>(self) -> I { if let Self::MultiRead(v) = self { v.into_iter().collect() } else { panic!("called `ActionResult::multi_read` on a `{}` value", self) } } pub unsafe fn unwrap_multi_read_unchecked<I: FromIterator<R>>(self) -> I { debug_assert!(self.is_multi_read()); if let Self::MultiRead(v) = self { v.into_iter().collect() } else { unreachable_unchecked() } } #[track_caller] #[inline] pub fn unwrap_update(self) { assert!( self.is_update(), "called `ActionResult::update` on a `{}` value", self ); } pub unsafe fn unwrap_update_unchecked(self) { debug_assert!(self.is_update()); if let Self::Update = self { } else { unreachable_unchecked() } } #[track_caller] #[inline] pub fn unwrap_delete(self) -> bool { if let Self::Delete(b) = self { b } else { panic!("called `ActionResult::delete` on a `{}` value", self) } } pub unsafe fn unwrap_delete_unchecked(self) -> bool { debug_assert!(self.is_delete()); if let Self::Delete(b) = self { b } else { unreachable_unchecked() } } } impl<R> Display for ActionResult<R> { fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult { match self { Self::Create => f.write_str("Create"), Self::SingleRead(_) | Self::MultiRead(_) => f.write_str("Read"), Self::Update => f.write_str("Update"), Self::Delete(_) => f.write_str("Delete"), } } }
use std::{ fmt::{Debug, Display, Formatter, Result as FmtResult}, hint::unreachable_unchecked, iter::FromIterator, }; use crate::Entry; #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] #[must_use = "an ActionResult should be asserted"] pub enum ActionResult<R> { Create, SingleRead(Option<R>), MultiRead(Vec<R>), Update, Delete(bool), } impl<R> ActionResult<R> { pub const fn is_create(&self) -> bool { matches!(self, Self::Create) } pub const fn is_single_read(&self) -> bool { matches!(self, Self::SingleRead(_)) } pub const fn is_multi_read(&self) -> bool { matches!(self, Self::MultiRead(_)) } pub const fn is_read(&self) -> bool { self.is_single_read() || self.is_multi_read() } pub const fn is_update(&self) -> bool { matches!(self, Self::Update) } pub const fn is_delete(&self) -> bool { matches!(self, Self::Delete(_)) } } impl<R: Entry> ActionResult<R> { #[track_caller] #[inline] pub fn unwrap_create(self) { assert!( self.is_create(), "called `ActionResult::create` on a `{}` value", self ); } #[inline] #[track_caller] pub unsafe fn unwrap_create_unchecked(self) { debug_assert!(self.is_create()); if let Self::Create = self { } else { unreachable_unchecked() } } #[track_caller] #[inline] pub fn unwrap_single_read(self) -> Option<R> { if let Self::SingleRead(v) = self { v } else { panic!("called `ActionResult::single_read` on a `{}` value", self); } } #[track_caller] #[inline]
#[track_caller] #[inline] pub fn unwrap_multi_read<I: FromIterator<R>>(self) -> I { if let Self::MultiRead(v) = self { v.into_iter().collect() } else { panic!("called `ActionResult::multi_read` on a `{}` value", self) } } pub unsafe fn unwrap_multi_read_unchecked<I: FromIterator<R>>(self) -> I { debug_assert!(self.is_multi_read()); if let Self::MultiRead(v) = self { v.into_iter().collect() } else { unreachable_unchecked() } } #[track_caller] #[inline] pub fn unwrap_update(self) { assert!( self.is_update(), "called `ActionResult::update` on a `{}` value", self ); } pub unsafe fn unwrap_update_unchecked(self) { debug_assert!(self.is_update()); if let Self::Update = self { } else { unreachable_unchecked() } } #[track_caller] #[inline] pub fn unwrap_delete(self) -> bool { if let Self::Delete(b) = self { b } else { panic!("called `ActionResult::delete` on a `{}` value", self) } } pub unsafe fn unwrap_delete_unchecked(self) -> bool { debug_assert!(self.is_delete()); if let Self::Delete(b) = self { b } else { unreachable_unchecked() } } } impl<R> Display for ActionResult<R> { fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult { match self { Self::Create => f.write_str("Create"), Self::SingleRead(_) | Self::MultiRead(_) => f.write_str("Read"), Self::Update => f.write_str("Update"), Self::Delete(_) => f.write_str("Delete"), } } }
pub unsafe fn unwrap_single_read_unchecked(self) -> Option<R> { debug_assert!(self.is_single_read()); if let Self::SingleRead(v) = self { v } else { unreachable_unchecked() } }
function_block-full_function
[ { "content": "#[cfg(not(feature = \"metadata\"))]\n\npub fn is_metadata(_: &str) -> bool {\n\n\tfalse\n\n}\n\n\n\npub unsafe trait InnerUnwrap<T> {\n\n\tunsafe fn inner_unwrap(self) -> T;\n\n}\n\n\n\n#[cfg(not(has_unwrap_unchecked))]\n\nunsafe impl<T> InnerUnwrap<T> for Option<T> {\n\n\t#[inline]\n\n\t#[track_c...
Rust
src/connectivity/bluetooth/profiles/bt-hfp-audio-gateway/src/peer/procedure/nrec.rs
fabio-d/fuchsia-stardock
e57f5d1cf015fe2294fc2a5aea704842294318d2
use super::{Procedure, ProcedureError, ProcedureMarker, ProcedureRequest}; use crate::peer::{service_level_connection::SlcState, slc_request::SlcRequest, update::AgUpdate}; use at_commands as at; #[derive(Debug, PartialEq, Clone, Copy)] enum State { Start, SetRequest, Terminated, } impl State { fn transition(&mut self) { match *self { Self::Start => *self = Self::SetRequest, Self::SetRequest => *self = Self::Terminated, Self::Terminated => *self = Self::Terminated, } } } #[derive(Debug)] pub struct NrecProcedure { state: State, } impl NrecProcedure { pub fn new() -> Self { Self { state: State::Start } } } impl Procedure for NrecProcedure { fn marker(&self) -> ProcedureMarker { ProcedureMarker::Nrec } fn hf_update(&mut self, update: at::Command, _state: &mut SlcState) -> ProcedureRequest { match (self.state, update) { (State::Start, at::Command::Nrec { nrec: enable }) => { self.state.transition(); let response = Box::new(Into::into); SlcRequest::SetNrec { enable, response }.into() } (_, update) => ProcedureRequest::Error(ProcedureError::UnexpectedHf(update)), } } fn ag_update(&mut self, update: AgUpdate, _state: &mut SlcState) -> ProcedureRequest { match (self.state, update) { (State::SetRequest, update @ AgUpdate::Ok) | (State::SetRequest, update @ AgUpdate::Error) => { self.state.transition(); update.into() } (_, update) => ProcedureRequest::Error(ProcedureError::UnexpectedAg(update)), } } fn is_terminated(&self) -> bool { self.state == State::Terminated } } #[cfg(test)] mod tests { use super::*; use assert_matches::assert_matches; #[test] fn state_transitions() { let mut state = State::Start; state.transition(); assert_eq!(state, State::SetRequest); state.transition(); assert_eq!(state, State::Terminated); state.transition(); assert_eq!(state, State::Terminated); } #[test] fn correct_marker() { let marker = NrecProcedure::new().marker(); assert_eq!(marker, ProcedureMarker::Nrec); } #[test] fn is_terminated_in_terminated_state() { let mut proc = NrecProcedure::new(); assert!(!proc.is_terminated()); proc.state = State::SetRequest; assert!(!proc.is_terminated()); proc.state = State::Terminated; assert!(proc.is_terminated()); } #[test] fn unexpected_hf_update_returns_error() { let mut proc = NrecProcedure::new(); let mut state = SlcState::default(); let random_hf = at::Command::CindRead {}; assert_matches!( proc.hf_update(random_hf, &mut state), ProcedureRequest::Error(ProcedureError::UnexpectedHf(_)) ); } #[test] fn unexpected_ag_update_returns_error() { let mut proc = NrecProcedure::new(); let mut state = SlcState::default(); let random_ag = AgUpdate::ThreeWaySupport; assert_matches!( proc.ag_update(random_ag, &mut state), ProcedureRequest::Error(ProcedureError::UnexpectedAg(_)) ); } #[test] fn updates_produce_expected_requests() { let mut proc = NrecProcedure::new(); let mut state = SlcState::default(); let req = proc.hf_update(at::Command::Nrec { nrec: true }, &mut state); let update = match req { ProcedureRequest::Request(SlcRequest::SetNrec { enable: true, response }) => { response(Ok(())) } x => panic!("Unexpected message: {:?}", x), }; let req = proc.ag_update(update, &mut state); assert_matches!( req, ProcedureRequest::SendMessages(resp) if resp == vec![at::Response::Ok] ); assert!(proc.is_terminated()); assert_matches!( proc.hf_update(at::Command::Nrec { nrec: true }, &mut state), ProcedureRequest::Error(ProcedureError::UnexpectedHf(_)) ); assert_matches!( proc.ag_update(AgUpdate::Ok, &mut state), ProcedureRequest::Error(ProcedureError::UnexpectedAg(_)) ); } }
use super::{Procedure, ProcedureError, ProcedureMarker, ProcedureRequest}; use crate::peer::{service_level_connection::SlcState, slc_request::SlcRequest, update::AgUpdate}; use at_commands as at; #[derive(Debug, PartialEq, Clone, Copy)] enum State { Start, SetRequest, Terminated, } impl State { fn transition(&mut self) { match *self { Self::Start => *self = Self::SetRequest, Self::SetRequest => *self = Self::Terminated, Self::Terminated => *self = Self::Terminated, } } } #[derive(Debug)] pub struct NrecProcedure { state: State, } impl NrecProcedure { pub fn new() -> Self { Self { state: State::Start } } } impl Procedure for NrecProcedure { fn marker(&self) -> ProcedureMarker { ProcedureMarker::Nrec } fn hf_update(&mut self, update: at::Command, _state: &mut SlcState) -> ProcedureRequest { match (self.state, update) { (State::Start, at::Command::Nrec { nrec: enable }) => { self.state.transition(); let response = Box::new(Into::into); SlcRequest::SetNrec { enable, response }.into() } (_, update) => ProcedureRequest::Error(ProcedureError::UnexpectedHf(update)), } } fn ag_update(&mut self, update: AgUpdate, _state: &mut SlcState) -> ProcedureRequest { match (self.state, update) { (State::SetRequest, update @ AgUpdate::Ok) | (State::SetRequest, update @ AgUpdate::Error) => { self.state.transition(); update.into() } (_, update) => ProcedureRequest::Error(ProcedureError::UnexpectedAg(update)), } } fn is_terminated(&self) -> bool { self.state == State::Terminated } } #[cfg(test)] mod tests { use super::*; use assert_matches::assert_matches; #[test] fn state_transitions() { let mut state = State::Start; state.transition(); assert_eq!(state, State::SetRequest); state.transition(); assert_eq!(state, State::Terminated); state.transition(); assert_eq!(state, State::Terminated); } #[test] fn correct_marker() { let marker = NrecProcedure::new().marker(); assert_eq!(marker, ProcedureMarker::Nrec); } #[test] fn is_terminated_in_terminated_state() { let mut proc = NrecProcedure::new(); assert!(!proc.is_terminated()); proc.state = State::SetRequest; assert!(!proc.is_terminated()); proc.state = State::Terminated; assert!(proc.is_terminated()); } #[test] fn unexpected_hf_update_returns_error() { let mut proc = NrecProcedure::new(); let mut state = SlcState::default(); let random_hf = at::Command::CindRead {}; assert_matches!( proc.hf_update(random_hf, &mut state)
eRequest::Error(ProcedureError::UnexpectedAg(_)) ); } #[test] fn updates_produce_expected_requests() { let mut proc = NrecProcedure::new(); let mut state = SlcState::default(); let req = proc.hf_update(at::Command::Nrec { nrec: true }, &mut state); let update = match req { ProcedureRequest::Request(SlcRequest::SetNrec { enable: true, response }) => { response(Ok(())) } x => panic!("Unexpected message: {:?}", x), }; let req = proc.ag_update(update, &mut state); assert_matches!( req, ProcedureRequest::SendMessages(resp) if resp == vec![at::Response::Ok] ); assert!(proc.is_terminated()); assert_matches!( proc.hf_update(at::Command::Nrec { nrec: true }, &mut state), ProcedureRequest::Error(ProcedureError::UnexpectedHf(_)) ); assert_matches!( proc.ag_update(AgUpdate::Ok, &mut state), ProcedureRequest::Error(ProcedureError::UnexpectedAg(_)) ); } }
, ProcedureRequest::Error(ProcedureError::UnexpectedHf(_)) ); } #[test] fn unexpected_ag_update_returns_error() { let mut proc = NrecProcedure::new(); let mut state = SlcState::default(); let random_ag = AgUpdate::ThreeWaySupport; assert_matches!( proc.ag_update(random_ag, &mut state), Procedur
random
[]
Rust
src/sstable/writer.rs
ikatson/rust-sstb
8f2996d4e330dd1e98a16154e5bb38c6f7b81576
use std::convert::TryFrom; use std::fs::File; use std::io::BufWriter; use std::io::{Seek, SeekFrom, Write}; use std::path::Path; use bincode; use bloomfilter::Bloom; use super::compress_ctx_writer::*; use super::compression; use super::ondisk_format::*; use super::options::*; use super::poswriter::PosWriter; use super::result::Result; use super::types::*; pub trait RawSSTableWriter { fn set(&mut self, key: &[u8], value: &[u8]) -> Result<()>; fn close(self) -> Result<()>; } pub struct SSTableWriterV2 { file: PosWriter<Box<dyn CompressionContextWriter<PosWriter<BufWriter<File>>>>>, meta: MetaV3_0, meta_start: u64, data_start: u64, flush_every: usize, sparse_index: Vec<(Vec<u8>, u64)>, bloom: Bloom<[u8]>, } impl SSTableWriterV2 { pub fn new<P: AsRef<Path>>(path: P) -> Result<Self> { Self::new_with_options(path, &WriteOptions::default()) } pub fn new_with_options<P: AsRef<Path>>(path: P, options: &WriteOptions) -> Result<Self> { let file = File::create(path)?; let mut writer = PosWriter::new(BufWriter::new(file), 0); writer.write_all(MAGIC)?; bincode::serialize_into(&mut writer, &VERSION_30)?; let meta_start = writer.current_offset() as u64; let mut meta = MetaV3_0::default(); meta.compression = options.compression; bincode::serialize_into(&mut writer, &meta)?; let data_start = writer.current_offset() as u64; let file: Box<dyn CompressionContextWriter<PosWriter<BufWriter<File>>>> = match options.compression { Compression::None => Box::new(UncompressedWriter::new(writer)), Compression::Zlib => Box::new(CompressionContextWriterImpl::new( writer, compression::ZlibCompressorFactory::new(None), )), Compression::Snappy => Box::new(CompressionContextWriterImpl::new( writer, compression::SnappyCompressorFactory::new(), )), }; Ok(Self { file: PosWriter::new(file, data_start), meta, meta_start, data_start, flush_every: options.flush_every, sparse_index: Vec::new(), bloom: Bloom::new( options.bloom.bitmap_size as usize, options.bloom.items_count, ), }) } pub fn finish(self) -> Result<()> { match self { SSTableWriterV2 { file, mut meta, meta_start, data_start, sparse_index, bloom, .. } => { let mut writer = file.into_inner(); let index_start = self.data_start + writer.reset_compression_context()? as u64; for (key, offset) in sparse_index.into_iter() { KVOffset::new(key.len(), offset)?.serialize_into(&mut writer)?; writer.write_all(&key)?; } let bloom_start = self.data_start + writer.reset_compression_context()? as u64; writer.write_all(&bloom.bitmap())?; let end = self.data_start + writer.reset_compression_context()? as u64; meta.finished = true; meta.index_len = bloom_start - index_start; meta.data_len = index_start - data_start; meta.bloom_len = end - bloom_start; meta.bloom.bitmap_bytes = u32::try_from(bloom.number_of_bits() / 8)?; meta.bloom.k_num = bloom.number_of_hash_functions(); meta.bloom.sip_keys = bloom.sip_keys(); let mut writer = writer.into_inner()?.into_inner(); writer.seek(SeekFrom::Start(meta_start as u64))?; bincode::serialize_into(&mut writer, &meta)?; Ok(()) } } } } impl RawSSTableWriter for SSTableWriterV2 { #[allow(clippy::collapsible_if)] fn set(&mut self, key: &[u8], value: &[u8]) -> Result<()> { let approx_msg_len = key.len() + 5 + value.len(); if self.meta.items == 0 { self.sparse_index.push((key.to_owned(), self.data_start)); } else { if self.file.current_offset() + approx_msg_len as u64 >= self.flush_every as u64 { let total_offset = self.data_start + self.file.get_mut().reset_compression_context()? as u64; self.file.reset_offset(0); self.sparse_index .push((key.to_owned(), total_offset as u64)); } } self.bloom.set(key); KVLength::new(key.len(), value.len())?.serialize_into(&mut self.file)?; self.file.write_all(key)?; self.file.write_all(value)?; self.meta.items += 1; Ok(()) } fn close(self) -> Result<()> { self.finish() } }
use std::convert::TryFrom; use std::fs::File; use std::io::BufWriter; use std::io::{Seek, SeekFrom, Write}; use std::path::Path; use bincode; use bloomfilter::Bloom; use super::compress_ctx_writer::*; use super::compression; use super::ondisk_format::*; use super::options::*; use super::poswriter::PosWriter; use super::result::Result; use super::types::*; pub trait RawSSTableWriter { fn set(&mut self, key: &[u8], value: &[u8]) -> Result<()>; fn close(self) -> Result<()>; } pub struct SSTableWriterV2 { file: PosWriter<Box<dyn CompressionContextWriter<PosWriter<BufWriter<File>>>>>, meta: MetaV3_0, meta_start: u64, data_start: u64, flush_every: usize, sparse_index: Vec<(Vec<u8>, u64)>, bloom: Bloom<[u8]>, } impl SSTableWriterV2 { pub fn new<P: AsRef<Path>>(path: P) -> Result<Self> { Self::new_with_options(path, &WriteOptions::default()) } pub fn new_with_options<P: AsRef<Path>>(path: P, options: &WriteOptions) -> Result<Self> { let file = File::create(path)?; let mut writer = PosWriter::new(BufWriter::new(file), 0); writer.write_all(MAGIC)?; bincode::serialize_into(&mut writer, &VERSION_30)?; let meta_start = writer.current_offset() as u64; let mut meta = MetaV3_0::default(); meta.compression = options.compression; bincode::serialize_into(&mut writer, &meta)?; let data_start = writer.current_offset() as u64; let file: Box<dyn CompressionContextWriter<PosWriter<BufWriter<File>>>> = match options.compression { Compression::None => Box::new(UncompressedWriter::new(writer)), Compression::Zlib => Box::new(CompressionContextWriterImpl::new( writer, compression::ZlibCompressorFactory::new(None), )), Compression::Snappy => Box::new(CompressionContextWriterImpl::new( writer, compression::SnappyCompressorFactory::new(), )), }; Ok(Self { file: PosWriter::new(file, data_start), meta, meta_start, data_start, flush_every: options.flush_every, sparse_index: Vec::new(), bloom: Bloom::new( options.bloom.bitmap_size as usize, options.bloom.items_count, ), }) }
} impl RawSSTableWriter for SSTableWriterV2 { #[allow(clippy::collapsible_if)] fn set(&mut self, key: &[u8], value: &[u8]) -> Result<()> { let approx_msg_len = key.len() + 5 + value.len(); if self.meta.items == 0 { self.sparse_index.push((key.to_owned(), self.data_start)); } else { if self.file.current_offset() + approx_msg_len as u64 >= self.flush_every as u64 { let total_offset = self.data_start + self.file.get_mut().reset_compression_context()? as u64; self.file.reset_offset(0); self.sparse_index .push((key.to_owned(), total_offset as u64)); } } self.bloom.set(key); KVLength::new(key.len(), value.len())?.serialize_into(&mut self.file)?; self.file.write_all(key)?; self.file.write_all(value)?; self.meta.items += 1; Ok(()) } fn close(self) -> Result<()> { self.finish() } }
pub fn finish(self) -> Result<()> { match self { SSTableWriterV2 { file, mut meta, meta_start, data_start, sparse_index, bloom, .. } => { let mut writer = file.into_inner(); let index_start = self.data_start + writer.reset_compression_context()? as u64; for (key, offset) in sparse_index.into_iter() { KVOffset::new(key.len(), offset)?.serialize_into(&mut writer)?; writer.write_all(&key)?; } let bloom_start = self.data_start + writer.reset_compression_context()? as u64; writer.write_all(&bloom.bitmap())?; let end = self.data_start + writer.reset_compression_context()? as u64; meta.finished = true; meta.index_len = bloom_start - index_start; meta.data_len = index_start - data_start; meta.bloom_len = end - bloom_start; meta.bloom.bitmap_bytes = u32::try_from(bloom.number_of_bits() / 8)?; meta.bloom.k_num = bloom.number_of_hash_functions(); meta.bloom.sip_keys = bloom.sip_keys(); let mut writer = writer.into_inner()?.into_inner(); writer.seek(SeekFrom::Start(meta_start as u64))?; bincode::serialize_into(&mut writer, &meta)?; Ok(()) } } }
function_block-full_function
[ { "content": "/// Find the key in the chunk by scanning sequentially.\n\n///\n\n/// This assumes the chunk was fetched from disk and has V1 ondisk format.\n\n///\n\n/// Returns the start and end index of the value.\n\n///\n\n/// TODO: this probably belongs in \"ondisk\" for version V1.\n\npub fn find_value_offs...
Rust
fifteen_min/src/isochrone.rs
balbok0/abstreet
3af15fefdb2772c83864c08724318418da8190a9
use std::collections::{HashMap, HashSet}; use abstutil::MultiMap; use geom::{Duration, Polygon}; use map_gui::tools::Grid; use map_model::{ connectivity, AmenityType, BuildingID, BuildingType, LaneType, Map, Path, PathConstraints, PathRequest, }; use widgetry::{Color, Drawable, EventCtx, GeomBatch}; use crate::App; pub struct Isochrone { pub start: BuildingID, pub options: Options, pub draw: Drawable, pub time_to_reach_building: HashMap<BuildingID, Duration>, pub amenities_reachable: MultiMap<AmenityType, BuildingID>, pub population: usize, pub onstreet_parking_spots: usize, } #[derive(Clone)] pub enum Options { Walking(connectivity::WalkingOptions), Biking, } impl Options { pub fn time_to_reach_building( self, map: &Map, start: BuildingID, ) -> HashMap<BuildingID, Duration> { match self { Options::Walking(opts) => { connectivity::all_walking_costs_from(map, start, Duration::minutes(15), opts) } Options::Biking => connectivity::all_vehicle_costs_from( map, start, Duration::minutes(15), PathConstraints::Bike, ), } } } impl Isochrone { pub fn new(ctx: &mut EventCtx, app: &App, start: BuildingID, options: Options) -> Isochrone { let time_to_reach_building = options.clone().time_to_reach_building(&app.map, start); let mut amenities_reachable = MultiMap::new(); let mut population = 0; let mut all_roads = HashSet::new(); for b in time_to_reach_building.keys() { let bldg = app.map.get_b(*b); for amenity in &bldg.amenities { if let Some(category) = AmenityType::categorize(&amenity.amenity_type) { amenities_reachable.insert(category, bldg.id); } } match bldg.bldg_type { BuildingType::Residential { num_residents, .. } | BuildingType::ResidentialCommercial(num_residents, _) => { population += num_residents; } _ => {} } all_roads.insert(app.map.get_l(bldg.sidewalk_pos.lane()).parent); } let mut onstreet_parking_spots = 0; for r in all_roads { let r = app.map.get_r(r); for (l, _, lt) in r.lanes_ltr() { if lt == LaneType::Parking { onstreet_parking_spots += app.map.get_l(l).number_parking_spots(app.map.get_config()); } } } let mut i = Isochrone { start, options, draw: Drawable::empty(ctx), time_to_reach_building, amenities_reachable, population, onstreet_parking_spots, }; i.draw = i.draw_isochrone(app).upload(ctx); i } pub fn path_to(&self, map: &Map, to: BuildingID) -> Option<Path> { if !self.time_to_reach_building.contains_key(&to) { return None; } let req = PathRequest::between_buildings( map, self.start, to, match self.options { Options::Walking(_) => PathConstraints::Pedestrian, Options::Biking => PathConstraints::Bike, }, )?; map.pathfind(req).ok() } pub fn draw_isochrone(&self, app: &App) -> GeomBatch { let bounds = app.map.get_bounds(); let resolution_m = 100.0; let mut grid: Grid<f64> = Grid::new( (bounds.width() / resolution_m).ceil() as usize, (bounds.height() / resolution_m).ceil() as usize, 0.0, ); for (b, cost) in &self.time_to_reach_building { let pt = app.map.get_b(*b).polygon.center(); let idx = grid.idx( ((pt.x() - bounds.min_x) / resolution_m) as usize, ((pt.y() - bounds.min_y) / resolution_m) as usize, ); grid.data[idx] = cost.inner_seconds(); } let thresholds = vec![ 0.1, Duration::minutes(5).inner_seconds(), Duration::minutes(10).inner_seconds(), Duration::minutes(15).inner_seconds(), ]; let colors = vec![ Color::GREEN.alpha(0.5), Color::ORANGE.alpha(0.5), Color::RED.alpha(0.5), ]; let smooth = false; let c = contour::ContourBuilder::new(grid.width as u32, grid.height as u32, smooth); let mut batch = GeomBatch::new(); for (feature, color) in c .contours(&grid.data, &thresholds) .unwrap() .into_iter() .zip(colors) { match feature.geometry.unwrap().value { geojson::Value::MultiPolygon(polygons) => { for p in polygons { if let Ok(poly) = Polygon::from_geojson(&p) { batch.push(color, poly.scale(resolution_m)); } } } _ => unreachable!(), } } batch } }
use std::collections::{HashMap, HashSet}; use abstutil::MultiMap; use geom::{Duration, Polygon}; use map_gui::tools::Grid; use map_model::{ connectivity, AmenityType, BuildingID, BuildingType, LaneType, Map, Path, PathConstraints, PathRequest, }; use widgetry::{Color, Drawable, EventCtx, GeomBatch}; use crate::App; pub struct Isochrone { pub start: BuildingID, pub options: Options, pub draw: Drawable, pub time_to_reach_building: HashMap<BuildingID, Duration>, pub amenities_reachable: MultiMap<AmenityType, BuildingID>, pub population: usize, pub onstreet_parking_spots: usize, } #[derive(Clone)] pub enum Options { Walking(connectivity::WalkingOptions), Biking, } impl Options { pub fn time_to_reach_building( self, map: &Map, start: BuildingID, ) -> HashMap<BuildingID, Duration> { match self { Options::Walking(opts) => { connectivity::all_walking_costs_from(map, start, Duration::minutes(15), opts) } Options::Biking => connectivity::all_vehicle_costs_from( map, start, Duration::minutes(15), PathConstraints::Bike, ), } } } impl Isochrone {
pub fn path_to(&self, map: &Map, to: BuildingID) -> Option<Path> { if !self.time_to_reach_building.contains_key(&to) { return None; } let req = PathRequest::between_buildings( map, self.start, to, match self.options { Options::Walking(_) => PathConstraints::Pedestrian, Options::Biking => PathConstraints::Bike, }, )?; map.pathfind(req).ok() } pub fn draw_isochrone(&self, app: &App) -> GeomBatch { let bounds = app.map.get_bounds(); let resolution_m = 100.0; let mut grid: Grid<f64> = Grid::new( (bounds.width() / resolution_m).ceil() as usize, (bounds.height() / resolution_m).ceil() as usize, 0.0, ); for (b, cost) in &self.time_to_reach_building { let pt = app.map.get_b(*b).polygon.center(); let idx = grid.idx( ((pt.x() - bounds.min_x) / resolution_m) as usize, ((pt.y() - bounds.min_y) / resolution_m) as usize, ); grid.data[idx] = cost.inner_seconds(); } let thresholds = vec![ 0.1, Duration::minutes(5).inner_seconds(), Duration::minutes(10).inner_seconds(), Duration::minutes(15).inner_seconds(), ]; let colors = vec![ Color::GREEN.alpha(0.5), Color::ORANGE.alpha(0.5), Color::RED.alpha(0.5), ]; let smooth = false; let c = contour::ContourBuilder::new(grid.width as u32, grid.height as u32, smooth); let mut batch = GeomBatch::new(); for (feature, color) in c .contours(&grid.data, &thresholds) .unwrap() .into_iter() .zip(colors) { match feature.geometry.unwrap().value { geojson::Value::MultiPolygon(polygons) => { for p in polygons { if let Ok(poly) = Polygon::from_geojson(&p) { batch.push(color, poly.scale(resolution_m)); } } } _ => unreachable!(), } } batch } }
pub fn new(ctx: &mut EventCtx, app: &App, start: BuildingID, options: Options) -> Isochrone { let time_to_reach_building = options.clone().time_to_reach_building(&app.map, start); let mut amenities_reachable = MultiMap::new(); let mut population = 0; let mut all_roads = HashSet::new(); for b in time_to_reach_building.keys() { let bldg = app.map.get_b(*b); for amenity in &bldg.amenities { if let Some(category) = AmenityType::categorize(&amenity.amenity_type) { amenities_reachable.insert(category, bldg.id); } } match bldg.bldg_type { BuildingType::Residential { num_residents, .. } | BuildingType::ResidentialCommercial(num_residents, _) => { population += num_residents; } _ => {} } all_roads.insert(app.map.get_l(bldg.sidewalk_pos.lane()).parent); } let mut onstreet_parking_spots = 0; for r in all_roads { let r = app.map.get_r(r); for (l, _, lt) in r.lanes_ltr() { if lt == LaneType::Parking { onstreet_parking_spots += app.map.get_l(l).number_parking_spots(app.map.get_config()); } } } let mut i = Isochrone { start, options, draw: Drawable::empty(ctx), time_to_reach_building, amenities_reachable, population, onstreet_parking_spots, }; i.draw = i.draw_isochrone(app).upload(ctx); i }
function_block-full_function
[ { "content": "pub fn pathfind(req: PathRequest, params: &RoutingParams, map: &Map) -> Option<(Path, Duration)> {\n\n if req.constraints == PathConstraints::Pedestrian {\n\n pathfind_walking(req, map)\n\n } else {\n\n let graph = build_graph_for_vehicles(map, req.constraints);\n\n calc...
Rust
src/objects/mod.rs
hinton-lang/hinton
796ae395ce45240676875b7ddeddb9b5e54016b2
use crate::built_in::{NativeBoundMethod, NativeFn}; use crate::core::chunk::Chunk; use crate::objects::class_obj::*; use crate::objects::dictionary_obj::*; use crate::objects::iter_obj::IterObject; use std::cell::RefCell; use std::fmt; use std::fmt::Formatter; use std::rc::Rc; pub mod class_obj; pub mod dictionary_obj; pub mod indexing; pub mod iter_obj; mod native_operations; #[derive(Clone)] pub struct RangeObject { pub min: i64, pub max: i64, } #[derive(Clone)] pub struct FuncObject { pub defaults: Vec<Object>, pub min_arity: u8, pub max_arity: u8, pub chunk: Chunk, pub name: String, pub up_val_count: usize, } impl Default for FuncObject { fn default() -> Self { Self { defaults: vec![], min_arity: 0, max_arity: 0, chunk: Chunk::new(), name: String::from(""), up_val_count: 0, } } } impl fmt::Display for FuncObject { fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), fmt::Error> { if self.name == "fn" { write!(f, "<Func '<lambda>' at {:p}>", &*self as *const _) } else { write!(f, "<Func '{}' at {:p}>", &self.name, &*self as *const _) } } } impl FuncObject { pub fn bound_method(f: Rc<RefCell<FuncObject>>, i: Rc<RefCell<InstanceObject>>) -> Object { Object::BoundMethod(BoundMethod { receiver: i, method: ClosureObject { function: f, up_values: vec![], }, }) } } #[derive(Clone)] pub struct NativeFuncObj { pub name: String, pub min_arity: u8, pub max_arity: u8, pub body: NativeFn, } impl fmt::Display for NativeFuncObj { fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), fmt::Error> { write!(f, "<Func '{}' at {:p}>", self.name, &self.body as *const _) } } #[derive(Clone)] pub struct NativeMethodObj { pub class_name: String, pub method_name: String, pub value: Box<Object>, pub min_arity: u8, pub max_arity: u8, pub body: NativeBoundMethod, } impl fmt::Display for NativeMethodObj { fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), fmt::Error> { write!( f, "<Method '{}.{}' at {:p}>", self.class_name, self.method_name, &self.body as *const _ ) } } #[derive(Clone)] pub struct ClosureObject { pub function: Rc<RefCell<FuncObject>>, pub up_values: Vec<Rc<RefCell<UpValRef>>>, } impl fmt::Display for ClosureObject { fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), fmt::Error> { write!(f, "{}", self.function.borrow()) } } impl ClosureObject { pub fn into_bound_method(self, c: Rc<RefCell<InstanceObject>>) -> Object { Object::BoundMethod(BoundMethod { receiver: c, method: self, }) } } #[derive(Clone)] pub enum UpValRef { Open(usize), Closed(Object), } impl UpValRef { pub fn is_open_at(&self, index: usize) -> bool { match self { UpValRef::Closed(_) => false, UpValRef::Open(i) => *i == index, } } } #[derive(Clone)] pub enum Object { Array(Rc<RefCell<Vec<Object>>>), Bool(bool), BoundMethod(BoundMethod), BoundNativeMethod(NativeMethodObj), Class(Rc<RefCell<ClassObject>>), Closure(ClosureObject), Dict(DictObject), Float(f64), Function(Rc<RefCell<FuncObject>>), Instance(Rc<RefCell<InstanceObject>>), Int(i64), Iter(Rc<RefCell<IterObject>>), Native(Box<NativeFuncObj>), Null, Range(RangeObject), String(String), Tuple(Rc<Vec<Object>>), } impl From<NativeFuncObj> for Object { fn from(o: NativeFuncObj) -> Self { Object::Native(Box::new(o)) } } impl From<NativeMethodObj> for Object { fn from(o: NativeMethodObj) -> Self { Object::BoundNativeMethod(o) } } impl From<FuncObject> for Object { fn from(o: FuncObject) -> Self { Object::Function(Rc::new(RefCell::new(o))) } } impl From<ClassObject> for Object { fn from(o: ClassObject) -> Self { Object::Class(Rc::new(RefCell::new(o))) } } impl From<InstanceObject> for Object { fn from(o: InstanceObject) -> Self { Object::Instance(Rc::new(RefCell::new(o))) } } impl From<String> for Object { fn from(o: String) -> Self { Object::String(o) } } impl From<&str> for Object { fn from(o: &str) -> Self { Object::String(o.to_string()) } } impl From<usize> for Object { fn from(o: usize) -> Self { Object::Int(o as i64) } } pub fn obj_vectors_equal(v1: &[Object], v2: &[Object]) -> bool { if v1.len() != v2.len() { false } else { for (i, o) in v1.iter().enumerate() { if o != &v2[i] { return false; } } true } } impl Object { pub fn type_name(&self) -> String { return match self { Self::Array(_) => String::from("Array"), Self::Bool(_) => String::from("Bool"), Self::Dict(_) => String::from("Dict"), Self::Float(_) => String::from("Float"), Self::Function(_) | Self::Native(_) | Self::Closure(_) | Self::BoundMethod(_) | Self::BoundNativeMethod(_) => String::from("Function"), Self::Int(_) => String::from("Int"), Self::Iter(_) => String::from("Iter"), Self::Null => String::from("Null"), Self::Range(_) => String::from("Range"), Self::String(_) => String::from("String"), Self::Tuple(_) => String::from("Tuple"), Self::Class(c) => c.borrow().name.clone(), Self::Instance(i) => i.borrow().class.borrow().name.clone(), }; } pub fn is_int(&self) -> bool { matches!(self, Object::Int(_)) } pub fn is_float(&self) -> bool { matches!(self, Object::Float(_)) } pub fn is_bool(&self) -> bool { matches!(self, Object::Bool(_)) } pub fn is_falsey(&self) -> bool { match self { Self::Null => true, Self::Bool(val) => !val, Self::Int(x) if *x == 0i64 => true, Self::Float(x) if *x == 0f64 => true, _ => false, } } pub fn as_int(&self) -> Option<i64> { match self { Object::Int(v) => Some(*v), Object::Bool(b) => { if *b { Some(1i64) } else { Some(0i64) } } _ => None, } } pub fn as_float(&self) -> Option<f64> { match self { Object::Float(v) => Some(*v), _ => None, } } pub fn as_bool(&self) -> Option<bool> { match self { Object::Bool(v) => Some(*v), _ => None, } } #[cfg(feature = "show_bytecode")] pub fn as_function(&self) -> Option<&Rc<RefCell<FuncObject>>> { match self { Object::Function(v) => Some(v), _ => None, } } } impl<'a> fmt::Display for Object { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { match *self { Object::Int(ref inner) => write!(f, "\x1b[38;5;81m{}\x1b[0m", inner), Object::Instance(ref inner) => write!(f, "{}", inner.borrow()), Object::Native(ref inner) => write!(f, "{}", inner), Object::String(ref inner) => write!(f, "{}", inner), Object::Bool(inner) => write!(f, "\x1b[38;5;3m{}\x1b[0m", if inner { "true" } else { "false" }), Object::Iter(ref inner) => write!(f, "{}", inner.borrow()), Object::Function(ref inner) => write!(f, "{}", inner.borrow()), Object::Closure(ref inner) => write!(f, "{}", inner), Object::BoundMethod(ref inner) => write!(f, "{}", inner), Object::BoundNativeMethod(ref inner) => write!(f, "{}", inner), Object::Null => f.write_str("\x1b[37;1mnull\x1b[0m"), Object::Dict(ref inner) => write!(f, "{}", inner), Object::Float(ref inner) => { let fractional = if inner.fract() == 0.0 { ".0" } else { "" }; write!(f, "\x1b[38;5;81m{}{}\x1b[0m", inner, fractional) } Object::Range(ref inner) => { write!( f, "[\x1b[38;5;81m{}\x1b[0m..\x1b[38;5;81m{}\x1b[0m]", inner.min, inner.max ) } Object::Class(ref inner) => { let prt_str = format!("{:p}", &*inner.borrow() as *const _); fmt::Display::fmt(&format!("<Class '{}' at {}>", inner.borrow().name, prt_str), f) } Object::Array(ref inner) => { let arr = &inner.borrow(); let mut arr_str = String::from("["); for (idx, obj) in arr.iter().enumerate() { if idx == arr.len() - 1 { arr_str += &(format!("{}", obj))[..] } else { arr_str += &(format!("{}, ", obj))[..]; } } arr_str += "]"; write!(f, "{}", arr_str) } Object::Tuple(ref inner) => { let mut arr_str = String::from("("); for (idx, obj) in inner.iter().enumerate() { if idx == inner.len() - 1 { arr_str += &(format!("{}", obj))[..] } else { arr_str += &(format!("{}, ", obj))[..]; } } arr_str += ")"; write!(f, "{}", arr_str) } } } }
use crate::built_in::{NativeBoundMethod, NativeFn}; use crate::core::chunk::Chunk; use crate::objects::class_obj::*; use crate::objects::dictionary_obj::*; use crate::objects::iter_obj::IterObject; use std::cell::RefCell; use std::fmt; use std::fmt::Formatter; use std::rc::Rc; pub mod class_obj; pub mod dictionary_obj; pub mod indexing; pub mod iter_obj; mod native_operations; #[derive(Clone)] pub struct RangeObject { pub min: i64, pub max: i64, } #[derive(Clone)] pub struct FuncObject { pub defaults: Vec<Object>, pub min_arity: u8, pub max_arity: u8, pub chunk: Chunk, pub name: String, pub up_val_count: usize, } impl Default for FuncObject { fn default() -> Self { Self { defaults: vec![], min_arity: 0, max_arity: 0, chunk: Chunk::new(), name: String::from(""), up_val_count: 0, } } } impl fmt::Display for FuncObject { fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), fmt::Error> { if self.name == "fn" { write!(f, "<Func '<lambda>' at {:p}>", &*self as *const _) } else { write!(f, "<Func '{}' at {:p}>", &self.name, &*self as *const _) } } } impl FuncObject { pub fn bound_method(f: Rc<RefCell<FuncObject>>, i: Rc<RefCell<InstanceObject>>) -> Object { Object::BoundMethod(BoundMethod { receiver: i, method: ClosureObject { function: f, up_values: vec![], }, }) } } #[derive(Clone)] pub struct NativeFuncObj { pub name: String, pub min_arity: u8, pub max_arity: u8, pub body: NativeFn, } impl fmt::Display for NativeFuncObj { fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), fmt::Error> { write!(f, "<Func '{}' at {:p}>", self.name, &self.body as *const _) } } #[derive(Clone)] pub struct NativeMethodObj { pub class_name: String, pub method_name: String, pub value: Box<Object>, pub min_arity: u8, pub max_arity: u8, pub body: NativeBoundMethod, } impl fmt::Display for NativeMethodObj { fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), fmt::Error> { write!( f, "<Method '{}.{}' at {:p}>", self.class_name, self.method_name, &self.body as *const _ ) } } #[derive(Clone)] pub struct ClosureObject { pub function: Rc<RefCell<FuncObject>>, pub up_values: Vec<Rc<RefCell<UpValRef>>>, } impl fmt::Display for ClosureObject { fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), fmt::Error> { write!(f, "{}", self.function.borrow()) } } impl ClosureObject {
} #[derive(Clone)] pub enum UpValRef { Open(usize), Closed(Object), } impl UpValRef { pub fn is_open_at(&self, index: usize) -> bool { match self { UpValRef::Closed(_) => false, UpValRef::Open(i) => *i == index, } } } #[derive(Clone)] pub enum Object { Array(Rc<RefCell<Vec<Object>>>), Bool(bool), BoundMethod(BoundMethod), BoundNativeMethod(NativeMethodObj), Class(Rc<RefCell<ClassObject>>), Closure(ClosureObject), Dict(DictObject), Float(f64), Function(Rc<RefCell<FuncObject>>), Instance(Rc<RefCell<InstanceObject>>), Int(i64), Iter(Rc<RefCell<IterObject>>), Native(Box<NativeFuncObj>), Null, Range(RangeObject), String(String), Tuple(Rc<Vec<Object>>), } impl From<NativeFuncObj> for Object { fn from(o: NativeFuncObj) -> Self { Object::Native(Box::new(o)) } } impl From<NativeMethodObj> for Object { fn from(o: NativeMethodObj) -> Self { Object::BoundNativeMethod(o) } } impl From<FuncObject> for Object { fn from(o: FuncObject) -> Self { Object::Function(Rc::new(RefCell::new(o))) } } impl From<ClassObject> for Object { fn from(o: ClassObject) -> Self { Object::Class(Rc::new(RefCell::new(o))) } } impl From<InstanceObject> for Object { fn from(o: InstanceObject) -> Self { Object::Instance(Rc::new(RefCell::new(o))) } } impl From<String> for Object { fn from(o: String) -> Self { Object::String(o) } } impl From<&str> for Object { fn from(o: &str) -> Self { Object::String(o.to_string()) } } impl From<usize> for Object { fn from(o: usize) -> Self { Object::Int(o as i64) } } pub fn obj_vectors_equal(v1: &[Object], v2: &[Object]) -> bool { if v1.len() != v2.len() { false } else { for (i, o) in v1.iter().enumerate() { if o != &v2[i] { return false; } } true } } impl Object { pub fn type_name(&self) -> String { return match self { Self::Array(_) => String::from("Array"), Self::Bool(_) => String::from("Bool"), Self::Dict(_) => String::from("Dict"), Self::Float(_) => String::from("Float"), Self::Function(_) | Self::Native(_) | Self::Closure(_) | Self::BoundMethod(_) | Self::BoundNativeMethod(_) => String::from("Function"), Self::Int(_) => String::from("Int"), Self::Iter(_) => String::from("Iter"), Self::Null => String::from("Null"), Self::Range(_) => String::from("Range"), Self::String(_) => String::from("String"), Self::Tuple(_) => String::from("Tuple"), Self::Class(c) => c.borrow().name.clone(), Self::Instance(i) => i.borrow().class.borrow().name.clone(), }; } pub fn is_int(&self) -> bool { matches!(self, Object::Int(_)) } pub fn is_float(&self) -> bool { matches!(self, Object::Float(_)) } pub fn is_bool(&self) -> bool { matches!(self, Object::Bool(_)) } pub fn is_falsey(&self) -> bool { match self { Self::Null => true, Self::Bool(val) => !val, Self::Int(x) if *x == 0i64 => true, Self::Float(x) if *x == 0f64 => true, _ => false, } } pub fn as_int(&self) -> Option<i64> { match self { Object::Int(v) => Some(*v), Object::Bool(b) => { if *b { Some(1i64) } else { Some(0i64) } } _ => None, } } pub fn as_float(&self) -> Option<f64> { match self { Object::Float(v) => Some(*v), _ => None, } } pub fn as_bool(&self) -> Option<bool> { match self { Object::Bool(v) => Some(*v), _ => None, } } #[cfg(feature = "show_bytecode")] pub fn as_function(&self) -> Option<&Rc<RefCell<FuncObject>>> { match self { Object::Function(v) => Some(v), _ => None, } } } impl<'a> fmt::Display for Object { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { match *self { Object::Int(ref inner) => write!(f, "\x1b[38;5;81m{}\x1b[0m", inner), Object::Instance(ref inner) => write!(f, "{}", inner.borrow()), Object::Native(ref inner) => write!(f, "{}", inner), Object::String(ref inner) => write!(f, "{}", inner), Object::Bool(inner) => write!(f, "\x1b[38;5;3m{}\x1b[0m", if inner { "true" } else { "false" }), Object::Iter(ref inner) => write!(f, "{}", inner.borrow()), Object::Function(ref inner) => write!(f, "{}", inner.borrow()), Object::Closure(ref inner) => write!(f, "{}", inner), Object::BoundMethod(ref inner) => write!(f, "{}", inner), Object::BoundNativeMethod(ref inner) => write!(f, "{}", inner), Object::Null => f.write_str("\x1b[37;1mnull\x1b[0m"), Object::Dict(ref inner) => write!(f, "{}", inner), Object::Float(ref inner) => { let fractional = if inner.fract() == 0.0 { ".0" } else { "" }; write!(f, "\x1b[38;5;81m{}{}\x1b[0m", inner, fractional) } Object::Range(ref inner) => { write!( f, "[\x1b[38;5;81m{}\x1b[0m..\x1b[38;5;81m{}\x1b[0m]", inner.min, inner.max ) } Object::Class(ref inner) => { let prt_str = format!("{:p}", &*inner.borrow() as *const _); fmt::Display::fmt(&format!("<Class '{}' at {}>", inner.borrow().name, prt_str), f) } Object::Array(ref inner) => { let arr = &inner.borrow(); let mut arr_str = String::from("["); for (idx, obj) in arr.iter().enumerate() { if idx == arr.len() - 1 { arr_str += &(format!("{}", obj))[..] } else { arr_str += &(format!("{}, ", obj))[..]; } } arr_str += "]"; write!(f, "{}", arr_str) } Object::Tuple(ref inner) => { let mut arr_str = String::from("("); for (idx, obj) in inner.iter().enumerate() { if idx == inner.len() - 1 { arr_str += &(format!("{}", obj))[..] } else { arr_str += &(format!("{}, ", obj))[..]; } } arr_str += ")"; write!(f, "{}", arr_str) } } } }
pub fn into_bound_method(self, c: Rc<RefCell<InstanceObject>>) -> Object { Object::BoundMethod(BoundMethod { receiver: c, method: self, }) }
function_block-full_function
[ { "content": "#[cfg(feature = \"show_bytecode\")]\n\npub fn disassemble_func_scope(chunk: &Chunk, natives: &[String], primitives: &[String], name: &str) {\n\n // prints this chunk's name\n\n println!(\"==== {} ====\", name);\n\n\n\n let mut current_line = 0;\n\n\n\n let mut idx = 0;\n\n while idx < ch...
Rust
crates/eww/src/script_var_handler.rs
RianFuro/eww
e1558965ff45f72c35b7aeed15774381f32e0165
use std::collections::HashMap; use crate::{ app, config::{create_script_var_failed_warn, script_var}, }; use anyhow::*; use app::DaemonCommand; use eww_shared_util::VarName; use nix::{ sys::signal, unistd::{setpgid, Pid}, }; use simplexpr::dynval::DynVal; use tokio::{ io::{AsyncBufReadExt, BufReader}, sync::mpsc::UnboundedSender, }; use tokio_util::sync::CancellationToken; use yuck::config::script_var_definition::{ListenScriptVar, PollScriptVar, ScriptVarDefinition, VarSource}; pub fn init(evt_send: UnboundedSender<DaemonCommand>) -> ScriptVarHandlerHandle { let (msg_send, mut msg_recv) = tokio::sync::mpsc::unbounded_channel(); let handle = ScriptVarHandlerHandle { msg_send }; std::thread::spawn(move || { let rt = tokio::runtime::Runtime::new().expect("Failed to initialize tokio runtime for script var handlers"); rt.block_on(async { let _: Result<_> = try { let mut handler = ScriptVarHandler { listen_handler: ListenVarHandler::new(evt_send.clone())?, poll_handler: PollVarHandler::new(evt_send)?, }; crate::loop_select_exiting! { Some(msg) = msg_recv.recv() => match msg { ScriptVarHandlerMsg::AddVar(var) => { handler.add(var).await; } ScriptVarHandlerMsg::Stop(name) => { handler.stop_for_variable(&name)?; } ScriptVarHandlerMsg::StopAll => { handler.stop_all(); } }, else => break, }; }; }) }); handle } pub struct ScriptVarHandlerHandle { msg_send: UnboundedSender<ScriptVarHandlerMsg>, } impl ScriptVarHandlerHandle { pub fn add(&self, script_var: ScriptVarDefinition) { crate::print_result_err!( "while forwarding instruction to script-var handler", self.msg_send.send(ScriptVarHandlerMsg::AddVar(script_var)) ); } pub fn stop_for_variable(&self, name: VarName) { crate::print_result_err!( "while forwarding instruction to script-var handler", self.msg_send.send(ScriptVarHandlerMsg::Stop(name)), ); } pub fn stop_all(&self) { crate::print_result_err!( "while forwarding instruction to script-var handler", self.msg_send.send(ScriptVarHandlerMsg::StopAll) ); } } #[derive(Debug, Eq, PartialEq)] enum ScriptVarHandlerMsg { AddVar(ScriptVarDefinition), Stop(VarName), StopAll, } struct ScriptVarHandler { listen_handler: ListenVarHandler, poll_handler: PollVarHandler, } impl ScriptVarHandler { async fn add(&mut self, script_var: ScriptVarDefinition) { match script_var { ScriptVarDefinition::Poll(var) => self.poll_handler.start(var).await, ScriptVarDefinition::Listen(var) => self.listen_handler.start(var).await, }; } fn stop_for_variable(&mut self, name: &VarName) -> Result<()> { log::debug!("Stopping script var process for variable {}", name); self.listen_handler.stop_for_variable(name); self.poll_handler.stop_for_variable(name); Ok(()) } fn stop_all(&mut self) { log::debug!("Stopping script-var-handlers"); self.listen_handler.stop_all(); self.poll_handler.stop_all(); } } struct PollVarHandler { evt_send: UnboundedSender<DaemonCommand>, poll_handles: HashMap<VarName, CancellationToken>, } impl PollVarHandler { fn new(evt_send: UnboundedSender<DaemonCommand>) -> Result<Self> { let handler = PollVarHandler { evt_send, poll_handles: HashMap::new() }; Ok(handler) } async fn start(&mut self, var: PollScriptVar) { if self.poll_handles.contains_key(&var.name) { return; } log::debug!("starting poll var {}", &var.name); let cancellation_token = CancellationToken::new(); self.poll_handles.insert(var.name.clone(), cancellation_token.clone()); let evt_send = self.evt_send.clone(); tokio::spawn(async move { let result: Result<_> = try { evt_send.send(app::DaemonCommand::UpdateVars(vec![(var.name.clone(), run_poll_once(&var)?)]))?; }; if let Err(err) = result { crate::error_handling_ctx::print_error(err); } crate::loop_select_exiting! { _ = cancellation_token.cancelled() => break, _ = tokio::time::sleep(var.interval) => { let result: Result<_> = try { evt_send.send(app::DaemonCommand::UpdateVars(vec![(var.name.clone(), run_poll_once(&var)?)]))?; }; if let Err(err) = result { crate::error_handling_ctx::print_error(err); } } } }); } fn stop_for_variable(&mut self, name: &VarName) { if let Some(token) = self.poll_handles.remove(name) { log::debug!("stopped poll var {}", name); token.cancel() } } fn stop_all(&mut self) { self.poll_handles.drain().for_each(|(_, token)| token.cancel()); } } fn run_poll_once(var: &PollScriptVar) -> Result<DynVal> { match &var.command { VarSource::Shell(span, command) => { script_var::run_command(command).map_err(|e| anyhow!(create_script_var_failed_warn(*span, &var.name, &e.to_string()))) } VarSource::Function(x) => x().map_err(|e| anyhow!(e)), } } impl Drop for PollVarHandler { fn drop(&mut self) { self.stop_all(); } } struct ListenVarHandler { evt_send: UnboundedSender<DaemonCommand>, listen_process_handles: HashMap<VarName, CancellationToken>, } impl ListenVarHandler { fn new(evt_send: UnboundedSender<DaemonCommand>) -> Result<Self> { let handler = ListenVarHandler { evt_send, listen_process_handles: HashMap::new() }; Ok(handler) } async fn start(&mut self, var: ListenScriptVar) { log::debug!("starting listen-var {}", &var.name); let cancellation_token = CancellationToken::new(); self.listen_process_handles.insert(var.name.clone(), cancellation_token.clone()); let evt_send = self.evt_send.clone(); tokio::spawn(async move { crate::try_logging_errors!(format!("Executing listen var-command {}", &var.command) => { let mut handle = unsafe { tokio::process::Command::new("sh") .args(&["-c", &var.command]) .stdout(std::process::Stdio::piped()) .stderr(std::process::Stdio::piped()) .stdin(std::process::Stdio::null()) .pre_exec(|| { let _ = setpgid(Pid::from_raw(0), Pid::from_raw(0)); Ok(()) }).spawn()? }; let mut stdout_lines = BufReader::new(handle.stdout.take().unwrap()).lines(); let mut stderr_lines = BufReader::new(handle.stderr.take().unwrap()).lines(); crate::loop_select_exiting! { _ = handle.wait() => break, _ = cancellation_token.cancelled() => break, Ok(Some(line)) = stdout_lines.next_line() => { let new_value = DynVal::from_string(line.to_owned()); evt_send.send(DaemonCommand::UpdateVars(vec![(var.name.to_owned(), new_value)]))?; } Ok(Some(line)) = stderr_lines.next_line() => { log::warn!("stderr of `{}`: {}", var.name, line); } else => break, } terminate_handle(handle).await; }); }); } fn stop_for_variable(&mut self, name: &VarName) { if let Some(token) = self.listen_process_handles.remove(name) { log::debug!("stopped listen-var {}", name); token.cancel(); } } fn stop_all(&mut self) { self.listen_process_handles.drain().for_each(|(_, token)| token.cancel()); } } impl Drop for ListenVarHandler { fn drop(&mut self) { self.stop_all(); } } async fn terminate_handle(mut child: tokio::process::Child) { if let Some(id) = child.id() { let _ = signal::killpg(Pid::from_raw(id as i32), signal::SIGTERM); tokio::select! { _ = child.wait() => {}, _ = tokio::time::sleep(std::time::Duration::from_secs(10)) => { let _ = child.kill().await; } }; } else { let _ = child.kill().await; } }
use std::collections::HashMap; use crate::{ app, config::{create_script_var_failed_warn, script_var}, }; use anyhow::*; use app::DaemonCommand; use eww_shared_util::VarName; use nix::{ sys::signal, unistd::{setpgid, Pid}, }; use simplexpr::dynval::DynVal; use tokio::{ io::{AsyncBufReadExt, BufReader}, sync::mpsc::UnboundedSender, }; use tokio_util::sync::CancellationToken; use yuck::config::script_var_definition::{ListenScriptVar, PollScriptVar, ScriptVarDefinition, VarSource}; pub fn init(evt_send: UnboundedSender<DaemonCommand>) -> ScriptVarHandlerHandle { let (msg_send, mut msg_recv) = tokio::sync::mpsc::unbounded_channel(); let handle = ScriptVarHandlerHandle { msg_send }; std::thread::spawn(move || { let rt = tokio::runtime::Runtime::new().expect("Failed to initialize tokio runtime for script var handlers"); rt.block_on(async { let _: Result<_> = try { let mut handler = ScriptVarHandler { listen_handler: ListenVarHandler::new(evt_send.clone())?, poll_handler: PollVarHandler::new(evt_send)?, }; crate::loop_select_exiting! { Some(msg) = msg_recv.recv() => match msg { ScriptVarHandlerMsg::AddVar(var) => { handler.add(var).await; } ScriptVarHandlerMsg::Stop(name) => { handler.stop_for_variable(&name)?; } ScriptVarHandlerMsg::StopAll => { handler.stop_all(); } }, else => break, }; }; }) }); handle } pub struct ScriptVarHandlerHandle { msg_send: UnboundedSender<ScriptVarHandlerMsg>, } impl ScriptVarHandlerHandle {
pub fn stop_for_variable(&self, name: VarName) { crate::print_result_err!( "while forwarding instruction to script-var handler", self.msg_send.send(ScriptVarHandlerMsg::Stop(name)), ); } pub fn stop_all(&self) { crate::print_result_err!( "while forwarding instruction to script-var handler", self.msg_send.send(ScriptVarHandlerMsg::StopAll) ); } } #[derive(Debug, Eq, PartialEq)] enum ScriptVarHandlerMsg { AddVar(ScriptVarDefinition), Stop(VarName), StopAll, } struct ScriptVarHandler { listen_handler: ListenVarHandler, poll_handler: PollVarHandler, } impl ScriptVarHandler { async fn add(&mut self, script_var: ScriptVarDefinition) { match script_var { ScriptVarDefinition::Poll(var) => self.poll_handler.start(var).await, ScriptVarDefinition::Listen(var) => self.listen_handler.start(var).await, }; } fn stop_for_variable(&mut self, name: &VarName) -> Result<()> { log::debug!("Stopping script var process for variable {}", name); self.listen_handler.stop_for_variable(name); self.poll_handler.stop_for_variable(name); Ok(()) } fn stop_all(&mut self) { log::debug!("Stopping script-var-handlers"); self.listen_handler.stop_all(); self.poll_handler.stop_all(); } } struct PollVarHandler { evt_send: UnboundedSender<DaemonCommand>, poll_handles: HashMap<VarName, CancellationToken>, } impl PollVarHandler { fn new(evt_send: UnboundedSender<DaemonCommand>) -> Result<Self> { let handler = PollVarHandler { evt_send, poll_handles: HashMap::new() }; Ok(handler) } async fn start(&mut self, var: PollScriptVar) { if self.poll_handles.contains_key(&var.name) { return; } log::debug!("starting poll var {}", &var.name); let cancellation_token = CancellationToken::new(); self.poll_handles.insert(var.name.clone(), cancellation_token.clone()); let evt_send = self.evt_send.clone(); tokio::spawn(async move { let result: Result<_> = try { evt_send.send(app::DaemonCommand::UpdateVars(vec![(var.name.clone(), run_poll_once(&var)?)]))?; }; if let Err(err) = result { crate::error_handling_ctx::print_error(err); } crate::loop_select_exiting! { _ = cancellation_token.cancelled() => break, _ = tokio::time::sleep(var.interval) => { let result: Result<_> = try { evt_send.send(app::DaemonCommand::UpdateVars(vec![(var.name.clone(), run_poll_once(&var)?)]))?; }; if let Err(err) = result { crate::error_handling_ctx::print_error(err); } } } }); } fn stop_for_variable(&mut self, name: &VarName) { if let Some(token) = self.poll_handles.remove(name) { log::debug!("stopped poll var {}", name); token.cancel() } } fn stop_all(&mut self) { self.poll_handles.drain().for_each(|(_, token)| token.cancel()); } } fn run_poll_once(var: &PollScriptVar) -> Result<DynVal> { match &var.command { VarSource::Shell(span, command) => { script_var::run_command(command).map_err(|e| anyhow!(create_script_var_failed_warn(*span, &var.name, &e.to_string()))) } VarSource::Function(x) => x().map_err(|e| anyhow!(e)), } } impl Drop for PollVarHandler { fn drop(&mut self) { self.stop_all(); } } struct ListenVarHandler { evt_send: UnboundedSender<DaemonCommand>, listen_process_handles: HashMap<VarName, CancellationToken>, } impl ListenVarHandler { fn new(evt_send: UnboundedSender<DaemonCommand>) -> Result<Self> { let handler = ListenVarHandler { evt_send, listen_process_handles: HashMap::new() }; Ok(handler) } async fn start(&mut self, var: ListenScriptVar) { log::debug!("starting listen-var {}", &var.name); let cancellation_token = CancellationToken::new(); self.listen_process_handles.insert(var.name.clone(), cancellation_token.clone()); let evt_send = self.evt_send.clone(); tokio::spawn(async move { crate::try_logging_errors!(format!("Executing listen var-command {}", &var.command) => { let mut handle = unsafe { tokio::process::Command::new("sh") .args(&["-c", &var.command]) .stdout(std::process::Stdio::piped()) .stderr(std::process::Stdio::piped()) .stdin(std::process::Stdio::null()) .pre_exec(|| { let _ = setpgid(Pid::from_raw(0), Pid::from_raw(0)); Ok(()) }).spawn()? }; let mut stdout_lines = BufReader::new(handle.stdout.take().unwrap()).lines(); let mut stderr_lines = BufReader::new(handle.stderr.take().unwrap()).lines(); crate::loop_select_exiting! { _ = handle.wait() => break, _ = cancellation_token.cancelled() => break, Ok(Some(line)) = stdout_lines.next_line() => { let new_value = DynVal::from_string(line.to_owned()); evt_send.send(DaemonCommand::UpdateVars(vec![(var.name.to_owned(), new_value)]))?; } Ok(Some(line)) = stderr_lines.next_line() => { log::warn!("stderr of `{}`: {}", var.name, line); } else => break, } terminate_handle(handle).await; }); }); } fn stop_for_variable(&mut self, name: &VarName) { if let Some(token) = self.listen_process_handles.remove(name) { log::debug!("stopped listen-var {}", name); token.cancel(); } } fn stop_all(&mut self) { self.listen_process_handles.drain().for_each(|(_, token)| token.cancel()); } } impl Drop for ListenVarHandler { fn drop(&mut self) { self.stop_all(); } } async fn terminate_handle(mut child: tokio::process::Child) { if let Some(id) = child.id() { let _ = signal::killpg(Pid::from_raw(id as i32), signal::SIGTERM); tokio::select! { _ = child.wait() => {}, _ = tokio::time::sleep(std::time::Duration::from_secs(10)) => { let _ = child.kill().await; } }; } else { let _ = child.kill().await; } }
pub fn add(&self, script_var: ScriptVarDefinition) { crate::print_result_err!( "while forwarding instruction to script-var handler", self.msg_send.send(ScriptVarHandlerMsg::AddVar(script_var)) ); }
function_block-function_prefix_line
[ { "content": "pub fn initial_value(var: &ScriptVarDefinition) -> Result<DynVal> {\n\n match var {\n\n ScriptVarDefinition::Poll(x) => match &x.initial_value {\n\n Some(value) => Ok(value.clone()),\n\n None => match &x.command {\n\n VarSource::Function(f) => f()\n\n...
Rust
src/engine/mod.rs
mersinvald/xsecurelock-saver-rs
e4c064918271a165657e52c4a22d20eb383e9e6a
use std::sync::Arc; use rayon::ThreadPoolBuilder; use sfml::graphics::{ Color, RenderTarget, RenderWindow, View as SfView, }; use sfml::system::{Clock, SfBox, Time, Vector2f}; use specs::{Component, System}; use shred::Resource; use physics::{ self, resources::{PhysicsDeltaTime, PhysicsElapsed}, systems::{ClearForceAccumulators, SetupNextPhysicsPosition}, }; use scene_management::{ self, resources::{SceneChange, SceneLoader}, SceneChangeHandler, SceneChangeHandlerBuilder, systems::DeleteSystem, }; use self::{ resources::{ draw::{ CurrentDrawLayer, DrawLayers, View, }, time::{ DeltaTime, Elapsed, }, }, systems::{ draw::{ DrawLayersUpdater, SyncDrawShapesSystem, DrawDrawShapesSystem, SfShape, }, specialized::{ SpecializedSystem, SpecializedSystemObject, }, }, }; pub mod components; pub mod resources; pub mod systems; pub struct EngineBuilder<'a, 'b> { world: ::specs::World, update_dispatcher: ::specs::DispatcherBuilder<'a, 'b>, scene_change_handler: SceneChangeHandlerBuilder<'a, 'b>, physics_update_dispatcher: ::specs::DispatcherBuilder<'a, 'b>, max_physics_updates: usize } impl<'a, 'b> EngineBuilder<'a, 'b> { pub fn new() -> Self { let thread_pool = Arc::new(ThreadPoolBuilder::new().build().unwrap()); Self { world: { let mut world = ::specs::World::new(); physics::register(&mut world); scene_management::register(&mut world); components::register_all(&mut world); resources::add_default_resources(&mut world); world }, update_dispatcher: ::specs::DispatcherBuilder::new() .with_pool(Arc::clone(&thread_pool)), scene_change_handler: SceneChangeHandlerBuilder::new() .with_threadpool(Arc::clone(&thread_pool)), physics_update_dispatcher: ::specs::DispatcherBuilder::new() .with_pool(thread_pool) .with(SetupNextPhysicsPosition, "", &[]) .with(ClearForceAccumulators, "", &[]) .with_barrier(), max_physics_updates: 5, } } pub fn with_update_sys<S>(mut self, sys: S, name: &str, dep: &[&str]) -> Self where S: for<'c> System<'c> + Send + 'a { self.add_update_sys(sys, name, dep); self } pub fn add_update_sys<S>(&mut self, sys: S, name: &str, dep: &[&str]) where S: for<'c> System<'c> + Send + 'a { self.update_dispatcher.add(sys, name, dep); } pub fn with_update_barrier(mut self) -> Self { self.add_update_barrier(); self } pub fn add_update_barrier(&mut self) { self.update_dispatcher.add_barrier(); } pub fn with_scene_change_sys<S>(mut self, sys: S, name: &str, dep: &[&str]) -> Self where S: for<'c> System<'c> + Send + 'a { self.add_scene_change_sys(sys, name, dep); self } pub fn add_scene_change_sys<S>(&mut self, sys: S, name: &str, dep: &[&str]) where S: for<'c> System<'c> + Send + 'a { self.scene_change_handler.add_pre_load_sys(sys, name, dep); } pub fn with_scene_change_barrier(mut self) -> Self { self.add_scene_change_barrier(); self } pub fn add_scene_change_barrier(&mut self) { self.scene_change_handler.add_pre_load_barrier(); } pub fn with_physics_update_sys<S>(mut self, sys: S, name: &str, dep: &[&str]) -> Self where S: for<'c> System<'c> + Send + 'a { self.add_physics_update_sys(sys, name, dep); self } pub fn add_physics_update_sys<S>(&mut self, sys: S, name: &str, dep: &[&str]) where S: for<'c> System<'c> + Send + 'a { self.physics_update_dispatcher.add(sys, name, dep); } pub fn with_physics_update_barrier(mut self) -> Self { self.add_physics_update_barrier(); self } pub fn add_physics_update_barrier(&mut self) { self.physics_update_dispatcher.add_barrier(); } pub fn with_component<C: Component>(mut self) -> Self where <C as Component>::Storage: Default { self.add_component::<C>(); self } pub fn add_component<C: Component>(&mut self) where <C as Component>::Storage: Default { self.world.register::<C>(); } pub fn with_resource<T: Resource>(mut self, res: T) -> Self { self.add_resource(res); self } pub fn add_resource<T: Resource>(&mut self, res: T) { self.world.add_resource(res); } pub fn with_initial_sceneloader<T>(mut self, loader: T) -> Self where T: for<'l> SceneLoader<'l> + Send + Sync + 'static { self.set_initial_sceneloader(loader); self } pub fn set_initial_sceneloader<T>(&mut self, loader: T) where T: for<'l> SceneLoader<'l> + Send + Sync + 'static { self.world.write_resource::<SceneChange>().change_scene(loader); } pub fn build<'tex>(self) -> Engine<'a, 'b, 'tex> { let mut engine = Engine { world: self.world, update_dispatcher: self.update_dispatcher .with_barrier() .with(DrawLayersUpdater::default(), "", &[]) .with(DeleteSystem, "", &[]) .build(), scene_change_handler: self.scene_change_handler.build(), physics_update_dispatcher: self.physics_update_dispatcher .with_barrier() .with(DeleteSystem, "", &[]) .build(), window: super::open_window(), view: SfView::new(Vector2f::new(0., 0.), Vector2f::new(1., 1.)), clock: Clock::start(), max_physics_updates: self.max_physics_updates, draw_shapes: Vec::new(), sync_draw_shapes: Default::default(), draw_draw_shapes: Default::default(), }; { let mut view = engine.world.write_resource::<View>(); let win_sz = engine.window.size(); let ratio = win_sz.x as f32 / win_sz.y as f32; view.size.y = 2000.; view.size.x = ratio * view.size.y; view.copy_to(&mut engine.view); } engine.update_dispatcher.setup(&mut engine.world.res); engine.scene_change_handler.setup(&mut engine.world); engine.physics_update_dispatcher.setup(&mut engine.world.res); engine.sync_draw_shapes.setup_special(&mut engine.draw_shapes, &mut engine.world.res); engine.draw_draw_shapes.setup_special( (&mut engine.window, &mut engine.draw_shapes), &mut engine.world.res); engine } } pub struct Engine<'a, 'b, 'tex> { world: ::specs::World, update_dispatcher: ::specs::Dispatcher<'a, 'b>, scene_change_handler: SceneChangeHandler<'a, 'b>, physics_update_dispatcher: ::specs::Dispatcher<'a, 'b>, window: RenderWindow, view: SfBox<SfView>, clock: Clock, max_physics_updates: usize, draw_shapes: Vec<Option<SfShape<'tex>>>, sync_draw_shapes: SyncDrawShapesSystem, draw_draw_shapes: DrawDrawShapesSystem, } impl<'a, 'b, 'tex> Engine<'a, 'b, 'tex> { pub fn create_entity(&mut self) -> ::specs::world::EntityBuilder { self.world.create_entity() } pub fn run(mut self) { sigint::init(); self.clock.restart(); { let start = self.clock.elapsed_time(); let mut physt = self.world.write_resource::<PhysicsElapsed>(); physt.current = start; physt.previous = start - self.world.read_resource::<PhysicsDeltaTime>().0; let mut dt = self.world.write_resource::<DeltaTime>(); dt.0 = Time::milliseconds(5); let mut t = self.world.write_resource::<Elapsed>(); t.current = start; t.previous = start - dt.0; } while !sigint::received_sigint() { let now = self.clock.elapsed_time(); self.maybe_physics_update(now); self.update(now); self.draw(); } } fn maybe_physics_update(&mut self, now: Time) { for _ in 0..self.max_physics_updates { { let mut physt = self.world.write_resource::<PhysicsElapsed>(); if physt.current >= now { return; } let physdt = self.world.read_resource::<PhysicsDeltaTime>(); physt.previous = physt.current; physt.current += physdt.0; } self.physics_update_dispatcher.dispatch(&self.world.res); self.world.maintain(); self.scene_change_handler.handle_scene_change(&mut self.world); } let mut phys = self.world.write_resource::<PhysicsElapsed>(); let dphys = self.world.read_resource::<PhysicsDeltaTime>(); while phys.current < now { phys.previous = phys.current; phys.current += dphys.0; } } fn update(&mut self, now: Time) { { let mut elapsed = self.world.write_resource::<Elapsed>(); elapsed.previous = elapsed.current; elapsed.current = now; let mut delta = self.world.write_resource::<DeltaTime>(); delta.0 = elapsed.current - elapsed.previous; } self.update_dispatcher.dispatch(&self.world.res); self.world.maintain(); self.scene_change_handler.handle_scene_change(&mut self.world); } fn draw(&mut self) { self.sync_draw_shapes.run(&mut self.draw_shapes, &self.world.res); self.world.write_resource::<View>().copy_to(&mut self.view); self.window.clear(Color::BLACK); self.window.set_view(&self.view); for layer in 0..=DrawLayers::NUM_LAYERS { self.world.write_resource::<CurrentDrawLayer>().set_layer(layer); self.draw_draw_shapes.run((&mut self.window, &mut self.draw_shapes), &self.world.res); } self.window.display(); } }
use std::sync::Arc; use rayon::ThreadPoolBuilder; use sfml::graphics::{ Color, RenderTarget, RenderWindow, View as SfView, }; use sfml::system::{Clock, SfBox, Time, Vector2f}; use specs::{Component, System}; use shred::Resource; use physics::{ self, resources::{PhysicsDeltaTime, PhysicsElapsed}, systems::{ClearForceAccumulators, SetupNextPhysicsPosition}, }; use scene_management::{ self, resources::{SceneChange, SceneLoader}, SceneChangeHandler, SceneChangeHandlerBuilder, systems::DeleteSystem, }; use self::{ resources::{ draw::{ CurrentDrawLayer, DrawLayers, View, }, time::{ DeltaTime, Elapsed, }, }, systems::{ draw::{ DrawLayersUpdater, SyncDrawShapesSystem, DrawDrawShapesSystem, SfShape, }, specialized::{ SpecializedSystem, SpecializedSystemObject, }, }, }; pub mod components; pub mod resources; pub mod systems; pub struct EngineBuilder<'a, 'b> { world: ::specs::World, update_dispatcher: ::specs::DispatcherBuilder<'a, 'b>, scene_change_handler: SceneChangeHandlerBuilder<'a, 'b>, physics_update_dispatcher: ::specs::DispatcherBuilder<'a, 'b>, max_physics_updates: usize } impl<'a, 'b> EngineBuilder<'a, 'b> {
pub fn with_update_sys<S>(mut self, sys: S, name: &str, dep: &[&str]) -> Self where S: for<'c> System<'c> + Send + 'a { self.add_update_sys(sys, name, dep); self } pub fn add_update_sys<S>(&mut self, sys: S, name: &str, dep: &[&str]) where S: for<'c> System<'c> + Send + 'a { self.update_dispatcher.add(sys, name, dep); } pub fn with_update_barrier(mut self) -> Self { self.add_update_barrier(); self } pub fn add_update_barrier(&mut self) { self.update_dispatcher.add_barrier(); } pub fn with_scene_change_sys<S>(mut self, sys: S, name: &str, dep: &[&str]) -> Self where S: for<'c> System<'c> + Send + 'a { self.add_scene_change_sys(sys, name, dep); self } pub fn add_scene_change_sys<S>(&mut self, sys: S, name: &str, dep: &[&str]) where S: for<'c> System<'c> + Send + 'a { self.scene_change_handler.add_pre_load_sys(sys, name, dep); } pub fn with_scene_change_barrier(mut self) -> Self { self.add_scene_change_barrier(); self } pub fn add_scene_change_barrier(&mut self) { self.scene_change_handler.add_pre_load_barrier(); } pub fn with_physics_update_sys<S>(mut self, sys: S, name: &str, dep: &[&str]) -> Self where S: for<'c> System<'c> + Send + 'a { self.add_physics_update_sys(sys, name, dep); self } pub fn add_physics_update_sys<S>(&mut self, sys: S, name: &str, dep: &[&str]) where S: for<'c> System<'c> + Send + 'a { self.physics_update_dispatcher.add(sys, name, dep); } pub fn with_physics_update_barrier(mut self) -> Self { self.add_physics_update_barrier(); self } pub fn add_physics_update_barrier(&mut self) { self.physics_update_dispatcher.add_barrier(); } pub fn with_component<C: Component>(mut self) -> Self where <C as Component>::Storage: Default { self.add_component::<C>(); self } pub fn add_component<C: Component>(&mut self) where <C as Component>::Storage: Default { self.world.register::<C>(); } pub fn with_resource<T: Resource>(mut self, res: T) -> Self { self.add_resource(res); self } pub fn add_resource<T: Resource>(&mut self, res: T) { self.world.add_resource(res); } pub fn with_initial_sceneloader<T>(mut self, loader: T) -> Self where T: for<'l> SceneLoader<'l> + Send + Sync + 'static { self.set_initial_sceneloader(loader); self } pub fn set_initial_sceneloader<T>(&mut self, loader: T) where T: for<'l> SceneLoader<'l> + Send + Sync + 'static { self.world.write_resource::<SceneChange>().change_scene(loader); } pub fn build<'tex>(self) -> Engine<'a, 'b, 'tex> { let mut engine = Engine { world: self.world, update_dispatcher: self.update_dispatcher .with_barrier() .with(DrawLayersUpdater::default(), "", &[]) .with(DeleteSystem, "", &[]) .build(), scene_change_handler: self.scene_change_handler.build(), physics_update_dispatcher: self.physics_update_dispatcher .with_barrier() .with(DeleteSystem, "", &[]) .build(), window: super::open_window(), view: SfView::new(Vector2f::new(0., 0.), Vector2f::new(1., 1.)), clock: Clock::start(), max_physics_updates: self.max_physics_updates, draw_shapes: Vec::new(), sync_draw_shapes: Default::default(), draw_draw_shapes: Default::default(), }; { let mut view = engine.world.write_resource::<View>(); let win_sz = engine.window.size(); let ratio = win_sz.x as f32 / win_sz.y as f32; view.size.y = 2000.; view.size.x = ratio * view.size.y; view.copy_to(&mut engine.view); } engine.update_dispatcher.setup(&mut engine.world.res); engine.scene_change_handler.setup(&mut engine.world); engine.physics_update_dispatcher.setup(&mut engine.world.res); engine.sync_draw_shapes.setup_special(&mut engine.draw_shapes, &mut engine.world.res); engine.draw_draw_shapes.setup_special( (&mut engine.window, &mut engine.draw_shapes), &mut engine.world.res); engine } } pub struct Engine<'a, 'b, 'tex> { world: ::specs::World, update_dispatcher: ::specs::Dispatcher<'a, 'b>, scene_change_handler: SceneChangeHandler<'a, 'b>, physics_update_dispatcher: ::specs::Dispatcher<'a, 'b>, window: RenderWindow, view: SfBox<SfView>, clock: Clock, max_physics_updates: usize, draw_shapes: Vec<Option<SfShape<'tex>>>, sync_draw_shapes: SyncDrawShapesSystem, draw_draw_shapes: DrawDrawShapesSystem, } impl<'a, 'b, 'tex> Engine<'a, 'b, 'tex> { pub fn create_entity(&mut self) -> ::specs::world::EntityBuilder { self.world.create_entity() } pub fn run(mut self) { sigint::init(); self.clock.restart(); { let start = self.clock.elapsed_time(); let mut physt = self.world.write_resource::<PhysicsElapsed>(); physt.current = start; physt.previous = start - self.world.read_resource::<PhysicsDeltaTime>().0; let mut dt = self.world.write_resource::<DeltaTime>(); dt.0 = Time::milliseconds(5); let mut t = self.world.write_resource::<Elapsed>(); t.current = start; t.previous = start - dt.0; } while !sigint::received_sigint() { let now = self.clock.elapsed_time(); self.maybe_physics_update(now); self.update(now); self.draw(); } } fn maybe_physics_update(&mut self, now: Time) { for _ in 0..self.max_physics_updates { { let mut physt = self.world.write_resource::<PhysicsElapsed>(); if physt.current >= now { return; } let physdt = self.world.read_resource::<PhysicsDeltaTime>(); physt.previous = physt.current; physt.current += physdt.0; } self.physics_update_dispatcher.dispatch(&self.world.res); self.world.maintain(); self.scene_change_handler.handle_scene_change(&mut self.world); } let mut phys = self.world.write_resource::<PhysicsElapsed>(); let dphys = self.world.read_resource::<PhysicsDeltaTime>(); while phys.current < now { phys.previous = phys.current; phys.current += dphys.0; } } fn update(&mut self, now: Time) { { let mut elapsed = self.world.write_resource::<Elapsed>(); elapsed.previous = elapsed.current; elapsed.current = now; let mut delta = self.world.write_resource::<DeltaTime>(); delta.0 = elapsed.current - elapsed.previous; } self.update_dispatcher.dispatch(&self.world.res); self.world.maintain(); self.scene_change_handler.handle_scene_change(&mut self.world); } fn draw(&mut self) { self.sync_draw_shapes.run(&mut self.draw_shapes, &self.world.res); self.world.write_resource::<View>().copy_to(&mut self.view); self.window.clear(Color::BLACK); self.window.set_view(&self.view); for layer in 0..=DrawLayers::NUM_LAYERS { self.world.write_resource::<CurrentDrawLayer>().set_layer(layer); self.draw_draw_shapes.run((&mut self.window, &mut self.draw_shapes), &self.world.res); } self.window.display(); } }
pub fn new() -> Self { let thread_pool = Arc::new(ThreadPoolBuilder::new().build().unwrap()); Self { world: { let mut world = ::specs::World::new(); physics::register(&mut world); scene_management::register(&mut world); components::register_all(&mut world); resources::add_default_resources(&mut world); world }, update_dispatcher: ::specs::DispatcherBuilder::new() .with_pool(Arc::clone(&thread_pool)), scene_change_handler: SceneChangeHandlerBuilder::new() .with_threadpool(Arc::clone(&thread_pool)), physics_update_dispatcher: ::specs::DispatcherBuilder::new() .with_pool(thread_pool) .with(SetupNextPhysicsPosition, "", &[]) .with(ClearForceAccumulators, "", &[]) .with_barrier(), max_physics_updates: 5, } }
function_block-full_function
[ { "content": "pub trait SpecializedSystem<'a, T> {\n\n type SystemData: SystemData<'a>;\n\n\n\n fn run_special(&mut self, specialized: T, data: Self::SystemData);\n\n\n\n fn setup_special(&mut self, _specialized: T, res: &mut Resources) {\n\n Self::SystemData::setup(res);\n\n }\n\n}\n\n\n\npu...
Rust
src/clock_control/config.rs
reitermarkus/esp32-hal
95c7596c78a8e380b858d34f4f0ad1170a5b259a
use super::Error; use crate::prelude::*; use core::fmt; use super::{ dfs, CPUSource, ClockControlConfig, FastRTCSource, SlowRTCSource, CLOCK_CONTROL, CLOCK_CONTROL_MUTEX, }; impl<'a> super::ClockControlConfig { pub fn cpu_frequency(&self) -> Hertz { unsafe { CLOCK_CONTROL.as_ref().unwrap().cpu_frequency } } pub fn apb_frequency(&self) -> Hertz { unsafe { CLOCK_CONTROL.as_ref().unwrap().apb_frequency } } pub fn cpu_frequency_default(&self) -> Hertz { unsafe { CLOCK_CONTROL.as_ref().unwrap().cpu_frequency_default } } pub fn cpu_frequency_locked(&self) -> Hertz { unsafe { CLOCK_CONTROL.as_ref().unwrap().cpu_frequency_locked } } pub fn cpu_frequency_apb_locked(&self) -> Hertz { unsafe { CLOCK_CONTROL.as_ref().unwrap().cpu_frequency_apb_locked } } pub fn apb_frequency_apb_locked(&self) -> Hertz { unsafe { CLOCK_CONTROL.as_ref().unwrap().apb_frequency_apb_locked } } pub fn is_ref_clock_stable(&self) -> bool { unsafe { CLOCK_CONTROL.as_ref().unwrap().ref_clock_stable } } pub fn ref_frequency(&self) -> Hertz { unsafe { CLOCK_CONTROL.as_ref().unwrap().ref_frequency } } pub fn slow_rtc_frequency(&self) -> Hertz { unsafe { CLOCK_CONTROL.as_ref().unwrap().slow_rtc_frequency } } pub fn fast_rtc_frequency(&self) -> Hertz { unsafe { CLOCK_CONTROL.as_ref().unwrap().fast_rtc_frequency } } pub fn apll_frequency(&self) -> Hertz { unsafe { CLOCK_CONTROL.as_ref().unwrap().apll_frequency } } pub fn pll_d2_frequency(&self) -> Hertz { unsafe { CLOCK_CONTROL.as_ref().unwrap().pll_d2_frequency } } pub fn xtal_frequency(&self) -> Hertz { unsafe { CLOCK_CONTROL.as_ref().unwrap().xtal_frequency } } pub fn xtal32k_frequency(&self) -> Hertz { unsafe { CLOCK_CONTROL.as_ref().unwrap().xtal32k_frequency } } pub fn pll_frequency(&self) -> Hertz { unsafe { CLOCK_CONTROL.as_ref().unwrap().pll_frequency } } pub fn rtc8m_frequency(&self) -> Hertz { unsafe { CLOCK_CONTROL.as_ref().unwrap().rtc8m_frequency } } pub fn rtc8md256_frequency(&self) -> Hertz { unsafe { CLOCK_CONTROL.as_ref().unwrap().rtc8md256_frequency } } pub fn rtc_frequency(&self) -> Hertz { unsafe { CLOCK_CONTROL.as_ref().unwrap().rtc_frequency } } pub fn cpu_source(&self) -> CPUSource { unsafe { CLOCK_CONTROL.as_ref().unwrap().cpu_source } } pub fn slow_rtc_source(&self) -> SlowRTCSource { unsafe { CLOCK_CONTROL.as_ref().unwrap().slow_rtc_source } } pub fn fast_rtc_source(&self) -> FastRTCSource { unsafe { CLOCK_CONTROL.as_ref().unwrap().fast_rtc_source } } pub fn lock_cpu_frequency(&self) -> dfs::LockCPU { unsafe { CLOCK_CONTROL.as_mut().unwrap().lock_cpu_frequency() } } pub fn lock_apb_frequency(&self) -> dfs::LockAPB { unsafe { CLOCK_CONTROL.as_mut().unwrap().lock_apb_frequency() } } pub fn lock_awake(&self) -> dfs::LockAwake { unsafe { CLOCK_CONTROL.as_mut().unwrap().lock_awake() } } pub fn lock_plld2(&self) -> dfs::LockPllD2 { unsafe { CLOCK_CONTROL.as_mut().unwrap().lock_plld2() } } pub fn add_callback<F>(&self, f: &'static F) -> Result<(), Error> where F: Fn(), { unsafe { CLOCK_CONTROL.as_mut().unwrap().add_callback(f) } } pub fn get_lock_count(&self) -> dfs::Locks { unsafe { CLOCK_CONTROL.as_mut().unwrap().get_lock_count() } } pub unsafe fn park_core(&mut self, core: crate::Core) { (&CLOCK_CONTROL_MUTEX).lock(|_| { CLOCK_CONTROL.as_mut().unwrap().park_core(core); }) } pub fn unpark_core(&mut self, core: crate::Core) { (&CLOCK_CONTROL_MUTEX) .lock(|_| unsafe { CLOCK_CONTROL.as_mut().unwrap().unpark_core(core) }) } pub fn start_app_core(&mut self, entry: fn() -> !) -> Result<(), Error> { (&CLOCK_CONTROL_MUTEX) .lock(|_| unsafe { CLOCK_CONTROL.as_mut().unwrap().start_app_core(entry) }) } pub fn rtc_tick_count(&self) -> TicksU64 { unsafe { CLOCK_CONTROL.as_mut().unwrap().rtc_tick_count() } } pub fn rtc_nanoseconds(&self) -> NanoSecondsU64 { unsafe { CLOCK_CONTROL.as_mut().unwrap().rtc_nanoseconds() } } } impl fmt::Debug for ClockControlConfig { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { unsafe { CLOCK_CONTROL.as_ref().unwrap().fmt(f) } } }
use super::Error; use crate::prelude::*; use core::fmt; use super::{ dfs, CPUSource, ClockControlConfig, FastRTCSource, SlowRTCSource, CLOCK_CONTROL, CLOCK_CONTROL_MUTEX, }; impl<'a> super::ClockControlConfig { pub fn cpu_frequency(&self) -> Hertz { unsafe { CLOCK_CONTROL.as_ref().unwrap().cpu_frequency } } pub fn apb_frequency(&self) -> Hertz { unsafe { CLOCK_CONTROL.as_ref().unwrap().apb_frequency } } pub fn cpu_frequency_default(&self) -> Hertz { unsafe { CLOCK_CONTROL.as_ref().unwrap().cpu_frequency_default } } pub fn cpu_frequency_locked(&self) -> Hertz { unsafe { CLOCK_CONTROL.as_ref().unwrap().cpu_frequency_locked } } pub fn cpu_frequency_apb_locked(&self) -> Hertz { unsafe { CLOCK_CONTROL.as_ref().unwrap().cpu_frequency_apb_locked } } pub fn apb_frequency_apb_locked(&self) -> Hertz { unsafe { CLOCK_CONTROL.as_ref().unwrap().apb_frequency_apb_locked } } pub fn is_ref_clock_stable(&self) -> bool { unsafe { CLOCK_CONTROL.as_ref().unwrap().ref_clock_stable } } pub fn ref_frequency(&self) -> Hertz { unsafe { CLOCK_CONTROL.as_ref().unwrap().ref_frequency } } pub fn slow_rtc_frequency(&self) -> Hertz { unsafe { CLOCK_CONTROL.as_ref().unwrap().slow_rtc_frequency } } pub fn fast_rtc_frequency(&self) -> Hertz { unsafe { CLOCK_CONTROL.as_ref().unwrap().fast_rtc_frequency } } pub fn apll_frequency(&self) -> Hertz { unsafe { CLOCK_CONTROL.as_ref().unwrap().apll_frequency } } pub fn pll_d2_frequency(&self) -> Hertz { unsafe { CLOCK_CONTROL.as_ref().unwrap().pll_d2_frequency } } pub fn xtal_frequency(&self) -> Hertz { unsafe { CLOCK_CONTROL.as_ref().unwrap().xtal_frequency } } pub fn xtal32k_frequency(&self) -> Hertz { unsafe { CLOCK_CONTROL.as_ref().unwrap().xtal32k_frequency } } pub fn pll_frequency(&self) -> Hertz { unsafe { CLOCK_CONTROL.as_ref().unwrap().pll_frequency } } pub fn rtc8m_frequency(&self) -> Hertz { unsafe { CLOCK_CONTROL.as_ref().unwrap().rtc8m_frequency } } pub fn rtc8md256_frequency(&self) -> Hertz { unsafe { CLOCK_CONTROL.as_ref().unwrap().rtc8md256_frequency } } pub fn rtc_frequency(&self) -> Hertz { unsafe { CLOCK_CONTROL.as_ref().unwrap().rtc_frequency } } pub fn cpu_source(&self) -> CPUSource { unsafe { CLOCK_CONTROL.as_ref().unwrap().cpu_source } } pub fn slow_rtc_source(&self) -> SlowRTCSource { unsafe { CLOCK_CONTROL.as_ref().unwrap().slow_rtc_source } } pub fn fast_rtc_source(&self) -> FastRTCSource { unsafe { CLOCK_CONTROL.as_ref().unwrap().fast_rtc_source } } pub fn lock_cpu_frequency(&self) -> dfs::LockCPU { unsafe { CLOCK_CONTROL.as_mut().unwrap().lock_cpu_frequency() } } pub fn lock_apb_frequency(&self) -> dfs::LockAPB { unsafe { CLOCK_CONTROL.as_mut().unwrap().lock_apb_frequency() } } pub fn lock_awake(&self) -> dfs::LockAwake { unsafe { CLOCK_CONTROL.as_mut().unwrap().lock_awake() } } pub fn lock_plld2(&self) -> dfs::LockPllD2 { unsafe { CLOCK_CONTROL.as_mut().unwrap().lock_plld2() } } pub fn add_callback<F>(&self, f: &'static F) -> Result<(), Error>
{ CLOCK_CONTROL.as_mut().unwrap().rtc_nanoseconds() } } } impl fmt::Debug for ClockControlConfig { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { unsafe { CLOCK_CONTROL.as_ref().unwrap().fmt(f) } } }
where F: Fn(), { unsafe { CLOCK_CONTROL.as_mut().unwrap().add_callback(f) } } pub fn get_lock_count(&self) -> dfs::Locks { unsafe { CLOCK_CONTROL.as_mut().unwrap().get_lock_count() } } pub unsafe fn park_core(&mut self, core: crate::Core) { (&CLOCK_CONTROL_MUTEX).lock(|_| { CLOCK_CONTROL.as_mut().unwrap().park_core(core); }) } pub fn unpark_core(&mut self, core: crate::Core) { (&CLOCK_CONTROL_MUTEX) .lock(|_| unsafe { CLOCK_CONTROL.as_mut().unwrap().unpark_core(core) }) } pub fn start_app_core(&mut self, entry: fn() -> !) -> Result<(), Error> { (&CLOCK_CONTROL_MUTEX) .lock(|_| unsafe { CLOCK_CONTROL.as_mut().unwrap().start_app_core(entry) }) } pub fn rtc_tick_count(&self) -> TicksU64 { unsafe { CLOCK_CONTROL.as_mut().unwrap().rtc_tick_count() } } pub fn rtc_nanoseconds(&self) -> NanoSecondsU64 { unsafe
random
[ { "content": "#[ram]\n\npub fn enable(interrupt: Interrupt) -> Result<(), Error> {\n\n match interrupt_to_cpu_interrupt(interrupt) {\n\n Ok(cpu_interrupt) => {\n\n unsafe { interrupt::enable_mask(1 << cpu_interrupt.0) };\n\n return Ok(());\n\n }\n\n Err(_) => enable...
Rust
src/lib.rs
gimli-rs/cpp_demangle
a8afba1db064469278c4530ad9bad28ec4d6c161
#![deny(missing_docs)] #![deny(missing_debug_implementations)] #![deny(unsafe_code)] #![allow(unknown_lints)] #![allow(clippy::inline_always)] #![allow(clippy::redundant_field_names)] #![cfg_attr(all(not(feature = "std"), feature = "alloc"), no_std)] #![cfg_attr(all(not(feature = "std"), feature = "alloc"), feature(alloc))] #[macro_use] extern crate cfg_if; cfg_if! { if #[cfg(all(not(feature = "std"), feature = "alloc"))] { extern crate core as std; #[macro_use] extern crate alloc; mod imports { pub use alloc::boxed; pub use alloc::vec; pub use alloc::string; pub use alloc::borrow; pub use alloc::collections::btree_map; } } else { mod imports { pub use std::boxed; pub use std::vec; pub use std::string; pub use std::borrow; pub use std::collections::btree_map; } } } use imports::*; use string::String; use vec::Vec; #[macro_use] mod logging; pub mod ast; pub mod error; mod index_str; mod subs; use ast::{Demangle, Parse, ParseContext}; use error::{Error, Result}; use index_str::IndexStr; use std::fmt; use std::num::NonZeroU32; #[derive(Clone, Copy, Debug, Default)] #[repr(C)] pub struct ParseOptions { recursion_limit: Option<NonZeroU32>, } impl ParseOptions { pub fn recursion_limit(mut self, limit: u32) -> Self { self.recursion_limit = Some(NonZeroU32::new(limit).expect("Recursion limit must be > 0")); self } } #[derive(Clone, Copy, Debug, Default)] #[repr(C)] pub struct DemangleOptions { no_params: bool, no_return_type: bool, recursion_limit: Option<NonZeroU32>, } impl DemangleOptions { pub fn new() -> Self { Default::default() } pub fn no_params(mut self) -> Self { self.no_params = true; self } pub fn no_return_type(mut self) -> Self { self.no_return_type = true; self } pub fn recursion_limit(mut self, limit: u32) -> Self { self.recursion_limit = Some(NonZeroU32::new(limit).expect("Recursion limit must be > 0")); self } } pub type OwnedSymbol = Symbol<Vec<u8>>; pub type BorrowedSymbol<'a> = Symbol<&'a [u8]>; #[derive(Clone, Debug, PartialEq)] pub struct Symbol<T> { raw: T, substitutions: subs::SubstitutionTable, parsed: ast::MangledName, } impl<T> Symbol<T> where T: AsRef<[u8]>, { #[inline] pub fn new(raw: T) -> Result<Symbol<T>> { Self::new_with_options(raw, &Default::default()) } pub fn new_with_options(raw: T, options: &ParseOptions) -> Result<Symbol<T>> { let mut substitutions = subs::SubstitutionTable::new(); let parsed = { let ctx = ParseContext::new(*options); let input = IndexStr::new(raw.as_ref()); let (parsed, tail) = ast::MangledName::parse(&ctx, &mut substitutions, input)?; debug_assert!(ctx.recursion_level() == 0); if tail.is_empty() { parsed } else { return Err(Error::UnexpectedText); } }; let symbol = Symbol { raw: raw, substitutions: substitutions, parsed: parsed, }; log!( "Successfully parsed '{}' as AST = {:#?} substitutions = {:#?}", String::from_utf8_lossy(symbol.raw.as_ref()), symbol.parsed, symbol.substitutions ); Ok(symbol) } #[allow(clippy::trivially_copy_pass_by_ref)] pub fn demangle(&self, options: &DemangleOptions) -> ::std::result::Result<String, fmt::Error> { let mut out = String::new(); { let mut ctx = ast::DemangleContext::new( &self.substitutions, self.raw.as_ref(), *options, &mut out, ); self.parsed.demangle(&mut ctx, None)?; } Ok(out) } #[allow(clippy::trivially_copy_pass_by_ref)] pub fn structured_demangle<W: DemangleWrite>( &self, out: &mut W, options: &DemangleOptions, ) -> fmt::Result { let mut ctx = ast::DemangleContext::new(&self.substitutions, self.raw.as_ref(), *options, out); self.parsed.demangle(&mut ctx, None) } } #[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)] pub enum DemangleNodeType { Prefix, TemplatePrefix, TemplateArgs, UnqualifiedName, TemplateParam, Decltype, DataMemberPrefix, NestedName, VirtualTable, __NonExhaustive, } pub trait DemangleWrite { fn push_demangle_node(&mut self, _: DemangleNodeType) {} fn write_string(&mut self, s: &str) -> fmt::Result; fn pop_demangle_node(&mut self) {} } impl<W: fmt::Write> DemangleWrite for W { fn write_string(&mut self, s: &str) -> fmt::Result { fmt::Write::write_str(self, s) } } impl<'a, T> Symbol<&'a T> where T: AsRef<[u8]> + ?Sized, { #[inline] pub fn with_tail(input: &'a T) -> Result<(BorrowedSymbol<'a>, &'a [u8])> { Self::with_tail_and_options(input, &Default::default()) } pub fn with_tail_and_options( input: &'a T, options: &ParseOptions, ) -> Result<(BorrowedSymbol<'a>, &'a [u8])> { let mut substitutions = subs::SubstitutionTable::new(); let ctx = ParseContext::new(*options); let idx_str = IndexStr::new(input.as_ref()); let (parsed, tail) = ast::MangledName::parse(&ctx, &mut substitutions, idx_str)?; debug_assert!(ctx.recursion_level() == 0); let symbol = Symbol { raw: input.as_ref(), substitutions: substitutions, parsed: parsed, }; log!( "Successfully parsed '{}' as AST = {:#?} substitutions = {:#?}", String::from_utf8_lossy(symbol.raw), symbol.parsed, symbol.substitutions ); Ok((symbol, tail.into())) } } impl<T> fmt::Display for Symbol<T> where T: AsRef<[u8]>, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let mut out = String::new(); { let options = DemangleOptions::default(); let mut ctx = ast::DemangleContext::new( &self.substitutions, self.raw.as_ref(), options, &mut out, ); self.parsed.demangle(&mut ctx, None).map_err(|err| { log!("Demangling error: {:#?}", err); fmt::Error })?; } write!(f, "{}", &out) } }
#![deny(missing_docs)] #![deny(missing_debug_implementations)] #![deny(unsafe_code)] #![allow(unknown_lints)] #![allow(clippy::inline_always)] #![allow(clippy::redundant_field_names)] #![cfg_attr(all(not(feature = "std"), feature = "alloc"), no_std)] #![cfg_attr(all(not(feature = "std"), feature = "alloc"), feature(alloc))] #[macro_use] extern crate cfg_if; cfg_if! { if #[cfg(all(not(feature = "std"), feature = "alloc"))] { extern crate core as std; #[macro_use] extern crate alloc; mod imports { pub use alloc::boxed; pub use alloc::vec; pub use alloc::string; pub use alloc::borrow; pub use alloc::collections::btree_map; } } else { mod imports { pub use std::boxed; pub use std::vec; pub use std::string; pub use std::borrow; pub use std::collections::btree_map; } } } use imports::*; use string::String; use vec::Vec; #[macro_use] mod logging; pub mod ast; pub mod error; mod index_str; mod subs; use ast::{Demangle, Parse, ParseContext}; use error::{Error, Result}; use index_str::IndexStr; use std::fmt; use std::num::NonZeroU32; #[derive(Clone, Copy, Debug, Default)] #[repr(C)] pub struct ParseOptions { recursion_limit: Option<NonZeroU32>, } impl ParseOptions { pub fn recursion_limit(mut self, limit: u32) -> Self { self.recursion_limit = Some(NonZeroU32::new(limit).expect("Recursion limit must be > 0")); self } } #[derive(Clone, Copy, Debug, Default)] #[repr(C)] pub struct DemangleOptions { no_params: bool, no_return_type: bool, recursion_limit: Option<NonZeroU32>, } impl DemangleOptions { pub fn new() -> Self { Default::default() } pub fn no_params(mut self) -> Self { self.no_params = true; self } pub fn no_return_type(mut self) -> Self { self.no_return_type = true; self } pub fn recursion_limit(mut self, limit: u32) -> Self { self.recursion_limit = Some(NonZeroU32::new(limit).expect("Recursion limit must be > 0")); self } } pub type OwnedSymbol = Symbol<Vec<u8>>; pub type BorrowedSymbol<'a> = Symbol<&'a [u8]>; #[derive(Clone, Debug, PartialEq)] pub struct Symbol<T> { raw: T, substitutions: subs::SubstitutionTable, parsed: ast::MangledName, } impl<T> Symbol<T> where T: AsRef<[u8]>, { #[inline] pub fn new(raw: T) -> Result<Symbol<T>> { Self::new_with_options(raw, &Default::default()) } pub fn new_with_options(raw: T, options: &ParseOptions) -> Result<Symbol<T>> { let mut substitutions = subs::SubstitutionTable::new(); let parsed = { let ctx = ParseContext::new(*options); let input = IndexStr::new(raw.as_ref()); let (parsed, tail) = ast::MangledName::parse(&ctx, &mut substitutions, input)?; debug_assert!(ctx.recursion_level() == 0);
}; let symbol = Symbol { raw: raw, substitutions: substitutions, parsed: parsed, }; log!( "Successfully parsed '{}' as AST = {:#?} substitutions = {:#?}", String::from_utf8_lossy(symbol.raw.as_ref()), symbol.parsed, symbol.substitutions ); Ok(symbol) } #[allow(clippy::trivially_copy_pass_by_ref)] pub fn demangle(&self, options: &DemangleOptions) -> ::std::result::Result<String, fmt::Error> { let mut out = String::new(); { let mut ctx = ast::DemangleContext::new( &self.substitutions, self.raw.as_ref(), *options, &mut out, ); self.parsed.demangle(&mut ctx, None)?; } Ok(out) } #[allow(clippy::trivially_copy_pass_by_ref)] pub fn structured_demangle<W: DemangleWrite>( &self, out: &mut W, options: &DemangleOptions, ) -> fmt::Result { let mut ctx = ast::DemangleContext::new(&self.substitutions, self.raw.as_ref(), *options, out); self.parsed.demangle(&mut ctx, None) } } #[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)] pub enum DemangleNodeType { Prefix, TemplatePrefix, TemplateArgs, UnqualifiedName, TemplateParam, Decltype, DataMemberPrefix, NestedName, VirtualTable, __NonExhaustive, } pub trait DemangleWrite { fn push_demangle_node(&mut self, _: DemangleNodeType) {} fn write_string(&mut self, s: &str) -> fmt::Result; fn pop_demangle_node(&mut self) {} } impl<W: fmt::Write> DemangleWrite for W { fn write_string(&mut self, s: &str) -> fmt::Result { fmt::Write::write_str(self, s) } } impl<'a, T> Symbol<&'a T> where T: AsRef<[u8]> + ?Sized, { #[inline] pub fn with_tail(input: &'a T) -> Result<(BorrowedSymbol<'a>, &'a [u8])> { Self::with_tail_and_options(input, &Default::default()) } pub fn with_tail_and_options( input: &'a T, options: &ParseOptions, ) -> Result<(BorrowedSymbol<'a>, &'a [u8])> { let mut substitutions = subs::SubstitutionTable::new(); let ctx = ParseContext::new(*options); let idx_str = IndexStr::new(input.as_ref()); let (parsed, tail) = ast::MangledName::parse(&ctx, &mut substitutions, idx_str)?; debug_assert!(ctx.recursion_level() == 0); let symbol = Symbol { raw: input.as_ref(), substitutions: substitutions, parsed: parsed, }; log!( "Successfully parsed '{}' as AST = {:#?} substitutions = {:#?}", String::from_utf8_lossy(symbol.raw), symbol.parsed, symbol.substitutions ); Ok((symbol, tail.into())) } } impl<T> fmt::Display for Symbol<T> where T: AsRef<[u8]>, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let mut out = String::new(); { let options = DemangleOptions::default(); let mut ctx = ast::DemangleContext::new( &self.substitutions, self.raw.as_ref(), options, &mut out, ); self.parsed.demangle(&mut ctx, None).map_err(|err| { log!("Demangling error: {:#?}", err); fmt::Error })?; } write!(f, "{}", &out) } }
if tail.is_empty() { parsed } else { return Err(Error::UnexpectedText); }
if_condition
[ { "content": "#[allow(unsafe_code)]\n\nfn parse_number(base: u32, allow_signed: bool, mut input: IndexStr) -> Result<(isize, IndexStr)> {\n\n if input.is_empty() {\n\n return Err(error::Error::UnexpectedEnd);\n\n }\n\n\n\n let num_is_negative = if allow_signed && input.as_ref()[0] == b'n' {\n\n ...
Rust
crates/nodes/src/logic_data.rs
gents83/NRG
62743a54ac873a8dea359f3816e24c189a323ebb
use sabi_serialize::{Deserialize, Serialize, SerializeFile}; use crate::{LogicContext, LogicExecution, NodeExecutionType, NodeState, NodeTree, PinId}; #[derive(Default, PartialEq, Eq, Hash, Clone)] struct LinkInfo { node: usize, pin: PinId, } #[derive(Default, Clone)] struct PinInfo { id: PinId, links: Vec<LinkInfo>, } #[derive(Default, Clone)] struct NodeInfo { inputs: Vec<PinInfo>, outputs: Vec<PinInfo>, } #[derive(Default, Serialize, Deserialize, Clone)] #[serde(crate = "sabi_serialize")] pub struct LogicData { #[serde(flatten)] tree: NodeTree, #[serde(skip)] active_nodes: Vec<LinkInfo>, #[serde(skip)] nodes_info: Vec<NodeInfo>, #[serde(skip)] execution_state: Vec<NodeState>, #[serde(skip)] context: LogicContext, } impl SerializeFile for LogicData { fn extension() -> &'static str { "logic" } } impl From<NodeTree> for LogicData { fn from(tree: NodeTree) -> Self { Self { tree, active_nodes: Vec::new(), nodes_info: Vec::new(), execution_state: Vec::new(), context: LogicContext::default(), } } } impl LogicData { pub fn context(&self) -> &LogicContext { &self.context } pub fn context_mut(&mut self) -> &mut LogicContext { &mut self.context } pub fn is_initialized(&self) -> bool { !self.execution_state.is_empty() } pub fn init(&mut self) { let nodes = self.tree.nodes(); nodes.iter().enumerate().for_each(|(node_index, n)| { if !n.node().has_input::<LogicExecution>() && n.node().has_output::<LogicExecution>() { self.active_nodes.push(LinkInfo { node: node_index, pin: PinId::invalid(), }); } let mut node_info = NodeInfo::default(); n.node().inputs().iter().for_each(|(id, _)| { let mut pin_info = PinInfo { id: id.clone(), ..Default::default() }; let links = self.tree.get_links_to_pin(n.name(), id.name()); links.iter().for_each(|l| { if let Some(from_node_index) = self.tree.find_node_index(l.from_node()) { if let Some((from_pin_id, _)) = nodes[from_node_index] .node() .outputs() .iter() .find(|(id, _)| id.name() == l.from_pin()) { let link_info = LinkInfo { node: from_node_index, pin: from_pin_id.clone(), }; pin_info.links.push(link_info); } else { eprintln!( "Unable to find output pin {} of node {}", l.from_pin(), nodes[from_node_index].name() ); } } }); node_info.inputs.push(pin_info); }); n.node().outputs().iter().for_each(|(id, _)| { let mut pin_info = PinInfo { id: id.clone(), ..Default::default() }; let links = self.tree.get_links_from_pin(n.name(), id.name()); links.iter().for_each(|l| { if let Some(to_node_index) = self.tree.find_node_index(l.to_node()) { if let Some((to_pin_id, _)) = nodes[to_node_index] .node() .inputs() .iter() .find(|(id, _)| id.name() == l.to_pin()) { let link_info = LinkInfo { node: to_node_index, pin: to_pin_id.clone(), }; pin_info.links.push(link_info); } else { eprintln!( "Unable to find input pin {} of node {}", l.to_pin(), nodes[to_node_index].name() ); } } }); node_info.outputs.push(pin_info); }); self.nodes_info.push(node_info); }); self.execution_state.resize(nodes.len(), NodeState::Active); } pub fn execute(&mut self) { self.execute_active_nodes(self.active_nodes.clone()); } fn execute_active_nodes(&mut self, mut nodes_to_execute: Vec<LinkInfo>) { if nodes_to_execute.is_empty() { return; } let mut new_nodes = Vec::new(); nodes_to_execute.iter().for_each(|l| { let mut nodes = Self::execute_node( &mut self.tree, &self.context, l, &self.nodes_info, &mut self.execution_state, ); new_nodes.append(&mut nodes); }); nodes_to_execute.retain(|link_info| { let node_state = &self.execution_state[link_info.node]; match node_state { NodeState::Active => true, NodeState::Running(_) => { if !self.active_nodes.contains(link_info) { self.active_nodes.push(link_info.clone()); } false } NodeState::Executed(_) => false, } }); new_nodes.iter().for_each(|l| { if self.execution_state[l.node] == NodeState::Active && !nodes_to_execute.contains(l) { nodes_to_execute.push(l.clone()); } }); self.active_nodes.retain(|l| { self.tree.nodes()[l.node].execytion_type() != NodeExecutionType::OneShot || self.tree.nodes()[l.node].execytion_type() == NodeExecutionType::Continuous }); self.execute_active_nodes(nodes_to_execute); } fn execute_node( tree: &mut NodeTree, context: &LogicContext, link_info: &LinkInfo, nodes_info: &[NodeInfo], execution_state: &mut [NodeState], ) -> Vec<LinkInfo> { let mut new_nodes_to_execute = Vec::new(); let info = &nodes_info[link_info.node]; info.inputs.iter().for_each(|pin_info| { let node = tree.nodes_mut()[link_info.node].node(); if node.is_input::<LogicExecution>(&pin_info.id) { return; } pin_info.links.iter().for_each(|l| { if execution_state[l.node] == NodeState::Active { let mut nodes = Self::execute_node(tree, context, l, nodes_info, execution_state); new_nodes_to_execute.append(&mut nodes); } let nodes = tree.nodes_mut(); let (from_node, to_node) = if l.node < link_info.node { let (start, end) = nodes.split_at_mut(link_info.node); (start[l.node].node(), end[0].node_mut()) } else { let (start, end) = nodes.split_at_mut(l.node); (end[0].node(), start[link_info.node].node_mut()) }; if let Some(input) = to_node.inputs_mut().get_mut(&pin_info.id) { input.copy_from(from_node, &l.pin); } }); }); let node = &mut tree.nodes_mut()[link_info.node]; execution_state[link_info.node] = node.execute(&link_info.pin, context); match &execution_state[link_info.node] { NodeState::Executed(output_pins) | NodeState::Running(output_pins) => { if let Some(pins) = output_pins { pins.iter().for_each(|pin_id| { info.outputs.iter().for_each(|o| { if pin_id == &o.id { o.links.iter().for_each(|link_info| { new_nodes_to_execute.push(link_info.clone()); }); } }); }); } } _ => {} } new_nodes_to_execute } }
use sabi_serialize::{Deserialize, Serialize, SerializeFile}; use crate::{LogicContext, LogicExecution, NodeExecutionType, NodeState, NodeTree, PinId}; #[derive(Default, PartialEq, Eq, Hash, Clone)] struct LinkInfo { node: usize, pin: PinId, } #[derive(Default, Clone)] struct PinInfo { id: PinId, links: Vec<LinkInfo>, } #[derive(Default, Clone)] struct NodeInfo { inputs: Vec<PinInfo>, outputs: Vec<PinInfo>, } #[derive(Default, Serialize, Deserialize, Clone)] #[serde(crate = "sabi_serialize")] pub struct LogicData { #[serde(flatten)] tree: NodeTree, #[serde(skip)] active_nodes: Vec<LinkInfo>, #[serde(skip)] nodes_info: Vec<NodeInfo>, #[serde(skip)] execution_state: Vec<NodeState>, #[serde(skip)] context: LogicContext, } impl SerializeFile for LogicData { fn extension() -> &'static str { "logic" } } impl From<NodeTree> for LogicData { fn from(tree: NodeTree) -> Self { Self { tree, active_nodes: Vec::new(), nodes_info: Vec::new(), execution_state: Vec::new(), context: LogicContext::default(), } } } impl LogicData { pub fn context(&self) -> &LogicContext { &self.context } pub fn context_mut(&mut self) -> &mut LogicContext { &mut self.context } pub fn is_initialized(&self) -> bool { !self.execution_state.is_empty() } pub fn init(&mut self) { let nodes = self.tree.nodes(); nodes.iter().enumerate().for_each(|(node_index, n)| { if !n.node().has_input::<LogicExecution>() && n.node().has_output::<LogicExecution>() { self.active_nodes.push(LinkInfo { node: node_index, pin: PinId::invalid(), }); } let mut node_info = NodeInfo::default(); n.node().inputs().iter().for_each(|(id, _)| { let mut pin_info = PinInfo { id: id.clone(), ..Default::default() }; let links = self.tree.get_links_to_pin(n.name(), id.name()); links.iter().for_each(|l| { if let Some(from_node_index) = self.tree.find_node_index(l.from_node()) { if let Some((from_pin_id, _)) = nodes[from_node_index] .node() .outputs() .iter() .find(|(id, _)| id.name() == l.from_pin()) { let link_info = LinkInfo { node: from_node_index, pin: from_pin_id.clone(), }; pin_info.links.push(link_info); } else { eprintln!( "Unable to find output pin {} of node {}", l.from_pin(), nodes[from_node_index].name() ); } } }); node_info.inputs.push(pin_info); }); n.node().outputs().iter().for_each(|(id, _)| { let mut pin_info = PinInfo { id: id.clone(), ..Default::default() }; let links = self.tree.get_links_from_pin(n.name(), id.name()); links.iter().for_each(|l| { if let Some(to_node_index) = self.tree.find_node_index(l.to_node()) { if let Some((to_pin_id, _)) = nodes[to_node_index] .node() .inputs() .iter() .find(|(id, _)| id.name() == l.to_pin()) { let link_info = LinkInfo { node: to_node_index, pin: to_pin_id.clone(), }; pin_info.links.push(link_info); } else { eprintln!( "Unable to find input pin {} of node {}", l.to_pin(), nodes[to_node_index].name() ); } } }); node_info.outputs.push(pin_info); }); self.nodes_info.push(node_info); }); self.execution_state.resize(nodes.len(), NodeState::Active); } pub fn execute(&mut self) { self.execute_active_nodes(self.active_nodes.clone()); } fn execute_active_nodes(&mut self, mut nodes_to_execute: Vec<LinkInfo>) { if nodes_to_execute.is_empty() { return; } let mut new_nodes = Vec::new(); nodes_to_execute.iter().for_each(|l| { let mut nodes = Self::execute_node( &mut self.tree, &self.context, l, &self.nodes_info, &mut self.execution_state, ); new_nodes.append(&mut nodes); }); nodes_to_execute.retain(|link_info| { let node_state = &self.execution_state[link_info.node]; match node_state { NodeState::Active => true, NodeState::Running(_) => { if !self.active_nodes.contains(link_info) { self.active_nodes.push(link_info.clone()); } false } NodeState::Executed(_) => false, } }); new_nodes.iter().for_each(|l| { if self.execution_state[l.node] == NodeState::Active && !nodes_to_execute.contains(l) { nodes_to_execute.push(l.clone()); } }); self.active_nodes.retain(|l| { self.tree.nodes()[l.node].execytion_type() != NodeExecutionType::OneShot || self.tree.nodes()[l.node].execytion_type() == NodeExecutionType::Continuous }); self.execute_active_nodes(nodes_to_execute); }
}
fn execute_node( tree: &mut NodeTree, context: &LogicContext, link_info: &LinkInfo, nodes_info: &[NodeInfo], execution_state: &mut [NodeState], ) -> Vec<LinkInfo> { let mut new_nodes_to_execute = Vec::new(); let info = &nodes_info[link_info.node]; info.inputs.iter().for_each(|pin_info| { let node = tree.nodes_mut()[link_info.node].node(); if node.is_input::<LogicExecution>(&pin_info.id) { return; } pin_info.links.iter().for_each(|l| { if execution_state[l.node] == NodeState::Active { let mut nodes = Self::execute_node(tree, context, l, nodes_info, execution_state); new_nodes_to_execute.append(&mut nodes); } let nodes = tree.nodes_mut(); let (from_node, to_node) = if l.node < link_info.node { let (start, end) = nodes.split_at_mut(link_info.node); (start[l.node].node(), end[0].node_mut()) } else { let (start, end) = nodes.split_at_mut(l.node); (end[0].node(), start[link_info.node].node_mut()) }; if let Some(input) = to_node.inputs_mut().get_mut(&pin_info.id) { input.copy_from(from_node, &l.pin); } }); }); let node = &mut tree.nodes_mut()[link_info.node]; execution_state[link_info.node] = node.execute(&link_info.pin, context); match &execution_state[link_info.node] { NodeState::Executed(output_pins) | NodeState::Running(output_pins) => { if let Some(pins) = output_pins { pins.iter().for_each(|pin_id| { info.outputs.iter().for_each(|o| { if pin_id == &o.id { o.links.iter().for_each(|link_info| { new_nodes_to_execute.push(link_info.clone()); }); } }); }); } } _ => {} } new_nodes_to_execute }
function_block-full_function
[]
Rust
components/resource_metering/src/recorder/cpu.rs
lroolle/tikv
f3f02d7fc6cf7e94abcf8cdb9b9ff52b110a72ba
use crate::localstorage::LocalStorage; use crate::recorder::SubRecorder; use crate::utils; use crate::utils::Stat; use crate::{RawRecord, RawRecords, SharedTagPtr}; use collections::HashMap; use fail::fail_point; use lazy_static::lazy_static; lazy_static! { static ref STAT_TASK_COUNT: prometheus::IntCounter = prometheus::register_int_counter!( "tikv_req_cpu_stat_task_count", "Counter of stat_task call" ) .unwrap(); } #[derive(Default)] pub struct CpuRecorder { thread_stats: HashMap<usize, ThreadStat>, } impl SubRecorder for CpuRecorder { fn tick(&mut self, records: &mut RawRecords, _: &mut HashMap<usize, LocalStorage>) { let records = &mut records.records; self.thread_stats.iter_mut().for_each(|(tid, thread_stat)| { let cur_tag = thread_stat.shared_ptr.take_clone(); fail_point!( "cpu-record-test-filter", cur_tag.as_ref().map_or(false, |t| !t .infos .extra_attachment .starts_with(crate::TEST_TAG_PREFIX)), |_| {} ); if let Some(cur_tag) = cur_tag { if let Ok(cur_stat) = utils::stat_task(utils::process_id(), *tid) { STAT_TASK_COUNT.inc(); let last_stat = &thread_stat.stat; let last_cpu_tick = last_stat.utime.wrapping_add(last_stat.stime); let cur_cpu_tick = cur_stat.utime.wrapping_add(cur_stat.stime); let delta_ticks = cur_cpu_tick.wrapping_sub(last_cpu_tick); if delta_ticks > 0 { let delta_ms = delta_ticks * 1_000 / utils::clock_tick(); let record = records.entry(cur_tag).or_insert_with(RawRecord::default); record.cpu_time += delta_ms as u32; } thread_stat.stat = cur_stat; } } }); } fn cleanup(&mut self) { const THREAD_STAT_LEN_THRESHOLD: usize = 500; if self.thread_stats.capacity() > THREAD_STAT_LEN_THRESHOLD && self.thread_stats.len() < THREAD_STAT_LEN_THRESHOLD / 2 { self.thread_stats.shrink_to(THREAD_STAT_LEN_THRESHOLD); } } fn reset(&mut self) { for (thread_id, stat) in &mut self.thread_stats { stat.stat = utils::stat_task(utils::process_id(), *thread_id).unwrap_or_default(); } } fn thread_created(&mut self, id: usize, shared_ptr: SharedTagPtr) { self.thread_stats.insert( id, ThreadStat { shared_ptr, stat: Stat::default(), }, ); } } struct ThreadStat { shared_ptr: SharedTagPtr, stat: Stat, } #[cfg(test)] #[cfg(not(target_os = "linux"))] mod tests { use super::*; #[test] fn test_record() { let mut recorder = CpuRecorder::default(); let mut records = RawRecords::default(); recorder.tick(&mut records, &mut HashMap::default()); assert!(records.records.is_empty()); } } #[cfg(test)] #[cfg(target_os = "linux")] mod tests { use super::*; use crate::{utils, RawRecords, TagInfos}; use std::sync::atomic::AtomicPtr; use std::sync::Arc; fn heavy_job() -> u64 { let m: u64 = rand::random(); let n: u64 = rand::random(); let m = m ^ n; let n = m.wrapping_mul(n); let m = m.wrapping_add(n); let n = m & n; let m = m | n; m.wrapping_sub(n) } #[test] fn test_record() { let info = Arc::new(TagInfos { store_id: 0, region_id: 0, peer_id: 0, extra_attachment: b"abc".to_vec(), }); let shared_ptr = SharedTagPtr { ptr: Arc::new(AtomicPtr::new(Arc::into_raw(info) as _)), }; let mut recorder = CpuRecorder::default(); recorder.thread_created(utils::thread_id(), shared_ptr); let thread_id = utils::thread_id(); let prev_stat = &recorder.thread_stats.get(&thread_id).unwrap().stat; let prev_cpu_ticks = prev_stat.utime.wrapping_add(prev_stat.stime); loop { let stat = utils::stat_task(utils::process_id(), thread_id).unwrap(); let cpu_ticks = stat.utime.wrapping_add(stat.stime); let delta_ms = cpu_ticks.wrapping_sub(prev_cpu_ticks) * 1_000 / utils::clock_tick(); if delta_ms != 0 { break; } heavy_job(); } let mut records = RawRecords::default(); recorder.tick(&mut records, &mut HashMap::default()); assert!(!records.records.is_empty()); } }
use crate::localstorage::LocalStorage; use crate::recorder::SubRecorder; use crate::utils; use crate::utils::Stat; use crate::{RawRecord, RawRecords, SharedTagPtr}; use collections::HashMap; use fail::fail_point; use lazy_static::lazy_static; lazy_static! { static ref STAT_TASK_COUNT: prometheus::IntCounter = prometheus::register_int_counter!( "tikv_req_cpu_stat_task_count", "Counter of stat_task call" ) .unwrap(); } #[derive(Default)] pub struct CpuRecorder { thread_stats: HashMap<usize, ThreadStat>, } impl SubRecorder for CpuRecorder { fn tick(&mut self, records: &mut RawRecords, _: &mut HashMap<usize, LocalStorage>) { let records = &mut records.records; self.thread_stats.iter_mut().for_each(|(tid, thread_stat)| { let cur_tag = thread_stat.shared_ptr.take_clone(); fail_point!( "cpu-record-test-filter", cur_tag.as_ref().map_or(false, |t| !t .infos .extra_attachment .starts_with(crate::TEST_TAG_PREFIX)), |_| {} ); if let Some(cur_tag) = cur_tag { if let Ok(cur_stat) = utils::stat_task(utils::process_id(), *tid) { STAT_TASK_COUNT.inc(); let last_stat = &thread_stat.stat; let last_cpu_tick = last_stat.utime.wrapping_add(last_stat.stime); let cur_cpu_tick = cur_stat.utime.wrapping_add(cur_stat.stime); let delta_ticks = cur_cpu_tick.wrapping_sub(last_cpu_tick); if delta_ticks > 0 { let delta_ms = delta_ticks * 1_000 / utils::clock_tick(); let record = records.entry(cur_tag).or_insert_with(RawRecord::default); record.cpu_time += delta_ms as u32; } thread_stat.stat = cur_stat; } } }); } fn cleanup(&mut self) { const THREAD_STAT_LEN_THRESHOLD: usize = 500; if self.thread_stats.capacity() > THREAD_STAT_LEN_THRESHOLD && self.thread_stats.len() < THREAD_STAT_LEN_THRESHOLD / 2 { self.thread_stats.shrink_to(THREAD_STAT_LEN_THRESHOLD); } } fn reset(&mut self) { for (thread_id, stat) in &mut self.thread_stats { stat.stat = utils::stat_task(utils::process_id(), *thread_id).unwrap_or_default(); } } fn thread_created(&mut self, id: usize, shared_ptr: SharedTagPtr) { self.thread_stats.insert( id, ThreadStat { shared_ptr, stat: Stat::default(), }, ); } } struct ThreadStat { shared_ptr: SharedTagPtr, stat: Stat, } #[cfg(test)] #[cfg(not(target_os = "linux"))] mod tests { use super::*; #[test] fn test_record() { let mut recorder = CpuRecorder::default(); let mut records = RawRecords::default(); recorder.tick(&mut records, &mut HashMap::default()); assert!(records.records.is_empty()); } } #[cfg(test)] #[cfg(target_os = "linux")] mod tests { use super::*; use crate::{utils, RawRecords, TagInfos}; use std::sync::atomic::AtomicPtr; use std::sync::Arc;
#[test] fn test_record() { let info = Arc::new(TagInfos { store_id: 0, region_id: 0, peer_id: 0, extra_attachment: b"abc".to_vec(), }); let shared_ptr = SharedTagPtr { ptr: Arc::new(AtomicPtr::new(Arc::into_raw(info) as _)), }; let mut recorder = CpuRecorder::default(); recorder.thread_created(utils::thread_id(), shared_ptr); let thread_id = utils::thread_id(); let prev_stat = &recorder.thread_stats.get(&thread_id).unwrap().stat; let prev_cpu_ticks = prev_stat.utime.wrapping_add(prev_stat.stime); loop { let stat = utils::stat_task(utils::process_id(), thread_id).unwrap(); let cpu_ticks = stat.utime.wrapping_add(stat.stime); let delta_ms = cpu_ticks.wrapping_sub(prev_cpu_ticks) * 1_000 / utils::clock_tick(); if delta_ms != 0 { break; } heavy_job(); } let mut records = RawRecords::default(); recorder.tick(&mut records, &mut HashMap::default()); assert!(!records.records.is_empty()); } }
fn heavy_job() -> u64 { let m: u64 = rand::random(); let n: u64 = rand::random(); let m = m ^ n; let n = m.wrapping_mul(n); let m = m.wrapping_add(n); let n = m & n; let m = m | n; m.wrapping_sub(n) }
function_block-full_function
[ { "content": "#[cfg(target_os = \"linux\")]\n\npub fn stat_task(pid: usize, tid: usize) -> std::io::Result<Stat> {\n\n procinfo::pid::stat_task(pid as _, tid as _).map(Into::into)\n\n}\n\n\n\n/// Get the [Stat] of the thread (tid) in the process (pid).\n", "file_path": "components/resource_metering/src/u...
Rust
alvr/experiments/graphics_tests/src/compositor/convert.rs
glegoo/ALVR
76d087fdb05f2035486626551c9ab9022ba645c6
use super::{Compositor, Context, Swapchain, TextureType}; use alvr_common::prelude::*; use ash::{extensions::khr, vk}; use openxr_sys as sys; use std::{ffi::CStr, slice}; use wgpu::{ DeviceDescriptor, Extent3d, Features, Texture, TextureDescriptor, TextureDimension, TextureFormat, TextureUsages, }; use wgpu_hal as hal; pub const TARGET_VULKAN_VERSION: u32 = vk::make_api_version(1, 0, 0, 0); pub fn get_vulkan_instance_extensions( entry: &ash::Entry, version: u32, ) -> StrResult<Vec<&'static CStr>> { let mut flags = hal::InstanceFlags::empty(); if cfg!(debug_assertions) { flags |= hal::InstanceFlags::VALIDATION; flags |= hal::InstanceFlags::DEBUG; } trace_err!(<hal::api::Vulkan as hal::Api>::Instance::required_extensions(entry, version, flags)) } pub fn create_vulkan_instance( entry: &ash::Entry, info: &vk::InstanceCreateInfo, ) -> StrResult<ash::Instance> { let mut extensions_ptrs = get_vulkan_instance_extensions(entry, unsafe { (*info.p_application_info).api_version })? .iter() .map(|x| x.as_ptr()) .collect::<Vec<_>>(); extensions_ptrs.extend_from_slice(unsafe { slice::from_raw_parts( info.pp_enabled_extension_names, info.enabled_extension_count as _, ) }); unsafe { trace_err!(entry.create_instance( &vk::InstanceCreateInfo { enabled_extension_count: extensions_ptrs.len() as _, pp_enabled_extension_names: extensions_ptrs.as_ptr(), ..*info }, None, )) } } pub fn get_vulkan_graphics_device( instance: &ash::Instance, adapter_index: Option<usize>, ) -> StrResult<vk::PhysicalDevice> { let mut physical_devices = unsafe { trace_err!(instance.enumerate_physical_devices())? }; Ok(physical_devices.remove(adapter_index.unwrap_or(0))) } pub fn get_vulkan_device_extensions(version: u32) -> Vec<&'static CStr> { let mut extensions = vec![khr::Swapchain::name()]; if version < vk::API_VERSION_1_1 { extensions.push(vk::KhrMaintenance1Fn::name()); extensions.push(vk::KhrMaintenance2Fn::name()); } extensions } pub fn create_vulkan_device( entry: &ash::Entry, version: u32, instance: &ash::Instance, physical_device: vk::PhysicalDevice, create_info: &vk::DeviceCreateInfo, ) -> StrResult<ash::Device> { let mut extensions_ptrs = get_vulkan_device_extensions(version) .iter() .map(|x| x.as_ptr()) .collect::<Vec<_>>(); extensions_ptrs.extend_from_slice(unsafe { slice::from_raw_parts( create_info.pp_enabled_extension_names, create_info.enabled_extension_count as _, ) }); let mut features = if !create_info.p_enabled_features.is_null() { unsafe { *create_info.p_enabled_features } } else { vk::PhysicalDeviceFeatures::default() }; features.robust_buffer_access = true as _; features.independent_blend = true as _; features.sample_rate_shading = true as _; unsafe { trace_err!(instance.create_device( physical_device, &vk::DeviceCreateInfo { enabled_extension_count: extensions_ptrs.len() as _, pp_enabled_extension_names: extensions_ptrs.as_ptr(), p_enabled_features: &features as *const _, ..*create_info }, None )) } } impl Context { pub fn from_vulkan( owned: bool, entry: ash::Entry, version: u32, vk_instance: ash::Instance, adapter_index: Option<usize>, vk_device: ash::Device, queue_family_index: u32, queue_index: u32, ) -> StrResult<Self> { let mut flags = hal::InstanceFlags::empty(); if cfg!(debug_assertions) { flags |= hal::InstanceFlags::VALIDATION; flags |= hal::InstanceFlags::DEBUG; }; let extensions = get_vulkan_instance_extensions(&entry, version)?; let instance = unsafe { trace_err!(<hal::api::Vulkan as hal::Api>::Instance::from_raw( entry, vk_instance.clone(), version, extensions, flags, owned.then(|| Box::new(()) as _) ))? }; let physical_device = get_vulkan_graphics_device(&vk_instance, adapter_index)?; let exposed_adapter = trace_none!(instance.expose_adapter(physical_device))?; let open_device = unsafe { trace_err!(exposed_adapter.adapter.device_from_raw( vk_device, owned, &get_vulkan_device_extensions(version), queue_family_index, queue_index, ))? }; #[cfg(not(target_os = "macos"))] { let instance = unsafe { wgpu::Instance::from_hal::<hal::api::Vulkan>(instance) }; let adapter = unsafe { instance.create_adapter_from_hal(exposed_adapter) }; let (device, queue) = unsafe { trace_err!(adapter.create_device_from_hal( open_device, &DeviceDescriptor { label: None, features: Features::PUSH_CONSTANTS, limits: adapter.limits(), }, None, ))? }; Ok(Self { instance, device, queue, }) } #[cfg(target_os = "macos")] unimplemented!() } pub fn new(adapter_index: Option<usize>) -> StrResult<Self> { let entry = unsafe { trace_err!(ash::Entry::new())? }; let vk_instance = trace_err!(create_vulkan_instance( &entry, &vk::InstanceCreateInfo::builder() .application_info( &vk::ApplicationInfo::builder().api_version(TARGET_VULKAN_VERSION) ) .build() ))?; let physical_device = get_vulkan_graphics_device(&vk_instance, adapter_index)?; let queue_family_index = unsafe { vk_instance .get_physical_device_queue_family_properties(physical_device) .into_iter() .enumerate() .find_map(|(queue_family_index, info)| { if info.queue_flags.contains(vk::QueueFlags::GRAPHICS) { Some(queue_family_index as u32) } else { None } }) .unwrap() }; let queue_index = 0; let vk_device = trace_err!(create_vulkan_device( &entry, TARGET_VULKAN_VERSION, &vk_instance, physical_device, &vk::DeviceCreateInfo::builder().queue_create_infos(&[ vk::DeviceQueueCreateInfo::builder() .queue_family_index(queue_family_index) .queue_priorities(&[1.0]) .build() ]) ))?; Self::from_vulkan( true, entry, TARGET_VULKAN_VERSION, vk_instance, adapter_index, vk_device, queue_family_index, queue_index, ) } } pub enum SwapchainCreateData { #[cfg(target_os = "linux")] External { images: Vec<vk::Image>, vk_usage: vk::ImageUsageFlags, vk_format: vk::Format, hal_usage: hal::TextureUses, }, Count(Option<usize>), } pub struct SwapchainCreateInfo { usage: sys::SwapchainUsageFlags, format: TextureFormat, sample_count: u32, width: u32, height: u32, texture_type: TextureType, mip_count: u32, } impl Compositor { pub fn create_swapchain( &self, data: SwapchainCreateData, info: SwapchainCreateInfo, ) -> StrResult<Swapchain> { let wgpu_usage = { let mut wgpu_usage = TextureUsages::TEXTURE_BINDING; if info .usage .contains(sys::SwapchainUsageFlags::COLOR_ATTACHMENT) { wgpu_usage |= TextureUsages::RENDER_ATTACHMENT; } if info .usage .contains(sys::SwapchainUsageFlags::DEPTH_STENCIL_ATTACHMENT) { wgpu_usage |= TextureUsages::RENDER_ATTACHMENT; } if info.usage.contains(sys::SwapchainUsageFlags::TRANSFER_SRC) { wgpu_usage |= TextureUsages::COPY_SRC; } if info.usage.contains(sys::SwapchainUsageFlags::TRANSFER_DST) { wgpu_usage |= TextureUsages::COPY_DST; } wgpu_usage }; let depth_or_array_layers = match info.texture_type { TextureType::D2 { array_size } => array_size, TextureType::Cubemap => 6, }; let texture_descriptor = TextureDescriptor { label: None, size: Extent3d { width: info.width, height: info.height, depth_or_array_layers, }, mip_level_count: info.mip_count, sample_count: info.sample_count, dimension: TextureDimension::D2, format: info.format, usage: wgpu_usage, }; let textures = match data { #[cfg(target_os = "linux")] SwapchainCreateData::External { images, vk_usage, vk_format, hal_usage, } => images .into_iter() .map(|vk_image| { let hal_texture = unsafe { <hal::api::Vulkan as hal::Api>::Device::texture_from_raw( vk_image, &hal::TextureDescriptor { label: None, size: Extent3d { width, height, depth_or_array_layers: array_size, }, mip_level_count: mip_count, sample_count, dimension: TextureDimension::D2, format, usage: hal_usage, memory_flags: hal::MemoryFlags::empty(), }, None, ) }; unsafe { self.context .device .create_texture_from_hal::<hal::api::Vulkan>( hal_texture, &texture_descriptor, ) } }) .collect(), SwapchainCreateData::Count(count) => (0..count.unwrap_or(2)) .map(|_| self.context.device.create_texture(&texture_descriptor)) .collect(), }; let array_size = match info.texture_type { TextureType::D2 { array_size } => array_size, TextureType::Cubemap => 1, }; Ok(self.inner_create_swapchain(textures, array_size)) } } #[cfg(not(target_os = "macos"))] pub fn to_vulkan_images(textures: &[Texture]) -> Vec<vk::Image> { textures .iter() .map(|tex| unsafe { let hal_texture = tex.as_hal::<hal::api::Vulkan>(); hal_texture.as_inner().unwrap().raw_handle() }) .collect() }
use super::{Compositor, Context, Swapchain, TextureType}; use alvr_common::prelude::*; use ash::{extensions::khr, vk}; use openxr_sys as sys; use std::{ffi::CStr, slice}; use wgpu::{ DeviceDescriptor, Extent3d, Features, Texture, TextureDescriptor, TextureDimension, TextureFormat, TextureUsages, }; use wgpu_hal as hal; pub const TARGET_VULKAN_VERSION: u32 = vk::make_api_version(1, 0, 0, 0); pub fn get_vulkan_instance_extensions( entry: &ash::Entry, version: u32, ) -> StrResult<Vec<&'static CStr>> { let mut flags = hal::InstanceFlags::empty(); if cfg!(debug_assertions) { flags |= hal::InstanceFlags::VALIDATION; flags |= hal::InstanceFlags::DEBUG; } trace_err!(<hal::api::Vulkan as hal::Api>::Instance::required_extensions(entry, version, flags)) } pub fn create_vulkan_instance( entry: &ash::Entry, info: &vk::InstanceCreateInfo, ) -> StrResult<ash::Instance> { let mut extensions_ptrs = get_vulkan_instance_extensions(entry, unsafe { (*info.p_application_info).api_version })? .iter() .map(|x| x.as_ptr()) .collect::<Vec<_>>(); extensions_ptrs.extend_from_slice(unsafe { slice::from_raw_parts( info.pp_enabled_extension_names, info.enabled_extension_count as _, ) }); unsafe { trace_err!(entry.create_instance( &vk::InstanceCreateInfo { enabled_extension_count: extensions_ptrs.len() as _, pp_enabled_extension_names: extensions_ptrs.as_ptr(), ..*info }, None, )) } } pub fn get_vulkan_graphics_device( instance: &ash::Instance, adapter_index: Option<usize>, ) -> StrResult<vk::PhysicalDevice> { let mut physical_devices = unsafe { trace_err!(instance.enumerate_physical_devices())? }; Ok(physical_devices.remove(adapter_index.unwrap_or(0))) } pub fn get_vulkan_device_extensions(version: u32) -> Vec<&'static CStr> { let mut extensions = vec![khr::Swapchain::name()]; if version < vk::API_VERSION_1_1 { extensions.push(vk::KhrMaintenance1Fn::name()); extensions.push(vk::KhrMaintenance2Fn::name()); } extensions } pub fn create_vulkan_device( entry: &ash::Entry, version: u32, instance: &ash::Instance, physical_device: vk::PhysicalDevice, create_info: &vk::DeviceCreateInfo, ) -> StrResult<ash::Device> { let mut extensions_ptrs = get_vulkan_device_extensions(version) .iter() .map(|x| x.as_ptr()) .collect::<Vec<_>>(); extensions_ptrs.extend_from_slice(unsafe { slice::from_raw_parts( create_info.pp_enabled_extension_names, create_info.enabled_extension_count as _, ) }); let mut features = if !create_info.p_enabled_features.is_null() { unsafe { *create_info.p_enabled_features } } else { vk::PhysicalDeviceFeatures::default() }; features.robust_buffer_access = true as _; features.independent_blend = true as _; features.sample_rate_shading = true as _; unsafe { trace_err!(instance.create_device( physical_device, &vk::DeviceCreateInfo { enabled_extension_count: extensions_ptrs.len() as _, pp_enabled_extension_names: extensions_ptrs.as_ptr(), p_enabled_features: &features as *const _, ..*create_info }, None )) } } impl Context {
pub fn new(adapter_index: Option<usize>) -> StrResult<Self> { let entry = unsafe { trace_err!(ash::Entry::new())? }; let vk_instance = trace_err!(create_vulkan_instance( &entry, &vk::InstanceCreateInfo::builder() .application_info( &vk::ApplicationInfo::builder().api_version(TARGET_VULKAN_VERSION) ) .build() ))?; let physical_device = get_vulkan_graphics_device(&vk_instance, adapter_index)?; let queue_family_index = unsafe { vk_instance .get_physical_device_queue_family_properties(physical_device) .into_iter() .enumerate() .find_map(|(queue_family_index, info)| { if info.queue_flags.contains(vk::QueueFlags::GRAPHICS) { Some(queue_family_index as u32) } else { None } }) .unwrap() }; let queue_index = 0; let vk_device = trace_err!(create_vulkan_device( &entry, TARGET_VULKAN_VERSION, &vk_instance, physical_device, &vk::DeviceCreateInfo::builder().queue_create_infos(&[ vk::DeviceQueueCreateInfo::builder() .queue_family_index(queue_family_index) .queue_priorities(&[1.0]) .build() ]) ))?; Self::from_vulkan( true, entry, TARGET_VULKAN_VERSION, vk_instance, adapter_index, vk_device, queue_family_index, queue_index, ) } } pub enum SwapchainCreateData { #[cfg(target_os = "linux")] External { images: Vec<vk::Image>, vk_usage: vk::ImageUsageFlags, vk_format: vk::Format, hal_usage: hal::TextureUses, }, Count(Option<usize>), } pub struct SwapchainCreateInfo { usage: sys::SwapchainUsageFlags, format: TextureFormat, sample_count: u32, width: u32, height: u32, texture_type: TextureType, mip_count: u32, } impl Compositor { pub fn create_swapchain( &self, data: SwapchainCreateData, info: SwapchainCreateInfo, ) -> StrResult<Swapchain> { let wgpu_usage = { let mut wgpu_usage = TextureUsages::TEXTURE_BINDING; if info .usage .contains(sys::SwapchainUsageFlags::COLOR_ATTACHMENT) { wgpu_usage |= TextureUsages::RENDER_ATTACHMENT; } if info .usage .contains(sys::SwapchainUsageFlags::DEPTH_STENCIL_ATTACHMENT) { wgpu_usage |= TextureUsages::RENDER_ATTACHMENT; } if info.usage.contains(sys::SwapchainUsageFlags::TRANSFER_SRC) { wgpu_usage |= TextureUsages::COPY_SRC; } if info.usage.contains(sys::SwapchainUsageFlags::TRANSFER_DST) { wgpu_usage |= TextureUsages::COPY_DST; } wgpu_usage }; let depth_or_array_layers = match info.texture_type { TextureType::D2 { array_size } => array_size, TextureType::Cubemap => 6, }; let texture_descriptor = TextureDescriptor { label: None, size: Extent3d { width: info.width, height: info.height, depth_or_array_layers, }, mip_level_count: info.mip_count, sample_count: info.sample_count, dimension: TextureDimension::D2, format: info.format, usage: wgpu_usage, }; let textures = match data { #[cfg(target_os = "linux")] SwapchainCreateData::External { images, vk_usage, vk_format, hal_usage, } => images .into_iter() .map(|vk_image| { let hal_texture = unsafe { <hal::api::Vulkan as hal::Api>::Device::texture_from_raw( vk_image, &hal::TextureDescriptor { label: None, size: Extent3d { width, height, depth_or_array_layers: array_size, }, mip_level_count: mip_count, sample_count, dimension: TextureDimension::D2, format, usage: hal_usage, memory_flags: hal::MemoryFlags::empty(), }, None, ) }; unsafe { self.context .device .create_texture_from_hal::<hal::api::Vulkan>( hal_texture, &texture_descriptor, ) } }) .collect(), SwapchainCreateData::Count(count) => (0..count.unwrap_or(2)) .map(|_| self.context.device.create_texture(&texture_descriptor)) .collect(), }; let array_size = match info.texture_type { TextureType::D2 { array_size } => array_size, TextureType::Cubemap => 1, }; Ok(self.inner_create_swapchain(textures, array_size)) } } #[cfg(not(target_os = "macos"))] pub fn to_vulkan_images(textures: &[Texture]) -> Vec<vk::Image> { textures .iter() .map(|tex| unsafe { let hal_texture = tex.as_hal::<hal::api::Vulkan>(); hal_texture.as_inner().unwrap().raw_handle() }) .collect() }
pub fn from_vulkan( owned: bool, entry: ash::Entry, version: u32, vk_instance: ash::Instance, adapter_index: Option<usize>, vk_device: ash::Device, queue_family_index: u32, queue_index: u32, ) -> StrResult<Self> { let mut flags = hal::InstanceFlags::empty(); if cfg!(debug_assertions) { flags |= hal::InstanceFlags::VALIDATION; flags |= hal::InstanceFlags::DEBUG; }; let extensions = get_vulkan_instance_extensions(&entry, version)?; let instance = unsafe { trace_err!(<hal::api::Vulkan as hal::Api>::Instance::from_raw( entry, vk_instance.clone(), version, extensions, flags, owned.then(|| Box::new(()) as _) ))? }; let physical_device = get_vulkan_graphics_device(&vk_instance, adapter_index)?; let exposed_adapter = trace_none!(instance.expose_adapter(physical_device))?; let open_device = unsafe { trace_err!(exposed_adapter.adapter.device_from_raw( vk_device, owned, &get_vulkan_device_extensions(version), queue_family_index, queue_index, ))? }; #[cfg(not(target_os = "macos"))] { let instance = unsafe { wgpu::Instance::from_hal::<hal::api::Vulkan>(instance) }; let adapter = unsafe { instance.create_adapter_from_hal(exposed_adapter) }; let (device, queue) = unsafe { trace_err!(adapter.create_device_from_hal( open_device, &DeviceDescriptor { label: None, features: Features::PUSH_CONSTANTS, limits: adapter.limits(), }, None, ))? }; Ok(Self { instance, device, queue, }) } #[cfg(target_os = "macos")] unimplemented!() }
function_block-full_function
[ { "content": "#[cfg(target_os = \"macos\")]\n\npub fn get_screen_size() -> StrResult<(u32, u32)> {\n\n Ok((0, 0))\n\n}\n", "file_path": "alvr/server/src/graphics_info.rs", "rank": 0, "score": 257298.96087876664 }, { "content": "pub fn version() -> String {\n\n let manifest_path = packa...
Rust
gtk/src/auto/text_tag_table.rs
pop-os/gtk-rs
0a0e50a2f5ea8f816c005bd8c3d145a5a9581d8c
use crate::Buildable; use crate::TextTag; use glib::object::Cast; use glib::object::IsA; use glib::signal::connect_raw; use glib::signal::SignalHandlerId; use glib::translate::*; use std::boxed::Box as Box_; use std::fmt; use std::mem::transmute; glib::wrapper! { pub struct TextTagTable(Object<ffi::GtkTextTagTable, ffi::GtkTextTagTableClass>) @implements Buildable; match fn { get_type => || ffi::gtk_text_tag_table_get_type(), } } impl TextTagTable { pub fn new() -> TextTagTable { assert_initialized_main_thread!(); unsafe { from_glib_full(ffi::gtk_text_tag_table_new()) } } } impl Default for TextTagTable { fn default() -> Self { Self::new() } } pub const NONE_TEXT_TAG_TABLE: Option<&TextTagTable> = None; pub trait TextTagTableExt: 'static { fn add<P: IsA<TextTag>>(&self, tag: &P) -> bool; fn foreach<P: FnMut(&TextTag)>(&self, func: P); fn get_size(&self) -> i32; fn lookup(&self, name: &str) -> Option<TextTag>; fn remove<P: IsA<TextTag>>(&self, tag: &P); fn connect_tag_added<F: Fn(&Self, &TextTag) + 'static>(&self, f: F) -> SignalHandlerId; fn connect_tag_changed<F: Fn(&Self, &TextTag, bool) + 'static>(&self, f: F) -> SignalHandlerId; fn connect_tag_removed<F: Fn(&Self, &TextTag) + 'static>(&self, f: F) -> SignalHandlerId; } impl<O: IsA<TextTagTable>> TextTagTableExt for O { fn add<P: IsA<TextTag>>(&self, tag: &P) -> bool { unsafe { from_glib(ffi::gtk_text_tag_table_add( self.as_ref().to_glib_none().0, tag.as_ref().to_glib_none().0, )) } } fn foreach<P: FnMut(&TextTag)>(&self, func: P) { let func_data: P = func; unsafe extern "C" fn func_func<P: FnMut(&TextTag)>( tag: *mut ffi::GtkTextTag, data: glib::ffi::gpointer, ) { let tag = from_glib_borrow(tag); let callback: *mut P = data as *const _ as usize as *mut P; (*callback)(&tag); } let func = Some(func_func::<P> as _); let super_callback0: &P = &func_data; unsafe { ffi::gtk_text_tag_table_foreach( self.as_ref().to_glib_none().0, func, super_callback0 as *const _ as usize as *mut _, ); } } fn get_size(&self) -> i32 { unsafe { ffi::gtk_text_tag_table_get_size(self.as_ref().to_glib_none().0) } } fn lookup(&self, name: &str) -> Option<TextTag> { unsafe { from_glib_none(ffi::gtk_text_tag_table_lookup( self.as_ref().to_glib_none().0, name.to_glib_none().0, )) } } fn remove<P: IsA<TextTag>>(&self, tag: &P) { unsafe { ffi::gtk_text_tag_table_remove( self.as_ref().to_glib_none().0, tag.as_ref().to_glib_none().0, ); } } fn connect_tag_added<F: Fn(&Self, &TextTag) + 'static>(&self, f: F) -> SignalHandlerId { unsafe extern "C" fn tag_added_trampoline<P, F: Fn(&P, &TextTag) + 'static>( this: *mut ffi::GtkTextTagTable, tag: *mut ffi::GtkTextTag, f: glib::ffi::gpointer, ) where P: IsA<TextTagTable>, { let f: &F = &*(f as *const F); f( &TextTagTable::from_glib_borrow(this).unsafe_cast_ref(), &from_glib_borrow(tag), ) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"tag-added\0".as_ptr() as *const _, Some(transmute::<_, unsafe extern "C" fn()>( tag_added_trampoline::<Self, F> as *const (), )), Box_::into_raw(f), ) } } fn connect_tag_changed<F: Fn(&Self, &TextTag, bool) + 'static>(&self, f: F) -> SignalHandlerId { unsafe extern "C" fn tag_changed_trampoline<P, F: Fn(&P, &TextTag, bool) + 'static>( this: *mut ffi::GtkTextTagTable, tag: *mut ffi::GtkTextTag, size_changed: glib::ffi::gboolean, f: glib::ffi::gpointer, ) where P: IsA<TextTagTable>, { let f: &F = &*(f as *const F); f( &TextTagTable::from_glib_borrow(this).unsafe_cast_ref(), &from_glib_borrow(tag), from_glib(size_changed), ) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"tag-changed\0".as_ptr() as *const _, Some(transmute::<_, unsafe extern "C" fn()>( tag_changed_trampoline::<Self, F> as *const (), )), Box_::into_raw(f), ) } } fn connect_tag_removed<F: Fn(&Self, &TextTag) + 'static>(&self, f: F) -> SignalHandlerId { unsafe extern "C" fn tag_removed_trampoline<P, F: Fn(&P, &TextTag) + 'static>( this: *mut ffi::GtkTextTagTable, tag: *mut ffi::GtkTextTag, f: glib::ffi::gpointer, ) where P: IsA<TextTagTable>, { let f: &F = &*(f as *const F); f( &TextTagTable::from_glib_borrow(this).unsafe_cast_ref(), &from_glib_borrow(tag), ) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"tag-removed\0".as_ptr() as *const _, Some(transmute::<_, unsafe extern "C" fn()>( tag_removed_trampoline::<Self, F> as *const (), )), Box_::into_raw(f), ) } } } impl fmt::Display for TextTagTable { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str("TextTagTable") } }
use crate::Buildable; use crate::TextTag; use glib::object::Cast; use glib::object::IsA; use glib::signal::connect_raw; use glib::signal::SignalHandlerId; use glib::translate::*; use std::boxed::Box as Box_; use std::fmt; use std::mem::transmute; glib::wrapper! { pub struct TextTagTable(Object<ffi::GtkTextTagTable, ffi::GtkTextTagTableClass>) @implements Buildable; match fn { get_type => || ffi::gtk_text_tag_table_get_type(), } } impl TextTagTable { pub fn new() -> TextTagTable { assert_initialized_main_thread!(); unsafe { from_glib_full(ffi::gtk_text_tag_table_new()) } } } impl Default for TextTagTable { fn default() -> Self { Self::new() } } pub const NONE_TEXT_TAG_TABLE: Option<&TextTagTable> = None; pub trait TextTagTableExt: 'static { fn add<P: IsA<TextTag>>(&self, tag: &P) -> bool; fn foreach<P: FnMut(&TextTag)>(&self, func: P); fn get_size(&self) -> i32; fn lookup(&self, name: &str) -> Option<TextTag>; fn remove<P: IsA<TextTag>>(&self, tag: &P); fn connect_tag_added<F: Fn(&Self, &TextTag) + 'static>(&self, f: F) -> SignalHandlerId; fn connect_tag_changed<F: Fn(&Self, &TextTag, bool) + 'static>(&self, f: F) -> SignalHandlerId; fn connect_tag_removed<F: Fn(&Self, &TextTag) + 'static>(&self, f: F) -> SignalHandlerId; } impl<O: IsA<TextTagTable>> TextTagTableExt for O { fn add<P: IsA<TextTag>>(&self, tag: &P) -> bool { unsafe { from_glib(ffi::gtk_text_tag_table_add( self.as_ref().to_glib_none().0, tag.as_ref().to_glib_none().0, )) } } fn foreach<P: FnMut(&TextTag)>(&self, func: P) { let func_data: P = func; unsafe extern "C" fn func_func<P: FnMut(&TextTag)>( tag: *mut ffi::GtkTextTag, data: glib::ffi::gpointer, ) { let tag = from_glib_borrow(tag); let callback: *mut P = data as *const _ as usize as *mut P; (*callback)(&tag); } let func = Some(func_func::<P> as _); let super_callback0: &P = &func_data; unsafe { ffi::gtk_text_tag_table_foreach( self.as_ref().to_glib_none().0, func, super_callback0 as *const _ as usize as *mut _, ); } } fn get_size(&self) -> i32 { unsafe { ffi::gtk_text_tag_table_get_size(self.as_ref().to_glib_none().0) } } fn lookup(&self, name: &str) -> Option<TextTag> { unsafe { from_glib_none(ffi::gtk_text_tag_table_lookup( self.as_ref().to_glib_none().0, name.to_glib_none().0, )) } } fn remove<P: IsA<TextTag>>(&self, tag: &P) { unsafe { ffi::gtk_text_tag_table_remove( self.as_ref().to_glib_none().0, tag.as_ref().to_glib_none().0, ); } } fn connect_tag_added<F: Fn(&Self, &TextTag) + 'static>(&self, f: F) -> SignalHandlerId { unsafe extern "C" fn tag_added_trampoline<P, F: Fn(&P, &TextTag) + 'static>( this: *mut ffi::GtkTextTagTable, tag: *mut ffi::GtkTextTag, f: glib::ffi::gpointer, ) where P: IsA<TextTagTable>, { let f: &F = &*(f as *const F); f( &TextTagTable::from_glib_borrow(this).unsafe_cast_ref(), &from_glib_borrow(tag), ) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"tag-added\0".as_ptr() as *const _, Some(transmute::<_, unsafe extern "C" fn()>( tag_added_trampoline::<Self, F> as *const (), )), Box_::into_raw(f), ) } } fn connect_tag_changed<F: Fn(&Self, &TextTag, bool) + 'static>(&self, f: F) -> SignalHandlerId { unsafe extern "C" fn tag_changed_trampoline<P, F: Fn(&P, &TextTag, bool) + 'static>( this: *mut ffi::GtkTextTagTable, tag: *mut ffi::GtkTextTag, size_changed: glib::ffi::gboolean, f: glib::ffi::gpointer, ) where P: IsA<TextTagTable>, {
fn connect_tag_removed<F: Fn(&Self, &TextTag) + 'static>(&self, f: F) -> SignalHandlerId { unsafe extern "C" fn tag_removed_trampoline<P, F: Fn(&P, &TextTag) + 'static>( this: *mut ffi::GtkTextTagTable, tag: *mut ffi::GtkTextTag, f: glib::ffi::gpointer, ) where P: IsA<TextTagTable>, { let f: &F = &*(f as *const F); f( &TextTagTable::from_glib_borrow(this).unsafe_cast_ref(), &from_glib_borrow(tag), ) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"tag-removed\0".as_ptr() as *const _, Some(transmute::<_, unsafe extern "C" fn()>( tag_removed_trampoline::<Self, F> as *const (), )), Box_::into_raw(f), ) } } } impl fmt::Display for TextTagTable { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str("TextTagTable") } }
let f: &F = &*(f as *const F); f( &TextTagTable::from_glib_borrow(this).unsafe_cast_ref(), &from_glib_borrow(tag), from_glib(size_changed), ) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"tag-changed\0".as_ptr() as *const _, Some(transmute::<_, unsafe extern "C" fn()>( tag_changed_trampoline::<Self, F> as *const (), )), Box_::into_raw(f), ) } }
function_block-function_prefix_line
[ { "content": "/// Adds a closure to be called by the main loop the return `Source` is attached to when it's idle.\n\n///\n\n/// `func` will be called repeatedly until it returns `Continue(false)`.\n\npub fn idle_source_new<F>(name: Option<&str>, priority: Priority, func: F) -> Source\n\nwhere\n\n F: FnMut() ...
Rust
python/src/expression.rs
boaz-codota/ballista
75f5f79bdcf18ac897d9ab9e11035040d932fc5e
/* A great deal of this files source code was pulled more or less verbatim from https://github.com/jorgecarleitao/datafusion-python/commit/688f0d23504704cfc2be3fca33e2707e964ea5bc which is dual liscensed as MIT or Apache-2.0. */ /* MIT License Copyright (c) 2020 Jorge Leitao 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 pyo3::{ basic::CompareOp, exceptions::PyException, prelude::*, types::PyTuple, PyNumberProtocol, PyObjectProtocol, }; use crate::util; use datafusion::logical_plan; use datafusion::logical_plan::Expr; #[pyclass(name = "Expression", module = "ballista")] #[derive(Debug, Clone)] pub struct BPyExpr { pub(crate) expr: Expr, } pub fn from_tuple(value: &PyTuple) -> PyResult<Vec<BPyExpr>> { value .iter() .map(|e| e.extract::<BPyExpr>()) .collect::<PyResult<_>>() } pub fn any_to_expression(any: &PyAny) -> PyResult<Expr> { if let Ok(expr) = any.extract::<BPyExpr>() { Ok(expr.expr) } else if let Ok(scalar_value) = any.extract::<crate::scalar::Scalar>() { Ok(Expr::Literal(scalar_value.scalar)) } else { let type_name = util::object_class_name(any) .unwrap_or_else(|err| format!("<Could not get class name:{}>", err)); Err(PyException::new_err(format!( "The rhs type {} could not be converted to an expression.", &type_name ))) } } #[pyproto] impl PyNumberProtocol for BPyExpr { fn __add__(lhs: BPyExpr, rhs: &PyAny) -> PyResult<BPyExpr> { let rhs_expr = any_to_expression(rhs)?; Ok(BPyExpr { expr: lhs.expr + rhs_expr, }) } fn __sub__(lhs: BPyExpr, rhs: &PyAny) -> PyResult<BPyExpr> { let rhs_expr = any_to_expression(rhs)?; Ok(BPyExpr { expr: lhs.expr - rhs_expr, }) } fn __truediv__(lhs: BPyExpr, rhs: &PyAny) -> PyResult<BPyExpr> { let rhs_expr = any_to_expression(rhs)?; Ok(BPyExpr { expr: lhs.expr / rhs_expr, }) } fn __mul__(lhs: BPyExpr, rhs: &PyAny) -> PyResult<BPyExpr> { let rhs_expr = any_to_expression(rhs)?; Ok(BPyExpr { expr: lhs.expr * rhs_expr, }) } fn __and__(lhs: BPyExpr, rhs: &PyAny) -> PyResult<BPyExpr> { let rhs_expr = any_to_expression(rhs)?; Ok(BPyExpr { expr: lhs.expr.and(rhs_expr), }) } fn __or__(lhs: BPyExpr, rhs: &PyAny) -> PyResult<BPyExpr> { let rhs_expr = any_to_expression(rhs)?; Ok(BPyExpr { expr: lhs.expr.or(rhs_expr), }) } fn __invert__(&self) -> PyResult<BPyExpr> { Ok(BPyExpr { expr: self.expr.not(), }) } } #[pyproto] impl PyObjectProtocol for BPyExpr { fn __str__(&self) -> String { format!("{:?}", self.expr) } fn __richcmp__(&self, other: &PyAny, op: CompareOp) -> PyResult<BPyExpr> { let other_expr = any_to_expression(other)?; Ok(match op { CompareOp::Lt => BPyExpr { expr: self.expr.lt(other_expr), }, CompareOp::Le => BPyExpr { expr: self.expr.lt_eq(other_expr), }, CompareOp::Eq => BPyExpr { expr: self.expr.eq(other_expr), }, CompareOp::Ne => BPyExpr { expr: self.expr.not_eq(other_expr), }, CompareOp::Gt => BPyExpr { expr: self.expr.gt(other_expr), }, CompareOp::Ge => BPyExpr { expr: self.expr.gt_eq(other_expr), }, }) } } #[pymethods] impl BPyExpr { #[new] fn new(expr: &PyAny) -> PyResult<BPyExpr> { let converted_expr = any_to_expression(expr)?; Ok(BPyExpr { expr: converted_expr, }) } pub fn alias(&self, name: &str) -> PyResult<BPyExpr> { Ok(BPyExpr { expr: self.expr.alias(name), }) } #[args(negated = "false")] pub fn between(&self, low: &PyAny, high: &PyAny, negated: bool) -> PyResult<BPyExpr> { let low_expr = any_to_expression(low)?; let high_expr = any_to_expression(high)?; Ok(BPyExpr { expr: Expr::Between { expr: Box::new(self.expr.clone()), low: Box::new(low_expr), high: Box::new(high_expr), negated, }, }) } } use pyo3::PyCell; #[pyclass(module = "ballista", module = "ballista")] #[derive(Clone)] pub struct CaseBuilder { case_expr: Option<logical_plan::Expr>, when_expr: Vec<logical_plan::Expr>, then_expr: Vec<logical_plan::Expr>, else_expr: Option<logical_plan::Expr>, built_expr: Option<BPyExpr>, } #[pymethods] impl CaseBuilder { #[new] #[args(case_expr = "None")] pub fn new(case_expr: Option<BPyExpr>) -> Self { Self { case_expr: case_expr.map(|e| e.expr), when_expr: vec![], then_expr: vec![], else_expr: None, built_expr: None, } } pub fn when<'a>( slf: &'a PyCell<Self>, when: &PyAny, then: &PyAny, ) -> PyResult<&'a PyCell<Self>> { { let mut __self = slf.try_borrow_mut()?; let when_expr = any_to_expression(when)?; let then_expr = any_to_expression(then)?; __self.when_impl(when_expr, then_expr)?; } Ok(slf) } pub fn otherwise(&mut self, else_expr: &PyAny) -> PyResult<BPyExpr> { let other_size_expr = any_to_expression(else_expr)?; self.is_built_error()?; self.else_expr = Some(other_size_expr); self.private_build() } pub fn build(&mut self) -> PyResult<BPyExpr> { if self.is_built() { return Ok(self.built_expr.as_ref().unwrap().clone()); } self.private_build() } #[getter] pub fn get_expr(&self) -> Option<BPyExpr> { self.built_expr.clone() } } impl CaseBuilder { pub fn case(case_expr: Expr) -> Self { Self::new(Some(BPyExpr { expr: case_expr })) } pub fn when_impl(&mut self, when: Expr, then: Expr) -> PyResult<()> { self.is_built_error()?; self.when_expr.push(when); self.then_expr.push(then); Ok(()) } fn is_built(&self) -> bool { self.built_expr.is_some() } fn is_built_error(&self) -> PyResult<()> { if self.is_built() { return Err(PyException::new_err("This case builder has already been used, use 'expr' attribute to access expression or create a new builder using case function")); } Ok(()) } fn private_build(&mut self) -> PyResult<BPyExpr> { let mut temp_case = None; if self.when_expr.is_empty() { return Err(PyException::new_err( "The builder must have at least one when then clause added before building", )); } std::mem::swap(&mut temp_case, &mut self.case_expr); let mut builder = match temp_case { Some(expr) => { logical_plan::case(expr).when(self.when_expr.remove(0), self.then_expr.remove(0)) } None => logical_plan::when(self.when_expr.remove(0), self.then_expr.remove(0)), }; let mut temp_when = vec![]; let mut temp_then = vec![]; std::mem::swap(&mut temp_when, &mut self.when_expr); std::mem::swap(&mut temp_then, &mut self.then_expr); for (when, then) in temp_when.into_iter().zip(temp_then.into_iter()) { builder = builder.when(when, then); } let mut temp_else = None; std::mem::swap(&mut temp_else, &mut self.else_expr); let build_result = match temp_else { Some(else_expr) => builder.otherwise(else_expr), None => builder.end(), } .map_err(util::wrap_err)?; self.built_expr = Some(BPyExpr { expr: build_result }); return Ok(self.built_expr.as_ref().unwrap().clone()); } }
/* A great deal of this files source code was pulled more or less verbatim from https://github.com/jorgecarleitao/datafusion-python/commit/688f0d23504704cfc2be3fca33e2707e964ea5bc which is dual liscensed as MIT or Apache-2.0. */ /* MIT License Copyright (c) 2020 Jorge Leitao 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 pyo3::{ basic::CompareOp, exceptions::PyException, prelude::*, types::PyTuple, PyNumberProtocol, PyObjectProtocol, }; use crate::util; use datafusion::logical_plan; use datafusion::logical_plan::Expr; #[pyclass(name = "Expression", module = "ballista")] #[derive(Debug, Clone)] pub struct BPyExpr { pub(crate) expr: Expr, } pub fn from_tuple(value: &PyTuple) -> PyResult<Vec<BPyExpr>> { value .iter() .map(|e| e.extract::<BPyExpr>()) .collect::<PyResult<_>>() } pub fn any_to_expression(any: &PyAny) -> PyResult<Expr> {
} #[pyproto] impl PyNumberProtocol for BPyExpr { fn __add__(lhs: BPyExpr, rhs: &PyAny) -> PyResult<BPyExpr> { let rhs_expr = any_to_expression(rhs)?; Ok(BPyExpr { expr: lhs.expr + rhs_expr, }) } fn __sub__(lhs: BPyExpr, rhs: &PyAny) -> PyResult<BPyExpr> { let rhs_expr = any_to_expression(rhs)?; Ok(BPyExpr { expr: lhs.expr - rhs_expr, }) } fn __truediv__(lhs: BPyExpr, rhs: &PyAny) -> PyResult<BPyExpr> { let rhs_expr = any_to_expression(rhs)?; Ok(BPyExpr { expr: lhs.expr / rhs_expr, }) } fn __mul__(lhs: BPyExpr, rhs: &PyAny) -> PyResult<BPyExpr> { let rhs_expr = any_to_expression(rhs)?; Ok(BPyExpr { expr: lhs.expr * rhs_expr, }) } fn __and__(lhs: BPyExpr, rhs: &PyAny) -> PyResult<BPyExpr> { let rhs_expr = any_to_expression(rhs)?; Ok(BPyExpr { expr: lhs.expr.and(rhs_expr), }) } fn __or__(lhs: BPyExpr, rhs: &PyAny) -> PyResult<BPyExpr> { let rhs_expr = any_to_expression(rhs)?; Ok(BPyExpr { expr: lhs.expr.or(rhs_expr), }) } fn __invert__(&self) -> PyResult<BPyExpr> { Ok(BPyExpr { expr: self.expr.not(), }) } } #[pyproto] impl PyObjectProtocol for BPyExpr { fn __str__(&self) -> String { format!("{:?}", self.expr) } fn __richcmp__(&self, other: &PyAny, op: CompareOp) -> PyResult<BPyExpr> { let other_expr = any_to_expression(other)?; Ok(match op { CompareOp::Lt => BPyExpr { expr: self.expr.lt(other_expr), }, CompareOp::Le => BPyExpr { expr: self.expr.lt_eq(other_expr), }, CompareOp::Eq => BPyExpr { expr: self.expr.eq(other_expr), }, CompareOp::Ne => BPyExpr { expr: self.expr.not_eq(other_expr), }, CompareOp::Gt => BPyExpr { expr: self.expr.gt(other_expr), }, CompareOp::Ge => BPyExpr { expr: self.expr.gt_eq(other_expr), }, }) } } #[pymethods] impl BPyExpr { #[new] fn new(expr: &PyAny) -> PyResult<BPyExpr> { let converted_expr = any_to_expression(expr)?; Ok(BPyExpr { expr: converted_expr, }) } pub fn alias(&self, name: &str) -> PyResult<BPyExpr> { Ok(BPyExpr { expr: self.expr.alias(name), }) } #[args(negated = "false")] pub fn between(&self, low: &PyAny, high: &PyAny, negated: bool) -> PyResult<BPyExpr> { let low_expr = any_to_expression(low)?; let high_expr = any_to_expression(high)?; Ok(BPyExpr { expr: Expr::Between { expr: Box::new(self.expr.clone()), low: Box::new(low_expr), high: Box::new(high_expr), negated, }, }) } } use pyo3::PyCell; #[pyclass(module = "ballista", module = "ballista")] #[derive(Clone)] pub struct CaseBuilder { case_expr: Option<logical_plan::Expr>, when_expr: Vec<logical_plan::Expr>, then_expr: Vec<logical_plan::Expr>, else_expr: Option<logical_plan::Expr>, built_expr: Option<BPyExpr>, } #[pymethods] impl CaseBuilder { #[new] #[args(case_expr = "None")] pub fn new(case_expr: Option<BPyExpr>) -> Self { Self { case_expr: case_expr.map(|e| e.expr), when_expr: vec![], then_expr: vec![], else_expr: None, built_expr: None, } } pub fn when<'a>( slf: &'a PyCell<Self>, when: &PyAny, then: &PyAny, ) -> PyResult<&'a PyCell<Self>> { { let mut __self = slf.try_borrow_mut()?; let when_expr = any_to_expression(when)?; let then_expr = any_to_expression(then)?; __self.when_impl(when_expr, then_expr)?; } Ok(slf) } pub fn otherwise(&mut self, else_expr: &PyAny) -> PyResult<BPyExpr> { let other_size_expr = any_to_expression(else_expr)?; self.is_built_error()?; self.else_expr = Some(other_size_expr); self.private_build() } pub fn build(&mut self) -> PyResult<BPyExpr> { if self.is_built() { return Ok(self.built_expr.as_ref().unwrap().clone()); } self.private_build() } #[getter] pub fn get_expr(&self) -> Option<BPyExpr> { self.built_expr.clone() } } impl CaseBuilder { pub fn case(case_expr: Expr) -> Self { Self::new(Some(BPyExpr { expr: case_expr })) } pub fn when_impl(&mut self, when: Expr, then: Expr) -> PyResult<()> { self.is_built_error()?; self.when_expr.push(when); self.then_expr.push(then); Ok(()) } fn is_built(&self) -> bool { self.built_expr.is_some() } fn is_built_error(&self) -> PyResult<()> { if self.is_built() { return Err(PyException::new_err("This case builder has already been used, use 'expr' attribute to access expression or create a new builder using case function")); } Ok(()) } fn private_build(&mut self) -> PyResult<BPyExpr> { let mut temp_case = None; if self.when_expr.is_empty() { return Err(PyException::new_err( "The builder must have at least one when then clause added before building", )); } std::mem::swap(&mut temp_case, &mut self.case_expr); let mut builder = match temp_case { Some(expr) => { logical_plan::case(expr).when(self.when_expr.remove(0), self.then_expr.remove(0)) } None => logical_plan::when(self.when_expr.remove(0), self.then_expr.remove(0)), }; let mut temp_when = vec![]; let mut temp_then = vec![]; std::mem::swap(&mut temp_when, &mut self.when_expr); std::mem::swap(&mut temp_then, &mut self.then_expr); for (when, then) in temp_when.into_iter().zip(temp_then.into_iter()) { builder = builder.when(when, then); } let mut temp_else = None; std::mem::swap(&mut temp_else, &mut self.else_expr); let build_result = match temp_else { Some(else_expr) => builder.otherwise(else_expr), None => builder.end(), } .map_err(util::wrap_err)?; self.built_expr = Some(BPyExpr { expr: build_result }); return Ok(self.built_expr.as_ref().unwrap().clone()); } }
if let Ok(expr) = any.extract::<BPyExpr>() { Ok(expr.expr) } else if let Ok(scalar_value) = any.extract::<crate::scalar::Scalar>() { Ok(Expr::Literal(scalar_value.scalar)) } else { let type_name = util::object_class_name(any) .unwrap_or_else(|err| format!("<Could not get class name:{}>", err)); Err(PyException::new_err(format!( "The rhs type {} could not be converted to an expression.", &type_name ))) }
if_condition
[ { "content": "#[pyfunction]\n\npub fn count(value: BPyExpr) -> BPyExpr {\n\n BPyExpr {\n\n expr: logical_plan::count(value.expr),\n\n }\n\n}\n\n\n", "file_path": "python/src/functions.rs", "rank": 0, "score": 210292.79264307546 }, { "content": "#[pyfunction]\n\npub fn min(value:...
Rust
zebra-chain/src/serialization/read_zcash.rs
ebfull/zebra
e61b5e50a2f00ebc6e16ac1de10031897acd71cc
use std::io; use std::net::{IpAddr, SocketAddr}; use byteorder::{BigEndian, LittleEndian, ReadBytesExt}; use super::SerializationError; pub trait ReadZcashExt: io::Read { #[inline] fn read_compactsize(&mut self) -> Result<u64, SerializationError> { use SerializationError::Parse; let flag_byte = self.read_u8()?; match flag_byte { n @ 0x00..=0xfc => Ok(n as u64), 0xfd => match self.read_u16::<LittleEndian>()? { n @ 0x0000_00fd..=0x0000_ffff => Ok(n as u64), _ => Err(Parse("non-canonical compactsize")), }, 0xfe => match self.read_u32::<LittleEndian>()? { n @ 0x0001_0000..=0xffff_ffff => Ok(n as u64), _ => Err(Parse("non-canonical compactsize")), }, 0xff => match self.read_u64::<LittleEndian>()? { n @ 0x1_0000_0000..=0xffff_ffff_ffff_ffff => Ok(n), _ => Err(Parse("non-canonical compactsize")), }, } } #[inline] fn read_ip_addr(&mut self) -> io::Result<IpAddr> { use std::net::{IpAddr::*, Ipv6Addr}; let mut octets = [0u8; 16]; self.read_exact(&mut octets)?; let v6_addr = Ipv6Addr::from(octets); match v6_addr.to_ipv4() { Some(v4_addr) => Ok(V4(v4_addr)), None => Ok(V6(v6_addr)), } } #[inline] fn read_socket_addr(&mut self) -> io::Result<SocketAddr> { let ip_addr = self.read_ip_addr()?; let port = self.read_u16::<BigEndian>()?; Ok(SocketAddr::new(ip_addr, port)) } #[inline] fn read_string(&mut self) -> Result<String, SerializationError> { let len = self.read_compactsize()?; let mut buf = vec![0; len as usize]; self.read_exact(&mut buf)?; String::from_utf8(buf).map_err(|_| SerializationError::Parse("invalid utf-8")) } #[inline] fn read_4_bytes(&mut self) -> io::Result<[u8; 4]> { let mut bytes = [0; 4]; self.read_exact(&mut bytes)?; Ok(bytes) } #[inline] fn read_12_bytes(&mut self) -> io::Result<[u8; 12]> { let mut bytes = [0; 12]; self.read_exact(&mut bytes)?; Ok(bytes) } #[inline] fn read_32_bytes(&mut self) -> io::Result<[u8; 32]> { let mut bytes = [0; 32]; self.read_exact(&mut bytes)?; Ok(bytes) } #[inline] fn read_64_bytes(&mut self) -> io::Result<[u8; 64]> { let mut bytes = [0; 64]; self.read_exact(&mut bytes)?; Ok(bytes) } } impl<R: io::Read + ?Sized> ReadZcashExt for R {}
use std::io; use std::net::{IpAddr, SocketAddr}; use byteorder::{BigEndian, LittleEndian, ReadBytesExt}; use super::SerializationError; pub trait ReadZcashExt: io::Read { #[inline] fn read_compactsize(&mut self) -> Result<u64, SerializationError> { use SerializationError::Parse; let flag_byte = self.read_u8()?; match flag_byte { n @ 0x00..=0xfc => Ok(n as u64), 0xfd => match self.read_u16::<LittleEndian>()? { n @ 0x0000_00fd..=0x0000_ffff => Ok(n as u64), _ => Err(Parse("non-canonical compactsize")), }, 0xfe => match self.read_u32::<LittleEndian>()? { n @ 0x0001_0000..=0xffff_ffff => Ok(n as u64), _ => Err(Parse("non-canonical compactsize")), }, 0xff => match self.read_u64::<LittleEndian>()? { n @ 0x1_0000_0000..=0xffff_ffff_ffff_ffff => Ok(n), _ => Err(Parse("non-canonical compactsize")), }, } } #[inline] fn read_ip_addr(&mut self) -> io::Result<IpAddr> { use std::net::{IpAddr::*, Ipv6Addr}; let mut octets = [0u8; 16]; self.read_exact(&mut octets)?; let v6_addr = Ipv6Addr::from(octets); match v6_addr.to_ipv4() { Some(v4_addr) => Ok(V4(v4_addr)), None => Ok(V6(v6_addr)), } } #[inline] fn read_socket_addr(&mut self) -> io::Result<SocketAddr> { let ip_addr = self.read_ip_addr()?; let port = self.read_u16::<BigEndian>()?; Ok(SocketAddr::new(ip_addr, port)) } #[inline] fn read_st
#[inline] fn read_4_bytes(&mut self) -> io::Result<[u8; 4]> { let mut bytes = [0; 4]; self.read_exact(&mut bytes)?; Ok(bytes) } #[inline] fn read_12_bytes(&mut self) -> io::Result<[u8; 12]> { let mut bytes = [0; 12]; self.read_exact(&mut bytes)?; Ok(bytes) } #[inline] fn read_32_bytes(&mut self) -> io::Result<[u8; 32]> { let mut bytes = [0; 32]; self.read_exact(&mut bytes)?; Ok(bytes) } #[inline] fn read_64_bytes(&mut self) -> io::Result<[u8; 64]> { let mut bytes = [0; 64]; self.read_exact(&mut bytes)?; Ok(bytes) } } impl<R: io::Read + ?Sized> ReadZcashExt for R {}
ring(&mut self) -> Result<String, SerializationError> { let len = self.read_compactsize()?; let mut buf = vec![0; len as usize]; self.read_exact(&mut buf)?; String::from_utf8(buf).map_err(|_| SerializationError::Parse("invalid utf-8")) }
function_block-function_prefixed
[ { "content": "/// Check that if there are no Spends or Outputs, that valueBalance is also 0.\n\n///\n\n/// https://zips.z.cash/protocol/canopy.pdf#consensusfrombitcoin\n\npub fn shielded_balances_match(\n\n shielded_data: &ShieldedData,\n\n value_balance: Amount,\n\n) -> Result<(), TransactionError> {\n\n...
Rust
src/de/mod.rs
RoccoDev/bson-rust
9781781212056c619464be8444a27587c7dc5de9
mod error; mod raw; mod serde; pub use self::{ error::{Error, Result}, serde::Deserializer, }; use std::io::Read; use crate::{ bson::{Array, Binary, Bson, DbPointer, Document, JavaScriptCodeWithScope, Regex, Timestamp}, oid::{self, ObjectId}, ser::write_i32, spec::{self, BinarySubtype}, Decimal128, }; use ::serde::{ de::{DeserializeOwned, Error as _, Unexpected}, Deserialize, }; pub(crate) use self::serde::BsonVisitor; pub(crate) const MAX_BSON_SIZE: i32 = 16 * 1024 * 1024; pub(crate) const MIN_BSON_DOCUMENT_SIZE: i32 = 4 + 1; pub(crate) const MIN_BSON_STRING_SIZE: i32 = 4 + 1; pub(crate) const MIN_CODE_WITH_SCOPE_SIZE: i32 = 4 + MIN_BSON_STRING_SIZE + MIN_BSON_DOCUMENT_SIZE; pub(crate) fn ensure_read_exactly<F, R>( reader: &mut R, length: usize, error_message: &str, func: F, ) -> Result<()> where F: FnOnce(&mut std::io::Cursor<Vec<u8>>) -> Result<()>, R: Read + ?Sized, { let mut buf = vec![0u8; length]; reader.read_exact(&mut buf)?; let mut cursor = std::io::Cursor::new(buf); func(&mut cursor)?; if cursor.position() != length as u64 { return Err(Error::invalid_length(length, &error_message)); } Ok(()) } pub(crate) fn read_string<R: Read + ?Sized>(reader: &mut R, utf8_lossy: bool) -> Result<String> { let len = read_i32(reader)?; if len < 1 { return Err(Error::invalid_length( len as usize, &"UTF-8 string must have at least 1 byte", )); } let s = if utf8_lossy { let mut buf = Vec::with_capacity(len as usize - 1); reader.take(len as u64 - 1).read_to_end(&mut buf)?; String::from_utf8_lossy(&buf).to_string() } else { let mut s = String::with_capacity(len as usize - 1); reader.take(len as u64 - 1).read_to_string(&mut s)?; s }; if read_u8(reader)? != 0 { return Err(Error::invalid_length( len as usize, &"contents of string longer than provided length", )); } Ok(s) } pub(crate) fn read_bool<R: Read>(mut reader: R) -> Result<bool> { let val = read_u8(&mut reader)?; if val > 1 { return Err(Error::invalid_value( Unexpected::Unsigned(val as u64), &"boolean must be stored as 0 or 1", )); } Ok(val != 0) } fn read_cstring<R: Read + ?Sized>(reader: &mut R) -> Result<String> { let mut v = Vec::new(); loop { let c = read_u8(reader)?; if c == 0 { break; } v.push(c); } Ok(String::from_utf8(v)?) } #[inline] pub(crate) fn read_u8<R: Read + ?Sized>(reader: &mut R) -> Result<u8> { let mut buf = [0; 1]; reader.read_exact(&mut buf)?; Ok(u8::from_le_bytes(buf)) } #[inline] pub(crate) fn read_i32<R: Read + ?Sized>(reader: &mut R) -> Result<i32> { let mut buf = [0; 4]; reader.read_exact(&mut buf)?; Ok(i32::from_le_bytes(buf)) } #[inline] pub(crate) fn read_i64<R: Read + ?Sized>(reader: &mut R) -> Result<i64> { let mut buf = [0; 8]; reader.read_exact(&mut buf)?; Ok(i64::from_le_bytes(buf)) } #[inline] fn read_f64<R: Read + ?Sized>(reader: &mut R) -> Result<f64> { let mut buf = [0; 8]; reader.read_exact(&mut buf)?; Ok(f64::from_le_bytes(buf)) } #[inline] fn read_f128<R: Read + ?Sized>(reader: &mut R) -> Result<Decimal128> { let mut buf = [0u8; 128 / 8]; reader.read_exact(&mut buf)?; Ok(Decimal128 { bytes: buf }) } fn deserialize_array<R: Read + ?Sized>(reader: &mut R, utf8_lossy: bool) -> Result<Array> { let mut arr = Array::new(); let length = read_i32(reader)?; if !(MIN_BSON_DOCUMENT_SIZE..=MAX_BSON_SIZE).contains(&length) { return Err(Error::invalid_length( length as usize, &format!( "array length must be between {} and {}", MIN_BSON_DOCUMENT_SIZE, MAX_BSON_SIZE ) .as_str(), )); } ensure_read_exactly( reader, (length as usize) - 4, "array length longer than contents", |cursor| { loop { let tag = read_u8(cursor)?; if tag == 0 { break; } let (_, val) = deserialize_bson_kvp(cursor, tag, utf8_lossy)?; arr.push(val) } Ok(()) }, )?; Ok(arr) } pub(crate) fn deserialize_bson_kvp<R: Read + ?Sized>( reader: &mut R, tag: u8, utf8_lossy: bool, ) -> Result<(String, Bson)> { use spec::ElementType; let key = read_cstring(reader)?; let val = match ElementType::from(tag) { Some(ElementType::Double) => Bson::Double(read_f64(reader)?), Some(ElementType::String) => read_string(reader, utf8_lossy).map(Bson::String)?, Some(ElementType::EmbeddedDocument) => Document::from_reader(reader).map(Bson::Document)?, Some(ElementType::Array) => deserialize_array(reader, utf8_lossy).map(Bson::Array)?, Some(ElementType::Binary) => Bson::Binary(Binary::from_reader(reader)?), Some(ElementType::ObjectId) => { let mut objid = [0; 12]; for x in &mut objid { *x = read_u8(reader)?; } Bson::ObjectId(oid::ObjectId::from_bytes(objid)) } Some(ElementType::Boolean) => Bson::Boolean(read_bool(reader)?), Some(ElementType::Null) => Bson::Null, Some(ElementType::RegularExpression) => { Bson::RegularExpression(Regex::from_reader(reader)?) } Some(ElementType::JavaScriptCode) => { read_string(reader, utf8_lossy).map(Bson::JavaScriptCode)? } Some(ElementType::JavaScriptCodeWithScope) => { Bson::JavaScriptCodeWithScope(JavaScriptCodeWithScope::from_reader(reader, utf8_lossy)?) } Some(ElementType::Int32) => read_i32(reader).map(Bson::Int32)?, Some(ElementType::Int64) => read_i64(reader).map(Bson::Int64)?, Some(ElementType::Timestamp) => Bson::Timestamp(Timestamp::from_reader(reader)?), Some(ElementType::DateTime) => { let time = read_i64(reader)?; Bson::DateTime(crate::DateTime::from_millis(time)) } Some(ElementType::Symbol) => read_string(reader, utf8_lossy).map(Bson::Symbol)?, Some(ElementType::Decimal128) => read_f128(reader).map(Bson::Decimal128)?, Some(ElementType::Undefined) => Bson::Undefined, Some(ElementType::DbPointer) => Bson::DbPointer(DbPointer::from_reader(reader)?), Some(ElementType::MaxKey) => Bson::MaxKey, Some(ElementType::MinKey) => Bson::MinKey, None => { return Err(Error::UnrecognizedDocumentElementType { key, element_type: tag, }) } }; Ok((key, val)) } impl Binary { pub(crate) fn from_reader<R: Read>(mut reader: R) -> Result<Self> { let len = read_i32(&mut reader)?; if !(0..=MAX_BSON_SIZE).contains(&len) { return Err(Error::invalid_length( len as usize, &format!("binary length must be between 0 and {}", MAX_BSON_SIZE).as_str(), )); } let subtype = BinarySubtype::from(read_u8(&mut reader)?); Self::from_reader_with_len_and_payload(reader, len, subtype) } pub(crate) fn from_reader_with_len_and_payload<R: Read>( mut reader: R, mut len: i32, subtype: BinarySubtype, ) -> Result<Self> { if !(0..=MAX_BSON_SIZE).contains(&len) { return Err(Error::invalid_length( len as usize, &format!("binary length must be between 0 and {}", MAX_BSON_SIZE).as_str(), )); } if let BinarySubtype::BinaryOld = subtype { let data_len = read_i32(&mut reader)?; if !(0..=(MAX_BSON_SIZE - 4)).contains(&data_len) { return Err(Error::invalid_length( data_len as usize, &format!("0x02 length must be between 0 and {}", MAX_BSON_SIZE - 4).as_str(), )); } if data_len + 4 != len { return Err(Error::invalid_length( data_len as usize, &"0x02 length did not match top level binary length", )); } len -= 4; } let mut bytes = Vec::with_capacity(len as usize); reader.take(len as u64).read_to_end(&mut bytes)?; Ok(Binary { subtype, bytes }) } } impl DbPointer { pub(crate) fn from_reader<R: Read>(mut reader: R) -> Result<Self> { let ns = read_string(&mut reader, false)?; let oid = ObjectId::from_reader(&mut reader)?; Ok(DbPointer { namespace: ns, id: oid, }) } } impl Regex { pub(crate) fn from_reader<R: Read>(mut reader: R) -> Result<Self> { let pattern = read_cstring(&mut reader)?; let options = read_cstring(&mut reader)?; Ok(Regex { pattern, options }) } } impl Timestamp { pub(crate) fn from_reader<R: Read>(mut reader: R) -> Result<Self> { read_i64(&mut reader).map(Timestamp::from_le_i64) } } impl ObjectId { pub(crate) fn from_reader<R: Read>(mut reader: R) -> Result<Self> { let mut buf = [0u8; 12]; reader.read_exact(&mut buf)?; Ok(Self::from_bytes(buf)) } } impl JavaScriptCodeWithScope { pub(crate) fn from_reader<R: Read>(mut reader: R, utf8_lossy: bool) -> Result<Self> { let length = read_i32(&mut reader)?; if length < MIN_CODE_WITH_SCOPE_SIZE { return Err(Error::invalid_length( length as usize, &format!( "code with scope length must be at least {}", MIN_CODE_WITH_SCOPE_SIZE ) .as_str(), )); } else if length > MAX_BSON_SIZE { return Err(Error::invalid_length( length as usize, &"code with scope length too large", )); } let mut buf = vec![0u8; (length - 4) as usize]; reader.read_exact(&mut buf)?; let mut slice = buf.as_slice(); let code = read_string(&mut slice, utf8_lossy)?; let scope = Document::from_reader(&mut slice)?; Ok(JavaScriptCodeWithScope { code, scope }) } } pub fn from_bson<T>(bson: Bson) -> Result<T> where T: DeserializeOwned, { let de = Deserializer::new(bson); Deserialize::deserialize(de) } pub fn from_document<T>(doc: Document) -> Result<T> where T: DeserializeOwned, { from_bson(Bson::Document(doc)) } fn reader_to_vec<R: Read>(mut reader: R) -> Result<Vec<u8>> { let length = read_i32(&mut reader)?; if length < MIN_BSON_DOCUMENT_SIZE { return Err(Error::custom("document size too small")); } let mut bytes = Vec::with_capacity(length as usize); write_i32(&mut bytes, length).map_err(Error::custom)?; reader.take(length as u64 - 4).read_to_end(&mut bytes)?; Ok(bytes) } pub fn from_reader<R, T>(reader: R) -> Result<T> where T: DeserializeOwned, R: Read, { let bytes = reader_to_vec(reader)?; from_slice(bytes.as_slice()) } pub fn from_reader_utf8_lossy<R, T>(reader: R) -> Result<T> where T: DeserializeOwned, R: Read, { let bytes = reader_to_vec(reader)?; from_slice_utf8_lossy(bytes.as_slice()) } pub fn from_slice<'de, T>(bytes: &'de [u8]) -> Result<T> where T: Deserialize<'de>, { let mut deserializer = raw::Deserializer::new(bytes, false); T::deserialize(&mut deserializer) } pub fn from_slice_utf8_lossy<'de, T>(bytes: &'de [u8]) -> Result<T> where T: Deserialize<'de>, { let mut deserializer = raw::Deserializer::new(bytes, true); T::deserialize(&mut deserializer) }
mod error; mod raw; mod serde; pub use self::{ error::{Error, Result}, serde::Deserializer, }; use std::io::Read; use crate::{ bson::{Array, Binary, Bson, DbPointer, Document, JavaScriptCodeWithScope, Regex, Timestamp}, oid::{self, ObjectId}, ser::write_i32, spec::{self, BinarySubtype}, Decimal128, }; use ::serde::{ de::{DeserializeOwned, Error as _, Unexpected}, Deserialize, }; pub(crate) use self::serde::BsonVisitor; pub(crate) const MAX_BSON_SIZE: i32 = 16 * 1024 * 1024; pub(crate) const MIN_BSON_DOCUMENT_SIZE: i32 = 4 + 1; pub(crate) const MIN_BSON_STRING_SIZE: i32 = 4 + 1; pub(crate) const MIN_CODE_WITH_SCOPE_SIZE: i32 = 4 + MIN_BSON_STRING_SIZE + MIN_BSON_DOCUMENT_SIZE; pub(crate) fn ensure_read_exactly<F, R>( reader: &mut R, length: usize, error_message: &str, func: F, ) -> Result<()> where F: FnOnce(&mut std::io::Cursor<Vec<u8>>) -> Result<()>, R: Read + ?Sized, { let mut buf = vec![0u8; length]; reader.read_exact(&mut buf)?; let mut cursor = std::io::Cursor::new(buf); func(&mut cursor)?; if cursor.position() != length as u64 { return Err(Error::invalid_length(length, &error_message)); } Ok(()) } pub(crate) fn read_string<R: Read + ?Sized>(reader: &mut R, utf8_lossy: bool) -> Result<String> { let len = read_i32(reader)?; if len < 1 { return Err(Error::invalid_length( len as usize, &"UTF-8 string must have at least 1 byte", )); } let s = if utf8_lossy { let mut buf = Vec::with_capacity(len as usize - 1); reader.take(len as u64 - 1).read_to_end(&mut buf)?; String::from_utf8_lossy(&buf).to_string() } else { let mut s = String::with_capacity(len as usize - 1); reader.take(len as u64 - 1).read_to_string(&mut s)?; s }; if read_u8(reader)? != 0 { return Err(Error::invalid_length( len as usize, &"contents of string longer than provided length", )); } Ok(s) } pub(crate) fn read_bool<R: Read>(mut reader: R) -> Result<bool> { let val = read_u8(&mut reader)?; if val > 1 { return Err(Error::invalid_value( Unexpected::Unsigned(val as u64), &"boolean must be stored as 0 or 1", )); } Ok(val != 0) } fn read_cstring<R: Read + ?Sized>(reader: &mut R) -> Result<String> { let mut v = Vec::new(); loop { let c = read_u8(reader)?; if c == 0 { break; } v.push(c); } Ok(String::from_utf8(v)?) } #[inline] pub(crate) fn read_u8<R: Read + ?Sized>(reader: &mut R) -> Result<u8> { let mut buf = [0; 1]; reader.read_exact(&mut buf)?; Ok(u8::from_le_bytes(buf)) } #[inline] pub(crate) fn read_i32<R: Read + ?Sized>(reader: &mut R) -> Result<i32> { let mut buf = [0; 4]; reader.read_exact(&mut buf)?; Ok(i32::from_le_bytes(buf)) } #[inline] pub(crate) fn read_i64<R: Read + ?Sized>(reader: &mut R) -> Result<i64> { let mut buf = [0; 8]; reader.read_exact(&mut buf)?; Ok(i64::from_le_bytes(buf)) } #[inline] fn read_f64<R: Read + ?Sized>(reader: &mut R) -> Result<f64> { let mut buf = [0; 8]; reader.read_exact(&mut buf)?; Ok(f64::from_le_bytes(buf)) } #[inline] fn read_f128<R: Read + ?Sized>(reader: &mut R) -> Result<Decimal128> { let mut buf = [0u8; 128 / 8]; reader.read_exact(&mut buf)?; Ok(Decimal128 { bytes: buf }) } fn deserialize_array<R: Read + ?Sized>(reader: &mut R, utf8_lossy: bool) -> Result<Array> { let mut arr = Array::new(); let length = read_i32(reader)?; if !(MIN_BSON_DOCUMENT_SIZE..=MAX_BSON_SIZE).contains(&length) { return Err(Error::invalid_length( length as usize, &format!( "array length must be between {} and {}", MIN_BSON_DOCUMENT_SIZE, MAX_BSON_SIZE ) .as_str(), )); } ensure_read_exactly( reader, (length as usize) - 4, "array length longer than contents", |cursor| { loop { let tag = read_u8(cursor)?; if tag == 0 {
pub(crate) fn deserialize_bson_kvp<R: Read + ?Sized>( reader: &mut R, tag: u8, utf8_lossy: bool, ) -> Result<(String, Bson)> { use spec::ElementType; let key = read_cstring(reader)?; let val = match ElementType::from(tag) { Some(ElementType::Double) => Bson::Double(read_f64(reader)?), Some(ElementType::String) => read_string(reader, utf8_lossy).map(Bson::String)?, Some(ElementType::EmbeddedDocument) => Document::from_reader(reader).map(Bson::Document)?, Some(ElementType::Array) => deserialize_array(reader, utf8_lossy).map(Bson::Array)?, Some(ElementType::Binary) => Bson::Binary(Binary::from_reader(reader)?), Some(ElementType::ObjectId) => { let mut objid = [0; 12]; for x in &mut objid { *x = read_u8(reader)?; } Bson::ObjectId(oid::ObjectId::from_bytes(objid)) } Some(ElementType::Boolean) => Bson::Boolean(read_bool(reader)?), Some(ElementType::Null) => Bson::Null, Some(ElementType::RegularExpression) => { Bson::RegularExpression(Regex::from_reader(reader)?) } Some(ElementType::JavaScriptCode) => { read_string(reader, utf8_lossy).map(Bson::JavaScriptCode)? } Some(ElementType::JavaScriptCodeWithScope) => { Bson::JavaScriptCodeWithScope(JavaScriptCodeWithScope::from_reader(reader, utf8_lossy)?) } Some(ElementType::Int32) => read_i32(reader).map(Bson::Int32)?, Some(ElementType::Int64) => read_i64(reader).map(Bson::Int64)?, Some(ElementType::Timestamp) => Bson::Timestamp(Timestamp::from_reader(reader)?), Some(ElementType::DateTime) => { let time = read_i64(reader)?; Bson::DateTime(crate::DateTime::from_millis(time)) } Some(ElementType::Symbol) => read_string(reader, utf8_lossy).map(Bson::Symbol)?, Some(ElementType::Decimal128) => read_f128(reader).map(Bson::Decimal128)?, Some(ElementType::Undefined) => Bson::Undefined, Some(ElementType::DbPointer) => Bson::DbPointer(DbPointer::from_reader(reader)?), Some(ElementType::MaxKey) => Bson::MaxKey, Some(ElementType::MinKey) => Bson::MinKey, None => { return Err(Error::UnrecognizedDocumentElementType { key, element_type: tag, }) } }; Ok((key, val)) } impl Binary { pub(crate) fn from_reader<R: Read>(mut reader: R) -> Result<Self> { let len = read_i32(&mut reader)?; if !(0..=MAX_BSON_SIZE).contains(&len) { return Err(Error::invalid_length( len as usize, &format!("binary length must be between 0 and {}", MAX_BSON_SIZE).as_str(), )); } let subtype = BinarySubtype::from(read_u8(&mut reader)?); Self::from_reader_with_len_and_payload(reader, len, subtype) } pub(crate) fn from_reader_with_len_and_payload<R: Read>( mut reader: R, mut len: i32, subtype: BinarySubtype, ) -> Result<Self> { if !(0..=MAX_BSON_SIZE).contains(&len) { return Err(Error::invalid_length( len as usize, &format!("binary length must be between 0 and {}", MAX_BSON_SIZE).as_str(), )); } if let BinarySubtype::BinaryOld = subtype { let data_len = read_i32(&mut reader)?; if !(0..=(MAX_BSON_SIZE - 4)).contains(&data_len) { return Err(Error::invalid_length( data_len as usize, &format!("0x02 length must be between 0 and {}", MAX_BSON_SIZE - 4).as_str(), )); } if data_len + 4 != len { return Err(Error::invalid_length( data_len as usize, &"0x02 length did not match top level binary length", )); } len -= 4; } let mut bytes = Vec::with_capacity(len as usize); reader.take(len as u64).read_to_end(&mut bytes)?; Ok(Binary { subtype, bytes }) } } impl DbPointer { pub(crate) fn from_reader<R: Read>(mut reader: R) -> Result<Self> { let ns = read_string(&mut reader, false)?; let oid = ObjectId::from_reader(&mut reader)?; Ok(DbPointer { namespace: ns, id: oid, }) } } impl Regex { pub(crate) fn from_reader<R: Read>(mut reader: R) -> Result<Self> { let pattern = read_cstring(&mut reader)?; let options = read_cstring(&mut reader)?; Ok(Regex { pattern, options }) } } impl Timestamp { pub(crate) fn from_reader<R: Read>(mut reader: R) -> Result<Self> { read_i64(&mut reader).map(Timestamp::from_le_i64) } } impl ObjectId { pub(crate) fn from_reader<R: Read>(mut reader: R) -> Result<Self> { let mut buf = [0u8; 12]; reader.read_exact(&mut buf)?; Ok(Self::from_bytes(buf)) } } impl JavaScriptCodeWithScope { pub(crate) fn from_reader<R: Read>(mut reader: R, utf8_lossy: bool) -> Result<Self> { let length = read_i32(&mut reader)?; if length < MIN_CODE_WITH_SCOPE_SIZE { return Err(Error::invalid_length( length as usize, &format!( "code with scope length must be at least {}", MIN_CODE_WITH_SCOPE_SIZE ) .as_str(), )); } else if length > MAX_BSON_SIZE { return Err(Error::invalid_length( length as usize, &"code with scope length too large", )); } let mut buf = vec![0u8; (length - 4) as usize]; reader.read_exact(&mut buf)?; let mut slice = buf.as_slice(); let code = read_string(&mut slice, utf8_lossy)?; let scope = Document::from_reader(&mut slice)?; Ok(JavaScriptCodeWithScope { code, scope }) } } pub fn from_bson<T>(bson: Bson) -> Result<T> where T: DeserializeOwned, { let de = Deserializer::new(bson); Deserialize::deserialize(de) } pub fn from_document<T>(doc: Document) -> Result<T> where T: DeserializeOwned, { from_bson(Bson::Document(doc)) } fn reader_to_vec<R: Read>(mut reader: R) -> Result<Vec<u8>> { let length = read_i32(&mut reader)?; if length < MIN_BSON_DOCUMENT_SIZE { return Err(Error::custom("document size too small")); } let mut bytes = Vec::with_capacity(length as usize); write_i32(&mut bytes, length).map_err(Error::custom)?; reader.take(length as u64 - 4).read_to_end(&mut bytes)?; Ok(bytes) } pub fn from_reader<R, T>(reader: R) -> Result<T> where T: DeserializeOwned, R: Read, { let bytes = reader_to_vec(reader)?; from_slice(bytes.as_slice()) } pub fn from_reader_utf8_lossy<R, T>(reader: R) -> Result<T> where T: DeserializeOwned, R: Read, { let bytes = reader_to_vec(reader)?; from_slice_utf8_lossy(bytes.as_slice()) } pub fn from_slice<'de, T>(bytes: &'de [u8]) -> Result<T> where T: Deserialize<'de>, { let mut deserializer = raw::Deserializer::new(bytes, false); T::deserialize(&mut deserializer) } pub fn from_slice_utf8_lossy<'de, T>(bytes: &'de [u8]) -> Result<T> where T: Deserialize<'de>, { let mut deserializer = raw::Deserializer::new(bytes, true); T::deserialize(&mut deserializer) }
break; } let (_, val) = deserialize_bson_kvp(cursor, tag, utf8_lossy)?; arr.push(val) } Ok(()) }, )?; Ok(arr) }
function_block-function_prefix_line
[ { "content": "/// Attempts to serialize a u64 as an i32. Errors if an exact conversion is not possible.\n\npub fn serialize_u64_as_i32<S: Serializer>(val: &u64, serializer: S) -> Result<S::Ok, S::Error> {\n\n match i32::try_from(*val) {\n\n Ok(val) => serializer.serialize_i32(val),\n\n Err(_) =...
Rust
src/shared/crossterm.rs
jojolepro/crossterm
f4d2ab4feb520e687540e8917793f4fb32f0fe34
use super::super::cursor; use super::super::style; use super::super::terminal::terminal; use Context; use std::fmt::Display; use std::mem; use std::rc::Rc; use std::sync::Arc; use std::convert::From; pub struct Crossterm { context: Rc<Context> } impl From<Rc<Context>> for Crossterm { fn from(context: Rc<Context>) -> Self { return Crossterm { context: context } } } impl Crossterm { pub fn new() -> Crossterm { return Crossterm { context: Context::new() }; } pub fn terminal(&self) -> terminal::Terminal { return terminal::Terminal::new(self.context.clone()); } pub fn cursor(&self) -> cursor::TerminalCursor { return cursor::TerminalCursor::new(self.context.clone()) } pub fn color(&self) -> style::TerminalColor { return style::TerminalColor::new(self.context.clone()); } pub fn paint<'a, D: Display>(&'a self, value: D) -> style::StyledObject<D> { self.terminal().paint(value) } pub fn write<D: Display>(&self, value: D) { self.terminal().write(value) } pub fn context(&self) -> Rc<Context> { self.context.clone() } }
use super::super::cursor; use super::super::style; use super::super::terminal::terminal; use Context; use std::fmt::Display; use std::mem; use std::rc::Rc; use std::sync::Arc; use std::convert::From; pub struct Crossterm { context: Rc<Context> } impl From<Rc<Context>> for Crossterm { fn from(context: Rc<Context>) -> Self { return Crossterm { context: context } } } impl Crossterm { pub fn new() -> Crossterm { return Crossterm { context: Context::new() }; } pub fn terminal(&self) -> terminal::Terminal { return terminal::Terminal::new(self.context.clone()); } pub fn cursor(&self) -> cursor::TerminalCursor { return cursor::TerminalCursor::new(self.context.clone()) } pub fn color(&self) -> style::TerminalColor { return style::TerminalColor::new(self.context.clone());
paint<'a, D: Display>(&'a self, value: D) -> style::StyledObject<D> { self.terminal().paint(value) } pub fn write<D: Display>(&self, value: D) { self.terminal().write(value) } pub fn context(&self) -> Rc<Context> { self.context.clone() } }
} pub fn
random
[ { "content": "/// print wait screen on alternate screen, then swich back.\n\npub fn print_wait_screen_on_alternate_window(context: Rc<Context>) {\n\n // create scope. If this scope ends the screen will be switched back to mainscreen.\n\n // because `AlternateScreen` switches back to main screen when switc...
Rust
nrf-softdevice/src/flash.rs
timokroeger/nrf-softdevice
6a01c4ceb7d1f1d9fc06e74e9a264037ac1159c5
use core::future::Future; use core::marker::PhantomData; use core::sync::atomic::{AtomicBool, Ordering}; use embassy::traits::flash::Error as FlashError; use crate::raw; use crate::util::{DropBomb, Signal}; use crate::{RawError, Softdevice}; pub struct Flash { _private: PhantomData<*mut ()>, } static FLASH_TAKEN: AtomicBool = AtomicBool::new(false); impl Flash { const PAGE_SIZE: usize = 4096; pub fn take(_sd: &Softdevice) -> Flash { if FLASH_TAKEN .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire) .is_err() { panic!("nrf_softdevice::Softdevice::take_flash() called multiple times.") } Flash { _private: PhantomData, } } } static SIGNAL: Signal<Result<(), FlashError>> = Signal::new(); pub(crate) fn on_flash_success() { SIGNAL.signal(Ok(())) } pub(crate) fn on_flash_error() { SIGNAL.signal(Err(FlashError::Failed)) } impl embassy::traits::flash::Flash for Flash { type ReadFuture<'a> = impl Future<Output = Result<(), FlashError>> + 'a; type WriteFuture<'a> = impl Future<Output = Result<(), FlashError>> + 'a; type ErasePageFuture<'a> = impl Future<Output = Result<(), FlashError>> + 'a; fn read<'a>(&'a mut self, address: usize, data: &'a mut [u8]) -> Self::ReadFuture<'a> { async move { data.copy_from_slice(unsafe { core::slice::from_raw_parts(address as *const u8, data.len()) }); Ok(()) } } fn write<'a>(&'a mut self, address: usize, data: &'a [u8]) -> Self::WriteFuture<'a> { async move { let data_ptr = data.as_ptr(); let data_len = data.len() as u32; if address % 4 != 0 { return Err(FlashError::AddressMisaligned); } if (data_ptr as u32) % 4 != 0 || data_len % 4 != 0 { return Err(FlashError::BufferMisaligned); } let words_ptr = data_ptr as *const u32; let words_len = data_len / 4; let bomb = DropBomb::new(); let ret = unsafe { raw::sd_flash_write(address as _, words_ptr, words_len) }; let ret = match RawError::convert(ret) { Ok(()) => SIGNAL.wait().await, Err(_e) => { warn!("sd_flash_write err {:?}", _e); Err(FlashError::Failed) } }; bomb.defuse(); ret } } fn erase<'a>(&'a mut self, address: usize) -> Self::ErasePageFuture<'a> { async move { if address % Self::PAGE_SIZE != 0 { return Err(FlashError::AddressMisaligned); } let page_number = address / Self::PAGE_SIZE; let bomb = DropBomb::new(); let ret = unsafe { raw::sd_flash_page_erase(page_number as u32) }; let ret = match RawError::convert(ret) { Ok(()) => SIGNAL.wait().await, Err(_e) => { warn!("sd_flash_page_erase err {:?}", _e); Err(FlashError::Failed) } }; bomb.defuse(); ret } } fn size(&self) -> usize { 256 * 4096 } fn read_size(&self) -> usize { 1 } fn write_size(&self) -> usize { 4 } fn erase_size(&self) -> usize { 4096 } }
use core::future::Future; use core::marker::PhantomData; use core::sync::atomic::{AtomicBool, Ordering}; use embassy::traits::flash::Error as FlashError; use crate::raw; use crate::util::{DropBomb, Signal}; use crate::{RawError, Softdevice}; pub struct Flash { _private: PhantomData<*mut ()>, } static FLASH_TAKEN: AtomicBool = AtomicBool::new(false); impl Flash { const PAGE_SIZE: usize = 4096; pub fn take(_sd: &Softdevice) -> Flash { if FLASH_TAKEN .compare_exchange(false, true, Order
a.as_ptr(); let data_len = data.len() as u32; if address % 4 != 0 { return Err(FlashError::AddressMisaligned); } if (data_ptr as u32) % 4 != 0 || data_len % 4 != 0 { return Err(FlashError::BufferMisaligned); } let words_ptr = data_ptr as *const u32; let words_len = data_len / 4; let bomb = DropBomb::new(); let ret = unsafe { raw::sd_flash_write(address as _, words_ptr, words_len) }; let ret = match RawError::convert(ret) { Ok(()) => SIGNAL.wait().await, Err(_e) => { warn!("sd_flash_write err {:?}", _e); Err(FlashError::Failed) } }; bomb.defuse(); ret } } fn erase<'a>(&'a mut self, address: usize) -> Self::ErasePageFuture<'a> { async move { if address % Self::PAGE_SIZE != 0 { return Err(FlashError::AddressMisaligned); } let page_number = address / Self::PAGE_SIZE; let bomb = DropBomb::new(); let ret = unsafe { raw::sd_flash_page_erase(page_number as u32) }; let ret = match RawError::convert(ret) { Ok(()) => SIGNAL.wait().await, Err(_e) => { warn!("sd_flash_page_erase err {:?}", _e); Err(FlashError::Failed) } }; bomb.defuse(); ret } } fn size(&self) -> usize { 256 * 4096 } fn read_size(&self) -> usize { 1 } fn write_size(&self) -> usize { 4 } fn erase_size(&self) -> usize { 4096 } }
ing::AcqRel, Ordering::Acquire) .is_err() { panic!("nrf_softdevice::Softdevice::take_flash() called multiple times.") } Flash { _private: PhantomData, } } } static SIGNAL: Signal<Result<(), FlashError>> = Signal::new(); pub(crate) fn on_flash_success() { SIGNAL.signal(Ok(())) } pub(crate) fn on_flash_error() { SIGNAL.signal(Err(FlashError::Failed)) } impl embassy::traits::flash::Flash for Flash { type ReadFuture<'a> = impl Future<Output = Result<(), FlashError>> + 'a; type WriteFuture<'a> = impl Future<Output = Result<(), FlashError>> + 'a; type ErasePageFuture<'a> = impl Future<Output = Result<(), FlashError>> + 'a; fn read<'a>(&'a mut self, address: usize, data: &'a mut [u8]) -> Self::ReadFuture<'a> { async move { data.copy_from_slice(unsafe { core::slice::from_raw_parts(address as *const u8, data.len()) }); Ok(()) } } fn write<'a>(&'a mut self, address: usize, data: &'a [u8]) -> Self::WriteFuture<'a> { async move { let data_ptr = dat
random
[ { "content": "pub fn gen_bindings(\n\n tmp_dir: &PathBuf,\n\n src_dir: &PathBuf,\n\n dst: &PathBuf,\n\n mut f: impl FnMut(String) -> String,\n\n) {\n\n let mut wrapper = String::new();\n\n\n\n for entry in WalkDir::new(src_dir)\n\n .follow_links(true)\n\n .into_iter()\n\n ...