repo
stringlengths
6
65
file_url
stringlengths
81
311
file_path
stringlengths
6
227
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:31:58
2026-01-04 20:25:31
truncated
bool
2 classes
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/数据结构和算法/linear_data_structure/src/bin/queue.rs
数据结构和算法/linear_data_structure/src/bin/queue.rs
//!实现队列 #[derive(Debug)] pub struct Queue<T> { cap: usize, datas: Vec<T>, } impl<T> Queue<T> { pub fn new(size: usize) -> Self { Self { cap: size, datas: Vec::with_capacity(size), } } // 判断队列元素个数 pub fn len(&self) -> usize { self.datas.len() } // 判断队列是否为空 pub fn is_empty(&self) -> bool { 0 == self.len() } // 判断队列是否满 pub fn is_full(&self) -> bool { self.len() == self.cap } // 清空队列 pub fn clear(&mut self) { self.datas.clear(); self.datas = Vec::with_capacity(self.cap); } // 入队 pub fn enqueue(&mut self, val: T) -> Result<(), String> { if self.is_full() { return Err("没有空间".to_string()); } else { self.datas.insert(0, val); } Ok(()) } // 出队 pub fn dequeue(&mut self) -> Option<T> { if self.is_empty() { None } else { self.datas.pop() } } // 将队列转换为迭代器(消耗队列) pub fn into_iter(self) -> IntoIter<T> { IntoIter(self) } // 将队列转换为引用迭代器 pub fn iter(&self) -> Iter<T> { let mut iter = Iter(Vec::new()); for i in self.datas.iter() { iter.0.push(i); } iter } // 将队列转换为可变引用迭代器 pub fn iter_mut(&mut self) -> IterMut<T> { let mut iter_mut = IterMut(Vec::new()); for i in self.datas.iter_mut() { iter_mut.0.push(i); } iter_mut } } struct IterMut<'a, T: 'a>(Vec<&'a mut T>); impl<'a, T> Iterator for IterMut<'a, T> { type Item = &'a mut T; fn next(&mut self) -> Option<Self::Item> { if self.0.len() == 0 { None } else { Some(self.0.remove(0)) } } } struct IntoIter<T>(Queue<T>); impl<T> Iterator for IntoIter<T> { type Item = T; fn next(&mut self) -> Option<Self::Item> { self.0.dequeue() } } struct Iter<'a, T: 'a>(Vec<&'a T>); impl<'a, T> Iterator for Iter<'a, T> { type Item = &'a T; fn next(&mut self) -> Option<Self::Item> { if 0 != self.0.len() { Some(self.0.remove(0)) } else { None } } } fn main() { basic(); iter(); fn basic() { let mut q = Queue::new(2); let _r1 = q.enqueue(1); let _r3 = q.enqueue(3); if let Err(error) = q.enqueue(5) { println!("Enqueue error: {error}"); } if let Some(data) = q.dequeue() { println!("dequeue data: {data}"); } else { println!("empty queue"); } println!("empty: {}, len: {}", q.is_empty(), q.len()); println!("full: {}", q.is_full()); println!("q: {:?}", q); q.clear(); println!("{:?}", q); } fn iter() { let mut q = Queue::new(3); let _r1 = q.enqueue(1); let _r3 = q.enqueue(3); let sum1 = q.iter().sum::<i32>(); let mut sum = 0; for item in q.iter_mut() { *item += 1; sum += 1; } let sum2 = q.iter().sum::<i32>(); println!("{sum1} + {sum} = {sum2}"); println!("sum = {}", q.into_iter().sum::<i32>()); } }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/数据结构和算法/linear_data_structure/src/bin/use_dequeue_palindrome_checker.rs
数据结构和算法/linear_data_structure/src/bin/use_dequeue_palindrome_checker.rs
//!使用双端队列进行回文检测 use dequeue::Dequeue; mod dequeue; // 检测字符串是否是回文字符串 fn check_palindrome(input: &str) -> bool { let mut dq = Dequeue::new(input.len()); for c in input.chars() { let _ = dq.add_rear(c); } let mut is_match = true; while dq.len() > 1 && is_match { let head = dq.remove_front(); let tail = dq.remove_rear(); if head != tail { is_match = false; } } is_match } fn main() { let a = "i love you"; println!("input:'{a}' is palindrome:{}", check_palindrome(a)); let a = "i love i"; println!("input:'{a}' is palindrome:{}", check_palindrome(a)); let a = "1 2 3 4 5 6 7 8 9 0 0 9 8 7 6 5 4 3 2 1"; println!("input:'{a}' is palindrome:{}", check_palindrome(a)); }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/数据结构和算法/consistency_hash/src/bin/consistency_hash.rs
数据结构和算法/consistency_hash/src/bin/consistency_hash.rs
//! 一致性hash算法 use std::{ collections::{hash_map::DefaultHasher, BTreeMap}, fmt::Debug, hash::{Hash, Hasher}, }; // 主机节点 #[derive(Debug, Clone)] struct MachineNode { host: &'static str, ip: &'static str, port: u16, } // 为MachineNode添加字符串转换 impl ToString for MachineNode { fn to_string(&self) -> String { self.ip.to_string() + &self.port.to_string() } } // 环 #[derive(Debug)] struct Ring<T: Clone + Debug + ToString> { // 每台主机的虚拟节点数 machine_virtual_node_num: usize, // 用于保存环上的数据 datas: BTreeMap<u64, T>, } // 默认主机虚拟节点数为10 const DEFAULT_MACHINE_VIRTUAL_NODE_NUM: usize = 10; // hash函数 fn hash<T: Hash>(val: &T) -> u64 { let mut hasher = DefaultHasher::new(); val.hash(&mut hasher); hasher.finish() % 197 } impl<T: Debug + Clone + ToString> Ring<T> { fn new() -> Self { Self::with_virtual_node_num(DEFAULT_MACHINE_VIRTUAL_NODE_NUM) } fn with_virtual_node_num(num: usize) -> Self { Self { machine_virtual_node_num: num, datas: BTreeMap::new(), } } // 增加节点到环上 fn add(&mut self, node: &T) { // 将主机虚拟出machine_virtual_node_num个数量 for i in 0..self.machine_virtual_node_num { let key = hash(&(node.to_string() + &i.to_string())); self.datas.insert(key, node.clone()); } } // 批量添加到环 fn mult_add(&mut self, nodes: &[T]) { if !nodes.is_empty() { for node in nodes { self.add(node); } } } // 从环上移除节点 fn remove(&mut self, node: &T) { assert!(!self.datas.is_empty()); for i in 0..self.machine_virtual_node_num { let key = hash(&(node.to_string() + &i.to_string())); self.datas.remove(&key); } } // 批量删除 fn mult_remove(&mut self, nodes: &[T]) { if !nodes.is_empty() { for node in nodes { self.remove(node); } } } // 获取节点 fn get(&self, key: u64) -> Option<&T> { if self.datas.is_empty() { println!("-----"); return None; } let mut keys = self.datas.keys(); println!("key:{key}"); keys.find(|&k| k >= &key) .and_then(|k| self.datas.get(k)) .or(keys.nth(0).and_then(|x| self.datas.get(x))) } // 获取处理数据的机器 fn dispatch(&self, data: i32) -> Option<&T> { let key = hash(&data); self.get(key) } } fn main() { let virtual_num = 2; let mut ring = Ring::with_virtual_node_num(virtual_num); let node1 = MachineNode { host: "bigdata1", ip: "192.168.0.29", port: 18088, }; let node2 = MachineNode { host: "bigdata2", ip: "192.168.0.14", port: 28089, }; let node3 = MachineNode { host: "bigdata3", ip: "192.168.0.22", port: 8088, }; let node4 = MachineNode { host: "bigdata4", ip: "192.168.0.222", port: 8088, }; ring.add(&node1); ring.add(&node2); ring.add(&node3); ring.add(&node4); println!("ring:{:#?}", ring); // 一个数据过来,通过get方法获取哪台机器处理 let quest = 123; let result = ring.dispatch(quest); println!("处理机器:{:#?}", result); let quest = 1234; let result = ring.dispatch(quest); println!("处理机器:{:#?}", result); let quest = 12345; let result = ring.dispatch(quest); println!("处理机器:{:#?}", result); }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/数据结构和算法/lru/src/bin/lru.rs
数据结构和算法/lru/src/bin/lru.rs
//! LRU 最近最少使用缓存淘汰算法 //! 基于LRUList数据结构:双向链表且头节点指向尾节点 use std::{collections::HashMap, mem::swap}; // 可变裸指针,方便通过裸指针修改 type LRUHandle<T> = *mut LRUNode<T>; #[derive(Debug)] struct LRUNode<T> { next: Option<Box<LRUNode<T>>>, prev: Option<LRUHandle<T>>, data: Option<T>, } #[derive(Debug)] struct LRUList<T> { head: LRUNode<T>, count: usize, } impl<T> LRUList<T> { /// 初始化LRUList fn new() -> Self { LRUList { head: LRUNode { next: None, prev: None, data: None, }, count: 0, } } /// 在首部插入值 fn insert(&mut self, data: T) -> LRUHandle<T> { // 长度+1 self.count += 1; // 判断插入的位置:尾部和首部 let mut node = Box::new(LRUNode { next: None, prev: Some(&mut self.head), data: Some(data), }); let newp = node.as_mut() as *mut LRUNode<T>; // 没有节点 if self.head.next.is_none() { // head的前驱节点指向最后加入的节点 self.head.prev = Some(newp); } // 在头部加入 else { self.head.next.as_mut().unwrap().prev = Some(newp); node.next = self.head.next.take(); } self.head.next = Some(node); newp } /// 从双向链表中删除数据 fn remove(&mut self, handle: LRUHandle<T>) -> T { unsafe { let d = (*handle).data.take().unwrap(); let mut current = (*(*handle).prev.unwrap()).next.take().unwrap(); let pre = current.prev.unwrap(); // 如果不是尾部节点 if current.next.is_some() { current.next.as_mut().unwrap().prev = current.prev.take(); } (*pre).next = current.next.take(); // 长度减1 self.count -= 1; d } } /// 删除最后一个数据 fn remove_last(&mut self) -> Option<T> { if self.count == 0 { return None; } let last = unsafe { // 找到最后节点的前一个节点,拿走next的所有权 (*(*self.head.prev.unwrap()).prev.unwrap()).next.take() }; if let Some(mut last_node) = last { // 修改head的prev指向last_node的前一个节点 self.head.prev = last_node.prev; self.count -= 1; // 拿走last_node数据所有权 last_node.data.take() } else { None } } /// 重新在首部插入数据 fn reinsert_front(&mut self, handler: LRUHandle<T>) { unsafe { // 当前节点的前向节点指针 let prevp = (*handler).prev.unwrap(); // 修改指针指向 // 1.当前节点处于中间 if let Some(next) = (*handler).next.as_mut() { next.prev = Some(prevp); } // 2.当前节点处于尾部 else { self.head.prev = Some(prevp); } // 3.交换指向 swap(&mut (*prevp).next, &mut (*handler).next); // prepv-handler.next;handler.next=self swap(&mut (*handler).next, &mut self.head.next); //head.next = handler;handler.next = old head.next if let Some(ref mut next) = (*handler).next { (*handler).prev = next.prev; next.prev = Some(handler); } else { self.head.prev = Some(handler); } } } fn count(&self) -> usize { self.count } } /// 基于LRUList构建Cache /// cache基于cachekey快速查找 type CacheKey = [u8; 16]; // 记录value和key在链表中的指针 type CacheEntry<T> = (T, LRUHandle<CacheKey>); #[derive(Debug)] struct Cache<T> { // 记录cache key的关系 list: LRUList<CacheKey>, // 记录key和value的关系 map: HashMap<CacheKey, CacheEntry<T>>, // cache容量 cap: usize, } impl<T> Cache<T> { fn new(cap: usize) -> Self { Cache { list: LRUList::new(), map: HashMap::with_capacity(cap * 2), cap, } } fn insert(&mut self, key: &CacheKey, data: T) { // 先移除最近最少使用数据再插入 if self.list.count >= self.cap { println!("缓存已满,删除最近最少使用数据..."); if let Some(remove_key) = self.list.remove_last() { self.map.remove(&remove_key).unwrap(); } else { println!("删除数据失败"); } } let handle = self.list.insert(*key); self.map.insert(*key, (data, handle)); } fn get(&mut self, key: &CacheKey) -> Option<&T> { match self.map.get(key) { None => None, Some((data, handle)) => { self.list.reinsert_front(*handle); Some(data) } } } fn remove(&mut self, key: &CacheKey) -> Option<T> { match self.map.remove(key) { None => None, Some((data, handle)) => { self.list.remove(handle); Some(data) } } } fn count(&self) -> usize { self.list.count() } } fn gen_key(a: u8, b: u8, c: u8) -> CacheKey { [a, b, c, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] } fn main() { let mut cache: Cache<i32> = Cache::new(3); let key1 = gen_key(1, 2, 3); let key2 = gen_key(1, 2, 5); let key3 = gen_key(1, 2, 7); let key4 = gen_key(1, 2, 9); let key5 = gen_key(1, 2, 11); let key6 = gen_key(1, 2, 12); cache.insert(&key1, 123); cache.insert(&key2, 125); cache.insert(&key3, 127); cache.insert(&key4, 129); cache.insert(&key5, 1211); cache.insert(&key6, 1212); println!("cache 数据条数:{}", cache.count()); println!("删除key5:{:?}", cache.remove(&key5)); println!("cache 数据条数:{}", cache.count()); cache.get(&key6); println!( "最近访问元素:{:?}", &cache.list.head.next.as_ref().unwrap().data ); cache.get(&key4); println!( "最近访问元素:{:?}", &cache.list.head.next.as_ref().unwrap().data ); }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/数据结构和算法/sort_algorithms/src/bin/heap_sort.rs
数据结构和算法/sort_algorithms/src/bin/heap_sort.rs
//! 堆排序 //! 平均复杂度O(nlog2n) 空间复杂度O(1) 不稳定 /// 计算父节点下标 fn parent(child_index: usize) -> usize { child_index >> 1 } /// 计算左子节点的下标 fn left_child(parent_index: usize) -> usize { parent_index << 1 } /// 计算右子节点的下标 fn right_child(parent_index: usize) -> usize { (parent_index << 1) + 1 } pub fn heap_sort(nums: &mut [i32]) { if nums.len() < 2 { return; } let len = nums.len() - 1; let parent = parent(len); // 非叶子节点:[0..len/2 -1] // 构建完成后,堆顶是最大元素 for p in (1..=parent).rev() { // 构建大顶堆 (下标从1开始是为了方便孩子节点关系:左孩子left_c=2*p 右孩子right_c=2*p+1) move_down(nums, p); } for end in (1..nums.len()).rev() { // 堆顶元素和最后一个元素交换 nums.swap(1, end); // 重建堆 move_down(&mut nums[..end], 1); } } fn move_down(nums: &mut [i32], mut parent: usize) { // nums最后索引 let last = nums.len() - 1; loop { // 左孩子 let left = left_child(parent); // 右孩子 let right = right_child(parent); // 退出条件 if left > last { break; } // 找到大的孩子 let child = if right <= last && nums[left] < nums[right] { right } else { left }; // 孩子子节点大于父节点,交换数据 if nums[child] > nums[parent] { nums.swap(parent, child); } // 一直下推,直到退出条件 parent = child; } } fn main() { // 第一项用0填充,是无效项 let mut nums = [0, 88, 99, 66, 33, 123, 45, 890, 10, 18, 9999, -9876]; println!("原始值:{:?}", &nums); heap_sort(&mut nums); println!("排序结果:{:?}", nums); }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/数据结构和算法/sort_algorithms/src/bin/counting_sort.rs
数据结构和算法/sort_algorithms/src/bin/counting_sort.rs
//! 计数排序 //! 平均时间复杂度O(n+k) 空间复杂度O(n+k) 稳定 n为待排数组长度,k为待排数据个数 pub fn counting_sort(nums: &mut [usize]) { if nums.len() <= 1 { return; } // 桶的数量等于最大值-最小值+1 let max = nums.iter().max().unwrap().clone(); let min = nums.iter().min().unwrap().clone(); let bkt_nums = max - min + 1; // 将数据入桶 let mut counter = vec![0; bkt_nums]; for i in nums.iter() { let index = (i - min) as usize; counter[index] += 1; } // 将数据写回 let mut j = 0; for i in 0..bkt_nums { while counter[i] > 0 { nums[j] = i + min; counter[i] -= 1; j += 1; } } } fn main() { let mut nums = [88999, 99, 66, 33, 123, 45, 890, 10, 18, 897543]; println!("原始值:{:?}", &nums); counting_sort(&mut nums); println!("排序结果:{:?}", nums); }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/数据结构和算法/sort_algorithms/src/bin/select_sort.rs
数据结构和算法/sort_algorithms/src/bin/select_sort.rs
//! 选择排序 //! 平均时间复杂度O(n^2) 空间复杂度 O(1) 不稳定 pub fn select_sort(nums: &mut [i32]) { let mut left = nums.len() - 1; while left > 0 { let mut pos_max = 0; for i in 1..=left { if nums[i] > nums[pos_max] { pos_max = i; } } // 交换数据,完成一轮数据的排序,并将待排序数据个数减1 nums.swap(left, pos_max); left -= 1; } } fn main() { let mut nums = [88, 99, 66, 33, 123, 45, 890, 10, 18, 9999, -9876]; println!("原始值:{:?}", &nums); select_sort(&mut nums); println!("排序结果:{:?}", nums); }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/数据结构和算法/sort_algorithms/src/bin/radix_sort.rs
数据结构和算法/sort_algorithms/src/bin/radix_sort.rs
//! 基数排序 //! 平均时间复杂度O(O*K) 空间复杂度O(n+k) 稳定 pub fn radix_sort(nums: &mut [usize]) { if nums.len() <= 1 { return; } // 最大值 let max_num = nums.iter().max().unwrap().clone(); // 寻找最小的x,使得2^x>= len let radix = nums.len().next_power_of_two(); let mut digit = 1; while digit <= max_num { let index_of = |x| x / digit % radix; let mut counter = vec![0; radix]; for &x in nums.iter() { counter[index_of(x)] += 1; } for i in 1..radix { counter[i] += counter[i - 1]; } for &x in nums.to_owned().iter().rev() { counter[index_of(x)] -= 1; nums[counter[index_of(x)]] = x; } digit *= radix; } } fn main() { let mut nums = [88999, 99, 66, 33, 123, 45, 890, 10, 18]; println!("原始值:{:?}", &nums); // 需要确保数值越大hash越大,不能用取余符号 radix_sort(&mut nums); println!("排序结果:{:?}", nums); }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/数据结构和算法/sort_algorithms/src/bin/compare_test.rs
数据结构和算法/sort_algorithms/src/bin/compare_test.rs
use std::time::{Duration, Instant}; use bubbule_sort::bubbule_sort; use shell_sort::shell_sort; use quick_sort::quick_sort; use insertion_sort::insert_sort; use merge_sort::merge_sort; use select_sort::select_sort; use heap_sort::heap_sort; use counting_sort::counting_sort; use bucket_sort::bucket_sort; use radix_sort::radix_sort; use rand::{thread_rng, Rng}; use std::thread; mod bubbule_sort; mod bucket_sort; mod counting_sort; mod heap_sort; mod insertion_sort; mod merge_sort; mod quick_sort; mod radix_sort; mod select_sort; mod shell_sort; fn gen_large_nums_usize()->Vec<usize>{ let mut rng = thread_rng(); let mut random_nums = Vec::with_capacity(100000); for _ in 0..100000{ random_nums.push(rng.gen_range(usize::MIN..=usize::MAX)); } random_nums } fn gen_large_nums_i32()->Vec<i32>{ let mut rng = thread_rng(); let mut random_nums = Vec::with_capacity(100000); for _ in 0..100000{ random_nums.push(rng.gen_range(i32::MIN..=i32::MAX)); } random_nums } fn main(){ let start = Instant::now(); bubbule_sort(&mut gen_large_nums_i32()); println!("冒泡排序耗时:{:?}",start.elapsed()); let start = Instant::now(); shell_sort(&mut gen_large_nums_i32()); println!("希尔排序耗时:{:?}",start.elapsed()); let start = Instant::now(); quick_sort(&mut gen_large_nums_i32(),0,99999); println!("快速排序耗时:{:?}",start.elapsed()); let start = Instant::now(); insert_sort(&mut gen_large_nums_i32()); println!("插入排序耗时:{:?}",start.elapsed()); let start = Instant::now(); merge_sort(&mut gen_large_nums_i32()); println!("归并排序耗时:{:?}",start.elapsed()); let start = Instant::now(); select_sort(&mut gen_large_nums_i32()); println!("选择排序耗时:{:?}",start.elapsed()); let start = Instant::now(); heap_sort(&mut gen_large_nums_i32()); println!("堆排序耗时:{:?}",start.elapsed()); let start = Instant::now(); bucket_sort(&mut gen_large_nums_i32(),|x|x/29); println!("桶排序耗时:{:?}",start.elapsed()); // 计数排序和基数排序不适合这个测试,且通常在元素个数小于10000的情况下使用 // let start = Instant::now(); // counting_sort(&mut gen_large_nums_usize()); // println!("计数排序排序耗时:{:?}",start.elapsed()); // let start = Instant::now(); // radix_sort(&mut gen_large_nums_usize()); // println!("基数排序耗时:{:?}",start.elapsed()); thread::sleep(Duration::from_secs(100)); }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/数据结构和算法/sort_algorithms/src/bin/merge_sort.rs
数据结构和算法/sort_algorithms/src/bin/merge_sort.rs
//! 归并排序 递归+合并 //! 平均时间复杂度O(nlog(2n)) 空间复杂度O(n) 稳定 pub fn merge_sort(nums: &mut [i32]) { if nums.len() > 1 { let mid = nums.len() >> 1; // 排序前半部分数据 merge_sort(&mut nums[..mid]); // 排序后半部分数据 merge_sort(&mut nums[mid..]); merge(nums, mid); } } fn merge(nums: &mut [i32], mid: usize) { let mut l = 0; let mut r = mid; let mut tmp = Vec::new(); for _ in 0..nums.len() { if r == nums.len() || l == mid { break; } // 将数据放到临时集合中 if nums[l] < nums[r] { tmp.push(nums[l]); l += 1; } else { tmp.push(nums[r]); r += 1 } } // 合并的两部分数据长度很大可能不一样,需要将集合中未处理的数据全部加入 if l < mid && r == nums.len() { for i in l..mid { tmp.push(nums[i]); } } else if l == mid && r < nums.len() { for i in r..nums.len() { tmp.push(nums[i]); } } // 将tmp中的数据放回nums for i in 0..nums.len() { nums[i] = tmp[i]; } } fn main() { let mut nums = [88, 99, 66, 33, 123, 45, 890, 10, 18, 9999, -9876]; println!("原始值:{:?}", &nums); merge_sort(&mut nums); println!("排序结果:{:?}", nums); }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/数据结构和算法/sort_algorithms/src/bin/insertion_sort.rs
数据结构和算法/sort_algorithms/src/bin/insertion_sort.rs
//! 插入排序算法 //! 平均时间复杂度O(n^2) 空间复杂度O(1) 稳定 pub fn insert_sort(nums: &mut [i32]) { if nums.len() <= 1 { return; } for i in 1..nums.len() { let mut pos = i; let current = nums[i]; while pos > 0 && current < nums[pos - 1] { nums[pos] = nums[pos - 1]; pos -= 1; } nums[pos] = current; } } fn main() { let mut nums = [88, 99, 66, 33, 123, 45, 890, 10, 18]; println!("原始值:{:?}", &nums); insert_sort(&mut nums); println!("排序结果:{:?}", nums); }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/数据结构和算法/sort_algorithms/src/bin/bubbule_sort.rs
数据结构和算法/sort_algorithms/src/bin/bubbule_sort.rs
//! 排序算法之冒泡排序 //! 平均时间复杂度为O(n^2) 空间复杂度O(1) 稳定 pub fn bubbule_sort(nums: &mut [i32]) { if nums.len() <= 1 { return; } else { for i in 1..nums.len() { for j in 0..nums.len() - i { // 如果j大于j+1元素,则交换 if nums[j] > nums[j + 1] { nums.swap(j, j + 1); } } } } } fn main() { let mut nums = [88, 99, 66, 33, 123, 45, 890, 10, 18]; bubbule_sort(&mut nums); println!("排序结果:{:?}", nums); }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/数据结构和算法/sort_algorithms/src/bin/quick_sort.rs
数据结构和算法/sort_algorithms/src/bin/quick_sort.rs
//! 快速排序 //! 平均时间复杂度O(nlog2N) 空间复杂度O(nlog2N) 不稳定 pub fn quick_sort(nums: &mut [i32], low: usize, high: usize) { if low < high { // 选出分裂点 let split_index = partition(nums, low, high); if split_index > 1 { // 对分裂点左边排序 quick_sort(nums, low, split_index - 1); } // 对分裂点右边排序 quick_sort(nums, split_index + 1, high); } } fn partition(nums: &mut [i32], low: usize, high: usize) -> usize { let mut left = low; // 左标记 let mut right = high; // 右标记 // nums[low]作为参考值 loop { // 左标记右移 while left <= right && nums[left] <= nums[low] { left += 1; } // 右标记左移 while left <= right && nums[right] >= nums[low] { right -= 1 } // 当左标记越过右标记时退出 if left > right { break; } else { // 交换左右标记的值 nums.swap(left, right); } } // 交换右标记和参考值 nums.swap(low, right); right } fn main() { let mut nums = [88, 99, 66, 33, 123, 45, 890, 10, 18]; println!("原始值:{:?}", &nums); let high = nums.len() - 1; quick_sort(&mut nums, 0, high); println!("排序结果:{:?}", nums); }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/数据结构和算法/sort_algorithms/src/bin/bucket_sort.rs
数据结构和算法/sort_algorithms/src/bin/bucket_sort.rs
//! 桶排序 //! 平均时间复杂度O(n+k),其中k是桶个数 空间复杂度O(n+k) 稳定 use std::fmt::Debug; struct Bucket<H, T> { hash: H, values: Vec<T>, } impl<H, T> Bucket<H, T> { fn new(hash: H, value: T) -> Self { Bucket { hash: hash, values: vec![value], } } } pub fn bucket_sort<H, T, F>(nums: &mut [T], hasher: F) where H: Ord, T: Ord + Clone + Debug, F: Fn(&T) -> H, { // 桶列表 let mut buckets: Vec<Bucket<H, T>> = Vec::new(); // 迭代数据,将数据放入桶中 for value in nums.iter() { // let hash = hasher(&value); // 对桶中数据进行二分查找并排序 match buckets.binary_search_by(|buckt| buckt.hash.cmp(&hash)) { Ok(index) => buckets[index].values.push(value.clone()), Err(index) => buckets.insert(index, Bucket::new(hash, value.clone())), } } // 合并桶中的数据 let ret = buckets .into_iter() .flat_map(|mut bucket| { bucket.values.sort(); bucket.values }) .collect::<Vec<T>>(); nums.clone_from_slice(&ret); } fn main() { let mut nums = [88999, -99, 66, 33, 123, 45, -890, 10, 18]; println!("原始值:{:?}", &nums); // 需要确保数值越大hash越大,不能用取余符号 bucket_sort(&mut nums, |v| v / 11); println!("排序结果:{:?}", nums); }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/数据结构和算法/sort_algorithms/src/bin/shell_sort.rs
数据结构和算法/sort_algorithms/src/bin/shell_sort.rs
//! 希尔排序 //! 平均时间复杂度O(n^1.3) 空间复杂度O(1) 不稳定 pub fn shell_sort(nums: &mut [i32]) { // 内部是插入排序 fn insert_sort(nums: &mut [i32], start: usize, gap: usize) { let mut i = start + gap; while i < nums.len() { let mut pos = i; let current = nums[pos]; while pos >= gap && current < nums[pos - gap] { nums[pos] = nums[pos - gap]; pos -= gap; } nums[pos] = current; i += gap; } } // 每次将gap减少一半,直到1为止 let mut gap = nums.len() / 2; while gap > 0 { insert_sort(nums, 0, gap); gap /= 2; } } fn main() { let mut nums = [88, 99, 66, 33, 123, 45, 890, 10, 18, 9999, -9876]; println!("原始值:{:?}", &nums); shell_sort(&mut nums); println!("排序结果:{:?}", nums); }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/数据结构和算法/filter_algorithms/src/bitset.rs
数据结构和算法/filter_algorithms/src/bitset.rs
//! 位图 #[derive(Debug)] pub struct BitSet { length: usize, bits: Vec<u64>, } // 对齐 const ALIGN: usize = 6; // 字大小(2^6 = 64) 一个u64存储64位 const WORD_SIZE: usize = 64; // vec的大小 fn vec_size(n: usize) -> usize { let mut size = 0; if n & (WORD_SIZE - 1) == 0 { size = n >> ALIGN; } size = (n >> ALIGN) + 1; size } // 找到Vec中u64 64位的下标 fn value_index(n: usize) -> usize { let index = n & (WORD_SIZE - 1); index } impl BitSet { pub fn new(cap: usize) -> Self { let size = vec_size(cap); Self { length: size * WORD_SIZE, bits: vec![0; size], } } /// 当前位图大小 pub fn len(&self) -> usize { self.length } /// 重置位图 pub fn reset(&mut self) { self.bits.fill(0); } /// 扩展位图 只能由小扩到大 fn extend(&mut self, length: usize) { assert!(length > self.length); // 扩展了几个 let new_add_size = vec_size(length - self.length); let new_bits = vec![0; new_add_size]; self.bits.extend(new_bits.iter()); // 位图长度加新字长度 self.length += new_add_size * WORD_SIZE; } /// 将pos位设置为1(索引从0开始) pub fn set(&mut self, pos: usize) { if pos >= self.len() { // 扩容 self.extend(pos + 1); } // 右移找到对应的字和字对应位的值做或运算 let index = pos >> ALIGN; self.bits[index] = self.bits[index] | 1 << value_index(pos); } /// test 检测第pos位是否为1 pub fn test(&self, pos: usize) -> bool { if pos >= self.len() { return false; } self.bits[pos >> ALIGN] & 1 << value_index(pos) != 0 } } #[cfg(test)] mod test { use super::*; #[test] fn test_alignof6() { let result = vec_size(99999); println!("result:{result}"); } #[test] fn test_bitset() { let mut bs = BitSet::new(10000); println!("start bs length:{}", bs.len()); bs.set(65); assert!(bs.test(65)); println!("end bs length:{}", bs.len()); println!("values:{:#?}", bs); } }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/数据结构和算法/filter_algorithms/src/lib.rs
数据结构和算法/filter_algorithms/src/lib.rs
pub mod bitset; pub mod bloom_filter;
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/数据结构和算法/filter_algorithms/src/bloom_filter.rs
数据结构和算法/filter_algorithms/src/bloom_filter.rs
//! 使用hash函数+BitSet实现 布隆过滤器 use std::{ collections::hash_map::DefaultHasher, hash::{Hash, Hasher}, }; #[path = "bitset.rs"] mod bitset; use bitset::BitSet; pub struct BloomFilter { pub k: usize, // 哈希函数的个数 pub bits: BitSet, } // 根据key,产生5个哈希值 fn hash<T: Hash + ?Sized>(key: &T) -> [u64; 5] { let mut hasher = DefaultHasher::new(); key.hash(&mut hasher); let v0 = hasher.finish(); (v0 & 0xF).hash(&mut hasher); let v1 = hasher.finish(); (v0 & 0xFF).hash(&mut hasher); let v2 = hasher.finish(); (v0 & 0xFFF).hash(&mut hasher); let v3 = hasher.finish(); (v0 & 0xFFFF).hash(&mut hasher); let v4 = hasher.finish(); [v0, v1, v2, v3, v4] } impl BloomFilter { /// 创建一个能容纳capacity个bit的过滤器,使用k个哈希函数 pub fn new(capacity: usize, k: usize) -> Self { Self { k: k, bits: BitSet::new(capacity), } } /// 将key添加到bitset pub fn add<T: Hash + ?Sized>(&mut self, key: &T) { let hashs = hash(key); for i in 0..self.k { let pos = self.location(&hashs, i); self.bits.set(pos); } } /// 计算添加的位置 fn location(&self, hashs: &[u64; 5], i: usize) -> usize { // 按照某种规则(可自定义)从hashs中找到第一个hash值 let p1 = hashs[((i + i % 2) % 4) / 2 + 3]; // 找到第二个hash值和第一个hash值相加 println!("p1:{p1}"); let (p2, _) = hashs[i % 2].overflowing_add(p1 / (i + 1) as u64); // 防止超过bitset表示范围 p2 as usize % self.bits.len() } /// 验证key是否存在于布隆过滤器中,如果存在返回true,否则返回false pub fn test<T: Hash + ?Sized>(&self, key: &T) -> bool { let hashs = hash(key); for i in 0..self.k { let pos = self.location(&hashs, i); if !self.bits.test(pos) { return false; } } true } } #[cfg(test)] mod test { use super::BloomFilter; #[test] fn test_bloom_filter() { let mut b = BloomFilter::new(1024, 3); println!("bitset len:{}", b.bits.len()); b.add(&999); b.add(&10); b.add("你好"); b.add(&345); assert!(b.test(&999)); assert!(b.test(&10)); assert!(b.test("你好")); assert!(b.test(&345)); println!("bitset len:{}", b.bits.len()); } }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/数据结构和算法/filter_algorithms/src/bin/run_bloom_filter.rs
数据结构和算法/filter_algorithms/src/bin/run_bloom_filter.rs
#[path = "../bloom_filter.rs"] mod bloom_filter; use bloom_filter::BloomFilter; fn main() { let mut b = BloomFilter::new(1024, 3); println!("bitset len:{}", b.bits.len()); b.add(&999); b.add(&10); b.add("你好"); b.add(&345); assert!(b.test(&999)); assert!(b.test(&10)); assert!(b.test("你好")); assert!(b.test(&345)); println!("bitset len:{}", b.bits.len()); }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/数据结构和算法/search_algorithms/src/bin/hash_search.rs
数据结构和算法/search_algorithms/src/bin/hash_search.rs
//! 哈希查找 //! hash函数:一种值到存储地址的映射函数,通过它直接建立值和地址的关系,达到快速查找的目的 //! hash 冲突的解决:拉链法,在冲突的槽位建立链表(或一颗红黑树),此时时间复杂度为O(log2N) use std::{ collections::hash_map::DefaultHasher, fmt::Debug, hash::{Hash, Hasher}, }; #[derive(Debug, Clone, PartialEq, PartialOrd)] struct HashMap<K, V> { // 分配的容量 cap: usize, // 存储key slot: Vec<K>, // 存储value data: Vec<V>, } impl<K, V> HashMap<K, V> where K: Clone + Default + PartialEq + PartialOrd + Debug + Hash, V: Clone + Default + PartialEq + PartialOrd + Debug + Hash, { fn new(cap: usize) -> Self { //初始化slot和data let mut slot = Vec::with_capacity(cap); let mut data = Vec::with_capacity(cap); for _ in 0..cap { slot.push(Default::default()); data.push(Default::default()); } HashMap { cap, slot, data } } fn len(&self) -> usize { let mut len = 0; for i in self.slot.iter() { // 不等于0表示有数据,长度+1 if *i != Default::default() { len += 1; } } len } fn is_empty(&self) -> bool { self.len() == 0 } fn clear(&mut self) { let mut slot = Vec::with_capacity(self.cap); let mut data = Vec::with_capacity(self.cap); for _ in 0..self.cap { slot.push(Default::default()); data.push(Default::default()); } self.slot = slot; self.data = data; } fn hash(&self, key: &K) -> usize { let mut hasher = DefaultHasher::new(); key.hash(&mut hasher); let result = hasher.finish() as usize; result % self.cap } fn rehash(&self, pos: usize) -> usize { (pos + 1) % self.cap } fn insert(&mut self, key: K, value: V) { if key == Default::default() { panic!("{:?}不能作为key", key); } let pos = self.hash(&key); // 槽位没有数据,直接插入 if self.slot[pos] == Default::default() { self.slot[pos] = key; self.data[pos] = value; } else { // 要插入的槽位有数据,线性探测下一个可以插入的位置 let mut next = self.rehash(pos); while self.slot[next] != Default::default() && key != self.slot[next] { next = self.rehash(next); // 一直寻找知道没有槽位为止 if next == pos { println!("WARN:槽位已用完"); return; } } // 在找到的槽位中插入数据 if self.slot[next] == Default::default() { self.slot[next] = key; self.data[next] = value; } else { self.data[next] = value; } } } fn remove(&mut self, key: K) -> Option<V> { if key == Default::default() { panic!("key:{:?}不能是默认值!", key); } let pos = self.hash(&key); if self.slot[pos] == Default::default() { None } else if key == self.slot[pos] { self.slot[pos] = Default::default(); let data = Some(self.data[pos].clone()); self.data[pos] = Default::default(); data } else { let mut data: Option<V> = None; let mut stop = false; let mut found = false; let mut current = pos; while self.slot[current] != Default::default() && !found && !stop { if key == self.slot[current] { found = true; self.slot[current] = Default::default(); data = Some(self.data[current].clone()); self.data[current] = Default::default(); } else { current = self.rehash(current); if current == pos { stop = true; } } } data } } fn get_pos(&self, key: K) -> usize { if key == Default::default() { panic!("key:{:?}不能是默认值!", key); } let pos = self.hash(&key); let mut stop = false; let mut found = false; let mut current = pos; while self.slot[current] != Default::default() && !found && !stop { if key == self.slot[current] { found = true; } else { current = self.rehash(current); if current == pos { stop = true; } } } current } fn get(&self, key: K) -> Option<&V> { let pos = self.get_pos(key); self.data.get(pos) } fn get_mut(&mut self, key: K) -> Option<&mut V> { let pos = self.get_pos(key); self.data.get_mut(pos) } fn contains(&self, key: K) -> bool { if key == Default::default() { panic!("key:{:?}不能是默认值!", key); } self.slot.contains(&key) } fn iter(&self) -> Iter<V> { let mut iter = Iter { datas: Vec::new() }; for item in self.data.iter() { iter.datas.push(item); } iter } fn iter_mut(&mut self) -> IterMut<V> { let mut iter = IterMut { datas: Vec::new() }; for item in self.data.iter_mut() { iter.datas.push(item); } iter } } struct Iter<'a, V: 'a> { datas: Vec<&'a V>, } impl<'a, V> Iterator for Iter<'a, V> { type Item = &'a V; fn next(&mut self) -> Option<Self::Item> { self.datas.pop() } } struct IterMut<'a, V: 'a> { datas: Vec<&'a mut V>, } impl<'a, V> Iterator for IterMut<'a, V> { type Item = &'a mut V; fn next(&mut self) -> Option<Self::Item> { self.datas.pop() } } fn main() { let mut map = HashMap::new(11); map.insert("小黑", 10); map.insert("小白", 20); map.insert("小宏", 30); map.insert("小红", 40); map.insert("小洪", 50); map.insert("小李", 60); map.insert("小样", 70); map.insert("小阳", 80); map.insert("小王", 100); println!("有小王吗:{}", map.contains("小王")); println!("有小王吧:{}", map.contains("小王吧")); println!("小王成绩:{}", map.get("小王").unwrap()); // 修改小王成绩 *map.get_mut("小王").unwrap() = 99; println!("修改后小王成绩:{}", map.get("小王").unwrap()); println!( "map 长度:{} 容量:{} 负载因子:{}", map.len(), map.cap, map.len() as f32 / map.cap as f32 ); // 删除小黑 map.remove("小黑"); // 迭代 let iter = map.iter(); for i in iter { println!("score:{i}"); } println!("数据个数:{}",map.len()); }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/数据结构和算法/search_algorithms/src/bin/binary_search.rs
数据结构和算法/search_algorithms/src/bin/binary_search.rs
//! 二分查找 //! 时间复杂度O(log2n) //! 前提条件:需要集合有序 /// 二分查找有序数组 fn binary_search<T: PartialEq + PartialOrd>(nums: &[T], num: T) -> bool { let mut found = false; let mut low = 0; let mut high = nums.len() - 1; while low <= high && !found { // 右移操作,mid为len的一半 let mid = (low + high) >> 1; if num == nums[mid] { found = true; break; } else if num < nums[mid] { high = mid - 1; } else { low = mid + 1; } } found } // 递归方式实现二分查找 fn binary_search_recursive<T: PartialEq + PartialOrd>(nums: &[T], num: T) -> bool { if nums.len() == 0 { return false; } let mid = nums.len() >> 1; if num == nums[mid] { return true; } else if num < nums[mid] { return binary_search_recursive(&nums[..mid], num); } else { return binary_search_recursive(&nums[mid..], num); } } fn main() { let num = 40; let nums = [2, 3, 4, 6, 7, 8, 9, 10]; let search_result = binary_search(&nums, num); println!("search result:{search_result}"); let num = 4; let nums = [2, 3, 4, 6, 7, 8, 9, 10]; let search_result = binary_search_recursive(&nums, num); println!("search result:{search_result}"); }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/数据结构和算法/search_algorithms/src/bin/sequential_search.rs
数据结构和算法/search_algorithms/src/bin/sequential_search.rs
//! 顺序查找 //! 时间复杂度O(n) fn sequential_search<T: PartialEq>(nums: &[T], num: T) -> bool { let mut found = false; let mut index = 0; while index < nums.len() { if num == nums[index] { found = true; break; } index += 1; } found } fn main() { let num = 4; let nums = [2, 3, 4, 6, 7, 8, 9, 10, 4]; let search_result = sequential_search(&nums, num); println!("search result:{search_result}"); }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/数据结构和算法/search_algorithms/src/bin/middle_insert_search.rs
数据结构和算法/search_algorithms/src/bin/middle_insert_search.rs
//! 内插查找 //! 它是二分查找的变体,思路是使用线性内插法 (y-y0)/(x-x0) = (y1-y0)/(x1-x0) => x = {(y-y0)(x1-x0)}/(y1-y0) + x0 //! 时间平均查找复杂度为O(loglog(n)) //! 前提条件:数组已经排好序 fn insert_search(nums: &[i32], target: i32) -> bool { if nums.is_empty() { return false; } let mut low = 0; let mut high = nums.len() - 1; // 一直循环找到上界 loop { let low_val = nums[low]; let high_val = nums[high]; if high <= low || target < low_val || target > high_val { break; } // 插值位置 let offset = (target - low_val) * (high - low) as i32 / (high_val - low_val); let insert_index = low + offset as usize; // 更新上/下界 if nums[insert_index as usize] > target { high = insert_index - 1; } else if nums[insert_index] < target { low = insert_index + 1; } else { high = insert_index; break; } } target == nums[high] } fn main() { let num = 11; let nums = [2, 3, 4, 6, 7, 8, 9, 10]; let search_result = insert_search(&nums, num); println!("search result:{search_result}"); let num = 2; let nums = [2, 3, 6, 7, 8, 9, 10]; let search_result = insert_search(&nums, num); println!("search result:{search_result}"); let num = 10; let nums = [2, 3, 6, 7, 8, 9, 10]; let search_result = insert_search(&nums, num); println!("search result:{search_result}"); }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/数据结构和算法/tree_structures_and_algos/src/bin/tire.rs
数据结构和算法/tree_structures_and_algos/src/bin/tire.rs
//! 字典树 #[derive(Default, Debug)] struct Trie { root: Box<Node>, // 字典树的根节点 } #[derive(Default, Debug)] struct Node { mark: bool, // 标识位:用于标识是否从根节点到此节点组成一个单词 childs: [Option<Box<Node>>; 26], //26个英文字母,只需要26个槽位 } impl Trie { fn new() -> Self { Self::default() } /// 向字典树插入单词 fn insert(&mut self, word: &str) { let mut current_node = &mut self.root; //逐个字符插入 for c in word.as_bytes() { // 字母在当前的childs的索引 let index = (c - b'a') as usize; let child = &mut current_node.childs[index]; // 如果child存在则插入,否则新建 current_node = child.get_or_insert_with(Box::<Node>::default); } // 将current_node的mark标记为true,表示从根节点到此节点组成一个单词 current_node.mark = true; } fn contains(&self, word: &str) -> bool { self.word_node(word).map_or(false, |node| node.mark) } fn start_with(&self, prifix: &str) -> bool { self.word_node(prifix).is_some() } fn word_node(&self, word: &str) -> Option<&Node> { let mut current_node = &self.root; for c in word.as_bytes() { let index = (c - b'a') as usize; match &current_node.childs[index] { None => return None, Some(node) => current_node = node, } } Some(&current_node) } } fn main() { let mut trie = Trie::new(); trie.insert("rust"); trie.insert("hug"); trie.insert("hello"); trie.insert("hugrust"); println!("hello in Trie:{}", trie.contains("hello")); println!("huga in Trie:{}", trie.contains("huga")); println!("Trie start with hella:{}", trie.start_with("hella")); println!("Trie start with rust:{}", trie.start_with("rust")); }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/数据结构和算法/postfix_expression_cal/src/stack.rs
数据结构和算法/postfix_expression_cal/src/stack.rs
//! 实现栈数据结构 #[derive(Debug)] pub struct Stack<T> { size: usize, // 栈大小 data: Vec<T>, // 栈数据,泛型T } impl<T> Stack<T> { // 初始化空栈 pub fn new() -> Self { Self { size: 0, data: vec![], } } // 判空 pub fn is_empty(&self) -> bool { self.size == 0 } // 栈元素个数 pub fn len(&self) -> usize { self.size } // 清空栈 pub fn clear(&mut self) { self.size = 0; self.data.clear(); } // 将数据压入栈顶 pub fn push(&mut self, val: T) { self.data.push(val); self.size += 1; } // 将数据从栈顶弹出 pub fn pop(&mut self) -> Option<T> { if self.is_empty() { return None; } else { self.size -= 1; self.data.pop() } } // “偷窥”栈顶元素,返回栈顶元素的引用 pub fn peek(&self) -> Option<&T> { if self.is_empty() { return None; } else { self.data.get(self.len() - 1) } } // 返回栈顶元素的可变引用 pub fn peek_mut(&mut self) -> Option<&mut T> { if self.is_empty() { return None; } else { self.data.get_mut(self.size - 1) } } // 为栈实现迭代器 // 将栈转换为迭代器 pub fn into_iter(self) -> IntoIter<T> { IntoIter(self) } // 获取不可变引用迭代器 pub fn iter(&self) -> Iter<T> { let mut iter = Iter(Stack::new()); for i in self.data.iter() { iter.0.push(i); } iter } // 获取可变引用迭代器 pub fn iter_mut(&mut self) -> IterMut<T> { let mut iter_mut = IterMut(vec![]); for i in self.data.iter_mut() { iter_mut.0.push(i); } iter_mut } } struct IntoIter<T>(Stack<T>); impl<T: Clone> Iterator for IntoIter<T> { type Item = T; fn next(&mut self) -> Option<Self::Item> { if self.0.is_empty() { None } else { self.0.size -= 1; self.0.pop() } } } struct Iter<'a, T: 'a>(Stack<&'a T>); impl<'a, T> Iterator for Iter<'a, T> { type Item = &'a T; fn next(&mut self) -> Option<Self::Item> { self.0.pop() } } struct IterMut<'a, T: 'a>(Vec<&'a mut T>); impl<'a, T> Iterator for IterMut<'a, T> { type Item = &'a mut T; fn next(&mut self) -> Option<Self::Item> { self.0.pop() } }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/数据结构和算法/postfix_expression_cal/src/par_checker.rs
数据结构和算法/postfix_expression_cal/src/par_checker.rs
use crate::stack::Stack; use std::vec; /// 判断是否匹配 fn matcher(left: char, right: char) -> bool { let lefts = "([{"; let rights = ")]}"; lefts.find(left) == rights.find(right) } // 使用栈判断括号是否匹配 pub fn par_checher(input: &str) -> bool { if input.is_empty() { return false; } else { let mut chars = vec![]; for c in input.chars() { chars.push(c); } // 记录chars的下标 let mut index = 0; // 标记是否匹配 let mut balance = true; let mut stack = Stack::new(); // 借助栈匹配字符,直至匹配完毕或者出现不匹配 while index < chars.len() && balance { let i = chars[index]; // 如果i='['或i='{'或i='(',则入栈 if i == '(' || i == '[' || i == '{' { stack.push(i); } // 如果i=']' 或i='}'或i=')',判断是否平衡 if i == ')' || i == '}' || i == ']' { if stack.is_empty() { balance = false; } else { let top = stack.pop().unwrap(); if !matcher(top, i) { balance = false; } } } index += 1; } balance && stack.is_empty() } }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/数据结构和算法/postfix_expression_cal/src/main.rs
数据结构和算法/postfix_expression_cal/src/main.rs
//! 后缀表达式计算 use std::collections::HashMap; use par_checker::par_checher; use stack::Stack; mod par_checker; mod stack; /// 中缀表达式转换为后缀表达式 fn infix_to_postfix(infix: &str) -> Option<String> { // 1.括号检测 if !par_checher(infix) { return None; } // 2.设置运算符优先级 let mut prec = HashMap::new(); // 括号优先级最低 prec.insert("(", 1); prec.insert(")", 1); prec.insert("+", 2); prec.insert("-", 2); // 乘除优先级最高 prec.insert("*", 3); prec.insert("/", 3); // 使用栈保存运算符,使用postfix保存后缀表达式 let mut ops_stack = Stack::new(); let mut postfix = Vec::new(); // 遍历表达式中的字符 for token in infix.split_whitespace() { // 将数字0~9放入postfix if "0" <= token && token <= "9" { postfix.push(token); } // 遇到"(",入栈 else if "(" == token { ops_stack.push(token); } // 遇到")",运算符出栈并追加到后缀表达式列表 else if ")" == token { let mut top = ops_stack.pop().unwrap(); // "("前的所有运算符都出栈 while top != "(" { postfix.push(top); top = ops_stack.pop().unwrap(); } } else { // 遇到+-*/运算符,先比较运算符的优先级并添加到postfix列表中 while (!ops_stack.is_empty()) && prec[ops_stack.peek().unwrap()] >= prec[token] { postfix.push(ops_stack.pop().unwrap()); } ops_stack.push(token); } } // 将剩下的运算符出栈追加到后缀表达式列表 while !ops_stack.is_empty() { postfix.push(ops_stack.pop().unwrap()); } //拼装成字符串 let mut postfix_str = String::new(); for c in postfix { postfix_str += &c.to_string(); postfix_str += &" ".to_string(); } Some(postfix_str) } // 通过后缀表达式计算值 fn postfix_eval(postfix: &str) -> Option<i32> { // 后缀表达式最少需要5个字符,一个运算符两个操作数及两个空格 if postfix.len() < 5 { return None; }; let mut ops_stack = Stack::new(); for token in postfix.split_ascii_whitespace() { // 先出栈的是第二个操作数,顺序对与-和/操作符很重要 if token >= "0" && token <= "9" { ops_stack.push(token.parse::<i32>().unwrap()); } else { let op_num2 = ops_stack.pop().unwrap(); let op_num1 = ops_stack.pop().unwrap(); let res = do_calculation(token, op_num1, op_num2); ops_stack.push(res); } } Some(ops_stack.pop().unwrap()) } fn do_calculation(token: &str, op_num1: i32, op_num2: i32) -> i32 { match token { "+" => op_num1 + op_num2, "-" => op_num1 - op_num2, "*" => op_num1 * op_num2, "/" => { if op_num2 == 0 { panic!("除零操作,非法!"); } op_num1 / op_num2 } _ => { panic!("非法字符"); } } } fn main() { // 表达式:( 1 + 5 ) * 3 + ( 15 - 7 ) / 2 // 转换为后缀表达式 let infix = "( 1 + 5 ) * 3 + ( 15 - 7 ) / 2"; let postfix = infix_to_postfix(infix); let result = postfix_eval(postfix.clone().unwrap().as_str()); println!( "infix:{infix} \r\npostfix:{:?}\r\nresult:{:?}", postfix.unwrap(), result.unwrap() ); }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/生命周期/src/bin/lifecycle.rs
生命周期/src/bin/lifecycle.rs
fn main() { // 悬垂指针 // let age; // { // let age1 = 30; // age = &age1; // } // println!("age:{age}"); // 生命周期标注语法 // 显式周期的引用 &'a u32 // 显式周期的可变引用 &'a mut u32 // 函数传参,显式标明生命周期 // 类似于泛型,要在尖括号中先声明才能使用 // 第一个参数是生命周期为'a的不可变引用 // 第二个参数是生命周期为'a的可变引用 fn bigest_age<'a>(age1:&'a i32,age2:&'a mut i32)->&'a i32{ println!("age1:{age1} age2:{age2}"); if age1 > age2{ age1 }else{ age2 } } let age1 = 123; let mut age2 = 73; let max_age = bigest_age(&age1, &mut age2); println!("max_age:{max_age}"); // 函数有两个一样的生命周期的参数,返回值的生命周期等于较小作用域的哪个值的生命周期 // let age1 = 123; // let max_age; // { // let mut age2 = 73; // max_age = bigest_age(&age1, &mut age2); // } // println!("max_age:{max_age}"); // 悬垂引用 编译不通过 // fn get_message<'a>()->&'a str{ // let msg = String::from("hello AI"); // msg.as_str() // } // 上述代码编译不通过,做如下修改,返回内部所有权 fn get_message()->String{ String::from("hello AI") } // 结构体中的生命周期 #[derive(Debug)] struct Message<'a>{ msg:&'a str } impl<'a> Message<'a>{ fn new(msg:&'a str)->Self{ Self{msg} } } let say_hi = String::from("hi,how are you"); let message = Message{msg:say_hi.as_str()}; println!("{:?}", message); // 下面方式声明会报错 // let message; // { // let say_hi = String::from("hi,how are you"); // message = Message{msg:say_hi.as_str()}; // } // println!("{:?}", message); }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/好用的第三方包/taste_crates/src/bin/taste_rustyline.rs
好用的第三方包/taste_crates/src/bin/taste_rustyline.rs
use rustyline::error::ReadlineError; use rustyline::{DefaultEditor, Result}; fn main() -> Result<()> { // `()` can be used when no completer is required let mut rl = DefaultEditor::new()?; #[cfg(feature = "with-file-history")] if rl.load_history("history.txt").is_err() { println!("No previous history."); } loop { let readline = rl.readline(">> "); match readline { Ok(line) => { rl.add_history_entry(line.as_str()); println!("Line: {}", line); } Err(ReadlineError::Interrupted) => { println!("CTRL-C"); break; } Err(ReadlineError::Eof) => { println!("CTRL-D"); break; } Err(err) => { println!("Error: {:?}", err); break; } } } #[cfg(feature = "with-file-history")] rl.save_history("history.txt"); Ok(()) }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/好用的第三方包/taste_crates/src/bin/taste_bigdecimal.rs
好用的第三方包/taste_crates/src/bin/taste_bigdecimal.rs
use bigdecimal::BigDecimal; fn main() { let two = BigDecimal::from(2); println!("sqrt(2) = {}", two.sqrt().unwrap()); let three = BigDecimal::from(3); println!("sqrt(3) = {}", three.sqrt().unwrap()); let four = BigDecimal::from(4); println!("sqrt(4) = {}", four.sqrt().unwrap()); }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/好用的第三方包/taste_crates/src/bin/taste_thiserror.rs
好用的第三方包/taste_crates/src/bin/taste_thiserror.rs
use std::io; use thiserror::Error as ThisError; fn main() { self_error_type(); self_error_type1(); self_error_type2(); } // 动态错误类型 fn self_error_type2() { // 自定义错误类型的定义 #[derive(ThisError, Debug)] pub enum MyError { // FailedWithCode 的错误描述,其中 {0} 会被动态地替换为具体的代码值 #[error("failed with code: {0}")] FailedWithCode(i32), } // fn process_data(error_code: i32) -> Result<(), MyError> { // 使用动态的 error_code 创建 FailedWithCode 错误 Err(MyError::FailedWithCode(error_code)) } let result = process_data(404); println!("result:{:?}", result); let result: Result<(), MyError> = process_data(500); println!("result:{:?}", result); let result = process_data(403); println!("result:{:?}", result); let result = process_data(503); println!("result:{:?}", result); } /// 自定义错误类型 fn self_error_type() { // 自定义错误类型的定义 #[derive(ThisError, Debug)] pub enum MyError { // DataNotFound 错误的描述 #[error("data not found")] DataNotFound, // InvalidInput 错误的描述 #[error("invalid input")] InvalidInput, } // 示例函数,展示如何使用自定义错误 fn search_data(query: &str) -> Result<(), MyError> { if query.is_empty() { // 当查询为空时,返回 InvalidInput 错误 return Err(MyError::InvalidInput); } // 这里省略了实际的数据查询逻辑 // ... // 数据未找到时返回 DataNotFound 错误 Err(MyError::DataNotFound) } let result = search_data(""); println!("result:{:#?}", result); } /// 自定义错误类型 - 嵌套错误 fn self_error_type1() { // 自定义错误类型的定义 #[derive(ThisError, Debug)] pub enum MyError { // IoError 错误的描述,它包含一个嵌套的 io::Error #[error("I/O error occurred")] IoError(#[from] io::Error), } // 示例函数,展示如何使用嵌套的错误 fn read_file(file_path: &str) -> Result<String, MyError> { // 如果 fs::read_to_string 返回错误,我们使用 MyError::from 将它转换为 MyError::IoError std::fs::read_to_string(file_path).map_err(MyError::from) } let result = read_file("./test.rs"); println!("result:{:?}", result); }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/好用的第三方包/taste_crates/src/bin/taste_seder.rs
好用的第三方包/taste_crates/src/bin/taste_seder.rs
use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, Debug)] struct Point { x: i32, y: i32, } fn main() { let point = Point { x: 1, y: 2 }; // Convert the Point to a JSON string. let serialized = serde_json::to_string(&point).unwrap(); // Prints serialized = {"x":1,"y":2} println!("serialized = {}", serialized); // Convert the JSON string back to a Point. let deserialized: Point = serde_json::from_str(&serialized).unwrap(); // Prints deserialized = Point { x: 1, y: 2 } println!("deserialized = {:?}", deserialized); }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/好用的第三方包/taste_crates/src/bin/taste_miette.rs
好用的第三方包/taste_crates/src/bin/taste_miette.rs
use miette::{Diagnostic, SourceSpan}; use miette::{NamedSource, Result as MietteResult}; use std::error::Error; use thiserror::Error; #[derive(Error, Debug, Diagnostic)] #[error("oops!")] #[diagnostic(code(src::bin::taste_miette), url(docsrs), help("请认真检查你的代码"))] struct MyBad { // The Source that we're gonna be printing snippets out of. // This can be a String if you don't have or care about file names. #[source_code] src: NamedSource<String>, // Snippets and highlights can be included in the diagnostic! #[label("这里错误")] bad_bit: SourceSpan, } fn this_gives_correct_formatting() -> MietteResult<()> { let res: Result<(), MyBad> = Err(MyBad { src: NamedSource::new("taste_miette.rs", "source\n text\n here".to_string()), bad_bit: (9, 4).into(), }); res?; Ok(()) } fn main() -> Result<(), Box<dyn Error>> { let res = this_gives_correct_formatting(); res?; Ok(()) }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/好用的第三方包/taste_crates/src/bin/taste_tabled1.rs
好用的第三方包/taste_crates/src/bin/taste_tabled1.rs
use tabled::{ settings::{object::Rows, Alignment, Modify, Style}, Table, Tabled, }; #[derive(Debug, Tabled)] struct Distribution { name: String, based_on: String, is_active: bool, } impl Distribution { fn new(name: &str, base: &str, is_active: bool) -> Self { Self { based_on: base.to_owned(), name: name.to_owned(), is_active, } } } fn main() { let data = [ Distribution::new("Debian", "", true), Distribution::new("Arch", "", true), Distribution::new("Manjaro", "Arch", true), ]; let mut table = Table::new(data); table .with(Style::markdown()) .with(Modify::new(Rows::first()).with(Alignment::center())); println!("{table}"); }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/好用的第三方包/taste_crates/src/bin/taste_derive_more.rs
好用的第三方包/taste_crates/src/bin/taste_derive_more.rs
use derive_more::{ Add, AddAssign, Constructor, Deref, DerefMut, Display, From, FromStr, Index, IndexMut, Into, IsVariant, Mul, MulAssign, Not, TryInto, }; /// Some docs #[derive( Add, AddAssign, Constructor, Display, From, FromStr, Into, Mul, MulAssign, Not, Clone, Copy, )] pub struct MyInt(i32); /// Some docs #[derive(Deref, DerefMut)] pub struct MyBoxedInt(Box<i32>); /// Some docs #[derive(Index, IndexMut)] pub struct MyVec(Vec<i32>); /// Some docs #[allow(dead_code)] #[derive(Clone, Copy, TryInto, IsVariant)] enum MixedInts { SmallInt(i32), NamedBigInt { int: i64 }, } fn main() { let a = MyInt(1000); let b = MyInt(20); let c = a + b; println!("{a} + {b} = {c}"); }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/好用的第三方包/taste_crates/src/bin/taste_tabled2.rs
好用的第三方包/taste_crates/src/bin/taste_tabled2.rs
use tabled::{ settings::{style::Style, themes::Theme, Color}, Table, Tabled, }; #[derive(Tabled)] struct CodeEditor { name: &'static str, first_release: &'static str, developer: &'static str, } impl CodeEditor { fn new(name: &'static str, first_release: &'static str, developer: &'static str) -> Self { Self { name, first_release, developer, } } } fn main() { let mut style = Theme::from(Style::extended()); style.set_border_color_top(Color::FG_RED); style.set_border_color_bottom(Color::FG_CYAN); style.set_border_color_left(Color::FG_BLUE); style.set_border_color_right(Color::FG_GREEN); style.set_border_color_corner_top_left(Color::FG_BLUE); style.set_border_color_corner_top_right(Color::FG_RED); style.set_border_color_corner_bottom_left(Color::FG_CYAN); style.set_border_color_corner_bottom_right(Color::FG_GREEN); style.set_border_color_intersection_bottom(Color::FG_CYAN); style.set_border_color_intersection_top(Color::FG_RED); style.set_border_color_intersection_right(Color::FG_GREEN); style.set_border_color_intersection_left(Color::FG_BLUE); style.set_border_color_intersection(Color::FG_MAGENTA); style.set_border_color_horizontal(Color::FG_MAGENTA); style.set_border_color_vertical(Color::FG_MAGENTA); let data = [ CodeEditor::new("Sublime Text 3", "2008", "Sublime HQ"), CodeEditor::new("Visual Studio Code", "2015", "Microsoft"), CodeEditor::new("Notepad++", "2003", "Don Ho"), CodeEditor::new("GNU Emacs", "1984", "Richard Stallman"), CodeEditor::new("Neovim", "2015", "Vim community"), ]; let table = Table::new(data).with(style).to_string(); println!("{table}"); }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/设计模式/bridge/src/bin/bridge.rs
设计模式/bridge/src/bin/bridge.rs
//! 桥接模式 // 定义实现接口 trait Implementor { fn op_impl(&self); } // 定义具体的实现类 struct ConcreteImplA; impl Implementor for ConcreteImplA { fn op_impl(&self) { println!("实现类ConcreteImplA op....") } } struct ConcreteImplB; impl Implementor for ConcreteImplB { fn op_impl(&self) { println!("实现类ConcreteImplB op....") } } // 定义抽象接口 trait Abstraction { fn op(&self); } // 实现具体的抽象类 struct RefinedAbstraction { // 有一个实现类的引用 implementor: Box<dyn Implementor>, } impl Abstraction for RefinedAbstraction { // 调用实现类的方法 fn op(&self) { self.implementor.op_impl(); } } impl RefinedAbstraction { fn new(implementor: impl Implementor + 'static) -> Self { Self { implementor: Box::new(implementor), } } } fn main() { // 创建具体的实现类 let impl_a = ConcreteImplA; let impl_b = ConcreteImplB; // 创建具体的抽象类 let abs_a = RefinedAbstraction::new(impl_a); let abs_b = RefinedAbstraction::new(impl_b); // 调用抽象类的操作方法 abs_a.op(); abs_b.op(); }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/设计模式/filter/src/bin/filter.rs
设计模式/filter/src/bin/filter.rs
//! 过滤器模式 // 需要过滤的结构体 #[derive(PartialEq, Clone)] struct Person { name: String, gender: String, marital_status: String, } impl Person { fn get_gender(&self) -> &str { self.gender.as_str() } fn get_marital_status(&self) -> &str { self.marital_status.as_str() } fn get_name(&self) -> &str { self.name.as_str() } } // 过滤器特征(又名标准特征) trait Criteria { fn fit_criteria(&self, persons: Vec<Person>) -> Vec<Person>; } // 男性过滤标准 struct MaleCriteria; impl Criteria for MaleCriteria { fn fit_criteria(&self, persons: Vec<Person>) -> Vec<Person> { persons .into_iter() .filter(|p| p.get_gender().eq("男")) .collect() } } // 女性过滤标准 struct FemaleCriteria; impl Criteria for FemaleCriteria { fn fit_criteria(&self, persons: Vec<Person>) -> Vec<Person> { persons .into_iter() .filter(|p| p.get_gender().eq("女")) .collect() } } // 单身标准 struct SingleCriteria; impl Criteria for SingleCriteria { fn fit_criteria(&self, persons: Vec<Person>) -> Vec<Person> { persons .into_iter() .filter(|p| p.get_marital_status().eq("未婚")) .collect() } } // 两个标准的交集 struct AndCriteria { one_criteria: Box<dyn Criteria>, two_criteria: Box<dyn Criteria>, } impl Criteria for AndCriteria { fn fit_criteria(&self, persons: Vec<Person>) -> Vec<Person> { self.one_criteria .fit_criteria(self.two_criteria.fit_criteria(persons)) } } // 两个标注的取Or struct OrCriteria { one_criteria: Box<dyn Criteria>, two_criteria: Box<dyn Criteria>, } impl Criteria for OrCriteria { fn fit_criteria(&self, persons: Vec<Person>) -> Vec<Person> { let mut one_criteria_items = self.one_criteria.fit_criteria(persons.clone()); let two_criteria_items = self.two_criteria.fit_criteria(persons); for p in two_criteria_items { if !one_criteria_items.contains(&p) { one_criteria_items.push(p); } } one_criteria_items } } fn print_persons(persons: Vec<Person>) { persons.into_iter().for_each(|p| { println!( "Person name:{} gender:{} marital_status:{}", p.get_name(), p.get_gender(), p.get_marital_status() ) }) } fn main() { // 构造Person集合 let mut persons = Vec::new(); persons.push(Person { name: "小张".to_string(), gender: "男".to_string(), marital_status: "未婚".to_string(), }); persons.push(Person { name: "小红".to_string(), gender: "女".to_string(), marital_status: "未婚".to_string(), }); persons.push(Person { name: "小杨".to_string(), gender: "女".to_string(), marital_status: "已婚".to_string(), }); persons.push(Person { name: "小林".to_string(), gender: "男".to_string(), marital_status: "未婚".to_string(), }); persons.push(Person { name: "小强".to_string(), gender: "男".to_string(), marital_status: "未婚".to_string(), }); persons.push(Person { name: "小李".to_string(), gender: "女".to_string(), marital_status: "已婚".to_string(), }); // 过滤出男士 let males = MaleCriteria.fit_criteria(persons.clone()); println!("-----男性用户------"); print_persons(males); // 过滤出女士 println!("-----女性用户------"); let females = FemaleCriteria.fit_criteria(persons.clone()); print_persons(females); // 过滤女性已婚 println!("-----女性单身用户------"); let single_females = AndCriteria { one_criteria: Box::new(FemaleCriteria), two_criteria: Box::new(SingleCriteria), } .fit_criteria(persons.clone()); print_persons(single_females); // 过滤男性或单身用户 println!("-----男性或单身用户------"); let single_or_males = OrCriteria { one_criteria: Box::new(MaleCriteria), two_criteria: Box::new(SingleCriteria), } .fit_criteria(persons.clone()); print_persons(single_or_males); }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/设计模式/state/src/bin/state.rs
设计模式/state/src/bin/state.rs
// 定义状态,不同的操作会影响状态,同时状态的改变又会影响对象和流程 trait State { fn handle(&self, context: &mut Context); fn get_temperature(&self) -> f32; } struct Context { state: Option<Box<dyn State>>, } impl Context { fn set_state(&mut self, state: Box<dyn State>) { self.state = Some(state); } fn request(&mut self) { self.state.take().as_mut().map(|s|s.handle(self)); } } struct Spring { temperature: f32, } impl State for Spring { fn handle(&self, context: &mut Context) { println!( "春天到了,万物又到了繁殖的季节....当前温度:{}", self.get_temperature() ); context.set_state(Box::new(Summer{temperature:33.2})); } fn get_temperature(&self) -> f32 { self.temperature } } struct Summer { temperature: f32, } impl State for Summer { fn handle(&self, context: &mut Context) { println!( "夏天到了,西瓜已经熟了....当前温度:{}", self.get_temperature() ); context.set_state(Box::new(Autumn{temperature:23.1})); } fn get_temperature(&self) -> f32 { self.temperature } } struct Autumn { temperature: f32, } impl State for Autumn { fn handle(&self, context: &mut Context) { println!( "秋天到了,稻子已经黄了....当前温度:{}", self.get_temperature() ); context.set_state(Box::new(Winter{temperature:-10.2})); } fn get_temperature(&self) -> f32 { self.temperature } } struct Winter { temperature: f32, } impl State for Winter { fn handle(&self, context: &mut Context) { println!("冬天来了,开始下雪....当前温度:{}", self.get_temperature()); context.set_state(Box::new(Spring{temperature:15.2})); } fn get_temperature(&self) -> f32 { self.temperature } } fn main() { let mut season = Context { state: Some(Box::new(Winter { temperature: -2.5 })), }; season.request(); season.request(); season.request(); season.request(); season.request(); season.request(); season.request(); season.request(); season.request(); season.request(); println!("."); println!("."); println!("."); println!("."); println!("."); println!("."); println!("一年四季,周而复始...."); }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/设计模式/visitor/src/bin/visitor.rs
设计模式/visitor/src/bin/visitor.rs
trait Visitor { fn visit_element_a(&self, element: &ElementA); fn visit_element_b(&self, element: &ElementB); } trait Element { fn accept(&self, viritor: &dyn Visitor); } #[derive(Debug)] struct ElementA { name: String, age: i32, } impl Element for ElementA { fn accept(&self, viritor: &dyn Visitor) { viritor.visit_element_a(self) } } #[derive(Debug)] struct ElementB { weight: f32, height: f32, } impl Element for ElementB { fn accept(&self, viritor: &dyn Visitor) { viritor.visit_element_b(self) } } // 具体的访问者 struct ConcreteVisitor; impl Visitor for ConcreteVisitor { fn visit_element_a(&self, element: &ElementA) { println!("elementa:{:?}", element); } fn visit_element_b(&self, element: &ElementB) { println!("elementb:{:?}", element); } } struct ObjectStructure { elements: Vec<Box<dyn Element>>, } impl ObjectStructure { fn new() -> Self { Self { elements: vec![] } } fn add_element(&mut self, element: Box<dyn Element>) { self.elements.push(element); } fn accept(&self, visitor: &dyn Visitor) { for element in &self.elements { element.accept(visitor); } } } fn main() { let mut object_structure = ObjectStructure::new(); //添加元素 object_structure.add_element(Box::new(ElementA { name: "小东西".to_string(), age: 3, })); object_structure.add_element(Box::new(ElementB { height: 60.1, weight: 10.3, })); // 访问者 let visitor = ConcreteVisitor; // 接收访问者 object_structure.accept(&visitor); }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/设计模式/proxy/src/bin/proxy.rs
设计模式/proxy/src/bin/proxy.rs
trait File { fn read(&self); } struct TxtFile { file_name: String, } impl TxtFile { fn load_from_dist(&self) { println!("加载文件:{}", &self.file_name); } fn new(file_name: String) -> Self { let file = TxtFile { file_name }; file.load_from_dist(); file } } impl File for TxtFile { fn read(&self) { println!("读取文件:{}", &self.file_name); } } struct ProxyFile { txt_file: TxtFile, file_name: String, } impl ProxyFile { fn new(file_name: String) -> Self { Self { txt_file: TxtFile::new(file_name.clone()), file_name, } } } impl File for ProxyFile { fn read(&self) { println!("-----------通过代理读取文件开始-----------"); self.txt_file.read(); println!("-----------通过代理读取文件结束-----------") } } fn main() { let proxy_file = ProxyFile::new("拥抱未来语言Rust".to_string()); proxy_file.read(); }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/设计模式/composite/src/bin/composite.rs
设计模式/composite/src/bin/composite.rs
//! 组合模式 // 组件接口 trait Component{ fn name(&self)->&'static str; fn search(&self,keyword:&str); } // 文件(Leaf) struct File{ name:&'static str } impl File{ fn new(name:&'static str)->Self{ Self{name} } } impl Component for File{ fn name(&self)->&'static str { self.name } fn search(&self,keyword:&str) { println!("在文件:‘{}’中搜索关键词:‘{}’",self.name,keyword); } } // 文件夹(Composite) struct Folder{ name:&'static str, childrens:Vec<Box<dyn Component>> } impl Folder{ fn new(name:&'static str)->Self{ Self{name,childrens:Vec::new()} } fn add_component(&mut self,component:impl Component+'static){ self.childrens.push(Box::new(component)); } } impl Component for Folder{ fn name(&self)->&'static str { self.name } fn search(&self,keyword:&str) { println!("在文件夹:‘{}’下搜索关键字:‘{}’",self.name,keyword); self.childrens.iter().for_each(|chi|chi.search(keyword)); } } fn main() { let file1 = File::new("组合模式.md"); let file2 = File::new("特征.md"); let file3 = File::new("struct.md"); let mut folder1 = Folder::new("设计模式"); folder1.add_component(file1); let mut folder2 = Folder::new("拥抱未来语言Rust"); folder2.add_component(file2); folder2.add_component(file3); folder2.add_component(folder1); // 拥抱未来语言Rust // / | \ // 特征.md struct.md 设计模式 // | // 组合模式.md folder2.search("rust"); }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/设计模式/builder/src/bin/builder.rs
设计模式/builder/src/bin/builder.rs
//! 实现构建者模式 // 使用构建者模式模拟食堂制备早餐 // 早餐包含的食物,抽象为Item trait Item { fn name(&self) -> String; fn price(&self) -> f32; fn packing(&self) -> String; } // 鸡肉汉堡 struct ChickenHamburg; impl Item for ChickenHamburg { fn name(&self) -> String { String::from("鸡肉汉堡") } fn price(&self) -> f32 { 23.2 } fn packing(&self) -> String { String::from("盒子") } } // 牛肉汉堡 struct BeafHamburg; impl Item for BeafHamburg { fn name(&self) -> String { "牛肉汉堡".to_string() } fn price(&self) -> f32 { 35.8 } fn packing(&self) -> String { "包装纸".to_string() } } // 百世可乐 struct Pepsi; impl Item for Pepsi { fn name(&self) -> String { "百事可乐".to_string() } fn price(&self) -> f32 { 5.5 } fn packing(&self) -> String { "罐装".to_string() } } // 苏打水 struct Soda; impl Item for Soda { fn name(&self) -> String { "苏打水".to_string() } fn price(&self) -> f32 { 4.5 } fn packing(&self) -> String { "罐装".to_string() } } // 食物 struct Meal { items: Vec<Box<dyn Item>>, } impl Meal { fn add_item(&mut self, item: Box<dyn Item>) { self.items.push(item); } fn get_cost(&self) -> f32 { self.items.iter().fold(0.0, |a, b| a + b.price()) } fn show_items(&self) { for i in self.items.iter() { println!( "name:{} price:{} packing:{}", i.name(), i.price(), i.packing() ) } } } // 构建者 trait Builder { fn prepare_beaf_humberg() -> Meal; fn prepare_chicken_humberg() -> Meal; } // 天津的小作坊 struct TiJinBuilder; impl Builder for TiJinBuilder { fn prepare_beaf_humberg() -> Meal { let mut meal = Meal { items: vec![] }; meal.add_item(Box::new(BeafHamburg)); meal.add_item(Box::new(Pepsi)); meal } fn prepare_chicken_humberg() -> Meal { let mut meal = Meal { items: vec![] }; meal.add_item(Box::new(ChickenHamburg)); meal.add_item(Box::new(Soda)); meal } } // 成都的小作坊 struct CdBuilder; impl Builder for CdBuilder { fn prepare_beaf_humberg() -> Meal { let mut meal = Meal { items: vec![] }; meal.add_item(Box::new(BeafHamburg)); meal.add_item(Box::new(Soda)); meal } fn prepare_chicken_humberg() -> Meal { let mut meal = Meal { items: vec![] }; meal.add_item(Box::new(ChickenHamburg)); meal.add_item(Box::new(Soda)); meal } } fn main() { // 成都小作坊制作的牛肉汉堡 let cd = CdBuilder::prepare_beaf_humberg(); cd.show_items(); cd.get_cost(); // 天津小作坊制作的牛肉汉堡 let tj = TiJinBuilder::prepare_beaf_humberg(); tj.show_items(); tj.get_cost(); }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/设计模式/command/src/bin/command.rs
设计模式/command/src/bin/command.rs
use std::{collections::HashMap, rc::Rc}; // 电视 Receiver struct Tv; impl Tv { fn on(&self) { println!("打开电视....") } fn off(&self) { println!("关闭电视....") } } // 命令接口 trait Command { fn execute(&self); } // 具体命令:打开电视 struct OnTvCommand { tv: Rc<Tv>, } impl OnTvCommand { fn new(tv: Rc<Tv>) -> Self { Self { tv } } } impl Command for OnTvCommand { fn execute(&self) { self.tv.on(); } } // 具体命令:关闭电视 struct OffTvCommand { tv: Rc<Tv>, } impl OffTvCommand { fn new(tv: Rc<Tv>) -> Self { Self { tv } } } impl Command for OffTvCommand { fn execute(&self) { self.tv.off(); } } // 遥控器:Invoker struct RemoteControl { commands: HashMap<String, Rc<dyn Command>>, } impl RemoteControl { fn new(tv: Rc<Tv>) -> Self { let mut commands: HashMap<String, Rc<dyn Command>> = HashMap::new(); commands.insert("on".to_string(), Rc::new(OnTvCommand::new(tv.clone()))); commands.insert("off".to_string(), Rc::new(OffTvCommand::new(tv.clone()))); Self { commands } } // 打开电视 fn on_tv(&self) { self.commands.get("on").map(|command| command.execute()); } // 关闭电视 fn off_tv(&self) { self.commands.get("off").map(|command| command.execute()); } } fn main() { let remote_control = RemoteControl::new(Rc::new(Tv)); remote_control.on_tv(); remote_control.off_tv(); }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/设计模式/observer/src/main.rs
设计模式/observer/src/main.rs
use std::collections::HashMap; trait Observer { fn update(&mut self, temperature: f32, pressure: f32, humidity: f32); fn display(&self); fn get_id(&self) -> i32; } struct Baidu { id: i32, temperature: f32, pressure: f32, humidity: f32, } impl Observer for Baidu { fn update(&mut self, temperature: f32, pressure: f32, humidity: f32) { self.temperature = temperature; self.pressure = pressure; self.humidity = humidity; self.display(); } fn display(&self) { println!("---------百度天气预报-------------"); println!( "温度:{} 气压:{} 湿度:{}", self.temperature, self.pressure, self.humidity ); println!("---------百度天气预报-------------"); } fn get_id(&self) -> i32 { self.id } } struct Sina { id: i32, temperature: f32, pressure: f32, humidity: f32, } impl Observer for Sina { fn update(&mut self, temperature: f32, pressure: f32, humidity: f32) { self.temperature = temperature; self.pressure = pressure; self.humidity = humidity; self.display(); } fn display(&self) { println!("---------新浪天气预报-------------"); println!( "温度:{} 气压:{} 湿度:{}", self.temperature, self.pressure, self.humidity ); println!("---------新浪天气预报-------------"); } fn get_id(&self) -> i32 { self.id } } trait Subject { fn attach(&mut self, observer: Box<dyn Observer>); fn dettach(&mut self, observer: Box<dyn Observer>); fn notifyall(&mut self); } struct CNWeather { temperature: f32, pressure: f32, humidity: f32, observers: HashMap<i32, Box<dyn Observer>>, } impl CNWeather { fn new() -> Self { CNWeather { temperature: 0_f32, pressure: 0_f32, humidity: 0_f32, observers: HashMap::new(), } } fn update(&mut self, temperature: f32, pressure: f32, humidity: f32) { self.temperature = temperature; self.pressure = pressure; self.humidity = humidity; self.notifyall(); } } impl Subject for CNWeather { fn attach(&mut self, observer: Box<dyn Observer>) { self.observers.entry(observer.get_id()).or_insert(observer); } fn dettach(&mut self, observer: Box<dyn Observer>) { self.observers.remove(&observer.get_id()); } fn notifyall(&mut self) { for observer in self.observers.iter_mut() { println!("\r\n"); observer .1 .update(self.temperature, self.pressure, self.humidity); println!("\r\n\r\n") } } } fn main() { let mut cn_weather = CNWeather::new(); let baidu = Baidu { id: 10001, temperature: 0_f32, pressure: 0_f32, humidity: 0_f32, }; let sina = Sina { id: 10002, temperature: 0_f32, pressure: 0_f32, humidity: 0_f32, }; cn_weather.attach(Box::new(baidu)); cn_weather.attach(Box::new(sina)); // 更新 cn_weather.update(23.1, 101.23, 89.1); }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/设计模式/singleton/src/main.rs
设计模式/singleton/src/main.rs
fn main() { println!("Hello, world!"); }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/设计模式/singleton/src/bin/sync_once_singleton.rs
设计模式/singleton/src/bin/sync_once_singleton.rs
use std::cell::RefCell; use std::sync::{Arc, Once}; use std::{thread, vec}; type V = Option<Arc<RefCell<Vec<i32>>>>; static mut VALS: V = None; static INIT: Once = Once::new(); fn main() { let handle1 = thread::spawn(move || { INIT.call_once(|| unsafe { VALS = Some(Arc::new(RefCell::new(vec![1, 2, 3, 4, 5]))); println!("thread1 INIT VALS:{:?}", VALS); }); }); let handle2 = thread::spawn(move || { INIT.call_once(|| unsafe { VALS = Some(Arc::new(RefCell::new(vec![1, 2, 3, 4, 5, 6]))); println!("thread1 INIT VALS:{:?}", VALS); }); }); handle1.join().unwrap(); handle2.join().unwrap(); println!("{:?}", unsafe { VALS.take() }); }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/设计模式/singleton/src/bin/static_mutex_singleton.rs
设计模式/singleton/src/bin/static_mutex_singleton.rs
use std::{ sync::{Arc, Mutex}, thread, time::Duration, }; #[derive(Debug)] struct Singleton(Vec<i32>); static mut INSTANCE: Option<Arc<Mutex<Singleton>>> = None; //静态初始化,只运行一次 static LOCK: Mutex<i32> = Mutex::new(0); impl Singleton { //关联方法, 获取单例实例的方法 fn get_instance(sec: u64) -> Arc<Mutex<Singleton>> { // 使用懒加载创建单例实例 // 这里使用了 Arc 和 Mutex 来实现线程安全的单例 // 只有第一次调用 get_instance 时会创建实例,之后都会返回已创建的实例 unsafe { if INSTANCE.is_none() { let lock = LOCK.lock().unwrap(); // get_or_insert_with ,如果是 None ,则将从data计算的值插入选项中,然后返回对包含值的可变引用。 INSTANCE .get_or_insert_with(|| { thread::sleep(Duration::from_secs(sec)); Arc::new(Mutex::new(Singleton(Vec::new()))) }) .clone() } else { INSTANCE.clone().unwrap() } } } fn show_message(&self) { println!("singleton vec addr:{:p}", &self.0); } } // 下面是错误的单例实现方式 struct Singleton1(Vec<i32>); impl Singleton1 { //关联方法, 获取单例实例的方法 fn get_instance(sec: u64) -> Arc<Mutex<Singleton1>> { // 使用懒加载创建单例实例 // 这里使用了 Arc 和 Mutex 来实现线程安全的单例 // 只有第一次调用 get_instance 时会创建实例,之后都会返回已创建的实例 static mut INSTANCE: Option<Arc<Mutex<Singleton1>>> = None; //静态初始化,只运行一次 unsafe { // get_or_insert_with ,如果是 None ,则将从data计算的值插入选项中,然后返回对包含值的可变引用。 INSTANCE .get_or_insert_with(|| { thread::sleep(Duration::from_secs(sec)); Arc::new(Mutex::new(Singleton1(Vec::new()))) }) .clone() } } fn show_message(&self) { println!("singleton1 vec addr:{:p}", &self.0); } } fn main() { // 获取单例实例,自定义 let handle1 = thread::spawn(|| { let instance = Singleton::get_instance(1); instance.lock().unwrap().show_message(); }); let handle2 = thread::spawn(|| { let instance = Singleton::get_instance(0); instance.lock().unwrap().show_message(); }); handle1.join().unwrap(); handle2.join().unwrap(); // 下面是错误的单例实例化方式 let handle1 = thread::spawn(|| { let instance = Singleton1::get_instance(2); instance.lock().unwrap().show_message(); }); let handle2 = thread::spawn(|| { let instance = Singleton1::get_instance(2); instance.lock().unwrap().show_message(); }); handle1.join().unwrap(); handle2.join().unwrap(); }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/设计模式/singleton/src/bin/lazy_static_singleton.rs
设计模式/singleton/src/bin/lazy_static_singleton.rs
use lazy_static::lazy_static; use std::{sync::Mutex, thread}; lazy_static! { pub static ref ARRAY: Mutex<Vec<u8>> = Mutex::new(Vec::new()); } pub fn do_a_call() { // 验证内存地址 println!("addr:{:p}", &*ARRAY.lock().unwrap()); ARRAY.lock().unwrap().push(1); } fn main() { // 获取单例实例,自定义 let handle1 = thread::spawn(|| { do_a_call(); }); let handle2 = thread::spawn(|| { do_a_call(); }); handle1.join().unwrap(); handle2.join().unwrap(); println!("Called {} times", ARRAY.lock().unwrap().len()); }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/设计模式/iterator/src/bin/stack.rs
设计模式/iterator/src/bin/stack.rs
//! 实现栈数据结构并为栈实现三种不同类型的迭代器 #[derive(Debug)] struct Stack<T> { size: usize, data: Vec<T>, } impl<T> Stack<T> { // 初始化栈 fn new() -> Self { Self { size: 0, data: vec![], } } // 判断栈是否为空 fn is_empty(&self) -> bool { self.size == 0 } // 栈的长度 fn len(&self) -> usize { self.size } // 清空栈 fn clear(&mut self) { self.data.clear(); self.size = 0; } // push元素 fn push(&mut self, value: T) { self.data.push(value); self.size += 1; } // pop弹出元素 fn pop(&mut self) -> Option<T> { self.size -= 1; self.data.pop() } // 返回栈顶数据的不可变引用 fn peek(&self) -> Option<&T> { self.data.get(self.size - 1) } // 返回栈顶数据的可变引用 fn peek_mut(&mut self) -> Option<&mut T> { self.data.get_mut(self.size - 1) } // 将集合转换为迭代器 fn into_iter(self) -> IntoIter<T> { IntoIter(self) } // 将集合转换为不可变引用迭代器 fn iter(&self) -> Iter<T> { let mut iter = Iter(Vec::new()); for item in self.data.iter() { iter.0.push(item); } iter } // 将集合转换为可变引用迭代器 fn iter_mut(&mut self) -> IterMut<T> { let mut iter = IterMut(Vec::new()); for item in self.data.iter_mut() { iter.0.push(item); } iter } } // 将Stack变成三种不同的迭代器 // 消费集合数据变成一个迭代器 struct IntoIter<T>(Stack<T>); impl<T> Iterator for IntoIter<T> { type Item = T; fn next(&mut self) -> Option<Self::Item> { if !self.0.is_empty() { self.0.size -= 1; self.0.data.pop() } else { None } } } // 不可变引用迭代器 struct Iter<'a, T: 'a>(Vec<&'a T>); impl<'a, T> Iterator for Iter<'a, T> { type Item = &'a T; fn next(&mut self) -> Option<Self::Item> { self.0.pop() } } // 可变引用迭代器 struct IterMut<'a, T: 'a>(Vec<&'a mut T>); impl<'a, T> Iterator for IterMut<'a, T> { type Item = &'a mut T; fn next(&mut self) -> Option<Self::Item> { self.0.pop() } } fn main() { let mut s = Stack::new(); s.push(100); s.push(200); s.push(99); s.push(888); // 不可变引用迭代器 let sum = s.iter().sum::<i32>(); println!("sum:{sum}"); // 输出1287 // 可变引用迭代器 // 输出ele:8880 ele:990 ele:2000 ele:1000 s.iter_mut() .map(|item| *item * 10) .for_each(|ele| print!("ele:{ele} ")); // 通过可变引用修改值 for i in s.iter_mut() { *i += 10; } println!("stack:{:?}", s); // 输出stack:Stack { size: 4, data: [110, 210, 109, 898] } // 将消费stack生成迭代器 let sum = s.into_iter().sum::<i32>(); println!("sum:{sum}"); // 输出1327 // stack已被消费,所有权已经转移,下面代码会报编译错误 // println!("stack:{:?}",s); }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/设计模式/iterator/src/bin/num_generator.rs
设计模式/iterator/src/bin/num_generator.rs
//! 基于Iterator实现数字生成器 use std::{collections::HashSet, ops::AddAssign}; pub struct NumberGenerator { // 开始 begin: usize, // 结束 end: usize, } impl NumberGenerator { pub fn new(begin: usize, end: usize) -> Self { Self { begin, end } } } impl Iterator for NumberGenerator { type Item = usize; fn next(&mut self) -> Option<Self::Item> { if self.begin < self.end { let res = self.begin; // begin+=1 self.begin.add_assign(1); Some(res) } else { None } } } fn main() { let nums = NumberGenerator::new(90, 100); for i in nums { println!("i = {i}"); } //使用Iterator上的transformation算子过滤出能被3和7整除的数。 let nums = NumberGenerator::new(10, 100).filter(|item| item % 3 == 0 && item % 7 == 0); for i in nums { println!("ii = {i}"); } // 常见的iterator上的方法 // filter for_each (0..5) //初始的迭代器 .filter(|n| n % 2 == 0) // 过滤的迭代器 .for_each(|n| println!("{n}")); //对迭代器每个元素进行操作 // map (0..5) .map(|n| n as f64) .map(|n| n.sqrt()) .for_each(|n| println!("{n}")); //统计元素个数 let a = count_iterator(0..=500); println!("collection count:{a}"); // 输出501 // 求和 println!("sum:{}", (1..=100).sum::<usize>()); // 输出5050 // fold let sum = (1..=100).fold(1, |init, n| init + n); println!("sum:{sum}"); // 输出5051 // collect map只要有None值,整个iterator都是None let vec = (0..5).collect::<Vec<usize>>(); assert_eq!(vec, vec![0, 1, 2, 3, 4]); let res = (1..50) .map(|n| if n <= 3 { Some(n) } else { None }) .collect::<Option<Vec<usize>>>(); assert_eq!(res, None); // collect hashset (0..5) .map(|n| if n > 3 { 3 } else { n }) .collect::<HashSet<usize>>() .iter() .for_each(|n| println!("{n}")); // 输出0 1 2 3 顺序不定 // flatten扁平化处理 vec![Some(1), None, Some(2)] .into_iter() .flatten() .collect::<Vec<usize>>() .into_iter() .for_each(|n| println!("{n}")); // 链式调用 (0..10) .map(|e| { println!("map:{e}"); e }) .filter(|e| { println!("filter:{e}"); *e >= 0 }).for_each(|e|println!("for_each:{e}")); } // 统计迭代器元素个数 fn count_iterator(mut iterator: impl Iterator) -> usize { let mut res = 0; while let Some(_) = iterator.next() { res.add_assign(1); } res }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/设计模式/chain_of_responsibility/src/bin/chain_of_responsibility.rs
设计模式/chain_of_responsibility/src/bin/chain_of_responsibility.rs
//! 责任链模式 //! // 定义Requst结构体抽象为Patient病人 struct Patient { name: String, } // 处理者Handler抽象为Department部门 trait Department { // 处理者接口 fn handle(&mut self, patient: &mut Patient); // 责任链的下一级 fn next(&mut self) -> &mut Option<Box<dyn Department>>; fn execute(&mut self, patient: &mut Patient) { self.handle(patient); self.next().as_mut().map(|d| { d.execute(patient); }); } } // 医生 struct Doctor { next: Option<Box<dyn Department>>, } impl Doctor { fn new(next: impl Department + 'static) -> Self { Self { next: Some(Box::new(next)), } } } impl Department for Doctor { fn handle(&mut self, patient: &mut Patient) { println!("医生正在给病人:'{}' 诊断...", patient.name); } fn next(&mut self) -> &mut Option<Box<dyn Department>> { &mut self.next } } // 药师 struct Medical { next: Option<Box<dyn Department>>, } impl Medical { fn new(next: impl Department + 'static) -> Self { Self { next: Some(Box::new(next)), } } } impl Department for Medical { fn handle(&mut self, patient: &mut Patient) { println!("药师正在给病人:'{}' 开药...", patient.name) } fn next(&mut self) -> &mut Option<Box<dyn Department>> { &mut self.next } } // 收银 #[derive(Default)] struct Cashier { next: Option<Box<dyn Department>>, } impl Department for Cashier { fn handle(&mut self, patient: &mut Patient) { println!("收银员正在给病人:'{}' 收银...", patient.name); } fn next(&mut self) -> &mut Option<Box<dyn Department>> { &mut self.next } } // 接待 struct Reception { next: Option<Box<dyn Department>>, } impl Reception { fn new(next: impl Department + 'static) -> Self { Self { next: Some(Box::new(next)), } } } impl Department for Reception { fn handle(&mut self, patient: &mut Patient) { println!("接待员正在接待病人:'{}'...", patient.name) } fn next(&mut self) -> &mut Option<Box<dyn Department>> { &mut self.next } } fn main() { // 构造责任链 let cashier = Cashier::default(); let medical = Medical::new(cashier); let doctor = Doctor::new(medical); let mut reception = Reception::new(doctor); // 病人 let mut patient = Patient { name: "张三".to_string(), }; // 执行 reception.execute(&mut patient); }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/设计模式/decorator/src/bin/decorator.rs
设计模式/decorator/src/bin/decorator.rs
// 先定义component,这里抽象为DataSource trait DataSource { fn write(&mut self); fn read(&self); } // 具体的component,这里为FileDataSource #[derive(Default)] struct FileDataSource; impl DataSource for FileDataSource { fn write(&mut self) { println!("文件数据写入...") } fn read(&self) { println!("文件数据读取...") } } // 装饰器接口,扩展自DataSource trait DataSourceDecorator: DataSource { fn wrap(data_source: impl DataSource + 'static) -> Self; } // 具体的压缩装饰器 struct CompressionDataSource { wrapper: Box<dyn DataSource>, } impl DataSourceDecorator for CompressionDataSource { fn wrap(data_source: impl DataSource + 'static) -> Self { Self { wrapper: Box::new(data_source), } } } impl DataSource for CompressionDataSource { fn write(&mut self) { println!("压缩..."); self.wrapper.write(); } fn read(&self) { println!("解压缩..."); self.wrapper.read(); } } // 加密装饰器 struct EncryptionDataSourceDecorator { wrapper: Box<dyn DataSource>, } impl DataSource for EncryptionDataSourceDecorator { fn read(&self) { println!("解密..."); self.wrapper.read(); } fn write(&mut self) { println!("加密..."); self.wrapper.write(); } } impl DataSourceDecorator for EncryptionDataSourceDecorator { fn wrap(data_source: impl DataSource + 'static) -> Self { Self { wrapper: Box::new(data_source), } } } fn main() { let file: FileDataSource = FileDataSource::default(); let encryption_decorator = EncryptionDataSourceDecorator::wrap(file); let mut compression_decorator = CompressionDataSource::wrap(encryption_decorator); // 压缩+加密 写入 compression_decorator.write(); // 解压缩+解密 读取 compression_decorator.read(); }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/设计模式/decorator/src/bin/std_io.rs
设计模式/decorator/src/bin/std_io.rs
use std::io::{BufReader, Cursor, Read}; fn main() { // 标准库中的io模块使用了装饰器模式 let mut input = BufReader::new(Cursor::new("study rust")); let mut buf = [0; 20]; input.read(&mut buf).ok(); for byte in buf { print!("{}", char::from(byte)); } }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/设计模式/template_method/src/bin/template_method.rs
设计模式/template_method/src/bin/template_method.rs
trait Template { // 抽象方法 fn step1(&self); // 默认方法 fn step2(&self) { println!("step2:去掉皮") } // 抽象方法 fn step3(&self); // 默认方法 fn step4(&self) { println!("step4:煮耙后出锅") } // 模板方法 fn action(&self) { self.step1(); self.step2(); self.step3(); self.step4(); } } // 具体类实现模板方法 struct PotatoImpl; impl Template for PotatoImpl { fn step1(&self) { println!("step1:将土豆洗干净") } fn step3(&self) { println!("step3:切成1厘米见方的小块") } } struct BeafImpl; impl Template for BeafImpl { fn step1(&self) { println!("step1:买一块上好的和牛,清洗干净") } fn step2(&self) { println!("step2:切成小块") } fn step3(&self) { println!("step3:配上料下锅煎至8成熟,起锅") } fn step4(&self) { println!("step4:摆盘,开整!") } } fn main() { println!("===========炖土豆==========="); let potato_impl = PotatoImpl; potato_impl.action(); println!("===========煎牛排==========="); let beaf_impl = BeafImpl; beaf_impl.action(); }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/设计模式/facade/src/bin/facade.rs
设计模式/facade/src/bin/facade.rs
// 零件 trait Part { fn run(&self); } // 喇叭 struct Horn; // 屏幕 struct Screen; // 网络 struct Net; // 变压器 struct Transformer; impl Part for Horn { fn run(&self) { println!("喇叭已就位...") } } impl Part for Screen { fn run(&self) { println!("屏幕已就位...") } } impl Part for Net { fn run(&self) { println!("网络已就位") } } impl Part for Transformer { fn run(&self) { println!("变压器已就位...") } } // 创建外观 struct TvFacade { horn: Horn, screen: Screen, net: Net, transformer: Transformer, } impl TvFacade { fn init(&self) { self.horn.run(); self.screen.run(); self.net.run(); self.transformer.run(); println!("初始化完毕....\r\n") } } fn main() { let tv = TvFacade { horn: Horn, screen: Screen, net: Net, transformer: Transformer, }; tv.init() }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/设计模式/mediator/src/bin/mediator.rs
设计模式/mediator/src/bin/mediator.rs
use std::collections::HashMap; trait Mediator { fn register_colleague(&mut self, member: Box<dyn Colleague>); fn notify(&self, member_name: &str, msg: String); } struct CenteralMediator { // 注册的同事名字-同事对象的对应关系 members: HashMap<String, Box<dyn Colleague>>, } impl Mediator for CenteralMediator { fn register_colleague(&mut self, member: Box<dyn Colleague>) { self.members.insert(member.name(), member); } fn notify(&self, member_name: &str, msg: String) { self.members .get(member_name) .map(|m| m.action(msg.as_str())); } } trait Colleague { fn name(&self) -> String; fn action(&self, msg: &str) { println!("msg:{msg}") } fn send(&self, mediator: &dyn Mediator, msg: &str) { mediator.notify(self.name().as_str(), msg.to_string()); } } // 闹钟 struct Alarm; impl Colleague for Alarm { fn name(&self) -> String { "Alarm".to_string() } fn send(&self, mediator: &dyn Mediator, msg: &str) { mediator.notify(self.name().as_str(), msg.to_string()); } } // 窗帘 struct Curtain; impl Colleague for Curtain { fn name(&self) -> String { "Curtain".to_string() } fn send(&self, mediator: &dyn Mediator, msg: &str) { mediator.notify(self.name().as_str(), msg.to_string()); } } // 灯 struct Lamp; impl Colleague for Lamp { fn name(&self) -> String { "Lamp".to_string() } fn send(&self, mediator: &dyn Mediator, msg: &str) { mediator.notify(self.name().as_str(), msg.to_string()); } } fn main() { // 具体中介者对象 let mut mediator = CenteralMediator { members: HashMap::new(), }; // 同事对象 let alarm = Alarm; let curtain = Curtain; let lamp = Lamp; // 注册到中介者 mediator.register_colleague(Box::new(alarm)); mediator.register_colleague(Box::new(curtain)); mediator.register_colleague(Box::new(lamp)); mediator .members .get("Alarm") .map(|m| m.send(&mediator, "闹钟开始响铃")); mediator .members .get("Curtain") .map(|m| m.send(&mediator, "自动打开窗帘")); mediator .members .get("Lamp") .map(|m| m.send(&mediator, "打开灯光")); mediator .members .get("Alarm") .map(|m| m.send(&mediator, "关闭闹钟")); }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/设计模式/prototype/src/bin/prototype.rs
设计模式/prototype/src/bin/prototype.rs
#[derive(Clone, PartialEq, Eq, Debug)] struct Shape { id: String, mtype: String, } impl Shape { fn set_id(&mut self, id: String) { self.id = id; } } #[derive(Clone, PartialEq, Eq, Debug)] struct Circle { shape: Shape, } impl Circle { fn new() -> Circle { Circle { shape: Shape { id: String::from("123"), mtype: String::from("圆"), }, } } } fn main() { // 通过构造方法构造对象 s是原型 let s = Circle::new(); // 通过clone方法复制对象 s1是原型s的克隆 let mut s1 = s.clone(); // 克隆的两个对象的值应该是相等的 println!("s:{:?}", s); println!("s1:{:?}", s1); // 修改s1 s1.shape.set_id(String::from("234")); println!("s:{:?}", s); println!("s1:{:?}", s1); }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/设计模式/factory_method_and_absfactory/src/main.rs
设计模式/factory_method_and_absfactory/src/main.rs
// 工厂模式和抽象工厂模式 fn main() { println!("Hello, world!"); }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/设计模式/factory_method_and_absfactory/src/bin/simple_factory.rs
设计模式/factory_method_and_absfactory/src/bin/simple_factory.rs
trait Product { fn weight(&self) -> f64; } #[derive(Debug)] struct Pen; #[derive(Debug)] struct Car; impl Product for Pen { fn weight(&self) -> f64 { println!("这只笔重量为150g"); 150.0 } } impl Product for Car { fn weight(&self) -> f64 { println!("这辆汽车重1.5吨"); 1500000.0 } } struct SimpleFactory; impl SimpleFactory { fn get_product(product: &str) -> Option<Box<dyn Product>> { if product == "car" { Some(Box::new(Car)) } else if product == "pen" { Some(Box::new(Pen)) } else { None } } } fn main() { SimpleFactory::get_product("pen").unwrap().weight(); SimpleFactory::get_product("car").unwrap().weight(); let product = SimpleFactory::get_product("other"); if product.is_some() { product.unwrap().weight(); } else { println!("没有该产品") } }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/设计模式/factory_method_and_absfactory/src/bin/factory_method.rs
设计模式/factory_method_and_absfactory/src/bin/factory_method.rs
trait Product { fn weight(&self) -> f64; } trait Factory { type ProductType; fn create_product(&self) -> Self::ProductType; } struct Pen; impl Product for Pen { fn weight(&self) -> f64 { println!("这只笔重量为150g"); 150.0 } } struct PenFactory; impl Factory for PenFactory { type ProductType = Pen; fn create_product(&self) -> Self::ProductType { Pen } } struct Car; impl Product for Car { fn weight(&self) -> f64 { println!("这辆汽车重1.5吨"); 1500000.0 } } struct CarFactory; impl Factory for CarFactory { type ProductType = Car; fn create_product(&self) -> Self::ProductType { Car } } fn main() { CarFactory.create_product().weight(); PenFactory.create_product().weight(); }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/设计模式/factory_method_and_absfactory/src/bin/abs_factory.rs
设计模式/factory_method_and_absfactory/src/bin/abs_factory.rs
trait Engine { fn show(&self); } trait Wheel { fn show(&self); } trait Factory { type E: Engine; type W: Wheel; // 返回具体的关联类型 fn create_engine(&self) -> Self::E; fn create_wheel(&self) -> Self::W; } trait DynFactory { // 返回特征对象,更具有通用性 fn dyn_create_engine(&self) -> Box<dyn Engine>; fn dyn_create_wheel(&self) -> Box<dyn Wheel>; } struct Engine1; impl Engine for Engine1 { fn show(&self) { println!("通用 LS"); } } struct Engine2; impl Engine for Engine2 { fn show(&self) { println!("福特 EcoBoost"); } } struct Wheel1; impl Wheel for Wheel1 { fn show(&self) { println!("米其林轮胎"); } } struct Wheel2; impl Wheel for Wheel2 { fn show(&self) { println!("朝阳轮胎"); } } struct XMS7Factory; // 通过关联类型返回 impl Factory for XMS7Factory { type E = Engine1; type W = Wheel1; fn create_engine(&self) -> Self::E { Engine1 } fn create_wheel(&self) -> Self::W { Wheel1 } } // 可以返回特征对象 impl DynFactory for XMS7Factory { fn dyn_create_engine(&self) -> Box<dyn Engine> { Box::new(Engine1) } fn dyn_create_wheel(&self) -> Box<dyn Wheel> { Box::new(Wheel1) } } fn main() { let xiaomi_su7_factory = XMS7Factory; let engine = xiaomi_su7_factory.create_engine(); engine.show(); let wheel = xiaomi_su7_factory.create_wheel(); wheel.show(); let engine = xiaomi_su7_factory.dyn_create_engine(); engine.show(); let wheel = xiaomi_su7_factory.dyn_create_wheel(); wheel.show(); }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/设计模式/memento/src/bin/memento.rs
设计模式/memento/src/bin/memento.rs
//! 备忘录模式 // 备忘录 #[derive(Clone)] struct Memento { state: String, } impl Memento { fn get_state(&self) -> &str { &self.state } fn set_state(&mut self, state: String) { self.state = state } } // 发起人 struct Originator { state: String, } impl Originator { fn get_state(&self) -> &str { &self.state } fn set_state(&mut self, state: String) { self.state = state } fn create_memento(&self) -> Memento { Memento { state: self.state.clone(), } } fn restore_from_memento(&mut self, memento: Memento) { self.state = memento.state } } // 存档 struct CareTacker { memento_list: Vec<Memento>, } impl CareTacker { fn add(&mut self, memento: Memento) { self.memento_list.push(memento); } fn get(&self, index: usize) -> Memento { self.memento_list.get(index).unwrap().clone() } } fn main() { // 发起人 let mut originator = Originator { state: "状态1:红灯".to_string(), }; println!("init state:{}", originator.get_state()); // 存档 let mut care_tacker = CareTacker { memento_list: vec![], }; // 将状态保存到备忘录并存档 care_tacker.add(originator.create_memento()); originator.set_state("状态2:黄灯".to_string()); println!("update state:{}", originator.get_state()); care_tacker.add(originator.create_memento()); originator.set_state("状态3:绿灯".to_string()); println!("update state:{}", originator.get_state()); care_tacker.add(originator.create_memento()); // 从存档恢复状态 originator.restore_from_memento(care_tacker.get(0)); println!("restore state:{}", originator.get_state()); }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/设计模式/adapter/src/bin/has_a_adapter.rs
设计模式/adapter/src/bin/has_a_adapter.rs
trait Target { fn request(&self) -> String; } pub struct Adaptee { value: i32, } impl Adaptee { fn specific_request(&self) -> String { format!("Adaptee value is {}", self.value) } } struct Adapter { adaptee: Adaptee, } impl Adapter { fn new(adaptee: Adaptee) -> Self { Adapter { adaptee } } } impl Target for Adapter { fn request(&self) -> String { self.adaptee.specific_request() } } fn main() { let adaptee = Adaptee { value: 100 }; let adapter = Adapter::new(adaptee); println!("{}", adapter.request()); }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/设计模式/strategy/src/main.rs
设计模式/strategy/src/main.rs
trait Strategy { fn do_operation(&self, num1: i32, num2: i32) -> i32; } struct StrategyAdd; impl Strategy for StrategyAdd { fn do_operation(&self, num1: i32, num2: i32) -> i32 { num1 + num2 } } struct StrategySub; impl Strategy for StrategySub { fn do_operation(&self, num1: i32, num2: i32) -> i32 { num1 - num2 } } struct StrategyMul; impl Strategy for StrategyMul { fn do_operation(&self, num1: i32, num2: i32) -> i32 { num1 * num2 } } struct Context { strategy: Box<dyn Strategy>, } impl Context { fn execute(&self, num1: i32, num2: i32) -> i32 { self.strategy.do_operation(num1, num2) } } fn main() { let mut context = Context { strategy: Box::new(StrategyAdd), }; let num1 = 100; let num2 = 200; println!("100 + 200 = {}", context.execute(num1, num2)); // 更改策略 context.strategy = Box::new(StrategyMul); println!("100 - 200 = {}", context.execute(num1, num2)); context.strategy = Box::new(StrategyMul); println!("100 * 200 = {}", context.execute(num1, num2)); }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/设计模式/interpreter/src/bin/interpreter.rs
设计模式/interpreter/src/bin/interpreter.rs
//! 解释器模式 trait Expression { fn interpret(&self) -> i32; } // 数字表达式 属于TerminalExpression struct NumberExpression { value: i32, } impl NumberExpression { fn new(value: i32) -> Self { NumberExpression { value } } } impl Expression for NumberExpression { fn interpret(&self) -> i32 { self.value } } // 加法表达式 属于NonterminalExpression struct AddExpression { left: Box<dyn Expression>, right: Box<dyn Expression>, } impl AddExpression { fn new(left: Box<dyn Expression>, right: Box<dyn Expression>) -> Self { Self { left, right } } } impl Expression for AddExpression { fn interpret(&self) -> i32 { self.left.interpret() + self.right.interpret() } } // 减法表达式 struct SubExpression { left: Box<dyn Expression>, right: Box<dyn Expression>, } impl SubExpression { fn new(left: Box<dyn Expression>, right: Box<dyn Expression>) -> Self { Self { left, right } } } impl Expression for SubExpression { fn interpret(&self) -> i32 { self.left.interpret() - self.right.interpret() } } // 乘法表达式 struct MulExpression { left: Box<dyn Expression>, right: Box<dyn Expression>, } impl MulExpression { fn new(left: Box<dyn Expression>, right: Box<dyn Expression>) -> Self { Self { left, right } } } impl Expression for MulExpression { fn interpret(&self) -> i32 { self.left.interpret() * self.right.interpret() } } // 除法表达式 struct DiviExpression { left: Box<dyn Expression>, right: Box<dyn Expression>, } impl DiviExpression { fn new(left: Box<dyn Expression>, right: Box<dyn Expression>) -> Self { Self { left, right } } } impl Expression for DiviExpression { fn interpret(&self) -> i32 { let tmp = self.right.interpret(); // 除数不能为0 assert_ne!(0, tmp); self.left.interpret() / self.right.interpret() } } fn main() { // 计算4 * 5 + 6 / 3 - 1 let a = NumberExpression::new(4); let b = NumberExpression::new(5); let c = NumberExpression::new(6); let d = NumberExpression::new(3); let e = NumberExpression::new(1); let part1 = MulExpression::new(Box::new(a), Box::new(b)); let part2 = DiviExpression::new(Box::new(c), Box::new(d)); let part3 = AddExpression::new(Box::new(part1), Box::new(part2)); let part4 = SubExpression::new(Box::new(part3), Box::new(e)); let result = part4.interpret(); println!(" 4 * 5 + 6 / 3 - 1 = {result} "); }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/设计模式/flyweight/src/bin/flyweight.rs
设计模式/flyweight/src/bin/flyweight.rs
use std::{collections::HashMap, sync::Arc}; #[warn(dead_code)] struct BigObject { data: [i32; 10000], } impl Default for BigObject { fn default() -> Self { Self { data: [0; 10000] } } } struct FlywightFactory { // BigObject需要共享,使用Arc只能指针 objects: HashMap<String, Arc<BigObject>>, } impl Default for FlywightFactory { fn default() -> Self { Self { objects: HashMap::new(), } } } impl FlywightFactory { fn get(&self, name: &str) -> Option<Arc<BigObject>> { self.objects.get(name).cloned() } fn create<T: FnOnce() -> BigObject>( &mut self, name: String, create_object: T, ) -> Arc<BigObject> { let res = Arc::new(create_object()); self.objects.insert(name, res.clone()); res } } fn main() { let mut flyweight_factory = FlywightFactory::default(); // 创建一个超大对象 flyweight_factory.create("bigobject".to_string(), BigObject::default); // 获取超大对象,不存在再创建 if let None = flyweight_factory.get("bigobject") { flyweight_factory.create("bigobject".to_string(), BigObject::default); } println!( "flyweight factory objects keys:{:?}", flyweight_factory.objects.keys() ); }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/手撸系列/write_a_db/mvcc/src/main.rs
手撸系列/write_a_db/mvcc/src/main.rs
use lazy_static::lazy_static; use serde::{Deserialize, Serialize}; use std::{ collections::{BTreeMap, HashMap, HashSet}, sync::{ atomic::{AtomicU64, Ordering}, Arc, Mutex, }, }; // 存储引擎定义,这里使用一个简单的内存 BTreeMap pub type KVEngine = BTreeMap<Vec<u8>, Option<Vec<u8>>>; // 全局递增的版本号 static VERSION: AtomicU64 = AtomicU64::new(1); // 获取下一个版本号 fn acquire_next_version() -> u64 { let version = VERSION.fetch_add(1, Ordering::SeqCst); version } lazy_static! { // 当前活跃的事务 id,及其已经写入的 key 信息 static ref ACTIVE_TXN: Arc<Mutex<HashMap<u64, Vec<Vec<u8>>>>> = Arc::new(Mutex::new(HashMap::new())); } // MVCC 事务定义 pub struct MVCC { // KV 存储引擎 kv: Arc<Mutex<KVEngine>>, } impl MVCC { pub fn new(kv: KVEngine) -> Self { Self { kv: Arc::new(Mutex::new(kv)), } } pub fn begin_transaction(&self) -> Transaction { Transaction::begin(self.kv.clone()) } } #[derive(Debug, Serialize, Deserialize)] struct Key { raw_key: Vec<u8>, version: u64, } impl Key { fn encode(&self) -> Vec<u8> { bincode::serialize(self).unwrap() } } fn decode_key(b: &Vec<u8>) -> Key { bincode::deserialize(&b).unwrap() } // MVCC 事务 pub struct Transaction { // 底层 KV 存储引擎 kv: Arc<Mutex<KVEngine>>, // 事务版本号 version: u64, // 事务启动时的活跃事务列表 active_xid: HashSet<u64>, } impl Transaction { // 开启事务 pub fn begin(kv: Arc<Mutex<KVEngine>>) -> Self { // 获取全局事务版本号 let version = acquire_next_version(); let mut active_txn: std::sync::MutexGuard<HashMap<u64, Vec<Vec<u8>>>> = ACTIVE_TXN.lock().unwrap(); // 这个 map 的 key 就是当前所有活跃的事务 let active_xid: HashSet<u64> = active_txn.keys().cloned().collect(); // 添加到当前活跃事务 id 列表中 active_txn.insert(version, vec![]); // 返回结果 Self { kv, version, active_xid, } } // 写入数据 pub fn set(&self, key: &[u8], value: Vec<u8>) { self.write(key, Some(value)) } // 删除数据 pub fn delete(&self, key: &[u8]) { self.write(key, None) } fn write(&self, key: &[u8], value: Option<Vec<u8>>) { // 判断当前写入的 key 是否和其他的事务冲突 // key 是按照 key-version 排序的,所以只需要判断最近的一个 key 即可 let mut kvengine: std::sync::MutexGuard<BTreeMap<Vec<u8>, Option<Vec<u8>>>> = self.kv.lock().unwrap(); for (enc_key, _) in kvengine.iter().rev() { let key_version = decode_key(enc_key); if key_version.raw_key.eq(key) { if !self.is_visible(key_version.version) { panic!("serialization error, try again."); } break; } } // 写入 TxnWrite let mut active_txn = ACTIVE_TXN.lock().unwrap(); active_txn .entry(self.version) .and_modify(|keys| keys.push(key.to_vec())) .or_insert_with(|| vec![key.to_vec()]); // 写入数据 let enc_key = Key { raw_key: key.to_vec(), version: self.version, }; kvengine.insert(enc_key.encode(), value); } // 读取数据,从最后一条数据进行遍历,找到第一条可见的数据 pub fn get(&self, key: &[u8]) -> Option<Vec<u8>> { let kvengine = self.kv.lock().unwrap(); for (k, v) in kvengine.iter().rev() { let key_version = decode_key(k); if key_version.raw_key.eq(key) && self.is_visible(key_version.version) { return v.clone(); } } None } // 打印出所有可见的数据 fn print_all(&self) { let mut records = BTreeMap::new(); let kvengine = self.kv.lock().unwrap(); for (k, v) in kvengine.iter() { let key_version = decode_key(k); if self.is_visible(key_version.version) { records.insert(key_version.raw_key.to_vec(), v.clone()); } } for (k, v) in records.iter() { if let Some(value) = v { print!( "{}={} ", String::from_utf8_lossy(k), String::from_utf8_lossy(value) ); } } println!(""); } // 提交事务 pub fn commit(&self) { // 清除活跃事务列表中的数据 let mut active_txn = ACTIVE_TXN.lock().unwrap(); active_txn.remove(&self.version); } // 回滚事务 pub fn rollback(&self) { // 清除写入的数据 let mut active_txn = ACTIVE_TXN.lock().unwrap(); if let Some(keys) = active_txn.get(&self.version) { let mut kvengine = self.kv.lock().unwrap(); for k in keys { let enc_key = Key { raw_key: k.to_vec(), version: self.version, }; let res = kvengine.remove(&enc_key.encode()); assert!(res.is_some()); } } // 清除活跃事务列表中的数据 active_txn.remove(&self.version); } // 判断一个版本的数据对当前事务是否可见 // 1. 如果是另一个活跃事务的修改,则不可见 // 2. 如果版本号比当前大,则不可见 fn is_visible(&self, version: u64) -> bool { if self.active_xid.contains(&version) { return false; } version <= self.version } } fn main() { let eng = KVEngine::new(); let mvcc = MVCC::new(eng); // 先新增几条数据 let tx0 = mvcc.begin_transaction(); tx0.set(b"a", b"a1".to_vec()); tx0.set(b"b", b"b1".to_vec()); tx0.set(b"c", b"c1".to_vec()); tx0.set(b"d", b"d1".to_vec()); tx0.set(b"e", b"e1".to_vec()); tx0.commit(); // 开启一个事务 let tx1 = mvcc.begin_transaction(); // 将 a 改为 a2,e 改为 e2 tx1.set(b"a", b"a2".to_vec()); tx1.set(b"e", b"e2".to_vec()); // Time // 1 a2 e2 // 0 a1 b1 c1 d1 e1 // a b c d e Keys // t1 虽然未提交,但是能看到自己的修改了 tx1.print_all(); // a=a2 b=b1 c=c1 d=d1 e=e2 // 开启一个新的事务 let tx2 = mvcc.begin_transaction(); // 删除 b tx2.delete(b"b"); // Time // 2 X // 1 a2 e2 // 0 a1 b1 c1 d1 e1 // a b c d e Keys // 此时 T1 没提交,所以 T2 看到的是 tx2.print_all(); // a=a1 c=c1 d=d1 e=e1 // 提交 T1 tx1.commit(); // 此时 T2 仍然看不到 T1 的提交,因为 T2 开启的时候,T2 还没有提交(可重复读) tx2.print_all(); // a=a1 c=c1 d=d1 e=e1 // 再开启一个新的事务 let tx3 = mvcc.begin_transaction(); // Time // 3 // 2 X uncommitted // 1 a2 e2 committed // 0 a1 b1 c1 d1 e1 // a b c d e Keys // T3 能看到 T1 的提交,但是看不到 T2 的提交 tx3.print_all(); // a=a2 b=b1 c=c1 d=d1 e=e2 // T3 写新的数据 tx3.set(b"f", b"f1".to_vec()); // T2 写同样的数据,会冲突 // 下面代码会报错 //tx2.set(b"f", b"f1".to_vec()); }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/手撸系列/write_a_db/adb/crates/services/arepl/src/main.rs
手撸系列/write_a_db/adb/crates/services/arepl/src/main.rs
use aparser::{ ast::{parse_sql_command, SqlCommand}, error::FormattedError, }; use miette::{Context, GraphicalReportHandler, IntoDiagnostic}; use rustyline::{ completion::FilenameCompleter, error::ReadlineError, highlight::Highlighter, Completer, CompletionType, Config, Editor, Helper, Hinter, Validator, }; const HISTORY_FILE: &str = "./history.txt"; #[derive(Completer, Helper, Hinter, Validator)] struct MyHelper(#[rustyline(Completer)] FilenameCompleter); impl Highlighter for MyHelper {} fn main() -> miette::Result<()> { let config = Config::builder() .history_ignore_space(true) .completion_type(CompletionType::List) .build(); let mut rl = Editor::with_config(config) .into_diagnostic() .wrap_err("初始化REPL")?; rl.set_helper(Some(MyHelper(FilenameCompleter::new()))); loop { let readline = rl.readline(">> "); match readline { Ok(line) => { rl.add_history_entry(line.as_str()).into_diagnostic()?; // todo 增加输入行处理函数 // 解析输入的命令 let result = parse_sql_command(&line); display(result); } Err(ReadlineError::Interrupted) => { // CTRL-C 跳过本次输入 } Err(ReadlineError::Eof) => { //"CTRL-D" 终止输入 break; } Err(err) => { println!("遇到错误: {err:?}"); break; } } } rl.save_history(HISTORY_FILE) .into_diagnostic() .wrap_err("Saving REPL history")?; Ok(()) } fn display(res: Result<SqlCommand, FormattedError>) { match res { Ok(exec_res) => println!("{:#?}", exec_res), Err(e) => { let mut s = String::new(); GraphicalReportHandler::new() .with_cause_chain() .with_context_lines(10) .render_report(&mut s, &e) .unwrap(); println!("{s}"); } } }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/手撸系列/write_a_db/adb/crates/libs/aexecution/src/main.rs
手撸系列/write_a_db/adb/crates/libs/aexecution/src/main.rs
fn main() { println!("Hello, world!"); }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/手撸系列/write_a_db/adb/crates/libs/aparser/src/ast.rs
手撸系列/write_a_db/adb/crates/libs/aparser/src/ast.rs
//! 将渐变语句、查询语句、插入语句整合起来 use crate::{ commands::{CreateStatement, InsertStatement, SelectStatement}, error::FormattedError, parse::{peek_then_cut, Parse}, }; use nom::{ branch::alt, character::complete::{char, multispace0}, combinator::{eof, map}, error::context, multi::many1, sequence::{preceded, tuple}, }; use serde::{Deserialize, Serialize}; /// 枚举,命令类型 #[derive(Debug, Clone, Hash, Serialize, Deserialize)] pub enum SqlCommand { Select(SelectStatement), Insert(InsertStatement), Create(CreateStatement), } // 为SqlCommand实现Parse特征 impl<'a> Parse<'a> for SqlCommand { fn parse(i: crate::parse::RawSpan<'a>) -> crate::parse::ParseResult<'a, Self> { let (rest, (command, _, _, _)) = context( "SQL命令解析", preceded( multispace0, tuple(( alt(( peek_then_cut("select", map(SelectStatement::parse, SqlCommand::Select)), peek_then_cut("insert", map(InsertStatement::parse, SqlCommand::Insert)), peek_then_cut("create", map(CreateStatement::parse, SqlCommand::Create)), )), multispace0, char(';'), multispace0, )), ), )(i)?; Ok((rest, command)) } } // 为SqlCommand实现tryFrom特征,尝试从字符串直接转换为Command impl<'a> TryFrom<&'a str> for SqlCommand { type Error = FormattedError<'a>; fn try_from(value: &'a str) -> Result<Self, Self::Error> { match SqlCommand::parse_format_error(&value) { Ok(command) => Ok(command), Err(e) => Err(e), } } } pub fn parse_sql_command(input: &str) -> Result<SqlCommand, FormattedError<'_>> { input.try_into() } // 为一组命令实现Parse特征 impl<'a> Parse<'a> for Vec<SqlCommand> { fn parse(i: crate::parse::RawSpan<'a>) -> crate::parse::ParseResult<'a, Self> { let (rest, (comands, _)) = tuple((many1(SqlCommand::parse), eof))(i)?; Ok((rest, comands)) } } pub fn parse_multiple_sqlcommand(input: &str) -> Result<Vec<SqlCommand>, FormattedError<'_>> { Vec::<SqlCommand>::parse_format_error(input) } #[cfg(test)] mod test { use super::*; #[test] fn test_insert_command() { let insert = "insert into student values '三角兽',18;"; let result = parse_sql_command(&insert); println!("result:{:#?}", result); } #[test] fn test_select_command() { let select = "select name,age from student;"; let result = parse_sql_command(&select); println!("result:{:#?}", result); } #[test] fn test_create_command() { let create = "create table student (name string,age int);"; let result = parse_sql_command(&create); println!("result:{:#?}", result); } #[test] fn test_multiple_command() { let create = r#" create table student (name string,age int); insert into student values '三角兽',18; select name,age from student;"#; let result = parse_multiple_sqlcommand(&create); println!("result:{:#?}", result); } }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/手撸系列/write_a_db/adb/crates/libs/aparser/src/lib.rs
手撸系列/write_a_db/adb/crates/libs/aparser/src/lib.rs
pub mod ast; pub mod commands; pub mod error; pub mod parse; pub mod parse_value;
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/手撸系列/write_a_db/adb/crates/libs/aparser/src/parse.rs
手撸系列/write_a_db/adb/crates/libs/aparser/src/parse.rs
//! 定义通用的解析方法 use nom::{ self, bytes::complete::{tag_no_case, take_while1}, character::complete::{char, multispace0}, combinator::{all_consuming, map, peek}, multi::separated_list1, sequence::{pair, tuple}, Finish, IResult, }; use nom_locate::LocatedSpan; use crate::error::{format_parse_error, FormattedError, MyParseError}; // 定义类型,用于包装输入str pub type RawSpan<'a> = LocatedSpan<&'a str>; // 定义解析结果类型,错误类型用自定义的MyParseError pub type ParseResult<'a, T> = IResult<RawSpan<'a>, T, MyParseError<'a>>; // 解析sql标识符的通用函数 pub fn identifier(i: RawSpan) -> ParseResult<String> { map(take_while1(|c: char| c.is_alphanumeric()), |s: RawSpan| { s.fragment().to_string() })(i) } /// 偷窥tag是否存在,如果存在则调用传入的解析器 pub fn peek_then_cut<'a, T, O, E, F>( peek_tag: T, f: F, ) -> impl FnMut(RawSpan<'a>) -> IResult<RawSpan<'a>, O, E> where T: nom::InputLength + Clone, F: nom::Parser<RawSpan<'a>, O, E>, E: nom::error::ParseError<RawSpan<'a>> + nom_supreme::tag::TagError<RawSpan<'a>, T>, LocatedSpan<&'a str>: nom::Compare<T>, { map(pair(peek(tag_no_case(peek_tag)), f), |(_, f_res)| f_res) } /// 按照逗号分隔 pub fn comma_sep<'a, O, E, F>(f: F) -> impl FnMut(RawSpan<'a>) -> IResult<RawSpan<'a>, Vec<O>, E> where F: nom::Parser<RawSpan<'a>, O, E>, E: nom::error::ParseError<RawSpan<'a>>, { separated_list1(tuple((multispace0, char(','), multispace0)), f) } /// 定义通用的解析trait,用于将sql转换为不同的指令 /// 使用Sized对trait进行限定,实现该trait的结构体都是大小可知的 pub trait Parse<'a>: Sized { fn parse(i: RawSpan<'a>) -> ParseResult<'a, Self>; // 输入原始字符串,包装成RawSpan类型,并调用自身的parse关联函数解析 fn parse_from_raw(input: &'a str) -> ParseResult<'a, Self> { let t = LocatedSpan::new(input); Self::parse(t) } // 统一错误处理,将错误信息处理为格式化的错误 fn parse_format_error(i: &'a str) -> Result<Self, FormattedError<'a>> { let input = LocatedSpan::new(i); match all_consuming(Self::parse)(input).finish() { Ok((_, query)) => Ok(query), Err(e) => Err(format_parse_error(i, e)), } } } #[cfg(test)] mod test { use super::*; #[test] fn test_identifier() { // 使用LocatedSpan将输入字符串转换为LocatedSpan(RawSpan) let result = identifier(LocatedSpan::new("select * from student")); println!("result:{:#?}", result); } #[test] fn test_peek_then_cut() {} }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/手撸系列/write_a_db/adb/crates/libs/aparser/src/error.rs
手撸系列/write_a_db/adb/crates/libs/aparser/src/error.rs
//! 统一错误错误 //! use miette::Diagnostic; use nom_supreme::error::{BaseErrorKind, ErrorTree, GenericErrorTree, StackContext}; use thiserror::Error; use crate::parse::RawSpan; // 定义错误类型 pub type MyParseError<'a> = ErrorTree<RawSpan<'a>>; // 定义miette断言的结构体 #[derive(Error, Debug, Diagnostic)] #[error("解析错误")] pub struct FormattedError<'b> { // 错误所在源码 #[source_code] src: &'b str, // 错误位置和错误类型 #[label("{kind}")] span: miette::SourceSpan, kind: BaseErrorKind<&'b str, Box<dyn std::error::Error + Send + Sync + 'static>>, // 关联的其它信息 #[related] others: Vec<FormattedErrorContext<'b>>, } #[derive(Debug, Error, Diagnostic)] #[error("解析错误上下文信息")] pub struct FormattedErrorContext<'b> { #[source_code] src: &'b str, #[label("{context}")] span: miette::SourceSpan, context: StackContext<&'b str>, } /// 将nom的解析错误转换为自定义错误 pub fn format_parse_error<'a>(input: &'a str, e: MyParseError<'a>) -> FormattedError<'a> { match e { GenericErrorTree::Base { location, kind } => { let offset = location.location_offset().into(); FormattedError { src: &input, span: miette::SourceSpan::new(offset, 0), kind, others: Vec::new(), } } GenericErrorTree::Alt(alt_errors) => alt_errors .into_iter() .map(|e| format_parse_error(input, e)) .max_by_key(|formated| formated.others.len()) .unwrap(), GenericErrorTree::Stack { base, contexts } => { let mut base = format_parse_error(input, *base); let mut contexts = contexts .into_iter() .map(|(loc, context)| { let offset = loc.location_offset().into(); FormattedErrorContext { src: input, span: miette::SourceSpan::new(offset, 0), context, } }) .collect(); base.others.append(&mut contexts); base } } }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/手撸系列/write_a_db/adb/crates/libs/aparser/src/parse_value.rs
手撸系列/write_a_db/adb/crates/libs/aparser/src/parse_value.rs
//! 解析值 use std::str::FromStr; use crate::parse::{peek_then_cut, Parse, ParseResult, RawSpan}; use bigdecimal::BigDecimal; use derive_more::Display; use nom::{ branch::alt, bytes::complete::{tag, take_until, take_while}, character::complete::multispace0, error::context, sequence::{preceded, terminated, tuple}, Parser, }; use serde::{Deserialize, Serialize}; /// 支持的值类型枚举 #[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, Display)] pub enum Value { Number(BigDecimal), // 小数 String(String), // 字符串 } /// 为Value实现Parse特征 impl<'a> Parse<'a> for Value { fn parse(input: RawSpan<'_>) -> ParseResult<'_, Value> { context( "值解析", preceded( multispace0, terminated( alt((peek_then_cut("'", parse_string_value), parse_number_value)), multispace0, ), ), )(input) } } /// 解析单引号字符串值 fn parse_string_value(input: RawSpan<'_>) -> ParseResult<'_, Value> { // 使用nom::error::context上下文包裹 let (remaining, (_, str_value, _)) = context( "字符串字面量解析", tuple(( tag("'"), // take_until不消耗最后一个字符,属于前闭后开 take_until("'").map(|r: RawSpan| Value::String(r.fragment().to_string())), tag("'"), )), )(input)?; Ok((remaining, str_value)) } /// 解析数值 fn parse_number_value(input: RawSpan<'_>) -> ParseResult<'_, Value> { let (remaining, digits) = context("数值字面量解析", take_while(|c: char| c.is_numeric()))(input)?; let digits = digits.fragment(); Ok(( remaining, Value::Number(BigDecimal::from_str(digits).unwrap()), )) } #[cfg(test)] mod test { use super::*; #[test] fn test_parse_string_value() { let s = "'兽兽',18".to_string(); let result = Value::parse_from_raw(s.as_str()); println!("result:{:?}", result); } #[test] fn test_parse_number_value() { let result = Value::parse_from_raw("1234567"); println!("result:{:?}", result); } }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/手撸系列/write_a_db/adb/crates/libs/aparser/src/commands/select.rs
手撸系列/write_a_db/adb/crates/libs/aparser/src/commands/select.rs
//! 查询命令解析 use crate::parse::{comma_sep, identifier, Parse}; use nom::{ bytes::complete::tag_no_case, character::complete::multispace1, error::context, sequence::tuple, }; use nom_supreme::ParserExt; use serde::{Deserialize, Serialize}; /// 查询命令结构体 #[derive(Debug, Clone, PartialEq, Default, Hash, Serialize, Deserialize)] pub struct SelectStatement { pub table: String, pub fields: Vec<String>, } // 实现Display特征 impl std::fmt::Display for SelectStatement { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "SELECT ")?; write!(f, "{}", self.fields.join(", "))?; write!(f, " FROM ")?; write!(f, "{}", self.table)?; Ok(()) } } // 实现Parse特征 impl<'a> Parse<'a> for SelectStatement { fn parse(i: crate::parse::RawSpan<'a>) -> crate::parse::ParseResult<'a, Self> { let (remaining_input, (_, _, fields, _, _, _, table)) = context( "查询语句解析", tuple(( tag_no_case("select"), multispace1, comma_sep(identifier).context("查询列名"), multispace1, tag_no_case("from"), multispace1, identifier.context("表名"), )), )(i)?; Ok((remaining_input, SelectStatement { table, fields })) } } #[cfg(test)] mod test { use super::SelectStatement; use crate::parse::Parse; #[test] fn test_select_statement() { let select = "select name,age from student"; let result = SelectStatement::parse_from_raw(&select); println!("result:{:#?}", result); } }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/手撸系列/write_a_db/adb/crates/libs/aparser/src/commands/insert.rs
手撸系列/write_a_db/adb/crates/libs/aparser/src/commands/insert.rs
//! 插入语句解析 use crate::{ parse::{comma_sep, identifier, Parse}, parse_value::Value, }; use nom::{ bytes::complete::tag_no_case, character::complete::multispace1, error::context, sequence::{preceded, tuple}, }; use nom_supreme::ParserExt; use serde::{Deserialize, Serialize}; /// 插入语句结构体 #[derive(Debug, Clone, PartialEq, Default, Hash, Serialize, Deserialize)] pub struct InsertStatement { pub table: String, pub values: Vec<Value>, } // 为InsertStatement实现Parse特征 impl<'a> Parse<'a> for InsertStatement { fn parse(i: crate::parse::RawSpan<'a>) -> crate::parse::ParseResult<'a, Self> { let (remaining_input, (_, _, table, _, values)) = context( "插入语句解析", tuple(( tag_no_case("insert"), preceded(multispace1, tag_no_case("into")), preceded(multispace1, identifier.context("表名")), preceded(multispace1, tag_no_case("values")), preceded(multispace1, comma_sep(Value::parse).context("值")), )), )(i)?; Ok((remaining_input, InsertStatement { table, values })) } } #[cfg(test)] mod test { use super::*; #[test] fn test_insert_statement_parse() { let insert = "insert into student values '三角兽',18"; let result = InsertStatement::parse_from_raw(&insert); println!("result:{:#?}", result); } }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/手撸系列/write_a_db/adb/crates/libs/aparser/src/commands/mod.rs
手撸系列/write_a_db/adb/crates/libs/aparser/src/commands/mod.rs
mod create; mod insert; mod select; pub use create::CreateStatement; pub use insert::InsertStatement; pub use select::SelectStatement;
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/手撸系列/write_a_db/adb/crates/libs/aparser/src/commands/create.rs
手撸系列/write_a_db/adb/crates/libs/aparser/src/commands/create.rs
//! create sql解析 use crate::parse::{comma_sep, identifier, Parse, ParseResult, RawSpan}; use derive_more::Display; use nom::{ branch::alt, bytes::complete::tag_no_case, character::{ complete::{char, multispace1}, streaming::multispace0, }, combinator::map, error::context, sequence::{preceded, separated_pair, tuple}, }; use nom_supreme::ParserExt; use serde::{Deserialize, Serialize}; /// 定义建表sql语句中的类型 /// 暂时只支持string 和 int #[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, Display, Copy)] pub enum FieldType { String, Int, } // 为FieldType实现Parse特征 impl<'a> Parse<'a> for FieldType { fn parse(i: crate::parse::RawSpan<'a>) -> crate::parse::ParseResult<'a, Self> { context( "字段类型", alt(( map(tag_no_case("string"), |_| Self::String), map(tag_no_case("int"), |_| Self::Int), )), )(i) } } /// 定义列结构体 #[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] pub struct Column { pub name: String, pub field_type: FieldType, } // 为Column实现Parse特征 impl<'a> Parse<'a> for Column { fn parse(i: crate::parse::RawSpan<'a>) -> crate::parse::ParseResult<'a, Self> { context( "列解析", map( separated_pair(identifier.context("列名"), multispace1, FieldType::parse), |(name, field_type)| Self { name, field_type }, ), )(i) } } // 解析所有的列 fn column_definition(input: RawSpan<'_>) -> ParseResult<'_, Vec<Column>> { context( "解析所有列", map( tuple(( char('('), multispace0, comma_sep(Column::parse), multispace0, char(')'), )), |(_, _, cols, _, _)| cols, ), )(input) } /// 解析建表语句 #[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] pub struct CreateStatement { pub table: String, pub columns: Vec<Column>, } /// 为CreateStatement实现Parse特征 impl<'a> Parse<'a> for CreateStatement { fn parse(i: RawSpan<'a>) -> ParseResult<'a, Self> { map( separated_pair( preceded( tuple(( tag_no_case("create"), multispace1, tag_no_case("table"), multispace1, )), identifier.context("表名"), ), multispace1, column_definition, ) .context("创建表"), |(table, columns)| Self { table, columns }, )(i) } } #[cfg(test)] mod test { use crate::parse::Parse; use super::CreateStatement; #[test] fn test_create_table() { let create_table = "create table student (name string,age int)"; let result = CreateStatement::parse_from_raw(&create_table); println!("result:{:#?}", result); } }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/手撸系列/mini_async_runtime/src/bin/mini-async-runtime.rs
手撸系列/mini_async_runtime/src/bin/mini-async-runtime.rs
use { futures::{ future::{BoxFuture, FutureExt}, task::{waker_ref, ArcWake}, }, std::{ future::Future, pin::Pin, sync::{ mpsc::{self, Receiver, Sender}, Arc, Mutex, }, task::{Context, Poll, Waker}, thread, time::{Duration, SystemTime}, }, }; fn main() { let (executor, spawner) = new_executor_and_spawner(); async fn hello() { thread::sleep(Duration::from_secs(1)); let current_time = SystemTime::now(); let msg = format!("{:?} from async hello , do something .....", current_time); } spawner.spawn( async { hello().await; }, "任务1", ); spawner.spawn( async { hello().await; hello().await; }, "任务2", ); spawner.spawn( async { hello().await; TimerFuture::new(Duration::new(1, 0)).await; hello().await; }, "任务3", ); spawner.spawn( async { hello().await; }, "任务4", ); // 关闭task_sender端,结束executor中的while let循环 drop(spawner); executor.run(); } /// Task,封装了future且拥有发送端,等待执行器去`poll` struct Task { // 进行中的Future,在未来的某个时间点会被完成 // BoxFuture<'a, T> = Pin<alloc::boxed::Box<dyn Future<Output = T> + Send + 'a>>; future: Mutex<BoxFuture<'static, ()>>, // 可以将该任务自身放回到任务通道中,等待执行器的poll task_sender: Sender<Arc<Task>>, task_name: String, } /// 为Task实现ArcWake trait /// ArcWake特征需要Task能在thread之间安全的共享 /// 要么加锁,要么使用Mutex impl ArcWake for Task { fn wake_by_ref(arc_self: &Arc<Self>) { let cloned = arc_self.clone(); arc_self.task_sender.send(cloned).expect("发送任务失败"); } } /// 任务执行器,负责从通道中接收任务然后执行 struct Executor { task_receiver: Receiver<Arc<Task>>, } /// `Spawner`负责创建新的`Future`然后将它发送到任务通道中 struct Spawner { task_sender: Sender<Arc<Task>>, } // 为Spawner实现spawn方法 impl Spawner { fn spawn(&self, future: impl Future<Output = ()> + 'static + Send, task_name: &str) { // boxed方法需要引入futures::future::FutureExt // Pin住future let future: std::pin::Pin<Box<dyn Future<Output = ()> + Send>> = future.boxed(); // 使用task封装future let task = Arc::new(Task { future: Mutex::new(future), task_sender: self.task_sender.clone(), task_name: String::from(task_name), }); // 发送task到channel self.task_sender.send(task).expect("发送消息失败"); } } /// 为Executor实现run方法 impl Executor { fn run(&self) { // 使用while let循环从channel中拿task while let Ok(task) = self.task_receiver.recv() { // 使用waker_ref方法生成WakerRef,需要task是Arc<_>类型 // 需要task实现ArcWake trait let waker = waker_ref(&task); // 构建context let context = &mut Context::from_waker(&*waker); let mut future_slot = task.future.lock().unwrap(); // 在poll方法中传入waker let status = future_slot.as_mut().poll(context); let current_time = SystemTime::now(); println!( "{:?} 任务状态:{:?} 任务名称:{:?}", current_time, status, &task.task_name ) } } } /// 辅助方法,创建spawner和executor fn new_executor_and_spawner() -> (Executor, Spawner) { let (task_sender, task_receiver) = mpsc::channel::<Arc<Task>>(); (Executor { task_receiver }, Spawner { task_sender }) } // 实现一个Future,调用wake方法通知executor执行 pub struct TimerFuture { shared_state: Arc<Mutex<SharedState>>, } /// 在Future和等待的线程间共享状态 struct SharedState { completed: bool, waker: Option<Waker>, } impl Future for TimerFuture { type Output = (); fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let mut shared_state = self.shared_state.lock().unwrap(); if shared_state.completed { let current_time = SystemTime::now(); //println!("{:?} task ready", current_time); Poll::Ready(()) } else { // poll方法将waker传入Future中 shared_state.waker = Some(cx.waker().clone()); let current_time = SystemTime::now(); //println!("{:?} task pending", current_time); Poll::Pending } } } impl TimerFuture { /// 创建一个新的`TimerFuture`,在指定的时间结束后,该`Future`可以完成 pub fn new(duration: Duration) -> Self { let shared_state = Arc::new(Mutex::new(SharedState { completed: false, waker: None, })); // 创建新线程 let thread_shared_state = shared_state.clone(); thread::spawn(move || { let current_time = SystemTime::now(); println!("{:?} 任务睡眠中 ...", current_time); thread::sleep(duration); let mut shared_state = thread_shared_state.lock().unwrap(); shared_state.completed = true; if let Some(waker) = shared_state.waker.take() { let current_time = SystemTime::now(); println!("{:?} 任务结束通知executor ...", current_time); waker.wake_by_ref() } }); TimerFuture { shared_state } } }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/手撸系列/mini_blockchain/src/bin/mini_blockchain.rs
手撸系列/mini_blockchain/src/bin/mini_blockchain.rs
//! 迷你区块链 use chrono::Utc; use serde::Serialize; use sha2::{Digest, Sha256}; use std::{thread, time::Duration}; /// 区块头 #[derive(Serialize, Debug, PartialEq, Eq)] struct BlockHeader { pre_hash: String, txs_hash: String, time: i64, } /// 区块体 #[derive(Debug)] struct Block { // 区块头 header: BlockHeader, // 区块包含的所有交易数据 tranxs: String, // 区块的hash hash: String, } impl Block { fn new(txs: String, pre_hash: String) -> Self { // 挖矿 println!("开始挖矿...."); thread::sleep(Duration::from_secs(5)); // 准备区块数据 let time = Utc::now().timestamp(); let txs_serialize = serialize(&txs); let txs_hash = cal_hash(&txs_serialize); let mut block = Block { header: BlockHeader { time: time, txs_hash: txs_hash, pre_hash: pre_hash, }, tranxs: txs, hash: "".to_string(), }; block.set_block_hash(); println!("产生出一个区块"); block } // 计算区块的hash fn set_block_hash(&mut self) { let header = serialize(&self.header); self.hash = cal_hash(&header); } } struct BlockChain { blocks: Vec<Block>, } impl BlockChain { fn new() -> Self { BlockChain { blocks: vec![Self::genesis_block()], } } // 添加区块 fn add_block(&mut self, txs: String) { // 前一个区块的hash let last_index = self.blocks.len() - 1; let pre_block = &self.blocks[last_index]; let pre_hash = pre_block.hash.clone(); // 创建新块并加入区块链 let new_block = Block::new(txs, pre_hash); self.blocks.push(new_block); } // 区块两信息 fn display(&self) { for i in self.blocks.iter() { println!("{:#?}", i); } } /// 创世块 fn genesis_block() -> Block { Block::new("创世块".to_string(), "2024".to_string()) } } /// T是实现了Serialize并且可变大小的泛型,返回二进制u8格式 fn serialize<T: ?Sized + Serialize>(value: &T) -> Vec<u8> { bincode::serialize(value).unwrap() } /// 计算hash值 fn cal_hash(value: &[u8]) -> String { let mut hasher = Sha256::new(); hasher.update(value); let hash = hasher.finalize(); format!("{:x}", hash) } fn main() { let mut block_chain = BlockChain::new(); let txs = r#" 账户A向账户B转账5元; 账户B向账户C转账4.6元; 账户E向账户A转账100元; "# .to_string(); block_chain.add_block(txs); let txs = r#" 账户E向账户B转账5元; 账户B向账户C转账4.6元; 账户C向账户A转账100元; "# .to_string(); block_chain.add_block(txs); block_chain.display(); }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/手撸系列/mini_kvm_sample/kvmsample-rust/src/main.rs
手撸系列/mini_kvm_sample/kvmsample-rust/src/main.rs
extern crate kvm_ioctls; extern crate kvm_bindings; extern crate libc; use std::{ffi::CString, fs::File, io::{Read, Write}, ptr::null_mut, slice, thread::JoinHandle, time::Duration}; use kvm_bindings::{kvm_userspace_memory_region, KVM_MEM_LOG_DIRTY_PAGES}; use kvm_ioctls::{Kvm, VcpuExit, VcpuFd, VmFd}; use std::thread; // 为虚拟机分配的内存大小 const RAM_SIZE:i32 = 512000000; // 段选择子 const CODE_START:u16 = 0x1000; // 代码段起始地址 const BASE:u64 = 0x1000 * 16; // 等价于0x10000 // 奇偶标识 表示偶数 const RFLAGS:u64 = 0x0000000000000002; // 栈指针,指向栈顶 const RSP:u64 = 0xffffffff; struct MyKvm {} impl MyKvm { fn kvm_reset_vcpu(vcpu_fd: &VcpuFd) { let mut sregs= vcpu_fd.get_sregs().unwrap(); // 下列代码是设置寄存器的值 // 段选择子,存储的是段描述符GDT的索引 sregs.cs.selector = CODE_START; sregs.cs.base = BASE; sregs.ss.selector = CODE_START; sregs.ss.base = BASE; sregs.ds.selector = CODE_START; sregs.ds.base = BASE; sregs.es.selector = CODE_START; sregs.es.base = BASE; sregs.fs.selector = CODE_START; sregs.fs.base = BASE; sregs.gs.selector = CODE_START; vcpu_fd.set_sregs(&sregs).unwrap(); let mut regs = vcpu_fd.get_regs().unwrap(); // 设置标志寄存器的值 regs.rflags = RFLAGS; // 指令指针 regs.rip = 0; // 栈指针 regs.rsp = RSP; // 基址指针寄存器 regs.rbp = 0; vcpu_fd.set_regs(&regs).unwrap(); } fn load_binary(ram_start: *mut u8, test: i32) { let binary_file:&str; if test == 0 { binary_file = "test.bin" } else { binary_file = "test2.bin" } // 打开可执行文件 match File::open(binary_file) { Ok(mut file) => { let mut buffer: Vec<u8> = Vec::new(); let len = file.read_to_end(&mut buffer).unwrap(); unsafe { // 加载到虚拟机的开始内存处 let mut slice = slice::from_raw_parts_mut(ram_start, len as usize); slice.write(&buffer[..]).unwrap(); } }, Err(_) => eprintln!("can not open binary file") } } /// 打开/dev/kvm设备文件,创建kvm fn kvm_init() -> Kvm { const KVM_DEVICE:&str = "/dev/kvm"; let kvm_path = CString::new(KVM_DEVICE).unwrap(); Kvm::new_with_path(&kvm_path).unwrap() } /// 为kvm创建虚拟内存 fn kvm_create_vm(kvm: &Kvm, ram_size: i32) -> (VmFd, *mut u8) { let vm_fd = Kvm::create_vm(kvm).unwrap(); let ram_size = ram_size as u64; let ram_start = unsafe { // 调用外部库,创建内存表,返回创建的内存表首地址 libc::mmap( null_mut(), ram_size as usize, libc::PROT_READ | libc::PROT_WRITE, libc::MAP_ANONYMOUS | libc::MAP_SHARED | libc::MAP_NORESERVE, -1, 0 ) as *mut u8 }; // kvm用户空间区域 let mem = kvm_userspace_memory_region { slot: 0, flags: KVM_MEM_LOG_DIRTY_PAGES, guest_phys_addr: 0, memory_size: ram_size, userspace_addr: ram_start as u64 }; unsafe { vm_fd.set_user_memory_region(mem).unwrap(); } (vm_fd, ram_start) } fn kvm_cpu_thread(vcpu_fd: &mut VcpuFd) { // 重置cpu寄存器 MyKvm::kvm_reset_vcpu(vcpu_fd); loop { // 运行虚拟机 match vcpu_fd.run().expect("run failed") { // 匹配虚拟机Exit码,获取模式值 VcpuExit::IoIn(addr, _data ) => { println!("KVM_EXIT_IO_IN addr {}", addr); } VcpuExit::IoOut(addr, data) => { println!("KVM_EXIT_IO_OUT addr:{} data:{}", addr, data[0]); } VcpuExit::Unknown => { println!("KVM_EXIT_UNKNOWN"); } VcpuExit::Debug(_debug) => { println!("KVM_EXIT_DEBUG"); } VcpuExit::MmioRead(_addr, _data ) => { println!("KVM_EXIT_MMIO_READ"); } VcpuExit::MmioWrite(_addr, _data ) => { println!("KVM_EXIT_MMIO_WRITE"); } VcpuExit::Intr => { println!("KVM_EXIT_INTR"); } VcpuExit::Shutdown => { println!("KVM_EXIT_SHUTDOWN"); break; } r => panic!("KVM PANIC {:?}", r) } thread::sleep(Duration::from_secs(1)); } } fn kvm_init_vcpu(vm_fd: VmFd, vcpu_id: u64) -> VcpuFd { vm_fd.create_vcpu(vcpu_id).unwrap() } fn kvm_run_vm(mut vcpu_fd: VcpuFd) -> JoinHandle<()> { let handle = std::thread::spawn(move|| { MyKvm::kvm_cpu_thread(&mut vcpu_fd); }); handle } } fn main() { let kvm = MyKvm::kvm_init(); let (vm_fd, ram_start) = MyKvm::kvm_create_vm(&kvm, RAM_SIZE); MyKvm::load_binary(ram_start, 0); let vcpu_fd = MyKvm::kvm_init_vcpu(vm_fd, 0); let handle0 = MyKvm::kvm_run_vm(vcpu_fd); let kvm = MyKvm::kvm_init(); let (vm_fd, ram_start) = MyKvm::kvm_create_vm(&kvm, RAM_SIZE); MyKvm::load_binary(ram_start, 1); let vcpu_fd = MyKvm::kvm_init_vcpu(vm_fd, 1); let handle1 = MyKvm::kvm_run_vm(vcpu_fd); // 等待线程退出 handle0.join().unwrap(); handle1.join().unwrap(); }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/手撸系列/password_generator/src/bin/password_generator.rs
手撸系列/password_generator/src/bin/password_generator.rs
//!实现一个通用的密码生成器 use anyhow::{bail, Error, Ok}; use base64::prelude::*; use clap::Parser; use rand::prelude::*; // 计算seed种子的hash值 fn seed_hash(seed: &str) -> usize { let mut hash: usize = 0; for (i, c) in seed.chars().enumerate() { hash += (i + 1) * (c as usize); } (hash % 31).pow(3) } // 密码子,随机的一串字符串,用于生成密码时,从中挑选字符 const CRYPTO:&str = r#"!@#$%^&*()POIUYTREWQSDAFSGJKZBXNCMVBL<:{}[]|abcedljloweiunbaljkfl1289829179438fsdljflfjasfdsbfJKFLSAFLSAJFELJ*(&(&(*&*^&^%$%$^&^*"#; // 产生密码的方法 fn generate_password(seed: &str, length: usize) -> Result<String, Error> { // 密码长度不能太短,至少6位数 if length < 6 { bail!("密码长度必须大于6位"); } else { let mut hash = seed_hash(seed); // 由hash求passwd let mut passwd = String::new(); let crypto_len = CRYPTO.len(); while hash > 0 { let index = hash % crypto_len; let nthc = CRYPTO.chars().nth(index).expect("从密码子中获取字符错误"); passwd.push(nthc); hash /= crypto_len; } // 将seed和passwd拼接起来 for c in seed.chars() { passwd.push(c); } // 将passwd编码为base64 passwd = BASE64_STANDARD.encode(passwd); // 替换掉字符串中的+和/为* passwd = passwd.replace("+", "*").replace("/", "*"); if passwd.len() < length { let mut rng = rand::thread_rng(); // 满足长度要求 while passwd.len() < length { let index = rng.gen_range(0..CRYPTO.len()); passwd.push(CRYPTO.chars().nth(index as usize).expect("获取字符错误")); } } // 返回length个字符作为密码 Ok(format!("seed:{} pwd:{}", seed, &passwd[..length])) } } // 命令行解析 #[derive(Debug,Parser)] #[clap(version,about)] struct Args{ //生成密码的种子 #[clap(short,long)] seed:String, // 密码长度 #[clap(short,long,default_value_t=15)] length:usize } fn main()->Result<(),Error> { let args = Args::parse(); // 种子长度必须大于等于4 if args.length < 4{ bail!("种子:{} 长度太短,请换一个",&args.seed); } let (seed,lenght) = (args.seed,args.length); let result = generate_password(&seed, lenght); println!("{:?}", result); Ok(()) }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/手撸系列/thread_pool/src/lib.rs
手撸系列/thread_pool/src/lib.rs
use std::{ sync::{ mpsc::{self, Receiver, Sender}, Arc, Mutex, }, thread::{self, JoinHandle}, time::SystemTime, }; type Job = Box<dyn FnOnce() + Send>; pub struct Threadpool { workers: Vec<Worker>, sender: Option<Sender<Job>>, } struct Worker { id: usize, handle: Option<JoinHandle<()>>, } // 为Threadpool实现方法 impl Threadpool { pub fn new(size: usize) -> Self { // 线程池的数量需要大于0 assert!(size > 0); let (sender, receiver) = mpsc::channel::<Job>(); // receiver需要在多个线程间共享所有权,使用Arc let receiver = Arc::new(Mutex::new(receiver)); let mut workers = Vec::with_capacity(size); for id in 1..=size { let receiver = receiver.clone(); workers.push(Worker::new(id, receiver)); } Threadpool { workers, sender: Some(sender), } } pub fn execute<F>(&self, f: F) where F: FnOnce() + Send + 'static, { let job = Box::new(f); self.sender.as_ref().unwrap().send(job).unwrap(); } } impl Drop for Threadpool { fn drop(&mut self) { // 需要等待所有线程都执行完成 // 先释放channel drop(self.sender.take()); // 等待线程结束 for worker in &mut self.workers { let time = SystemTime::now(); if let Some(thread) = worker.handle.take() { thread.join().unwrap(); } println!("{:?} shutdown worker:{}", time, worker.id); } // println let time = SystemTime::now(); println!("{:?} shutdown thread pool", time); } } // 为Worker实现方法 impl Worker { fn new(id: usize, receiver: Arc<Mutex<Receiver<Job>>>) -> Self { let handle = thread::spawn(move || { // 从channel拉取job执行 // 线程需要一直运行,用loop循环 loop { let job = receiver.lock().unwrap().recv(); match job { Ok(job) => { let time = SystemTime::now(); println!("{:?} Worker {id} is working...", time); job(); } Err(_) => { let time = SystemTime::now(); println!("{:?} Worker {id} disconnected ; exit", time); break; } } } }); Worker { id, handle: Some(handle), } } } #[cfg(test)] mod test { use std::time::{Instant, SystemTime}; use crate::Threadpool; #[test] fn test_thread_pool() { let pool = Threadpool::new(2); let f1 = || { let time = SystemTime::now(); let result = 1 + 1; println!("{:?} result:{result}", time); }; let f2 = || { let time = SystemTime::now(); let result = 99*88*77*76; println!("{:?} result:{result}", time); }; let f3 = || { let time = SystemTime::now(); let result = 1000*9899; println!("{:?} result:{result}", time); }; pool.execute(f1); pool.execute(f2); pool.execute(f3); } }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/手撸系列/thread_pool/src/main.rs
手撸系列/thread_pool/src/main.rs
fn main() { println!("Hello, world!"); }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/手撸系列/mini_vm/src/bin/mini_vm.rs
手撸系列/mini_vm/src/bin/mini_vm.rs
//! mini virtual machine 迷你虚拟机 #[derive(Debug)] struct Instruct { // 指令 code: IP, // 执行指令的条件 cond: Condition, // 指令的参数指针 p1: i32, p2: i32, } // 指令枚举 #[derive(Debug)] enum IP { IADD, // 加法 ISUB, // 减法 ICMP, // 判断 IJMP, // 跳转 IMOV, // 赋值 ISTIP, // 保存ip ILDIP, // 加载ip(跳转) ILD, // 加载一个立即数 IOUT, // 输出 ISTOP, // 挂起虚拟机 } // 条件枚举 #[derive(Debug, PartialEq)] enum Condition { FNA, // 任何状态下都执行 FEQ, // 状态为相等时执行 FNE, // 状态不相等时执行 } // 保存状态的结构体 #[derive(Debug)] struct VMState<'a> { ip: i32, // 指令指针,指向具体的指令Instruct flag: Condition, //判断标志 code_ptr: &'a [Instruct], // 代码段地址 data_ptr: &'a mut [i32], //数据段地址 } impl<'a> VMState<'a> { // 使用代码段和数据段初始化构建一个虚拟机 fn build(code_ptr: &'a [Instruct], data_ptr: &'a mut [i32]) -> Self { VMState { ip: 0, flag: Condition::FNA, code_ptr, data_ptr, } } } struct VMMachine; impl VMMachine { fn execute(vm_state: &mut VMState) { loop { // 一直循环知道挂起为止 let current_index = vm_state.ip as usize; // 指令自动后移 vm_state.ip += 1; let current_instruct = &vm_state.code_ptr[current_index]; if current_instruct.cond != Condition::FNA && current_instruct.cond != vm_state.flag { continue; } match current_instruct.code { IP::IADD => { vm_state.data_ptr[current_instruct.p1 as usize] += vm_state.data_ptr[current_instruct.p2 as usize]; } IP::ISUB => { vm_state.data_ptr[current_instruct.p1 as usize] -= vm_state.data_ptr[current_instruct.p2 as usize]; } IP::ICMP => { // 比较p1和p2指向的数据 if vm_state.data_ptr[current_instruct.p1 as usize] == vm_state.data_ptr[current_instruct.p2 as usize] { vm_state.flag = Condition::FEQ; } else { vm_state.flag = Condition::FNE; } } IP::IJMP => { // 根据p1进行偏移 vm_state.ip += current_instruct.p1; } IP::IMOV => { // 将p1指向的数据设置为p2指向的数据 vm_state.data_ptr[current_instruct.p1 as usize] = vm_state.data_ptr[current_instruct.p2 as usize]; } IP::ISTIP => { // 将IP保存到p1指向的数据 vm_state.data_ptr[current_instruct.p1 as usize] = vm_state.ip; } IP::ILDIP => { // 将ip设置为p1指向的数据 vm_state.ip = vm_state.data_ptr[current_instruct.p1 as usize]; } IP::ILD => { // 将立即数p2 加载到p1指向的数据 vm_state.data_ptr[current_instruct.p1 as usize] = current_instruct.p2; } IP::IOUT => { // 输出p1指向的数据 println!("result:{}", vm_state.data_ptr[current_instruct.p1 as usize]); } IP::ISTOP => { return; } } } } } fn main() { //下面的指令是 // ``` // let mut sum = 0; // for i in 0..101{ // sum += i // } // ``` // 编译成的指令 // let codes = [ Instruct {code: IP::ILD, cond: Condition::FNA,p1: 2, p2: 101}, Instruct {code: IP::ILD, cond: Condition::FNA,p1: 3, p2: 1}, Instruct {code: IP::ILD, cond: Condition::FNA,p1: 1, p2: 1}, Instruct {code: IP::ILD, cond: Condition::FNA,p1: 0, p2: 0}, Instruct {code: IP::ICMP, cond: Condition::FNA,p1: 1, p2: 2}, Instruct {code: IP::IJMP, cond: Condition::FEQ,p1: 3, p2: 0}, Instruct {code: IP::IADD, cond: Condition::FNA,p1: 0, p2: 1}, Instruct {code: IP::IADD, cond: Condition::FNA,p1: 1, p2: 3}, Instruct {code: IP::IJMP, cond: Condition::FNA,p1: -5,p2: 0}, Instruct {code: IP::IOUT, cond: Condition::FNA,p1: 0, p2: 0}, Instruct {code: IP::ISTOP,cond: Condition::FNA,p1: 0, p2: 0} ]; let mut datas = [0; 16]; let mut vm_state: VMState = VMState::build(&codes, &mut datas); VMMachine::execute(&mut vm_state); }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/手撸系列/nom-practice/src/main.rs
手撸系列/nom-practice/src/main.rs
//! 时序数据库协议解析 use nom::{ branch::alt, bytes::complete::{tag, tag_no_case, take_while1}, character::complete::{digit1, one_of}, combinator::{map, map_res, opt, recognize, value}, error::ErrorKind, multi::{many1, separated_list1}, sequence::{delimited, pair, preceded, separated_pair, terminated, tuple}, IResult, }; use std::time::Instant; use std::{thread, time::Duration}; pub mod data; #[derive(Debug, Clone, Copy, PartialEq)] enum FieldValue<'a> { Bool(bool), // 布尔数据类型 Int(i64), // 有符号整数 Uint(u64), // 无符号整数 Float(f64), // 浮点数 String(&'a str), // 字符串 } #[derive(Debug, PartialEq)] pub struct Line<'a> { measurement: &'a str, tag_set: Vec<(&'a str, &'a str)>, field_set: Vec<(&'a str, FieldValue<'a>)>, timestamp: i64, } fn measurement(input: &str) -> IResult<&str, &str> { recognize(many1(alt(( tag("\\ "), // 匹配出现的\ 字符 tag("\\,"), // 匹配出现的,逗号字符,逗号字符使用\转义了 tag("\\"), take_while1(|c| c != ',' && c != ',' && c != '\\'), // 一直取出字符做匹配,直到不满足条件为止 ))))(input) } fn tag_k_v(input: &str) -> IResult<&str, &str> { recognize(many1(alt(( tag("\\ "), // "\ " tag("\\,"), // "\," tag("\\="), // "\=" tag("\\"), // "\" take_while1(|c| c != ' ' && c != ',' && c != '\\' && c != '='), ))))(input) } fn tag_set(input: &str) -> IResult<&str, Vec<(&str, &str)>> { many1(preceded( tag(","), separated_pair(tag_k_v, tag("="), tag_k_v), ))(input) } fn bool_value(input: &str) -> IResult<&str, FieldValue> { alt(( value(FieldValue::Bool(true), tag_no_case("true")), value(FieldValue::Bool(false), tag_no_case("false")), value(FieldValue::Bool(true), tag_no_case("t")), value(FieldValue::Bool(false), tag_no_case("f")), ))(input) } fn parse_int(input: &str) -> IResult<&str, i64> { map_res( recognize(pair(opt(alt((tag("+"), tag("-")))), digit1)), |s: &str| s.parse::<i64>(), )(input) } fn int_value(input: &str) -> IResult<&str, FieldValue> { terminated(map(parse_int, |i| FieldValue::Int(i)), tag_no_case("i"))(input) } fn uint_value(input: &str) -> IResult<&str, FieldValue> { map( terminated( map_res(digit1, |s: &str| s.parse::<u64>()), tag_no_case("u"), ), |u| FieldValue::Uint(u), )(input) } fn parse_double(input: &str) -> IResult<&str, f64> { map_res( alt(( recognize(tuple(( opt(one_of("+-")), digit1, tag("."), digit1, tag("e"), opt(one_of("+-")), digit1, ))), // 识别小数开头的科学计数法 recognize(tuple((opt(one_of("+-")), digit1, tag("."), digit1))), //识别小数 recognize(tuple(( opt(one_of("+-")), digit1, tag("e"), opt(one_of("+-")), digit1, ))), // 识别整数开头的科学计数法 recognize(pair(opt(alt((tag("+"), tag("-")))), digit1)), // 单独的整数识别为浮点数 )), |s: &str| s.parse::<f64>(), )(input) } fn float_value(input: &str) -> IResult<&str, FieldValue> { map(parse_double, |f| FieldValue::Float(f))(input) } fn parse_str(input: &str) -> IResult<&str, &str> { delimited( tag("\""), recognize(many1(alt((take_while1(|c| c != '"'),)))), tag("\""), )(input) } fn str_value(input: &str) -> IResult<&str, FieldValue> { alt(( value( FieldValue::String(""), recognize(pair(tag("\""), tag("\""))), ), map(parse_str, |s: &str| FieldValue::String(s)), ))(input) } fn field_value(input: &str) -> IResult<&str, FieldValue> { alt((bool_value, int_value, uint_value, float_value, str_value))(input) } fn field_set(input: &str) -> IResult<&str, Vec<(&str, FieldValue)>> { separated_list1(tag(","), separated_pair(tag_k_v, tag("="), field_value))(input) } fn time_stamp(input: &str) -> IResult<&str, i64> { map_res(digit1, |s: &str| s.parse::<i64>())(input) } fn line(input: &str) -> IResult<&str, Line> { map( tuple(( measurement, // 解析表名 terminated(tag_set, tag(" ")), // 解析静态标签,忽略最后的空格 terminated(field_set, tag(" ")), // 解析动态标签,忽略最后的空格 time_stamp, // 解析时间戳 )), |(m, t, f, ts)| Line { measurement: m, tag_set: t, field_set: f, timestamp: ts, }, // 使用map函数,使用tuple中的每个解析器的值分别构造Line的一个字段 )(input) } fn lines(input: &str) -> IResult<&str, Vec<Line>> { let input = input.trim(); let mut res = Vec::new(); for l in input.lines() { let l = l.trim(); match line(l) { Ok((input, line)) => { if !input.is_empty() { return Err(nom::Err::Error(nom::error::Error::new( input, ErrorKind::Complete, ))); } else { res.push(line) } } Err(e) => { return Err(e); } }; } Ok(("", res)) } fn main() { // 构造10万行时序数据并解析 // 记录开始时间 let start = Instant::now(); let results = lines(data::DATA).unwrap().1; println!( "耗时:{:?} , 解析结果数:{:?}", start.elapsed(), results.len() ); println!("解析样例数据:{:#?}", results.last()); thread::sleep(Duration::from_secs(20)); } #[test] fn test_mesurement() { assert_eq!(measurement("天气"), Ok(("", "天气"))); assert_eq!(measurement("天气\\\\ \\,啊"), Ok(("", "天气\\\\ \\,啊"))); assert_eq!(measurement("天气,预报"), Ok((",预报", "天气"))); assert_eq!(measurement("天气\\\\,预报"), Ok(("", "天气\\\\,预报"))); assert_eq!(measurement("天气\\\\ 预报"), Ok(("", "天气\\\\ 预报"))); } #[test] fn test_tag_k_v() { assert_eq!(tag_k_v("时间"), Ok(("", "时间"))); assert_eq!(tag_k_v("时间 "), Ok((" ", "时间"))); assert_eq!(tag_k_v(r#"时间\ \,\=\"#), Ok(("", r#"时间\ \,\=\"#))); // r#支持原生写法 println!("{:?}", r#"时间\ \,\=\"#); assert_eq!(tag_k_v(r#"时间\ \,\=,"#), Ok((",", r#"时间\ \,\="#))); } #[test] fn test_tag_set() { assert_eq!( tag_set(",name=小红,age=12,height=160,"), Ok(( ",", vec![("name", "小红"), ("age", "12"), ("height", "160")] )) ); assert_eq!( tag_set(",name=小红 ,age=12,height=160,"), Ok((" ,age=12,height=160,", vec![("name", "小红")])) ); assert_eq!( tag_set(",name=小红\\ ,age=12,height=160,"), Ok(( ",", vec![("name", "小红\\ "), ("age", "12"), ("height", "160")] )) ); } #[test] fn test_bool_value() { assert_eq!(bool_value("T"), Ok(("", FieldValue::Bool(true)))); assert_eq!(bool_value("TRue"), Ok(("", FieldValue::Bool(true)))); assert_eq!(bool_value("FalSE"), Ok(("", FieldValue::Bool(false)))); } #[test] fn test_parse_int() { assert_eq!(parse_int("+12345"), Ok(("", 12345))); assert_eq!(parse_int("-12345"), Ok(("", -12345))); assert_eq!(parse_int("12345"), Ok(("", 12345))); } #[test] fn test_int_value() { assert_eq!(int_value("+12345i"), Ok(("", FieldValue::Int(12345)))); assert_eq!(int_value("-12345i"), Ok(("", FieldValue::Int(-12345)))); assert_eq!(int_value("12345i"), Ok(("", FieldValue::Int(12345)))); } #[test] fn test_uint_value() { assert_eq!(uint_value("957867U"), Ok(("", FieldValue::Uint(957867)))); } #[test] fn test_parse_double() { assert_eq!(parse_double("5"), Ok(("", 5 as f64))); assert_eq!(parse_double("7.4"), Ok(("", 7.4))); assert_eq!(parse_double("2.31e5"), Ok(("", 2.31e5))); assert_eq!(parse_double("-3.14e5"), Ok(("", -3.14e5))); assert_eq!(parse_double("-3.14e-5"), Ok(("", -3.14e-5))); assert_eq!(parse_double("-1e-6"), Ok(("", -1e-6))); } #[test] fn test_float_value() { assert_eq!(float_value("-1e-6"), Ok(("", FieldValue::Float(-1e-6)))); assert_eq!(float_value("-3.14e5"), Ok(("", FieldValue::Float(-3.14e5)))); } #[test] fn test_str_value() { assert_eq!( str_value("\"hello rust\""), Ok(("", FieldValue::String("hello rust"))) ); assert_eq!(str_value("\"\""), Ok(("", FieldValue::String("")))); } #[test] fn test_field_set() { assert_eq!( field_set("name=\"小红\",age=12u,height=165.4,weight=50.1,score=89i"), Ok(( "", vec![ ("name", FieldValue::String("小红")), ("age", FieldValue::Uint(12)), ("height", FieldValue::Float(165.4 as f64)), ("weight", FieldValue::Float(50.1 as f64)), ("score", FieldValue::Int(89)) ] )) ) } #[test] fn test_time_stamp() { assert_eq!( time_stamp("1640995200000000000"), Ok(("", 1640995200000000000)) ); } #[test] fn test_line() { println!( "{:?}", line("onview,xxx=1,yyyy=2.3 aaa=3,bbb=4 1640995200000000000") ); }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/手撸系列/nom-practice/src/data.rs
手撸系列/nom-practice/src/data.rs
pub static DATA: &'static str = r#"onview,name=event_0,fleet=South,driver=Trish,model=H_2,device_version=v2_3 latitude=52.31854,longitude=4.72037,elevation=124,velocity=0,heading=221,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_1,fleet=South,driver=Albert,model=F_150,device_version=v1_5 latitude=72.45258,longitude=68.83761,elevation=255,velocity=0,heading=181,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_2,fleet=North,driver=Derek,model=F_150,device_version=v1_5 latitude=24.5208,longitude=28.09377,elevation=428,velocity=0,heading=304,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_3,fleet=East,driver=Albert,model=F_150,device_version=v2_0 latitude=18.11037,longitude=98.65573,elevation=387,velocity=0,heading=192,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_4,fleet=West,driver=Andy,model=G_2000,device_version=v1_5 latitude=81.93919,longitude=56.12266,elevation=236,velocity=0,heading=335,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_6,fleet=East,driver=Trish,model=G_2000,device_version=v1_0 latitude=41.59689,longitude=57.90174,elevation=395,velocity=0,heading=150,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_7,fleet=East,driver=Andy,model=H_2,device_version=v2_0 latitude=7.74826,longitude=14.96075,elevation=105,velocity=0,heading=323,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_8,fleet=South,driver=Seth,model=G_2000,device_version=v1_0 latitude=21.89157,longitude=44.58919,elevation=411,velocity=0,heading=232,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_10,fleet=North,driver=Albert,model=F_150,device_version=v2_3 latitude=35.05682,longitude=36.20513,elevation=359,velocity=0,heading=68,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_11,fleet=South,driver=Derek,model=F_150,device_version=v1_0 latitude=87.9924,longitude=134.71544,elevation=293,velocity=0,heading=133,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_12,fleet=East,driver=Trish,model=G_2000,device_version=v1_0 latitude=36.03928,longitude=113.87118,elevation=39,velocity=0,heading=294,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_5,fleet=East,driver=Seth,model=F_150,device_version=v2_0 latitude=5.00552,longitude=114.50557,elevation=89,velocity=0,heading=187,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_14,driver=Albert,model=H_2,device_version=v1_0 latitude=66.68217,longitude=105.76965,elevation=222,velocity=0,heading=252,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_16,fleet=South,driver=Albert,model=G_2000,device_version=v1_5 latitude=51.16438,longitude=121.32451,elevation=455,velocity=0,heading=290,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_18,fleet=West,driver=Trish,model=F_150,device_version=v2_0 latitude=67.15164,longitude=153.56165,elevation=252,velocity=0,heading=240,grade=0,fuel_consumption=25,load_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_20,fleet=North,driver=Rodney,model=G_2000,device_version=v2_0 latitude=38.88807,longitude=65.86698,elevation=104,velocity=0,heading=44,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_21,fleet=East,driver=Derek,model=G_2000,device_version=v2_0 latitude=81.87812,longitude=167.8083,elevation=345,velocity=0,heading=327,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_22,fleet=West,driver=Albert,model=G_2000,device_version=v1_5 latitude=39.9433,longitude=16.0241,elevation=449,velocity=0,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_23,fleet=South,driver=Andy,model=F_150,device_version=v2_0 latitude=73.28358,longitude=98.05159,elevation=198,velocity=0,heading=276,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_24,fleet=West,driver=Rodney,model=G_2000,device_version=v2_3 latitude=22.19262,longitude=0.27462,elevation=223,velocity=0,heading=318,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_15,fleet=South,driver=Albert,model=H_2,device_version=v1_5 latitude=6.7849,longitude=166.86587,elevation=1,velocity=0,heading=112,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_27,fleet=West,driver=Seth,model=G_2000,device_version=v1_5 latitude=79.55971,longitude=97.86182,elevation=252,velocity=0,heading=345,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_17,fleet=West,driver=Derek,model=H_2,device_version=v1_5 latitude=8.12884,longitude=56.57752,elevation=8,velocity=0,heading=9,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_30,fleet=East,driver=Andy,model=G_2000,device_version=v1_5 latitude=29.62198,longitude=83.73482,elevation=291,velocity=0,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_33,fleet=West,driver=Rodney,model=G_2000,device_version=v1_5 latitude=89.19448,longitude=10.47499,elevation=407,velocity=0,heading=169,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_34,fleet=West,driver=Rodney,model=G_2000,device_version=v2_0 latitude=73.7383,longitude=10.79582,elevation=488,velocity=0,heading=170,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_35,fleet=West,driver=Seth,model=G_2000,device_version=v2_3 latitude=60.02428,longitude=2.51011,elevation=480,velocity=0,heading=307,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_36,fleet=North,driver=Andy,model=G_2000,device_version=v1_0 latitude=87.52877,longitude=45.07308,elevation=161,velocity=0,heading=128,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_37,fleet=South,driver=Andy,model=G_2000,device_version=v2_0 latitude=57.90077,longitude=77.20136,elevation=77,velocity=0,heading=179,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_38,fleet=West,driver=Andy,model=H_2,device_version=v2_3 latitude=63.54604,longitude=119.82031,elevation=282,velocity=0,heading=325,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_25,fleet=North,driver=Trish,model=F_150,device_version=v2_0 latitude=17.26704,longitude=16.91226,elevation=461,velocity=0,heading=183,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_29,fleet=East,driver=Rodney,model=G_2000,device_version=v2_0 latitude=80.30543,longitude=146.54308,elevation=345,velocity=0,heading=119,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_39,fleet=East,driver=Derek,model=G_2000,device_version=v1_5 latitude=33.83548,longitude=3.90996,elevation=294,velocity=0,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_31,fleet=North,driver=Albert,model=G_2000,device_version=v1_0 latitude=0.75251,longitude=116.83474,elevation=455,velocity=0,heading=49,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_32,fleet=West,driver=Seth,model=F_150,device_version=v2_0 latitude=4.07566,longitude=164.43909,elevation=297,velocity=0,heading=277,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_40,fleet=West,driver=Albert,model=H_2,device_version=v2_0 latitude=32.32773,longitude=118.43138,elevation=276,velocity=0,heading=316,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_41,fleet=East,driver=Rodney,model=F_150,device_version=v1_0 latitude=68.85572,longitude=173.23123,elevation=478,velocity=0,heading=207,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_42,fleet=West,driver=Trish,model=F_150,device_version=v2_0 latitude=38.45195,longitude=171.2884,elevation=113,velocity=0,heading=180,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_43,fleet=East,driver=Derek,model=H_2,device_version=v2_0 latitude=52.90189,longitude=49.76966,elevation=295,velocity=0,heading=195,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_44,fleet=South,driver=Seth,model=H_2,device_version=v1_0 latitude=32.33297,longitude=3.89306,elevation=396,velocity=0,heading=320,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_26,fleet=South,driver=Seth,model=F_150,device_version=v1_5 latitude=45.65327,longitude=144.60354,elevation=58,velocity=0,heading=182,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_47,fleet=South,driver=Derek,model=G_2000,device_version=v1_5 latitude=41.62173,longitude=110.80422,elevation=111,velocity=0,heading=78,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_48,fleet=East,driver=Trish,model=G_2000,device_version=v1_5 latitude=63.90773,longitude=141.50555,elevation=53,velocity=0,heading=89,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_49,fleet=South,driver=Andy,model=F_150,device_version=v2_0 latitude=38.9349,longitude=179.94282,elevation=289,velocity=0,heading=269,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_50,fleet=East,driver=Andy,model=H_2,device_version=v2_3 latitude=45.44111,longitude=172.39833,elevation=219,velocity=0,heading=88,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_51,fleet=East,driver=Rodney,model=F_150,device_version=v2_3 latitude=89.03645,longitude=91.57675,elevation=457,velocity=0,heading=337,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_52,fleet=West,driver=Derek,model=G_2000,device_version=v1_0 latitude=89.0133,longitude=97.8037,elevation=23,velocity=0,heading=168,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_53,fleet=West,driver=Seth,model=G_2000,device_version=v2_3 latitude=25.02,longitude=157.45082,elevation=272,heading=5,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_54,fleet=North,driver=Andy,model=H_2,device_version=v2_0 latitude=87.62736,longitude=106.0376,elevation=360,velocity=0,heading=66,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_55,fleet=East,driver=Albert,model=G_2000,device_version=v1_0 latitude=78.56605,longitude=71.16225,elevation=295,velocity=0,heading=150,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_56,fleet=North,driver=Derek,model=F_150,device_version=v2_0 latitude=23.51619,longitude=123.22682,elevation=71,velocity=0,heading=209,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_58,fleet=South,driver=Derek,model=F_150,device_version=v2_0 latitude=84.79333,longitude=79.23813,elevation=175,velocity=0,heading=246,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_46,fleet=West,driver=Seth,model=H_2,device_version=v2_3 latitude=26.07966,longitude=118.49629,elevation=321,velocity=0,heading=267,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_60,fleet=South,driver=Derek,model=H_2,device_version=v1_5 latitude=57.99184,longitude=33.45994,elevation=310,velocity=0,heading=93,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_62,fleet=East,driver=Derek,model=H_2,device_version=v1_5 latitude=54.61668,longitude=103.21398,elevation=231,velocity=0,heading=143,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_64,fleet=South,driver=Albert,model=G_2000,device_version=v2_0 latitude=45.04214,longitude=10.73002,elevation=447,velocity=0,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_65,fleet=North,driver=Rodney,model=F_150,device_version=v1_0 latitude=67.34642,longitude=152.93415,elevation=362,velocity=0,heading=112,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_66,fleet=South,driver=Seth,model=G_2000,device_version=v2_0 latitude=42.24286,longitude=151.8978,elevation=227,velocity=0,heading=67,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_67,fleet=South,driver=Seth,model=H_2,device_version=v1_0 latitude=4.62985,longitude=155.01707,elevation=308,velocity=0,heading=22,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_68,fleet=West,driver=Rodney,model=F_150,device_version=v1_5 latitude=16.90741,longitude=123.03863,elevation=303,velocity=0,heading=43,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_69,fleet=East,driver=Derek,model=H_2,device_version=v2_3 latitude=79.88424,longitude=120.79121,elevation=407,velocity=0,heading=138,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_57,fleet=South,driver=Rodney,model=F_150,device_version=v2_3 latitude=26.07996,longitude=159.92716,elevation=454,velocity=0,heading=22,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_61,fleet=East,driver=Albert,model=G_2000,device_version=v2_3 latitude=75.91676,longitude=167.78366,elevation=462,velocity=0,heading=60,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_72,fleet=South,driver=Andy,model=G_2000,device_version=v2_3 latitude=82.46228,longitude=2.44504,elevation=487,velocity=0,heading=39,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_73,fleet=North,driver=Seth,model=F_150,device_version=v1_5 latitude=37.67468,longitude=91.09732,elevation=489,velocity=0,heading=103,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_74,fleet=North,driver=Trish,model=H_2,device_version=v1_0 latitude=41.4456,longitude=158.13897,elevation=206,velocity=0,heading=79,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_75,fleet=South,driver=Andy,model=F_150,device_version=v1_5 latitude=4.11709,longitude=175.65994,elevation=378,velocity=0,heading=176,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_76,fleet=South,driver=Rodney,model=F_150,device_version=v2_3 latitude=71.62798,longitude=121.89842,elevation=283,velocity=0,heading=164,grade=0,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_77,fleet=East,driver=Trish,model=F_150,device_version=v2_0 latitude=80.5734,longitude=17.68311,velocity=0,heading=218,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_78,fleet=South,driver=Seth,model=F_150,device_version=v2_0 latitude=13.96218,elevation=433,velocity=0,heading=326,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_79,fleet=South,driver=Andy,model=G_2000,device_version=v2_0 latitude=56.54137,longitude=174.44318,elevation=46,velocity=0,heading=127,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_70,fleet=North,driver=Albert,model=H_2,device_version=v2_0 latitude=77.87592,longitude=164.70924,elevation=270,velocity=0,heading=21,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_82,fleet=West,driver=Derek,model=H_2,device_version=v2_0 latitude=57.00976,longitude=90.13642,elevation=102,velocity=0,heading=296,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_45,fleet=East,driver=Trish,model=G_2000,device_version=v1_0 latitude=17.48624,longitude=100.78121,elevation=306,velocity=0,heading=193,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_83,fleet=South,driver=Albert,model=F_150,device_version=v2_0 latitude=49.20261,longitude=115.98262,elevation=449,velocity=0,heading=132,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_84,fleet=West,driver=Derek,model=H_2,device_version=v1_0 latitude=70.16476,longitude=59.05399,elevation=301,velocity=0,heading=134,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_63,fleet=South,driver=Rodney,model=H_2,device_version=v2_0 latitude=37.13702,longitude=149.25546,elevation=46,velocity=0,heading=118,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_85,fleet=West,driver=Derek,model=G_2000,device_version=v1_0 latitude=11.75251,longitude=142.86513,elevation=358,velocity=0,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_86,fleet=West,driver=Rodney,model=G_2000,device_version=v1_0 latitude=30.92821,longitude=127.53274,elevation=367,velocity=0,heading=162,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_87,fleet=West,driver=Rodney,model=H_2,device_version=v2_0 latitude=32.86913,longitude=155.7666,elevation=122,velocity=0,heading=337,grade=0,fuel_consumption=25,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_94,fleet=North,driver=Derek,model=F_150,device_version=v1_0 latitude=59.53287,longitude=26.98247,elevation=427,velocity=0,heading=341,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_102,fleet=North,driver=Andy,model=H_2,device_version=v2_0 latitude=42.18662,longitude=54.71293,elevation=95,velocity=0,heading=119,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_103,fleet=East,driver=Albert,model=H_2,device_version=v1_0 latitude=56.29649,longitude=70.69738,elevation=315,velocity=0,heading=121,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_105,fleet=North,driver=Seth,model=H_2,device_version=v1_5 latitude=86.84972,longitude=89.88505,elevation=382,velocity=0,heading=113,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_106,fleet=West,driver=Andy,model=H_2,device_version=v1_0 latitude=62.14583,longitude=89.69073,elevation=378,velocity=0,heading=51,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_107,fleet=West,driver=Rodney,model=H_2,device_version=v2_3 latitude=4.40498,longitude=59.42118,elevation=322,velocity=0,heading=309,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_110,fleet=North,driver=Trish,model=H_2,device_version=v1_5 latitude=20.26338,longitude=139.14372,elevation=75,velocity=0,heading=42,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_111,fleet=West,driver=Seth,model=F_150,device_version=v1_0 latitude=39.35405,longitude=154.29641,elevation=476,velocity=0,heading=29,grade=0,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_112,fleet=South,driver=Seth,model=F_150,device_version=v1_5 latitude=60.09378,longitude=85.93094,elevation=287,velocity=0,heading=92,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_113,fleet=West,driver=Andy,model=F_150,device_version=v1_0 latitude=69.11827,longitude=140.84973,elevation=234,velocity=0,heading=50,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_80,fleet=East,driver=Andy,model=G_2000,device_version=v2_3 latitude=46.13937,longitude=137.42962,elevation=295,velocity=0,heading=290,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_89,fleet=South,driver=Trish,model=F_150,device_version=v1_5 latitude=69.56303,longitude=31.94727,elevation=294,velocity=0,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_92,fleet=North,driver=Derek,model=H_2,device_version=v1_0 latitude=54.40335,longitude=153.5809,elevation=123,velocity=0,heading=150,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_95,fleet=East,driver=Albert,model=G_2000,device_version=v2_0 latitude=37.31513,longitude=134.40078,elevation=383,velocity=0,heading=121,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_96,fleet=East,driver=Albert,model=G_2000,device_version=v1_5 latitude=15.78803,longitude=146.68255,elevation=348,velocity=0,heading=189,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_97,fleet=South,driver=Seth,model=F_150,device_version=v1_0 latitude=14.08559,longitude=18.49763,elevation=369,velocity=0,heading=34,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_98,fleet=South,driver=Albert,model=G_2000,device_version=v1_5 latitude=15.1474,longitude=71.85194,elevation=89,velocity=0,heading=238,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_99,fleet=West,driver=Trish,model=G_2000,device_version=v1_5 latitude=62.73061,longitude=26.1884,elevation=309,velocity=0,heading=202,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_100,fleet=West,driver=Seth,model=H_2,device_version=v2_0 latitude=89.90659,longitude=164.90738,elevation=364,velocity=0,heading=130,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_101,fleet=East,driver=Albert,model=H_2,device_version=v1_5 latitude=58.47594,longitude=175.2698,elevation=185,velocity=0,heading=308,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_114,fleet=West,driver=Rodney,model=F_150,device_version=v2_0 latitude=5.97259,longitude=13.82164,elevation=334,velocity=0,heading=163,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_117,fleet=East,driver=Seth,model=G_2000,device_version=v1_5 latitude=18.81365,longitude=90.57291,velocity=0,heading=331,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_120,fleet=North,driver=Trish,model=F_150,device_version=v1_0 latitude=36.884,longitude=24.51837,elevation=300,velocity=0,heading=270,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_122,fleet=East,driver=Rodney,device_version=v2_0 latitude=18.4872,longitude=55.71869,elevation=398,velocity=0,heading=224,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_123,fleet=South,driver=Rodney,model=H_2,device_version=v2_3 latitude=19.63769,longitude=179.3212,elevation=197,velocity=0,heading=216,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_124,fleet=West,driver=Trish,model=G_2000,device_version=v1_0 latitude=9.51553,longitude=150.73086,elevation=476,velocity=0,heading=216,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_125,fleet=South,driver=Andy,model=H_2,device_version=v1_0 latitude=73.40009,longitude=118.61056,elevation=20,velocity=0,heading=246,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_126,fleet=West,driver=Albert,model=H_2,device_version=v1_0 latitude=55.34824,longitude=7.74413,elevation=49,velocity=0,heading=265,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_127,fleet=North,driver=Andy,model=G_2000,device_version=v1_5 latitude=48.33546,longitude=7.72643,elevation=25,velocity=0,heading=16,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_128,fleet=East,driver=Trish,model=G_2000,device_version=v2_3 latitude=60.85333,longitude=127.44771,elevation=309,velocity=0,heading=3,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_129,fleet=West,driver=Rodney,model=F_150,device_version=v2_0 latitude=54.28227,longitude=172.73092,elevation=381,velocity=0,heading=148,grade=0,fuel_consumption=25,load_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_81,fleet=West,driver=Rodney,model=G_2000,device_version=v2_3 latitude=59.42624,longitude=115.59744,elevation=68,velocity=0,heading=296,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_115,fleet=East,driver=Trish,model=G_2000,device_version=v1_5 latitude=58.55996,longitude=45.01045,elevation=492,velocity=0,heading=224,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_130,fleet=East,driver=Rodney,model=G_2000,device_version=v2_3 latitude=89.17613,longitude=161.37179,elevation=499,velocity=0,heading=128,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_131,fleet=West,driver=Derek,model=F_150,device_version=v1_5 latitude=68.58781,elevation=260,velocity=0,heading=221,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_121,fleet=North,driver=Andy,model=F_150,device_version=v2_3 latitude=51.91465,longitude=175.98481,elevation=201,heading=249,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_132,fleet=West,driver=Rodney,model=H_2,device_version=v2_3 latitude=83.225,longitude=56.15063,elevation=490,velocity=0,heading=116,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_134,fleet=East,driver=Seth,model=H_2,device_version=v1_5 latitude=10.13464,longitude=62.99114,elevation=300,velocity=0,heading=51,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_135,fleet=South,driver=Andy,model=G_2000,device_version=v1_0 latitude=19.67053,longitude=146.51556,elevation=64,velocity=0,heading=5,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_136,fleet=East,driver=Seth,model=H_2,device_version=v1_0 latitude=61.82203,longitude=16.28983,elevation=282,velocity=0,heading=197,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_137,fleet=East,driver=Albert,model=F_150,device_version=v2_0 latitude=34.89144,longitude=99.23335,elevation=280,velocity=0,heading=246,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_138,fleet=South,driver=Trish,model=H_2,device_version=v1_5 latitude=84.03285,longitude=177.32909,elevation=206,velocity=0,heading=142,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_139,fleet=South,driver=Trish,model=G_2000,device_version=v2_3 latitude=56.59674,longitude=10.30437,elevation=414,velocity=0,heading=152,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_140,fleet=West,driver=Seth,model=F_150,device_version=v1_5 latitude=49.78419,longitude=105.45629,elevation=101,velocity=0,heading=329,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_133,fleet=East,driver=Seth,model=G_2000,device_version=v2_3 latitude=80.29634,longitude=109.07111,elevation=104,velocity=0,heading=244,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_141,fleet=East,driver=Trish,model=G_2000,device_version=v2_0 latitude=18.01978,longitude=139.44312,elevation=321,velocity=0,heading=193,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000 onview,name=event_142,fleet=West,driver=Albert,model=H_2,device_version=v1_0 latitude=16.10132,longitude=148.51718,elevation=121,velocity=0,heading=253,grade=0,fuel_consumption=25,load_capacity=0,fuel_capacity=0,nominal_fuel_consumption=0 1640995200000000000
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
true
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/手撸系列/nom-practice/src/bin/hello_parser_generator.rs
手撸系列/nom-practice/src/bin/hello_parser_generator.rs
fn main() { let msg = "hello,rust"; let mut parse_generator = hello_parser_generator("hello"); let hello1 = parse_generator(msg); println!("parse result:{:?}", hello1); } /// hello解析器生成器 /// 返回参数:剩余字符串,解析出来的字符串 fn hello_parser_generator<'a>( tag: &'a str, ) -> impl FnMut(&'a str) -> Result<(&'a str, &'a str), &'a str> { move |msg| { if !msg.is_empty() && msg.starts_with(tag) { Ok((&msg[tag.len()..], tag)) } else { Err("parse error") } } }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/手撸系列/nom-practice/src/bin/parser_combinor.rs
手撸系列/nom-practice/src/bin/parser_combinor.rs
fn main() { let msg = "hello,rust"; let result = parser_combinor(msg, hello_parser, comma_parser, rust_parser); println!("result:{:?}", result); } /// hello解析器 /// 返回参数:剩余字符串,解析出来的字符串 fn hello_parser(msg: &str) -> Result<(&str, &str), &str> { if !msg.is_empty() && msg.starts_with("hello") { Ok((&msg["hello".len()..], "hello")) } else { Err("parse error") } } /// 逗号解析器 /// 返回参数:剩余字符串,解析出来的字符串 fn comma_parser(msg: &str) -> Result<(&str, &str), &str> { if !msg.is_empty() && msg.starts_with(",") { Ok((&msg[",".len()..], ",")) } else { Err("parse error") } } /// rust解析器解析器 /// 返回参数:剩余字符串,解析出来的字符串 fn rust_parser(msg: &str) -> Result<(&str, &str), &str> { if !msg.is_empty() && msg.starts_with("rust") { Ok((&msg["rust".len()..], "rust")) } else { Err("parse error") } } fn parser_combinor<F, F1, F2>( msg: &str, mut hello_parser: F, mut comma_parser: F1, mut rust_parser: F2, ) -> Vec<&str> where F: FnMut(&str) -> Result<(&str, &str), &str>, F1: FnMut(&str) -> Result<(&str, &str), &str>, F2: FnMut(&str) -> Result<(&str, &str), &str>, { let mut result = vec![]; if let Ok((input, res)) = hello_parser(msg) { result.push(res); if let Ok((input, res)) = comma_parser(&input) { result.push(res); if let Ok((_, res)) = rust_parser(&input) { result.push(res); } } } else { result.push("parse error"); } result }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/手撸系列/nom-practice/src/bin/hello_parser.rs
手撸系列/nom-practice/src/bin/hello_parser.rs
fn main() { let msg = "hello,rust"; let hello = hello_parser(msg); println!("parse result:{:?}", hello); } /// hello解析器 /// 返回参数:剩余字符串,解析出来的字符串 fn hello_parser(msg: &str) -> Result<(&str, &str), &str> { if !msg.is_empty() && msg.starts_with("hello") { Ok((&msg["hello".len()..], "hello")) } else { Err("parse error") } }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
reganzm/hug_rust
https://github.com/reganzm/hug_rust/blob/6a2801769c8b062477c2e6273af0218e0e21e75d/手撸系列/nom-practice/src/bin/nom_functions.rs
手撸系列/nom-practice/src/bin/nom_functions.rs
use nom::{ branch::alt, bytes::complete::tag, combinator::{consumed, map, peek, recognize}, multi::{many0, many1}, sequence::{delimited, pair, preceded, separated_pair, terminated, tuple}, IResult, }; fn main() { let msg = "hello,rust"; let msg1 = "hellohello,rust"; println!("tag:{:?}", hello_parser(msg)); println!("peek:{:?}", peek_parser(msg)); println!("pair:{:?}", pair_parser(msg)); println!("tuple:{:?}", tuple_parser(msg)); println!("alt:{:?}", alt_parser(msg)); println!("delimited:{:?}", delimited_parser(msg)); println!("separated:{:?}", separated_pair_parser(msg)); println!("preceded:{:?}", preceded_parser(msg)); println!("terminated:{:?}", ternimated_parser(msg)); println!("recognize:{:?}", recognize_parser(msg)); println!("consumed:{:?}", comsumed_parser(msg)); println!("many0:{:?}", many0_parser(msg1)); println!("many1:{:?}", many1_parser(msg1)); println!("map:{:?}", map_transformation(msg1)); } // 解析器——消耗 fn hello_parser(input: &str) -> IResult<&str, &str> { tag("hello")(input) } // 解析器——产生一个解析器 但是不消耗匹配的源 fn peek_parser(input: &str) -> IResult<&str, &str> { peek(tag("hello"))(input) } // 组合算子——串联——pair——消耗 支持两个解析器 fn pair_parser(input: &str) -> IResult<&str, (&str, (&str, &str))> { pair(tag("hello"), pair(tag(","), tag("rust")))(input) } // 组合算子——串联——tuple——消耗 最多支持21个解析器 fn tuple_parser(input: &str) -> IResult<&str, (&str, &str, &str)> { tuple((tag("hello"), tag(","), tag("rust")))(input) } // 组合算子——并联——alt——消耗 只要一个解析器成功即成功 fn alt_parser(input: &str) -> IResult<&str, &str> { alt((tag("hello"), tag(","), tag("rust")))(input) } // 组合算子——delimited——消耗 传入三个解析器 所有解析器成功后才算成功,成功后返回中间解析器的值 fn delimited_parser(input: &str) -> IResult<&str, &str> { delimited(tag("hello"), tag(","), tag("rust"))(input) } // 组合算子——separated_pair——消耗 传入三个解析器 所有解析器都成功后才算成功,返回第一个和第三个解析器中的值,忽略第二个解析器产生的值 fn separated_pair_parser(input: &str) -> IResult<&str, (&str, &str)> { separated_pair(tag("hello"), tag(","), tag("rust"))(input) } // 组合算子——proceded——消耗 传入两个解析器,所有解析器都成功才算成功,返回第二个解析器中的值 fn preceded_parser(input: &str) -> IResult<&str, &str> { preceded(tag("hello"), tag(","))(input) } // 组合算子——terminated——消耗 传入两个解析器,所有解析器都成功才算成功,返回第一个解析器产生的值 fn ternimated_parser(input: &str) -> IResult<&str, &str> { terminated(tag("hello"), tag(","))(input) } // 组合算子——recognize——消耗 将子解析器解析成功的返回值拼接起来作为返回值 fn recognize_parser(input: &str) -> IResult<&str, &str> { recognize(separated_pair_parser)(input) } // 组合算子——consumed——非消耗 返回子解析器的值且不消耗传入的数据源 fn comsumed_parser(input: &str) -> IResult<&str, (&str, (&str, &str))> { consumed(separated_pair_parser)(input) } // 多匹配算子——many0——消耗 产生0到多个匹配的解析器 类似于正则表达式中的* fn many0_parser(input: &str) -> IResult<&str, Vec<&str>> { many0(tag("hello"))(input) } // 多匹配算子——many1——消耗 产生1到多个匹配的解析器 类似与正则表达式中的+ fn many1_parser(input: &str) -> IResult<&str, Vec<&str>> { many1(tag("hello"))(input) } // map转换函数 fn map_transformation(input: &str) -> IResult<&str, usize> { map(many0(tag("hello")), |s: Vec<_>| s.len())(input) }
rust
Apache-2.0
6a2801769c8b062477c2e6273af0218e0e21e75d
2026-01-04T20:24:35.074754Z
false
doonv/bevy_dev_console
https://github.com/doonv/bevy_dev_console/blob/98355f16b7d83ad0db983f2204426079780aa2ae/src/config.rs
src/config.rs
//! Configuration structs for the developer console. use bevy::log::Level; use bevy::prelude::*; use bevy_egui::egui::{Color32, FontId, TextFormat}; /// The configuration of the developer console. #[derive(Resource, Reflect, Debug)] pub struct ConsoleConfig { /// The colors used in the developer console. pub theme: ConsoleTheme, /// The key used to open the developer console. pub open_key: KeyCode, /// The key used to submit a command to the command parser. pub submit_key: KeyCode, } impl Default for ConsoleConfig { fn default() -> Self { Self { theme: ConsoleTheme::ONE_DARK, open_key: KeyCode::Backquote, submit_key: KeyCode::Enter, } } } /// The colors used by the text in the developer console. #[derive(Reflect, Debug)] pub struct ConsoleTheme { /// The font used in the developer console. #[reflect(ignore)] pub font: FontId, /// The default color of text. pub text_color: Color, /// The color of dark text. pub dark: Color, /// The color of the "error" level. /// /// Designates very serious errors. pub error: Color, /// The color of the "warn" level. /// /// Designates hazardous situations. pub warning: Color, /// The color of the "info" level. /// /// Designates useful information. pub info: Color, /// The color of the "debug" level. /// /// Designates lower priority information. pub debug: Color, /// The color of the "trace" level. /// /// Designates very low priority, often extremely verbose, information. pub trace: Color, } /// Helper trait that allows conversion between [`bevy::Color`](Color) and [`egui::Color32`]. pub trait ToColor32 { /// Convert this [`bevy::Color`](Color) to a [`egui::Color32`]. fn to_color32(&self) -> Color32; } impl ToColor32 for Color { fn to_color32(&self) -> Color32 { let Srgba { red, green, blue, alpha, } = self.to_srgba(); Color32::from_rgba_unmultiplied( (red * 255.0) as u8, (green * 255.0) as u8, (blue * 255.0) as u8, (alpha * 255.0) as u8, ) } } macro_rules! define_text_format_method { ($name:ident, $color:ident) => { #[doc = concat!("Returns a [`TextFormat`] colored with [`Self::", stringify!($color), "`]")] pub fn $name(&self) -> TextFormat { TextFormat { color: self.$color.to_color32(), ..self.format_text() } } }; } impl ConsoleTheme { /// Atom's iconic One Dark theme. pub const ONE_DARK: Self = Self { font: FontId::monospace(14.0), dark: Color::srgb(0.42, 0.44, 0.48), text_color: Color::srgb(0.67, 0.7, 0.75), error: Color::srgb(0.91, 0.46, 0.5), warning: Color::srgb(0.82, 0.56, 0.32), info: Color::srgb(0.55, 0.76, 0.4), debug: Color::srgb(0.29, 0.65, 0.94), trace: Color::srgb(0.78, 0.45, 0.89), }; /// High contrast theme, might help some people. pub const HIGH_CONTRAST: Self = Self { font: FontId::monospace(14.0), dark: Color::srgb(0.5, 0.5, 0.5), text_color: Color::srgb(1.0, 1.0, 1.0), error: Color::srgb(1.0, 0.0, 0.0), warning: Color::srgb(1.0, 1.0, 0.0), info: Color::srgb(0.0, 1.0, 0.0), debug: Color::srgb(0.25, 0.25, 1.0), trace: Color::srgb(1.0, 0.0, 1.0), }; /// Returns a [`Color32`] based on the `level` pub fn color_level(&self, level: Level) -> Color32 { match level { Level::ERROR => self.error.to_color32(), Level::WARN => self.warning.to_color32(), Level::INFO => self.info.to_color32(), Level::DEBUG => self.debug.to_color32(), Level::TRACE => self.trace.to_color32(), } } /// Returns a [`TextFormat`] with a color based on the [`Level`] and the [`ConsoleTheme`]. pub fn format_level(&self, level: Level) -> TextFormat { TextFormat { color: self.color_level(level), ..self.format_text() } } /// Returns a [`TextFormat`] with the default font and color. pub fn format_text(&self) -> TextFormat { TextFormat { font_id: self.font.clone(), color: self.text_color.to_color32(), ..default() } } /// Returns a [`TextFormat`] with the default font and white color. pub fn format_bold(&self) -> TextFormat { TextFormat { font_id: self.font.clone(), color: Color32::WHITE, ..default() } } define_text_format_method!(format_dark, dark); define_text_format_method!(format_error, error); define_text_format_method!(format_warning, warning); define_text_format_method!(format_info, info); define_text_format_method!(format_debug, debug); define_text_format_method!(format_trace, trace); }
rust
Apache-2.0
98355f16b7d83ad0db983f2204426079780aa2ae
2026-01-04T20:24:35.637367Z
false
doonv/bevy_dev_console
https://github.com/doonv/bevy_dev_console/blob/98355f16b7d83ad0db983f2204426079780aa2ae/src/prelude.rs
src/prelude.rs
//! `use bevy_dev_console::prelude::*` to quickly import the required plugins for [`bevy_dev_console`](crate). pub use crate::config::ConsoleConfig; pub use crate::logging::custom_log_layer; pub use crate::DevConsolePlugin;
rust
Apache-2.0
98355f16b7d83ad0db983f2204426079780aa2ae
2026-01-04T20:24:35.637367Z
false
doonv/bevy_dev_console
https://github.com/doonv/bevy_dev_console/blob/98355f16b7d83ad0db983f2204426079780aa2ae/src/lib.rs
src/lib.rs
#![doc = include_str!("../README.md")] use bevy::prelude::*; use bevy_egui::EguiPlugin; use command::CommandHints; use config::ConsoleConfig; use ui::ConsoleUiState; #[cfg(feature = "builtin-parser")] pub mod builtin_parser; pub mod command; pub mod config; pub mod logging; pub mod prelude; pub mod ui; /// Adds a Developer Console to your Bevy application. /// /// Requires [custom_log_layer](logging::custom_log_layer). pub struct DevConsolePlugin; impl Plugin for DevConsolePlugin { fn build(&self, app: &mut App) { if !app.is_plugin_added::<EguiPlugin>() { app.add_plugins(EguiPlugin); } #[cfg(feature = "builtin-parser")] { app.init_non_send_resource::<builtin_parser::Environment>(); app.init_resource::<command::DefaultCommandParser>(); #[cfg(feature = "builtin-parser-completions")] app.init_resource::<builtin_parser::completions::EnvironmentCache>(); } #[cfg(feature = "completions")] app.init_resource::<command::AutoCompletions>(); app.init_resource::<ConsoleUiState>() .init_resource::<CommandHints>() .init_resource::<ConsoleConfig>() .register_type::<ConsoleConfig>() .add_systems( Update, ( ui::read_logs, ( ui::open_close_ui, ui::render_ui_system.run_if(|s: Res<ConsoleUiState>| s.open), ) .chain(), ), ); } }
rust
Apache-2.0
98355f16b7d83ad0db983f2204426079780aa2ae
2026-01-04T20:24:35.637367Z
false
doonv/bevy_dev_console
https://github.com/doonv/bevy_dev_console/blob/98355f16b7d83ad0db983f2204426079780aa2ae/src/command.rs
src/command.rs
//! Command execution functionality. use std::borrow::Cow; use std::ops::Range; use bevy::ecs::world::Command; use bevy::prelude::*; /// The command parser currently being used by the dev console. #[derive(Resource)] pub struct DefaultCommandParser(pub Box<dyn CommandParser>); impl DefaultCommandParser { /// Shortcut method for calling `parser.0.parse(command, world)`. #[inline] pub fn parse(&self, command: &str, world: &mut World) { self.0.parse(command, world) } /// Shortcut method for calling `parser.0.completion(command, world)`. #[inline] #[must_use] #[cfg(feature = "completions")] pub fn completion(&self, keyword: &str, world: &World) -> Vec<CompletionSuggestion> { self.0.completion(keyword, world) } } impl<Parser: CommandParser> From<Parser> for DefaultCommandParser { fn from(value: Parser) -> Self { Self(Box::new(value)) } } impl From<Box<dyn CommandParser>> for DefaultCommandParser { fn from(value: Box<dyn CommandParser>) -> Self { Self(value) } } /// A hint displayed to the user when they make a mistake. #[derive(Debug, Clone)] pub struct CommandHint { /// The color of the hint. pub color: CommandHintColor, /// The location of the hint in the command. pub span: Range<usize>, /// Additional information about the hint when hovered over. /// (Doesn't do anything atm) pub description: Cow<'static, str>, } impl CommandHint { /// Creates a new [`CommandHint`]. pub fn new( span: Range<usize>, color: CommandHintColor, description: impl Into<Cow<'static, str>>, ) -> Self { Self { color, span, description: description.into(), } } } /// The color of a [`CommandHint`], may either be a standard color or a [`Custom`](CommandHintColor::Custom) [`Color`]. #[derive(Debug, Clone)] pub enum CommandHintColor { /// An error marks bad code that cannot be recovered from. /// /// Usually colored red. Error, /// A warning marks code that could cause problems in the future. /// /// Usually colored yellow. Warning, /// A hint marks code that is questionable, but is otherwise fine. /// /// Usually colored blue. Hint, /// This marks code that could be improved. /// /// Usually colored green. Help, /// A custom color of your choice! This is usually not recommended as /// you're much better off using the standard colors. Custom(Color), } /// A resource where hints (errors/warnings/etc) are stored /// to be displayed in the developer console. #[derive(Resource, Debug, Default, Deref)] pub struct CommandHints { #[deref] hints: Vec<Vec<CommandHint>>, hint_added: bool, } impl CommandHints { /// Push a list of hints. This should be done once per command call. pub fn push(&mut self, hints: impl Into<Vec<CommandHint>>) { if self.hint_added { warn!( "Hints were added twice! Hint 1: {:?}, Hint 2: {:?}", self.hints.last(), hints.into() ) } else { self.hint_added = true; self.hints.push(hints.into()); } } pub(crate) fn reset_hint_added(&mut self) { if !self.hint_added { self.push([]); } self.hint_added = false; } } /// The trait that all [`CommandParser`]s implement. /// You can take a look at the [builtin parser](crate::builtin_parser) for an advanced example. /// /// ``` /// # use bevy::ecs::world::World; /// # use bevy_dev_console::command::CommandParser; /// # use bevy::log::info; /// # use bevy_dev_console::ui::COMMAND_RESULT_NAME; /// /// pub struct MyCustomParser; /// impl CommandParser for MyCustomParser { /// fn parse(&self, command: &str, world: &mut World) { /// // The `name: COMMAND_RESULT_NAME` tells the console this is a result from /// // the parser and then formats it accordingly. /// # // TODO: figure out better solution for this /// info!(name: COMMAND_RESULT_NAME, "You just entered the command {command}") /// } /// } /// ``` pub trait CommandParser: Send + Sync + 'static { /// This method is called by the console when a command is ran. fn parse(&self, command: &str, world: &mut World); /// This method is called by the console when the command is changed. #[inline] #[must_use] #[cfg(feature = "completions")] fn completion(&self, keyword: &str, world: &World) -> Vec<CompletionSuggestion> { let _ = (keyword, world); Vec::new() } } /// A suggestion for autocomplete. #[cfg(feature = "completions")] pub struct CompletionSuggestion { /// The suggestion string pub suggestion: String, /// The character indices of the [`suggestion`](Self::suggestion) to highlight. pub highlighted_indices: Vec<usize>, } pub(crate) struct ExecuteCommand(pub String); impl Command for ExecuteCommand { fn apply(self, world: &mut World) { if let Some(parser) = world.remove_resource::<DefaultCommandParser>() { parser.parse(&self.0, world); world.insert_resource(parser); } else { error!("Default command parser doesn't exist, cannot execute command."); } } } #[derive(Resource, Default, Deref, DerefMut)] #[cfg(feature = "completions")] pub struct AutoCompletions(pub(crate) Vec<CompletionSuggestion>); #[cfg(feature = "completions")] pub(crate) struct UpdateAutoComplete(pub String); #[cfg(feature = "completions")] impl Command for UpdateAutoComplete { fn apply(self, world: &mut World) { if let Some(parser) = world.remove_resource::<DefaultCommandParser>() { let completions = parser.completion(&self.0, world); world.resource_mut::<AutoCompletions>().0 = completions; world.insert_resource(parser); } } }
rust
Apache-2.0
98355f16b7d83ad0db983f2204426079780aa2ae
2026-01-04T20:24:35.637367Z
false
doonv/bevy_dev_console
https://github.com/doonv/bevy_dev_console/blob/98355f16b7d83ad0db983f2204426079780aa2ae/src/builtin_parser.rs
src/builtin_parser.rs
//! [`bevy_dev_console`](crate)'s built-in command parser. //! //! Currently the built-in command parser is in very early development. //! It's purpose is to provide a simple, yet powerful method of modifying //! the game world via commands. use bevy::prelude::*; use logos::Span; use crate::builtin_parser::runner::ExecutionError; use crate::command::{CommandHints, CommandParser, DefaultCommandParser}; #[cfg(feature = "builtin-parser-completions")] use crate::command::CompletionSuggestion; #[cfg(feature = "builtin-parser-completions")] pub(crate) mod completions; pub(crate) mod lexer; pub(crate) mod number; pub(crate) mod parser; pub(crate) mod runner; pub use number::*; pub use runner::environment::Environment; pub use runner::error::EvalError; pub use runner::unique_rc::*; pub use runner::Value; /// Additional traits for span. pub trait SpanExtension { /// Wrap this value with a [`Spanned`]. #[must_use] fn wrap<T>(self, value: T) -> Spanned<T>; /// Combine two [`Span`]s into one. #[must_use] fn join(self, span: Self) -> Self; } impl SpanExtension for Span { #[inline] fn wrap<T>(self, value: T) -> Spanned<T> { Spanned { span: self, value } } #[inline] fn join(self, span: Self) -> Self { self.start..span.end } } /// Wrapper around `T` that stores a [Span] (A location in the source code) #[derive(Debug, Clone)] pub struct Spanned<T> { /// The location of `T` in the source/command. pub span: Span, /// The value of `T`. pub value: T, } impl<T> Spanned<T> { /// Maps a [`Spanned<T>`] to [`Spanned<U>`] by applying a function to the /// contained `T` value, leaving the [`Span`] value untouched. #[must_use] pub fn map<U>(self, f: impl FnOnce(T) -> U) -> Spanned<U> { Spanned { span: self.span, value: f(self.value), } } } impl Default for DefaultCommandParser { fn default() -> Self { Self(Box::new(BuiltinCommandParser)) } } /// [`bevy_dev_console`](crate)'s built-in command parser. /// /// See the [module level documentation for more](self). #[derive(Default)] pub struct BuiltinCommandParser; impl CommandParser for BuiltinCommandParser { fn parse(&self, command: &str, world: &mut World) { let mut tokens = lexer::TokenStream::new(command); let environment = world.non_send_resource::<Environment>(); let ast = parser::parse(&mut tokens, environment); dbg!(&ast); match ast { Ok(ast) => match runner::run(ast, world) { Ok(()) => (), Err(error) => { if let ExecutionError::Eval(eval_error) = &error { world .resource_mut::<CommandHints>() .push(eval_error.hints()); } error!("{error}") } }, Err(err) => { world.resource_mut::<CommandHints>().push([err.hint()]); error!("{err}") } } #[cfg(feature = "builtin-parser-completions")] { *world.resource_mut() = completions::store_in_cache(world.non_send_resource::<Environment>()); } } #[cfg(feature = "builtin-parser-completions")] fn completion(&self, command: &str, world: &World) -> Vec<CompletionSuggestion> { use fuzzy_matcher::FuzzyMatcher; use crate::builtin_parser::completions::EnvironmentCache; let matcher = fuzzy_matcher::skim::SkimMatcherV2::default(); let environment_cache = world.resource::<EnvironmentCache>(); let mut names: Vec<_> = environment_cache .function_names .iter() .chain(environment_cache.variable_names.iter()) .map(|name| (matcher.fuzzy_indices(name, command), name.clone())) .filter_map(|(fuzzy, name)| fuzzy.map(|v| (v, name))) .collect(); names.sort_by_key(|((score, _), _)| std::cmp::Reverse(*score)); names.truncate(crate::ui::MAX_COMPLETION_SUGGESTIONS); names .into_iter() .map(|((_, indices), name)| CompletionSuggestion { suggestion: name, highlighted_indices: indices, }) .collect() } }
rust
Apache-2.0
98355f16b7d83ad0db983f2204426079780aa2ae
2026-01-04T20:24:35.637367Z
false
doonv/bevy_dev_console
https://github.com/doonv/bevy_dev_console/blob/98355f16b7d83ad0db983f2204426079780aa2ae/src/ui.rs
src/ui.rs
//! The module that handles the user interface of the console. //! //! Made with [`bevy_egui`]. use bevy::prelude::*; use bevy_egui::egui::text::LayoutJob; use bevy_egui::egui::{Stroke, TextFormat}; use bevy_egui::*; use chrono::prelude::*; use web_time::SystemTime; use crate::command::{CommandHints, ExecuteCommand}; use crate::config::ToColor32; use crate::logging::LogMessage; use crate::prelude::ConsoleConfig; #[cfg(feature = "completions")] use crate::command::AutoCompletions; #[cfg(feature = "completions")] mod completions; #[cfg(feature = "completions")] pub use completions::MAX_COMPLETION_SUGGESTIONS; /// Prefix for log messages that show a previous command. pub const COMMAND_MESSAGE_PREFIX: &str = "$ "; /// Prefix for log messages that show the result of a command. pub const COMMAND_RESULT_PREFIX: &str = "> "; /// Identifier for log messages that show a previous command. pub const COMMAND_MESSAGE_NAME: &str = "console_command"; /// Identifier for log messages that show the result of a command. pub const COMMAND_RESULT_NAME: &str = "console_result"; #[derive(Default, Resource)] pub struct ConsoleUiState { /// Whether the console is open or not. pub(crate) open: bool, /// Whether we have set focus this open or not. pub(crate) text_focus: bool, /// A list of all log messages received plus an /// indicator indicating if the message is new. pub(crate) log: Vec<(LogMessage, bool)>, /// The command in the text bar. pub(crate) command: String, #[cfg(feature = "completions")] pub(crate) selected_completion: usize, } impl ConsoleUiState { /// Whether the console is currently open or not pub fn open(&self) -> bool { self.open } } fn system_time_to_chrono_utc(t: SystemTime) -> chrono::DateTime<chrono::Utc> { let dur = t.duration_since(web_time::SystemTime::UNIX_EPOCH).unwrap(); let (sec, nsec) = (dur.as_secs() as i64, dur.subsec_nanos()); chrono::Utc.timestamp_opt(sec, nsec).unwrap() } pub(crate) fn read_logs(mut logs: EventReader<LogMessage>, mut state: ResMut<ConsoleUiState>) { for log_message in logs.read() { state.log.push((log_message.clone(), true)); } } pub(crate) fn open_close_ui( mut state: ResMut<ConsoleUiState>, key: Res<ButtonInput<KeyCode>>, config: Res<ConsoleConfig>, ) { if key.just_pressed(config.open_key) { state.open = !state.open; state.text_focus = false; } } pub(crate) fn render_ui_system( mut contexts: EguiContexts, mut commands: Commands, mut state: ResMut<ConsoleUiState>, key: Res<ButtonInput<KeyCode>>, mut hints: ResMut<CommandHints>, config: Res<ConsoleConfig>, #[cfg(feature = "completions")] completions: Res<AutoCompletions>, ) { egui::Window::new("Developer Console") .collapsible(false) .default_width(900.) .show(contexts.ctx_mut(), |ui| { render_ui( ui, &mut commands, &mut state, &key, &mut hints, &config, &completions, ) }); } /// The function that renders the UI of the developer console. pub fn render_ui( ui: &mut egui::Ui, commands: &mut Commands, state: &mut ConsoleUiState, key: &ButtonInput<KeyCode>, hints: &mut CommandHints, config: &ConsoleConfig, #[cfg(feature = "completions")] completions: &AutoCompletions, ) { fn submit_command(command: &mut String, commands: &mut Commands) { if !command.trim().is_empty() { info!(name: COMMAND_MESSAGE_NAME, "{COMMAND_MESSAGE_PREFIX}{}", command.trim()); // Get the owned command string by replacing it with an empty string let command = std::mem::take(command); commands.add(ExecuteCommand(command)); } } if key.just_pressed(config.submit_key) { submit_command(&mut state.command, commands); } completions::change_selected_completion(ui, state, &completions); // A General rule when creating layouts in egui is to place elements which fill remaining space last. // Since immediate mode ui can't predict the final sizes of widgets until they've already been drawn // Thus we create a bottom panel first, where our text edit and submit button resides. egui::TopBottomPanel::bottom("bottom panel") .frame(egui::Frame::none().outer_margin(egui::Margin { left: 5.0, right: 5.0, top: 5. + 6., bottom: 5.0, })) .show_inside(ui, |ui| { let text_edit_id = egui::Id::new("text_edit"); //We can use a right to left layout, so we can place the text input last and tell it to fill all remaining space ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { // ui.button is a shorthand command, a similar command exists for text edits, but this is how to manually construct a widget. // doing this also allows access to more options of the widget, rather than being stuck with the default the shorthand picks. if ui.button("Submit").clicked() { submit_command(&mut state.command, commands); // Return keyboard focus to the text edit control. ui.ctx().memory_mut(|mem| mem.request_focus(text_edit_id)); } #[cfg_attr(not(feature = "completions"), allow(unused_variables))] let text_edit = egui::TextEdit::singleline(&mut state.command) .id(text_edit_id) .desired_width(ui.available_width()) .margin(egui::Vec2::splat(4.0)) .font(config.theme.font.clone()) .lock_focus(true) .show(ui); // Display completions if the "completions" feature is enabled #[cfg(feature = "completions")] completions::completions( text_edit, text_edit_id, state, ui, commands, &completions, &config, ); // Each time we open the console, we want to set focus to the text edit control. if !state.text_focus { state.text_focus = true; ui.ctx().memory_mut(|mem| mem.request_focus(text_edit_id)); } }); }); // Now we can fill the remaining minutespace with a scrollarea, which has only the vertical scrollbar enabled and expands to be as big as possible. egui::ScrollArea::new([false, true]) .auto_shrink([false, true]) .show(ui, |ui| { ui.vertical(|ui| { let mut command_index = 0; for (id, (message, is_new)) in state.log.iter_mut().enumerate() { add_log(ui, id, message, is_new, hints, &config, &mut command_index); } }); }); } fn add_log( ui: &mut egui::Ui, id: usize, event: &LogMessage, is_new: &mut bool, hints: &mut CommandHints, config: &ConsoleConfig, command_index: &mut usize, ) { ui.push_id(id, |ui| { let time_utc = system_time_to_chrono_utc(event.time); let time: DateTime<chrono::Local> = time_utc.into(); let text = format_line(time, config, event, *is_new, command_index, hints); let label = ui.label(text); if *is_new { label.scroll_to_me(Some(egui::Align::Max)); *is_new = false; } label.on_hover_ui(|ui| { let mut text = LayoutJob::default(); text.append("Time: ", 0.0, config.theme.format_text()); text.append( &time.format("%x %X %:z").to_string(), 0.0, config.theme.format_dark(), ); text.append("\nTime (UTC): ", 0.0, config.theme.format_text()); text.append( &time_utc.to_rfc3339_opts(chrono::SecondsFormat::Micros, true), 0.0, config.theme.format_dark(), ); text.append("\nName: ", 0.0, config.theme.format_text()); text.append(event.name, 0.0, config.theme.format_dark()); text.append("\nTarget : ", 0.0, config.theme.format_text()); text.append(event.target, 0.0, config.theme.format_dark()); text.append("\nModule Path: ", 0.0, config.theme.format_text()); if let Some(module_path) = event.module_path { text.append(module_path, 0.0, config.theme.format_dark()); } else { text.append("(Unknown)", 0.0, config.theme.format_dark()); } text.append("\nFile: ", 0.0, config.theme.format_text()); if let (Some(file), Some(line)) = (event.file, event.line) { text.append(&format!("{file}:{line}"), 0.0, config.theme.format_dark()); } else { text.append("(Unknown)", 0.0, config.theme.format_dark()); } ui.label(text); }); }); } fn format_line( time: DateTime<chrono::Local>, config: &ConsoleConfig, LogMessage { message, name, level, .. }: &LogMessage, new: bool, command_index: &mut usize, hints: &mut CommandHints, ) -> LayoutJob { let mut text = LayoutJob::default(); text.append( &time.format("%H:%M ").to_string(), 0.0, config.theme.format_dark(), ); match *name { COMMAND_MESSAGE_NAME => { if new { hints.reset_hint_added(); } let hints = &hints[*command_index]; *command_index += 1; let message_stripped = message .strip_prefix(COMMAND_MESSAGE_PREFIX) .unwrap_or(message); text.append(COMMAND_MESSAGE_PREFIX, 0.0, config.theme.format_dark()); // TODO: Handle more than just the first element if let Some(hint) = hints.first() { text.append( &message_stripped[..hint.span.start], 0., config.theme.format_text(), ); text.append( &message_stripped[hint.span.start..hint.span.end], 0., TextFormat { underline: Stroke::new(1.0, config.theme.error.to_color32()), ..config.theme.format_text() }, ); text.append( &message_stripped[hint.span.end..], 0., config.theme.format_text(), ); return text; } text.append(message_stripped, 0.0, config.theme.format_text()); text } COMMAND_RESULT_NAME => { text.append(COMMAND_RESULT_PREFIX, 0.0, config.theme.format_dark()); text.append( message .strip_prefix(COMMAND_RESULT_PREFIX) .unwrap_or(message), 0.0, config.theme.format_text(), ); text } _ => { text.append(level.as_str(), 0.0, config.theme.format_level(*level)); text.append(&format!(" {message}"), 0.0, config.theme.format_text()); text } } }
rust
Apache-2.0
98355f16b7d83ad0db983f2204426079780aa2ae
2026-01-04T20:24:35.637367Z
false
doonv/bevy_dev_console
https://github.com/doonv/bevy_dev_console/blob/98355f16b7d83ad0db983f2204426079780aa2ae/src/logging.rs
src/logging.rs
//! Custom [LogPlugin](bevy::log::LogPlugin) functionality. use bevy::log::{BoxedLayer, Level}; use bevy::prelude::*; use bevy::utils::tracing::Subscriber; use std::sync::mpsc; use tracing_subscriber::field::Visit; use tracing_subscriber::Layer; use web_time::SystemTime; /// A function that implements the log reading functionality for the /// developer console via [`LogPlugin::custom_layer`](bevy::log::LogPlugin::custom_layer). pub fn custom_log_layer(app: &mut App) -> Option<BoxedLayer> { Some(Box::new(create_custom_log_layer(app))) } fn create_custom_log_layer(app: &mut App) -> LogCaptureLayer { let (sender, receiver) = mpsc::channel(); app.add_event::<LogMessage>(); app.insert_non_send_resource(CapturedLogEvents(receiver)); app.add_systems(PostUpdate, transfer_log_events); LogCaptureLayer { sender } } /// A [`tracing`](bevy::utils::tracing) log message event. /// /// This event is helpful for creating custom log viewing systems such as consoles and terminals. #[derive(Event, Debug, Clone)] pub(crate) struct LogMessage { /// The message contents. pub message: String, /// The name of the span described by this metadata. pub name: &'static str, /// The part of the system that the span that this /// metadata describes occurred in. pub target: &'static str, /// The level of verbosity of the described span. pub level: Level, /// The name of the Rust module where the span occurred, /// or `None` if this could not be determined. pub module_path: Option<&'static str>, /// The name of the source code file where the span occurred, /// or `None` if this could not be determined. pub file: Option<&'static str>, /// The line number in the source code file where the span occurred, /// or `None` if this could not be determined. pub line: Option<u32>, /// The time the log occurred. pub time: SystemTime, } /// Transfers information from the [`CapturedLogEvents`] resource to [`Events<LogMessage>`](LogMessage). fn transfer_log_events( receiver: NonSend<CapturedLogEvents>, mut log_events: EventWriter<LogMessage>, ) { log_events.send_batch(receiver.0.try_iter()); } /// This struct temporarily stores [`LogMessage`]s before they are /// written to [`EventWriter<LogMessage>`] by [`transfer_log_events`]. struct CapturedLogEvents(mpsc::Receiver<LogMessage>); /// A [`Layer`] that captures log events and saves them to [`CapturedLogEvents`]. struct LogCaptureLayer { sender: mpsc::Sender<LogMessage>, } impl<S: Subscriber> Layer<S> for LogCaptureLayer { fn on_event( &self, event: &bevy::utils::tracing::Event<'_>, _ctx: tracing_subscriber::layer::Context<'_, S>, ) { let mut message = None; event.record(&mut LogEventVisitor(&mut message)); if let Some(message) = message { let metadata = event.metadata(); self.sender .send(LogMessage { message, name: metadata.name(), target: metadata.target(), level: *metadata.level(), module_path: metadata.module_path(), file: metadata.file(), line: metadata.line(), time: SystemTime::now(), }) .expect("CapturedLogEvents resource no longer exists!"); } } } /// A [`Visit`]or that records log messages that are transferred to [`LogCaptureLayer`]. struct LogEventVisitor<'a>(&'a mut Option<String>); impl Visit for LogEventVisitor<'_> { fn record_debug( &mut self, field: &bevy::utils::tracing::field::Field, value: &dyn std::fmt::Debug, ) { // Only log out messages if field.name() == "message" { *self.0 = Some(format!("{value:?}")); } } }
rust
Apache-2.0
98355f16b7d83ad0db983f2204426079780aa2ae
2026-01-04T20:24:35.637367Z
false
doonv/bevy_dev_console
https://github.com/doonv/bevy_dev_console/blob/98355f16b7d83ad0db983f2204426079780aa2ae/src/builtin_parser/lexer.rs
src/builtin_parser/lexer.rs
//! Generates a stream of tokens from a string. use logos::{Lexer, Logos, Span}; #[derive(Debug, Clone, Default, PartialEq)] pub struct FailedToLexCharacter; #[derive(Logos, Debug, Clone, PartialEq)] #[logos(skip r"[ \t\n\f]+", error = FailedToLexCharacter)] pub enum Token { #[token("(")] LeftParen, #[token(")")] RightParen, #[token("{")] LeftBracket, #[token("}")] RightBracket, #[token("[")] LeftBrace, #[token("]")] RightBrace, #[token("=")] Equals, #[token("+")] Plus, #[token("-")] Minus, #[token("/")] Slash, #[token("*")] Asterisk, #[token("%")] Modulo, #[token(".", priority = 10)] Dot, #[token("&")] Ampersand, #[token("loop")] Loop, #[token("for")] For, #[token("while")] While, #[token("in")] In, #[token(":")] Colon, #[token(";")] SemiColon, #[token(",")] Comma, #[token("true")] True, #[token("false")] False, #[regex(r#""(\\[\\"]|[^"])*""#)] String, #[regex("[a-zA-Z_][a-zA-Z0-9_]*")] Identifier, #[regex(r#"[0-9]+"#)] IntegerNumber, #[regex(r#"[0-9]+\.[0-9]*"#)] FloatNumber, #[token("i8")] #[token("i16")] #[token("i32")] #[token("i64")] #[token("isize")] #[token("u8")] #[token("u16")] #[token("u32")] #[token("u64")] #[token("usize")] #[token("f32")] #[token("f64")] NumberType, } /// A wrapper for the lexer which provides token peeking and other helper functions #[derive(Debug)] pub struct TokenStream<'a> { lexer: Lexer<'a, Token>, next: Option<Result<Token, FailedToLexCharacter>>, current_slice: &'a str, current_span: Span, } impl<'a> TokenStream<'a> { /// Creates a new [`TokenStream`] from `src`. pub fn new(src: &'a str) -> Self { let mut lexer = Token::lexer(src); let current_slice = lexer.slice(); let current_span = lexer.span(); let next = lexer.next(); Self { lexer, next, current_slice, current_span, } } /// Returns the next [`Token`] and advances the iterator pub fn next(&mut self) -> Option<Result<Token, FailedToLexCharacter>> { let val = self.next.take(); self.current_slice = self.lexer.slice(); self.current_span = self.lexer.span(); self.next = self.lexer.next(); val } // pub fn next_pe(&mut self) -> Result<Token, ParseError> { // let token = self.next(); // self.to_parse_error(token) // } // pub fn to_parse_error( // &mut self, // token: Option<Result<Token, FailedToLexCharacter>>, // ) -> Result<Token, ParseError> { // Ok(token // .ok_or(ParseError::ExpectedMoreTokens(self.span()))? // .map_err(|FailedToLexCharacter| ParseError::FailedToLexCharacter(self.span()))?) // } /// Returns a reference to next [`Token`] without advancing the iterator #[inline] #[must_use] pub fn peek(&self) -> &Option<Result<Token, FailedToLexCharacter>> { &self.next } /// Get the range for the current [`Token`] in `Source`. #[inline] #[must_use] pub fn span(&self) -> Span { self.current_span.clone() } /// Get a [`str`] slice of the current [`Token`]. #[inline] #[must_use] pub fn slice(&self) -> &str { self.current_slice } /// Get a [`str`] slice of the next [`Token`]. #[inline] #[must_use] pub fn peek_slice(&self) -> &str { self.lexer.slice() } /// Get a [`Span`] of the next [`Token`]. #[inline] #[must_use] pub fn peek_span(&self) -> Span { self.lexer.span() } } impl Iterator for TokenStream<'_> { type Item = Result<Token, FailedToLexCharacter>; #[inline] fn next(&mut self) -> Option<Result<Token, FailedToLexCharacter>> { self.next() } } #[cfg(test)] mod tests { use super::{Token, TokenStream}; #[test] fn var_assign() { let mut lexer = TokenStream::new("x = 1 + 2 - 30.6"); assert_eq!(lexer.next(), Some(Ok(Token::Identifier))); assert_eq!(lexer.slice(), "x"); assert_eq!(lexer.next(), Some(Ok(Token::Equals))); assert_eq!(lexer.slice(), "="); assert_eq!(lexer.next(), Some(Ok(Token::IntegerNumber))); assert_eq!(lexer.slice(), "1"); assert_eq!(lexer.next(), Some(Ok(Token::Plus))); assert_eq!(lexer.slice(), "+"); assert_eq!(lexer.next(), Some(Ok(Token::IntegerNumber))); assert_eq!(lexer.slice(), "2"); assert_eq!(lexer.next(), Some(Ok(Token::Minus))); assert_eq!(lexer.slice(), "-"); assert_eq!(lexer.next(), Some(Ok(Token::FloatNumber))); assert_eq!(lexer.slice(), "30.6"); } }
rust
Apache-2.0
98355f16b7d83ad0db983f2204426079780aa2ae
2026-01-04T20:24:35.637367Z
false