repo
stringlengths
6
65
file_url
stringlengths
81
311
file_path
stringlengths
6
227
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:31:58
2026-01-04 20:25:31
truncated
bool
2 classes
smallnest/rpcx-rs
https://github.com/smallnest/rpcx-rs/blob/09578e704de21af635da8357d36be468f10df27b/rpcx_client/src/lib.rs
rpcx_client/src/lib.rs
pub mod client; pub mod discovery; pub mod selector; pub mod xclient; pub use client::*; pub use discovery::*; pub use selector::*; pub use xclient::*; use async_trait::async_trait; use rpcx_protocol::{CallFuture, Metadata, Result, RpcxParam}; #[async_trait] pub trait RpcxClient { fn call<T>( &mut self, service_method: &str, is_oneway: bool, metadata: &Metadata, args: &dyn RpcxParam, ) -> Option<Result<T>> where T: RpcxParam + Default; fn send<T>( &mut self, service_method: &str, is_oneway: bool, metadata: &Metadata, args: &dyn RpcxParam, ) -> CallFuture where T: RpcxParam + Default + Sync + Send + 'static; }
rust
Apache-2.0
09578e704de21af635da8357d36be468f10df27b
2026-01-04T20:19:51.398380Z
false
smallnest/rpcx-rs
https://github.com/smallnest/rpcx-rs/blob/09578e704de21af635da8357d36be468f10df27b/rpcx_client/src/client.rs
rpcx_client/src/client.rs
use std::{ cell::RefCell, collections::HashMap, error::Error as StdError, io::{BufReader, BufWriter, Write}, net::{Shutdown, SocketAddr, TcpStream}, sync::{ atomic::{AtomicU64, Ordering}, mpsc::{self, Receiver, SendError, Sender}, Arc, Mutex, }, thread, time::Duration, }; use rpcx_protocol::{call::*, *}; use tokio::runtime::Runtime; #[derive(Debug, Copy, Clone)] pub struct Opt { pub retry: u8, pub compress_type: CompressType, pub serialize_type: SerializeType, pub connect_timeout: Duration, pub read_timeout: Duration, pub write_timeout: Duration, pub nodelay: Option<bool>, pub ttl: Option<u32>, } impl Default for Opt { fn default() -> Self { Opt { retry: 3, compress_type: CompressType::CompressNone, serialize_type: SerializeType::JSON, connect_timeout: Default::default(), read_timeout: Default::default(), write_timeout: Default::default(), nodelay: None, ttl: None, } } } #[derive(Debug, Default)] struct RpcData { seq: u64, data: Vec<u8>, } /// a direct client to connect rpcx services. #[derive(Debug)] pub struct Client { pub opt: Opt, addr: String, stream: Option<TcpStream>, seq: Arc<AtomicU64>, chan_sender: Sender<RpcData>, chan_receiver: Arc<Mutex<Receiver<RpcData>>>, calls: Arc<Mutex<HashMap<u64, ArcCall>>>, } impl Client { pub fn new(addr: &str) -> Client { let (sender, receiver) = mpsc::channel(); Client { opt: Default::default(), addr: String::from(addr), stream: None, seq: Arc::new(AtomicU64::new(0)), chan_sender: sender, chan_receiver: Arc::new(Mutex::new(receiver)), calls: Arc::new(Mutex::new(HashMap::new())), } } pub fn start(&mut self) -> Result<()> { let stream = if self.opt.connect_timeout.as_millis() == 0 { TcpStream::connect(self.addr.as_str())? } else { let socket_addr: SocketAddr = self .addr .parse() .map_err(|err| Error::new(ErrorKind::Network, err))?; TcpStream::connect_timeout(&socket_addr, self.opt.connect_timeout)? }; if self.opt.read_timeout.as_millis() > 0 { stream.set_read_timeout(Some(self.opt.read_timeout))?; } if self.opt.write_timeout.as_millis() > 0 { stream.set_write_timeout(Some(self.opt.write_timeout))?; } if self.opt.nodelay.is_some() { stream.set_nodelay(self.opt.nodelay.unwrap())?; } if self.opt.ttl.is_some() { stream.set_ttl(self.opt.ttl.unwrap())?; } let read_stream = stream.try_clone()?; let write_stream = stream.try_clone()?; self.stream = Some(stream); let calls = self.calls.clone(); thread::spawn(move || { let mut reader = BufReader::new(read_stream.try_clone().unwrap()); loop { let mut msg = Message::new(); match msg.decode(&mut reader) { Ok(()) => { if let Some(call) = calls.lock().unwrap().remove(&msg.get_seq()) { let internal_call_cloned = call.clone(); let mut internal_call_mutex = internal_call_cloned.lock().unwrap(); let internal_call = internal_call_mutex.get_mut(); internal_call.is_client_error = false; if let Some(MessageStatusType::Error) = msg.get_message_status_type() { internal_call.error = msg.get_error().unwrap_or_else(|| "".to_owned()); } else { internal_call.reply_data.extend_from_slice(&msg.payload); } let mut status = internal_call.state.lock().unwrap(); status.ready = true; if let Some(ref task) = status.task { task.clone().wake() } } } Err(err) => { println!("failed to read: {}", err.to_string()); Self::drain_calls(calls, err); match read_stream.shutdown(Shutdown::Both) { Ok(_) => {} Err(err) => eprintln!("failed to shutdown stream: {}", err), } return; } } } }); let chan_receiver = self.chan_receiver.clone(); let send_calls = self.calls.clone(); thread::spawn(move || { let mut writer = BufWriter::new(write_stream.try_clone().unwrap()); loop { match chan_receiver.lock().unwrap().recv() { Err(_err) => { //eprintln!("failed to fetch RpcData: {}", err.to_string()); write_stream.shutdown(Shutdown::Both).unwrap(); return; } Ok(rpcdata) => { match writer.write_all(rpcdata.data.as_slice()) { Ok(()) => { //println!("wrote"); } Err(err) => { //println!("failed to write: {}", err.to_string()); Self::drain_calls(send_calls.clone(), err); write_stream.shutdown(Shutdown::Both).unwrap(); return; } } match writer.flush() { Ok(()) => { //println!("flushed"); } Err(err) => { //println!("failed to flush: {}", err.to_string()); Self::drain_calls(send_calls.clone(), err); write_stream.shutdown(Shutdown::Both).unwrap(); return; } } } } } }); Ok(()) } pub fn send( &self, service_path: &str, service_method: &str, is_oneway: bool, is_heartbeat: bool, metadata: &Metadata, args: &dyn RpcxParam, ) -> CallFuture { let seq = self.seq.clone().fetch_add(1, Ordering::SeqCst); let mut req = Message::new(); req.set_version(0); req.set_message_type(MessageType::Request); req.set_serialize_type(self.opt.serialize_type); req.set_compress_type(self.opt.compress_type); req.set_seq(seq); req.service_path = service_path.to_string(); req.service_method = service_method.to_string(); let mut new_metadata = HashMap::with_capacity(metadata.len()); for (k, v) in metadata { new_metadata.insert(k.clone(), v.clone()); } req.metadata.replace(new_metadata); let payload = args.into_bytes(self.opt.serialize_type).unwrap(); req.payload = payload; let data = req.encode(); let call_future = if !is_oneway && !is_heartbeat { let callback = Call::new(seq); let arc_call = Arc::new(Mutex::new(RefCell::from(callback))); self.calls .clone() .lock() .unwrap() .insert(seq, arc_call.clone()); CallFuture::new(Some(arc_call)) } else { CallFuture::new(None) }; let send_data = RpcData { seq, data }; match self.chan_sender.clone().send(send_data) { Ok(_) => {} Err(err) => self.remove_call_with_senderr(err), } call_future } fn remove_call_with_senderr(&self, err: SendError<RpcData>) { let seq = err.0.seq; let calls = self.calls.clone(); let mut m = calls.lock().unwrap(); if let Some(call) = m.remove(&seq) { let internal_call_cloned = call.clone(); let mut internal_call_mutex = internal_call_cloned.lock().unwrap(); let internal_call = internal_call_mutex.get_mut(); internal_call.error = String::from(err.description()); let mut status = internal_call.state.lock().unwrap(); status.ready = true; if let Some(ref task) = status.task { task.clone().wake() } } } fn drain_calls<T: StdError>(calls: Arc<Mutex<HashMap<u64, ArcCall>>>, err: T) { let mut m = calls.lock().unwrap(); for (_, call) in m.drain().take(1) { let internal_call_cloned = call.clone(); let mut internal_call_mutex = internal_call_cloned.lock().unwrap(); let internal_call = internal_call_mutex.get_mut(); internal_call.error = String::from(err.description()); let mut status = internal_call.state.lock().unwrap(); status.ready = true; if let Some(ref task) = status.task { task.clone().wake() } } } #[allow(dead_code)] fn remove_call_with_err<T: StdError>(&mut self, seq: u64, err: T) { let calls = self.calls.clone(); let m = calls.lock().unwrap(); if let Some(call) = m.get(&seq) { let internal_call_cloned = call.clone(); let mut internal_call_mutex = internal_call_cloned.lock().unwrap(); let internal_call = internal_call_mutex.get_mut(); internal_call.error = String::from(err.description()); let mut status = internal_call.state.lock().unwrap(); status.ready = true; if let Some(ref task) = status.task { task.clone().wake() } } } pub fn call<T>( &mut self, service_path: &str, service_method: &str, is_oneway: bool, metadata: &Metadata, args: &dyn RpcxParam, ) -> Option<Result<T>> where T: RpcxParam + Default, { let rt = Runtime::new().unwrap(); let callfuture = rt.block_on(async { let f = self.send( service_path, service_method, is_oneway, false, metadata, args, ); f.await }); if is_oneway { return None; } let arc_call_1 = callfuture.unwrap().clone(); let mut arc_call_2 = arc_call_1.lock().unwrap(); let arc_call_3 = arc_call_2.get_mut(); let reply_data = &arc_call_3.reply_data; if !arc_call_3.error.is_empty() { let err = &arc_call_3.error; if arc_call_3.is_client_error { return Some(Err(Error::new(ErrorKind::Client, String::from(err)))); } else { return Some(Err(Error::from(String::from(err)))); } } let mut reply: T = Default::default(); match reply.from_slice(self.opt.serialize_type, &reply_data) { Ok(()) => Some(Ok(reply)), Err(err) => Some(Err(err)), } } }
rust
Apache-2.0
09578e704de21af635da8357d36be468f10df27b
2026-01-04T20:19:51.398380Z
false
smallnest/rpcx-rs
https://github.com/smallnest/rpcx-rs/blob/09578e704de21af635da8357d36be468f10df27b/rpcx_client/src/xclient.rs
rpcx_client/src/xclient.rs
#![allow(non_snake_case)] use std::collections::HashMap; use super::selector::ClientSelector; use super::{ client::{Client, Opt}, RpcxClient, }; use rpcx_protocol::{call::*, CallFuture, Error, ErrorKind, Metadata, Result, RpcxParam}; use std::{ boxed::Box, cell::RefCell, sync::{Arc, Mutex, RwLock, RwLockWriteGuard}, }; use strum_macros::{Display, EnumIter, EnumString}; #[derive(Debug, Copy, Clone, Display, PartialEq, EnumIter, EnumString)] pub enum FailMode { //Failover selects another server automaticaly Failover = 0, //Failfast returns error immediately Failfast = 1, //Failtry use current client again Failtry = 2, //Failbackup select another server if the first server doesn't respon in specified time and // use the fast response. Failbackup = 3, } #[derive(Debug, Copy, Clone, Display, PartialEq, EnumIter, EnumString)] pub enum SelectMode { //RandomSelect is selecting randomly RandomSelect = 0, //RoundRobin is selecting by round robin RoundRobin = 1, //WeightedRoundRobin is selecting by weighted round robin WeightedRoundRobin = 2, //WeightedICMP is selecting by weighted Ping time WeightedICMP = 3, //ConsistentHash is selecting by hashing ConsistentHash = 4, //Closest is selecting the closest server Closest = 5, // SelectByUser is selecting by implementation of users SelectByUser = 1000, } pub struct XClient<S: ClientSelector> { pub opt: Opt, service_path: String, fail_mode: FailMode, clients: Arc<RwLock<HashMap<String, RefCell<Client>>>>, selector: Box<S>, } unsafe impl<S: ClientSelector> Send for XClient<S> {} unsafe impl<S: ClientSelector> Sync for XClient<S> {} impl<S: ClientSelector> XClient<S> { pub fn new(service_path: String, fm: FailMode, s: Box<S>, opt: Opt) -> Self { XClient { service_path, fail_mode: fm, selector: s, clients: Arc::new(RwLock::new(HashMap::new())), opt, } } fn get_cached_client<'a>( &'a self, clients_guard: &'a mut RwLockWriteGuard<HashMap<String, RefCell<Client>>>, k: String, ) -> Result<&'a mut RefCell<Client>> { let client = clients_guard.get_mut(&k); if client.is_none() { drop(client); match clients_guard.get(&k) { Some(_) => {} None => { let mut items: Vec<&str> = k.split('@').collect(); if items.len() == 1 { items.insert(0, "tcp"); } let mut created_client = Client::new(&items[1]); created_client.opt = self.opt; match created_client.start() { Ok(_) => { clients_guard.insert(k.clone(), RefCell::new(created_client)); } Err(err) => return Err(err), } } } } let client = clients_guard.get_mut(&k); match client { Some(_) => Ok(client.unwrap()), None => Err(Error::from("client still not found".to_owned())), } } } impl<S: ClientSelector> RpcxClient for XClient<S> { fn call<T>( &mut self, service_method: &str, is_oneway: bool, metadata: &Metadata, args: &dyn RpcxParam, ) -> Option<Result<T>> where T: RpcxParam + Default, { let service_path = self.service_path.as_str(); // get a key from selector let selector = &mut (self.selector); let k = selector.select(service_path, service_method, args); if k.is_empty() { return Some(Err(Error::new( ErrorKind::Client, "server not found".to_owned(), ))); } let mut clients_guard = self.clients.write().unwrap(); let client = self.get_cached_client(&mut clients_guard, k.clone()); if let Err(err) = client { return Some(Err(Error::new(ErrorKind::Client, err))); } // invoke this client let mut selected_client = client.unwrap().borrow_mut(); let opt_rt = (*selected_client).call::<T>(service_path, service_method, is_oneway, metadata, args); if is_oneway { return opt_rt; } let rt = opt_rt.unwrap(); match rt { Err(rt_err) => { if rt_err.kind() == ErrorKind::Client { match self.fail_mode { FailMode::Failover => { let mut retry = self.opt.retry; while retry > 0 { retry -= 1; // re-select let mut clients_guard = self.clients.write().unwrap(); let client = self.get_cached_client(&mut clients_guard, k.clone()); if let Err(err) = client { return Some(Err(err)); } let mut selected_client = client.unwrap().borrow_mut(); let opt_rt = (*selected_client).call::<T>( service_path, service_method, is_oneway, metadata, args, ); let rt = opt_rt.unwrap(); if rt.is_ok() { return Some(rt); } if rt.unwrap_err().kind() == ErrorKind::Client { continue; } } } FailMode::Failfast => return Some(Err(rt_err)), FailMode::Failtry => { let mut retry = self.opt.retry; while retry > 0 { retry -= 1; let opt_rt = (*selected_client).call::<T>( service_path, service_method, is_oneway, metadata, args, ); let rt = opt_rt.unwrap(); if rt.is_ok() { return Some(rt); } if rt.unwrap_err().kind() == ErrorKind::Client { continue; } } } FailMode::Failbackup => {} } } Some(Err(rt_err)) } Ok(r) => Some(Ok(r)), } } fn send<T>( &mut self, service_method: &str, is_oneway: bool, metadata: &Metadata, args: &dyn RpcxParam, ) -> CallFuture where T: RpcxParam + Default + Sync + Send + 'static, { let service_path = self.service_path.as_str(); // get a key from selector let k = self.selector.select(service_path, service_method, args); if k.is_empty() { let callback = Call::new(0); let arc_call = Arc::new(Mutex::new(RefCell::from(callback))); let internal_call_cloned = arc_call.clone(); let mut internal_call_mutex = internal_call_cloned.lock().unwrap(); let internal_call = internal_call_mutex.get_mut(); internal_call.error = "server not found".to_owned(); let mut status = internal_call.state.lock().unwrap(); status.ready = true; if let Some(ref task) = status.task { task.clone().wake() } return CallFuture::new(Some(arc_call)); } let mut clients_guard = self.clients.write().unwrap(); let client = self.get_cached_client(&mut clients_guard, k.clone()); if let Err(err) = client { let callback = Call::new(0); let arc_call = Arc::new(Mutex::new(RefCell::from(callback))); let internal_call_cloned = arc_call.clone(); let mut internal_call_mutex = internal_call_cloned.lock().unwrap(); let internal_call = internal_call_mutex.get_mut(); internal_call.error = err.to_string(); let mut status = internal_call.state.lock().unwrap(); status.ready = true; if let Some(ref task) = status.task { task.clone().wake() } return CallFuture::new(Some(arc_call)); } // invoke this client let selected_client = client.unwrap().borrow_mut(); selected_client.send( service_path, service_method, is_oneway, false, metadata, args, ) } }
rust
Apache-2.0
09578e704de21af635da8357d36be468f10df27b
2026-01-04T20:19:51.398380Z
false
smallnest/rpcx-rs
https://github.com/smallnest/rpcx-rs/blob/09578e704de21af635da8357d36be468f10df27b/rpcx_client/src/selector.rs
rpcx_client/src/selector.rs
use qstring::QString; use rand::{prelude::*, Rng}; use rpcx_protocol::{RpcxParam, SerializeType}; use std::{ collections::HashMap, sync::{Arc, RwLock}, }; use weighted_rs::*; pub trait ClientSelector { fn select(&mut self, service_path: &str, service_method: &str, args: &dyn RpcxParam) -> String; fn update_server(&self, servers: &HashMap<String, String>); } #[derive(Default)] pub struct RandomSelector { pub servers: Arc<RwLock<Vec<String>>>, rnd: ThreadRng, } impl RandomSelector { pub fn new() -> Self { RandomSelector { servers: Arc::new(RwLock::new(Vec::new())), rnd: thread_rng(), } } } unsafe impl Sync for RandomSelector {} unsafe impl Send for RandomSelector {} impl ClientSelector for RandomSelector { fn select( &mut self, _service_path: &str, _service_method: &str, _args: &dyn RpcxParam, ) -> String { let servers = (*self).servers.read().unwrap(); let size = servers.len(); if size == 0 { return String::new(); } let idx = (*self).rnd.gen_range(0..size); let s = &servers[idx]; String::from(s) } fn update_server(&self, map: &HashMap<String, String>) { let mut servers = self.servers.write().unwrap(); servers.clear(); for k in map.keys() { servers.push(String::from(k)); } } } #[derive(Default)] pub struct RoundbinSelector { pub servers: Arc<RwLock<Vec<String>>>, index: usize, } impl RoundbinSelector { pub fn new() -> Self { RoundbinSelector { servers: Arc::new(RwLock::new(Vec::new())), index: 0, } } } unsafe impl Sync for RoundbinSelector {} unsafe impl Send for RoundbinSelector {} impl ClientSelector for RoundbinSelector { fn select( &mut self, _service_path: &str, _service_method: &str, _args: &dyn RpcxParam, ) -> String { let servers = (*self).servers.read().unwrap(); let size = servers.len(); if size == 0 { return String::new(); } self.index = (self.index + 1) % size; let s = &servers[self.index]; String::from(s) } fn update_server(&self, map: &HashMap<String, String>) { let mut servers = self.servers.write().unwrap(); servers.clear(); for k in map.keys() { servers.push(String::from(k)); } } } #[derive(Default)] pub struct WeightedSelector { pub servers: Arc<RwLock<SmoothWeight<String>>>, } impl WeightedSelector { pub fn new() -> Self { WeightedSelector { servers: Arc::new(RwLock::new(SmoothWeight::new())), } } } unsafe impl Sync for WeightedSelector {} unsafe impl Send for WeightedSelector {} impl ClientSelector for WeightedSelector { fn select( &mut self, _service_path: &str, _service_method: &str, _args: &dyn RpcxParam, ) -> String { let mut servers = self.servers.write().unwrap(); let mut sw = servers.next(); match &mut sw { Some(s) => s.clone(), None => String::new(), } } fn update_server(&self, map: &HashMap<String, String>) { let mut servers = self.servers.write().unwrap(); servers.reset(); for (k, v) in map.iter() { let qs = QString::from(v.as_str()); if let Some(val) = qs.get("weight") { if let Ok(w) = val.parse::<isize>() { servers.add(k.clone(), w); } else { servers.add(k.clone(), 1); } } else { servers.add(k.clone(), 1); } } } } #[derive(Default)] pub struct ConsistentHashSelector { pub servers: Arc<RwLock<Vec<String>>>, } impl ConsistentHashSelector { pub fn new() -> Self { ConsistentHashSelector { servers: Arc::new(RwLock::new(Vec::new())), } } } fn hash_request( data: &mut Vec<u8>, service_path: &str, service_method: &str, args: &dyn RpcxParam, ) { data.extend(service_path.to_string().into_bytes()); data.extend(service_method.to_string().into_bytes()); data.extend(args.into_bytes(SerializeType::JSON).unwrap()); } impl ClientSelector for ConsistentHashSelector { fn select(&mut self, service_path: &str, service_method: &str, args: &dyn RpcxParam) -> String { let servers = (*self).servers.read().unwrap(); let size = servers.len(); if size == 0 { return String::new(); } // let data = Vec::new(service_path.len() + service_method.len()); let jh = jumphash::JumpHasher::new(); let mut data = Vec::new(); hash_request(&mut data, service_path, service_method, args); let index = jh.slot(&data, size as u32); let s = &servers[index as usize]; String::from(s) } fn update_server(&self, map: &HashMap<String, String>) { let mut servers = (*self).servers.write().unwrap(); for k in map.keys() { servers.push(String::from(k)); } } }
rust
Apache-2.0
09578e704de21af635da8357d36be468f10df27b
2026-01-04T20:19:51.398380Z
false
smallnest/rpcx-rs
https://github.com/smallnest/rpcx-rs/blob/09578e704de21af635da8357d36be468f10df27b/rpcx/src/lib.rs
rpcx/src/lib.rs
pub use rpcx_client::*; pub use rpcx_derive::*; pub use rpcx_protocol::*; pub use rpcx_server::*;
rust
Apache-2.0
09578e704de21af635da8357d36be468f10df27b
2026-01-04T20:19:51.398380Z
false
smallnest/rpcx-rs
https://github.com/smallnest/rpcx-rs/blob/09578e704de21af635da8357d36be468f10df27b/rpcx_derive/src/lib.rs
rpcx_derive/src/lib.rs
#![recursion_limit = "128"] extern crate proc_macro; use proc_macro::TokenStream; use quote::quote; use syn::{parse_macro_input, DeriveInput}; #[proc_macro_derive(RpcxParam)] pub fn rpcx_param(input: TokenStream) -> TokenStream { let input = parse_macro_input!(input as DeriveInput); let name = input.ident; let expanded = quote! { impl RpcxParam for #name { fn into_bytes(&self, st: SerializeType) -> Result<Vec<u8>> { match st { SerializeType::JSON => serde_json::to_vec(self).map_err(|err| Error::from(err)), SerializeType::MsgPack => { rmps::to_vec(self).map_err(|err| Error::new(ErrorKind::Other, err.description())) } _ => Err(Error::new(ErrorKind::Other, "unknown format")), } } fn from_slice(&mut self, st: SerializeType, data: &[u8]) -> Result<()> { match st { SerializeType::JSON => { let param: Self = serde_json::from_slice(data)?; *self = param; Ok(()) } SerializeType::MsgPack => { let param: Self = rmps::from_slice(data) .map_err(|err| Error::new(ErrorKind::Other, err.description()))?; *self = param; Ok(()) } _ => Err(Error::new(ErrorKind::Other, "unknown format")), } } } }; // Hand the output tokens back to the compiler TokenStream::from(expanded) }
rust
Apache-2.0
09578e704de21af635da8357d36be468f10df27b
2026-01-04T20:19:51.398380Z
false
smallnest/rpcx-rs
https://github.com/smallnest/rpcx-rs/blob/09578e704de21af635da8357d36be468f10df27b/rpcx_protocol/src/lib.rs
rpcx_protocol/src/lib.rs
pub mod call; pub mod error; pub mod message; pub use call::*; pub use error::*; pub use message::*;
rust
Apache-2.0
09578e704de21af635da8357d36be468f10df27b
2026-01-04T20:19:51.398380Z
false
smallnest/rpcx-rs
https://github.com/smallnest/rpcx-rs/blob/09578e704de21af635da8357d36be468f10df27b/rpcx_protocol/src/call.rs
rpcx_protocol/src/call.rs
use crate::Result; use std::{ cell::RefCell, fmt::Debug, future::Future, pin::Pin, sync::{Arc, Mutex}, task::{Context, Poll, Waker}, }; use crate::SerializeType; use bytes::BytesMut; use super::Error; pub trait RpcxParam: Debug { fn into_bytes(&self, st: SerializeType) -> Result<Vec<u8>>; fn from_slice(&mut self, st: SerializeType, data: &[u8]) -> Result<()>; } impl RpcxParam for BytesMut { fn into_bytes(&self, _: SerializeType) -> Result<Vec<u8>> { let rt = self.to_vec(); Ok(rt) } fn from_slice(&mut self, _: SerializeType, data: &[u8]) -> Result<()> { (*self).extend_from_slice(data); Ok(()) } } #[derive(Debug)] pub struct Status { pub ready: bool, pub task: Option<Waker>, } #[derive(Debug)] pub struct Call { pub seq: u64, pub is_client_error: bool, pub state: Arc<Mutex<Status>>, pub error: String, pub reply_data: Vec<u8>, } impl Call { pub fn new(seq: u64) -> Self { Call { seq, is_client_error: true, state: Arc::new(Mutex::new(Status { ready: false, task: None, })), error: String::new(), reply_data: Vec::new(), } } } pub type ArcCall = Arc<Mutex<RefCell<Call>>>; pub fn get_result<T>(arc_call: Option<ArcCall>, st: SerializeType) -> Result<T> where T: RpcxParam + Default, { if arc_call.is_none() { return Err(Error::from("reply is empty")); } let arc_call_1 = arc_call.unwrap().clone(); let mut arc_call_2 = arc_call_1.lock().unwrap(); let arc_call_3 = arc_call_2.get_mut(); let reply_data = &arc_call_3.reply_data; if !arc_call_3.error.is_empty() { let err = &arc_call_3.error; return Err(Error::from(String::from(err))); } let mut reply: T = Default::default(); match reply.from_slice(st, &reply_data) { Ok(()) => Ok(reply), Err(err) => Err(err), } } pub struct CallFuture { pub arc_call: Option<ArcCall>, } impl CallFuture { pub fn new(opt: Option<ArcCall>) -> Self { CallFuture { arc_call: opt } } } impl Future for CallFuture { type Output = Option<ArcCall>; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { if self.arc_call.is_none() { return Poll::Ready(None); } let arc_call = self.arc_call.as_ref().unwrap().clone(); let mut arc_call_1 = arc_call.lock().unwrap(); let state = &arc_call_1.get_mut().state; let mut status = state.lock().expect("!lock"); if status.ready { Poll::Ready(Some(arc_call.clone())) } else { status.task = Some(cx.waker().clone()); Poll::Pending } } } unsafe impl Send for Call {} unsafe impl Sync for Call {}
rust
Apache-2.0
09578e704de21af635da8357d36be468f10df27b
2026-01-04T20:19:51.398380Z
false
smallnest/rpcx-rs
https://github.com/smallnest/rpcx-rs/blob/09578e704de21af635da8357d36be468f10df27b/rpcx_protocol/src/error.rs
rpcx_protocol/src/error.rs
use std::{convert::From, error, fmt, result, str}; pub type Result<T> = result::Result<T, Error>; pub struct Error { repr: Repr, } impl fmt::Debug for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Debug::fmt(&self.repr, f) } } enum Repr { Other(String), Simple(ErrorKind), Custom(Box<Custom>), } #[derive(Debug)] struct Custom { kind: ErrorKind, error: Box<dyn error::Error + Send + Sync>, } #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] pub enum ErrorKind { Protocol, IO, Client, Network, Server, Serialization, Other, } impl ErrorKind { pub(crate) fn as_str(self) -> &'static str { match self { ErrorKind::Protocol => "invalid protocol", ErrorKind::IO => "io issue", ErrorKind::Client => "client error", ErrorKind::Network => "network issue", ErrorKind::Server => "server error", ErrorKind::Serialization => "serialization failure", ErrorKind::Other => "other", } } } impl From<&'static str> for Error { #[inline] fn from(s: &'static str) -> Error { Error { repr: Repr::Other(s.to_owned()), } } } impl From<String> for Error { #[inline] fn from(s: String) -> Error { Error { repr: Repr::Other(s), } } } impl From<serde_json::error::Error> for Error { #[inline] fn from(err: serde_json::error::Error) -> Error { Error::new(ErrorKind::IO, err) } } impl From<std::io::Error> for Error { #[inline] fn from(err: std::io::Error) -> Error { Error::new(ErrorKind::IO, err) } } impl From<Box<dyn std::error::Error + Send + Sync>> for Error { #[inline] fn from(err: Box<dyn std::error::Error + Send + Sync>) -> Error { Error::_new(ErrorKind::Other, err) } } impl From<ErrorKind> for Error { #[inline] fn from(kind: ErrorKind) -> Error { Error { repr: Repr::Simple(kind), } } } impl Error { pub fn new<E>(kind: ErrorKind, error: E) -> Error where E: Into<Box<dyn error::Error + Send + Sync>>, { Self::_new(kind, error.into()) } fn _new(kind: ErrorKind, error: Box<dyn error::Error + Send + Sync>) -> Error { Error { repr: Repr::Custom(Box::new(Custom { kind, error })), } } pub fn get_ref(&self) -> Option<&(dyn error::Error + Send + Sync + 'static)> { match self.repr { Repr::Other(..) => None, Repr::Simple(..) => None, Repr::Custom(ref c) => Some(&*c.error), } } pub fn get_mut(&mut self) -> Option<&mut (dyn error::Error + Send + Sync + 'static)> { match self.repr { Repr::Other(..) => None, Repr::Simple(..) => None, Repr::Custom(ref mut c) => Some(&mut *c.error), } } pub fn into_inner(self) -> Option<Box<dyn error::Error + Send + Sync>> { match self.repr { Repr::Other(..) => None, Repr::Simple(..) => None, Repr::Custom(c) => Some(c.error), } } pub fn kind(&self) -> ErrorKind { match self.repr { Repr::Other(_) => ErrorKind::Other, Repr::Custom(ref c) => c.kind, Repr::Simple(kind) => kind, } } } impl fmt::Debug for Repr { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { match &*self { Repr::Other(s) => write!(fmt, "{}", s), Repr::Custom(ref c) => fmt::Debug::fmt(&c, fmt), Repr::Simple(kind) => fmt.debug_tuple("Kind").field(&kind).finish(), } } } impl fmt::Display for Error { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { match &self.repr { Repr::Other(s) => write!(fmt, "{}", s), Repr::Custom(ref c) => c.error.fmt(fmt), Repr::Simple(kind) => write!(fmt, "{}", kind.as_str()), } } } impl error::Error for Error { fn description(&self) -> &str { match &self.repr { Repr::Other(s) => &s[..], Repr::Simple(..) => self.kind().as_str(), Repr::Custom(ref c) => c.error.description(), } } fn cause(&self) -> Option<&dyn error::Error> { match self.repr { Repr::Other(..) => None, Repr::Simple(..) => None, Repr::Custom(ref c) => c.error.source(), } } fn source(&self) -> Option<&(dyn error::Error + 'static)> { match self.repr { Repr::Other(..) => None, Repr::Simple(..) => None, Repr::Custom(ref c) => c.error.source(), } } }
rust
Apache-2.0
09578e704de21af635da8357d36be468f10df27b
2026-01-04T20:19:51.398380Z
false
smallnest/rpcx-rs
https://github.com/smallnest/rpcx-rs/blob/09578e704de21af635da8357d36be468f10df27b/rpcx_protocol/src/message.rs
rpcx_protocol/src/message.rs
use byteorder::{BigEndian, ByteOrder}; use enum_primitive_derive::Primitive; use flate2::{read::GzDecoder, write::GzEncoder, Compression}; use num_traits::{FromPrimitive, ToPrimitive}; use strum_macros::{Display, EnumIter, EnumString}; use std::{ cell::RefCell, collections::hash_map::HashMap, io::{Read, Write}, }; use crate::{Error, Result}; const MAGIC_NUMBER: u8 = 0x08; pub const SERVICE_ERROR: &str = "__rpcx_error__"; #[derive(Debug, Copy, Clone, Display, PartialEq, EnumIter, EnumString, Primitive)] pub enum MessageType { Request = 0, Response = 1, } #[derive(Debug, Copy, Clone, Display, PartialEq, EnumIter, EnumString, Primitive)] pub enum MessageStatusType { Normal = 0, Error = 1, } #[derive(Debug, Copy, Clone, Display, PartialEq, EnumIter, EnumString, Primitive)] pub enum CompressType { CompressNone = 0, Gzip = 1, } #[derive(Debug, Copy, Clone, Display, PartialEq, EnumIter, EnumString, Primitive)] pub enum SerializeType { SerializeNone = 0, JSON = 1, Protobuf = 2, MsgPack = 3, Thrift = 4, } /// define the rpcx message interface. pub trait RpcxMessage { fn check_magic_number(&self) -> bool; fn get_version(&self) -> u8; fn set_version(&mut self, v: u8); fn get_message_type(&self) -> Option<MessageType>; fn set_message_type(&mut self, mt: MessageType); fn is_heartbeat(&self) -> bool; fn set_heartbeat(&mut self, b: bool); fn is_oneway(&self) -> bool; fn set_oneway(&mut self, b: bool); fn get_compress_type(&self) -> Option<CompressType>; fn set_compress_type(&mut self, ct: CompressType); fn get_message_status_type(&self) -> Option<MessageStatusType>; fn set_message_status_type(&mut self, mst: MessageStatusType); fn get_serialize_type(&self) -> Option<SerializeType>; fn set_serialize_type(&mut self, st: SerializeType); fn get_seq(&self) -> u64; fn set_seq(&mut self, seq: u64); fn decode<R: ?Sized>(&mut self, r: &mut R) -> Result<()> where R: Read; fn encode(&self) -> Vec<u8>; fn get_error(&self) -> Option<String>; } pub type Metadata = HashMap<String, String>; /// a commmon struct for request and response. #[derive(Debug, Default)] pub struct Message { pub header: [u8; 12], pub service_path: String, pub service_method: String, pub metadata: RefCell<Metadata>, pub payload: Vec<u8>, } impl Message { /// Creates a new `Message` pub fn new() -> Self { let mut msg: Message = Default::default(); msg.header = [0u8; 12]; msg.header[0] = MAGIC_NUMBER; msg.metadata = RefCell::new(HashMap::new()); msg } pub fn get_reply(&self) -> Result<Self> { let mut reply = Message::new(); reply.set_version(self.get_version()); reply.set_compress_type(self.get_compress_type().unwrap()); reply.set_message_status_type(MessageStatusType::Normal); reply.set_message_type(MessageType::Response); reply.set_serialize_type(self.get_serialize_type().unwrap()); reply.set_seq(self.get_seq()); reply.service_path = self.service_path.clone(); reply.service_method = self.service_method.clone(); Ok(reply) } } impl RpcxMessage for Message { fn check_magic_number(&self) -> bool { self.header[0] == MAGIC_NUMBER } fn get_version(&self) -> u8 { self.header[1] } fn set_version(&mut self, v: u8) { self.header[1] = v; } fn get_message_type(&self) -> Option<MessageType> { MessageType::from_u8((self.header[2] & 0x80) >> 7 as u8) } fn set_message_type(&mut self, mt: MessageType) { self.header[2] |= mt.to_u8().unwrap() << 7; } fn is_heartbeat(&self) -> bool { self.header[2] & 0x40 == 0x40 } fn set_heartbeat(&mut self, b: bool) { if b { self.header[2] |= 0x40; } else { self.header[2] &= !0x40; } } fn is_oneway(&self) -> bool { self.header[2] & 0x20 == 0x20 } fn set_oneway(&mut self, b: bool) { if b { self.header[2] |= 0x20; } else { self.header[2] &= !0x20; } } fn get_compress_type(&self) -> Option<CompressType> { CompressType::from_u8((self.header[2] & 0x1C) >> 2) } fn set_compress_type(&mut self, ct: CompressType) { self.header[2] = (self.header[2] & !0x1C) | (ct.to_u8().unwrap() << 2 & 0x1C); } fn get_message_status_type(&self) -> Option<MessageStatusType> { MessageStatusType::from_u8(self.header[2] & 0x03) } fn set_message_status_type(&mut self, mst: MessageStatusType) { self.header[2] = (self.header[2] & !0x03) | (mst.to_u8().unwrap() & 0x03); } fn get_serialize_type(&self) -> Option<SerializeType> { SerializeType::from_u8((self.header[3] & 0xF0) >> 4) } fn set_serialize_type(&mut self, st: SerializeType) { self.header[3] = (self.header[3] & !0xF0) | (st.to_u8().unwrap() << 4) } fn get_seq(&self) -> u64 { u64_from_slice(&(self.header[4..])) } fn set_seq(&mut self, seq: u64) { u64_to_slice(seq, &mut self.header[4..]); } fn decode<R: ?Sized>(&mut self, r: &mut R) -> Result<()> where R: Read, { r.read_exact(&mut self.header)?; let mut buf = [0u8; 4]; r.read(&mut buf[..]).map(|_| {})?; let len = BigEndian::read_u32(&buf); //length of all expect header let mut buf = vec![0u8; len as usize]; r.read(&mut buf[..]).map(|_| ())?; let mut start = 0; // read service_path let len = read_len(&buf[start..(start + 4)]) as usize; let service_path = read_str(&buf[(start + 4)..(start + 4 + len)])?; self.service_path = service_path; start = start + 4 + len; // read service_method let len = read_len(&buf[start..(start + 4)]) as usize; let service_method = read_str(&buf[(start + 4)..(start + 4 + len)])?; self.service_method = service_method; start = start + 4 + len; //metadata let len = read_len(&buf[start..(start + 4)]) as usize; let metadata_bytes = &buf[(start + 4)..(start + 4 + len)]; let mut meta_start = 0; while meta_start < len { let sl = read_len(&metadata_bytes[meta_start..(meta_start + 4)]) as usize; let key = read_str(&metadata_bytes[(meta_start + 4)..(meta_start + 4 + sl)])?; meta_start = meta_start + 4 + sl; if meta_start < len { let value_len = read_len(&metadata_bytes[meta_start..(meta_start + 4)]) as usize; let value = read_str(&metadata_bytes[(meta_start + 4)..(meta_start + 4 + value_len)])?; self.metadata.borrow_mut().insert(key, value); meta_start = meta_start + 4 + value_len; } else { self.metadata.borrow_mut().insert(key, String::new()); break; } } start = start + 4 + len; // payload let len = read_len(&buf[start..start + 4]) as usize; let payload = &buf[start + 4..]; if len != payload.len() { return Err(Error::from("invalid payload length")); } let mut vp = Vec::with_capacity(payload.len()); match self.get_compress_type().unwrap() { CompressType::Gzip => { let mut deflater = GzDecoder::new(payload); deflater.read_to_end(&mut vp)?; } CompressType::CompressNone => { vp.extend_from_slice(&payload); } } self.payload = vp; Ok(()) } fn encode(&self) -> Vec<u8> { // encode all except header let mut buf = Vec::<u8>::with_capacity(20); buf.extend_from_slice(&self.header); // push fake length let len_bytes = write_len(0); buf.extend_from_slice(&len_bytes); // service_path let len = self.service_path.len(); let len_bytes = write_len(len as u32); buf.extend_from_slice(&len_bytes); buf.extend_from_slice(self.service_path.as_bytes()); // service_method let len = self.service_method.len(); let len_bytes = write_len(len as u32); buf.extend_from_slice(&len_bytes); buf.extend_from_slice(self.service_method.as_bytes()); // metadata let mut metadata_bytes = Vec::<u8>::new(); let metadata = self.metadata.borrow_mut(); for meta in metadata.iter() { let key = meta.0; let len_bytes = write_len(key.len() as u32); metadata_bytes.extend_from_slice(&len_bytes); metadata_bytes.extend_from_slice(key.as_bytes()); let value = meta.1; let len_bytes = write_len(value.len() as u32); metadata_bytes.extend_from_slice(&len_bytes); metadata_bytes.extend_from_slice(value.as_bytes()); } let len = metadata_bytes.len(); let len_bytes = write_len(len as u32); buf.extend_from_slice(&len_bytes); buf.append(&mut metadata_bytes); // data // check compress match self.get_compress_type().unwrap() { CompressType::Gzip => { let mut e = GzEncoder::new(Vec::new(), Compression::fast()); let _ = e.write_all(&self.payload[..]); let compressed_payload = e.finish().unwrap(); let len = compressed_payload.len(); let len_bytes = write_len(len as u32); buf.extend_from_slice(&len_bytes); buf.extend_from_slice(&compressed_payload); } _ => { let len = self.payload.len(); let len_bytes = write_len(len as u32); buf.extend_from_slice(&len_bytes); buf.extend_from_slice(&self.payload); } } // set the real length let len = buf.len() - 12 - 4; let len_bytes = write_len(len as u32); buf[12] = len_bytes[0]; buf[13] = len_bytes[1]; buf[14] = len_bytes[2]; buf[15] = len_bytes[3]; buf } fn get_error(&self) -> Option<String> { match self.get_message_status_type() { Some(MessageStatusType::Error) => { let metadata = &self.metadata; let metadata2 = metadata.borrow(); let err_msg = metadata2.get(&SERVICE_ERROR.to_owned())?; Some(String::from(err_msg)) } _ => None, } } } fn read_len(buf: &[u8]) -> u32 { BigEndian::read_u32(&buf[..4]) } fn write_len(len: u32) -> [u8; 4] { let mut buf = [0u8; 4]; BigEndian::write_u32(&mut buf, len); buf } fn read_str(buf: &[u8]) -> Result<String> { let s = std::str::from_utf8(&buf).unwrap(); let str: String = std::string::String::from(s); Ok(str) } fn u64_from_slice(b: &[u8]) -> u64 { BigEndian::read_u64(b) } fn u64_to_slice(v: u64, b: &mut [u8]) { BigEndian::write_u64(b, v); } #[cfg(test)] mod tests { use super::*; #[test] fn parse_header() { let msg_data: Vec<u8> = vec![ 8, 0, 0, 16, 0, 0, 0, 0, 73, 150, 2, 210, 0, 0, 0, 98, 0, 0, 0, 5, 65, 114, 105, 116, 104, 0, 0, 0, 3, 65, 100, 100, 0, 0, 0, 48, 0, 0, 0, 4, 95, 95, 73, 68, 0, 0, 0, 36, 54, 98, 97, 55, 98, 56, 49, 48, 45, 57, 100, 97, 100, 45, 49, 49, 100, 49, 45, 56, 48, 98, 52, 45, 48, 48, 99, 48, 52, 102, 100, 52, 51, 48, 99, 57, 0, 0, 0, 26, 123, 10, 9, 9, 34, 65, 34, 58, 32, 49, 44, 10, 9, 9, 34, 66, 34, 58, 32, 50, 44, 10, 9, 125, 10, 9, ]; let mut msg = Message::new(); (&mut msg.header).copy_from_slice(&msg_data[..12]); assert_eq!(true, msg.check_magic_number()); assert_eq!(0, msg.get_version()); assert_eq!(MessageType::Request, msg.get_message_type().unwrap()); assert_eq!(false, msg.is_heartbeat()); assert_eq!(false, msg.is_oneway()); assert_eq!(CompressType::CompressNone, msg.get_compress_type().unwrap()); assert_eq!( MessageStatusType::Normal, msg.get_message_status_type().unwrap() ); assert_eq!(SerializeType::JSON, msg.get_serialize_type().unwrap()); assert_eq!(1234567890, msg.get_seq()); } #[test] fn set_header() { let msg_data: Vec<u8> = vec![ 8, 0, 0, 16, 0, 0, 0, 0, 73, 150, 2, 210, 0, 0, 0, 98, 0, 0, 0, 5, 65, 114, 105, 116, 104, 0, 0, 0, 3, 65, 100, 100, 0, 0, 0, 48, 0, 0, 0, 4, 95, 95, 73, 68, 0, 0, 0, 36, 54, 98, 97, 55, 98, 56, 49, 48, 45, 57, 100, 97, 100, 45, 49, 49, 100, 49, 45, 56, 48, 98, 52, 45, 48, 48, 99, 48, 52, 102, 100, 52, 51, 48, 99, 57, 0, 0, 0, 26, 123, 10, 9, 9, 34, 65, 34, 58, 32, 49, 44, 10, 9, 9, 34, 66, 34, 58, 32, 50, 44, 10, 9, 125, 10, 9, ]; let mut msg = Message::new(); msg.header.copy_from_slice(&msg_data[..12]); msg.set_version(0); msg.set_message_type(MessageType::Response); msg.set_heartbeat(true); msg.set_oneway(true); msg.set_compress_type(CompressType::Gzip); msg.set_serialize_type(SerializeType::MsgPack); msg.set_message_status_type(MessageStatusType::Normal); msg.set_seq(1000000); assert_eq!(true, msg.check_magic_number()); assert_eq!(0, msg.get_version()); assert_eq!(MessageType::Response, msg.get_message_type().unwrap()); assert_eq!(true, msg.is_heartbeat()); assert_eq!(true, msg.is_oneway()); assert_eq!(CompressType::Gzip, msg.get_compress_type().unwrap()); assert_eq!( MessageStatusType::Normal, msg.get_message_status_type().unwrap() ); assert_eq!(SerializeType::MsgPack, msg.get_serialize_type().unwrap()); assert_eq!(1000000, msg.get_seq()); } #[test] fn decode() { let msg_data: [u8; 114] = [ 8, 0, 0, 16, 0, 0, 0, 0, 73, 150, 2, 210, 0, 0, 0, 98, 0, 0, 0, 5, 65, 114, 105, 116, 104, 0, 0, 0, 3, 65, 100, 100, 0, 0, 0, 48, 0, 0, 0, 4, 95, 95, 73, 68, 0, 0, 0, 36, 54, 98, 97, 55, 98, 56, 49, 48, 45, 57, 100, 97, 100, 45, 49, 49, 100, 49, 45, 56, 48, 98, 52, 45, 48, 48, 99, 48, 52, 102, 100, 52, 51, 48, 99, 57, 0, 0, 0, 26, 123, 10, 9, 9, 34, 65, 34, 58, 32, 49, 44, 10, 9, 9, 34, 66, 34, 58, 32, 50, 44, 10, 9, 125, 10, 9, ]; let mut msg = Message::new(); let mut data = &msg_data[..] as &[u8]; match msg.decode(&mut data) { Err(err) => println!("failed to parse: {}", err), Ok(()) => {} } assert_eq!("Arith", msg.service_path); assert_eq!("Add", msg.service_method); assert_eq!( "6ba7b810-9dad-11d1-80b4-00c04fd430c9", msg.metadata.borrow().get("__ID").unwrap() ); assert_eq!( "{\n\t\t\"A\": 1,\n\t\t\"B\": 2,\n\t}\n\t", std::str::from_utf8(&msg.payload).unwrap() ); } #[test] fn encode() { let msg_data: [u8; 114] = [ 8, 0, 0, 16, 0, 0, 0, 0, 73, 150, 2, 210, 0, 0, 0, 98, 0, 0, 0, 5, 65, 114, 105, 116, 104, 0, 0, 0, 3, 65, 100, 100, 0, 0, 0, 48, 0, 0, 0, 4, 95, 95, 73, 68, 0, 0, 0, 36, 54, 98, 97, 55, 98, 56, 49, 48, 45, 57, 100, 97, 100, 45, 49, 49, 100, 49, 45, 56, 48, 98, 52, 45, 48, 48, 99, 48, 52, 102, 100, 52, 51, 48, 99, 57, 0, 0, 0, 26, 123, 10, 9, 9, 34, 65, 34, 58, 32, 49, 44, 10, 9, 9, 34, 66, 34, 58, 32, 50, 44, 10, 9, 125, 10, 9, ]; let mut msg = Message::new(); let mut data = &msg_data[..] as &[u8]; match msg.decode(&mut data) { Err(err) => println!("failed to parse: {}", err), Ok(()) => {} } let encoded_bytes = msg.encode(); assert_eq!(&msg_data[..], &encoded_bytes[..]); } }
rust
Apache-2.0
09578e704de21af635da8357d36be468f10df27b
2026-01-04T20:19:51.398380Z
false
smallnest/rpcx-rs
https://github.com/smallnest/rpcx-rs/blob/09578e704de21af635da8357d36be468f10df27b/test_suite/tests/test_xclient.rs
test_suite/tests/test_xclient.rs
#[cfg(test)] mod tests { use mul_model::{ArithAddArgs, ArithAddReply}; use rpcx::*; use std::{ collections::HashMap, net::{SocketAddr, TcpListener}, os::unix::io::AsRawFd, thread, }; fn add(args: ArithAddArgs) -> ArithAddReply { ArithAddReply { c: args.a + args.b } } fn mul(args: ArithAddArgs) -> ArithAddReply { ArithAddReply { c: args.a * args.b } } #[test] fn test_xclient_and_server() { // setup server let mut rpc_server = Server::new("0.0.0.0:8972".to_owned(), 0); register_func!( rpc_server, "Arith", "Add", add, "weight=10".to_owned(), ArithAddArgs, ArithAddReply ); register_func!( rpc_server, "Arith", "Mul", mul, "weight=10".to_owned(), ArithAddArgs, ArithAddReply ); let addr = rpc_server .addr .parse::<SocketAddr>() .map_err(|err| Error::new(ErrorKind::Other, err)) .unwrap(); let listener = TcpListener::bind(&addr).unwrap(); let raw_fd = listener.as_raw_fd(); let handler = thread::spawn(move || match rpc_server.start_with_listener(listener) { Ok(()) => {} Err(err) => println!("{}", err), }); // setup client // use static server let mut servers = HashMap::new(); servers.insert("tcp@127.0.0.1:8972".to_owned(), "weight=10".to_owned()); let selector = WeightedSelector::new(); // set discovery with static peers let disc = StaticDiscovery::new(); disc.add_selector(&selector); disc.update_servers(&servers); // init xclient let mut opt: Opt = Default::default(); opt.serialize_type = SerializeType::JSON; opt.compress_type = CompressType::Gzip; let mut xc = XClient::new( String::from("Arith"), FailMode::Failfast, Box::new(selector), opt, ); let mut a = 1; for _ in 0..10 { let service_method = String::from("Mul"); let metadata = HashMap::new(); let args = ArithAddArgs { a, b: 10 }; a += 1; let reply: Option<Result<ArithAddReply>> = xc.call(&service_method, false, &metadata, &args); if reply.is_none() { continue; } let result_reply = reply.unwrap(); match result_reply { Ok(r) => assert!(r.c == (a - 1) * 10), Err(err) => assert!(false, err), } } // clean drop(xc); unsafe { libc::close(raw_fd); } let _ = handler.join(); } }
rust
Apache-2.0
09578e704de21af635da8357d36be468f10df27b
2026-01-04T20:19:51.398380Z
false
smallnest/rpcx-rs
https://github.com/smallnest/rpcx-rs/blob/09578e704de21af635da8357d36be468f10df27b/examples/server_register/src/main.rs
examples/server_register/src/main.rs
use mul_model::{ArithAddArgs, ArithAddReply}; use rpcx::*; fn test(args: ArithAddArgs) -> ArithAddReply { ArithAddReply { c: args.a + args.b } } fn main() { let mut rpc_server = Server::new("0.0.0.0:8972".to_owned(), 0); register_func!( rpc_server, "Arith", "Add", test, "".to_owned(), ArithAddArgs, ArithAddReply ); let f = rpc_server .get_fn(String::from("Arith"), String::from("Add")) .unwrap(); let s = String::from(r#"{"A":1,"B":2}"#); let reply = f(s.as_ref(), SerializeType::JSON).unwrap(); println!("reply:{}", String::from_utf8(reply).unwrap()); }
rust
Apache-2.0
09578e704de21af635da8357d36be468f10df27b
2026-01-04T20:19:51.398380Z
false
smallnest/rpcx-rs
https://github.com/smallnest/rpcx-rs/blob/09578e704de21af635da8357d36be468f10df27b/examples/server_mul/src/main.rs
examples/server_mul/src/main.rs
use mul_model::{ArithAddArgs, ArithAddReply}; use rpcx::*; fn add(args: ArithAddArgs) -> ArithAddReply { ArithAddReply { c: args.a + args.b } } fn mul(args: ArithAddArgs) -> ArithAddReply { ArithAddReply { c: args.a * args.b } } fn main() { let mut rpc_server = Server::new("0.0.0.0:8972".to_owned(), 0); register_func!( rpc_server, "Arith", "Add", add, "".to_owned(), ArithAddArgs, ArithAddReply ); register_func!( rpc_server, "Arith", "Mul", mul, "".to_owned(), ArithAddArgs, ArithAddReply ); rpc_server.start().unwrap(); }
rust
Apache-2.0
09578e704de21af635da8357d36be468f10df27b
2026-01-04T20:19:51.398380Z
false
smallnest/rpcx-rs
https://github.com/smallnest/rpcx-rs/blob/09578e704de21af635da8357d36be468f10df27b/examples/mul_model/src/lib.rs
examples/mul_model/src/lib.rs
use std::error::Error as StdError; use rmp_serde as rmps; use serde::{Deserialize, Serialize}; use rpcx::*; #[derive(RpcxParam, Default, Debug, Copy, Clone, Serialize, Deserialize)] pub struct ArithAddArgs { #[serde(rename = "A")] pub a: u64, #[serde(rename = "B")] pub b: u64, } #[derive(RpcxParam, Default, Debug, Copy, Clone, Serialize, Deserialize)] pub struct ArithAddReply { #[serde(rename = "C")] pub c: u64, }
rust
Apache-2.0
09578e704de21af635da8357d36be468f10df27b
2026-01-04T20:19:51.398380Z
false
smallnest/rpcx-rs
https://github.com/smallnest/rpcx-rs/blob/09578e704de21af635da8357d36be468f10df27b/examples/client_call_mul/src/main.rs
examples/client_call_mul/src/main.rs
use std::collections::hash_map::HashMap; use mul_model::*; use rpcx::{Client, CompressType, Result, SerializeType}; pub fn main() { let mut c: Client = Client::new("127.0.0.1:8972"); c.start().map_err(|err| println!("{}", err)).unwrap(); c.opt.serialize_type = SerializeType::JSON; c.opt.compress_type = CompressType::Gzip; let mut a = 1; loop { let service_path = String::from("Arith"); let service_method = String::from("Mul"); let metadata = HashMap::new(); let args = ArithAddArgs { a, b: 10 }; a += 1; let reply: Option<Result<ArithAddReply>> = c.call(&service_path, &service_method, false, &metadata, &args); if reply.is_none() { continue; } let result_reply = reply.unwrap(); match result_reply { Ok(r) => println!("received: {:?}", r), Err(err) => println!("received err:{}", err), } } }
rust
Apache-2.0
09578e704de21af635da8357d36be468f10df27b
2026-01-04T20:19:51.398380Z
false
smallnest/rpcx-rs
https://github.com/smallnest/rpcx-rs/blob/09578e704de21af635da8357d36be468f10df27b/examples/xclient_call_mul/src/main.rs
examples/xclient_call_mul/src/main.rs
use std::collections::hash_map::HashMap; use mul_model::*; use rpcx::*; pub fn main() { let mut servers = HashMap::new(); servers.insert("tcp@127.0.0.1:8972".to_owned(), "".to_owned()); let selector = RandomSelector::new(); let disc = StaticDiscovery::new(); disc.add_selector(&selector); disc.update_servers(&servers); let mut opt: Opt = Default::default(); opt.serialize_type = SerializeType::JSON; opt.compress_type = CompressType::Gzip; let mut xc = XClient::new( String::from("Arith"), FailMode::Failfast, Box::new(selector), opt, ); let mut a = 1; loop { let service_method = String::from("Mul"); let metadata = HashMap::new(); let args = ArithAddArgs { a, b: 10 }; a += 1; let reply: Option<Result<ArithAddReply>> = xc.call(&service_method, false, &metadata, &args); if reply.is_none() { continue; } let result_reply = reply.unwrap(); match result_reply { Ok(r) => println!("received: {:?}", r), Err(err) => println!("received err:{}", err), } } }
rust
Apache-2.0
09578e704de21af635da8357d36be468f10df27b
2026-01-04T20:19:51.398380Z
false
smallnest/rpcx-rs
https://github.com/smallnest/rpcx-rs/blob/09578e704de21af635da8357d36be468f10df27b/examples/protobuf/server_mul/src/main.rs
examples/protobuf/server_mul/src/main.rs
use mul_model_proto::{ProtoArgs, ProtoReply}; use rpcx::*; fn add(args: ProtoArgs) -> ProtoReply { let mut rt: ProtoReply = Default::default(); rt.set_C(args.A + args.B); rt } fn mul(args: ProtoArgs) -> ProtoReply { let mut rt: ProtoReply = Default::default(); rt.set_C(args.A * args.B); rt } fn main() { let mut rpc_server = Server::new("0.0.0.0:8972".to_owned(), 0); register_func!( rpc_server, "Arith", "Add", add, "".to_owned(), ProtoArgs, ProtoReply ); register_func!( rpc_server, "Arith", "Mul", mul, "".to_owned(), ProtoArgs, ProtoReply ); rpc_server.start().unwrap(); }
rust
Apache-2.0
09578e704de21af635da8357d36be468f10df27b
2026-01-04T20:19:51.398380Z
false
smallnest/rpcx-rs
https://github.com/smallnest/rpcx-rs/blob/09578e704de21af635da8357d36be468f10df27b/examples/protobuf/client_call_mul/src/main.rs
examples/protobuf/client_call_mul/src/main.rs
use std::collections::hash_map::HashMap; use mul_model_proto::*; use rpcx::{Client, CompressType, Result, SerializeType}; pub fn main() { let mut c: Client = Client::new("127.0.0.1:8972"); c.start().map_err(|err| println!("{}", err)).unwrap(); c.opt.serialize_type = SerializeType::Protobuf; c.opt.compress_type = CompressType::Gzip; let mut a = 1; loop { let service_path = String::from("Arith"); let service_method = String::from("Mul"); let metadata = HashMap::new(); let mut args = ProtoArgs::new(); args.set_A(a); args.set_B(20); a += 1; let reply: Option<Result<ProtoReply>> = c.call(&service_path, &service_method, false, &metadata, &args); if reply.is_none() { continue; } let result_reply = reply.unwrap(); match result_reply { Ok(r) => println!("received: {:?}", r), Err(err) => println!("received err:{}", err), } } }
rust
Apache-2.0
09578e704de21af635da8357d36be468f10df27b
2026-01-04T20:19:51.398380Z
false
smallnest/rpcx-rs
https://github.com/smallnest/rpcx-rs/blob/09578e704de21af635da8357d36be468f10df27b/examples/protobuf/mul_model_proto/build.rs
examples/protobuf/mul_model_proto/build.rs
use protoc_rust::Customize; fn main() { // protoc_rust::run(protoc_rust::Args { // out_dir: "src/", // input: &["protos/arith.proto"], // includes: &["protos"], // customize: Customize { // // serde_derive_cfg: None, // // serde_derive: Some(true), // ..Default::default() // }, // }).expect("protoc"); protobuf_codegen_pure::run(protobuf_codegen_pure::Args { out_dir: "src/", input: &["protos/arith.proto"], includes: &["protos"], customize: Customize { // serde_derive_cfg: None, // serde_derive: Some(true), ..Default::default() }, }) .expect("protoc"); }
rust
Apache-2.0
09578e704de21af635da8357d36be468f10df27b
2026-01-04T20:19:51.398380Z
false
smallnest/rpcx-rs
https://github.com/smallnest/rpcx-rs/blob/09578e704de21af635da8357d36be468f10df27b/examples/protobuf/mul_model_proto/src/arith.rs
examples/protobuf/mul_model_proto/src/arith.rs
// This file is generated by rust-protobuf 2.28.0. Do not edit // @generated // https://github.com/rust-lang/rust-clippy/issues/702 #![allow(unknown_lints)] #![allow(clippy::all)] #![allow(unused_attributes)] #![cfg_attr(rustfmt, rustfmt::skip)] #![allow(box_pointers)] #![allow(dead_code)] #![allow(missing_docs)] #![allow(non_camel_case_types)] #![allow(non_snake_case)] #![allow(non_upper_case_globals)] #![allow(trivial_casts)] #![allow(unused_imports)] #![allow(unused_results)] //! Generated file from `arith.proto` /// Generated files are compatible only with the same version /// of protobuf runtime. // const _PROTOBUF_VERSION_CHECK: () = ::protobuf::VERSION_2_28_0; #[derive(PartialEq,Clone,Default)] pub struct ProtoArgs { // message fields pub A: i32, pub B: i32, // special fields pub unknown_fields: ::protobuf::UnknownFields, pub cached_size: ::protobuf::CachedSize, } impl<'a> ::std::default::Default for &'a ProtoArgs { fn default() -> &'a ProtoArgs { <ProtoArgs as ::protobuf::Message>::default_instance() } } impl ProtoArgs { pub fn new() -> ProtoArgs { ::std::default::Default::default() } // int32 A = 1; pub fn get_A(&self) -> i32 { self.A } pub fn clear_A(&mut self) { self.A = 0; } // Param is passed by value, moved pub fn set_A(&mut self, v: i32) { self.A = v; } // int32 B = 2; pub fn get_B(&self) -> i32 { self.B } pub fn clear_B(&mut self) { self.B = 0; } // Param is passed by value, moved pub fn set_B(&mut self, v: i32) { self.B = v; } } impl ::protobuf::Message for ProtoArgs { fn is_initialized(&self) -> bool { true } fn merge_from(&mut self, is: &mut ::protobuf::CodedInputStream<'_>) -> ::protobuf::ProtobufResult<()> { while !is.eof()? { let (field_number, wire_type) = is.read_tag_unpack()?; match field_number { 1 => { if wire_type != ::protobuf::wire_format::WireTypeVarint { return ::std::result::Result::Err(::protobuf::rt::unexpected_wire_type(wire_type)); } let tmp = is.read_int32()?; self.A = tmp; }, 2 => { if wire_type != ::protobuf::wire_format::WireTypeVarint { return ::std::result::Result::Err(::protobuf::rt::unexpected_wire_type(wire_type)); } let tmp = is.read_int32()?; self.B = tmp; }, _ => { ::protobuf::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; }, }; } ::std::result::Result::Ok(()) } // Compute sizes of nested messages #[allow(unused_variables)] fn compute_size(&self) -> u32 { let mut my_size = 0; if self.A != 0 { my_size += ::protobuf::rt::value_size(1, self.A, ::protobuf::wire_format::WireTypeVarint); } if self.B != 0 { my_size += ::protobuf::rt::value_size(2, self.B, ::protobuf::wire_format::WireTypeVarint); } my_size += ::protobuf::rt::unknown_fields_size(self.get_unknown_fields()); self.cached_size.set(my_size); my_size } fn write_to_with_cached_sizes(&self, os: &mut ::protobuf::CodedOutputStream<'_>) -> ::protobuf::ProtobufResult<()> { if self.A != 0 { os.write_int32(1, self.A)?; } if self.B != 0 { os.write_int32(2, self.B)?; } os.write_unknown_fields(self.get_unknown_fields())?; ::std::result::Result::Ok(()) } fn get_cached_size(&self) -> u32 { self.cached_size.get() } fn get_unknown_fields(&self) -> &::protobuf::UnknownFields { &self.unknown_fields } fn mut_unknown_fields(&mut self) -> &mut ::protobuf::UnknownFields { &mut self.unknown_fields } fn as_any(&self) -> &dyn (::std::any::Any) { self as &dyn (::std::any::Any) } fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { self as &mut dyn (::std::any::Any) } fn into_any(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> { self } fn descriptor(&self) -> &'static ::protobuf::reflect::MessageDescriptor { Self::descriptor_static() } fn new() -> ProtoArgs { ProtoArgs::new() } fn descriptor_static() -> &'static ::protobuf::reflect::MessageDescriptor { static descriptor: ::protobuf::rt::LazyV2<::protobuf::reflect::MessageDescriptor> = ::protobuf::rt::LazyV2::INIT; descriptor.get(|| { let mut fields = ::std::vec::Vec::new(); fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeInt32>( "A", |m: &ProtoArgs| { &m.A }, |m: &mut ProtoArgs| { &mut m.A }, )); fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeInt32>( "B", |m: &ProtoArgs| { &m.B }, |m: &mut ProtoArgs| { &mut m.B }, )); ::protobuf::reflect::MessageDescriptor::new_pb_name::<ProtoArgs>( "ProtoArgs", fields, file_descriptor_proto() ) }) } fn default_instance() -> &'static ProtoArgs { static instance: ::protobuf::rt::LazyV2<ProtoArgs> = ::protobuf::rt::LazyV2::INIT; instance.get(ProtoArgs::new) } } impl ::protobuf::Clear for ProtoArgs { fn clear(&mut self) { self.A = 0; self.B = 0; self.unknown_fields.clear(); } } impl ::std::fmt::Debug for ProtoArgs { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { ::protobuf::text_format::fmt(self, f) } } impl ::protobuf::reflect::ProtobufValue for ProtoArgs { fn as_ref(&self) -> ::protobuf::reflect::ReflectValueRef { ::protobuf::reflect::ReflectValueRef::Message(self) } } #[derive(PartialEq,Clone,Default)] pub struct ProtoReply { // message fields pub C: i32, // special fields pub unknown_fields: ::protobuf::UnknownFields, pub cached_size: ::protobuf::CachedSize, } impl<'a> ::std::default::Default for &'a ProtoReply { fn default() -> &'a ProtoReply { <ProtoReply as ::protobuf::Message>::default_instance() } } impl ProtoReply { pub fn new() -> ProtoReply { ::std::default::Default::default() } // int32 C = 1; pub fn get_C(&self) -> i32 { self.C } pub fn clear_C(&mut self) { self.C = 0; } // Param is passed by value, moved pub fn set_C(&mut self, v: i32) { self.C = v; } } impl ::protobuf::Message for ProtoReply { fn is_initialized(&self) -> bool { true } fn merge_from(&mut self, is: &mut ::protobuf::CodedInputStream<'_>) -> ::protobuf::ProtobufResult<()> { while !is.eof()? { let (field_number, wire_type) = is.read_tag_unpack()?; match field_number { 1 => { if wire_type != ::protobuf::wire_format::WireTypeVarint { return ::std::result::Result::Err(::protobuf::rt::unexpected_wire_type(wire_type)); } let tmp = is.read_int32()?; self.C = tmp; }, _ => { ::protobuf::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; }, }; } ::std::result::Result::Ok(()) } // Compute sizes of nested messages #[allow(unused_variables)] fn compute_size(&self) -> u32 { let mut my_size = 0; if self.C != 0 { my_size += ::protobuf::rt::value_size(1, self.C, ::protobuf::wire_format::WireTypeVarint); } my_size += ::protobuf::rt::unknown_fields_size(self.get_unknown_fields()); self.cached_size.set(my_size); my_size } fn write_to_with_cached_sizes(&self, os: &mut ::protobuf::CodedOutputStream<'_>) -> ::protobuf::ProtobufResult<()> { if self.C != 0 { os.write_int32(1, self.C)?; } os.write_unknown_fields(self.get_unknown_fields())?; ::std::result::Result::Ok(()) } fn get_cached_size(&self) -> u32 { self.cached_size.get() } fn get_unknown_fields(&self) -> &::protobuf::UnknownFields { &self.unknown_fields } fn mut_unknown_fields(&mut self) -> &mut ::protobuf::UnknownFields { &mut self.unknown_fields } fn as_any(&self) -> &dyn (::std::any::Any) { self as &dyn (::std::any::Any) } fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { self as &mut dyn (::std::any::Any) } fn into_any(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> { self } fn descriptor(&self) -> &'static ::protobuf::reflect::MessageDescriptor { Self::descriptor_static() } fn new() -> ProtoReply { ProtoReply::new() } fn descriptor_static() -> &'static ::protobuf::reflect::MessageDescriptor { static descriptor: ::protobuf::rt::LazyV2<::protobuf::reflect::MessageDescriptor> = ::protobuf::rt::LazyV2::INIT; descriptor.get(|| { let mut fields = ::std::vec::Vec::new(); fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeInt32>( "C", |m: &ProtoReply| { &m.C }, |m: &mut ProtoReply| { &mut m.C }, )); ::protobuf::reflect::MessageDescriptor::new_pb_name::<ProtoReply>( "ProtoReply", fields, file_descriptor_proto() ) }) } fn default_instance() -> &'static ProtoReply { static instance: ::protobuf::rt::LazyV2<ProtoReply> = ::protobuf::rt::LazyV2::INIT; instance.get(ProtoReply::new) } } impl ::protobuf::Clear for ProtoReply { fn clear(&mut self) { self.C = 0; self.unknown_fields.clear(); } } impl ::std::fmt::Debug for ProtoReply { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { ::protobuf::text_format::fmt(self, f) } } impl ::protobuf::reflect::ProtobufValue for ProtoReply { fn as_ref(&self) -> ::protobuf::reflect::ReflectValueRef { ::protobuf::reflect::ReflectValueRef::Message(self) } } static file_descriptor_proto_data: &'static [u8] = b"\ \n\x0barith.proto\x12\x06client\"-\n\tProtoArgs\x12\x0e\n\x01A\x18\x01\ \x20\x01(\x05R\x01AB\0\x12\x0e\n\x01B\x18\x02\x20\x01(\x05R\x01BB\0:\0\"\ \x1e\n\nProtoReply\x12\x0e\n\x01C\x18\x01\x20\x01(\x05R\x01CB\0:\0B\0b\ \x06proto3\ "; static file_descriptor_proto_lazy: ::protobuf::rt::LazyV2<::protobuf::descriptor::FileDescriptorProto> = ::protobuf::rt::LazyV2::INIT; fn parse_descriptor_proto() -> ::protobuf::descriptor::FileDescriptorProto { ::protobuf::Message::parse_from_bytes(file_descriptor_proto_data).unwrap() } pub fn file_descriptor_proto() -> &'static ::protobuf::descriptor::FileDescriptorProto { file_descriptor_proto_lazy.get(|| { parse_descriptor_proto() }) }
rust
Apache-2.0
09578e704de21af635da8357d36be468f10df27b
2026-01-04T20:19:51.398380Z
false
smallnest/rpcx-rs
https://github.com/smallnest/rpcx-rs/blob/09578e704de21af635da8357d36be468f10df27b/examples/protobuf/mul_model_proto/src/lib.rs
examples/protobuf/mul_model_proto/src/lib.rs
pub mod arith; pub use arith::*; use protobuf::Message; use rpcx::{Error, ErrorKind, Result, RpcxParam, SerializeType}; impl RpcxParam for ProtoArgs { fn into_bytes(&self, st: SerializeType) -> Result<Vec<u8>> { match st { SerializeType::Protobuf => self .write_to_bytes() .map_err(|err| Error::new(ErrorKind::Serialization, err)), _ => Err(Error::new(ErrorKind::Other, "unknown format")), } } fn from_slice(&mut self, st: SerializeType, data: &[u8]) -> Result<()> { match st { SerializeType::Protobuf => self .merge_from_bytes(data) .map_err(|err| Error::new(ErrorKind::Serialization, err)), _ => Err(Error::new(ErrorKind::Other, "unknown format")), } } } impl RpcxParam for ProtoReply { fn into_bytes(&self, st: SerializeType) -> Result<Vec<u8>> { match st { SerializeType::Protobuf => self .write_to_bytes() .map_err(|err| Error::new(ErrorKind::Serialization, err)), _ => Err(Error::new(ErrorKind::Other, "unknown format")), } } fn from_slice(&mut self, st: SerializeType, data: &[u8]) -> Result<()> { match st { SerializeType::Protobuf => self .merge_from_bytes(data) .map_err(|err| Error::new(ErrorKind::Serialization, err)), _ => Err(Error::new(ErrorKind::Other, "unknown format")), } } }
rust
Apache-2.0
09578e704de21af635da8357d36be468f10df27b
2026-01-04T20:19:51.398380Z
false
smallnest/rpcx-rs
https://github.com/smallnest/rpcx-rs/blob/09578e704de21af635da8357d36be468f10df27b/examples/client_call_mul_async/src/main.rs
examples/client_call_mul_async/src/main.rs
use std::collections::hash_map::HashMap; use mul_model::*; use rpcx::*; #[tokio::main] pub async fn main() -> Result<()> { let mut c: Client = Client::new("127.0.0.1:8972"); c.start().map_err(|err| println!("{}", err)).unwrap(); c.opt.serialize_type = SerializeType::MsgPack; let mut a = 1; loop { let service_path = String::from("Arith"); let service_method = String::from("Mul"); let metadata = HashMap::new(); let args = ArithAddArgs { a, b: 10 }; a += 1; let resp = c .send( &service_path, &service_method, false, false, &metadata, &args, ) .await; let reply: Result<ArithAddReply> = get_result(resp, SerializeType::MsgPack); match reply { Ok(r) => println!("received: {:?}", r), Err(err) => println!("received err:{}", err), } } }
rust
Apache-2.0
09578e704de21af635da8357d36be468f10df27b
2026-01-04T20:19:51.398380Z
false
luis-ota/swaptop
https://github.com/luis-ota/swaptop/blob/7b724d1125d48c737562fdb45537c6143141a685/src/swap_info.rs
src/swap_info.rs
use std::collections::HashMap; use thiserror::Error; #[cfg(target_os = "windows")] use std::io; #[cfg(target_os = "linux")] use proc_mounts::SwapIter; #[cfg(target_os = "linux")] use procfs::{self, Current, Meminfo}; #[derive(Debug, Clone)] pub struct ProcessSwapInfo { pub pid: u32, pub name: String, pub swap_size: f64, } #[cfg(target_os = "linux")] #[derive(Debug, Clone)] pub struct InfoSwap { pub name: String, pub kind: String, pub size_kb: f64, pub used_kb: f64, pub priority: isize, } #[derive(Debug, Clone, Default)] pub struct SwapUpdate { #[cfg(target_os = "linux")] pub swap_devices: Vec<InfoSwap>, pub total_swap: u64, pub used_swap: u64, } #[derive(Debug, Clone, Default)] pub enum SizeUnits { #[default] KB, MB, GB, } #[cfg(target_os = "linux")] #[derive(Debug, Error)] pub enum SwapDataError { #[error("Procfs error: {0}")] Procfs(#[from] procfs::ProcError), #[error("I/O error accessing /proc: {0}")] Io(#[from] std::io::Error), } #[cfg(target_os = "windows")] #[derive(Debug, Error)] pub enum SwapDataError { #[error("I/O error accessing system information: {0}")] Io(#[from] io::Error), } #[cfg(target_os = "linux")] pub fn get_swap_devices(unit: SizeUnits) -> std::io::Result<Vec<InfoSwap>> { let mut out = Vec::new(); for swap in SwapIter::new()? { let s = swap?; out.push(InfoSwap { name: s.source.to_string_lossy().into_owned(), kind: s.kind.to_string_lossy().into_owned(), size_kb: convert_swap(s.size as u64, unit.to_owned()), used_kb: convert_swap(s.used as u64, unit.to_owned()), priority: s.priority, }); } Ok(out) } #[cfg(target_os = "linux")] pub fn get_processes_using_swap(unit: SizeUnits) -> Result<Vec<ProcessSwapInfo>, SwapDataError> { let mut swap_processes = Vec::new(); for process in (procfs::process::all_processes()?).flatten() { let pid = process.pid; if let Ok(status) = process.status() && let Some(swap_kb) = status.vmswap && swap_kb > 0 { let name = match process.stat() { Ok(stat) => stat.comm, Err(_) => "unknown".to_string(), }; let swap_size = convert_swap(swap_kb, unit.clone()); let info = ProcessSwapInfo { pid: pid as u32, name, swap_size, }; swap_processes.push(info); } } Ok(swap_processes) } #[cfg(target_os = "linux")] pub fn find_mount_device(path: &std::path::Path) -> Option<String> { let abs_path = path.canonicalize().ok()?; let mountinfo = procfs::process::Process::myself() .and_then(|p| p.mountinfo()) .ok()?; let best_mount = mountinfo .into_iter() .filter(|m| abs_path.starts_with(&m.mount_point)) .max_by_key(|m| m.mount_point.components().count())?; Some(if best_mount.fs_type == "devtmpfs" { "RAM".to_owned() } else { best_mount.mount_source? }) } #[cfg(target_os = "windows")] pub fn get_processes_using_swap(unit: SizeUnits) -> Result<Vec<ProcessSwapInfo>, SwapDataError> { let mut profile_page_processes = Vec::new(); if let Ok(tasks) = tasklist::Tasklist::new() { for task in tasks { let meminfo = task.get_memory_info(); let info = ProcessSwapInfo { pid: task.pid, name: task.pname, swap_size: convert_swap(meminfo.get_pagefile_usage() as u64 / 1024, unit.clone()), }; profile_page_processes.push(info); } } Ok(profile_page_processes) } #[cfg(target_os = "linux")] pub fn get_chart_info(unit: SizeUnits) -> Result<SwapUpdate, SwapDataError> { let meminfo = Meminfo::current()?; let total_swap_kb = meminfo.swap_total / 1024; let used_swap_kb = meminfo.swap_total.saturating_sub(meminfo.swap_free) / 1024; Ok(SwapUpdate { swap_devices: get_swap_devices(unit)?, total_swap: total_swap_kb, used_swap: used_swap_kb, }) } #[cfg(target_os = "windows")] pub fn get_chart_info() -> Result<SwapUpdate, SwapDataError> { use std::mem::MaybeUninit; use winapi::um::sysinfoapi::{GlobalMemoryStatusEx, MEMORYSTATUSEX}; unsafe { let mut mem_status = MaybeUninit::<MEMORYSTATUSEX>::zeroed(); mem_status.as_mut_ptr().write(MEMORYSTATUSEX { dwLength: std::mem::size_of::<MEMORYSTATUSEX>() as u32, ..Default::default() }); if GlobalMemoryStatusEx(mem_status.as_mut_ptr()) == 0 { return Err(SwapDataError::Io(std::io::Error::last_os_error())); } let mem_status = mem_status.assume_init(); // Page file values are in bytes, convert to KB let total_swap = mem_status.ullTotalPageFile / 1024; let used_swap = (mem_status.ullTotalPageFile - mem_status.ullAvailPageFile) / 1024; Ok(SwapUpdate { total_swap, used_swap, }) } } pub fn convert_swap(kb: u64, unit: SizeUnits) -> f64 { match unit { SizeUnits::KB => kb as f64, SizeUnits::MB => kb as f64 / 1024.0, SizeUnits::GB => kb as f64 / (1024.0 * 1024.0), } } pub fn aggregate_processes(processes: Vec<ProcessSwapInfo>) -> Vec<ProcessSwapInfo> { let mut name_to_info: HashMap<String, (f64, u32)> = HashMap::new(); for process in processes { let entry = name_to_info.entry(process.name).or_insert((0.0, 0)); entry.0 += process.swap_size; entry.1 += 1; } let mut aggregated_processes: Vec<ProcessSwapInfo> = name_to_info .into_iter() .map(|(name, (swap_size, count))| ProcessSwapInfo { pid: count, name, swap_size, }) .collect(); aggregated_processes.sort_by(|a, b| { b.swap_size .partial_cmp(&a.swap_size) .unwrap_or(std::cmp::Ordering::Equal) }); aggregated_processes }
rust
MIT
7b724d1125d48c737562fdb45537c6143141a685
2026-01-04T20:19:37.018154Z
false
luis-ota/swaptop
https://github.com/luis-ota/swaptop/blob/7b724d1125d48c737562fdb45537c6143141a685/src/theme.rs
src/theme.rs
use ratatui::style::Color; #[derive(Debug, Clone, Copy, Default)] pub enum ThemeType { #[default] Default, Solarized, Monokai, Dracula, Nord, } #[derive(Debug, Clone, Copy)] pub struct Theme { pub primary: Color, pub secondary: Color, pub text: Color, pub border: Color, pub background: Color, pub scrollbar: Color, } impl Theme { pub fn from(theme_type: ThemeType) -> Self { match theme_type { ThemeType::Default => Self::default_theme(), ThemeType::Solarized => Self::solarized_theme(), ThemeType::Monokai => Self::monokai_theme(), ThemeType::Dracula => Self::dracula_theme(), ThemeType::Nord => Self::nord_theme(), } } fn default_theme() -> Self { Self { primary: Color::Rgb(100, 200, 255), secondary: Color::Rgb(150, 150, 255), text: Color::Rgb(220, 220, 220), border: Color::Rgb(80, 80, 120), background: Color::Rgb(20, 20, 30), scrollbar: Color::Rgb(100, 100, 140), } } fn solarized_theme() -> Self { Self { primary: Color::Rgb(38, 139, 210), // Blue secondary: Color::Rgb(42, 161, 152), // Cyan text: Color::Rgb(238, 232, 213), // Base1 border: Color::Rgb(88, 110, 117), // Base01 background: Color::Rgb(0, 43, 54), // Base03 scrollbar: Color::Rgb(101, 123, 131), // Base00 } } fn monokai_theme() -> Self { Self { primary: Color::Rgb(249, 38, 114), // Pink secondary: Color::Rgb(102, 217, 239), // Cyan text: Color::Rgb(248, 248, 242), // White border: Color::Rgb(117, 113, 94), // Gray background: Color::Rgb(39, 40, 34), // Dark gray scrollbar: Color::Rgb(105, 105, 105), } } fn dracula_theme() -> Self { Self { primary: Color::Rgb(189, 147, 249), // Purple secondary: Color::Rgb(139, 233, 253), // Cyan text: Color::Rgb(248, 248, 242), // White border: Color::Rgb(98, 114, 164), // Blue-gray background: Color::Rgb(40, 42, 54), // Dark purple scrollbar: Color::Rgb(68, 71, 90), } } fn nord_theme() -> Self { Self { primary: Color::Rgb(129, 161, 193), // Frost1 secondary: Color::Rgb(136, 192, 208), // Frost2 text: Color::Rgb(236, 239, 244), // Snow1 border: Color::Rgb(76, 86, 106), // PolarNight2 background: Color::Rgb(46, 52, 64), // PolarNight0 scrollbar: Color::Rgb(67, 76, 94), } } }
rust
MIT
7b724d1125d48c737562fdb45537c6143141a685
2026-01-04T20:19:37.018154Z
false
luis-ota/swaptop
https://github.com/luis-ota/swaptop/blob/7b724d1125d48c737562fdb45537c6143141a685/src/main.rs
src/main.rs
mod swap_info; mod theme; #[cfg(target_os = "linux")] use crate::swap_info::find_mount_device; use crate::swap_info::{SwapUpdate, aggregate_processes, convert_swap}; use crate::theme::{Theme, ThemeType}; use color_eyre::Result; use crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers}; use ratatui::{ DefaultTerminal, Frame, layout::{Alignment, Constraint, Direction, Layout, Rect}, style::{Style, Stylize}, symbols::Marker, text::Line, widgets::{ Axis, Block, BorderType, Chart, Dataset, GraphType, Paragraph, Scrollbar, ScrollbarOrientation, ScrollbarState, }, }; use std::time::{Duration, Instant}; use swap_info::{SizeUnits, get_chart_info, get_processes_using_swap}; const LINUX: bool = cfg!(target_os = "linux"); fn main() -> color_eyre::Result<()> { color_eyre::install()?; let terminal = ratatui::init(); let result = App::new().run(terminal); ratatui::restore(); result } #[derive(Debug, Default)] pub struct App { running: bool, display_devices: bool, pub vertical_scroll_state: ScrollbarState, pub vertical_scroll: usize, pub swap_size_unit: crate::SizeUnits, pub swap_processes_lines: Vec<Line<'static>>, pub last_update: Option<Instant>, pub chart_info: SwapUpdate, pub aggregated: bool, current_theme: ThemeType, time_window: [f64; 2], chart_data: Vec<(f64, f64)>, timeout: u64, visible_height: usize, } impl App { pub fn new() -> Self { Self { running: false, display_devices: false, vertical_scroll_state: ScrollbarState::default(), vertical_scroll: 0, swap_size_unit: SizeUnits::KB, swap_processes_lines: Vec::new(), last_update: None, chart_info: SwapUpdate::default(), aggregated: false, current_theme: ThemeType::Dracula, time_window: [0.0, 60.0], chart_data: Vec::new(), timeout: 1000, visible_height: 0, } } #[cfg(target_os = "linux")] pub fn run(mut self, mut terminal: DefaultTerminal) -> Result<()> { self.running = true; self.swap_processes_lines = self.create_process_lines(self.aggregated); self.chart_info = get_chart_info(self.swap_size_unit.to_owned())?; self.last_update = Some(Instant::now()); while self.running { if event::poll(Duration::from_millis(100))? { self.handle_crossterm_events()?; } if let Some(last_update) = self.last_update && last_update.elapsed() >= Duration::from_millis(self.timeout) { self.chart_info = get_chart_info(self.swap_size_unit.to_owned())?; self.update_chart_data(); self.last_update = Some(Instant::now()); self.swap_processes_lines = self.create_process_lines(self.aggregated); } terminal.draw(|frame| self.render(frame))?; } Ok(()) } #[cfg(target_os = "windows")] pub fn run(mut self, mut terminal: DefaultTerminal) -> Result<()> { self.running = true; self.swap_processes_lines = self.create_process_lines(self.aggregated); self.chart_info = get_chart_info()?; self.last_update = Some(Instant::now()); while self.running { if event::poll(Duration::from_millis(100))? { self.handle_crossterm_events()?; } if let Some(last_update) = self.last_update && last_update.elapsed() >= Duration::from_millis(self.timeout) { self.chart_info = get_chart_info()?; self.update_chart_data(); self.last_update = Some(Instant::now()); self.swap_processes_lines = self.create_process_lines(self.aggregated); } terminal.draw(|frame| self.render(frame))?; } Ok(()) } #[cfg(target_os = "linux")] fn render(&mut self, frame: &mut Frame) { let theme = Theme::from(self.current_theme); let main_block = Block::bordered() .border_type(BorderType::Rounded) .border_style(Style::default().fg(theme.border)) .title( Line::from(" swaptop ") .bold() .fg(theme.primary) .left_aligned(), ) .title( Line::from(format!("theme (t to change): {:?}", self.current_theme)) .bold() .fg(theme.primary) .right_aligned(), ) .title( Line::from(format!(" < {:?}ms > ", self.timeout)) .bold() .fg(theme.primary) .centered(), ) .style(Style::default().bg(theme.background).fg(theme.text)); let main_area = main_block.inner(frame.area()); let chunks = Layout::default() .direction(Direction::Vertical) .constraints([Constraint::Percentage(35), Constraint::Percentage(65)]) .split(main_area); if self.display_devices { let upper_chunks = Layout::default() .direction(Direction::Horizontal) .constraints([Constraint::Percentage(70), Constraint::Percentage(30)]) .split(chunks[0]); self.render_animated_chart(frame, upper_chunks[1], &theme); self.render_processes_list(frame, chunks[1], &theme); self.render_swap_devices(frame, upper_chunks[0], &theme); } else { self.render_animated_chart(frame, chunks[0], &theme); self.render_processes_list(frame, chunks[1], &theme); } frame.render_widget(main_block, frame.area()); } #[cfg(target_os = "windows")] fn render(&mut self, frame: &mut Frame) { let theme = Theme::from(self.current_theme); let main_block = Block::bordered() .border_type(BorderType::Rounded) .border_style(Style::default().fg(theme.border)) .title( Line::from(" swaptop ") .bold() .fg(theme.primary) .left_aligned(), ) .title( Line::from(format!("theme (t to change): {:?}", self.current_theme)) .bold() .fg(theme.primary) .right_aligned(), ) .title( Line::from(format!(" < {:?}ms > ", self.timeout)) .bold() .fg(theme.primary) .centered(), ) .style(Style::default().bg(theme.background).fg(theme.text)); let main_area = main_block.inner(frame.area()); let chunks = Layout::default() .direction(Direction::Vertical) .constraints([Constraint::Percentage(35), Constraint::Percentage(65)]) .split(main_area); self.render_animated_chart(frame, chunks[0], &theme); self.render_processes_list(frame, chunks[1], &theme); frame.render_widget(main_block, frame.area()); } fn update_chart_data(&mut self) { let timestamp = self.time_window[1]; let swap_usage = self.chart_info.used_swap as f64; self.chart_data.push((timestamp, swap_usage)); if self.chart_data.len() > 60 { self.chart_data.drain(0..1); } self.time_window[0] += 1.0; self.time_window[1] += 1.0; } fn handle_crossterm_events(&mut self) -> Result<()> { match event::read()? { Event::Key(key) if key.kind == KeyEventKind::Press => self.on_key_event(key), Event::Mouse(_) => {} Event::Resize(_, _) => {} _ => {} } Ok(()) } #[cfg(target_os = "linux")] fn on_key_event(&mut self, key: KeyEvent) { if key.kind != KeyEventKind::Press { return; } match key.code { // quit KeyCode::Esc | KeyCode::Char('q') => self.quit(), KeyCode::Char('c') if key.modifiers.contains(KeyModifiers::CONTROL) => self.quit(), // up and down list KeyCode::Char('d') | KeyCode::Down => { self.vertical_scroll = self.vertical_scroll.saturating_add(1); self.vertical_scroll_state = self.vertical_scroll_state.position(self.vertical_scroll); } KeyCode::Char('u') | KeyCode::Up => { self.vertical_scroll = self.vertical_scroll.saturating_sub(1); self.vertical_scroll_state = self.vertical_scroll_state.position(self.vertical_scroll); } KeyCode::End => { self.vertical_scroll = self.swap_processes_lines.len(); self.vertical_scroll_state = self.vertical_scroll_state.position(self.vertical_scroll); } KeyCode::Home => { self.vertical_scroll = 0; self.vertical_scroll_state = self.vertical_scroll_state.position(self.vertical_scroll); } KeyCode::PageDown => { let page_size = self.visible_height.saturating_sub(4); self.vertical_scroll = self .vertical_scroll .saturating_add(page_size) .min(self.swap_processes_lines.len().saturating_sub(1)); self.vertical_scroll_state = self.vertical_scroll_state.position(self.vertical_scroll); } KeyCode::PageUp => { let page_size = self.visible_height.saturating_sub(4); self.vertical_scroll = self.vertical_scroll.saturating_sub(page_size); self.vertical_scroll_state = self.vertical_scroll_state.position(self.vertical_scroll); } // change unit KeyCode::Char('k') => { self.swap_size_unit = SizeUnits::KB; if let Ok(info) = get_chart_info(self.swap_size_unit.clone()) { self.chart_info = info; self.swap_processes_lines = self.create_process_lines(self.aggregated); } } KeyCode::Char('m') => { self.swap_size_unit = SizeUnits::MB; if let Ok(info) = get_chart_info(self.swap_size_unit.clone()) { self.chart_info = info; self.swap_processes_lines = self.create_process_lines(self.aggregated); } } KeyCode::Char('g') => { self.swap_size_unit = SizeUnits::GB; if let Ok(info) = get_chart_info(self.swap_size_unit.clone()) { self.chart_info = info; self.swap_processes_lines = self.create_process_lines(self.aggregated); } } // aggregate KeyCode::Char('a') => self.aggregated = !self.aggregated, // change theme KeyCode::Char('t') => self.cycle_theme(), // display swap devices KeyCode::Char('h') => { if LINUX { self.display_devices = !self.display_devices } } // change timeout KeyCode::Left | KeyCode::Right => self.change_timout(key.code), _ => {} } } #[cfg(target_os = "windows")] fn on_key_event(&mut self, key: KeyEvent) { if key.kind != KeyEventKind::Press { return; } match key.code { // quit KeyCode::Esc | KeyCode::Char('q') => self.quit(), KeyCode::Char('c') if key.modifiers.contains(KeyModifiers::CONTROL) => self.quit(), // up and down list KeyCode::Char('d') | KeyCode::Down => { self.vertical_scroll = self.vertical_scroll.saturating_add(1); self.vertical_scroll_state = self.vertical_scroll_state.position(self.vertical_scroll); } KeyCode::Char('u') | KeyCode::Up => { self.vertical_scroll = self.vertical_scroll.saturating_sub(1); self.vertical_scroll_state = self.vertical_scroll_state.position(self.vertical_scroll); } KeyCode::End => { self.vertical_scroll = self.swap_processes_lines.len(); self.vertical_scroll_state = self.vertical_scroll_state.position(self.vertical_scroll); } KeyCode::Home => { self.vertical_scroll = 0; self.vertical_scroll_state = self.vertical_scroll_state.position(self.vertical_scroll); } KeyCode::PageDown => { let page_size = self.visible_height.saturating_sub(4); self.vertical_scroll = self .vertical_scroll .saturating_add(page_size) .min(self.swap_processes_lines.len().saturating_sub(1)); self.vertical_scroll_state = self.vertical_scroll_state.position(self.vertical_scroll); } KeyCode::PageUp => { let page_size = self.visible_height.saturating_sub(4); self.vertical_scroll = self.vertical_scroll.saturating_sub(page_size); self.vertical_scroll_state = self.vertical_scroll_state.position(self.vertical_scroll); } // change unit KeyCode::Char('k') => { self.swap_size_unit = SizeUnits::KB; if let Ok(info) = get_chart_info() { self.chart_info = info; self.swap_processes_lines = self.create_process_lines(self.aggregated); } } KeyCode::Char('m') => { self.swap_size_unit = SizeUnits::MB; if let Ok(info) = get_chart_info() { self.chart_info = info; self.swap_processes_lines = self.create_process_lines(self.aggregated); } } KeyCode::Char('g') => { self.swap_size_unit = SizeUnits::GB; if let Ok(info) = get_chart_info() { self.chart_info = info; self.swap_processes_lines = self.create_process_lines(self.aggregated); } } // aggregate KeyCode::Char('a') => self.aggregated = !self.aggregated, // change theme KeyCode::Char('t') => self.cycle_theme(), // display swap devices KeyCode::Char('h') => { if LINUX { self.display_devices = !self.display_devices } } // change timeout KeyCode::Left | KeyCode::Right => self.change_timout(key.code), _ => {} } } fn cycle_theme(&mut self) { self.current_theme = match self.current_theme { ThemeType::Default => ThemeType::Solarized, ThemeType::Solarized => ThemeType::Monokai, ThemeType::Monokai => ThemeType::Dracula, ThemeType::Dracula => ThemeType::Nord, ThemeType::Nord => ThemeType::Default, }; self.swap_processes_lines = self.create_process_lines(self.aggregated); } fn change_timout(&mut self, action: KeyCode) { match action { KeyCode::Left => { self.timeout = self.timeout.saturating_sub(100).max(1); } KeyCode::Right => { self.timeout = self.timeout.saturating_add(100).min(10000); } _ => {} } } fn quit(&mut self) { self.running = false; } fn create_process_lines(&self, aggregated: bool) -> Vec<Line<'static>> { let mut lines = Vec::new(); lines.push(Line::from(vec![ format!("{:>12}", if self.aggregated { "COUNT" } else { "PID" }).bold(), " | ".into(), format!("{:30}", "PROCESS").bold(), " | ".into(), format!("{:10}", "USED").bold(), ])); if let Ok(mut processes) = get_processes_using_swap(self.swap_size_unit.clone()) { processes.sort_by(|a, b| { b.swap_size .partial_cmp(&a.swap_size) .unwrap_or(std::cmp::Ordering::Equal) }); if aggregated { processes = aggregate_processes(processes); } for process in processes { let mut process_size: String = format!("{:.2}", process.swap_size); if let SizeUnits::KB = self.swap_size_unit { process_size = format!("{}", process.swap_size) } lines.push(Line::from(vec![ format!("{:12}", process.pid).into(), " | ".into(), format!("{:30}", process.name).into(), " | ".into(), format!("{:10}", process_size).into(), ])); } } lines } fn generete_total_used_title(&mut self) -> String { let total = convert_swap(self.chart_info.total_swap, self.swap_size_unit.clone()); let used = convert_swap(self.chart_info.used_swap, self.swap_size_unit.clone()); let total_used_title: String = match self.swap_size_unit { SizeUnits::KB => format!("total: {} | used: {}", total, used), SizeUnits::MB => format!("total: {} | used: {:.2}", total.round(), used), SizeUnits::GB => format!("total: {:.2} | used: {:.2}", total, used), }; total_used_title } #[cfg(target_os = "linux")] fn render_swap_devices(&mut self, frame: &mut Frame, area: Rect, theme: &Theme) { let total_used_title = self.generete_total_used_title(); let total_n_used_line = if !self.display_devices { Line::from("").fg(theme.text).left_aligned() } else { Line::from(total_used_title).fg(theme.text).left_aligned() }; let name_width = self .chart_info .swap_devices .iter() .map(|d| d.name.len()) .max() .unwrap_or(10) .max(10); let source_width = self .chart_info .swap_devices .iter() .map(|d| { let src = find_mount_device(std::path::Path::new(&d.name)) .unwrap_or_else(|| "RAM".into()); src.len() }) .max() .unwrap_or(4) .max(4); let wide = area.width >= 80; let mut lines = Vec::new(); if wide { lines.push(Line::from(format!( "{:<source_width$} | {:<name_width$} | {:<10} | {:>8} | {:>10} | {:>10}", "disk", "path", "type", "priority", "total", "used" ))); } else { lines.push(Line::from(format!( "{:<source_width$} | {:<name_width$} | {:<10} | {:>10}", "disk", "path", "total", "used" ))); } for device in &self.chart_info.swap_devices { let used = match self.swap_size_unit { SizeUnits::KB => device.used_kb.to_string(), _ => format!("{:.2}", device.used_kb), }; let source = find_mount_device(std::path::Path::new(&device.name)) .unwrap_or_else(|| "RAM".into()); let total = match self.swap_size_unit { SizeUnits::KB => device.size_kb.to_string(), _ => format!("{:.2}", device.size_kb), }; let row = if wide { format!( "{:<source_width$} | {:<name_width$} | {:<10} | {:>8} | {:>10} | {:>10}", source, device.name, device.kind, device.priority, total, used ) } else { format!( "{:<source_width$} | {:<name_width$} | {:<10} | {:>10}", source, device.name, total, used ) }; lines.push(Line::from(row)); } let block = Block::bordered() .border_type(BorderType::Rounded) .border_style(Style::default().fg(theme.border)) .style(Style::default().bg(theme.background)) .title(total_n_used_line.right_aligned()) .title(Line::from("swap devices").fg(theme.text).left_aligned()) .title_bottom(Line::from("(h to hide swap devices)").left_aligned()); let para = Paragraph::new(lines).block(block).centered(); frame.render_widget(para, area); } fn render_animated_chart(&mut self, frame: &mut Frame, area: Rect, theme: &Theme) { let total_used_title = self.generete_total_used_title(); let total_n_used_line = if self.display_devices { Line::from("").fg(theme.text).left_aligned() } else { Line::from(total_used_title).fg(theme.text).left_aligned() }; let swap_usage_percent = self.chart_info.used_swap as f64 / self.chart_info.total_swap as f64 * 100.0; let datasets = vec![ Dataset::default() .marker(Marker::Braille) .style(Style::default().fg(theme.primary)) .graph_type(GraphType::Line) .data(&self.chart_data), ]; let bottom_title = if LINUX && !self.display_devices { "(h to show swap devices)" } else { "" }; let chart = Chart::new(datasets) .block( Block::bordered() .border_type(BorderType::Rounded) .border_style(Style::default().fg(theme.border)) .title( Line::from(format!("swap usage {}%", swap_usage_percent.round() as u64)) .fg(theme.primary) .bold() .right_aligned(), ) .title(total_n_used_line) .title_bottom(Line::from(bottom_title).left_aligned()) .border_style(Style::default().fg(theme.border)) .style(Style::default().bg(theme.background)), ) .x_axis( Axis::default() .style(Style::default().fg(theme.text)) .bounds(self.time_window), ) .y_axis( Axis::default() .style(Style::default().fg(theme.text)) .bounds([0.0, self.chart_info.total_swap as f64]), ); frame.render_widget(chart, area); } fn render_processes_list(&mut self, frame: &mut Frame, area: Rect, theme: &Theme) { let unit_buttons = match self.swap_size_unit { SizeUnits::KB => "▶KB◀─MB─GB", SizeUnits::MB => "KB─▶MB◀─GB", SizeUnits::GB => "KB─MB─▶GB◀", }; self.visible_height = area.height as usize; let content_height = self.swap_processes_lines.len() + 2; self.vertical_scroll = self .vertical_scroll .min(content_height.saturating_sub(self.visible_height)); self.vertical_scroll_state = self .vertical_scroll_state .content_length(content_height) .position(self.vertical_scroll); let bottom_block = Block::bordered() .border_type(BorderType::Rounded) .border_style(Style::default().fg(theme.border)) .style(Style::default().bg(theme.background)) .title( Line::from("(a to aggregate) (u/d|▲/▼|home/end|pgup/pgdown to scroll)") .fg(theme.text) .right_aligned(), ) .title( Line::from(format!("unit (k/m/g to change): {}", unit_buttons)) .fg(theme.secondary) .bold() .left_aligned(), ); let process_paragraph = Paragraph::new(self.swap_processes_lines.clone()) .alignment(Alignment::Center) .block(bottom_block) .scroll((self.vertical_scroll as u16, 0)); frame.render_widget(process_paragraph, area); frame.render_stateful_widget( Scrollbar::new(ScrollbarOrientation::VerticalRight) .begin_symbol(Some("↑")) .end_symbol(Some("↓")) .style(Style::default().fg(theme.scrollbar)) .thumb_style(Style::default().fg(theme.primary)), area, &mut self.vertical_scroll_state, ); } }
rust
MIT
7b724d1125d48c737562fdb45537c6143141a685
2026-01-04T20:19:37.018154Z
false
ethicalhackingplayground/pathbuster
https://github.com/ethicalhackingplayground/pathbuster/blob/0df3d492f21ad5d0ee12043a2269c1276f34f86b/src/main.rs
src/main.rs
use std::collections::HashMap; use std::error::Error; use std::io::Write; use std::process::exit; use std::time::Duration; use clap::App; use clap::Arg; use futures::stream::FuturesUnordered; use futures::StreamExt; use tokio::fs::OpenOptions; use tokio::sync::mpsc; use tokio::io::{AsyncBufReadExt, BufReader}; use tokio::runtime::Builder; use tokio::time::Instant; use tokio::{fs::File, task}; use colored::Colorize; use indicatif::{ProgressBar, ProgressDrawTarget, ProgressStyle}; use crate::bruteforcer::BruteJob; use crate::bruteforcer::BruteResult; use crate::detector::Job; use crate::detector::JobResult; mod bruteforcer; mod detector; mod utils; // our fancy ascii banner to make it look hackery :D fn print_banner() { const BANNER: &str = r#" __ __ __ __ ____ ____ _/ /_/ /_ / /_ __ _______/ /____ _____ / __ \/ __ `/ __/ __ \/ __ \/ / / / ___/ __/ _ \/ ___/ / /_/ / /_/ / /_/ / / / /_/ / /_/ (__ ) /_/ __/ / / .___/\__,_/\__/_/ /_/_.___/\__,_/____/\__/\___/_/ /_/ v0.5.5 ------ path normalization pentesting tool "#; write!(&mut rainbowcoat::stdout(), "{}", BANNER).unwrap(); println!( "{}{}{} {}", "[".bold().white(), "WRN".bold().yellow(), "]".bold().white(), "Use with caution. You are responsible for your actions" .bold() .white() ); println!( "{}{}{} {}", "[".bold().white(), "WRN".bold().yellow(), "]".bold().white(), "Developers assume no liability and are not responsible for any misuse or damage." .bold() .white() ); println!( "{}{}{} {}\n", "[".bold().white(), "WRN".bold().yellow(), "]".bold().white(), "By using pathbuster, you also agree to the terms of the APIs used." .bold() .white() ); } // asynchronous entry point main where the magic happens. #[tokio::main] async fn main() -> Result<(), Box<dyn Error + Send + Sync + 'static>> { // print the banner print_banner(); // parse the cli arguments let matches = App::new("pathbuster") .version("0.5.5") .author("Blake Jacobs <krypt0mux@gmail.com>") .about("path-normalization pentesting tool") .arg( Arg::with_name("urls") .short('u') .long("urls") .takes_value(true) .required(true) .display_order(1) .help("the url you would like to test"), ) .arg( Arg::with_name("rate") .short('r') .long("rate") .takes_value(true) .default_value("1000") .display_order(2) .help("Maximum in-flight requests per second"), ) .arg( Arg::with_name("skip-brute") .long("skip-brute") .takes_value(false) .required(false) .display_order(3) .help("skip the directory bruteforcing stage"), ) .arg( Arg::with_name("drop-after-fail") .long("drop-after-fail") .takes_value(true) .default_value("302,301") .required(false) .display_order(4) .help("ignore requests with the same response code multiple times in a row"), ) .arg( Arg::with_name("int-status") .long("int-status") .takes_value(true) .required(false) .default_value("404,500") .display_order(5) .help("the internal web root status"), ) .arg( Arg::with_name("pub-status") .long("pub-status") .takes_value(true) .required(false) .default_value("400") .display_order(6) .help("the public web root status"), ) .arg( Arg::with_name("proxy") .short('p') .long("proxy") .required(false) .takes_value(true) .display_order(7) .help("http proxy to use (eg http://127.0.0.1:8080)"), ) .arg( Arg::with_name("skip-validation") .short('s') .long("skip-validation") .required(false) .takes_value(false) .display_order(8) .long_help("this is used to bypass known protected endpoints using traversals") .help("skips the validation process"), ) .arg( Arg::with_name("concurrency") .short('c') .long("concurrency") .default_value("1000") .takes_value(true) .display_order(9) .help("The amount of concurrent requests"), ) .arg( Arg::with_name("timeout") .long("timeout") .default_value("10") .takes_value(true) .display_order(10) .help("The delay between each request"), ) .arg( Arg::with_name("header") .long("header") .default_value("") .takes_value(true) .display_order(11) .help("The header to insert into each request"), ) .arg( Arg::with_name("workers") .short('w') .long("workers") .default_value("10") .takes_value(true) .display_order(12) .help("The amount of workers"), ) .arg( Arg::with_name("payloads") .long("payloads") .required(true) .takes_value(true) .display_order(13) .default_value("./payloads/traversals.txt") .help("the file containing the traversal payloads"), ) .arg( Arg::with_name("wordlist") .long("wordlist") .required(true) .takes_value(true) .display_order(14) .default_value("./wordlists/wordlist.txt") .help("the file containing the wordlist used for directory bruteforcing"), ) .arg( Arg::with_name("out") .short('o') .long("out") .display_order(15) .takes_value(true) .help("The output file"), ) .get_matches(); let rate = match matches.value_of("rate").unwrap().parse::<u32>() { Ok(n) => n, Err(_) => { println!("{}", "could not parse rate, using default of 1000"); 1000 } }; let concurrency = match matches.value_of("concurrency").unwrap().parse::<u32>() { Ok(n) => n, Err(_) => { println!("{}", "could not parse concurrency, using default of 1000"); 1000 } }; let drop_after_fail = match matches .get_one::<String>("drop-after-fail") .map(|s| s.to_string()) { Some(drop_after_fail) => drop_after_fail, None => { println!( "{}", "could not parse drop-after-fail, using default of 302,301" ); "".to_string() } }; let http_proxy = match matches.get_one::<String>("proxy").map(|p| p.to_string()) { Some(http_proxy) => http_proxy, None => "".to_string(), }; let payloads_path = match matches.value_of("payloads") { Some(payloads_path) => payloads_path, None => { println!("{}", "invalid payloads file"); exit(1); } }; let header = match matches.value_of("header").unwrap().parse::<String>() { Ok(header) => header, Err(_) => "".to_string(), }; let mut skip_dir = matches.is_present("skip-brute"); let skip_validation = matches.is_present("skip-validation"); if skip_validation { skip_dir = true; } let wordlist_path = match matches.value_of("wordlist") { Some(wordlist_path) => wordlist_path, None => { println!("{}", "invalid wordlist file"); exit(1); } }; let urls_path = match matches.get_one::<String>("urls").map(|s| s.to_string()) { Some(urls_path) => urls_path, None => "".to_string(), }; // copy some variables let _urls_path = urls_path.clone(); let int_status = match matches .get_one::<String>("int-status") .map(|s| s.to_string()) { Some(int_status) => int_status, None => "".to_string(), }; let pub_status = match matches .get_one::<String>("pub-status") .map(|s| s.to_string()) { Some(pub_status) => pub_status, None => "".to_string(), }; let timeout = match matches.get_one::<String>("timeout").map(|s| s.to_string()) { Some(timeout) => timeout.parse::<usize>().unwrap(), None => 10, }; let w: usize = match matches.value_of("workers").unwrap().parse::<usize>() { Ok(w) => w, Err(_) => { println!("{}", "could not parse workers, using default of 10"); 10 } }; // Set up a worker pool with 4 threads let rt = Builder::new_multi_thread() .enable_all() .worker_threads(w) .build() .unwrap(); let now = Instant::now(); // define the file handle for the wordlists. let payloads_handle = match File::open(payloads_path).await { Ok(payloads_handle) => payloads_handle, Err(e) => { println!("failed to open input file: {:?}", e); exit(1); } }; // define the file handle for the wordlists. let wordlist_handle = match File::open(wordlist_path).await { Ok(wordlist_handle) => wordlist_handle, Err(e) => { println!("failed to open input file: {:?}", e); exit(1); } }; // build our wordlists by constructing the arrays and storing // the words in the array. let (job_tx, job_rx) = spmc::channel::<Job>(); let (result_tx, _result_rx) = mpsc::channel::<JobResult>(w); let mut urls = vec![]; let mut payloads = vec![]; let mut wordlist = vec![]; let payload_buf = BufReader::new(payloads_handle); let mut payload_lines = payload_buf.lines(); // read the payloads file and append each line to an array. while let Ok(Some(payload)) = payload_lines.next_line().await { payloads.push(payload); } let wordlist_buf = BufReader::new(wordlist_handle); let mut wordlist_lines = wordlist_buf.lines(); // read the payloads file and append each line to an array. while let Ok(Some(word)) = wordlist_lines.next_line().await { wordlist.push(word); } // read the hosts file if specified and append each line to an array. let urls_handle = match File::open(urls_path).await { Ok(urls_handle) => urls_handle, Err(e) => { println!("failed to open input file: {:?}", e); exit(1); } }; let urls_buf = BufReader::new(urls_handle); let mut urls_lines = urls_buf.lines(); while let Ok(Some(url)) = urls_lines.next_line().await { urls.push(url); } // set the message println!( "{}", "----------------------------------------------------------" .bold() .white() ); println!( "{} {} {} {}\n{} {} {} {}\n{} {} {} {}\n{} {} {} {}\n{} {} {} {}\n{} {} {} {}", ">".bold().green(), "Payloads".bold().white(), ":".bold().white(), payloads.len().to_string().bold().cyan(), ">".bold().green(), "Urls".bold().white(), ":".bold().white(), urls.len().to_string().bold().cyan(), ">".bold().green(), "Int Matchers".bold().white(), ":".bold().white(), int_status.to_string().bold().cyan(), ">".bold().green(), "Pub Matchers".bold().white(), ":".bold().white(), pub_status.to_string().bold().cyan(), ">".bold().green(), "Concurrency".bold().white(), ":".bold().white(), concurrency.to_string().bold().cyan(), ">".bold().green(), "Workers".bold().white(), ":".bold().white(), w.to_string().bold().cyan(), ); println!( "{}", "----------------------------------------------------------" .bold() .white() ); println!(""); let bar_length = (urls.len() * payloads.len()) as u64; let pb = ProgressBar::new(bar_length); pb.set_draw_target(ProgressDrawTarget::stderr()); pb.enable_steady_tick(Duration::from_millis(200)); pb.set_style( ProgressStyle::with_template("{spinner:.blue} ({eta}) {elapsed} ({len}) {pos} {msg}") .unwrap() .progress_chars(r#"#>-"#), ); // spawn our workers let out_pb = pb.clone(); let job_pb: ProgressBar = pb.clone(); let job_wordlist = wordlist.clone(); rt.spawn(async move { detector::send_url( job_tx, urls, payloads, job_wordlist, rate, int_status, pub_status, drop_after_fail, skip_validation, header, ) .await }); // process the jobs let workers = FuturesUnordered::new(); // process the jobs for scanning. for _ in 0..concurrency { let http_proxy = http_proxy.clone(); let jrx = job_rx.clone(); let jtx: mpsc::Sender<JobResult> = result_tx.clone(); let jpb = job_pb.clone(); workers.push(task::spawn(async move { // run the detector detector::run_tester(jpb, jrx, jtx, timeout, http_proxy).await })); } let outfile_path = match matches.value_of("out") { Some(outfile_path) => outfile_path, None => { println!("{}", "invalid output file path"); exit(1); } }; let mut outfile_path_brute = String::from("discovered-routes"); outfile_path_brute.push_str(".txt"); // print the results let out_pb = out_pb.clone(); let brute_wordlist = wordlist.clone(); let worker_results: Vec<_> = workers.collect().await; let mut results: Vec<String> = vec![]; let mut brute_results: HashMap<String, String> = HashMap::new(); for result in worker_results { let result = match result { Ok(result) => result, Err(_) => continue, }; let result_data = result.data.clone(); let out_data = result.data.clone(); if result.data.is_empty() == false { let out_pb = out_pb.clone(); results.push(result_data); let outfile_handle_traversal = match OpenOptions::new() .create(true) .write(true) .append(true) .open(outfile_path) .await { Ok(outfile_handle_traversal) => outfile_handle_traversal, Err(e) => { println!("failed to open output file: {:?}", e); exit(1); } }; detector::save_traversals(out_pb, outfile_handle_traversal, out_data).await; } } if !skip_dir { let pb_results = results.clone(); let outfile_path_brute = outfile_path_brute.clone(); let outfile_handle_brute = match OpenOptions::new() .create(true) .write(true) .append(true) .open(outfile_path_brute) .await { Ok(outfile_handle_brute) => outfile_handle_brute, Err(e) => { println!("failed to open output file: {:?}", e); exit(1); } }; let out_pb = out_pb.clone(); let bar_length = (pb_results.len() * wordlist.len()) as u64; out_pb.set_length(bar_length); out_pb.set_position(0); let brute_pb = out_pb.clone(); let brute_wordlist = brute_wordlist.clone(); let (brute_job_tx, brute_job_rx) = spmc::channel::<BruteJob>(); let (brute_result_tx, brute_result_rx) = mpsc::channel::<BruteResult>(w); // start orchestrator tasks rt.spawn(async move { bruteforcer::send_word_to_url(brute_job_tx, results, brute_wordlist, rate).await }); rt.spawn(async move { bruteforcer::save_discoveries(out_pb, outfile_handle_brute, brute_result_rx).await }); // process the jobs for directory bruteforcing. let workers = FuturesUnordered::new(); for _ in 0..concurrency { let http_proxy = http_proxy.clone(); let brx = brute_job_rx.clone(); let btx: mpsc::Sender<BruteResult> = brute_result_tx.clone(); let bpb = brute_pb.clone(); workers.push(task::spawn(async move { bruteforcer::run_bruteforcer(bpb, brx, btx, timeout, http_proxy).await })); } let worker_results: Vec<_> = workers.collect().await; for result in worker_results { let result = match result { Ok(result) => result, Err(_) => continue, }; let content_length = result.rs.clone(); let result_data = result.data.clone(); if result.data.is_empty() == false { brute_results.insert(result_data, content_length); } } } rt.shutdown_background(); // print out the discoveries. println!("\n\n"); println!("{}", "Discovered:".bold().green()); println!("{}", "===========".bold().green()); for result in brute_results { println!( "{} {} {} {}", "::".bold().green(), result.0.bold().white(), "::".bold().green(), result.1.bold().white() ); } let elapsed_time = now.elapsed(); println!("\n\n"); println!( "{}, {} {}{}", "Completed!".bold().green(), "scan took".bold().white(), elapsed_time.as_secs().to_string().bold().white(), "s".bold().white() ); println!( "{} {}", "results are saved in".bold().white(), outfile_path.bold().cyan(), ); Ok(()) }
rust
MIT
0df3d492f21ad5d0ee12043a2269c1276f34f86b
2026-01-04T20:19:52.199745Z
false
ethicalhackingplayground/pathbuster
https://github.com/ethicalhackingplayground/pathbuster/blob/0df3d492f21ad5d0ee12043a2269c1276f34f86b/src/bruteforcer/mod.rs
src/bruteforcer/mod.rs
use std::{error::Error, process::exit, time::Duration}; use colored::Colorize; use difference::{Changeset, Difference}; use governor::{Quota, RateLimiter}; use indicatif::ProgressBar; use itertools::iproduct; use reqwest::{redirect, Proxy}; use tokio::{fs::File, io::AsyncWriteExt, sync::mpsc}; use crate::utils; // the BruteResult struct which will be used as jobs // to save the data to a file #[derive(Clone, Debug)] pub struct BruteResult { pub data: String, pub rs: String, } // the Job struct which will be used as jobs for directory bruteforcing #[derive(Clone, Debug)] pub struct BruteJob { pub url: Option<String>, pub word: Option<String>, } // this asynchronous function will send the results to another set of workers // for each worker to perform a directory brute force operation on each url. pub async fn send_word_to_url( mut tx: spmc::Sender<BruteJob>, urls: Vec<String>, wordlists: Vec<String>, rate: u32, ) -> Result<(), Box<dyn Error + Send + Sync + 'static>> { //set rate limit let lim = RateLimiter::direct(Quota::per_second(std::num::NonZeroU32::new(rate).unwrap())); // start the scan for (word, url) in iproduct!(wordlists, urls) { let url_cp = url.clone(); let msg = BruteJob { url: Some(url_cp), word: Some(word.clone()), }; if let Err(_) = tx.send(msg) { continue; } lim.until_ready().await; } Ok(()) } // runs the directory bruteforcer on the job pub async fn run_bruteforcer( pb: ProgressBar, rx: spmc::Receiver<BruteJob>, tx: mpsc::Sender<BruteResult>, timeout: usize, http_proxy: String, ) -> BruteResult { let mut headers = reqwest::header::HeaderMap::new(); headers.insert( reqwest::header::USER_AGENT, reqwest::header::HeaderValue::from_static( "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:95.0) Gecko/20100101 Firefox/95.0", ), ); let client; if http_proxy.is_empty() { //no certs client = reqwest::Client::builder() .default_headers(headers) .redirect(redirect::Policy::none()) .timeout(Duration::from_secs(timeout.try_into().unwrap())) .danger_accept_invalid_hostnames(true) .danger_accept_invalid_certs(true) .build() .unwrap(); } else { let proxy = match Proxy::all(http_proxy) { Ok(proxy) => proxy, Err(e) => { pb.println(format!("Could not setup proxy, err: {:?}", e)); exit(1); } }; //no certs client = reqwest::Client::builder() .default_headers(headers) .redirect(redirect::Policy::none()) .timeout(Duration::from_secs(timeout.try_into().unwrap())) .danger_accept_invalid_hostnames(true) .danger_accept_invalid_certs(true) .proxy(proxy) .build() .unwrap(); } while let Ok(job) = rx.recv() { let job_url = job.url.unwrap(); let job_word = job.word.unwrap(); let job_url_new = job_url.clone(); pb.inc(1); let mut web_root_url: String = String::from(""); let mut internal_web_root_url: String = String::from(job_url); let url = match reqwest::Url::parse(&job_url_new) { Ok(url) => url, Err(_) => { continue; } }; let schema = url.scheme().to_string(); let host = match url.host_str() { Some(host) => host, None => continue, }; web_root_url.push_str(&schema); web_root_url.push_str("://"); web_root_url.push_str(&host); web_root_url.push_str("/"); web_root_url.push_str(&job_word); internal_web_root_url.push_str(&job_word); let internal_url = internal_web_root_url.clone(); let internal_web_url = internal_url.clone(); pb.set_message(format!( "{} {}", "directory bruteforcing ::".bold().white(), internal_url.bold().blue(), )); let internal_url = internal_web_url.clone(); let get = client.get(internal_web_url); let internal_get = client.get(internal_web_root_url); let public_get = client.get(web_root_url); let public_req = match public_get.build() { Ok(req) => req, Err(_) => { continue; } }; let internal_req = match internal_get.build() { Ok(req) => req, Err(_) => { continue; } }; let public_resp = match client.execute(public_req).await { Ok(public_resp) => public_resp, Err(_) => { continue; } }; let internal_resp = match client.execute(internal_req).await { Ok(internal_resp) => internal_resp, Err(_) => { continue; } }; let public_resp_text = match public_resp.text().await { Ok(public_resp_text) => public_resp_text, Err(_) => continue, }; let internal_resp_text = match internal_resp.text().await { Ok(internal_resp_text) => internal_resp_text, Err(_) => continue, }; let req = match get.build() { Ok(req) => req, Err(_) => { continue; } }; let resp = match client.execute(req).await { Ok(resp) => resp, Err(_) => { continue; } }; let content_length = match resp.content_length() { Some(content_length) => content_length.to_string(), None => "".to_string(), }; let (ok, distance_between_responses) = utils::get_response_change(&internal_resp_text, &public_resp_text); if ok && resp.status().as_str() == "200" { let internal_resp_text_lines = internal_resp_text.lines().collect::<Vec<_>>(); let public_resp_text_lines = public_resp_text.lines().collect::<Vec<_>>(); let changeset = Changeset::new( &internal_resp_text_lines.join("\n"), &public_resp_text_lines.join("\n"), "", ); if !changeset.diffs.is_empty() { pb.println(format!( "\n{}{}{} {}", "(".bold().white(), "*".bold().blue(), ")".bold().white(), "found some response changes:".bold().green(), )); for diff in changeset.diffs { match diff { Difference::Same(_) => (), // ignore Difference::Add(text) => { // Add pb.println(format!("{}", text.bold().green())); } Difference::Rem(text) => { // Remove pb.println(format!("{}", text.bold().red())); } } } } pb.println(format!("\n")); pb.println(format!( "{} {}{}{} {} {}", "found something interesting".bold().green(), "(".bold().white(), distance_between_responses.to_string().bold().white(), ")".bold().white(), "deviations from webroot ::".bold().white(), internal_url.bold().blue(), )); // send the result message through the channel to the workers. let result_msg = BruteResult { data: internal_url.to_owned(), rs: content_length, }; let result = result_msg.clone(); if let Err(_) = tx.send(result_msg).await { continue; } pb.inc_length(1); return result; } } return BruteResult { data: "".to_string(), rs: "".to_string(), }; } // Saves the output to a file pub async fn save_discoveries( _: ProgressBar, mut outfile: File, mut brx: mpsc::Receiver<BruteResult>, ) { while let Some(result) = brx.recv().await { let mut outbuf = result.data.as_bytes().to_owned(); outbuf.extend_from_slice(b"\n"); if let Err(_) = outfile.write(&outbuf).await { continue; } } }
rust
MIT
0df3d492f21ad5d0ee12043a2269c1276f34f86b
2026-01-04T20:19:52.199745Z
false
ethicalhackingplayground/pathbuster
https://github.com/ethicalhackingplayground/pathbuster/blob/0df3d492f21ad5d0ee12043a2269c1276f34f86b/src/detector/mod.rs
src/detector/mod.rs
use std::{error::Error, process::exit, str::FromStr, time::Duration}; use colored::Colorize; use governor::{Quota, RateLimiter}; use indicatif::ProgressBar; use itertools::iproduct; use regex::Regex; use reqwest::{redirect, Proxy}; use tokio::{fs::File, io::AsyncWriteExt, sync::mpsc}; // the Job struct which will be used to define our settings for the detection jobs #[derive(Clone, Debug)] pub struct JobSettings { int_status: String, pub_status: String, drop_after_fail: String, skip_validation: bool, } // the Job struct will be used as jobs for the detection phase #[derive(Clone, Debug)] pub struct Job { settings: Option<JobSettings>, url: Option<String>, word: Option<String>, payload: Option<String>, header: Option<String>, } // the JobResult struct which will be used as jobs // to save the data to a file #[derive(Clone, Debug)] pub struct JobResult { pub data: String, } // this asynchronous function will send the url as jobs to all the workers // each worker will perform tests to detect path normalization misconfigurations. pub async fn send_url( mut tx: spmc::Sender<Job>, urls: Vec<String>, payloads: Vec<String>, wordlists: Vec<String>, rate: u32, int_status: String, pub_status: String, drop_after_fail: String, skip_validation: bool, header: String, ) -> Result<(), Box<dyn Error + Send + Sync + 'static>> { //set rate limit let lim = RateLimiter::direct(Quota::per_second(std::num::NonZeroU32::new(rate).unwrap())); // the job settings let job_settings = JobSettings { int_status: int_status.to_string(), pub_status: pub_status.to_string(), drop_after_fail: drop_after_fail, skip_validation: skip_validation, }; println!("{}", header); if skip_validation { // send the jobs for (url, payload, word) in iproduct!(urls, payloads, wordlists) { let msg = Job { settings: Some(job_settings.clone()), url: Some(url.clone()), word: Some(word.clone()), payload: Some(payload.clone()), header: Some(header.clone()), }; if let Err(_) = tx.send(msg) { continue; } lim.until_ready().await; } } else { // send the jobs for (url, payload) in iproduct!(urls, payloads) { let msg = Job { settings: Some(job_settings.clone()), url: Some(url.clone()), word: Some("".to_string()), payload: Some(payload.clone()), header: Some(header.clone()), }; if let Err(_) = tx.send(msg) { continue; } lim.until_ready().await; } } Ok(()) } // this function will test for path normalization vulnerabilities pub async fn run_tester( pb: ProgressBar, rx: spmc::Receiver<Job>, tx: mpsc::Sender<JobResult>, timeout: usize, http_proxy: String, ) -> JobResult { let mut headers = reqwest::header::HeaderMap::new(); headers.insert( reqwest::header::USER_AGENT, reqwest::header::HeaderValue::from_static( "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:95.0) Gecko/20100101 Firefox/95.0", ), ); let client; if http_proxy.is_empty() { //no certs client = reqwest::Client::builder() .default_headers(headers) .redirect(redirect::Policy::limited(10)) .timeout(Duration::from_secs(timeout.try_into().unwrap())) .danger_accept_invalid_hostnames(true) .danger_accept_invalid_certs(true) .build() .unwrap(); } else { let proxy = match Proxy::all(http_proxy) { Ok(proxy) => proxy, Err(e) => { pb.println(format!("Could not setup proxy, err: {:?}", e)); exit(1); } }; //no certs client = reqwest::Client::builder() .default_headers(headers) .redirect(redirect::Policy::limited(10)) .timeout(Duration::from_secs(timeout.try_into().unwrap())) .danger_accept_invalid_hostnames(true) .danger_accept_invalid_certs(true) .proxy(proxy) .build() .unwrap(); } while let Ok(job) = rx.recv() { let job_url = job.url.unwrap(); let job_payload = job.payload.unwrap(); let job_settings = job.settings.unwrap(); let job_url_new = job_url.clone(); let job_payload_new = job_payload.clone(); let job_header = match job.header { Some(job_header) => job_header, None => "".to_owned(), }; let job_word = match job.word { Some(job_word) => job_word, None => "".to_string(), }; let url = match reqwest::Url::parse(&job_url_new) { Ok(url) => url, Err(_) => { continue; } }; let mut job_url_with_path: String = String::from(""); let mut job_url_without_path: String = String::from(""); let schema = url.scheme().to_string(); let path = url.path().to_string(); let host = match url.host_str() { Some(host) => host, None => continue, }; job_url_with_path.push_str(&schema); job_url_with_path.push_str("://"); job_url_with_path.push_str(&host); job_url_with_path.push_str(&path); job_url_without_path.push_str(&schema); job_url_without_path.push_str("://"); job_url_without_path.push_str(&host); job_url_without_path.push_str("/"); let path_cnt = path.split("/").count() + 5; let mut payload = String::from(job_payload); let new_url = String::from(&job_url); let mut track_status_codes = 0; for _ in 0..path_cnt { let mut new_url = new_url.clone(); if !new_url.as_str().ends_with("/") { new_url.push_str("/"); } if job_settings.skip_validation { new_url.push_str(&payload); new_url.push_str(&job_word); let result_url = new_url.clone(); let title_url = result_url.clone(); pb.set_message(format!( "{} {}", "scanning ::".bold().white(), new_url.bold().blue(), )); let get = client.get(new_url); let mut req = match get.build() { Ok(req) => req, Err(_) => { continue; } }; if job_header != "" { let header_str = job_header.clone(); let header_parts: Vec<String> = header_str.split(':').map(String::from).collect(); let header_key = header_parts[0].to_string(); let header_value = header_parts[1].to_string(); let key = match reqwest::header::HeaderName::from_str(header_key.as_str()) { Ok(key) => key, Err(_) => continue, }; let value = match reqwest::header::HeaderValue::from_str(header_value.as_str()) { Ok(value) => value, Err(_) => continue, }; req.headers_mut().append(key, value); } let response = match client.execute(req).await { Ok(resp) => resp, Err(_) => { continue; } }; // fetch the server from the headers let server = match response.headers().get("Server") { Some(server) => match server.to_str() { Ok(server) => server, Err(_) => "Unknown", }, None => "Unknown", }; let content_length = match response.content_length() { Some(content_length) => content_length.to_string(), None => { "" }.to_owned(), }; let get = client.get(title_url); let mut request = match get.build() { Ok(request) => request, Err(_) => { continue; } }; if job_header != "" { let header_str = job_header.clone(); let header_parts: Vec<String> = header_str.split(':').map(String::from).collect(); let header_key = header_parts[0].to_string(); let header_value = header_parts[1].to_string(); let key = match reqwest::header::HeaderName::from_str(header_key.as_str()) { Ok(key) => key, Err(_) => continue, }; let value = match reqwest::header::HeaderValue::from_str(header_value.as_str()) { Ok(value) => value, Err(_) => continue, }; request.headers_mut().append(key, value); } let response_title = match client.execute(request).await { Ok(response_title) => response_title, Err(_) => { continue; } }; let mut title = String::from(""); let content = match response_title.text().await { Ok(content) => content, Err(_) => "".to_string(), }; let re = Regex::new(r"<title>(.*?)</title>").unwrap(); for cap in re.captures_iter(&content) { title.push_str(&cap[1]); } if job_settings.int_status.contains(response.status().as_str()) { if response.status().is_client_error() { pb.println(format!( "{}{}{} {}{}{}\n{}{}{} {}\n\t {} {}{}{}\n\t {} {}{}{}\n\t {} {}{}{}\n\t {} {}{}{}\n\t {} {}{}{}\n\t", "[".bold().white(), "OK".bold().green(), "]".bold().white(), "[".bold().white(), result_url.bold().cyan(), "]".bold().white(), "[".bold().white(), "*".bold().green(), "]".bold().white(), "Response:".bold().white(), "payload:".bold().white(), "[".bold().white(), job_payload_new.bold().blue(), "]".bold().white(), "status:".bold().white(), "[".bold().white(), response.status().as_str().bold().blue(), "]".bold().white(), "content_length:".bold().white(), "[".bold().white(), content_length.yellow(), "]".bold().white(), "server:".bold().white(), "[".bold().white(), server.bold().purple(), "]".bold().white(), "title:".bold().white(), "[".bold().white(), title.bold().purple(), "]".bold().white(), )); } if response.status().is_success() { pb.println(format!( "{}{}{} {}{}{}\n{}{}{} {}\n\t {} {}{}{}\n\t {} {}{}{}\n\t {} {}{}{}\n\t {} {}{}{}\n\t {} {}{}{}\n\t", "[".bold().white(), "OK".bold().green(), "]".bold().white(), "[".bold().white(), result_url.bold().cyan(), "]".bold().white(), "[".bold().white(), "*".bold().green(), "]".bold().white(), "Response:".bold().white(), "payload:".bold().white(), "[".bold().white(), job_payload_new.bold().blue(), "]".bold().white(), "status:".bold().white(), "[".bold().white(), response.status().as_str().bold().green(), "]".bold().white(), "content_length:".bold().white(), "[".bold().white(), content_length.yellow(), "]".bold().white(), "server:".bold().white(), "[".bold().white(), server.bold().purple(), "]".bold().white(), "title:".bold().white(), "[".bold().white(), title.bold().purple(), "]".bold().white(), )); } if response.status().is_redirection() { pb.println(format!( "{}{}{} {}{}{}\n{}{}{} {}\n\t {} {}{}{}\n\t {} {}{}{}\n\t {} {}{}{}\n\t {} {}{}{}\n\t {} {}{}{}\n\t", "[".bold().white(), "OK".bold().green(), "]".bold().white(), "[".bold().white(), result_url.bold().cyan(), "]".bold().white(), "[".bold().white(), "*".bold().green(), "]".bold().white(), "Response:".bold().white(), "payload:".bold().white(), "[".bold().white(), job_payload_new.bold().blue(), "]".bold().white(), "status:".bold().white(), "[".bold().white(), response.status().as_str().bold().blue(), "]".bold().white(), "content_length:".bold().white(), "[".bold().white(), content_length.yellow(), "]".bold().white(), "server:".bold().white(), "[".bold().white(), server.bold().purple(), "]".bold().white(), "title:".bold().white(), "[".bold().white(), title.bold().purple(), "]".bold().white(), )); } if response.status().is_server_error() { pb.println(format!( "{}{}{} {}{}{}\n{}{}{} {}\n\t {} {}{}{}\n\t {} {}{}{}\n\t {} {}{}{}\n\t {} {}{}{}\n\t {} {}{}{}\n\t", "[".bold().white(), "OK".bold().green(), "]".bold().white(), "[".bold().white(), result_url.bold().cyan(), "]".bold().white(), "[".bold().white(), "*".bold().green(), "]".bold().white(), "Response:".bold().white(), "payload:".bold().white(), "[".bold().white(), job_payload_new.bold().blue(), "]".bold().white(), "status:".bold().white(), "[".bold().white(), response.status().as_str().bold().red(), "]".bold().white(), "content_length:".bold().white(), "[".bold().white(), content_length.yellow(), "]".bold().white(), "server:".bold().white(), "[".bold().white(), server.bold().purple(), "]".bold().white(), "title:".bold().white(), "[".bold().white(), title.bold().purple(), "]".bold().white(), )); } if response.status().is_informational() { pb.println(format!( "{}{}{} {}{}{}\n{}{}{} {}\n\t {} {}{}{}\n\t {} {}{}{}\n\t {} {}{}{}\n\t {} {}{}{}\n\t {} {}{}{}\n\t", "[".bold().white(), "OK".bold().green(), "]".bold().white(), "[".bold().white(), result_url.bold().cyan(), "]".bold().white(), "[".bold().white(), "*".bold().green(), "]".bold().white(), "Response:".bold().white(), "payload:".bold().white(), "[".bold().white(), job_payload_new.bold().blue(), "]".bold().white(), "status:".bold().white(), "[".bold().white(), response.status().as_str().bold().purple(), "]".bold().white(), "content_length:".bold().white(), "[".bold().white(), content_length.yellow(), "]".bold().white(), "server:".bold().white(), "[".bold().white(), server.bold().purple(), "]".bold().white(), "title:".bold().white(), "[".bold().white(), title.bold().purple(), "]".bold().white(), )); } // send the result message through the channel to the workers. let result_msg = JobResult { data: result_url.to_owned(), }; let result_job = result_msg.clone(); if let Err(_) = tx.send(result_msg).await { continue; } return result_job; } } else { new_url.push_str(&payload); pb.set_message(format!( "{} {}", "scanning ::".bold().white(), new_url.bold().blue(), )); let new_url2 = new_url.clone(); let get = client.get(new_url); let mut req = match get.build() { Ok(req) => req, Err(_) => { continue; } }; if job_header != "" { let header_str = job_header.clone(); let header_parts: Vec<String> = header_str.split(':').map(String::from).collect(); let header_key = header_parts[0].to_string(); let header_value = header_parts[1].to_string(); let key = match reqwest::header::HeaderName::from_str(header_key.as_str()) { Ok(key) => key, Err(_) => continue, }; let value = match reqwest::header::HeaderValue::from_str(header_value.as_str()) { Ok(value) => value, Err(_) => continue, }; req.headers_mut().append(key, value); } let resp = match client.execute(req).await { Ok(resp) => resp, Err(_) => { continue; } }; let content_length = match resp.content_length() { Some(content_length) => content_length.to_string(), None => { "" }.to_owned(), }; let backonemore_url = new_url2.clone(); if job_settings.pub_status.contains(resp.status().as_str()) { // strip the suffix hax and traverse back one more level // to reach the internal doc root. let backonemore = match backonemore_url.strip_suffix(job_payload_new.as_str()) { Some(backonemore) => backonemore, None => "", }; let get = client.get(backonemore); let mut request = match get.build() { Ok(request) => request, Err(_) => { continue; } }; if job_header != "" { let header_str = job_header.clone(); let header_parts: Vec<String> = header_str.split(':').map(String::from).collect(); let header_key = header_parts[0].to_string(); let header_value = header_parts[1].to_string(); let key = match reqwest::header::HeaderName::from_str(header_key.as_str()) { Ok(key) => key, Err(_) => continue, }; let value = match reqwest::header::HeaderValue::from_str(header_value.as_str()) { Ok(value) => value, Err(_) => continue, }; request.headers_mut().append(key, value); } let response_title = match client.execute(request).await { Ok(response_title) => response_title, Err(_) => { continue; } }; let result_url = backonemore; let get = client.get(backonemore); let mut request = match get.build() { Ok(request) => request, Err(_) => { continue; } }; if job_header != "" { let header_str = job_header.clone(); let header_parts: Vec<String> = header_str.split(':').map(String::from).collect(); let header_key = header_parts[0].to_string(); let header_value = header_parts[1].to_string(); let key = match reqwest::header::HeaderName::from_str(header_key.as_str()) { Ok(key) => key, Err(_) => continue, }; let value = match reqwest::header::HeaderValue::from_str(header_value.as_str()) { Ok(value) => value, Err(_) => continue, }; request.headers_mut().append(key, value); } let response = match client.execute(request).await { Ok(response) => response, Err(_) => { continue; } }; // we hit the internal doc root. if job_settings .int_status .contains(&response.status().as_str()) && result_url.contains(&job_payload_new) { // track the status codes if job_settings.drop_after_fail == response.status().as_str() { track_status_codes += 1; if track_status_codes >= 5 { return JobResult { data: "".to_string(), }; } } pb.println(format!( "{} {}", "found internal doc root :: ".bold().green(), result_url.bold().blue(), )); let mut title = String::from(""); let content = match response_title.text().await { Ok(content) => content, Err(_) => "".to_string(), }; let re = Regex::new(r"<title>(.*?)</title>").unwrap(); for cap in re.captures_iter(&content) { title.push_str(&cap[1]); } // fetch the server from the headers let server = match response.headers().get("Server") { Some(server) => match server.to_str() { Ok(server) => server, Err(_) => "Unknown", }, None => "Unknown", }; if response.status().is_client_error() { pb.println(format!( "{}{}{} {}{}{}\n{}{}{} {}\n\t {} {}{}{}\n\t {} {}{}{}\n\t {} {}{}{}\n\t {} {}{}{}\n\t {} {}{}{}\n\t", "[".bold().white(), "OK".bold().green(), "]".bold().white(), "[".bold().white(), result_url.bold().cyan(), "]".bold().white(), "[".bold().white(), "*".bold().green(), "]".bold().white(), "Response:".bold().white(), "payload:".bold().white(), "[".bold().white(), job_payload_new.bold().blue(), "]".bold().white(), "status:".bold().white(), "[".bold().white(), response.status().as_str().bold().blue(), "]".bold().white(), "content_length:".bold().white(), "[".bold().white(), content_length.yellow(), "]".bold().white(), "server:".bold().white(), "[".bold().white(), server.bold().purple(), "]".bold().white(), "title:".bold().white(), "[".bold().white(), title.bold().purple(), "]".bold().white(), )); } if response.status().is_success() { pb.println(format!( "{}{}{} {}{}{}\n{}{}{} {}\n\t {} {}{}{}\n\t {} {}{}{}\n\t {} {}{}{}\n\t {} {}{}{}\n\t {} {}{}{}\n\t", "[".bold().white(), "OK".bold().green(), "]".bold().white(), "[".bold().white(), result_url.bold().cyan(), "]".bold().white(), "[".bold().white(), "*".bold().green(), "]".bold().white(), "Response:".bold().white(), "payload:".bold().white(), "[".bold().white(), job_payload_new.bold().blue(), "]".bold().white(), "status:".bold().white(), "[".bold().white(), response.status().as_str().bold().green(), "]".bold().white(), "content_length:".bold().white(), "[".bold().white(), content_length.yellow(), "]".bold().white(), "server:".bold().white(), "[".bold().white(), server.bold().purple(), "]".bold().white(), "title:".bold().white(), "[".bold().white(), title.bold().purple(), "]".bold().white(), )); } if response.status().is_redirection() { pb.println(format!( "{}{}{} {}{}{}\n{}{}{} {}\n\t {} {}{}{}\n\t {} {}{}{}\n\t {} {}{}{}\n\t {} {}{}{}\n\t {} {}{}{}\n\t", "[".bold().white(), "OK".bold().green(), "]".bold().white(), "[".bold().white(), result_url.bold().cyan(), "]".bold().white(), "[".bold().white(), "*".bold().green(), "]".bold().white(), "Response:".bold().white(), "payload:".bold().white(), "[".bold().white(), job_payload_new.bold().blue(), "]".bold().white(), "status:".bold().white(), "[".bold().white(), response.status().as_str().bold().blue(), "]".bold().white(), "content_length:".bold().white(), "[".bold().white(), content_length.yellow(), "]".bold().white(), "server:".bold().white(), "[".bold().white(), server.bold().purple(), "]".bold().white(),
rust
MIT
0df3d492f21ad5d0ee12043a2269c1276f34f86b
2026-01-04T20:19:52.199745Z
true
ethicalhackingplayground/pathbuster
https://github.com/ethicalhackingplayground/pathbuster/blob/0df3d492f21ad5d0ee12043a2269c1276f34f86b/src/utils/mod.rs
src/utils/mod.rs
use distance::sift3; // the Threshold struct which will be used as a range // to tell how far appart the responses are from the web root struct Threshold { threshold_start: f32, threshold_end: f32, } // make it global :) const CHANGE: Threshold = Threshold { threshold_start: 500.0, threshold_end: 500000.0, }; // uses the sift3 alogirthm to find the differences between to str inputs. pub fn get_response_change(a: &str, b: &str) -> (bool, f32) { let s = sift3(a, b); if s > CHANGE.threshold_start && s < CHANGE.threshold_end { return (true, s); } return (false, 0.0); }
rust
MIT
0df3d492f21ad5d0ee12043a2269c1276f34f86b
2026-01-04T20:19:52.199745Z
false
OpenByteDev/netcorehost
https://github.com/OpenByteDev/netcorehost/blob/4742a5d235b279a35b235bf7726c5afb9bde521d/src/lib.rs
src/lib.rs
#![cfg_attr(feature = "nightly", feature(try_trait_v2))] #![cfg_attr(feature = "doc-cfg", feature(doc_cfg))] #![warn(clippy::pedantic, clippy::cargo, unsafe_op_in_unsafe_fn, missing_docs)] #![allow( clippy::missing_safety_doc, clippy::missing_errors_doc, clippy::missing_panics_doc, clippy::module_name_repetitions, clippy::multiple_crate_versions, clippy::doc_markdown, clippy::cast_sign_loss, clippy::shadow_unrelated, clippy::redundant_closure_for_method_calls, clippy::transmute_ptr_to_ptr )] //! A Rust library for hosting the .NET Core runtime. //! //! It utilizes the .NET Core hosting API to load and execute managed code from withing the current process. //! //! # Usage //! ## Running an application //! The example below will setup the runtime, load `Test.dll` and run its `Main` method: //! ```rust //! # #[path = "../tests/common.rs"] //! # mod common; //! # common::setup(); //! # use netcorehost::{nethost, pdcstr}; //! let hostfxr = nethost::load_hostfxr().unwrap(); //! let context = hostfxr.initialize_for_dotnet_command_line(common::test_dll_path()).unwrap(); //! let result = context.run_app().value(); //! ``` //! The full example can be found in [examples/run-app](https://github.com/OpenByteDev/netcorehost/tree/master/examples/run-app). //! //! ## Calling a managed function //! A function pointer to a managed method can be aquired using an [`AssemblyDelegateLoader`](crate::hostfxr::AssemblyDelegateLoader). //! This is only supported for [`HostfxrContext`'s](crate::hostfxr::HostfxrContext) that are initialized using [`Hostfxr::initialize_for_runtime_config`](crate::hostfxr::Hostfxr::initialize_for_runtime_config). //! The [`runtimeconfig.json`](https://docs.microsoft.com/en-us/dotnet/core/run-time-config/) is automatically generated for executables, for libraries it is neccessary to add `<GenerateRuntimeConfigurationFiles>True</GenerateRuntimeConfigurationFiles>` to the projects `.csproj` file. //! ### Using the default signature //! The default method signature is defined as follows: //! ```cs //! public delegate int ComponentEntryPoint(IntPtr args, int sizeBytes); //! ``` //! //! A method with the default signature (see code below) can be loaded using [`AssemblyDelegateLoader::get_function_with_default_signature`]. //! //! **C#** //! ```cs //! using System; //! //! namespace Test { //! public static class Program { //! public static int Hello(IntPtr args, int sizeBytes) { //! Console.WriteLine("Hello from C#!"); //! return 42; //! } //! } //! } //! ``` //! //! **Rust** //! ```rust //! # #[path = "../tests/common.rs"] //! # mod common; //! # common::setup(); //! # use netcorehost::{nethost, pdcstr}; //! let hostfxr = nethost::load_hostfxr().unwrap(); //! let context = //! hostfxr.initialize_for_runtime_config(common::test_runtime_config_path()).unwrap(); //! let fn_loader = //! context.get_delegate_loader_for_assembly(common::test_dll_path()).unwrap(); //! let hello = fn_loader.get_function_with_default_signature( //! pdcstr!("Test.Program, Test"), //! pdcstr!("Hello"), //! ).unwrap(); //! let result = unsafe { hello(std::ptr::null(), 0) }; //! assert_eq!(result, 42); //! ``` //! //! ### Using UnmanagedCallersOnly //! A function pointer to a method annotated with [`UnmanagedCallersOnly`] can be loaded without //! specifying its signature (as these methods cannot be overloaded). //! //! **C#** //! ```cs //! using System; //! using System.Runtime.InteropServices; //! //! namespace Test { //! public static class Program { //! [UnmanagedCallersOnly] //! public static void UnmanagedHello() { //! Console.WriteLine("Hello from C#!"); //! } //! } //! } //! ``` //! //! **Rust** //! ```rust //! # #[path = "../tests/common.rs"] //! # mod common; //! # common::setup(); //! # use netcorehost::{nethost, pdcstr}; //! let hostfxr = nethost::load_hostfxr().unwrap(); //! let context = //! hostfxr.initialize_for_runtime_config(common::test_runtime_config_path()).unwrap(); //! let fn_loader = //! context.get_delegate_loader_for_assembly(common::test_dll_path()).unwrap(); //! let hello = fn_loader.get_function_with_unmanaged_callers_only::<fn()>( //! pdcstr!("Test.Program, Test"), //! pdcstr!("UnmanagedHello"), //! ).unwrap(); //! hello(); //! ``` //! //! //! ### Specifying the delegate type //! Another option is to define a custom delegate type and passing its assembly qualified name to [`AssemblyDelegateLoader::get_function`]. //! //! **C#** //! ```cs //! using System; //! //! namespace Test { //! public static class Program { //! public delegate void CustomHelloFunc(); //! //! public static void CustomHello() { //! Console.WriteLine("Hello from C#!"); //! } //! } //! } //! ``` //! //! **Rust** //! ```rust //! # #[path = "../tests/common.rs"] //! # mod common; //! # common::setup(); //! # use netcorehost::{nethost, pdcstr}; //! let hostfxr = nethost::load_hostfxr().unwrap(); //! let context = //! hostfxr.initialize_for_runtime_config(common::test_runtime_config_path()).unwrap(); //! let fn_loader = //! context.get_delegate_loader_for_assembly(common::test_dll_path()).unwrap(); //! let hello = fn_loader.get_function::<fn()>( //! pdcstr!("Test.Program, Test"), //! pdcstr!("CustomHello"), //! pdcstr!("Test.Program+CustomHelloFunc, Test") //! ).unwrap(); //! hello(); //! ``` //! //! The full examples can be found in [examples/call-managed-function](https://github.com/OpenByteDev/netcorehost/tree/master/examples/call-managed-function). //! //! ## Passing complex parameters //! Examples for passing non-primitive parameters can be found in [examples/passing-parameters](https://github.com/OpenByteDev/netcorehost/tree/master/examples/passing-parameters). //! //! # Features //! - `nethost` - Links against nethost and allows for automatic detection of the hostfxr library. //! - `download-nethost` - Automatically downloads the latest nethost binary from [NuGet](https://www.nuget.org/packages/Microsoft.NETCore.DotNetHost/). //! //! [`UnmanagedCallersOnly`]: <https://docs.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.unmanagedcallersonlyattribute> //! [`AssemblyDelegateLoader`]: crate::hostfxr::AssemblyDelegateLoader //! [`AssemblyDelegateLoader::get_function_with_default_signature`]: crate::hostfxr::AssemblyDelegateLoader::get_function_with_default_signature //! [`AssemblyDelegateLoader::get_function`]: crate::hostfxr::AssemblyDelegateLoader::get_function /// Module for the raw bindings for hostfxr and nethost. pub mod bindings; /// Module for abstractions of the hostfxr library. pub mod hostfxr; /// Module for abstractions of the nethost library. #[cfg(feature = "nethost")] #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "nethost")))] pub mod nethost; /// Module for a platform dependent c-like string type. #[allow(missing_docs)] pub mod pdcstring; /// Module containing error enums. pub mod error; /// Module containing additional utilities. (currently unix-only) #[cfg(feature = "utils")] #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "utils")))] pub mod utils; #[doc(hidden)] pub use hostfxr_sys::dlopen2;
rust
MIT
4742a5d235b279a35b235bf7726c5afb9bde521d
2026-01-04T20:18:20.341772Z
false
OpenByteDev/netcorehost
https://github.com/OpenByteDev/netcorehost/blob/4742a5d235b279a35b235bf7726c5afb9bde521d/src/nethost.rs
src/nethost.rs
use crate::{ bindings::{nethost::get_hostfxr_parameters, MAX_PATH}, error::{HostingError, HostingResult, HostingSuccess}, hostfxr::Hostfxr, pdcstring::{self, PdCStr, PdUChar}, }; use std::{ffi::OsString, mem::MaybeUninit, ptr}; use thiserror::Error; /// Gets the path to the hostfxr library. pub fn get_hostfxr_path() -> Result<OsString, HostingError> { unsafe { get_hostfxr_path_with_parameters(ptr::null()) } } /// Gets the path to the hostfxr library. /// Hostfxr is located as if the `assembly_path` is the apphost. pub fn get_hostfxr_path_with_assembly_path<P: AsRef<PdCStr>>( assembly_path: P, ) -> Result<OsString, HostingError> { let parameters = get_hostfxr_parameters::with_assembly_path(assembly_path.as_ref().as_ptr()); unsafe { get_hostfxr_path_with_parameters(&raw const parameters) } } /// Gets the path to the hostfxr library. /// Hostfxr is located as if an application is started using `dotnet app.dll`, which means it will be /// searched for under the `dotnet_root` path. pub fn get_hostfxr_path_with_dotnet_root<P: AsRef<PdCStr>>( dotnet_root: P, ) -> Result<OsString, HostingError> { let parameters = get_hostfxr_parameters::with_dotnet_root(dotnet_root.as_ref().as_ptr()); unsafe { get_hostfxr_path_with_parameters(&raw const parameters) } } unsafe fn get_hostfxr_path_with_parameters( parameters: *const get_hostfxr_parameters, ) -> Result<OsString, HostingError> { let mut path_buffer = [const { MaybeUninit::<PdUChar>::uninit() }; MAX_PATH]; let mut path_length = path_buffer.len(); let result = unsafe { crate::bindings::nethost::get_hostfxr_path( path_buffer.as_mut_ptr().cast(), &raw mut path_length, parameters, ) }; match HostingResult::from(result).into_result() { Ok(_) => { let path_slice = unsafe { maybe_uninit_slice_assume_init_ref(&path_buffer[..path_length]) }; Ok(unsafe { PdCStr::from_slice_with_nul_unchecked(path_slice) }.to_os_string()) } Err(HostingError::HostApiBufferTooSmall) => { let mut path_vec = Vec::new(); path_vec.resize(path_length, MaybeUninit::<pdcstring::PdUChar>::uninit()); let result = unsafe { crate::bindings::nethost::get_hostfxr_path( path_vec[0].as_mut_ptr().cast(), &raw mut path_length, parameters, ) }; assert_eq!(result as u32, HostingSuccess::Success.value()); let path_slice = unsafe { maybe_uninit_slice_assume_init_ref(&path_vec[..path_length]) }; Ok(unsafe { PdCStr::from_slice_with_nul_unchecked(path_slice) }.to_os_string()) } Err(err) => Err(err), } } /// Retrieves the path to the hostfxr library and loads it. pub fn load_hostfxr() -> Result<Hostfxr, LoadHostfxrError> { let hostfxr_path = get_hostfxr_path()?; let hostfxr = Hostfxr::load_from_path(hostfxr_path)?; Ok(hostfxr) } /// Retrieves the path to the hostfxr library and loads it. /// Hostfxr is located as if the `assembly_path` is the apphost. pub fn load_hostfxr_with_assembly_path<P: AsRef<PdCStr>>( assembly_path: P, ) -> Result<Hostfxr, LoadHostfxrError> { let hostfxr_path = get_hostfxr_path_with_assembly_path(assembly_path)?; let hostfxr = Hostfxr::load_from_path(hostfxr_path)?; Ok(hostfxr) } /// Retrieves the path to the hostfxr library and loads it. /// Hostfxr is located as if an application is started using `dotnet app.dll`, which means it will be /// searched for under the `dotnet_root` path. pub fn load_hostfxr_with_dotnet_root<P: AsRef<PdCStr>>( dotnet_root: P, ) -> Result<Hostfxr, LoadHostfxrError> { let hostfxr_path = get_hostfxr_path_with_dotnet_root(dotnet_root)?; let hostfxr = Hostfxr::load_from_path(hostfxr_path)?; Ok(hostfxr) } /// Enum for errors that can occur while locating and loading the hostfxr library. #[derive(Debug, Error)] pub enum LoadHostfxrError { /// An error occured inside the hosting components. #[error(transparent)] Hosting(#[from] HostingError), /// An error occured while loading the hostfxr library. #[error(transparent)] DlOpen(#[from] crate::dlopen2::Error), } const unsafe fn maybe_uninit_slice_assume_init_ref<T>(slice: &[MaybeUninit<T>]) -> &[T] { // not yet stable as const #[cfg(feature = "nightly")] unsafe { slice.assume_init_ref() } #[cfg(not(feature = "nightly"))] unsafe { &*(std::ptr::from_ref::<[MaybeUninit<T>]>(slice) as *const [T]) } }
rust
MIT
4742a5d235b279a35b235bf7726c5afb9bde521d
2026-01-04T20:18:20.341772Z
false
OpenByteDev/netcorehost
https://github.com/OpenByteDev/netcorehost/blob/4742a5d235b279a35b235bf7726c5afb9bde521d/src/utils.rs
src/utils.rs
#![cfg(unix)] /// Utilities for configuring the alternate signal stack on Unix platforms. /// /// Rust installs a small alternate signal stack for handling certain signals such as `SIGSEGV`. /// When embedding or hosting the .NET CoreCLR inside Rust, this small stack may be insufficient /// for the CLR exception-handling mechanisms. Increasing or disabling the alternate signal stack /// may be necessary to avoid a segfault in such cases. /// /// See <https://github.com/OpenByteDev/netcorehost/issues/38> for more details. pub mod altstack { use libc::{ mmap, sigaltstack, stack_t, MAP_ANON, MAP_FAILED, MAP_PRIVATE, PROT_READ, PROT_WRITE, SS_DISABLE, }; use std::{io, mem::MaybeUninit, ptr}; /// Represents the desired configuration of the alternate signal stack. #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)] pub enum State { /// Disables Rust's alternate signal stack. Disabled, /// Enables and sets the alternate signal stack to a given size in bytes. Enabled { /// Target altstack size size: usize, }, } impl Default for State { fn default() -> Self { Self::Enabled { size: 8 * 1024 } } } /// Configures the alternate signal stack according to the provided status. pub fn set(state: State) -> io::Result<()> { match state { State::Disabled => { let ss = stack_t { ss_flags: SS_DISABLE, ss_sp: ptr::null_mut(), ss_size: 0, }; let result = unsafe { sigaltstack(&raw const ss, ptr::null_mut()) }; if result != 0 { return Err(io::Error::last_os_error()); } } State::Enabled { size } => { let ptr = unsafe { mmap( ptr::null_mut(), size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0, ) }; if ptr == MAP_FAILED { return Err(io::Error::last_os_error()); } let ss = stack_t { ss_sp: ptr, ss_size: size, ss_flags: 0, }; let result = unsafe { sigaltstack(&raw const ss, ptr::null_mut()) }; if result != 0 { return Err(io::Error::last_os_error()); } } } Ok(()) } /// Returns the current altstack status. pub fn get() -> io::Result<State> { let mut current = MaybeUninit::uninit(); let result = unsafe { sigaltstack(ptr::null(), current.as_mut_ptr()) }; if result != 0 { return Err(io::Error::last_os_error()); } let current = unsafe { current.assume_init() }; let enabled = current.ss_flags & SS_DISABLE == 0; let state = if enabled { State::Enabled { size: current.ss_size, } } else { State::Disabled }; Ok(state) } }
rust
MIT
4742a5d235b279a35b235bf7726c5afb9bde521d
2026-01-04T20:18:20.341772Z
false
OpenByteDev/netcorehost
https://github.com/OpenByteDev/netcorehost/blob/4742a5d235b279a35b235bf7726c5afb9bde521d/src/hostfxr/delegate_loader.rs
src/hostfxr/delegate_loader.rs
use crate::{ bindings::{ char_t, hostfxr::{component_entry_point_fn, load_assembly_and_get_function_pointer_fn}, }, error::{HostingError, HostingResult, HostingSuccess}, pdcstring::{PdCStr, PdCString}, }; use num_enum::TryFromPrimitive; use std::{convert::TryFrom, mem::MaybeUninit, path::Path, ptr}; use thiserror::Error; use super::{as_managed, FnPtr, ManagedFunction, RawFnPtr, SharedHostfxrLibrary}; #[cfg(feature = "net5_0")] use crate::bindings::hostfxr::{get_function_pointer_fn, UNMANAGED_CALLERS_ONLY_METHOD}; /// A pointer to a function with the default signature. pub type ManagedFunctionWithDefaultSignature = ManagedFunction<component_entry_point_fn>; /// A pointer to a function with an unknown signature. pub type ManagedFunctionWithUnknownSignature = ManagedFunction<RawFnPtr>; /// A struct for loading pointers to managed functions for a given [`HostfxrContext`]. /// /// [`HostfxrContext`]: super::HostfxrContext #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "netcore3_0")))] pub struct DelegateLoader { pub(crate) get_load_assembly_and_get_function_pointer: load_assembly_and_get_function_pointer_fn, #[cfg(feature = "net5_0")] pub(crate) get_function_pointer: get_function_pointer_fn, #[allow(unused)] pub(crate) hostfxr: SharedHostfxrLibrary, } impl Clone for DelegateLoader { fn clone(&self) -> Self { Self { get_load_assembly_and_get_function_pointer: self .get_load_assembly_and_get_function_pointer, #[cfg(feature = "net5_0")] get_function_pointer: self.get_function_pointer, hostfxr: self.hostfxr.clone(), } } } impl DelegateLoader { unsafe fn load_assembly_and_get_function_pointer_raw( &self, assembly_path: *const char_t, type_name: *const char_t, method_name: *const char_t, delegate_type_name: *const char_t, ) -> Result<RawFnPtr, GetManagedFunctionError> { let mut delegate = MaybeUninit::uninit(); let result = unsafe { (self.get_load_assembly_and_get_function_pointer)( assembly_path, type_name, method_name, delegate_type_name, ptr::null(), delegate.as_mut_ptr(), ) }; GetManagedFunctionError::from_status_code(result)?; Ok(unsafe { delegate.assume_init() }.cast()) } fn validate_assembly_path( assembly_path: impl AsRef<PdCStr>, ) -> Result<(), GetManagedFunctionError> { #[cfg(windows)] let assembly_path = assembly_path.as_ref().to_os_string(); #[cfg(not(windows))] let assembly_path = <std::ffi::OsStr as std::os::unix::prelude::OsStrExt>::from_bytes( assembly_path.as_ref().as_slice(), ); if Path::new(&assembly_path).exists() { Ok(()) } else { Err(GetManagedFunctionError::AssemblyNotFound) } } #[cfg(feature = "net5_0")] unsafe fn get_function_pointer_raw( &self, type_name: *const char_t, method_name: *const char_t, delegate_type_name: *const char_t, ) -> Result<RawFnPtr, GetManagedFunctionError> { let mut delegate = MaybeUninit::uninit(); let result = unsafe { (self.get_function_pointer)( type_name, method_name, delegate_type_name, ptr::null(), ptr::null(), delegate.as_mut_ptr(), ) }; GetManagedFunctionError::from_status_code(result)?; Ok(unsafe { delegate.assume_init() }.cast()) } /// Calling this function will load the specified assembly in isolation (into its own `AssemblyLoadContext`) /// and it will use `AssemblyDependencyResolver` on it to provide dependency resolution. /// Once loaded it will find the specified type and method and return a native function pointer /// to that method. /// /// # Arguments /// * `assembly_path`: /// Path to the assembly to load. /// In case of complex component, this should be the main assembly of the component (the one with the .deps.json next to it). /// Note that this does not have to be the assembly from which the `type_name` and `method_name` are. /// * `type_name`: /// Assembly qualified type name to find /// * `method_name`: /// Name of the method on the `type_name` to find. The method must be static and must match the signature of `delegate_type_name`. /// * `delegate_type_name`: /// Assembly qualified delegate type name for the method signature. pub fn load_assembly_and_get_function<F: FnPtr>( &self, assembly_path: &PdCStr, type_name: &PdCStr, method_name: &PdCStr, delegate_type_name: &PdCStr, ) -> Result<ManagedFunction<as_managed!(F)>, GetManagedFunctionError> { Self::validate_assembly_path(assembly_path)?; let function = unsafe { self.load_assembly_and_get_function_pointer_raw( assembly_path.as_ptr(), type_name.as_ptr(), method_name.as_ptr(), delegate_type_name.as_ptr(), ) }?; Ok(ManagedFunction(unsafe { <as_managed!(F)>::from_ptr(function) })) } /// Calling this function will load the specified assembly in isolation (into its own `AssemblyLoadContext`) /// and it will use `AssemblyDependencyResolver` on it to provide dependency resolution. /// Once loaded it will find the specified type and method and return a native function pointer /// to that method. /// /// # Arguments /// * `assembly_path`: /// Path to the assembly to load. /// In case of complex component, this should be the main assembly of the component (the one with the .deps.json next to it). /// Note that this does not have to be the assembly from which the `type_name` and `method_name` are. /// * `type_name`: /// Assembly qualified type name to find /// * `method_name`: /// Name of the method on the `type_name` to find. The method must be static and must match the following signature: /// `public delegate int ComponentEntryPoint(IntPtr args, int sizeBytes);` pub fn load_assembly_and_get_function_with_default_signature( &self, assembly_path: &PdCStr, type_name: &PdCStr, method_name: &PdCStr, ) -> Result<ManagedFunctionWithDefaultSignature, GetManagedFunctionError> { Self::validate_assembly_path(assembly_path)?; let function = unsafe { self.load_assembly_and_get_function_pointer_raw( assembly_path.as_ptr(), type_name.as_ptr(), method_name.as_ptr(), ptr::null(), ) }?; Ok(ManagedFunction(unsafe { FnPtr::from_ptr(function) })) } /// Calling this function will load the specified assembly in isolation (into its own `AssemblyLoadContext`) /// and it will use `AssemblyDependencyResolver` on it to provide dependency resolution. /// Once loaded it will find the specified type and method and return a native function pointer /// to that method. The target method has to be annotated with the [`UnmanagedCallersOnlyAttribute`]. /// /// # Arguments /// * `assembly_path`: /// Path to the assembly to load. /// In case of complex component, this should be the main assembly of the component (the one with the .deps.json next to it). /// Note that this does not have to be the assembly from which the `type_name` and `method_name` are. /// * `type_name`: /// Assembly qualified type name to find /// * `method_name`: /// Name of the method on the `type_name` to find. The method must be static and must match be annotated with [`[UnmanagedCallersOnly]`][UnmanagedCallersOnly]. /// /// [`UnmanagedCallersOnlyAttribute`]: <https://docs.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.unmanagedcallersonlyattribute> /// [UnmanagedCallersOnly]: <https://docs.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.unmanagedcallersonlyattribute> #[cfg(feature = "net5_0")] #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "net5_0")))] pub fn load_assembly_and_get_function_with_unmanaged_callers_only<F: FnPtr>( &self, assembly_path: &PdCStr, type_name: &PdCStr, method_name: &PdCStr, ) -> Result<ManagedFunction<as_managed!(F)>, GetManagedFunctionError> { Self::validate_assembly_path(assembly_path)?; let function = unsafe { self.load_assembly_and_get_function_pointer_raw( assembly_path.as_ptr(), type_name.as_ptr(), method_name.as_ptr(), UNMANAGED_CALLERS_ONLY_METHOD, ) }?; Ok(ManagedFunction(unsafe { <as_managed!(F)>::from_ptr(function) })) } /// Calling this function will find the specified type and method and return a native function pointer to that method. /// This will **NOT** load the containing assembly. /// /// # Arguments /// * `type_name`: /// Assembly qualified type name to find /// * `method_name`: /// Name of the method on the `type_name` to find. The method must be static and must match the signature of `delegate_type_name`. /// * `delegate_type_name`: /// Assembly qualified delegate type name for the method signature. #[cfg(feature = "net5_0")] #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "net5_0")))] pub fn get_function<F: FnPtr>( &self, type_name: &PdCStr, method_name: &PdCStr, delegate_type_name: &PdCStr, ) -> Result<ManagedFunction<as_managed!(F)>, GetManagedFunctionError> { let function = unsafe { self.get_function_pointer_raw( type_name.as_ptr(), method_name.as_ptr(), delegate_type_name.as_ptr(), ) }?; Ok(ManagedFunction(unsafe { <as_managed!(F)>::from_ptr(function) })) } /// Calling this function will find the specified type and method and return a native function pointer to that method. /// This will **NOT** load the containing assembly. /// /// # Arguments /// * `type_name`: /// Assembly qualified type name to find /// * `method_name`: /// Name of the method on the `type_name` to find. The method must be static and must match the following signature: /// `public delegate int ComponentEntryPoint(IntPtr args, int sizeBytes);` #[cfg(feature = "net5_0")] pub fn get_function_with_default_signature( &self, type_name: &PdCStr, method_name: &PdCStr, ) -> Result<ManagedFunctionWithDefaultSignature, GetManagedFunctionError> { let function = unsafe { self.get_function_pointer_raw(type_name.as_ptr(), method_name.as_ptr(), ptr::null()) }?; Ok(ManagedFunction(unsafe { FnPtr::from_ptr(function) })) } /// Calling this function will find the specified type and method and return a native function pointer to that method. /// This will **NOT** load the containing assembly. /// /// # Arguments /// * `type_name`: /// Assembly qualified type name to find /// * `method_name`: /// Name of the method on the `type_name` to find. The method must be static and must match be annotated with [`UnmanagedCallersOnly`]. /// /// [`UnmanagedCallersOnlyAttribute`]: https://docs.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.unmanagedcallersonlyattribute /// [`UnmanagedCallersOnly`]: https://docs.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.unmanagedcallersonlyattribute #[cfg(feature = "net5_0")] #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "net5_0")))] pub fn get_function_with_unmanaged_callers_only<F: FnPtr>( &self, type_name: &PdCStr, method_name: &PdCStr, ) -> Result<ManagedFunction<as_managed!(F)>, GetManagedFunctionError> { let function = unsafe { self.get_function_pointer_raw( type_name.as_ptr(), method_name.as_ptr(), UNMANAGED_CALLERS_ONLY_METHOD, ) }?; Ok(ManagedFunction(unsafe { <as_managed!(F)>::from_ptr(function) })) } } /// A struct for loading pointers to managed functions for a given [`HostfxrContext`] which automatically loads the /// assembly from the given path on the first access. /// /// [`HostfxrContext`]: super::HostfxrContext #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "netcore3_0")))] #[derive(Clone)] pub struct AssemblyDelegateLoader { loader: DelegateLoader, assembly_path: PdCString, } impl AssemblyDelegateLoader { /// Creates a new [`AssemblyDelegateLoader`] wrapping the given [`DelegateLoader`] loading the assembly /// from the given path on the first access. pub fn new(loader: DelegateLoader, assembly_path: impl Into<PdCString>) -> Self { let assembly_path = assembly_path.into(); Self { loader, assembly_path, } } /// If this is the first loaded function pointer, calling this function will load the specified assembly in /// isolation (into its own `AssemblyLoadContext`) and it will use `AssemblyDependencyResolver` on it to provide /// dependency resolution. /// Otherwise or once loaded it will find the specified type and method and return a native function pointer to that method. /// Calling this function will find the specified type and method and return a native function pointer to that method. /// /// # Arguments /// * `type_name`: /// Assembly qualified type name to find /// * `method_name`: /// Name of the method on the `type_name` to find. The method must be static and must match the signature of `delegate_type_name`. /// * `delegate_type_name`: /// Assembly qualified delegate type name for the method signature. pub fn get_function<F: FnPtr>( &self, type_name: &PdCStr, method_name: &PdCStr, delegate_type_name: &PdCStr, ) -> Result<ManagedFunction<as_managed!(F)>, GetManagedFunctionError> { self.loader.load_assembly_and_get_function::<F>( self.assembly_path.as_ref(), type_name, method_name, delegate_type_name, ) } /// If this is the first loaded function pointer, calling this function will load the specified assembly in /// isolation (into its own `AssemblyLoadContext`) and it will use `AssemblyDependencyResolver` on it to provide /// dependency resolution. /// Otherwise or once loaded it will find the specified type and method and return a native function pointer to that method. /// Calling this function will find the specified type and method and return a native function pointer to that method. /// /// # Arguments /// * `type_name`: /// Assembly qualified type name to find /// * `method_name`: /// Name of the method on the `type_name` to find. The method must be static and must match the following signature: /// `public delegate int ComponentEntryPoint(IntPtr args, int sizeBytes);` pub fn get_function_with_default_signature( &self, type_name: &PdCStr, method_name: &PdCStr, ) -> Result<ManagedFunctionWithDefaultSignature, GetManagedFunctionError> { self.loader .load_assembly_and_get_function_with_default_signature( self.assembly_path.as_ref(), type_name, method_name, ) } /// If this is the first loaded function pointer, calling this function will load the specified assembly in /// isolation (into its own `AssemblyLoadContext`) and it will use `AssemblyDependencyResolver` on it to provide /// dependency resolution. /// Otherwise or once loaded it will find the specified type and method and return a native function pointer to that method. /// Calling this function will find the specified type and method and return a native function pointer to that method. /// /// # Arguments /// * `type_name`: /// Assembly qualified type name to find /// * `method_name`: /// Name of the method on the `type_name` to find. The method must be static and must match be annotated with [`UnmanagedCallersOnly`]. /// /// [`UnmanagedCallersOnlyAttribute`]: https://docs.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.unmanagedcallersonlyattribute /// [`UnmanagedCallersOnly`]: https://docs.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.unmanagedcallersonlyattribute #[cfg(feature = "net5_0")] #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "net5_0")))] pub fn get_function_with_unmanaged_callers_only<F: FnPtr>( &self, type_name: &PdCStr, method_name: &PdCStr, ) -> Result<ManagedFunction<as_managed!(F)>, GetManagedFunctionError> { self.loader .load_assembly_and_get_function_with_unmanaged_callers_only::<F>( self.assembly_path.as_ref(), type_name, method_name, ) } } /// Enum for errors that can occur while loading a managed assembly or managed function pointers. #[derive(Error, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "netcore3_0")))] pub enum GetManagedFunctionError { /// An error occured inside the hosting components. #[error("Error from hosting components: {}.", .0)] Hosting(#[from] HostingError), /// A type with the specified name could not be found or loaded. #[error("Failed to load the type or method or it has an incompatible signature.")] TypeOrMethodNotFound, /// The specified assembly could not be found. #[error("The specified assembly could not be found.")] AssemblyNotFound, /// The target method is not annotated with [`UnmanagedCallersOnly`](https://docs.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.unmanagedcallersonlyattribute). #[error("The target method is not annotated with UnmanagedCallersOnly.")] MethodNotUnmanagedCallersOnly, /// Some other unknown error occured. #[error("Unknown error code: {}", format!("{:#08X}", .0))] Other(u32), } impl GetManagedFunctionError { /// Converts the given staus code to a [`GetManagedFunctionError`]. pub fn from_status_code(code: i32) -> Result<HostingSuccess, Self> { let code = code as u32; match HostingResult::known_from_status_code(code) { Ok(HostingResult(Ok(code))) => return Ok(code), Ok(HostingResult(Err(code))) => return Err(GetManagedFunctionError::Hosting(code)), _ => {} } match HResult::try_from(code) { Ok( HResult::COR_E_TYPELOAD | HResult::COR_E_MISSINGMETHOD | HResult::COR_E_ARGUMENT, ) => return Err(Self::TypeOrMethodNotFound), Ok(HResult::FILE_NOT_FOUND) => return Err(Self::AssemblyNotFound), Ok(HResult::COR_E_INVALIDOPERATION) => return Err(Self::MethodNotUnmanagedCallersOnly), _ => {} } Err(Self::Other(code)) } } #[repr(u32)] #[non_exhaustive] #[derive(TryFromPrimitive, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[allow(non_camel_case_types)] #[rustfmt::skip] enum HResult { E_POINTER = 0x8000_4003, // System.ArgumentNullException COR_E_ARGUMENTOUTOFRANGE = 0x8013_1502, // System.ArgumentOutOfRangeException (reserved was not 0) COR_E_TYPELOAD = 0x8013_1522, // invalid type COR_E_MISSINGMETHOD = 0x8013_1513, // invalid method /*COR_E_*/FILE_NOT_FOUND = 0x8007_0002, // assembly with specified name not found (from type name) COR_E_ARGUMENT = 0x8007_0057, // invalid method signature or method not found COR_E_INVALIDOPERATION = 0x8013_1509, // invalid assembly path or not unmanaged, }
rust
MIT
4742a5d235b279a35b235bf7726c5afb9bde521d
2026-01-04T20:18:20.341772Z
false
OpenByteDev/netcorehost
https://github.com/OpenByteDev/netcorehost/blob/4742a5d235b279a35b235bf7726c5afb9bde521d/src/hostfxr/managed_function.rs
src/hostfxr/managed_function.rs
use std::{fmt::Debug, ops::Deref}; pub use fn_ptr::{FnPtr, UntypedFnPtr as RawFnPtr}; /// A wrapper around a managed function pointer. pub struct ManagedFunction<F: ManagedFnPtr>(pub(crate) F); impl<F: ManagedFnPtr> Debug for ManagedFunction<F> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("ManagedFunction") .field("ptr", &self.0.as_ptr()) .field("sig", &std::any::type_name::<F>()) .finish() } } impl<F: ManagedFnPtr> Deref for ManagedFunction<F> { type Target = F; fn deref(&self) -> &Self::Target { &self.0 } } /// Trait representing a managed function pointer. pub trait ManagedFnPtr: fn_ptr::FnPtr + fn_ptr::HasAbi<{ fn_ptr::abi!("system") }> {} impl<T: fn_ptr::FnPtr + fn_ptr::HasAbi<{ fn_ptr::abi!("system") }>> ManagedFnPtr for T {} #[macro_export] #[doc(hidden)] macro_rules! __as_managed { ($t:ty) => { ::fn_ptr::with_abi!(::fn_ptr::Abi::System, $t) }; } pub(crate) use __as_managed as as_managed;
rust
MIT
4742a5d235b279a35b235bf7726c5afb9bde521d
2026-01-04T20:18:20.341772Z
false
OpenByteDev/netcorehost
https://github.com/OpenByteDev/netcorehost/blob/4742a5d235b279a35b235bf7726c5afb9bde521d/src/hostfxr/runtime_property.rs
src/hostfxr/runtime_property.rs
use std::{collections::HashMap, mem::MaybeUninit, ptr}; use crate::{ error::{HostingError, HostingResult}, pdcstring::PdCStr, }; use super::HostfxrContext; impl<I> HostfxrContext<I> { /// Gets the runtime property value for the given key of this host context. pub fn get_runtime_property_value( &self, name: impl AsRef<PdCStr>, ) -> Result<&'_ PdCStr, HostingError> { let mut value = MaybeUninit::uninit(); let result = unsafe { self.library().hostfxr_get_runtime_property_value( self.handle().as_raw(), name.as_ref().as_ptr(), value.as_mut_ptr(), ) } .unwrap(); HostingResult::from(result).into_result()?; Ok(unsafe { PdCStr::from_str_ptr(value.assume_init()) }) } /// Sets the value of a runtime property for this host context. pub fn set_runtime_property_value( &mut self, name: impl AsRef<PdCStr>, value: impl AsRef<PdCStr>, ) -> Result<(), HostingError> { let result = unsafe { self.library().hostfxr_set_runtime_property_value( self.handle().as_raw(), name.as_ref().as_ptr(), value.as_ref().as_ptr(), ) } .unwrap(); HostingResult::from(result).into_result().map(|_| ()) } /// Remove a runtime property for this host context. pub fn remove_runtime_property_value( &mut self, name: impl AsRef<PdCStr>, ) -> Result<(), HostingError> { let result = unsafe { self.library().hostfxr_set_runtime_property_value( self.handle().as_raw(), name.as_ref().as_ptr(), ptr::null(), ) } .unwrap(); HostingResult::from(result).into_result().map(|_| ()) } /// Get all runtime properties for this host context. pub fn runtime_properties(&self) -> Result<HashMap<&'_ PdCStr, &'_ PdCStr>, HostingError> { // get count let mut count = MaybeUninit::uninit(); let mut result = unsafe { self.library().hostfxr_get_runtime_properties( self.handle().as_raw(), count.as_mut_ptr(), ptr::null_mut(), ptr::null_mut(), ) } .unwrap(); // ignore buffer too small error as the first call is only to get the required buffer size. match HostingResult::from(result).into_result() { Ok(_) | Err(HostingError::HostApiBufferTooSmall) => {} Err(e) => return Err(e), } // get values / fill buffer let mut count = unsafe { count.assume_init() }; let mut keys = Vec::with_capacity(count); let mut values = Vec::with_capacity(count); result = unsafe { self.library().hostfxr_get_runtime_properties( self.handle().as_raw(), &raw mut count, keys.as_mut_ptr(), values.as_mut_ptr(), ) } .unwrap(); HostingResult::from(result).into_result()?; unsafe { keys.set_len(count) }; unsafe { values.set_len(count) }; let keys = keys.into_iter().map(|e| unsafe { PdCStr::from_str_ptr(e) }); let values = values .into_iter() .map(|e| unsafe { PdCStr::from_str_ptr(e) }); let map = keys.zip(values).collect(); Ok(map) } }
rust
MIT
4742a5d235b279a35b235bf7726c5afb9bde521d
2026-01-04T20:18:20.341772Z
false
OpenByteDev/netcorehost
https://github.com/OpenByteDev/netcorehost/blob/4742a5d235b279a35b235bf7726c5afb9bde521d/src/hostfxr/library2_1.rs
src/hostfxr/library2_1.rs
use crate::{ bindings::hostfxr::{ hostfxr_resolve_sdk2_flags_t, hostfxr_resolve_sdk2_result_key_t, PATH_LIST_SEPARATOR, }, error::{HostingError, HostingResult}, hostfxr::{AppOrHostingResult, Hostfxr}, pdcstring::{PdCStr, PdUChar}, }; use coreclr_hosting_shared::char_t; use std::{cell::RefCell, io, mem::MaybeUninit, path::PathBuf, ptr, slice}; use super::UNSUPPORTED_HOST_VERSION_ERROR_CODE; impl Hostfxr { /// Run an application. /// /// # Arguments /// * `app_path` /// path to the application to run /// * `args` /// command-line arguments /// * `host_path` /// path to the host application /// * `dotnet_root` /// path to the .NET Core installation root /// /// This function does not return until the application completes execution. /// It will shutdown CoreCLR after the application executes. /// If the application is successfully executed, this value will return the exit code of the application. /// Otherwise, it will return an error code indicating the failure. #[cfg_attr( feature = "netcore3_0", deprecated(note = "Use `HostfxrContext::run_app` instead"), allow(deprecated) )] #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "netcore2_1")))] pub fn run_app_with_args_and_startup_info<'a, A: AsRef<PdCStr>>( &'a self, app_path: &'a PdCStr, args: impl IntoIterator<Item = &'a PdCStr>, host_path: &PdCStr, dotnet_root: &PdCStr, ) -> io::Result<AppOrHostingResult> { let args = [&self.dotnet_exe, app_path] .into_iter() .chain(args) .map(|s| s.as_ptr()) .collect::<Vec<_>>(); let result = unsafe { self.lib.hostfxr_main_startupinfo( args.len().try_into().unwrap(), args.as_ptr(), host_path.as_ptr(), dotnet_root.as_ptr(), app_path.as_ptr(), ) } .unwrap_or(UNSUPPORTED_HOST_VERSION_ERROR_CODE); Ok(AppOrHostingResult::from(result)) } /// Determine the directory location of the SDK, accounting for `global.json` and multi-level lookup policy. /// /// # Arguments /// * `sdk_dir` - main directory where SDKs are located in `sdk\[version]` sub-folders. /// * `working_dir` - directory where the search for `global.json` will start and proceed upwards /// * `allow_prerelease` - allow resolution to return a pre-release SDK version #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "netcore2_1")))] pub fn resolve_sdk( &self, sdk_dir: &PdCStr, working_dir: &PdCStr, allow_prerelease: bool, ) -> Result<ResolveSdkResult, HostingError> { let flags = if allow_prerelease { hostfxr_resolve_sdk2_flags_t::none } else { hostfxr_resolve_sdk2_flags_t::disallow_prerelease }; // Reset the output let raw_result = RawResolveSdkResult::default(); RESOLVE_SDK2_DATA.with(|sdk| *sdk.borrow_mut() = Some(raw_result)); let result = unsafe { self.lib.hostfxr_resolve_sdk2( sdk_dir.as_ptr(), working_dir.as_ptr(), flags, resolve_sdk2_callback, ) } .unwrap_or(UNSUPPORTED_HOST_VERSION_ERROR_CODE); HostingResult::from(result).into_result()?; let raw_result = RESOLVE_SDK2_DATA .with(|sdk| sdk.borrow_mut().take()) .unwrap(); Ok(ResolveSdkResult::new(raw_result)) } /// Get the list of all available SDKs ordered by ascending version. #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "netcore2_1")))] #[must_use] pub fn get_available_sdks(&self) -> Vec<PathBuf> { self.get_available_sdks_raw(None) } /// Get the list of all available SDKs ordered by ascending version, based on the provided `dotnet` executable. #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "netcore2_1")))] #[must_use] pub fn get_available_sdks_with_dotnet_path(&self, dotnet_path: &PdCStr) -> Vec<PathBuf> { self.get_available_sdks_raw(Some(dotnet_path)) } #[must_use] fn get_available_sdks_raw(&self, dotnet_path: Option<&PdCStr>) -> Vec<PathBuf> { let dotnet_path = dotnet_path.map_or_else(ptr::null, |s| s.as_ptr()); unsafe { self.lib .hostfxr_get_available_sdks(dotnet_path, get_available_sdks_callback) }; GET_AVAILABLE_SDKS_DATA .with(|sdks| sdks.borrow_mut().take()) .unwrap() } /// Get the native search directories of the runtime based upon the specified app. /// /// # Arguments /// * `app_path` - path to application #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "netcore2_1")))] pub fn get_native_search_directories( &self, app_path: &PdCStr, ) -> Result<Vec<PathBuf>, HostingError> { let mut buffer = Vec::<PdUChar>::new(); let args = [self.dotnet_exe.as_ptr(), app_path.as_ptr()]; let mut required_buffer_size = MaybeUninit::uninit(); unsafe { self.lib.hostfxr_get_native_search_directories( args.len().try_into().unwrap(), args.as_ptr(), buffer.as_mut_ptr().cast(), 0, required_buffer_size.as_mut_ptr(), ) }; let mut required_buffer_size = unsafe { required_buffer_size.assume_init() }; buffer.reserve(required_buffer_size.try_into().unwrap()); let result = unsafe { self.lib.hostfxr_get_native_search_directories( args.len().try_into().unwrap(), args.as_ptr(), buffer.spare_capacity_mut().as_mut_ptr().cast(), buffer.spare_capacity_mut().len().try_into().unwrap(), &raw mut required_buffer_size, ) } .unwrap_or(UNSUPPORTED_HOST_VERSION_ERROR_CODE); HostingResult::from(result).into_result()?; unsafe { buffer.set_len(required_buffer_size.try_into().unwrap()) }; let mut directories = Vec::new(); let last_start = 0; for i in 0..buffer.len() { if buffer[i] == PATH_LIST_SEPARATOR as PdUChar || buffer[i] == 0 { buffer[i] = 0; let directory = PdCStr::from_slice_with_nul(&buffer[last_start..=i]).unwrap(); directories.push(PathBuf::from(directory.to_os_string())); break; } } Ok(directories) } } thread_local! { static GET_AVAILABLE_SDKS_DATA: RefCell<Option<Vec<PathBuf>>> = const { RefCell::new(None) }; static RESOLVE_SDK2_DATA: RefCell<Option<RawResolveSdkResult>> = const { RefCell::new(None) }; } extern "C" fn get_available_sdks_callback(sdk_count: i32, sdks_ptr: *const *const char_t) { GET_AVAILABLE_SDKS_DATA.with(|sdks| { let mut sdks_opt = sdks.borrow_mut(); let sdks = sdks_opt.get_or_insert_with(Vec::new); let raw_sdks = unsafe { slice::from_raw_parts(sdks_ptr, sdk_count as usize) }; sdks.extend(raw_sdks.iter().copied().map(|raw_sdk| { unsafe { PdCStr::from_str_ptr(raw_sdk) } .to_os_string() .into() })); }); } extern "C" fn resolve_sdk2_callback(key: hostfxr_resolve_sdk2_result_key_t, value: *const char_t) { RESOLVE_SDK2_DATA.with(|sdks| { let path: PathBuf = unsafe { PdCStr::from_str_ptr(value) }.to_os_string().into(); let mut guard = sdks.borrow_mut(); let raw_result = guard.as_mut().unwrap(); match key { hostfxr_resolve_sdk2_result_key_t::resolved_sdk_dir => { assert_eq!(raw_result.resolved_sdk_dir, None); raw_result.resolved_sdk_dir = Some(path); } hostfxr_resolve_sdk2_result_key_t::global_json_path => { assert_eq!(raw_result.global_json_path, None); raw_result.global_json_path = Some(path); } hostfxr_resolve_sdk2_result_key_t::requested_version => { assert_eq!(raw_result.requested_version, None); raw_result.requested_version = Some(path); } hostfxr_resolve_sdk2_result_key_t::global_json_state => { assert_eq!(raw_result.global_json_state, None); raw_result.global_json_state = Some(path); } _ => { // new key encountered } } }); } #[derive(Debug, Default)] struct RawResolveSdkResult { pub resolved_sdk_dir: Option<PathBuf>, pub global_json_path: Option<PathBuf>, pub requested_version: Option<PathBuf>, pub global_json_state: Option<PathBuf>, } /// Result of [`Hostfxr::resolve_sdk`]. #[derive(Debug, Clone, PartialEq, Eq)] #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "netcore2_1")))] #[must_use] pub struct ResolveSdkResult { /// Path to the directory of the resolved sdk. pub sdk_dir: PathBuf, /// State of the global.json encountered during sdk resolution. pub global_json: GlobalJsonState, } /// State of global.json during sdk resolution with [`Hostfxr::resolve_sdk`]. #[derive(Debug, Clone, PartialEq, Eq)] pub enum GlobalJsonState { /// The global.json contained invalid data, such as a malformed version number. InvalidData, /// The global.json does not contain valid json. InvalidJson, /// No global.json was found. NotFound, /// A global.json was found and was valid. Found(GlobalJsonInfo), } impl ResolveSdkResult { fn new(raw: RawResolveSdkResult) -> Self { use hostfxr_sys::hostfxr_resolve_sdk2_global_json_state; let global_json = match raw.global_json_state { None => GlobalJsonState::NotFound, // assume not found, but could also be invalid Some(s) => match s.to_string_lossy().as_ref() { hostfxr_resolve_sdk2_global_json_state::INVALID_DATA => { GlobalJsonState::InvalidData } hostfxr_resolve_sdk2_global_json_state::INVALID_JSON => { GlobalJsonState::InvalidJson } hostfxr_resolve_sdk2_global_json_state::VALID => { GlobalJsonState::Found(GlobalJsonInfo { path: raw .global_json_path .expect("global.json found but no path provided"), requested_version: raw .requested_version .expect("global.json found but requested version not provided") .to_string_lossy() .to_string(), }) } _ => GlobalJsonState::NotFound, }, }; let sdk_dir = raw .resolved_sdk_dir .expect("resolve_sdk2 succeeded but no sdk_dir provided."); Self { sdk_dir, global_json, } } } /// Info about global.json if valid with [`Hostfxr::resolve_sdk`]. #[derive(Debug, Clone, PartialEq, Eq)] pub struct GlobalJsonInfo { path: PathBuf, requested_version: String, }
rust
MIT
4742a5d235b279a35b235bf7726c5afb9bde521d
2026-01-04T20:18:20.341772Z
false
OpenByteDev/netcorehost
https://github.com/OpenByteDev/netcorehost/blob/4742a5d235b279a35b235bf7726c5afb9bde521d/src/hostfxr/library.rs
src/hostfxr/library.rs
use crate::{ dlopen2::wrapper::Container, error::{HostingError, HostingResult}, pdcstring::PdCString, }; use derive_more::From; use std::{ env::consts::EXE_SUFFIX, ffi::OsString, path::{Path, PathBuf}, sync::Arc, }; pub(crate) type HostfxrLibrary = Container<crate::bindings::hostfxr::wrapper_option::Hostfxr>; pub(crate) type SharedHostfxrLibrary = Arc<HostfxrLibrary>; #[allow(unused, clippy::cast_possible_wrap)] pub(crate) const UNSUPPORTED_HOST_VERSION_ERROR_CODE: i32 = HostingError::HostApiUnsupportedVersion.value() as i32; /// A struct representing a loaded hostfxr library. #[derive(Clone, From)] pub struct Hostfxr { /// The underlying hostfxr library. pub lib: SharedHostfxrLibrary, pub(crate) dotnet_exe: PdCString, } fn find_dotnet_bin(hostfxr_path: impl AsRef<Path>) -> PathBuf { let mut p = hostfxr_path.as_ref().to_path_buf(); loop { if let Some(dir) = p.file_name() { if dir == "dotnet" || dir == ".dotnet" { break; } p.pop(); } else { p.clear(); break; } } p.push("dotnet"); let mut p = OsString::from(p); p.extend(Path::new(EXE_SUFFIX)); PathBuf::from(p) } impl Hostfxr { /// Loads the hostfxr library from the given path. pub fn load_from_path(path: impl AsRef<Path>) -> Result<Self, crate::dlopen2::Error> { let path = path.as_ref(); let lib = SharedHostfxrLibrary::new(unsafe { Container::load(path) }?); // Some APIs of hostfxr.dll require a path to the dotnet executable, so we try to locate it here based on the hostfxr path. let dotnet_exe = PdCString::from_os_str(find_dotnet_bin(path)).unwrap(); Ok(Self { lib, dotnet_exe }) } /// Locates the hostfxr library using [`nethost`](crate::nethost) and loads it. #[cfg(feature = "nethost")] pub fn load_with_nethost() -> Result<Self, crate::nethost::LoadHostfxrError> { crate::nethost::load_hostfxr() } /// Returns the path to the dotnet root. #[must_use] pub fn get_dotnet_root(&self) -> PathBuf { self.get_dotnet_exe().parent().unwrap().to_owned() } /// Returns the path to the dotnet executable of the same installation as hostfxr. #[must_use] pub fn get_dotnet_exe(&self) -> PathBuf { self.dotnet_exe.to_os_string().into() } } /// Either the exit code of the app if it ran successful, otherwise the error from the hosting components. #[repr(transparent)] #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct AppOrHostingResult(i32); impl AppOrHostingResult { /// Gets the raw value of the result. #[must_use] pub const fn value(&self) -> i32 { self.0 } /// Converts the result to an hosting exit code. pub fn as_hosting_exit_code(self) -> HostingResult { HostingResult::from(self.0) } } impl From<AppOrHostingResult> for i32 { fn from(code: AppOrHostingResult) -> Self { code.value() } } impl From<i32> for AppOrHostingResult { fn from(code: i32) -> Self { Self(code) } }
rust
MIT
4742a5d235b279a35b235bf7726c5afb9bde521d
2026-01-04T20:18:20.341772Z
false
OpenByteDev/netcorehost
https://github.com/OpenByteDev/netcorehost/blob/4742a5d235b279a35b235bf7726c5afb9bde521d/src/hostfxr/mod.rs
src/hostfxr/mod.rs
mod library; pub use library::*; #[cfg(feature = "netcore1_0")] mod library1_0; #[cfg(feature = "netcore1_0")] #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "netcore1_0")))] #[allow(unused)] pub use library1_0::*; #[cfg(feature = "netcore2_1")] mod library2_1; #[cfg(feature = "netcore2_1")] #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "netcore2_1")))] pub use library2_1::*; #[cfg(feature = "netcore3_0")] mod library3_0; #[cfg(feature = "netcore3_0")] #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "netcore3_0")))] #[allow(unused)] pub use library3_0::*; #[cfg(feature = "net6_0")] mod library6_0; #[cfg(feature = "net6_0")] #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "net6_0")))] pub use library6_0::*; #[cfg(feature = "netcore3_0")] mod context; #[cfg(feature = "netcore3_0")] #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "netcore3_0")))] pub use context::*; #[cfg(feature = "netcore3_0")] mod delegate_loader; #[cfg(feature = "netcore3_0")] #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "netcore3_0")))] pub use delegate_loader::*; #[cfg(feature = "netcore3_0")] mod runtime_property; #[cfg(feature = "netcore3_0")] #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "netcore3_0")))] #[allow(unused)] pub use runtime_property::*; #[cfg(feature = "netcore3_0")] mod managed_function; #[cfg(feature = "netcore3_0")] #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "netcore3_0")))] pub use managed_function::*;
rust
MIT
4742a5d235b279a35b235bf7726c5afb9bde521d
2026-01-04T20:18:20.341772Z
false
OpenByteDev/netcorehost
https://github.com/OpenByteDev/netcorehost/blob/4742a5d235b279a35b235bf7726c5afb9bde521d/src/hostfxr/library6_0.rs
src/hostfxr/library6_0.rs
use hostfxr_sys::hostfxr_dotnet_environment_info; use crate::{ error::{HostingError, HostingResult}, hostfxr::Hostfxr, pdcstring::{PdCStr, PdCString}, }; use std::{ffi::c_void, mem::MaybeUninit, path::PathBuf, ptr, slice}; use super::UNSUPPORTED_HOST_VERSION_ERROR_CODE; /// Information about the current dotnet environment loaded using [Hostfxr::get_dotnet_environment_info]. #[derive(Debug, Clone)] pub struct EnvironmentInfo { /// Version of hostfxr used to load this info. pub hostfxr_version: String, /// Commit hash of hostfxr used to load this info. pub hostfxr_commit_hash: String, /// Currently installed sdks, ordered by version ascending. pub sdks: Vec<SdkInfo>, /// Currently installed frameworks, ordered by name and then version ascending. pub frameworks: Vec<FrameworkInfo>, } impl PartialEq for EnvironmentInfo { fn eq(&self, other: &Self) -> bool { self.hostfxr_version == other.hostfxr_version && (self .hostfxr_commit_hash .starts_with(&other.hostfxr_commit_hash) || other .hostfxr_commit_hash .starts_with(&self.hostfxr_commit_hash)) && self.sdks == other.sdks && self.frameworks == other.frameworks } } impl Eq for EnvironmentInfo {} impl PartialOrd for EnvironmentInfo { fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { Some(self.hostfxr_version.cmp(&other.hostfxr_version)) } } /// A struct representing an installed sdk. #[derive(Debug, Clone, PartialEq, Eq)] pub struct SdkInfo { /// The version of the sdk. pub version: String, /// The directory containing the sdk. pub path: PathBuf, } impl PartialOrd for SdkInfo { fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { Some(self.cmp(other)) } } impl Ord for SdkInfo { fn cmp(&self, other: &Self) -> std::cmp::Ordering { self.version.cmp(&other.version) } } /// A struct representing an installed framework. #[derive(Debug, Clone, PartialEq, Eq)] pub struct FrameworkInfo { /// The name of the framework. pub name: String, /// The version of the framework. pub version: String, /// The directory containing the framework. pub path: PathBuf, } impl PartialOrd for FrameworkInfo { fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { Some(self.cmp(other)) } } impl Ord for FrameworkInfo { fn cmp(&self, other: &Self) -> std::cmp::Ordering { self.name .cmp(&other.name) .then_with(|| self.version.cmp(&other.version)) } } impl Hostfxr { /// Loads info about the dotnet environemnt, including the version of hostfxr and installed sdks and frameworks. /// /// # Ordering /// SDks are ordered by version ascending and multi-level lookup locations are put before private locations - items later in the list have priority over items earlier in the list. /// Frameworks are ordered by name ascending followed by version ascending. Multi-level lookup locations are put before private locations. /// /// # Note /// This is equivalent to the info retrieved using `dotnet --info`. /// Which means it enumerates SDKs and frameworks from the dotnet root directory (either explicitly specified or using global install location per design). /// If `DOTNET_MULTILEVEL_LOOKUP` is enabled (Windows-only), and the dotnet root is specified and it's not the global install location, /// then it will also enumerate SDKs and frameworks from the global install location. #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "net6_0")))] pub fn get_dotnet_environment_info(&self) -> Result<EnvironmentInfo, HostingError> { let dotnet_root = PdCString::from_os_str(self.get_dotnet_root()).ok(); let dotnet_root_ptr = dotnet_root.as_ref().map_or_else(ptr::null, |p| p.as_ptr()); let mut info = MaybeUninit::<EnvironmentInfo>::uninit(); let result = unsafe { self.lib.hostfxr_get_dotnet_environment_info( dotnet_root_ptr, ptr::null_mut(), get_dotnet_environment_info_callback, info.as_mut_ptr().cast(), ) } .unwrap_or(UNSUPPORTED_HOST_VERSION_ERROR_CODE); HostingResult::from(result).into_result()?; let info = unsafe { MaybeUninit::assume_init(info) }; Ok(info) } } extern "C" fn get_dotnet_environment_info_callback( info: *const hostfxr_dotnet_environment_info, result_context: *mut c_void, ) { let result = result_context.cast::<EnvironmentInfo>(); let raw_info = unsafe { &*info }; let hostfxr_version = unsafe { PdCStr::from_str_ptr(raw_info.hostfxr_version) }.to_string_lossy(); let hostfxr_commit_hash = unsafe { PdCStr::from_str_ptr(raw_info.hostfxr_commit_hash) }.to_string_lossy(); let raw_sdks = unsafe { slice::from_raw_parts(raw_info.sdks, raw_info.sdk_count) }; let sdks = raw_sdks .iter() .map(|raw_sdk| { let version = unsafe { PdCStr::from_str_ptr(raw_sdk.version) }.to_string_lossy(); let path = unsafe { PdCStr::from_str_ptr(raw_sdk.path) } .to_os_string() .into(); SdkInfo { version, path } }) .collect::<Vec<_>>(); let raw_frameworks = unsafe { slice::from_raw_parts(raw_info.frameworks, raw_info.framework_count) }; let frameworks = raw_frameworks .iter() .map(|raw_framework| { let name = unsafe { PdCStr::from_str_ptr(raw_framework.name) }.to_string_lossy(); let version = unsafe { PdCStr::from_str_ptr(raw_framework.version) }.to_string_lossy(); let path = unsafe { PdCStr::from_str_ptr(raw_framework.path) } .to_os_string() .into(); FrameworkInfo { name, version, path, } }) .collect::<Vec<_>>(); let info = EnvironmentInfo { hostfxr_version, hostfxr_commit_hash, sdks, frameworks, }; unsafe { result.write(info) }; }
rust
MIT
4742a5d235b279a35b235bf7726c5afb9bde521d
2026-01-04T20:18:20.341772Z
false
OpenByteDev/netcorehost
https://github.com/OpenByteDev/netcorehost/blob/4742a5d235b279a35b235bf7726c5afb9bde521d/src/hostfxr/library1_0.rs
src/hostfxr/library1_0.rs
use crate::{ hostfxr::{AppOrHostingResult, Hostfxr}, pdcstring::PdCStr, }; use super::UNSUPPORTED_HOST_VERSION_ERROR_CODE; impl Hostfxr { /// Run an application. /// /// # Note /// This function does not return until the application completes execution. /// It will shutdown CoreCLR after the application executes. /// If the application is successfully executed, this value will return the exit code of the application. /// Otherwise, it will return an error code indicating the failure. #[cfg_attr( feature = "netcore3_0", deprecated(note = "Use `HostfxrContext::run_app` instead"), allow(deprecated) )] #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "netcore1_0")))] #[must_use] pub fn run_app(&self, app_path: &PdCStr) -> AppOrHostingResult { self.run_app_with_args::<&PdCStr>(app_path, &[]) } /// Run an application with the specified arguments. /// /// # Note /// This function does not return until the application completes execution. /// It will shutdown CoreCLR after the application executes. /// If the application is successfully executed, this value will return the exit code of the application. /// Otherwise, it will return an error code indicating the failure. #[cfg_attr( feature = "netcore3_0", deprecated(note = "Use `HostfxrContext::run_app` instead") )] #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "netcore1_0")))] pub fn run_app_with_args<A: AsRef<PdCStr>>( &self, app_path: &PdCStr, args: &[A], ) -> AppOrHostingResult { let args = [&self.dotnet_exe, app_path] .into_iter() .chain(args.iter().map(|s| s.as_ref())) .map(|s| s.as_ptr()) .collect::<Vec<_>>(); let result = unsafe { self.lib .hostfxr_main(args.len().try_into().unwrap(), args.as_ptr()) } .unwrap_or(UNSUPPORTED_HOST_VERSION_ERROR_CODE); AppOrHostingResult::from(result) } }
rust
MIT
4742a5d235b279a35b235bf7726c5afb9bde521d
2026-01-04T20:18:20.341772Z
false
OpenByteDev/netcorehost
https://github.com/OpenByteDev/netcorehost/blob/4742a5d235b279a35b235bf7726c5afb9bde521d/src/hostfxr/library3_0.rs
src/hostfxr/library3_0.rs
use crate::{ bindings::hostfxr::{hostfxr_handle, hostfxr_initialize_parameters}, error::{HostingError, HostingResult, HostingSuccess}, hostfxr::{ Hostfxr, HostfxrContext, HostfxrHandle, InitializedForCommandLine, InitializedForRuntimeConfig, }, pdcstring::{PdCStr, PdChar}, }; use std::{iter, mem::MaybeUninit, ptr}; use super::UNSUPPORTED_HOST_VERSION_ERROR_CODE; impl Hostfxr { /// Initializes the hosting components for a dotnet command line running an application /// /// Like all the other `initialize` functions, this function will /// * Process the `.runtimeconfig.json` /// * Resolve framework references and find actual frameworks /// * Find the root framework (`Microsoft.NETCore.App`) and load the hostpolicy from it /// * The hostpolicy will then process all relevant `.deps.json` files and produce the list of assemblies, native search paths and other artifacts needed to initialize the runtime. /// /// The functions will **NOT** load the `CoreCLR` runtime. They just prepare everything to the point where it can be loaded. /// /// # Arguments /// * `app_path`: /// The path to the target application. /// /// # Remarks /// This function parses the specified command-line arguments to determine the application to run. It will /// then find the corresponding `.runtimeconfig.json` and `.deps.json` with which to resolve frameworks and /// dependencies and prepare everything needed to load the runtime. #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "netcore3_0")))] pub fn initialize_for_dotnet_command_line( &self, app_path: impl AsRef<PdCStr>, ) -> Result<HostfxrContext<InitializedForCommandLine>, HostingError> { self.initialize_for_dotnet_command_line_with_args(app_path, iter::empty::<&PdCStr>()) } /// Initializes the hosting components for a dotnet command line running an application /// /// Like all the other `initialize` functions, this function will /// * Process the `.runtimeconfig.json` /// * Resolve framework references and find actual frameworks /// * Find the root framework (`Microsoft.NETCore.App`) and load the hostpolicy from it /// * The hostpolicy will then process all relevant `.deps.json` files and produce the list of assemblies, native search paths and other artifacts needed to initialize the runtime. /// /// The functions will **NOT** load the `CoreCLR` runtime. They just prepare everything to the point where it can be loaded. /// /// # Arguments /// * `app_path`: /// The path to the target application. /// * `host_path`: /// Path to the native host (typically the `.exe`). /// This value is not used for anything by the hosting components. /// It's just passed to the `CoreCLR` as the path to the executable. /// It can point to a file which is not executable itself, if such file doesn't exist (for example in COM activation scenarios this points to the `comhost.dll`). /// This is used by PAL to initialize internal command line structures, process name and so on. /// /// # Remarks /// This function parses the specified command-line arguments to determine the application to run. It will /// then find the corresponding `.runtimeconfig.json` and `.deps.json` with which to resolve frameworks and /// dependencies and prepare everything needed to load the runtime. #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "netcore3_0")))] pub fn initialize_for_dotnet_command_line_with_host_path( &self, app_path: impl AsRef<PdCStr>, host_path: impl AsRef<PdCStr>, ) -> Result<HostfxrContext<InitializedForCommandLine>, HostingError> { self.initialize_for_dotnet_command_line_with_args_and_host_path( app_path, iter::empty::<&PdCStr>(), host_path, ) } /// Initializes the hosting components for a dotnet command line running an application /// /// Like all the other `initialize` functions, this function will /// * Process the `.runtimeconfig.json` /// * Resolve framework references and find actual frameworks /// * Find the root framework (`Microsoft.NETCore.App`) and load the hostpolicy from it /// * The hostpolicy will then process all relevant `.deps.json` files and produce the list of assemblies, native search paths and other artifacts needed to initialize the runtime. /// /// The functions will **NOT** load the `CoreCLR` runtime. They just prepare everything to the point where it can be loaded. /// /// # Arguments /// * `app_path`: /// The path to the target application. /// * `dotnet_root`: /// Path to the root of the .NET Core installation in use. /// This typically points to the install location from which the hostfxr has been loaded. /// For example on Windows this would typically point to `C:\Program Files\dotnet`. /// The path is used to search for shared frameworks and potentially SDKs. /// /// # Remarks /// This function parses the specified command-line arguments to determine the application to run. It will /// then find the corresponding `.runtimeconfig.json` and `.deps.json` with which to resolve frameworks and /// dependencies and prepare everything needed to load the runtime. #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "netcore3_0")))] pub fn initialize_for_dotnet_command_line_with_dotnet_root( &self, app_path: impl AsRef<PdCStr>, dotnet_root: impl AsRef<PdCStr>, ) -> Result<HostfxrContext<InitializedForCommandLine>, HostingError> { self.initialize_for_dotnet_command_line_with_args_and_dotnet_root( app_path, iter::empty::<&PdCStr>(), dotnet_root, ) } /// Initializes the hosting components for a dotnet command line running an application /// /// Like all the other `initialize` functions, this function will /// * Process the `.runtimeconfig.json` /// * Resolve framework references and find actual frameworks /// * Find the root framework (`Microsoft.NETCore.App`) and load the hostpolicy from it /// * The hostpolicy will then process all relevant `.deps.json` files and produce the list of assemblies, native search paths and other artifacts needed to initialize the runtime. /// /// The functions will **NOT** load the `CoreCLR` runtime. They just prepare everything to the point where it can be loaded. /// /// # Arguments /// * `app_path`: /// The path to the target application. /// * `args`: /// The command line arguments for the managed application. /// /// # Remarks /// This function parses the specified command-line arguments to determine the application to run. It will /// then find the corresponding `.runtimeconfig.json` and `.deps.json` with which to resolve frameworks and /// dependencies and prepare everything needed to load the runtime. #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "netcore3_0")))] pub fn initialize_for_dotnet_command_line_with_args( &self, app_path: impl AsRef<PdCStr>, args: impl Iterator<Item = impl AsRef<PdCStr>>, ) -> Result<HostfxrContext<InitializedForCommandLine>, HostingError> { unsafe { self.initialize_for_dotnet_command_line_with_parameters(app_path, args, ptr::null()) } } /// Initializes the hosting components for a dotnet command line running an application /// /// Like all the other `initialize` functions, this function will /// * Process the `.runtimeconfig.json` /// * Resolve framework references and find actual frameworks /// * Find the root framework (`Microsoft.NETCore.App`) and load the hostpolicy from it /// * The hostpolicy will then process all relevant `.deps.json` files and produce the list of assemblies, native search paths and other artifacts needed to initialize the runtime. /// /// The functions will **NOT** load the `CoreCLR` runtime. They just prepare everything to the point where it can be loaded. /// /// # Arguments /// * `app_path`: /// The path to the target application. /// * `args`: /// The command line arguments for the managed application. /// * `host_path`: /// Path to the native host (typically the `.exe`). /// This value is not used for anything by the hosting components. /// It's just passed to the `CoreCLR` as the path to the executable. /// It can point to a file which is not executable itself, if such file doesn't exist (for example in COM activation scenarios this points to the `comhost.dll`). /// This is used by PAL to initialize internal command line structures, process name and so on. /// /// # Remarks /// This function parses the specified command-line arguments to determine the application to run. It will /// then find the corresponding `.runtimeconfig.json` and `.deps.json` with which to resolve frameworks and /// dependencies and prepare everything needed to load the runtime. #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "netcore3_0")))] pub fn initialize_for_dotnet_command_line_with_args_and_host_path( &self, app_path: impl AsRef<PdCStr>, args: impl Iterator<Item = impl AsRef<PdCStr>>, host_path: impl AsRef<PdCStr>, ) -> Result<HostfxrContext<InitializedForCommandLine>, HostingError> { let parameters = hostfxr_initialize_parameters::with_host_path(host_path.as_ref().as_ptr()); unsafe { self.initialize_for_dotnet_command_line_with_parameters( app_path, args, &raw const parameters, ) } } /// Initializes the hosting components for a dotnet command line running an application /// /// Like all the other `initialize` functions, this function will /// * Process the `.runtimeconfig.json` /// * Resolve framework references and find actual frameworks /// * Find the root framework (`Microsoft.NETCore.App`) and load the hostpolicy from it /// * The hostpolicy will then process all relevant `.deps.json` files and produce the list of assemblies, native search paths and other artifacts needed to initialize the runtime. /// /// The functions will **NOT** load the `CoreCLR` runtime. They just prepare everything to the point where it can be loaded. /// /// # Arguments /// * `app_path`: /// The path to the target application. /// * `args`: /// The command line arguments for the managed application. /// * `dotnet_root`: /// Path to the root of the .NET Core installation in use. /// This typically points to the install location from which the hostfxr has been loaded. /// For example on Windows this would typically point to `C:\Program Files\dotnet`. /// The path is used to search for shared frameworks and potentially SDKs. /// /// # Remarks /// This function parses the specified command-line arguments to determine the application to run. It will /// then find the corresponding `.runtimeconfig.json` and `.deps.json` with which to resolve frameworks and /// dependencies and prepare everything needed to load the runtime. #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "netcore3_0")))] pub fn initialize_for_dotnet_command_line_with_args_and_dotnet_root( &self, app_path: impl AsRef<PdCStr>, args: impl Iterator<Item = impl AsRef<PdCStr>>, dotnet_root: impl AsRef<PdCStr>, ) -> Result<HostfxrContext<InitializedForCommandLine>, HostingError> { let parameters = hostfxr_initialize_parameters::with_dotnet_root(dotnet_root.as_ref().as_ptr()); unsafe { self.initialize_for_dotnet_command_line_with_parameters( app_path, args, &raw const parameters, ) } } unsafe fn initialize_for_dotnet_command_line_with_parameters( &self, app_path: impl AsRef<PdCStr>, args: impl Iterator<Item = impl AsRef<PdCStr>>, parameters: *const hostfxr_initialize_parameters, ) -> Result<HostfxrContext<InitializedForCommandLine>, HostingError> { let mut hostfxr_handle = MaybeUninit::<hostfxr_handle>::uninit(); let app_path = app_path.as_ref().as_ptr(); let args = args.map(|arg| arg.as_ref().as_ptr()); let app_path_and_args = iter::once(app_path).chain(args).collect::<Vec<_>>(); let result = unsafe { self.lib.hostfxr_initialize_for_dotnet_command_line( app_path_and_args.len().try_into().unwrap(), app_path_and_args.as_ptr(), parameters, hostfxr_handle.as_mut_ptr(), ) } .unwrap_or(UNSUPPORTED_HOST_VERSION_ERROR_CODE); let success_code = HostingResult::from(result).into_result()?; let is_primary = matches!(success_code, HostingSuccess::Success); Ok(unsafe { HostfxrContext::from_handle( HostfxrHandle::new_unchecked(hostfxr_handle.assume_init()), self.clone(), is_primary, ) }) } /// This function loads the specified `.runtimeconfig.json`, resolve all frameworks, resolve all the assets from those frameworks and /// then prepare runtime initialization where the TPA contains only frameworks. /// Note that this case does **NOT** consume any `.deps.json` from the app/component (only processes the framework's `.deps.json`). /// /// Like all the other `initialize` functions, this function will /// * Process the `.runtimeconfig.json` /// * Resolve framework references and find actual frameworks /// * Find the root framework (`Microsoft.NETCore.App`) and load the hostpolicy from it /// * The hostpolicy will then process all relevant `.deps.json` files and produce the list of assemblies, native search paths and other artifacts needed to initialize the runtime. /// /// The functions will **NOT** load the `CoreCLR` runtime. They just prepare everything to the point where it can be loaded. /// /// # Arguments /// * `runtime_config_path`: /// Path to the `.runtimeconfig.json` file to process. /// Unlike with [`initialize_for_dotnet_command_line`], any `.deps.json` from the app/component will not be processed by the hosting layers. /// /// [`initialize_for_dotnet_command_line`]: Hostfxr::initialize_for_dotnet_command_line #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "netcore3_0")))] pub fn initialize_for_runtime_config( &self, runtime_config_path: impl AsRef<PdCStr>, ) -> Result<HostfxrContext<InitializedForRuntimeConfig>, HostingError> { unsafe { self.initialize_for_runtime_config_with_parameters(runtime_config_path, ptr::null()) } } /// This function loads the specified `.runtimeconfig.json`, resolve all frameworks, resolve all the assets from those frameworks and /// then prepare runtime initialization where the TPA contains only frameworks. /// Note that this case does **NOT** consume any `.deps.json` from the app/component (only processes the framework's `.deps.json`). /// /// Like all the other `initialize` functions, this function will /// * Process the `.runtimeconfig.json` /// * Resolve framework references and find actual frameworks /// * Find the root framework (`Microsoft.NETCore.App`) and load the hostpolicy from it /// * The hostpolicy will then process all relevant `.deps.json` files and produce the list of assemblies, native search paths and other artifacts needed to initialize the runtime. /// /// The functions will **NOT** load the `CoreCLR` runtime. They just prepare everything to the point where it can be loaded. /// /// # Arguments /// * `runtime_config_path`: /// Path to the `.runtimeconfig.json` file to process. /// Unlike with [`initialize_for_dotnet_command_line`], any `.deps.json` from the app/component will not be processed by the hosting layers. /// * `host_path`: /// Path to the native host (typically the `.exe`). /// This value is not used for anything by the hosting components. /// It's just passed to the `CoreCLR` as the path to the executable. /// It can point to a file which is not executable itself, if such file doesn't exist (for example in COM activation scenarios this points to the `comhost.dll`). /// This is used by PAL to initialize internal command line structures, process name and so on. /// /// [`initialize_for_dotnet_command_line`]: Hostfxr::initialize_for_dotnet_command_line #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "netcore3_0")))] pub fn initialize_for_runtime_config_with_host_path( &self, runtime_config_path: impl AsRef<PdCStr>, host_path: impl AsRef<PdCStr>, ) -> Result<HostfxrContext<InitializedForRuntimeConfig>, HostingError> { let parameters = hostfxr_initialize_parameters::with_host_path(host_path.as_ref().as_ptr()); unsafe { self.initialize_for_runtime_config_with_parameters( runtime_config_path, &raw const parameters, ) } } /// This function loads the specified `.runtimeconfig.json`, resolve all frameworks, resolve all the assets from those frameworks and /// then prepare runtime initialization where the TPA contains only frameworks. /// Note that this case does **NOT** consume any `.deps.json` from the app/component (only processes the framework's `.deps.json`). /// /// Like all the other `initialize` functions, this function will /// * Process the `.runtimeconfig.json` /// * Resolve framework references and find actual frameworks /// * Find the root framework (`Microsoft.NETCore.App`) and load the hostpolicy from it /// * The hostpolicy will then process all relevant `.deps.json` files and produce the list of assemblies, native search paths and other artifacts needed to initialize the runtime. /// /// The functions will **NOT** load the `CoreCLR` runtime. They just prepare everything to the point where it can be loaded. /// /// # Arguments /// * `runtime_config_path`: /// Path to the `.runtimeconfig.json` file to process. /// Unlike with [`initialize_for_dotnet_command_line`], any `.deps.json` from the app/component will not be processed by the hosting layers. /// * `dotnet_root`: /// Path to the root of the .NET Core installation in use. /// This typically points to the install location from which the hostfxr has been loaded. /// For example on Windows this would typically point to `C:\Program Files\dotnet`. /// The path is used to search for shared frameworks and potentially SDKs. /// /// [`initialize_for_dotnet_command_line`]: Hostfxr::initialize_for_dotnet_command_line #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "netcore3_0")))] pub fn initialize_for_runtime_config_with_dotnet_root( &self, runtime_config_path: impl AsRef<PdCStr>, dotnet_root: impl AsRef<PdCStr>, ) -> Result<HostfxrContext<InitializedForRuntimeConfig>, HostingError> { let parameters = hostfxr_initialize_parameters::with_dotnet_root(dotnet_root.as_ref().as_ptr()); unsafe { self.initialize_for_runtime_config_with_parameters( runtime_config_path, &raw const parameters, ) } } unsafe fn initialize_for_runtime_config_with_parameters( &self, runtime_config_path: impl AsRef<PdCStr>, parameters: *const hostfxr_initialize_parameters, ) -> Result<HostfxrContext<InitializedForRuntimeConfig>, HostingError> { let mut hostfxr_handle = MaybeUninit::uninit(); let result = unsafe { self.lib.hostfxr_initialize_for_runtime_config( runtime_config_path.as_ref().as_ptr(), parameters, hostfxr_handle.as_mut_ptr(), ) } .unwrap_or(UNSUPPORTED_HOST_VERSION_ERROR_CODE); let success_code = HostingResult::from(result).into_result()?; let is_primary = matches!(success_code, HostingSuccess::Success); Ok(unsafe { HostfxrContext::from_handle( HostfxrHandle::new_unchecked(hostfxr_handle.assume_init()), self.clone(), is_primary, ) }) } /// Sets a callback which is to be used to write errors to. /// /// # Arguments /// * `error_writer` /// A callback function which will be invoked every time an error is to be reported. /// Or [`None`] to unregister previously registered callbacks and return to the default behavior. /// /// # Remarks /// The error writer is registered per-thread, so the registration is thread-local. On each thread /// only one callback can be registered. Subsequent registrations overwrite the previous ones. /// /// By default no callback is registered in which case the errors are written to stderr. /// /// Each call to the error writer is sort of like writing a single line (the EOL character is omitted). /// Multiple calls to the error writer may occure for one failure. /// /// If the hostfxr invokes functions in hostpolicy as part of its operation, the error writer /// will be propagated to hostpolicy for the duration of the call. This means that errors from /// both hostfxr and hostpolicy will be reporter through the same error writer. #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "netcore3_0")))] pub fn set_error_writer(&self, error_writer: Option<ErrorWriter>) { let new_raw_error_writer = error_writer .as_ref() .map(|_| error_writer_trampoline as hostfxr_sys::hostfxr_error_writer_fn); unsafe { self.lib.hostfxr_set_error_writer(new_raw_error_writer) }; CURRENT_ERROR_WRITER.with(|current_writer| { *current_writer.borrow_mut() = error_writer; }); } } type ErrorWriter = Box<dyn FnMut(&PdCStr)>; thread_local! { static CURRENT_ERROR_WRITER: std::cell::RefCell<Option<ErrorWriter>> = std::cell::RefCell::new(None); } extern "C" fn error_writer_trampoline(raw_error: *const PdChar) { CURRENT_ERROR_WRITER.with(|writer_holder| { if let Some(writer) = writer_holder.borrow_mut().as_mut() { let error_message = unsafe { PdCStr::from_str_ptr(raw_error) }; writer(error_message); } }); }
rust
MIT
4742a5d235b279a35b235bf7726c5afb9bde521d
2026-01-04T20:18:20.341772Z
false
OpenByteDev/netcorehost
https://github.com/OpenByteDev/netcorehost/blob/4742a5d235b279a35b235bf7726c5afb9bde521d/src/hostfxr/context.rs
src/hostfxr/context.rs
use crate::{ bindings::hostfxr::{ hostfxr_delegate_type, hostfxr_handle, load_assembly_and_get_function_pointer_fn, }, error::{HostingError, HostingResult, HostingSuccess}, hostfxr::{ AppOrHostingResult, AssemblyDelegateLoader, DelegateLoader, Hostfxr, HostfxrLibrary, RawFnPtr, SharedHostfxrLibrary, }, pdcstring::PdCString, }; #[cfg(feature = "net5_0")] use crate::bindings::hostfxr::get_function_pointer_fn; #[cfg(feature = "net8_0")] use crate::{ bindings::hostfxr::{load_assembly_bytes_fn, load_assembly_fn}, pdcstring::PdCStr, }; use std::{ cell::Cell, ffi::c_void, fmt::{self, Debug}, marker::PhantomData, mem::{self, ManuallyDrop, MaybeUninit}, ptr::NonNull, }; #[cfg(feature = "net8_0")] use std::ptr; use destruct_drop::DestructDrop; use enum_map::EnumMap; use once_cell::unsync::OnceCell; /// A marker struct indicating that the context was initialized with a runtime config. /// This means that it is not possible to run the application associated with the context. #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "netcore3_0")))] #[derive(Debug, Clone, Copy)] pub struct InitializedForRuntimeConfig; /// A marker struct indicating that the context was initialized for the dotnet command line. /// This means that it is possible to run the application associated with the context. #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "netcore3_0")))] #[derive(Debug, Clone, Copy)] pub struct InitializedForCommandLine; /// Handle of a loaded [`HostfxrContext`]. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] #[repr(transparent)] #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "netcore3_0")))] pub struct HostfxrHandle(NonNull<c_void>); impl HostfxrHandle { /// Creates a new hostfxr handle from the given raw handle. /// /// # Safety /// - The given raw handle has to be non-null. /// - The given handle has to be valid and has to represent a hostfxr context. #[must_use] pub const unsafe fn new_unchecked(ptr: hostfxr_handle) -> Self { Self(unsafe { NonNull::new_unchecked(ptr.cast_mut()) }) } /// Returns the raw underlying handle. #[must_use] pub const fn as_raw(&self) -> hostfxr_handle { self.0.as_ptr() } } impl From<HostfxrHandle> for hostfxr_handle { fn from(handle: HostfxrHandle) -> Self { handle.as_raw() } } /// State which hostfxr creates and maintains and represents a logical operation on the hosting components. #[derive(DestructDrop)] #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "netcore3_0")))] pub struct HostfxrContext<I> { handle: HostfxrHandle, hostfxr: SharedHostfxrLibrary, is_primary: bool, runtime_delegates: EnumMap<hostfxr_delegate_type, OnceCell<RawFnPtr>>, context_type: PhantomData<I>, not_sync: PhantomData<Cell<HostfxrLibrary>>, } unsafe impl<I> Send for HostfxrContext<I> {} impl<I> Debug for HostfxrContext<I> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("HostfxrContext") .field("handle", &self.handle) .field("is_primary", &self.is_primary) .field("runtime_delegates", &self.runtime_delegates) .field("context_type", &self.context_type) .finish_non_exhaustive() } } impl<I> HostfxrContext<I> { /// Creates a new context from the given handle. /// /// # Safety /// The context handle has to be match the context type `I`. /// If the context was initialized using [`initialize_for_dotnet_command_line`] `I` has to be [`InitializedForCommandLine`]. /// If the context was initialized using [`initialize_for_runtime_config`] `I` has to be [`InitializedForRuntimeConfig`]. /// /// [`initialize_for_dotnet_command_line`]: crate::hostfxr::Hostfxr::initialize_for_dotnet_command_line /// [`initialize_for_runtime_config`]: crate::hostfxr::Hostfxr::initialize_for_runtime_config #[must_use] pub unsafe fn from_handle(handle: HostfxrHandle, hostfxr: Hostfxr, is_primary: bool) -> Self { Self { handle, hostfxr: hostfxr.lib, is_primary, runtime_delegates: EnumMap::default(), context_type: PhantomData, not_sync: PhantomData, } } /// Gets the underlying handle to the hostfxr context. #[must_use] pub const fn handle(&self) -> HostfxrHandle { self.handle } /// Gets the underlying handle to the hostfxr context and consume this context. #[must_use] pub fn into_handle(self) -> HostfxrHandle { let this = ManuallyDrop::new(self); this.handle } /// Gets whether the context is the primary hostfxr context. /// There can only be a single primary context in a process. /// /// # Note /// <https://github.com/dotnet/core-setup/blob/master/Documentation/design-docs/native-hosting.md#synchronization> #[must_use] pub const fn is_primary(&self) -> bool { self.is_primary } #[must_use] pub(crate) const fn library(&self) -> &SharedHostfxrLibrary { &self.hostfxr } /// Gets a typed delegate from the currently loaded `CoreCLR` or from a newly created one. /// You propably want to use [`get_delegate_loader`] or [`get_delegate_loader_for_assembly`] /// instead of this function if you want to load function pointers. /// /// # Remarks /// If the context was initialized using [`initialize_for_runtime_config`], then all delegate types are supported. /// If it was initialized using [`initialize_for_dotnet_command_line`], then only the following /// delegate types are currently supported: /// * [`hdt_load_assembly_and_get_function_pointer`] /// * [`hdt_get_function_pointer`] /// /// [`get_delegate_loader`]: HostfxrContext::get_delegate_loader /// [`get_delegate_loader_for_assembly`]: HostfxrContext::get_delegate_loader_for_assembly /// [`hdt_load_assembly_and_get_function_pointer`]: hostfxr_delegate_type::hdt_load_assembly_and_get_function_pointer /// [`hdt_get_function_pointer`]: hostfxr_delegate_type::hdt_get_function_pointer /// [`initialize_for_runtime_config`]: Hostfxr::initialize_for_runtime_config /// [`initialize_for_dotnet_command_line`]: Hostfxr::initialize_for_dotnet_command_line pub fn get_runtime_delegate( &self, r#type: hostfxr_delegate_type, ) -> Result<RawFnPtr, HostingError> { self.runtime_delegates[r#type] .get_or_try_init(|| self.get_runtime_delegate_uncached(r#type)) .copied() } fn get_runtime_delegate_uncached( &self, r#type: hostfxr_delegate_type, ) -> Result<RawFnPtr, HostingError> { let mut delegate = MaybeUninit::uninit(); let result = unsafe { self.hostfxr.hostfxr_get_runtime_delegate( self.handle.as_raw(), r#type, delegate.as_mut_ptr(), ) } .unwrap(); HostingResult::from(result).into_result()?; Ok(unsafe { delegate.assume_init() }.cast()) } fn get_load_assembly_and_get_function_pointer_delegate( &self, ) -> Result<load_assembly_and_get_function_pointer_fn, HostingError> { unsafe { self.get_runtime_delegate( hostfxr_delegate_type::hdt_load_assembly_and_get_function_pointer, ) .map(|ptr| mem::transmute(ptr)) } } #[cfg(feature = "net5_0")] fn get_get_function_pointer_delegate(&self) -> Result<get_function_pointer_fn, HostingError> { unsafe { self.get_runtime_delegate(hostfxr_delegate_type::hdt_get_function_pointer) .map(|ptr| mem::transmute(ptr)) } } #[cfg(feature = "net8_0")] fn get_load_assembly_delegate(&self) -> Result<load_assembly_fn, HostingError> { unsafe { self.get_runtime_delegate(hostfxr_delegate_type::hdt_load_assembly) .map(|ptr| mem::transmute(ptr)) } } #[cfg(feature = "net8_0")] fn get_load_assembly_bytes_delegate(&self) -> Result<load_assembly_bytes_fn, HostingError> { unsafe { self.get_runtime_delegate(hostfxr_delegate_type::hdt_load_assembly_bytes) .map(|ptr| mem::transmute(ptr)) } } /// Gets a delegate loader for loading an assembly and contained function pointers. pub fn get_delegate_loader(&self) -> Result<DelegateLoader, HostingError> { Ok(DelegateLoader { get_load_assembly_and_get_function_pointer: self .get_load_assembly_and_get_function_pointer_delegate()?, #[cfg(feature = "net5_0")] get_function_pointer: self.get_get_function_pointer_delegate()?, hostfxr: self.hostfxr.clone(), }) } /// Gets a delegate loader for loading function pointers of the assembly with the given path. /// The assembly will be loaded lazily when the first function pointer is loaded. pub fn get_delegate_loader_for_assembly( &self, assembly_path: impl Into<PdCString>, ) -> Result<AssemblyDelegateLoader, HostingError> { self.get_delegate_loader() .map(|loader| AssemblyDelegateLoader::new(loader, assembly_path)) } /// Loads the specified assembly in the default load context from the given path. /// It uses [`AssemblyDependencyResolver`] to register additional dependency resolution for the load context. /// Function pointers to methods in the assembly can then be loaded using a [`DelegateLoader`]. /// /// [`AssemblyDependencyResolver`]: https://learn.microsoft.com/en-us/dotnet/api/system.runtime.loader.assemblydependencyresolver /// [`AssemblyLoadContext.LoadFromAssembly`]: https://learn.microsoft.com/en-us/dotnet/api/system.runtime.loader.assemblyloadcontext.loadfromassemblypath #[cfg(feature = "net8_0")] pub fn load_assembly_from_path( &self, assembly_path: impl AsRef<PdCStr>, ) -> Result<(), HostingError> { let assembly_path = assembly_path.as_ref(); let load_assembly = self.get_load_assembly_delegate()?; let result = unsafe { load_assembly(assembly_path.as_ptr(), ptr::null(), ptr::null()) }; HostingResult::from(result).into_result()?; Ok(()) } /// Loads the specified assembly in the default load context from the given buffers. /// It does not provide a mechanism for registering additional dependency resolution, as mechanisms like `.deps.json` and [`AssemblyDependencyResolver`] are file-based. /// Dependencies can be pre-loaded (for example, via a previous call to this function) or the specified assembly can explicitly register its own resolution logic (for example, via the [`AssemblyLoadContext.Resolving`] event). /// It uses [`AssemblyDependencyResolver`] to register additional dependency resolution for the load context. /// Function pointers to methods in the assembly can then be loaded using a [`DelegateLoader`]. /// /// [`AssemblyDependencyResolver`]: https://learn.microsoft.com/en-us/dotnet/api/system.runtime.loader.assemblydependencyresolver /// [`AssemblyLoadContext.Resolving`]: https://learn.microsoft.com/en-us/dotnet/api/system.runtime.loader.assemblyloadcontext.resolving?view=net-7.0 #[cfg(feature = "net8_0")] pub fn load_assembly_from_bytes( &self, assembly_bytes: impl AsRef<[u8]>, symbols_bytes: impl AsRef<[u8]>, ) -> Result<(), HostingError> { let symbols_bytes = symbols_bytes.as_ref(); let assembly_bytes = assembly_bytes.as_ref(); let load_assembly_bytes = self.get_load_assembly_bytes_delegate()?; let result = unsafe { load_assembly_bytes( assembly_bytes.as_ptr(), assembly_bytes.len(), symbols_bytes.as_ptr(), symbols_bytes.len(), ptr::null_mut(), ptr::null_mut(), ) }; HostingResult::from(result).into_result()?; Ok(()) } /// Closes an initialized host context. /// This method is automatically called on drop, but can be explicitely called to handle errors during closing. pub fn close(self) -> Result<HostingSuccess, HostingError> { let result = unsafe { self.close_raw() }; self.destruct_drop(); result } /// Internal non-consuming version of [`close`](HostfxrContext::close) unsafe fn close_raw(&self) -> Result<HostingSuccess, HostingError> { let result = unsafe { self.hostfxr.hostfxr_close(self.handle.as_raw()) }.unwrap(); HostingResult::from(result).into_result() } } impl HostfxrContext<InitializedForCommandLine> { /// Load the dotnet runtime and run the application. /// /// # Return value /// If the app was successfully run, the exit code of the application. Otherwise, the error code result. #[must_use] pub fn run_app(self) -> AppOrHostingResult { let result = unsafe { self.hostfxr.hostfxr_run_app(self.handle.as_raw()) }.unwrap(); AppOrHostingResult::from(result) } } impl<I> Drop for HostfxrContext<I> { fn drop(&mut self) { let _ = unsafe { self.close_raw() }; } }
rust
MIT
4742a5d235b279a35b235bf7726c5afb9bde521d
2026-01-04T20:18:20.341772Z
false
OpenByteDev/netcorehost
https://github.com/OpenByteDev/netcorehost/blob/4742a5d235b279a35b235bf7726c5afb9bde521d/src/error/univ.rs
src/error/univ.rs
use thiserror::Error; /// A universal error type encompassing all possible errors from the [`netcorehost`](crate) crate. #[derive(Debug, Error)] pub enum Error { /// An error from the native hosting components. #[error(transparent)] Hosting(#[from] crate::error::HostingError), /// An error while loading a function pointer to a managed method. #[error(transparent)] #[cfg(feature = "netcore3_0")] #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "netcore3_0")))] GetFunctionPointer(#[from] crate::hostfxr::GetManagedFunctionError), /// An error while loading the hostfxr library. #[error(transparent)] #[cfg(feature = "nethost")] #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "nethost")))] LoadHostfxr(#[from] crate::nethost::LoadHostfxrError), } #[cfg(feature = "nethost")] impl From<crate::dlopen2::Error> for Error { fn from(err: crate::dlopen2::Error) -> Self { Self::LoadHostfxr(crate::nethost::LoadHostfxrError::DlOpen(err)) } }
rust
MIT
4742a5d235b279a35b235bf7726c5afb9bde521d
2026-01-04T20:18:20.341772Z
false
OpenByteDev/netcorehost
https://github.com/OpenByteDev/netcorehost/blob/4742a5d235b279a35b235bf7726c5afb9bde521d/src/error/mod.rs
src/error/mod.rs
mod hosting_result; pub use hosting_result::*; mod univ; pub use univ::*;
rust
MIT
4742a5d235b279a35b235bf7726c5afb9bde521d
2026-01-04T20:18:20.341772Z
false
OpenByteDev/netcorehost
https://github.com/OpenByteDev/netcorehost/blob/4742a5d235b279a35b235bf7726c5afb9bde521d/src/error/hosting_result.rs
src/error/hosting_result.rs
use std::convert::TryFrom; #[cfg(feature = "nightly")] use std::ops::{ControlFlow, FromResidual, Try}; use crate::bindings; use derive_more::{Deref, Display, From}; /// Result of a hosting API operation of `hostfxr`, `hostpolicy` and `nethost`. /// /// Source: [https://github.com/dotnet/runtime/blob/main/docs/design/features/host-error-codes.md](https://github.com/dotnet/runtime/blob/main/docs/design/features/host-error-codes.md) #[must_use] #[derive(Debug, PartialEq, Eq, Clone, Copy, PartialOrd, Ord, Hash, Deref, From)] #[repr(transparent)] pub struct HostingResult(pub Result<HostingSuccess, HostingError>); impl HostingResult { /// Creates a new [`HostingResult`] from the raw status code. #[allow(clippy::cast_possible_wrap)] pub const fn from_status_code(code: u32) -> Self { if code as i32 >= 0 { Self::from_success(HostingSuccess::from_status_code(code)) } else { Self::from_error(HostingError::from_status_code(code)) } } /// Creates a new successful [`HostingResult`] from the give [`HostingSuccess`]. pub const fn from_success(success: HostingSuccess) -> Self { Self(Ok(success)) } /// Creates a new erroneous [`HostingResult`] from the give [`HostingError`]. pub const fn from_error(error: HostingError) -> Self { Self(Err(error)) } /// Tries to create a new [`HostingResult`] from the raw status code if it is known. /// Otherwise returns the given value as an [`Err`]. pub const fn known_from_status_code(code: u32) -> Result<Self, u32> { if let Ok(success) = HostingSuccess::known_from_status_code(code) { Ok(Self::from_success(success)) } else if let Ok(error) = HostingError::known_from_status_code(code) { Ok(Self::from_error(error)) } else { Err(code) } } /// Returns the underlying status code value. #[must_use] pub fn value(&self) -> u32 { match self.0 { Ok(success) => success.value(), Err(error) => error.value(), } } /// Returns whether the status code of this result has a known meaning. #[must_use] pub fn is_known(&self) -> bool { match self.0 { Ok(success) => success.is_known(), Err(error) => error.is_known(), } } /// Returns whether the status code of this result has a unknown meaning. #[must_use] pub fn is_unknown(&self) -> bool { match self.0 { Ok(success) => success.is_unknown(), Err(error) => error.is_unknown(), } } /// Transforms the result into a [`Result<HostingSuccess, HostingError>`]. pub fn into_result(&self) -> Result<HostingSuccess, HostingError> { self.0 } } impl From<u32> for HostingResult { fn from(code: u32) -> Self { Self::from_status_code(code) } } impl From<i32> for HostingResult { fn from(code: i32) -> Self { Self::from(code as u32) } } impl From<HostingResult> for u32 { fn from(code: HostingResult) -> Self { code.value() } } impl From<HostingResult> for i32 { #[allow(clippy::cast_possible_wrap)] fn from(code: HostingResult) -> Self { code.value() as i32 } } impl From<HostingSuccess> for HostingResult { fn from(success: HostingSuccess) -> Self { Self::from_success(success) } } impl From<HostingError> for HostingResult { fn from(error: HostingError) -> Self { Self::from_error(error) } } #[cfg(feature = "nightly")] impl Try for HostingResult { type Output = HostingSuccess; type Residual = HostingError; fn branch(self) -> ControlFlow<Self::Residual, Self::Output> { match self.into_result().branch() { ControlFlow::Continue(code) => ControlFlow::Continue(code), ControlFlow::Break(r) => ControlFlow::Break(r.unwrap_err()), } } fn from_output(code: HostingSuccess) -> Self { HostingResult(Ok(code)) } } #[cfg(feature = "nightly")] impl FromResidual for HostingResult { fn from_residual(r: HostingError) -> Self { HostingResult(Err(r)) } } /// Success codes returned by the hosting APIs from `hostfxr`, `hostpolicy` and `nethost`. /// /// Source: [https://github.com/dotnet/runtime/blob/main/docs/design/features/host-error-codes.md](https://github.com/dotnet/runtime/blob/main/docs/design/features/host-error-codes.md) #[derive(Debug, PartialEq, Eq, Clone, Copy, PartialOrd, Ord, Hash, Display)] pub enum HostingSuccess { /// Operation was successful. #[display("Operation was successful.")] Success, /// Initialization was successful, but another host context is already initialized, so the returned context is "secondary". /// The requested context was otherwise fully compatible with the already initialized context. /// This is returned by `hostfxr_initialize_for_runtime_config` if it's called when the host is already initialized in the process. /// Comes from `corehost_initialize` in `hostpolicy`. #[display( "Initialization was successful, but another host context is already initialized, so the returned context is 'secondary'" )] HostAlreadyInitialized, /// Initialization was successful, but another host context is already initialized and the requested context specified some runtime properties which are not the same (either in value or in presence) to the already initialized context. /// This is returned by `hostfxr_initialize_for_runtime_config` if it's called when the host is already initialized in the process. /// Comes from `corehost_initialize` in `hostpolicy`. #[display( "Initialization was successful, but another host context is already initialized and the requested context specified some runtime properties which are not the same (either in value or in presence) to the already initialized context." )] DifferentRuntimeProperties, /// Unknown success status code. #[display("Unknown success status code: {_0:#08X}")] Unknown(u32), } impl HostingSuccess { /// Creates a new [`HostingSuccess`] from the raw status code. #[must_use] pub const fn from_status_code(code: u32) -> Self { match Self::known_from_status_code(code) { Ok(s) => s, Err(code) => Self::Unknown(code), } } /// Tries to create a new [`HostingSuccess`] from the raw status code if it is known. /// Otherwise returns the given value as an [`Err`]. pub const fn known_from_status_code(code: u32) -> Result<Self, u32> { match code { c if c == bindings::StatusCode::Success as u32 => Ok(Self::Success), c if c == bindings::StatusCode::Success_DifferentRuntimeProperties as u32 => { Ok(Self::DifferentRuntimeProperties) } c if c == bindings::StatusCode::Success_HostAlreadyInitialized as u32 => { Ok(Self::HostAlreadyInitialized) } _ => Err(code), } } /// Returns the underlying status code value. #[must_use] pub const fn value(&self) -> u32 { match self { Self::Success => bindings::StatusCode::Success as u32, Self::DifferentRuntimeProperties => { bindings::StatusCode::Success_DifferentRuntimeProperties as u32 } Self::HostAlreadyInitialized => { bindings::StatusCode::Success_HostAlreadyInitialized as u32 } Self::Unknown(code) => *code, } } /// Returns whether the status code of this success has a known meaning. #[must_use] pub const fn is_known(&self) -> bool { !self.is_unknown() } /// Returns whether the status code of this success has a unknown meaning. #[must_use] pub const fn is_unknown(&self) -> bool { matches!(self, Self::Unknown(_)) } } impl TryFrom<u32> for HostingSuccess { type Error = u32; fn try_from(code: u32) -> Result<Self, Self::Error> { Self::known_from_status_code(code) } } impl From<HostingSuccess> for u32 { fn from(code: HostingSuccess) -> Self { code.value() } } /// Error codes returned by the hosting APIs from `hostfxr`, `hostpolicy` and `nethost`. /// /// Source: [https://github.com/dotnet/runtime/blob/main/docs/design/features/host-error-codes.md](https://github.com/dotnet/runtime/blob/main/docs/design/features/host-error-codes.md) #[derive(Debug, PartialEq, Eq, Clone, Copy, PartialOrd, Ord, Hash, Display)] #[must_use] pub enum HostingError { /// One of the specified arguments for the operation is invalid. #[display("One of the specified arguments for the operation is invalid.")] InvalidArgFailure, /// There was a failure loading a dependent library. /// If any of the hosting components calls `LoadLibrary`/`dlopen` on a dependent library and the call fails, this error code is returned. /// The most common case for this failure is if the dependent library is missing some of its dependencies (for example the necessary CRT is missing on the machine), likely corrupt or incomplete install. /// This error code is also returned from `corehost_resolve_component_dependencies` if it's called on a `hostpolicy` which has not been initialized via the hosting layer. /// This would typically happen if `coreclr` is loaded directly without the hosting layer and then `AssemblyDependencyResolver` is used (which is an unsupported scenario). #[display("There was a failure loading a dependent library.")] CoreHostLibLoadFailure, /// One of the dependent libraries is missing. /// Typically when the `hostfxr`, `hostpolicy` or `coreclr` dynamic libraries are not present in the expected locations. /// Probably means corrupted or incomplete installation. #[display("One of the dependent libraries is missing.")] CoreHostLibMissingFailure, /// One of the dependent libraries is missing a required entry point. #[display("One of the dependent libraries is missing a required entry point.")] CoreHostEntryPointFailure, /// If the hosting component is trying to use the path to the current module (the hosting component itself) and from it deduce the location of the installation. /// Either the location of the current module could not be determined (some weird OS call failure) or the location is not in the right place relative to other expected components. /// For example the `hostfxr` may look at its location and try to deduce the location of the `shared` folder with the framework from it. /// It assumes the typical install layout on disk. If this doesn't work, this error will be returned. #[display( "Either the location of the current module could not be determined (some weird OS call failure) or the location is not in the right place relative to other expected components." )] CoreHostCurHostFindFailure, /// If the `coreclr` library could not be found. /// The hosting layer (`hostpolicy`) looks for `coreclr` library either next to the app itself (for self-contained) or in the root framework (for framework-dependent). /// This search can be done purely by looking at disk or more commonly by looking into the respective `.deps.json`. /// If the `coreclr` library is missing in `.deps.json` or it's there but doesn't exist on disk, this error is returned. #[display("The coreclr library could not be found.")] CoreClrResolveFailure, /// The loaded `coreclr` library doesn't have one of the required entry points. #[display("The loaded coreclr library doesn't have one of the required entry points.")] CoreClrBindFailure, /// The call to `coreclr_initialize` failed. /// The actual error returned by `coreclr` is reported in the error message. #[display("The call to coreclr_initialize failed.")] CoreClrInitFailure, /// The call to `coreclr_execute_assembly` failed. /// Note that this does not mean anything about the app's exit code, this failure occurs if `coreclr` failed to run the app itself. #[display("The call to coreclr_execute_assembly failed.")] CoreClrExeFailure, /// Initialization of the `hostpolicy` dependency resolver failed. /// This can be: /// - One of the frameworks or the app is missing a required `.deps.json` file. /// - One of the `.deps.json` files is invalid (invalid JSON, or missing required properties and so on). #[display("Initialization of the hostpolicy dependency resolver failed.")] ResolverInitFailure, /// Resolution of dependencies in `hostpolicy` failed. /// This can mean many different things, but in general one of the processed `.deps.json` contains entry for a file which could not found, or its resolution failed for some other reason (conflict for example). #[display("Resolution of dependencies in `hostpolicy` failed.")] ResolverResolveFailure, /// Failure to determine the location of the current executable. /// The hosting layer uses the current executable path to deduce the install location in some cases. /// If this path can't be obtained (OS call fails, or the returned path doesn't exist), this error is returned. #[display("Failure to determine the location of the current executable.")] LibHostCurExeFindFailure, /// Initialization of the `hostpolicy` library failed. /// The `corehost_load` method takes a structure with lot of initialization parameters. /// If the version of this structure doesn't match the expected value, this error code is returned. /// This would in general mean incompatibility between the `hostfxr` and `hostpolicy`, which should really only happen if somehow a newer `hostpolicy` is used by older `hostfxr`. /// This typically means corrupted installation. #[display("Initialization of the `hostpolicy` library failed.")] LibHostInitFailure, // Error only present in `error_codes.h` not in `host-error-codes.md` #[doc(hidden)] #[display("LibHostExecModeFailure")] LibHostExecModeFailure, /// Failure to find the requested SDK. /// This happens in the `hostfxr` when an SDK (also called CLI) command is used with `dotnet`. /// In this case the hosting layer tries to find an installed .NET SDK to run the command on. /// The search is based on deduced install location and on the requested version from potential `global.json` file. /// If either no matching SDK version can be found, or that version exists, but it's missing the `dotnet.dll` file, this error code is returned. #[display("Failure to find the requested SDK.")] LibHostSdkFindFailure, /// Arguments to `hostpolicy` are invalid. /// This is used in three unrelated places in the `hostpolicy`, but in all cases it means the component calling `hostpolicy` did something wrong: /// - Command line arguments for the app - the failure would typically mean that wrong argument was passed or such. /// For example if the application main assembly is not specified on the command line. /// On its own this should not happen as `hostfxr` should have parsed and validated all command line arguments. /// - `hostpolicy` context's `get_delegate` - if the requested delegate enum value is not recognized. /// Again this would mean `hostfxr` passed the wrong value. /// - `corehost_resolve_component_dependencies` - if something went wrong initializing `hostpolicy` internal structures. /// Would happen for example when the `component_main_assembly_path` argument is wrong. #[display("Arguments to hostpolicy are invalid.")] LibHostInvalidArgs, /// The `.runtimeconfig.json` file is invalid. /// The reasons for this failure can be among these: /// - Failure to read from the file /// - Invalid JSON /// - Invalid value for a property (for example number for property which requires a string) /// - Missing required property /// - Other inconsistencies (for example `rollForward` and `applyPatches` are not allowed to be specified in the same config file) /// - Any of the above failures reading the `.runtimecofig.dev.json` file /// - Self-contained `.runtimeconfig.json` used in `hostfxr_initialize_for_runtime_config`. /// Note that missing `.runtimconfig.json` is not an error (means self-contained app). /// This error code is also used when there is a problem reading the CLSID map file in `comhost`. #[display("Arguments to hostpolicy are invalid.")] InvalidConfigFile, /// Used internally when the command line for `dotnet.exe` doesn't contain path to the application to run. /// In such case the command line is considered to be a CLI/SDK command. /// This error code should never be returned to external caller. #[doc(hidden)] #[display( "[Internal error] The command line for dotnet.exe doesn't contain the path to the application to run." )] AppArgNotRunnable, /// `apphost` failed to determine which application to run. /// This can mean: /// - The `apphost` binary has not been imprinted with the path to the app to run (so freshly built `apphost.exe` from the branch will fail to run like this) /// - The `apphost` is a bundle (single-file exe) and it failed to extract correctly. #[display("apphost failed to determine which application to run.")] AppHostExeNotBoundFailure, /// It was not possible to find a compatible framework version. /// This originates in `hostfxr` (`resolve_framework_reference`) and means that the app specified a reference to a framework in its `.runtimeconfig.json` which could not be resolved. /// The failure to resolve can mean that no such framework is available on the disk, or that the available frameworks don't match the minimum version specified or that the roll forward options specified excluded all available frameworks. /// Typically this would be used if a 3.0 app is trying to run on a machine which has no 3.0 installed. /// It would also be used for example if a 32bit 3.0 app is running on a machine which has 3.0 installed but only for 64bit. #[display("It was not possible to find a compatible framework version.")] FrameworkMissingFailure, /// Returned by `hostfxr_get_native_search_directories` if the `hostpolicy` could not calculate the `NATIVE_DLL_SEARCH_DIRECTORIES`. #[display("hostpolicy could not calculate the NATIVE_DLL_SEARCH_DIRECTORIES.")] HostApiFailed, /// Returned when the buffer specified to an API is not big enough to fit the requested value. /// Can be returned from: /// - `hostfxr_get_runtime_properties` /// - `hostfxr_get_native_search_directories` /// - `get_hostfxr_path` #[display( "Returned when the buffer specified to an API is not big enough to fit the requested value." )] HostApiBufferTooSmall, /// Returned by `hostpolicy` if the `corehost_main_with_output_buffer` is called with unsupported host command. /// This error code means there is incompatibility between the `hostfxr` and `hostpolicy`. /// In reality this should pretty much never happen. #[display("corehost_main_with_output_buffer was called with an unsupported host command.")] LibHostUnknownCommand, /// Returned by `apphost` if the imprinted application path doesn't exist. /// This would happen if the app is built with an executable (the `apphost`) and the main `app.dll` is missing. #[display("The imprinted application path doesn't exist.")] LibHostAppRootFindFailure, /// Returned from `hostfxr_resolve_sdk2` when it fails to find matching SDK. /// Similar to `LibHostSdkFindFailure` but only used in the `hostfxr_resolve_sdk2`. #[display("hostfxr_resolve_sdk2 failed to find a matching SDK.")] SdkResolverResolveFailure, /// During processing of `.runtimeconfig.json` there were two framework references to the same framework which were not compatible. /// This can happen if the app specified a framework reference to a lower-level framework which is also specified by a higher-level framework which is also used by the app. /// For example, this would happen if the app referenced `Microsoft.AspNet.App` version 2.0 and `Microsoft.NETCore.App` version 3.0. In such case the `Microsoft.AspNet.App` has `.runtimeconfig.json` which also references `Microsoft.NETCore.App` but it only allows versions 2.0 up to 2.9 (via roll forward options). /// So the version 3.0 requested by the app is incompatible. #[display( "During processing of `.runtimeconfig.json` there were two framework references to the same framework which were not compatible." )] FrameworkCompatFailure, /// Error used internally if the processing of framework references from `.runtimeconfig.json` reached a point where it needs to reprocess another already processed framework reference. /// If this error is returned to the external caller, it would mean there's a bug in the framework resolution algorithm. #[doc(hidden)] #[display( "[Internal error] The processing of framework references from .runtimeconfig.json reached a point where it needs to reprocess another already processed framework reference." )] FrameworkCompatRetry, /// Error reading the bundle footer metadata from a single-file `apphost`. /// This would mean a corrupted `apphost`. #[display("Error reading the bundle footer metadata from a single-file apphost.")] AppHostExeNotBundle, /// Error extracting single-file `apphost` bundle. /// This is used in case of any error related to the bundle itself. /// Typically would mean a corrupted bundle. #[display("Error extracting single-file apphost bundle.")] BundleExtractionFailure, /// Error reading or writing files during single-file `apphost` bundle extraction. #[display("Error reading or writing files during single-file apphost bundle extraction.")] BundleExtractionIOError, /// The `.runtimeconfig.json` specified by the app contains a runtime property which is also produced by the hosting layer. /// For example if the `.runtimeconfig.json` would specify a property `TRUSTED_PLATFORM_ROOTS`, this error code would be returned. /// It is not allowed to specify properties which are otherwise populated by the hosting layer (`hostpolicy`) as there is not good way to resolve such conflicts. #[display( "The .runtimeconfig.json specified by the app contains a runtime property which is also produced by the hosting layer." )] LibHostDuplicateProperty, /// Feature which requires certain version of the hosting layer binaries was used on a version which doesn't support it. /// For example if COM component specified to run on 2.0 `Microsoft.NETCore.App` - as that contains older version of `hostpolicy` which doesn't support the necessary features to provide COM services. #[display( "Feature which requires certain version of the hosting layer binaries was used on a version which doesn't support it." )] HostApiUnsupportedVersion, /// Error code returned by the hosting APIs in `hostfxr` if the current state is incompatible with the requested operation. /// There are many such cases, please refer to the documentation of the hosting APIs for details. /// For example if `hostfxr_get_runtime_property_value` is called with the `host_context_handle` `nullptr` (meaning get property from the active runtime) but there's no active runtime in the process. #[display("The current state is incompatible with the requested operation.")] HostInvalidState, /// Property requested by `hostfxr_get_runtime_property_value` doesn't exist. #[display("Property requested by hostfxr_get_runtime_property_value doesn't exist.")] HostPropertyNotFound, /// Error returned by `hostfxr_initialize_for_runtime_config` if the component being initialized requires framework which is not available or incompatible with the frameworks loaded by the runtime already in the process. /// For example trying to load a component which requires 3.0 into a process which is already running a 2.0 runtime. #[display( "Error returned by hostfxr_initialize_for_runtime_config if the component being initialized requires framework which is not available or incompatible with the frameworks loaded by the runtime already in the process." )] CoreHostIncompatibleConfig, /// Error returned by `hostfxr_get_runtime_delegate` when `hostfxr` doesn't currently support requesting the given delegate type using the given context. #[display( "Requesting the given delegate type using the given context is currently not supported." )] HostApiUnsupportedScenario, /// Error returned by `hostfxr_get_runtime_delegate` when managed feature support for native host is disabled. #[display("Managed feature support for native hosting is disabled")] HostFeatureDisabled, /// Unknown error status code. #[display("Unknown error status code: {_0:#08X}")] Unknown(u32), } impl std::error::Error for HostingError {} impl HostingError { /// Creates a new [`HostingError`] from the raw status code. pub const fn from_status_code(code: u32) -> Self { match Self::known_from_status_code(code) { Ok(s) => s, Err(code) => Self::Unknown(code), } } /// Tries to create a new [`HostingError`] from the raw status code if it is known. /// Otherwise returns the given value as an [`Err`]. pub const fn known_from_status_code(code: u32) -> Result<Self, u32> { match code { c if c == bindings::StatusCode::InvalidArgFailure as u32 => Ok(Self::InvalidArgFailure), c if c == bindings::StatusCode::CoreHostLibLoadFailure as u32 => { Ok(Self::CoreHostLibLoadFailure) } c if c == bindings::StatusCode::CoreHostLibMissingFailure as u32 => { Ok(Self::CoreHostLibMissingFailure) } c if c == bindings::StatusCode::CoreHostEntryPointFailure as u32 => { Ok(Self::CoreHostEntryPointFailure) } c if c == bindings::StatusCode::CoreHostCurHostFindFailure as u32 => { Ok(Self::CoreHostCurHostFindFailure) } c if c == bindings::StatusCode::CoreClrResolveFailure as u32 => { Ok(Self::CoreClrResolveFailure) } c if c == bindings::StatusCode::CoreClrBindFailure as u32 => { Ok(Self::CoreClrBindFailure) } c if c == bindings::StatusCode::CoreClrInitFailure as u32 => { Ok(Self::CoreClrInitFailure) } c if c == bindings::StatusCode::CoreClrExeFailure as u32 => Ok(Self::CoreClrExeFailure), c if c == bindings::StatusCode::ResolverInitFailure as u32 => { Ok(Self::ResolverInitFailure) } c if c == bindings::StatusCode::ResolverResolveFailure as u32 => { Ok(Self::ResolverResolveFailure) } c if c == bindings::StatusCode::LibHostCurExeFindFailure as u32 => { Ok(Self::LibHostCurExeFindFailure) } c if c == bindings::StatusCode::LibHostInitFailure as u32 => { Ok(Self::LibHostInitFailure) } c if c == bindings::StatusCode::LibHostExecModeFailure as u32 => { Ok(Self::LibHostExecModeFailure) } c if c == bindings::StatusCode::LibHostSdkFindFailure as u32 => { Ok(Self::LibHostSdkFindFailure) } c if c == bindings::StatusCode::LibHostInvalidArgs as u32 => { Ok(Self::LibHostInvalidArgs) } c if c == bindings::StatusCode::InvalidConfigFile as u32 => Ok(Self::InvalidConfigFile), c if c == bindings::StatusCode::AppArgNotRunnable as u32 => Ok(Self::AppArgNotRunnable), c if c == bindings::StatusCode::AppHostExeNotBoundFailure as u32 => { Ok(Self::AppHostExeNotBoundFailure) } c if c == bindings::StatusCode::FrameworkMissingFailure as u32 => { Ok(Self::FrameworkMissingFailure) } c if c == bindings::StatusCode::HostApiFailed as u32 => Ok(Self::HostApiFailed), c if c == bindings::StatusCode::HostApiBufferTooSmall as u32 => { Ok(Self::HostApiBufferTooSmall) } c if c == bindings::StatusCode::LibHostUnknownCommand as u32 => { Ok(Self::LibHostUnknownCommand) } c if c == bindings::StatusCode::LibHostAppRootFindFailure as u32 => { Ok(Self::LibHostAppRootFindFailure) } c if c == bindings::StatusCode::SdkResolverResolveFailure as u32 => { Ok(Self::SdkResolverResolveFailure) } c if c == bindings::StatusCode::FrameworkCompatFailure as u32 => { Ok(Self::FrameworkCompatFailure) } c if c == bindings::StatusCode::FrameworkCompatRetry as u32 => { Ok(Self::FrameworkCompatRetry) } c if c == bindings::StatusCode::BundleExtractionFailure as u32 => { Ok(Self::BundleExtractionFailure) } c if c == bindings::StatusCode::BundleExtractionIOError as u32 => { Ok(Self::BundleExtractionIOError) } c if c == bindings::StatusCode::LibHostDuplicateProperty as u32 => { Ok(Self::LibHostDuplicateProperty) } c if c == bindings::StatusCode::HostApiUnsupportedVersion as u32 => { Ok(Self::HostApiUnsupportedVersion) } c if c == bindings::StatusCode::HostInvalidState as u32 => Ok(Self::HostInvalidState), c if c == bindings::StatusCode::HostPropertyNotFound as u32 => { Ok(Self::HostPropertyNotFound) } c if c == bindings::StatusCode::CoreHostIncompatibleConfig as u32 => { Ok(Self::CoreHostIncompatibleConfig) } c if c == bindings::StatusCode::HostApiUnsupportedScenario as u32 => { Ok(Self::HostApiUnsupportedScenario) } c if c == bindings::StatusCode::HostFeatureDisabled as u32 => { Ok(Self::HostFeatureDisabled) } _ => Err(code), } } /// Returns the underlying status code value. #[must_use] pub const fn value(&self) -> u32 { match self { Self::InvalidArgFailure => bindings::StatusCode::InvalidArgFailure as u32, Self::CoreHostLibLoadFailure => bindings::StatusCode::CoreHostLibLoadFailure as u32, Self::CoreHostLibMissingFailure => { bindings::StatusCode::CoreHostLibMissingFailure as u32 } Self::CoreHostEntryPointFailure => { bindings::StatusCode::CoreHostEntryPointFailure as u32 } Self::CoreHostCurHostFindFailure => { bindings::StatusCode::CoreHostCurHostFindFailure as u32 } Self::CoreClrResolveFailure => bindings::StatusCode::CoreClrResolveFailure as u32, Self::CoreClrBindFailure => bindings::StatusCode::CoreClrBindFailure as u32, Self::CoreClrInitFailure => bindings::StatusCode::CoreClrInitFailure as u32, Self::CoreClrExeFailure => bindings::StatusCode::CoreClrExeFailure as u32, Self::ResolverInitFailure => bindings::StatusCode::ResolverInitFailure as u32, Self::ResolverResolveFailure => bindings::StatusCode::ResolverResolveFailure as u32, Self::LibHostCurExeFindFailure => bindings::StatusCode::LibHostCurExeFindFailure as u32, Self::LibHostInitFailure => bindings::StatusCode::LibHostInitFailure as u32, Self::LibHostExecModeFailure => bindings::StatusCode::LibHostExecModeFailure as u32, Self::LibHostSdkFindFailure => bindings::StatusCode::LibHostSdkFindFailure as u32, Self::LibHostInvalidArgs => bindings::StatusCode::LibHostInvalidArgs as u32, Self::InvalidConfigFile => bindings::StatusCode::InvalidConfigFile as u32, Self::AppArgNotRunnable => bindings::StatusCode::AppArgNotRunnable as u32, Self::AppHostExeNotBoundFailure => {
rust
MIT
4742a5d235b279a35b235bf7726c5afb9bde521d
2026-01-04T20:18:20.341772Z
true
OpenByteDev/netcorehost
https://github.com/OpenByteDev/netcorehost/blob/4742a5d235b279a35b235bf7726c5afb9bde521d/src/pdcstring/error.rs
src/pdcstring/error.rs
use std::{ error::Error, fmt::{self, Display}, }; use super::{MissingNulTerminatorInnerImpl, PdUChar, ToStringErrorInner, ToStringErrorInnerImpl}; // same definition as ffi::NulError and widestring::error::ContainsNul<u16> /// An error returned to indicate that an invalid nul value was found in a string. #[must_use] #[derive(Clone, PartialEq, Eq, Debug)] pub struct ContainsNul(usize, Vec<PdUChar>); impl ContainsNul { pub(crate) fn new(nul_position: usize, data: Vec<PdUChar>) -> Self { Self(nul_position, data) } /// Returns the position of the nul byte in the slice. #[must_use] pub fn nul_position(&self) -> usize { self.0 } /// Consumes this error, returning the underlying vector of bytes which /// generated the error in the first place. #[must_use] pub fn into_vec(self) -> Vec<PdUChar> { self.1 } } #[cfg(not(windows))] impl From<std::ffi::NulError> for ContainsNul { fn from(err: std::ffi::NulError) -> Self { Self::new(err.nul_position(), err.into_vec()) } } #[cfg(windows)] impl From<widestring::error::ContainsNul<PdUChar>> for ContainsNul { fn from(err: widestring::error::ContainsNul<PdUChar>) -> Self { Self::new(err.nul_position(), err.into_vec().unwrap()) } } impl Error for ContainsNul { fn description(&self) -> &'static str { "nul value found in data" } } impl fmt::Display for ContainsNul { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "nul byte found in provided data at position: {}", self.0) } } impl From<ContainsNul> for Vec<PdUChar> { fn from(e: ContainsNul) -> Vec<PdUChar> { e.into_vec() } } // common definition of str::Utf8Error and widestring::error::Utf16Error /// Errors which can occur when attempting to interpret a sequence of platform-dependent characters as a string. #[must_use] #[derive(Clone, Debug)] pub struct ToStringError(pub(crate) ToStringErrorInnerImpl); impl ToStringError { /// Returns [`Some`]`(index)` in the given string at which the invalid value occurred or /// [`None`] if the end of the input was reached unexpectedly. #[must_use] pub fn index(&self) -> Option<usize> { ToStringErrorInner::index(&self.0) } } impl Display for ToStringError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.0.fmt(f) } } impl Error for ToStringError { fn source(&self) -> Option<&(dyn Error + 'static)> { Some(&self.0) } } /// An error returned from to indicate that a terminating nul value was missing. #[must_use] #[derive(Clone, Debug)] pub struct MissingNulTerminator(pub(crate) MissingNulTerminatorInnerImpl); impl Display for MissingNulTerminator { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.0.fmt(f) } } impl Error for MissingNulTerminator { fn source(&self) -> Option<&(dyn Error + 'static)> { Some(&self.0) } }
rust
MIT
4742a5d235b279a35b235bf7726c5afb9bde521d
2026-01-04T20:18:20.341772Z
false
OpenByteDev/netcorehost
https://github.com/OpenByteDev/netcorehost/blob/4742a5d235b279a35b235bf7726c5afb9bde521d/src/pdcstring/mod.rs
src/pdcstring/mod.rs
mod error; pub use error::*; /// The platform-dependent character type used by the hosting components. pub type PdChar = crate::bindings::char_t; /// The unsigned version of the platform-dependent character type used by the hosting components. #[cfg(windows)] pub type PdUChar = u16; /// The unsigned version of the platform-dependent character type used by the hosting components. #[cfg(not(windows))] pub type PdUChar = u8; mod r#impl; pub use r#impl::*; mod shared; pub use shared::*;
rust
MIT
4742a5d235b279a35b235bf7726c5afb9bde521d
2026-01-04T20:18:20.341772Z
false
OpenByteDev/netcorehost
https://github.com/OpenByteDev/netcorehost/blob/4742a5d235b279a35b235bf7726c5afb9bde521d/src/pdcstring/shared.rs
src/pdcstring/shared.rs
use std::{ borrow::Borrow, convert::TryFrom, ffi::{OsStr, OsString}, fmt::{self, Debug, Display, Formatter}, ops::Deref, str::FromStr, }; use super::{ ContainsNul, MissingNulTerminator, PdCStrInner, PdCStrInnerImpl, PdCStringInner, PdCStringInnerImpl, PdChar, PdUChar, ToStringError, }; /// A platform-dependent c-like string type for interacting with the .NET hosting components. #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Default)] #[repr(transparent)] pub struct PdCString(pub(crate) PdCStringInnerImpl); impl PdCString { #[inline] pub(crate) fn from_inner(inner: PdCStringInnerImpl) -> Self { Self(inner) } #[inline] pub(crate) fn into_inner(self) -> PdCStringInnerImpl { self.0 } /// Construct a [`PdCString`] copy from an [`OsStr`], reencoding it in a platform-dependent manner. #[inline] pub fn from_os_str(s: impl AsRef<OsStr>) -> Result<Self, ContainsNul> { PdCStringInner::from_os_str(s).map(Self::from_inner) } /// Constructs a new [`PdCString`] copied from a nul-terminated string pointer. #[inline] #[must_use] pub unsafe fn from_str_ptr(ptr: *const PdChar) -> Self { Self::from_inner(unsafe { PdCStringInner::from_str_ptr(ptr) }) } /// Constructs a [`PdCString`] from a container of platform-dependent character data. #[inline] pub fn from_vec(vec: impl Into<Vec<PdUChar>>) -> Result<Self, ContainsNul> { PdCStringInner::from_vec(vec).map(Self::from_inner) } /// Converts the string into a [`Vec`] without a nul terminator, consuming the string in the process. #[inline] #[must_use] pub fn into_vec(self) -> Vec<PdUChar> { PdCStringInner::into_vec(self.into_inner()) } /// Converts the string into a [`Vec`], consuming the string in the process. #[inline] #[must_use] pub fn into_vec_with_nul(self) -> Vec<PdUChar> { PdCStringInner::into_vec_with_nul(self.into_inner()) } } /// A borrowed slice of a [`PdCString`]. #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[repr(transparent)] pub struct PdCStr(pub(crate) PdCStrInnerImpl); impl PdCStr { #[inline] pub(crate) fn from_inner(inner: &PdCStrInnerImpl) -> &Self { // Safety: // Safe because PdCStr has the same layout as PdCStrInnerImpl unsafe { &*(std::ptr::from_ref::<PdCStrInnerImpl>(inner) as *const PdCStr) } } #[inline] pub(crate) fn as_inner(&self) -> &PdCStrInnerImpl { // Safety: // Safe because PdCStr has the same layout as PdCStrInnerImpl unsafe { &*(std::ptr::from_ref::<PdCStr>(self) as *const PdCStrInnerImpl) } } /// Returns a raw pointer to the string. #[inline] #[must_use] pub fn as_ptr(&self) -> *const PdChar { PdCStrInner::as_ptr(self.as_inner()) } /// Constructs a [`PdCStr`] from a nul-terminated string pointer. #[inline] #[must_use] pub unsafe fn from_str_ptr<'a>(ptr: *const PdChar) -> &'a Self { Self::from_inner(unsafe { PdCStrInner::from_str_ptr(ptr) }) } /// Constructs a [`PdCStr`] from a slice of characters with a terminating nul, checking for invalid interior nul values. #[inline] pub fn from_slice_with_nul(slice: &[PdUChar]) -> Result<&Self, MissingNulTerminator> { PdCStrInner::from_slice_with_nul(slice).map(Self::from_inner) } /// Constructs a [`PdCStr`] from a slice of values without checking for a terminating or interior nul values. #[inline] #[must_use] pub unsafe fn from_slice_with_nul_unchecked(slice: &[PdUChar]) -> &Self { Self::from_inner(unsafe { PdCStrInner::from_slice_with_nul_unchecked(slice) }) } /// Copys the string to an owned [`OsString`]. #[inline] #[must_use] pub fn to_os_string(&self) -> OsString { PdCStrInner::to_os_string(self.as_inner()) } /// Converts this string to a slice of the underlying elements. /// The slice will **not** include the nul terminator. #[inline] #[must_use] pub fn as_slice(&self) -> &[PdUChar] { PdCStrInner::as_slice(self.as_inner()) } /// Converts this string to a slice of the underlying elements, including the nul terminator. #[inline] #[must_use] pub fn as_slice_with_nul(&self) -> &[PdUChar] { PdCStrInner::as_slice_with_nul(self.as_inner()) } /// Returns whether this string contains no data (i.e. is only the nul terminator). #[inline] #[must_use] pub fn is_empty(&self) -> bool { PdCStrInner::is_empty(self.as_inner()) } /// Returns the length of the string as number of elements (not number of bytes) not including the nul terminator. #[inline] #[must_use] pub fn len(&self) -> usize { PdCStrInner::len(self.as_inner()) } /// Copies the string to a [`String`] if it contains valid encoded data. #[inline] pub fn to_string(&self) -> Result<String, ToStringError> { PdCStrInner::to_string(self.as_inner()) } /// Decodes the string to a [`String`] even if it contains invalid data. /// Any invalid sequences are replaced with U+FFFD REPLACEMENT CHARACTER, which looks like this: �. It will *not have a nul terminator. #[inline] #[must_use] pub fn to_string_lossy(&self) -> String { PdCStrInner::to_string_lossy(self.as_inner()) } } impl Borrow<PdCStr> for PdCString { fn borrow(&self) -> &PdCStr { PdCStr::from_inner(self.0.borrow()) } } impl AsRef<PdCStr> for PdCString { fn as_ref(&self) -> &PdCStr { self.borrow() } } impl Deref for PdCString { type Target = PdCStr; fn deref(&self) -> &Self::Target { self.borrow() } } impl Display for PdCStr { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { self.0.fmt(f) } } impl<'a> From<&'a PdCString> for &'a PdCStr { fn from(s: &'a PdCString) -> Self { s.as_ref() } } impl<'a> From<&'a PdCStr> for PdCString { fn from(s: &'a PdCStr) -> Self { s.to_owned() } } impl FromStr for PdCString { type Err = ContainsNul; fn from_str(s: &str) -> Result<Self, Self::Err> { PdCStringInner::from_str(s).map(Self::from_inner) } } impl<'a> TryFrom<&'a str> for PdCString { type Error = ContainsNul; fn try_from(s: &'a str) -> Result<Self, Self::Error> { Self::from_str(s) } } impl<'a> TryFrom<&'a OsStr> for PdCString { type Error = ContainsNul; fn try_from(s: &'a OsStr) -> Result<Self, Self::Error> { Self::from_os_str(s) } } impl TryFrom<Vec<PdUChar>> for PdCString { type Error = ContainsNul; fn try_from(vec: Vec<PdUChar>) -> Result<Self, Self::Error> { Self::from_vec(vec) } } impl From<PdCString> for Vec<PdUChar> { fn from(s: PdCString) -> Vec<PdUChar> { s.into_vec() } } impl AsRef<PdCStr> for PdCStr { fn as_ref(&self) -> &Self { self } } impl ToOwned for PdCStr { type Owned = PdCString; fn to_owned(&self) -> Self::Owned { PdCString::from_inner(self.0.to_owned()) } }
rust
MIT
4742a5d235b279a35b235bf7726c5afb9bde521d
2026-01-04T20:18:20.341772Z
false
OpenByteDev/netcorehost
https://github.com/OpenByteDev/netcorehost/blob/4742a5d235b279a35b235bf7726c5afb9bde521d/src/pdcstring/impl/mod.rs
src/pdcstring/impl/mod.rs
mod traits; pub(crate) use traits::*; #[cfg(windows)] pub mod windows; #[cfg(windows)] pub(crate) use windows::*; #[cfg(not(windows))] pub mod other; #[cfg(not(windows))] pub(crate) use other::*;
rust
MIT
4742a5d235b279a35b235bf7726c5afb9bde521d
2026-01-04T20:18:20.341772Z
false
OpenByteDev/netcorehost
https://github.com/OpenByteDev/netcorehost/blob/4742a5d235b279a35b235bf7726c5afb9bde521d/src/pdcstring/impl/traits.rs
src/pdcstring/impl/traits.rs
use std::{ error::Error, ffi::{OsStr, OsString}, fmt::{Debug, Display}, }; use crate::pdcstring::{ContainsNul, MissingNulTerminator, PdChar, PdUChar, ToStringError}; pub(crate) trait PdCStringInner where Self: Sized, { fn from_str(s: impl AsRef<str>) -> Result<Self, ContainsNul>; fn from_os_str(s: impl AsRef<OsStr>) -> Result<Self, ContainsNul>; unsafe fn from_str_ptr(ptr: *const PdChar) -> Self; fn from_vec(vec: impl Into<Vec<PdUChar>>) -> Result<Self, ContainsNul>; fn into_vec(self) -> Vec<PdUChar>; fn into_vec_with_nul(self) -> Vec<PdUChar>; } pub(crate) trait PdCStrInner { fn as_ptr(&self) -> *const PdChar; unsafe fn from_str_ptr<'a>(ptr: *const PdChar) -> &'a Self; unsafe fn from_slice_with_nul_unchecked(slice: &[PdUChar]) -> &Self; fn to_os_string(&self) -> OsString; fn from_slice_with_nul(slice: &[PdUChar]) -> Result<&Self, MissingNulTerminator>; fn as_slice(&self) -> &[PdUChar]; fn as_slice_with_nul(&self) -> &[PdUChar]; fn is_empty(&self) -> bool; fn len(&self) -> usize; fn to_string(&self) -> Result<String, ToStringError>; fn to_string_lossy(&self) -> String; } pub(crate) trait ToStringErrorInner: Debug + Display + Error + Clone { fn index(&self) -> Option<usize>; } #[allow(dead_code)] pub(crate) trait MissingNulTerminatorInner: Debug + Display + Error + Clone {}
rust
MIT
4742a5d235b279a35b235bf7726c5afb9bde521d
2026-01-04T20:18:20.341772Z
false
OpenByteDev/netcorehost
https://github.com/OpenByteDev/netcorehost/blob/4742a5d235b279a35b235bf7726c5afb9bde521d/src/pdcstring/impl/windows/pdcstring.rs
src/pdcstring/impl/windows/pdcstring.rs
use widestring::U16CString; use crate::pdcstring::{ContainsNul, PdCStringInner, PdChar}; impl PdCStringInner for U16CString { fn from_str(s: impl AsRef<str>) -> Result<Self, ContainsNul> { Ok(U16CString::from_str(s)?) } fn from_os_str(s: impl AsRef<std::ffi::OsStr>) -> Result<Self, ContainsNul> { U16CString::from_os_str(s).map_err(|e| e.into()) } unsafe fn from_str_ptr(ptr: *const PdChar) -> Self { unsafe { U16CString::from_ptr_str(ptr) } } fn from_vec(vec: impl Into<Vec<PdChar>>) -> Result<Self, ContainsNul> { U16CString::from_vec(vec).map_err(|e| e.into()) } fn into_vec(self) -> Vec<PdChar> { U16CString::into_vec(self) } fn into_vec_with_nul(self) -> Vec<PdChar> { U16CString::into_vec_with_nul(self) } }
rust
MIT
4742a5d235b279a35b235bf7726c5afb9bde521d
2026-01-04T20:18:20.341772Z
false
OpenByteDev/netcorehost
https://github.com/OpenByteDev/netcorehost/blob/4742a5d235b279a35b235bf7726c5afb9bde521d/src/pdcstring/impl/windows/ext.rs
src/pdcstring/impl/windows/ext.rs
use widestring::{U16CStr, U16CString}; use crate::pdcstring::{PdCStr, PdCString}; pub trait PdCStringExt where Self: Sized, { fn from_u16_c_string(s: U16CString) -> Self; fn into_u16_c_string(self) -> U16CString; } impl PdCStringExt for PdCString { fn from_u16_c_string(s: U16CString) -> Self { Self::from_inner(s) } fn into_u16_c_string(self) -> U16CString { self.into_inner() } } pub trait PdCStrExt { fn from_u16_c_str(s: &U16CStr) -> &Self; fn as_u16_c_str(&self) -> &U16CStr; } impl PdCStrExt for PdCStr { fn from_u16_c_str(s: &U16CStr) -> &Self { Self::from_inner(s) } fn as_u16_c_str(&self) -> &U16CStr { self.as_inner() } }
rust
MIT
4742a5d235b279a35b235bf7726c5afb9bde521d
2026-01-04T20:18:20.341772Z
false
OpenByteDev/netcorehost
https://github.com/OpenByteDev/netcorehost/blob/4742a5d235b279a35b235bf7726c5afb9bde521d/src/pdcstring/impl/windows/error.rs
src/pdcstring/impl/windows/error.rs
use crate::pdcstring::{MissingNulTerminatorInner, ToStringErrorInner}; impl ToStringErrorInner for widestring::error::Utf16Error { fn index(&self) -> Option<usize> { Some(self.index()) } } impl MissingNulTerminatorInner for widestring::error::MissingNulTerminator {}
rust
MIT
4742a5d235b279a35b235bf7726c5afb9bde521d
2026-01-04T20:18:20.341772Z
false
OpenByteDev/netcorehost
https://github.com/OpenByteDev/netcorehost/blob/4742a5d235b279a35b235bf7726c5afb9bde521d/src/pdcstring/impl/windows/pdcstr.rs
src/pdcstring/impl/windows/pdcstr.rs
use std::ffi::OsString; use widestring::U16CStr; use crate::pdcstring::{MissingNulTerminator, PdCStrInner, PdChar, ToStringError}; #[doc(hidden)] pub extern crate widestring; #[macro_export] /// A macro for creating a [`PdCStr`](crate::pdcstring::PdCStr) at compile time. macro_rules! pdcstr { ($expression:expr) => { <$crate::pdcstring::PdCStr as $crate::pdcstring::windows::PdCStrExt>::from_u16_c_str( $crate::pdcstring::windows::widestring::u16cstr!($expression), ) }; } impl PdCStrInner for U16CStr { fn as_ptr(&self) -> *const PdChar { U16CStr::as_ptr(self) } unsafe fn from_str_ptr<'a>(ptr: *const PdChar) -> &'a Self { unsafe { U16CStr::from_ptr_str(ptr) } } unsafe fn from_slice_with_nul_unchecked(slice: &[PdChar]) -> &Self { unsafe { U16CStr::from_slice_unchecked(slice) } } fn to_os_string(&self) -> OsString { U16CStr::to_os_string(self) } fn from_slice_with_nul(slice: &[PdChar]) -> Result<&Self, MissingNulTerminator> { U16CStr::from_slice_truncate(slice).map_err(MissingNulTerminator) } fn as_slice(&self) -> &[PdChar] { U16CStr::as_slice(self) } fn as_slice_with_nul(&self) -> &[PdChar] { U16CStr::as_slice_with_nul(self) } fn is_empty(&self) -> bool { U16CStr::is_empty(self) } fn len(&self) -> usize { U16CStr::len(self) } fn to_string(&self) -> Result<String, ToStringError> { U16CStr::to_string(self).map_err(ToStringError) } fn to_string_lossy(&self) -> String { U16CStr::to_string_lossy(self) } }
rust
MIT
4742a5d235b279a35b235bf7726c5afb9bde521d
2026-01-04T20:18:20.341772Z
false
OpenByteDev/netcorehost
https://github.com/OpenByteDev/netcorehost/blob/4742a5d235b279a35b235bf7726c5afb9bde521d/src/pdcstring/impl/windows/mod.rs
src/pdcstring/impl/windows/mod.rs
pub(crate) type PdCStringInnerImpl = widestring::U16CString; pub(crate) type PdCStrInnerImpl = widestring::U16CStr; pub(crate) type ToStringErrorInnerImpl = widestring::error::Utf16Error; pub(crate) type MissingNulTerminatorInnerImpl = widestring::error::MissingNulTerminator; mod pdcstr; pub use pdcstr::*; mod pdcstring; #[allow(unused)] pub use pdcstring::*; mod error; #[allow(unused)] pub use error::*; mod ext; pub use ext::*;
rust
MIT
4742a5d235b279a35b235bf7726c5afb9bde521d
2026-01-04T20:18:20.341772Z
false
OpenByteDev/netcorehost
https://github.com/OpenByteDev/netcorehost/blob/4742a5d235b279a35b235bf7726c5afb9bde521d/src/pdcstring/impl/other/pdcstring.rs
src/pdcstring/impl/other/pdcstring.rs
use std::{ ffi::{CStr, CString}, os::unix::prelude::OsStrExt, }; use crate::pdcstring::{ContainsNul, PdCStringInner, PdChar, PdUChar}; impl PdCStringInner for CString { fn from_str(s: impl AsRef<str>) -> Result<Self, ContainsNul> { Self::from_vec(s.as_ref().as_bytes().to_vec()) } fn from_os_str(s: impl AsRef<std::ffi::OsStr>) -> Result<Self, ContainsNul> { Self::from_vec(s.as_ref().as_bytes().to_vec()) } unsafe fn from_str_ptr(ptr: *const PdChar) -> Self { unsafe { CStr::from_ptr(ptr) }.to_owned() } fn from_vec(vec: impl Into<Vec<PdUChar>>) -> Result<Self, ContainsNul> { CString::new(vec).map_err(|e| e.into()) } fn into_vec(self) -> Vec<PdUChar> { CString::into_bytes(self) } fn into_vec_with_nul(self) -> Vec<PdUChar> { CString::into_bytes_with_nul(self) } }
rust
MIT
4742a5d235b279a35b235bf7726c5afb9bde521d
2026-01-04T20:18:20.341772Z
false
OpenByteDev/netcorehost
https://github.com/OpenByteDev/netcorehost/blob/4742a5d235b279a35b235bf7726c5afb9bde521d/src/pdcstring/impl/other/ext.rs
src/pdcstring/impl/other/ext.rs
use std::ffi::{CStr, CString}; use crate::pdcstring::{PdCStr, PdCString}; pub trait PdCStringExt where Self: Sized, { fn from_c_string(s: CString) -> Self; fn into_c_string(self) -> CString; } impl PdCStringExt for PdCString { fn from_c_string(s: CString) -> Self { Self::from_inner(s) } fn into_c_string(self) -> CString { self.into_inner() } } pub trait PdCStrExt { fn from_c_str(s: &CStr) -> &Self; fn as_c_str(&self) -> &CStr; } impl PdCStrExt for PdCStr { fn from_c_str(s: &CStr) -> &Self { Self::from_inner(s) } fn as_c_str(&self) -> &CStr { self.as_inner() } }
rust
MIT
4742a5d235b279a35b235bf7726c5afb9bde521d
2026-01-04T20:18:20.341772Z
false
OpenByteDev/netcorehost
https://github.com/OpenByteDev/netcorehost/blob/4742a5d235b279a35b235bf7726c5afb9bde521d/src/pdcstring/impl/other/error.rs
src/pdcstring/impl/other/error.rs
use crate::pdcstring::{MissingNulTerminatorInner, ToStringErrorInner}; impl ToStringErrorInner for std::str::Utf8Error { fn index(&self) -> Option<usize> { self.error_len() } } impl MissingNulTerminatorInner for std::ffi::FromBytesWithNulError {}
rust
MIT
4742a5d235b279a35b235bf7726c5afb9bde521d
2026-01-04T20:18:20.341772Z
false
OpenByteDev/netcorehost
https://github.com/OpenByteDev/netcorehost/blob/4742a5d235b279a35b235bf7726c5afb9bde521d/src/pdcstring/impl/other/pdcstr.rs
src/pdcstring/impl/other/pdcstr.rs
use std::{ ffi::{CStr, OsStr, OsString}, os::unix::prelude::OsStrExt, }; use crate::pdcstring::{MissingNulTerminator, PdCStrInner, PdChar, PdUChar, ToStringError}; #[doc(hidden)] pub extern crate cstr; #[macro_export] /// A macro for creating a [`PdCStr`](crate::pdcstring::PdCStr) at compile time. macro_rules! pdcstr { ($expression:expr) => { <$crate::pdcstring::PdCStr as $crate::pdcstring::other::PdCStrExt>::from_c_str( $crate::pdcstring::other::cstr::cstr!($expression), ) }; } impl PdCStrInner for CStr { fn as_ptr(&self) -> *const PdChar { CStr::as_ptr(self) } unsafe fn from_str_ptr<'a>(ptr: *const PdChar) -> &'a Self { unsafe { CStr::from_ptr(ptr) } } unsafe fn from_slice_with_nul_unchecked(slice: &[PdUChar]) -> &Self { unsafe { CStr::from_bytes_with_nul_unchecked(slice) } } fn to_os_string(&self) -> OsString { OsStr::from_bytes(CStr::to_bytes(self)).to_owned() } fn from_slice_with_nul(slice: &[PdUChar]) -> Result<&Self, MissingNulTerminator> { CStr::from_bytes_with_nul(slice).map_err(MissingNulTerminator) } fn as_slice(&self) -> &[PdUChar] { CStr::to_bytes(self) } fn as_slice_with_nul(&self) -> &[PdUChar] { CStr::to_bytes_with_nul(self) } fn is_empty(&self) -> bool { CStr::to_bytes(self).is_empty() } fn len(&self) -> usize { CStr::to_bytes(self).len() } fn to_string(&self) -> Result<String, ToStringError> { CStr::to_str(self) .map(str::to_string) .map_err(ToStringError) } fn to_string_lossy(&self) -> String { CStr::to_string_lossy(self).to_string() } }
rust
MIT
4742a5d235b279a35b235bf7726c5afb9bde521d
2026-01-04T20:18:20.341772Z
false
OpenByteDev/netcorehost
https://github.com/OpenByteDev/netcorehost/blob/4742a5d235b279a35b235bf7726c5afb9bde521d/src/pdcstring/impl/other/mod.rs
src/pdcstring/impl/other/mod.rs
pub(crate) type PdCStringInnerImpl = std::ffi::CString; pub(crate) type PdCStrInnerImpl = std::ffi::CStr; pub(crate) type ToStringErrorInnerImpl = std::str::Utf8Error; pub(crate) type MissingNulTerminatorInnerImpl = std::ffi::FromBytesWithNulError; mod pdcstr; pub use pdcstr::*; mod pdcstring; #[allow(unused)] pub use pdcstring::*; mod error; #[allow(unused)] pub use error::*; mod ext; pub use ext::*;
rust
MIT
4742a5d235b279a35b235bf7726c5afb9bde521d
2026-01-04T20:18:20.341772Z
false
OpenByteDev/netcorehost
https://github.com/OpenByteDev/netcorehost/blob/4742a5d235b279a35b235bf7726c5afb9bde521d/src/bindings/mod.rs
src/bindings/mod.rs
extern crate coreclr_hosting_shared; /// Module for shared bindings for all hosting components. pub use coreclr_hosting_shared::*; /// Module containing the raw bindings for hostfxr. pub use hostfxr_sys as hostfxr; /// Module containing the raw bindings for nethost. #[cfg(feature = "nethost")] pub use nethost_sys as nethost;
rust
MIT
4742a5d235b279a35b235bf7726c5afb9bde521d
2026-01-04T20:18:20.341772Z
false
OpenByteDev/netcorehost
https://github.com/OpenByteDev/netcorehost/blob/4742a5d235b279a35b235bf7726c5afb9bde521d/tests/errors.rs
tests/errors.rs
#![cfg(feature = "netcore3_0")] use netcorehost::{hostfxr::GetManagedFunctionError, nethost, pdcstr}; use rusty_fork::rusty_fork_test; #[path = "common.rs"] mod common; rusty_fork_test! { #[test] fn get_function_pointer() { common::setup(); let hostfxr = nethost::load_hostfxr().unwrap(); let context = hostfxr .initialize_for_runtime_config(common::test_runtime_config_path()) .unwrap(); let fn_loader = context .get_delegate_loader_for_assembly(common::test_dll_path()) .unwrap(); let invalid_method_name = fn_loader.get_function_with_default_signature( pdcstr!("Test.Program, Test"), pdcstr!("SomeMethodThatDoesNotExist"), ); assert!(invalid_method_name.is_err()); assert_eq!( invalid_method_name.unwrap_err(), GetManagedFunctionError::TypeOrMethodNotFound ); let invalid_method_signature = fn_loader .get_function_with_default_signature(pdcstr!("Test.Program, Test"), pdcstr!("Main")); assert!(invalid_method_signature.is_err()); assert_eq!( invalid_method_signature.unwrap_err(), GetManagedFunctionError::TypeOrMethodNotFound ); let invalid_type_name = fn_loader.get_function_with_default_signature( pdcstr!("Test.SomeTypeThatDoesNotExist, Test"), pdcstr!("Hello"), ); assert!(invalid_type_name.is_err()); assert_eq!( invalid_type_name.unwrap_err(), GetManagedFunctionError::TypeOrMethodNotFound ); let invalid_namespace_name = fn_loader.get_function_with_default_signature( pdcstr!("SomeNamespaceThatDoesNotExist.Program, Test"), pdcstr!("Hello"), ); assert!(invalid_namespace_name.is_err()); assert_eq!( invalid_namespace_name.unwrap_err(), GetManagedFunctionError::TypeOrMethodNotFound ); let invalid_assembly_name = fn_loader.get_function_with_default_signature( pdcstr!("Test.Program, SomeAssemblyThatDoesNotExist"), pdcstr!("Hello"), ); assert!(invalid_assembly_name.is_err()); assert_eq!( invalid_assembly_name.unwrap_err(), GetManagedFunctionError::AssemblyNotFound ); let method_not_marked = fn_loader.get_function_with_unmanaged_callers_only::<fn()>( pdcstr!("Test.Program, Test"), pdcstr!("Hello"), ); assert!(method_not_marked.is_err()); assert_eq!( method_not_marked.unwrap_err(), GetManagedFunctionError::MethodNotUnmanagedCallersOnly ); let invalid_delegate_type_name = fn_loader.get_function::<fn()>( pdcstr!("Test.Program, Test"), pdcstr!("Hello"), pdcstr!("Test.Program+SomeDelegateThatDoesNotExist, Test"), ); assert!(invalid_delegate_type_name.is_err()); assert_eq!( invalid_delegate_type_name.unwrap_err(), GetManagedFunctionError::TypeOrMethodNotFound ); context.close().unwrap(); } #[test] fn get_delegate_loader_for_assembly() { common::setup(); let hostfxr = nethost::load_hostfxr().unwrap(); let context = hostfxr .initialize_for_runtime_config(common::test_runtime_config_path()) .unwrap(); let fn_loader = context .get_delegate_loader_for_assembly(pdcstr!("tests/errors.rs")) .unwrap(); let invalid_assembly_path = fn_loader .get_function_with_default_signature(pdcstr!("Test.Program, Test"), pdcstr!("Hello")); assert!(invalid_assembly_path.is_err()); assert_eq!( invalid_assembly_path.unwrap_err(), GetManagedFunctionError::AssemblyNotFound ); let fn_loader = context .get_delegate_loader_for_assembly(pdcstr!("PathThatDoesNotExist.dll")) .unwrap(); let non_existant_assembly_path = fn_loader .get_function_with_default_signature(pdcstr!("Test.Program, Test"), pdcstr!("Hello")); assert!(non_existant_assembly_path.is_err()); assert_eq!( non_existant_assembly_path.unwrap_err(), GetManagedFunctionError::AssemblyNotFound ); context.close().unwrap(); } }
rust
MIT
4742a5d235b279a35b235bf7726c5afb9bde521d
2026-01-04T20:18:20.341772Z
false
OpenByteDev/netcorehost
https://github.com/OpenByteDev/netcorehost/blob/4742a5d235b279a35b235bf7726c5afb9bde521d/tests/manual_close_frees_lib.rs
tests/manual_close_frees_lib.rs
#![cfg(feature = "netcore3_0")] use std::sync::Arc; use netcorehost::nethost; use rusty_fork::rusty_fork_test; #[path = "common.rs"] mod common; rusty_fork_test! { #[test] fn manual_close_frees_lib() { common::setup(); let hostfxr = nethost::load_hostfxr().unwrap(); let context = hostfxr .initialize_for_runtime_config(common::test_runtime_config_path()) .unwrap(); let weak = Arc::downgrade(&hostfxr.lib); drop(hostfxr); context.close().unwrap(); assert_eq!(weak.strong_count(), 0); } }
rust
MIT
4742a5d235b279a35b235bf7726c5afb9bde521d
2026-01-04T20:18:20.341772Z
false
OpenByteDev/netcorehost
https://github.com/OpenByteDev/netcorehost/blob/4742a5d235b279a35b235bf7726c5afb9bde521d/tests/custom_delegate_type.rs
tests/custom_delegate_type.rs
#![cfg(feature = "netcore3_0")] use netcorehost::{nethost, pdcstr}; use rusty_fork::rusty_fork_test; #[path = "common.rs"] mod common; rusty_fork_test! { fn unmanaged_caller_hello_world() { common::setup(); let hostfxr = nethost::load_hostfxr().unwrap(); let context = hostfxr .initialize_for_runtime_config(common::test_runtime_config_path()) .unwrap(); let fn_loader = context .get_delegate_loader_for_assembly(common::test_dll_path()) .unwrap(); let hello = fn_loader .get_function::<fn()>( pdcstr!("Test.Program, Test"), pdcstr!("CustomHello"), pdcstr!("Test.Program+CustomHelloFunc, Test"), ) .unwrap(); hello(); } }
rust
MIT
4742a5d235b279a35b235bf7726c5afb9bde521d
2026-01-04T20:18:20.341772Z
false
OpenByteDev/netcorehost
https://github.com/OpenByteDev/netcorehost/blob/4742a5d235b279a35b235bf7726c5afb9bde521d/tests/run_app.rs
tests/run_app.rs
#![allow(deprecated)] use netcorehost::nethost; use rusty_fork::rusty_fork_test; #[path = "common.rs"] mod common; rusty_fork_test! { #[test] #[cfg(feature = "netcore3_0")] fn run_app_with_context() { common::setup(); let hostfxr = nethost::load_hostfxr().unwrap(); let context = hostfxr .initialize_for_dotnet_command_line(common::test_dll_path()) .unwrap(); let result = context.run_app().value(); assert_eq!(result, 42); } #[test] #[cfg(feature = "netcore1_0")] fn run_app_direct() { common::setup(); let hostfxr = nethost::load_hostfxr().unwrap(); let result = hostfxr.run_app(&common::test_dll_path()); result.as_hosting_exit_code().unwrap(); assert_eq!(result.value(), 42); } }
rust
MIT
4742a5d235b279a35b235bf7726c5afb9bde521d
2026-01-04T20:18:20.341772Z
false
OpenByteDev/netcorehost
https://github.com/OpenByteDev/netcorehost/blob/4742a5d235b279a35b235bf7726c5afb9bde521d/tests/hello_world.rs
tests/hello_world.rs
#![cfg(feature = "netcore3_0")] use netcorehost::{nethost, pdcstr}; use rusty_fork::rusty_fork_test; use std::ptr; #[path = "common.rs"] mod common; rusty_fork_test! { #[test] fn hello_world() { common::setup(); let hostfxr = nethost::load_hostfxr().unwrap(); let context = hostfxr .initialize_for_runtime_config(common::test_runtime_config_path()) .unwrap(); let fn_loader = context .get_delegate_loader_for_assembly(common::test_dll_path()) .unwrap(); let hello = fn_loader .get_function_with_default_signature(pdcstr!("Test.Program, Test"), pdcstr!("Hello")) .unwrap(); let result = unsafe { hello(ptr::null(), 0) }; assert_eq!(result, 42); } #[test] fn hello_world_twice() { common::setup(); let hostfxr = nethost::load_hostfxr().unwrap(); let context = hostfxr .initialize_for_runtime_config(common::test_runtime_config_path()) .unwrap(); let fn_loader = context .get_delegate_loader_for_assembly(common::test_dll_path()) .unwrap(); let hello_one = fn_loader .get_function_with_default_signature(pdcstr!("Test.Program, Test"), pdcstr!("Hello")) .unwrap(); let result = unsafe { hello_one(ptr::null(), 0) }; assert_eq!(result, 42); let hello_two = fn_loader .get_function_with_default_signature(pdcstr!("Test.Program, Test"), pdcstr!("Hello2")) .unwrap(); let result = unsafe { hello_two(ptr::null(), 0) }; assert_eq!(result, 0); } }
rust
MIT
4742a5d235b279a35b235bf7726c5afb9bde521d
2026-01-04T20:18:20.341772Z
false
OpenByteDev/netcorehost
https://github.com/OpenByteDev/netcorehost/blob/4742a5d235b279a35b235bf7726c5afb9bde521d/tests/unhandled_managed_exeptions.rs
tests/unhandled_managed_exeptions.rs
#![cfg(all(feature = "netcore3_0", feature = "utils", unix))] // see https://github.com/OpenByteDev/netcorehost/issues/38 #[path = "common.rs"] mod common; use netcorehost::{ nethost, pdcstr, utils::altstack::{self, State}, }; use rusty_fork::{fork, rusty_fork_id, ChildWrapper, ExitStatusWrapper}; use std::{io::Read, process::Stdio}; macro_rules! function_name { () => {{ fn f() {} fn type_name_of<T>(_: T) -> &'static str { std::any::type_name::<T>() } type_name_of(f) .rsplit("::") .find(|&part| part != "f" && part != "{{closure}}") .expect("failed to get function name") }}; } macro_rules! assert_contains { ($string:expr, $substring:expr) => {{ let string_ref: &str = &($string); let substring_ref: &str = &($substring); assert!( string_ref.contains(substring_ref), "Expected `{}` to contain `{}`", string_ref, substring_ref ); }}; } macro_rules! assert_not_contains { ($string:expr, $substring:expr) => {{ let string_ref: &str = &($string); let substring_ref: &str = &($substring); assert!( !string_ref.contains(substring_ref), "Expected `{}` NOT to contain `{}`", string_ref, substring_ref ); }}; } const MANAGED_HANDLER_OUTPUT: &str = "Unhandled exception. System.NullReferenceException: Object reference not set to an instance of an object."; #[test] fn segfault_with_small_altstack() { common::setup(); altstack_test( function_name!(), || { altstack::set(State::Enabled { size: 2 * 1024 }).unwrap(); }, |status, _, stderr| { assert_eq!(status.unix_signal(), Some(libc::SIGSEGV)); assert_not_contains!(stderr, MANAGED_HANDLER_OUTPUT); }, ); } #[test] fn no_segfault_with_large_altstack() { common::setup(); altstack_test( function_name!(), || { altstack::set(State::Enabled { size: 16 * 1024 }).unwrap(); }, |status, _, stderr| { assert_ne!(status.unix_signal(), Some(libc::SIGSEGV)); assert_contains!(stderr, MANAGED_HANDLER_OUTPUT); }, ); } #[test] fn no_segfault_with_altstack_disabled() { common::setup(); altstack_test( function_name!(), || { altstack::set(State::Disabled).unwrap(); }, |status, _, stderr| { assert_ne!(status.unix_signal(), Some(libc::SIGSEGV)); assert_contains!(stderr, MANAGED_HANDLER_OUTPUT); }, ); } fn altstack_test( test_name: &str, configure_altstack: impl FnOnce(), verify: impl FnOnce(ExitStatusWrapper, /* stdout */ String, /* stderr */ String), ) { common::setup(); // Defines the code the forked process will execute let body = || { configure_altstack(); let hostfxr = nethost::load_hostfxr().unwrap(); let context = hostfxr .initialize_for_runtime_config(common::test_runtime_config_path()) .unwrap(); let fn_loader = context .get_delegate_loader_for_assembly(common::test_dll_path()) .unwrap(); let throw_fn = fn_loader .get_function_with_unmanaged_callers_only::<unsafe fn()>( pdcstr!("Test.Program, Test"), pdcstr!("Throw"), ) .unwrap(); unsafe { throw_fn() }; }; // Pipe stdout and stderr fn configure_child(child: &mut std::process::Command) { child.stdout(Stdio::piped()); child.stderr(Stdio::piped()); } // Define how to verifz the output ot the child. let supervise = |child: &mut ChildWrapper, _file: &mut std::fs::File| { let mut stdout = String::new(); child .inner_mut() .stdout .as_mut() .unwrap() .read_to_string(&mut stdout) .unwrap(); let mut stderr = String::new(); child .inner_mut() .stderr .as_mut() .unwrap() .read_to_string(&mut stderr) .unwrap(); let status = child.wait().expect("unable to wait for child"); println!("status: {status}"); println!("stdout: {stdout}"); println!("stderr: {stderr}"); verify(status, stdout, stderr); }; // Run the test in a forked child fork( test_name, rusty_fork_id!(), configure_child, supervise, body, ) .expect("fork failed"); }
rust
MIT
4742a5d235b279a35b235bf7726c5afb9bde521d
2026-01-04T20:18:20.341772Z
false
OpenByteDev/netcorehost
https://github.com/OpenByteDev/netcorehost/blob/4742a5d235b279a35b235bf7726c5afb9bde521d/tests/environment_info.rs
tests/environment_info.rs
#![cfg(feature = "net6_0")] use netcorehost::{ hostfxr::{EnvironmentInfo, FrameworkInfo, SdkInfo}, nethost, }; use std::{ collections::HashMap, path::{Path, PathBuf}, process::Command, str::FromStr, }; #[path = "common.rs"] mod common; #[test] fn get_dotnet_environment_info() { use netcorehost::pdcstring::PdCString; let hostfxr = if let Some(dotnet_root) = option_env!("DOTNET_ROOT") { nethost::load_hostfxr_with_dotnet_root(PdCString::from_str(dotnet_root).unwrap()) } else { nethost::load_hostfxr() } .unwrap(); let actual_env = hostfxr.get_dotnet_environment_info().unwrap(); let expected_env = get_expected_environment_info(); assert_eq!(expected_env.hostfxr_version, actual_env.hostfxr_version); assert_eq!(expected_env.sdks, actual_env.sdks); assert_eq!(expected_env.frameworks, actual_env.frameworks); } fn get_expected_environment_info() -> EnvironmentInfo { let dotnet_path = option_env!("DOTNET_ROOT") .map(|root| Path::new(root).join("dotnet")) .unwrap_or_else(|| PathBuf::from_str("dotnet").unwrap()); let output = Command::new(dotnet_path).arg("--info").output().unwrap(); assert!(output.status.success()); let output = String::from_utf8_lossy(&output.stdout); let mut sections = Vec::new(); let mut current_section = None; for line in output.lines() { if line.is_empty() { if let Some(section) = current_section.take() { sections.push(section); } continue; } match &mut current_section { None => current_section = Some((line.trim().trim_end_matches(':'), Vec::new())), Some((_header, content)) => { content.push(line.trim()); } } } let host_section_content = sections .iter() .find(|(header, _content)| *header == "Host") .map(|(_header, content)| content) .unwrap(); let host_info = host_section_content .iter() .map(|line| { let (key, value) = line.split_once(':').unwrap(); (key.trim(), value.trim()) }) .collect::<HashMap<_, _>>(); let hostfxr_version = host_info["Version"].to_string(); let hostfxr_commit_hash = host_info["Commit"].to_string(); let sdk_section_content = sections .iter() .find(|(header, _content)| *header == ".NET SDKs installed") .map(|(_header, content)| content) .unwrap(); let sdks = sdk_section_content .iter() .map(|line| { let (version, enclosed_path) = line.split_once(' ').unwrap(); let path = enclosed_path.trim_start_matches('[').trim_end_matches(']'); let version = version.to_string(); let mut path = PathBuf::from(path); path.push(&version); SdkInfo { version, path } }) .collect::<Vec<_>>(); let framework_section_content = sections .iter() .find(|(header, _content)| *header == ".NET runtimes installed") .map(|(_header, content)| content) .unwrap(); let frameworks = framework_section_content .iter() .map(|line| { let mut items = line.splitn(3, ' '); let name = items.next().unwrap(); let version = items.next().unwrap(); let enclosed_path = items.next().unwrap(); assert_eq!(items.next(), None); let name = name.to_string(); let path = PathBuf::from(enclosed_path.trim_start_matches('[').trim_end_matches(']')); let version = version.to_string(); FrameworkInfo { name, version, path, } }) .collect::<Vec<_>>(); EnvironmentInfo { hostfxr_version, hostfxr_commit_hash, sdks, frameworks, } }
rust
MIT
4742a5d235b279a35b235bf7726c5afb9bde521d
2026-01-04T20:18:20.341772Z
false
OpenByteDev/netcorehost
https://github.com/OpenByteDev/netcorehost/blob/4742a5d235b279a35b235bf7726c5afb9bde521d/tests/runtime_properties.rs
tests/runtime_properties.rs
#![cfg(feature = "netcore3_0")] use netcorehost::{nethost, pdcstr}; use rusty_fork::rusty_fork_test; #[path = "common.rs"] mod common; rusty_fork_test! { #[test] fn runtime_properties() { common::setup(); let hostfxr = nethost::load_hostfxr().unwrap(); let mut context = hostfxr .initialize_for_runtime_config(common::test_runtime_config_path()) .unwrap(); let test_property_name = pdcstr!("TEST_PROPERTY"); let test_property_value = pdcstr!("TEST_VALUE"); context .set_runtime_property_value(test_property_name, test_property_value) .unwrap(); let property_value = context .get_runtime_property_value(test_property_name) .unwrap(); assert_eq!(test_property_value, property_value); let properties = context.runtime_properties().unwrap(); let property_value = properties.get(test_property_name).copied().unwrap(); assert_eq!(test_property_value, property_value); } }
rust
MIT
4742a5d235b279a35b235bf7726c5afb9bde521d
2026-01-04T20:18:20.341772Z
false
OpenByteDev/netcorehost
https://github.com/OpenByteDev/netcorehost/blob/4742a5d235b279a35b235bf7726c5afb9bde521d/tests/pdcstr.rs
tests/pdcstr.rs
use std::{fs, process::Command}; #[test] fn try_build() { // as different macros are used depending on the os -> copy the correct contents to the .stderr fil. let family = if cfg!(windows) { "windows" } else { "other" }; fs::copy( format!( "tests/macro-build-tests/pdcstr-compile-fail.{}.stderr", family ), "tests/macro-build-tests/pdcstr-compile-fail.stderr", ) .unwrap(); let t = trybuild::TestCases::new(); t.pass("tests/macro-build-tests/pdcstr-pass.rs"); t.compile_fail("tests/macro-build-tests/pdcstr-compile-fail.rs"); } #[test] fn correct_reexports() { // check that macro dependencies are correctly exported and do not need to be manually referenced by the consuming crate. let exit_status = Command::new("cargo") .arg("build") .arg("--target") .arg(current_platform::CURRENT_PLATFORM) .current_dir("tests/macro-test-crate") .spawn() .unwrap() .wait() .unwrap(); assert!(exit_status.success()); }
rust
MIT
4742a5d235b279a35b235bf7726c5afb9bde521d
2026-01-04T20:18:20.341772Z
false
OpenByteDev/netcorehost
https://github.com/OpenByteDev/netcorehost/blob/4742a5d235b279a35b235bf7726c5afb9bde521d/tests/load_assembly_manually.rs
tests/load_assembly_manually.rs
#![cfg(feature = "net8_0")] use netcorehost::{nethost, pdcstr}; use rusty_fork::rusty_fork_test; use std::fs; #[path = "common.rs"] mod common; rusty_fork_test! { #[test] fn load_from_path() { common::setup(); let hostfxr = nethost::load_hostfxr().unwrap(); let context = hostfxr .initialize_for_runtime_config(common::test_runtime_config_path()) .unwrap(); context .load_assembly_from_path(common::library_dll_path()) .unwrap(); let fn_loader = context .get_delegate_loader_for_assembly(common::library_dll_path()) .unwrap(); let hello = fn_loader .get_function_with_unmanaged_callers_only::<fn() -> i32>( pdcstr!("ClassLibrary.Library, ClassLibrary"), pdcstr!("Hello"), ) .unwrap(); let result = hello(); assert_eq!(result, 42); } #[test] fn load_from_bytes() { common::setup(); let hostfxr = nethost::load_hostfxr().unwrap(); let context = hostfxr .initialize_for_runtime_config(common::test_runtime_config_path()) .unwrap(); let assembly_bytes = fs::read(common::library_dll_path().to_os_string()).unwrap(); let symbol_bytes = fs::read(common::library_symbols_path().to_os_string()).unwrap(); context .load_assembly_from_bytes(assembly_bytes, symbol_bytes) .unwrap(); let fn_loader = context .get_delegate_loader_for_assembly(common::library_dll_path()) .unwrap(); let hello = fn_loader .get_function_with_unmanaged_callers_only::<fn() -> i32>( pdcstr!("ClassLibrary.Library, ClassLibrary"), pdcstr!("Hello"), ) .unwrap(); let result = hello(); assert_eq!(result, 42); } }
rust
MIT
4742a5d235b279a35b235bf7726c5afb9bde521d
2026-01-04T20:18:20.341772Z
false
OpenByteDev/netcorehost
https://github.com/OpenByteDev/netcorehost/blob/4742a5d235b279a35b235bf7726c5afb9bde521d/tests/error_writer.rs
tests/error_writer.rs
#![allow(deprecated)] use netcorehost::{hostfxr::Hostfxr, nethost, pdcstr}; use rusty_fork::rusty_fork_test; use std::cell::Cell; #[path = "common.rs"] mod common; fn cause_error(hostfxr: &Hostfxr) { let bad_path = pdcstr!("bad.runtimeconfig.json"); let _ = hostfxr.initialize_for_runtime_config(bad_path); } rusty_fork_test! { #[test] #[cfg(feature = "netcore3_0")] fn gets_called() { common::setup(); let hostfxr = nethost::load_hostfxr().unwrap(); let was_called = Box::leak(Box::new(Cell::new(false))); hostfxr.set_error_writer(Some(Box::new( |_| { was_called.set(true); } ))); cause_error(&hostfxr); assert!(was_called.get()); } #[test] #[cfg(feature = "netcore3_0")] fn can_be_replaced() { common::setup(); let hostfxr = nethost::load_hostfxr().unwrap(); let counter = Box::leak(Box::new(Cell::new(0))); hostfxr.set_error_writer(Some(Box::new( |_| { counter.set(counter.get() + 1); } ))); cause_error(&hostfxr); hostfxr.set_error_writer(Some(Box::new( |_| { } ))); cause_error(&hostfxr); hostfxr.set_error_writer(Some(Box::new( |_| { counter.set(counter.get() + 1); } ))); cause_error(&hostfxr); hostfxr.set_error_writer(None); cause_error(&hostfxr); assert_eq!(counter.get(), 2); } }
rust
MIT
4742a5d235b279a35b235bf7726c5afb9bde521d
2026-01-04T20:18:20.341772Z
false
OpenByteDev/netcorehost
https://github.com/OpenByteDev/netcorehost/blob/4742a5d235b279a35b235bf7726c5afb9bde521d/tests/primary_and_secondary.rs
tests/primary_and_secondary.rs
#![cfg(feature = "netcore3_0")] use netcorehost::nethost; use rusty_fork::rusty_fork_test; #[path = "common.rs"] mod common; rusty_fork_test! { #[test] fn primary_is_primary() { common::setup(); let hostfxr = nethost::load_hostfxr().unwrap(); let context = hostfxr .initialize_for_runtime_config(common::test_runtime_config_path()) .unwrap(); assert!(context.is_primary()); context.close().unwrap(); } #[test] fn secondary_is_secondary() { common::setup(); let hostfxr = nethost::load_hostfxr().unwrap(); let context = hostfxr .initialize_for_dotnet_command_line(common::test_dll_path()) .unwrap(); assert!(context.is_primary()); context.run_app().as_hosting_exit_code().unwrap(); let context2 = hostfxr .initialize_for_runtime_config(common::test_runtime_config_path()) .unwrap(); assert!(!context2.is_primary()); context2.close().unwrap(); } }
rust
MIT
4742a5d235b279a35b235bf7726c5afb9bde521d
2026-01-04T20:18:20.341772Z
false
OpenByteDev/netcorehost
https://github.com/OpenByteDev/netcorehost/blob/4742a5d235b279a35b235bf7726c5afb9bde521d/tests/common.rs
tests/common.rs
#![allow(unused)] use netcorehost::pdcstring::PdCString; use path_absolutize::Absolutize; use std::{ env, path::{Path, PathBuf}, process::Command, str::FromStr, }; pub fn test_netcore_version() -> String { env::var("NETCOREHOST_TEST_NETCORE_VERSION").unwrap_or_else(|_| "net10.0".to_string()) } pub fn test_project_file_path() -> PathBuf { PathBuf::from_str(&format!( "tests/Test/Test-{}.csproj", test_netcore_version() )) .unwrap() .absolutize() .unwrap() .to_path_buf() } pub fn test_runtime_config_path() -> PdCString { PdCString::from_os_str( PathBuf::from_str(&format!( "tests/Test/bin/Debug/{}/Test.runtimeconfig.json", test_netcore_version() )) .unwrap() .absolutize() .unwrap() .as_os_str(), ) .unwrap() } pub fn test_dll_path() -> PdCString { PdCString::from_os_str( PathBuf::from_str(&format!( "tests/Test/bin/Debug/{}/Test.dll", test_netcore_version() )) .unwrap() .absolutize() .unwrap() .as_os_str(), ) .unwrap() } pub fn library_project_file_path() -> PathBuf { PathBuf::from_str(&format!( "tests/ClassLibrary/ClassLibrary-{}.csproj", test_netcore_version() )) .unwrap() .absolutize() .unwrap() .to_path_buf() } pub fn library_symbols_path() -> PdCString { PdCString::from_os_str( PathBuf::from_str(&format!( "tests/ClassLibrary/bin/Debug/{}/ClassLibrary.pdb", test_netcore_version() )) .unwrap() .absolutize() .unwrap() .as_os_str(), ) .unwrap() } pub fn library_dll_path() -> PdCString { PdCString::from_os_str( PathBuf::from_str(&format!( "tests/ClassLibrary/bin/Debug/{}/ClassLibrary.dll", test_netcore_version() )) .unwrap() .absolutize() .unwrap() .as_os_str(), ) .unwrap() } pub fn display_framework_id(id: &str) -> String { let s = id.trim_start_matches('.'); if let Some(rest) = s.strip_prefix("netcoreapp") { // .netcoreappX.Y → .NET Core X.Y let version = rest.trim_start_matches('.'); return format!(".NET Core {}", version); } if let Some(rest) = s.strip_prefix("net") { // .netX.Y → .NET X.Y let version = rest.trim_start_matches('.'); return format!(".NET {}", version); } // Fallback id.to_string() } pub fn setup() { println!("Running Test Setup"); println!("Using {}", display_framework_id(&test_netcore_version())); println!("Building Test Project"); build_test_project(); println!("Building Library Project"); build_library_project(); } pub fn build_test_project() { if Path::new(&test_dll_path().to_os_string()).exists() { return; } let netcore_version = test_netcore_version(); let project_file_path = test_project_file_path(); let project_dir = project_file_path.parent().unwrap(); Command::new("dotnet") .arg("build") .arg(&project_file_path) .arg("--framework") .arg(netcore_version) .current_dir(project_dir) .spawn() .expect("dotnet build failed") .wait() .expect("dotnet build failed"); } pub fn build_library_project() { if Path::new(&library_dll_path().to_os_string()).exists() { return; } let netcore_version = test_netcore_version(); let project_file_path = library_project_file_path(); let project_dir = project_file_path.parent().unwrap(); Command::new("dotnet") .arg("build") .arg(&project_file_path) .arg("--framework") .arg(netcore_version) .current_dir(project_dir) .spawn() .expect("dotnet build failed") .wait() .expect("dotnet build failed"); }
rust
MIT
4742a5d235b279a35b235bf7726c5afb9bde521d
2026-01-04T20:18:20.341772Z
false
OpenByteDev/netcorehost
https://github.com/OpenByteDev/netcorehost/blob/4742a5d235b279a35b235bf7726c5afb9bde521d/tests/unmanaged_callers_only.rs
tests/unmanaged_callers_only.rs
#![cfg(feature = "netcore3_0")] use netcorehost::{nethost, pdcstr}; use rusty_fork::rusty_fork_test; #[path = "common.rs"] mod common; rusty_fork_test! { fn unmanaged_caller_hello_world() { common::setup(); let hostfxr = nethost::load_hostfxr().unwrap(); let context = hostfxr .initialize_for_runtime_config(common::test_runtime_config_path()) .unwrap(); let fn_loader = context .get_delegate_loader_for_assembly(common::test_dll_path()) .unwrap(); let hello = fn_loader .get_function_with_unmanaged_callers_only::<fn() -> i32>( pdcstr!("Test.Program, Test"), pdcstr!("UnmanagedHello"), ) .unwrap(); let result = hello(); assert_eq!(result, 42); } }
rust
MIT
4742a5d235b279a35b235bf7726c5afb9bde521d
2026-01-04T20:18:20.341772Z
false
OpenByteDev/netcorehost
https://github.com/OpenByteDev/netcorehost/blob/4742a5d235b279a35b235bf7726c5afb9bde521d/tests/sdk_resolve.rs
tests/sdk_resolve.rs
use netcorehost::{nethost, pdcstr, pdcstring::PdCString}; use std::{ path::{Path, PathBuf}, process::Command, }; #[path = "common.rs"] mod common; #[test] #[cfg(feature = "netcore3_0")] fn resolve_sdk() { let hostfxr = nethost::load_hostfxr().unwrap(); let actual_sdks = get_sdks(); let sdks_dir = actual_sdks .first() .unwrap() .parent() .unwrap() .parent() .unwrap(); let sdk = hostfxr .resolve_sdk( &PdCString::from_os_str(sdks_dir).unwrap(), pdcstr!("."), true, ) .unwrap(); assert!(actual_sdks.contains(&sdk.sdk_dir)); } #[test] #[cfg(feature = "netcore3_0")] fn list_sdks() { let hostfxr = nethost::load_hostfxr().unwrap(); let mut actual_sdks = get_sdks(); let sdks_dir = actual_sdks .first() .unwrap() .parent() .unwrap() .parent() .unwrap(); let mut sdks = hostfxr.get_available_sdks_with_dotnet_path(&PdCString::from_os_str(sdks_dir).unwrap()); sdks.sort(); actual_sdks.sort(); assert_eq!(actual_sdks, sdks); } #[test] #[cfg(feature = "netcore2_1")] fn get_native_search_directories() { common::setup(); let hostfxr = nethost::load_hostfxr().unwrap(); hostfxr .get_native_search_directories(&common::test_dll_path()) .unwrap(); } fn get_sdks() -> Vec<PathBuf> { let sdks_output = Command::new("dotnet").arg("--list-sdks").output().unwrap(); assert!(sdks_output.status.success()); String::from_utf8_lossy(&sdks_output.stdout) .lines() .map(|line| { let (version, path) = line.split_once(' ').unwrap(); Path::new(&path[1..(path.len() - 1)]).join(version) }) .collect::<Vec<_>>() }
rust
MIT
4742a5d235b279a35b235bf7726c5afb9bde521d
2026-01-04T20:18:20.341772Z
false
OpenByteDev/netcorehost
https://github.com/OpenByteDev/netcorehost/blob/4742a5d235b279a35b235bf7726c5afb9bde521d/tests/macro-build-tests/pdcstr-compile-fail.rs
tests/macro-build-tests/pdcstr-compile-fail.rs
fn main() { // with internal nul let _ = netcorehost::pdcstr!("\0"); let _ = netcorehost::pdcstr!("somerandomteststring\0"); let _ = netcorehost::pdcstr!("somerandomteststring\0somerandomteststring"); }
rust
MIT
4742a5d235b279a35b235bf7726c5afb9bde521d
2026-01-04T20:18:20.341772Z
false
OpenByteDev/netcorehost
https://github.com/OpenByteDev/netcorehost/blob/4742a5d235b279a35b235bf7726c5afb9bde521d/tests/macro-build-tests/pdcstr-pass.rs
tests/macro-build-tests/pdcstr-pass.rs
fn main() { let _ = netcorehost::pdcstr!(""); let _ = netcorehost::pdcstr!("test"); let _ = netcorehost::pdcstr!("test with spaces"); let _ = netcorehost::pdcstr!("0"); let _ = netcorehost::pdcstr!("\\0"); let _ = netcorehost::pdcstr!("κόσμε"); }
rust
MIT
4742a5d235b279a35b235bf7726c5afb9bde521d
2026-01-04T20:18:20.341772Z
false
OpenByteDev/netcorehost
https://github.com/OpenByteDev/netcorehost/blob/4742a5d235b279a35b235bf7726c5afb9bde521d/tests/macro-test-crate/src/main.rs
tests/macro-test-crate/src/main.rs
fn main() { let _ = netcorehost::pdcstr!("test"); }
rust
MIT
4742a5d235b279a35b235bf7726c5afb9bde521d
2026-01-04T20:18:20.341772Z
false
OpenByteDev/netcorehost
https://github.com/OpenByteDev/netcorehost/blob/4742a5d235b279a35b235bf7726c5afb9bde521d/examples/run-app/main.rs
examples/run-app/main.rs
use netcorehost::{nethost, pdcstr}; fn main() { let hostfxr = nethost::load_hostfxr().unwrap(); let context = hostfxr .initialize_for_dotnet_command_line(pdcstr!( "examples/run-app/ExampleProject/bin/Debug/net10.0/ExampleProject.dll" )) .unwrap(); context.run_app().as_hosting_exit_code().unwrap(); }
rust
MIT
4742a5d235b279a35b235bf7726c5afb9bde521d
2026-01-04T20:18:20.341772Z
false
OpenByteDev/netcorehost
https://github.com/OpenByteDev/netcorehost/blob/4742a5d235b279a35b235bf7726c5afb9bde521d/examples/call-managed-function/main.rs
examples/call-managed-function/main.rs
use netcorehost::{nethost, pdcstr}; fn main() { let hostfxr = nethost::load_hostfxr().unwrap(); let context = hostfxr.initialize_for_runtime_config(pdcstr!("examples/call-managed-function/ExampleProject/bin/Debug/net10.0/ExampleProject.runtimeconfig.json")).unwrap(); let delegate_loader = context .get_delegate_loader_for_assembly(pdcstr!( "examples/call-managed-function/ExampleProject/bin/Debug/net10.0/ExampleProject.dll" )) .unwrap(); let hello_world1 = delegate_loader .get_function::<fn()>( pdcstr!("ExampleProject.Program, ExampleProject"), pdcstr!("HelloWorld1"), pdcstr!("ExampleProject.Program+HelloWorld1Delegate, ExampleProject"), ) .unwrap(); hello_world1(); let hello_world2 = delegate_loader .get_function_with_unmanaged_callers_only::<fn()>( pdcstr!("ExampleProject.Program, ExampleProject"), pdcstr!("HelloWorld2"), ) .unwrap(); hello_world2(); let hello_world3 = delegate_loader .get_function_with_default_signature( pdcstr!("ExampleProject.Program, ExampleProject"), pdcstr!("HelloWorld3"), ) .unwrap(); unsafe { hello_world3(std::ptr::null(), 0) }; }
rust
MIT
4742a5d235b279a35b235bf7726c5afb9bde521d
2026-01-04T20:18:20.341772Z
false
OpenByteDev/netcorehost
https://github.com/OpenByteDev/netcorehost/blob/4742a5d235b279a35b235bf7726c5afb9bde521d/examples/return-string-from-managed/main.rs
examples/return-string-from-managed/main.rs
#![warn(unsafe_op_in_unsafe_fn)] // See also call-native-function example use core::slice; use std::{ ffi::{CStr, CString}, mem::{self, MaybeUninit}, os::raw::c_char, str::Utf8Error, string::FromUtf16Error, }; use netcorehost::{ hostfxr::{AssemblyDelegateLoader, ManagedFunction}, nethost, pdcstr, }; use std::sync::OnceLock; fn main() { let hostfxr = nethost::load_hostfxr().unwrap(); let context = hostfxr.initialize_for_runtime_config(pdcstr!("examples/return-string-from-managed/ExampleProject/bin/Debug/net10.0/ExampleProject.runtimeconfig.json")).unwrap(); let delegate_loader = context .get_delegate_loader_for_assembly(pdcstr!( "examples/return-string-from-managed/ExampleProject/bin/Debug/net10.0/ExampleProject.dll" )) .unwrap(); print_string_from_csharp_using_c_string(&delegate_loader); print_string_from_csharp_using_unmanaged_alloc(&delegate_loader); print_string_from_csharp_using_gc_handle(&delegate_loader); print_string_from_csharp_using_rust_allocate(&delegate_loader); } // Method 1: using CString fn print_string_from_csharp_using_c_string(delegate_loader: &AssemblyDelegateLoader) { let set_copy_to_c_string = delegate_loader .get_function_with_unmanaged_callers_only::<fn(f: unsafe extern "system" fn(*const u16, i32) -> *mut c_char)>( pdcstr!("ExampleProject.Method1, ExampleProject"), pdcstr!("SetCopyToCStringFunctionPtr"), ) .unwrap(); set_copy_to_c_string(copy_to_c_string); let get_name = delegate_loader .get_function_with_unmanaged_callers_only::<fn() -> *mut c_char>( pdcstr!("ExampleProject.Method1, ExampleProject"), pdcstr!("GetNameAsCString"), ) .unwrap(); let name_ptr = get_name(); let name = unsafe { CString::from_raw(name_ptr) }; println!("{}", name.to_string_lossy()); } unsafe extern "system" fn copy_to_c_string(ptr: *const u16, length: i32) -> *mut c_char { let wide_chars = unsafe { slice::from_raw_parts(ptr, length as usize) }; let string = String::from_utf16_lossy(wide_chars); let c_string = match CString::new(string) { Ok(c_string) => c_string, Err(_) => return std::ptr::null_mut(), }; c_string.into_raw() } // Method 2: using GCHandle fn print_string_from_csharp_using_unmanaged_alloc(delegate_loader: &AssemblyDelegateLoader) { // one time setup let free_h_global = delegate_loader .get_function_with_unmanaged_callers_only::<fn(*const u8)>( pdcstr!("ExampleProject.Method2, ExampleProject"), pdcstr!("FreeUnmanagedMemory"), ) .unwrap(); FREE_H_GLOBAL .set(free_h_global) .expect("string interop already init"); // actual usage let get_name = delegate_loader .get_function_with_unmanaged_callers_only::<fn() -> *const u8>( pdcstr!("ExampleProject.Method2, ExampleProject"), pdcstr!("GetNameAsUnmanagedMemory"), ) .unwrap(); let name_h_global = get_name(); let name = unsafe { HGlobalString::from_h_global(name_h_global) }; println!("{}", name.as_str().unwrap()); } static FREE_H_GLOBAL: OnceLock<ManagedFunction<extern "system" fn(*const u8)>> = OnceLock::new(); struct HGlobalString { ptr: *const u8, len: usize, } impl HGlobalString { pub unsafe fn from_h_global(ptr: *const u8) -> Self { let len = unsafe { CStr::from_ptr(ptr.cast()) }.to_bytes().len(); Self { ptr, len } } #[allow(dead_code)] pub fn as_bytes(&self) -> &[u8] { unsafe { slice::from_raw_parts(self.ptr, self.len) } } pub fn as_bytes_with_nul(&self) -> &[u8] { unsafe { slice::from_raw_parts(self.ptr, self.len + 1) } } pub fn as_c_str(&self) -> &CStr { unsafe { CStr::from_bytes_with_nul_unchecked(self.as_bytes_with_nul()) } } pub fn as_str(&self) -> Result<&str, Utf8Error> { self.as_c_str().to_str() } } impl Drop for HGlobalString { fn drop(&mut self) { FREE_H_GLOBAL.get().expect("string interop not init")(self.ptr); } } // Method 3: using GCHandle fn print_string_from_csharp_using_gc_handle(delegate_loader: &AssemblyDelegateLoader) { // one time setup let free_gc_handle_string = delegate_loader .get_function_with_unmanaged_callers_only::<fn(*const *const u16)>( pdcstr!("ExampleProject.Method3, ExampleProject"), pdcstr!("FreeGCHandleString"), ) .unwrap(); FREE_GC_HANDLE_STRING .set(free_gc_handle_string) .expect("string interop already init"); let get_string_data_offset = delegate_loader .get_function_with_unmanaged_callers_only::<fn() -> usize>( pdcstr!("ExampleProject.Method3, ExampleProject"), pdcstr!("GetStringDataOffset"), ) .unwrap(); let string_data_offset = get_string_data_offset(); STRING_DATA_OFFSET .set(string_data_offset) .expect("string interop already init"); // actual usage let get_name = delegate_loader .get_function_with_unmanaged_callers_only::<fn() -> *const *const u16>( pdcstr!("ExampleProject.Method3, ExampleProject"), pdcstr!("GetNameAsGCHandle"), ) .unwrap(); let name_gc_handle = get_name(); let name = unsafe { GcHandleString::from_gc_handle(name_gc_handle) }; println!("{}", name.to_string_lossy()); } static FREE_GC_HANDLE_STRING: OnceLock<ManagedFunction<extern "system" fn(*const *const u16)>> = OnceLock::new(); static STRING_DATA_OFFSET: OnceLock<usize> = OnceLock::new(); struct GcHandleString(*const *const u16); impl GcHandleString { pub unsafe fn from_gc_handle(ptr: *const *const u16) -> Self { Self(ptr) } pub fn data_ptr(&self) -> *const u16 { // convert the handle pointer to the actual string pointer by removing the mark. let unmarked_ptr = (self.0 as usize & !1usize) as *const *const u16; let string_ptr = unsafe { *unmarked_ptr }; let string_data_offset = *STRING_DATA_OFFSET.get().expect("string interop not init"); unsafe { string_ptr.byte_add(string_data_offset) }.cast::<u16>() } pub fn len(&self) -> usize { // read the length of the string which is stored in front of the data. let len_ptr = unsafe { self.data_ptr().byte_sub(mem::size_of::<i32>()) }.cast::<i32>(); unsafe { *len_ptr as usize } } pub fn wide_chars(&self) -> &[u16] { unsafe { slice::from_raw_parts(self.data_ptr(), self.len()) } } #[allow(dead_code)] pub fn to_string(&self) -> Result<String, FromUtf16Error> { String::from_utf16(self.wide_chars()) } pub fn to_string_lossy(&self) -> String { String::from_utf16_lossy(self.wide_chars()) } } impl Drop for GcHandleString { fn drop(&mut self) { FREE_GC_HANDLE_STRING .get() .expect("string interop not init")(self.0); } } // Method 4: using rust allocate fn print_string_from_csharp_using_rust_allocate(delegate_loader: &AssemblyDelegateLoader) { // one time setup let set_rust_allocate_memory = delegate_loader .get_function_with_unmanaged_callers_only::<fn(extern "system" fn(usize, *mut RawVec<u8>))>( pdcstr!("ExampleProject.Method4, ExampleProject"), pdcstr!("SetRustAllocateMemory"), ) .unwrap(); set_rust_allocate_memory(rust_allocate_memory); // actual usage let get_name = delegate_loader .get_function_with_unmanaged_callers_only::<fn(*mut RawVec<u8>)>( pdcstr!("ExampleProject.Method4, ExampleProject"), pdcstr!("GetNameIntoRustVec"), ) .unwrap(); let mut name_raw_vec = MaybeUninit::uninit(); get_name(name_raw_vec.as_mut_ptr()); let name_raw_vec = unsafe { name_raw_vec.assume_init() }; let name_vec = unsafe { Vec::from_raw_parts(name_raw_vec.data, name_raw_vec.len, name_raw_vec.capacity) }; let name = String::from_utf8(name_vec).unwrap(); println!("{}", name); } extern "system" fn rust_allocate_memory(size: usize, vec: *mut RawVec<u8>) { let mut buf = Vec::<u8>::with_capacity(size); unsafe { *vec = RawVec { data: buf.as_mut_ptr(), len: buf.len(), capacity: buf.capacity(), } }; mem::forget(buf); } #[repr(C)] struct RawVec<T> { data: *mut T, len: usize, capacity: usize, }
rust
MIT
4742a5d235b279a35b235bf7726c5afb9bde521d
2026-01-04T20:18:20.341772Z
false
OpenByteDev/netcorehost
https://github.com/OpenByteDev/netcorehost/blob/4742a5d235b279a35b235bf7726c5afb9bde521d/examples/call-native-function/main.rs
examples/call-native-function/main.rs
// Note that this example requires the unstable rustc flag "-Z export-executable-symbols" use netcorehost::{nethost, pdcstr}; #[no_mangle] pub extern "system" fn rusty_increment(n: i32) -> i32 { println!("Called rusty increment with {n}"); n + 1 } fn main() { let hostfxr = nethost::load_hostfxr().unwrap(); let context = hostfxr.initialize_for_runtime_config(pdcstr!("examples/call-native-function/ExampleProject/bin/Debug/net10.0/ExampleProject.runtimeconfig.json")).unwrap(); let delegate_loader = context .get_delegate_loader_for_assembly(pdcstr!( "examples/call-native-function/ExampleProject/bin/Debug/net10.0/ExampleProject.dll" )) .unwrap(); let increment1 = delegate_loader .get_function_with_unmanaged_callers_only::<fn(i32) -> i32>( pdcstr!("ExampleProject.Program, ExampleProject"), pdcstr!("IndirectIncrement1"), ) .unwrap(); #[cfg(windows)] let increment2 = delegate_loader .get_function_with_unmanaged_callers_only::<fn(i32) -> i32>( pdcstr!("ExampleProject.Program, ExampleProject"), pdcstr!("IndirectIncrement2"), ) .unwrap(); assert_eq!(2, increment1(1)); #[cfg(windows)] assert_eq!(3, increment2(2)); }
rust
MIT
4742a5d235b279a35b235bf7726c5afb9bde521d
2026-01-04T20:18:20.341772Z
false
OpenByteDev/netcorehost
https://github.com/OpenByteDev/netcorehost/blob/4742a5d235b279a35b235bf7726c5afb9bde521d/examples/run-app-with-args/main.rs
examples/run-app-with-args/main.rs
use std::env; use netcorehost::{nethost, pdcstr, pdcstring::PdCString}; fn main() { let hostfxr = nethost::load_hostfxr().unwrap(); let args = env::args() .skip(1) // skip rust host program name .map(|arg| PdCString::from_os_str(arg).unwrap()); let context = hostfxr .initialize_for_dotnet_command_line_with_args( pdcstr!( "examples/run-app-with-args/ExampleProject/bin/Debug/net10.0/ExampleProject.dll" ), args, ) .unwrap(); let result = context.run_app().value(); println!("Exit code: {}", result); }
rust
MIT
4742a5d235b279a35b235bf7726c5afb9bde521d
2026-01-04T20:18:20.341772Z
false
OpenByteDev/netcorehost
https://github.com/OpenByteDev/netcorehost/blob/4742a5d235b279a35b235bf7726c5afb9bde521d/examples/passing-parameters/main.rs
examples/passing-parameters/main.rs
use netcorehost::{hostfxr::AssemblyDelegateLoader, nethost, pdcstr}; fn main() { let hostfxr = nethost::load_hostfxr().unwrap(); let context = hostfxr.initialize_for_runtime_config(pdcstr!("examples/passing-parameters/ExampleProject/bin/Debug/net10.0/ExampleProject.runtimeconfig.json")).unwrap(); let delegate_loader = context .get_delegate_loader_for_assembly(pdcstr!( "examples/passing-parameters/ExampleProject/bin/Debug/net10.0/ExampleProject.dll" )) .unwrap(); print_utf8_example(&delegate_loader); print_utf16_example(&delegate_loader); is_palindrom_example(&delegate_loader); get_length_example(&delegate_loader); } fn print_utf8_example(delegate_loader: &AssemblyDelegateLoader) { let print_utf8 = delegate_loader .get_function_with_unmanaged_callers_only::<fn(text_ptr: *const u8, text_length: i32)>( pdcstr!("ExampleProject.Program, ExampleProject"), pdcstr!("PrintUtf8"), ) .unwrap(); let test_string = "Hello World!"; print_utf8(test_string.as_ptr(), test_string.len() as i32); } fn print_utf16_example(delegate_loader: &AssemblyDelegateLoader) { let print_utf16 = delegate_loader .get_function_with_unmanaged_callers_only::<fn(text_ptr: *const u16, text_length: i32)>( pdcstr!("ExampleProject.Program, ExampleProject"), pdcstr!("PrintUtf16"), ) .unwrap(); let test_string = widestring::U16String::from_str("Hello World!"); print_utf16(test_string.as_ptr(), test_string.len() as i32); } fn is_palindrom_example(delegate_loader: &AssemblyDelegateLoader) { let is_palindrom = delegate_loader .get_function_with_unmanaged_callers_only::<fn(text_ptr: *const u16, text_length: i32) -> i32>( pdcstr!("ExampleProject.Program, ExampleProject"), pdcstr!("IsPalindrom"), ) .unwrap(); for s in ["Racecar", "stats", "hello", "test"].iter() { let widestring = widestring::U16String::from_str(s); let palindrom_answer = if is_palindrom(widestring.as_ptr(), widestring.len() as i32) != 0 { "Yes" } else { "No" }; println!("Is '{}' a palindrom? {}!", s, palindrom_answer); } } fn get_length_example(delegate_loader: &AssemblyDelegateLoader) { let get_length = delegate_loader .get_function_with_unmanaged_callers_only::<fn(text_ptr: *const Vector2f) -> f32>( pdcstr!("ExampleProject.Program, ExampleProject"), pdcstr!("GetLength"), ) .unwrap(); let vec = Vector2f { x: 3.0f32, y: 4.0f32, }; let length = get_length(&vec); println!("The length of {:?} is {:?}", vec, length); } #[derive(Debug)] #[repr(C)] struct Vector2f { x: f32, y: f32, }
rust
MIT
4742a5d235b279a35b235bf7726c5afb9bde521d
2026-01-04T20:18:20.341772Z
false
teenjuna/prae
https://github.com/teenjuna/prae/blob/bd2bfd476108ebcfcb91c2710fdf92eb123a169d/prae/src/lib.rs
prae/src/lib.rs
#![cfg_attr(docsrs, feature(doc_cfg))] //! `prae` is a crate that aims to provide a better way to define types that //! require validation. //! //! The main concept of the library is the [`Wrapper`](crate::Wrapper) trait. //! This trait describes a //! [`Newtype`](https://rust-unofficial.github.io/patterns/patterns/behavioural/newtype.html) //! wrapper struct that contains some inner value and provides methods to //! construct, read and mutate it. //! //! The easiest way to create a type that implements [`Wrapper`](crate::Wrapper) //! is to use [`define!`](crate::define) and [`extend!`](crate::extend) macros. //! //! # Example //! Suppose you want to create a type `Username`. You want this type to be a //! `String`, and you don't want it to be empty. Traditionally, you would create //! a wrapper struct with getter and setter functions, like this simplified //! example: //! ``` //! #[derive(Debug)] //! pub struct Username(String); //! //! impl Username { //! pub fn new(username: &str) -> Result<Self, &'static str> { //! let username = username.trim().to_owned(); //! if username.is_empty() { //! Err("value is invalid") //! } else { //! Ok(Self(username)) //! } //! } //! //! pub fn get(&self) -> &str { //! &self.0 //! } //! //! pub fn set(&mut self, username: &str) -> Result<(), &'static str> { //! let username = username.trim().to_owned(); //! if username.is_empty() { //! Err("value is invalid") //! } else { //! self.0 = username; //! Ok(()) //! } //! } //! } //! //! let username = Username::new(" my username ").unwrap(); //! assert_eq!(username.get(), "my username"); //! //! let err = Username::new(" ").unwrap_err(); //! assert_eq!(err, "value is invalid"); //! ``` //! //! Using `prae`, you will do it like this: //! ``` //! use prae::Wrapper; //! //! prae::define! { //! #[derive(Debug)] //! pub Username: String; //! adjust |username| *username = username.trim().to_owned(); //! ensure |username| !username.is_empty(); //! } //! //! let username = Username::new(" my username ").unwrap(); //! assert_eq!(username.get(), "my username"); //! //! let err = Username::new(" ").unwrap_err(); //! assert_eq!(err.original, "value is invalid"); //! assert_eq!(err.value, ""); //! ``` //! //! Futhermore, `prae` allows you to use custom errors and extend your types. //! See docs for [`define!`](crate::define) and [`extend!`](crate::define) for //! more information and examples. //! //! # Compilation speed //! //! The macros provided by this crate are declarative, therefore make almost //! zero impact on the compilation speed. //! //! # Performarnce impact //! //! If you find yourself in a situation where the internal adjustment and //! validation of your type becomes a performance bottleneck (for example, you //! perform a heavy validation and mutate your type in a hot loop) - try //! `_unprocessed` variants of [`Wrapper`] methods. They won't call //! [`Wrapper::PROCESS`]. However, I strongly advise you to call //! [`Wrapper::verify`] after such operations. //! //! # Feature flags //! //! `prae` provides additional features: //! //! Name | Description //! ---|--- //! `serde` | Adds the [`impl_serde`] plugin. //! //! # Credits //! This crate was highly inspired by the //! [tightness](https://github.com/PabloMansanet/tightness) crate. It's basically //! just a fork of tightness with a slightly different philosophy. //! See [this](https://github.com/PabloMansanet/tightness/issues/2) issue for details. mod core; mod plugins; pub use crate::core::*; /// Convenience macro that creates a /// [`Newtype`](https://rust-unofficial.github.io/patterns/patterns/behavioural/newtype.html) /// wrapper struct that implements [`Wrapper`]. /// /// The macro accepts several arguments (see [macro structure](#macro-structure) /// for more info). By default, it generates a bare minimum of code: /// - The `Newtype` struct; /// - The implementation of the [`Wrapper`] for the struct; /// - The implementation of the [`AsRef`](AsRef); /// [`Borrow`](::core::borrow::Borrow), /// [`TryFrom`](TryFrom) and [`From`](From) traits for the struct. /// /// However, the generated code can be extended in using two methods: /// - Attribute macros attached to the type signature (e.g. `#[derive(Debug)]`); /// - Type plugins specified in the end of the macro. /// /// It is worth noting that the inner value of created `Newtype` struct can be /// accessed from the code in the same module. To fully protect this value from /// being accessed directly, put your type in a separate module. /// /// # Macro structure /// /// Table of contents: /// - [Type signature](#type-signature) /// - [`adjust` closure](#adjust-closure) /// - [`ensure` closure](#ensure-closure) /// - [`validate` closure](#validate-closure) /// - [Plugins](#plugins) /// /// ## Type signature /// /// This is the only required argument of the macro. It specifies the visibiliy /// and the name of the created struct, as well as it's inner type. For /// example, this /// ``` /// prae::define! { /// /// An ID of a user. /// pub UserID: i64; /// } /// /// prae::define! { /// /// A name of a user. /// Username: String; /// } /// ``` /// will expand into this: /// ``` /// /// An ID of a user. /// pub struct UserID(i64); /// // other impls... /// /// /// A name of a user. /// struct Username(String); /// // other impls... /// ``` /// You could also use attribute macros on top of your signature if you like. /// For example, this /// ``` /// prae::define! { /// #[derive(Debug, Clone)] /// pub Username: String; /// } /// ``` /// will expand into this: /// ``` /// #[derive(Debug, Clone)] /// pub struct Username(String); /// // other impls... /// ``` /// Meaning that your type now implements `Debug` and `Clone`. /// /// **Note**: check out /// [`derive_more`](https://docs.rs/derive_more/latest/derive_more/) /// for more derive macros. /// /// # `adjust` closure /// /// This argument specifies a closure that will be executed on every /// construction and mutation of the wrapper to make sure that it's value is /// adjusted properly. For example: /// ``` /// use prae::Wrapper; /// /// prae::define! { /// #[derive(Debug)] /// pub Text: String; /// adjust |text: &mut String| *text = text.trim().to_owned(); /// } /// /// let mut text = Text::new(" hello world! ").unwrap(); /// assert_eq!(text.get(), "hello world!"); /// /// text.set(" new value\n\n\n").unwrap(); /// assert_eq!(text.get(), "new value"); /// ``` /// /// # `ensure` closure /// /// This argument specifies a closure that will be executed on every /// construction and mutation of the wrapper to make sure that it's value is /// valid. For example: /// ``` /// use prae::Wrapper; /// /// prae::define! { /// #[derive(Debug)] /// pub Text: String; /// ensure |text: &String| !text.is_empty(); /// } /// /// assert!(Text::new("hello world").is_ok()); /// assert!(Text::new("").is_err()); /// ``` /// As you can see, the closure receives a shared reference to the inner value /// and returns `true` if the value is valid, and `false` if it's not. /// /// This closure is easy to use, but it has a downside: you can't customize your /// error type. The [`Wrapper::Error`] type will always /// be a `&'static str` with a generic error message: /// ``` /// # use prae::Wrapper; /// # prae::define! { /// # #[derive(Debug)] /// # pub Text: String; /// # ensure |text: &String| !text.is_empty(); /// # } /// let err = Text::new("").unwrap_err(); /// assert_eq!(err.original, "value is invalid"); /// assert_eq!( /// err.to_string(), /// "failed to construct type Text from value \"\": value is invalid", /// ) /// ``` /// If you want more control, use [`validate` closure](#validate-closure) /// closure described below. /// /// **Note**: /// - this closure can be used together with the [`adjust` /// closure](#adjust-closure) and will be executed after it; /// - this closure can't be used together with the [`validate` /// closure](#validate-closure). /// /// # `validate` closure /// This closure is similar to the [`ensure` closure](#ensure-closure), but uses /// custom error specified by the user: /// ``` /// use ::core::fmt; /// use prae::Wrapper; /// /// #[derive(Debug)] /// pub enum TextError { /// Empty, /// } /// /// // Required in order for `err.to_string()` to work. /// impl fmt::Display for TextError { /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { /// write!(f, "{}", match self { /// Self::Empty => "text is empty", /// }) /// } /// } /// /// prae::define! { /// #[derive(Debug)] /// pub Text: String; /// validate(TextError) |text: &String| { /// if text.is_empty() { /// Err(TextError::Empty) /// } else { /// Ok(()) /// } /// }; /// } /// /// let err = Text::new("").unwrap_err(); /// assert!(matches!(err.original, TextError::Empty)); /// assert_eq!( /// err.to_string(), /// "failed to construct type Text from value \"\": text is empty", /// ) /// ``` /// As you can see, the closure receives a shared reference to the inner value /// and returns `Ok(())` if the value is valid, and `Err(...)` if it’s not. /// /// **Note**: /// - this closure can be used together with the [`adjust` /// closure](#adjust-closure) and will be executed after it; /// - this closure can't be used together with the [`ensure` /// closure](#ensure-closure). /// /// # Plugins /// /// Sometimes attribute macros just dont't cut it. In this case, you have two /// options: /// - add manual `impl` to your type; /// - use plugins. /// /// In the context of this macro, plugin is just a macro that takes your type as /// an input and does something with it. /// /// For example, suppose we want our type to implement /// [`serde::Serialize`](::serde::Serialize) and /// [`serde::Deserialize`](::serde::Deserialize). We *could* use attribute /// macros: /// ``` /// use serde::{Serialize, Deserialize}; /// /// prae::define! { /// #[derive(Serialize, Deserialize)] /// pub Username: String; /// adjust |un| *un = un.trim().to_owned(); /// ensure |un| !un.is_empty(); /// } /// ``` /// However, this implementation won't use our `adjust` and `ensure` closures /// for the type deserialization. This means, that we can create `Username` with /// invalid data: /// ``` /// # use prae::Wrapper; /// # use serde::{Serialize, Deserialize}; /// # prae::define! { /// # #[derive(Serialize, Deserialize)] /// # pub Username: String; /// # adjust |un| *un = un.trim().to_owned(); /// # ensure |un| !un.is_empty(); /// # } /// // This won't work /// assert!(Username::new(" ").is_err()); /// /// // But this will /// let un: Username = serde_json::from_str("\" \"").unwrap(); /// assert_eq!(un.get(), " "); // not good /// ``` /// To avoid this, we need to add a custom implementation of /// [`serde::Deserialize`](::serde::Deserialize) for our type. Since the /// implementation is indentical for any type created with this crate, `prae` /// ships with a built-in (under `serde` feature) plugin called /// [`impl_serde`]. This plugin will implement both /// [`serde::Serialize`](::serde::Serialize) and /// [`serde::Deserialize`](::serde::Deserialize) the right way: /// ``` /// use prae::Wrapper; /// use serde::{Serialize, Deserialize}; /// /// prae::define! { /// #[derive(Debug)] /// pub Username: String; /// adjust |un| *un = un.trim().to_owned(); /// ensure |un| !un.is_empty(); /// plugins: [ /// prae::impl_serde, /// ]; /// } /// /// // This will work /// let un: Username = serde_json::from_str("\" qwerty \"").unwrap(); /// assert_eq!(un.get(), "qwerty"); /// /// // But this won't /// let err = serde_json::from_str::<Username>("\" \"").unwrap_err(); /// assert_eq!(err.to_string(), "value is invalid"); /// ``` /// You can implement your own plugins and use them for your types - it's easy. #[macro_export] macro_rules! define { // Required part: // - Optional attribute macro; // - Required type signature; // - Optional closures. // - Optional plugins. { $(#[$meta:meta])* $vis:vis $wrapper:ident: $inner:ty; $(adjust $adjust:expr;)? $(ensure $ensure:expr;)? $(validate($err:ty) $validate:expr;)? $(plugins: [$($plugin:path),+ $(,)?];)? } => { $(#[$meta])* $vis struct $wrapper($inner); impl $crate::Wrapper for $wrapper { const NAME: &'static str = stringify!($wrapper); type Inner = $inner; $crate::define!( $(adjust $adjust;)? $(ensure $ensure;)? $(validate($err) $validate;)? ); $crate::__impl_wrapper_methods!(); } $crate::__impl_external_traits!($wrapper, $inner); $($($plugin!($wrapper);)*)? }; // Optional closures 1: // - Optional `adjust` closure. { $(adjust $adjust:expr;)? } => { type Error = ::core::convert::Infallible; const PROCESS: fn(&mut Self::Inner) -> Result<(), Self::Error> = |mut _v| { $({ let adjust: fn(&mut Self::Inner) = $adjust; adjust(&mut _v); })? Ok(()) }; }; // Optional closures 2: // - Optional `adjust` closure. // - Required `ensure` closure. { $(adjust $adjust:expr;)? ensure $ensure:expr; } => { type Error = &'static str; const PROCESS: fn(&mut Self::Inner) -> Result<(), Self::Error> = |mut _v| { $({ let adjust: fn(&mut Self::Inner) = $adjust; adjust(&mut _v); })? { let ensure: fn(&Self::Inner) -> bool = $ensure; if !ensure(&_v) { return Err("value is invalid") } } Ok(()) }; }; // Optional closures 3: // - Optional `adjust` closure. // - Required `validate` closure. { $(adjust $adjust:expr;)? validate($err:ty) $validate:expr; } => { type Error = $err; const PROCESS: fn(&mut Self::Inner) -> Result<(), Self::Error> = |mut _v| { $({ let adjust: fn(&mut Self::Inner) = $adjust; adjust(&mut _v); })? { let validate: fn(&Self::Inner) -> Result<(), Self::Error> = $validate; if let Err(err) = validate(&_v) { return Err(err) } } Ok(()) }; } } /// Convenience macro that creates a /// [`Newtype`](https://rust-unofficial.github.io/patterns/patterns/behavioural/newtype.html) /// wrapper struct that implements [`Wrapper`] and extends another [`Wrapper`]. /// /// The usage of the macro is identical to the [`define!`](crate::define), so /// check out it's documentation to learn more. The only difference is the fact /// that the inner type specified in the type signature must implement /// [`Wrapper`]. /// /// The created struct will inherit the inner type of that another wrapper, and /// also will run that another wrapper's adjustment and validation closures /// before it's own adjustment and validation closures. For example: /// ``` /// use prae::Wrapper; /// /// prae::define! { /// pub Text: String; /// adjust |text| *text = text.trim().to_owned(); /// ensure |text| !text.is_empty(); /// } /// /// prae::extend! { /// #[derive(Debug)] /// pub Sentence: Text; /// ensure |sentence: &String| { /// // Note that `sentence` is a `&String`, not `&Text`! /// // It's value is already trimmed and checked for emptiness. /// // Now we only need to check conditions that are important /// // for the new type /// sentence.ends_with(&['.', '!', '?'][..]) /// }; /// } /// /// // It works /// let sentence = Sentence::new(" My sentence! ").unwrap(); /// assert_eq!(sentence.get(), "My sentence!"); /// /// // Doesn't pass the validation of `Text` /// assert!(Sentence::new(" ").is_err()); /// /// // Doesn't pass the validation of `Sentence` /// assert!(Sentence::new("Without punctuation").is_err()); /// ``` #[macro_export] macro_rules! extend { // Required part: // - Optional attribute macro; // - Required type signature; // - Optional closures. // - Optional plugins. { $(#[$meta:meta])* $vis:vis $wrapper:ident: $inner:ty; $(adjust $adjust:expr;)? $(ensure $ensure:expr;)? $(validate($err:ty) $validate:expr;)? $(plugins: [$($plugin:path),+ $(,)?];)? } => { $(#[$meta])* $vis struct $wrapper(<$inner as $crate::Wrapper>::Inner); impl $crate::Wrapper for $wrapper { const NAME: &'static str = stringify!($wrapper); type Inner = <$inner as $crate::Wrapper>::Inner; $crate::extend!( $inner; $(adjust $adjust;)? $(ensure $ensure;)? $(validate($err) $validate;)? ); $crate::__impl_wrapper_methods!(); } $crate::__impl_external_traits!($wrapper, <$inner as $crate::Wrapper>::Inner); $($($plugin!($wrapper);)*)? }; // Optional closures 1: // - Optional `adjust` closure. { $inner:ty; $(adjust $adjust:expr;)? } => { type Error = &'static str; const PROCESS: fn(&mut Self::Inner) -> Result<(), Self::Error> = |mut _v| { <$inner as $crate::Wrapper>::PROCESS(&mut _v)?; $({ let adjust: fn(&mut Self::Inner) = $adjust; adjust(&mut _v); })? Ok(()) }; }; // Optional closures 2: // - Optional `adjust` closure. // - Required `ensure` closure. { $inner:ty; $(adjust $adjust:expr;)? ensure $ensure:expr; } => { type Error = &'static str; const PROCESS: fn(&mut Self::Inner) -> Result<(), Self::Error> = |mut _v| { <$inner as $crate::Wrapper>::PROCESS(&mut _v)?; $({ let adjust: fn(&mut Self::Inner) = $adjust; adjust(&mut _v); })? { let ensure: fn(&Self::Inner) -> bool = $ensure; if !ensure(&_v) { return Err("value is invalid") } } Ok(()) }; }; // Optional closures 3: // - Optional `adjust` closure. // - Required `validate` closure. { $inner:ty; $(adjust $adjust:expr;)? validate($err:ty) $validate:expr; } => { type Error = $err; const PROCESS: fn(&mut Self::Inner) -> Result<(), Self::Error> = |mut _v| { <$inner as $crate::Wrapper>::PROCESS(&mut _v)?; $({ let adjust: fn(&mut Self::Inner) = $adjust; adjust(&mut _v); })? { let validate: fn(&Self::Inner) -> Result<(), Self::Error> = $validate; if let Err(err) = validate(&_v) { return Err(err) } } Ok(()) }; } } #[doc(hidden)] #[macro_export] macro_rules! __impl_wrapper_methods { () => { fn new(value: impl Into<Self::Inner>) -> Result<Self, $crate::ConstructionError<Self>> { let mut value = value.into(); match Self::PROCESS(&mut value) { Ok(()) => Ok(Self(value)), Err(original) => Err($crate::ConstructionError { original, value }), } } fn get(&self) -> &Self::Inner { &self.0 } fn set( &mut self, value: impl Into<Self::Inner>, ) -> Result<(), $crate::ConstructionError<Self>> { let mut value = value.into(); match Self::PROCESS(&mut value) { Ok(()) => { self.0 = value; Ok(()) } Err(original) => Err($crate::ConstructionError { original, value }), } } fn into_inner(self) -> Self::Inner { self.0 } fn __mutate_with( &mut self, clone: impl Fn(&Self::Inner) -> Self::Inner, f: impl FnOnce(&mut Self::Inner), ) -> Result<(), $crate::MutationError<Self>> { let mut value = clone(&self.0); f(&mut value); match Self::PROCESS(&mut value) { Ok(()) => { self.0 = value; Ok(()) } Err(original) => Err($crate::MutationError { original, old_value: clone(&self.0), new_value: value, }), } } fn new_unprocessed(value: impl Into<Self::Inner>) -> Self { let mut value = value.into(); debug_assert!(Self::PROCESS(&mut value).is_ok()); Self(value) } fn set_unprocessed(&mut self, value: impl Into<Self::Inner>) { let mut value = value.into(); debug_assert!(Self::PROCESS(&mut value).is_ok()); self.0 = value; } fn mutate_unprocessed(&mut self, f: impl FnOnce(&mut Self::Inner)) { f(&mut self.0); debug_assert!(Self::PROCESS(&mut self.0).is_ok()); } fn verify(mut self) -> Result<Self, $crate::VerificationError<Self>> { match Self::PROCESS(&mut self.0) { Ok(()) => Ok(self), Err(original) => Err($crate::VerificationError { original, value: self.0, }), } } }; } #[doc(hidden)] #[macro_export] macro_rules! __impl_external_traits { ($wrapper:ident, $inner:ty) => { impl ::core::convert::AsRef<$inner> for $wrapper { fn as_ref(&self) -> &$inner { &self.0 } } impl ::core::borrow::Borrow<$inner> for $wrapper { fn borrow(&self) -> &$inner { &self.0 } } impl ::core::convert::TryFrom<$inner> for $wrapper { type Error = $crate::ConstructionError<$wrapper>; fn try_from(value: $inner) -> Result<Self, Self::Error> { <$wrapper as $crate::Wrapper>::new(value) } } impl ::core::convert::From<$wrapper> for $inner { fn from(wrapper: $wrapper) -> Self { wrapper.0 } } }; }
rust
Unlicense
bd2bfd476108ebcfcb91c2710fdf92eb123a169d
2026-01-04T20:20:00.811147Z
false
teenjuna/prae
https://github.com/teenjuna/prae/blob/bd2bfd476108ebcfcb91c2710fdf92eb123a169d/prae/src/core.rs
prae/src/core.rs
use std::error::Error; use std::fmt; /// A trait that describes a /// [`Newtype`](https://rust-unofficial.github.io/patterns/patterns/behavioural/newtype.html) /// wrapper struct generated by [`define!`](crate::define) and /// [`extend!`](crate::extend) macros. pub trait Wrapper: Sized { /// Name of the wrapper. Will be used for nice error messages. const NAME: &'static str; /// The inner type of the wrapper. type Inner; /// The type of an error that can occur during the construction or mutation /// of the wrapper's value. type Error; /// The function that will mutate and validate wrapper's inner value on /// every construction and mutation. /// /// It's behaviour is based on the closures that were provided during the /// invocation of [`define!`](crate::define)/[`extend!`](crate::extend) /// macros (e.g. `adjust`, `ensure` and `validate`). /// /// If no closures were provided, this function will not mutate the value /// and always return `Ok(())`. const PROCESS: fn(&mut Self::Inner) -> Result<(), Self::Error>; /// Construct a new wrapper. /// /// It will return an error if the provided `value` doesn't pass /// [`Self::PROCESS`](Self::PROCESS). fn new(value: impl Into<Self::Inner>) -> Result<Self, ConstructionError<Self>>; /// Get a shared reference to the inner value. fn get(&self) -> &Self::Inner; // TODO: maybe change `ConstructionError` to `ReplacementError`? /// Replace inner value with the provided one. /// /// It will return an error if the provided `value` doesn't pass /// [`Self::PROCESS`](Self::PROCESS). fn set(&mut self, value: impl Into<Self::Inner>) -> Result<(), ConstructionError<Self>>; /// Mutate inner value using provided closure. /// /// To make sure that the closure doesn't corrupt the inner value, this /// method is only available when the inner type implements /// [`Clone`](Clone). This way, the closure receives a copy of the inner /// value, and then, if the mutated value passes /// [`Self::PROCESS`](Self::PROCESS), it will replace the inner value. fn mutate(&mut self, f: impl FnOnce(&mut Self::Inner)) -> Result<(), MutationError<Self>> where Self::Inner: Clone, { self.__mutate_with(Self::Inner::clone, f) } /// Unwrap the value into the inner type. fn into_inner(self) -> Self::Inner; /// This is a helper method that should be implemented in order for `mutate` /// method to work in a generic way. This method should not be used directly /// by the user (hence `#[doc(hidden)]` and a weird name). /// /// Using this method, we're allowing the trait to be implemented for both /// `Clone` and `!Clone` types. `Clone` types will have the `mutate` method, /// while the `!Clone` types won't. /// /// The idea for this method originated here: /// https://users.rust-lang.org/t/is-it-possible-to-implement-trait-method-with-where-clause-on-a-concrete-type/72846/12?u=teenjuna #[doc(hidden)] fn __mutate_with( &mut self, _clone: impl Fn(&Self::Inner) -> Self::Inner, _f: impl FnOnce(&mut Self::Inner), ) -> Result<(), MutationError<Self>> { unimplemented!() } /// Construct a new wrapper without calling /// [`Self::PROCESS`](Self::PROCESS). fn new_unprocessed(value: impl Into<Self::Inner>) -> Self; /// Replace inner value with the provided one without calling /// [`Self::PROCESS`](Self::PROCESS). fn set_unprocessed(&mut self, value: impl Into<Self::Inner>); /// Mutate inner value using provided closure without calling /// [`Self::PROCESS`](Self::PROCESS). fn mutate_unprocessed(&mut self, f: impl FnOnce(&mut Self::Inner)); /// Verify that inner value still passes [`Self::PROCESS`](Self::PROCESS). fn verify(self) -> Result<Self, VerificationError<Self>>; } /// A wrapper-error that will be returned if the /// [`Wrapper::new`](crate::Wrapper::new) or /// [`Wrapper::set`](crate::Wrapper::set) methods receive a value that doesn't /// pass [`Wrapper::PROCESS`](crate::Wrapper::PROCESS) function. /// /// This wrapper contains both the value that caused the error and the original /// error returned by the [`Wrapper::PROCESS`](crate::Wrapper::PROCESS) /// function. #[derive(Debug)] pub struct ConstructionError<W: Wrapper> { /// Value that caused the error. pub value: W::Inner, /// Original error. pub original: W::Error, } impl<W> fmt::Display for ConstructionError<W> where W: Wrapper, W::Inner: fmt::Debug, W::Error: fmt::Display, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "failed to construct type {} from value {:?}: {}", W::NAME, self.value, self.original, ) } } impl<W> Error for ConstructionError<W> where W: Wrapper + fmt::Debug, W::Inner: fmt::Debug, W::Error: fmt::Display + fmt::Debug, { // NOTE: `self.error` could be used for `source` function. // However, it would require `W::Error: Error + 'static`, // which is more restrictive, therefore less appealing. // It's also not clear for me if this change would be // useful. // Waiting for the stabilization of specialization? } /// A wrapper-error that will be returned if the /// [`Wrapper::mutate`](crate::Wrapper::mutate) method receives a closure that /// mutates the inner value in such a way that it no longer passes /// the [`Wrapper::PROCESS`](crate::Wrapper::PROCESS) function. /// /// This wrapper contains the mutated value that caused the error, the /// value before the mutation and the original error returned by /// [`Wrapper::PROCESS`](crate::Wrapper::PROCESS) function. #[derive(Debug)] pub struct MutationError<W: Wrapper> { /// Value before the mutation. pub old_value: W::Inner, /// Value after mutation (the cause of the error). pub new_value: W::Inner, /// Original error. pub original: W::Error, } impl<W> fmt::Display for MutationError<W> where W: Wrapper, W::Inner: fmt::Debug, W::Error: fmt::Display, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "failed to mutate type {} from value {:?} to value {:?}: {}", W::NAME, self.old_value, self.new_value, self.original, ) } } impl<W> Error for MutationError<W> where W: Wrapper + fmt::Debug, W::Inner: fmt::Debug, W::Error: fmt::Display + fmt::Debug, { } /// A wrapper-error that will be returned if the /// [`Wrapper::verify`](crate::Wrapper::verify) method is called on a wrapper /// whose inner value no longer passes the /// [`Wrapper::PROCESS`](crate::Wrapper::PROCESS) function. /// /// This wrapper contains both the value that caused the error and the original /// error returned by the [`Wrapper::PROCESS`](crate::Wrapper::PROCESS) /// function. #[derive(Debug)] pub struct VerificationError<W: Wrapper> { /// Value that caused the error. pub value: W::Inner, /// Original error. pub original: W::Error, } impl<W> fmt::Display for VerificationError<W> where W: Wrapper, W::Inner: fmt::Debug, W::Error: fmt::Display, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "verification of type {} with value {:?} failed: {}", W::NAME, self.value, self.original, ) } } impl<W> Error for VerificationError<W> where W: Wrapper + fmt::Debug, W::Inner: fmt::Debug, W::Error: fmt::Display + fmt::Debug, { } /// Convenience trait that allows mapping from `Result<_, /// ConstructionError<Wrapper>>`, `Result<_, MutationError<Wrapper>` and /// `Result<_, VerificationError<Wrapper>>` to `Result<_, Wrapper::Error>`. pub trait MapOriginalError<O, E> { fn map_original(self) -> Result<O, E>; } impl<O, W: Wrapper> MapOriginalError<O, W::Error> for Result<O, ConstructionError<W>> { fn map_original(self) -> Result<O, W::Error> { self.map_err(|err| err.original) } } impl<O, W: Wrapper> MapOriginalError<O, W::Error> for Result<O, MutationError<W>> { fn map_original(self) -> Result<O, W::Error> { self.map_err(|err| err.original) } } impl<O, W: Wrapper> MapOriginalError<O, W::Error> for Result<O, VerificationError<W>> { fn map_original(self) -> Result<O, W::Error> { self.map_err(|err| err.original) } }
rust
Unlicense
bd2bfd476108ebcfcb91c2710fdf92eb123a169d
2026-01-04T20:20:00.811147Z
false
teenjuna/prae
https://github.com/teenjuna/prae/blob/bd2bfd476108ebcfcb91c2710fdf92eb123a169d/prae/src/plugins.rs
prae/src/plugins.rs
mod serde; mod std;
rust
Unlicense
bd2bfd476108ebcfcb91c2710fdf92eb123a169d
2026-01-04T20:20:00.811147Z
false
teenjuna/prae
https://github.com/teenjuna/prae/blob/bd2bfd476108ebcfcb91c2710fdf92eb123a169d/prae/src/plugins/serde.rs
prae/src/plugins/serde.rs
/// Implement [`serde::Serialize`](::serde::Serialize) and /// [`serde::Deserialize`](::serde::Deserialize) for the wrapper. Deserilization /// will fail if the value doesn't pass wrapper's /// [`PROCESS`](crate::Wrapper::PROCESS) function. /// /// For this to work, the inner type of the wrapper must also implement these /// traits. #[cfg(feature = "serde")] #[cfg_attr(docsrs, doc(cfg(feature = "serde")))] #[macro_export] macro_rules! impl_serde { ($wrapper:ident) => { impl<'de> ::serde::Deserialize<'de> for $wrapper where Self: $crate::Wrapper + ::std::fmt::Debug, <Self as $crate::Wrapper>::Inner: ::serde::Deserialize<'de> + ::std::fmt::Debug, <Self as $crate::Wrapper>::Error: ::std::fmt::Display + std::fmt::Debug, { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: ::serde::Deserializer<'de>, { <Self as $crate::Wrapper>::new(<Self as $crate::Wrapper>::Inner::deserialize( deserializer, )?) .map_err(|err| ::serde::de::Error::custom(err.original)) } } impl ::serde::Serialize for $wrapper where Self: $crate::Wrapper + ::std::fmt::Debug, <Self as $crate::Wrapper>::Inner: ::serde::Serialize, <Self as $crate::Wrapper>::Error: ::std::fmt::Display + std::fmt::Debug, { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: ::serde::Serializer, { <Self as $crate::Wrapper>::Inner::serialize(&self.0, serializer) } } }; }
rust
Unlicense
bd2bfd476108ebcfcb91c2710fdf92eb123a169d
2026-01-04T20:20:00.811147Z
false
teenjuna/prae
https://github.com/teenjuna/prae/blob/bd2bfd476108ebcfcb91c2710fdf92eb123a169d/prae/src/plugins/std.rs
prae/src/plugins/std.rs
/// Implement [`Deref`](::core::ops::Deref) for the wrapper. #[macro_export] macro_rules! impl_deref { ($wrapper:ident) => { impl ::core::ops::Deref for $wrapper { type Target = <$wrapper as $crate::Wrapper>::Inner; fn deref(&self) -> &Self::Target { &self.0 } } }; } /// Implement [`Index`](::core::ops::Index) for the wrapper. #[macro_export] macro_rules! impl_index { ($wrapper:ident) => { impl<Idx> ::core::ops::Index<Idx> for $wrapper where <$wrapper as $crate::Wrapper>::Inner: ::core::ops::Index<Idx>, { type Output = <<$wrapper as $crate::Wrapper>::Inner as ::core::ops::Index<Idx>>::Output; fn index(&self, idx: Idx) -> &Self::Output { &self.0.index(idx) } } }; } /// Implement [`Display`](::core::fmt::Display) for the wrapper. #[macro_export] macro_rules! impl_display { ($wrapper:ident) => { impl ::core::fmt::Display for $wrapper where <$wrapper as $crate::Wrapper>::Inner: ::core::fmt::Display, { fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { self.0.fmt(f) } } }; }
rust
Unlicense
bd2bfd476108ebcfcb91c2710fdf92eb123a169d
2026-01-04T20:20:00.811147Z
false
teenjuna/prae
https://github.com/teenjuna/prae/blob/bd2bfd476108ebcfcb91c2710fdf92eb123a169d/prae/tests/impl_serde.rs
prae/tests/impl_serde.rs
#[cfg(feature = "serde")] mod tests { use prae::Wrapper; use serde::{Deserialize, Serialize}; #[derive(Debug, Serialize, Deserialize)] struct User { name: Username, } prae::define! { #[derive(Debug)] Username: String; adjust |u| *u = u.trim().to_owned(); ensure |u| !u.is_empty(); plugins: [ prae::impl_serde ]; } #[test] fn deserialization_succeeds_with_valid_data() { let json = r#" { "name": " some name " } "#; let u: User = serde_json::from_str(json).unwrap(); assert_eq!(u.name.get(), "some name"); } #[test] fn deserialization_fails_with_invalid_data() { let json = r#" { "name": " " } "#; let err = serde_json::from_str::<User>(json).unwrap_err(); assert_eq!(err.to_string(), "value is invalid at line 4 column 9"); } #[test] fn serialization_succeeds() { let u = User { name: Username::new("some name").unwrap(), }; let json = serde_json::to_string(&u).unwrap(); assert_eq!(r#"{"name":"some name"}"#, json) } }
rust
Unlicense
bd2bfd476108ebcfcb91c2710fdf92eb123a169d
2026-01-04T20:20:00.811147Z
false
teenjuna/prae
https://github.com/teenjuna/prae/blob/bd2bfd476108ebcfcb91c2710fdf92eb123a169d/prae/tests/impl_index.rs
prae/tests/impl_index.rs
use prae::Wrapper; prae::define! { #[derive(Debug)] Numbers: Vec<u64>; plugins: [ prae::impl_index, ]; } #[test] fn index_works() { let nums = Numbers::new([1, 2, 3]).unwrap(); assert_eq!(nums[1], 2); }
rust
Unlicense
bd2bfd476108ebcfcb91c2710fdf92eb123a169d
2026-01-04T20:20:00.811147Z
false
teenjuna/prae
https://github.com/teenjuna/prae/blob/bd2bfd476108ebcfcb91c2710fdf92eb123a169d/prae/tests/ensure.rs
prae/tests/ensure.rs
use assert_matches::assert_matches; use prae::Wrapper; prae::define! { #[derive(Debug)] pub Username: String; ensure |u| !u.is_empty(); } #[test] fn construction_error_formats_correctly() { let err = Username::new("").unwrap_err(); assert_eq!( err.to_string(), "failed to construct type Username from value \"\": value is invalid" ); } #[test] fn mutation_error_formats_correctly() { let mut un = Username::new("user").unwrap(); let err = un.mutate(|u| *u = "".to_owned()).unwrap_err(); assert_eq!( err.to_string(), "failed to mutate type Username from value \"user\" to value \"\": value is invalid" ); } #[test] fn construction_fails_for_invalid_data() { assert_matches!(Username::new(""), Err(prae::ConstructionError { .. })); } #[test] fn construction_succeeds_for_valid_data() { let un = Username::new(" user ").unwrap(); assert_eq!(un.get(), " user "); } #[test] fn mutation_fails_for_invalid_data() { let mut un = Username::new("user").unwrap(); assert_matches!( un.mutate(|u| *u = "".to_owned()), Err(prae::MutationError { .. }) ) }
rust
Unlicense
bd2bfd476108ebcfcb91c2710fdf92eb123a169d
2026-01-04T20:20:00.811147Z
false
teenjuna/prae
https://github.com/teenjuna/prae/blob/bd2bfd476108ebcfcb91c2710fdf92eb123a169d/prae/tests/adjust_ensure.rs
prae/tests/adjust_ensure.rs
use assert_matches::assert_matches; use prae::Wrapper; prae::define! { #[derive(Debug)] pub Username: String; adjust |u| *u = u.trim().to_owned(); ensure |u| !u.is_empty(); } #[test] fn construction_fails_for_invalid_data() { assert_matches!(Username::new(" "), Err(prae::ConstructionError { .. })) } #[test] fn construction_succeeds_for_valid_data() { let un = Username::new(" user ").unwrap(); assert_eq!(un.get(), "user"); } #[test] fn mutation_fails_for_invalid_data() { let mut un = Username::new("user").unwrap(); assert_matches!( un.mutate(|u| *u = " ".to_owned()), Err(prae::MutationError { .. }) ) } #[test] fn mutation_succeeds_for_valid_data() { let mut un = Username::new("user").unwrap(); un.mutate(|u| *u = " new user ".to_owned()).unwrap(); assert_eq!(un.get(), "new user"); }
rust
Unlicense
bd2bfd476108ebcfcb91c2710fdf92eb123a169d
2026-01-04T20:20:00.811147Z
false
teenjuna/prae
https://github.com/teenjuna/prae/blob/bd2bfd476108ebcfcb91c2710fdf92eb123a169d/prae/tests/extend.rs
prae/tests/extend.rs
use prae::Wrapper; prae::define! { #[derive(Debug)] Text: String; adjust |t| *t = t.trim().to_owned(); validate(&'static str) |t| { if t.is_empty() { Err("provided text is empty") } else { Ok(()) } }; } prae::extend! { #[derive(Debug)] CapText: Text; adjust |t| { let mut cs = t.chars(); *t = cs.next().unwrap().to_uppercase().collect::<String>() + cs.as_str(); }; } prae::extend! { #[derive(Debug)] Sentence: CapText; validate(String) |s| { if s.ends_with(&['.', '!', '?'][..]) { Ok(()) } else { Err("provided sentence has no ending punctuation mark".to_owned()) } }; } #[test] fn extended_works() { let t = CapText::new(" a couple of words").unwrap(); assert_eq!(t.get(), "A couple of words"); let e = CapText::new(" ").unwrap_err(); assert_eq!(e.original, "provided text is empty"); } #[test] fn double_extended_works() { let t = Sentence::new(" a sentence. ").unwrap(); assert_eq!(t.get(), "A sentence."); let e = Sentence::new(" ").unwrap_err(); assert_eq!(e.original, "provided text is empty"); let e = Sentence::new(" a sentence ").unwrap_err(); assert_eq!( e.original, "provided sentence has no ending punctuation mark" ); }
rust
Unlicense
bd2bfd476108ebcfcb91c2710fdf92eb123a169d
2026-01-04T20:20:00.811147Z
false
teenjuna/prae
https://github.com/teenjuna/prae/blob/bd2bfd476108ebcfcb91c2710fdf92eb123a169d/prae/tests/non_clone.rs
prae/tests/non_clone.rs
struct User { name: String, } prae::define! { ValidUser: User; ensure |u| !u.name.is_empty(); }
rust
Unlicense
bd2bfd476108ebcfcb91c2710fdf92eb123a169d
2026-01-04T20:20:00.811147Z
false
teenjuna/prae
https://github.com/teenjuna/prae/blob/bd2bfd476108ebcfcb91c2710fdf92eb123a169d/prae/tests/impl_display.rs
prae/tests/impl_display.rs
use prae::Wrapper; prae::define! { #[derive(Debug)] Username: String; plugins: [ prae::impl_display, ]; } #[test] fn display_works() { let un = Username::new("lala").unwrap(); assert_eq!(format!("{}", un), "lala"); }
rust
Unlicense
bd2bfd476108ebcfcb91c2710fdf92eb123a169d
2026-01-04T20:20:00.811147Z
false
teenjuna/prae
https://github.com/teenjuna/prae/blob/bd2bfd476108ebcfcb91c2710fdf92eb123a169d/prae/tests/impl_deref.rs
prae/tests/impl_deref.rs
use prae::Wrapper; prae::define! { #[derive(Clone, Debug)] ImplementsClone: String; plugins: [ prae::impl_deref, ]; } prae::define! { #[derive(Debug)] NotImplementsClone: String; plugins: [ prae::impl_deref, ]; } #[test] #[allow(clippy::redundant_clone)] fn deref_works() { let ic = ImplementsClone::new("lala").unwrap(); let ic_clone = ic.clone(); // implemented Clone at work assert_eq!(ic_clone.get(), "lala"); let nic = NotImplementsClone::new("lala").unwrap(); let nic_clone = nic.clone(); // Deref at work assert_eq!(nic_clone, "lala"); }
rust
Unlicense
bd2bfd476108ebcfcb91c2710fdf92eb123a169d
2026-01-04T20:20:00.811147Z
false
teenjuna/prae
https://github.com/teenjuna/prae/blob/bd2bfd476108ebcfcb91c2710fdf92eb123a169d/prae/tests/unprocessed.rs
prae/tests/unprocessed.rs
#[cfg(feature = "unprocessed")] mod tests { use prae::Wrapper; prae::define! { pub Username: String; ensure |u| !u.is_empty(); } #[test] fn unprocessed_construction_never_fails() { let u = Username::new_unprocessed("lala"); assert_eq!(u.get(), "lala"); let u = Username::new_unprocessed(""); assert_eq!(u.get(), ""); } #[test] fn unprocessed_mutation_never_fails() { let mut u = Username::new_unprocessed("lala"); u.mutate_unprocessed(|u| *u = "lolo".to_owned()); assert_eq!(u.get(), "lolo"); u.mutate_unprocessed(|u| *u = "".to_owned()); assert_eq!(u.get(), ""); } }
rust
Unlicense
bd2bfd476108ebcfcb91c2710fdf92eb123a169d
2026-01-04T20:20:00.811147Z
false
teenjuna/prae
https://github.com/teenjuna/prae/blob/bd2bfd476108ebcfcb91c2710fdf92eb123a169d/prae/tests/adjust_validate.rs
prae/tests/adjust_validate.rs
use assert_matches::assert_matches; use prae::Wrapper; #[derive(Debug)] pub struct UsernameError; prae::define! { #[derive(Debug)] pub Username: String; adjust |u| *u = u.trim().to_owned(); validate(UsernameError) |u| { if u.is_empty() { Err(UsernameError) } else { Ok(()) } }; } #[test] fn construction_fails_for_invalid_data() { assert_matches!(Username::new(" "), Err(prae::ConstructionError { .. })); } #[test] fn construction_succeeds_for_valid_data() { let un = Username::new(" user ").unwrap(); assert_eq!(un.get(), "user"); } #[test] fn mutation_fails_for_invalid_data() { let mut un = Username::new("user").unwrap(); assert_matches!( un.mutate(|u| *u = " ".to_owned()), Err(prae::MutationError { .. }) ); } #[test] fn mutation_succeeds_for_valid_data() { let mut un = Username::new("user").unwrap(); un.mutate(|u| *u = " new user ".to_owned()).unwrap(); assert_eq!(un.get(), "new user"); }
rust
Unlicense
bd2bfd476108ebcfcb91c2710fdf92eb123a169d
2026-01-04T20:20:00.811147Z
false