Dataset Viewer
Auto-converted to Parquet Duplicate
hexsha
stringlengths
40
40
size
int64
32
998k
ext
stringclasses
1 value
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
6
206
max_stars_repo_name
stringlengths
6
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
sequencelengths
1
6
max_stars_count
float64
1
368k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
6
206
max_issues_repo_name
stringlengths
6
110
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
sequencelengths
1
6
max_issues_count
float64
1
77k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
6
206
max_forks_repo_name
stringlengths
6
110
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
sequencelengths
1
6
max_forks_count
float64
1
28.6k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
32
998k
avg_line_length
float64
5.99
517
max_line_length
int64
15
222k
alphanum_fraction
float64
0.05
0.98
test_functions
sequencelengths
1
633
f700019f6cc8e4d84dab4aa28137258fd5f3bf7d
11,234
rs
Rust
src/impls/memory.rs
Zyian/rust-vfs
40fe15a947479054d98b8303f11db123ffd723cc
[ "Apache-2.0" ]
null
null
null
src/impls/memory.rs
Zyian/rust-vfs
40fe15a947479054d98b8303f11db123ffd723cc
[ "Apache-2.0" ]
null
null
null
src/impls/memory.rs
Zyian/rust-vfs
40fe15a947479054d98b8303f11db123ffd723cc
[ "Apache-2.0" ]
null
null
null
//! An ephemeral in-memory file system, intended mainly for unit tests use crate::{FileSystem, VfsFileType}; use crate::{SeekAndRead, VfsMetadata}; use crate::{VfsError, VfsResult}; use core::cmp; use std::collections::HashMap; use std::fmt; use std::fmt::{Debug, Formatter}; use std::io::{Cursor, Read, Seek, SeekFrom, Write}; use std::mem::swap; use std::sync::{Arc, RwLock}; type MemoryFsHandle = Arc<RwLock<MemoryFsImpl>>; /// An ephemeral in-memory file system, intended mainly for unit tests pub struct MemoryFS { handle: MemoryFsHandle, } impl Debug for MemoryFS { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { f.write_str("In Memory File System") } } impl MemoryFS { /// Create a new in-memory filesystem pub fn new() -> Self { MemoryFS { handle: Arc::new(RwLock::new(MemoryFsImpl::new())), } } fn ensure_has_parent(&self, path: &str) -> VfsResult<()> { let separator = path.rfind('/'); if let Some(index) = separator { if self.exists(&path[..index])? { return Ok(()); } } Err(VfsError::Other { message: format!("Parent path of {} does not exist", path), }) } } impl Default for MemoryFS { fn default() -> Self { Self::new() } } struct WritableFile { content: Cursor<Vec<u8>>, destination: String, fs: MemoryFsHandle, } impl Write for WritableFile { fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> { self.content.write(buf) } fn flush(&mut self) -> std::io::Result<()> { self.content.flush() } } impl Drop for WritableFile { fn drop(&mut self) { let mut content = vec![]; swap(&mut content, self.content.get_mut()); self.fs.write().unwrap().files.insert( self.destination.clone(), MemoryFile { file_type: VfsFileType::File, content: Arc::new(content), }, ); } } struct ReadableFile { #[allow(clippy::rc_buffer)] // to allow accessing the same object as writable content: Arc<Vec<u8>>, position: u64, } impl ReadableFile { fn len(&self) -> u64 { self.content.len() as u64 - self.position } } impl Read for ReadableFile { fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> { let amt = cmp::min(buf.len(), self.len() as usize); if amt == 1 { buf[0] = self.content[self.position as usize]; } else { buf[..amt].copy_from_slice( &self.content.as_slice()[self.position as usize..self.position as usize + amt], ); } self.position += amt as u64; Ok(amt) } } impl Seek for ReadableFile { fn seek(&mut self, pos: SeekFrom) -> std::io::Result<u64> { match pos { SeekFrom::Start(offset) => self.position = offset, SeekFrom::Current(offset) => self.position = (self.position as i64 + offset) as u64, SeekFrom::End(offset) => self.position = (self.content.len() as i64 + offset) as u64, } Ok(self.position) } } impl FileSystem for MemoryFS { fn read_dir(&self, path: &str) -> VfsResult<Box<dyn Iterator<Item = String>>> { let prefix = format!("{}/", path); let handle = self.handle.read().unwrap(); let mut found_directory = false; #[allow(clippy::needless_collect)] // need collect to satisfy lifetime requirements let entries: Vec<_> = handle .files .iter() .filter_map(|(candidate_path, _)| { if candidate_path == path { found_directory = true; } if candidate_path.starts_with(&prefix) { let rest = &candidate_path[prefix.len()..]; if !rest.contains('/') { return Some(rest.to_string()); } } None }) .collect(); if !found_directory { return Err(VfsError::FileNotFound { path: path.to_string(), }); } Ok(Box::new(entries.into_iter())) } fn create_dir(&self, path: &str) -> VfsResult<()> { self.ensure_has_parent(path)?; self.handle.write().unwrap().files.insert( path.to_string(), MemoryFile { file_type: VfsFileType::Directory, content: Default::default(), }, ); Ok(()) } fn open_file(&self, path: &str) -> VfsResult<Box<dyn SeekAndRead>> { let handle = self.handle.read().unwrap(); let file = handle .files .get(path) .ok_or_else(|| VfsError::FileNotFound { path: path.to_string(), })?; ensure_file(file)?; Ok(Box::new(ReadableFile { content: file.content.clone(), position: 0, })) } fn create_file(&self, path: &str) -> VfsResult<Box<dyn Write>> { self.ensure_has_parent(path)?; let content = Arc::new(Vec::<u8>::new()); self.handle.write().unwrap().files.insert( path.to_string(), MemoryFile { file_type: VfsFileType::File, content, }, ); let writer = WritableFile { content: Cursor::new(vec![]), destination: path.to_string(), fs: self.handle.clone(), }; Ok(Box::new(writer)) } fn append_file(&self, path: &str) -> VfsResult<Box<dyn Write>> { let handle = self.handle.write().unwrap(); let file = &handle.files[path]; let mut content = Cursor::new(file.content.as_ref().clone()); content.seek(SeekFrom::End(0))?; let writer = WritableFile { content, destination: path.to_string(), fs: self.handle.clone(), }; Ok(Box::new(writer)) } fn metadata(&self, path: &str) -> VfsResult<VfsMetadata> { let guard = self.handle.read().unwrap(); let files = &guard.files; let file = files.get(path).ok_or_else(|| VfsError::FileNotFound { path: path.to_string(), })?; Ok(VfsMetadata { file_type: file.file_type, len: file.content.len() as u64, }) } fn exists(&self, path: &str) -> VfsResult<bool> { Ok(self.handle.read().unwrap().files.contains_key(path)) } fn remove_file(&self, path: &str) -> VfsResult<()> { let mut handle = self.handle.write().unwrap(); handle .files .remove(path) .ok_or_else(|| VfsError::FileNotFound { path: path.to_string(), })?; Ok(()) } fn remove_dir(&self, path: &str) -> VfsResult<()> { if self.read_dir(path)?.next().is_some() { return Err(VfsError::Other { message: "Directory to remove is not empty".to_string(), }); } let mut handle = self.handle.write().unwrap(); handle .files .remove(path) .ok_or_else(|| VfsError::FileNotFound { path: path.to_string(), })?; Ok(()) } } struct MemoryFsImpl { files: HashMap<String, MemoryFile>, } impl MemoryFsImpl { pub fn new() -> Self { let mut files = HashMap::new(); // Add root directory files.insert( "".to_string(), MemoryFile { file_type: VfsFileType::Directory, content: Arc::new(vec![]), }, ); Self { files } } } struct MemoryFile { file_type: VfsFileType, #[allow(clippy::rc_buffer)] // to allow accessing the same object as writable content: Arc<Vec<u8>>, } #[cfg(test)] mod tests { use super::*; use crate::VfsPath; test_vfs!(MemoryFS::new()); #[test] fn write_and_read_file() -> VfsResult<()> { let root = VfsPath::new(MemoryFS::new()); let path = root.join("foobar.txt").unwrap(); let _send = &path as &dyn Send; { let mut file = path.create_file().unwrap(); write!(file, "Hello world").unwrap(); write!(file, "!").unwrap(); } { let mut file = path.open_file().unwrap(); let mut string: String = String::new(); file.read_to_string(&mut string).unwrap(); assert_eq!(string, "Hello world!"); } assert!(path.exists()?); assert!(!root.join("foo").unwrap().exists()?); let metadata = path.metadata().unwrap(); assert_eq!(metadata.len, 12); assert_eq!(metadata.file_type, VfsFileType::File); Ok(()) } #[test] fn append_file() { let root = VfsPath::new(MemoryFS::new()); let _string = String::new(); let path = root.join("test_append.txt").unwrap(); path.create_file().unwrap().write_all(b"Testing 1").unwrap(); path.append_file().unwrap().write_all(b"Testing 2").unwrap(); { let mut file = path.open_file().unwrap(); let mut string: String = String::new(); file.read_to_string(&mut string).unwrap(); assert_eq!(string, "Testing 1Testing 2"); } } #[test] fn create_dir() { let root = VfsPath::new(MemoryFS::new()); let _string = String::new(); let path = root.join("foo").unwrap(); path.create_dir().unwrap(); let metadata = path.metadata().unwrap(); assert_eq!(metadata.file_type, VfsFileType::Directory); } #[test] fn remove_dir_error_message() { let root = VfsPath::new(MemoryFS::new()); let path = root.join("foo").unwrap(); let result = path.remove_dir(); assert_eq!(format!("{}", result.unwrap_err()), "Could not remove directory '/foo', cause: The file or directory `/foo` could not be found"); } #[test] fn read_dir_error_message() { let root = VfsPath::new(MemoryFS::new()); let path = root.join("foo").unwrap(); let result = path.read_dir(); match result { Ok(_) => panic!("Error expected"), Err(err) => { assert_eq!(format!("{}", err), "Could not read directory '/foo', cause: The file or directory `/foo` could not be found"); } } } #[test] fn copy_file_across_filesystems() -> VfsResult<()> { let root_a = VfsPath::new(MemoryFS::new()); let root_b = VfsPath::new(MemoryFS::new()); let src = root_a.join("a.txt")?; let dest = root_b.join("b.txt")?; src.create_file()?.write_all(b"Hello World")?; src.copy_file(&dest)?; assert_eq!(&dest.read_to_string()?, "Hello World"); Ok(()) } } fn ensure_file(file: &MemoryFile) -> VfsResult<()> { if file.file_type != VfsFileType::File { return Err(VfsError::Other { message: "Not a file".to_string(), }); } Ok(()) }
29.798408
148
0.527951
[ "#[cfg(test)]\nmod tests {\n use super::*;\n #[test]\n fn write_and_read_file() -> VfsResult<()> {\n let root = VfsPath::new(MemoryFS::new());\n let path = root.join(\"foobar.txt\").unwrap();\n let _send = &path as &dyn Send;\n {\n let mut file = path.create_file().unwrap();\n write!(file, \"Hello world\").unwrap();\n write!(file, \"!\").unwrap();\n }\n {\n let mut file = path.open_file().unwrap();\n let mut string: String = String::new();\n file.read_to_string(&mut string).unwrap();\n assert_eq!(string, \"Hello world!\");\n }\n assert!(path.exists()?);\n assert!(!root.join(\"foo\").unwrap().exists()?);\n let metadata = path.metadata().unwrap();\n assert_eq!(metadata.len, 12);\n assert_eq!(metadata.file_type, VfsFileType::File);\n Ok(())\n }\n}", "#[cfg(test)]\nmod tests {\n use super::*;\n #[test]\n fn append_file() {\n let root = VfsPath::new(MemoryFS::new());\n let _string = String::new();\n let path = root.join(\"test_append.txt\").unwrap();\n path.create_file().unwrap().write_all(b\"Testing 1\").unwrap();\n path.append_file().unwrap().write_all(b\"Testing 2\").unwrap();\n {\n let mut file = path.open_file().unwrap();\n let mut string: String = String::new();\n file.read_to_string(&mut string).unwrap();\n assert_eq!(string, \"Testing 1Testing 2\");\n }\n }\n}", "#[cfg(test)]\nmod tests {\n use super::*;\n #[test]\n fn create_dir() {\n let root = VfsPath::new(MemoryFS::new());\n let _string = String::new();\n let path = root.join(\"foo\").unwrap();\n path.create_dir().unwrap();\n let metadata = path.metadata().unwrap();\n assert_eq!(metadata.file_type, VfsFileType::Directory);\n }\n}", "#[cfg(test)]\nmod tests {\n use super::*;\n #[test]\n fn remove_dir_error_message() {\n let root = VfsPath::new(MemoryFS::new());\n let path = root.join(\"foo\").unwrap();\n let result = path.remove_dir();\n assert_eq!(format!(\"{}\", result.unwrap_err()), \"Could not remove directory '/foo', cause: The file or directory `/foo` could not be found\");\n }\n}", "#[cfg(test)]\nmod tests {\n use super::*;\n #[test]\n fn read_dir_error_message() {\n let root = VfsPath::new(MemoryFS::new());\n let path = root.join(\"foo\").unwrap();\n let result = path.read_dir();\n match result {\n Ok(_) => panic!(\"Error expected\"),\n Err(err) => {\n assert_eq!(format!(\"{}\", err), \"Could not read directory '/foo', cause: The file or directory `/foo` could not be found\");\n }\n }\n }\n}", "#[cfg(test)]\nmod tests {\n use super::*;\n #[test]\n fn copy_file_across_filesystems() -> VfsResult<()> {\n let root_a = VfsPath::new(MemoryFS::new());\n let root_b = VfsPath::new(MemoryFS::new());\n let src = root_a.join(\"a.txt\")?;\n let dest = root_b.join(\"b.txt\")?;\n src.create_file()?.write_all(b\"Hello World\")?;\n src.copy_file(&dest)?;\n assert_eq!(&dest.read_to_string()?, \"Hello World\");\n Ok(())\n }\n}" ]
f700b4631291779bac31279265cd69455dcacb17
899
rs
Rust
src/ppu/control_register/spec_tests.rs
planet-s/rs-nes
d6e15726b30b17736df990762165d541b43394b7
[ "MIT" ]
103
2016-12-06T17:14:33.000Z
2021-09-09T16:42:24.000Z
src/ppu/control_register/spec_tests.rs
planet-s/rs-nes
d6e15726b30b17736df990762165d541b43394b7
[ "MIT" ]
15
2015-07-27T01:20:30.000Z
2019-01-20T20:42:56.000Z
src/ppu/control_register/spec_tests.rs
planet-s/rs-nes
d6e15726b30b17736df990762165d541b43394b7
[ "MIT" ]
3
2017-10-11T01:45:05.000Z
2020-07-24T07:58:57.000Z
use super::*; #[test] fn vram_addr_increment() { let ppu_ctrl = new_control_register(0b00000000); assert_eq!(IncrementAmount::One, ppu_ctrl.vram_addr_increment()); let ppu_ctrl = new_control_register(0b00000100); assert_eq!(IncrementAmount::ThirtyTwo, ppu_ctrl.vram_addr_increment()); } #[test] fn sprite_size() { let ppu_ctrl = new_control_register(0b00000000); assert_eq!(SpriteSize::X8, ppu_ctrl.sprite_size()); let ppu_ctrl = new_control_register(0b00100000); assert_eq!(SpriteSize::X16, ppu_ctrl.sprite_size()); } #[test] fn nmi_on_vblank_start() { let ppu_ctrl = new_control_register(0b00000000); assert_eq!(false, ppu_ctrl.nmi_on_vblank_start()); let ppu_ctrl = new_control_register(0b10000000); assert_eq!(true, ppu_ctrl.nmi_on_vblank_start()); } fn new_control_register(val: u8) -> ControlRegister { ControlRegister { reg: val } }
27.242424
75
0.734149
[ "#[cfg(test)]\nmod tests {\n use super::*;\n #[test]\n fn vram_addr_increment() {\n let ppu_ctrl = new_control_register(0b00000000);\n assert_eq!(IncrementAmount::One, ppu_ctrl.vram_addr_increment());\n\n let ppu_ctrl = new_control_register(0b00000100);\n assert_eq!(IncrementAmount::ThirtyTwo, ppu_ctrl.vram_addr_increment());\n}\n}", "#[cfg(test)]\nmod tests {\n use super::*;\n #[test]\n fn sprite_size() {\n let ppu_ctrl = new_control_register(0b00000000);\n assert_eq!(SpriteSize::X8, ppu_ctrl.sprite_size());\n\n let ppu_ctrl = new_control_register(0b00100000);\n assert_eq!(SpriteSize::X16, ppu_ctrl.sprite_size());\n}\n}", "#[cfg(test)]\nmod tests {\n use super::*;\n #[test]\n fn nmi_on_vblank_start() {\n let ppu_ctrl = new_control_register(0b00000000);\n assert_eq!(false, ppu_ctrl.nmi_on_vblank_start());\n\n let ppu_ctrl = new_control_register(0b10000000);\n assert_eq!(true, ppu_ctrl.nmi_on_vblank_start());\n}\n}" ]
f700b7fd9eddfed7dd46360828c9f9a5d963a15f
1,422
rs
Rust
crates/category/tests/find.rs
Nertsal/categories
3fd0a8b4f5c9a3df78c35126bb4af3a9ed10bae3
[ "MIT" ]
1
2021-11-14T14:33:37.000Z
2021-11-14T14:33:37.000Z
crates/category/tests/find.rs
Nertsal/categories
3fd0a8b4f5c9a3df78c35126bb4af3a9ed10bae3
[ "MIT" ]
11
2021-11-14T19:09:44.000Z
2022-03-23T17:08:52.000Z
crates/category/tests/find.rs
Nertsal/categories
3fd0a8b4f5c9a3df78c35126bb4af3a9ed10bae3
[ "MIT" ]
null
null
null
use category::constraint::ConstraintsBuilder; use category::prelude::*; use category::{Bindings, CategoryBuilder}; #[test] fn test_find() { let category = CategoryBuilder::<(), (), (), &str>::new() .object("A", vec![], ()) .object("B", vec![], ()) .object("AxB", vec![ObjectTag::Product("A", "B")], ()) .morphism("p1", "AxB", "A", vec![], ()) .morphism("p2", "AxB", "B", vec![], ()) .morphism("id", "AxB", "AxB", vec![MorphismTag::Identity("AxB")], ()) .build(); let constraints = ConstraintsBuilder::<&str>::new() .object("A", vec![]) .object("B", vec![]) .object("AxB", vec![ObjectTag::Product("A", "B")]) .morphism("p1", "AxB", "A", vec![]) .morphism("p2", "AxB", "B", vec![]) .object("C", vec![]) .morphism("f", "C", "A", vec![]) .morphism("g", "C", "B", vec![]) .morphism("m", "C", "AxB", vec![]) .equality(vec!["m", "p1"], vec!["f"]) .equality(vec!["m", "p2"], vec!["g"]) .build(); let candidates = category .find_candidates(&constraints, &Bindings::new()) .unwrap() .collect::<Vec<_>>(); println!("Candidates for:"); println!(" {constraints:?}"); println!("are:"); for (i, candidate) in candidates.iter().enumerate() { println!("{i:4}) {candidate:?}"); } assert_eq!(candidates.len(), 1); }
33.069767
77
0.483122
[ "#[cfg(test)]\nmod tests {\n use super::*;\n #[test]\n fn test_find() {\n let category = CategoryBuilder::<(), (), (), &str>::new()\n .object(\"A\", vec![], ())\n .object(\"B\", vec![], ())\n .object(\"AxB\", vec![ObjectTag::Product(\"A\", \"B\")], ())\n .morphism(\"p1\", \"AxB\", \"A\", vec![], ())\n .morphism(\"p2\", \"AxB\", \"B\", vec![], ())\n .morphism(\"id\", \"AxB\", \"AxB\", vec![MorphismTag::Identity(\"AxB\")], ())\n .build();\n\n let constraints = ConstraintsBuilder::<&str>::new()\n .object(\"A\", vec![])\n .object(\"B\", vec![])\n .object(\"AxB\", vec![ObjectTag::Product(\"A\", \"B\")])\n .morphism(\"p1\", \"AxB\", \"A\", vec![])\n .morphism(\"p2\", \"AxB\", \"B\", vec![])\n .object(\"C\", vec![])\n .morphism(\"f\", \"C\", \"A\", vec![])\n .morphism(\"g\", \"C\", \"B\", vec![])\n .morphism(\"m\", \"C\", \"AxB\", vec![])\n .equality(vec![\"m\", \"p1\"], vec![\"f\"])\n .equality(vec![\"m\", \"p2\"], vec![\"g\"])\n .build();\n let candidates = category\n .find_candidates(&constraints, &Bindings::new())\n .unwrap()\n .collect::<Vec<_>>();\n\n println!(\"Candidates for:\");\n println!(\" {constraints:?}\");\n println!(\"are:\");\n for (i, candidate) in candidates.iter().enumerate() {\n println!(\"{i:4}) {candidate:?}\");\n }\n\n assert_eq!(candidates.len(), 1);\n}\n}" ]
f700c24903be957b81cc4024bba608c4c4f3039a
4,655
rs
Rust
crypto-ws-client/tests/bybit.rs
xermicus/crypto-crawler-rs
d594bcdcd7aef1b3085dc3270ec398f089b4d66d
[ "Apache-2.0" ]
68
2020-12-31T07:13:11.000Z
2022-03-23T03:36:51.000Z
crypto-ws-client/tests/bybit.rs
xermicus/crypto-crawler-rs
d594bcdcd7aef1b3085dc3270ec398f089b4d66d
[ "Apache-2.0" ]
13
2021-11-11T19:53:06.000Z
2022-03-12T11:55:42.000Z
crypto-ws-client/tests/bybit.rs
xermicus/crypto-crawler-rs
d594bcdcd7aef1b3085dc3270ec398f089b4d66d
[ "Apache-2.0" ]
22
2021-01-02T14:14:14.000Z
2022-03-19T19:27:27.000Z
#[macro_use] mod utils; #[cfg(test)] mod bybit_inverse_future { use crypto_ws_client::{BybitInverseFutureWSClient, WSClient}; use std::sync::mpsc::{Receiver, Sender}; #[test] fn subscribe() { gen_test_code!( BybitInverseFutureWSClient, subscribe, &vec!["trade.BTCUSDZ21".to_string()] ); } #[test] fn subscribe_raw_json() { gen_test_code!( BybitInverseFutureWSClient, subscribe, &vec![r#"{"op":"subscribe","args":["trade.BTCUSDZ21"]}"#.to_string()] ); } #[test] fn subscribe_trade() { gen_test_code!( BybitInverseFutureWSClient, subscribe_trade, &vec!["BTCUSDZ21".to_string()] ); } #[test] fn subscribe_orderbook_topk() { gen_test_code!( BybitInverseFutureWSClient, subscribe_orderbook_topk, &vec!["BTCUSDZ21".to_string()] ); } #[test] fn subscribe_orderbook() { gen_test_code!( BybitInverseFutureWSClient, subscribe_orderbook, &vec!["BTCUSDZ21".to_string()] ); } #[test] fn subscribe_ticker() { gen_test_code!( BybitInverseFutureWSClient, subscribe_ticker, &vec!["BTCUSDZ21".to_string()] ); } #[test] fn subscribe_candlestick() { gen_test_subscribe_candlestick!( BybitInverseFutureWSClient, &vec![("BTCUSDZ21".to_string(), 60)] ); gen_test_subscribe_candlestick!( BybitInverseFutureWSClient, &vec![("BTCUSDZ21".to_string(), 2592000)] ); } } #[cfg(test)] mod bybit_inverse_swap { use crypto_ws_client::{BybitInverseSwapWSClient, WSClient}; use std::sync::mpsc::{Receiver, Sender}; #[test] fn subscribe() { gen_test_code!( BybitInverseSwapWSClient, subscribe, &vec!["trade.BTCUSD".to_string()] ); } #[test] fn subscribe_raw_json() { gen_test_code!( BybitInverseSwapWSClient, subscribe, &vec![r#"{"op":"subscribe","args":["trade.BTCUSD"]}"#.to_string()] ); } #[test] fn subscribe_trade() { gen_test_code!( BybitInverseSwapWSClient, subscribe_trade, &vec!["BTCUSD".to_string()] ); } #[test] fn subscribe_orderbook_topk() { gen_test_code!( BybitInverseSwapWSClient, subscribe_orderbook_topk, &vec!["BTCUSD".to_string()] ); } #[test] fn subscribe_orderbook() { gen_test_code!( BybitInverseSwapWSClient, subscribe_orderbook, &vec!["BTCUSD".to_string()] ); } #[test] fn subscribe_ticker() { gen_test_code!( BybitInverseSwapWSClient, subscribe_ticker, &vec!["BTCUSD".to_string()] ); } #[test] fn subscribe_candlestick() { gen_test_subscribe_candlestick!( BybitInverseSwapWSClient, &vec![("BTCUSD".to_string(), 60)] ); gen_test_subscribe_candlestick!( BybitInverseSwapWSClient, &vec![("BTCUSD".to_string(), 2592000)] ); } } #[cfg(test)] mod bybit_linear_swap { use crypto_ws_client::{BybitLinearSwapWSClient, WSClient}; use std::sync::mpsc::{Receiver, Sender}; #[test] fn subscribe_trade() { gen_test_code!( BybitLinearSwapWSClient, subscribe_trade, &vec!["BTCUSDT".to_string()] ); } #[test] fn subscribe_orderbook_topk() { gen_test_code!( BybitLinearSwapWSClient, subscribe_orderbook_topk, &vec!["BTCUSDT".to_string()] ); } #[test] fn subscribe_orderbook() { gen_test_code!( BybitLinearSwapWSClient, subscribe_orderbook, &vec!["BTCUSDT".to_string()] ); } #[test] fn subscribe_ticker() { gen_test_code!( BybitLinearSwapWSClient, subscribe_ticker, &vec!["BTCUSDT".to_string()] ); } #[test] fn subscribe_candlestick() { gen_test_subscribe_candlestick!( BybitLinearSwapWSClient, &vec![("BTCUSDT".to_string(), 60)] ); gen_test_subscribe_candlestick!( BybitLinearSwapWSClient, &vec![("BTCUSDT".to_string(), 2592000)] ); } }
23.159204
81
0.53319
[ "#[cfg(test)]\nmod tests {\n use super::*;\n #[test]\n fn subscribe() {\n gen_test_code!(\n BybitInverseFutureWSClient,\n subscribe,\n &vec![\"trade.BTCUSDZ21\".to_string()]\n );\n }\n}", "#[cfg(test)]\nmod tests {\n use super::*;\n #[test]\n fn subscribe_raw_json() {\n gen_test_code!(\n BybitInverseFutureWSClient,\n subscribe,\n &vec![r#\"{\"op\":\"subscribe\",\"args\":[\"trade.BTCUSDZ21\"]}\"#.to_string()]\n );\n }\n}", "#[cfg(test)]\nmod tests {\n use super::*;\n #[test]\n fn subscribe_trade() {\n gen_test_code!(\n BybitInverseFutureWSClient,\n subscribe_trade,\n &vec![\"BTCUSDZ21\".to_string()]\n );\n }\n}", "#[cfg(test)]\nmod tests {\n use super::*;\n #[test]\n fn subscribe_orderbook_topk() {\n gen_test_code!(\n BybitInverseFutureWSClient,\n subscribe_orderbook_topk,\n &vec![\"BTCUSDZ21\".to_string()]\n );\n }\n}", "#[cfg(test)]\nmod tests {\n use super::*;\n #[test]\n fn subscribe_orderbook() {\n gen_test_code!(\n BybitInverseFutureWSClient,\n subscribe_orderbook,\n &vec![\"BTCUSDZ21\".to_string()]\n );\n }\n}", "#[cfg(test)]\nmod tests {\n use super::*;\n #[test]\n fn subscribe_ticker() {\n gen_test_code!(\n BybitInverseFutureWSClient,\n subscribe_ticker,\n &vec![\"BTCUSDZ21\".to_string()]\n );\n }\n}", "#[cfg(test)]\nmod tests {\n use super::*;\n #[test]\n fn subscribe_candlestick() {\n gen_test_subscribe_candlestick!(\n BybitInverseFutureWSClient,\n &vec![(\"BTCUSDZ21\".to_string(), 60)]\n );\n gen_test_subscribe_candlestick!(\n BybitInverseFutureWSClient,\n &vec![(\"BTCUSDZ21\".to_string(), 2592000)]\n );\n }\n}", "#[cfg(test)]\nmod tests {\n use super::*;\n #[test]\n fn subscribe() {\n gen_test_code!(\n BybitInverseSwapWSClient,\n subscribe,\n &vec![\"trade.BTCUSD\".to_string()]\n );\n }\n}", "#[cfg(test)]\nmod tests {\n use super::*;\n #[test]\n fn subscribe_raw_json() {\n gen_test_code!(\n BybitInverseSwapWSClient,\n subscribe,\n &vec![r#\"{\"op\":\"subscribe\",\"args\":[\"trade.BTCUSD\"]}\"#.to_string()]\n );\n }\n}", "#[cfg(test)]\nmod tests {\n use super::*;\n #[test]\n fn subscribe_trade() {\n gen_test_code!(\n BybitInverseSwapWSClient,\n subscribe_trade,\n &vec![\"BTCUSD\".to_string()]\n );\n }\n}", "#[cfg(test)]\nmod tests {\n use super::*;\n #[test]\n fn subscribe_orderbook_topk() {\n gen_test_code!(\n BybitInverseSwapWSClient,\n subscribe_orderbook_topk,\n &vec![\"BTCUSD\".to_string()]\n );\n }\n}", "#[cfg(test)]\nmod tests {\n use super::*;\n #[test]\n fn subscribe_orderbook() {\n gen_test_code!(\n BybitInverseSwapWSClient,\n subscribe_orderbook,\n &vec![\"BTCUSD\".to_string()]\n );\n }\n}", "#[cfg(test)]\nmod tests {\n use super::*;\n #[test]\n fn subscribe_ticker() {\n gen_test_code!(\n BybitInverseSwapWSClient,\n subscribe_ticker,\n &vec![\"BTCUSD\".to_string()]\n );\n }\n}", "#[cfg(test)]\nmod tests {\n use super::*;\n #[test]\n fn subscribe_candlestick() {\n gen_test_subscribe_candlestick!(\n BybitInverseSwapWSClient,\n &vec![(\"BTCUSD\".to_string(), 60)]\n );\n gen_test_subscribe_candlestick!(\n BybitInverseSwapWSClient,\n &vec![(\"BTCUSD\".to_string(), 2592000)]\n );\n }\n}", "#[cfg(test)]\nmod tests {\n use super::*;\n #[test]\n fn subscribe_trade() {\n gen_test_code!(\n BybitLinearSwapWSClient,\n subscribe_trade,\n &vec![\"BTCUSDT\".to_string()]\n );\n }\n}", "#[cfg(test)]\nmod tests {\n use super::*;\n #[test]\n fn subscribe_orderbook_topk() {\n gen_test_code!(\n BybitLinearSwapWSClient,\n subscribe_orderbook_topk,\n &vec![\"BTCUSDT\".to_string()]\n );\n }\n}", "#[cfg(test)]\nmod tests {\n use super::*;\n #[test]\n fn subscribe_orderbook() {\n gen_test_code!(\n BybitLinearSwapWSClient,\n subscribe_orderbook,\n &vec![\"BTCUSDT\".to_string()]\n );\n }\n}", "#[cfg(test)]\nmod tests {\n use super::*;\n #[test]\n fn subscribe_ticker() {\n gen_test_code!(\n BybitLinearSwapWSClient,\n subscribe_ticker,\n &vec![\"BTCUSDT\".to_string()]\n );\n }\n}", "#[cfg(test)]\nmod tests {\n use super::*;\n #[test]\n fn subscribe_candlestick() {\n gen_test_subscribe_candlestick!(\n BybitLinearSwapWSClient,\n &vec![(\"BTCUSDT\".to_string(), 60)]\n );\n gen_test_subscribe_candlestick!(\n BybitLinearSwapWSClient,\n &vec![(\"BTCUSDT\".to_string(), 2592000)]\n );\n }\n}" ]
f700c3da5c347ccb3bff98f4b254376ca3b73b71
2,711
rs
Rust
tests/query.rs
SimonSapin/warp
6d21e73ac2de6205ee233e4287ff7b52f77b3664
[ "MIT" ]
null
null
null
tests/query.rs
SimonSapin/warp
6d21e73ac2de6205ee233e4287ff7b52f77b3664
[ "MIT" ]
null
null
null
tests/query.rs
SimonSapin/warp
6d21e73ac2de6205ee233e4287ff7b52f77b3664
[ "MIT" ]
null
null
null
#![deny(warnings)] extern crate warp; #[macro_use] extern crate serde_derive; use std::collections::HashMap; use warp::Filter; #[test] fn query() { let as_map = warp::query::<HashMap<String, String>>(); let req = warp::test::request().path("/?foo=bar&baz=quux"); let extracted = req.filter(&as_map).unwrap(); assert_eq!(extracted["foo"], "bar"); assert_eq!(extracted["baz"], "quux"); } #[test] fn query_struct() { let as_struct = warp::query::<MyArgs>(); let req = warp::test::request().path("/?foo=bar&baz=quux"); let extracted = req.filter(&as_struct).unwrap(); assert_eq!( extracted, MyArgs { foo: Some("bar".into()), baz: Some("quux".into()) } ); } #[test] fn empty_query_struct() { let as_struct = warp::query::<MyArgs>(); let req = warp::test::request().path("/?"); let extracted = req.filter(&as_struct).unwrap(); assert_eq!( extracted, MyArgs { foo: None, baz: None } ); } #[test] fn missing_query_struct() { let as_struct = warp::query::<MyArgs>(); let req = warp::test::request().path("/"); let extracted = req.filter(&as_struct).unwrap(); assert_eq!( extracted, MyArgs { foo: None, baz: None } ); } #[derive(Deserialize, Debug, Eq, PartialEq)] struct MyArgs { foo: Option<String>, baz: Option<String>, } #[test] fn required_query_struct() { let as_struct = warp::query::<MyRequiredArgs>(); let req = warp::test::request().path("/?foo=bar&baz=quux"); let extracted = req.filter(&as_struct).unwrap(); assert_eq!( extracted, MyRequiredArgs { foo: "bar".into(), baz: "quux".into() } ); } #[test] fn missing_required_query_struct_partial() { let as_struct = warp::query::<MyRequiredArgs>(); let req = warp::test::request().path("/?foo=something"); let extracted = req.filter(&as_struct); assert!(extracted.is_err()) } #[test] fn missing_required_query_struct_no_query() { let as_struct = warp::query::<MyRequiredArgs>().map(|_| warp::reply()); let req = warp::test::request().path("/"); let res = req.reply(&as_struct); assert_eq!(res.status(), 400); assert_eq!(res.body(), "Invalid query string"); } #[derive(Deserialize, Debug, Eq, PartialEq)] struct MyRequiredArgs { foo: String, baz: String, } #[test] fn raw_query() { let as_raw = warp::query::raw(); let req = warp::test::request().path("/?foo=bar&baz=quux"); let extracted = req.filter(&as_raw).unwrap(); assert_eq!(extracted, "foo=bar&baz=quux".to_owned()); }
21.515873
75
0.582811
[ "#[cfg(test)]\nmod tests {\n use super::*;\n #[test]\n fn query() {\n let as_map = warp::query::<HashMap<String, String>>();\n\n let req = warp::test::request().path(\"/?foo=bar&baz=quux\");\n\n let extracted = req.filter(&as_map).unwrap();\n assert_eq!(extracted[\"foo\"], \"bar\");\n assert_eq!(extracted[\"baz\"], \"quux\");\n}\n}", "#[cfg(test)]\nmod tests {\n use super::*;\n #[test]\n fn query_struct() {\n let as_struct = warp::query::<MyArgs>();\n\n let req = warp::test::request().path(\"/?foo=bar&baz=quux\");\n\n let extracted = req.filter(&as_struct).unwrap();\n assert_eq!(\n extracted,\n MyArgs {\n foo: Some(\"bar\".into()),\n baz: Some(\"quux\".into())\n }\n );\n}\n}", "#[cfg(test)]\nmod tests {\n use super::*;\n #[test]\n fn empty_query_struct() {\n let as_struct = warp::query::<MyArgs>();\n\n let req = warp::test::request().path(\"/?\");\n\n let extracted = req.filter(&as_struct).unwrap();\n assert_eq!(\n extracted,\n MyArgs {\n foo: None,\n baz: None\n }\n );\n}\n}", "#[cfg(test)]\nmod tests {\n use super::*;\n #[test]\n fn missing_query_struct() {\n let as_struct = warp::query::<MyArgs>();\n\n let req = warp::test::request().path(\"/\");\n\n let extracted = req.filter(&as_struct).unwrap();\n assert_eq!(\n extracted,\n MyArgs {\n foo: None,\n baz: None\n }\n );\n}\n}", "#[cfg(test)]\nmod tests {\n use super::*;\n #[test]\n fn required_query_struct() {\n let as_struct = warp::query::<MyRequiredArgs>();\n\n let req = warp::test::request().path(\"/?foo=bar&baz=quux\");\n\n let extracted = req.filter(&as_struct).unwrap();\n assert_eq!(\n extracted,\n MyRequiredArgs {\n foo: \"bar\".into(),\n baz: \"quux\".into()\n }\n );\n}\n}", "#[cfg(test)]\nmod tests {\n use super::*;\n #[test]\n fn missing_required_query_struct_partial() {\n let as_struct = warp::query::<MyRequiredArgs>();\n\n let req = warp::test::request().path(\"/?foo=something\");\n\n let extracted = req.filter(&as_struct);\n assert!(extracted.is_err())\n}\n}", "#[cfg(test)]\nmod tests {\n use super::*;\n #[test]\n fn missing_required_query_struct_no_query() {\n let as_struct = warp::query::<MyRequiredArgs>().map(|_| warp::reply());\n\n let req = warp::test::request().path(\"/\");\n\n let res = req.reply(&as_struct);\n assert_eq!(res.status(), 400);\n assert_eq!(res.body(), \"Invalid query string\");\n}\n}", "#[cfg(test)]\nmod tests {\n use super::*;\n #[test]\n fn raw_query() {\n let as_raw = warp::query::raw();\n\n let req = warp::test::request().path(\"/?foo=bar&baz=quux\");\n\n let extracted = req.filter(&as_raw).unwrap();\n assert_eq!(extracted, \"foo=bar&baz=quux\".to_owned());\n}\n}" ]
f7010908986b983516c0c14e2e8db609547e7532
1,376
rs
Rust
rust-playground/unionfind/src/quickfind.rs
sravyapulavarthi/algorithm-playground
331fd3eeb4459afe871c36d80f8d01e5002e747a
[ "MIT" ]
85
2017-12-19T19:51:51.000Z
2021-05-26T20:00:39.000Z
rust-playground/unionfind/src/quickfind.rs
sangeetha77/algorithm-playground
331fd3eeb4459afe871c36d80f8d01e5002e747a
[ "MIT" ]
1
2019-01-02T07:00:40.000Z
2019-01-02T07:00:40.000Z
rust-playground/unionfind/src/quickfind.rs
sangeetha77/algorithm-playground
331fd3eeb4459afe871c36d80f8d01e5002e747a
[ "MIT" ]
34
2018-03-29T11:51:53.000Z
2020-11-17T08:24:51.000Z
use UnionFind; #[derive(Debug)] pub struct QuickFind { pub n: usize, pub id: Vec<usize>, } impl UnionFind for QuickFind { fn new(n: usize) -> Self { let id: Vec<usize> = (0..n).collect(); QuickFind { n, id } } fn connected(&mut self, p: usize, q: usize) -> bool { self.id[p] == self.id[q] } fn union(&mut self, p: usize, q:usize) { if self.connected(p, q) { return; } let id_p = self.id[p]; for k in 0..self.n { if self.id[k] == id_p { self.id[k] = self.id[q]; } } } } #[cfg(test)] mod test { use super::*; #[test] fn test_simple_connected() { let mut q = QuickFind::new(10); let i = q.connected(4, 7); let j = q.connected(3, 6); let k = q.connected(1, 2); assert!(!i); assert!(!j); assert!(!k); } #[test] fn test_simple_union() { let mut q = QuickFind::new(10); q.union(4, 3); assert_eq!(q.id, vec![0, 1, 2, 3, 3, 5, 6, 7, 8, 9]); q.union(3, 8); assert_eq!(q.id, vec![0, 1, 2, 8, 8, 5, 6, 7, 8, 9]); let i = q.connected(4, 3); let j = q.connected(8, 3); let k = q.connected(4, 8); assert!(i); assert!(j); assert!(k); } }
19.380282
61
0.43968
[ "#[cfg(test)]\nmod tests {\n use super::*;\n #[test]\n fn test_simple_connected() {\n\n let mut q = QuickFind::new(10);\n \n let i = q.connected(4, 7);\n let j = q.connected(3, 6);\n let k = q.connected(1, 2);\n \n assert!(!i);\n assert!(!j);\n assert!(!k);\n }\n}", "#[cfg(test)]\nmod tests {\n use super::*;\n #[test]\n fn test_simple_union() {\n\n let mut q = QuickFind::new(10);\n\n q.union(4, 3);\n assert_eq!(q.id, vec![0, 1, 2, 3, 3, 5, 6, 7, 8, 9]);\n\n q.union(3, 8);\n assert_eq!(q.id, vec![0, 1, 2, 8, 8, 5, 6, 7, 8, 9]);\n\n let i = q.connected(4, 3);\n let j = q.connected(8, 3);\n let k = q.connected(4, 8);\n\n assert!(i);\n assert!(j);\n assert!(k);\n }\n}" ]
f7011be990eed39c7e23a73ecec42804e16e4392
4,748
rs
Rust
src/tests.rs
xemwebe/argmin
77697603314afac948a6603f870f1ae32f05e2e1
[ "Apache-2.0", "MIT" ]
null
null
null
src/tests.rs
xemwebe/argmin
77697603314afac948a6603f870f1ae32f05e2e1
[ "Apache-2.0", "MIT" ]
null
null
null
src/tests.rs
xemwebe/argmin
77697603314afac948a6603f870f1ae32f05e2e1
[ "Apache-2.0", "MIT" ]
null
null
null
// Copyright 2019-2020 argmin developers // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according to those terms. #![allow(non_snake_case)] use approx::assert_relative_eq; use ndarray::prelude::*; use ndarray::{Array1, Array2}; use crate::prelude::*; use crate::solver::gradientdescent::SteepestDescent; use crate::solver::linesearch::{HagerZhangLineSearch, MoreThuenteLineSearch}; use crate::solver::newton::NewtonCG; use crate::solver::quasinewton::{BFGS, DFP, LBFGS}; #[cfg(feature = "serde1")] use serde::{Deserialize, Serialize}; #[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))] #[derive(Clone, Default, Debug)] struct MaxEntropy { F: Array2<f64>, K: Array1<f64>, param_opt: Array1<f64>, param_init: Array1<f64>, } /// Base test case for a simple constrained entropy maximization problem /// (the machine translation example of Berger et al in /// Computational Linguistics, vol 22, num 1, pp 39--72, 1996.) /// /// Adapted from scipy.optimize.test.test_optimize impl MaxEntropy { fn new() -> MaxEntropy { let F: Array2<f64> = arr2(&[ [1., 1., 1.], [1., 1., 0.], [1., 0., 1.], [1., 0., 0.], [1., 0., 0.], ]); let K: Array1<f64> = arr1(&[1., 0.3, 0.5]); let param_opt: Array1<f64> = arr1(&[0., -0.524869316, 0.487525860]); let param_init: Array1<f64> = arr1(&[0.0, 0.0, 0.0]); MaxEntropy { F, K, param_opt, param_init, } } } impl ArgminOp for MaxEntropy { type Param = Array1<f64>; type Output = f64; type Hessian = Array2<f64>; type Jacobian = (); fn apply(&self, p: &Self::Param) -> Result<Self::Output, Error> { let log_pdot = self.F.dot(&p.t()); let log_z = log_pdot.mapv(|x| x.exp()).sum().ln(); let loss = log_z - self.K.dot(&p.t()); Ok(loss) } fn gradient(&self, p: &Self::Param) -> Result<Self::Param, Error> { let log_pdot = self.F.dot(&p.t()); let log_z = log_pdot.mapv(|x| x.exp()).sum().ln(); let y = (log_pdot - log_z).mapv(|x| x.exp()); let grad = self.F.clone().t().dot(&y) - self.K.clone(); Ok(grad) } fn hessian(&self, p: &Self::Param) -> Result<Self::Hessian, Error> { let log_pdot = self.F.dot(&p.t()); let log_z = log_pdot.mapv(|x| x.exp()).sum().ln(); let y = (log_pdot - log_z).mapv(|x| x.exp()); // TODO: replace with Array2::from_diag when it is available // ndarray#673 let mut y2_diag = Array2::zeros((y.len(), y.len())); y2_diag.diag_mut().assign(&y); let tmp = self.F.clone() - self.F.clone().t().dot(&y); let hess = self.F.clone().t().dot(&y2_diag.dot(&tmp)); Ok(hess) } } macro_rules! entropy_max_tests { ($($name:ident: $solver:expr,)*) => { $( #[test] fn $name() { let cost = MaxEntropy::new(); let res = Executor::new(cost.clone(), $solver, cost.param_init.clone()) .max_iters(100) .run() .unwrap(); assert_relative_eq!( cost.apply(&res.state.param).unwrap(), cost.apply(&cost.param_opt).unwrap(), epsilon = 1e-6 ); } )* } } entropy_max_tests! { test_max_entropy_lbfgs_morethuente: LBFGS::new(MoreThuenteLineSearch::new(), 10), test_max_entropy_lbfgs_hagerzhang: LBFGS::new(HagerZhangLineSearch::new(), 10), test_max_entropy_bfgs: BFGS::new(Array2::eye(3), MoreThuenteLineSearch::new()), test_max_entropy_dfp: DFP::new(Array2::eye(3), MoreThuenteLineSearch::new()), test_max_entropy_newton_cg: NewtonCG::new(MoreThuenteLineSearch::new()), test_max_entropy_steepest_descent: SteepestDescent::new(MoreThuenteLineSearch::new()), } #[test] fn test_lbfgs_func_count() { let cost = MaxEntropy::new(); let linesearch = MoreThuenteLineSearch::new(); let solver = LBFGS::new(linesearch, 10); let res = Executor::new(cost.clone(), solver, cost.param_init.clone()) .max_iters(100) .run() .unwrap(); assert_relative_eq!( cost.apply(&res.state.param).unwrap(), cost.apply(&cost.param_opt).unwrap(), epsilon = 1e-6 ); // Check the number of cost function evaluation and gradient // evaluation with that in scipy assert!(res.state.cost_func_count <= 7); // The following value is 5 in scipy.optimize, but the convergence // criteria is different assert!(res.state.grad_func_count <= 6); }
32.29932
91
0.606361
[ "#[cfg(test)]\nmod tests {\n use super::*;\n #[test]\n fn test_lbfgs_func_count() {\n let cost = MaxEntropy::new();\n\n let linesearch = MoreThuenteLineSearch::new();\n let solver = LBFGS::new(linesearch, 10);\n let res = Executor::new(cost.clone(), solver, cost.param_init.clone())\n .max_iters(100)\n .run()\n .unwrap();\n\n assert_relative_eq!(\n cost.apply(&res.state.param).unwrap(),\n cost.apply(&cost.param_opt).unwrap(),\n epsilon = 1e-6\n );\n\n // Check the number of cost function evaluation and gradient\n // evaluation with that in scipy\n assert!(res.state.cost_func_count <= 7);\n // The following value is 5 in scipy.optimize, but the convergence\n // criteria is different\n assert!(res.state.grad_func_count <= 6);\n}\n}" ]
f7016ec1c8cf24eecaa5a0e4f950b5a2a20954df
1,377
rs
Rust
tests/expectations/tests/ctypes-prefix-path.rs
JRF63/rust-bindgen
cb8266620596222b1cd9dbe6551cc1e3e8bb7f72
[ "BSD-3-Clause" ]
1
2021-01-07T18:48:18.000Z
2021-01-07T18:48:18.000Z
tests/expectations/tests/ctypes-prefix-path.rs
JRF63/rust-bindgen
cb8266620596222b1cd9dbe6551cc1e3e8bb7f72
[ "BSD-3-Clause" ]
3
2016-05-31T14:38:04.000Z
2016-07-18T21:18:09.000Z
tests/expectations/tests/ctypes-prefix-path.rs
JRF63/rust-bindgen
cb8266620596222b1cd9dbe6551cc1e3e8bb7f72
[ "BSD-3-Clause" ]
2
2016-05-30T18:46:14.000Z
2016-06-01T08:14:25.000Z
/* automatically generated by rust-bindgen */ #![allow( dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals )] #![no_std] mod libc { pub mod foo { pub type c_int = i32; pub enum c_void {} } } #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct foo { pub a: libc::foo::c_int, pub b: libc::foo::c_int, pub bar: *mut libc::foo::c_void, } #[test] fn bindgen_test_layout_foo() { assert_eq!( ::core::mem::size_of::<foo>(), 16usize, concat!("Size of: ", stringify!(foo)) ); assert_eq!( ::core::mem::align_of::<foo>(), 8usize, concat!("Alignment of ", stringify!(foo)) ); assert_eq!( unsafe { &(*(::core::ptr::null::<foo>())).a as *const _ as usize }, 0usize, concat!("Offset of field: ", stringify!(foo), "::", stringify!(a)) ); assert_eq!( unsafe { &(*(::core::ptr::null::<foo>())).b as *const _ as usize }, 4usize, concat!("Offset of field: ", stringify!(foo), "::", stringify!(b)) ); assert_eq!( unsafe { &(*(::core::ptr::null::<foo>())).bar as *const _ as usize }, 8usize, concat!("Offset of field: ", stringify!(foo), "::", stringify!(bar)) ); } impl Default for foo { fn default() -> Self { unsafe { ::core::mem::zeroed() } } }
24.157895
77
0.525054
[ "#[cfg(test)]\nmod tests {\n use super::*;\n #[test]\n fn bindgen_test_layout_foo() {\n assert_eq!(\n ::core::mem::size_of::<foo>(),\n 16usize,\n concat!(\"Size of: \", stringify!(foo))\n );\n assert_eq!(\n ::core::mem::align_of::<foo>(),\n 8usize,\n concat!(\"Alignment of \", stringify!(foo))\n );\n assert_eq!(\n unsafe { &(*(::core::ptr::null::<foo>())).a as *const _ as usize },\n 0usize,\n concat!(\"Offset of field: \", stringify!(foo), \"::\", stringify!(a))\n );\n assert_eq!(\n unsafe { &(*(::core::ptr::null::<foo>())).b as *const _ as usize },\n 4usize,\n concat!(\"Offset of field: \", stringify!(foo), \"::\", stringify!(b))\n );\n assert_eq!(\n unsafe { &(*(::core::ptr::null::<foo>())).bar as *const _ as usize },\n 8usize,\n concat!(\"Offset of field: \", stringify!(foo), \"::\", stringify!(bar))\n );\n}\n}" ]
f701853727620eb267dc35f65b9a824f16eacb7c
1,016
rs
Rust
tests/match.rs
tcr/hoodlum
e0e1416ecea7ec58a71bcdd7571afe3e426af4b1
[ "Apache-2.0", "MIT" ]
102
2016-08-19T13:02:42.000Z
2022-03-04T22:09:57.000Z
tests/match.rs
tcr/hoodlum
e0e1416ecea7ec58a71bcdd7571afe3e426af4b1
[ "Apache-2.0", "MIT" ]
30
2016-11-04T21:49:29.000Z
2018-11-16T14:29:33.000Z
tests/match.rs
tcr/hoodlum
e0e1416ecea7ec58a71bcdd7571afe3e426af4b1
[ "Apache-2.0", "MIT" ]
5
2016-10-17T07:06:51.000Z
2020-01-23T00:48:57.000Z
extern crate hoodlum; use hoodlum::*; #[test] fn match_or() { let code = r#" match a { 0 | 1 => { } _ => { } } "#; let valid = r#" case (a) 0, 1: begin end default: begin end endcase "#; let res = parse_results(code, hoodlum::hdl_parser::parse_SeqStatement(code)); let out = res.to_verilog(&Default::default()); assert_eq!(out.trim(), valid.trim()); } //TODO #[ignore] #[test] #[should_panic] fn match_without_default() { let code = r#" match a { 0 => { } 1 => { } } "#; let _ = parse_results(code, hoodlum::hdl_parser::parse_SeqStatement(code)); } //TODO #[ignore] #[test] fn match_expr() { let code = r#" match a { 0 => a <= 1, 1 => a <= 2, 2 => a <= 0, } "#; let valid = r#" case (a) 0, 1: begin end default: begin end endcase "#; let res = parse_results(code, hoodlum::hdl_parser::parse_SeqStatement(code)); let out = res.to_verilog(&Default::default()); assert_eq!(out.trim(), valid.trim()); }
14.941176
81
0.556102
[ "#[cfg(test)]\nmod tests {\n use super::*;\n #[test]\n fn match_or() {\n let code = r#\"\nmatch a {\n 0 | 1 => { }\n _ => { }\n}\n\"#;\n\n let valid = r#\"\ncase (a)\n 0, 1: begin\n end\n default: begin\n end\nendcase\n\"#;\n\n let res = parse_results(code, hoodlum::hdl_parser::parse_SeqStatement(code));\n let out = res.to_verilog(&Default::default());\n assert_eq!(out.trim(), valid.trim());\n}\n}", "#[cfg(test)]\nmod tests {\n use super::*;\n #[test]\n fn match_without_default() {\n let code = r#\"\nmatch a {\n 0 => { }\n 1 => { }\n}\n\"#;\n\n let _ = parse_results(code, hoodlum::hdl_parser::parse_SeqStatement(code));\n}\n}", "#[cfg(test)]\nmod tests {\n use super::*;\n #[test]\n fn match_expr() {\n let code = r#\"\nmatch a {\n 0 => a <= 1,\n 1 => a <= 2,\n 2 => a <= 0,\n}\n\"#;\n\n let valid = r#\"\ncase (a)\n 0, 1: begin\n end\n default: begin\n end\nendcase\n\"#;\n\n let res = parse_results(code, hoodlum::hdl_parser::parse_SeqStatement(code));\n let out = res.to_verilog(&Default::default());\n assert_eq!(out.trim(), valid.trim());\n}\n}" ]
f70194552609ff6af8171b4e07459adf6d772449
13,731
rs
Rust
amethyst_rendy/src/batch.rs
lambdaxymox/amethyst
698ca6736f5a35cfed9ee73fccce1780e783ea4c
[ "MIT" ]
null
null
null
amethyst_rendy/src/batch.rs
lambdaxymox/amethyst
698ca6736f5a35cfed9ee73fccce1780e783ea4c
[ "MIT" ]
null
null
null
amethyst_rendy/src/batch.rs
lambdaxymox/amethyst
698ca6736f5a35cfed9ee73fccce1780e783ea4c
[ "MIT" ]
null
null
null
//! Module containing structures useful for batching draw calls //! in scenarios with various known assumptions, e.g. order independence. use std::{ collections::hash_map::Entry, iter::{Extend, FromIterator}, ops::Range, }; use derivative::Derivative; use smallvec::{smallvec, SmallVec}; #[cfg(feature = "profiler")] use thread_profiler::profile_scope; use crate::util::TapCountIter; /// Iterator trait for grouping iterated 2-tuples `(K, V)` by contiguous ranges with equal `K`, /// providing access in a group-by-group manner. pub trait GroupIterator<K, V> where Self: Iterator<Item = (K, V)> + Sized, K: PartialEq, { /// Perform grouping. Evaluates passed closure on every next /// contiguous list of data with same group identifier. fn for_each_group<F>(self, on_group: F) where F: FnMut(K, &mut Vec<V>); } // This would be an iterator adaptor if `Item` type would allow a borrow on iterator itself. // FIXME: Implement once `StreamingIterator` is a thing. impl<K, V, I> GroupIterator<K, V> for I where K: PartialEq, I: Iterator<Item = (K, V)>, { fn for_each_group<F>(self, mut on_group: F) where F: FnMut(K, &mut Vec<V>), { #[cfg(feature = "profiler")] profile_scope!("for_each_group"); let mut block: Option<(K, Vec<V>)> = None; for (next_group_id, value) in self { match &mut block { slot @ None => { let mut group_buffer = Vec::with_capacity(64); group_buffer.push(value); slot.replace((next_group_id, group_buffer)); } Some((group_id, group_buffer)) if group_id == &next_group_id => { group_buffer.push(value); } Some((group_id, ref mut group_buffer)) => { let submitted_group_id = std::mem::replace(group_id, next_group_id); on_group(submitted_group_id, group_buffer); group_buffer.clear(); group_buffer.push(value); } } } if let Some((group_id, mut group_buffer)) = block.take() { on_group(group_id, &mut group_buffer); } } } /// Batching implementation which provides two levels of indirection and grouping for a given batch. /// This batch method is used, for example, batching meshes and textures; for any given draw call, /// a user would want to batch all draws using a specific texture together, and then also group all /// draw calls for a specific mesh together. /// /// `PK` - First level of batch grouping /// `SK` - Secondary level of batch grouping /// `C` - the actual final type being batched. /// /// Internally, this batch type is implemented using a `FnvHashMap` for its outer primary batching /// layer. The inner layer is then implemented as a tuple indexed `SmallVec`. #[derive(Derivative, Debug)] #[derivative(Default(bound = ""))] pub struct TwoLevelBatch<PK, SK, C> where PK: Eq + std::hash::Hash, { map: fnv::FnvHashMap<PK, SmallVec<[(SK, C); 1]>>, data_count: usize, } impl<PK, SK, C> TwoLevelBatch<PK, SK, C> where PK: Eq + std::hash::Hash, SK: PartialEq, C: IntoIterator, C: FromIterator<<C as IntoIterator>::Item>, C: Extend<<C as IntoIterator>::Item>, { /// Clears all batch data. pub fn clear_inner(&mut self) { self.data_count = 0; for (_, data) in self.map.iter_mut() { data.clear(); } } /// Removes empty batch indices from internal storage. pub fn prune(&mut self) { self.map.retain(|_, b| !b.is_empty()); } /// Inserts a set of batch items. pub fn insert(&mut self, pk: PK, sk: SK, data: impl IntoIterator<Item = C::Item>) { #[cfg(feature = "profiler")] profile_scope!("twolevel_insert"); let instance_data = data.into_iter().tap_count(&mut self.data_count); match self.map.entry(pk) { Entry::Occupied(mut e) => { let e = e.get_mut(); // scan for the same key to try to combine batches. // Scanning limited slots to limit complexity. if let Some(batch) = e.iter_mut().take(8).find(|(k, _)| k == &sk) { batch.1.extend(instance_data); } else { e.push((sk, instance_data.collect())); } } Entry::Vacant(e) => { e.insert(smallvec![(sk, instance_data.collect())]); } } } /// Returns an iterator over the internally batched raw data. pub fn data(&self) -> impl Iterator<Item = &C> { self.map .iter() .flat_map(|(_, batch)| batch.iter().map(|data| &data.1)) } /// Returns an iterator over the internally batched data, which includes the group keys. pub fn iter(&self) -> impl Iterator<Item = (&PK, impl Iterator<Item = &(SK, C)>)> { self.map.iter().map(|(pk, batch)| (pk, batch.iter())) } /// Returns the number of items currently in this batch. pub fn count(&self) -> usize { self.data_count } } /// Batching implementation which provides two levels of indirection and grouping for a given batch. /// This batch method is used, for example, batching meshes and textures; for any given draw call, /// a user would want to batch all draws using a specific texture together, and then also group all /// draw calls for a specific mesh together. /// /// `PK` - First level of batch grouping /// `SK` - Secondary level of batch grouping /// `D` - the actual final type being batched. /// /// Internally, this batch type is implemented with sorted tuple `Vec` structures. /// /// `OrderedTwoLevelBatch` differs from [TwoLevelBatch] in that it sorts and orders on both levels /// of batching. #[derive(Derivative, Debug)] #[derivative(Default(bound = ""))] pub struct OrderedTwoLevelBatch<PK, SK, D> where PK: PartialEq, SK: PartialEq, { old_pk_list: Vec<(PK, u32)>, old_sk_list: Vec<(SK, Range<u32>)>, pk_list: Vec<(PK, u32)>, sk_list: Vec<(SK, Range<u32>)>, data_list: Vec<D>, } impl<PK, SK, D> OrderedTwoLevelBatch<PK, SK, D> where PK: PartialEq, SK: PartialEq, { /// Clears all data and indices from this batch set. pub fn swap_clear(&mut self) { std::mem::swap(&mut self.old_pk_list, &mut self.pk_list); std::mem::swap(&mut self.old_sk_list, &mut self.sk_list); self.pk_list.clear(); self.sk_list.clear(); self.data_list.clear(); } /// Inserts a set of batch data to the specified grouping. pub fn insert(&mut self, pk: PK, sk: SK, data: impl IntoIterator<Item = D>) { #[cfg(feature = "profiler")] profile_scope!("ordered_twolevel_insert"); let start = self.data_list.len() as u32; self.data_list.extend(data); let end = self.data_list.len() as u32; match (self.pk_list.last_mut(), self.sk_list.last_mut()) { (Some((last_pk, _)), Some((last_sk, last_sk_range))) if last_pk == &pk && last_sk == &sk => { last_sk_range.end = end; } (Some((last_pk, last_pk_len)), _) if last_pk == &pk => { *last_pk_len += 1; self.sk_list.push((sk, start..end)); } _ => { self.pk_list.push((pk, 1)); self.sk_list.push((sk, start..end)); } } } /// Returns the raw storage data of this batch container. pub fn data(&self) -> &Vec<D> { &self.data_list } /// Iterator that returns primary keys and all inner submitted batches pub fn iter<'a>(&'a self) -> impl Iterator<Item = (&'a PK, &[(SK, Range<u32>)])> { let mut pk_offset = 0; self.pk_list.iter().map(move |(pk, pk_len)| { let range = pk_offset..pk_offset + *pk_len as usize; pk_offset += *pk_len as usize; (pk, &self.sk_list[range]) }) } /// Returns true if sorting this batch resulted in a change in order. pub fn changed(&self) -> bool { self.pk_list != self.old_pk_list || self.sk_list != self.old_sk_list } /// Returns the number of items currently in this batch. pub fn count(&self) -> usize { self.data_list.len() } } /// A batching implementation with one level of indexing. Data type `D` batched by primary key `PK`. /// Items with the same `PK` are always grouped. #[derive(Derivative, Debug)] #[derivative(Default(bound = ""))] pub struct OneLevelBatch<PK, D> where PK: Eq + std::hash::Hash, { map: fnv::FnvHashMap<PK, Vec<D>>, data_count: usize, } impl<PK, D> OneLevelBatch<PK, D> where PK: Eq + std::hash::Hash, { /// Clears all data and indices from this batch set. pub fn clear_inner(&mut self) { self.data_count = 0; for (_, data) in self.map.iter_mut() { data.clear(); } } /// Removes any empty grouping indices. pub fn prune(&mut self) { self.map.retain(|_, b| !b.is_empty()); } /// Inserts the provided set of batch data for `PK` pub fn insert(&mut self, pk: PK, data: impl IntoIterator<Item = D>) { #[cfg(feature = "profiler")] profile_scope!("onelevel_insert"); let instance_data = data.into_iter(); match self.map.entry(pk) { Entry::Occupied(mut e) => { let vec = e.get_mut(); let old_len = vec.len(); vec.extend(instance_data); self.data_count += vec.len() - old_len; } Entry::Vacant(e) => { let collected = instance_data.collect::<Vec<_>>(); self.data_count += collected.len(); e.insert(collected); } } } /// Returns an iterator over batched data lists. pub fn data(&self) -> impl Iterator<Item = &Vec<D>> { self.map.values() } /// Returns an iterator over batched values, providing batch `PK` and data list. pub fn iter(&self) -> impl Iterator<Item = (&PK, Range<u32>)> { let mut offset = 0; self.map.iter().map(move |(pk, data)| { let range = offset..offset + data.len() as u32; offset = range.end; (pk, range) }) } /// Returns the number of items currently in this batch. pub fn count(&self) -> usize { self.data_count } } /// A batching implementation with one level of indexing. Data type `D` batched by primary key `PK`. /// /// Items are always kept in insertion order, grouped only by contiguous ranges of equal `PK`. #[derive(Derivative, Debug)] #[derivative(Default(bound = ""))] pub struct OrderedOneLevelBatch<PK, D> where PK: PartialEq, { old_keys: Vec<(PK, u32)>, keys_list: Vec<(PK, u32)>, data_list: Vec<D>, } impl<PK, D> OrderedOneLevelBatch<PK, D> where PK: PartialEq, { /// Clears all data and indices from this batch set. pub fn swap_clear(&mut self) { std::mem::swap(&mut self.old_keys, &mut self.keys_list); self.keys_list.clear(); self.data_list.clear(); } /// Inserts the provided set of batch data for `PK` pub fn insert(&mut self, pk: PK, data: impl IntoIterator<Item = D>) { #[cfg(feature = "profiler")] profile_scope!("ordered_onelevel_insert"); let start = self.data_list.len() as u32; self.data_list.extend(data); let added_len = self.data_list.len() as u32 - start; if added_len == 0 { return; } match self.keys_list.last_mut() { Some((last_pk, last_len)) if last_pk == &pk => { *last_len += added_len; } _ => { self.keys_list.push((pk, added_len)); } } } /// Returns an iterator to raw data for this batch. pub fn data(&self) -> &Vec<D> { &self.data_list } /// Iterator that returns primary keys and lengths of submitted batch pub fn iter(&self) -> impl Iterator<Item = (&PK, Range<u32>)> { let mut offset = 0; self.keys_list.iter().map(move |(pk, size)| { let range = offset..offset + *size; offset = range.end; (pk, range) }) } /// Returns an iterator to raw data for this batch. pub fn changed(&self) -> bool { self.keys_list != self.old_keys } /// Returns the number of items currently in this batch. pub fn count(&self) -> usize { self.data_list.len() } } #[cfg(test)] mod tests { use super::*; #[test] fn test_ordered_onelevel_batch_single_insert() { let mut batch = OrderedOneLevelBatch::<u32, u32>::default(); batch.insert(0, Some(0)); assert_eq!(batch.count(), 1); assert_eq!(batch.iter().collect::<Vec<_>>(), vec![(&0, 0..1)]); } #[test] fn test_ordered_onelevel_batch_insert_existing() { let mut batch = OrderedOneLevelBatch::<u32, u32>::default(); batch.insert(0, Some(0)); batch.insert(0, Some(1)); batch.insert(1, Some(0)); assert_eq!(batch.count(), 3); assert_eq!( batch.iter().collect::<Vec<_>>(), vec![(&0, 0..2), (&1, 2..3)] ); } #[test] fn test_ordered_onelevel_batch_empty_insert() { let mut batch = OrderedOneLevelBatch::<u32, u32>::default(); batch.insert(0, None); assert_eq!(batch.count(), 0); assert_eq!(batch.iter().collect::<Vec<_>>(), vec![]); } }
32.156909
100
0.57738
[ "#[cfg(test)]\nmod tests {\n use super::*;\n #[test]\n fn test_ordered_onelevel_batch_single_insert() {\n let mut batch = OrderedOneLevelBatch::<u32, u32>::default();\n batch.insert(0, Some(0));\n assert_eq!(batch.count(), 1);\n assert_eq!(batch.iter().collect::<Vec<_>>(), vec![(&0, 0..1)]);\n }\n}", "#[cfg(test)]\nmod tests {\n use super::*;\n #[test]\n fn test_ordered_onelevel_batch_insert_existing() {\n let mut batch = OrderedOneLevelBatch::<u32, u32>::default();\n batch.insert(0, Some(0));\n batch.insert(0, Some(1));\n batch.insert(1, Some(0));\n assert_eq!(batch.count(), 3);\n assert_eq!(\n batch.iter().collect::<Vec<_>>(),\n vec![(&0, 0..2), (&1, 2..3)]\n );\n }\n}", "#[cfg(test)]\nmod tests {\n use super::*;\n #[test]\n fn test_ordered_onelevel_batch_empty_insert() {\n let mut batch = OrderedOneLevelBatch::<u32, u32>::default();\n batch.insert(0, None);\n assert_eq!(batch.count(), 0);\n assert_eq!(batch.iter().collect::<Vec<_>>(), vec![]);\n }\n}" ]
f701a7312a3bcea3ecd9bfd2bf7fa634a8eba26c
69,192
rs
Rust
src/sys/socket/mod.rs
sporksmith/nix
4d8504bee10778d37a804f812e865d7440f2c3b9
[ "MIT" ]
null
null
null
src/sys/socket/mod.rs
sporksmith/nix
4d8504bee10778d37a804f812e865d7440f2c3b9
[ "MIT" ]
null
null
null
src/sys/socket/mod.rs
sporksmith/nix
4d8504bee10778d37a804f812e865d7440f2c3b9
[ "MIT" ]
null
null
null
//! Socket interface functions //! //! [Further reading](https://man7.org/linux/man-pages/man7/socket.7.html) use cfg_if::cfg_if; use crate::{Error, Result, errno::Errno}; use libc::{self, c_void, c_int, iovec, socklen_t, size_t, CMSG_FIRSTHDR, CMSG_NXTHDR, CMSG_DATA, CMSG_LEN}; use memoffset::offset_of; use std::{mem, ptr, slice}; use std::os::unix::io::RawFd; #[cfg(all(target_os = "linux"))] use crate::sys::time::TimeSpec; use crate::sys::time::TimeVal; use crate::sys::uio::IoVec; mod addr; pub mod sockopt; /* * * ===== Re-exports ===== * */ #[cfg(not(any(target_os = "illumos", target_os = "solaris")))] pub use self::addr::{ AddressFamily, SockAddr, InetAddr, UnixAddr, IpAddr, Ipv4Addr, Ipv6Addr, LinkAddr, }; #[cfg(any(target_os = "illumos", target_os = "solaris"))] pub use self::addr::{ AddressFamily, SockAddr, InetAddr, UnixAddr, IpAddr, Ipv4Addr, Ipv6Addr, }; #[cfg(any(target_os = "android", target_os = "linux"))] pub use crate::sys::socket::addr::netlink::NetlinkAddr; #[cfg(any(target_os = "android", target_os = "linux"))] pub use crate::sys::socket::addr::alg::AlgAddr; #[cfg(any(target_os = "android", target_os = "linux"))] pub use crate::sys::socket::addr::vsock::VsockAddr; pub use libc::{ cmsghdr, msghdr, sa_family_t, sockaddr, sockaddr_in, sockaddr_in6, sockaddr_storage, sockaddr_un, }; // Needed by the cmsg_space macro #[doc(hidden)] pub use libc::{c_uint, CMSG_SPACE}; /// These constants are used to specify the communication semantics /// when creating a socket with [`socket()`](fn.socket.html) #[derive(Clone, Copy, PartialEq, Eq, Debug)] #[repr(i32)] #[non_exhaustive] pub enum SockType { /// Provides sequenced, reliable, two-way, connection- /// based byte streams. An out-of-band data transmission /// mechanism may be supported. Stream = libc::SOCK_STREAM, /// Supports datagrams (connectionless, unreliable /// messages of a fixed maximum length). Datagram = libc::SOCK_DGRAM, /// Provides a sequenced, reliable, two-way connection- /// based data transmission path for datagrams of fixed /// maximum length; a consumer is required to read an /// entire packet with each input system call. SeqPacket = libc::SOCK_SEQPACKET, /// Provides raw network protocol access. Raw = libc::SOCK_RAW, /// Provides a reliable datagram layer that does not /// guarantee ordering. Rdm = libc::SOCK_RDM, } /// Constants used in [`socket`](fn.socket.html) and [`socketpair`](fn.socketpair.html) /// to specify the protocol to use. #[repr(i32)] #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] #[non_exhaustive] pub enum SockProtocol { /// TCP protocol ([ip(7)](https://man7.org/linux/man-pages/man7/ip.7.html)) Tcp = libc::IPPROTO_TCP, /// UDP protocol ([ip(7)](https://man7.org/linux/man-pages/man7/ip.7.html)) Udp = libc::IPPROTO_UDP, /// Allows applications and other KEXTs to be notified when certain kernel events occur /// ([ref](https://developer.apple.com/library/content/documentation/Darwin/Conceptual/NKEConceptual/control/control.html)) #[cfg(any(target_os = "ios", target_os = "macos"))] KextEvent = libc::SYSPROTO_EVENT, /// Allows applications to configure and control a KEXT /// ([ref](https://developer.apple.com/library/content/documentation/Darwin/Conceptual/NKEConceptual/control/control.html)) #[cfg(any(target_os = "ios", target_os = "macos"))] KextControl = libc::SYSPROTO_CONTROL, /// Receives routing and link updates and may be used to modify the routing tables (both IPv4 and IPv6), IP addresses, link // parameters, neighbor setups, queueing disciplines, traffic classes and packet classifiers /// ([ref](https://www.man7.org/linux/man-pages/man7/netlink.7.html)) #[cfg(any(target_os = "android", target_os = "linux"))] NetlinkRoute = libc::NETLINK_ROUTE, /// Reserved for user-mode socket protocols /// ([ref](https://www.man7.org/linux/man-pages/man7/netlink.7.html)) #[cfg(any(target_os = "android", target_os = "linux"))] NetlinkUserSock = libc::NETLINK_USERSOCK, /// Query information about sockets of various protocol families from the kernel /// ([ref](https://www.man7.org/linux/man-pages/man7/netlink.7.html)) #[cfg(any(target_os = "android", target_os = "linux"))] NetlinkSockDiag = libc::NETLINK_SOCK_DIAG, /// SELinux event notifications. /// ([ref](https://www.man7.org/linux/man-pages/man7/netlink.7.html)) #[cfg(any(target_os = "android", target_os = "linux"))] NetlinkSELinux = libc::NETLINK_SELINUX, /// Open-iSCSI /// ([ref](https://www.man7.org/linux/man-pages/man7/netlink.7.html)) #[cfg(any(target_os = "android", target_os = "linux"))] NetlinkISCSI = libc::NETLINK_ISCSI, /// Auditing /// ([ref](https://www.man7.org/linux/man-pages/man7/netlink.7.html)) #[cfg(any(target_os = "android", target_os = "linux"))] NetlinkAudit = libc::NETLINK_AUDIT, /// Access to FIB lookup from user space /// ([ref](https://www.man7.org/linux/man-pages/man7/netlink.7.html)) #[cfg(any(target_os = "android", target_os = "linux"))] NetlinkFIBLookup = libc::NETLINK_FIB_LOOKUP, /// Netfilter subsystem /// ([ref](https://www.man7.org/linux/man-pages/man7/netlink.7.html)) #[cfg(any(target_os = "android", target_os = "linux"))] NetlinkNetFilter = libc::NETLINK_NETFILTER, /// SCSI Transports /// ([ref](https://www.man7.org/linux/man-pages/man7/netlink.7.html)) #[cfg(any(target_os = "android", target_os = "linux"))] NetlinkSCSITransport = libc::NETLINK_SCSITRANSPORT, /// Infiniband RDMA /// ([ref](https://www.man7.org/linux/man-pages/man7/netlink.7.html)) #[cfg(any(target_os = "android", target_os = "linux"))] NetlinkRDMA = libc::NETLINK_RDMA, /// Transport IPv6 packets from netfilter to user space. Used by ip6_queue kernel module. /// ([ref](https://www.man7.org/linux/man-pages/man7/netlink.7.html)) #[cfg(any(target_os = "android", target_os = "linux"))] NetlinkIPv6Firewall = libc::NETLINK_IP6_FW, /// DECnet routing messages /// ([ref](https://www.man7.org/linux/man-pages/man7/netlink.7.html)) #[cfg(any(target_os = "android", target_os = "linux"))] NetlinkDECNetRoutingMessage = libc::NETLINK_DNRTMSG, /// Kernel messages to user space /// ([ref](https://www.man7.org/linux/man-pages/man7/netlink.7.html)) #[cfg(any(target_os = "android", target_os = "linux"))] NetlinkKObjectUEvent = libc::NETLINK_KOBJECT_UEVENT, /// Netlink interface to request information about ciphers registered with the kernel crypto API as well as allow /// configuration of the kernel crypto API. /// ([ref](https://www.man7.org/linux/man-pages/man7/netlink.7.html)) #[cfg(any(target_os = "android", target_os = "linux"))] NetlinkCrypto = libc::NETLINK_CRYPTO, } libc_bitflags!{ /// Additional socket options pub struct SockFlag: c_int { /// Set non-blocking mode on the new socket #[cfg(any(target_os = "android", target_os = "dragonfly", target_os = "freebsd", target_os = "illumos", target_os = "linux", target_os = "netbsd", target_os = "openbsd"))] SOCK_NONBLOCK; /// Set close-on-exec on the new descriptor #[cfg(any(target_os = "android", target_os = "dragonfly", target_os = "freebsd", target_os = "illumos", target_os = "linux", target_os = "netbsd", target_os = "openbsd"))] SOCK_CLOEXEC; /// Return `EPIPE` instead of raising `SIGPIPE` #[cfg(target_os = "netbsd")] SOCK_NOSIGPIPE; /// For domains `AF_INET(6)`, only allow `connect(2)`, `sendto(2)`, or `sendmsg(2)` /// to the DNS port (typically 53) #[cfg(target_os = "openbsd")] SOCK_DNS; } } libc_bitflags!{ /// Flags for send/recv and their relatives pub struct MsgFlags: c_int { /// Sends or requests out-of-band data on sockets that support this notion /// (e.g., of type [`Stream`](enum.SockType.html)); the underlying protocol must also /// support out-of-band data. MSG_OOB; /// Peeks at an incoming message. The data is treated as unread and the next /// [`recv()`](fn.recv.html) /// or similar function shall still return this data. MSG_PEEK; /// Receive operation blocks until the full amount of data can be /// returned. The function may return smaller amount of data if a signal /// is caught, an error or disconnect occurs. MSG_WAITALL; /// Enables nonblocking operation; if the operation would block, /// `EAGAIN` or `EWOULDBLOCK` is returned. This provides similar /// behavior to setting the `O_NONBLOCK` flag /// (via the [`fcntl`](../../fcntl/fn.fcntl.html) /// `F_SETFL` operation), but differs in that `MSG_DONTWAIT` is a per- /// call option, whereas `O_NONBLOCK` is a setting on the open file /// description (see [open(2)](https://man7.org/linux/man-pages/man2/open.2.html)), /// which will affect all threads in /// the calling process and as well as other processes that hold /// file descriptors referring to the same open file description. MSG_DONTWAIT; /// Receive flags: Control Data was discarded (buffer too small) MSG_CTRUNC; /// For raw ([`Packet`](addr/enum.AddressFamily.html)), Internet datagram /// (since Linux 2.4.27/2.6.8), /// netlink (since Linux 2.6.22) and UNIX datagram (since Linux 3.4) /// sockets: return the real length of the packet or datagram, even /// when it was longer than the passed buffer. Not implemented for UNIX /// domain ([unix(7)](https://linux.die.net/man/7/unix)) sockets. /// /// For use with Internet stream sockets, see [tcp(7)](https://linux.die.net/man/7/tcp). MSG_TRUNC; /// Terminates a record (when this notion is supported, as for /// sockets of type [`SeqPacket`](enum.SockType.html)). MSG_EOR; /// This flag specifies that queued errors should be received from /// the socket error queue. (For more details, see /// [recvfrom(2)](https://linux.die.net/man/2/recvfrom)) #[cfg(any(target_os = "android", target_os = "linux"))] MSG_ERRQUEUE; /// Set the `close-on-exec` flag for the file descriptor received via a UNIX domain /// file descriptor using the `SCM_RIGHTS` operation (described in /// [unix(7)](https://linux.die.net/man/7/unix)). /// This flag is useful for the same reasons as the `O_CLOEXEC` flag of /// [open(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/open.html). /// /// Only used in [`recvmsg`](fn.recvmsg.html) function. #[cfg(any(target_os = "android", target_os = "dragonfly", target_os = "freebsd", target_os = "linux", target_os = "netbsd", target_os = "openbsd"))] MSG_CMSG_CLOEXEC; } } cfg_if! { if #[cfg(any(target_os = "android", target_os = "linux"))] { /// Unix credentials of the sending process. /// /// This struct is used with the `SO_PEERCRED` ancillary message /// and the `SCM_CREDENTIALS` control message for UNIX sockets. #[repr(transparent)] #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct UnixCredentials(libc::ucred); impl UnixCredentials { /// Creates a new instance with the credentials of the current process pub fn new() -> Self { UnixCredentials(libc::ucred { pid: crate::unistd::getpid().as_raw(), uid: crate::unistd::getuid().as_raw(), gid: crate::unistd::getgid().as_raw(), }) } /// Returns the process identifier pub fn pid(&self) -> libc::pid_t { self.0.pid } /// Returns the user identifier pub fn uid(&self) -> libc::uid_t { self.0.uid } /// Returns the group identifier pub fn gid(&self) -> libc::gid_t { self.0.gid } } impl Default for UnixCredentials { fn default() -> Self { Self::new() } } impl From<libc::ucred> for UnixCredentials { fn from(cred: libc::ucred) -> Self { UnixCredentials(cred) } } impl Into<libc::ucred> for UnixCredentials { fn into(self) -> libc::ucred { self.0 } } } else if #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))] { /// Unix credentials of the sending process. /// /// This struct is used with the `SCM_CREDS` ancillary message for UNIX sockets. #[repr(transparent)] #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct UnixCredentials(libc::cmsgcred); impl UnixCredentials { /// Returns the process identifier pub fn pid(&self) -> libc::pid_t { self.0.cmcred_pid } /// Returns the real user identifier pub fn uid(&self) -> libc::uid_t { self.0.cmcred_uid } /// Returns the effective user identifier pub fn euid(&self) -> libc::uid_t { self.0.cmcred_euid } /// Returns the real group identifier pub fn gid(&self) -> libc::gid_t { self.0.cmcred_gid } /// Returns a list group identifiers (the first one being the effective GID) pub fn groups(&self) -> &[libc::gid_t] { unsafe { slice::from_raw_parts(self.0.cmcred_groups.as_ptr() as *const libc::gid_t, self.0.cmcred_ngroups as _) } } } impl From<libc::cmsgcred> for UnixCredentials { fn from(cred: libc::cmsgcred) -> Self { UnixCredentials(cred) } } } } cfg_if!{ if #[cfg(any( target_os = "dragonfly", target_os = "freebsd", target_os = "macos", target_os = "ios" ))] { /// Return type of [`LocalPeerCred`](crate::sys::socket::sockopt::LocalPeerCred) #[repr(transparent)] #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct XuCred(libc::xucred); impl XuCred { /// Structure layout version pub fn version(&self) -> u32 { self.0.cr_version } /// Effective user ID pub fn uid(&self) -> libc::uid_t { self.0.cr_uid } /// Returns a list of group identifiers (the first one being the /// effective GID) pub fn groups(&self) -> &[libc::gid_t] { &self.0.cr_groups } } } } /// Request for multicast socket operations /// /// This is a wrapper type around `ip_mreq`. #[repr(transparent)] #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct IpMembershipRequest(libc::ip_mreq); impl IpMembershipRequest { /// Instantiate a new `IpMembershipRequest` /// /// If `interface` is `None`, then `Ipv4Addr::any()` will be used for the interface. pub fn new(group: Ipv4Addr, interface: Option<Ipv4Addr>) -> Self { IpMembershipRequest(libc::ip_mreq { imr_multiaddr: group.0, imr_interface: interface.unwrap_or_else(Ipv4Addr::any).0, }) } } /// Request for ipv6 multicast socket operations /// /// This is a wrapper type around `ipv6_mreq`. #[repr(transparent)] #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct Ipv6MembershipRequest(libc::ipv6_mreq); impl Ipv6MembershipRequest { /// Instantiate a new `Ipv6MembershipRequest` pub const fn new(group: Ipv6Addr) -> Self { Ipv6MembershipRequest(libc::ipv6_mreq { ipv6mr_multiaddr: group.0, ipv6mr_interface: 0, }) } } /// Create a buffer large enough for storing some control messages as returned /// by [`recvmsg`](fn.recvmsg.html). /// /// # Examples /// /// ``` /// # #[macro_use] extern crate nix; /// # use nix::sys::time::TimeVal; /// # use std::os::unix::io::RawFd; /// # fn main() { /// // Create a buffer for a `ControlMessageOwned::ScmTimestamp` message /// let _ = cmsg_space!(TimeVal); /// // Create a buffer big enough for a `ControlMessageOwned::ScmRights` message /// // with two file descriptors /// let _ = cmsg_space!([RawFd; 2]); /// // Create a buffer big enough for a `ControlMessageOwned::ScmRights` message /// // and a `ControlMessageOwned::ScmTimestamp` message /// let _ = cmsg_space!(RawFd, TimeVal); /// # } /// ``` // Unfortunately, CMSG_SPACE isn't a const_fn, or else we could return a // stack-allocated array. #[macro_export] macro_rules! cmsg_space { ( $( $x:ty ),* ) => { { let mut space = 0; $( // CMSG_SPACE is always safe space += unsafe { $crate::sys::socket::CMSG_SPACE(::std::mem::size_of::<$x>() as $crate::sys::socket::c_uint) } as usize; )* Vec::<u8>::with_capacity(space) } } } #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct RecvMsg<'a> { pub bytes: usize, cmsghdr: Option<&'a cmsghdr>, pub address: Option<SockAddr>, pub flags: MsgFlags, mhdr: msghdr, } impl<'a> RecvMsg<'a> { /// Iterate over the valid control messages pointed to by this /// msghdr. pub fn cmsgs(&self) -> CmsgIterator { CmsgIterator { cmsghdr: self.cmsghdr, mhdr: &self.mhdr } } } #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct CmsgIterator<'a> { /// Control message buffer to decode from. Must adhere to cmsg alignment. cmsghdr: Option<&'a cmsghdr>, mhdr: &'a msghdr } impl<'a> Iterator for CmsgIterator<'a> { type Item = ControlMessageOwned; fn next(&mut self) -> Option<ControlMessageOwned> { match self.cmsghdr { None => None, // No more messages Some(hdr) => { // Get the data. // Safe if cmsghdr points to valid data returned by recvmsg(2) let cm = unsafe { Some(ControlMessageOwned::decode_from(hdr))}; // Advance the internal pointer. Safe if mhdr and cmsghdr point // to valid data returned by recvmsg(2) self.cmsghdr = unsafe { let p = CMSG_NXTHDR(self.mhdr as *const _, hdr as *const _); p.as_ref() }; cm } } } } /// A type-safe wrapper around a single control message, as used with /// [`recvmsg`](#fn.recvmsg). /// /// [Further reading](https://man7.org/linux/man-pages/man3/cmsg.3.html) // Nix version 0.13.0 and earlier used ControlMessage for both recvmsg and // sendmsg. However, on some platforms the messages returned by recvmsg may be // unaligned. ControlMessageOwned takes those messages by copy, obviating any // alignment issues. // // See https://github.com/nix-rust/nix/issues/999 #[derive(Clone, Debug, Eq, PartialEq)] #[non_exhaustive] pub enum ControlMessageOwned { /// Received version of /// [`ControlMessage::ScmRights`][#enum.ControlMessage.html#variant.ScmRights] ScmRights(Vec<RawFd>), /// Received version of /// [`ControlMessage::ScmCredentials`][#enum.ControlMessage.html#variant.ScmCredentials] #[cfg(any(target_os = "android", target_os = "linux"))] ScmCredentials(UnixCredentials), /// Received version of /// [`ControlMessage::ScmCreds`][#enum.ControlMessage.html#variant.ScmCreds] #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))] ScmCreds(UnixCredentials), /// A message of type `SCM_TIMESTAMP`, containing the time the /// packet was received by the kernel. /// /// See the kernel's explanation in "SO_TIMESTAMP" of /// [networking/timestamping](https://www.kernel.org/doc/Documentation/networking/timestamping.txt). /// /// # Examples /// /// ``` /// # #[macro_use] extern crate nix; /// # use nix::sys::socket::*; /// # use nix::sys::uio::IoVec; /// # use nix::sys::time::*; /// # use std::time::*; /// # fn main() { /// // Set up /// let message = "Ohayō!".as_bytes(); /// let in_socket = socket( /// AddressFamily::Inet, /// SockType::Datagram, /// SockFlag::empty(), /// None).unwrap(); /// setsockopt(in_socket, sockopt::ReceiveTimestamp, &true).unwrap(); /// let localhost = InetAddr::new(IpAddr::new_v4(127, 0, 0, 1), 0); /// bind(in_socket, &SockAddr::new_inet(localhost)).unwrap(); /// let address = getsockname(in_socket).unwrap(); /// // Get initial time /// let time0 = SystemTime::now(); /// // Send the message /// let iov = [IoVec::from_slice(message)]; /// let flags = MsgFlags::empty(); /// let l = sendmsg(in_socket, &iov, &[], flags, Some(&address)).unwrap(); /// assert_eq!(message.len(), l); /// // Receive the message /// let mut buffer = vec![0u8; message.len()]; /// let mut cmsgspace = cmsg_space!(TimeVal); /// let iov = [IoVec::from_mut_slice(&mut buffer)]; /// let r = recvmsg(in_socket, &iov, Some(&mut cmsgspace), flags).unwrap(); /// let rtime = match r.cmsgs().next() { /// Some(ControlMessageOwned::ScmTimestamp(rtime)) => rtime, /// Some(_) => panic!("Unexpected control message"), /// None => panic!("No control message") /// }; /// // Check the final time /// let time1 = SystemTime::now(); /// // the packet's received timestamp should lie in-between the two system /// // times, unless the system clock was adjusted in the meantime. /// let rduration = Duration::new(rtime.tv_sec() as u64, /// rtime.tv_usec() as u32 * 1000); /// assert!(time0.duration_since(UNIX_EPOCH).unwrap() <= rduration); /// assert!(rduration <= time1.duration_since(UNIX_EPOCH).unwrap()); /// // Close socket /// nix::unistd::close(in_socket).unwrap(); /// # } /// ``` ScmTimestamp(TimeVal), /// Nanoseconds resolution timestamp /// /// [Further reading](https://www.kernel.org/doc/html/latest/networking/timestamping.html) #[cfg(all(target_os = "linux"))] ScmTimestampns(TimeSpec), #[cfg(any( target_os = "android", target_os = "ios", target_os = "linux", target_os = "macos", target_os = "netbsd", ))] Ipv4PacketInfo(libc::in_pktinfo), #[cfg(any( target_os = "android", target_os = "dragonfly", target_os = "freebsd", target_os = "ios", target_os = "linux", target_os = "macos", target_os = "openbsd", target_os = "netbsd", ))] Ipv6PacketInfo(libc::in6_pktinfo), #[cfg(any( target_os = "freebsd", target_os = "ios", target_os = "macos", target_os = "netbsd", target_os = "openbsd", ))] Ipv4RecvIf(libc::sockaddr_dl), #[cfg(any( target_os = "freebsd", target_os = "ios", target_os = "macos", target_os = "netbsd", target_os = "openbsd", ))] Ipv4RecvDstAddr(libc::in_addr), /// UDP Generic Receive Offload (GRO) allows receiving multiple UDP /// packets from a single sender. /// Fixed-size payloads are following one by one in a receive buffer. /// This Control Message indicates the size of all smaller packets, /// except, maybe, the last one. /// /// `UdpGroSegment` socket option should be enabled on a socket /// to allow receiving GRO packets. #[cfg(target_os = "linux")] UdpGroSegments(u16), /// SO_RXQ_OVFL indicates that an unsigned 32 bit value /// ancilliary msg (cmsg) should be attached to recieved /// skbs indicating the number of packets dropped by the /// socket between the last recieved packet and this /// received packet. /// /// `RxqOvfl` socket option should be enabled on a socket /// to allow receiving the drop counter. #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))] RxqOvfl(u32), /// Catch-all variant for unimplemented cmsg types. #[doc(hidden)] Unknown(UnknownCmsg), } impl ControlMessageOwned { /// Decodes a `ControlMessageOwned` from raw bytes. /// /// This is only safe to call if the data is correct for the message type /// specified in the header. Normally, the kernel ensures that this is the /// case. "Correct" in this case includes correct length, alignment and /// actual content. // Clippy complains about the pointer alignment of `p`, not understanding // that it's being fed to a function that can handle that. #[allow(clippy::cast_ptr_alignment)] unsafe fn decode_from(header: &cmsghdr) -> ControlMessageOwned { let p = CMSG_DATA(header); let len = header as *const _ as usize + header.cmsg_len as usize - p as usize; match (header.cmsg_level, header.cmsg_type) { (libc::SOL_SOCKET, libc::SCM_RIGHTS) => { let n = len / mem::size_of::<RawFd>(); let mut fds = Vec::with_capacity(n); for i in 0..n { let fdp = (p as *const RawFd).add(i); fds.push(ptr::read_unaligned(fdp)); } ControlMessageOwned::ScmRights(fds) }, #[cfg(any(target_os = "android", target_os = "linux"))] (libc::SOL_SOCKET, libc::SCM_CREDENTIALS) => { let cred: libc::ucred = ptr::read_unaligned(p as *const _); ControlMessageOwned::ScmCredentials(cred.into()) } #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))] (libc::SOL_SOCKET, libc::SCM_CREDS) => { let cred: libc::cmsgcred = ptr::read_unaligned(p as *const _); ControlMessageOwned::ScmCreds(cred.into()) } (libc::SOL_SOCKET, libc::SCM_TIMESTAMP) => { let tv: libc::timeval = ptr::read_unaligned(p as *const _); ControlMessageOwned::ScmTimestamp(TimeVal::from(tv)) }, #[cfg(all(target_os = "linux"))] (libc::SOL_SOCKET, libc::SCM_TIMESTAMPNS) => { let ts: libc::timespec = ptr::read_unaligned(p as *const _); ControlMessageOwned::ScmTimestampns(TimeSpec::from(ts)) } #[cfg(any( target_os = "android", target_os = "freebsd", target_os = "ios", target_os = "linux", target_os = "macos" ))] (libc::IPPROTO_IPV6, libc::IPV6_PKTINFO) => { let info = ptr::read_unaligned(p as *const libc::in6_pktinfo); ControlMessageOwned::Ipv6PacketInfo(info) } #[cfg(any( target_os = "android", target_os = "ios", target_os = "linux", target_os = "macos", target_os = "netbsd", ))] (libc::IPPROTO_IP, libc::IP_PKTINFO) => { let info = ptr::read_unaligned(p as *const libc::in_pktinfo); ControlMessageOwned::Ipv4PacketInfo(info) } #[cfg(any( target_os = "freebsd", target_os = "ios", target_os = "macos", target_os = "netbsd", target_os = "openbsd", ))] (libc::IPPROTO_IP, libc::IP_RECVIF) => { let dl = ptr::read_unaligned(p as *const libc::sockaddr_dl); ControlMessageOwned::Ipv4RecvIf(dl) }, #[cfg(any( target_os = "freebsd", target_os = "ios", target_os = "macos", target_os = "netbsd", target_os = "openbsd", ))] (libc::IPPROTO_IP, libc::IP_RECVDSTADDR) => { let dl = ptr::read_unaligned(p as *const libc::in_addr); ControlMessageOwned::Ipv4RecvDstAddr(dl) }, #[cfg(target_os = "linux")] (libc::SOL_UDP, libc::UDP_GRO) => { let gso_size: u16 = ptr::read_unaligned(p as *const _); ControlMessageOwned::UdpGroSegments(gso_size) }, #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))] (libc::SOL_SOCKET, libc::SO_RXQ_OVFL) => { let drop_counter = ptr::read_unaligned(p as *const u32); ControlMessageOwned::RxqOvfl(drop_counter) }, (_, _) => { let sl = slice::from_raw_parts(p, len); let ucmsg = UnknownCmsg(*header, Vec::<u8>::from(sl)); ControlMessageOwned::Unknown(ucmsg) } } } } /// A type-safe zero-copy wrapper around a single control message, as used wih /// [`sendmsg`](#fn.sendmsg). More types may be added to this enum; do not /// exhaustively pattern-match it. /// /// [Further reading](https://man7.org/linux/man-pages/man3/cmsg.3.html) #[derive(Clone, Copy, Debug, Eq, PartialEq)] #[non_exhaustive] pub enum ControlMessage<'a> { /// A message of type `SCM_RIGHTS`, containing an array of file /// descriptors passed between processes. /// /// See the description in the "Ancillary messages" section of the /// [unix(7) man page](https://man7.org/linux/man-pages/man7/unix.7.html). /// /// Using multiple `ScmRights` messages for a single `sendmsg` call isn't /// recommended since it causes platform-dependent behaviour: It might /// swallow all but the first `ScmRights` message or fail with `EINVAL`. /// Instead, you can put all fds to be passed into a single `ScmRights` /// message. ScmRights(&'a [RawFd]), /// A message of type `SCM_CREDENTIALS`, containing the pid, uid and gid of /// a process connected to the socket. /// /// This is similar to the socket option `SO_PEERCRED`, but requires a /// process to explicitly send its credentials. A process running as root is /// allowed to specify any credentials, while credentials sent by other /// processes are verified by the kernel. /// /// For further information, please refer to the /// [`unix(7)`](https://man7.org/linux/man-pages/man7/unix.7.html) man page. #[cfg(any(target_os = "android", target_os = "linux"))] ScmCredentials(&'a UnixCredentials), /// A message of type `SCM_CREDS`, containing the pid, uid, euid, gid and groups of /// a process connected to the socket. /// /// This is similar to the socket options `LOCAL_CREDS` and `LOCAL_PEERCRED`, but /// requires a process to explicitly send its credentials. /// /// Credentials are always overwritten by the kernel, so this variant does have /// any data, unlike the receive-side /// [`ControlMessageOwned::ScmCreds`][#enum.ControlMessageOwned.html#variant.ScmCreds]. /// /// For further information, please refer to the /// [`unix(4)`](https://www.freebsd.org/cgi/man.cgi?query=unix) man page. #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))] ScmCreds, /// Set IV for `AF_ALG` crypto API. /// /// For further information, please refer to the /// [`documentation`](https://kernel.readthedocs.io/en/sphinx-samples/crypto-API.html) #[cfg(any( target_os = "android", target_os = "linux", ))] AlgSetIv(&'a [u8]), /// Set crypto operation for `AF_ALG` crypto API. It may be one of /// `ALG_OP_ENCRYPT` or `ALG_OP_DECRYPT` /// /// For further information, please refer to the /// [`documentation`](https://kernel.readthedocs.io/en/sphinx-samples/crypto-API.html) #[cfg(any( target_os = "android", target_os = "linux", ))] AlgSetOp(&'a libc::c_int), /// Set the length of associated authentication data (AAD) (applicable only to AEAD algorithms) /// for `AF_ALG` crypto API. /// /// For further information, please refer to the /// [`documentation`](https://kernel.readthedocs.io/en/sphinx-samples/crypto-API.html) #[cfg(any( target_os = "android", target_os = "linux", ))] AlgSetAeadAssoclen(&'a u32), /// UDP GSO makes it possible for applications to generate network packets /// for a virtual MTU much greater than the real one. /// The length of the send data no longer matches the expected length on /// the wire. /// The size of the datagram payload as it should appear on the wire may be /// passed through this control message. /// Send buffer should consist of multiple fixed-size wire payloads /// following one by one, and the last, possibly smaller one. #[cfg(target_os = "linux")] UdpGsoSegments(&'a u16), /// Configure the sending addressing and interface for v4 /// /// For further information, please refer to the /// [`ip(7)`](https://man7.org/linux/man-pages/man7/ip.7.html) man page. #[cfg(any(target_os = "linux", target_os = "macos", target_os = "netbsd", target_os = "android", target_os = "ios",))] Ipv4PacketInfo(&'a libc::in_pktinfo), /// Configure the sending addressing and interface for v6 /// /// For further information, please refer to the /// [`ipv6(7)`](https://man7.org/linux/man-pages/man7/ipv6.7.html) man page. #[cfg(any(target_os = "linux", target_os = "macos", target_os = "netbsd", target_os = "freebsd", target_os = "android", target_os = "ios",))] Ipv6PacketInfo(&'a libc::in6_pktinfo), /// SO_RXQ_OVFL indicates that an unsigned 32 bit value /// ancilliary msg (cmsg) should be attached to recieved /// skbs indicating the number of packets dropped by the /// socket between the last recieved packet and this /// received packet. #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))] RxqOvfl(&'a u32), } // An opaque structure used to prevent cmsghdr from being a public type #[doc(hidden)] #[derive(Clone, Debug, Eq, PartialEq)] pub struct UnknownCmsg(cmsghdr, Vec<u8>); impl<'a> ControlMessage<'a> { /// The value of CMSG_SPACE on this message. /// Safe because CMSG_SPACE is always safe fn space(&self) -> usize { unsafe{CMSG_SPACE(self.len() as libc::c_uint) as usize} } /// The value of CMSG_LEN on this message. /// Safe because CMSG_LEN is always safe #[cfg(any(target_os = "android", all(target_os = "linux", not(target_env = "musl"))))] fn cmsg_len(&self) -> usize { unsafe{CMSG_LEN(self.len() as libc::c_uint) as usize} } #[cfg(not(any(target_os = "android", all(target_os = "linux", not(target_env = "musl")))))] fn cmsg_len(&self) -> libc::c_uint { unsafe{CMSG_LEN(self.len() as libc::c_uint)} } /// Return a reference to the payload data as a byte pointer fn copy_to_cmsg_data(&self, cmsg_data: *mut u8) { let data_ptr = match *self { ControlMessage::ScmRights(fds) => { fds as *const _ as *const u8 }, #[cfg(any(target_os = "android", target_os = "linux"))] ControlMessage::ScmCredentials(creds) => { &creds.0 as *const libc::ucred as *const u8 } #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))] ControlMessage::ScmCreds => { // The kernel overwrites the data, we just zero it // to make sure it's not uninitialized memory unsafe { ptr::write_bytes(cmsg_data, 0, self.len()) }; return } #[cfg(any(target_os = "android", target_os = "linux"))] ControlMessage::AlgSetIv(iv) => { #[allow(deprecated)] // https://github.com/rust-lang/libc/issues/1501 let af_alg_iv = libc::af_alg_iv { ivlen: iv.len() as u32, iv: [0u8; 0], }; let size = mem::size_of_val(&af_alg_iv); unsafe { ptr::copy_nonoverlapping( &af_alg_iv as *const _ as *const u8, cmsg_data, size, ); ptr::copy_nonoverlapping( iv.as_ptr(), cmsg_data.add(size), iv.len() ); }; return }, #[cfg(any(target_os = "android", target_os = "linux"))] ControlMessage::AlgSetOp(op) => { op as *const _ as *const u8 }, #[cfg(any(target_os = "android", target_os = "linux"))] ControlMessage::AlgSetAeadAssoclen(len) => { len as *const _ as *const u8 }, #[cfg(target_os = "linux")] ControlMessage::UdpGsoSegments(gso_size) => { gso_size as *const _ as *const u8 }, #[cfg(any(target_os = "linux", target_os = "macos", target_os = "netbsd", target_os = "android", target_os = "ios",))] ControlMessage::Ipv4PacketInfo(info) => info as *const _ as *const u8, #[cfg(any(target_os = "linux", target_os = "macos", target_os = "netbsd", target_os = "freebsd", target_os = "android", target_os = "ios",))] ControlMessage::Ipv6PacketInfo(info) => info as *const _ as *const u8, #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))] ControlMessage::RxqOvfl(drop_count) => { drop_count as *const _ as *const u8 }, }; unsafe { ptr::copy_nonoverlapping( data_ptr, cmsg_data, self.len() ) }; } /// The size of the payload, excluding its cmsghdr fn len(&self) -> usize { match *self { ControlMessage::ScmRights(fds) => { mem::size_of_val(fds) }, #[cfg(any(target_os = "android", target_os = "linux"))] ControlMessage::ScmCredentials(creds) => { mem::size_of_val(creds) } #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))] ControlMessage::ScmCreds => { mem::size_of::<libc::cmsgcred>() } #[cfg(any(target_os = "android", target_os = "linux"))] ControlMessage::AlgSetIv(iv) => { mem::size_of_val(&iv) + iv.len() }, #[cfg(any(target_os = "android", target_os = "linux"))] ControlMessage::AlgSetOp(op) => { mem::size_of_val(op) }, #[cfg(any(target_os = "android", target_os = "linux"))] ControlMessage::AlgSetAeadAssoclen(len) => { mem::size_of_val(len) }, #[cfg(target_os = "linux")] ControlMessage::UdpGsoSegments(gso_size) => { mem::size_of_val(gso_size) }, #[cfg(any(target_os = "linux", target_os = "macos", target_os = "netbsd", target_os = "android", target_os = "ios",))] ControlMessage::Ipv4PacketInfo(info) => mem::size_of_val(info), #[cfg(any(target_os = "linux", target_os = "macos", target_os = "netbsd", target_os = "freebsd", target_os = "android", target_os = "ios",))] ControlMessage::Ipv6PacketInfo(info) => mem::size_of_val(info), #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))] ControlMessage::RxqOvfl(drop_count) => { mem::size_of_val(drop_count) }, } } /// Returns the value to put into the `cmsg_level` field of the header. fn cmsg_level(&self) -> libc::c_int { match *self { ControlMessage::ScmRights(_) => libc::SOL_SOCKET, #[cfg(any(target_os = "android", target_os = "linux"))] ControlMessage::ScmCredentials(_) => libc::SOL_SOCKET, #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))] ControlMessage::ScmCreds => libc::SOL_SOCKET, #[cfg(any(target_os = "android", target_os = "linux"))] ControlMessage::AlgSetIv(_) | ControlMessage::AlgSetOp(_) | ControlMessage::AlgSetAeadAssoclen(_) => libc::SOL_ALG, #[cfg(target_os = "linux")] ControlMessage::UdpGsoSegments(_) => libc::SOL_UDP, #[cfg(any(target_os = "linux", target_os = "macos", target_os = "netbsd", target_os = "android", target_os = "ios",))] ControlMessage::Ipv4PacketInfo(_) => libc::IPPROTO_IP, #[cfg(any(target_os = "linux", target_os = "macos", target_os = "netbsd", target_os = "freebsd", target_os = "android", target_os = "ios",))] ControlMessage::Ipv6PacketInfo(_) => libc::IPPROTO_IPV6, #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))] ControlMessage::RxqOvfl(_) => libc::SOL_SOCKET, } } /// Returns the value to put into the `cmsg_type` field of the header. fn cmsg_type(&self) -> libc::c_int { match *self { ControlMessage::ScmRights(_) => libc::SCM_RIGHTS, #[cfg(any(target_os = "android", target_os = "linux"))] ControlMessage::ScmCredentials(_) => libc::SCM_CREDENTIALS, #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))] ControlMessage::ScmCreds => libc::SCM_CREDS, #[cfg(any(target_os = "android", target_os = "linux"))] ControlMessage::AlgSetIv(_) => { libc::ALG_SET_IV }, #[cfg(any(target_os = "android", target_os = "linux"))] ControlMessage::AlgSetOp(_) => { libc::ALG_SET_OP }, #[cfg(any(target_os = "android", target_os = "linux"))] ControlMessage::AlgSetAeadAssoclen(_) => { libc::ALG_SET_AEAD_ASSOCLEN }, #[cfg(target_os = "linux")] ControlMessage::UdpGsoSegments(_) => { libc::UDP_SEGMENT }, #[cfg(any(target_os = "linux", target_os = "macos", target_os = "netbsd", target_os = "android", target_os = "ios",))] ControlMessage::Ipv4PacketInfo(_) => libc::IP_PKTINFO, #[cfg(any(target_os = "linux", target_os = "macos", target_os = "netbsd", target_os = "freebsd", target_os = "android", target_os = "ios",))] ControlMessage::Ipv6PacketInfo(_) => libc::IPV6_PKTINFO, #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))] ControlMessage::RxqOvfl(_) => { libc::SO_RXQ_OVFL }, } } // Unsafe: cmsg must point to a valid cmsghdr with enough space to // encode self. unsafe fn encode_into(&self, cmsg: *mut cmsghdr) { (*cmsg).cmsg_level = self.cmsg_level(); (*cmsg).cmsg_type = self.cmsg_type(); (*cmsg).cmsg_len = self.cmsg_len(); self.copy_to_cmsg_data(CMSG_DATA(cmsg)); } } /// Send data in scatter-gather vectors to a socket, possibly accompanied /// by ancillary data. Optionally direct the message at the given address, /// as with sendto. /// /// Allocates if cmsgs is nonempty. pub fn sendmsg(fd: RawFd, iov: &[IoVec<&[u8]>], cmsgs: &[ControlMessage], flags: MsgFlags, addr: Option<&SockAddr>) -> Result<usize> { let capacity = cmsgs.iter().map(|c| c.space()).sum(); // First size the buffer needed to hold the cmsgs. It must be zeroed, // because subsequent code will not clear the padding bytes. let mut cmsg_buffer = vec![0u8; capacity]; let mhdr = pack_mhdr_to_send(&mut cmsg_buffer[..], &iov, &cmsgs, addr); let ret = unsafe { libc::sendmsg(fd, &mhdr, flags.bits()) }; Errno::result(ret).map(|r| r as usize) } #[cfg(any( target_os = "linux", target_os = "android", target_os = "freebsd", target_os = "netbsd", ))] #[derive(Debug)] pub struct SendMmsgData<'a, I, C> where I: AsRef<[IoVec<&'a [u8]>]>, C: AsRef<[ControlMessage<'a>]> { pub iov: I, pub cmsgs: C, pub addr: Option<SockAddr>, pub _lt: std::marker::PhantomData<&'a I>, } /// An extension of `sendmsg` that allows the caller to transmit multiple /// messages on a socket using a single system call. This has performance /// benefits for some applications. /// /// Allocations are performed for cmsgs and to build `msghdr` buffer /// /// # Arguments /// /// * `fd`: Socket file descriptor /// * `data`: Struct that implements `IntoIterator` with `SendMmsgData` items /// * `flags`: Optional flags passed directly to the operating system. /// /// # Returns /// `Vec` with numbers of sent bytes on each sent message. /// /// # References /// [`sendmsg`](fn.sendmsg.html) #[cfg(any( target_os = "linux", target_os = "android", target_os = "freebsd", target_os = "netbsd", ))] pub fn sendmmsg<'a, I, C>( fd: RawFd, data: impl std::iter::IntoIterator<Item=&'a SendMmsgData<'a, I, C>>, flags: MsgFlags ) -> Result<Vec<usize>> where I: AsRef<[IoVec<&'a [u8]>]> + 'a, C: AsRef<[ControlMessage<'a>]> + 'a, { let iter = data.into_iter(); let size_hint = iter.size_hint(); let reserve_items = size_hint.1.unwrap_or(size_hint.0); let mut output = Vec::<libc::mmsghdr>::with_capacity(reserve_items); let mut cmsgs_buffers = Vec::<Vec<u8>>::with_capacity(reserve_items); for d in iter { let capacity: usize = d.cmsgs.as_ref().iter().map(|c| c.space()).sum(); let mut cmsgs_buffer = vec![0u8; capacity]; output.push(libc::mmsghdr { msg_hdr: pack_mhdr_to_send( &mut cmsgs_buffer, &d.iov, &d.cmsgs, d.addr.as_ref() ), msg_len: 0, }); cmsgs_buffers.push(cmsgs_buffer); }; let ret = unsafe { libc::sendmmsg(fd, output.as_mut_ptr(), output.len() as _, flags.bits() as _) }; let sent_messages = Errno::result(ret)? as usize; let mut sent_bytes = Vec::with_capacity(sent_messages); for item in &output { sent_bytes.push(item.msg_len as usize); } Ok(sent_bytes) } #[cfg(any( target_os = "linux", target_os = "android", target_os = "freebsd", target_os = "netbsd", ))] #[derive(Debug)] pub struct RecvMmsgData<'a, I> where I: AsRef<[IoVec<&'a mut [u8]>]> + 'a, { pub iov: I, pub cmsg_buffer: Option<&'a mut Vec<u8>>, } /// An extension of `recvmsg` that allows the caller to receive multiple /// messages from a socket using a single system call. This has /// performance benefits for some applications. /// /// `iov` and `cmsg_buffer` should be constructed similarly to `recvmsg` /// /// Multiple allocations are performed /// /// # Arguments /// /// * `fd`: Socket file descriptor /// * `data`: Struct that implements `IntoIterator` with `RecvMmsgData` items /// * `flags`: Optional flags passed directly to the operating system. /// /// # RecvMmsgData /// /// * `iov`: Scatter-gather list of buffers to receive the message /// * `cmsg_buffer`: Space to receive ancillary data. Should be created by /// [`cmsg_space!`](macro.cmsg_space.html) /// /// # Returns /// A `Vec` with multiple `RecvMsg`, one per received message /// /// # References /// - [`recvmsg`](fn.recvmsg.html) /// - [`RecvMsg`](struct.RecvMsg.html) #[cfg(any( target_os = "linux", target_os = "android", target_os = "freebsd", target_os = "netbsd", ))] pub fn recvmmsg<'a, I>( fd: RawFd, data: impl std::iter::IntoIterator<Item=&'a mut RecvMmsgData<'a, I>, IntoIter=impl ExactSizeIterator + Iterator<Item=&'a mut RecvMmsgData<'a, I>>>, flags: MsgFlags, timeout: Option<crate::sys::time::TimeSpec> ) -> Result<Vec<RecvMsg<'a>>> where I: AsRef<[IoVec<&'a mut [u8]>]> + 'a, { let iter = data.into_iter(); let num_messages = iter.len(); let mut output: Vec<libc::mmsghdr> = Vec::with_capacity(num_messages); // Addresses should be pre-allocated. pack_mhdr_to_receive will store them // as raw pointers, so we may not move them. Turn the vec into a boxed // slice so we won't inadvertently reallocate the vec. let mut addresses = vec![mem::MaybeUninit::uninit(); num_messages] .into_boxed_slice(); let results: Vec<_> = iter.enumerate().map(|(i, d)| { let (msg_controllen, mhdr) = unsafe { pack_mhdr_to_receive( d.iov.as_ref(), &mut d.cmsg_buffer, addresses[i].as_mut_ptr(), ) }; output.push( libc::mmsghdr { msg_hdr: mhdr, msg_len: 0, } ); (msg_controllen as usize, &mut d.cmsg_buffer) }).collect(); let timeout = if let Some(mut t) = timeout { t.as_mut() as *mut libc::timespec } else { ptr::null_mut() }; let ret = unsafe { libc::recvmmsg(fd, output.as_mut_ptr(), output.len() as _, flags.bits() as _, timeout) }; let _ = Errno::result(ret)?; Ok(output .into_iter() .take(ret as usize) .zip(addresses.iter().map(|addr| unsafe{addr.assume_init()})) .zip(results.into_iter()) .map(|((mmsghdr, address), (msg_controllen, cmsg_buffer))| { unsafe { read_mhdr( mmsghdr.msg_hdr, mmsghdr.msg_len as isize, msg_controllen, address, cmsg_buffer ) } }) .collect()) } unsafe fn read_mhdr<'a, 'b>( mhdr: msghdr, r: isize, msg_controllen: usize, address: sockaddr_storage, cmsg_buffer: &'a mut Option<&'b mut Vec<u8>> ) -> RecvMsg<'b> { let cmsghdr = { if mhdr.msg_controllen > 0 { // got control message(s) cmsg_buffer .as_mut() .unwrap() .set_len(mhdr.msg_controllen as usize); debug_assert!(!mhdr.msg_control.is_null()); debug_assert!(msg_controllen >= mhdr.msg_controllen as usize); CMSG_FIRSTHDR(&mhdr as *const msghdr) } else { ptr::null() }.as_ref() }; let address = sockaddr_storage_to_addr( &address , mhdr.msg_namelen as usize ).ok(); RecvMsg { bytes: r as usize, cmsghdr, address, flags: MsgFlags::from_bits_truncate(mhdr.msg_flags), mhdr, } } unsafe fn pack_mhdr_to_receive<'a, I>( iov: I, cmsg_buffer: &mut Option<&mut Vec<u8>>, address: *mut sockaddr_storage, ) -> (usize, msghdr) where I: AsRef<[IoVec<&'a mut [u8]>]> + 'a, { let (msg_control, msg_controllen) = cmsg_buffer.as_mut() .map(|v| (v.as_mut_ptr(), v.capacity())) .unwrap_or((ptr::null_mut(), 0)); let mhdr = { // Musl's msghdr has private fields, so this is the only way to // initialize it. let mut mhdr = mem::MaybeUninit::<msghdr>::zeroed(); let p = mhdr.as_mut_ptr(); (*p).msg_name = address as *mut c_void; (*p).msg_namelen = mem::size_of::<sockaddr_storage>() as socklen_t; (*p).msg_iov = iov.as_ref().as_ptr() as *mut iovec; (*p).msg_iovlen = iov.as_ref().len() as _; (*p).msg_control = msg_control as *mut c_void; (*p).msg_controllen = msg_controllen as _; (*p).msg_flags = 0; mhdr.assume_init() }; (msg_controllen, mhdr) } fn pack_mhdr_to_send<'a, I, C>( cmsg_buffer: &mut [u8], iov: I, cmsgs: C, addr: Option<&SockAddr> ) -> msghdr where I: AsRef<[IoVec<&'a [u8]>]>, C: AsRef<[ControlMessage<'a>]> { let capacity = cmsg_buffer.len(); // Next encode the sending address, if provided let (name, namelen) = match addr { Some(addr) => { let (x, y) = addr.as_ffi_pair(); (x as *const _, y) }, None => (ptr::null(), 0), }; // The message header must be initialized before the individual cmsgs. let cmsg_ptr = if capacity > 0 { cmsg_buffer.as_ptr() as *mut c_void } else { ptr::null_mut() }; let mhdr = unsafe { // Musl's msghdr has private fields, so this is the only way to // initialize it. let mut mhdr = mem::MaybeUninit::<msghdr>::zeroed(); let p = mhdr.as_mut_ptr(); (*p).msg_name = name as *mut _; (*p).msg_namelen = namelen; // transmute iov into a mutable pointer. sendmsg doesn't really mutate // the buffer, but the standard says that it takes a mutable pointer (*p).msg_iov = iov.as_ref().as_ptr() as *mut _; (*p).msg_iovlen = iov.as_ref().len() as _; (*p).msg_control = cmsg_ptr; (*p).msg_controllen = capacity as _; (*p).msg_flags = 0; mhdr.assume_init() }; // Encode each cmsg. This must happen after initializing the header because // CMSG_NEXT_HDR and friends read the msg_control and msg_controllen fields. // CMSG_FIRSTHDR is always safe let mut pmhdr: *mut cmsghdr = unsafe { CMSG_FIRSTHDR(&mhdr as *const msghdr) }; for cmsg in cmsgs.as_ref() { assert_ne!(pmhdr, ptr::null_mut()); // Safe because we know that pmhdr is valid, and we initialized it with // sufficient space unsafe { cmsg.encode_into(pmhdr) }; // Safe because mhdr is valid pmhdr = unsafe { CMSG_NXTHDR(&mhdr as *const msghdr, pmhdr) }; } mhdr } /// Receive message in scatter-gather vectors from a socket, and /// optionally receive ancillary data into the provided buffer. /// If no ancillary data is desired, use () as the type parameter. /// /// # Arguments /// /// * `fd`: Socket file descriptor /// * `iov`: Scatter-gather list of buffers to receive the message /// * `cmsg_buffer`: Space to receive ancillary data. Should be created by /// [`cmsg_space!`](macro.cmsg_space.html) /// * `flags`: Optional flags passed directly to the operating system. /// /// # References /// [recvmsg(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/recvmsg.html) pub fn recvmsg<'a>(fd: RawFd, iov: &[IoVec<&mut [u8]>], mut cmsg_buffer: Option<&'a mut Vec<u8>>, flags: MsgFlags) -> Result<RecvMsg<'a>> { let mut address = mem::MaybeUninit::uninit(); let (msg_controllen, mut mhdr) = unsafe { pack_mhdr_to_receive(&iov, &mut cmsg_buffer, address.as_mut_ptr()) }; let ret = unsafe { libc::recvmsg(fd, &mut mhdr, flags.bits()) }; let r = Errno::result(ret)?; Ok(unsafe { read_mhdr(mhdr, r, msg_controllen, address.assume_init(), &mut cmsg_buffer) }) } /// Create an endpoint for communication /// /// The `protocol` specifies a particular protocol to be used with the /// socket. Normally only a single protocol exists to support a /// particular socket type within a given protocol family, in which case /// protocol can be specified as `None`. However, it is possible that many /// protocols may exist, in which case a particular protocol must be /// specified in this manner. /// /// [Further reading](https://pubs.opengroup.org/onlinepubs/9699919799/functions/socket.html) pub fn socket<T: Into<Option<SockProtocol>>>(domain: AddressFamily, ty: SockType, flags: SockFlag, protocol: T) -> Result<RawFd> { let protocol = match protocol.into() { None => 0, Some(p) => p as c_int, }; // SockFlags are usually embedded into `ty`, but we don't do that in `nix` because it's a // little easier to understand by separating it out. So we have to merge these bitfields // here. let mut ty = ty as c_int; ty |= flags.bits(); let res = unsafe { libc::socket(domain as c_int, ty, protocol) }; Errno::result(res) } /// Create a pair of connected sockets /// /// [Further reading](https://pubs.opengroup.org/onlinepubs/9699919799/functions/socketpair.html) pub fn socketpair<T: Into<Option<SockProtocol>>>(domain: AddressFamily, ty: SockType, protocol: T, flags: SockFlag) -> Result<(RawFd, RawFd)> { let protocol = match protocol.into() { None => 0, Some(p) => p as c_int, }; // SockFlags are usually embedded into `ty`, but we don't do that in `nix` because it's a // little easier to understand by separating it out. So we have to merge these bitfields // here. let mut ty = ty as c_int; ty |= flags.bits(); let mut fds = [-1, -1]; let res = unsafe { libc::socketpair(domain as c_int, ty, protocol, fds.as_mut_ptr()) }; Errno::result(res)?; Ok((fds[0], fds[1])) } /// Listen for connections on a socket /// /// [Further reading](https://pubs.opengroup.org/onlinepubs/9699919799/functions/listen.html) pub fn listen(sockfd: RawFd, backlog: usize) -> Result<()> { let res = unsafe { libc::listen(sockfd, backlog as c_int) }; Errno::result(res).map(drop) } /// Bind a name to a socket /// /// [Further reading](https://pubs.opengroup.org/onlinepubs/9699919799/functions/bind.html) pub fn bind(fd: RawFd, addr: &SockAddr) -> Result<()> { let res = unsafe { let (ptr, len) = addr.as_ffi_pair(); libc::bind(fd, ptr, len) }; Errno::result(res).map(drop) } /// Accept a connection on a socket /// /// [Further reading](https://pubs.opengroup.org/onlinepubs/9699919799/functions/accept.html) pub fn accept(sockfd: RawFd) -> Result<RawFd> { let res = unsafe { libc::accept(sockfd, ptr::null_mut(), ptr::null_mut()) }; Errno::result(res) } /// Accept a connection on a socket /// /// [Further reading](https://man7.org/linux/man-pages/man2/accept.2.html) #[cfg(any(all( target_os = "android", any( target_arch = "aarch64", target_arch = "x86", target_arch = "x86_64" ) ), target_os = "freebsd", target_os = "linux", target_os = "openbsd"))] pub fn accept4(sockfd: RawFd, flags: SockFlag) -> Result<RawFd> { let res = unsafe { libc::accept4(sockfd, ptr::null_mut(), ptr::null_mut(), flags.bits()) }; Errno::result(res) } /// Initiate a connection on a socket /// /// [Further reading](https://pubs.opengroup.org/onlinepubs/9699919799/functions/connect.html) pub fn connect(fd: RawFd, addr: &SockAddr) -> Result<()> { let res = unsafe { let (ptr, len) = addr.as_ffi_pair(); libc::connect(fd, ptr, len) }; Errno::result(res).map(drop) } /// Receive data from a connection-oriented socket. Returns the number of /// bytes read /// /// [Further reading](https://pubs.opengroup.org/onlinepubs/9699919799/functions/recv.html) pub fn recv(sockfd: RawFd, buf: &mut [u8], flags: MsgFlags) -> Result<usize> { unsafe { let ret = libc::recv( sockfd, buf.as_ptr() as *mut c_void, buf.len() as size_t, flags.bits()); Errno::result(ret).map(|r| r as usize) } } /// Receive data from a connectionless or connection-oriented socket. Returns /// the number of bytes read and, for connectionless sockets, the socket /// address of the sender. /// /// [Further reading](https://pubs.opengroup.org/onlinepubs/9699919799/functions/recvfrom.html) pub fn recvfrom(sockfd: RawFd, buf: &mut [u8]) -> Result<(usize, Option<SockAddr>)> { unsafe { let mut addr: sockaddr_storage = mem::zeroed(); let mut len = mem::size_of::<sockaddr_storage>() as socklen_t; let ret = Errno::result(libc::recvfrom( sockfd, buf.as_ptr() as *mut c_void, buf.len() as size_t, 0, &mut addr as *mut libc::sockaddr_storage as *mut libc::sockaddr, &mut len as *mut socklen_t))? as usize; match sockaddr_storage_to_addr(&addr, len as usize) { Err(Errno::ENOTCONN) => Ok((ret, None)), Ok(addr) => Ok((ret, Some(addr))), Err(e) => Err(e) } } } /// Send a message to a socket /// /// [Further reading](https://pubs.opengroup.org/onlinepubs/9699919799/functions/sendto.html) pub fn sendto(fd: RawFd, buf: &[u8], addr: &SockAddr, flags: MsgFlags) -> Result<usize> { let ret = unsafe { let (ptr, len) = addr.as_ffi_pair(); libc::sendto(fd, buf.as_ptr() as *const c_void, buf.len() as size_t, flags.bits(), ptr, len) }; Errno::result(ret).map(|r| r as usize) } /// Send data to a connection-oriented socket. Returns the number of bytes read /// /// [Further reading](https://pubs.opengroup.org/onlinepubs/9699919799/functions/send.html) pub fn send(fd: RawFd, buf: &[u8], flags: MsgFlags) -> Result<usize> { let ret = unsafe { libc::send(fd, buf.as_ptr() as *const c_void, buf.len() as size_t, flags.bits()) }; Errno::result(ret).map(|r| r as usize) } /* * * ===== Socket Options ===== * */ /// Represents a socket option that can be accessed or set. Used as an argument /// to `getsockopt` pub trait GetSockOpt : Copy { type Val; #[doc(hidden)] fn get(&self, fd: RawFd) -> Result<Self::Val>; } /// Represents a socket option that can be accessed or set. Used as an argument /// to `setsockopt` pub trait SetSockOpt : Clone { type Val; #[doc(hidden)] fn set(&self, fd: RawFd, val: &Self::Val) -> Result<()>; } /// Get the current value for the requested socket option /// /// [Further reading](https://pubs.opengroup.org/onlinepubs/9699919799/functions/getsockopt.html) pub fn getsockopt<O: GetSockOpt>(fd: RawFd, opt: O) -> Result<O::Val> { opt.get(fd) } /// Sets the value for the requested socket option /// /// [Further reading](https://pubs.opengroup.org/onlinepubs/9699919799/functions/setsockopt.html) /// /// # Examples /// /// ``` /// use nix::sys::socket::setsockopt; /// use nix::sys::socket::sockopt::KeepAlive; /// use std::net::TcpListener; /// use std::os::unix::io::AsRawFd; /// /// let listener = TcpListener::bind("0.0.0.0:0").unwrap(); /// let fd = listener.as_raw_fd(); /// let res = setsockopt(fd, KeepAlive, &true); /// assert!(res.is_ok()); /// ``` pub fn setsockopt<O: SetSockOpt>(fd: RawFd, opt: O, val: &O::Val) -> Result<()> { opt.set(fd, val) } /// Get the address of the peer connected to the socket `fd`. /// /// [Further reading](https://pubs.opengroup.org/onlinepubs/9699919799/functions/getpeername.html) pub fn getpeername(fd: RawFd) -> Result<SockAddr> { unsafe { let mut addr = mem::MaybeUninit::uninit(); let mut len = mem::size_of::<sockaddr_storage>() as socklen_t; let ret = libc::getpeername( fd, addr.as_mut_ptr() as *mut libc::sockaddr, &mut len ); Errno::result(ret)?; sockaddr_storage_to_addr(&addr.assume_init(), len as usize) } } /// Get the current address to which the socket `fd` is bound. /// /// [Further reading](https://pubs.opengroup.org/onlinepubs/9699919799/functions/getsockname.html) pub fn getsockname(fd: RawFd) -> Result<SockAddr> { unsafe { let mut addr = mem::MaybeUninit::uninit(); let mut len = mem::size_of::<sockaddr_storage>() as socklen_t; let ret = libc::getsockname( fd, addr.as_mut_ptr() as *mut libc::sockaddr, &mut len ); Errno::result(ret)?; sockaddr_storage_to_addr(&addr.assume_init(), len as usize) } } /// Return the appropriate `SockAddr` type from a `sockaddr_storage` of a /// certain size. /// /// In C this would usually be done by casting. The `len` argument /// should be the number of bytes in the `sockaddr_storage` that are actually /// allocated and valid. It must be at least as large as all the useful parts /// of the structure. Note that in the case of a `sockaddr_un`, `len` need not /// include the terminating null. pub fn sockaddr_storage_to_addr( addr: &sockaddr_storage, len: usize) -> Result<SockAddr> { assert!(len <= mem::size_of::<sockaddr_storage>()); if len < mem::size_of_val(&addr.ss_family) { return Err(Error::from(Errno::ENOTCONN)); } match c_int::from(addr.ss_family) { libc::AF_INET => { assert!(len as usize >= mem::size_of::<sockaddr_in>()); let sin = unsafe { *(addr as *const sockaddr_storage as *const sockaddr_in) }; Ok(SockAddr::Inet(InetAddr::V4(sin))) } libc::AF_INET6 => { assert!(len as usize >= mem::size_of::<sockaddr_in6>()); let sin6 = unsafe { *(addr as *const _ as *const sockaddr_in6) }; Ok(SockAddr::Inet(InetAddr::V6(sin6))) } libc::AF_UNIX => { let pathlen = len - offset_of!(sockaddr_un, sun_path); let sun = unsafe { *(addr as *const _ as *const sockaddr_un) }; Ok(SockAddr::Unix(UnixAddr(sun, pathlen))) } #[cfg(any(target_os = "android", target_os = "linux"))] libc::AF_PACKET => { use libc::sockaddr_ll; // Don't assert anything about the size. // Apparently the Linux kernel can return smaller sizes when // the value in the last element of sockaddr_ll (`sll_addr`) is // smaller than the declared size of that field let sll = unsafe { *(addr as *const _ as *const sockaddr_ll) }; Ok(SockAddr::Link(LinkAddr(sll))) } #[cfg(any(target_os = "android", target_os = "linux"))] libc::AF_NETLINK => { use libc::sockaddr_nl; let snl = unsafe { *(addr as *const _ as *const sockaddr_nl) }; Ok(SockAddr::Netlink(NetlinkAddr(snl))) } #[cfg(any(target_os = "android", target_os = "linux"))] libc::AF_ALG => { use libc::sockaddr_alg; let salg = unsafe { *(addr as *const _ as *const sockaddr_alg) }; Ok(SockAddr::Alg(AlgAddr(salg))) } #[cfg(any(target_os = "android", target_os = "linux"))] libc::AF_VSOCK => { use libc::sockaddr_vm; let svm = unsafe { *(addr as *const _ as *const sockaddr_vm) }; Ok(SockAddr::Vsock(VsockAddr(svm))) } af => panic!("unexpected address family {}", af), } } #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub enum Shutdown { /// Further receptions will be disallowed. Read, /// Further transmissions will be disallowed. Write, /// Further receptions and transmissions will be disallowed. Both, } /// Shut down part of a full-duplex connection. /// /// [Further reading](https://pubs.opengroup.org/onlinepubs/9699919799/functions/shutdown.html) pub fn shutdown(df: RawFd, how: Shutdown) -> Result<()> { unsafe { use libc::shutdown; let how = match how { Shutdown::Read => libc::SHUT_RD, Shutdown::Write => libc::SHUT_WR, Shutdown::Both => libc::SHUT_RDWR, }; Errno::result(shutdown(df, how)).map(drop) } } #[cfg(test)] mod tests { #[test] fn can_use_cmsg_space() { let _ = cmsg_space!(u8); } }
36.706631
130
0.581397
[ "#[cfg(test)]\nmod tests {\n use super::*;\n #[test]\n fn can_use_cmsg_space() {\n let _ = cmsg_space!(u8);\n }\n}" ]
f701cc09ffa27d21e22cd3cddb86c098ad91ff22
9,309
rs
Rust
src/util.rs
alpearce/rust-tuf
4d4fa7330ba105481c0c4018a57e15efdb27be98
[ "Apache-2.0", "MIT" ]
null
null
null
src/util.rs
alpearce/rust-tuf
4d4fa7330ba105481c0c4018a57e15efdb27be98
[ "Apache-2.0", "MIT" ]
null
null
null
src/util.rs
alpearce/rust-tuf
4d4fa7330ba105481c0c4018a57e15efdb27be98
[ "Apache-2.0", "MIT" ]
null
null
null
use chrono::offset::Utc; use chrono::DateTime; use futures_io::AsyncRead; use futures_util::ready; use ring::digest::{self, SHA256, SHA512}; use std::io::{self, ErrorKind}; use std::marker::Unpin; use std::pin::Pin; use std::task::{Context, Poll}; use crate::crypto::{HashAlgorithm, HashValue}; use crate::error::Error; use crate::Result; /// Wrapper to verify a byte stream as it is read. /// /// Wraps a `Read` to ensure that the consumer can't read more than a capped maximum number of /// bytes. Also, this ensures that a minimum bitrate and returns an `Err` if it is not. Finally, /// when the underlying `Read` is fully consumed, the hash of the data is optionally calculated. If /// the calculated hash does not match the given hash, it will return an `Err`. Consumers of a /// `SafeReader` should purge and untrust all read bytes if this ever returns an `Err`. /// /// It is **critical** that none of the bytes from this struct are used until it has been fully /// consumed as the data is untrusted. pub struct SafeReader<R> { inner: R, max_size: u64, min_bytes_per_second: u32, hasher: Option<(digest::Context, HashValue)>, start_time: Option<DateTime<Utc>>, bytes_read: u64, } impl<R: AsyncRead> SafeReader<R> { /// Create a new `SafeReader`. /// /// The argument `hash_data` takes a `HashAlgorithm` and expected `HashValue`. The given /// algorithm is used to hash the data as it is read. At the end of the stream, the digest is /// calculated and compared against `HashValue`. If the two are not equal, it means the data /// stream has been tampered with in some way. pub fn new( read: R, max_size: u64, min_bytes_per_second: u32, hash_data: Option<(&HashAlgorithm, HashValue)>, ) -> Result<Self> { let hasher = match hash_data { Some((alg, value)) => { let ctx = match *alg { HashAlgorithm::Sha256 => digest::Context::new(&SHA256), HashAlgorithm::Sha512 => digest::Context::new(&SHA512), HashAlgorithm::Unknown(ref s) => { return Err(Error::IllegalArgument(format!( "Unknown hash algorithm: {}", s ))); } }; Some((ctx, value)) } None => None, }; Ok(SafeReader { inner: read, max_size, min_bytes_per_second, hasher, start_time: None, bytes_read: 0, }) } } impl<R: AsyncRead + Unpin> AsyncRead for SafeReader<R> { fn poll_read( mut self: Pin<&mut Self>, cx: &mut Context, buf: &mut [u8], ) -> Poll<io::Result<usize>> { let read_bytes = ready!(Pin::new(&mut self.inner).poll_read(cx, buf))?; if self.start_time.is_none() { self.start_time = Some(Utc::now()) } if read_bytes == 0 { if let Some((context, expected_hash)) = self.hasher.take() { let generated_hash = context.finish(); if generated_hash.as_ref() != expected_hash.value() { return Poll::Ready(Err(io::Error::new( ErrorKind::InvalidData, "Calculated hash did not match the required hash.", ))); } } return Poll::Ready(Ok(0)); } match self.bytes_read.checked_add(read_bytes as u64) { Some(sum) if sum <= self.max_size => self.bytes_read = sum, _ => { return Poll::Ready(Err(io::Error::new( ErrorKind::InvalidData, "Read exceeded the maximum allowed bytes.", ))); } } let duration = Utc::now().signed_duration_since(self.start_time.unwrap()); // 30 second grace period before we start checking the bitrate if duration.num_seconds() >= 30 { if (self.bytes_read as f32) / (duration.num_seconds() as f32) < self.min_bytes_per_second as f32 { return Poll::Ready(Err(io::Error::new( ErrorKind::TimedOut, "Read aborted. Bitrate too low.", ))); } } if let Some((ref mut context, _)) = self.hasher { context.update(&buf[..(read_bytes)]); } Poll::Ready(Ok(read_bytes)) } } #[cfg(test)] mod test { use super::*; use futures_executor::block_on; use futures_util::io::AsyncReadExt; #[test] fn valid_read() { block_on(async { let bytes: &[u8] = &[0x00, 0x01, 0x02, 0x03]; let mut reader = SafeReader::new(bytes, bytes.len() as u64, 0, None).unwrap(); let mut buf = Vec::new(); assert!(reader.read_to_end(&mut buf).await.is_ok()); assert_eq!(buf, bytes); }) } #[test] fn valid_read_large_data() { block_on(async { let bytes: &[u8] = &[0x00; 64 * 1024]; let mut reader = SafeReader::new(bytes, bytes.len() as u64, 0, None).unwrap(); let mut buf = Vec::new(); assert!(reader.read_to_end(&mut buf).await.is_ok()); assert_eq!(buf, bytes); }) } #[test] fn valid_read_below_max_size() { block_on(async { let bytes: &[u8] = &[0x00, 0x01, 0x02, 0x03]; let mut reader = SafeReader::new(bytes, (bytes.len() as u64) + 1, 0, None).unwrap(); let mut buf = Vec::new(); assert!(reader.read_to_end(&mut buf).await.is_ok()); assert_eq!(buf, bytes); }) } #[test] fn invalid_read_above_max_size() { block_on(async { let bytes: &[u8] = &[0x00, 0x01, 0x02, 0x03]; let mut reader = SafeReader::new(bytes, (bytes.len() as u64) - 1, 0, None).unwrap(); let mut buf = Vec::new(); assert!(reader.read_to_end(&mut buf).await.is_err()); }) } #[test] fn invalid_read_above_max_size_large_data() { block_on(async { let bytes: &[u8] = &[0x00; 64 * 1024]; let mut reader = SafeReader::new(bytes, (bytes.len() as u64) - 1, 0, None).unwrap(); let mut buf = Vec::new(); assert!(reader.read_to_end(&mut buf).await.is_err()); }) } #[test] fn valid_read_good_hash() { block_on(async { let bytes: &[u8] = &[0x00, 0x01, 0x02, 0x03]; let mut context = digest::Context::new(&SHA256); context.update(&bytes); let hash_value = HashValue::new(context.finish().as_ref().to_vec()); let mut reader = SafeReader::new( bytes, bytes.len() as u64, 0, Some((&HashAlgorithm::Sha256, hash_value)), ) .unwrap(); let mut buf = Vec::new(); assert!(reader.read_to_end(&mut buf).await.is_ok()); assert_eq!(buf, bytes); }) } #[test] fn invalid_read_bad_hash() { block_on(async { let bytes: &[u8] = &[0x00, 0x01, 0x02, 0x03]; let mut context = digest::Context::new(&SHA256); context.update(&bytes); context.update(&[0xFF]); // evil bytes let hash_value = HashValue::new(context.finish().as_ref().to_vec()); let mut reader = SafeReader::new( bytes, bytes.len() as u64, 0, Some((&HashAlgorithm::Sha256, hash_value)), ) .unwrap(); let mut buf = Vec::new(); assert!(reader.read_to_end(&mut buf).await.is_err()); }) } #[test] fn valid_read_good_hash_large_data() { block_on(async { let bytes: &[u8] = &[0x00; 64 * 1024]; let mut context = digest::Context::new(&SHA256); context.update(&bytes); let hash_value = HashValue::new(context.finish().as_ref().to_vec()); let mut reader = SafeReader::new( bytes, bytes.len() as u64, 0, Some((&HashAlgorithm::Sha256, hash_value)), ) .unwrap(); let mut buf = Vec::new(); assert!(reader.read_to_end(&mut buf).await.is_ok()); assert_eq!(buf, bytes); }) } #[test] fn invalid_read_bad_hash_large_data() { block_on(async { let bytes: &[u8] = &[0x00; 64 * 1024]; let mut context = digest::Context::new(&SHA256); context.update(&bytes); context.update(&[0xFF]); // evil bytes let hash_value = HashValue::new(context.finish().as_ref().to_vec()); let mut reader = SafeReader::new( bytes, bytes.len() as u64, 0, Some((&HashAlgorithm::Sha256, hash_value)), ) .unwrap(); let mut buf = Vec::new(); assert!(reader.read_to_end(&mut buf).await.is_err()); }) } }
34.350554
99
0.520034
[ "#[cfg(test)]\nmod tests {\n use super::*;\n #[test]\n fn valid_read() {\n block_on(async {\n let bytes: &[u8] = &[0x00, 0x01, 0x02, 0x03];\n let mut reader = SafeReader::new(bytes, bytes.len() as u64, 0, None).unwrap();\n let mut buf = Vec::new();\n assert!(reader.read_to_end(&mut buf).await.is_ok());\n assert_eq!(buf, bytes);\n })\n }\n}", "#[cfg(test)]\nmod tests {\n use super::*;\n #[test]\n fn valid_read_large_data() {\n block_on(async {\n let bytes: &[u8] = &[0x00; 64 * 1024];\n let mut reader = SafeReader::new(bytes, bytes.len() as u64, 0, None).unwrap();\n let mut buf = Vec::new();\n assert!(reader.read_to_end(&mut buf).await.is_ok());\n assert_eq!(buf, bytes);\n })\n }\n}", "#[cfg(test)]\nmod tests {\n use super::*;\n #[test]\n fn valid_read_below_max_size() {\n block_on(async {\n let bytes: &[u8] = &[0x00, 0x01, 0x02, 0x03];\n let mut reader = SafeReader::new(bytes, (bytes.len() as u64) + 1, 0, None).unwrap();\n let mut buf = Vec::new();\n assert!(reader.read_to_end(&mut buf).await.is_ok());\n assert_eq!(buf, bytes);\n })\n }\n}", "#[cfg(test)]\nmod tests {\n use super::*;\n #[test]\n fn invalid_read_above_max_size() {\n block_on(async {\n let bytes: &[u8] = &[0x00, 0x01, 0x02, 0x03];\n let mut reader = SafeReader::new(bytes, (bytes.len() as u64) - 1, 0, None).unwrap();\n let mut buf = Vec::new();\n assert!(reader.read_to_end(&mut buf).await.is_err());\n })\n }\n}", "#[cfg(test)]\nmod tests {\n use super::*;\n #[test]\n fn invalid_read_above_max_size_large_data() {\n block_on(async {\n let bytes: &[u8] = &[0x00; 64 * 1024];\n let mut reader = SafeReader::new(bytes, (bytes.len() as u64) - 1, 0, None).unwrap();\n let mut buf = Vec::new();\n assert!(reader.read_to_end(&mut buf).await.is_err());\n })\n }\n}", "#[cfg(test)]\nmod tests {\n use super::*;\n #[test]\n fn valid_read_good_hash() {\n block_on(async {\n let bytes: &[u8] = &[0x00, 0x01, 0x02, 0x03];\n let mut context = digest::Context::new(&SHA256);\n context.update(&bytes);\n let hash_value = HashValue::new(context.finish().as_ref().to_vec());\n let mut reader = SafeReader::new(\n bytes,\n bytes.len() as u64,\n 0,\n Some((&HashAlgorithm::Sha256, hash_value)),\n )\n .unwrap();\n let mut buf = Vec::new();\n assert!(reader.read_to_end(&mut buf).await.is_ok());\n assert_eq!(buf, bytes);\n })\n }\n}", "#[cfg(test)]\nmod tests {\n use super::*;\n #[test]\n fn invalid_read_bad_hash() {\n block_on(async {\n let bytes: &[u8] = &[0x00, 0x01, 0x02, 0x03];\n let mut context = digest::Context::new(&SHA256);\n context.update(&bytes);\n context.update(&[0xFF]); // evil bytes\n let hash_value = HashValue::new(context.finish().as_ref().to_vec());\n let mut reader = SafeReader::new(\n bytes,\n bytes.len() as u64,\n 0,\n Some((&HashAlgorithm::Sha256, hash_value)),\n )\n .unwrap();\n let mut buf = Vec::new();\n assert!(reader.read_to_end(&mut buf).await.is_err());\n })\n }\n}", "#[cfg(test)]\nmod tests {\n use super::*;\n #[test]\n fn valid_read_good_hash_large_data() {\n block_on(async {\n let bytes: &[u8] = &[0x00; 64 * 1024];\n let mut context = digest::Context::new(&SHA256);\n context.update(&bytes);\n let hash_value = HashValue::new(context.finish().as_ref().to_vec());\n let mut reader = SafeReader::new(\n bytes,\n bytes.len() as u64,\n 0,\n Some((&HashAlgorithm::Sha256, hash_value)),\n )\n .unwrap();\n let mut buf = Vec::new();\n assert!(reader.read_to_end(&mut buf).await.is_ok());\n assert_eq!(buf, bytes);\n })\n }\n}", "#[cfg(test)]\nmod tests {\n use super::*;\n #[test]\n fn invalid_read_bad_hash_large_data() {\n block_on(async {\n let bytes: &[u8] = &[0x00; 64 * 1024];\n let mut context = digest::Context::new(&SHA256);\n context.update(&bytes);\n context.update(&[0xFF]); // evil bytes\n let hash_value = HashValue::new(context.finish().as_ref().to_vec());\n let mut reader = SafeReader::new(\n bytes,\n bytes.len() as u64,\n 0,\n Some((&HashAlgorithm::Sha256, hash_value)),\n )\n .unwrap();\n let mut buf = Vec::new();\n assert!(reader.read_to_end(&mut buf).await.is_err());\n })\n }\n}" ]
f7023ef38590c3d50f3eb561efad5d6f442fdacb
9,332
rs
Rust
src/serialization/v1.rs
akkoro/macaroon
6015828846f11251248fcdd717e015c33bab8b70
[ "MIT" ]
14
2020-05-26T07:49:44.000Z
2022-01-16T22:16:03.000Z
src/serialization/v1.rs
akkoro/macaroon
6015828846f11251248fcdd717e015c33bab8b70
[ "MIT" ]
40
2020-05-11T11:34:28.000Z
2022-03-23T12:19:48.000Z
src/serialization/v1.rs
akkoro/macaroon
6015828846f11251248fcdd717e015c33bab8b70
[ "MIT" ]
5
2020-09-10T08:15:16.000Z
2021-10-31T05:44:25.000Z
use caveat::{Caveat, CaveatBuilder}; use error::MacaroonError; use serialization::macaroon_builder::MacaroonBuilder; use std::str; use ByteString; use Macaroon; use Result; // Version 1 fields const LOCATION: &str = "location"; const IDENTIFIER: &str = "identifier"; const SIGNATURE: &str = "signature"; const CID: &str = "cid"; const VID: &str = "vid"; const CL: &str = "cl"; const HEADER_SIZE: usize = 4; fn serialize_as_packet<'r>(tag: &'r str, value: &'r [u8]) -> Vec<u8> { let mut packet: Vec<u8> = Vec::new(); let size = HEADER_SIZE + 2 + tag.len() + value.len(); packet.extend(packet_header(size)); packet.extend_from_slice(tag.as_bytes()); packet.extend_from_slice(b" "); packet.extend_from_slice(value); packet.extend_from_slice(b"\n"); packet } fn to_hex_char(value: u8) -> u8 { let hex = format!("{:1x}", value); hex.as_bytes()[0] } fn packet_header(size: usize) -> Vec<u8> { vec![ to_hex_char(((size >> 12) & 15) as u8), to_hex_char(((size >> 8) & 15) as u8), to_hex_char(((size >> 4) & 15) as u8), to_hex_char((size & 15) as u8), ] } pub fn serialize(macaroon: &Macaroon) -> Result<Vec<u8>> { let mut serialized: Vec<u8> = Vec::new(); if let Some(ref location) = macaroon.location() { serialized.extend(serialize_as_packet(LOCATION, location.as_bytes())); }; serialized.extend(serialize_as_packet(IDENTIFIER, &macaroon.identifier().0)); for c in macaroon.caveats() { match c { Caveat::FirstParty(fp) => { serialized.extend(serialize_as_packet(CID, &fp.predicate().0)); } Caveat::ThirdParty(tp) => { serialized.extend(serialize_as_packet(CID, &tp.id().0)); serialized.extend(serialize_as_packet(VID, &tp.verifier_id().0)); serialized.extend(serialize_as_packet(CL, tp.location().as_bytes())) } } } serialized.extend(serialize_as_packet(SIGNATURE, &macaroon.signature())); Ok(base64::encode_config(&serialized, base64::URL_SAFE) .as_bytes() .to_vec()) } fn base64_decode(s: &str) -> Result<Vec<u8>> { Ok(base64::decode_config(s, base64::URL_SAFE)?) } struct Packet { key: String, value: Vec<u8>, } fn deserialize_as_packets(data: &[u8], mut packets: Vec<Packet>) -> Result<Vec<Packet>> { if data.is_empty() { return Ok(packets); } let hex: &str = str::from_utf8(&data[..4])?; let size: usize = usize::from_str_radix(hex, 16)?; let packet_data = &data[4..size]; let index = split_index(packet_data)?; let (key_slice, value_slice) = packet_data.split_at(index); packets.push(Packet { key: String::from_utf8(key_slice.to_vec())?, // skip beginning space and terminating \n value: value_slice[1..value_slice.len() - 1].to_vec(), }); deserialize_as_packets(&data[size..], packets) } fn split_index(packet: &[u8]) -> Result<usize> { match packet.iter().position(|&r| r == b' ') { Some(index) => Ok(index), None => Err(MacaroonError::DeserializationError(String::from( "Key/value error", ))), } } pub fn deserialize(base64: &[u8]) -> Result<Macaroon> { let data = base64_decode(&String::from_utf8(base64.to_vec())?)?; let mut builder: MacaroonBuilder = MacaroonBuilder::new(); let mut caveat_builder: CaveatBuilder = CaveatBuilder::new(); for packet in deserialize_as_packets(data.as_slice(), Vec::new())? { match packet.key.as_str() { LOCATION => { builder.set_location(&String::from_utf8(packet.value)?); } IDENTIFIER => { builder.set_identifier(ByteString(packet.value)); } SIGNATURE => { if caveat_builder.has_id() { builder.add_caveat(caveat_builder.build()?); caveat_builder = CaveatBuilder::new(); } if packet.value.len() != 32 { error!( "deserialize_v1: Deserialization error - signature length is {}", packet.value.len() ); return Err(MacaroonError::DeserializationError(String::from( "Illegal signature \ length in \ packet", ))); } builder.set_signature(&packet.value); } CID => { if caveat_builder.has_id() { builder.add_caveat(caveat_builder.build()?); caveat_builder = CaveatBuilder::new(); caveat_builder.add_id(ByteString(packet.value)); } else { caveat_builder.add_id(ByteString(packet.value)); } } VID => { caveat_builder.add_verifier_id(ByteString(packet.value)); } CL => caveat_builder.add_location(String::from_utf8(packet.value)?), _ => { return Err(MacaroonError::DeserializationError(String::from( "Unknown key", ))) } }; } builder.build() } #[cfg(test)] mod tests { use ByteString; use Caveat; use Macaroon; use MacaroonKey; #[test] fn test_deserialize() { let mut serialized = "MDAyMWxvY2F0aW9uIGh0dHA6Ly9leGFtcGxlLm9yZy8KMDAxNWlkZW50aWZpZXIga2V5aWQKMDAyZnNpZ25hdHVyZSB83ueSURxbxvUoSFgF3-myTnheKOKpkwH51xHGCeOO9wo"; let mut signature: MacaroonKey = [ 124, 222, 231, 146, 81, 28, 91, 198, 245, 40, 72, 88, 5, 223, 233, 178, 78, 120, 94, 40, 226, 169, 147, 1, 249, 215, 17, 198, 9, 227, 142, 247, ] .into(); let macaroon = super::deserialize(&serialized.as_bytes().to_vec()).unwrap(); assert!(macaroon.location().is_some()); assert_eq!("http://example.org/", &macaroon.location().unwrap()); assert_eq!(ByteString::from("keyid"), macaroon.identifier()); assert_eq!(signature, macaroon.signature()); serialized = "MDAyMWxvY2F0aW9uIGh0dHA6Ly9leGFtcGxlLm9yZy8KMDAxNWlkZW50aWZpZXIga2V5aWQKMDAxZGNpZCBhY2NvdW50ID0gMzczNTkyODU1OQowMDJmc2lnbmF0dXJlIPVIB_bcbt-Ivw9zBrOCJWKjYlM9v3M5umF2XaS9JZ2HCg"; signature = [ 245, 72, 7, 246, 220, 110, 223, 136, 191, 15, 115, 6, 179, 130, 37, 98, 163, 98, 83, 61, 191, 115, 57, 186, 97, 118, 93, 164, 189, 37, 157, 135, ] .into(); let macaroon = super::deserialize(&serialized.as_bytes().to_vec()).unwrap(); assert!(macaroon.location().is_some()); assert_eq!("http://example.org/", &macaroon.location().unwrap()); assert_eq!(ByteString::from("keyid"), macaroon.identifier()); assert_eq!(1, macaroon.caveats().len()); let predicate = match &macaroon.caveats()[0] { Caveat::FirstParty(fp) => fp.predicate(), _ => ByteString::default(), }; assert_eq!(ByteString::from("account = 3735928559"), predicate); assert_eq!(signature, macaroon.signature()); } #[test] fn test_deserialize_two_caveats() { let serialized = "MDAyMWxvY2F0aW9uIGh0dHA6Ly9leGFtcGxlLm9yZy8KMDAxNWlkZW50aWZpZXIga2V5aWQKMDAxZGNpZCBhY2NvdW50ID0gMzczNTkyODU1OQowMDE1Y2lkIHVzZXIgPSBhbGljZQowMDJmc2lnbmF0dXJlIEvpZ80eoMaya69qSpTumwWxWIbaC6hejEKpPI0OEl78Cg"; let signature: MacaroonKey = [ 75, 233, 103, 205, 30, 160, 198, 178, 107, 175, 106, 74, 148, 238, 155, 5, 177, 88, 134, 218, 11, 168, 94, 140, 66, 169, 60, 141, 14, 18, 94, 252, ] .into(); let macaroon = super::deserialize(&serialized.as_bytes().to_vec()).unwrap(); assert!(macaroon.location().is_some()); assert_eq!("http://example.org/", &macaroon.location().unwrap()); assert_eq!(ByteString::from("keyid"), macaroon.identifier()); assert_eq!(signature, macaroon.signature()); assert_eq!(2, macaroon.caveats().len()); let predicate = match &macaroon.caveats()[0] { Caveat::FirstParty(fp) => fp.predicate(), _ => ByteString::default(), }; assert_eq!(ByteString::from("account = 3735928559"), predicate); let predicate = match &macaroon.caveats()[1] { Caveat::FirstParty(fp) => fp.predicate(), _ => ByteString::default(), }; assert_eq!(ByteString::from("user = alice"), predicate); } #[test] fn test_serialize_deserialize() { let mut macaroon: Macaroon = Macaroon::create( Some("http://example.org/".into()), &"my key".into(), "keyid".into(), ) .unwrap(); macaroon.add_first_party_caveat("account = 3735928559".into()); macaroon.add_first_party_caveat("user = alice".into()); macaroon.add_third_party_caveat( "https://auth.mybank.com", &"caveat key".into(), "caveat".into(), ); let serialized = macaroon.serialize(super::super::Format::V1).unwrap(); let deserialized = Macaroon::deserialize(&serialized).unwrap(); assert_eq!(macaroon, deserialized); } }
38.561983
230
0.583155
[ "#[cfg(test)]\nmod tests {\n use super::*;\n #[test]\n fn test_deserialize() {\n let mut serialized = \"MDAyMWxvY2F0aW9uIGh0dHA6Ly9leGFtcGxlLm9yZy8KMDAxNWlkZW50aWZpZXIga2V5aWQKMDAyZnNpZ25hdHVyZSB83ueSURxbxvUoSFgF3-myTnheKOKpkwH51xHGCeOO9wo\";\n let mut signature: MacaroonKey = [\n 124, 222, 231, 146, 81, 28, 91, 198, 245, 40, 72, 88, 5, 223, 233, 178, 78, 120, 94,\n 40, 226, 169, 147, 1, 249, 215, 17, 198, 9, 227, 142, 247,\n ]\n .into();\n let macaroon = super::deserialize(&serialized.as_bytes().to_vec()).unwrap();\n assert!(macaroon.location().is_some());\n assert_eq!(\"http://example.org/\", &macaroon.location().unwrap());\n assert_eq!(ByteString::from(\"keyid\"), macaroon.identifier());\n assert_eq!(signature, macaroon.signature());\n serialized = \"MDAyMWxvY2F0aW9uIGh0dHA6Ly9leGFtcGxlLm9yZy8KMDAxNWlkZW50aWZpZXIga2V5aWQKMDAxZGNpZCBhY2NvdW50ID0gMzczNTkyODU1OQowMDJmc2lnbmF0dXJlIPVIB_bcbt-Ivw9zBrOCJWKjYlM9v3M5umF2XaS9JZ2HCg\";\n signature = [\n 245, 72, 7, 246, 220, 110, 223, 136, 191, 15, 115, 6, 179, 130, 37, 98, 163, 98, 83,\n 61, 191, 115, 57, 186, 97, 118, 93, 164, 189, 37, 157, 135,\n ]\n .into();\n let macaroon = super::deserialize(&serialized.as_bytes().to_vec()).unwrap();\n assert!(macaroon.location().is_some());\n assert_eq!(\"http://example.org/\", &macaroon.location().unwrap());\n assert_eq!(ByteString::from(\"keyid\"), macaroon.identifier());\n assert_eq!(1, macaroon.caveats().len());\n let predicate = match &macaroon.caveats()[0] {\n Caveat::FirstParty(fp) => fp.predicate(),\n _ => ByteString::default(),\n };\n assert_eq!(ByteString::from(\"account = 3735928559\"), predicate);\n assert_eq!(signature, macaroon.signature());\n }\n}", "#[cfg(test)]\nmod tests {\n use super::*;\n #[test]\n fn test_deserialize_two_caveats() {\n let serialized = \"MDAyMWxvY2F0aW9uIGh0dHA6Ly9leGFtcGxlLm9yZy8KMDAxNWlkZW50aWZpZXIga2V5aWQKMDAxZGNpZCBhY2NvdW50ID0gMzczNTkyODU1OQowMDE1Y2lkIHVzZXIgPSBhbGljZQowMDJmc2lnbmF0dXJlIEvpZ80eoMaya69qSpTumwWxWIbaC6hejEKpPI0OEl78Cg\";\n let signature: MacaroonKey = [\n 75, 233, 103, 205, 30, 160, 198, 178, 107, 175, 106, 74, 148, 238, 155, 5, 177, 88,\n 134, 218, 11, 168, 94, 140, 66, 169, 60, 141, 14, 18, 94, 252,\n ]\n .into();\n let macaroon = super::deserialize(&serialized.as_bytes().to_vec()).unwrap();\n assert!(macaroon.location().is_some());\n assert_eq!(\"http://example.org/\", &macaroon.location().unwrap());\n assert_eq!(ByteString::from(\"keyid\"), macaroon.identifier());\n assert_eq!(signature, macaroon.signature());\n assert_eq!(2, macaroon.caveats().len());\n let predicate = match &macaroon.caveats()[0] {\n Caveat::FirstParty(fp) => fp.predicate(),\n _ => ByteString::default(),\n };\n assert_eq!(ByteString::from(\"account = 3735928559\"), predicate);\n let predicate = match &macaroon.caveats()[1] {\n Caveat::FirstParty(fp) => fp.predicate(),\n _ => ByteString::default(),\n };\n assert_eq!(ByteString::from(\"user = alice\"), predicate);\n }\n}", "#[cfg(test)]\nmod tests {\n use super::*;\n #[test]\n fn test_serialize_deserialize() {\n let mut macaroon: Macaroon = Macaroon::create(\n Some(\"http://example.org/\".into()),\n &\"my key\".into(),\n \"keyid\".into(),\n )\n .unwrap();\n macaroon.add_first_party_caveat(\"account = 3735928559\".into());\n macaroon.add_first_party_caveat(\"user = alice\".into());\n macaroon.add_third_party_caveat(\n \"https://auth.mybank.com\",\n &\"caveat key\".into(),\n \"caveat\".into(),\n );\n let serialized = macaroon.serialize(super::super::Format::V1).unwrap();\n let deserialized = Macaroon::deserialize(&serialized).unwrap();\n assert_eq!(macaroon, deserialized);\n }\n}" ]
f70262df02c7d1c2e8c07a1c139c588f5708a655
10,018
rs
Rust
third-party/RustaCUDA/src/module.rs
fossabot/necsim-rust
996b6a6977bc27a997a123e3e4f5a7b11e1a1aef
[ "Apache-2.0", "MIT" ]
null
null
null
third-party/RustaCUDA/src/module.rs
fossabot/necsim-rust
996b6a6977bc27a997a123e3e4f5a7b11e1a1aef
[ "Apache-2.0", "MIT" ]
null
null
null
third-party/RustaCUDA/src/module.rs
fossabot/necsim-rust
996b6a6977bc27a997a123e3e4f5a7b11e1a1aef
[ "Apache-2.0", "MIT" ]
null
null
null
//! Functions and types for working with CUDA modules. use crate::{ error::{CudaResult, DropResult, IntoResult}, function::Function, memory::{CopyDestination, DeviceCopy, DevicePointer}, }; use cuda_driver_sys as cuda; use std::{ ffi::{c_void, CStr}, fmt, marker::PhantomData, mem, ptr, }; /// A compiled CUDA module, loaded into a context. #[derive(Debug)] pub struct Module { inner: cuda::CUmodule, } impl Module { /// Load a module from the given file name into the current context. /// /// The given file should be either a cubin file, a ptx file, or a fatbin /// file such as those produced by `nvcc`. /// /// # Example /// /// ``` /// # use rustacuda::*; /// # use std::error::Error; /// # fn main() -> Result<(), Box<dyn Error>> { /// # let _ctx = quick_init()?; /// use rustacuda::module::Module; /// use std::ffi::CString; /// /// let filename = CString::new("./resources/add.ptx")?; /// let module = Module::load_from_file(&filename)?; /// # Ok(()) /// # } /// ``` pub fn load_from_file(filename: &CStr) -> CudaResult<Module> { unsafe { let mut module = Module { inner: ptr::null_mut(), }; cuda::cuModuleLoad(&mut module.inner as *mut cuda::CUmodule, filename.as_ptr()) .into_result()?; Ok(module) } } /// Load a module from a CStr. /// /// This is useful in combination with `include_str!`, to include the device /// code into the compiled executable. /// /// The given CStr must contain the bytes of a cubin file, a ptx file or a /// fatbin file such as those produced by `nvcc`. /// /// # Example /// /// ``` /// # use rustacuda::*; /// # use std::error::Error; /// # fn main() -> Result<(), Box<dyn Error>> { /// # let _ctx = quick_init()?; /// use rustacuda::module::Module; /// use std::ffi::CString; /// /// let image = CString::new(include_str!("../resources/add.ptx"))?; /// let module = Module::load_from_string(&image)?; /// # Ok(()) /// # } /// ``` pub fn load_from_string(image: &CStr) -> CudaResult<Module> { unsafe { let mut module = Module { inner: ptr::null_mut(), }; cuda::cuModuleLoadData( &mut module.inner as *mut cuda::CUmodule, image.as_ptr() as *const c_void, ) .into_result()?; Ok(module) } } /// Get a reference to a global symbol, which can then be copied to/from. /// /// # Panics: /// /// This function panics if the size of the symbol is not the same as the /// `mem::sizeof<T>()`. /// /// # Examples /// /// ``` /// # use rustacuda::*; /// # use rustacuda::memory::CopyDestination; /// # use std::error::Error; /// # fn main() -> Result<(), Box<dyn Error>> { /// # let _ctx = quick_init()?; /// use rustacuda::module::Module; /// use std::ffi::CString; /// /// let ptx = CString::new(include_str!("../resources/add.ptx"))?; /// let module = Module::load_from_string(&ptx)?; /// let name = CString::new("my_constant")?; /// let symbol = module.get_global::<u32>(&name)?; /// let mut host_const = 0; /// symbol.copy_to(&mut host_const)?; /// assert_eq!(314, host_const); /// # Ok(()) /// # } /// ``` pub fn get_global<'a, T: DeviceCopy>(&'a self, name: &CStr) -> CudaResult<Symbol<'a, T>> { unsafe { let mut ptr: DevicePointer<T> = DevicePointer::null(); let mut size: usize = 0; cuda::cuModuleGetGlobal_v2( &mut ptr as *mut DevicePointer<T> as *mut cuda::CUdeviceptr, &mut size as *mut usize, self.inner, name.as_ptr(), ) .into_result()?; assert_eq!(size, mem::size_of::<T>()); Ok(Symbol { ptr, module: PhantomData, }) } } /// Get a reference to a kernel function which can then be launched. /// /// # Examples /// /// ``` /// # use rustacuda::*; /// # use std::error::Error; /// # fn main() -> Result<(), Box<dyn Error>> { /// # let _ctx = quick_init()?; /// use rustacuda::module::Module; /// use std::ffi::CString; /// /// let ptx = CString::new(include_str!("../resources/add.ptx"))?; /// let module = Module::load_from_string(&ptx)?; /// let name = CString::new("sum")?; /// let function = module.get_function(&name)?; /// # Ok(()) /// # } /// ``` pub fn get_function<'a>(&'a self, name: &CStr) -> CudaResult<Function<'a>> { unsafe { let mut func: cuda::CUfunction = ptr::null_mut(); cuda::cuModuleGetFunction( &mut func as *mut cuda::CUfunction, self.inner, name.as_ptr(), ) .into_result()?; Ok(Function::new(func, self)) } } /// Destroy a `Module`, returning an error. /// /// Destroying a module can return errors from previous asynchronous work. /// This function destroys the given module and returns the error and /// the un-destroyed module on failure. /// /// # Example /// /// ``` /// # use rustacuda::*; /// # use std::error::Error; /// # fn main() -> Result<(), Box<dyn Error>> { /// # let _ctx = quick_init()?; /// use rustacuda::module::Module; /// use std::ffi::CString; /// /// let ptx = CString::new(include_str!("../resources/add.ptx"))?; /// let module = Module::load_from_string(&ptx)?; /// match Module::drop(module) { /// Ok(()) => println!("Successfully destroyed"), /// Err((e, module)) => { /// println!("Failed to destroy module: {:?}", e); /// // Do something with module /// }, /// } /// # Ok(()) /// # } /// ``` pub fn drop(mut module: Module) -> DropResult<Module> { if module.inner.is_null() { return Ok(()); } unsafe { let inner = mem::replace(&mut module.inner, ptr::null_mut()); match cuda::cuModuleUnload(inner).into_result() { Ok(()) => { mem::forget(module); Ok(()) }, Err(e) => Err((e, Module { inner })), } } } } impl Drop for Module { fn drop(&mut self) { if self.inner.is_null() { return; } unsafe { // No choice but to panic if this fails... let module = mem::replace(&mut self.inner, ptr::null_mut()); cuda::cuModuleUnload(module) .into_result() .expect("Failed to unload CUDA module"); } } } /// Handle to a symbol defined within a CUDA module. #[derive(Debug)] pub struct Symbol<'a, T: DeviceCopy> { ptr: DevicePointer<T>, module: PhantomData<&'a Module>, } impl<'a, T: DeviceCopy> crate::private::Sealed for Symbol<'a, T> {} impl<'a, T: DeviceCopy> fmt::Pointer for Symbol<'a, T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Pointer::fmt(&self.ptr, f) } } impl<'a, T: DeviceCopy> CopyDestination<T> for Symbol<'a, T> { fn copy_from(&mut self, val: &T) -> CudaResult<()> { let size = mem::size_of::<T>(); if size != 0 { unsafe { cuda::cuMemcpyHtoD_v2( self.ptr.as_raw_mut() as u64, val as *const T as *const c_void, size, ) .into_result()? } } Ok(()) } fn copy_to(&self, val: &mut T) -> CudaResult<()> { let size = mem::size_of::<T>(); if size != 0 { unsafe { cuda::cuMemcpyDtoH_v2( val as *const T as *mut c_void, self.ptr.as_raw() as u64, size, ) .into_result()? } } Ok(()) } } #[cfg(test)] mod test { use super::*; use crate::quick_init; use std::{error::Error, ffi::CString}; #[test] fn test_load_from_file() -> Result<(), Box<dyn Error>> { let _context = quick_init(); let filename = CString::new("./resources/add.ptx")?; let module = Module::load_from_file(&filename)?; drop(module); Ok(()) } #[test] fn test_load_from_memory() -> Result<(), Box<dyn Error>> { let _context = quick_init(); let ptx_text = CString::new(include_str!("../resources/add.ptx"))?; let module = Module::load_from_string(&ptx_text)?; drop(module); Ok(()) } #[test] fn test_copy_from_module() -> Result<(), Box<dyn Error>> { let _context = quick_init(); let ptx = CString::new(include_str!("../resources/add.ptx"))?; let module = Module::load_from_string(&ptx)?; let constant_name = CString::new("my_constant")?; let symbol = module.get_global::<u32>(&constant_name)?; let mut constant_copy = 0u32; symbol.copy_to(&mut constant_copy)?; assert_eq!(314, constant_copy); Ok(()) } #[test] fn test_copy_to_module() -> Result<(), Box<dyn Error>> { let _context = quick_init(); let ptx = CString::new(include_str!("../resources/add.ptx"))?; let module = Module::load_from_string(&ptx)?; let constant_name = CString::new("my_constant")?; let mut symbol = module.get_global::<u32>(&constant_name)?; symbol.copy_from(&100)?; let mut constant_copy = 0u32; symbol.copy_to(&mut constant_copy)?; assert_eq!(100, constant_copy); Ok(()) } }
29.994012
94
0.50539
[ "#[cfg(test)]\nmod tests {\n use super::*;\n #[test]\n fn test_load_from_file() -> Result<(), Box<dyn Error>> {\n let _context = quick_init();\n\n let filename = CString::new(\"./resources/add.ptx\")?;\n let module = Module::load_from_file(&filename)?;\n drop(module);\n Ok(())\n }\n}", "#[cfg(test)]\nmod tests {\n use super::*;\n #[test]\n fn test_load_from_memory() -> Result<(), Box<dyn Error>> {\n let _context = quick_init();\n let ptx_text = CString::new(include_str!(\"../resources/add.ptx\"))?;\n let module = Module::load_from_string(&ptx_text)?;\n drop(module);\n Ok(())\n }\n}", "#[cfg(test)]\nmod tests {\n use super::*;\n #[test]\n fn test_copy_from_module() -> Result<(), Box<dyn Error>> {\n let _context = quick_init();\n\n let ptx = CString::new(include_str!(\"../resources/add.ptx\"))?;\n let module = Module::load_from_string(&ptx)?;\n\n let constant_name = CString::new(\"my_constant\")?;\n let symbol = module.get_global::<u32>(&constant_name)?;\n\n let mut constant_copy = 0u32;\n symbol.copy_to(&mut constant_copy)?;\n assert_eq!(314, constant_copy);\n Ok(())\n }\n}", "#[cfg(test)]\nmod tests {\n use super::*;\n #[test]\n fn test_copy_to_module() -> Result<(), Box<dyn Error>> {\n let _context = quick_init();\n\n let ptx = CString::new(include_str!(\"../resources/add.ptx\"))?;\n let module = Module::load_from_string(&ptx)?;\n\n let constant_name = CString::new(\"my_constant\")?;\n let mut symbol = module.get_global::<u32>(&constant_name)?;\n\n symbol.copy_from(&100)?;\n\n let mut constant_copy = 0u32;\n symbol.copy_to(&mut constant_copy)?;\n assert_eq!(100, constant_copy);\n Ok(())\n }\n}" ]
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
1