file_name
large_stringlengths
4
69
prefix
large_stringlengths
0
26.7k
suffix
large_stringlengths
0
24.8k
middle
large_stringlengths
0
2.12k
fim_type
large_stringclasses
4 values
declare.rs
/*! Functionality for declaring Objective-C classes. Classes can be declared using the `ClassDecl` struct. Instance variables and methods can then be added before the class is ultimately registered. # Example The following example demonstrates declaring a class named `MyNumber` that has one ivar, a `u32` named `_number` and a `number` method that returns it: ``` no_run # #[macro_use] extern crate makepad_objc_sys; # use makepad_objc_sys::declare::ClassDecl; # use makepad_objc_sys::runtime::{Class, Object, Sel}; # fn main() { let superclass = class!(NSObject); let mut decl = ClassDecl::new("MyNumber", superclass).unwrap(); // Add an instance variable decl.add_ivar::<u32>("_number"); // Add an ObjC method for getting the number extern fn my_number_get(this: &Object, _cmd: Sel) -> u32 { unsafe { *this.get_ivar("_number") } } unsafe { decl.add_method(sel!(number), my_number_get as extern fn(&Object, Sel) -> u32); } decl.register(); # } ``` */ use std::ffi::CString; use std::mem; use std::ptr; use runtime::{BOOL, Class, Imp, NO, Object, Protocol, Sel, self}; use {Encode, EncodeArguments, Encoding, Message}; /// Types that can be used as the implementation of an Objective-C method. pub trait MethodImplementation { /// The callee type of the method. type Callee: Message; /// The return type of the method. type Ret: Encode; /// The argument types of the method. type Args: EncodeArguments; /// Returns self as an `Imp` of a method. fn imp(self) -> Imp; } macro_rules! method_decl_impl { (-$s:ident, $r:ident, $f:ty, $($t:ident),*) => ( impl<$s, $r $(, $t)*> MethodImplementation for $f where $s: Message, $r: Encode $(, $t: Encode)* { type Callee = $s; type Ret = $r; type Args = ($($t,)*); fn imp(self) -> Imp { unsafe { mem::transmute(self) } } } ); ($($t:ident),*) => ( method_decl_impl!(-T, R, extern fn(&T, Sel $(, $t)*) -> R, $($t),*); method_decl_impl!(-T, R, extern fn(&mut T, Sel $(, $t)*) -> R, $($t),*); ); } method_decl_impl!(); method_decl_impl!(A); method_decl_impl!(A, B); method_decl_impl!(A, B, C); method_decl_impl!(A, B, C, D); method_decl_impl!(A, B, C, D, E); method_decl_impl!(A, B, C, D, E, F); method_decl_impl!(A, B, C, D, E, F, G); method_decl_impl!(A, B, C, D, E, F, G, H); method_decl_impl!(A, B, C, D, E, F, G, H, I); method_decl_impl!(A, B, C, D, E, F, G, H, I, J); method_decl_impl!(A, B, C, D, E, F, G, H, I, J, K); method_decl_impl!(A, B, C, D, E, F, G, H, I, J, K, L); fn count_args(sel: Sel) -> usize { sel.name().chars().filter(|&c| c == ':').count() } fn method_type_encoding(ret: &Encoding, args: &[Encoding]) -> CString { let mut types = ret.as_str().to_owned(); // First two arguments are always self and the selector types.push_str(<*mut Object>::encode().as_str()); types.push_str(Sel::encode().as_str()); types.extend(args.iter().map(|e| e.as_str())); CString::new(types).unwrap() } fn log2_align_of<T>() -> u8 { let align = mem::align_of::<T>(); // Alignments are required to be powers of 2 debug_assert!(align.count_ones() == 1); // log2 of a power of 2 is the number of trailing zeros align.trailing_zeros() as u8 } /// A type for declaring a new class and adding new methods and ivars to it /// before registering it. pub struct ClassDecl { cls: *mut Class, } impl ClassDecl { fn with_superclass(name: &str, superclass: Option<&Class>) -> Option<ClassDecl> { let name = CString::new(name).unwrap(); let super_ptr = superclass.map_or(ptr::null(), |c| c); let cls = unsafe { runtime::objc_allocateClassPair(super_ptr, name.as_ptr(), 0) }; if cls.is_null()
else { Some(ClassDecl { cls }) } } /// Constructs a `ClassDecl` with the given name and superclass. /// Returns `None` if the class couldn't be allocated. pub fn new(name: &str, superclass: &Class) -> Option<ClassDecl> { ClassDecl::with_superclass(name, Some(superclass)) } /** Constructs a `ClassDecl` declaring a new root class with the given name. Returns `None` if the class couldn't be allocated. An implementation for `+initialize` must also be given; the runtime calls this method for all classes, so it must be defined on root classes. Note that implementing a root class is not a simple endeavor. For example, your class probably cannot be passed to Cocoa code unless the entire `NSObject` protocol is implemented. Functionality it expects, like implementations of `-retain` and `-release` used by ARC, will not be present otherwise. */ pub fn root(name: &str, intitialize_fn: extern fn(&Class, Sel)) -> Option<ClassDecl> { let mut decl = ClassDecl::with_superclass(name, None); if let Some(ref mut decl) = decl { unsafe { decl.add_class_method(sel!(initialize), intitialize_fn); } } decl } /// Adds a method with the given name and implementation to self. /// Panics if the method wasn't sucessfully added /// or if the selector and function take different numbers of arguments. /// Unsafe because the caller must ensure that the types match those that /// are expected when the method is invoked from Objective-C. pub unsafe fn add_method<F>(&mut self, sel: Sel, func: F) where F: MethodImplementation<Callee=Object> { let encs = F::Args::encodings(); let encs = encs.as_ref(); let sel_args = count_args(sel); assert!(sel_args == encs.len(), "Selector accepts {} arguments, but function accepts {}", sel_args, encs.len(), ); let types = method_type_encoding(&F::Ret::encode(), encs); let success = runtime::class_addMethod(self.cls, sel, func.imp(), types.as_ptr()); assert!(success!= NO, "Failed to add method {:?}", sel); } /// Adds a class method with the given name and implementation to self. /// Panics if the method wasn't sucessfully added /// or if the selector and function take different numbers of arguments. /// Unsafe because the caller must ensure that the types match those that /// are expected when the method is invoked from Objective-C. pub unsafe fn add_class_method<F>(&mut self, sel: Sel, func: F) where F: MethodImplementation<Callee=Class> { let encs = F::Args::encodings(); let encs = encs.as_ref(); let sel_args = count_args(sel); assert!(sel_args == encs.len(), "Selector accepts {} arguments, but function accepts {}", sel_args, encs.len(), ); let types = method_type_encoding(&F::Ret::encode(), encs); let metaclass = (*self.cls).metaclass() as *const _ as *mut _; let success = runtime::class_addMethod(metaclass, sel, func.imp(), types.as_ptr()); assert!(success!= NO, "Failed to add class method {:?}", sel); } /// Adds an ivar with type `T` and the provided name to self. /// Panics if the ivar wasn't successfully added. pub fn add_ivar<T>(&mut self, name: &str) where T: Encode { let c_name = CString::new(name).unwrap(); let encoding = CString::new(T::encode().as_str()).unwrap(); let size = mem::size_of::<T>(); let align = log2_align_of::<T>(); let success = unsafe { runtime::class_addIvar(self.cls, c_name.as_ptr(), size, align, encoding.as_ptr()) }; assert!(success!= NO, "Failed to add ivar {}", name); } /// Adds a protocol to self. Panics if the protocol wasn't successfully /// added pub fn add_protocol(&mut self, proto: &Protocol) { let success = unsafe { runtime::class_addProtocol(self.cls, proto) }; assert!(success!= NO, "Failed to add protocol {:?}", proto); } /// Registers self, consuming it and returning a reference to the /// newly registered `Class`. pub fn register(self) -> &'static Class { unsafe { let cls = self.cls; runtime::objc_registerClassPair(cls); // Forget self otherwise the class will be disposed in drop mem::forget(self); &*cls } } } impl Drop for ClassDecl { fn drop(&mut self) { unsafe { runtime::objc_disposeClassPair(self.cls); } } } /// A type for declaring a new protocol and adding new methods to it /// before registering it. pub struct ProtocolDecl { proto: *mut Protocol } impl ProtocolDecl { /// Constructs a `ProtocolDecl` with the given name. Returns `None` if the /// protocol couldn't be allocated. pub fn new(name: &str) -> Option<ProtocolDecl> { let c_name = CString::new(name).unwrap(); let proto = unsafe { runtime::objc_allocateProtocol(c_name.as_ptr()) }; if proto.is_null() { None } else { Some(ProtocolDecl { proto }) } } fn add_method_description_common<Args, Ret>(&mut self, sel: Sel, is_required: bool, is_instance_method: bool) where Args: EncodeArguments, Ret: Encode { let encs = Args::encodings(); let encs = encs.as_ref(); let sel_args = count_args(sel); assert!(sel_args == encs.len(), "Selector accepts {} arguments, but function accepts {}", sel_args, encs.len(), ); let types = method_type_encoding(&Ret::encode(), encs); unsafe { runtime::protocol_addMethodDescription( self.proto, sel, types.as_ptr(), is_required as BOOL, is_instance_method as BOOL); } } /// Adds an instance method declaration with a given description to self. pub fn add_method_description<Args, Ret>(&mut self, sel: Sel, is_required: bool) where Args: EncodeArguments, Ret: Encode { self.add_method_description_common::<Args, Ret>(sel, is_required, true) } /// Adds a class method declaration with a given description to self. pub fn add_class_method_description<Args, Ret>(&mut self, sel: Sel, is_required: bool) where Args: EncodeArguments, Ret: Encode { self.add_method_description_common::<Args, Ret>(sel, is_required, false) } /// Adds a requirement on another protocol. pub fn add_protocol(&mut self, proto: &Protocol) { unsafe { runtime::protocol_addProtocol(self.proto, proto); } } /// Registers self, consuming it and returning a reference to the /// newly registered `Protocol`. pub fn register(self) -> &'static Protocol { unsafe { runtime::objc_registerProtocol(self.proto); &*self.proto } } } /* #[cfg(test)] mod tests { use test_utils; #[test] fn test_custom_class() { // Registering the custom class is in test_utils let obj = test_utils::custom_object(); unsafe { let _: () = msg_send![obj, setFoo:13u32]; let result: u32 = msg_send![obj, foo]; assert!(result == 13); } } #[test] fn test_class_method() { let cls = test_utils::custom_class(); unsafe { let result: u32 = msg_send![cls, classFoo]; assert!(result == 7); } } }*/
{ None }
conditional_block
declare.rs
/*! Functionality for declaring Objective-C classes. Classes can be declared using the `ClassDecl` struct. Instance variables and methods can then be added before the class is ultimately registered. # Example The following example demonstrates declaring a class named `MyNumber` that has one ivar, a `u32` named `_number` and a `number` method that returns it: ``` no_run # #[macro_use] extern crate makepad_objc_sys; # use makepad_objc_sys::declare::ClassDecl; # use makepad_objc_sys::runtime::{Class, Object, Sel}; # fn main() { let superclass = class!(NSObject); let mut decl = ClassDecl::new("MyNumber", superclass).unwrap(); // Add an instance variable decl.add_ivar::<u32>("_number"); // Add an ObjC method for getting the number extern fn my_number_get(this: &Object, _cmd: Sel) -> u32 { unsafe { *this.get_ivar("_number") } } unsafe { decl.add_method(sel!(number), my_number_get as extern fn(&Object, Sel) -> u32); } decl.register(); # } ``` */ use std::ffi::CString; use std::mem; use std::ptr; use runtime::{BOOL, Class, Imp, NO, Object, Protocol, Sel, self}; use {Encode, EncodeArguments, Encoding, Message}; /// Types that can be used as the implementation of an Objective-C method. pub trait MethodImplementation { /// The callee type of the method. type Callee: Message; /// The return type of the method. type Ret: Encode; /// The argument types of the method. type Args: EncodeArguments; /// Returns self as an `Imp` of a method. fn imp(self) -> Imp; } macro_rules! method_decl_impl { (-$s:ident, $r:ident, $f:ty, $($t:ident),*) => ( impl<$s, $r $(, $t)*> MethodImplementation for $f where $s: Message, $r: Encode $(, $t: Encode)* { type Callee = $s; type Ret = $r; type Args = ($($t,)*); fn imp(self) -> Imp { unsafe { mem::transmute(self) } } } ); ($($t:ident),*) => ( method_decl_impl!(-T, R, extern fn(&T, Sel $(, $t)*) -> R, $($t),*); method_decl_impl!(-T, R, extern fn(&mut T, Sel $(, $t)*) -> R, $($t),*); ); } method_decl_impl!(); method_decl_impl!(A); method_decl_impl!(A, B); method_decl_impl!(A, B, C); method_decl_impl!(A, B, C, D); method_decl_impl!(A, B, C, D, E); method_decl_impl!(A, B, C, D, E, F); method_decl_impl!(A, B, C, D, E, F, G); method_decl_impl!(A, B, C, D, E, F, G, H); method_decl_impl!(A, B, C, D, E, F, G, H, I); method_decl_impl!(A, B, C, D, E, F, G, H, I, J); method_decl_impl!(A, B, C, D, E, F, G, H, I, J, K); method_decl_impl!(A, B, C, D, E, F, G, H, I, J, K, L); fn count_args(sel: Sel) -> usize { sel.name().chars().filter(|&c| c == ':').count() } fn method_type_encoding(ret: &Encoding, args: &[Encoding]) -> CString { let mut types = ret.as_str().to_owned(); // First two arguments are always self and the selector types.push_str(<*mut Object>::encode().as_str()); types.push_str(Sel::encode().as_str()); types.extend(args.iter().map(|e| e.as_str())); CString::new(types).unwrap() } fn log2_align_of<T>() -> u8 { let align = mem::align_of::<T>(); // Alignments are required to be powers of 2 debug_assert!(align.count_ones() == 1); // log2 of a power of 2 is the number of trailing zeros align.trailing_zeros() as u8 } /// A type for declaring a new class and adding new methods and ivars to it /// before registering it. pub struct ClassDecl { cls: *mut Class, } impl ClassDecl { fn with_superclass(name: &str, superclass: Option<&Class>) -> Option<ClassDecl> { let name = CString::new(name).unwrap(); let super_ptr = superclass.map_or(ptr::null(), |c| c); let cls = unsafe { runtime::objc_allocateClassPair(super_ptr, name.as_ptr(), 0) }; if cls.is_null() { None } else { Some(ClassDecl { cls }) } } /// Constructs a `ClassDecl` with the given name and superclass. /// Returns `None` if the class couldn't be allocated. pub fn new(name: &str, superclass: &Class) -> Option<ClassDecl> { ClassDecl::with_superclass(name, Some(superclass)) } /** Constructs a `ClassDecl` declaring a new root class with the given name. Returns `None` if the class couldn't be allocated. An implementation for `+initialize` must also be given; the runtime calls this method for all classes, so it must be defined on root classes. Note that implementing a root class is not a simple endeavor. For example, your class probably cannot be passed to Cocoa code unless the entire `NSObject` protocol is implemented. Functionality it expects, like implementations of `-retain` and `-release` used by ARC, will not be present otherwise. */ pub fn root(name: &str, intitialize_fn: extern fn(&Class, Sel)) -> Option<ClassDecl> { let mut decl = ClassDecl::with_superclass(name, None); if let Some(ref mut decl) = decl { unsafe { decl.add_class_method(sel!(initialize), intitialize_fn); } } decl } /// Adds a method with the given name and implementation to self. /// Panics if the method wasn't sucessfully added /// or if the selector and function take different numbers of arguments. /// Unsafe because the caller must ensure that the types match those that /// are expected when the method is invoked from Objective-C. pub unsafe fn add_method<F>(&mut self, sel: Sel, func: F) where F: MethodImplementation<Callee=Object> { let encs = F::Args::encodings(); let encs = encs.as_ref(); let sel_args = count_args(sel); assert!(sel_args == encs.len(), "Selector accepts {} arguments, but function accepts {}", sel_args, encs.len(), ); let types = method_type_encoding(&F::Ret::encode(), encs); let success = runtime::class_addMethod(self.cls, sel, func.imp(), types.as_ptr()); assert!(success!= NO, "Failed to add method {:?}", sel); } /// Adds a class method with the given name and implementation to self. /// Panics if the method wasn't sucessfully added /// or if the selector and function take different numbers of arguments. /// Unsafe because the caller must ensure that the types match those that /// are expected when the method is invoked from Objective-C. pub unsafe fn add_class_method<F>(&mut self, sel: Sel, func: F) where F: MethodImplementation<Callee=Class> { let encs = F::Args::encodings(); let encs = encs.as_ref(); let sel_args = count_args(sel); assert!(sel_args == encs.len(), "Selector accepts {} arguments, but function accepts {}", sel_args, encs.len(), ); let types = method_type_encoding(&F::Ret::encode(), encs); let metaclass = (*self.cls).metaclass() as *const _ as *mut _; let success = runtime::class_addMethod(metaclass, sel, func.imp(), types.as_ptr()); assert!(success!= NO, "Failed to add class method {:?}", sel); } /// Adds an ivar with type `T` and the provided name to self. /// Panics if the ivar wasn't successfully added. pub fn add_ivar<T>(&mut self, name: &str) where T: Encode { let c_name = CString::new(name).unwrap();
let size = mem::size_of::<T>(); let align = log2_align_of::<T>(); let success = unsafe { runtime::class_addIvar(self.cls, c_name.as_ptr(), size, align, encoding.as_ptr()) }; assert!(success!= NO, "Failed to add ivar {}", name); } /// Adds a protocol to self. Panics if the protocol wasn't successfully /// added pub fn add_protocol(&mut self, proto: &Protocol) { let success = unsafe { runtime::class_addProtocol(self.cls, proto) }; assert!(success!= NO, "Failed to add protocol {:?}", proto); } /// Registers self, consuming it and returning a reference to the /// newly registered `Class`. pub fn register(self) -> &'static Class { unsafe { let cls = self.cls; runtime::objc_registerClassPair(cls); // Forget self otherwise the class will be disposed in drop mem::forget(self); &*cls } } } impl Drop for ClassDecl { fn drop(&mut self) { unsafe { runtime::objc_disposeClassPair(self.cls); } } } /// A type for declaring a new protocol and adding new methods to it /// before registering it. pub struct ProtocolDecl { proto: *mut Protocol } impl ProtocolDecl { /// Constructs a `ProtocolDecl` with the given name. Returns `None` if the /// protocol couldn't be allocated. pub fn new(name: &str) -> Option<ProtocolDecl> { let c_name = CString::new(name).unwrap(); let proto = unsafe { runtime::objc_allocateProtocol(c_name.as_ptr()) }; if proto.is_null() { None } else { Some(ProtocolDecl { proto }) } } fn add_method_description_common<Args, Ret>(&mut self, sel: Sel, is_required: bool, is_instance_method: bool) where Args: EncodeArguments, Ret: Encode { let encs = Args::encodings(); let encs = encs.as_ref(); let sel_args = count_args(sel); assert!(sel_args == encs.len(), "Selector accepts {} arguments, but function accepts {}", sel_args, encs.len(), ); let types = method_type_encoding(&Ret::encode(), encs); unsafe { runtime::protocol_addMethodDescription( self.proto, sel, types.as_ptr(), is_required as BOOL, is_instance_method as BOOL); } } /// Adds an instance method declaration with a given description to self. pub fn add_method_description<Args, Ret>(&mut self, sel: Sel, is_required: bool) where Args: EncodeArguments, Ret: Encode { self.add_method_description_common::<Args, Ret>(sel, is_required, true) } /// Adds a class method declaration with a given description to self. pub fn add_class_method_description<Args, Ret>(&mut self, sel: Sel, is_required: bool) where Args: EncodeArguments, Ret: Encode { self.add_method_description_common::<Args, Ret>(sel, is_required, false) } /// Adds a requirement on another protocol. pub fn add_protocol(&mut self, proto: &Protocol) { unsafe { runtime::protocol_addProtocol(self.proto, proto); } } /// Registers self, consuming it and returning a reference to the /// newly registered `Protocol`. pub fn register(self) -> &'static Protocol { unsafe { runtime::objc_registerProtocol(self.proto); &*self.proto } } } /* #[cfg(test)] mod tests { use test_utils; #[test] fn test_custom_class() { // Registering the custom class is in test_utils let obj = test_utils::custom_object(); unsafe { let _: () = msg_send![obj, setFoo:13u32]; let result: u32 = msg_send![obj, foo]; assert!(result == 13); } } #[test] fn test_class_method() { let cls = test_utils::custom_class(); unsafe { let result: u32 = msg_send![cls, classFoo]; assert!(result == 7); } } }*/
let encoding = CString::new(T::encode().as_str()).unwrap();
random_line_split
declare.rs
/*! Functionality for declaring Objective-C classes. Classes can be declared using the `ClassDecl` struct. Instance variables and methods can then be added before the class is ultimately registered. # Example The following example demonstrates declaring a class named `MyNumber` that has one ivar, a `u32` named `_number` and a `number` method that returns it: ``` no_run # #[macro_use] extern crate makepad_objc_sys; # use makepad_objc_sys::declare::ClassDecl; # use makepad_objc_sys::runtime::{Class, Object, Sel}; # fn main() { let superclass = class!(NSObject); let mut decl = ClassDecl::new("MyNumber", superclass).unwrap(); // Add an instance variable decl.add_ivar::<u32>("_number"); // Add an ObjC method for getting the number extern fn my_number_get(this: &Object, _cmd: Sel) -> u32 { unsafe { *this.get_ivar("_number") } } unsafe { decl.add_method(sel!(number), my_number_get as extern fn(&Object, Sel) -> u32); } decl.register(); # } ``` */ use std::ffi::CString; use std::mem; use std::ptr; use runtime::{BOOL, Class, Imp, NO, Object, Protocol, Sel, self}; use {Encode, EncodeArguments, Encoding, Message}; /// Types that can be used as the implementation of an Objective-C method. pub trait MethodImplementation { /// The callee type of the method. type Callee: Message; /// The return type of the method. type Ret: Encode; /// The argument types of the method. type Args: EncodeArguments; /// Returns self as an `Imp` of a method. fn imp(self) -> Imp; } macro_rules! method_decl_impl { (-$s:ident, $r:ident, $f:ty, $($t:ident),*) => ( impl<$s, $r $(, $t)*> MethodImplementation for $f where $s: Message, $r: Encode $(, $t: Encode)* { type Callee = $s; type Ret = $r; type Args = ($($t,)*); fn imp(self) -> Imp { unsafe { mem::transmute(self) } } } ); ($($t:ident),*) => ( method_decl_impl!(-T, R, extern fn(&T, Sel $(, $t)*) -> R, $($t),*); method_decl_impl!(-T, R, extern fn(&mut T, Sel $(, $t)*) -> R, $($t),*); ); } method_decl_impl!(); method_decl_impl!(A); method_decl_impl!(A, B); method_decl_impl!(A, B, C); method_decl_impl!(A, B, C, D); method_decl_impl!(A, B, C, D, E); method_decl_impl!(A, B, C, D, E, F); method_decl_impl!(A, B, C, D, E, F, G); method_decl_impl!(A, B, C, D, E, F, G, H); method_decl_impl!(A, B, C, D, E, F, G, H, I); method_decl_impl!(A, B, C, D, E, F, G, H, I, J); method_decl_impl!(A, B, C, D, E, F, G, H, I, J, K); method_decl_impl!(A, B, C, D, E, F, G, H, I, J, K, L); fn count_args(sel: Sel) -> usize { sel.name().chars().filter(|&c| c == ':').count() } fn method_type_encoding(ret: &Encoding, args: &[Encoding]) -> CString { let mut types = ret.as_str().to_owned(); // First two arguments are always self and the selector types.push_str(<*mut Object>::encode().as_str()); types.push_str(Sel::encode().as_str()); types.extend(args.iter().map(|e| e.as_str())); CString::new(types).unwrap() } fn log2_align_of<T>() -> u8 { let align = mem::align_of::<T>(); // Alignments are required to be powers of 2 debug_assert!(align.count_ones() == 1); // log2 of a power of 2 is the number of trailing zeros align.trailing_zeros() as u8 } /// A type for declaring a new class and adding new methods and ivars to it /// before registering it. pub struct ClassDecl { cls: *mut Class, } impl ClassDecl { fn with_superclass(name: &str, superclass: Option<&Class>) -> Option<ClassDecl> { let name = CString::new(name).unwrap(); let super_ptr = superclass.map_or(ptr::null(), |c| c); let cls = unsafe { runtime::objc_allocateClassPair(super_ptr, name.as_ptr(), 0) }; if cls.is_null() { None } else { Some(ClassDecl { cls }) } } /// Constructs a `ClassDecl` with the given name and superclass. /// Returns `None` if the class couldn't be allocated. pub fn new(name: &str, superclass: &Class) -> Option<ClassDecl> { ClassDecl::with_superclass(name, Some(superclass)) } /** Constructs a `ClassDecl` declaring a new root class with the given name. Returns `None` if the class couldn't be allocated. An implementation for `+initialize` must also be given; the runtime calls this method for all classes, so it must be defined on root classes. Note that implementing a root class is not a simple endeavor. For example, your class probably cannot be passed to Cocoa code unless the entire `NSObject` protocol is implemented. Functionality it expects, like implementations of `-retain` and `-release` used by ARC, will not be present otherwise. */ pub fn root(name: &str, intitialize_fn: extern fn(&Class, Sel)) -> Option<ClassDecl> { let mut decl = ClassDecl::with_superclass(name, None); if let Some(ref mut decl) = decl { unsafe { decl.add_class_method(sel!(initialize), intitialize_fn); } } decl } /// Adds a method with the given name and implementation to self. /// Panics if the method wasn't sucessfully added /// or if the selector and function take different numbers of arguments. /// Unsafe because the caller must ensure that the types match those that /// are expected when the method is invoked from Objective-C. pub unsafe fn
<F>(&mut self, sel: Sel, func: F) where F: MethodImplementation<Callee=Object> { let encs = F::Args::encodings(); let encs = encs.as_ref(); let sel_args = count_args(sel); assert!(sel_args == encs.len(), "Selector accepts {} arguments, but function accepts {}", sel_args, encs.len(), ); let types = method_type_encoding(&F::Ret::encode(), encs); let success = runtime::class_addMethod(self.cls, sel, func.imp(), types.as_ptr()); assert!(success!= NO, "Failed to add method {:?}", sel); } /// Adds a class method with the given name and implementation to self. /// Panics if the method wasn't sucessfully added /// or if the selector and function take different numbers of arguments. /// Unsafe because the caller must ensure that the types match those that /// are expected when the method is invoked from Objective-C. pub unsafe fn add_class_method<F>(&mut self, sel: Sel, func: F) where F: MethodImplementation<Callee=Class> { let encs = F::Args::encodings(); let encs = encs.as_ref(); let sel_args = count_args(sel); assert!(sel_args == encs.len(), "Selector accepts {} arguments, but function accepts {}", sel_args, encs.len(), ); let types = method_type_encoding(&F::Ret::encode(), encs); let metaclass = (*self.cls).metaclass() as *const _ as *mut _; let success = runtime::class_addMethod(metaclass, sel, func.imp(), types.as_ptr()); assert!(success!= NO, "Failed to add class method {:?}", sel); } /// Adds an ivar with type `T` and the provided name to self. /// Panics if the ivar wasn't successfully added. pub fn add_ivar<T>(&mut self, name: &str) where T: Encode { let c_name = CString::new(name).unwrap(); let encoding = CString::new(T::encode().as_str()).unwrap(); let size = mem::size_of::<T>(); let align = log2_align_of::<T>(); let success = unsafe { runtime::class_addIvar(self.cls, c_name.as_ptr(), size, align, encoding.as_ptr()) }; assert!(success!= NO, "Failed to add ivar {}", name); } /// Adds a protocol to self. Panics if the protocol wasn't successfully /// added pub fn add_protocol(&mut self, proto: &Protocol) { let success = unsafe { runtime::class_addProtocol(self.cls, proto) }; assert!(success!= NO, "Failed to add protocol {:?}", proto); } /// Registers self, consuming it and returning a reference to the /// newly registered `Class`. pub fn register(self) -> &'static Class { unsafe { let cls = self.cls; runtime::objc_registerClassPair(cls); // Forget self otherwise the class will be disposed in drop mem::forget(self); &*cls } } } impl Drop for ClassDecl { fn drop(&mut self) { unsafe { runtime::objc_disposeClassPair(self.cls); } } } /// A type for declaring a new protocol and adding new methods to it /// before registering it. pub struct ProtocolDecl { proto: *mut Protocol } impl ProtocolDecl { /// Constructs a `ProtocolDecl` with the given name. Returns `None` if the /// protocol couldn't be allocated. pub fn new(name: &str) -> Option<ProtocolDecl> { let c_name = CString::new(name).unwrap(); let proto = unsafe { runtime::objc_allocateProtocol(c_name.as_ptr()) }; if proto.is_null() { None } else { Some(ProtocolDecl { proto }) } } fn add_method_description_common<Args, Ret>(&mut self, sel: Sel, is_required: bool, is_instance_method: bool) where Args: EncodeArguments, Ret: Encode { let encs = Args::encodings(); let encs = encs.as_ref(); let sel_args = count_args(sel); assert!(sel_args == encs.len(), "Selector accepts {} arguments, but function accepts {}", sel_args, encs.len(), ); let types = method_type_encoding(&Ret::encode(), encs); unsafe { runtime::protocol_addMethodDescription( self.proto, sel, types.as_ptr(), is_required as BOOL, is_instance_method as BOOL); } } /// Adds an instance method declaration with a given description to self. pub fn add_method_description<Args, Ret>(&mut self, sel: Sel, is_required: bool) where Args: EncodeArguments, Ret: Encode { self.add_method_description_common::<Args, Ret>(sel, is_required, true) } /// Adds a class method declaration with a given description to self. pub fn add_class_method_description<Args, Ret>(&mut self, sel: Sel, is_required: bool) where Args: EncodeArguments, Ret: Encode { self.add_method_description_common::<Args, Ret>(sel, is_required, false) } /// Adds a requirement on another protocol. pub fn add_protocol(&mut self, proto: &Protocol) { unsafe { runtime::protocol_addProtocol(self.proto, proto); } } /// Registers self, consuming it and returning a reference to the /// newly registered `Protocol`. pub fn register(self) -> &'static Protocol { unsafe { runtime::objc_registerProtocol(self.proto); &*self.proto } } } /* #[cfg(test)] mod tests { use test_utils; #[test] fn test_custom_class() { // Registering the custom class is in test_utils let obj = test_utils::custom_object(); unsafe { let _: () = msg_send![obj, setFoo:13u32]; let result: u32 = msg_send![obj, foo]; assert!(result == 13); } } #[test] fn test_class_method() { let cls = test_utils::custom_class(); unsafe { let result: u32 = msg_send![cls, classFoo]; assert!(result == 7); } } }*/
add_method
identifier_name
annealing3.rs
use crate::common::*; use geo::algorithm::coords_iter::CoordsIter; use rand::prelude::*; use rand::seq::SliceRandom; use std::collections::VecDeque; use std::time::{Duration, Instant}; static SEED: [u8; 32] = [ 0xfd, 0x00, 0xf1, 0x5c, 0xde, 0x01, 0x11, 0xc6, 0xc3, 0xea, 0xfb, 0xbf, 0xf3, 0xca, 0xd8, 0x32, 0x6a, 0xe3, 0x07, 0x99, 0xc5, 0xe0, 0x52, 0xe4, 0xaa, 0x35, 0x07, 0x99, 0xe3, 0x2b, 0x9d, 0xc6, ]; fn tscore(solution: &Vec<Point>, input: &Input) -> (f64, f64)
( dislike / (input.hole.exterior().coords_count() as f64), -(vx + vy), ) } fn ascore(value: (f64, f64), progress: f64) -> f64 { value.0 * progress + (1.0 - progress) * value.1 } pub fn solve( input: &Input, mut solution: Vec<Point>, time_limit: Duration, fix_seed: bool, initial_temperature: f64, ) -> (Vec<Point>, f64) { let n = solution.len(); let mut rng = if fix_seed { SmallRng::from_seed(SEED) } else { SmallRng::from_entropy() }; let mut current_score = tscore(&solution, &input); let out_edges = make_out_edges(&input.figure.edges, n); let original_vertices = &input.figure.vertices; let mut orders = vec![vec![]; n]; for i in 0..n { orders[i] = make_determined_order(&out_edges, Some(i)); } let start_at = Instant::now(); let mut best_solution = solution.clone(); let mut best_score = current_score; let mut progress = 0.0; let mut temperature = initial_temperature; eprintln!("initial_temperature = {}", initial_temperature); let distance_sums = calc_distance_sums(&out_edges, original_vertices.len()); let distance_total: usize = distance_sums.iter().sum(); // eprintln!("{} {:?}", distance_total, distance_sums); let mut iter = 0; let mut move_count = 0; loop { // check time limit iter += 1; if iter % 100 == 0 { let elapsed = Instant::now() - start_at; if best_score.0 == 0.0 || elapsed >= time_limit { eprintln!("iter = {}, move_count = {}", iter, move_count); let dislike = calculate_dislike(&best_solution, &input.hole); return (best_solution, dislike); } // tweak temperature progress = elapsed.as_secs_f64() / time_limit.as_secs_f64(); temperature = initial_temperature * (1.0 - progress) * (-progress).exp2(); } // move to neighbor let r = rng.gen::<f64>(); if r > progress { let mut i = 0; { let r = rng.gen::<usize>() % distance_total; let mut sum = 0; for index in 0..n { sum += distance_sums[index]; if r < sum { i = index; break; } } } let w = rng.gen::<usize>() % 40 + 5; let next_solution = random_move_one_point(i, w, &solution, &input, &mut rng, &out_edges, &orders); if next_solution.is_none() { continue; } move_count += 1; let next_solution = next_solution.unwrap(); // calculate score. FIXME: slow let new_score = tscore(&next_solution, &input); let accept = { let current = ascore(current_score, progress); let new = ascore(new_score, progress); if new < current { true } else { // new_score >= current_score let delta = new - current; let accept_prob = (-delta / temperature).exp(); rng.gen::<f64>() < accept_prob } }; if accept { // accept candidate current_score = new_score; solution = next_solution; } } else { let i = rng.gen::<usize>() % n; let candidate = make_next_candidates( i, original_vertices, &input.hole, input.epsilon, &solution, &out_edges, &mut rng, ); if candidate!= original_vertices[i] { move_count += 1; } // calculate score. FIXME: slow let old = solution[i]; solution[i] = candidate; let new_score = tscore(&solution, &input); let accept = { let current = ascore(current_score, progress); let new = ascore(new_score, progress); if new < current { true } else { // new_score >= current_score let delta = new - current; let accept_prob = (-delta / temperature).exp(); rng.gen::<f64>() < accept_prob } }; if accept { // accept candidate current_score = new_score; } else { // reject candidate solution[i] = old; } } if current_score < best_score { best_score = current_score; best_solution = solution.clone(); } } } fn make_next_candidates( i: usize, original_vertices: &[Point], hole: &Polygon, epsilon: i64, solution: &[Point], out_edges: &[Vec<usize>], rng: &mut SmallRng, ) -> Point { let some_neighbor = out_edges[i][0]; let original_squared_distance = squared_distance(&original_vertices[i], &original_vertices[some_neighbor]); if original_squared_distance < 100.0 || epsilon < 100000 { let ring = Ring::from_epsilon(solution[some_neighbor], epsilon, original_squared_distance); let mut points = ring_points(&ring); points.shuffle(rng); for &p in points.iter() { if!is_valid_point_move(i, &p, solution, original_vertices, out_edges, hole, epsilon) { continue; } return p; } } else { let od = original_squared_distance.sqrt(); let low = od * (1.0 - epsilon as f64 / 1000000.0).sqrt(); let high = od * (1.0 + epsilon as f64 / 1000000.0).sqrt(); for _iter in 0..100 { let d = low + (high - low) * rng.gen::<f64>(); let theta = 2.0 * std::f64::consts::PI * rng.gen::<f64>(); let vect = Point::new( (theta.cos() * d + 0.5).floor(), (theta.sin() * d + 0.5).floor(), ); let p = solution[some_neighbor] + vect; if!is_valid_point_move(i, &p, solution, original_vertices, out_edges, hole, epsilon) { continue; } return p; } return solution[i]; } unreachable!() } fn is_valid_point_move( index: usize, p: &Point, solution: &[Point], original_vertices: &[Point], out_edges: &[Vec<usize>], hole: &Polygon, epsilon: i64, ) -> bool { let ok1 = out_edges[index].iter().all(|&dst| { is_allowed_distance( &p, &solution[dst], &original_vertices[index], &original_vertices[dst], epsilon, false, ) }); if!ok1 { return false; } let ok2 = out_edges[index] .iter() .all(|&dst| does_line_fit_in_hole(&p, &solution[dst], hole)); if!ok2 { return false; } return true; } fn random_move_one_point( from: usize, w: usize, solution: &Vec<Point>, input: &Input, rng: &mut SmallRng, out_edges: &Vec<Vec<usize>>, orders: &Vec<Vec<usize>>, ) -> Option<Vec<Point>> { let mut gx: f64 = 0.0; let mut gy: f64 = 0.0; for p in solution.iter() { gx += p.x(); gy += p.y(); } gx /= solution.len() as f64; gy /= solution.len() as f64; let g = Point::new(gx, gy); let mut vect1 = solution[from] - g; vect1 = vect1 / squared_distance(&solution[from], &g).sqrt(); let mut np = solution[from]; for iter in 0..5 { let dx = (rng.gen::<usize>() % (w * 2 + 1)) as f64 - w as f64; let dy = (rng.gen::<usize>() % (w * 2 + 1)) as f64 - w as f64; let vect2 = Point::new(dx, dy) / (dx * dx + dy * dy).sqrt(); np = solution[from] + Point::new(dx, dy); if vect1.dot(vect2) > 0.4 - iter as f64 * 0.2 { break; } } if solution[from] == np { return None; } let mut solution = solution.clone(); let old = solution[from]; solution[from] = np; let next_solution = fix_allowed_distance_violation(from, &solution, &input, &out_edges, &orders); solution[from] = old; return next_solution; } fn calc_distance_sums(edges: &Vec<Vec<usize>>, n: usize) -> Vec<usize> { let mut ret = vec![0; n]; for start in 0..n { let mut visited = vec![false; n]; visited[start] = true; let mut que = VecDeque::new(); que.push_back((start, 0)); while let Some((from, dist)) = que.pop_front() { ret[start] += dist * dist; // ret[start] += dist; for &to in edges[from].iter() { if visited[to] { continue; } visited[to] = true; que.push_back((to, dist + 1)); } } } return ret; }
{ let dislike = calculate_dislike(&solution, &input.hole); let mut gx: f64 = 0.0; let mut gy: f64 = 0.0; for p in solution.iter() { gx += p.x(); gy += p.y(); } gx /= solution.len() as f64; gy /= solution.len() as f64; let mut vx: f64 = 0.0; let mut vy: f64 = 0.0; for p in solution.iter() { vx += pow2(p.x() - gx); vy += pow2(p.y() - gy); } vx /= solution.len() as f64; vy /= solution.len() as f64;
identifier_body
annealing3.rs
use crate::common::*; use geo::algorithm::coords_iter::CoordsIter; use rand::prelude::*; use rand::seq::SliceRandom; use std::collections::VecDeque; use std::time::{Duration, Instant}; static SEED: [u8; 32] = [ 0xfd, 0x00, 0xf1, 0x5c, 0xde, 0x01, 0x11, 0xc6, 0xc3, 0xea, 0xfb, 0xbf, 0xf3, 0xca, 0xd8, 0x32, 0x6a, 0xe3, 0x07, 0x99, 0xc5, 0xe0, 0x52, 0xe4, 0xaa, 0x35, 0x07, 0x99, 0xe3, 0x2b, 0x9d, 0xc6, ]; fn tscore(solution: &Vec<Point>, input: &Input) -> (f64, f64) { let dislike = calculate_dislike(&solution, &input.hole); let mut gx: f64 = 0.0; let mut gy: f64 = 0.0; for p in solution.iter() { gx += p.x(); gy += p.y(); } gx /= solution.len() as f64; gy /= solution.len() as f64; let mut vx: f64 = 0.0; let mut vy: f64 = 0.0; for p in solution.iter() { vx += pow2(p.x() - gx); vy += pow2(p.y() - gy); } vx /= solution.len() as f64; vy /= solution.len() as f64; ( dislike / (input.hole.exterior().coords_count() as f64), -(vx + vy), ) } fn ascore(value: (f64, f64), progress: f64) -> f64 { value.0 * progress + (1.0 - progress) * value.1 } pub fn solve( input: &Input, mut solution: Vec<Point>, time_limit: Duration, fix_seed: bool, initial_temperature: f64, ) -> (Vec<Point>, f64) { let n = solution.len(); let mut rng = if fix_seed { SmallRng::from_seed(SEED) } else { SmallRng::from_entropy() }; let mut current_score = tscore(&solution, &input); let out_edges = make_out_edges(&input.figure.edges, n); let original_vertices = &input.figure.vertices; let mut orders = vec![vec![]; n]; for i in 0..n { orders[i] = make_determined_order(&out_edges, Some(i)); } let start_at = Instant::now(); let mut best_solution = solution.clone(); let mut best_score = current_score; let mut progress = 0.0; let mut temperature = initial_temperature; eprintln!("initial_temperature = {}", initial_temperature); let distance_sums = calc_distance_sums(&out_edges, original_vertices.len()); let distance_total: usize = distance_sums.iter().sum(); // eprintln!("{} {:?}", distance_total, distance_sums); let mut iter = 0; let mut move_count = 0; loop { // check time limit iter += 1; if iter % 100 == 0 { let elapsed = Instant::now() - start_at; if best_score.0 == 0.0 || elapsed >= time_limit { eprintln!("iter = {}, move_count = {}", iter, move_count); let dislike = calculate_dislike(&best_solution, &input.hole); return (best_solution, dislike); }
temperature = initial_temperature * (1.0 - progress) * (-progress).exp2(); } // move to neighbor let r = rng.gen::<f64>(); if r > progress { let mut i = 0; { let r = rng.gen::<usize>() % distance_total; let mut sum = 0; for index in 0..n { sum += distance_sums[index]; if r < sum { i = index; break; } } } let w = rng.gen::<usize>() % 40 + 5; let next_solution = random_move_one_point(i, w, &solution, &input, &mut rng, &out_edges, &orders); if next_solution.is_none() { continue; } move_count += 1; let next_solution = next_solution.unwrap(); // calculate score. FIXME: slow let new_score = tscore(&next_solution, &input); let accept = { let current = ascore(current_score, progress); let new = ascore(new_score, progress); if new < current { true } else { // new_score >= current_score let delta = new - current; let accept_prob = (-delta / temperature).exp(); rng.gen::<f64>() < accept_prob } }; if accept { // accept candidate current_score = new_score; solution = next_solution; } } else { let i = rng.gen::<usize>() % n; let candidate = make_next_candidates( i, original_vertices, &input.hole, input.epsilon, &solution, &out_edges, &mut rng, ); if candidate!= original_vertices[i] { move_count += 1; } // calculate score. FIXME: slow let old = solution[i]; solution[i] = candidate; let new_score = tscore(&solution, &input); let accept = { let current = ascore(current_score, progress); let new = ascore(new_score, progress); if new < current { true } else { // new_score >= current_score let delta = new - current; let accept_prob = (-delta / temperature).exp(); rng.gen::<f64>() < accept_prob } }; if accept { // accept candidate current_score = new_score; } else { // reject candidate solution[i] = old; } } if current_score < best_score { best_score = current_score; best_solution = solution.clone(); } } } fn make_next_candidates( i: usize, original_vertices: &[Point], hole: &Polygon, epsilon: i64, solution: &[Point], out_edges: &[Vec<usize>], rng: &mut SmallRng, ) -> Point { let some_neighbor = out_edges[i][0]; let original_squared_distance = squared_distance(&original_vertices[i], &original_vertices[some_neighbor]); if original_squared_distance < 100.0 || epsilon < 100000 { let ring = Ring::from_epsilon(solution[some_neighbor], epsilon, original_squared_distance); let mut points = ring_points(&ring); points.shuffle(rng); for &p in points.iter() { if!is_valid_point_move(i, &p, solution, original_vertices, out_edges, hole, epsilon) { continue; } return p; } } else { let od = original_squared_distance.sqrt(); let low = od * (1.0 - epsilon as f64 / 1000000.0).sqrt(); let high = od * (1.0 + epsilon as f64 / 1000000.0).sqrt(); for _iter in 0..100 { let d = low + (high - low) * rng.gen::<f64>(); let theta = 2.0 * std::f64::consts::PI * rng.gen::<f64>(); let vect = Point::new( (theta.cos() * d + 0.5).floor(), (theta.sin() * d + 0.5).floor(), ); let p = solution[some_neighbor] + vect; if!is_valid_point_move(i, &p, solution, original_vertices, out_edges, hole, epsilon) { continue; } return p; } return solution[i]; } unreachable!() } fn is_valid_point_move( index: usize, p: &Point, solution: &[Point], original_vertices: &[Point], out_edges: &[Vec<usize>], hole: &Polygon, epsilon: i64, ) -> bool { let ok1 = out_edges[index].iter().all(|&dst| { is_allowed_distance( &p, &solution[dst], &original_vertices[index], &original_vertices[dst], epsilon, false, ) }); if!ok1 { return false; } let ok2 = out_edges[index] .iter() .all(|&dst| does_line_fit_in_hole(&p, &solution[dst], hole)); if!ok2 { return false; } return true; } fn random_move_one_point( from: usize, w: usize, solution: &Vec<Point>, input: &Input, rng: &mut SmallRng, out_edges: &Vec<Vec<usize>>, orders: &Vec<Vec<usize>>, ) -> Option<Vec<Point>> { let mut gx: f64 = 0.0; let mut gy: f64 = 0.0; for p in solution.iter() { gx += p.x(); gy += p.y(); } gx /= solution.len() as f64; gy /= solution.len() as f64; let g = Point::new(gx, gy); let mut vect1 = solution[from] - g; vect1 = vect1 / squared_distance(&solution[from], &g).sqrt(); let mut np = solution[from]; for iter in 0..5 { let dx = (rng.gen::<usize>() % (w * 2 + 1)) as f64 - w as f64; let dy = (rng.gen::<usize>() % (w * 2 + 1)) as f64 - w as f64; let vect2 = Point::new(dx, dy) / (dx * dx + dy * dy).sqrt(); np = solution[from] + Point::new(dx, dy); if vect1.dot(vect2) > 0.4 - iter as f64 * 0.2 { break; } } if solution[from] == np { return None; } let mut solution = solution.clone(); let old = solution[from]; solution[from] = np; let next_solution = fix_allowed_distance_violation(from, &solution, &input, &out_edges, &orders); solution[from] = old; return next_solution; } fn calc_distance_sums(edges: &Vec<Vec<usize>>, n: usize) -> Vec<usize> { let mut ret = vec![0; n]; for start in 0..n { let mut visited = vec![false; n]; visited[start] = true; let mut que = VecDeque::new(); que.push_back((start, 0)); while let Some((from, dist)) = que.pop_front() { ret[start] += dist * dist; // ret[start] += dist; for &to in edges[from].iter() { if visited[to] { continue; } visited[to] = true; que.push_back((to, dist + 1)); } } } return ret; }
// tweak temperature progress = elapsed.as_secs_f64() / time_limit.as_secs_f64();
random_line_split
annealing3.rs
use crate::common::*; use geo::algorithm::coords_iter::CoordsIter; use rand::prelude::*; use rand::seq::SliceRandom; use std::collections::VecDeque; use std::time::{Duration, Instant}; static SEED: [u8; 32] = [ 0xfd, 0x00, 0xf1, 0x5c, 0xde, 0x01, 0x11, 0xc6, 0xc3, 0xea, 0xfb, 0xbf, 0xf3, 0xca, 0xd8, 0x32, 0x6a, 0xe3, 0x07, 0x99, 0xc5, 0xe0, 0x52, 0xe4, 0xaa, 0x35, 0x07, 0x99, 0xe3, 0x2b, 0x9d, 0xc6, ]; fn tscore(solution: &Vec<Point>, input: &Input) -> (f64, f64) { let dislike = calculate_dislike(&solution, &input.hole); let mut gx: f64 = 0.0; let mut gy: f64 = 0.0; for p in solution.iter() { gx += p.x(); gy += p.y(); } gx /= solution.len() as f64; gy /= solution.len() as f64; let mut vx: f64 = 0.0; let mut vy: f64 = 0.0; for p in solution.iter() { vx += pow2(p.x() - gx); vy += pow2(p.y() - gy); } vx /= solution.len() as f64; vy /= solution.len() as f64; ( dislike / (input.hole.exterior().coords_count() as f64), -(vx + vy), ) } fn ascore(value: (f64, f64), progress: f64) -> f64 { value.0 * progress + (1.0 - progress) * value.1 } pub fn solve( input: &Input, mut solution: Vec<Point>, time_limit: Duration, fix_seed: bool, initial_temperature: f64, ) -> (Vec<Point>, f64) { let n = solution.len(); let mut rng = if fix_seed { SmallRng::from_seed(SEED) } else { SmallRng::from_entropy() }; let mut current_score = tscore(&solution, &input); let out_edges = make_out_edges(&input.figure.edges, n); let original_vertices = &input.figure.vertices; let mut orders = vec![vec![]; n]; for i in 0..n { orders[i] = make_determined_order(&out_edges, Some(i)); } let start_at = Instant::now(); let mut best_solution = solution.clone(); let mut best_score = current_score; let mut progress = 0.0; let mut temperature = initial_temperature; eprintln!("initial_temperature = {}", initial_temperature); let distance_sums = calc_distance_sums(&out_edges, original_vertices.len()); let distance_total: usize = distance_sums.iter().sum(); // eprintln!("{} {:?}", distance_total, distance_sums); let mut iter = 0; let mut move_count = 0; loop { // check time limit iter += 1; if iter % 100 == 0 { let elapsed = Instant::now() - start_at; if best_score.0 == 0.0 || elapsed >= time_limit { eprintln!("iter = {}, move_count = {}", iter, move_count); let dislike = calculate_dislike(&best_solution, &input.hole); return (best_solution, dislike); } // tweak temperature progress = elapsed.as_secs_f64() / time_limit.as_secs_f64(); temperature = initial_temperature * (1.0 - progress) * (-progress).exp2(); } // move to neighbor let r = rng.gen::<f64>(); if r > progress { let mut i = 0; { let r = rng.gen::<usize>() % distance_total; let mut sum = 0; for index in 0..n { sum += distance_sums[index]; if r < sum { i = index; break; } } } let w = rng.gen::<usize>() % 40 + 5; let next_solution = random_move_one_point(i, w, &solution, &input, &mut rng, &out_edges, &orders); if next_solution.is_none() { continue; } move_count += 1; let next_solution = next_solution.unwrap(); // calculate score. FIXME: slow let new_score = tscore(&next_solution, &input); let accept = { let current = ascore(current_score, progress); let new = ascore(new_score, progress); if new < current { true } else { // new_score >= current_score let delta = new - current; let accept_prob = (-delta / temperature).exp(); rng.gen::<f64>() < accept_prob } }; if accept { // accept candidate current_score = new_score; solution = next_solution; } } else { let i = rng.gen::<usize>() % n; let candidate = make_next_candidates( i, original_vertices, &input.hole, input.epsilon, &solution, &out_edges, &mut rng, ); if candidate!= original_vertices[i] { move_count += 1; } // calculate score. FIXME: slow let old = solution[i]; solution[i] = candidate; let new_score = tscore(&solution, &input); let accept = { let current = ascore(current_score, progress); let new = ascore(new_score, progress); if new < current { true } else { // new_score >= current_score let delta = new - current; let accept_prob = (-delta / temperature).exp(); rng.gen::<f64>() < accept_prob } }; if accept { // accept candidate current_score = new_score; } else { // reject candidate solution[i] = old; } } if current_score < best_score { best_score = current_score; best_solution = solution.clone(); } } } fn make_next_candidates( i: usize, original_vertices: &[Point], hole: &Polygon, epsilon: i64, solution: &[Point], out_edges: &[Vec<usize>], rng: &mut SmallRng, ) -> Point { let some_neighbor = out_edges[i][0]; let original_squared_distance = squared_distance(&original_vertices[i], &original_vertices[some_neighbor]); if original_squared_distance < 100.0 || epsilon < 100000 { let ring = Ring::from_epsilon(solution[some_neighbor], epsilon, original_squared_distance); let mut points = ring_points(&ring); points.shuffle(rng); for &p in points.iter() { if!is_valid_point_move(i, &p, solution, original_vertices, out_edges, hole, epsilon) { continue; } return p; } } else { let od = original_squared_distance.sqrt(); let low = od * (1.0 - epsilon as f64 / 1000000.0).sqrt(); let high = od * (1.0 + epsilon as f64 / 1000000.0).sqrt(); for _iter in 0..100 { let d = low + (high - low) * rng.gen::<f64>(); let theta = 2.0 * std::f64::consts::PI * rng.gen::<f64>(); let vect = Point::new( (theta.cos() * d + 0.5).floor(), (theta.sin() * d + 0.5).floor(), ); let p = solution[some_neighbor] + vect; if!is_valid_point_move(i, &p, solution, original_vertices, out_edges, hole, epsilon)
return p; } return solution[i]; } unreachable!() } fn is_valid_point_move( index: usize, p: &Point, solution: &[Point], original_vertices: &[Point], out_edges: &[Vec<usize>], hole: &Polygon, epsilon: i64, ) -> bool { let ok1 = out_edges[index].iter().all(|&dst| { is_allowed_distance( &p, &solution[dst], &original_vertices[index], &original_vertices[dst], epsilon, false, ) }); if!ok1 { return false; } let ok2 = out_edges[index] .iter() .all(|&dst| does_line_fit_in_hole(&p, &solution[dst], hole)); if!ok2 { return false; } return true; } fn random_move_one_point( from: usize, w: usize, solution: &Vec<Point>, input: &Input, rng: &mut SmallRng, out_edges: &Vec<Vec<usize>>, orders: &Vec<Vec<usize>>, ) -> Option<Vec<Point>> { let mut gx: f64 = 0.0; let mut gy: f64 = 0.0; for p in solution.iter() { gx += p.x(); gy += p.y(); } gx /= solution.len() as f64; gy /= solution.len() as f64; let g = Point::new(gx, gy); let mut vect1 = solution[from] - g; vect1 = vect1 / squared_distance(&solution[from], &g).sqrt(); let mut np = solution[from]; for iter in 0..5 { let dx = (rng.gen::<usize>() % (w * 2 + 1)) as f64 - w as f64; let dy = (rng.gen::<usize>() % (w * 2 + 1)) as f64 - w as f64; let vect2 = Point::new(dx, dy) / (dx * dx + dy * dy).sqrt(); np = solution[from] + Point::new(dx, dy); if vect1.dot(vect2) > 0.4 - iter as f64 * 0.2 { break; } } if solution[from] == np { return None; } let mut solution = solution.clone(); let old = solution[from]; solution[from] = np; let next_solution = fix_allowed_distance_violation(from, &solution, &input, &out_edges, &orders); solution[from] = old; return next_solution; } fn calc_distance_sums(edges: &Vec<Vec<usize>>, n: usize) -> Vec<usize> { let mut ret = vec![0; n]; for start in 0..n { let mut visited = vec![false; n]; visited[start] = true; let mut que = VecDeque::new(); que.push_back((start, 0)); while let Some((from, dist)) = que.pop_front() { ret[start] += dist * dist; // ret[start] += dist; for &to in edges[from].iter() { if visited[to] { continue; } visited[to] = true; que.push_back((to, dist + 1)); } } } return ret; }
{ continue; }
conditional_block
annealing3.rs
use crate::common::*; use geo::algorithm::coords_iter::CoordsIter; use rand::prelude::*; use rand::seq::SliceRandom; use std::collections::VecDeque; use std::time::{Duration, Instant}; static SEED: [u8; 32] = [ 0xfd, 0x00, 0xf1, 0x5c, 0xde, 0x01, 0x11, 0xc6, 0xc3, 0xea, 0xfb, 0xbf, 0xf3, 0xca, 0xd8, 0x32, 0x6a, 0xe3, 0x07, 0x99, 0xc5, 0xe0, 0x52, 0xe4, 0xaa, 0x35, 0x07, 0x99, 0xe3, 0x2b, 0x9d, 0xc6, ]; fn tscore(solution: &Vec<Point>, input: &Input) -> (f64, f64) { let dislike = calculate_dislike(&solution, &input.hole); let mut gx: f64 = 0.0; let mut gy: f64 = 0.0; for p in solution.iter() { gx += p.x(); gy += p.y(); } gx /= solution.len() as f64; gy /= solution.len() as f64; let mut vx: f64 = 0.0; let mut vy: f64 = 0.0; for p in solution.iter() { vx += pow2(p.x() - gx); vy += pow2(p.y() - gy); } vx /= solution.len() as f64; vy /= solution.len() as f64; ( dislike / (input.hole.exterior().coords_count() as f64), -(vx + vy), ) } fn ascore(value: (f64, f64), progress: f64) -> f64 { value.0 * progress + (1.0 - progress) * value.1 } pub fn solve( input: &Input, mut solution: Vec<Point>, time_limit: Duration, fix_seed: bool, initial_temperature: f64, ) -> (Vec<Point>, f64) { let n = solution.len(); let mut rng = if fix_seed { SmallRng::from_seed(SEED) } else { SmallRng::from_entropy() }; let mut current_score = tscore(&solution, &input); let out_edges = make_out_edges(&input.figure.edges, n); let original_vertices = &input.figure.vertices; let mut orders = vec![vec![]; n]; for i in 0..n { orders[i] = make_determined_order(&out_edges, Some(i)); } let start_at = Instant::now(); let mut best_solution = solution.clone(); let mut best_score = current_score; let mut progress = 0.0; let mut temperature = initial_temperature; eprintln!("initial_temperature = {}", initial_temperature); let distance_sums = calc_distance_sums(&out_edges, original_vertices.len()); let distance_total: usize = distance_sums.iter().sum(); // eprintln!("{} {:?}", distance_total, distance_sums); let mut iter = 0; let mut move_count = 0; loop { // check time limit iter += 1; if iter % 100 == 0 { let elapsed = Instant::now() - start_at; if best_score.0 == 0.0 || elapsed >= time_limit { eprintln!("iter = {}, move_count = {}", iter, move_count); let dislike = calculate_dislike(&best_solution, &input.hole); return (best_solution, dislike); } // tweak temperature progress = elapsed.as_secs_f64() / time_limit.as_secs_f64(); temperature = initial_temperature * (1.0 - progress) * (-progress).exp2(); } // move to neighbor let r = rng.gen::<f64>(); if r > progress { let mut i = 0; { let r = rng.gen::<usize>() % distance_total; let mut sum = 0; for index in 0..n { sum += distance_sums[index]; if r < sum { i = index; break; } } } let w = rng.gen::<usize>() % 40 + 5; let next_solution = random_move_one_point(i, w, &solution, &input, &mut rng, &out_edges, &orders); if next_solution.is_none() { continue; } move_count += 1; let next_solution = next_solution.unwrap(); // calculate score. FIXME: slow let new_score = tscore(&next_solution, &input); let accept = { let current = ascore(current_score, progress); let new = ascore(new_score, progress); if new < current { true } else { // new_score >= current_score let delta = new - current; let accept_prob = (-delta / temperature).exp(); rng.gen::<f64>() < accept_prob } }; if accept { // accept candidate current_score = new_score; solution = next_solution; } } else { let i = rng.gen::<usize>() % n; let candidate = make_next_candidates( i, original_vertices, &input.hole, input.epsilon, &solution, &out_edges, &mut rng, ); if candidate!= original_vertices[i] { move_count += 1; } // calculate score. FIXME: slow let old = solution[i]; solution[i] = candidate; let new_score = tscore(&solution, &input); let accept = { let current = ascore(current_score, progress); let new = ascore(new_score, progress); if new < current { true } else { // new_score >= current_score let delta = new - current; let accept_prob = (-delta / temperature).exp(); rng.gen::<f64>() < accept_prob } }; if accept { // accept candidate current_score = new_score; } else { // reject candidate solution[i] = old; } } if current_score < best_score { best_score = current_score; best_solution = solution.clone(); } } } fn make_next_candidates( i: usize, original_vertices: &[Point], hole: &Polygon, epsilon: i64, solution: &[Point], out_edges: &[Vec<usize>], rng: &mut SmallRng, ) -> Point { let some_neighbor = out_edges[i][0]; let original_squared_distance = squared_distance(&original_vertices[i], &original_vertices[some_neighbor]); if original_squared_distance < 100.0 || epsilon < 100000 { let ring = Ring::from_epsilon(solution[some_neighbor], epsilon, original_squared_distance); let mut points = ring_points(&ring); points.shuffle(rng); for &p in points.iter() { if!is_valid_point_move(i, &p, solution, original_vertices, out_edges, hole, epsilon) { continue; } return p; } } else { let od = original_squared_distance.sqrt(); let low = od * (1.0 - epsilon as f64 / 1000000.0).sqrt(); let high = od * (1.0 + epsilon as f64 / 1000000.0).sqrt(); for _iter in 0..100 { let d = low + (high - low) * rng.gen::<f64>(); let theta = 2.0 * std::f64::consts::PI * rng.gen::<f64>(); let vect = Point::new( (theta.cos() * d + 0.5).floor(), (theta.sin() * d + 0.5).floor(), ); let p = solution[some_neighbor] + vect; if!is_valid_point_move(i, &p, solution, original_vertices, out_edges, hole, epsilon) { continue; } return p; } return solution[i]; } unreachable!() } fn is_valid_point_move( index: usize, p: &Point, solution: &[Point], original_vertices: &[Point], out_edges: &[Vec<usize>], hole: &Polygon, epsilon: i64, ) -> bool { let ok1 = out_edges[index].iter().all(|&dst| { is_allowed_distance( &p, &solution[dst], &original_vertices[index], &original_vertices[dst], epsilon, false, ) }); if!ok1 { return false; } let ok2 = out_edges[index] .iter() .all(|&dst| does_line_fit_in_hole(&p, &solution[dst], hole)); if!ok2 { return false; } return true; } fn
( from: usize, w: usize, solution: &Vec<Point>, input: &Input, rng: &mut SmallRng, out_edges: &Vec<Vec<usize>>, orders: &Vec<Vec<usize>>, ) -> Option<Vec<Point>> { let mut gx: f64 = 0.0; let mut gy: f64 = 0.0; for p in solution.iter() { gx += p.x(); gy += p.y(); } gx /= solution.len() as f64; gy /= solution.len() as f64; let g = Point::new(gx, gy); let mut vect1 = solution[from] - g; vect1 = vect1 / squared_distance(&solution[from], &g).sqrt(); let mut np = solution[from]; for iter in 0..5 { let dx = (rng.gen::<usize>() % (w * 2 + 1)) as f64 - w as f64; let dy = (rng.gen::<usize>() % (w * 2 + 1)) as f64 - w as f64; let vect2 = Point::new(dx, dy) / (dx * dx + dy * dy).sqrt(); np = solution[from] + Point::new(dx, dy); if vect1.dot(vect2) > 0.4 - iter as f64 * 0.2 { break; } } if solution[from] == np { return None; } let mut solution = solution.clone(); let old = solution[from]; solution[from] = np; let next_solution = fix_allowed_distance_violation(from, &solution, &input, &out_edges, &orders); solution[from] = old; return next_solution; } fn calc_distance_sums(edges: &Vec<Vec<usize>>, n: usize) -> Vec<usize> { let mut ret = vec![0; n]; for start in 0..n { let mut visited = vec![false; n]; visited[start] = true; let mut que = VecDeque::new(); que.push_back((start, 0)); while let Some((from, dist)) = que.pop_front() { ret[start] += dist * dist; // ret[start] += dist; for &to in edges[from].iter() { if visited[to] { continue; } visited[to] = true; que.push_back((to, dist + 1)); } } } return ret; }
random_move_one_point
identifier_name
mod.rs
use futures::prelude::*; use http::Uri; use slog::Logger; use std::{ iter::FromIterator, path::{Path, PathBuf}, str::FromStr, }; use crate::{ cache::{self, Cacheable, Cache as _}, download, error::prelude::*, }; use tokio::io::AsyncReadExt; mod hash_writer; use hash_writer::HashWriter; mod error{ use snafu::Snafu; #[derive(Debug,Snafu)] #[snafu(visibility(pub))] pub enum Error{ #[snafu(display("Invalid uri: {}", source))] BadUri{ source: http::uri::InvalidUri, }, #[snafu(display("Invalid url: {}", source))] BadUrl{ source: url::ParseError, }, } } #[derive(Debug)] pub enum VerifyResult { Good, Bad, NotInCache, } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Hash)] pub struct Artifact { pub group: String, pub artifact: String, pub version: String, pub classifier: Option<String>, pub extension: Option<String>, } #[derive(Debug, Clone)] pub struct ResolvedArtifact { pub artifact: Artifact, pub repo: Uri, } pub struct Cache; impl Cacheable for ResolvedArtifact { type Cache = crate::cache::FileCache; fn cached_path(&self) -> PathBuf { let mut p = PathBuf::new(); p.push(app_dirs::app_dir(app_dirs::AppDataType::UserCache, crate::APP_INFO, "maven_cache").expect("Cache directory must be accesible")); p.push(&self.artifact.to_path()); p } fn uri(&self) -> crate::cache::Result<Uri> { crate::cache::ResultExt::erased(self.artifact.get_uri_on(&self.repo)) } } impl cache::Cache<ResolvedArtifact> for Cache { fn with( artifact: ResolvedArtifact, manager: download::Manager, log: Logger, ) -> crate::cache::BoxFuture<PathBuf> { let cached_path = artifact.cached_path(); let log = log.new( o!("artifact"=>artifact.artifact.to_string(),"repo"=>artifact.repo.to_string(),"cached_path"=>cached_path.as_path().to_string_lossy().into_owned()), ); Box::pin(async move{ info!(log, "caching maven artifact"); if!Self::is_cached(&artifact) { info!(log, "artifact is not cached, downloading now"); let uri = artifact.uri()?; manager .download(uri.clone(), cached_path.clone(), false, &log).await.context(crate::cache::error::Downloading{uri})?; } Ok(cached_path) }) } } impl Cache { pub async fn verify_cached( resolved: ResolvedArtifact, manager: download::Manager, ) -> download::Result<VerifyResult> { if Self::is_cached(&resolved) { let cached_path = resolved.cached_path(); let sha_url_res = resolved.sha_uri(); let mut cached_file = tokio::fs::File::open(cached_path).await.context(download::error::Io)?; let mut sha = HashWriter::new(); cached_file.copy(&mut sha).await.context(download::error::Io)?; let cached_sha = sha.digest(); let sha_uri = sha_url_res?; let (res,_) = manager.get(sha_uri)?.await?; let hash_str = res.into_body().map_ok(hyper::Chunk::into_bytes).try_concat().await.context(download::error::Hyper)?; if hash_str == format!("{}", cached_sha) { Ok(VerifyResult::Good) } else { Ok(VerifyResult::Bad) } } else { Ok(VerifyResult::NotInCache) } } } impl Artifact { fn to_path(&self) -> PathBuf { let mut p = PathBuf::new(); p.push(&self.group_path()); p.push(&self.artifact); p.push(&self.version); p.push(&self.artifact_filename()); p } pub fn get_uri_on(&self, base: &Uri) -> Result<Uri,error::Error> { let base = crate::util::uri_to_url(base).context(error::BadUrl)?; let path = self.to_path(); let url = base.join(path.to_str().expect("non unicode path encountered")).context(error::BadUrl)?; crate::util::url_to_uri(&url).context(error::BadUri) } fn group_path(&self) -> PathBuf { PathBuf::from_iter(self.group.split('.')) } fn artifact_filename(&self) -> String { let classifier_fmt = match self.classifier { Some(ref class) => format!("-{classifier}", classifier = class), None => "".to_string(), }; let extension_fmt = match self.extension { Some(ref extension) => extension.clone(), None => "jar".to_string(), }; format!( "{artifact}-{version}{classifier}.{extension}", artifact = self.artifact, version = self.version, classifier = classifier_fmt, extension = extension_fmt ) } pub fn
(&self, repo_uri: Uri) -> ResolvedArtifact { ResolvedArtifact { artifact: self.clone(), repo: repo_uri, } } pub fn download_from( &self, location: &Path, repo_uri: Uri, manager: download::Manager, log: Logger, ) -> impl Future<Output=Result<(), crate::cache::Error>> + Send { Cache::install_at(self.resolve(repo_uri), location.to_owned(), manager, log) } } impl ResolvedArtifact { pub fn to_path(&self) -> PathBuf { self.artifact.to_path() } pub fn sha_uri(&self) -> crate::download::Result<Uri> { let mut url = crate::util::uri_to_url(&self.uri().context(download::error::Cached)?).context(download::error::BadUrl)?; let mut path = url.path().to_owned(); path.push_str(".sha1"); url.set_path(path.as_ref()); crate::util::url_to_uri(&url).context(download::error::BadUri) } pub fn install_at_no_classifier( self, location: PathBuf, manager: download::Manager, log: Logger, ) -> impl Future<Output=crate::cache::Result<()>> + Send { async move{ let cached_path_no_classifier = Self { artifact: Artifact { classifier: None, ..self.artifact.clone() }, repo: self.repo.clone(), }.cached_path(); let filename = cached_path_no_classifier.file_name().expect("Maven artifact should have a filename"); <Self as Cacheable>::install_at_custom_filename(self, location, filename.to_os_string(), manager, log).await } } } #[derive(Debug, PartialEq, Eq)] pub enum ArtifactParseError { BadNumberOfParts, } impl ToString for Artifact { fn to_string(&self) -> String { let mut strn = String::new(); strn.push_str(&self.group); strn.push(':'); strn.push_str(&self.artifact); strn.push(':'); strn.push_str(&self.version); if let Some(ref classifier) = self.classifier { strn.push(':'); strn.push_str(classifier); } if let Some(ref ext) = self.extension { strn.push('@'); strn.push_str(ext); } strn } } impl FromStr for Artifact { type Err = ArtifactParseError; fn from_str(s: &str) -> ::std::result::Result<Self, Self::Err> { let parts: Vec<&str> = s.split('@').collect(); let (s, ext): (&str, Option<String>) = match *parts.as_slice() { [s, ext] => (s, Some(ext.to_string())), _ => (s, None), }; let parts = s.split(':'); let parts: Vec<&str> = parts.collect(); match *parts.as_slice() { [grp, art, ver] => Ok(Self { group: grp.into(), artifact: art.into(), version: ver.into(), classifier: None, extension: ext, }), [grp, art, ver, class] => Ok(Self { group: grp.into(), artifact: art.into(), version: ver.into(), classifier: Some(class.into()), extension: ext, }), _ => Err(ArtifactParseError::BadNumberOfParts), } } } #[cfg(test)] mod test { use super::Artifact; #[test] fn parses_simple() { assert_eq!( "net.minecraftforge.forge:some-jar:some-version".parse(), Ok(Artifact { group: "net.minecraftforge.forge".into(), artifact: "some-jar".into(), version: "some-version".into(), classifier: None, extension: None, }) ) } #[test] fn parses_with_ext() { assert_eq!( "net.minecraftforge.forge:some-jar:some-version@zip".parse(), Ok(Artifact { group: "net.minecraftforge.forge".into(), artifact: "some-jar".into(), version: "some-version".into(), classifier: None, extension: Some("zip".into()), }) ) } #[test] fn parses_with_classifier() { assert_eq!( "net.minecraftforge.forge:some-jar:some-version:universal".parse(), Ok(Artifact { group: "net.minecraftforge.forge".into(), artifact: "some-jar".into(), version: "some-version".into(), classifier: Some("universal".into()), extension: None, }) ) } #[test] fn parses_with_ext_and_classifier() { assert_eq!( "net.minecraftforge.forge:some-jar:some-version:universal@zip".parse(), Ok(Artifact { group: "net.minecraftforge.forge".into(), artifact: "some-jar".into(), version: "some-version".into(), classifier: Some("universal".into()), extension: Some("zip".into()), }) ) } }
resolve
identifier_name
mod.rs
use futures::prelude::*; use http::Uri; use slog::Logger; use std::{ iter::FromIterator, path::{Path, PathBuf}, str::FromStr, }; use crate::{ cache::{self, Cacheable, Cache as _}, download, error::prelude::*, }; use tokio::io::AsyncReadExt; mod hash_writer; use hash_writer::HashWriter; mod error{ use snafu::Snafu; #[derive(Debug,Snafu)] #[snafu(visibility(pub))] pub enum Error{ #[snafu(display("Invalid uri: {}", source))] BadUri{ source: http::uri::InvalidUri, }, #[snafu(display("Invalid url: {}", source))] BadUrl{ source: url::ParseError, }, } } #[derive(Debug)] pub enum VerifyResult { Good, Bad, NotInCache, } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Hash)] pub struct Artifact { pub group: String, pub artifact: String, pub version: String, pub classifier: Option<String>, pub extension: Option<String>, } #[derive(Debug, Clone)] pub struct ResolvedArtifact { pub artifact: Artifact, pub repo: Uri, } pub struct Cache; impl Cacheable for ResolvedArtifact { type Cache = crate::cache::FileCache; fn cached_path(&self) -> PathBuf { let mut p = PathBuf::new(); p.push(app_dirs::app_dir(app_dirs::AppDataType::UserCache, crate::APP_INFO, "maven_cache").expect("Cache directory must be accesible")); p.push(&self.artifact.to_path()); p } fn uri(&self) -> crate::cache::Result<Uri> { crate::cache::ResultExt::erased(self.artifact.get_uri_on(&self.repo)) } } impl cache::Cache<ResolvedArtifact> for Cache { fn with( artifact: ResolvedArtifact, manager: download::Manager, log: Logger, ) -> crate::cache::BoxFuture<PathBuf> { let cached_path = artifact.cached_path(); let log = log.new( o!("artifact"=>artifact.artifact.to_string(),"repo"=>artifact.repo.to_string(),"cached_path"=>cached_path.as_path().to_string_lossy().into_owned()), ); Box::pin(async move{ info!(log, "caching maven artifact"); if!Self::is_cached(&artifact) { info!(log, "artifact is not cached, downloading now"); let uri = artifact.uri()?; manager .download(uri.clone(), cached_path.clone(), false, &log).await.context(crate::cache::error::Downloading{uri})?; } Ok(cached_path) }) } } impl Cache { pub async fn verify_cached( resolved: ResolvedArtifact, manager: download::Manager, ) -> download::Result<VerifyResult> { if Self::is_cached(&resolved) { let cached_path = resolved.cached_path(); let sha_url_res = resolved.sha_uri(); let mut cached_file = tokio::fs::File::open(cached_path).await.context(download::error::Io)?; let mut sha = HashWriter::new(); cached_file.copy(&mut sha).await.context(download::error::Io)?; let cached_sha = sha.digest(); let sha_uri = sha_url_res?; let (res,_) = manager.get(sha_uri)?.await?; let hash_str = res.into_body().map_ok(hyper::Chunk::into_bytes).try_concat().await.context(download::error::Hyper)?; if hash_str == format!("{}", cached_sha) { Ok(VerifyResult::Good) } else { Ok(VerifyResult::Bad) } } else { Ok(VerifyResult::NotInCache) } } } impl Artifact { fn to_path(&self) -> PathBuf { let mut p = PathBuf::new(); p.push(&self.group_path()); p.push(&self.artifact); p.push(&self.version); p.push(&self.artifact_filename()); p } pub fn get_uri_on(&self, base: &Uri) -> Result<Uri,error::Error> { let base = crate::util::uri_to_url(base).context(error::BadUrl)?; let path = self.to_path(); let url = base.join(path.to_str().expect("non unicode path encountered")).context(error::BadUrl)?; crate::util::url_to_uri(&url).context(error::BadUri) } fn group_path(&self) -> PathBuf { PathBuf::from_iter(self.group.split('.')) } fn artifact_filename(&self) -> String { let classifier_fmt = match self.classifier { Some(ref class) => format!("-{classifier}", classifier = class), None => "".to_string(), }; let extension_fmt = match self.extension { Some(ref extension) => extension.clone(), None => "jar".to_string(), }; format!( "{artifact}-{version}{classifier}.{extension}", artifact = self.artifact, version = self.version, classifier = classifier_fmt, extension = extension_fmt ) } pub fn resolve(&self, repo_uri: Uri) -> ResolvedArtifact { ResolvedArtifact { artifact: self.clone(), repo: repo_uri, } } pub fn download_from( &self, location: &Path, repo_uri: Uri, manager: download::Manager, log: Logger, ) -> impl Future<Output=Result<(), crate::cache::Error>> + Send { Cache::install_at(self.resolve(repo_uri), location.to_owned(), manager, log) } } impl ResolvedArtifact { pub fn to_path(&self) -> PathBuf { self.artifact.to_path() } pub fn sha_uri(&self) -> crate::download::Result<Uri> { let mut url = crate::util::uri_to_url(&self.uri().context(download::error::Cached)?).context(download::error::BadUrl)?; let mut path = url.path().to_owned(); path.push_str(".sha1"); url.set_path(path.as_ref()); crate::util::url_to_uri(&url).context(download::error::BadUri) } pub fn install_at_no_classifier( self, location: PathBuf, manager: download::Manager, log: Logger, ) -> impl Future<Output=crate::cache::Result<()>> + Send { async move{ let cached_path_no_classifier = Self { artifact: Artifact { classifier: None, ..self.artifact.clone() }, repo: self.repo.clone(), }.cached_path(); let filename = cached_path_no_classifier.file_name().expect("Maven artifact should have a filename"); <Self as Cacheable>::install_at_custom_filename(self, location, filename.to_os_string(), manager, log).await } } } #[derive(Debug, PartialEq, Eq)] pub enum ArtifactParseError { BadNumberOfParts, } impl ToString for Artifact { fn to_string(&self) -> String { let mut strn = String::new(); strn.push_str(&self.group); strn.push(':'); strn.push_str(&self.artifact); strn.push(':'); strn.push_str(&self.version); if let Some(ref classifier) = self.classifier
if let Some(ref ext) = self.extension { strn.push('@'); strn.push_str(ext); } strn } } impl FromStr for Artifact { type Err = ArtifactParseError; fn from_str(s: &str) -> ::std::result::Result<Self, Self::Err> { let parts: Vec<&str> = s.split('@').collect(); let (s, ext): (&str, Option<String>) = match *parts.as_slice() { [s, ext] => (s, Some(ext.to_string())), _ => (s, None), }; let parts = s.split(':'); let parts: Vec<&str> = parts.collect(); match *parts.as_slice() { [grp, art, ver] => Ok(Self { group: grp.into(), artifact: art.into(), version: ver.into(), classifier: None, extension: ext, }), [grp, art, ver, class] => Ok(Self { group: grp.into(), artifact: art.into(), version: ver.into(), classifier: Some(class.into()), extension: ext, }), _ => Err(ArtifactParseError::BadNumberOfParts), } } } #[cfg(test)] mod test { use super::Artifact; #[test] fn parses_simple() { assert_eq!( "net.minecraftforge.forge:some-jar:some-version".parse(), Ok(Artifact { group: "net.minecraftforge.forge".into(), artifact: "some-jar".into(), version: "some-version".into(), classifier: None, extension: None, }) ) } #[test] fn parses_with_ext() { assert_eq!( "net.minecraftforge.forge:some-jar:some-version@zip".parse(), Ok(Artifact { group: "net.minecraftforge.forge".into(), artifact: "some-jar".into(), version: "some-version".into(), classifier: None, extension: Some("zip".into()), }) ) } #[test] fn parses_with_classifier() { assert_eq!( "net.minecraftforge.forge:some-jar:some-version:universal".parse(), Ok(Artifact { group: "net.minecraftforge.forge".into(), artifact: "some-jar".into(), version: "some-version".into(), classifier: Some("universal".into()), extension: None, }) ) } #[test] fn parses_with_ext_and_classifier() { assert_eq!( "net.minecraftforge.forge:some-jar:some-version:universal@zip".parse(), Ok(Artifact { group: "net.minecraftforge.forge".into(), artifact: "some-jar".into(), version: "some-version".into(), classifier: Some("universal".into()), extension: Some("zip".into()), }) ) } }
{ strn.push(':'); strn.push_str(classifier); }
conditional_block
mod.rs
use futures::prelude::*; use http::Uri; use slog::Logger; use std::{ iter::FromIterator, path::{Path, PathBuf}, str::FromStr, }; use crate::{ cache::{self, Cacheable, Cache as _}, download, error::prelude::*, }; use tokio::io::AsyncReadExt; mod hash_writer; use hash_writer::HashWriter; mod error{ use snafu::Snafu; #[derive(Debug,Snafu)] #[snafu(visibility(pub))] pub enum Error{ #[snafu(display("Invalid uri: {}", source))] BadUri{ source: http::uri::InvalidUri, }, #[snafu(display("Invalid url: {}", source))] BadUrl{ source: url::ParseError, }, } } #[derive(Debug)] pub enum VerifyResult { Good, Bad, NotInCache, } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Hash)] pub struct Artifact { pub group: String, pub artifact: String, pub version: String, pub classifier: Option<String>, pub extension: Option<String>, } #[derive(Debug, Clone)] pub struct ResolvedArtifact { pub artifact: Artifact, pub repo: Uri, } pub struct Cache; impl Cacheable for ResolvedArtifact { type Cache = crate::cache::FileCache; fn cached_path(&self) -> PathBuf { let mut p = PathBuf::new(); p.push(app_dirs::app_dir(app_dirs::AppDataType::UserCache, crate::APP_INFO, "maven_cache").expect("Cache directory must be accesible")); p.push(&self.artifact.to_path()); p } fn uri(&self) -> crate::cache::Result<Uri> { crate::cache::ResultExt::erased(self.artifact.get_uri_on(&self.repo)) } } impl cache::Cache<ResolvedArtifact> for Cache { fn with( artifact: ResolvedArtifact, manager: download::Manager, log: Logger, ) -> crate::cache::BoxFuture<PathBuf> { let cached_path = artifact.cached_path(); let log = log.new( o!("artifact"=>artifact.artifact.to_string(),"repo"=>artifact.repo.to_string(),"cached_path"=>cached_path.as_path().to_string_lossy().into_owned()), ); Box::pin(async move{ info!(log, "caching maven artifact"); if!Self::is_cached(&artifact) { info!(log, "artifact is not cached, downloading now"); let uri = artifact.uri()?; manager .download(uri.clone(), cached_path.clone(), false, &log).await.context(crate::cache::error::Downloading{uri})?; } Ok(cached_path) }) } } impl Cache { pub async fn verify_cached( resolved: ResolvedArtifact, manager: download::Manager, ) -> download::Result<VerifyResult> { if Self::is_cached(&resolved) { let cached_path = resolved.cached_path(); let sha_url_res = resolved.sha_uri(); let mut cached_file = tokio::fs::File::open(cached_path).await.context(download::error::Io)?; let mut sha = HashWriter::new(); cached_file.copy(&mut sha).await.context(download::error::Io)?; let cached_sha = sha.digest(); let sha_uri = sha_url_res?; let (res,_) = manager.get(sha_uri)?.await?; let hash_str = res.into_body().map_ok(hyper::Chunk::into_bytes).try_concat().await.context(download::error::Hyper)?; if hash_str == format!("{}", cached_sha) { Ok(VerifyResult::Good) } else { Ok(VerifyResult::Bad) } } else { Ok(VerifyResult::NotInCache) } } } impl Artifact { fn to_path(&self) -> PathBuf { let mut p = PathBuf::new(); p.push(&self.group_path()); p.push(&self.artifact); p.push(&self.version); p.push(&self.artifact_filename()); p } pub fn get_uri_on(&self, base: &Uri) -> Result<Uri,error::Error> { let base = crate::util::uri_to_url(base).context(error::BadUrl)?; let path = self.to_path(); let url = base.join(path.to_str().expect("non unicode path encountered")).context(error::BadUrl)?; crate::util::url_to_uri(&url).context(error::BadUri) } fn group_path(&self) -> PathBuf { PathBuf::from_iter(self.group.split('.')) } fn artifact_filename(&self) -> String { let classifier_fmt = match self.classifier { Some(ref class) => format!("-{classifier}", classifier = class), None => "".to_string(), }; let extension_fmt = match self.extension { Some(ref extension) => extension.clone(), None => "jar".to_string(), }; format!( "{artifact}-{version}{classifier}.{extension}", artifact = self.artifact, version = self.version,
classifier = classifier_fmt, extension = extension_fmt ) } pub fn resolve(&self, repo_uri: Uri) -> ResolvedArtifact { ResolvedArtifact { artifact: self.clone(), repo: repo_uri, } } pub fn download_from( &self, location: &Path, repo_uri: Uri, manager: download::Manager, log: Logger, ) -> impl Future<Output=Result<(), crate::cache::Error>> + Send { Cache::install_at(self.resolve(repo_uri), location.to_owned(), manager, log) } } impl ResolvedArtifact { pub fn to_path(&self) -> PathBuf { self.artifact.to_path() } pub fn sha_uri(&self) -> crate::download::Result<Uri> { let mut url = crate::util::uri_to_url(&self.uri().context(download::error::Cached)?).context(download::error::BadUrl)?; let mut path = url.path().to_owned(); path.push_str(".sha1"); url.set_path(path.as_ref()); crate::util::url_to_uri(&url).context(download::error::BadUri) } pub fn install_at_no_classifier( self, location: PathBuf, manager: download::Manager, log: Logger, ) -> impl Future<Output=crate::cache::Result<()>> + Send { async move{ let cached_path_no_classifier = Self { artifact: Artifact { classifier: None, ..self.artifact.clone() }, repo: self.repo.clone(), }.cached_path(); let filename = cached_path_no_classifier.file_name().expect("Maven artifact should have a filename"); <Self as Cacheable>::install_at_custom_filename(self, location, filename.to_os_string(), manager, log).await } } } #[derive(Debug, PartialEq, Eq)] pub enum ArtifactParseError { BadNumberOfParts, } impl ToString for Artifact { fn to_string(&self) -> String { let mut strn = String::new(); strn.push_str(&self.group); strn.push(':'); strn.push_str(&self.artifact); strn.push(':'); strn.push_str(&self.version); if let Some(ref classifier) = self.classifier { strn.push(':'); strn.push_str(classifier); } if let Some(ref ext) = self.extension { strn.push('@'); strn.push_str(ext); } strn } } impl FromStr for Artifact { type Err = ArtifactParseError; fn from_str(s: &str) -> ::std::result::Result<Self, Self::Err> { let parts: Vec<&str> = s.split('@').collect(); let (s, ext): (&str, Option<String>) = match *parts.as_slice() { [s, ext] => (s, Some(ext.to_string())), _ => (s, None), }; let parts = s.split(':'); let parts: Vec<&str> = parts.collect(); match *parts.as_slice() { [grp, art, ver] => Ok(Self { group: grp.into(), artifact: art.into(), version: ver.into(), classifier: None, extension: ext, }), [grp, art, ver, class] => Ok(Self { group: grp.into(), artifact: art.into(), version: ver.into(), classifier: Some(class.into()), extension: ext, }), _ => Err(ArtifactParseError::BadNumberOfParts), } } } #[cfg(test)] mod test { use super::Artifact; #[test] fn parses_simple() { assert_eq!( "net.minecraftforge.forge:some-jar:some-version".parse(), Ok(Artifact { group: "net.minecraftforge.forge".into(), artifact: "some-jar".into(), version: "some-version".into(), classifier: None, extension: None, }) ) } #[test] fn parses_with_ext() { assert_eq!( "net.minecraftforge.forge:some-jar:some-version@zip".parse(), Ok(Artifact { group: "net.minecraftforge.forge".into(), artifact: "some-jar".into(), version: "some-version".into(), classifier: None, extension: Some("zip".into()), }) ) } #[test] fn parses_with_classifier() { assert_eq!( "net.minecraftforge.forge:some-jar:some-version:universal".parse(), Ok(Artifact { group: "net.minecraftforge.forge".into(), artifact: "some-jar".into(), version: "some-version".into(), classifier: Some("universal".into()), extension: None, }) ) } #[test] fn parses_with_ext_and_classifier() { assert_eq!( "net.minecraftforge.forge:some-jar:some-version:universal@zip".parse(), Ok(Artifact { group: "net.minecraftforge.forge".into(), artifact: "some-jar".into(), version: "some-version".into(), classifier: Some("universal".into()), extension: Some("zip".into()), }) ) } }
random_line_split
mod.rs
use futures::prelude::*; use http::Uri; use slog::Logger; use std::{ iter::FromIterator, path::{Path, PathBuf}, str::FromStr, }; use crate::{ cache::{self, Cacheable, Cache as _}, download, error::prelude::*, }; use tokio::io::AsyncReadExt; mod hash_writer; use hash_writer::HashWriter; mod error{ use snafu::Snafu; #[derive(Debug,Snafu)] #[snafu(visibility(pub))] pub enum Error{ #[snafu(display("Invalid uri: {}", source))] BadUri{ source: http::uri::InvalidUri, }, #[snafu(display("Invalid url: {}", source))] BadUrl{ source: url::ParseError, }, } } #[derive(Debug)] pub enum VerifyResult { Good, Bad, NotInCache, } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Hash)] pub struct Artifact { pub group: String, pub artifact: String, pub version: String, pub classifier: Option<String>, pub extension: Option<String>, } #[derive(Debug, Clone)] pub struct ResolvedArtifact { pub artifact: Artifact, pub repo: Uri, } pub struct Cache; impl Cacheable for ResolvedArtifact { type Cache = crate::cache::FileCache; fn cached_path(&self) -> PathBuf { let mut p = PathBuf::new(); p.push(app_dirs::app_dir(app_dirs::AppDataType::UserCache, crate::APP_INFO, "maven_cache").expect("Cache directory must be accesible")); p.push(&self.artifact.to_path()); p } fn uri(&self) -> crate::cache::Result<Uri> { crate::cache::ResultExt::erased(self.artifact.get_uri_on(&self.repo)) } } impl cache::Cache<ResolvedArtifact> for Cache { fn with( artifact: ResolvedArtifact, manager: download::Manager, log: Logger, ) -> crate::cache::BoxFuture<PathBuf> { let cached_path = artifact.cached_path(); let log = log.new( o!("artifact"=>artifact.artifact.to_string(),"repo"=>artifact.repo.to_string(),"cached_path"=>cached_path.as_path().to_string_lossy().into_owned()), ); Box::pin(async move{ info!(log, "caching maven artifact"); if!Self::is_cached(&artifact) { info!(log, "artifact is not cached, downloading now"); let uri = artifact.uri()?; manager .download(uri.clone(), cached_path.clone(), false, &log).await.context(crate::cache::error::Downloading{uri})?; } Ok(cached_path) }) } } impl Cache { pub async fn verify_cached( resolved: ResolvedArtifact, manager: download::Manager, ) -> download::Result<VerifyResult> { if Self::is_cached(&resolved) { let cached_path = resolved.cached_path(); let sha_url_res = resolved.sha_uri(); let mut cached_file = tokio::fs::File::open(cached_path).await.context(download::error::Io)?; let mut sha = HashWriter::new(); cached_file.copy(&mut sha).await.context(download::error::Io)?; let cached_sha = sha.digest(); let sha_uri = sha_url_res?; let (res,_) = manager.get(sha_uri)?.await?; let hash_str = res.into_body().map_ok(hyper::Chunk::into_bytes).try_concat().await.context(download::error::Hyper)?; if hash_str == format!("{}", cached_sha) { Ok(VerifyResult::Good) } else { Ok(VerifyResult::Bad) } } else { Ok(VerifyResult::NotInCache) } } } impl Artifact { fn to_path(&self) -> PathBuf
pub fn get_uri_on(&self, base: &Uri) -> Result<Uri,error::Error> { let base = crate::util::uri_to_url(base).context(error::BadUrl)?; let path = self.to_path(); let url = base.join(path.to_str().expect("non unicode path encountered")).context(error::BadUrl)?; crate::util::url_to_uri(&url).context(error::BadUri) } fn group_path(&self) -> PathBuf { PathBuf::from_iter(self.group.split('.')) } fn artifact_filename(&self) -> String { let classifier_fmt = match self.classifier { Some(ref class) => format!("-{classifier}", classifier = class), None => "".to_string(), }; let extension_fmt = match self.extension { Some(ref extension) => extension.clone(), None => "jar".to_string(), }; format!( "{artifact}-{version}{classifier}.{extension}", artifact = self.artifact, version = self.version, classifier = classifier_fmt, extension = extension_fmt ) } pub fn resolve(&self, repo_uri: Uri) -> ResolvedArtifact { ResolvedArtifact { artifact: self.clone(), repo: repo_uri, } } pub fn download_from( &self, location: &Path, repo_uri: Uri, manager: download::Manager, log: Logger, ) -> impl Future<Output=Result<(), crate::cache::Error>> + Send { Cache::install_at(self.resolve(repo_uri), location.to_owned(), manager, log) } } impl ResolvedArtifact { pub fn to_path(&self) -> PathBuf { self.artifact.to_path() } pub fn sha_uri(&self) -> crate::download::Result<Uri> { let mut url = crate::util::uri_to_url(&self.uri().context(download::error::Cached)?).context(download::error::BadUrl)?; let mut path = url.path().to_owned(); path.push_str(".sha1"); url.set_path(path.as_ref()); crate::util::url_to_uri(&url).context(download::error::BadUri) } pub fn install_at_no_classifier( self, location: PathBuf, manager: download::Manager, log: Logger, ) -> impl Future<Output=crate::cache::Result<()>> + Send { async move{ let cached_path_no_classifier = Self { artifact: Artifact { classifier: None, ..self.artifact.clone() }, repo: self.repo.clone(), }.cached_path(); let filename = cached_path_no_classifier.file_name().expect("Maven artifact should have a filename"); <Self as Cacheable>::install_at_custom_filename(self, location, filename.to_os_string(), manager, log).await } } } #[derive(Debug, PartialEq, Eq)] pub enum ArtifactParseError { BadNumberOfParts, } impl ToString for Artifact { fn to_string(&self) -> String { let mut strn = String::new(); strn.push_str(&self.group); strn.push(':'); strn.push_str(&self.artifact); strn.push(':'); strn.push_str(&self.version); if let Some(ref classifier) = self.classifier { strn.push(':'); strn.push_str(classifier); } if let Some(ref ext) = self.extension { strn.push('@'); strn.push_str(ext); } strn } } impl FromStr for Artifact { type Err = ArtifactParseError; fn from_str(s: &str) -> ::std::result::Result<Self, Self::Err> { let parts: Vec<&str> = s.split('@').collect(); let (s, ext): (&str, Option<String>) = match *parts.as_slice() { [s, ext] => (s, Some(ext.to_string())), _ => (s, None), }; let parts = s.split(':'); let parts: Vec<&str> = parts.collect(); match *parts.as_slice() { [grp, art, ver] => Ok(Self { group: grp.into(), artifact: art.into(), version: ver.into(), classifier: None, extension: ext, }), [grp, art, ver, class] => Ok(Self { group: grp.into(), artifact: art.into(), version: ver.into(), classifier: Some(class.into()), extension: ext, }), _ => Err(ArtifactParseError::BadNumberOfParts), } } } #[cfg(test)] mod test { use super::Artifact; #[test] fn parses_simple() { assert_eq!( "net.minecraftforge.forge:some-jar:some-version".parse(), Ok(Artifact { group: "net.minecraftforge.forge".into(), artifact: "some-jar".into(), version: "some-version".into(), classifier: None, extension: None, }) ) } #[test] fn parses_with_ext() { assert_eq!( "net.minecraftforge.forge:some-jar:some-version@zip".parse(), Ok(Artifact { group: "net.minecraftforge.forge".into(), artifact: "some-jar".into(), version: "some-version".into(), classifier: None, extension: Some("zip".into()), }) ) } #[test] fn parses_with_classifier() { assert_eq!( "net.minecraftforge.forge:some-jar:some-version:universal".parse(), Ok(Artifact { group: "net.minecraftforge.forge".into(), artifact: "some-jar".into(), version: "some-version".into(), classifier: Some("universal".into()), extension: None, }) ) } #[test] fn parses_with_ext_and_classifier() { assert_eq!( "net.minecraftforge.forge:some-jar:some-version:universal@zip".parse(), Ok(Artifact { group: "net.minecraftforge.forge".into(), artifact: "some-jar".into(), version: "some-version".into(), classifier: Some("universal".into()), extension: Some("zip".into()), }) ) } }
{ let mut p = PathBuf::new(); p.push(&self.group_path()); p.push(&self.artifact); p.push(&self.version); p.push(&self.artifact_filename()); p }
identifier_body
main.rs
Err(e) => e.to_string() }; assert_eq!("5", end); } fn _result_match() { let result: Result<i32, &str> = Ok(5); let number = match result { Ok(x) => x, Err(_e) => 0, }; assert_eq!(5, number) } fn _threads() { let handles: Vec<_> = (0..10).map(|x| { thread::spawn(move|| { println!("{}", x) }) }).collect(); for h in handles { h.join().ok().expect("No se pudo unir un hilo!"); } } fn _threads_join() { thread::spawn(|| { thread::sleep(Duration::from_millis(3000)); println!("Hola desde 1"); }); let thread2 = thread::spawn(|| { thread::sleep(Duration::from_millis(3000)); println!("Hola desde 2"); }); println!("end..."); thread2.join().expect("Error"); //thread::sleep(Duration::from_millis(4000)); } fn _iteradores() { let mut rango = 0..10; loop { match rango.next() { Some(x) => { println!("{}", x); }, None => { break } } } let nums = vec![1, 2, 3]; for num in nums.iter() { println!("{}", num); } } fn _consumidores() { let _uno_hasta_cien = (1..101).collect::<Vec<i32>>(); let _uno_hasta_cien = (1..101).collect::<Vec<_>>(); let mayores_a_cuarenta_y_dos = (0..100) .find(|x| *x > 42); match mayores_a_cuarenta_y_dos { Some(_) => println!("Tenemos algunos números!"), None => println!("No se encontraron números :("), } let suma = (1..4).fold(0, |suma, x| suma + x); //6 assert_eq!(6, suma); } fn _adaptadores_de_iterador() { let _nums = (1..100).map(|x| x + 1).collect::<Vec<_>>(); let _nums = (1..30) .filter(|&x| x % 2 == 0) .filter(|&x| x % 3 == 0) .take(5) .collect::<Vec<i32>>(); for x in (1..11).map(|x| x + 1).collect::<Vec<_>>() { println!("{}", x); } } fn _hilos() { thread::spawn(|| { println!("Hola desde un hilo!"); }); thread::sleep(Duration::from_millis(10)); } fn _thread_handle() { let handle = thread::spawn(|| { "Hola desde un hilo!" }); //unwrap() hará un pánico ( panic! ) si el Result es Err assert_eq!("Hola desde un hilo!", handle.join().unwrap()); } fn _panico_hilo() { let valor = 1; let result = thread::spawn(move || { if valor % 2 == 0 { panic!("ups!"); } 1 }).join(); let resultado = match result { Ok(n) => n, Err(_e) => 0 }; assert_eq!(1, resultado); } fn _panico_unreachable() { enum Estado { _Activo, _Inactivo, Desconocido } use Estado::{_Activo, _Inactivo, Desconocido}; let estado = Desconocido; let _numero = match estado { _Activo => 1, _Inactivo => 0, _ => unreachable!() }; println!("Linea no alcanzable") } fn _option() { let s = "foo"; assert_eq!(s.find('f'), Some(0)); assert_eq!(s.find('z'), None); assert_eq!(s.find('f').map(|p| p + 1), Some(1)); assert_eq!(s.find('z').map(|p| p + 1), None); } fn _option_match() { let option = Some(5); let number = match option { Some(x) => x, None => 0, }; assert_eq!(5, number); } fn _result_funciones() { enum Error { Tecnico } let f: fn(i32) -> Result<i32, Error> = |num: i32| match num { 1 => Ok(num + 1), _ => Err(Error::Tecnico) }; /*fn f(num: i32) -> Result<i32, Error> { match num { 1 => Ok(num + 1), _ => Err(Error::Tecnico) } }*/ assert!(f(1).is_ok()); assert!(f(2).is_err()); let result: Result<i32, &str> = f(2) .map(|ok| ok) .map_err(|_err| "Error =("); match result { Ok(n) => println!("{}", n), Err(e) => println!("{}", e) }; } fn _panic_result() { let result: Result<i32, &str> = Ok(1); //let result: Result<i32, &str> = Err("Error =("); let valor = result.ok().expect("Error!"); assert_eq!(1, valor) } fn _try() { fn _parser(num: &str) -> Result<i32, ParseIntError> { num.parse() } fn f(x: &str, y: &str) -> Result<i32, ParseIntError> { let num1 = _parser(x); let num2 = _parser(y); //let resultado = _parser(x)? + _parser(y)?; let resultado = num1? + num2?; Ok(resultado) } assert!(f("1", "2").is_ok()); assert!(f("1P", "2").is_err()); match f("1P", "2") { Ok(n) => println!("Ok: {}", n), Err(e) => println!("Error: {}", e) } } fn _try_azucar_sintactico() { fn foo(n: i32) -> Result<i32, String> { if n % 2 == 0 { Ok(1) } else { Err(String::from("Error")) } } fn bar() -> Result<i32, String> { Ok(2) } fn foo_bar() -> Result<i32, String> { let res = foo(2)? + bar()?; Ok(res) } let fb = foo_bar(); assert!(fb.is_ok()); } fn _apuntadores_a_funcion() { fn mas_uno(i: i32) -> i32 { i + 1 } let f: fn(i32) -> i32 = mas_uno; assert_eq!(2, f(1)); } fn _primitivos() { let _a: bool = false; let _b: char = 'x'; let _c: i32 = 42; //i8, i16, i32, i64, u8, u16, u32, u64, isize, usize, f32, f64 } fn _arreglos() { let mut m: [i32; 3] = [1, 2, 3]; m[2] = 5; assert_eq!(5, m[2]); } fn _slices() { let a: [i32; 5] = [0, 1, 2, 3, 4]; let middle: &[i32] = &a[1..4]; assert_eq!(1, middle[0]); } fn _tuplas() { let (x, y) = (1, "Hello"); assert_eq!(1, x); assert_eq!("Hello", y); let z = (1, "Hello"); assert_eq!(1, z.0); } fn _expresiones() { let x = 5; let y = if x == 5 { 10 } else { 15 }; assert_eq!(10, y) } fn _while() { let mut x = 0; while x < 10 { x += 1; } assert_eq!(10, x) } fn _for() { for x in 0..10 { println!("{}", x); } } fn _loop() { let mut x = 0; loop { x += 1; if x >= 10 { break } } assert_eq!(10, x) } fn _etiquetas_loop() { 'exterior: for x in 0..10 { 'interior: for y in 0..10 { if x % 2 == 0 { continue 'exterior; } // continua el ciclo por encima de x if y % 2 == 0 { continue 'interior; } // continua el ciclo por encima de y println!("x: {}, y: {}", x, y); } } } fn _enumerate() { for (i,j) in (5..10).enumerate() { println!("i = {} y j = {}", i, j); } let lineas = "hola\nmundo".lines(); for (numero_linea, linea) in lineas.enumerate() { println!("{}: {}", numero_linea, linea); } } fn _pertenencia() { let v = vec![1, 2, 3]; let v2 = v; println!("v2[0] es: {}", v2[0]); //println!("v[0] es: {}", v[0]); // Error borrow of moved value: `v` } fn _pertenencia_funcion() { fn tomar(_v: Vec<i32>) { // Algo } let v = vec![1, 2, 3]; tomar(v); //println!("v[0] es: {}", v[0]); // Error borrow of moved value: `v` } fn _copy() { // i32, Todos los tipos primitivos implementan el trait Copy // Se realiza una copia y su pertenencia no es movida let v: i32 = 1; let _v2 = v; println!("v es: {}", v); // =) } fn _devolver_pertenencia() { fn _foo(v: Vec<i32>) -> Vec<i32> { v } fn foo(v1: Vec<i32>, v2: Vec<i32>) -> (Vec<i32>, Vec<i32>, i32) { (v1, v2, 42) } let v1 = vec![1, 2, 3]; let v2 = vec![1, 2, 3]; let (v1, _v2, _r) = foo(v1, v2); assert_eq!(1, v1[0]); } fn _prestamo() { fn foo(_v1: &Vec<i32>, _v2: &Vec<i32>) -> i32 { 42 } let v1 = vec![1, 2, 3]; let _v2 = vec![1, 2, 3]; let _r = foo(&v1, &_v2); // podemos usar a v1 y v2 aqui assert_eq!(1, v1[0]); } fn _mutabilidad() { let mut x = 5; assert_eq!(5, x); x = 6; assert_eq!(6, x); } fn _estructuras() { struct Punto { x: i32, y: i32, } let origen = Punto { x: 0, y: 0 }; assert_eq!(0, origen.x); assert_eq!(0, origen.y); } fn _sintaxis_de_actualizacion() { struct Punto3d { _x: i32, _y: i32, _z: i32, } let origen = Punto3d { _x: 1, _y: 2, _z: 3 }; let punto = Punto3d { _y: 1,.. origen }; assert_eq!(3, punto._z); } fn _estructuras_pertenencia() { struct Punto { x: i32, y: i32, } fn foo(punto: Punto) -> i32 { punto.x + punto.y } let origen = Punto { x: 1, y: 2 }; let suma = foo(origen); println!("{}", suma); //println!("Punto x {}", origen.x); // Error borrow of moved value: `origen` } fn _estructuras_prestamo() { struct Punto { x: i32, y: i32, } fn foo(punto: &Punto) -> i32 { punto.x + punto.y } let origen = Punto { x: 1, y: 2 }; let suma = foo(&origen); assert_eq!(3, suma); assert_eq!(1, origen.x); } fn _tupla_estructuras() { struct Color(i32, i32, i32); let azul = Color(0, 0, 255); assert_eq!(255, azul.2); } fn _estructuras_tipo_unitario() { struct Electron; let _e = Electron; } fn _enumeraciones() { enum Mensaje { Salir, CambiarColor(i32, i32, i32), Mover { _x: i32, _y: i32 }, Escribir(String), } let _salir = Mensaje::Salir; let _cambiar_color = Mensaje::CambiarColor(0, 0, 255); use Mensaje::{Mover}; let _mover = Mover {_x: 0, _y: 2}; let _escribir = Mensaje::Escribir("Hello".to_string()); } fn _match_en_enums() { enum _Mensaje { Salir, CambiarColor(i32, i32, i32), Mover { x: i32, _y: i32 }, Escribir(String), } fn _salir() { /*... */ } fn _cambiar_color(_r: i32, _g: i32, _b: i32) { /*... */ } fn _mover_cursor(_x: i32, _y: i32) { /*... */ } fn _procesar_mensaje(msj: _Mensaje) { match msj { _Mensaje::Salir => _salir(), _Mensaje::CambiarColor(r, g, b) => _cambiar_color(r, g, b), _Mensaje::Mover { x, _y: y } => _mover_cursor(x, y), _Mensaje::Escribir(s) => println!("{}", s),
let x = 2; let num = match x { 1 | 2 => "1, 2", 3 => "3", _ => "...", }; assert_eq!("1, 2", num); } fn _match_rangos() { let x = 3; let resultado = match x { 1..= 5 => "uno al cinco", _ => "cualquier cosa", }; assert_eq!("uno al cinco", resultado); let y ='s'; let letra = match y { 'a'..= 'j' => "letra temprana", 'k'..= 'z' => "letra tardia", _ => "algo mas" }; assert_eq!("letra tardia", letra); } fn _destructuracion() { struct Punto { x: i32, y: i32, } let origen = Punto { x: 0, y: 2 }; match origen { Punto { x, y } => println!("({},{})", x, y), } match origen { Punto { x,.. } => println!("x es {}", x) } } fn _enlaces_a_variable() { let x = 1; match x { e @ 1..= 5 => println!("valor de rango {} obtenido", e), _ => println!("lo que sea"), } } fn _guardias() { enum EnteroOpcional { Valor(i32), _Faltante, } let x = EnteroOpcional::Valor(5); match x { EnteroOpcional::Valor(i) if i > 5 => println!("Entero mayor a cinco obtenido!"), EnteroOpcional::Valor(..) => println!("Entero obtenido!"), EnteroOpcional::_Faltante => println!("Sin suerte."), } } fn _multiples_patrones_y_guardias() { let x = 4; let y = false; let resultado = match x { 4 | 5 if y => "si", _ => "no" }; assert_eq!("no", resultado); } fn _llamadas_a_metodos() { struct Circulo { _x: f64, _y: f64, radio: f64, } impl Circulo { fn area(&self) -> f64 { std::f64::consts::PI * (self.radio * self.radio) } } let c = Circulo { _x: 0.0, _y: 0.0, radio: 2.0 }; println!("{}", c.area()); } fn _metodos_en_cadena() { struct Circulo { x: f64, y: f64, radio: f64, } impl Circulo { fn agrandar(&self, incremento: f64) -> Circulo { Circulo { x: self.x, y: self.y, radio: self.radio + incremento } } fn area(&self) -> f64 { std::f64::consts::PI * (self.radio * self.radio) } } let c = Circulo { x: 0.0, y: 0.0, radio: 2.0 }; println!("{}", c.area()); let d = c.agrandar(2.0).area(); println!("{}", d); } fn _funciones_asociadas() { struct Circulo { _x: f64, _y: f64, radio: f64, } impl Circulo { fn new(x: f64, y: f64, radio: f64) -> Circulo { Circulo { _x: x, _y: y, radio: radio, } } } let c = Circulo::new(0.0, 0.0, 2.0); assert_eq!(2.0, c.radio); } fn _builder() { struct Circulo { x: f64, y: f64, radio: f64 } impl Circulo { fn area(&self) -> f64 { std::f64::consts::PI * (self.radio * self.radio) } } struct CirculoBuilder { x: f64, y: f64, radio: f64 } impl CirculoBuilder { fn new() -> CirculoBuilder { CirculoBuilder { x: 0.0, y: 0.0, radio: 1.0, } } fn x(&mut self, coordenada: f64) -> &mut CirculoBuilder { self.x = coordenada; self } fn y(&mut self, coordenada: f64) -> &mut CirculoBuilder { self.y = coordenada; self } fn radio(&mut self, radio: f64) -> &mut CirculoBuilder { self.radio = radio; self } fn build(&self) -> Circulo { Circulo { x: self.x, y: self.y, radio: self.radio } } } let c = CirculoBuilder::new() .x(1.0) .y(2.0) .radio(2.0) .build(); println!("area: {}", c.area()); println!("x: {}", c.x); println!("y: {}", c.y); assert_eq!(2.0, c.y); } fn _cadenas_de_caracteres() { let _saludo: &str = "Hola."; let mut s: String = "Hola".to_string(); s.push_str(", mundo."); assert_eq!("Hola, mundo.", s); } fn _genericos() { enum _Option<T> { _Some(T), _None, } let _x: _Option<i32> = _Option::_Some(5); } fn _funciones_genericas() { fn foo<T>(x: T) -> T { x } let num = foo(1); assert_eq!(1, num); } fn _structs_genericos() { struct Info<T1, T2> { x: T1, y: T2, } impl<T1, T2> Info<T1, T2> { fn foo(&self) { // } } let info = Info { x: 1, y: "=)" }; info.foo(); assert_eq!(1, info.x); assert_eq!("=)", info.y); } fn _traits() { trait Area { fn area(&self) -> f64; } struct Circulo { _x: f64, _y: f64, radio: f64 } impl Area for Circulo { fn area(&self) -> f64 { std::f64::consts::PI * (self.radio * self.radio) } } let c = Circulo{ _x:0.0, _y:0.0, radio: 2.0 }; let a = c.area(); println!("{}", a); //Genericos fn imrimir_area<T: Area>(figura: T) { println!("Esta figura tiene un area de {}", figura.area()); } imrimir_area(c) } fn _multiples_limites_de_trait() { use std::fmt::Display; fn foo<T: Clone, K: Clone + Display>(x: T, y: K) -> String { let _x_clone = x.clone(); let y_clone = y.clone(); format!("{}", y_clone) } fn bar<T, K>(x: T, y: K) -> String where T: Clone, K: Clone + Display { let _x_clone = x.clone(); let y_clone = y.clone(); format!("{}", y_clone) } let r_foo = foo("Hola", "mundo"); let r_bar = bar("Hola", "mundo"); assert_eq!(r_foo, r_bar); } fn _metodos_por_defecto() { trait Foo { fn es_valido(&self) -> bool; fn es_invalido(&self) -> bool {!self.es_valido() } } struct Default; impl Foo for Default { fn es_valido(&self) -> bool { true } } let default = Default; assert!(default.es_valido()); assert!(!default.es_invalido()); } fn _metodos_por_defecto_bar() { trait Bar { fn plus_one(x: i32) -> i32 { x + 1}
}; } } fn _multiples_patrones() {
random_line_split
main.rs
Err(e) => e.to_string() }; assert_eq!("5", end); } fn _result_match() { let result: Result<i32, &str> = Ok(5); let number = match result { Ok(x) => x, Err(_e) => 0, }; assert_eq!(5, number) } fn _threads() { let handles: Vec<_> = (0..10).map(|x| { thread::spawn(move|| { println!("{}", x) }) }).collect(); for h in handles { h.join().ok().expect("No se pudo unir un hilo!"); } } fn _threads_join() { thread::spawn(|| { thread::sleep(Duration::from_millis(3000)); println!("Hola desde 1"); }); let thread2 = thread::spawn(|| { thread::sleep(Duration::from_millis(3000)); println!("Hola desde 2"); }); println!("end..."); thread2.join().expect("Error"); //thread::sleep(Duration::from_millis(4000)); } fn _iteradores() { let mut rango = 0..10; loop { match rango.next() { Some(x) => { println!("{}", x); }, None => { break } } } let nums = vec![1, 2, 3]; for num in nums.iter() { println!("{}", num); } } fn _consumidores() { let _uno_hasta_cien = (1..101).collect::<Vec<i32>>(); let _uno_hasta_cien = (1..101).collect::<Vec<_>>(); let mayores_a_cuarenta_y_dos = (0..100) .find(|x| *x > 42); match mayores_a_cuarenta_y_dos { Some(_) => println!("Tenemos algunos números!"), None => println!("No se encontraron números :("), } let suma = (1..4).fold(0, |suma, x| suma + x); //6 assert_eq!(6, suma); } fn _adaptadores_de_iterador() { let _nums = (1..100).map(|x| x + 1).collect::<Vec<_>>(); let _nums = (1..30) .filter(|&x| x % 2 == 0) .filter(|&x| x % 3 == 0) .take(5) .collect::<Vec<i32>>(); for x in (1..11).map(|x| x + 1).collect::<Vec<_>>() { println!("{}", x); } } fn _hilos() { thread::spawn(|| { println!("Hola desde un hilo!"); }); thread::sleep(Duration::from_millis(10)); } fn _thread_handle() { let handle = thread::spawn(|| { "Hola desde un hilo!" }); //unwrap() hará un pánico ( panic! ) si el Result es Err assert_eq!("Hola desde un hilo!", handle.join().unwrap()); } fn _panico_hilo() { let valor = 1; let result = thread::spawn(move || { if valor % 2 == 0 { panic!("ups!"); } 1 }).join(); let resultado = match result { Ok(n) => n, Err(_e) => 0 }; assert_eq!(1, resultado); } fn _panico_unreachable() { enum Estado { _Activo, _Inactivo, Desconocido } use Estado::{_Activo, _Inactivo, Desconocido}; let estado = Desconocido; let _numero = match estado { _Activo => 1, _Inactivo => 0, _ => unreachable!() }; println!("Linea no alcanzable") } fn _option() { let s = "foo"; assert_eq!(s.find('f'), Some(0)); assert_eq!(s.find('z'), None); assert_eq!(s.find('f').map(|p| p + 1), Some(1)); assert_eq!(s.find('z').map(|p| p + 1), None); } fn _option_match() { let option = Some(5); let number = match option { Some(x) => x, None => 0, }; assert_eq!(5, number); } fn _result_funciones() { enum Error { Tecnico } let f: fn(i32) -> Result<i32, Error> = |num: i32| match num { 1 => Ok(num + 1), _ => Err(Error::Tecnico) }; /*fn f(num: i32) -> Result<i32, Error> { match num { 1 => Ok(num + 1), _ => Err(Error::Tecnico) } }*/ assert!(f(1).is_ok()); assert!(f(2).is_err()); let result: Result<i32, &str> = f(2) .map(|ok| ok) .map_err(|_err| "Error =("); match result { Ok(n) => println!("{}", n), Err(e) => println!("{}", e) }; } fn _panic_result() { let result: Result<i32, &str> = Ok(1); //let result: Result<i32, &str> = Err("Error =("); let valor = result.ok().expect("Error!"); assert_eq!(1, valor) } fn _try() { fn _parser(num: &str) -> Result<i32, ParseIntError> { num.parse() } fn f(x: &str, y: &str) -> Result<i32, ParseIntError> { let num1 = _parser(x); let num2 = _parser(y); //let resultado = _parser(x)? + _parser(y)?; let resultado = num1? + num2?; Ok(resultado) } assert!(f("1", "2").is_ok()); assert!(f("1P", "2").is_err()); match f("1P", "2") { Ok(n) => println!("Ok: {}", n), Err(e) => println!("Error: {}", e) } } fn _try_azucar_sintactico() { fn foo(n: i32) -> Result<i32, String> { if n % 2 == 0 { Ok(1) } else { Err(String::from("Error")) } } fn bar() -> Result<i32, String> { Ok(2) } fn foo_bar() -> Result<i32, String> { let res = foo(2)? + bar()?; Ok(res) } let fb = foo_bar(); assert!(fb.is_ok()); } fn _apuntadores_a_funcion() { fn mas_uno(i: i32) -> i32 { i + 1 } let f: fn(i32) -> i32 = mas_uno; assert_eq!(2, f(1)); } fn _primitivos() { let _a: bool = false; let _b: char = 'x'; let _c: i32 = 42; //i8, i16, i32, i64, u8, u16, u32, u64, isize, usize, f32, f64 } fn _arreglos() { let mut m: [i32; 3] = [1, 2, 3]; m[2] = 5; assert_eq!(5, m[2]); } fn _slices() { let a: [i32; 5] = [0, 1, 2, 3, 4]; let middle: &[i32] = &a[1..4]; assert_eq!(1, middle[0]); } fn _tuplas() { let (x, y) = (1, "Hello"); assert_eq!(1, x); assert_eq!("Hello", y); let z = (1, "Hello"); assert_eq!(1, z.0); } fn _expresiones() { let x = 5; let y = if x == 5 { 10 } else { 15 }; assert_eq!(10, y) } fn _while() { let mut x = 0; while x < 10 { x += 1; } assert_eq!(10, x) } fn _for() { for x in 0..10 { println!("{}", x); } } fn _loop() { let mut x = 0; loop { x += 1; if x >= 10 { break } } assert_eq!(10, x) } fn _etiquetas_loop() { 'exterior: for x in 0..10 { 'interior: for y in 0..10 { if x % 2 == 0 { continue 'exterior; } // continua el ciclo por encima de x if y % 2 == 0 { continue 'interior; } // continua el ciclo por encima de y println!("x: {}, y: {}", x, y); } } } fn _enumerate() { for (i,j) in (5..10).enumerate() { println!("i = {} y j = {}", i, j); } let lineas = "hola\nmundo".lines(); for (numero_linea, linea) in lineas.enumerate() { println!("{}: {}", numero_linea, linea); } } fn _pertenencia() { let v = vec![1, 2, 3]; let v2 = v; println!("v2[0] es: {}", v2[0]); //println!("v[0] es: {}", v[0]); // Error borrow of moved value: `v` } fn _pertenencia_funcion() { fn tomar(_v: Vec<i32>) { // Algo } let v = vec![1, 2, 3]; tomar(v); //println!("v[0] es: {}", v[0]); // Error borrow of moved value: `v` } fn _copy() { // i32, Todos los tipos primitivos implementan el trait Copy // Se realiza una copia y su pertenencia no es movida let v: i32 = 1; let _v2 = v; println!("v es: {}", v); // =) } fn _devolver_pertenencia() { fn _foo(v: Vec<i32>) -> Vec<i32> { v } fn foo(v1: Vec<i32>, v2: Vec<i32>) -> (Vec<i32>, Vec<i32>, i32) { (v1, v2, 42) } let v1 = vec![1, 2, 3]; let v2 = vec![1, 2, 3]; let (v1, _v2, _r) = foo(v1, v2); assert_eq!(1, v1[0]); } fn _prestamo() { fn foo(_v1: &Vec<i32>, _v2: &Vec<i32>) -> i32 { 42 } let v1 = vec![1, 2, 3]; let _v2 = vec![1, 2, 3]; let _r = foo(&v1, &_v2); // podemos usar a v1 y v2 aqui assert_eq!(1, v1[0]); } fn _mutabilidad() { let mut x = 5; assert_eq!(5, x); x = 6; assert_eq!(6, x); } fn _estructuras() { struct Punto { x: i32, y: i32, } let origen = Punto { x: 0, y: 0 }; assert_eq!(0, origen.x); assert_eq!(0, origen.y); } fn _sintaxis_de_actualizacion() { struct Punto3d { _x: i32, _y: i32, _z: i32, } let origen = Punto3d { _x: 1, _y: 2, _z: 3 }; let punto = Punto3d { _y: 1,.. origen }; assert_eq!(3, punto._z); } fn _estructuras_pertenencia() { struct Punto { x: i32, y: i32, } fn foo(punto: Punto) -> i32 { punto.x + punto.y } let origen = Punto { x: 1, y: 2 }; let suma = foo(origen); println!("{}", suma); //println!("Punto x {}", origen.x); // Error borrow of moved value: `origen` } fn _estructuras_prestamo() { struct Punto { x: i32, y: i32, } fn foo(punto: &Punto) -> i32 {
let origen = Punto { x: 1, y: 2 }; let suma = foo(&origen); assert_eq!(3, suma); assert_eq!(1, origen.x); } fn _tupla_estructuras() { struct Color(i32, i32, i32); let azul = Color(0, 0, 255); assert_eq!(255, azul.2); } fn _estructuras_tipo_unitario() { struct Electron; let _e = Electron; } fn _enumeraciones() { enum Mensaje { Salir, CambiarColor(i32, i32, i32), Mover { _x: i32, _y: i32 }, Escribir(String), } let _salir = Mensaje::Salir; let _cambiar_color = Mensaje::CambiarColor(0, 0, 255); use Mensaje::{Mover}; let _mover = Mover {_x: 0, _y: 2}; let _escribir = Mensaje::Escribir("Hello".to_string()); } fn _match_en_enums() { enum _Mensaje { Salir, CambiarColor(i32, i32, i32), Mover { x: i32, _y: i32 }, Escribir(String), } fn _salir() { /*... */ } fn _cambiar_color(_r: i32, _g: i32, _b: i32) { /*... */ } fn _mover_cursor(_x: i32, _y: i32) { /*... */ } fn _procesar_mensaje(msj: _Mensaje) { match msj { _Mensaje::Salir => _salir(), _Mensaje::CambiarColor(r, g, b) => _cambiar_color(r, g, b), _Mensaje::Mover { x, _y: y } => _mover_cursor(x, y), _Mensaje::Escribir(s) => println!("{}", s), }; } } fn _multiples_patrones() { let x = 2; let num = match x { 1 | 2 => "1, 2", 3 => "3", _ => "...", }; assert_eq!("1, 2", num); } fn _match_rangos() { let x = 3; let resultado = match x { 1..= 5 => "uno al cinco", _ => "cualquier cosa", }; assert_eq!("uno al cinco", resultado); let y ='s'; let letra = match y { 'a'..= 'j' => "letra temprana", 'k'..= 'z' => "letra tardia", _ => "algo mas" }; assert_eq!("letra tardia", letra); } fn _destructuracion() { struct Punto { x: i32, y: i32, } let origen = Punto { x: 0, y: 2 }; match origen { Punto { x, y } => println!("({},{})", x, y), } match origen { Punto { x,.. } => println!("x es {}", x) } } fn _enlaces_a_variable() { let x = 1; match x { e @ 1..= 5 => println!("valor de rango {} obtenido", e), _ => println!("lo que sea"), } } fn _guardias() { enum EnteroOpcional { Valor(i32), _Faltante, } let x = EnteroOpcional::Valor(5); match x { EnteroOpcional::Valor(i) if i > 5 => println!("Entero mayor a cinco obtenido!"), EnteroOpcional::Valor(..) => println!("Entero obtenido!"), EnteroOpcional::_Faltante => println!("Sin suerte."), } } fn _multiples_patrones_y_guardias() { let x = 4; let y = false; let resultado = match x { 4 | 5 if y => "si", _ => "no" }; assert_eq!("no", resultado); } fn _llamadas_a_metodos() { struct Circulo { _x: f64, _y: f64, radio: f64, } impl Circulo { fn area(&self) -> f64 { std::f64::consts::PI * (self.radio * self.radio) } } let c = Circulo { _x: 0.0, _y: 0.0, radio: 2.0 }; println!("{}", c.area()); } fn _metodos_en_cadena() { struct Circulo { x: f64, y: f64, radio: f64, } impl Circulo { fn agrandar(&self, incremento: f64) -> Circulo { Circulo { x: self.x, y: self.y, radio: self.radio + incremento } } fn area(&self) -> f64 { std::f64::consts::PI * (self.radio * self.radio) } } let c = Circulo { x: 0.0, y: 0.0, radio: 2.0 }; println!("{}", c.area()); let d = c.agrandar(2.0).area(); println!("{}", d); } fn _funciones_asociadas() { struct Circulo { _x: f64, _y: f64, radio: f64, } impl Circulo { fn new(x: f64, y: f64, radio: f64) -> Circulo { Circulo { _x: x, _y: y, radio: radio, } } } let c = Circulo::new(0.0, 0.0, 2.0); assert_eq!(2.0, c.radio); } fn _builder() { struct Circulo { x: f64, y: f64, radio: f64 } impl Circulo { fn area(&self) -> f64 { std::f64::consts::PI * (self.radio * self.radio) } } struct CirculoBuilder { x: f64, y: f64, radio: f64 } impl CirculoBuilder { fn new() -> CirculoBuilder { CirculoBuilder { x: 0.0, y: 0.0, radio: 1.0, } } fn x(&mut self, coordenada: f64) -> &mut CirculoBuilder { self.x = coordenada; self } fn y(&mut self, coordenada: f64) -> &mut CirculoBuilder { self.y = coordenada; self } fn radio(&mut self, radio: f64) -> &mut CirculoBuilder { self.radio = radio; self } fn build(&self) -> Circulo { Circulo { x: self.x, y: self.y, radio: self.radio } } } let c = CirculoBuilder::new() .x(1.0) .y(2.0) .radio(2.0) .build(); println!("area: {}", c.area()); println!("x: {}", c.x); println!("y: {}", c.y); assert_eq!(2.0, c.y); } fn _cadenas_de_caracteres() { let _saludo: &str = "Hola."; let mut s: String = "Hola".to_string(); s.push_str(", mundo."); assert_eq!("Hola, mundo.", s); } fn _genericos() { enum _Option<T> { _Some(T), _None, } let _x: _Option<i32> = _Option::_Some(5); } fn _funciones_genericas() { fn foo<T>(x: T) -> T { x } let num = foo(1); assert_eq!(1, num); } fn _structs_genericos() { struct Info<T1, T2> { x: T1, y: T2, } impl<T1, T2> Info<T1, T2> { fn foo(&self) { // } } let info = Info { x: 1, y: "=)" }; info.foo(); assert_eq!(1, info.x); assert_eq!("=)", info.y); } fn _traits() { trait Area { fn area(&self) -> f64; } struct Circulo { _x: f64, _y: f64, radio: f64 } impl Area for Circulo { fn area(&self) -> f64 { std::f64::consts::PI * (self.radio * self.radio) } } let c = Circulo{ _x:0.0, _y:0.0, radio: 2.0 }; let a = c.area(); println!("{}", a); //Genericos fn imrimir_area<T: Area>(figura: T) { println!("Esta figura tiene un area de {}", figura.area()); } imrimir_area(c) } fn _multiples_limites_de_trait() { use std::fmt::Display; fn foo<T: Clone, K: Clone + Display>(x: T, y: K) -> String { let _x_clone = x.clone(); let y_clone = y.clone(); format!("{}", y_clone) } fn bar<T, K>(x: T, y: K) -> String where T: Clone, K: Clone + Display { let _x_clone = x.clone(); let y_clone = y.clone(); format!("{}", y_clone) } let r_foo = foo("Hola", "mundo"); let r_bar = bar("Hola", "mundo"); assert_eq!(r_foo, r_bar); } fn _metodos_por_defecto() { trait Foo { fn es_valido(&self) -> bool; fn es_invalido(&self) -> bool {!self.es_valido() } } struct Default; impl Foo for Default { fn es_valido(&self) -> bool { true } } let default = Default; assert!(default.es_valido()); assert!(!default.es_invalido()); } fn _metodos_por_defecto_bar() { trait Bar { fn plus_one(x: i32) -> i32 { x + 1}
punto.x + punto.y }
identifier_body
main.rs
Err(e) => e.to_string() }; assert_eq!("5", end); } fn _result_match() { let result: Result<i32, &str> = Ok(5); let number = match result { Ok(x) => x, Err(_e) => 0, }; assert_eq!(5, number) } fn _threads() { let handles: Vec<_> = (0..10).map(|x| { thread::spawn(move|| { println!("{}", x) }) }).collect(); for h in handles { h.join().ok().expect("No se pudo unir un hilo!"); } } fn _threads_join() { thread::spawn(|| { thread::sleep(Duration::from_millis(3000)); println!("Hola desde 1"); }); let thread2 = thread::spawn(|| { thread::sleep(Duration::from_millis(3000)); println!("Hola desde 2"); }); println!("end..."); thread2.join().expect("Error"); //thread::sleep(Duration::from_millis(4000)); } fn _iteradores() { let mut rango = 0..10; loop { match rango.next() { Some(x) => { println!("{}", x); }, None => { break } } } let nums = vec![1, 2, 3]; for num in nums.iter() { println!("{}", num); } } fn _consumidores() { let _uno_hasta_cien = (1..101).collect::<Vec<i32>>(); let _uno_hasta_cien = (1..101).collect::<Vec<_>>(); let mayores_a_cuarenta_y_dos = (0..100) .find(|x| *x > 42); match mayores_a_cuarenta_y_dos { Some(_) => println!("Tenemos algunos números!"), None => println!("No se encontraron números :("), } let suma = (1..4).fold(0, |suma, x| suma + x); //6 assert_eq!(6, suma); } fn _adaptadores_de_iterador() { let _nums = (1..100).map(|x| x + 1).collect::<Vec<_>>(); let _nums = (1..30) .filter(|&x| x % 2 == 0) .filter(|&x| x % 3 == 0) .take(5) .collect::<Vec<i32>>(); for x in (1..11).map(|x| x + 1).collect::<Vec<_>>() { println!("{}", x); } } fn _hilos() { thread::spawn(|| { println!("Hola desde un hilo!"); }); thread::sleep(Duration::from_millis(10)); } fn _thread_handle() { let handle = thread::spawn(|| { "Hola desde un hilo!" }); //unwrap() hará un pánico ( panic! ) si el Result es Err assert_eq!("Hola desde un hilo!", handle.join().unwrap()); } fn _panico_hilo() { let valor = 1; let result = thread::spawn(move || { if valor % 2 == 0 { panic!("ups!"); } 1 }).join(); let resultado = match result { Ok(n) => n, Err(_e) => 0 }; assert_eq!(1, resultado); } fn _panico_unreachable() { enum Estado { _Activo, _Inactivo, Desconocido } use Estado::{_Activo, _Inactivo, Desconocido}; let estado = Desconocido; let _numero = match estado { _Activo => 1, _Inactivo => 0, _ => unreachable!() }; println!("Linea no alcanzable") } fn _option() { let s = "foo"; assert_eq!(s.find('f'), Some(0)); assert_eq!(s.find('z'), None); assert_eq!(s.find('f').map(|p| p + 1), Some(1)); assert_eq!(s.find('z').map(|p| p + 1), None); } fn _option_match() { let option = Some(5); let number = match option { Some(x) => x, None => 0, }; assert_eq!(5, number); } fn _result_funciones() { enum Error { Tecnico } let f: fn(i32) -> Result<i32, Error> = |num: i32| match num { 1 => Ok(num + 1), _ => Err(Error::Tecnico) }; /*fn f(num: i32) -> Result<i32, Error> { match num { 1 => Ok(num + 1), _ => Err(Error::Tecnico) } }*/ assert!(f(1).is_ok()); assert!(f(2).is_err()); let result: Result<i32, &str> = f(2) .map(|ok| ok) .map_err(|_err| "Error =("); match result { Ok(n) => println!("{}", n), Err(e) => println!("{}", e) }; } fn _panic_result() { let result: Result<i32, &str> = Ok(1); //let result: Result<i32, &str> = Err("Error =("); let valor = result.ok().expect("Error!"); assert_eq!(1, valor) } fn _try() { fn _parser(num: &str) -> Result<i32, ParseIntError> { num.parse() } fn f(x: &str, y: &str) -> Result<i32, ParseIntError> { let num1 = _parser(x); let num2 = _parser(y); //let resultado = _parser(x)? + _parser(y)?; let resultado = num1? + num2?; Ok(resultado) } assert!(f("1", "2").is_ok()); assert!(f("1P", "2").is_err()); match f("1P", "2") { Ok(n) => println!("Ok: {}", n), Err(e) => println!("Error: {}", e) } } fn _try_azucar_sintactico() { fn foo(n: i32) -> Result<i32, String> { if n % 2 == 0 { Ok(1) } else { Err(String::from("Error")) } } fn bar() -> Result<i32, String> { Ok(2) } fn foo_bar() -> Result<i32, String> { let res = foo(2)? + bar()?; Ok(res) } let fb = foo_bar(); assert!(fb.is_ok()); } fn _apuntadores_a_funcion() { fn mas_uno(i: i32) -> i32 { i + 1 } let f: fn(i32) -> i32 = mas_uno; assert_eq!(2, f(1)); } fn _primitivos() { let _a: bool = false; let _b: char = 'x'; let _c: i32 = 42; //i8, i16, i32, i64, u8, u16, u32, u64, isize, usize, f32, f64 } fn _arreglos() { let mut m: [i32; 3] = [1, 2, 3]; m[2] = 5; assert_eq!(5, m[2]); } fn _slices() { let a: [i32; 5] = [0, 1, 2, 3, 4]; let middle: &[i32] = &a[1..4]; assert_eq!(1, middle[0]); } fn _tuplas() { let (x, y) = (1, "Hello"); assert_eq!(1, x); assert_eq!("Hello", y); let z = (1, "Hello"); assert_eq!(1, z.0); } fn _expresiones() { let x = 5; let y = if x == 5 { 10 } else { 15 }; assert_eq!(10, y) } fn _while() { let mut x = 0; while x < 10 { x += 1; } assert_eq!(10, x) } fn _for() { for x in 0..10 { println!("{}", x); } } fn _loop() { let mut x = 0; loop { x += 1; if x >= 10 { break } } assert_eq!(10, x) } fn _etiquetas_loop() { 'exterior: for x in 0..10 { 'interior: for y in 0..10 { if x % 2 == 0 { continue 'exterior; } // continua el ciclo por encima de x if y % 2 == 0 { continue 'interior; } // continua el ciclo por encima de y println!("x: {}, y: {}", x, y); } } } fn _enumerate() { for (i,j) in (5..10).enumerate() { println!("i = {} y j = {}", i, j); } let lineas = "hola\nmundo".lines(); for (numero_linea, linea) in lineas.enumerate() { println!("{}: {}", numero_linea, linea); } } fn _pertenencia() { let v = vec![1, 2, 3]; let v2 = v; println!("v2[0] es: {}", v2[0]); //println!("v[0] es: {}", v[0]); // Error borrow of moved value: `v` } fn _pertenencia_funcion() { fn tomar(_v: Vec<i32>) { // Algo } let v = vec![1, 2, 3]; tomar(v); //println!("v[0] es: {}", v[0]); // Error borrow of moved value: `v` } fn _copy() { // i32, Todos los tipos primitivos implementan el trait Copy // Se realiza una copia y su pertenencia no es movida let v: i32 = 1; let _v2 = v; println!("v es: {}", v); // =) } fn _devolver_pertenencia() { fn _foo(v: Vec<i32>) -> Vec<i32> { v } fn foo(v1: Vec<i32>, v2: Vec<i32>) -> (Vec<i32>, Vec<i32>, i32) { (v1, v2, 42) } let v1 = vec![1, 2, 3]; let v2 = vec![1, 2, 3]; let (v1, _v2, _r) = foo(v1, v2); assert_eq!(1, v1[0]); } fn _prestamo() { fn foo(_v1: &Vec<i32>, _v2: &Vec<i32>) -> i32 { 42 } let v1 = vec![1, 2, 3]; let _v2 = vec![1, 2, 3]; let _r = foo(&v1, &_v2); // podemos usar a v1 y v2 aqui assert_eq!(1, v1[0]); } fn _mutabilidad() { let mut x = 5; assert_eq!(5, x); x = 6; assert_eq!(6, x); } fn _estructuras() { struct Punto { x: i32, y: i32, } let origen = Punto { x: 0, y: 0 }; assert_eq!(0, origen.x); assert_eq!(0, origen.y); } fn _sintaxis_de_actualizacion() { struct Punto3d { _x: i32, _y: i32, _z: i32, } let origen = Punto3d { _x: 1, _y: 2, _z: 3 }; let punto = Punto3d { _y: 1,.. origen }; assert_eq!(3, punto._z); } fn _estructuras_pertenencia() { struct Punto { x: i32, y: i32, } fn foo(punto: Punto) -> i32 { punto.x + punto.y } let origen = Punto { x: 1, y: 2 }; let suma = foo(origen); println!("{}", suma); //println!("Punto x {}", origen.x); // Error borrow of moved value: `origen` } fn _estructuras_prestamo() { struct Punto { x: i32, y: i32, } fn foo(punto: &Punto) -> i32 { punto.x + punto.y } let origen = Punto { x: 1, y: 2 }; let suma = foo(&origen); assert_eq!(3, suma); assert_eq!(1, origen.x); } fn _tupla_estructuras() { struct Color(i32, i32, i32); let azul = Color(0, 0, 255); assert_eq!(255, azul.2); } fn _estructuras_tipo_unitario() { struct Electron; let _e = Electron; } fn _enumeraciones() { enum Mensaje { Salir, CambiarColor(i32, i32, i32), Mover { _x: i32, _y: i32 }, Escribir(String), } let _salir = Mensaje::Salir; let _cambiar_color = Mensaje::CambiarColor(0, 0, 255); use Mensaje::{Mover}; let _mover = Mover {_x: 0, _y: 2}; let _escribir = Mensaje::Escribir("Hello".to_string()); } fn _match_en_enums() { enum _Mensaje { Salir, CambiarColor(i32, i32, i32), Mover { x: i32, _y: i32 }, Escribir(String), } fn _salir() { /*... */ } fn _cambiar_color(_r: i32, _g: i32, _b: i32) { /*... */ } fn _mover_cursor(_x: i32, _y: i32) { /*... */ } fn _procesar_mensaje(msj: _Mensaje) { match msj { _Mensaje::Salir => _salir(), _Mensaje::CambiarColor(r, g, b) => _cambiar_color(r, g, b), _Mensaje::Mover { x, _y: y } => _mover_cursor(x, y), _Mensaje::Escribir(s) => println!("{}", s), }; } } fn _mul
let x = 2; let num = match x { 1 | 2 => "1, 2", 3 => "3", _ => "...", }; assert_eq!("1, 2", num); } fn _match_rangos() { let x = 3; let resultado = match x { 1..= 5 => "uno al cinco", _ => "cualquier cosa", }; assert_eq!("uno al cinco", resultado); let y ='s'; let letra = match y { 'a'..= 'j' => "letra temprana", 'k'..= 'z' => "letra tardia", _ => "algo mas" }; assert_eq!("letra tardia", letra); } fn _destructuracion() { struct Punto { x: i32, y: i32, } let origen = Punto { x: 0, y: 2 }; match origen { Punto { x, y } => println!("({},{})", x, y), } match origen { Punto { x,.. } => println!("x es {}", x) } } fn _enlaces_a_variable() { let x = 1; match x { e @ 1..= 5 => println!("valor de rango {} obtenido", e), _ => println!("lo que sea"), } } fn _guardias() { enum EnteroOpcional { Valor(i32), _Faltante, } let x = EnteroOpcional::Valor(5); match x { EnteroOpcional::Valor(i) if i > 5 => println!("Entero mayor a cinco obtenido!"), EnteroOpcional::Valor(..) => println!("Entero obtenido!"), EnteroOpcional::_Faltante => println!("Sin suerte."), } } fn _multiples_patrones_y_guardias() { let x = 4; let y = false; let resultado = match x { 4 | 5 if y => "si", _ => "no" }; assert_eq!("no", resultado); } fn _llamadas_a_metodos() { struct Circulo { _x: f64, _y: f64, radio: f64, } impl Circulo { fn area(&self) -> f64 { std::f64::consts::PI * (self.radio * self.radio) } } let c = Circulo { _x: 0.0, _y: 0.0, radio: 2.0 }; println!("{}", c.area()); } fn _metodos_en_cadena() { struct Circulo { x: f64, y: f64, radio: f64, } impl Circulo { fn agrandar(&self, incremento: f64) -> Circulo { Circulo { x: self.x, y: self.y, radio: self.radio + incremento } } fn area(&self) -> f64 { std::f64::consts::PI * (self.radio * self.radio) } } let c = Circulo { x: 0.0, y: 0.0, radio: 2.0 }; println!("{}", c.area()); let d = c.agrandar(2.0).area(); println!("{}", d); } fn _funciones_asociadas() { struct Circulo { _x: f64, _y: f64, radio: f64, } impl Circulo { fn new(x: f64, y: f64, radio: f64) -> Circulo { Circulo { _x: x, _y: y, radio: radio, } } } let c = Circulo::new(0.0, 0.0, 2.0); assert_eq!(2.0, c.radio); } fn _builder() { struct Circulo { x: f64, y: f64, radio: f64 } impl Circulo { fn area(&self) -> f64 { std::f64::consts::PI * (self.radio * self.radio) } } struct CirculoBuilder { x: f64, y: f64, radio: f64 } impl CirculoBuilder { fn new() -> CirculoBuilder { CirculoBuilder { x: 0.0, y: 0.0, radio: 1.0, } } fn x(&mut self, coordenada: f64) -> &mut CirculoBuilder { self.x = coordenada; self } fn y(&mut self, coordenada: f64) -> &mut CirculoBuilder { self.y = coordenada; self } fn radio(&mut self, radio: f64) -> &mut CirculoBuilder { self.radio = radio; self } fn build(&self) -> Circulo { Circulo { x: self.x, y: self.y, radio: self.radio } } } let c = CirculoBuilder::new() .x(1.0) .y(2.0) .radio(2.0) .build(); println!("area: {}", c.area()); println!("x: {}", c.x); println!("y: {}", c.y); assert_eq!(2.0, c.y); } fn _cadenas_de_caracteres() { let _saludo: &str = "Hola."; let mut s: String = "Hola".to_string(); s.push_str(", mundo."); assert_eq!("Hola, mundo.", s); } fn _genericos() { enum _Option<T> { _Some(T), _None, } let _x: _Option<i32> = _Option::_Some(5); } fn _funciones_genericas() { fn foo<T>(x: T) -> T { x } let num = foo(1); assert_eq!(1, num); } fn _structs_genericos() { struct Info<T1, T2> { x: T1, y: T2, } impl<T1, T2> Info<T1, T2> { fn foo(&self) { // } } let info = Info { x: 1, y: "=)" }; info.foo(); assert_eq!(1, info.x); assert_eq!("=)", info.y); } fn _traits() { trait Area { fn area(&self) -> f64; } struct Circulo { _x: f64, _y: f64, radio: f64 } impl Area for Circulo { fn area(&self) -> f64 { std::f64::consts::PI * (self.radio * self.radio) } } let c = Circulo{ _x:0.0, _y:0.0, radio: 2.0 }; let a = c.area(); println!("{}", a); //Genericos fn imrimir_area<T: Area>(figura: T) { println!("Esta figura tiene un area de {}", figura.area()); } imrimir_area(c) } fn _multiples_limites_de_trait() { use std::fmt::Display; fn foo<T: Clone, K: Clone + Display>(x: T, y: K) -> String { let _x_clone = x.clone(); let y_clone = y.clone(); format!("{}", y_clone) } fn bar<T, K>(x: T, y: K) -> String where T: Clone, K: Clone + Display { let _x_clone = x.clone(); let y_clone = y.clone(); format!("{}", y_clone) } let r_foo = foo("Hola", "mundo"); let r_bar = bar("Hola", "mundo"); assert_eq!(r_foo, r_bar); } fn _metodos_por_defecto() { trait Foo { fn es_valido(&self) -> bool; fn es_invalido(&self) -> bool {!self.es_valido() } } struct Default; impl Foo for Default { fn es_valido(&self) -> bool { true } } let default = Default; assert!(default.es_valido()); assert!(!default.es_invalido()); } fn _metodos_por_defecto_bar() { trait Bar { fn plus_one(x: i32) -> i32 { x +
tiples_patrones() {
identifier_name
main.rs
Err(e) => e.to_string() }; assert_eq!("5", end); } fn _result_match() { let result: Result<i32, &str> = Ok(5); let number = match result { Ok(x) => x, Err(_e) => 0, }; assert_eq!(5, number) } fn _threads() { let handles: Vec<_> = (0..10).map(|x| { thread::spawn(move|| { println!("{}", x) }) }).collect(); for h in handles { h.join().ok().expect("No se pudo unir un hilo!"); } } fn _threads_join() { thread::spawn(|| { thread::sleep(Duration::from_millis(3000)); println!("Hola desde 1"); }); let thread2 = thread::spawn(|| { thread::sleep(Duration::from_millis(3000)); println!("Hola desde 2"); }); println!("end..."); thread2.join().expect("Error"); //thread::sleep(Duration::from_millis(4000)); } fn _iteradores() { let mut rango = 0..10; loop { match rango.next() { Some(x) => { println!("{}", x); }, None => { break } } } let nums = vec![1, 2, 3]; for num in nums.iter() { println!("{}", num); } } fn _consumidores() { let _uno_hasta_cien = (1..101).collect::<Vec<i32>>(); let _uno_hasta_cien = (1..101).collect::<Vec<_>>(); let mayores_a_cuarenta_y_dos = (0..100) .find(|x| *x > 42); match mayores_a_cuarenta_y_dos { Some(_) => println!("Tenemos algunos números!"), None => println!("No se encontraron números :("), } let suma = (1..4).fold(0, |suma, x| suma + x); //6 assert_eq!(6, suma); } fn _adaptadores_de_iterador() { let _nums = (1..100).map(|x| x + 1).collect::<Vec<_>>(); let _nums = (1..30) .filter(|&x| x % 2 == 0) .filter(|&x| x % 3 == 0) .take(5) .collect::<Vec<i32>>(); for x in (1..11).map(|x| x + 1).collect::<Vec<_>>() { println!("{}", x); } } fn _hilos() { thread::spawn(|| { println!("Hola desde un hilo!"); }); thread::sleep(Duration::from_millis(10)); } fn _thread_handle() { let handle = thread::spawn(|| { "Hola desde un hilo!" }); //unwrap() hará un pánico ( panic! ) si el Result es Err assert_eq!("Hola desde un hilo!", handle.join().unwrap()); } fn _panico_hilo() { let valor = 1; let result = thread::spawn(move || { if valor % 2 == 0 { panic!("ups!"); } 1 }).join(); let resultado = match result { Ok(n) => n, Err(_e) => 0 }; assert_eq!(1, resultado); } fn _panico_unreachable() { enum Estado { _Activo, _Inactivo, Desconocido } use Estado::{_Activo, _Inactivo, Desconocido}; let estado = Desconocido; let _numero = match estado { _Activo => 1, _Inactivo => 0, _ => unreachable!() }; println!("Linea no alcanzable") } fn _option() { let s = "foo"; assert_eq!(s.find('f'), Some(0)); assert_eq!(s.find('z'), None); assert_eq!(s.find('f').map(|p| p + 1), Some(1)); assert_eq!(s.find('z').map(|p| p + 1), None); } fn _option_match() { let option = Some(5); let number = match option { Some(x) => x, None => 0, }; assert_eq!(5, number); } fn _result_funciones() { enum Error { Tecnico } let f: fn(i32) -> Result<i32, Error> = |num: i32| match num { 1 => Ok(num + 1), _ => Err(Error::Tecnico) }; /*fn f(num: i32) -> Result<i32, Error> { match num { 1 => Ok(num + 1), _ => Err(Error::Tecnico) } }*/ assert!(f(1).is_ok()); assert!(f(2).is_err()); let result: Result<i32, &str> = f(2) .map(|ok| ok) .map_err(|_err| "Error =("); match result { Ok(n) => println!("{}", n), Err(e) => println!("{}", e) }; } fn _panic_result() { let result: Result<i32, &str> = Ok(1); //let result: Result<i32, &str> = Err("Error =("); let valor = result.ok().expect("Error!"); assert_eq!(1, valor) } fn _try() { fn _parser(num: &str) -> Result<i32, ParseIntError> { num.parse() } fn f(x: &str, y: &str) -> Result<i32, ParseIntError> { let num1 = _parser(x); let num2 = _parser(y); //let resultado = _parser(x)? + _parser(y)?; let resultado = num1? + num2?; Ok(resultado) } assert!(f("1", "2").is_ok()); assert!(f("1P", "2").is_err()); match f("1P", "2") { Ok(n) => println!("Ok: {}", n), Err(e) => println!("Error: {}", e) } } fn _try_azucar_sintactico() { fn foo(n: i32) -> Result<i32, String> { if n % 2 == 0 { Ok(1) } else { Err(String::from("Error")) } } fn bar() -> Result<i32, String> { Ok(2) } fn foo_bar() -> Result<i32, String> { let res = foo(2)? + bar()?; Ok(res) } let fb = foo_bar(); assert!(fb.is_ok()); } fn _apuntadores_a_funcion() { fn mas_uno(i: i32) -> i32 { i + 1 } let f: fn(i32) -> i32 = mas_uno; assert_eq!(2, f(1)); } fn _primitivos() { let _a: bool = false; let _b: char = 'x'; let _c: i32 = 42; //i8, i16, i32, i64, u8, u16, u32, u64, isize, usize, f32, f64 } fn _arreglos() { let mut m: [i32; 3] = [1, 2, 3]; m[2] = 5; assert_eq!(5, m[2]); } fn _slices() { let a: [i32; 5] = [0, 1, 2, 3, 4]; let middle: &[i32] = &a[1..4]; assert_eq!(1, middle[0]); } fn _tuplas() { let (x, y) = (1, "Hello"); assert_eq!(1, x); assert_eq!("Hello", y); let z = (1, "Hello"); assert_eq!(1, z.0); } fn _expresiones() { let x = 5; let y = if x == 5 { 10 } else { 15 }; assert_eq!(10, y) } fn _while() { let mut x = 0; while x < 10 { x += 1; } assert_eq!(10, x) } fn _for() { for x in 0..10 { println!("{}", x); } } fn _loop() { let mut x = 0; loop { x += 1; if x >= 10 { break } } assert_eq!(10, x) } fn _etiquetas_loop() { 'exterior: for x in 0..10 { 'interior: for y in 0..10 { if x % 2 == 0 { continue 'exterior; } // continua el ciclo por encima de x if y % 2 == 0 { co
continua el ciclo por encima de y println!("x: {}, y: {}", x, y); } } } fn _enumerate() { for (i,j) in (5..10).enumerate() { println!("i = {} y j = {}", i, j); } let lineas = "hola\nmundo".lines(); for (numero_linea, linea) in lineas.enumerate() { println!("{}: {}", numero_linea, linea); } } fn _pertenencia() { let v = vec![1, 2, 3]; let v2 = v; println!("v2[0] es: {}", v2[0]); //println!("v[0] es: {}", v[0]); // Error borrow of moved value: `v` } fn _pertenencia_funcion() { fn tomar(_v: Vec<i32>) { // Algo } let v = vec![1, 2, 3]; tomar(v); //println!("v[0] es: {}", v[0]); // Error borrow of moved value: `v` } fn _copy() { // i32, Todos los tipos primitivos implementan el trait Copy // Se realiza una copia y su pertenencia no es movida let v: i32 = 1; let _v2 = v; println!("v es: {}", v); // =) } fn _devolver_pertenencia() { fn _foo(v: Vec<i32>) -> Vec<i32> { v } fn foo(v1: Vec<i32>, v2: Vec<i32>) -> (Vec<i32>, Vec<i32>, i32) { (v1, v2, 42) } let v1 = vec![1, 2, 3]; let v2 = vec![1, 2, 3]; let (v1, _v2, _r) = foo(v1, v2); assert_eq!(1, v1[0]); } fn _prestamo() { fn foo(_v1: &Vec<i32>, _v2: &Vec<i32>) -> i32 { 42 } let v1 = vec![1, 2, 3]; let _v2 = vec![1, 2, 3]; let _r = foo(&v1, &_v2); // podemos usar a v1 y v2 aqui assert_eq!(1, v1[0]); } fn _mutabilidad() { let mut x = 5; assert_eq!(5, x); x = 6; assert_eq!(6, x); } fn _estructuras() { struct Punto { x: i32, y: i32, } let origen = Punto { x: 0, y: 0 }; assert_eq!(0, origen.x); assert_eq!(0, origen.y); } fn _sintaxis_de_actualizacion() { struct Punto3d { _x: i32, _y: i32, _z: i32, } let origen = Punto3d { _x: 1, _y: 2, _z: 3 }; let punto = Punto3d { _y: 1,.. origen }; assert_eq!(3, punto._z); } fn _estructuras_pertenencia() { struct Punto { x: i32, y: i32, } fn foo(punto: Punto) -> i32 { punto.x + punto.y } let origen = Punto { x: 1, y: 2 }; let suma = foo(origen); println!("{}", suma); //println!("Punto x {}", origen.x); // Error borrow of moved value: `origen` } fn _estructuras_prestamo() { struct Punto { x: i32, y: i32, } fn foo(punto: &Punto) -> i32 { punto.x + punto.y } let origen = Punto { x: 1, y: 2 }; let suma = foo(&origen); assert_eq!(3, suma); assert_eq!(1, origen.x); } fn _tupla_estructuras() { struct Color(i32, i32, i32); let azul = Color(0, 0, 255); assert_eq!(255, azul.2); } fn _estructuras_tipo_unitario() { struct Electron; let _e = Electron; } fn _enumeraciones() { enum Mensaje { Salir, CambiarColor(i32, i32, i32), Mover { _x: i32, _y: i32 }, Escribir(String), } let _salir = Mensaje::Salir; let _cambiar_color = Mensaje::CambiarColor(0, 0, 255); use Mensaje::{Mover}; let _mover = Mover {_x: 0, _y: 2}; let _escribir = Mensaje::Escribir("Hello".to_string()); } fn _match_en_enums() { enum _Mensaje { Salir, CambiarColor(i32, i32, i32), Mover { x: i32, _y: i32 }, Escribir(String), } fn _salir() { /*... */ } fn _cambiar_color(_r: i32, _g: i32, _b: i32) { /*... */ } fn _mover_cursor(_x: i32, _y: i32) { /*... */ } fn _procesar_mensaje(msj: _Mensaje) { match msj { _Mensaje::Salir => _salir(), _Mensaje::CambiarColor(r, g, b) => _cambiar_color(r, g, b), _Mensaje::Mover { x, _y: y } => _mover_cursor(x, y), _Mensaje::Escribir(s) => println!("{}", s), }; } } fn _multiples_patrones() { let x = 2; let num = match x { 1 | 2 => "1, 2", 3 => "3", _ => "...", }; assert_eq!("1, 2", num); } fn _match_rangos() { let x = 3; let resultado = match x { 1..= 5 => "uno al cinco", _ => "cualquier cosa", }; assert_eq!("uno al cinco", resultado); let y ='s'; let letra = match y { 'a'..= 'j' => "letra temprana", 'k'..= 'z' => "letra tardia", _ => "algo mas" }; assert_eq!("letra tardia", letra); } fn _destructuracion() { struct Punto { x: i32, y: i32, } let origen = Punto { x: 0, y: 2 }; match origen { Punto { x, y } => println!("({},{})", x, y), } match origen { Punto { x,.. } => println!("x es {}", x) } } fn _enlaces_a_variable() { let x = 1; match x { e @ 1..= 5 => println!("valor de rango {} obtenido", e), _ => println!("lo que sea"), } } fn _guardias() { enum EnteroOpcional { Valor(i32), _Faltante, } let x = EnteroOpcional::Valor(5); match x { EnteroOpcional::Valor(i) if i > 5 => println!("Entero mayor a cinco obtenido!"), EnteroOpcional::Valor(..) => println!("Entero obtenido!"), EnteroOpcional::_Faltante => println!("Sin suerte."), } } fn _multiples_patrones_y_guardias() { let x = 4; let y = false; let resultado = match x { 4 | 5 if y => "si", _ => "no" }; assert_eq!("no", resultado); } fn _llamadas_a_metodos() { struct Circulo { _x: f64, _y: f64, radio: f64, } impl Circulo { fn area(&self) -> f64 { std::f64::consts::PI * (self.radio * self.radio) } } let c = Circulo { _x: 0.0, _y: 0.0, radio: 2.0 }; println!("{}", c.area()); } fn _metodos_en_cadena() { struct Circulo { x: f64, y: f64, radio: f64, } impl Circulo { fn agrandar(&self, incremento: f64) -> Circulo { Circulo { x: self.x, y: self.y, radio: self.radio + incremento } } fn area(&self) -> f64 { std::f64::consts::PI * (self.radio * self.radio) } } let c = Circulo { x: 0.0, y: 0.0, radio: 2.0 }; println!("{}", c.area()); let d = c.agrandar(2.0).area(); println!("{}", d); } fn _funciones_asociadas() { struct Circulo { _x: f64, _y: f64, radio: f64, } impl Circulo { fn new(x: f64, y: f64, radio: f64) -> Circulo { Circulo { _x: x, _y: y, radio: radio, } } } let c = Circulo::new(0.0, 0.0, 2.0); assert_eq!(2.0, c.radio); } fn _builder() { struct Circulo { x: f64, y: f64, radio: f64 } impl Circulo { fn area(&self) -> f64 { std::f64::consts::PI * (self.radio * self.radio) } } struct CirculoBuilder { x: f64, y: f64, radio: f64 } impl CirculoBuilder { fn new() -> CirculoBuilder { CirculoBuilder { x: 0.0, y: 0.0, radio: 1.0, } } fn x(&mut self, coordenada: f64) -> &mut CirculoBuilder { self.x = coordenada; self } fn y(&mut self, coordenada: f64) -> &mut CirculoBuilder { self.y = coordenada; self } fn radio(&mut self, radio: f64) -> &mut CirculoBuilder { self.radio = radio; self } fn build(&self) -> Circulo { Circulo { x: self.x, y: self.y, radio: self.radio } } } let c = CirculoBuilder::new() .x(1.0) .y(2.0) .radio(2.0) .build(); println!("area: {}", c.area()); println!("x: {}", c.x); println!("y: {}", c.y); assert_eq!(2.0, c.y); } fn _cadenas_de_caracteres() { let _saludo: &str = "Hola."; let mut s: String = "Hola".to_string(); s.push_str(", mundo."); assert_eq!("Hola, mundo.", s); } fn _genericos() { enum _Option<T> { _Some(T), _None, } let _x: _Option<i32> = _Option::_Some(5); } fn _funciones_genericas() { fn foo<T>(x: T) -> T { x } let num = foo(1); assert_eq!(1, num); } fn _structs_genericos() { struct Info<T1, T2> { x: T1, y: T2, } impl<T1, T2> Info<T1, T2> { fn foo(&self) { // } } let info = Info { x: 1, y: "=)" }; info.foo(); assert_eq!(1, info.x); assert_eq!("=)", info.y); } fn _traits() { trait Area { fn area(&self) -> f64; } struct Circulo { _x: f64, _y: f64, radio: f64 } impl Area for Circulo { fn area(&self) -> f64 { std::f64::consts::PI * (self.radio * self.radio) } } let c = Circulo{ _x:0.0, _y:0.0, radio: 2.0 }; let a = c.area(); println!("{}", a); //Genericos fn imrimir_area<T: Area>(figura: T) { println!("Esta figura tiene un area de {}", figura.area()); } imrimir_area(c) } fn _multiples_limites_de_trait() { use std::fmt::Display; fn foo<T: Clone, K: Clone + Display>(x: T, y: K) -> String { let _x_clone = x.clone(); let y_clone = y.clone(); format!("{}", y_clone) } fn bar<T, K>(x: T, y: K) -> String where T: Clone, K: Clone + Display { let _x_clone = x.clone(); let y_clone = y.clone(); format!("{}", y_clone) } let r_foo = foo("Hola", "mundo"); let r_bar = bar("Hola", "mundo"); assert_eq!(r_foo, r_bar); } fn _metodos_por_defecto() { trait Foo { fn es_valido(&self) -> bool; fn es_invalido(&self) -> bool {!self.es_valido() } } struct Default; impl Foo for Default { fn es_valido(&self) -> bool { true } } let default = Default; assert!(default.es_valido()); assert!(!default.es_invalido()); } fn _metodos_por_defecto_bar() { trait Bar { fn plus_one(x: i32) -> i32 { x
ntinue 'interior; } //
conditional_block
fixed.rs
//! Groups all the static pages together. use maud::Markup; use rocket::Route; mod contacts; mod links; mod projects; mod resume; /// Returns the "index" page, aka the home page of the website. /// /// This simply calls [`page_client::home::index()`] from [`page_client`]. #[get("/")] fn get_index() -> Markup { htmlgen::index() } /// Provides a [`Vec`] of [`Route`]s to be attached with [`rocket::Rocket::mount()`]. pub fn
() -> Vec<Route> { routes![ get_index, resume::get, links::get, contacts::get, projects::get, projects::project::get, ] } /// Functions generating my home page. pub mod htmlgen { use maud::{html, Markup, Render}; use page_client::{data, partials}; /// Create a basic menu. pub fn menu() -> Option<data::Menu<'static>> { Some(data::Menu(&[data::MenuItem { text: "Blog", link: Some("/blog"), children: None, }])) } /// Returns a list of links as [`Markup`]. fn link_group() -> Markup { let links = vec![ data::LogoLink { url: "https://github.com/AlterionX/", logo: "public/img/icon/github.png", alt_text: "Github", text: "AlterionX", }, data::LogoLink { url: "mailto:[email protected]", logo: "public/img/icon/email.svg", alt_text: "Email", text: "[email protected]", }, data::LogoLink { url: "public/resume/resume.pdf", logo: "public/img/icon/resume.svg", alt_text: "Resume", text: "Resume", }, ]; html! { .link-group { @for link in links.iter() { (link) } } } } /// Returns the slide show as [`Markup`]. fn slides() -> Markup { html! { .slides { (my_intro()) (my_story()) (my_work()) (my_interests()) (my_passion()) (my_reading_time()) (my_gaming_time()) } .slide-attachments { img#slide-prev.slide-attachment src="public/img/left-simple-arrow.svg"; .slide-markers.slide-attachment { (slide_markers(7)) } img#slide-next.slide-attachment src="public/img/right-simple-arrow.svg"; } } } /// Returns a slide as [`Markup`]. fn slide<T: Render, U: Render>(title: T, text: U, cls: Option<&str>) -> Markup { html! { div class={ "slide" @if let Some(cls) = cls { " " (cls) } } { h2.slide-heading { (title) } .slide-text { (text) } } } } /// Returns the slide_markers as [`Markup`]. fn slide_markers(slide_cnt: u8) -> Markup { html! { @for i in 0..slide_cnt { (slide_marker(i)) } } } /// Returns the slide_marker as [`Markup`]. fn slide_marker(idx: u8) -> Markup { html! { div id = { "slide-marker-"(idx) } class={"slide-marker" @if idx == 0 { (" active-slide-marker") }} {} } } /// Returns the first slide as [`Markup`]. fn my_intro() -> Markup { slide( "Nice to meet you", html! { p { "My name is Ben. I am a developer, but I am also:" } ul { li { "a reader; I love to read. But that can get long, so let's save the details for later." } li { "a writer; " a href="https://www.nanowrimo.org/participants/alterionx/novels" { "NaNoWriMo" } " \ (a.k.a. November) is simultaneously my favorite and most hated month of the year." } li { "a gamer; still waiting for " a href="https://robertsspaceindustries.com/" { "Star Citizen." } } li { "a linguist: I technically know Chinese, and am studying Japanese." } } p {"\ But mostly, I just enjoy watching pretty colors scroll really " span.italic.bold { "really" } " fast down \ my terminal screen while I run my programs and blabber endlessly about my interests.\ "} }, Some("intro active-slide"), ) } /// Returns the second slide as [`Markup`]. fn my_interests() -> Markup { slide( "Everything is fascinating", html! { p {"\ C, C++, and Rust are my favorite languages. I have worked in both OpenGl and Vulkan. \ I've dabbled with Unity, Godot, and Unreal; Amethyst sounds interesting as well. \ However, I also enjoy gaming and reading in my spare time, as well as learning even more about \ tech and interesting projects such as WASM, xi, TypeScript, Fuschia, and AR glasses.\ "} p {"\ As a note, just for fun, this entire website is built with Rust + WASM \ (Such a fun word. Anyways...). I don't know how many browsers it runs on, \ but it was definitely fun. \ "} }, None, ) } /// Returns the third slide as [`Markup`]. fn my_story() -> Markup { slide( "Improve a little, day by day", html! { p {"\ There was a day in 10th grade, when one of my friends introduced me to Java. I was \ enamored the moment I touched the keyboard. The actual program was cute little \ thing, reading and adding two numbers.\ "} p {"\ It blew my mind. "} p {"\ Now that I think about it, it fits; I had been enchanted by the power of words so I wanted to be a novelist,\ but then I found something even more powerful.\ "} p {"\ Either way, I had decided then and there that I knew that I wanted to program for \ a living. And now I'm here, seeking to live a life programming and architecting solutions.\ "} }, None, ) } /// Returns the fourth slide as [`Markup`]. fn my_work() -> Markup { slide( "Learning to code", html! { p {"\ I've picked up a lot of different skills since that day. I developed a custom Wordpress theme and wrote \ a chatlog for my English class. In my last year of high school, I learned about automata theory.\ "} p {"\ When I came to college, I wrote part of an OS in no-std C++ and a Python frontend for connecting to a server and testing. \ I fell in love with writing tools and performance-critical programming.\ "} p {"\ I've written (with a friend) a ray tracer, a fluid simulation, and a shattering simulation. I am in the \ middle of writing a simulation in Rust that combines a majority of these concepts. I ended up devoting \ enough time to it that I will make it my thesis project.\ "} }, None, ) } /// Returns the fifth slide as [`Markup`]. fn my_passion() -> Markup { slide( "Programming and Writing", html! { p {"\ I focus on systems development, rendering, and physical simulation. I think I've already said \ enough about that. But I also have a string interest in game development and story writing.\ "} p {"\ In fact, by virtue of NaNoWriMo, I have the first version of my novel finished!\ "} }, None, ) } /// Returns the sixth slide as [`Markup`]. fn my_reading_time() -> Markup { slide( "Breaktime: Reading!", html! { p {"\ Speaking of wriing, I love to read as well. " a href="https://brandonsanderson.com/" { "Brandon Sanderson" } "'s my favorite author, \ but " a href="https://www.patrickrothfuss.com/content/index.asp" { "Patrick Rothfuss" } " is the most \ inspirational one—still waiting for " span.underline { "The Doors of Stone" } ". (It's alright. We've only waited for a decade-ish.)\ "} p {"\ Rothfuss is the one who inspired me to write, so I aim to take just as long as him to finish my stories. \ But, actually, the subtelty and detailed foreshadowing in his work is mind boggling. As I attempt to do \ the same, I realize this all the more.\ "} }, None, ) } /// Returns the seventh slide as [`Markup`]. fn my_gaming_time() -> Markup { slide( "Breaktime: Gaming!", html! { p {"\ Games are the other half of my free time. Shooters are good as stress relief but my favorites are RPGs. \ My favorites, however, is The Last of Us. It is a work of art. Nier: Automata comes in at a close second; it's only lower \ due to the PC port -- as a developer, its poor performance was obvious.\ "} p {"\ The favorites I'd listed are RPGs, but I find myself more engrossed in Terraria and Stellaris than RPGs since they leave a lot of room to \ establish a character and role play despite not being an RPG. Dungeons and Dragons (DnD) is pretty fun as well.\ "} p {"\ I also enjoy various space sims, but Star Citizen has captured my heart and I don't think I could ever play a different \ space sim without thinking about Star Citizen.\ "} }, None, ) } /// Returns a list of [`Css`](crate::data::Css) scripts that go in my home page. fn css_scripts<'a>() -> [data::Css<'a>; 4] { [ data::Css::Critical { src: "reset" }, data::Css::Critical { src: "typography" }, data::Css::Critical { src: "main" }, data::Css::Critical { src: "index" }, ] } /// Returns the [`Markup`] version of my home page. pub fn index() -> Markup { let (glue, load) = data::Script::wasm_bindgen_loader("wasm_slideshow"); let js_scripts = [ data::Script::External(glue.as_str()), data::Script::Embedded(load.as_str()), ]; let css_scripts = css_scripts(); let menu = menu(); let logo = crate::shared_html::logo_markup(); let meta = data::MetaData::builder() .scripts(&js_scripts[..]) .css(&css_scripts[..]) .menu(menu.as_ref()) .logo(logo.as_ref()) .build(); partials::basic_page( html! { div.profile { h1.tagline { "Ben Xu | Developer" } img.propic src="public/img/propic.jpg" alt="Profile Picture"; (link_group()) (slides()) } }, Some(&meta), ) } }
routes
identifier_name
fixed.rs
//! Groups all the static pages together. use maud::Markup; use rocket::Route; mod contacts; mod links; mod projects; mod resume; /// Returns the "index" page, aka the home page of the website. /// /// This simply calls [`page_client::home::index()`] from [`page_client`]. #[get("/")] fn get_index() -> Markup { htmlgen::index() } /// Provides a [`Vec`] of [`Route`]s to be attached with [`rocket::Rocket::mount()`]. pub fn routes() -> Vec<Route> { routes![ get_index, resume::get, links::get, contacts::get, projects::get, projects::project::get, ] } /// Functions generating my home page. pub mod htmlgen { use maud::{html, Markup, Render}; use page_client::{data, partials}; /// Create a basic menu. pub fn menu() -> Option<data::Menu<'static>> { Some(data::Menu(&[data::MenuItem { text: "Blog", link: Some("/blog"), children: None, }])) } /// Returns a list of links as [`Markup`]. fn link_group() -> Markup { let links = vec![ data::LogoLink { url: "https://github.com/AlterionX/", logo: "public/img/icon/github.png", alt_text: "Github", text: "AlterionX", }, data::LogoLink { url: "mailto:[email protected]", logo: "public/img/icon/email.svg", alt_text: "Email", text: "[email protected]", }, data::LogoLink { url: "public/resume/resume.pdf", logo: "public/img/icon/resume.svg", alt_text: "Resume", text: "Resume", }, ]; html! { .link-group { @for link in links.iter() { (link) } } } } /// Returns the slide show as [`Markup`]. fn slides() -> Markup { html! { .slides { (my_intro()) (my_story()) (my_work()) (my_interests()) (my_passion()) (my_reading_time()) (my_gaming_time()) } .slide-attachments { img#slide-prev.slide-attachment src="public/img/left-simple-arrow.svg"; .slide-markers.slide-attachment { (slide_markers(7)) } img#slide-next.slide-attachment src="public/img/right-simple-arrow.svg"; } } } /// Returns a slide as [`Markup`]. fn slide<T: Render, U: Render>(title: T, text: U, cls: Option<&str>) -> Markup { html! { div class={ "slide" @if let Some(cls) = cls { " " (cls) } } { h2.slide-heading { (title) } .slide-text { (text) } } } } /// Returns the slide_markers as [`Markup`]. fn slide_markers(slide_cnt: u8) -> Markup { html! { @for i in 0..slide_cnt { (slide_marker(i)) } } } /// Returns the slide_marker as [`Markup`]. fn slide_marker(idx: u8) -> Markup
/// Returns the first slide as [`Markup`]. fn my_intro() -> Markup { slide( "Nice to meet you", html! { p { "My name is Ben. I am a developer, but I am also:" } ul { li { "a reader; I love to read. But that can get long, so let's save the details for later." } li { "a writer; " a href="https://www.nanowrimo.org/participants/alterionx/novels" { "NaNoWriMo" } " \ (a.k.a. November) is simultaneously my favorite and most hated month of the year." } li { "a gamer; still waiting for " a href="https://robertsspaceindustries.com/" { "Star Citizen." } } li { "a linguist: I technically know Chinese, and am studying Japanese." } } p {"\ But mostly, I just enjoy watching pretty colors scroll really " span.italic.bold { "really" } " fast down \ my terminal screen while I run my programs and blabber endlessly about my interests.\ "} }, Some("intro active-slide"), ) } /// Returns the second slide as [`Markup`]. fn my_interests() -> Markup { slide( "Everything is fascinating", html! { p {"\ C, C++, and Rust are my favorite languages. I have worked in both OpenGl and Vulkan. \ I've dabbled with Unity, Godot, and Unreal; Amethyst sounds interesting as well. \ However, I also enjoy gaming and reading in my spare time, as well as learning even more about \ tech and interesting projects such as WASM, xi, TypeScript, Fuschia, and AR glasses.\ "} p {"\ As a note, just for fun, this entire website is built with Rust + WASM \ (Such a fun word. Anyways...). I don't know how many browsers it runs on, \ but it was definitely fun. \ "} }, None, ) } /// Returns the third slide as [`Markup`]. fn my_story() -> Markup { slide( "Improve a little, day by day", html! { p {"\ There was a day in 10th grade, when one of my friends introduced me to Java. I was \ enamored the moment I touched the keyboard. The actual program was cute little \ thing, reading and adding two numbers.\ "} p {"\ It blew my mind. "} p {"\ Now that I think about it, it fits; I had been enchanted by the power of words so I wanted to be a novelist,\ but then I found something even more powerful.\ "} p {"\ Either way, I had decided then and there that I knew that I wanted to program for \ a living. And now I'm here, seeking to live a life programming and architecting solutions.\ "} }, None, ) } /// Returns the fourth slide as [`Markup`]. fn my_work() -> Markup { slide( "Learning to code", html! { p {"\ I've picked up a lot of different skills since that day. I developed a custom Wordpress theme and wrote \ a chatlog for my English class. In my last year of high school, I learned about automata theory.\ "} p {"\ When I came to college, I wrote part of an OS in no-std C++ and a Python frontend for connecting to a server and testing. \ I fell in love with writing tools and performance-critical programming.\ "} p {"\ I've written (with a friend) a ray tracer, a fluid simulation, and a shattering simulation. I am in the \ middle of writing a simulation in Rust that combines a majority of these concepts. I ended up devoting \ enough time to it that I will make it my thesis project.\ "} }, None, ) } /// Returns the fifth slide as [`Markup`]. fn my_passion() -> Markup { slide( "Programming and Writing", html! { p {"\ I focus on systems development, rendering, and physical simulation. I think I've already said \ enough about that. But I also have a string interest in game development and story writing.\ "} p {"\ In fact, by virtue of NaNoWriMo, I have the first version of my novel finished!\ "} }, None, ) } /// Returns the sixth slide as [`Markup`]. fn my_reading_time() -> Markup { slide( "Breaktime: Reading!", html! { p {"\ Speaking of wriing, I love to read as well. " a href="https://brandonsanderson.com/" { "Brandon Sanderson" } "'s my favorite author, \ but " a href="https://www.patrickrothfuss.com/content/index.asp" { "Patrick Rothfuss" } " is the most \ inspirational one—still waiting for " span.underline { "The Doors of Stone" } ". (It's alright. We've only waited for a decade-ish.)\ "} p {"\ Rothfuss is the one who inspired me to write, so I aim to take just as long as him to finish my stories. \ But, actually, the subtelty and detailed foreshadowing in his work is mind boggling. As I attempt to do \ the same, I realize this all the more.\ "} }, None, ) } /// Returns the seventh slide as [`Markup`]. fn my_gaming_time() -> Markup { slide( "Breaktime: Gaming!", html! { p {"\ Games are the other half of my free time. Shooters are good as stress relief but my favorites are RPGs. \ My favorites, however, is The Last of Us. It is a work of art. Nier: Automata comes in at a close second; it's only lower \ due to the PC port -- as a developer, its poor performance was obvious.\ "} p {"\ The favorites I'd listed are RPGs, but I find myself more engrossed in Terraria and Stellaris than RPGs since they leave a lot of room to \ establish a character and role play despite not being an RPG. Dungeons and Dragons (DnD) is pretty fun as well.\ "} p {"\ I also enjoy various space sims, but Star Citizen has captured my heart and I don't think I could ever play a different \ space sim without thinking about Star Citizen.\ "} }, None, ) } /// Returns a list of [`Css`](crate::data::Css) scripts that go in my home page. fn css_scripts<'a>() -> [data::Css<'a>; 4] { [ data::Css::Critical { src: "reset" }, data::Css::Critical { src: "typography" }, data::Css::Critical { src: "main" }, data::Css::Critical { src: "index" }, ] } /// Returns the [`Markup`] version of my home page. pub fn index() -> Markup { let (glue, load) = data::Script::wasm_bindgen_loader("wasm_slideshow"); let js_scripts = [ data::Script::External(glue.as_str()), data::Script::Embedded(load.as_str()), ]; let css_scripts = css_scripts(); let menu = menu(); let logo = crate::shared_html::logo_markup(); let meta = data::MetaData::builder() .scripts(&js_scripts[..]) .css(&css_scripts[..]) .menu(menu.as_ref()) .logo(logo.as_ref()) .build(); partials::basic_page( html! { div.profile { h1.tagline { "Ben Xu | Developer" } img.propic src="public/img/propic.jpg" alt="Profile Picture"; (link_group()) (slides()) } }, Some(&meta), ) } }
{ html! { div id = { "slide-marker-"(idx) } class={"slide-marker" @if idx == 0 { (" active-slide-marker") }} {} } }
identifier_body
fixed.rs
//! Groups all the static pages together. use maud::Markup; use rocket::Route; mod contacts; mod links; mod projects; mod resume; /// Returns the "index" page, aka the home page of the website. /// /// This simply calls [`page_client::home::index()`] from [`page_client`]. #[get("/")] fn get_index() -> Markup { htmlgen::index() } /// Provides a [`Vec`] of [`Route`]s to be attached with [`rocket::Rocket::mount()`]. pub fn routes() -> Vec<Route> { routes![ get_index, resume::get, links::get, contacts::get, projects::get, projects::project::get, ] } /// Functions generating my home page. pub mod htmlgen { use maud::{html, Markup, Render}; use page_client::{data, partials}; /// Create a basic menu. pub fn menu() -> Option<data::Menu<'static>> { Some(data::Menu(&[data::MenuItem { text: "Blog", link: Some("/blog"), children: None, }])) } /// Returns a list of links as [`Markup`]. fn link_group() -> Markup { let links = vec![ data::LogoLink { url: "https://github.com/AlterionX/", logo: "public/img/icon/github.png", alt_text: "Github", text: "AlterionX", }, data::LogoLink { url: "mailto:[email protected]", logo: "public/img/icon/email.svg", alt_text: "Email", text: "[email protected]", }, data::LogoLink { url: "public/resume/resume.pdf", logo: "public/img/icon/resume.svg", alt_text: "Resume", text: "Resume", }, ]; html! { .link-group { @for link in links.iter() { (link) } } } } /// Returns the slide show as [`Markup`]. fn slides() -> Markup { html! { .slides { (my_intro()) (my_story()) (my_work()) (my_interests()) (my_passion()) (my_reading_time()) (my_gaming_time()) } .slide-attachments { img#slide-prev.slide-attachment src="public/img/left-simple-arrow.svg"; .slide-markers.slide-attachment { (slide_markers(7)) } img#slide-next.slide-attachment src="public/img/right-simple-arrow.svg"; } } } /// Returns a slide as [`Markup`]. fn slide<T: Render, U: Render>(title: T, text: U, cls: Option<&str>) -> Markup { html! { div class={ "slide" @if let Some(cls) = cls { " " (cls) } } { h2.slide-heading { (title) } .slide-text { (text) } } } }
@for i in 0..slide_cnt { (slide_marker(i)) } } } /// Returns the slide_marker as [`Markup`]. fn slide_marker(idx: u8) -> Markup { html! { div id = { "slide-marker-"(idx) } class={"slide-marker" @if idx == 0 { (" active-slide-marker") }} {} } } /// Returns the first slide as [`Markup`]. fn my_intro() -> Markup { slide( "Nice to meet you", html! { p { "My name is Ben. I am a developer, but I am also:" } ul { li { "a reader; I love to read. But that can get long, so let's save the details for later." } li { "a writer; " a href="https://www.nanowrimo.org/participants/alterionx/novels" { "NaNoWriMo" } " \ (a.k.a. November) is simultaneously my favorite and most hated month of the year." } li { "a gamer; still waiting for " a href="https://robertsspaceindustries.com/" { "Star Citizen." } } li { "a linguist: I technically know Chinese, and am studying Japanese." } } p {"\ But mostly, I just enjoy watching pretty colors scroll really " span.italic.bold { "really" } " fast down \ my terminal screen while I run my programs and blabber endlessly about my interests.\ "} }, Some("intro active-slide"), ) } /// Returns the second slide as [`Markup`]. fn my_interests() -> Markup { slide( "Everything is fascinating", html! { p {"\ C, C++, and Rust are my favorite languages. I have worked in both OpenGl and Vulkan. \ I've dabbled with Unity, Godot, and Unreal; Amethyst sounds interesting as well. \ However, I also enjoy gaming and reading in my spare time, as well as learning even more about \ tech and interesting projects such as WASM, xi, TypeScript, Fuschia, and AR glasses.\ "} p {"\ As a note, just for fun, this entire website is built with Rust + WASM \ (Such a fun word. Anyways...). I don't know how many browsers it runs on, \ but it was definitely fun. \ "} }, None, ) } /// Returns the third slide as [`Markup`]. fn my_story() -> Markup { slide( "Improve a little, day by day", html! { p {"\ There was a day in 10th grade, when one of my friends introduced me to Java. I was \ enamored the moment I touched the keyboard. The actual program was cute little \ thing, reading and adding two numbers.\ "} p {"\ It blew my mind. "} p {"\ Now that I think about it, it fits; I had been enchanted by the power of words so I wanted to be a novelist,\ but then I found something even more powerful.\ "} p {"\ Either way, I had decided then and there that I knew that I wanted to program for \ a living. And now I'm here, seeking to live a life programming and architecting solutions.\ "} }, None, ) } /// Returns the fourth slide as [`Markup`]. fn my_work() -> Markup { slide( "Learning to code", html! { p {"\ I've picked up a lot of different skills since that day. I developed a custom Wordpress theme and wrote \ a chatlog for my English class. In my last year of high school, I learned about automata theory.\ "} p {"\ When I came to college, I wrote part of an OS in no-std C++ and a Python frontend for connecting to a server and testing. \ I fell in love with writing tools and performance-critical programming.\ "} p {"\ I've written (with a friend) a ray tracer, a fluid simulation, and a shattering simulation. I am in the \ middle of writing a simulation in Rust that combines a majority of these concepts. I ended up devoting \ enough time to it that I will make it my thesis project.\ "} }, None, ) } /// Returns the fifth slide as [`Markup`]. fn my_passion() -> Markup { slide( "Programming and Writing", html! { p {"\ I focus on systems development, rendering, and physical simulation. I think I've already said \ enough about that. But I also have a string interest in game development and story writing.\ "} p {"\ In fact, by virtue of NaNoWriMo, I have the first version of my novel finished!\ "} }, None, ) } /// Returns the sixth slide as [`Markup`]. fn my_reading_time() -> Markup { slide( "Breaktime: Reading!", html! { p {"\ Speaking of wriing, I love to read as well. " a href="https://brandonsanderson.com/" { "Brandon Sanderson" } "'s my favorite author, \ but " a href="https://www.patrickrothfuss.com/content/index.asp" { "Patrick Rothfuss" } " is the most \ inspirational one—still waiting for " span.underline { "The Doors of Stone" } ". (It's alright. We've only waited for a decade-ish.)\ "} p {"\ Rothfuss is the one who inspired me to write, so I aim to take just as long as him to finish my stories. \ But, actually, the subtelty and detailed foreshadowing in his work is mind boggling. As I attempt to do \ the same, I realize this all the more.\ "} }, None, ) } /// Returns the seventh slide as [`Markup`]. fn my_gaming_time() -> Markup { slide( "Breaktime: Gaming!", html! { p {"\ Games are the other half of my free time. Shooters are good as stress relief but my favorites are RPGs. \ My favorites, however, is The Last of Us. It is a work of art. Nier: Automata comes in at a close second; it's only lower \ due to the PC port -- as a developer, its poor performance was obvious.\ "} p {"\ The favorites I'd listed are RPGs, but I find myself more engrossed in Terraria and Stellaris than RPGs since they leave a lot of room to \ establish a character and role play despite not being an RPG. Dungeons and Dragons (DnD) is pretty fun as well.\ "} p {"\ I also enjoy various space sims, but Star Citizen has captured my heart and I don't think I could ever play a different \ space sim without thinking about Star Citizen.\ "} }, None, ) } /// Returns a list of [`Css`](crate::data::Css) scripts that go in my home page. fn css_scripts<'a>() -> [data::Css<'a>; 4] { [ data::Css::Critical { src: "reset" }, data::Css::Critical { src: "typography" }, data::Css::Critical { src: "main" }, data::Css::Critical { src: "index" }, ] } /// Returns the [`Markup`] version of my home page. pub fn index() -> Markup { let (glue, load) = data::Script::wasm_bindgen_loader("wasm_slideshow"); let js_scripts = [ data::Script::External(glue.as_str()), data::Script::Embedded(load.as_str()), ]; let css_scripts = css_scripts(); let menu = menu(); let logo = crate::shared_html::logo_markup(); let meta = data::MetaData::builder() .scripts(&js_scripts[..]) .css(&css_scripts[..]) .menu(menu.as_ref()) .logo(logo.as_ref()) .build(); partials::basic_page( html! { div.profile { h1.tagline { "Ben Xu | Developer" } img.propic src="public/img/propic.jpg" alt="Profile Picture"; (link_group()) (slides()) } }, Some(&meta), ) } }
/// Returns the slide_markers as [`Markup`]. fn slide_markers(slide_cnt: u8) -> Markup { html! {
random_line_split
routes.rs
use rocket::State; use rocket::response::{Flash, Redirect}; use rocket::request::{Form, FormItems, FromForm}; use option_filter::OptionFilterExt; use super::{html, StudentPreferences, TimeSlotRating}; use config; use db::Db; use dict::{self, Locale}; use errors::*; use state::PreparationState; use template::{NavItem, Page}; use user::{AuthUser, Role, User}; use timeslot::Rating; fn
(locale: Locale) -> Vec<NavItem> { // TODO: pass `Dict` once possible let dict = dict::new(locale).prep; vec![ NavItem::new(dict.nav_overview_title(), "/prep"), NavItem::new(dict.nav_timeslots_title(), "/prep/timeslots"), ] } #[get("/prep")] pub fn overview( auth_user: AuthUser, locale: Locale, db: State<Db>, _state: PreparationState, ) -> Result<Page> { let dict = dict::new(locale).prep; match auth_user.role() { // ===== Student ====================================================== Role::Student => { let student = auth_user.into_user().into_student().unwrap(); let pref = StudentPreferences::load_for(&student, &db)?; let partner = pref.partner.as_ref() .map_or(Ok(None), |name| User::load_by_username(name, &db))? .and_then(|u| u.into_student().ok()) .filter(|s| s.id()!= student.id()); Page::empty() .with_title(dict.overview_title()) .add_nav_items(nav_items(locale)) .with_active_nav_route("/prep") .with_content(html::student_overview( locale, &pref, &partner, )) } // ===== Tutor or admin =============================================== Role::Tutor | Role::Admin => { use diesel::prelude::*; use diesel::expression::sql; use db::schema::{timeslot_ratings, users}; let conn = &*db.conn()?; let stats = { let num_students = users::table .filter(sql("role ='student'")) .count() .get_result::<i64>(conn)?; let num_students_with_slots = users::table .inner_join(timeslot_ratings::table) .filter(sql("rating <> 'bad' AND role ='student'")) .select(sql("count(distinct user_id) as count")) .get_result::<i64>(conn)?; let avg_good_rating_per_student = sql(" select cast(avg(count) as float) from ( select count(*) as count, user_id from timeslot_ratings inner join users on users.id = user_id where rating = 'good' and role ='student' group by user_id ) as counts ").get_result::<f64>(conn)?; let avg_ok_rating_per_student = sql(" select cast(avg(count) as float) from ( select count(*) as count, user_id from timeslot_ratings inner join users on users.id = user_id where rating <> 'bad' and role ='student' group by user_id ) as counts ").get_result::<f64>(conn)?; html::TutorAdminStats { num_students: num_students as u64, num_students_with_slots: num_students_with_slots as u64, avg_good_rating_per_student, avg_ok_rating_per_student, } }; let tutors = users::table .inner_join(timeslot_ratings::table) .filter(sql("role = 'tutor'")) .group_by(users::columns::id) .select(sql(" username, name, sum(case when rating='good' then 1 else 0 end) as num_good, sum(case when rating<>'bad' then 1 else 0 end) as num_ok ")) .load::<(String, Option<String>, i64, i64)>(conn)?; let content = html::tutor_admin_overview( locale, auth_user.is_tutor(), stats, &tutors, ); Page::empty() .with_title(dict.overview_title()) .add_nav_items(nav_items(locale)) .with_active_nav_route("/prep") .with_content(content) } }.make_ok() } #[post("/prep_student_settings", data = "<form>")] pub fn set_general_settings( auth_user: AuthUser, form: Form<GeneralStudentSettings>, db: State<Db>, _state: PreparationState, locale: Locale, ) -> Result<Flash<Redirect>> { fn err<S: AsRef<str>>(msg: S) -> Result<Flash<Redirect>> { Ok(Flash::error(Redirect::to("/prep"), msg)) } let dict = dict::new(locale).prep; // The auth_user needs to be a student. Tutors and admins should not be // forwarded to this route. let student = match auth_user.into_user().into_student() { Ok(s) => s, Err(_) => { return err(bad_request(locale)); } }; let mut pref = StudentPreferences::load_for(&student, &db)?; let form = form.into_inner(); // Set partner match form.partner.as_ref() { "random" => { pref.partner = None; } "chosen" => { if let Some(id) = form.partner_id { match User::load_by_username(&id, &db)? { Some(ref u) if u.is_student() => { pref.partner = Some(id); } Some(ref u) => { return Ok(Flash::error( Redirect::to("/prep"), dict.flash_err_partner_not_a_student(u.username()), )); } None => { return Ok(Flash::error( Redirect::to("/prep"), dict.flash_err_user_not_found(), )); } } } else { return err(bad_request(locale)); } } _ => return err(bad_request(locale)), } // Set preferred language match form.language.as_ref() { "de" => pref.prefers_english = false, "en" => pref.prefers_english = true, _ => return err(bad_request(locale)), } // Finally, store the changes in the database. pref.update(&db)?; Ok(Flash::success(Redirect::to("/prep"), dict.flash_success_storing_preferences())) } #[derive(Debug, Clone, FromForm)] pub struct GeneralStudentSettings { partner: String, partner_id: Option<String>, language: String, } #[get("/prep/timeslots")] pub fn timeslots( auth_user: AuthUser, locale: Locale, db: State<Db>, _state: PreparationState, ) -> Result<Page> { let dict = dict::new(locale).prep; // Load all ratings of the user. let ratings = TimeSlotRating::load_all_of_user(&auth_user, &db)?; match auth_user.role() { Role::Student | Role::Tutor => { let (explanation, min_good, min_ok) = match auth_user.role() { Role::Student => ( dict.timeslots_student_explanation(), config::MIN_GOOD_SLOTS_STUDENT, config::MIN_OK_SLOTS_STUDENT, ), Role::Tutor => ( dict.timeslots_tutor_explanation(), config::MIN_GOOD_SLOTS_TUTOR, config::MIN_OK_SLOTS_TUTOR, ), _ => unreachable!(), }; let content = html::timeslots( &explanation, min_good, min_ok, &ratings, locale, ); Page::empty() .with_title(dict.timeslots_title()) .add_nav_items(nav_items(locale)) .with_active_nav_route("/prep/timeslots") .with_content(content) .make_ok() } Role::Admin => { Page::unimplemented().make_ok() } } } /// Stores a list of (timeslot_id, rating). #[derive(Debug)] pub struct TimeSlotForm { slots: Vec<(i16, Rating)>, } impl<'f> FromForm<'f> for TimeSlotForm { type Error = TimeSlotFormError; fn from_form(items: &mut FormItems<'f>, _: bool) -> StdResult<Self, Self::Error> { let slots = items.into_iter().map(|(key, value)| { // The keys come in the form `slot-34` and we want this number. if!key.starts_with("slot-") { return Err(TimeSlotFormError::InvalidId); } let id = match key[5..].parse() { Err(_) => return Err(TimeSlotFormError::InvalidId), Ok(id) => id, }; // The value should only be one of those three values. let rating = match value.as_str() { "good" => Rating::Good, "tolerable" => Rating::Tolerable, "bad" => Rating::Bad, _ => return Err(TimeSlotFormError::InvalidRating), }; Ok((id, rating)) }).collect::<StdResult<Vec<_>, _>>()?; Ok(Self { slots }) } } #[derive(Debug)] pub enum TimeSlotFormError { InvalidRating, InvalidId, } #[post("/prep/update_timeslots", data = "<form>")] fn update_timeslots( auth_user: AuthUser, form: Form<TimeSlotForm>, locale: Locale, db: State<Db>, _state: PreparationState, ) -> Result<Flash<Redirect>> { let form = form.into_inner(); TimeSlotRating::update_all(&auth_user, &form.slots, &db)?; Ok(Flash::success( Redirect::to("/prep/timeslots"), dict::new(locale).prep.flash_success_storing_timeslot_ratings(), )) }
nav_items
identifier_name
routes.rs
use rocket::State; use rocket::response::{Flash, Redirect}; use rocket::request::{Form, FormItems, FromForm}; use option_filter::OptionFilterExt; use super::{html, StudentPreferences, TimeSlotRating}; use config; use db::Db; use dict::{self, Locale}; use errors::*; use state::PreparationState; use template::{NavItem, Page}; use user::{AuthUser, Role, User}; use timeslot::Rating; fn nav_items(locale: Locale) -> Vec<NavItem> { // TODO: pass `Dict` once possible let dict = dict::new(locale).prep; vec![ NavItem::new(dict.nav_overview_title(), "/prep"), NavItem::new(dict.nav_timeslots_title(), "/prep/timeslots"), ] } #[get("/prep")] pub fn overview( auth_user: AuthUser, locale: Locale, db: State<Db>, _state: PreparationState, ) -> Result<Page> { let dict = dict::new(locale).prep; match auth_user.role() { // ===== Student ====================================================== Role::Student => { let student = auth_user.into_user().into_student().unwrap(); let pref = StudentPreferences::load_for(&student, &db)?; let partner = pref.partner.as_ref() .map_or(Ok(None), |name| User::load_by_username(name, &db))? .and_then(|u| u.into_student().ok()) .filter(|s| s.id()!= student.id()); Page::empty() .with_title(dict.overview_title()) .add_nav_items(nav_items(locale)) .with_active_nav_route("/prep") .with_content(html::student_overview( locale, &pref, &partner, )) } // ===== Tutor or admin =============================================== Role::Tutor | Role::Admin => { use diesel::prelude::*; use diesel::expression::sql; use db::schema::{timeslot_ratings, users}; let conn = &*db.conn()?; let stats = { let num_students = users::table .filter(sql("role ='student'")) .count() .get_result::<i64>(conn)?; let num_students_with_slots = users::table .inner_join(timeslot_ratings::table) .filter(sql("rating <> 'bad' AND role ='student'")) .select(sql("count(distinct user_id) as count")) .get_result::<i64>(conn)?; let avg_good_rating_per_student = sql(" select cast(avg(count) as float) from ( select count(*) as count, user_id from timeslot_ratings inner join users on users.id = user_id
").get_result::<f64>(conn)?; let avg_ok_rating_per_student = sql(" select cast(avg(count) as float) from ( select count(*) as count, user_id from timeslot_ratings inner join users on users.id = user_id where rating <> 'bad' and role ='student' group by user_id ) as counts ").get_result::<f64>(conn)?; html::TutorAdminStats { num_students: num_students as u64, num_students_with_slots: num_students_with_slots as u64, avg_good_rating_per_student, avg_ok_rating_per_student, } }; let tutors = users::table .inner_join(timeslot_ratings::table) .filter(sql("role = 'tutor'")) .group_by(users::columns::id) .select(sql(" username, name, sum(case when rating='good' then 1 else 0 end) as num_good, sum(case when rating<>'bad' then 1 else 0 end) as num_ok ")) .load::<(String, Option<String>, i64, i64)>(conn)?; let content = html::tutor_admin_overview( locale, auth_user.is_tutor(), stats, &tutors, ); Page::empty() .with_title(dict.overview_title()) .add_nav_items(nav_items(locale)) .with_active_nav_route("/prep") .with_content(content) } }.make_ok() } #[post("/prep_student_settings", data = "<form>")] pub fn set_general_settings( auth_user: AuthUser, form: Form<GeneralStudentSettings>, db: State<Db>, _state: PreparationState, locale: Locale, ) -> Result<Flash<Redirect>> { fn err<S: AsRef<str>>(msg: S) -> Result<Flash<Redirect>> { Ok(Flash::error(Redirect::to("/prep"), msg)) } let dict = dict::new(locale).prep; // The auth_user needs to be a student. Tutors and admins should not be // forwarded to this route. let student = match auth_user.into_user().into_student() { Ok(s) => s, Err(_) => { return err(bad_request(locale)); } }; let mut pref = StudentPreferences::load_for(&student, &db)?; let form = form.into_inner(); // Set partner match form.partner.as_ref() { "random" => { pref.partner = None; } "chosen" => { if let Some(id) = form.partner_id { match User::load_by_username(&id, &db)? { Some(ref u) if u.is_student() => { pref.partner = Some(id); } Some(ref u) => { return Ok(Flash::error( Redirect::to("/prep"), dict.flash_err_partner_not_a_student(u.username()), )); } None => { return Ok(Flash::error( Redirect::to("/prep"), dict.flash_err_user_not_found(), )); } } } else { return err(bad_request(locale)); } } _ => return err(bad_request(locale)), } // Set preferred language match form.language.as_ref() { "de" => pref.prefers_english = false, "en" => pref.prefers_english = true, _ => return err(bad_request(locale)), } // Finally, store the changes in the database. pref.update(&db)?; Ok(Flash::success(Redirect::to("/prep"), dict.flash_success_storing_preferences())) } #[derive(Debug, Clone, FromForm)] pub struct GeneralStudentSettings { partner: String, partner_id: Option<String>, language: String, } #[get("/prep/timeslots")] pub fn timeslots( auth_user: AuthUser, locale: Locale, db: State<Db>, _state: PreparationState, ) -> Result<Page> { let dict = dict::new(locale).prep; // Load all ratings of the user. let ratings = TimeSlotRating::load_all_of_user(&auth_user, &db)?; match auth_user.role() { Role::Student | Role::Tutor => { let (explanation, min_good, min_ok) = match auth_user.role() { Role::Student => ( dict.timeslots_student_explanation(), config::MIN_GOOD_SLOTS_STUDENT, config::MIN_OK_SLOTS_STUDENT, ), Role::Tutor => ( dict.timeslots_tutor_explanation(), config::MIN_GOOD_SLOTS_TUTOR, config::MIN_OK_SLOTS_TUTOR, ), _ => unreachable!(), }; let content = html::timeslots( &explanation, min_good, min_ok, &ratings, locale, ); Page::empty() .with_title(dict.timeslots_title()) .add_nav_items(nav_items(locale)) .with_active_nav_route("/prep/timeslots") .with_content(content) .make_ok() } Role::Admin => { Page::unimplemented().make_ok() } } } /// Stores a list of (timeslot_id, rating). #[derive(Debug)] pub struct TimeSlotForm { slots: Vec<(i16, Rating)>, } impl<'f> FromForm<'f> for TimeSlotForm { type Error = TimeSlotFormError; fn from_form(items: &mut FormItems<'f>, _: bool) -> StdResult<Self, Self::Error> { let slots = items.into_iter().map(|(key, value)| { // The keys come in the form `slot-34` and we want this number. if!key.starts_with("slot-") { return Err(TimeSlotFormError::InvalidId); } let id = match key[5..].parse() { Err(_) => return Err(TimeSlotFormError::InvalidId), Ok(id) => id, }; // The value should only be one of those three values. let rating = match value.as_str() { "good" => Rating::Good, "tolerable" => Rating::Tolerable, "bad" => Rating::Bad, _ => return Err(TimeSlotFormError::InvalidRating), }; Ok((id, rating)) }).collect::<StdResult<Vec<_>, _>>()?; Ok(Self { slots }) } } #[derive(Debug)] pub enum TimeSlotFormError { InvalidRating, InvalidId, } #[post("/prep/update_timeslots", data = "<form>")] fn update_timeslots( auth_user: AuthUser, form: Form<TimeSlotForm>, locale: Locale, db: State<Db>, _state: PreparationState, ) -> Result<Flash<Redirect>> { let form = form.into_inner(); TimeSlotRating::update_all(&auth_user, &form.slots, &db)?; Ok(Flash::success( Redirect::to("/prep/timeslots"), dict::new(locale).prep.flash_success_storing_timeslot_ratings(), )) }
where rating = 'good' and role = 'student' group by user_id ) as counts
random_line_split
ui.rs
//! Implements how the user interfaces with the application. pub(crate) use crate::num::{Length, NonNegativeI32}; use crate::{fmt, Debug, Display, Formatter, Mrc, TryFrom, TryFromIntError}; use pancurses::Input; use std::cell::RefCell; use std::error; use std::rc::Rc; /// The [`Result`] returned by functions of this module. pub type Outcome = Result<(), Error>; /// The type specified by all grid index values /// /// Specified by [`pancurses`]. pub(crate) type IndexType = i32; /// The type of all grid index values. pub type Index = NonNegativeI32; /// The character that represents the `Backspace` key. pub const BACKSPACE: char = '\u{08}'; /// The character that represents the `Enter` key. pub(crate) const ENTER: char = '\n'; // Currently ESC is set to Ctrl-C to allow manual testing within vim terminal where ESC is already // mapped. /// The character that represents the `Esc` key. pub const ESC: char = ''; /// Represents the default color. const DEFAULT_COLOR: i16 = -1; /// Describes possible errors during ui functions. #[derive(Clone, Copy, Debug)] pub enum Error { /// Describes an error due to no user interface being created. NoUi, /// Describes a possible error during call to `endwin()`. Endwin, /// Describes a possible error during call to `flash()`. Flash, /// Describes a possible error during call to `init_pair()`. InitPair, /// Describes a possible error during call to `noecho()`. Noecho, /// Describes a possible error during call to `start_color()`. StartColor, /// Describes a possible error during call to `use_default_colors()`. UseDefaultColors, /// Describes a possible error during call to `waddch()`. Waddch, /// Describes a possible error during call to `waddstr()`. Waddstr, /// Describes a possible error during call to `wchgat()`. Wchgat, /// Describes a possible error during call to `wclear()`. Wclear, /// Describes a possible error during call to `wcleartoeol()`. Wcleartoeol, /// Describes a possible error during call to `wdelch()`. Wdelch, /// Describes a possible error during call to `winsch()`. Winsch, /// Describes a possible error during call to `wmove()`. Wmove, /// Describes a possible error during call to `nodelay()`. Nodelay, } impl Error { /// Returns the function that caused the current `Error`. fn get_function(&self) -> &str { match self { Error::Endwin => "endwin", Error::Flash => "flash", Error::InitPair => "init_pair", Error::Noecho => "noecho", Error::StartColor => "start_color", Error::UseDefaultColors => "use_default_colors", Error::Waddch => "waddch", Error::Waddstr => "waddstr", Error::Wchgat => "wchgat", Error::Wclear => "wclear", Error::Wcleartoeol => "wcleartoeol", Error::Wdelch => "wdelch", Error::Winsch => "winsch", Error::Wmove => "wmove", Error::Nodelay => "nodelay", Error::NoUi => "", } } } impl Display for Error { #[inline] fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { match self { Error::NoUi => write!(f, "No UserInterface was created."), _ => write!(f, "Failed while calling {}().", self.get_function()), } } } impl error::Error for Error {} /// Signifies a specific cell in the grid. #[derive(Clone, Copy, Eq, Debug, Default, Hash, Ord, PartialEq, PartialOrd)] pub struct Address { /// The index of the row that contains the cell (starts at 0). row: Index, /// The index of the column that contains the cell (starts at 0). column: Index, } impl Address { /// Creates a new `Address` with a given row and column. #[inline] pub fn new(row: Index, column: Index) -> Self { Self { row, column } } /// Returns the column of `self`. /// /// Used with [`pancurses`]. /// /// [`pancurses`]:../../pancurses/index.html fn x(self) -> IndexType { IndexType::from(self.column) } /// Returns the row of `self`. /// /// Used with [`pancurses`]. /// /// [`pancurses`]:../../pancurses/index.html fn y(self) -> IndexType { IndexType::from(self.row) } } impl Display for Address { #[inline] fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { write!(f, "({}, {})", self.row, self.column) } } /// Signifies a modification to the grid. #[derive(Clone, Debug, Eq, Hash, PartialEq)] pub enum Change { /// Removes the previous cell, moving all subsequent cells to the left. Backspace, /// Clears all cells. Clear, /// Sets the color of a given number of cells. Format(Length, Color), /// Inserts a cell containing a character, moving all subsequent cells to the right. Insert(char), /// Does nothing. Nothing, /// Writes the characters of a string in sequence and clears all subsequent cells. Row(String), /// Flashes the display. Flash, } impl Default for Change { #[inline] fn default() -> Self { Change::Nothing } } impl Display for Change {
Change::Clear => write!(f, "Clear"), Change::Format(n, color) => write!(f, "Format {} cells to {}", n, color), Change::Insert(input) => write!(f, "Insert '{}'", input), Change::Nothing => write!(f, "Nothing"), Change::Row(row_str) => write!(f, "Write row '{}'", row_str), Change::Flash => write!(f, "Flash"), } } } /// Signifies a color. // Order must be kept as defined to match pancurses. #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub enum Color { /// The default foreground on the default background. Default, /// The default foreground on a red background. Red, /// The default foreground on a green background. Green, /// The default foreground on a yellow background. Yellow, /// The default foreground on a blue background. Blue, } impl Color { /// Converts `self` to a `color-pair` as specified in [`pancurses`]. fn cp(self) -> i16 { self as i16 } } impl Display for Color { #[inline] fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { match self { Color::Default => write!(f, "Default"), Color::Red => write!(f, "Red"), Color::Green => write!(f, "Green"), Color::Yellow => write!(f, "Yellow"), Color::Blue => write!(f, "Blue"), } } } /// Signifies a [`Change`] to make to an [`Address`]. /// /// [`Change`]: enum.Change.html /// [`Address`]: struct.Address.html #[derive(Clone, Debug, Default, Eq, Hash, PartialEq)] pub struct Edit { /// The [`Change`] to be made. change: Change, /// The [`Address`] on which the [`Change`] is intended. address: Option<Address>, } impl Edit { /// Creates a new `Edit`. #[inline] pub fn new(address: Option<Address>, change: Change) -> Self { Self { address, change } } } /// The interface between the user and the application. /// /// All output is displayed in a grid of cells. Each cell contains one character and can change its /// background color. pub trait UserInterface: Debug { /// Sets up the user interface for use. fn init(&self) -> Outcome; /// Closes the user interface. fn close(&self) -> Outcome; /// Returns the number of cells that make up the height of the grid. fn grid_height(&self) -> Result<Index, TryFromIntError>; /// Applies the edit to the output. fn apply(&self, edit: Edit) -> Outcome; /// Flashes the output. fn flash(&self) -> Outcome; /// Returns the input from the user. /// /// Returns [`None`] if no character input is provided. fn receive_input(&self) -> Option<Input>; } /// The user interface provided by a terminal. #[derive(Debug)] pub struct Terminal { /// The window that interfaces with the application. window: pancurses::Window, } impl Terminal { /// Creates a new `Terminal`. #[inline] pub fn new() -> Mrc<Self> { Rc::new(RefCell::new(Self { // Must call initscr() first. window: pancurses::initscr(), })) } /// Converts given result of ui function to a [`Outcome`]. fn process(result: i32, error: Error) -> Outcome { if result == pancurses::OK { Ok(()) } else { Err(error) } } /// Overwrites the block at cursor with a character. fn add_char(&self, c: char) -> Outcome { Self::process(self.window.addch(c), Error::Waddch) } /// Writes a string starting at the cursor. fn add_str(&self, s: String) -> Outcome { Self::process(self.window.addstr(s), Error::Waddstr) } /// Clears the entire window. fn clear_all(&self) -> Outcome { Self::process(self.window.clear(), Error::Wclear) } /// Clears all blocks from the cursor to the end of the row. fn clear_to_row_end(&self) -> Outcome { Self::process(self.window.clrtoeol(), Error::Wcleartoeol) } /// Defines [`Color`] as having a background color. fn define_color(&self, color: Color, background: i16) -> Outcome { Self::process( pancurses::init_pair(color.cp(), DEFAULT_COLOR, background), Error::InitPair, ) } /// Deletes the character at the cursor. /// /// All subseqent characters are shifted to the left and a blank block is added at the end. fn delete_char(&self) -> Outcome { Self::process(self.window.delch(), Error::Wdelch) } /// Disables echoing received characters on the screen. fn disable_echo(&self) -> Outcome { Self::process(pancurses::noecho(), Error::Noecho) } /// Sets user interface to not wait for an input. fn enable_nodelay(&self) -> Outcome { Self::process(self.window.nodelay(true), Error::Nodelay) } /// Sets the color of the next specified number of blocks from the cursor. fn format(&self, length: Length, color: Color) -> Outcome { Self::process( self.window .chgat(i32::from(length), pancurses::A_NORMAL, color.cp()), Error::Wchgat, ) } /// Inserts a character at the cursor, shifting all subsequent blocks to the right. fn insert_char(&self, c: char) -> Outcome { Self::process(self.window.insch(c), Error::Winsch) } /// Moves the cursor to an [`Address`]. fn move_to(&self, address: Address) -> Outcome { Self::process(self.window.mv(address.y(), address.x()), Error::Wmove) } /// Initializes color processing. /// /// Must be called before any other color manipulation routine is called. fn start_color(&self) -> Outcome { Self::process(pancurses::start_color(), Error::StartColor) } /// Initializes the default colors. fn use_default_colors(&self) -> Outcome { Self::process(pancurses::use_default_colors(), Error::UseDefaultColors) } } impl UserInterface for Terminal { #[inline] fn init(&self) -> Outcome { self.start_color()?; self.use_default_colors()?; self.disable_echo()?; self.enable_nodelay()?; self.define_color(Color::Red, pancurses::COLOR_RED)?; self.define_color(Color::Blue, pancurses::COLOR_BLUE)?; Ok(()) } #[inline] fn close(&self) -> Outcome { Self::process(pancurses::endwin(), Error::Endwin) } #[inline] fn flash(&self) -> Outcome { Self::process(pancurses::flash(), Error::Flash) } #[inline] fn apply(&self, edit: Edit) -> Outcome { if let Some(address) = edit.address { self.move_to(address)?; } match edit.change { Change::Backspace => { // Add BACKSPACE (move cursor 1 cell to the left) and delete that character. self.add_char(BACKSPACE)?; self.delete_char() } Change::Clear => self.clear_all(), Change::Format(n, color) => self.format(n, color), Change::Insert(c) => self.insert_char(c), Change::Nothing => Ok(()), Change::Row(s) => { self.add_str(s)?; self.clear_to_row_end() } Change::Flash => self.flash(), } } // TODO: Store this value and update when size is changed. #[inline] fn grid_height(&self) -> Result<Index, TryFromIntError> { Index::try_from(self.window.get_max_y()) } #[inline] fn receive_input(&self) -> Option<Input> { self.window.getch() } }
#[inline] fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { match self { Change::Backspace => write!(f, "Backspace"),
random_line_split
ui.rs
//! Implements how the user interfaces with the application. pub(crate) use crate::num::{Length, NonNegativeI32}; use crate::{fmt, Debug, Display, Formatter, Mrc, TryFrom, TryFromIntError}; use pancurses::Input; use std::cell::RefCell; use std::error; use std::rc::Rc; /// The [`Result`] returned by functions of this module. pub type Outcome = Result<(), Error>; /// The type specified by all grid index values /// /// Specified by [`pancurses`]. pub(crate) type IndexType = i32; /// The type of all grid index values. pub type Index = NonNegativeI32; /// The character that represents the `Backspace` key. pub const BACKSPACE: char = '\u{08}'; /// The character that represents the `Enter` key. pub(crate) const ENTER: char = '\n'; // Currently ESC is set to Ctrl-C to allow manual testing within vim terminal where ESC is already // mapped. /// The character that represents the `Esc` key. pub const ESC: char = ''; /// Represents the default color. const DEFAULT_COLOR: i16 = -1; /// Describes possible errors during ui functions. #[derive(Clone, Copy, Debug)] pub enum Error { /// Describes an error due to no user interface being created. NoUi, /// Describes a possible error during call to `endwin()`. Endwin, /// Describes a possible error during call to `flash()`. Flash, /// Describes a possible error during call to `init_pair()`. InitPair, /// Describes a possible error during call to `noecho()`. Noecho, /// Describes a possible error during call to `start_color()`. StartColor, /// Describes a possible error during call to `use_default_colors()`. UseDefaultColors, /// Describes a possible error during call to `waddch()`. Waddch, /// Describes a possible error during call to `waddstr()`. Waddstr, /// Describes a possible error during call to `wchgat()`. Wchgat, /// Describes a possible error during call to `wclear()`. Wclear, /// Describes a possible error during call to `wcleartoeol()`. Wcleartoeol, /// Describes a possible error during call to `wdelch()`. Wdelch, /// Describes a possible error during call to `winsch()`. Winsch, /// Describes a possible error during call to `wmove()`. Wmove, /// Describes a possible error during call to `nodelay()`. Nodelay, } impl Error { /// Returns the function that caused the current `Error`. fn get_function(&self) -> &str { match self { Error::Endwin => "endwin", Error::Flash => "flash", Error::InitPair => "init_pair", Error::Noecho => "noecho", Error::StartColor => "start_color", Error::UseDefaultColors => "use_default_colors", Error::Waddch => "waddch", Error::Waddstr => "waddstr", Error::Wchgat => "wchgat", Error::Wclear => "wclear", Error::Wcleartoeol => "wcleartoeol", Error::Wdelch => "wdelch", Error::Winsch => "winsch", Error::Wmove => "wmove", Error::Nodelay => "nodelay", Error::NoUi => "", } } } impl Display for Error { #[inline] fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { match self { Error::NoUi => write!(f, "No UserInterface was created."), _ => write!(f, "Failed while calling {}().", self.get_function()), } } } impl error::Error for Error {} /// Signifies a specific cell in the grid. #[derive(Clone, Copy, Eq, Debug, Default, Hash, Ord, PartialEq, PartialOrd)] pub struct Address { /// The index of the row that contains the cell (starts at 0). row: Index, /// The index of the column that contains the cell (starts at 0). column: Index, } impl Address { /// Creates a new `Address` with a given row and column. #[inline] pub fn new(row: Index, column: Index) -> Self { Self { row, column } } /// Returns the column of `self`. /// /// Used with [`pancurses`]. /// /// [`pancurses`]:../../pancurses/index.html fn x(self) -> IndexType { IndexType::from(self.column) } /// Returns the row of `self`. /// /// Used with [`pancurses`]. /// /// [`pancurses`]:../../pancurses/index.html fn y(self) -> IndexType { IndexType::from(self.row) } } impl Display for Address { #[inline] fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { write!(f, "({}, {})", self.row, self.column) } } /// Signifies a modification to the grid. #[derive(Clone, Debug, Eq, Hash, PartialEq)] pub enum Change { /// Removes the previous cell, moving all subsequent cells to the left. Backspace, /// Clears all cells. Clear, /// Sets the color of a given number of cells. Format(Length, Color), /// Inserts a cell containing a character, moving all subsequent cells to the right. Insert(char), /// Does nothing. Nothing, /// Writes the characters of a string in sequence and clears all subsequent cells. Row(String), /// Flashes the display. Flash, } impl Default for Change { #[inline] fn default() -> Self { Change::Nothing } } impl Display for Change { #[inline] fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { match self { Change::Backspace => write!(f, "Backspace"), Change::Clear => write!(f, "Clear"), Change::Format(n, color) => write!(f, "Format {} cells to {}", n, color), Change::Insert(input) => write!(f, "Insert '{}'", input), Change::Nothing => write!(f, "Nothing"), Change::Row(row_str) => write!(f, "Write row '{}'", row_str), Change::Flash => write!(f, "Flash"), } } } /// Signifies a color. // Order must be kept as defined to match pancurses. #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub enum Color { /// The default foreground on the default background. Default, /// The default foreground on a red background. Red, /// The default foreground on a green background. Green, /// The default foreground on a yellow background. Yellow, /// The default foreground on a blue background. Blue, } impl Color { /// Converts `self` to a `color-pair` as specified in [`pancurses`]. fn cp(self) -> i16 { self as i16 } } impl Display for Color { #[inline] fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result
} /// Signifies a [`Change`] to make to an [`Address`]. /// /// [`Change`]: enum.Change.html /// [`Address`]: struct.Address.html #[derive(Clone, Debug, Default, Eq, Hash, PartialEq)] pub struct Edit { /// The [`Change`] to be made. change: Change, /// The [`Address`] on which the [`Change`] is intended. address: Option<Address>, } impl Edit { /// Creates a new `Edit`. #[inline] pub fn new(address: Option<Address>, change: Change) -> Self { Self { address, change } } } /// The interface between the user and the application. /// /// All output is displayed in a grid of cells. Each cell contains one character and can change its /// background color. pub trait UserInterface: Debug { /// Sets up the user interface for use. fn init(&self) -> Outcome; /// Closes the user interface. fn close(&self) -> Outcome; /// Returns the number of cells that make up the height of the grid. fn grid_height(&self) -> Result<Index, TryFromIntError>; /// Applies the edit to the output. fn apply(&self, edit: Edit) -> Outcome; /// Flashes the output. fn flash(&self) -> Outcome; /// Returns the input from the user. /// /// Returns [`None`] if no character input is provided. fn receive_input(&self) -> Option<Input>; } /// The user interface provided by a terminal. #[derive(Debug)] pub struct Terminal { /// The window that interfaces with the application. window: pancurses::Window, } impl Terminal { /// Creates a new `Terminal`. #[inline] pub fn new() -> Mrc<Self> { Rc::new(RefCell::new(Self { // Must call initscr() first. window: pancurses::initscr(), })) } /// Converts given result of ui function to a [`Outcome`]. fn process(result: i32, error: Error) -> Outcome { if result == pancurses::OK { Ok(()) } else { Err(error) } } /// Overwrites the block at cursor with a character. fn add_char(&self, c: char) -> Outcome { Self::process(self.window.addch(c), Error::Waddch) } /// Writes a string starting at the cursor. fn add_str(&self, s: String) -> Outcome { Self::process(self.window.addstr(s), Error::Waddstr) } /// Clears the entire window. fn clear_all(&self) -> Outcome { Self::process(self.window.clear(), Error::Wclear) } /// Clears all blocks from the cursor to the end of the row. fn clear_to_row_end(&self) -> Outcome { Self::process(self.window.clrtoeol(), Error::Wcleartoeol) } /// Defines [`Color`] as having a background color. fn define_color(&self, color: Color, background: i16) -> Outcome { Self::process( pancurses::init_pair(color.cp(), DEFAULT_COLOR, background), Error::InitPair, ) } /// Deletes the character at the cursor. /// /// All subseqent characters are shifted to the left and a blank block is added at the end. fn delete_char(&self) -> Outcome { Self::process(self.window.delch(), Error::Wdelch) } /// Disables echoing received characters on the screen. fn disable_echo(&self) -> Outcome { Self::process(pancurses::noecho(), Error::Noecho) } /// Sets user interface to not wait for an input. fn enable_nodelay(&self) -> Outcome { Self::process(self.window.nodelay(true), Error::Nodelay) } /// Sets the color of the next specified number of blocks from the cursor. fn format(&self, length: Length, color: Color) -> Outcome { Self::process( self.window .chgat(i32::from(length), pancurses::A_NORMAL, color.cp()), Error::Wchgat, ) } /// Inserts a character at the cursor, shifting all subsequent blocks to the right. fn insert_char(&self, c: char) -> Outcome { Self::process(self.window.insch(c), Error::Winsch) } /// Moves the cursor to an [`Address`]. fn move_to(&self, address: Address) -> Outcome { Self::process(self.window.mv(address.y(), address.x()), Error::Wmove) } /// Initializes color processing. /// /// Must be called before any other color manipulation routine is called. fn start_color(&self) -> Outcome { Self::process(pancurses::start_color(), Error::StartColor) } /// Initializes the default colors. fn use_default_colors(&self) -> Outcome { Self::process(pancurses::use_default_colors(), Error::UseDefaultColors) } } impl UserInterface for Terminal { #[inline] fn init(&self) -> Outcome { self.start_color()?; self.use_default_colors()?; self.disable_echo()?; self.enable_nodelay()?; self.define_color(Color::Red, pancurses::COLOR_RED)?; self.define_color(Color::Blue, pancurses::COLOR_BLUE)?; Ok(()) } #[inline] fn close(&self) -> Outcome { Self::process(pancurses::endwin(), Error::Endwin) } #[inline] fn flash(&self) -> Outcome { Self::process(pancurses::flash(), Error::Flash) } #[inline] fn apply(&self, edit: Edit) -> Outcome { if let Some(address) = edit.address { self.move_to(address)?; } match edit.change { Change::Backspace => { // Add BACKSPACE (move cursor 1 cell to the left) and delete that character. self.add_char(BACKSPACE)?; self.delete_char() } Change::Clear => self.clear_all(), Change::Format(n, color) => self.format(n, color), Change::Insert(c) => self.insert_char(c), Change::Nothing => Ok(()), Change::Row(s) => { self.add_str(s)?; self.clear_to_row_end() } Change::Flash => self.flash(), } } // TODO: Store this value and update when size is changed. #[inline] fn grid_height(&self) -> Result<Index, TryFromIntError> { Index::try_from(self.window.get_max_y()) } #[inline] fn receive_input(&self) -> Option<Input> { self.window.getch() } }
{ match self { Color::Default => write!(f, "Default"), Color::Red => write!(f, "Red"), Color::Green => write!(f, "Green"), Color::Yellow => write!(f, "Yellow"), Color::Blue => write!(f, "Blue"), } }
identifier_body
ui.rs
//! Implements how the user interfaces with the application. pub(crate) use crate::num::{Length, NonNegativeI32}; use crate::{fmt, Debug, Display, Formatter, Mrc, TryFrom, TryFromIntError}; use pancurses::Input; use std::cell::RefCell; use std::error; use std::rc::Rc; /// The [`Result`] returned by functions of this module. pub type Outcome = Result<(), Error>; /// The type specified by all grid index values /// /// Specified by [`pancurses`]. pub(crate) type IndexType = i32; /// The type of all grid index values. pub type Index = NonNegativeI32; /// The character that represents the `Backspace` key. pub const BACKSPACE: char = '\u{08}'; /// The character that represents the `Enter` key. pub(crate) const ENTER: char = '\n'; // Currently ESC is set to Ctrl-C to allow manual testing within vim terminal where ESC is already // mapped. /// The character that represents the `Esc` key. pub const ESC: char = ''; /// Represents the default color. const DEFAULT_COLOR: i16 = -1; /// Describes possible errors during ui functions. #[derive(Clone, Copy, Debug)] pub enum Error { /// Describes an error due to no user interface being created. NoUi, /// Describes a possible error during call to `endwin()`. Endwin, /// Describes a possible error during call to `flash()`. Flash, /// Describes a possible error during call to `init_pair()`. InitPair, /// Describes a possible error during call to `noecho()`. Noecho, /// Describes a possible error during call to `start_color()`. StartColor, /// Describes a possible error during call to `use_default_colors()`. UseDefaultColors, /// Describes a possible error during call to `waddch()`. Waddch, /// Describes a possible error during call to `waddstr()`. Waddstr, /// Describes a possible error during call to `wchgat()`. Wchgat, /// Describes a possible error during call to `wclear()`. Wclear, /// Describes a possible error during call to `wcleartoeol()`. Wcleartoeol, /// Describes a possible error during call to `wdelch()`. Wdelch, /// Describes a possible error during call to `winsch()`. Winsch, /// Describes a possible error during call to `wmove()`. Wmove, /// Describes a possible error during call to `nodelay()`. Nodelay, } impl Error { /// Returns the function that caused the current `Error`. fn get_function(&self) -> &str { match self { Error::Endwin => "endwin", Error::Flash => "flash", Error::InitPair => "init_pair", Error::Noecho => "noecho", Error::StartColor => "start_color", Error::UseDefaultColors => "use_default_colors", Error::Waddch => "waddch", Error::Waddstr => "waddstr", Error::Wchgat => "wchgat", Error::Wclear => "wclear", Error::Wcleartoeol => "wcleartoeol", Error::Wdelch => "wdelch", Error::Winsch => "winsch", Error::Wmove => "wmove", Error::Nodelay => "nodelay", Error::NoUi => "", } } } impl Display for Error { #[inline] fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { match self { Error::NoUi => write!(f, "No UserInterface was created."), _ => write!(f, "Failed while calling {}().", self.get_function()), } } } impl error::Error for Error {} /// Signifies a specific cell in the grid. #[derive(Clone, Copy, Eq, Debug, Default, Hash, Ord, PartialEq, PartialOrd)] pub struct Address { /// The index of the row that contains the cell (starts at 0). row: Index, /// The index of the column that contains the cell (starts at 0). column: Index, } impl Address { /// Creates a new `Address` with a given row and column. #[inline] pub fn new(row: Index, column: Index) -> Self { Self { row, column } } /// Returns the column of `self`. /// /// Used with [`pancurses`]. /// /// [`pancurses`]:../../pancurses/index.html fn x(self) -> IndexType { IndexType::from(self.column) } /// Returns the row of `self`. /// /// Used with [`pancurses`]. /// /// [`pancurses`]:../../pancurses/index.html fn y(self) -> IndexType { IndexType::from(self.row) } } impl Display for Address { #[inline] fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { write!(f, "({}, {})", self.row, self.column) } } /// Signifies a modification to the grid. #[derive(Clone, Debug, Eq, Hash, PartialEq)] pub enum Change { /// Removes the previous cell, moving all subsequent cells to the left. Backspace, /// Clears all cells. Clear, /// Sets the color of a given number of cells. Format(Length, Color), /// Inserts a cell containing a character, moving all subsequent cells to the right. Insert(char), /// Does nothing. Nothing, /// Writes the characters of a string in sequence and clears all subsequent cells. Row(String), /// Flashes the display. Flash, } impl Default for Change { #[inline] fn default() -> Self { Change::Nothing } } impl Display for Change { #[inline] fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { match self { Change::Backspace => write!(f, "Backspace"), Change::Clear => write!(f, "Clear"), Change::Format(n, color) => write!(f, "Format {} cells to {}", n, color), Change::Insert(input) => write!(f, "Insert '{}'", input), Change::Nothing => write!(f, "Nothing"), Change::Row(row_str) => write!(f, "Write row '{}'", row_str), Change::Flash => write!(f, "Flash"), } } } /// Signifies a color. // Order must be kept as defined to match pancurses. #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub enum Color { /// The default foreground on the default background. Default, /// The default foreground on a red background. Red, /// The default foreground on a green background. Green, /// The default foreground on a yellow background. Yellow, /// The default foreground on a blue background. Blue, } impl Color { /// Converts `self` to a `color-pair` as specified in [`pancurses`]. fn cp(self) -> i16 { self as i16 } } impl Display for Color { #[inline] fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { match self { Color::Default => write!(f, "Default"), Color::Red => write!(f, "Red"), Color::Green => write!(f, "Green"), Color::Yellow => write!(f, "Yellow"), Color::Blue => write!(f, "Blue"), } } } /// Signifies a [`Change`] to make to an [`Address`]. /// /// [`Change`]: enum.Change.html /// [`Address`]: struct.Address.html #[derive(Clone, Debug, Default, Eq, Hash, PartialEq)] pub struct Edit { /// The [`Change`] to be made. change: Change, /// The [`Address`] on which the [`Change`] is intended. address: Option<Address>, } impl Edit { /// Creates a new `Edit`. #[inline] pub fn new(address: Option<Address>, change: Change) -> Self { Self { address, change } } } /// The interface between the user and the application. /// /// All output is displayed in a grid of cells. Each cell contains one character and can change its /// background color. pub trait UserInterface: Debug { /// Sets up the user interface for use. fn init(&self) -> Outcome; /// Closes the user interface. fn close(&self) -> Outcome; /// Returns the number of cells that make up the height of the grid. fn grid_height(&self) -> Result<Index, TryFromIntError>; /// Applies the edit to the output. fn apply(&self, edit: Edit) -> Outcome; /// Flashes the output. fn flash(&self) -> Outcome; /// Returns the input from the user. /// /// Returns [`None`] if no character input is provided. fn receive_input(&self) -> Option<Input>; } /// The user interface provided by a terminal. #[derive(Debug)] pub struct Terminal { /// The window that interfaces with the application. window: pancurses::Window, } impl Terminal { /// Creates a new `Terminal`. #[inline] pub fn new() -> Mrc<Self> { Rc::new(RefCell::new(Self { // Must call initscr() first. window: pancurses::initscr(), })) } /// Converts given result of ui function to a [`Outcome`]. fn process(result: i32, error: Error) -> Outcome { if result == pancurses::OK { Ok(()) } else { Err(error) } } /// Overwrites the block at cursor with a character. fn add_char(&self, c: char) -> Outcome { Self::process(self.window.addch(c), Error::Waddch) } /// Writes a string starting at the cursor. fn add_str(&self, s: String) -> Outcome { Self::process(self.window.addstr(s), Error::Waddstr) } /// Clears the entire window. fn clear_all(&self) -> Outcome { Self::process(self.window.clear(), Error::Wclear) } /// Clears all blocks from the cursor to the end of the row. fn clear_to_row_end(&self) -> Outcome { Self::process(self.window.clrtoeol(), Error::Wcleartoeol) } /// Defines [`Color`] as having a background color. fn define_color(&self, color: Color, background: i16) -> Outcome { Self::process( pancurses::init_pair(color.cp(), DEFAULT_COLOR, background), Error::InitPair, ) } /// Deletes the character at the cursor. /// /// All subseqent characters are shifted to the left and a blank block is added at the end. fn
(&self) -> Outcome { Self::process(self.window.delch(), Error::Wdelch) } /// Disables echoing received characters on the screen. fn disable_echo(&self) -> Outcome { Self::process(pancurses::noecho(), Error::Noecho) } /// Sets user interface to not wait for an input. fn enable_nodelay(&self) -> Outcome { Self::process(self.window.nodelay(true), Error::Nodelay) } /// Sets the color of the next specified number of blocks from the cursor. fn format(&self, length: Length, color: Color) -> Outcome { Self::process( self.window .chgat(i32::from(length), pancurses::A_NORMAL, color.cp()), Error::Wchgat, ) } /// Inserts a character at the cursor, shifting all subsequent blocks to the right. fn insert_char(&self, c: char) -> Outcome { Self::process(self.window.insch(c), Error::Winsch) } /// Moves the cursor to an [`Address`]. fn move_to(&self, address: Address) -> Outcome { Self::process(self.window.mv(address.y(), address.x()), Error::Wmove) } /// Initializes color processing. /// /// Must be called before any other color manipulation routine is called. fn start_color(&self) -> Outcome { Self::process(pancurses::start_color(), Error::StartColor) } /// Initializes the default colors. fn use_default_colors(&self) -> Outcome { Self::process(pancurses::use_default_colors(), Error::UseDefaultColors) } } impl UserInterface for Terminal { #[inline] fn init(&self) -> Outcome { self.start_color()?; self.use_default_colors()?; self.disable_echo()?; self.enable_nodelay()?; self.define_color(Color::Red, pancurses::COLOR_RED)?; self.define_color(Color::Blue, pancurses::COLOR_BLUE)?; Ok(()) } #[inline] fn close(&self) -> Outcome { Self::process(pancurses::endwin(), Error::Endwin) } #[inline] fn flash(&self) -> Outcome { Self::process(pancurses::flash(), Error::Flash) } #[inline] fn apply(&self, edit: Edit) -> Outcome { if let Some(address) = edit.address { self.move_to(address)?; } match edit.change { Change::Backspace => { // Add BACKSPACE (move cursor 1 cell to the left) and delete that character. self.add_char(BACKSPACE)?; self.delete_char() } Change::Clear => self.clear_all(), Change::Format(n, color) => self.format(n, color), Change::Insert(c) => self.insert_char(c), Change::Nothing => Ok(()), Change::Row(s) => { self.add_str(s)?; self.clear_to_row_end() } Change::Flash => self.flash(), } } // TODO: Store this value and update when size is changed. #[inline] fn grid_height(&self) -> Result<Index, TryFromIntError> { Index::try_from(self.window.get_max_y()) } #[inline] fn receive_input(&self) -> Option<Input> { self.window.getch() } }
delete_char
identifier_name
response.rs
use hyper::header::{self, CookiePair as Cookie, ContentType, Header, SetCookie}; use hyper::status::StatusCode as Status; use hyper::Headers; use hyper::mime::{Mime, TopLevel, SubLevel, Attr, Value}; use serde_json::value as json; use serde_json::value::ToJson; use std::any::Any; use std::boxed::Box; use std::borrow::Cow; use std::{error, fmt, result}; use std::fs::File; use std::io::{self, ErrorKind, Read, Write}; use std::path::Path; /// Defines a handler error #[derive(Debug)] pub struct Error { pub status: Status, pub message: Option<Cow<'static, str>> } pub type Result = result::Result<Action, Error>; impl Error { fn new(status: Status, message: Option<Cow<'static, str>>) -> Error { Error { status: status, message: message } } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { use std::error::Error; self.description().fmt(f) } } impl error::Error for Error { fn description(&self) -> &str { match self.message { None => "<no description available>", Some(ref message) => &message } } fn
(&self) -> Option<&error::Error> { None } } impl From<Status> for Error { fn from(status: Status) -> Error { Error::new(status, None) } } impl From<(Status, &'static str)> for Error { fn from(pair: (Status, &'static str)) -> Error { Error::new(pair.0, Some(Cow::Borrowed(pair.1))) } } impl From<(Status, String)> for Error { fn from(pair: (Status, String)) -> Error { Error::new(pair.0, Some(Cow::Owned(pair.1))) } } /// Defines the action to be taken when returning from a handler pub enum Action { /// Ends the response with no body and the given status (if given). /// /// If the status is not given, the status currently set on the response is used. /// By default, a response has a status 200 OK. End(Option<Status>), /// Redirects to the given URL with a 3xx status (use 302 Found if unsure). Redirect(Status, String), /// Renders the template with the given name using the given JSON value. /// /// If no Content-Type header is set, the content type is set to `text/html`. Render(String, json::Value), /// Sends the response with the given bytes as the body. Send(Vec<u8>), /// Returns a closure that is called with a Stream argument. Stream(Box<Fn(&mut Any, &mut Write)>), /// Sends the given file, setting the Content-Type based on the file's extension. /// /// Known extensions are: /// - application: js, m3u8, mpd, xml /// - image: gif, jpg, jpeg, png /// - text: css, htm, html, txt /// - video: avi, mp4, mpg, mpeg, ts /// If the file does not exist, this method sends a 404 Not Found response. SendFile(String) } /// Conversion from `()` into `End(None)`. impl From<()> for Action { fn from(_: ()) -> Action { Action::End(None) } } /// Conversion from `Status` into `End(Some(status))`. impl From<Status> for Action { fn from(status: Status) -> Action { Action::End(Some(status)) } } /// Conversion from `(Status, &str)` into `Action::Redirect(status, url)`. impl<'a> From<(Status, &'a str)> for Action { fn from(pair: (Status, &'a str)) -> Action { Action::Redirect(pair.0, pair.1.to_string()) } } /// Conversion from `(Status, String)` into `Action::Redirect(status, url)`. impl From<(Status, String)> for Action { fn from(pair: (Status, String)) -> Action { From::from((pair.0, pair.1.as_str())) } } /// Conversion from `(&str, T)`, where `T` can be converted to a JSON value, /// into `Action::Render(template_name, json)`. impl<'a, T> From<(&'a str, T)> for Action where T: ToJson { fn from(pair: (&'a str, T)) -> Action { Action::Render(pair.0.to_string(), pair.1.to_json()) } } /// Conversion from `(String, T)`, where `T` can be converted to a JSON value, /// into `Action::Render(template_name, json)`. impl<T> From<(String, T)> for Action where T: ToJson { fn from(pair: (String, T)) -> Action { Action::Render(pair.0, pair.1.to_json()) } } /// Conversion from `Vec<u8>` into `Action::Send(bytes)`. impl From<Vec<u8>> for Action { fn from(bytes: Vec<u8>) -> Action { Action::Send(bytes) } } /// Conversion from `&str` into `Action::Send(bytes)`. impl<'a> From<&'a str> for Action { fn from(string: &'a str) -> Action { Action::Send(string.as_bytes().to_vec()) } } /// Conversion from `String` into `Action::Send(bytes)`. impl From<String> for Action { fn from(string: String) -> Action { Action::Send(string.into_bytes()) } } /// Conversion from `json::Value` into `Action::Send(bytes)`. impl From<json::Value> for Action { fn from(json: json::Value) -> Action { From::from(json.to_string()) } } /// Wraps the given closure in a box and returns `Ok(Action::Stream(box))`. /// /// The closure will be called with a writer implementing the `Write` trait /// so that each call to `write` notifies the handler that data can be written /// to the HTTP transport. pub fn stream<F, T, R>(closure: F) -> Result where T: Any, F:'static + Fn(&mut T, &mut Write) -> io::Result<R> { Ok(Action::Stream(Box::new(move |any, writer| { if let Some(app) = any.downcast_mut::<T>() { if let Err(e) = closure(app, writer) { error!("{}", e); } } }))) } /// This represents the response that will be sent back to the application. /// /// Includes a status code (default 200 OK), headers, and a body. /// The response can be updated and sent back immediately in a synchronous way, /// or deferred pending some computation (asynchronous mode). /// /// The response is sent when it is dropped. pub struct Response { pub status: Status, pub headers: Headers, streaming: bool } impl Response { pub fn new() -> Response { Response { status: Status::Ok, headers: Headers::default(), streaming: false } } /// Sets the status code of this response. pub fn status(&mut self, status: Status) -> &mut Self { self.status = status; self } /// Sets the Content-Type header. pub fn content_type<S: Into<Vec<u8>>>(&mut self, mime: S) -> &mut Self { self.headers.set_raw("Content-Type", vec![mime.into()]); self } /// Sets the Content-Length header. pub fn len(&mut self, len: u64) -> &mut Self { self.headers.set(header::ContentLength(len)); self } /// Sets the given cookie. pub fn cookie(&mut self, cookie: Cookie) { if self.headers.has::<SetCookie>() { self.headers.get_mut::<SetCookie>().unwrap().push(cookie) } else { self.headers.set(SetCookie(vec![cookie])) } } /// Sets the given header. pub fn header<H: Header>(&mut self, header: H) -> &mut Self { self.headers.set(header); self } /// Sets the given header with raw strings. pub fn header_raw<K: Into<Cow<'static, str>> + fmt::Debug, V: Into<Vec<u8>>>(&mut self, name: K, value: V) -> &mut Self { self.headers.set_raw(name, vec![value.into()]); self } /// Sets the Location header. pub fn location<S: Into<String>>(&mut self, url: S) -> &mut Self { self.headers.set(header::Location(url.into())); self } /// Sends the given file, setting the Content-Type based on the file's extension. /// /// Known extensions are: /// - application: js, m3u8, mpd, xml /// - image: gif, jpg, jpeg, png /// - text: css, htm, html, txt /// - video: avi, mp4, mpg, mpeg, ts /// If the file does not exist, this method sends a 404 Not Found response. fn send_file<P: AsRef<Path>>(&mut self, path: P) -> Option<Vec<u8>> { if!self.headers.has::<ContentType>() { let extension = path.as_ref().extension(); if let Some(ext) = extension { let content_type = match ext.to_string_lossy().as_ref() { // application "js" => Some(("application", "javascript", None)), "m3u8" => Some(("application", "vnd.apple.mpegurl", None)), "mpd" => Some(("application", "dash+xml", None)), "xml" => Some(("application", "xml", None)), // image "gif" => Some(("image", "gif", None)), "jpg" | "jpeg" => Some(("image", "jpeg", None)), "png" => Some(("image", "png", None)), // text "css" => Some(("text", "css", None)), "htm" | "html" => Some(("text", "html", Some((Attr::Charset, Value::Utf8)))), "txt" => Some(("text", "plain", Some((Attr::Charset, Value::Utf8)))), // video "avi" => Some(("video", "x-msvideo", None)), "mp4" => Some(("video", "mp4", None)), "mpg" | "mpeg" => Some(("video", "mpeg", None)), "ts" => Some(("video", "mp2t", None)), _ => None }; if let Some((top, sub, attr)) = content_type { self.headers.set(ContentType(Mime(TopLevel::Ext(top.to_string()), SubLevel::Ext(sub.to_string()), match attr { None => vec![], Some(val) => vec![val] } ))); } } } // read the whole file at once and send it // probably not the best idea for big files, we should use stream instead in that case match File::open(path) { Ok(mut file) => { let mut buf = Vec::with_capacity(file.metadata().ok().map_or(1024, |meta| meta.len() as usize)); if let Err(err) = file.read_to_end(&mut buf) { self.status(Status::InternalServerError).content_type("text/plain"); Some(format!("{}", err).into()) } else { Some(buf) } }, Err(ref err) if err.kind() == ErrorKind::NotFound => { self.status(Status::NotFound); None }, Err(ref err) => { self.status(Status::InternalServerError).content_type("text/plain"); Some(format!("{}", err).into()) } } } } pub fn send_file<P: AsRef<Path>>(response: &mut Response, path: P) -> Option<Vec<u8>> { response.send_file(path) } pub fn set_streaming(response: &mut Response) { response.streaming = true; } pub fn is_streaming(response: &Response) -> bool { response.streaming }
cause
identifier_name
response.rs
use hyper::header::{self, CookiePair as Cookie, ContentType, Header, SetCookie}; use hyper::status::StatusCode as Status; use hyper::Headers; use hyper::mime::{Mime, TopLevel, SubLevel, Attr, Value}; use serde_json::value as json; use serde_json::value::ToJson; use std::any::Any; use std::boxed::Box; use std::borrow::Cow; use std::{error, fmt, result}; use std::fs::File; use std::io::{self, ErrorKind, Read, Write}; use std::path::Path; /// Defines a handler error #[derive(Debug)] pub struct Error { pub status: Status, pub message: Option<Cow<'static, str>> } pub type Result = result::Result<Action, Error>; impl Error { fn new(status: Status, message: Option<Cow<'static, str>>) -> Error { Error { status: status, message: message } } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { use std::error::Error; self.description().fmt(f) } } impl error::Error for Error { fn description(&self) -> &str { match self.message { None => "<no description available>", Some(ref message) => &message } } fn cause(&self) -> Option<&error::Error> { None } } impl From<Status> for Error { fn from(status: Status) -> Error { Error::new(status, None) } } impl From<(Status, &'static str)> for Error { fn from(pair: (Status, &'static str)) -> Error { Error::new(pair.0, Some(Cow::Borrowed(pair.1))) } } impl From<(Status, String)> for Error { fn from(pair: (Status, String)) -> Error { Error::new(pair.0, Some(Cow::Owned(pair.1))) } } /// Defines the action to be taken when returning from a handler pub enum Action { /// Ends the response with no body and the given status (if given). /// /// If the status is not given, the status currently set on the response is used. /// By default, a response has a status 200 OK. End(Option<Status>), /// Redirects to the given URL with a 3xx status (use 302 Found if unsure). Redirect(Status, String), /// Renders the template with the given name using the given JSON value. /// /// If no Content-Type header is set, the content type is set to `text/html`. Render(String, json::Value), /// Sends the response with the given bytes as the body. Send(Vec<u8>), /// Returns a closure that is called with a Stream argument. Stream(Box<Fn(&mut Any, &mut Write)>), /// Sends the given file, setting the Content-Type based on the file's extension. /// /// Known extensions are: /// - application: js, m3u8, mpd, xml /// - image: gif, jpg, jpeg, png /// - text: css, htm, html, txt /// - video: avi, mp4, mpg, mpeg, ts /// If the file does not exist, this method sends a 404 Not Found response. SendFile(String) } /// Conversion from `()` into `End(None)`. impl From<()> for Action { fn from(_: ()) -> Action { Action::End(None) } } /// Conversion from `Status` into `End(Some(status))`. impl From<Status> for Action { fn from(status: Status) -> Action { Action::End(Some(status)) } } /// Conversion from `(Status, &str)` into `Action::Redirect(status, url)`. impl<'a> From<(Status, &'a str)> for Action { fn from(pair: (Status, &'a str)) -> Action { Action::Redirect(pair.0, pair.1.to_string()) } } /// Conversion from `(Status, String)` into `Action::Redirect(status, url)`. impl From<(Status, String)> for Action { fn from(pair: (Status, String)) -> Action { From::from((pair.0, pair.1.as_str())) } } /// Conversion from `(&str, T)`, where `T` can be converted to a JSON value, /// into `Action::Render(template_name, json)`. impl<'a, T> From<(&'a str, T)> for Action where T: ToJson { fn from(pair: (&'a str, T)) -> Action { Action::Render(pair.0.to_string(), pair.1.to_json()) } } /// Conversion from `(String, T)`, where `T` can be converted to a JSON value, /// into `Action::Render(template_name, json)`. impl<T> From<(String, T)> for Action where T: ToJson { fn from(pair: (String, T)) -> Action { Action::Render(pair.0, pair.1.to_json()) } } /// Conversion from `Vec<u8>` into `Action::Send(bytes)`. impl From<Vec<u8>> for Action { fn from(bytes: Vec<u8>) -> Action { Action::Send(bytes) } } /// Conversion from `&str` into `Action::Send(bytes)`. impl<'a> From<&'a str> for Action { fn from(string: &'a str) -> Action { Action::Send(string.as_bytes().to_vec()) } } /// Conversion from `String` into `Action::Send(bytes)`. impl From<String> for Action { fn from(string: String) -> Action { Action::Send(string.into_bytes()) } } /// Conversion from `json::Value` into `Action::Send(bytes)`. impl From<json::Value> for Action { fn from(json: json::Value) -> Action { From::from(json.to_string()) } } /// Wraps the given closure in a box and returns `Ok(Action::Stream(box))`. /// /// The closure will be called with a writer implementing the `Write` trait /// so that each call to `write` notifies the handler that data can be written /// to the HTTP transport. pub fn stream<F, T, R>(closure: F) -> Result where T: Any, F:'static + Fn(&mut T, &mut Write) -> io::Result<R> { Ok(Action::Stream(Box::new(move |any, writer| { if let Some(app) = any.downcast_mut::<T>() { if let Err(e) = closure(app, writer) { error!("{}", e); } } }))) } /// This represents the response that will be sent back to the application. /// /// Includes a status code (default 200 OK), headers, and a body. /// The response can be updated and sent back immediately in a synchronous way, /// or deferred pending some computation (asynchronous mode). /// /// The response is sent when it is dropped. pub struct Response { pub status: Status, pub headers: Headers, streaming: bool } impl Response { pub fn new() -> Response { Response { status: Status::Ok, headers: Headers::default(), streaming: false } } /// Sets the status code of this response. pub fn status(&mut self, status: Status) -> &mut Self { self.status = status; self } /// Sets the Content-Type header. pub fn content_type<S: Into<Vec<u8>>>(&mut self, mime: S) -> &mut Self { self.headers.set_raw("Content-Type", vec![mime.into()]); self } /// Sets the Content-Length header. pub fn len(&mut self, len: u64) -> &mut Self { self.headers.set(header::ContentLength(len)); self } /// Sets the given cookie. pub fn cookie(&mut self, cookie: Cookie) { if self.headers.has::<SetCookie>() { self.headers.get_mut::<SetCookie>().unwrap().push(cookie) } else { self.headers.set(SetCookie(vec![cookie])) } } /// Sets the given header. pub fn header<H: Header>(&mut self, header: H) -> &mut Self { self.headers.set(header); self } /// Sets the given header with raw strings. pub fn header_raw<K: Into<Cow<'static, str>> + fmt::Debug, V: Into<Vec<u8>>>(&mut self, name: K, value: V) -> &mut Self { self.headers.set_raw(name, vec![value.into()]); self } /// Sets the Location header. pub fn location<S: Into<String>>(&mut self, url: S) -> &mut Self { self.headers.set(header::Location(url.into())); self } /// Sends the given file, setting the Content-Type based on the file's extension. /// /// Known extensions are: /// - application: js, m3u8, mpd, xml /// - image: gif, jpg, jpeg, png /// - text: css, htm, html, txt /// - video: avi, mp4, mpg, mpeg, ts /// If the file does not exist, this method sends a 404 Not Found response. fn send_file<P: AsRef<Path>>(&mut self, path: P) -> Option<Vec<u8>> { if!self.headers.has::<ContentType>() { let extension = path.as_ref().extension(); if let Some(ext) = extension { let content_type = match ext.to_string_lossy().as_ref() { // application "js" => Some(("application", "javascript", None)), "m3u8" => Some(("application", "vnd.apple.mpegurl", None)), "mpd" => Some(("application", "dash+xml", None)), "xml" => Some(("application", "xml", None)), // image "gif" => Some(("image", "gif", None)), "jpg" | "jpeg" => Some(("image", "jpeg", None)), "png" => Some(("image", "png", None)), // text "css" => Some(("text", "css", None)), "htm" | "html" => Some(("text", "html", Some((Attr::Charset, Value::Utf8)))), "txt" => Some(("text", "plain", Some((Attr::Charset, Value::Utf8)))), // video "avi" => Some(("video", "x-msvideo", None)), "mp4" => Some(("video", "mp4", None)), "mpg" | "mpeg" => Some(("video", "mpeg", None)), "ts" => Some(("video", "mp2t", None)), _ => None }; if let Some((top, sub, attr)) = content_type { self.headers.set(ContentType(Mime(TopLevel::Ext(top.to_string()), SubLevel::Ext(sub.to_string()), match attr { None => vec![], Some(val) => vec![val] } ))); } } } // read the whole file at once and send it // probably not the best idea for big files, we should use stream instead in that case match File::open(path) { Ok(mut file) => { let mut buf = Vec::with_capacity(file.metadata().ok().map_or(1024, |meta| meta.len() as usize)); if let Err(err) = file.read_to_end(&mut buf) { self.status(Status::InternalServerError).content_type("text/plain"); Some(format!("{}", err).into()) } else { Some(buf) } }, Err(ref err) if err.kind() == ErrorKind::NotFound => { self.status(Status::NotFound); None }, Err(ref err) => { self.status(Status::InternalServerError).content_type("text/plain"); Some(format!("{}", err).into()) } } } } pub fn send_file<P: AsRef<Path>>(response: &mut Response, path: P) -> Option<Vec<u8>> { response.send_file(path) } pub fn set_streaming(response: &mut Response) { response.streaming = true; } pub fn is_streaming(response: &Response) -> bool
{ response.streaming }
identifier_body
response.rs
use hyper::header::{self, CookiePair as Cookie, ContentType, Header, SetCookie}; use hyper::status::StatusCode as Status; use hyper::Headers; use hyper::mime::{Mime, TopLevel, SubLevel, Attr, Value}; use serde_json::value as json; use serde_json::value::ToJson; use std::any::Any; use std::boxed::Box; use std::borrow::Cow; use std::{error, fmt, result}; use std::fs::File; use std::io::{self, ErrorKind, Read, Write}; use std::path::Path; /// Defines a handler error #[derive(Debug)] pub struct Error { pub status: Status, pub message: Option<Cow<'static, str>> } pub type Result = result::Result<Action, Error>; impl Error { fn new(status: Status, message: Option<Cow<'static, str>>) -> Error { Error { status: status, message: message } } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { use std::error::Error; self.description().fmt(f) } } impl error::Error for Error { fn description(&self) -> &str { match self.message { None => "<no description available>", Some(ref message) => &message } } fn cause(&self) -> Option<&error::Error> { None } } impl From<Status> for Error { fn from(status: Status) -> Error { Error::new(status, None) } } impl From<(Status, &'static str)> for Error { fn from(pair: (Status, &'static str)) -> Error { Error::new(pair.0, Some(Cow::Borrowed(pair.1))) } } impl From<(Status, String)> for Error { fn from(pair: (Status, String)) -> Error { Error::new(pair.0, Some(Cow::Owned(pair.1))) } } /// Defines the action to be taken when returning from a handler pub enum Action { /// Ends the response with no body and the given status (if given). /// /// If the status is not given, the status currently set on the response is used. /// By default, a response has a status 200 OK. End(Option<Status>), /// Redirects to the given URL with a 3xx status (use 302 Found if unsure). Redirect(Status, String), /// Renders the template with the given name using the given JSON value. /// /// If no Content-Type header is set, the content type is set to `text/html`. Render(String, json::Value), /// Sends the response with the given bytes as the body. Send(Vec<u8>), /// Returns a closure that is called with a Stream argument. Stream(Box<Fn(&mut Any, &mut Write)>), /// Sends the given file, setting the Content-Type based on the file's extension. /// /// Known extensions are: /// - application: js, m3u8, mpd, xml /// - image: gif, jpg, jpeg, png /// - text: css, htm, html, txt /// - video: avi, mp4, mpg, mpeg, ts /// If the file does not exist, this method sends a 404 Not Found response. SendFile(String) } /// Conversion from `()` into `End(None)`. impl From<()> for Action { fn from(_: ()) -> Action { Action::End(None) } } /// Conversion from `Status` into `End(Some(status))`. impl From<Status> for Action { fn from(status: Status) -> Action { Action::End(Some(status)) } } /// Conversion from `(Status, &str)` into `Action::Redirect(status, url)`. impl<'a> From<(Status, &'a str)> for Action { fn from(pair: (Status, &'a str)) -> Action { Action::Redirect(pair.0, pair.1.to_string()) } } /// Conversion from `(Status, String)` into `Action::Redirect(status, url)`. impl From<(Status, String)> for Action { fn from(pair: (Status, String)) -> Action { From::from((pair.0, pair.1.as_str())) } } /// Conversion from `(&str, T)`, where `T` can be converted to a JSON value, /// into `Action::Render(template_name, json)`. impl<'a, T> From<(&'a str, T)> for Action where T: ToJson { fn from(pair: (&'a str, T)) -> Action { Action::Render(pair.0.to_string(), pair.1.to_json()) } } /// Conversion from `(String, T)`, where `T` can be converted to a JSON value, /// into `Action::Render(template_name, json)`. impl<T> From<(String, T)> for Action where T: ToJson { fn from(pair: (String, T)) -> Action { Action::Render(pair.0, pair.1.to_json()) } } /// Conversion from `Vec<u8>` into `Action::Send(bytes)`. impl From<Vec<u8>> for Action { fn from(bytes: Vec<u8>) -> Action { Action::Send(bytes) } } /// Conversion from `&str` into `Action::Send(bytes)`. impl<'a> From<&'a str> for Action { fn from(string: &'a str) -> Action { Action::Send(string.as_bytes().to_vec()) } } /// Conversion from `String` into `Action::Send(bytes)`. impl From<String> for Action { fn from(string: String) -> Action { Action::Send(string.into_bytes()) } } /// Conversion from `json::Value` into `Action::Send(bytes)`. impl From<json::Value> for Action { fn from(json: json::Value) -> Action { From::from(json.to_string()) } } /// Wraps the given closure in a box and returns `Ok(Action::Stream(box))`. /// /// The closure will be called with a writer implementing the `Write` trait /// so that each call to `write` notifies the handler that data can be written /// to the HTTP transport. pub fn stream<F, T, R>(closure: F) -> Result where T: Any, F:'static + Fn(&mut T, &mut Write) -> io::Result<R> { Ok(Action::Stream(Box::new(move |any, writer| { if let Some(app) = any.downcast_mut::<T>() { if let Err(e) = closure(app, writer) { error!("{}", e); } } }))) } /// This represents the response that will be sent back to the application. /// /// Includes a status code (default 200 OK), headers, and a body. /// The response can be updated and sent back immediately in a synchronous way, /// or deferred pending some computation (asynchronous mode). /// /// The response is sent when it is dropped. pub struct Response { pub status: Status, pub headers: Headers, streaming: bool } impl Response { pub fn new() -> Response { Response { status: Status::Ok, headers: Headers::default(), streaming: false } } /// Sets the status code of this response. pub fn status(&mut self, status: Status) -> &mut Self { self.status = status; self } /// Sets the Content-Type header. pub fn content_type<S: Into<Vec<u8>>>(&mut self, mime: S) -> &mut Self { self.headers.set_raw("Content-Type", vec![mime.into()]); self } /// Sets the Content-Length header. pub fn len(&mut self, len: u64) -> &mut Self { self.headers.set(header::ContentLength(len)); self } /// Sets the given cookie. pub fn cookie(&mut self, cookie: Cookie) { if self.headers.has::<SetCookie>() { self.headers.get_mut::<SetCookie>().unwrap().push(cookie) } else { self.headers.set(SetCookie(vec![cookie])) } } /// Sets the given header. pub fn header<H: Header>(&mut self, header: H) -> &mut Self { self.headers.set(header); self } /// Sets the given header with raw strings. pub fn header_raw<K: Into<Cow<'static, str>> + fmt::Debug, V: Into<Vec<u8>>>(&mut self, name: K, value: V) -> &mut Self { self.headers.set_raw(name, vec![value.into()]); self } /// Sets the Location header. pub fn location<S: Into<String>>(&mut self, url: S) -> &mut Self { self.headers.set(header::Location(url.into())); self } /// Sends the given file, setting the Content-Type based on the file's extension. /// /// Known extensions are: /// - application: js, m3u8, mpd, xml /// - image: gif, jpg, jpeg, png /// - text: css, htm, html, txt /// - video: avi, mp4, mpg, mpeg, ts /// If the file does not exist, this method sends a 404 Not Found response. fn send_file<P: AsRef<Path>>(&mut self, path: P) -> Option<Vec<u8>> { if!self.headers.has::<ContentType>() { let extension = path.as_ref().extension(); if let Some(ext) = extension { let content_type = match ext.to_string_lossy().as_ref() { // application "js" => Some(("application", "javascript", None)), "m3u8" => Some(("application", "vnd.apple.mpegurl", None)), "mpd" => Some(("application", "dash+xml", None)), "xml" => Some(("application", "xml", None)), // image "gif" => Some(("image", "gif", None)), "jpg" | "jpeg" => Some(("image", "jpeg", None)), "png" => Some(("image", "png", None)), // text "css" => Some(("text", "css", None)), "htm" | "html" => Some(("text", "html", Some((Attr::Charset, Value::Utf8)))), "txt" => Some(("text", "plain", Some((Attr::Charset, Value::Utf8)))), // video "avi" => Some(("video", "x-msvideo", None)), "mp4" => Some(("video", "mp4", None)), "mpg" | "mpeg" => Some(("video", "mpeg", None)), "ts" => Some(("video", "mp2t", None)), _ => None }; if let Some((top, sub, attr)) = content_type { self.headers.set(ContentType(Mime(TopLevel::Ext(top.to_string()), SubLevel::Ext(sub.to_string()), match attr { None => vec![], Some(val) => vec![val] } ))); } } } // read the whole file at once and send it
self.status(Status::InternalServerError).content_type("text/plain"); Some(format!("{}", err).into()) } else { Some(buf) } }, Err(ref err) if err.kind() == ErrorKind::NotFound => { self.status(Status::NotFound); None }, Err(ref err) => { self.status(Status::InternalServerError).content_type("text/plain"); Some(format!("{}", err).into()) } } } } pub fn send_file<P: AsRef<Path>>(response: &mut Response, path: P) -> Option<Vec<u8>> { response.send_file(path) } pub fn set_streaming(response: &mut Response) { response.streaming = true; } pub fn is_streaming(response: &Response) -> bool { response.streaming }
// probably not the best idea for big files, we should use stream instead in that case match File::open(path) { Ok(mut file) => { let mut buf = Vec::with_capacity(file.metadata().ok().map_or(1024, |meta| meta.len() as usize)); if let Err(err) = file.read_to_end(&mut buf) {
random_line_split
lib.rs
//! An element-tree style XML library //! //! # Examples //! //! ## Reading //! //! ``` //! use treexml::Document; //! //! let doc_raw = r#" //! <?xml version="1.1" encoding="UTF-8"?> //! <table> //! <fruit type="apple">worm</fruit> //! <vegetable /> //! </table> //! "#; //! //! let doc = Document::parse(doc_raw.as_bytes()).unwrap(); //! let root = doc.root.unwrap(); //! //! let fruit = root.find_child(|tag| tag.name == "fruit").unwrap().clone(); //! println!("{} [{:?}] = {}", fruit.name, fruit.attributes, fruit.text.unwrap()); //! ``` //! //! ## Writing //! //! ``` //! use treexml::{Document, Element}; //! //! let mut root = Element::new("root"); //! let mut child = Element::new("child"); //! child.text = Some("contents".to_owned()); //! root.children.push(child); //! //! let doc = Document{ //! root: Some(root), //! .. Document::default() //! }; //! //! println!("{}", doc); //! ``` //! //! // `error_chain!` can recurse deeply #![recursion_limit = "1024"] #[macro_use] extern crate failure; extern crate indexmap; mod errors; extern crate xml; mod builder; use std::borrow::Cow; use std::fmt; use std::io::{Read, Write}; use std::iter::Filter; use std::slice::{Iter, IterMut}; use std::str::FromStr; use std::string::ToString;
use indexmap::IndexMap; use xml::common::XmlVersion as BaseXmlVersion; /// Enumeration of XML versions /// /// This exists solely because `xml-rs`'s `XmlVersion` doesn't implement Debug #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub enum XmlVersion { /// XML Version 1.0 Version10, /// XML Version 1.1 Version11, } impl From<BaseXmlVersion> for XmlVersion { fn from(value: BaseXmlVersion) -> XmlVersion { match value { BaseXmlVersion::Version10 => XmlVersion::Version10, BaseXmlVersion::Version11 => XmlVersion::Version11, } } } impl From<XmlVersion> for BaseXmlVersion { fn from(value: XmlVersion) -> BaseXmlVersion { match value { XmlVersion::Version10 => BaseXmlVersion::Version10, XmlVersion::Version11 => BaseXmlVersion::Version11, } } } /// An XML element #[derive(Debug, Clone, PartialEq, Eq)] pub struct Element { /// Tag prefix, used for namespacing: `xsl` in `xsl:for-each` pub prefix: Option<String>, /// Tag name: `for-each` in `xsl:for-each` pub name: String, /// Tag attributes pub attributes: IndexMap<String, String>, /// A vector of child elements pub children: Vec<Element>, /// Contents of the element pub text: Option<String>, /// CDATA contents of the element pub cdata: Option<String>, } impl Default for Element { fn default() -> Self { Element { prefix: None, name: "tag".to_owned(), attributes: IndexMap::new(), children: Vec::new(), text: None, cdata: None, } } } impl Element { /// Create a new `Element` with the tag name `name` pub fn new<S>(name: S) -> Element where S: ToString, { Element { name: name.to_string(), ..Element::default() } } /// Parse the contents of an element fn parse<R: Read>( &mut self, mut reader: &mut xml::reader::EventReader<R>, ) -> Result<(), Error> { use xml::reader::XmlEvent; loop { let ev = reader.next()?; match ev { XmlEvent::StartElement { name, attributes,.. } => { let mut attr_map = IndexMap::new(); for attr in attributes { let attr_name = match attr.name.prefix { Some(prefix) => format!("{}:{}", prefix, attr.name.local_name), None => attr.name.local_name, }; attr_map.insert(attr_name, attr.value); } let mut child = Element { prefix: name.prefix, name: name.local_name, attributes: attr_map, ..Element::default() }; child.parse(&mut reader)?; self.children.push(child); } XmlEvent::EndElement { name } => { if name.prefix == self.prefix && name.local_name == self.name { return Ok(()); } else { // This should never happen, since the base xml library will panic first panic!("Unexpected closing tag: {}, expected {}", name, self.name); } } XmlEvent::Characters(s) => { let text = match self.text { Some(ref v) => v.clone(), None => String::new(), }; self.text = Some(text + &s); } XmlEvent::CData(s) => { let cdata = match self.cdata { Some(ref v) => v.clone(), None => String::new(), }; self.cdata = Some(cdata + &s); } XmlEvent::StartDocument {.. } | XmlEvent::EndDocument | XmlEvent::ProcessingInstruction {.. } | XmlEvent::Whitespace(_) | XmlEvent::Comment(_) => {} } } } /// Write an element and its contents to `writer` fn write<W: Write>(&self, writer: &mut xml::writer::EventWriter<W>) -> Result<(), Error> { use xml::attribute::Attribute; use xml::name::Name; use xml::namespace::Namespace; use xml::writer::XmlEvent; let name = Name::local(&self.name); let mut attributes = Vec::with_capacity(self.attributes.len()); for (k, v) in &self.attributes { attributes.push(Attribute { name: Name::local(k), value: v, }); } let namespace = Namespace::empty(); writer.write(XmlEvent::StartElement { name: name, attributes: Cow::Owned(attributes), namespace: Cow::Owned(namespace), })?; if let Some(ref text) = self.text { writer.write(XmlEvent::Characters(&text[..]))?; } if let Some(ref cdata) = self.cdata { writer.write(XmlEvent::CData(&cdata[..]))?; } for e in &self.children { e.write(writer)?; } writer.write(XmlEvent::EndElement { name: Some(name) })?; Ok(()) } /// Find a single child of the current `Element`, given a predicate pub fn find_child<P>(&self, predicate: P) -> Option<&Element> where P: for<'r> Fn(&'r &Element) -> bool, { self.children.iter().find(predicate) } /// Find a single child of the current `Element`, given a predicate; returns a mutable borrow pub fn find_child_mut<P>(&mut self, predicate: P) -> Option<&mut Element> where P: for<'r> FnMut(&'r &mut Element) -> bool, { self.children.iter_mut().find(predicate) } /// Traverse element using an xpath-like string: root/child/a pub fn find(&self, path: &str) -> Result<&Element, Error> { Self::find_path(&path.split('/').collect::<Vec<&str>>(), path, self) } pub fn find_value<T: FromStr>(&self, path: &str) -> Result<Option<T>, Error> { let el = self.find(path)?; if let Some(text) = el.text.as_ref() { match T::from_str(text) { Err(_) => Err(errors::Error::ValueFromStr { t: text.to_string(), }.into()), Ok(value) => Ok(Some(value)), } } else { Ok(None) } } fn find_path<'a>( path: &[&str], original: &str, tree: &'a Element, ) -> Result<&'a Element, Error> { if path.is_empty() { return Ok(tree); } match tree.find_child(|t| t.name == path[0]) { Some(element) => Self::find_path(&path[1..], original, element), None => Err(errors::Error::ElementNotFound { t: original.into() }.into()), } } /// Filters the children of the current `Element`, given a predicate pub fn filter_children<P>(&self, predicate: P) -> Filter<Iter<Element>, P> where P: for<'r> Fn(&'r &Element) -> bool, { self.children.iter().filter(predicate) } /// Filters the children of the current `Element`, given a predicate; returns a mutable iterator pub fn filter_children_mut<P>(&mut self, predicate: P) -> Filter<IterMut<Element>, P> where P: for<'r> FnMut(&'r &mut Element) -> bool, { self.children.iter_mut().filter(predicate) } } impl fmt::Display for Element { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let doc = Document { root: Some(self.clone()), ..Document::default() }; let mut v = Vec::<u8>::new(); doc.write_with(&mut v, false, " ", true).unwrap(); let s = String::from_utf8(v).unwrap(); f.write_str(&s[..]) } } /// An XML document #[derive(Debug, Clone, PartialEq, Eq)] pub struct Document { /// Version of the XML document pub version: XmlVersion, /// Encoding of the XML document pub encoding: String, /// Root tag of the XML document pub root: Option<Element>, } impl Default for Document { fn default() -> Self { Document { version: XmlVersion::Version10, encoding: "UTF-8".to_owned(), root: None, } } } impl Document { /// Create a new `Document` with default values pub fn new() -> Document { Document { ..Document::default() } } /// Create a new `Document` with an Element or ElementBuilder at its root. pub fn build(root: &mut ElementBuilder) -> Self { Document { root: Some(root.element()), ..Self::default() } } /// Parse data from a reader to construct an XML document /// /// # Failures /// /// Passes any errors that the `xml-rs` library returns up the stack pub fn parse<R: Read>(r: R) -> Result<Document, Error> { use xml::reader::{EventReader, XmlEvent}; let mut reader = EventReader::new(r); let mut doc = Document::new(); loop { let ev = reader.next()?; match ev { XmlEvent::StartDocument { version, encoding,.. } => { doc.version = XmlVersion::from(version); doc.encoding = encoding; } XmlEvent::StartElement { name, attributes,.. } => { // Start of the root element let mut attr_map = IndexMap::new(); for attr in attributes { let attr_name = match attr.name.prefix { Some(prefix) => format!("{}:{}", prefix, attr.name.local_name), None => attr.name.local_name, }; attr_map.insert(attr_name, attr.value); } let mut root = Element { prefix: name.prefix, name: name.local_name, attributes: attr_map, ..Element::default() }; root.parse(&mut reader)?; doc.root = Some(root); } XmlEvent::EndDocument => break, _ => {} } } Ok(doc) } pub fn write<W: Write>(&self, mut w: &mut W) -> Result<(), Error> { self.write_with(&mut w, true, " ", true) } /// Writes a document to `w` pub fn write_with<W: Write>( &self, w: &mut W, document_decl: bool, indent_str: &'static str, indent: bool, ) -> Result<(), Error> { use xml::writer::{EmitterConfig, XmlEvent}; let mut writer = EmitterConfig::new() .perform_indent(indent) .write_document_declaration(document_decl) .indent_string(indent_str) .create_writer(w); if document_decl { writer.write(XmlEvent::StartDocument { version: self.version.into(), encoding: Some(&self.encoding), standalone: None, })?; } if let Some(ref e) = self.root { e.write(&mut writer)?; } Ok(()) } } impl fmt::Display for Document { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let mut v = Vec::<u8>::new(); self.write(&mut v).unwrap(); let s = String::from_utf8(v).unwrap(); f.write_str(&s[..]) } }
pub use errors::*; pub use builder::*;
random_line_split
lib.rs
//! An element-tree style XML library //! //! # Examples //! //! ## Reading //! //! ``` //! use treexml::Document; //! //! let doc_raw = r#" //! <?xml version="1.1" encoding="UTF-8"?> //! <table> //! <fruit type="apple">worm</fruit> //! <vegetable /> //! </table> //! "#; //! //! let doc = Document::parse(doc_raw.as_bytes()).unwrap(); //! let root = doc.root.unwrap(); //! //! let fruit = root.find_child(|tag| tag.name == "fruit").unwrap().clone(); //! println!("{} [{:?}] = {}", fruit.name, fruit.attributes, fruit.text.unwrap()); //! ``` //! //! ## Writing //! //! ``` //! use treexml::{Document, Element}; //! //! let mut root = Element::new("root"); //! let mut child = Element::new("child"); //! child.text = Some("contents".to_owned()); //! root.children.push(child); //! //! let doc = Document{ //! root: Some(root), //! .. Document::default() //! }; //! //! println!("{}", doc); //! ``` //! //! // `error_chain!` can recurse deeply #![recursion_limit = "1024"] #[macro_use] extern crate failure; extern crate indexmap; mod errors; extern crate xml; mod builder; use std::borrow::Cow; use std::fmt; use std::io::{Read, Write}; use std::iter::Filter; use std::slice::{Iter, IterMut}; use std::str::FromStr; use std::string::ToString; pub use errors::*; pub use builder::*; use indexmap::IndexMap; use xml::common::XmlVersion as BaseXmlVersion; /// Enumeration of XML versions /// /// This exists solely because `xml-rs`'s `XmlVersion` doesn't implement Debug #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub enum XmlVersion { /// XML Version 1.0 Version10, /// XML Version 1.1 Version11, } impl From<BaseXmlVersion> for XmlVersion { fn from(value: BaseXmlVersion) -> XmlVersion { match value { BaseXmlVersion::Version10 => XmlVersion::Version10, BaseXmlVersion::Version11 => XmlVersion::Version11, } } } impl From<XmlVersion> for BaseXmlVersion { fn
(value: XmlVersion) -> BaseXmlVersion { match value { XmlVersion::Version10 => BaseXmlVersion::Version10, XmlVersion::Version11 => BaseXmlVersion::Version11, } } } /// An XML element #[derive(Debug, Clone, PartialEq, Eq)] pub struct Element { /// Tag prefix, used for namespacing: `xsl` in `xsl:for-each` pub prefix: Option<String>, /// Tag name: `for-each` in `xsl:for-each` pub name: String, /// Tag attributes pub attributes: IndexMap<String, String>, /// A vector of child elements pub children: Vec<Element>, /// Contents of the element pub text: Option<String>, /// CDATA contents of the element pub cdata: Option<String>, } impl Default for Element { fn default() -> Self { Element { prefix: None, name: "tag".to_owned(), attributes: IndexMap::new(), children: Vec::new(), text: None, cdata: None, } } } impl Element { /// Create a new `Element` with the tag name `name` pub fn new<S>(name: S) -> Element where S: ToString, { Element { name: name.to_string(), ..Element::default() } } /// Parse the contents of an element fn parse<R: Read>( &mut self, mut reader: &mut xml::reader::EventReader<R>, ) -> Result<(), Error> { use xml::reader::XmlEvent; loop { let ev = reader.next()?; match ev { XmlEvent::StartElement { name, attributes,.. } => { let mut attr_map = IndexMap::new(); for attr in attributes { let attr_name = match attr.name.prefix { Some(prefix) => format!("{}:{}", prefix, attr.name.local_name), None => attr.name.local_name, }; attr_map.insert(attr_name, attr.value); } let mut child = Element { prefix: name.prefix, name: name.local_name, attributes: attr_map, ..Element::default() }; child.parse(&mut reader)?; self.children.push(child); } XmlEvent::EndElement { name } => { if name.prefix == self.prefix && name.local_name == self.name { return Ok(()); } else { // This should never happen, since the base xml library will panic first panic!("Unexpected closing tag: {}, expected {}", name, self.name); } } XmlEvent::Characters(s) => { let text = match self.text { Some(ref v) => v.clone(), None => String::new(), }; self.text = Some(text + &s); } XmlEvent::CData(s) => { let cdata = match self.cdata { Some(ref v) => v.clone(), None => String::new(), }; self.cdata = Some(cdata + &s); } XmlEvent::StartDocument {.. } | XmlEvent::EndDocument | XmlEvent::ProcessingInstruction {.. } | XmlEvent::Whitespace(_) | XmlEvent::Comment(_) => {} } } } /// Write an element and its contents to `writer` fn write<W: Write>(&self, writer: &mut xml::writer::EventWriter<W>) -> Result<(), Error> { use xml::attribute::Attribute; use xml::name::Name; use xml::namespace::Namespace; use xml::writer::XmlEvent; let name = Name::local(&self.name); let mut attributes = Vec::with_capacity(self.attributes.len()); for (k, v) in &self.attributes { attributes.push(Attribute { name: Name::local(k), value: v, }); } let namespace = Namespace::empty(); writer.write(XmlEvent::StartElement { name: name, attributes: Cow::Owned(attributes), namespace: Cow::Owned(namespace), })?; if let Some(ref text) = self.text { writer.write(XmlEvent::Characters(&text[..]))?; } if let Some(ref cdata) = self.cdata { writer.write(XmlEvent::CData(&cdata[..]))?; } for e in &self.children { e.write(writer)?; } writer.write(XmlEvent::EndElement { name: Some(name) })?; Ok(()) } /// Find a single child of the current `Element`, given a predicate pub fn find_child<P>(&self, predicate: P) -> Option<&Element> where P: for<'r> Fn(&'r &Element) -> bool, { self.children.iter().find(predicate) } /// Find a single child of the current `Element`, given a predicate; returns a mutable borrow pub fn find_child_mut<P>(&mut self, predicate: P) -> Option<&mut Element> where P: for<'r> FnMut(&'r &mut Element) -> bool, { self.children.iter_mut().find(predicate) } /// Traverse element using an xpath-like string: root/child/a pub fn find(&self, path: &str) -> Result<&Element, Error> { Self::find_path(&path.split('/').collect::<Vec<&str>>(), path, self) } pub fn find_value<T: FromStr>(&self, path: &str) -> Result<Option<T>, Error> { let el = self.find(path)?; if let Some(text) = el.text.as_ref() { match T::from_str(text) { Err(_) => Err(errors::Error::ValueFromStr { t: text.to_string(), }.into()), Ok(value) => Ok(Some(value)), } } else { Ok(None) } } fn find_path<'a>( path: &[&str], original: &str, tree: &'a Element, ) -> Result<&'a Element, Error> { if path.is_empty() { return Ok(tree); } match tree.find_child(|t| t.name == path[0]) { Some(element) => Self::find_path(&path[1..], original, element), None => Err(errors::Error::ElementNotFound { t: original.into() }.into()), } } /// Filters the children of the current `Element`, given a predicate pub fn filter_children<P>(&self, predicate: P) -> Filter<Iter<Element>, P> where P: for<'r> Fn(&'r &Element) -> bool, { self.children.iter().filter(predicate) } /// Filters the children of the current `Element`, given a predicate; returns a mutable iterator pub fn filter_children_mut<P>(&mut self, predicate: P) -> Filter<IterMut<Element>, P> where P: for<'r> FnMut(&'r &mut Element) -> bool, { self.children.iter_mut().filter(predicate) } } impl fmt::Display for Element { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let doc = Document { root: Some(self.clone()), ..Document::default() }; let mut v = Vec::<u8>::new(); doc.write_with(&mut v, false, " ", true).unwrap(); let s = String::from_utf8(v).unwrap(); f.write_str(&s[..]) } } /// An XML document #[derive(Debug, Clone, PartialEq, Eq)] pub struct Document { /// Version of the XML document pub version: XmlVersion, /// Encoding of the XML document pub encoding: String, /// Root tag of the XML document pub root: Option<Element>, } impl Default for Document { fn default() -> Self { Document { version: XmlVersion::Version10, encoding: "UTF-8".to_owned(), root: None, } } } impl Document { /// Create a new `Document` with default values pub fn new() -> Document { Document { ..Document::default() } } /// Create a new `Document` with an Element or ElementBuilder at its root. pub fn build(root: &mut ElementBuilder) -> Self { Document { root: Some(root.element()), ..Self::default() } } /// Parse data from a reader to construct an XML document /// /// # Failures /// /// Passes any errors that the `xml-rs` library returns up the stack pub fn parse<R: Read>(r: R) -> Result<Document, Error> { use xml::reader::{EventReader, XmlEvent}; let mut reader = EventReader::new(r); let mut doc = Document::new(); loop { let ev = reader.next()?; match ev { XmlEvent::StartDocument { version, encoding,.. } => { doc.version = XmlVersion::from(version); doc.encoding = encoding; } XmlEvent::StartElement { name, attributes,.. } => { // Start of the root element let mut attr_map = IndexMap::new(); for attr in attributes { let attr_name = match attr.name.prefix { Some(prefix) => format!("{}:{}", prefix, attr.name.local_name), None => attr.name.local_name, }; attr_map.insert(attr_name, attr.value); } let mut root = Element { prefix: name.prefix, name: name.local_name, attributes: attr_map, ..Element::default() }; root.parse(&mut reader)?; doc.root = Some(root); } XmlEvent::EndDocument => break, _ => {} } } Ok(doc) } pub fn write<W: Write>(&self, mut w: &mut W) -> Result<(), Error> { self.write_with(&mut w, true, " ", true) } /// Writes a document to `w` pub fn write_with<W: Write>( &self, w: &mut W, document_decl: bool, indent_str: &'static str, indent: bool, ) -> Result<(), Error> { use xml::writer::{EmitterConfig, XmlEvent}; let mut writer = EmitterConfig::new() .perform_indent(indent) .write_document_declaration(document_decl) .indent_string(indent_str) .create_writer(w); if document_decl { writer.write(XmlEvent::StartDocument { version: self.version.into(), encoding: Some(&self.encoding), standalone: None, })?; } if let Some(ref e) = self.root { e.write(&mut writer)?; } Ok(()) } } impl fmt::Display for Document { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let mut v = Vec::<u8>::new(); self.write(&mut v).unwrap(); let s = String::from_utf8(v).unwrap(); f.write_str(&s[..]) } }
from
identifier_name
component.rs
}; use wasmtime_jit::{CodeMemory, CompiledModuleInfo}; use wasmtime_runtime::{MmapVec, VMFunctionBody, VMTrampoline}; /// A compiled WebAssembly Component. // // FIXME: need to write more docs here. #[derive(Clone)] pub struct Component { inner: Arc<ComponentInner>, } struct ComponentInner { /// Core wasm modules that the component defined internally, indexed by the /// compile-time-assigned `ModuleUpvarIndex`. static_modules: PrimaryMap<StaticModuleIndex, Module>, /// Code-related information such as the compiled artifact, type /// information, etc. /// /// Note that the `Arc` here is used to share this allocation with internal /// modules. code: Arc<CodeObject>, /// Metadata produced during compilation. info: CompiledComponentInfo, } #[derive(Serialize, Deserialize)] struct CompiledComponentInfo { /// Type information calculated during translation about this component. component: wasmtime_environ::component::Component, /// Where lowered function trampolines are located within the `text` /// section of `code_memory`. /// /// These trampolines are the function pointer within the /// `VMCallerCheckedFuncRef` and will delegate indirectly to a host function /// pointer when called. lowerings: PrimaryMap<LoweredIndex, FunctionLoc>, /// Where the "always trap" functions are located within the `text` section /// of `code_memory`. /// /// These functions are "degenerate functions" here solely to implement /// functions that are `canon lift`'d then immediately `canon lower`'d. The /// `u32` value here is the offset of the trap instruction from the start fo /// the function. always_trap: PrimaryMap<RuntimeAlwaysTrapIndex, FunctionLoc>, /// Where all the cranelift-generated transcode functions are located in the /// compiled image of this component. transcoders: PrimaryMap<RuntimeTranscoderIndex, FunctionLoc>, /// Extra trampolines other than those contained in static modules /// necessary for this component. trampolines: Vec<(SignatureIndex, FunctionLoc)>, } #[derive(Serialize, Deserialize)] pub(crate) struct ComponentArtifacts { info: CompiledComponentInfo, types: ComponentTypes, static_modules: PrimaryMap<StaticModuleIndex, CompiledModuleInfo>, } impl Component { /// Compiles a new WebAssembly component from the in-memory wasm image /// provided. // // FIXME: need to write more docs here. #[cfg(compiler)] #[cfg_attr(nightlydoc, doc(cfg(feature = "cranelift")))] // see build.rs pub fn new(engine: &Engine, bytes: impl AsRef<[u8]>) -> Result<Component> { let bytes = bytes.as_ref(); #[cfg(feature = "wat")] let bytes = wat::parse_bytes(bytes)?; Component::from_binary(engine, &bytes) } /// Compiles a new WebAssembly component from a wasm file on disk pointed to /// by `file`. // // FIXME: need to write more docs here. #[cfg(compiler)] #[cfg_attr(nightlydoc, doc(cfg(feature = "cranelift")))] // see build.rs pub fn from_file(engine: &Engine, file: impl AsRef<Path>) -> Result<Component> { match Self::new( engine, &fs::read(&file).with_context(|| "failed to read input file")?, ) { Ok(m) => Ok(m), Err(e) => { cfg_if::cfg_if! { if #[cfg(feature = "wat")] { let mut e = e.downcast::<wat::Error>()?; e.set_path(file); bail!(e) } else { Err(e) } } } } } /// Compiles a new WebAssembly component from the in-memory wasm image /// provided. // // FIXME: need to write more docs here. #[cfg(compiler)] #[cfg_attr(nightlydoc, doc(cfg(feature = "cranelift")))] // see build.rs pub fn from_binary(engine: &Engine, binary: &[u8]) -> Result<Component> { engine .check_compatible_with_native_host() .context("compilation settings are not compatible with the native host")?; let (mmap, artifacts) = Component::build_artifacts(engine, binary)?; let mut code_memory = CodeMemory::new(mmap)?; code_memory.publish()?; Component::from_parts(engine, Arc::new(code_memory), Some(artifacts)) } /// Same as [`Module::deserialize`], but for components. /// /// Note that the file referenced here must contain contents previously /// produced by [`Engine::precompile_component`] or /// [`Component::serialize`]. /// /// For more information see the [`Module::deserialize`] method. /// /// [`Module::deserialize`]: crate::Module::deserialize pub unsafe fn deserialize(engine: &Engine, bytes: impl AsRef<[u8]>) -> Result<Component> { let code = engine.load_code_bytes(bytes.as_ref(), ObjectKind::Component)?; Component::from_parts(engine, code, None) } /// Same as [`Module::deserialize_file`], but for components. /// /// For more information see the [`Component::deserialize`] and /// [`Module::deserialize_file`] methods. /// /// [`Module::deserialize_file`]: crate::Module::deserialize_file pub unsafe fn deserialize_file(engine: &Engine, path: impl AsRef<Path>) -> Result<Component> { let code = engine.load_code_file(path.as_ref(), ObjectKind::Component)?; Component::from_parts(engine, code, None) } /// Performs the compilation phase for a component, translating and /// validating the provided wasm binary to machine code. /// /// This method will compile all nested core wasm binaries in addition to /// any necessary extra functions required for operation with components. /// The output artifact here is the serialized object file contained within /// an owned mmap along with metadata about the compilation itself. #[cfg(compiler)] pub(crate) fn build_artifacts( engine: &Engine, binary: &[u8], ) -> Result<(MmapVec, ComponentArtifacts)> { let tunables = &engine.config().tunables; let compiler = engine.compiler(); let scope = ScopeVec::new(); let mut validator = wasmparser::Validator::new_with_features(engine.config().features.clone()); let mut types = Default::default(); let (component, mut modules) = Translator::new(tunables, &mut validator, &mut types, &scope) .translate(binary) .context("failed to parse WebAssembly module")?; let types = types.finish(); // Compile all core wasm modules, in parallel, which will internally // compile all their functions in parallel as well. let module_funcs = engine.run_maybe_parallel(modules.values_mut().collect(), |module| { Module::compile_functions(engine, module, types.module_types()) })?; // Compile all host-to-wasm trampolines where the required set of // trampolines is unioned from all core wasm modules plus what the // component itself needs. let module_trampolines = modules .iter() .flat_map(|(_, m)| m.exported_signatures.iter().copied()) .collect::<BTreeSet<_>>(); let trampolines = module_trampolines .iter() .copied() .chain( // All lowered functions will require a trampoline to be available in // case they're used when entering wasm. For example a lowered function // could be immediately lifted in which case we'll need a trampoline to // call that lowered function. // // Most of the time trampolines can come from the core wasm modules // since lifted functions come from core wasm. For these esoteric cases // though we may have to compile trampolines specifically into the // component object as well in case core wasm doesn't provide the // necessary trampoline. component.initializers.iter().filter_map(|init| match init { GlobalInitializer::LowerImport(i) => Some(i.canonical_abi), GlobalInitializer::AlwaysTrap(i) => Some(i.canonical_abi), _ => None, }), ) .collect::<BTreeSet<_>>(); let compiled_trampolines = engine .run_maybe_parallel(trampolines.iter().cloned().collect(), |i| { compiler.compile_host_to_wasm_trampoline(&types[i]) })?; // Compile all transcoders required which adapt from a // core-wasm-specific ABI (e.g. 32 or 64-bit) into the host transcoder // ABI through an indirect libcall. let transcoders = component .initializers .iter() .filter_map(|init| match init { GlobalInitializer::Transcoder(i) => Some(i), _ => None, }) .collect(); let transcoders = engine.run_maybe_parallel(transcoders, |info| { compiler .component_compiler() .compile_transcoder(&component, info, &types) })?; // Compile all "always trap" functions which are small typed shims that // exits to solely trap immediately for components. let always_trap = component .initializers .iter() .filter_map(|init| match init { GlobalInitializer::AlwaysTrap(i) => Some(i), _ => None, }) .collect(); let always_trap = engine.run_maybe_parallel(always_trap, |info| { compiler .component_compiler() .compile_always_trap(&types[info.canonical_abi]) })?; // Compile all "lowerings" which are adapters that go from core wasm // into the host which will process the canonical ABI. let lowerings = component .initializers .iter() .filter_map(|init| match init { GlobalInitializer::LowerImport(i) => Some(i), _ => None, }) .collect(); let lowerings = engine.run_maybe_parallel(lowerings, |lowering| { compiler .component_compiler() .compile_lowered_trampoline(&component, lowering, &types) })?; // Collect the results of all of the function-based compilations above // into one large list of functions to get appended into the text // section of the final module. let mut funcs = Vec::new(); let mut module_func_start_index = Vec::new(); let mut func_index_to_module_index = Vec::new(); let mut func_infos = Vec::new(); for (i, list) in module_funcs.into_iter().enumerate() { module_func_start_index.push(func_index_to_module_index.len()); let mut infos = Vec::new(); for (j, (info, func)) in list.into_iter().enumerate() { func_index_to_module_index.push(i); let name = format!("_wasm{i}_function{j}"); funcs.push((name, func)); infos.push(info); } func_infos.push(infos); } for (sig, func) in trampolines.iter().zip(compiled_trampolines) { let name = format!("_wasm_trampoline{}", sig.as_u32()); funcs.push((name, func)); } let ntranscoders = transcoders.len(); for (i, func) in transcoders.into_iter().enumerate() { let name = format!("_wasm_component_transcoder{i}"); funcs.push((name, func)); } let nalways_trap = always_trap.len(); for (i, func) in always_trap.into_iter().enumerate() { let name = format!("_wasm_component_always_trap{i}"); funcs.push((name, func)); } let nlowerings = lowerings.len(); for (i, func) in lowerings.into_iter().enumerate() { let name = format!("_wasm_component_lowering{i}"); funcs.push((name, func)); } let mut object = compiler.object(ObjectKind::Component)?; let locs = compiler.append_code(&mut object, &funcs, tunables, &|i, idx| { // Map from the `i`th function which is requesting the relocation to // the index in `modules` that the function belongs to. Using that // metadata we can resolve `idx: FuncIndex` to a `DefinedFuncIndex` // to the index of that module's function that's being called. // // Note that this will panic if `i` is a function beyond the initial // set of core wasm module functions. That's intentional, however, // since trampolines and otherwise should not have relocations to // resolve. let module_index = func_index_to_module_index[i]; let defined_index = modules[StaticModuleIndex::new(module_index)] .module .defined_func_index(idx) .unwrap(); // Additionally use the module index to determine where that // module's list of functions started at to factor in as an offset // as well. let offset = module_func_start_index[module_index]; defined_index.index() + offset })?; engine.append_compiler_info(&mut object); engine.append_bti(&mut object); // Disassemble the result of the appending to the text section, where // each function is in the module, into respective maps. let mut locs = locs.into_iter().map(|(_sym, loc)| loc); let funcs = func_infos .into_iter() .map(|infos| { infos .into_iter() .zip(&mut locs) .collect::<PrimaryMap<_, _>>() }) .collect::<Vec<_>>(); let signature_to_trampoline = trampolines .iter() .cloned() .zip(&mut locs) .collect::<HashMap<_, _>>(); let transcoders = locs .by_ref() .take(ntranscoders) .collect::<PrimaryMap<RuntimeTranscoderIndex, _>>(); let always_trap = locs .by_ref() .take(nalways_trap) .collect::<PrimaryMap<RuntimeAlwaysTrapIndex, _>>(); let lowerings = locs .by_ref() .take(nlowerings) .collect::<PrimaryMap<LoweredIndex, _>>(); assert!(locs.next().is_none()); // Convert all `ModuleTranslation` instances into `CompiledModuleInfo` // through an `ObjectBuilder` here. This is then used to create the // final `mmap` which is the final compilation artifact. let mut builder = wasmtime_jit::ObjectBuilder::new(object, tunables); let mut static_modules = PrimaryMap::new(); for ((_, module), funcs) in modules.into_iter().zip(funcs) { // Build the list of trampolines for this module from its set of // exported signatures, which is the list of expected trampolines, // from the set of trampolines that were compiled for everything // within this component. let trampolines = module .exported_signatures .iter() .map(|sig| (*sig, signature_to_trampoline[sig])) .collect(); let info = builder.append(module, funcs, trampolines)?; static_modules.push(info); } let info = CompiledComponentInfo { always_trap, component, lowerings, trampolines: trampolines .difference(&module_trampolines) .map(|i| (*i, signature_to_trampoline[i])) .collect(), transcoders, }; let artifacts = ComponentArtifacts { info, types, static_modules, }; builder.serialize_info(&artifacts); let mmap = builder.finish()?; Ok((mmap, artifacts)) } /// Final assembly step for a component from its in-memory representation. /// /// If the `artifacts` are specified as `None` here then they will be /// deserialized from `code_memory`. fn from_parts( engine: &Engine, code_memory: Arc<CodeMemory>, artifacts: Option<ComponentArtifacts>, ) -> Result<Component> { let ComponentArtifacts { info, types, static_modules, } = match artifacts { Some(artifacts) => artifacts, None => bincode::deserialize(code_memory.wasmtime_info())?, }; // Create a signature registration with the `Engine` for all trampolines // and core wasm types found within this component, both for the // component and for all included core wasm modules. let signatures = SignatureCollection::new_for_module( engine.signatures(), types.module_types(), static_modules .iter() .flat_map(|(_, m)| m.trampolines.iter().copied()) .chain(info.trampolines.iter().copied()) .map(|(sig, loc)| { let trampoline = code_memory.text()[loc.start as usize..].as_ptr(); (sig, unsafe { mem::transmute::<*const u8, VMTrampoline>(trampoline) }) }), ); // Assemble the `CodeObject` artifact which is shared by all core wasm // modules as well as the final component. let types = Arc::new(types); let code = Arc::new(CodeObject::new(code_memory, signatures, types.into())); // Convert all information about static core wasm modules into actual // `Module` instances by converting each `CompiledModuleInfo`, the // `types` type information, and the code memory to a runtime object. let static_modules = static_modules .into_iter() .map(|(_, info)| Module::from_parts_raw(engine, code.clone(), info, false)) .collect::<Result<_>>()?; Ok(Component { inner: Arc::new(ComponentInner { static_modules, code, info, }), }) } pub(crate) fn env_component(&self) -> &wasmtime_environ::component::Component { &self.inner.info.component } pub(crate) fn static_module(&self, idx: StaticModuleIndex) -> &Module { &self.inner.static_modules[idx] } pub(crate) fn types(&self) -> &Arc<ComponentTypes>
pub(crate) fn signatures(&self) -> &SignatureCollection { self.inner.code.signatures() } pub(crate) fn text(&self) -> &[u8] { self.inner.code.code_memory().text() } pub(crate) fn lowering_ptr(&self, index: LoweredIndex) -> NonNull<VMFunctionBody> { let info = &self.inner.info.lowerings[index]; self.func(info) } pub(crate) fn always_trap_ptr(&self, index: RuntimeAlwaysTrapIndex) -> NonNull<VMFunctionBody> { let loc = &self.inner.info.always_trap[index]; self.func(loc)
{ match self.inner.code.types() { crate::code::Types::Component(types) => types, // The only creator of a `Component` is itself which uses the other // variant, so this shouldn't be possible. crate::code::Types::Module(_) => unreachable!(), } }
identifier_body
component.rs
Index}; use wasmtime_jit::{CodeMemory, CompiledModuleInfo}; use wasmtime_runtime::{MmapVec, VMFunctionBody, VMTrampoline}; /// A compiled WebAssembly Component. // // FIXME: need to write more docs here. #[derive(Clone)] pub struct Component { inner: Arc<ComponentInner>, } struct ComponentInner { /// Core wasm modules that the component defined internally, indexed by the /// compile-time-assigned `ModuleUpvarIndex`. static_modules: PrimaryMap<StaticModuleIndex, Module>, /// Code-related information such as the compiled artifact, type /// information, etc. /// /// Note that the `Arc` here is used to share this allocation with internal /// modules. code: Arc<CodeObject>, /// Metadata produced during compilation. info: CompiledComponentInfo, } #[derive(Serialize, Deserialize)] struct CompiledComponentInfo { /// Type information calculated during translation about this component. component: wasmtime_environ::component::Component, /// Where lowered function trampolines are located within the `text` /// section of `code_memory`. /// /// These trampolines are the function pointer within the /// `VMCallerCheckedFuncRef` and will delegate indirectly to a host function /// pointer when called. lowerings: PrimaryMap<LoweredIndex, FunctionLoc>, /// Where the "always trap" functions are located within the `text` section /// of `code_memory`. /// /// These functions are "degenerate functions" here solely to implement /// functions that are `canon lift`'d then immediately `canon lower`'d. The /// `u32` value here is the offset of the trap instruction from the start fo /// the function. always_trap: PrimaryMap<RuntimeAlwaysTrapIndex, FunctionLoc>, /// Where all the cranelift-generated transcode functions are located in the /// compiled image of this component. transcoders: PrimaryMap<RuntimeTranscoderIndex, FunctionLoc>, /// Extra trampolines other than those contained in static modules /// necessary for this component. trampolines: Vec<(SignatureIndex, FunctionLoc)>, } #[derive(Serialize, Deserialize)] pub(crate) struct ComponentArtifacts { info: CompiledComponentInfo, types: ComponentTypes, static_modules: PrimaryMap<StaticModuleIndex, CompiledModuleInfo>, } impl Component { /// Compiles a new WebAssembly component from the in-memory wasm image /// provided. // // FIXME: need to write more docs here. #[cfg(compiler)] #[cfg_attr(nightlydoc, doc(cfg(feature = "cranelift")))] // see build.rs pub fn new(engine: &Engine, bytes: impl AsRef<[u8]>) -> Result<Component> { let bytes = bytes.as_ref(); #[cfg(feature = "wat")] let bytes = wat::parse_bytes(bytes)?; Component::from_binary(engine, &bytes) } /// Compiles a new WebAssembly component from a wasm file on disk pointed to /// by `file`. // // FIXME: need to write more docs here. #[cfg(compiler)] #[cfg_attr(nightlydoc, doc(cfg(feature = "cranelift")))] // see build.rs pub fn from_file(engine: &Engine, file: impl AsRef<Path>) -> Result<Component> { match Self::new( engine, &fs::read(&file).with_context(|| "failed to read input file")?, ) { Ok(m) => Ok(m), Err(e) => { cfg_if::cfg_if! { if #[cfg(feature = "wat")] { let mut e = e.downcast::<wat::Error>()?; e.set_path(file); bail!(e) } else { Err(e) } } } } } /// Compiles a new WebAssembly component from the in-memory wasm image /// provided. // // FIXME: need to write more docs here. #[cfg(compiler)] #[cfg_attr(nightlydoc, doc(cfg(feature = "cranelift")))] // see build.rs pub fn from_binary(engine: &Engine, binary: &[u8]) -> Result<Component> { engine .check_compatible_with_native_host() .context("compilation settings are not compatible with the native host")?; let (mmap, artifacts) = Component::build_artifacts(engine, binary)?; let mut code_memory = CodeMemory::new(mmap)?; code_memory.publish()?; Component::from_parts(engine, Arc::new(code_memory), Some(artifacts)) } /// Same as [`Module::deserialize`], but for components. /// /// Note that the file referenced here must contain contents previously /// produced by [`Engine::precompile_component`] or /// [`Component::serialize`]. /// /// For more information see the [`Module::deserialize`] method. /// /// [`Module::deserialize`]: crate::Module::deserialize pub unsafe fn deserialize(engine: &Engine, bytes: impl AsRef<[u8]>) -> Result<Component> { let code = engine.load_code_bytes(bytes.as_ref(), ObjectKind::Component)?; Component::from_parts(engine, code, None) } /// Same as [`Module::deserialize_file`], but for components. /// /// For more information see the [`Component::deserialize`] and /// [`Module::deserialize_file`] methods. /// /// [`Module::deserialize_file`]: crate::Module::deserialize_file pub unsafe fn deserialize_file(engine: &Engine, path: impl AsRef<Path>) -> Result<Component> { let code = engine.load_code_file(path.as_ref(), ObjectKind::Component)?; Component::from_parts(engine, code, None) } /// Performs the compilation phase for a component, translating and /// validating the provided wasm binary to machine code. /// /// This method will compile all nested core wasm binaries in addition to /// any necessary extra functions required for operation with components. /// The output artifact here is the serialized object file contained within /// an owned mmap along with metadata about the compilation itself. #[cfg(compiler)] pub(crate) fn build_artifacts( engine: &Engine, binary: &[u8], ) -> Result<(MmapVec, ComponentArtifacts)> { let tunables = &engine.config().tunables; let compiler = engine.compiler(); let scope = ScopeVec::new(); let mut validator = wasmparser::Validator::new_with_features(engine.config().features.clone()); let mut types = Default::default(); let (component, mut modules) = Translator::new(tunables, &mut validator, &mut types, &scope) .translate(binary) .context("failed to parse WebAssembly module")?; let types = types.finish(); // Compile all core wasm modules, in parallel, which will internally // compile all their functions in parallel as well. let module_funcs = engine.run_maybe_parallel(modules.values_mut().collect(), |module| { Module::compile_functions(engine, module, types.module_types()) })?; // Compile all host-to-wasm trampolines where the required set of // trampolines is unioned from all core wasm modules plus what the // component itself needs. let module_trampolines = modules .iter() .flat_map(|(_, m)| m.exported_signatures.iter().copied()) .collect::<BTreeSet<_>>(); let trampolines = module_trampolines .iter() .copied() .chain( // All lowered functions will require a trampoline to be available in // case they're used when entering wasm. For example a lowered function // could be immediately lifted in which case we'll need a trampoline to // call that lowered function. // // Most of the time trampolines can come from the core wasm modules // since lifted functions come from core wasm. For these esoteric cases // though we may have to compile trampolines specifically into the // component object as well in case core wasm doesn't provide the // necessary trampoline. component.initializers.iter().filter_map(|init| match init { GlobalInitializer::LowerImport(i) => Some(i.canonical_abi), GlobalInitializer::AlwaysTrap(i) => Some(i.canonical_abi), _ => None, }), ) .collect::<BTreeSet<_>>(); let compiled_trampolines = engine .run_maybe_parallel(trampolines.iter().cloned().collect(), |i| { compiler.compile_host_to_wasm_trampoline(&types[i]) })?; // Compile all transcoders required which adapt from a // core-wasm-specific ABI (e.g. 32 or 64-bit) into the host transcoder // ABI through an indirect libcall. let transcoders = component .initializers .iter() .filter_map(|init| match init { GlobalInitializer::Transcoder(i) => Some(i), _ => None, }) .collect(); let transcoders = engine.run_maybe_parallel(transcoders, |info| { compiler .component_compiler() .compile_transcoder(&component, info, &types) })?; // Compile all "always trap" functions which are small typed shims that // exits to solely trap immediately for components. let always_trap = component .initializers .iter() .filter_map(|init| match init { GlobalInitializer::AlwaysTrap(i) => Some(i), _ => None, }) .collect(); let always_trap = engine.run_maybe_parallel(always_trap, |info| { compiler .component_compiler() .compile_always_trap(&types[info.canonical_abi]) })?; // Compile all "lowerings" which are adapters that go from core wasm // into the host which will process the canonical ABI. let lowerings = component .initializers .iter() .filter_map(|init| match init { GlobalInitializer::LowerImport(i) => Some(i), _ => None, }) .collect(); let lowerings = engine.run_maybe_parallel(lowerings, |lowering| { compiler .component_compiler() .compile_lowered_trampoline(&component, lowering, &types) })?; // Collect the results of all of the function-based compilations above // into one large list of functions to get appended into the text // section of the final module. let mut funcs = Vec::new(); let mut module_func_start_index = Vec::new(); let mut func_index_to_module_index = Vec::new(); let mut func_infos = Vec::new(); for (i, list) in module_funcs.into_iter().enumerate() { module_func_start_index.push(func_index_to_module_index.len()); let mut infos = Vec::new(); for (j, (info, func)) in list.into_iter().enumerate() { func_index_to_module_index.push(i); let name = format!("_wasm{i}_function{j}"); funcs.push((name, func)); infos.push(info); } func_infos.push(infos); } for (sig, func) in trampolines.iter().zip(compiled_trampolines) { let name = format!("_wasm_trampoline{}", sig.as_u32()); funcs.push((name, func)); } let ntranscoders = transcoders.len(); for (i, func) in transcoders.into_iter().enumerate() { let name = format!("_wasm_component_transcoder{i}"); funcs.push((name, func)); } let nalways_trap = always_trap.len(); for (i, func) in always_trap.into_iter().enumerate() { let name = format!("_wasm_component_always_trap{i}"); funcs.push((name, func)); } let nlowerings = lowerings.len(); for (i, func) in lowerings.into_iter().enumerate() { let name = format!("_wasm_component_lowering{i}"); funcs.push((name, func)); } let mut object = compiler.object(ObjectKind::Component)?; let locs = compiler.append_code(&mut object, &funcs, tunables, &|i, idx| { // Map from the `i`th function which is requesting the relocation to // the index in `modules` that the function belongs to. Using that // metadata we can resolve `idx: FuncIndex` to a `DefinedFuncIndex` // to the index of that module's function that's being called. // // Note that this will panic if `i` is a function beyond the initial // set of core wasm module functions. That's intentional, however, // since trampolines and otherwise should not have relocations to // resolve. let module_index = func_index_to_module_index[i]; let defined_index = modules[StaticModuleIndex::new(module_index)] .module .defined_func_index(idx) .unwrap(); // Additionally use the module index to determine where that // module's list of functions started at to factor in as an offset // as well. let offset = module_func_start_index[module_index]; defined_index.index() + offset })?; engine.append_compiler_info(&mut object); engine.append_bti(&mut object); // Disassemble the result of the appending to the text section, where // each function is in the module, into respective maps. let mut locs = locs.into_iter().map(|(_sym, loc)| loc); let funcs = func_infos .into_iter() .map(|infos| { infos .into_iter() .zip(&mut locs) .collect::<PrimaryMap<_, _>>() }) .collect::<Vec<_>>(); let signature_to_trampoline = trampolines .iter() .cloned() .zip(&mut locs) .collect::<HashMap<_, _>>(); let transcoders = locs .by_ref() .take(ntranscoders) .collect::<PrimaryMap<RuntimeTranscoderIndex, _>>(); let always_trap = locs .by_ref() .take(nalways_trap) .collect::<PrimaryMap<RuntimeAlwaysTrapIndex, _>>(); let lowerings = locs .by_ref() .take(nlowerings) .collect::<PrimaryMap<LoweredIndex, _>>(); assert!(locs.next().is_none()); // Convert all `ModuleTranslation` instances into `CompiledModuleInfo` // through an `ObjectBuilder` here. This is then used to create the // final `mmap` which is the final compilation artifact. let mut builder = wasmtime_jit::ObjectBuilder::new(object, tunables); let mut static_modules = PrimaryMap::new(); for ((_, module), funcs) in modules.into_iter().zip(funcs) { // Build the list of trampolines for this module from its set of // exported signatures, which is the list of expected trampolines, // from the set of trampolines that were compiled for everything // within this component. let trampolines = module .exported_signatures .iter() .map(|sig| (*sig, signature_to_trampoline[sig])) .collect(); let info = builder.append(module, funcs, trampolines)?; static_modules.push(info); } let info = CompiledComponentInfo { always_trap, component, lowerings, trampolines: trampolines .difference(&module_trampolines) .map(|i| (*i, signature_to_trampoline[i])) .collect(), transcoders, }; let artifacts = ComponentArtifacts { info, types, static_modules, }; builder.serialize_info(&artifacts); let mmap = builder.finish()?; Ok((mmap, artifacts)) } /// Final assembly step for a component from its in-memory representation. /// /// If the `artifacts` are specified as `None` here then they will be /// deserialized from `code_memory`. fn from_parts( engine: &Engine, code_memory: Arc<CodeMemory>, artifacts: Option<ComponentArtifacts>, ) -> Result<Component> { let ComponentArtifacts { info, types, static_modules, } = match artifacts { Some(artifacts) => artifacts, None => bincode::deserialize(code_memory.wasmtime_info())?, }; // Create a signature registration with the `Engine` for all trampolines // and core wasm types found within this component, both for the // component and for all included core wasm modules. let signatures = SignatureCollection::new_for_module( engine.signatures(), types.module_types(), static_modules .iter() .flat_map(|(_, m)| m.trampolines.iter().copied()) .chain(info.trampolines.iter().copied()) .map(|(sig, loc)| { let trampoline = code_memory.text()[loc.start as usize..].as_ptr(); (sig, unsafe { mem::transmute::<*const u8, VMTrampoline>(trampoline) }) }), ); // Assemble the `CodeObject` artifact which is shared by all core wasm // modules as well as the final component. let types = Arc::new(types); let code = Arc::new(CodeObject::new(code_memory, signatures, types.into())); // Convert all information about static core wasm modules into actual // `Module` instances by converting each `CompiledModuleInfo`, the // `types` type information, and the code memory to a runtime object. let static_modules = static_modules .into_iter() .map(|(_, info)| Module::from_parts_raw(engine, code.clone(), info, false)) .collect::<Result<_>>()?; Ok(Component { inner: Arc::new(ComponentInner { static_modules, code, info, }), }) } pub(crate) fn env_component(&self) -> &wasmtime_environ::component::Component { &self.inner.info.component } pub(crate) fn static_module(&self, idx: StaticModuleIndex) -> &Module { &self.inner.static_modules[idx] } pub(crate) fn types(&self) -> &Arc<ComponentTypes> { match self.inner.code.types() { crate::code::Types::Component(types) => types, // The only creator of a `Component` is itself which uses the other // variant, so this shouldn't be possible. crate::code::Types::Module(_) => unreachable!(), } } pub(crate) fn signatures(&self) -> &SignatureCollection { self.inner.code.signatures() } pub(crate) fn text(&self) -> &[u8] { self.inner.code.code_memory().text() } pub(crate) fn lowering_ptr(&self, index: LoweredIndex) -> NonNull<VMFunctionBody> {
let loc = &self.inner.info.always_trap[index]; self.func(loc)
let info = &self.inner.info.lowerings[index]; self.func(info) } pub(crate) fn always_trap_ptr(&self, index: RuntimeAlwaysTrapIndex) -> NonNull<VMFunctionBody> {
random_line_split
component.rs
}; use wasmtime_jit::{CodeMemory, CompiledModuleInfo}; use wasmtime_runtime::{MmapVec, VMFunctionBody, VMTrampoline}; /// A compiled WebAssembly Component. // // FIXME: need to write more docs here. #[derive(Clone)] pub struct Component { inner: Arc<ComponentInner>, } struct ComponentInner { /// Core wasm modules that the component defined internally, indexed by the /// compile-time-assigned `ModuleUpvarIndex`. static_modules: PrimaryMap<StaticModuleIndex, Module>, /// Code-related information such as the compiled artifact, type /// information, etc. /// /// Note that the `Arc` here is used to share this allocation with internal /// modules. code: Arc<CodeObject>, /// Metadata produced during compilation. info: CompiledComponentInfo, } #[derive(Serialize, Deserialize)] struct CompiledComponentInfo { /// Type information calculated during translation about this component. component: wasmtime_environ::component::Component, /// Where lowered function trampolines are located within the `text` /// section of `code_memory`. /// /// These trampolines are the function pointer within the /// `VMCallerCheckedFuncRef` and will delegate indirectly to a host function /// pointer when called. lowerings: PrimaryMap<LoweredIndex, FunctionLoc>, /// Where the "always trap" functions are located within the `text` section /// of `code_memory`. /// /// These functions are "degenerate functions" here solely to implement /// functions that are `canon lift`'d then immediately `canon lower`'d. The /// `u32` value here is the offset of the trap instruction from the start fo /// the function. always_trap: PrimaryMap<RuntimeAlwaysTrapIndex, FunctionLoc>, /// Where all the cranelift-generated transcode functions are located in the /// compiled image of this component. transcoders: PrimaryMap<RuntimeTranscoderIndex, FunctionLoc>, /// Extra trampolines other than those contained in static modules /// necessary for this component. trampolines: Vec<(SignatureIndex, FunctionLoc)>, } #[derive(Serialize, Deserialize)] pub(crate) struct ComponentArtifacts { info: CompiledComponentInfo, types: ComponentTypes, static_modules: PrimaryMap<StaticModuleIndex, CompiledModuleInfo>, } impl Component { /// Compiles a new WebAssembly component from the in-memory wasm image /// provided. // // FIXME: need to write more docs here. #[cfg(compiler)] #[cfg_attr(nightlydoc, doc(cfg(feature = "cranelift")))] // see build.rs pub fn new(engine: &Engine, bytes: impl AsRef<[u8]>) -> Result<Component> { let bytes = bytes.as_ref(); #[cfg(feature = "wat")] let bytes = wat::parse_bytes(bytes)?; Component::from_binary(engine, &bytes) } /// Compiles a new WebAssembly component from a wasm file on disk pointed to /// by `file`. // // FIXME: need to write more docs here. #[cfg(compiler)] #[cfg_attr(nightlydoc, doc(cfg(feature = "cranelift")))] // see build.rs pub fn from_file(engine: &Engine, file: impl AsRef<Path>) -> Result<Component> { match Self::new( engine, &fs::read(&file).with_context(|| "failed to read input file")?, ) { Ok(m) => Ok(m), Err(e) => { cfg_if::cfg_if! { if #[cfg(feature = "wat")] { let mut e = e.downcast::<wat::Error>()?; e.set_path(file); bail!(e) } else { Err(e) } } } } } /// Compiles a new WebAssembly component from the in-memory wasm image /// provided. // // FIXME: need to write more docs here. #[cfg(compiler)] #[cfg_attr(nightlydoc, doc(cfg(feature = "cranelift")))] // see build.rs pub fn from_binary(engine: &Engine, binary: &[u8]) -> Result<Component> { engine .check_compatible_with_native_host() .context("compilation settings are not compatible with the native host")?; let (mmap, artifacts) = Component::build_artifacts(engine, binary)?; let mut code_memory = CodeMemory::new(mmap)?; code_memory.publish()?; Component::from_parts(engine, Arc::new(code_memory), Some(artifacts)) } /// Same as [`Module::deserialize`], but for components. /// /// Note that the file referenced here must contain contents previously /// produced by [`Engine::precompile_component`] or /// [`Component::serialize`]. /// /// For more information see the [`Module::deserialize`] method. /// /// [`Module::deserialize`]: crate::Module::deserialize pub unsafe fn deserialize(engine: &Engine, bytes: impl AsRef<[u8]>) -> Result<Component> { let code = engine.load_code_bytes(bytes.as_ref(), ObjectKind::Component)?; Component::from_parts(engine, code, None) } /// Same as [`Module::deserialize_file`], but for components. /// /// For more information see the [`Component::deserialize`] and /// [`Module::deserialize_file`] methods. /// /// [`Module::deserialize_file`]: crate::Module::deserialize_file pub unsafe fn deserialize_file(engine: &Engine, path: impl AsRef<Path>) -> Result<Component> { let code = engine.load_code_file(path.as_ref(), ObjectKind::Component)?; Component::from_parts(engine, code, None) } /// Performs the compilation phase for a component, translating and /// validating the provided wasm binary to machine code. /// /// This method will compile all nested core wasm binaries in addition to /// any necessary extra functions required for operation with components. /// The output artifact here is the serialized object file contained within /// an owned mmap along with metadata about the compilation itself. #[cfg(compiler)] pub(crate) fn build_artifacts( engine: &Engine, binary: &[u8], ) -> Result<(MmapVec, ComponentArtifacts)> { let tunables = &engine.config().tunables; let compiler = engine.compiler(); let scope = ScopeVec::new(); let mut validator = wasmparser::Validator::new_with_features(engine.config().features.clone()); let mut types = Default::default(); let (component, mut modules) = Translator::new(tunables, &mut validator, &mut types, &scope) .translate(binary) .context("failed to parse WebAssembly module")?; let types = types.finish(); // Compile all core wasm modules, in parallel, which will internally // compile all their functions in parallel as well. let module_funcs = engine.run_maybe_parallel(modules.values_mut().collect(), |module| { Module::compile_functions(engine, module, types.module_types()) })?; // Compile all host-to-wasm trampolines where the required set of // trampolines is unioned from all core wasm modules plus what the // component itself needs. let module_trampolines = modules .iter() .flat_map(|(_, m)| m.exported_signatures.iter().copied()) .collect::<BTreeSet<_>>(); let trampolines = module_trampolines .iter() .copied() .chain( // All lowered functions will require a trampoline to be available in // case they're used when entering wasm. For example a lowered function // could be immediately lifted in which case we'll need a trampoline to // call that lowered function. // // Most of the time trampolines can come from the core wasm modules // since lifted functions come from core wasm. For these esoteric cases // though we may have to compile trampolines specifically into the // component object as well in case core wasm doesn't provide the // necessary trampoline. component.initializers.iter().filter_map(|init| match init { GlobalInitializer::LowerImport(i) => Some(i.canonical_abi), GlobalInitializer::AlwaysTrap(i) => Some(i.canonical_abi), _ => None, }), ) .collect::<BTreeSet<_>>(); let compiled_trampolines = engine .run_maybe_parallel(trampolines.iter().cloned().collect(), |i| { compiler.compile_host_to_wasm_trampoline(&types[i]) })?; // Compile all transcoders required which adapt from a // core-wasm-specific ABI (e.g. 32 or 64-bit) into the host transcoder // ABI through an indirect libcall. let transcoders = component .initializers .iter() .filter_map(|init| match init { GlobalInitializer::Transcoder(i) => Some(i), _ => None, }) .collect(); let transcoders = engine.run_maybe_parallel(transcoders, |info| { compiler .component_compiler() .compile_transcoder(&component, info, &types) })?; // Compile all "always trap" functions which are small typed shims that // exits to solely trap immediately for components. let always_trap = component .initializers .iter() .filter_map(|init| match init { GlobalInitializer::AlwaysTrap(i) => Some(i), _ => None, }) .collect(); let always_trap = engine.run_maybe_parallel(always_trap, |info| { compiler .component_compiler() .compile_always_trap(&types[info.canonical_abi]) })?; // Compile all "lowerings" which are adapters that go from core wasm // into the host which will process the canonical ABI. let lowerings = component .initializers .iter() .filter_map(|init| match init { GlobalInitializer::LowerImport(i) => Some(i), _ => None, }) .collect(); let lowerings = engine.run_maybe_parallel(lowerings, |lowering| { compiler .component_compiler() .compile_lowered_trampoline(&component, lowering, &types) })?; // Collect the results of all of the function-based compilations above // into one large list of functions to get appended into the text // section of the final module. let mut funcs = Vec::new(); let mut module_func_start_index = Vec::new(); let mut func_index_to_module_index = Vec::new(); let mut func_infos = Vec::new(); for (i, list) in module_funcs.into_iter().enumerate() { module_func_start_index.push(func_index_to_module_index.len()); let mut infos = Vec::new(); for (j, (info, func)) in list.into_iter().enumerate() { func_index_to_module_index.push(i); let name = format!("_wasm{i}_function{j}"); funcs.push((name, func)); infos.push(info); } func_infos.push(infos); } for (sig, func) in trampolines.iter().zip(compiled_trampolines) { let name = format!("_wasm_trampoline{}", sig.as_u32()); funcs.push((name, func)); } let ntranscoders = transcoders.len(); for (i, func) in transcoders.into_iter().enumerate() { let name = format!("_wasm_component_transcoder{i}"); funcs.push((name, func)); } let nalways_trap = always_trap.len(); for (i, func) in always_trap.into_iter().enumerate() { let name = format!("_wasm_component_always_trap{i}"); funcs.push((name, func)); } let nlowerings = lowerings.len(); for (i, func) in lowerings.into_iter().enumerate() { let name = format!("_wasm_component_lowering{i}"); funcs.push((name, func)); } let mut object = compiler.object(ObjectKind::Component)?; let locs = compiler.append_code(&mut object, &funcs, tunables, &|i, idx| { // Map from the `i`th function which is requesting the relocation to // the index in `modules` that the function belongs to. Using that // metadata we can resolve `idx: FuncIndex` to a `DefinedFuncIndex` // to the index of that module's function that's being called. // // Note that this will panic if `i` is a function beyond the initial // set of core wasm module functions. That's intentional, however, // since trampolines and otherwise should not have relocations to // resolve. let module_index = func_index_to_module_index[i]; let defined_index = modules[StaticModuleIndex::new(module_index)] .module .defined_func_index(idx) .unwrap(); // Additionally use the module index to determine where that // module's list of functions started at to factor in as an offset // as well. let offset = module_func_start_index[module_index]; defined_index.index() + offset })?; engine.append_compiler_info(&mut object); engine.append_bti(&mut object); // Disassemble the result of the appending to the text section, where // each function is in the module, into respective maps. let mut locs = locs.into_iter().map(|(_sym, loc)| loc); let funcs = func_infos .into_iter() .map(|infos| { infos .into_iter() .zip(&mut locs) .collect::<PrimaryMap<_, _>>() }) .collect::<Vec<_>>(); let signature_to_trampoline = trampolines .iter() .cloned() .zip(&mut locs) .collect::<HashMap<_, _>>(); let transcoders = locs .by_ref() .take(ntranscoders) .collect::<PrimaryMap<RuntimeTranscoderIndex, _>>(); let always_trap = locs .by_ref() .take(nalways_trap) .collect::<PrimaryMap<RuntimeAlwaysTrapIndex, _>>(); let lowerings = locs .by_ref() .take(nlowerings) .collect::<PrimaryMap<LoweredIndex, _>>(); assert!(locs.next().is_none()); // Convert all `ModuleTranslation` instances into `CompiledModuleInfo` // through an `ObjectBuilder` here. This is then used to create the // final `mmap` which is the final compilation artifact. let mut builder = wasmtime_jit::ObjectBuilder::new(object, tunables); let mut static_modules = PrimaryMap::new(); for ((_, module), funcs) in modules.into_iter().zip(funcs) { // Build the list of trampolines for this module from its set of // exported signatures, which is the list of expected trampolines, // from the set of trampolines that were compiled for everything // within this component. let trampolines = module .exported_signatures .iter() .map(|sig| (*sig, signature_to_trampoline[sig])) .collect(); let info = builder.append(module, funcs, trampolines)?; static_modules.push(info); } let info = CompiledComponentInfo { always_trap, component, lowerings, trampolines: trampolines .difference(&module_trampolines) .map(|i| (*i, signature_to_trampoline[i])) .collect(), transcoders, }; let artifacts = ComponentArtifacts { info, types, static_modules, }; builder.serialize_info(&artifacts); let mmap = builder.finish()?; Ok((mmap, artifacts)) } /// Final assembly step for a component from its in-memory representation. /// /// If the `artifacts` are specified as `None` here then they will be /// deserialized from `code_memory`. fn from_parts( engine: &Engine, code_memory: Arc<CodeMemory>, artifacts: Option<ComponentArtifacts>, ) -> Result<Component> { let ComponentArtifacts { info, types, static_modules, } = match artifacts { Some(artifacts) => artifacts, None => bincode::deserialize(code_memory.wasmtime_info())?, }; // Create a signature registration with the `Engine` for all trampolines // and core wasm types found within this component, both for the // component and for all included core wasm modules. let signatures = SignatureCollection::new_for_module( engine.signatures(), types.module_types(), static_modules .iter() .flat_map(|(_, m)| m.trampolines.iter().copied()) .chain(info.trampolines.iter().copied()) .map(|(sig, loc)| { let trampoline = code_memory.text()[loc.start as usize..].as_ptr(); (sig, unsafe { mem::transmute::<*const u8, VMTrampoline>(trampoline) }) }), ); // Assemble the `CodeObject` artifact which is shared by all core wasm // modules as well as the final component. let types = Arc::new(types); let code = Arc::new(CodeObject::new(code_memory, signatures, types.into())); // Convert all information about static core wasm modules into actual // `Module` instances by converting each `CompiledModuleInfo`, the // `types` type information, and the code memory to a runtime object. let static_modules = static_modules .into_iter() .map(|(_, info)| Module::from_parts_raw(engine, code.clone(), info, false)) .collect::<Result<_>>()?; Ok(Component { inner: Arc::new(ComponentInner { static_modules, code, info, }), }) } pub(crate) fn env_component(&self) -> &wasmtime_environ::component::Component { &self.inner.info.component } pub(crate) fn static_module(&self, idx: StaticModuleIndex) -> &Module { &self.inner.static_modules[idx] } pub(crate) fn types(&self) -> &Arc<ComponentTypes> { match self.inner.code.types() { crate::code::Types::Component(types) => types, // The only creator of a `Component` is itself which uses the other // variant, so this shouldn't be possible. crate::code::Types::Module(_) => unreachable!(), } } pub(crate) fn signatures(&self) -> &SignatureCollection { self.inner.code.signatures() } pub(crate) fn
(&self) -> &[u8] { self.inner.code.code_memory().text() } pub(crate) fn lowering_ptr(&self, index: LoweredIndex) -> NonNull<VMFunctionBody> { let info = &self.inner.info.lowerings[index]; self.func(info) } pub(crate) fn always_trap_ptr(&self, index: RuntimeAlwaysTrapIndex) -> NonNull<VMFunctionBody> { let loc = &self.inner.info.always_trap[index]; self.func(loc)
text
identifier_name
lib.rs
//! # L2 //!# What is L2? //! //!> L2 is named after the L2 or Euclidean distance, a popular distance function in deep learning //! //!L2 is a Pytorch-style Tensor+Autograd library written in the Rust programming language. It contains a multidimensional array class, `Tensor`, with support for strided arrays, numpy-style array slicing, //!broadcasting, and most major math operations (including fast, BLAS-accelerated matrix multiplication!). On top of this, L2 has a built-in efficient graph-based autograd engine that keeps track of all //!operations performed on a tensor and topologically sorts and traverses the graph to compute the gradients. //! //!I also made a more simplified C++ version of l2 last year, which you can take a look at [here](https://github.com/bilal2vec/L2/tree/c%2B%2B) //! //!# Example //! //!```rust //!use l2::tensor::*; //! //!fn main() -> Result<(), l2::errors::TensorError> { //! let x: Tensor = Tensor::normal(&[2, 4], 0.0, 1.0)?; //! let y: Tensor = Tensor::normal(&[4, 1], 0.0, 1.0)?; //! //! let z: Tensor = l2::matmul(&x, &y)?; //! //! z.backward(); //! //! println!("{}", z); //! //! Ok(()) //!} //!``` //! //!# Design choices //! //!I made L2 to get better at using Rust and to learn more about how libraries like Pytorch and Tensorflow work behind the scenes, so don't expect this library to be production-ready :) //! //!L2 is surprisingly fast especially since I didn't try very hard to optimize all the operators, it's usually only less than one order of magnitude slower than Pytorch in most of the benchmarks that I ran. L2 //!only supports a cpu backend at the moment since I'm not familiar enough with rust to start working with CUDA and cudnn. So far, l2 doesn't have any Pytorch-style abstractions like the Parameter, Layer, or //!Module classes. There might still be some bugs in the transpose operators and calling `.backward()` on tensors with more dimensions. I was interested in using Rust's [Const Generics](https://github.com/ //!rust-lang/rfcs/blob/master/text/2000-const-generics.md) to run compile-time shape checks but I decided to leave it until some other time. //! //!# Contributing //! //!This repository is still a work in progress, so if you find a bug, think there is something missing, or have any suggestions for new features, feel free to open an issue or a pull request. Feel free to use //!the library or code from it in your own projects, and if you feel that some code used in this project hasn't been properly accredited, please open an issue. //! //!# Authors //! //!- _Bilal Khan_ //! //!# License //! //!This project is licensed under the MIT License - see the license file for details //! //!# Acknowledgements //! //!The fast.ai deep learning from the foundations course (https://course.fast.ai/part2) teaches a lot about how to make your own deep learning library //! //!Some of the resources that I found useful when working on this library include: //! //!- http://blog.ezyang.com/2019/05/pytorch-internals/ //!- https://pytorch.org/tutorials/beginner/nn_tutorial.html //!- https://eisenjulian.github.io/deep-learning-in-100-lines/ //!- https://medium.com/@florian.caesar/how-to-create-a-machine-learning-framework-from-scratch-in-491-steps-93428369a4eb //!- https://medium.com/@johan.mabille/how-we-wrote-xtensor-1-n-n-dimensional-containers-f79f9f4966a7 //!- https://erikpartridge.com/2019-03/rust-ml-simd-blas-lapack //!- https://medium.com/@GolDDranks/things-rust-doesnt-let-you-do-draft-f596a3c740a5 //!- https://datascience.stackexchange.com/questions/20139/gradients-for-bias-terms-in-backpropagation //!- https://cs231n.github.io/optimization-2/ //!- https://cs231n.github.io/neural-networks-case-study/#grad //!- https://stackoverflow.com/questions/38082835/backpropagation-in-gradient-descent-for-neural-networks-vs-linear-regression //!- https://medium.com/@karpathy/yes-you-should-understand-backprop-e2f06eab496b //!- https://stackoverflow.com/questions/38082835/backpropagation-in-gradient-descent-for-neural-networks-vs-linear-regression //!- https://github.com/karpathy/micrograd //!- https://rufflewind.com/2016-12-30/reverse-mode-automatic-differentiation //! - https://github.com/ibab/rust-ad //! - https://github.com/Rufflewind/revad/blob/eb3978b3ccdfa8189f3ff59d1ecee71f51c33fd7/revad.py //! - https://github.com/srirambandi/ai //!- https://discuss.pytorch.org/t/is-pytorch-autograd-tape-based/13992/3 //!- https://www.reddit.com/r/MachineLearning/comments/8ep130/d_how_does_autograd_work/ //!- https://github.com/mattjj/autodidact //!- https://github.com/karpathy/recurrentjs //!- https://github.com/karpathy/randomfun //!- https://medium.com/@ralphmao95/simple-autograd-implementation-understand-automatic-differentiation-hand-by-hand-9e86f6d703ab //!- https://evcu.github.io/ml/autograd/ //!- https://blog.paperspace.com/pytorch-101-understanding-graphs-and-automatic-differentiation/ //!- https://github.com/maciejkula/wyrm //!- https://medium.com/@maciejkula/building-an-autodifferentiation-library-9ccf32c7a658 //!- https://github.com/evcu/numpy_autograd/blob/master/my_autograd.py#L147 //!- https://github.com/evcu/numpy_autograd/blob/master/Autograd.ipynb //!- https://cs231n.github.io/optimization-2/ //!- https://github.com/explosion/thinc //!- https://github.com/joelgrus/joelnet //!- https://github.com/QuantStack/xtensor //!- https://github.com/ThinkingTransistor/Sigma //!- https://github.com/mratsim/Arraymancer //!- https://github.com/siekmanj/sieknet //!- https://github.com/siekmanj/sieknet_2.0 //!- https://github.com/Daniel-Liu-c0deb0t/Java-Machine-Learning //!- https://github.com/karpathy/micrograd //! //!This README is based on: //! //!- https://github.com/bilal2vec/pytorch_zoo //!- https://github.com/bilal2vec/grover //!- https://github.com/rish-16/gpt2client //!- https://github.com/mxbi/mlcrate //!- https://github.com/athityakumar/colorls //!- https://github.com/amitmerchant1990/electron-markdownify //! //!I used carbon.now.sh with the "Shades of Purple" theme for the screenshot at the beginning of this README //! //!This project contains ~4300 lines of code pub mod errors; mod ops; pub mod tensor; use errors::TensorError; use tensor::Tensor; pub fn add<'a>(lhs: &'a Tensor, rhs: &'a Tensor) -> Tensor<'a> { lhs + rhs } pub fn sub<'a>(lhs: &'a Tensor, rhs: &'a Tensor) -> Tensor<'a> { lhs - rhs } pub fn mul<'a>(lhs: &'a Tensor, rhs: &'a Tensor) -> Tensor<'a> { lhs * rhs } pub fn div<'a>(lhs: &'a Tensor, rhs: &'a Tensor) -> Tensor<'a> { lhs / rhs } pub fn pow<'a>(lhs: &'a Tensor, exp: f32) -> Result<Tensor<'a>, TensorError> { lhs.pow(exp) } pub fn sqrt<'a>(lhs: &'a Tensor) -> Result<Tensor<'a>, TensorError> { lhs.sqrt() } pub fn exp<'a>(lhs: &'a Tensor) -> Result<Tensor<'a>, TensorError> { lhs.exp() } pub fn log10<'a>(lhs: &'a Tensor) -> Result<Tensor<'a>, TensorError> { lhs.log10() } pub fn log<'a>(lhs: &'a Tensor) -> Result<Tensor<'a>, TensorError> { lhs.log() } pub fn abs<'a>(lhs: &'a Tensor) -> Result<Tensor<'a>, TensorError> { lhs.abs() } pub fn sin<'a>(lhs: &'a Tensor) -> Result<Tensor<'a>, TensorError> { lhs.sin() } pub fn cos<'a>(lhs: &'a Tensor) -> Result<Tensor<'a>, TensorError> { lhs.cos() } pub fn tan<'a>(lhs: &'a Tensor) -> Result<Tensor<'a>, TensorError> { lhs.tan() } pub fn sum<'a>(lhs: &'a Tensor, dim: isize) -> Result<Tensor<'a>, TensorError> { lhs.sum(dim) } pub fn mean<'a>(lhs: &'a Tensor, dim: isize) -> Result<Tensor<'a>, TensorError> { lhs.mean(dim) } pub fn max<'a>(lhs: &'a Tensor, dim: isize) -> Result<Tensor<'a>, TensorError> { lhs.max(dim) } pub fn min<'a>(lhs: &'a Tensor, dim: isize) -> Result<Tensor<'a>, TensorError> { lhs.min(dim) } pub fn argmax<'a>(lhs: &'a Tensor, dim: isize) -> Result<Tensor<'a>, TensorError> { lhs.argmax(dim) } pub fn argmin<'a>(lhs: &'a Tensor, dim: isize) -> Result<Tensor<'a>, TensorError> { lhs.argmin(dim) } pub fn matmul<'a>(lhs: &'a Tensor, rhs: &'a Tensor) -> Result<Tensor<'a>, TensorError> { lhs.matmul(rhs) } pub fn concat<'a>(lhs: &'a Tensor, rhs: &'a Tensor, dim: isize) -> Result<Tensor<'a>, TensorError> { lhs.concat(&rhs, dim) } #[cfg(test)] mod tests { use super::tensor::*; use super::*; #[test] fn test_add() { let a = Tensor::new(vec![2.0, 3.0], &[2]).unwrap(); let b = Tensor::new(vec![2.0, 3.0], &[2]).unwrap(); let c = add(&a, &b); assert!((c.data == vec![4.0, 6.0]) && (c.shape == vec![2])) } #[test] fn test_subtract() { let a = Tensor::new(vec![2.0, 3.0], &[2]).unwrap(); let b = Tensor::new(vec![2.0, 3.0], &[2]).unwrap(); let c = sub(&a, &b); assert!((c.data == vec![0.0, 0.0]) && (c.shape == vec![2])) } #[test] fn test_mul() { let a = Tensor::new(vec![2.0, 3.0], &[2]).unwrap(); let b = Tensor::new(vec![2.0, 3.0], &[2]).unwrap(); let c = mul(&a, &b); assert!((c.data == vec![4.0, 9.0]) && (c.shape == vec![2])) } #[test] fn test_div() { let a = Tensor::new(vec![2.0, 3.0], &[2]).unwrap(); let b = Tensor::new(vec![2.0, 3.0], &[2]).unwrap(); let c = div(&a, &b); assert!((c.data == vec![1.0, 1.0]) && (c.shape == vec![2])) } #[test] fn test_pow() { let a = Tensor::new(vec![2.0, 3.0], &[2]).unwrap(); let c = pow(&a, 2.0).unwrap(); assert!((c.data == vec![4.0, 9.0]) && (c.shape == vec![2])) } #[test] fn
() { let a = Tensor::new(vec![2.0, 3.0], &[2]).unwrap(); let c = sum(&a, 0).unwrap(); assert!((c.data == vec![5.0]) && (c.shape == vec![1])) } #[test] fn test_mean() { let a = Tensor::new(vec![2.0, 3.0], &[2]).unwrap(); let c = mean(&a, 0).unwrap(); assert!((c.data == vec![2.5]) && (c.shape == vec![1])) } #[test] fn test_max() { let a = Tensor::new(vec![2.0, 3.0], &[2]).unwrap(); let c = max(&a, 0).unwrap(); assert!((c.data == vec![3.0]) && (c.shape == vec![1])) } #[test] fn test_min() { let a = Tensor::new(vec![2.0, 3.0], &[2]).unwrap(); let c = min(&a, 0).unwrap(); assert!((c.data == vec![2.0]) && (c.shape == vec![1])) } #[test] fn test_argmax() { let a = Tensor::new(vec![2.0, 3.0], &[2]).unwrap(); let c = argmax(&a, 0).unwrap(); assert!((c.data == vec![1.0]) && (c.shape == vec![1])) } #[test] fn test_argmin() { let a = Tensor::new(vec![2.0, 3.0], &[2]).unwrap(); let c = argmin(&a, 0).unwrap(); assert!((c.data == vec![0.0]) && (c.shape == vec![1])) } #[test] fn test_matmul() { let x = Tensor::new( vec![ 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, ], &[2, 2, 4], ) .unwrap(); let y = Tensor::new( vec![ 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, ], &[2, 4, 2], ) .unwrap(); let z = matmul(&x, &y).unwrap(); assert!( (z.data == vec![50.0, 60.0, 114.0, 140.0, 514.0, 556.0, 706.0, 764.0]) && (z.shape == vec![2, 2, 2]) ) } #[test] fn test_concat() { let x = Tensor::new( vec![ 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, ], &[2, 2, 2, 2], ) .unwrap(); let y = Tensor::new( vec![ 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, ], &[2, 2, 2, 2], ) .unwrap(); let z = concat(&x, &y, -1).unwrap(); assert!( (z.data == vec![ 1.0, 2.0, 1.0, 2.0, 3.0, 4.0, 3.0, 4.0, 5.0, 6.0, 5.0, 6.0, 7.0, 8.0, 7.0, 8.0, 9.0, 10.0, 9.0, 10.0, 11.0, 12.0, 11.0, 12.0, 13.0, 14.0, 13.0, 14.0, 15.0, 16.0, 15.0, 16.0 ]) && (z.shape == vec![2, 2, 2, 4]) ) } }
test_sum
identifier_name
lib.rs
//! # L2 //!# What is L2? //! //!> L2 is named after the L2 or Euclidean distance, a popular distance function in deep learning //! //!L2 is a Pytorch-style Tensor+Autograd library written in the Rust programming language. It contains a multidimensional array class, `Tensor`, with support for strided arrays, numpy-style array slicing, //!broadcasting, and most major math operations (including fast, BLAS-accelerated matrix multiplication!). On top of this, L2 has a built-in efficient graph-based autograd engine that keeps track of all //!operations performed on a tensor and topologically sorts and traverses the graph to compute the gradients. //! //!I also made a more simplified C++ version of l2 last year, which you can take a look at [here](https://github.com/bilal2vec/L2/tree/c%2B%2B) //! //!# Example //! //!```rust //!use l2::tensor::*; //! //!fn main() -> Result<(), l2::errors::TensorError> { //! let x: Tensor = Tensor::normal(&[2, 4], 0.0, 1.0)?; //! let y: Tensor = Tensor::normal(&[4, 1], 0.0, 1.0)?; //! //! let z: Tensor = l2::matmul(&x, &y)?; //! //! z.backward(); //! //! println!("{}", z); //! //! Ok(()) //!} //!``` //! //!# Design choices //! //!I made L2 to get better at using Rust and to learn more about how libraries like Pytorch and Tensorflow work behind the scenes, so don't expect this library to be production-ready :) //! //!L2 is surprisingly fast especially since I didn't try very hard to optimize all the operators, it's usually only less than one order of magnitude slower than Pytorch in most of the benchmarks that I ran. L2 //!only supports a cpu backend at the moment since I'm not familiar enough with rust to start working with CUDA and cudnn. So far, l2 doesn't have any Pytorch-style abstractions like the Parameter, Layer, or //!Module classes. There might still be some bugs in the transpose operators and calling `.backward()` on tensors with more dimensions. I was interested in using Rust's [Const Generics](https://github.com/ //!rust-lang/rfcs/blob/master/text/2000-const-generics.md) to run compile-time shape checks but I decided to leave it until some other time. //! //!# Contributing //! //!This repository is still a work in progress, so if you find a bug, think there is something missing, or have any suggestions for new features, feel free to open an issue or a pull request. Feel free to use //!the library or code from it in your own projects, and if you feel that some code used in this project hasn't been properly accredited, please open an issue. //! //!# Authors //! //!- _Bilal Khan_ //! //!# License //! //!This project is licensed under the MIT License - see the license file for details //! //!# Acknowledgements //! //!The fast.ai deep learning from the foundations course (https://course.fast.ai/part2) teaches a lot about how to make your own deep learning library //! //!Some of the resources that I found useful when working on this library include: //! //!- http://blog.ezyang.com/2019/05/pytorch-internals/ //!- https://pytorch.org/tutorials/beginner/nn_tutorial.html //!- https://eisenjulian.github.io/deep-learning-in-100-lines/ //!- https://medium.com/@florian.caesar/how-to-create-a-machine-learning-framework-from-scratch-in-491-steps-93428369a4eb //!- https://medium.com/@johan.mabille/how-we-wrote-xtensor-1-n-n-dimensional-containers-f79f9f4966a7 //!- https://erikpartridge.com/2019-03/rust-ml-simd-blas-lapack //!- https://medium.com/@GolDDranks/things-rust-doesnt-let-you-do-draft-f596a3c740a5 //!- https://datascience.stackexchange.com/questions/20139/gradients-for-bias-terms-in-backpropagation //!- https://cs231n.github.io/optimization-2/ //!- https://cs231n.github.io/neural-networks-case-study/#grad //!- https://stackoverflow.com/questions/38082835/backpropagation-in-gradient-descent-for-neural-networks-vs-linear-regression //!- https://medium.com/@karpathy/yes-you-should-understand-backprop-e2f06eab496b //!- https://stackoverflow.com/questions/38082835/backpropagation-in-gradient-descent-for-neural-networks-vs-linear-regression //!- https://github.com/karpathy/micrograd //!- https://rufflewind.com/2016-12-30/reverse-mode-automatic-differentiation //! - https://github.com/ibab/rust-ad //! - https://github.com/Rufflewind/revad/blob/eb3978b3ccdfa8189f3ff59d1ecee71f51c33fd7/revad.py //! - https://github.com/srirambandi/ai //!- https://discuss.pytorch.org/t/is-pytorch-autograd-tape-based/13992/3 //!- https://www.reddit.com/r/MachineLearning/comments/8ep130/d_how_does_autograd_work/ //!- https://github.com/mattjj/autodidact //!- https://github.com/karpathy/recurrentjs //!- https://github.com/karpathy/randomfun //!- https://medium.com/@ralphmao95/simple-autograd-implementation-understand-automatic-differentiation-hand-by-hand-9e86f6d703ab //!- https://evcu.github.io/ml/autograd/ //!- https://blog.paperspace.com/pytorch-101-understanding-graphs-and-automatic-differentiation/ //!- https://github.com/maciejkula/wyrm //!- https://medium.com/@maciejkula/building-an-autodifferentiation-library-9ccf32c7a658 //!- https://github.com/evcu/numpy_autograd/blob/master/my_autograd.py#L147 //!- https://github.com/evcu/numpy_autograd/blob/master/Autograd.ipynb //!- https://cs231n.github.io/optimization-2/ //!- https://github.com/explosion/thinc //!- https://github.com/joelgrus/joelnet //!- https://github.com/QuantStack/xtensor //!- https://github.com/ThinkingTransistor/Sigma //!- https://github.com/mratsim/Arraymancer //!- https://github.com/siekmanj/sieknet //!- https://github.com/siekmanj/sieknet_2.0 //!- https://github.com/Daniel-Liu-c0deb0t/Java-Machine-Learning //!- https://github.com/karpathy/micrograd //! //!This README is based on: //! //!- https://github.com/bilal2vec/pytorch_zoo //!- https://github.com/bilal2vec/grover //!- https://github.com/rish-16/gpt2client //!- https://github.com/mxbi/mlcrate //!- https://github.com/athityakumar/colorls //!- https://github.com/amitmerchant1990/electron-markdownify //! //!I used carbon.now.sh with the "Shades of Purple" theme for the screenshot at the beginning of this README //! //!This project contains ~4300 lines of code pub mod errors; mod ops; pub mod tensor; use errors::TensorError; use tensor::Tensor; pub fn add<'a>(lhs: &'a Tensor, rhs: &'a Tensor) -> Tensor<'a> { lhs + rhs } pub fn sub<'a>(lhs: &'a Tensor, rhs: &'a Tensor) -> Tensor<'a> { lhs - rhs } pub fn mul<'a>(lhs: &'a Tensor, rhs: &'a Tensor) -> Tensor<'a> { lhs * rhs } pub fn div<'a>(lhs: &'a Tensor, rhs: &'a Tensor) -> Tensor<'a> { lhs / rhs } pub fn pow<'a>(lhs: &'a Tensor, exp: f32) -> Result<Tensor<'a>, TensorError> { lhs.pow(exp) } pub fn sqrt<'a>(lhs: &'a Tensor) -> Result<Tensor<'a>, TensorError> { lhs.sqrt() } pub fn exp<'a>(lhs: &'a Tensor) -> Result<Tensor<'a>, TensorError> { lhs.exp() } pub fn log10<'a>(lhs: &'a Tensor) -> Result<Tensor<'a>, TensorError> { lhs.log10() } pub fn log<'a>(lhs: &'a Tensor) -> Result<Tensor<'a>, TensorError> { lhs.log() } pub fn abs<'a>(lhs: &'a Tensor) -> Result<Tensor<'a>, TensorError> { lhs.abs() } pub fn sin<'a>(lhs: &'a Tensor) -> Result<Tensor<'a>, TensorError> { lhs.sin() } pub fn cos<'a>(lhs: &'a Tensor) -> Result<Tensor<'a>, TensorError> { lhs.cos() } pub fn tan<'a>(lhs: &'a Tensor) -> Result<Tensor<'a>, TensorError> { lhs.tan() } pub fn sum<'a>(lhs: &'a Tensor, dim: isize) -> Result<Tensor<'a>, TensorError> { lhs.sum(dim) } pub fn mean<'a>(lhs: &'a Tensor, dim: isize) -> Result<Tensor<'a>, TensorError> { lhs.mean(dim) } pub fn max<'a>(lhs: &'a Tensor, dim: isize) -> Result<Tensor<'a>, TensorError> { lhs.max(dim) } pub fn min<'a>(lhs: &'a Tensor, dim: isize) -> Result<Tensor<'a>, TensorError> { lhs.min(dim) } pub fn argmax<'a>(lhs: &'a Tensor, dim: isize) -> Result<Tensor<'a>, TensorError> { lhs.argmax(dim) } pub fn argmin<'a>(lhs: &'a Tensor, dim: isize) -> Result<Tensor<'a>, TensorError> { lhs.argmin(dim)
pub fn matmul<'a>(lhs: &'a Tensor, rhs: &'a Tensor) -> Result<Tensor<'a>, TensorError> { lhs.matmul(rhs) } pub fn concat<'a>(lhs: &'a Tensor, rhs: &'a Tensor, dim: isize) -> Result<Tensor<'a>, TensorError> { lhs.concat(&rhs, dim) } #[cfg(test)] mod tests { use super::tensor::*; use super::*; #[test] fn test_add() { let a = Tensor::new(vec![2.0, 3.0], &[2]).unwrap(); let b = Tensor::new(vec![2.0, 3.0], &[2]).unwrap(); let c = add(&a, &b); assert!((c.data == vec![4.0, 6.0]) && (c.shape == vec![2])) } #[test] fn test_subtract() { let a = Tensor::new(vec![2.0, 3.0], &[2]).unwrap(); let b = Tensor::new(vec![2.0, 3.0], &[2]).unwrap(); let c = sub(&a, &b); assert!((c.data == vec![0.0, 0.0]) && (c.shape == vec![2])) } #[test] fn test_mul() { let a = Tensor::new(vec![2.0, 3.0], &[2]).unwrap(); let b = Tensor::new(vec![2.0, 3.0], &[2]).unwrap(); let c = mul(&a, &b); assert!((c.data == vec![4.0, 9.0]) && (c.shape == vec![2])) } #[test] fn test_div() { let a = Tensor::new(vec![2.0, 3.0], &[2]).unwrap(); let b = Tensor::new(vec![2.0, 3.0], &[2]).unwrap(); let c = div(&a, &b); assert!((c.data == vec![1.0, 1.0]) && (c.shape == vec![2])) } #[test] fn test_pow() { let a = Tensor::new(vec![2.0, 3.0], &[2]).unwrap(); let c = pow(&a, 2.0).unwrap(); assert!((c.data == vec![4.0, 9.0]) && (c.shape == vec![2])) } #[test] fn test_sum() { let a = Tensor::new(vec![2.0, 3.0], &[2]).unwrap(); let c = sum(&a, 0).unwrap(); assert!((c.data == vec![5.0]) && (c.shape == vec![1])) } #[test] fn test_mean() { let a = Tensor::new(vec![2.0, 3.0], &[2]).unwrap(); let c = mean(&a, 0).unwrap(); assert!((c.data == vec![2.5]) && (c.shape == vec![1])) } #[test] fn test_max() { let a = Tensor::new(vec![2.0, 3.0], &[2]).unwrap(); let c = max(&a, 0).unwrap(); assert!((c.data == vec![3.0]) && (c.shape == vec![1])) } #[test] fn test_min() { let a = Tensor::new(vec![2.0, 3.0], &[2]).unwrap(); let c = min(&a, 0).unwrap(); assert!((c.data == vec![2.0]) && (c.shape == vec![1])) } #[test] fn test_argmax() { let a = Tensor::new(vec![2.0, 3.0], &[2]).unwrap(); let c = argmax(&a, 0).unwrap(); assert!((c.data == vec![1.0]) && (c.shape == vec![1])) } #[test] fn test_argmin() { let a = Tensor::new(vec![2.0, 3.0], &[2]).unwrap(); let c = argmin(&a, 0).unwrap(); assert!((c.data == vec![0.0]) && (c.shape == vec![1])) } #[test] fn test_matmul() { let x = Tensor::new( vec![ 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, ], &[2, 2, 4], ) .unwrap(); let y = Tensor::new( vec![ 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, ], &[2, 4, 2], ) .unwrap(); let z = matmul(&x, &y).unwrap(); assert!( (z.data == vec![50.0, 60.0, 114.0, 140.0, 514.0, 556.0, 706.0, 764.0]) && (z.shape == vec![2, 2, 2]) ) } #[test] fn test_concat() { let x = Tensor::new( vec![ 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, ], &[2, 2, 2, 2], ) .unwrap(); let y = Tensor::new( vec![ 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, ], &[2, 2, 2, 2], ) .unwrap(); let z = concat(&x, &y, -1).unwrap(); assert!( (z.data == vec![ 1.0, 2.0, 1.0, 2.0, 3.0, 4.0, 3.0, 4.0, 5.0, 6.0, 5.0, 6.0, 7.0, 8.0, 7.0, 8.0, 9.0, 10.0, 9.0, 10.0, 11.0, 12.0, 11.0, 12.0, 13.0, 14.0, 13.0, 14.0, 15.0, 16.0, 15.0, 16.0 ]) && (z.shape == vec![2, 2, 2, 4]) ) } }
}
random_line_split
lib.rs
//! # L2 //!# What is L2? //! //!> L2 is named after the L2 or Euclidean distance, a popular distance function in deep learning //! //!L2 is a Pytorch-style Tensor+Autograd library written in the Rust programming language. It contains a multidimensional array class, `Tensor`, with support for strided arrays, numpy-style array slicing, //!broadcasting, and most major math operations (including fast, BLAS-accelerated matrix multiplication!). On top of this, L2 has a built-in efficient graph-based autograd engine that keeps track of all //!operations performed on a tensor and topologically sorts and traverses the graph to compute the gradients. //! //!I also made a more simplified C++ version of l2 last year, which you can take a look at [here](https://github.com/bilal2vec/L2/tree/c%2B%2B) //! //!# Example //! //!```rust //!use l2::tensor::*; //! //!fn main() -> Result<(), l2::errors::TensorError> { //! let x: Tensor = Tensor::normal(&[2, 4], 0.0, 1.0)?; //! let y: Tensor = Tensor::normal(&[4, 1], 0.0, 1.0)?; //! //! let z: Tensor = l2::matmul(&x, &y)?; //! //! z.backward(); //! //! println!("{}", z); //! //! Ok(()) //!} //!``` //! //!# Design choices //! //!I made L2 to get better at using Rust and to learn more about how libraries like Pytorch and Tensorflow work behind the scenes, so don't expect this library to be production-ready :) //! //!L2 is surprisingly fast especially since I didn't try very hard to optimize all the operators, it's usually only less than one order of magnitude slower than Pytorch in most of the benchmarks that I ran. L2 //!only supports a cpu backend at the moment since I'm not familiar enough with rust to start working with CUDA and cudnn. So far, l2 doesn't have any Pytorch-style abstractions like the Parameter, Layer, or //!Module classes. There might still be some bugs in the transpose operators and calling `.backward()` on tensors with more dimensions. I was interested in using Rust's [Const Generics](https://github.com/ //!rust-lang/rfcs/blob/master/text/2000-const-generics.md) to run compile-time shape checks but I decided to leave it until some other time. //! //!# Contributing //! //!This repository is still a work in progress, so if you find a bug, think there is something missing, or have any suggestions for new features, feel free to open an issue or a pull request. Feel free to use //!the library or code from it in your own projects, and if you feel that some code used in this project hasn't been properly accredited, please open an issue. //! //!# Authors //! //!- _Bilal Khan_ //! //!# License //! //!This project is licensed under the MIT License - see the license file for details //! //!# Acknowledgements //! //!The fast.ai deep learning from the foundations course (https://course.fast.ai/part2) teaches a lot about how to make your own deep learning library //! //!Some of the resources that I found useful when working on this library include: //! //!- http://blog.ezyang.com/2019/05/pytorch-internals/ //!- https://pytorch.org/tutorials/beginner/nn_tutorial.html //!- https://eisenjulian.github.io/deep-learning-in-100-lines/ //!- https://medium.com/@florian.caesar/how-to-create-a-machine-learning-framework-from-scratch-in-491-steps-93428369a4eb //!- https://medium.com/@johan.mabille/how-we-wrote-xtensor-1-n-n-dimensional-containers-f79f9f4966a7 //!- https://erikpartridge.com/2019-03/rust-ml-simd-blas-lapack //!- https://medium.com/@GolDDranks/things-rust-doesnt-let-you-do-draft-f596a3c740a5 //!- https://datascience.stackexchange.com/questions/20139/gradients-for-bias-terms-in-backpropagation //!- https://cs231n.github.io/optimization-2/ //!- https://cs231n.github.io/neural-networks-case-study/#grad //!- https://stackoverflow.com/questions/38082835/backpropagation-in-gradient-descent-for-neural-networks-vs-linear-regression //!- https://medium.com/@karpathy/yes-you-should-understand-backprop-e2f06eab496b //!- https://stackoverflow.com/questions/38082835/backpropagation-in-gradient-descent-for-neural-networks-vs-linear-regression //!- https://github.com/karpathy/micrograd //!- https://rufflewind.com/2016-12-30/reverse-mode-automatic-differentiation //! - https://github.com/ibab/rust-ad //! - https://github.com/Rufflewind/revad/blob/eb3978b3ccdfa8189f3ff59d1ecee71f51c33fd7/revad.py //! - https://github.com/srirambandi/ai //!- https://discuss.pytorch.org/t/is-pytorch-autograd-tape-based/13992/3 //!- https://www.reddit.com/r/MachineLearning/comments/8ep130/d_how_does_autograd_work/ //!- https://github.com/mattjj/autodidact //!- https://github.com/karpathy/recurrentjs //!- https://github.com/karpathy/randomfun //!- https://medium.com/@ralphmao95/simple-autograd-implementation-understand-automatic-differentiation-hand-by-hand-9e86f6d703ab //!- https://evcu.github.io/ml/autograd/ //!- https://blog.paperspace.com/pytorch-101-understanding-graphs-and-automatic-differentiation/ //!- https://github.com/maciejkula/wyrm //!- https://medium.com/@maciejkula/building-an-autodifferentiation-library-9ccf32c7a658 //!- https://github.com/evcu/numpy_autograd/blob/master/my_autograd.py#L147 //!- https://github.com/evcu/numpy_autograd/blob/master/Autograd.ipynb //!- https://cs231n.github.io/optimization-2/ //!- https://github.com/explosion/thinc //!- https://github.com/joelgrus/joelnet //!- https://github.com/QuantStack/xtensor //!- https://github.com/ThinkingTransistor/Sigma //!- https://github.com/mratsim/Arraymancer //!- https://github.com/siekmanj/sieknet //!- https://github.com/siekmanj/sieknet_2.0 //!- https://github.com/Daniel-Liu-c0deb0t/Java-Machine-Learning //!- https://github.com/karpathy/micrograd //! //!This README is based on: //! //!- https://github.com/bilal2vec/pytorch_zoo //!- https://github.com/bilal2vec/grover //!- https://github.com/rish-16/gpt2client //!- https://github.com/mxbi/mlcrate //!- https://github.com/athityakumar/colorls //!- https://github.com/amitmerchant1990/electron-markdownify //! //!I used carbon.now.sh with the "Shades of Purple" theme for the screenshot at the beginning of this README //! //!This project contains ~4300 lines of code pub mod errors; mod ops; pub mod tensor; use errors::TensorError; use tensor::Tensor; pub fn add<'a>(lhs: &'a Tensor, rhs: &'a Tensor) -> Tensor<'a> { lhs + rhs } pub fn sub<'a>(lhs: &'a Tensor, rhs: &'a Tensor) -> Tensor<'a> { lhs - rhs } pub fn mul<'a>(lhs: &'a Tensor, rhs: &'a Tensor) -> Tensor<'a> { lhs * rhs } pub fn div<'a>(lhs: &'a Tensor, rhs: &'a Tensor) -> Tensor<'a> { lhs / rhs } pub fn pow<'a>(lhs: &'a Tensor, exp: f32) -> Result<Tensor<'a>, TensorError> { lhs.pow(exp) } pub fn sqrt<'a>(lhs: &'a Tensor) -> Result<Tensor<'a>, TensorError> { lhs.sqrt() } pub fn exp<'a>(lhs: &'a Tensor) -> Result<Tensor<'a>, TensorError> { lhs.exp() } pub fn log10<'a>(lhs: &'a Tensor) -> Result<Tensor<'a>, TensorError> { lhs.log10() } pub fn log<'a>(lhs: &'a Tensor) -> Result<Tensor<'a>, TensorError> { lhs.log() } pub fn abs<'a>(lhs: &'a Tensor) -> Result<Tensor<'a>, TensorError> { lhs.abs() } pub fn sin<'a>(lhs: &'a Tensor) -> Result<Tensor<'a>, TensorError> { lhs.sin() } pub fn cos<'a>(lhs: &'a Tensor) -> Result<Tensor<'a>, TensorError> { lhs.cos() } pub fn tan<'a>(lhs: &'a Tensor) -> Result<Tensor<'a>, TensorError> { lhs.tan() } pub fn sum<'a>(lhs: &'a Tensor, dim: isize) -> Result<Tensor<'a>, TensorError> { lhs.sum(dim) } pub fn mean<'a>(lhs: &'a Tensor, dim: isize) -> Result<Tensor<'a>, TensorError> { lhs.mean(dim) } pub fn max<'a>(lhs: &'a Tensor, dim: isize) -> Result<Tensor<'a>, TensorError> { lhs.max(dim) } pub fn min<'a>(lhs: &'a Tensor, dim: isize) -> Result<Tensor<'a>, TensorError> { lhs.min(dim) } pub fn argmax<'a>(lhs: &'a Tensor, dim: isize) -> Result<Tensor<'a>, TensorError> { lhs.argmax(dim) } pub fn argmin<'a>(lhs: &'a Tensor, dim: isize) -> Result<Tensor<'a>, TensorError> { lhs.argmin(dim) } pub fn matmul<'a>(lhs: &'a Tensor, rhs: &'a Tensor) -> Result<Tensor<'a>, TensorError> { lhs.matmul(rhs) } pub fn concat<'a>(lhs: &'a Tensor, rhs: &'a Tensor, dim: isize) -> Result<Tensor<'a>, TensorError> { lhs.concat(&rhs, dim) } #[cfg(test)] mod tests { use super::tensor::*; use super::*; #[test] fn test_add() { let a = Tensor::new(vec![2.0, 3.0], &[2]).unwrap(); let b = Tensor::new(vec![2.0, 3.0], &[2]).unwrap(); let c = add(&a, &b); assert!((c.data == vec![4.0, 6.0]) && (c.shape == vec![2])) } #[test] fn test_subtract() { let a = Tensor::new(vec![2.0, 3.0], &[2]).unwrap(); let b = Tensor::new(vec![2.0, 3.0], &[2]).unwrap(); let c = sub(&a, &b); assert!((c.data == vec![0.0, 0.0]) && (c.shape == vec![2])) } #[test] fn test_mul() { let a = Tensor::new(vec![2.0, 3.0], &[2]).unwrap(); let b = Tensor::new(vec![2.0, 3.0], &[2]).unwrap(); let c = mul(&a, &b); assert!((c.data == vec![4.0, 9.0]) && (c.shape == vec![2])) } #[test] fn test_div() { let a = Tensor::new(vec![2.0, 3.0], &[2]).unwrap(); let b = Tensor::new(vec![2.0, 3.0], &[2]).unwrap(); let c = div(&a, &b); assert!((c.data == vec![1.0, 1.0]) && (c.shape == vec![2])) } #[test] fn test_pow() { let a = Tensor::new(vec![2.0, 3.0], &[2]).unwrap(); let c = pow(&a, 2.0).unwrap(); assert!((c.data == vec![4.0, 9.0]) && (c.shape == vec![2])) } #[test] fn test_sum()
#[test] fn test_mean() { let a = Tensor::new(vec![2.0, 3.0], &[2]).unwrap(); let c = mean(&a, 0).unwrap(); assert!((c.data == vec![2.5]) && (c.shape == vec![1])) } #[test] fn test_max() { let a = Tensor::new(vec![2.0, 3.0], &[2]).unwrap(); let c = max(&a, 0).unwrap(); assert!((c.data == vec![3.0]) && (c.shape == vec![1])) } #[test] fn test_min() { let a = Tensor::new(vec![2.0, 3.0], &[2]).unwrap(); let c = min(&a, 0).unwrap(); assert!((c.data == vec![2.0]) && (c.shape == vec![1])) } #[test] fn test_argmax() { let a = Tensor::new(vec![2.0, 3.0], &[2]).unwrap(); let c = argmax(&a, 0).unwrap(); assert!((c.data == vec![1.0]) && (c.shape == vec![1])) } #[test] fn test_argmin() { let a = Tensor::new(vec![2.0, 3.0], &[2]).unwrap(); let c = argmin(&a, 0).unwrap(); assert!((c.data == vec![0.0]) && (c.shape == vec![1])) } #[test] fn test_matmul() { let x = Tensor::new( vec![ 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, ], &[2, 2, 4], ) .unwrap(); let y = Tensor::new( vec![ 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, ], &[2, 4, 2], ) .unwrap(); let z = matmul(&x, &y).unwrap(); assert!( (z.data == vec![50.0, 60.0, 114.0, 140.0, 514.0, 556.0, 706.0, 764.0]) && (z.shape == vec![2, 2, 2]) ) } #[test] fn test_concat() { let x = Tensor::new( vec![ 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, ], &[2, 2, 2, 2], ) .unwrap(); let y = Tensor::new( vec![ 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, ], &[2, 2, 2, 2], ) .unwrap(); let z = concat(&x, &y, -1).unwrap(); assert!( (z.data == vec![ 1.0, 2.0, 1.0, 2.0, 3.0, 4.0, 3.0, 4.0, 5.0, 6.0, 5.0, 6.0, 7.0, 8.0, 7.0, 8.0, 9.0, 10.0, 9.0, 10.0, 11.0, 12.0, 11.0, 12.0, 13.0, 14.0, 13.0, 14.0, 15.0, 16.0, 15.0, 16.0 ]) && (z.shape == vec![2, 2, 2, 4]) ) } }
{ let a = Tensor::new(vec![2.0, 3.0], &[2]).unwrap(); let c = sum(&a, 0).unwrap(); assert!((c.data == vec![5.0]) && (c.shape == vec![1])) }
identifier_body
lib.rs
use ndarray::{concatenate, s, Array1, Array2, Axis}; #[macro_use] extern crate lazy_static; peg::parser!(grammar parse_tile() for str { pub rule parse_tile_id() -> usize = "Tile " id:$(['0'..='9']+) ":" { id.parse().unwrap() } pub rule parse_border() -> (u32, u32) = line:$(['#' | '.']+) { let line = line.chars().map(|x| match x { '#' => '1', '.' => '0', _ => unimplemented!("invalid image pixel"), }).collect::<String>(); (u32::from_str_radix(&line, 2).unwrap(), u32::from_str_radix(&line.chars().rev().collect::<String>(), 2).unwrap()) } pub rule parse_sub_image() -> Array1<u8> = line:$(['#' | '.']+) { let mut arr = unsafe { Array1::<u8>::uninitialized(line.len()) }; for (i, c) in line.chars().enumerate() { match c { '#' => arr[[i]] = 1, '.' => arr[[i]] = 0, _ => unimplemented!("unsupport character {}", c), } } arr } }); pub trait ImageTransformer<T> { fn original(&self) -> Array2<T>; fn rot90_clockwise(&self) -> Array2<T>; fn rot180_clockwise(&self) -> Array2<T>; fn rot270_clockwise(&self) -> Array2<T>; fn flip_vertical(&self) -> Array2<T>; fn flip_horizontal(&self) -> Array2<T>; fn flip_main_diagonal(&self) -> Array2<T>; fn flip_sub_diagonal(&self) -> Array2<T>; } impl<T> ImageTransformer<T> for Array2<T> where T: Copy, { fn original(&self) -> Array2<T> { self.clone() } fn rot90_clockwise(&self) -> Array2<T> { let mut arr = self.clone(); arr.swap_axes(0, 1); arr.flip_horizontal() } fn rot180_clockwise(&self) -> Array2<T> { let shape = self.shape()[0]; let mut arr = unsafe { Array2::uninitialized((shape, shape)) }; arr.assign(&self.slice(s![..;-1,..;-1])); arr } fn rot270_clockwise(&self) -> Array2<T> { let shape = self.shape()[0]; let mut arr = unsafe { Array2::uninitialized((shape, shape)) }; arr.assign(&self.slice(s![..,..;-1])); arr.swap_axes(0, 1); arr } fn flip_vertical(&self) -> Array2<T> { let shape = self.shape()[0]; let mut arr = unsafe { Array2::uninitialized((shape, shape)) }; arr.assign(&self.slice(s![..;-1,..])); arr } fn flip_horizontal(&self) -> Array2<T> { let shape = self.shape()[0]; let mut arr = unsafe { Array2::uninitialized((shape, shape)) }; arr.assign(&self.slice(s![..,..;-1])); arr } fn flip_main_diagonal(&self) -> Array2<T> { let shape = self.shape()[0]; let mut arr = unsafe { Array2::uninitialized((shape, shape)) }; arr.assign(&self.t()); arr } fn flip_sub_diagonal(&self) -> Array2<T> { let shape = self.shape()[0]; let mut arr: Array2<T> = unsafe { Array2::uninitialized((shape, shape)) }; arr.assign(&self.rot270_clockwise().t()); arr.rot90_clockwise() } } #[allow(unused)] #[derive(Eq)] pub struct Tile { tile_id: usize, sub_image: Array2<u8>, borders: Vec<(u32, u32, u32, u32)>, } impl PartialEq for Tile { fn eq(&self, other: &Self) -> bool { self.tile_id == other.tile_id } } use std::fmt::Debug; impl Debug for Tile { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "[{}]", self.tile_id)?; Ok(()) } } impl Tile { pub fn new(data: &str) -> Self { let lines = data .split('\n') .map(|s| s.trim_end().to_string()) .collect::<Vec<_>>(); let shape = lines[1].len() - 2; let tile_id = parse_tile::parse_tile_id(&lines[0]).unwrap(); let (top, top_rev) = parse_tile::parse_border(&lines[1]).unwrap(); let left_col = lines .iter() .skip(1) .map(|s| s.chars().next().unwrap()) .collect::<String>(); let (left, left_rev) = parse_tile::parse_border(&left_col).unwrap(); let right_col = lines .iter() .skip(1) .map(|s| s.chars().last().unwrap()) .collect::<String>(); let (right, right_rev) = parse_tile::parse_border(&right_col).unwrap(); let (bottom, bottom_rev) = parse_tile::parse_border(&lines[lines.len() - 1]).unwrap(); let mut sub_image = unsafe { Array2::<u8>::uninitialized((shape, shape)) }; for (i, row) in lines.iter().enumerate().skip(2).take(shape) { let row_pixels = parse_tile::parse_sub_image(&row[1..row.len() - 1]).unwrap(); sub_image.row_mut(i - 2).assign(&row_pixels); } Self { tile_id, sub_image, borders: vec![ (top, right, bottom, left), // original sub image (left_rev, top, right_rev, bottom), // rotate 90 degree clockwise (bottom_rev, left_rev, top_rev, right_rev), // rotate 180 degree clockwise (right, bottom_rev, left, top_rev), // rotate 270 degree clockwise (bottom, right_rev, top, left_rev), // flip vertical (top_rev, left, bottom_rev, right), // flip horizontal (left, bottom, right, top), // flip along main diagonal (right_rev, top_rev, left_rev, bottom_rev), // flip along sub diagonal ], } } pub fn get_sub_image(&self, idx: usize) -> Array2<u8> { match idx { 0 => self.sub_image.original(), 1 => self.sub_image.rot90_clockwise(), 2 => self.sub_image.rot180_clockwise(), 3 => self.sub_image.rot270_clockwise(), 4 => self.sub_image.flip_vertical(), 5 => self.sub_image.flip_horizontal(), 6 => self.sub_image.flip_main_diagonal(), 7 => self.sub_image.flip_sub_diagonal(), _ => unreachable!("not a valid form index: {}", idx), } } } pub struct BigImage { tiles: Vec<Tile>, shape: usize, } impl BigImage { pub fn new(tiles: Vec<Tile>) -> Self { let shape = (tiles.len() as f64).sqrt() as usize; Self { shape, tiles } } pub fn
<'a>( &'a self, row: usize, col: usize, prev_images: &[(&'a Tile, usize)], ) -> Vec<(&'a Tile, usize)> { let mut result: Vec<(&Tile, usize)> = vec![]; result.extend_from_slice(prev_images); for tile in self.tiles.iter() { if result.iter().any(|(t, _)| t == &tile) { continue; } result.push((tile, 0)); let upper_tile = if row > 0 { Some(result[(row - 1) * self.shape + col]) } else { None }; let left_tile = if col > 0 { Some(result[row * self.shape + col - 1]) } else { None }; for idx in 0..8 { result.last_mut().unwrap().1 = idx; if (row == 0 || tile.borders[idx].0 == upper_tile.unwrap().0.borders[upper_tile.unwrap().1].2) && (col == 0 || tile.borders[idx].3 == left_tile.unwrap().0.borders[left_tile.unwrap().1].1) { if row == self.shape - 1 && col == self.shape - 1 { return result; } let (new_row, new_col) = if col + 1 >= self.shape { (row + 1, 0) } else { (row, col + 1) }; let ret = self.fits(new_row, new_col, &result); if!ret.is_empty() { return ret; } } } result.pop(); } vec![] } pub fn splice_result(&self, fit_result: &[(&Tile, usize)]) -> Array2<u8> { let pixels = fit_result[0].0.sub_image.shape()[0]; let mut big_image = Array2::<u8>::zeros((0, self.shape * pixels)); for row in 0..self.shape { let mut row_image = Array2::<u8>::zeros((pixels, 0)); for col in 0..self.shape { let result = fit_result[row * self.shape + col]; row_image = concatenate![Axis(1), row_image, result.0.get_sub_image(result.1)]; } big_image = concatenate![Axis(0), big_image, row_image]; } big_image } } pub fn part1_solution(fit_result: &[(&Tile, usize)]) -> usize { let shape = (fit_result.len() as f64).sqrt() as usize; let corner_idx = &[0, shape - 1, shape * (shape - 1), shape * shape - 1]; fit_result .iter() .enumerate() .filter(|(idx, _)| corner_idx.contains(idx)) .map(|(_, (t, _))| t.tile_id) .product() } lazy_static! { static ref MONSTER: Array2<u8> = unsafe { Array2::from_shape_vec_unchecked( (3, 20), vec![ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, ], ) }; } fn find_all_monsters(image: &Array2<u8>) -> Vec<(usize, usize)> { let shape = image.shape()[0]; let mut found = vec![]; for row in 0..=shape - MONSTER.shape()[0] { for col in 0..=shape - MONSTER.shape()[1] { if &image.slice(s![ row..row + MONSTER.shape()[0], col..col + MONSTER.shape()[1] ]) & &MONSTER.slice(s![..,..]) == MONSTER.slice(s![..,..]) { found.push((row, col)); } } } found } pub fn part2_solution(big_image: &BigImage, fit_result: &[(&Tile, usize)]) -> usize { let mut image = big_image.splice_result(fit_result); let monsters_pos = find_all_monsters(&image); for (row, col) in monsters_pos { let region = &image.slice(s![ row..row + MONSTER.shape()[0], col..col + MONSTER.shape()[1] ]) - &MONSTER.slice(s![..,..]); image .slice_mut(s![ row..row + MONSTER.shape()[0], col..col + MONSTER.shape()[1] ]) .assign(&(region)); } image.iter().map(|x| *x as usize).sum::<usize>() } pub fn read_input(input_file: &str) -> Vec<Tile> { std::fs::read_to_string(input_file) .unwrap() .split("\n\n") .filter(|&b|!b.trim().is_empty()) .map(|b| Tile::new(b)) .collect() } #[cfg(test)] mod tests { use super::*; use ndarray::Array; #[test] fn test_matrix_transforms() { let m = Array::range(1., 5., 1.).into_shape((2, 2)).unwrap(); assert_eq!(m.original(), ndarray::arr2(&[[1., 2.], [3., 4.]])); assert_eq!(m.rot90_clockwise(), ndarray::arr2(&[[3., 1.], [4., 2.]])); assert_eq!(m.rot180_clockwise(), ndarray::arr2(&[[4., 3.], [2., 1.]])); assert_eq!(m.rot270_clockwise(), ndarray::arr2(&[[2., 4.], [1., 3.]])); assert_eq!(m.flip_vertical(), ndarray::arr2(&[[3., 4.], [1., 2.]])); assert_eq!(m.flip_horizontal(), ndarray::arr2(&[[2., 1.], [4., 3.]])); assert_eq!(m.flip_main_diagonal(), ndarray::arr2(&[[1., 3.], [2., 4.]])); assert_eq!(m.flip_sub_diagonal(), ndarray::arr2(&[[4., 2.], [3., 1.]])); } #[test] fn test_part1() { let testcase = read_input("../testcase1.txt"); let test_image = BigImage::new(testcase); let result = vec![]; let result = test_image.fits(0, 0, &result); assert_eq!(part1_solution(&result), 20899048083289); } #[test] fn test_part2() { let testcase = read_input("../testcase1.txt"); let test_image = BigImage::new(testcase); let result = vec![]; let result = test_image.fits(0, 0, &result); assert_eq!(part2_solution(&test_image, &result), 273); } }
fits
identifier_name
lib.rs
use ndarray::{concatenate, s, Array1, Array2, Axis}; #[macro_use] extern crate lazy_static; peg::parser!(grammar parse_tile() for str { pub rule parse_tile_id() -> usize = "Tile " id:$(['0'..='9']+) ":" { id.parse().unwrap() } pub rule parse_border() -> (u32, u32) = line:$(['#' | '.']+) { let line = line.chars().map(|x| match x { '#' => '1', '.' => '0', _ => unimplemented!("invalid image pixel"), }).collect::<String>(); (u32::from_str_radix(&line, 2).unwrap(), u32::from_str_radix(&line.chars().rev().collect::<String>(), 2).unwrap()) } pub rule parse_sub_image() -> Array1<u8> = line:$(['#' | '.']+) { let mut arr = unsafe { Array1::<u8>::uninitialized(line.len()) }; for (i, c) in line.chars().enumerate() { match c { '#' => arr[[i]] = 1, '.' => arr[[i]] = 0, _ => unimplemented!("unsupport character {}", c), } } arr } }); pub trait ImageTransformer<T> { fn original(&self) -> Array2<T>; fn rot90_clockwise(&self) -> Array2<T>; fn rot180_clockwise(&self) -> Array2<T>; fn rot270_clockwise(&self) -> Array2<T>; fn flip_vertical(&self) -> Array2<T>; fn flip_horizontal(&self) -> Array2<T>; fn flip_main_diagonal(&self) -> Array2<T>; fn flip_sub_diagonal(&self) -> Array2<T>; } impl<T> ImageTransformer<T> for Array2<T> where T: Copy, { fn original(&self) -> Array2<T> { self.clone() } fn rot90_clockwise(&self) -> Array2<T> { let mut arr = self.clone(); arr.swap_axes(0, 1); arr.flip_horizontal() } fn rot180_clockwise(&self) -> Array2<T> { let shape = self.shape()[0]; let mut arr = unsafe { Array2::uninitialized((shape, shape)) }; arr.assign(&self.slice(s![..;-1,..;-1])); arr } fn rot270_clockwise(&self) -> Array2<T> { let shape = self.shape()[0]; let mut arr = unsafe { Array2::uninitialized((shape, shape)) }; arr.assign(&self.slice(s![..,..;-1])); arr.swap_axes(0, 1); arr } fn flip_vertical(&self) -> Array2<T> { let shape = self.shape()[0]; let mut arr = unsafe { Array2::uninitialized((shape, shape)) }; arr.assign(&self.slice(s![..;-1,..])); arr } fn flip_horizontal(&self) -> Array2<T> { let shape = self.shape()[0]; let mut arr = unsafe { Array2::uninitialized((shape, shape)) }; arr.assign(&self.slice(s![..,..;-1])); arr } fn flip_main_diagonal(&self) -> Array2<T> { let shape = self.shape()[0]; let mut arr = unsafe { Array2::uninitialized((shape, shape)) }; arr.assign(&self.t()); arr } fn flip_sub_diagonal(&self) -> Array2<T> { let shape = self.shape()[0]; let mut arr: Array2<T> = unsafe { Array2::uninitialized((shape, shape)) }; arr.assign(&self.rot270_clockwise().t()); arr.rot90_clockwise() } } #[allow(unused)] #[derive(Eq)] pub struct Tile { tile_id: usize, sub_image: Array2<u8>, borders: Vec<(u32, u32, u32, u32)>, } impl PartialEq for Tile { fn eq(&self, other: &Self) -> bool { self.tile_id == other.tile_id } } use std::fmt::Debug; impl Debug for Tile { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "[{}]", self.tile_id)?; Ok(()) } } impl Tile { pub fn new(data: &str) -> Self { let lines = data .split('\n') .map(|s| s.trim_end().to_string()) .collect::<Vec<_>>(); let shape = lines[1].len() - 2; let tile_id = parse_tile::parse_tile_id(&lines[0]).unwrap(); let (top, top_rev) = parse_tile::parse_border(&lines[1]).unwrap(); let left_col = lines .iter() .skip(1) .map(|s| s.chars().next().unwrap()) .collect::<String>(); let (left, left_rev) = parse_tile::parse_border(&left_col).unwrap(); let right_col = lines .iter() .skip(1) .map(|s| s.chars().last().unwrap()) .collect::<String>(); let (right, right_rev) = parse_tile::parse_border(&right_col).unwrap(); let (bottom, bottom_rev) = parse_tile::parse_border(&lines[lines.len() - 1]).unwrap(); let mut sub_image = unsafe { Array2::<u8>::uninitialized((shape, shape)) }; for (i, row) in lines.iter().enumerate().skip(2).take(shape) { let row_pixels = parse_tile::parse_sub_image(&row[1..row.len() - 1]).unwrap(); sub_image.row_mut(i - 2).assign(&row_pixels); } Self { tile_id, sub_image, borders: vec![ (top, right, bottom, left), // original sub image (left_rev, top, right_rev, bottom), // rotate 90 degree clockwise (bottom_rev, left_rev, top_rev, right_rev), // rotate 180 degree clockwise (right, bottom_rev, left, top_rev), // rotate 270 degree clockwise (bottom, right_rev, top, left_rev), // flip vertical (top_rev, left, bottom_rev, right), // flip horizontal (left, bottom, right, top), // flip along main diagonal (right_rev, top_rev, left_rev, bottom_rev), // flip along sub diagonal ], } } pub fn get_sub_image(&self, idx: usize) -> Array2<u8> { match idx { 0 => self.sub_image.original(), 1 => self.sub_image.rot90_clockwise(), 2 => self.sub_image.rot180_clockwise(), 3 => self.sub_image.rot270_clockwise(), 4 => self.sub_image.flip_vertical(), 5 => self.sub_image.flip_horizontal(), 6 => self.sub_image.flip_main_diagonal(), 7 => self.sub_image.flip_sub_diagonal(), _ => unreachable!("not a valid form index: {}", idx), } } } pub struct BigImage { tiles: Vec<Tile>, shape: usize, } impl BigImage { pub fn new(tiles: Vec<Tile>) -> Self { let shape = (tiles.len() as f64).sqrt() as usize; Self { shape, tiles } } pub fn fits<'a>( &'a self, row: usize, col: usize, prev_images: &[(&'a Tile, usize)], ) -> Vec<(&'a Tile, usize)> { let mut result: Vec<(&Tile, usize)> = vec![]; result.extend_from_slice(prev_images); for tile in self.tiles.iter() { if result.iter().any(|(t, _)| t == &tile) { continue; } result.push((tile, 0)); let upper_tile = if row > 0 { Some(result[(row - 1) * self.shape + col]) } else { None }; let left_tile = if col > 0 { Some(result[row * self.shape + col - 1]) } else { None }; for idx in 0..8 { result.last_mut().unwrap().1 = idx; if (row == 0 || tile.borders[idx].0 == upper_tile.unwrap().0.borders[upper_tile.unwrap().1].2) && (col == 0 || tile.borders[idx].3 == left_tile.unwrap().0.borders[left_tile.unwrap().1].1) { if row == self.shape - 1 && col == self.shape - 1 { return result; } let (new_row, new_col) = if col + 1 >= self.shape { (row + 1, 0) } else { (row, col + 1) }; let ret = self.fits(new_row, new_col, &result); if!ret.is_empty() { return ret; } } } result.pop(); } vec![] } pub fn splice_result(&self, fit_result: &[(&Tile, usize)]) -> Array2<u8> { let pixels = fit_result[0].0.sub_image.shape()[0]; let mut big_image = Array2::<u8>::zeros((0, self.shape * pixels)); for row in 0..self.shape { let mut row_image = Array2::<u8>::zeros((pixels, 0)); for col in 0..self.shape { let result = fit_result[row * self.shape + col]; row_image = concatenate![Axis(1), row_image, result.0.get_sub_image(result.1)]; } big_image = concatenate![Axis(0), big_image, row_image]; } big_image } } pub fn part1_solution(fit_result: &[(&Tile, usize)]) -> usize { let shape = (fit_result.len() as f64).sqrt() as usize; let corner_idx = &[0, shape - 1, shape * (shape - 1), shape * shape - 1]; fit_result .iter() .enumerate() .filter(|(idx, _)| corner_idx.contains(idx)) .map(|(_, (t, _))| t.tile_id) .product() } lazy_static! { static ref MONSTER: Array2<u8> = unsafe { Array2::from_shape_vec_unchecked( (3, 20), vec![ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, ], ) }; } fn find_all_monsters(image: &Array2<u8>) -> Vec<(usize, usize)> { let shape = image.shape()[0]; let mut found = vec![]; for row in 0..=shape - MONSTER.shape()[0] { for col in 0..=shape - MONSTER.shape()[1] { if &image.slice(s![ row..row + MONSTER.shape()[0], col..col + MONSTER.shape()[1] ]) & &MONSTER.slice(s![..,..]) == MONSTER.slice(s![..,..]) { found.push((row, col)); } } } found } pub fn part2_solution(big_image: &BigImage, fit_result: &[(&Tile, usize)]) -> usize { let mut image = big_image.splice_result(fit_result); let monsters_pos = find_all_monsters(&image); for (row, col) in monsters_pos { let region = &image.slice(s![ row..row + MONSTER.shape()[0], col..col + MONSTER.shape()[1] ]) - &MONSTER.slice(s![..,..]); image .slice_mut(s![ row..row + MONSTER.shape()[0], col..col + MONSTER.shape()[1] ]) .assign(&(region)); } image.iter().map(|x| *x as usize).sum::<usize>() } pub fn read_input(input_file: &str) -> Vec<Tile> { std::fs::read_to_string(input_file) .unwrap() .split("\n\n") .filter(|&b|!b.trim().is_empty()) .map(|b| Tile::new(b)) .collect() } #[cfg(test)] mod tests { use super::*; use ndarray::Array; #[test] fn test_matrix_transforms() { let m = Array::range(1., 5., 1.).into_shape((2, 2)).unwrap(); assert_eq!(m.original(), ndarray::arr2(&[[1., 2.], [3., 4.]])); assert_eq!(m.rot90_clockwise(), ndarray::arr2(&[[3., 1.], [4., 2.]])); assert_eq!(m.rot180_clockwise(), ndarray::arr2(&[[4., 3.], [2., 1.]])); assert_eq!(m.rot270_clockwise(), ndarray::arr2(&[[2., 4.], [1., 3.]])); assert_eq!(m.flip_vertical(), ndarray::arr2(&[[3., 4.], [1., 2.]])); assert_eq!(m.flip_horizontal(), ndarray::arr2(&[[2., 1.], [4., 3.]])); assert_eq!(m.flip_main_diagonal(), ndarray::arr2(&[[1., 3.], [2., 4.]])); assert_eq!(m.flip_sub_diagonal(), ndarray::arr2(&[[4., 2.], [3., 1.]])); } #[test] fn test_part1() { let testcase = read_input("../testcase1.txt"); let test_image = BigImage::new(testcase); let result = vec![]; let result = test_image.fits(0, 0, &result); assert_eq!(part1_solution(&result), 20899048083289); } #[test] fn test_part2() {
} }
let testcase = read_input("../testcase1.txt"); let test_image = BigImage::new(testcase); let result = vec![]; let result = test_image.fits(0, 0, &result); assert_eq!(part2_solution(&test_image, &result), 273);
random_line_split
lib.rs
use ndarray::{concatenate, s, Array1, Array2, Axis}; #[macro_use] extern crate lazy_static; peg::parser!(grammar parse_tile() for str { pub rule parse_tile_id() -> usize = "Tile " id:$(['0'..='9']+) ":" { id.parse().unwrap() } pub rule parse_border() -> (u32, u32) = line:$(['#' | '.']+) { let line = line.chars().map(|x| match x { '#' => '1', '.' => '0', _ => unimplemented!("invalid image pixel"), }).collect::<String>(); (u32::from_str_radix(&line, 2).unwrap(), u32::from_str_radix(&line.chars().rev().collect::<String>(), 2).unwrap()) } pub rule parse_sub_image() -> Array1<u8> = line:$(['#' | '.']+) { let mut arr = unsafe { Array1::<u8>::uninitialized(line.len()) }; for (i, c) in line.chars().enumerate() { match c { '#' => arr[[i]] = 1, '.' => arr[[i]] = 0, _ => unimplemented!("unsupport character {}", c), } } arr } }); pub trait ImageTransformer<T> { fn original(&self) -> Array2<T>; fn rot90_clockwise(&self) -> Array2<T>; fn rot180_clockwise(&self) -> Array2<T>; fn rot270_clockwise(&self) -> Array2<T>; fn flip_vertical(&self) -> Array2<T>; fn flip_horizontal(&self) -> Array2<T>; fn flip_main_diagonal(&self) -> Array2<T>; fn flip_sub_diagonal(&self) -> Array2<T>; } impl<T> ImageTransformer<T> for Array2<T> where T: Copy, { fn original(&self) -> Array2<T> { self.clone() } fn rot90_clockwise(&self) -> Array2<T> { let mut arr = self.clone(); arr.swap_axes(0, 1); arr.flip_horizontal() } fn rot180_clockwise(&self) -> Array2<T> { let shape = self.shape()[0]; let mut arr = unsafe { Array2::uninitialized((shape, shape)) }; arr.assign(&self.slice(s![..;-1,..;-1])); arr } fn rot270_clockwise(&self) -> Array2<T> { let shape = self.shape()[0]; let mut arr = unsafe { Array2::uninitialized((shape, shape)) }; arr.assign(&self.slice(s![..,..;-1])); arr.swap_axes(0, 1); arr } fn flip_vertical(&self) -> Array2<T> { let shape = self.shape()[0]; let mut arr = unsafe { Array2::uninitialized((shape, shape)) }; arr.assign(&self.slice(s![..;-1,..])); arr } fn flip_horizontal(&self) -> Array2<T> { let shape = self.shape()[0]; let mut arr = unsafe { Array2::uninitialized((shape, shape)) }; arr.assign(&self.slice(s![..,..;-1])); arr } fn flip_main_diagonal(&self) -> Array2<T> { let shape = self.shape()[0]; let mut arr = unsafe { Array2::uninitialized((shape, shape)) }; arr.assign(&self.t()); arr } fn flip_sub_diagonal(&self) -> Array2<T> { let shape = self.shape()[0]; let mut arr: Array2<T> = unsafe { Array2::uninitialized((shape, shape)) }; arr.assign(&self.rot270_clockwise().t()); arr.rot90_clockwise() } } #[allow(unused)] #[derive(Eq)] pub struct Tile { tile_id: usize, sub_image: Array2<u8>, borders: Vec<(u32, u32, u32, u32)>, } impl PartialEq for Tile { fn eq(&self, other: &Self) -> bool { self.tile_id == other.tile_id } } use std::fmt::Debug; impl Debug for Tile { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "[{}]", self.tile_id)?; Ok(()) } } impl Tile { pub fn new(data: &str) -> Self
let (bottom, bottom_rev) = parse_tile::parse_border(&lines[lines.len() - 1]).unwrap(); let mut sub_image = unsafe { Array2::<u8>::uninitialized((shape, shape)) }; for (i, row) in lines.iter().enumerate().skip(2).take(shape) { let row_pixels = parse_tile::parse_sub_image(&row[1..row.len() - 1]).unwrap(); sub_image.row_mut(i - 2).assign(&row_pixels); } Self { tile_id, sub_image, borders: vec![ (top, right, bottom, left), // original sub image (left_rev, top, right_rev, bottom), // rotate 90 degree clockwise (bottom_rev, left_rev, top_rev, right_rev), // rotate 180 degree clockwise (right, bottom_rev, left, top_rev), // rotate 270 degree clockwise (bottom, right_rev, top, left_rev), // flip vertical (top_rev, left, bottom_rev, right), // flip horizontal (left, bottom, right, top), // flip along main diagonal (right_rev, top_rev, left_rev, bottom_rev), // flip along sub diagonal ], } } pub fn get_sub_image(&self, idx: usize) -> Array2<u8> { match idx { 0 => self.sub_image.original(), 1 => self.sub_image.rot90_clockwise(), 2 => self.sub_image.rot180_clockwise(), 3 => self.sub_image.rot270_clockwise(), 4 => self.sub_image.flip_vertical(), 5 => self.sub_image.flip_horizontal(), 6 => self.sub_image.flip_main_diagonal(), 7 => self.sub_image.flip_sub_diagonal(), _ => unreachable!("not a valid form index: {}", idx), } } } pub struct BigImage { tiles: Vec<Tile>, shape: usize, } impl BigImage { pub fn new(tiles: Vec<Tile>) -> Self { let shape = (tiles.len() as f64).sqrt() as usize; Self { shape, tiles } } pub fn fits<'a>( &'a self, row: usize, col: usize, prev_images: &[(&'a Tile, usize)], ) -> Vec<(&'a Tile, usize)> { let mut result: Vec<(&Tile, usize)> = vec![]; result.extend_from_slice(prev_images); for tile in self.tiles.iter() { if result.iter().any(|(t, _)| t == &tile) { continue; } result.push((tile, 0)); let upper_tile = if row > 0 { Some(result[(row - 1) * self.shape + col]) } else { None }; let left_tile = if col > 0 { Some(result[row * self.shape + col - 1]) } else { None }; for idx in 0..8 { result.last_mut().unwrap().1 = idx; if (row == 0 || tile.borders[idx].0 == upper_tile.unwrap().0.borders[upper_tile.unwrap().1].2) && (col == 0 || tile.borders[idx].3 == left_tile.unwrap().0.borders[left_tile.unwrap().1].1) { if row == self.shape - 1 && col == self.shape - 1 { return result; } let (new_row, new_col) = if col + 1 >= self.shape { (row + 1, 0) } else { (row, col + 1) }; let ret = self.fits(new_row, new_col, &result); if!ret.is_empty() { return ret; } } } result.pop(); } vec![] } pub fn splice_result(&self, fit_result: &[(&Tile, usize)]) -> Array2<u8> { let pixels = fit_result[0].0.sub_image.shape()[0]; let mut big_image = Array2::<u8>::zeros((0, self.shape * pixels)); for row in 0..self.shape { let mut row_image = Array2::<u8>::zeros((pixels, 0)); for col in 0..self.shape { let result = fit_result[row * self.shape + col]; row_image = concatenate![Axis(1), row_image, result.0.get_sub_image(result.1)]; } big_image = concatenate![Axis(0), big_image, row_image]; } big_image } } pub fn part1_solution(fit_result: &[(&Tile, usize)]) -> usize { let shape = (fit_result.len() as f64).sqrt() as usize; let corner_idx = &[0, shape - 1, shape * (shape - 1), shape * shape - 1]; fit_result .iter() .enumerate() .filter(|(idx, _)| corner_idx.contains(idx)) .map(|(_, (t, _))| t.tile_id) .product() } lazy_static! { static ref MONSTER: Array2<u8> = unsafe { Array2::from_shape_vec_unchecked( (3, 20), vec![ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, ], ) }; } fn find_all_monsters(image: &Array2<u8>) -> Vec<(usize, usize)> { let shape = image.shape()[0]; let mut found = vec![]; for row in 0..=shape - MONSTER.shape()[0] { for col in 0..=shape - MONSTER.shape()[1] { if &image.slice(s![ row..row + MONSTER.shape()[0], col..col + MONSTER.shape()[1] ]) & &MONSTER.slice(s![..,..]) == MONSTER.slice(s![..,..]) { found.push((row, col)); } } } found } pub fn part2_solution(big_image: &BigImage, fit_result: &[(&Tile, usize)]) -> usize { let mut image = big_image.splice_result(fit_result); let monsters_pos = find_all_monsters(&image); for (row, col) in monsters_pos { let region = &image.slice(s![ row..row + MONSTER.shape()[0], col..col + MONSTER.shape()[1] ]) - &MONSTER.slice(s![..,..]); image .slice_mut(s![ row..row + MONSTER.shape()[0], col..col + MONSTER.shape()[1] ]) .assign(&(region)); } image.iter().map(|x| *x as usize).sum::<usize>() } pub fn read_input(input_file: &str) -> Vec<Tile> { std::fs::read_to_string(input_file) .unwrap() .split("\n\n") .filter(|&b|!b.trim().is_empty()) .map(|b| Tile::new(b)) .collect() } #[cfg(test)] mod tests { use super::*; use ndarray::Array; #[test] fn test_matrix_transforms() { let m = Array::range(1., 5., 1.).into_shape((2, 2)).unwrap(); assert_eq!(m.original(), ndarray::arr2(&[[1., 2.], [3., 4.]])); assert_eq!(m.rot90_clockwise(), ndarray::arr2(&[[3., 1.], [4., 2.]])); assert_eq!(m.rot180_clockwise(), ndarray::arr2(&[[4., 3.], [2., 1.]])); assert_eq!(m.rot270_clockwise(), ndarray::arr2(&[[2., 4.], [1., 3.]])); assert_eq!(m.flip_vertical(), ndarray::arr2(&[[3., 4.], [1., 2.]])); assert_eq!(m.flip_horizontal(), ndarray::arr2(&[[2., 1.], [4., 3.]])); assert_eq!(m.flip_main_diagonal(), ndarray::arr2(&[[1., 3.], [2., 4.]])); assert_eq!(m.flip_sub_diagonal(), ndarray::arr2(&[[4., 2.], [3., 1.]])); } #[test] fn test_part1() { let testcase = read_input("../testcase1.txt"); let test_image = BigImage::new(testcase); let result = vec![]; let result = test_image.fits(0, 0, &result); assert_eq!(part1_solution(&result), 20899048083289); } #[test] fn test_part2() { let testcase = read_input("../testcase1.txt"); let test_image = BigImage::new(testcase); let result = vec![]; let result = test_image.fits(0, 0, &result); assert_eq!(part2_solution(&test_image, &result), 273); } }
{ let lines = data .split('\n') .map(|s| s.trim_end().to_string()) .collect::<Vec<_>>(); let shape = lines[1].len() - 2; let tile_id = parse_tile::parse_tile_id(&lines[0]).unwrap(); let (top, top_rev) = parse_tile::parse_border(&lines[1]).unwrap(); let left_col = lines .iter() .skip(1) .map(|s| s.chars().next().unwrap()) .collect::<String>(); let (left, left_rev) = parse_tile::parse_border(&left_col).unwrap(); let right_col = lines .iter() .skip(1) .map(|s| s.chars().last().unwrap()) .collect::<String>(); let (right, right_rev) = parse_tile::parse_border(&right_col).unwrap();
identifier_body
linebreak.rs
slen sstart tabwidth tlen underlen winfo wlen wordlen use std::cmp; use std::i64; use std::io::{BufWriter, Stdout, Write}; use std::mem; use uucore::crash; use crate::parasplit::{ParaWords, Paragraph, WordInfo}; use crate::FmtOptions; struct BreakArgs<'a> { opts: &'a FmtOptions, init_len: usize, indent_str: &'a str, indent_len: usize, uniform: bool, ostream: &'a mut BufWriter<Stdout>, } impl<'a> BreakArgs<'a> { fn compute_width(&self, winfo: &WordInfo, posn: usize, fresh: bool) -> usize { if fresh { 0 } else { let post = winfo.after_tab; match winfo.before_tab { None => post, Some(pre) => { post + ((pre + posn) / self.opts.tabwidth + 1) * self.opts.tabwidth - posn } } } } } pub fn break_lines( para: &Paragraph, opts: &FmtOptions, ostream: &mut BufWriter<Stdout>, ) -> std::io::Result<()> { // indent let p_indent = &para.indent_str[..]; let p_indent_len = para.indent_len; // words let p_words = ParaWords::new(opts, para); let mut p_words_words = p_words.words(); // the first word will *always* appear on the first line // make sure of this here let (w, w_len) = match p_words_words.next() { Some(winfo) => (winfo.word, winfo.word_nchars), None => { return ostream.write_all(b"\n"); } }; // print the init, if it exists, and get its length let p_init_len = w_len + if opts.crown || opts.tagged { // handle "init" portion ostream.write_all(para.init_str.as_bytes())?; para.init_len } else if!para.mail_header { // for non-(crown, tagged) that's the same as a normal indent ostream.write_all(p_indent.as_bytes())?; p_indent_len } else { // except that mail headers get no indent at all 0 }; // write first word after writing init ostream.write_all(w.as_bytes())?; // does this paragraph require uniform spacing? let uniform = para.mail_header || opts.uniform; let mut break_args = BreakArgs { opts, init_len: p_init_len, indent_str: p_indent, indent_len: p_indent_len, uniform, ostream, }; if opts.quick || para.mail_header { break_simple(p_words_words, &mut break_args) } else { break_knuth_plass(p_words_words, &mut break_args) } } // break_simple implements a "greedy" breaking algorithm: print words until // maxlength would be exceeded, then print a linebreak and indent and continue. fn break_simple<'a, T: Iterator<Item = &'a WordInfo<'a>>>( mut iter: T, args: &mut BreakArgs<'a>, ) -> std::io::Result<()> { iter.try_fold((args.init_len, false), |l, winfo| { accum_words_simple(args, l, winfo) })?; args.ostream.write_all(b"\n") } fn accum_words_simple<'a>( args: &mut BreakArgs<'a>, (l, prev_punct): (usize, bool), winfo: &'a WordInfo<'a>, ) -> std::io::Result<(usize, bool)> { // compute the length of this word, considering how tabs will expand at this position on the line let wlen = winfo.word_nchars + args.compute_width(winfo, l, false); let slen = compute_slen( args.uniform, winfo.new_line, winfo.sentence_start, prev_punct, ); if l + wlen + slen > args.opts.width { write_newline(args.indent_str, args.ostream)?; write_with_spaces(&winfo.word[winfo.word_start..], 0, args.ostream)?; Ok((args.indent_len + winfo.word_nchars, winfo.ends_punct)) } else { write_with_spaces(winfo.word, slen, args.ostream)?; Ok((l + wlen + slen, winfo.ends_punct)) } } // break_knuth_plass implements an "optimal" breaking algorithm in the style of // Knuth, D.E., and Plass, M.F. "Breaking Paragraphs into Lines." in Software, // Practice and Experience. Vol. 11, No. 11, November 1981. // http://onlinelibrary.wiley.com/doi/10.1002/spe.4380111102/pdf fn break_knuth_plass<'a, T: Clone + Iterator<Item = &'a WordInfo<'a>>>( mut iter: T, args: &mut BreakArgs<'a>, ) -> std::io::Result<()> { // run the algorithm to get the breakpoints let breakpoints = find_kp_breakpoints(iter.clone(), args); // iterate through the breakpoints (note that breakpoints is in reverse break order, so we.rev() it let result: std::io::Result<(bool, bool)> = breakpoints.iter().rev().try_fold( (false, false), |(mut prev_punct, mut fresh), &(next_break, break_before)| { if fresh { write_newline(args.indent_str, args.ostream)?; } // at each breakpoint, keep emitting words until we find the word matching this breakpoint for winfo in &mut iter { let (slen, word) = slice_if_fresh( fresh, winfo.word, winfo.word_start, args.uniform, winfo.new_line, winfo.sentence_start, prev_punct, ); fresh = false; prev_punct = winfo.ends_punct; // We find identical breakpoints here by comparing addresses of the references. // This is OK because the backing vector is not mutating once we are linebreaking. let winfo_ptr = winfo as *const _; let next_break_ptr = next_break as *const _; if winfo_ptr == next_break_ptr { // OK, we found the matching word if break_before { write_newline(args.indent_str, args.ostream)?; write_with_spaces(&winfo.word[winfo.word_start..], 0, args.ostream)?; } else { // breaking after this word, so that means "fresh" is true for the next iteration write_with_spaces(word, slen, args.ostream)?; fresh = true; } break; } else { write_with_spaces(word, slen, args.ostream)?; } } Ok((prev_punct, fresh)) }, ); let (mut prev_punct, mut fresh) = result?; // after the last linebreak, write out the rest of the final line. for winfo in iter { if fresh { write_newline(args.indent_str, args.ostream)?; } let (slen, word) = slice_if_fresh( fresh, winfo.word, winfo.word_start, args.uniform, winfo.new_line, winfo.sentence_start, prev_punct, ); prev_punct = winfo.ends_punct; fresh = false; write_with_spaces(word, slen, args.ostream)?; } args.ostream.write_all(b"\n") } struct LineBreak<'a> { prev: usize, linebreak: Option<&'a WordInfo<'a>>, break_before: bool, demerits: i64, prev_rat: f32, length: usize, fresh: bool, } #[allow(clippy::cognitive_complexity)] fn find_kp_breakpoints<'a, T: Iterator<Item = &'a WordInfo<'a>>>( iter: T, args: &BreakArgs<'a>, ) -> Vec<(&'a WordInfo<'a>, bool)> { let mut iter = iter.peekable(); // set up the initial null linebreak let mut linebreaks = vec![LineBreak { prev: 0, linebreak: None, break_before: false, demerits: 0, prev_rat: 0.0f32, length: args.init_len, fresh: false, }]; // this vec holds the current active linebreaks; next_ holds the breaks that will be active for // the next word let active_breaks = &mut vec![0]; let next_active_breaks = &mut vec![]; let stretch = (args.opts.width - args.opts.goal) as isize; let minlength = args.opts.goal - stretch as usize; let mut new_linebreaks = vec![]; let mut is_sentence_start = false; let mut least_demerits = 0; loop { let w = match iter.next() { None => break, Some(w) => w, }; // if this is the last word, we don't add additional demerits for this break let (is_last_word, is_sentence_end) = match iter.peek() { None => (true, true), Some(&&WordInfo { sentence_start: st, new_line: nl, .. }) => (false, st || (nl && w.ends_punct)), }; // should we be adding extra space at the beginning of the next sentence? let slen = compute_slen(args.uniform, w.new_line, is_sentence_start, false); let mut ld_new = i64::MAX; let mut ld_next = i64::MAX; let mut ld_idx = 0; new_linebreaks.clear(); next_active_breaks.clear(); // go through each active break, extending it and possibly adding a new active // break if we are above the minimum required length #[allow(clippy::explicit_iter_loop)] for &i in active_breaks.iter() { let active = &mut linebreaks[i]; // normalize demerits to avoid overflow, and record if this is the least active.demerits -= least_demerits; if active.demerits < ld_next { ld_next = active.demerits; ld_idx = i; } // get the new length let tlen = w.word_nchars + args.compute_width(w, active.length, active.fresh) + slen + active.length; // if tlen is longer than args.opts.width, we drop this break from the active list // otherwise, we extend the break, and possibly add a new break at this point if tlen <= args.opts.width { // this break will still be active next time next_active_breaks.push(i); // we can put this word on this line active.fresh = false; active.length = tlen; // if we're above the minlength, we can also consider breaking here if tlen >= minlength { let (new_demerits, new_ratio) = if is_last_word { // there is no penalty for the final line's length (0, 0.0) } else { compute_demerits( args.opts.goal as isize - tlen as isize, stretch, w.word_nchars as isize, active.prev_rat, ) }; // do not even consider adding a line that has too many demerits // also, try to detect overflow by checking signum let total_demerits = new_demerits + active.demerits; if new_demerits < BAD_INFTY_SQ && total_demerits < ld_new && active.demerits.signum() <= new_demerits.signum() { ld_new = total_demerits; new_linebreaks.push(LineBreak { prev: i, linebreak: Some(w), break_before: false, demerits: total_demerits, prev_rat: new_ratio, length: args.indent_len, fresh: true, }); } } } } // if we generated any new linebreaks, add the last one to the list // the last one is always the best because we don't add to new_linebreaks unless // it's better than the best one so far match new_linebreaks.pop() { None => (), Some(lb) => { next_active_breaks.push(linebreaks.len()); linebreaks.push(lb); } } if next_active_breaks.is_empty() { // every potential linebreak is too long! choose the linebreak with the least demerits, ld_idx let new_break = restart_active_breaks(args, &linebreaks[ld_idx], ld_idx, w, slen, minlength); next_active_breaks.push(linebreaks.len()); linebreaks.push(new_break); least_demerits = 0; } else { // next time around, normalize out the demerits fields // on active linebreaks to make overflow less likely least_demerits = cmp::max(ld_next, 0); } // swap in new list of active breaks mem::swap(active_breaks, next_active_breaks); // If this was the last word in a sentence, the next one must be the first in the next. is_sentence_start = is_sentence_end; } // return the best path build_best_path(&linebreaks, active_breaks) } fn
<'a>(paths: &[LineBreak<'a>], active: &[usize]) -> Vec<(&'a WordInfo<'a>, bool)> { let mut breakwords = vec![]; // of the active paths, we select the one with the fewest demerits let mut best_idx = match active.iter().min_by_key(|&&a| paths[a].demerits) { None => crash!( 1, "Failed to find a k-p linebreak solution. This should never happen." ), Some(&s) => s, }; // now, chase the pointers back through the break list, recording // the words at which we should break loop { let next_best = &paths[best_idx]; match next_best.linebreak { None => return breakwords, Some(prev) => { breakwords.push((prev, next_best.break_before)); best_idx = next_best.prev; } } } } // "infinite" badness is more like (1+BAD_INFTY)^2 because of how demerits are computed const BAD_INFTY: i64 = 10_000_000; const BAD_INFTY_SQ: i64 = BAD_INFTY * BAD_INFTY; // badness = BAD_MULT * abs(r) ^ 3 const BAD_MULT: f32 = 100.0; // DR_MULT is multiplier for delta-R between lines const DR_MULT: f32 = 600.0; // DL_MULT is penalty multiplier for short words at end of line const DL_MULT: f32 = 300.0; fn compute_demerits(delta_len: isize, stretch: isize, wlen: isize, prev_rat: f32) -> (i64, f32) { // how much stretch are we using? let ratio = if delta_len == 0 { 0.0f32 } else { delta_len as f32 / stretch as f32 }; // compute badness given the stretch ratio let bad_linelen = if ratio.abs() > 1.0f32 { BAD_INFTY } else { (BAD_MULT * ratio.powi(3).abs()) as i64 }; // we penalize lines ending in really short words let bad_wordlen = if wlen >= stretch { 0 } else { (DL_MULT * ((stretch - wlen) as f32 / (stretch - 1) as f32) .powi(3) .abs()) as i64 }; // we penalize lines that have very different ratios from previous lines let bad_delta_r = (DR_MULT * (((ratio - prev_rat) / 2.0).powi(3)).abs()) as i64; let demerits = i64::pow(1 + bad_linelen + bad_wordlen + bad_delta_r, 2); (demerits, ratio) } fn restart_active_breaks<'a>( args: &BreakArgs<'a>, active: &LineBreak<'a>, act_idx: usize, w: &'a WordInfo<'a>, slen: usize, min: usize, ) -> LineBreak<'a> { let (break_before, line_length) = if active.fresh { // never break before a word if that word would be the first on a line (false, args.indent_len) } else { // choose the lesser evil: breaking too early, or breaking too late let wlen = w.word_nchars + args.compute_width(w, active.length, active.fresh); let underlen = (min - active.length) as isize; let overlen = ((wlen + slen + active.length) - args.opts.width) as isize; if overlen > underlen { // break early, put this word on the next line (true, args.indent_len + w.word_nchars) } else { (false, args.indent_len) } }; // restart the linebreak. This will be our only active path. LineBreak { prev: act_idx, linebreak: Some(w), break_before, demerits: 0, // this is the only active break, so we can reset the demerit count prev_rat: if break_before { 1.0 } else { -1.0 }, length: line_length, fresh:!break_before, } } // Number of spaces to add before a word, based on mode, newline, sentence start. fn compute_slen(uniform: bool, newline: bool, start: bool, punct: bool) -> usize { if uniform || newline { if start || (newline && punct) { 2 } else { 1 } } else { 0 } } // If we're on a fresh line, slen=0 and we slice off leading whitespace. // Otherwise, compute slen and leave whitespace alone. fn slice_if_fresh( fresh: bool, word: &str, start: usize, uniform: bool, newline: bool, sstart: bool, punct: bool, ) -> (usize, &str) { if fresh { (0, &word[start..]) } else { (compute_slen(uniform, newline, sstart, punct), word) } } // Write a newline
build_best_path
identifier_name
linebreak.rs
slen sstart tabwidth tlen underlen winfo wlen wordlen use std::cmp; use std::i64; use std::io::{BufWriter, Stdout, Write}; use std::mem; use uucore::crash; use crate::parasplit::{ParaWords, Paragraph, WordInfo}; use crate::FmtOptions; struct BreakArgs<'a> { opts: &'a FmtOptions, init_len: usize, indent_str: &'a str, indent_len: usize, uniform: bool, ostream: &'a mut BufWriter<Stdout>, } impl<'a> BreakArgs<'a> { fn compute_width(&self, winfo: &WordInfo, posn: usize, fresh: bool) -> usize { if fresh { 0 } else { let post = winfo.after_tab; match winfo.before_tab { None => post, Some(pre) => { post + ((pre + posn) / self.opts.tabwidth + 1) * self.opts.tabwidth - posn } } } } } pub fn break_lines( para: &Paragraph, opts: &FmtOptions, ostream: &mut BufWriter<Stdout>, ) -> std::io::Result<()> { // indent let p_indent = &para.indent_str[..]; let p_indent_len = para.indent_len; // words let p_words = ParaWords::new(opts, para); let mut p_words_words = p_words.words(); // the first word will *always* appear on the first line // make sure of this here let (w, w_len) = match p_words_words.next() { Some(winfo) => (winfo.word, winfo.word_nchars), None => { return ostream.write_all(b"\n"); } }; // print the init, if it exists, and get its length let p_init_len = w_len + if opts.crown || opts.tagged { // handle "init" portion ostream.write_all(para.init_str.as_bytes())?; para.init_len } else if!para.mail_header { // for non-(crown, tagged) that's the same as a normal indent ostream.write_all(p_indent.as_bytes())?; p_indent_len } else { // except that mail headers get no indent at all 0 }; // write first word after writing init ostream.write_all(w.as_bytes())?; // does this paragraph require uniform spacing? let uniform = para.mail_header || opts.uniform; let mut break_args = BreakArgs { opts, init_len: p_init_len, indent_str: p_indent, indent_len: p_indent_len, uniform, ostream, }; if opts.quick || para.mail_header { break_simple(p_words_words, &mut break_args) } else
} // break_simple implements a "greedy" breaking algorithm: print words until // maxlength would be exceeded, then print a linebreak and indent and continue. fn break_simple<'a, T: Iterator<Item = &'a WordInfo<'a>>>( mut iter: T, args: &mut BreakArgs<'a>, ) -> std::io::Result<()> { iter.try_fold((args.init_len, false), |l, winfo| { accum_words_simple(args, l, winfo) })?; args.ostream.write_all(b"\n") } fn accum_words_simple<'a>( args: &mut BreakArgs<'a>, (l, prev_punct): (usize, bool), winfo: &'a WordInfo<'a>, ) -> std::io::Result<(usize, bool)> { // compute the length of this word, considering how tabs will expand at this position on the line let wlen = winfo.word_nchars + args.compute_width(winfo, l, false); let slen = compute_slen( args.uniform, winfo.new_line, winfo.sentence_start, prev_punct, ); if l + wlen + slen > args.opts.width { write_newline(args.indent_str, args.ostream)?; write_with_spaces(&winfo.word[winfo.word_start..], 0, args.ostream)?; Ok((args.indent_len + winfo.word_nchars, winfo.ends_punct)) } else { write_with_spaces(winfo.word, slen, args.ostream)?; Ok((l + wlen + slen, winfo.ends_punct)) } } // break_knuth_plass implements an "optimal" breaking algorithm in the style of // Knuth, D.E., and Plass, M.F. "Breaking Paragraphs into Lines." in Software, // Practice and Experience. Vol. 11, No. 11, November 1981. // http://onlinelibrary.wiley.com/doi/10.1002/spe.4380111102/pdf fn break_knuth_plass<'a, T: Clone + Iterator<Item = &'a WordInfo<'a>>>( mut iter: T, args: &mut BreakArgs<'a>, ) -> std::io::Result<()> { // run the algorithm to get the breakpoints let breakpoints = find_kp_breakpoints(iter.clone(), args); // iterate through the breakpoints (note that breakpoints is in reverse break order, so we.rev() it let result: std::io::Result<(bool, bool)> = breakpoints.iter().rev().try_fold( (false, false), |(mut prev_punct, mut fresh), &(next_break, break_before)| { if fresh { write_newline(args.indent_str, args.ostream)?; } // at each breakpoint, keep emitting words until we find the word matching this breakpoint for winfo in &mut iter { let (slen, word) = slice_if_fresh( fresh, winfo.word, winfo.word_start, args.uniform, winfo.new_line, winfo.sentence_start, prev_punct, ); fresh = false; prev_punct = winfo.ends_punct; // We find identical breakpoints here by comparing addresses of the references. // This is OK because the backing vector is not mutating once we are linebreaking. let winfo_ptr = winfo as *const _; let next_break_ptr = next_break as *const _; if winfo_ptr == next_break_ptr { // OK, we found the matching word if break_before { write_newline(args.indent_str, args.ostream)?; write_with_spaces(&winfo.word[winfo.word_start..], 0, args.ostream)?; } else { // breaking after this word, so that means "fresh" is true for the next iteration write_with_spaces(word, slen, args.ostream)?; fresh = true; } break; } else { write_with_spaces(word, slen, args.ostream)?; } } Ok((prev_punct, fresh)) }, ); let (mut prev_punct, mut fresh) = result?; // after the last linebreak, write out the rest of the final line. for winfo in iter { if fresh { write_newline(args.indent_str, args.ostream)?; } let (slen, word) = slice_if_fresh( fresh, winfo.word, winfo.word_start, args.uniform, winfo.new_line, winfo.sentence_start, prev_punct, ); prev_punct = winfo.ends_punct; fresh = false; write_with_spaces(word, slen, args.ostream)?; } args.ostream.write_all(b"\n") } struct LineBreak<'a> { prev: usize, linebreak: Option<&'a WordInfo<'a>>, break_before: bool, demerits: i64, prev_rat: f32, length: usize, fresh: bool, } #[allow(clippy::cognitive_complexity)] fn find_kp_breakpoints<'a, T: Iterator<Item = &'a WordInfo<'a>>>( iter: T, args: &BreakArgs<'a>, ) -> Vec<(&'a WordInfo<'a>, bool)> { let mut iter = iter.peekable(); // set up the initial null linebreak let mut linebreaks = vec![LineBreak { prev: 0, linebreak: None, break_before: false, demerits: 0, prev_rat: 0.0f32, length: args.init_len, fresh: false, }]; // this vec holds the current active linebreaks; next_ holds the breaks that will be active for // the next word let active_breaks = &mut vec![0]; let next_active_breaks = &mut vec![]; let stretch = (args.opts.width - args.opts.goal) as isize; let minlength = args.opts.goal - stretch as usize; let mut new_linebreaks = vec![]; let mut is_sentence_start = false; let mut least_demerits = 0; loop { let w = match iter.next() { None => break, Some(w) => w, }; // if this is the last word, we don't add additional demerits for this break let (is_last_word, is_sentence_end) = match iter.peek() { None => (true, true), Some(&&WordInfo { sentence_start: st, new_line: nl, .. }) => (false, st || (nl && w.ends_punct)), }; // should we be adding extra space at the beginning of the next sentence? let slen = compute_slen(args.uniform, w.new_line, is_sentence_start, false); let mut ld_new = i64::MAX; let mut ld_next = i64::MAX; let mut ld_idx = 0; new_linebreaks.clear(); next_active_breaks.clear(); // go through each active break, extending it and possibly adding a new active // break if we are above the minimum required length #[allow(clippy::explicit_iter_loop)] for &i in active_breaks.iter() { let active = &mut linebreaks[i]; // normalize demerits to avoid overflow, and record if this is the least active.demerits -= least_demerits; if active.demerits < ld_next { ld_next = active.demerits; ld_idx = i; } // get the new length let tlen = w.word_nchars + args.compute_width(w, active.length, active.fresh) + slen + active.length; // if tlen is longer than args.opts.width, we drop this break from the active list // otherwise, we extend the break, and possibly add a new break at this point if tlen <= args.opts.width { // this break will still be active next time next_active_breaks.push(i); // we can put this word on this line active.fresh = false; active.length = tlen; // if we're above the minlength, we can also consider breaking here if tlen >= minlength { let (new_demerits, new_ratio) = if is_last_word { // there is no penalty for the final line's length (0, 0.0) } else { compute_demerits( args.opts.goal as isize - tlen as isize, stretch, w.word_nchars as isize, active.prev_rat, ) }; // do not even consider adding a line that has too many demerits // also, try to detect overflow by checking signum let total_demerits = new_demerits + active.demerits; if new_demerits < BAD_INFTY_SQ && total_demerits < ld_new && active.demerits.signum() <= new_demerits.signum() { ld_new = total_demerits; new_linebreaks.push(LineBreak { prev: i, linebreak: Some(w), break_before: false, demerits: total_demerits, prev_rat: new_ratio, length: args.indent_len, fresh: true, }); } } } } // if we generated any new linebreaks, add the last one to the list // the last one is always the best because we don't add to new_linebreaks unless // it's better than the best one so far match new_linebreaks.pop() { None => (), Some(lb) => { next_active_breaks.push(linebreaks.len()); linebreaks.push(lb); } } if next_active_breaks.is_empty() { // every potential linebreak is too long! choose the linebreak with the least demerits, ld_idx let new_break = restart_active_breaks(args, &linebreaks[ld_idx], ld_idx, w, slen, minlength); next_active_breaks.push(linebreaks.len()); linebreaks.push(new_break); least_demerits = 0; } else { // next time around, normalize out the demerits fields // on active linebreaks to make overflow less likely least_demerits = cmp::max(ld_next, 0); } // swap in new list of active breaks mem::swap(active_breaks, next_active_breaks); // If this was the last word in a sentence, the next one must be the first in the next. is_sentence_start = is_sentence_end; } // return the best path build_best_path(&linebreaks, active_breaks) } fn build_best_path<'a>(paths: &[LineBreak<'a>], active: &[usize]) -> Vec<(&'a WordInfo<'a>, bool)> { let mut breakwords = vec![]; // of the active paths, we select the one with the fewest demerits let mut best_idx = match active.iter().min_by_key(|&&a| paths[a].demerits) { None => crash!( 1, "Failed to find a k-p linebreak solution. This should never happen." ), Some(&s) => s, }; // now, chase the pointers back through the break list, recording // the words at which we should break loop { let next_best = &paths[best_idx]; match next_best.linebreak { None => return breakwords, Some(prev) => { breakwords.push((prev, next_best.break_before)); best_idx = next_best.prev; } } } } // "infinite" badness is more like (1+BAD_INFTY)^2 because of how demerits are computed const BAD_INFTY: i64 = 10_000_000; const BAD_INFTY_SQ: i64 = BAD_INFTY * BAD_INFTY; // badness = BAD_MULT * abs(r) ^ 3 const BAD_MULT: f32 = 100.0; // DR_MULT is multiplier for delta-R between lines const DR_MULT: f32 = 600.0; // DL_MULT is penalty multiplier for short words at end of line const DL_MULT: f32 = 300.0; fn compute_demerits(delta_len: isize, stretch: isize, wlen: isize, prev_rat: f32) -> (i64, f32) { // how much stretch are we using? let ratio = if delta_len == 0 { 0.0f32 } else { delta_len as f32 / stretch as f32 }; // compute badness given the stretch ratio let bad_linelen = if ratio.abs() > 1.0f32 { BAD_INFTY } else { (BAD_MULT * ratio.powi(3).abs()) as i64 }; // we penalize lines ending in really short words let bad_wordlen = if wlen >= stretch { 0 } else { (DL_MULT * ((stretch - wlen) as f32 / (stretch - 1) as f32) .powi(3) .abs()) as i64 }; // we penalize lines that have very different ratios from previous lines let bad_delta_r = (DR_MULT * (((ratio - prev_rat) / 2.0).powi(3)).abs()) as i64; let demerits = i64::pow(1 + bad_linelen + bad_wordlen + bad_delta_r, 2); (demerits, ratio) } fn restart_active_breaks<'a>( args: &BreakArgs<'a>, active: &LineBreak<'a>, act_idx: usize, w: &'a WordInfo<'a>, slen: usize, min: usize, ) -> LineBreak<'a> { let (break_before, line_length) = if active.fresh { // never break before a word if that word would be the first on a line (false, args.indent_len) } else { // choose the lesser evil: breaking too early, or breaking too late let wlen = w.word_nchars + args.compute_width(w, active.length, active.fresh); let underlen = (min - active.length) as isize; let overlen = ((wlen + slen + active.length) - args.opts.width) as isize; if overlen > underlen { // break early, put this word on the next line (true, args.indent_len + w.word_nchars) } else { (false, args.indent_len) } }; // restart the linebreak. This will be our only active path. LineBreak { prev: act_idx, linebreak: Some(w), break_before, demerits: 0, // this is the only active break, so we can reset the demerit count prev_rat: if break_before { 1.0 } else { -1.0 }, length: line_length, fresh:!break_before, } } // Number of spaces to add before a word, based on mode, newline, sentence start. fn compute_slen(uniform: bool, newline: bool, start: bool, punct: bool) -> usize { if uniform || newline { if start || (newline && punct) { 2 } else { 1 } } else { 0 } } // If we're on a fresh line, slen=0 and we slice off leading whitespace. // Otherwise, compute slen and leave whitespace alone. fn slice_if_fresh( fresh: bool, word: &str, start: usize, uniform: bool, newline: bool, sstart: bool, punct: bool, ) -> (usize, &str) { if fresh { (0, &word[start..]) } else { (compute_slen(uniform, newline, sstart, punct), word) } } // Write a newline
{ break_knuth_plass(p_words_words, &mut break_args) }
conditional_block
linebreak.rs
signum slen sstart tabwidth tlen underlen winfo wlen wordlen use std::cmp; use std::i64; use std::io::{BufWriter, Stdout, Write}; use std::mem; use uucore::crash; use crate::parasplit::{ParaWords, Paragraph, WordInfo}; use crate::FmtOptions; struct BreakArgs<'a> { opts: &'a FmtOptions, init_len: usize, indent_str: &'a str, indent_len: usize, uniform: bool, ostream: &'a mut BufWriter<Stdout>, } impl<'a> BreakArgs<'a> { fn compute_width(&self, winfo: &WordInfo, posn: usize, fresh: bool) -> usize { if fresh { 0 } else { let post = winfo.after_tab; match winfo.before_tab { None => post, Some(pre) => { post + ((pre + posn) / self.opts.tabwidth + 1) * self.opts.tabwidth - posn } } } } } pub fn break_lines( para: &Paragraph, opts: &FmtOptions, ostream: &mut BufWriter<Stdout>, ) -> std::io::Result<()> { // indent let p_indent = &para.indent_str[..]; let p_indent_len = para.indent_len; // words let p_words = ParaWords::new(opts, para); let mut p_words_words = p_words.words(); // the first word will *always* appear on the first line // make sure of this here let (w, w_len) = match p_words_words.next() { Some(winfo) => (winfo.word, winfo.word_nchars), None => { return ostream.write_all(b"\n"); } }; // print the init, if it exists, and get its length let p_init_len = w_len + if opts.crown || opts.tagged { // handle "init" portion ostream.write_all(para.init_str.as_bytes())?; para.init_len } else if!para.mail_header { // for non-(crown, tagged) that's the same as a normal indent ostream.write_all(p_indent.as_bytes())?; p_indent_len } else { // except that mail headers get no indent at all 0 }; // write first word after writing init ostream.write_all(w.as_bytes())?; // does this paragraph require uniform spacing? let uniform = para.mail_header || opts.uniform; let mut break_args = BreakArgs { opts, init_len: p_init_len, indent_str: p_indent, indent_len: p_indent_len, uniform, ostream, }; if opts.quick || para.mail_header { break_simple(p_words_words, &mut break_args) } else { break_knuth_plass(p_words_words, &mut break_args) } } // break_simple implements a "greedy" breaking algorithm: print words until // maxlength would be exceeded, then print a linebreak and indent and continue. fn break_simple<'a, T: Iterator<Item = &'a WordInfo<'a>>>( mut iter: T, args: &mut BreakArgs<'a>, ) -> std::io::Result<()> { iter.try_fold((args.init_len, false), |l, winfo| { accum_words_simple(args, l, winfo) })?; args.ostream.write_all(b"\n") } fn accum_words_simple<'a>( args: &mut BreakArgs<'a>, (l, prev_punct): (usize, bool), winfo: &'a WordInfo<'a>, ) -> std::io::Result<(usize, bool)> { // compute the length of this word, considering how tabs will expand at this position on the line let wlen = winfo.word_nchars + args.compute_width(winfo, l, false); let slen = compute_slen( args.uniform, winfo.new_line, winfo.sentence_start, prev_punct, ); if l + wlen + slen > args.opts.width { write_newline(args.indent_str, args.ostream)?; write_with_spaces(&winfo.word[winfo.word_start..], 0, args.ostream)?; Ok((args.indent_len + winfo.word_nchars, winfo.ends_punct)) } else { write_with_spaces(winfo.word, slen, args.ostream)?; Ok((l + wlen + slen, winfo.ends_punct)) } } // break_knuth_plass implements an "optimal" breaking algorithm in the style of // Knuth, D.E., and Plass, M.F. "Breaking Paragraphs into Lines." in Software, // Practice and Experience. Vol. 11, No. 11, November 1981. // http://onlinelibrary.wiley.com/doi/10.1002/spe.4380111102/pdf fn break_knuth_plass<'a, T: Clone + Iterator<Item = &'a WordInfo<'a>>>( mut iter: T, args: &mut BreakArgs<'a>, ) -> std::io::Result<()> { // run the algorithm to get the breakpoints let breakpoints = find_kp_breakpoints(iter.clone(), args); // iterate through the breakpoints (note that breakpoints is in reverse break order, so we.rev() it let result: std::io::Result<(bool, bool)> = breakpoints.iter().rev().try_fold( (false, false), |(mut prev_punct, mut fresh), &(next_break, break_before)| { if fresh { write_newline(args.indent_str, args.ostream)?; } // at each breakpoint, keep emitting words until we find the word matching this breakpoint for winfo in &mut iter { let (slen, word) = slice_if_fresh( fresh, winfo.word, winfo.word_start, args.uniform, winfo.new_line, winfo.sentence_start, prev_punct, ); fresh = false; prev_punct = winfo.ends_punct; // We find identical breakpoints here by comparing addresses of the references. // This is OK because the backing vector is not mutating once we are linebreaking. let winfo_ptr = winfo as *const _; let next_break_ptr = next_break as *const _; if winfo_ptr == next_break_ptr { // OK, we found the matching word if break_before { write_newline(args.indent_str, args.ostream)?; write_with_spaces(&winfo.word[winfo.word_start..], 0, args.ostream)?; } else { // breaking after this word, so that means "fresh" is true for the next iteration write_with_spaces(word, slen, args.ostream)?; fresh = true; } break; } else { write_with_spaces(word, slen, args.ostream)?; } } Ok((prev_punct, fresh)) }, ); let (mut prev_punct, mut fresh) = result?; // after the last linebreak, write out the rest of the final line. for winfo in iter { if fresh { write_newline(args.indent_str, args.ostream)?; } let (slen, word) = slice_if_fresh( fresh, winfo.word, winfo.word_start, args.uniform, winfo.new_line, winfo.sentence_start, prev_punct, ); prev_punct = winfo.ends_punct; fresh = false; write_with_spaces(word, slen, args.ostream)?; } args.ostream.write_all(b"\n") } struct LineBreak<'a> { prev: usize, linebreak: Option<&'a WordInfo<'a>>, break_before: bool, demerits: i64, prev_rat: f32, length: usize, fresh: bool, } #[allow(clippy::cognitive_complexity)] fn find_kp_breakpoints<'a, T: Iterator<Item = &'a WordInfo<'a>>>( iter: T, args: &BreakArgs<'a>, ) -> Vec<(&'a WordInfo<'a>, bool)> { let mut iter = iter.peekable(); // set up the initial null linebreak let mut linebreaks = vec![LineBreak { prev: 0, linebreak: None, break_before: false, demerits: 0, prev_rat: 0.0f32, length: args.init_len, fresh: false, }]; // this vec holds the current active linebreaks; next_ holds the breaks that will be active for // the next word let active_breaks = &mut vec![0]; let next_active_breaks = &mut vec![]; let stretch = (args.opts.width - args.opts.goal) as isize; let minlength = args.opts.goal - stretch as usize; let mut new_linebreaks = vec![]; let mut is_sentence_start = false; let mut least_demerits = 0; loop { let w = match iter.next() { None => break, Some(w) => w, }; // if this is the last word, we don't add additional demerits for this break let (is_last_word, is_sentence_end) = match iter.peek() { None => (true, true), Some(&&WordInfo { sentence_start: st, new_line: nl, .. }) => (false, st || (nl && w.ends_punct)), }; // should we be adding extra space at the beginning of the next sentence? let slen = compute_slen(args.uniform, w.new_line, is_sentence_start, false); let mut ld_new = i64::MAX; let mut ld_next = i64::MAX; let mut ld_idx = 0; new_linebreaks.clear(); next_active_breaks.clear(); // go through each active break, extending it and possibly adding a new active // break if we are above the minimum required length #[allow(clippy::explicit_iter_loop)] for &i in active_breaks.iter() { let active = &mut linebreaks[i]; // normalize demerits to avoid overflow, and record if this is the least active.demerits -= least_demerits; if active.demerits < ld_next { ld_next = active.demerits; ld_idx = i; } // get the new length let tlen = w.word_nchars + args.compute_width(w, active.length, active.fresh) + slen + active.length; // if tlen is longer than args.opts.width, we drop this break from the active list // otherwise, we extend the break, and possibly add a new break at this point if tlen <= args.opts.width { // this break will still be active next time next_active_breaks.push(i); // we can put this word on this line active.fresh = false; active.length = tlen; // if we're above the minlength, we can also consider breaking here if tlen >= minlength { let (new_demerits, new_ratio) = if is_last_word { // there is no penalty for the final line's length (0, 0.0) } else { compute_demerits( args.opts.goal as isize - tlen as isize, stretch, w.word_nchars as isize, active.prev_rat, ) }; // do not even consider adding a line that has too many demerits // also, try to detect overflow by checking signum let total_demerits = new_demerits + active.demerits; if new_demerits < BAD_INFTY_SQ && total_demerits < ld_new && active.demerits.signum() <= new_demerits.signum() { ld_new = total_demerits; new_linebreaks.push(LineBreak { prev: i, linebreak: Some(w), break_before: false, demerits: total_demerits, prev_rat: new_ratio, length: args.indent_len, fresh: true, }); } } } } // if we generated any new linebreaks, add the last one to the list // the last one is always the best because we don't add to new_linebreaks unless // it's better than the best one so far match new_linebreaks.pop() { None => (), Some(lb) => { next_active_breaks.push(linebreaks.len()); linebreaks.push(lb); } } if next_active_breaks.is_empty() { // every potential linebreak is too long! choose the linebreak with the least demerits, ld_idx let new_break = restart_active_breaks(args, &linebreaks[ld_idx], ld_idx, w, slen, minlength); next_active_breaks.push(linebreaks.len()); linebreaks.push(new_break); least_demerits = 0; } else { // next time around, normalize out the demerits fields // on active linebreaks to make overflow less likely least_demerits = cmp::max(ld_next, 0); } // swap in new list of active breaks mem::swap(active_breaks, next_active_breaks); // If this was the last word in a sentence, the next one must be the first in the next. is_sentence_start = is_sentence_end; } // return the best path build_best_path(&linebreaks, active_breaks) } fn build_best_path<'a>(paths: &[LineBreak<'a>], active: &[usize]) -> Vec<(&'a WordInfo<'a>, bool)> { let mut breakwords = vec![]; // of the active paths, we select the one with the fewest demerits let mut best_idx = match active.iter().min_by_key(|&&a| paths[a].demerits) { None => crash!( 1, "Failed to find a k-p linebreak solution. This should never happen." ), Some(&s) => s, }; // now, chase the pointers back through the break list, recording // the words at which we should break loop { let next_best = &paths[best_idx]; match next_best.linebreak { None => return breakwords, Some(prev) => { breakwords.push((prev, next_best.break_before)); best_idx = next_best.prev; } } } } // "infinite" badness is more like (1+BAD_INFTY)^2 because of how demerits are computed const BAD_INFTY: i64 = 10_000_000; const BAD_INFTY_SQ: i64 = BAD_INFTY * BAD_INFTY; // badness = BAD_MULT * abs(r) ^ 3 const BAD_MULT: f32 = 100.0; // DR_MULT is multiplier for delta-R between lines const DR_MULT: f32 = 600.0; // DL_MULT is penalty multiplier for short words at end of line const DL_MULT: f32 = 300.0; fn compute_demerits(delta_len: isize, stretch: isize, wlen: isize, prev_rat: f32) -> (i64, f32) { // how much stretch are we using? let ratio = if delta_len == 0 { 0.0f32 } else { delta_len as f32 / stretch as f32 }; // compute badness given the stretch ratio let bad_linelen = if ratio.abs() > 1.0f32 { BAD_INFTY } else { (BAD_MULT * ratio.powi(3).abs()) as i64 }; // we penalize lines ending in really short words let bad_wordlen = if wlen >= stretch { 0 } else { (DL_MULT * ((stretch - wlen) as f32 / (stretch - 1) as f32) .powi(3) .abs()) as i64 }; // we penalize lines that have very different ratios from previous lines let bad_delta_r = (DR_MULT * (((ratio - prev_rat) / 2.0).powi(3)).abs()) as i64; let demerits = i64::pow(1 + bad_linelen + bad_wordlen + bad_delta_r, 2); (demerits, ratio) } fn restart_active_breaks<'a>( args: &BreakArgs<'a>, active: &LineBreak<'a>, act_idx: usize, w: &'a WordInfo<'a>, slen: usize, min: usize, ) -> LineBreak<'a> { let (break_before, line_length) = if active.fresh { // never break before a word if that word would be the first on a line (false, args.indent_len) } else { // choose the lesser evil: breaking too early, or breaking too late let wlen = w.word_nchars + args.compute_width(w, active.length, active.fresh); let underlen = (min - active.length) as isize; let overlen = ((wlen + slen + active.length) - args.opts.width) as isize; if overlen > underlen { // break early, put this word on the next line (true, args.indent_len + w.word_nchars) } else { (false, args.indent_len) } }; // restart the linebreak. This will be our only active path. LineBreak { prev: act_idx, linebreak: Some(w), break_before, demerits: 0, // this is the only active break, so we can reset the demerit count prev_rat: if break_before { 1.0 } else { -1.0 }, length: line_length, fresh:!break_before, } } // Number of spaces to add before a word, based on mode, newline, sentence start. fn compute_slen(uniform: bool, newline: bool, start: bool, punct: bool) -> usize {
1 } } else { 0 } } // If we're on a fresh line, slen=0 and we slice off leading whitespace. // Otherwise, compute slen and leave whitespace alone. fn slice_if_fresh( fresh: bool, word: &str, start: usize, uniform: bool, newline: bool, sstart: bool, punct: bool, ) -> (usize, &str) { if fresh { (0, &word[start..]) } else { (compute_slen(uniform, newline, sstart, punct), word) } } // Write a newline and
if uniform || newline { if start || (newline && punct) { 2 } else {
random_line_split
ioapic.rs
use core::{fmt, ptr}; use alloc::vec::Vec; use spin::Mutex; #[cfg(feature = "acpi")] use crate::acpi::madt::{self, Madt, MadtEntry, MadtIoApic, MadtIntSrcOverride}; use crate::arch::interrupt::irq; use crate::memory::Frame; use crate::paging::{KernelMapper, Page, PageFlags, PhysicalAddress, RmmA, RmmArch, VirtualAddress}; use crate::paging::entry::EntryFlags; use super::super::cpuid::cpuid; use super::pic; pub struct IoApicRegs { pointer: *const u32, } impl IoApicRegs { fn ioregsel(&self) -> *const u32 { self.pointer } fn iowin(&self) -> *const u32 { // offset 0x10 unsafe { self.pointer.offset(4) } } fn write_ioregsel(&mut self, value: u32) { unsafe { ptr::write_volatile::<u32>(self.ioregsel() as *mut u32, value) } } fn read_iowin(&self) -> u32 { unsafe { ptr::read_volatile::<u32>(self.iowin()) } } fn write_iowin(&mut self, value: u32) { unsafe { ptr::write_volatile::<u32>(self.iowin() as *mut u32, value) } } fn read_reg(&mut self, reg: u8) -> u32 { self.write_ioregsel(reg.into()); self.read_iowin() } fn write_reg(&mut self, reg: u8, value: u32) { self.write_ioregsel(reg.into()); self.write_iowin(value); } pub fn read_ioapicid(&mut self) -> u32 { self.read_reg(0x00) } pub fn write_ioapicid(&mut self, value: u32) { self.write_reg(0x00, value); } pub fn read_ioapicver(&mut self) -> u32 { self.read_reg(0x01) } pub fn read_ioapicarb(&mut self) -> u32 { self.read_reg(0x02) } pub fn read_ioredtbl(&mut self, idx: u8) -> u64 { assert!(idx < 24); let lo = self.read_reg(0x10 + idx * 2); let hi = self.read_reg(0x10 + idx * 2 + 1); u64::from(lo) | (u64::from(hi) << 32) } pub fn write_ioredtbl(&mut self, idx: u8, value: u64) { assert!(idx < 24); let lo = value as u32; let hi = (value >> 32) as u32; self.write_reg(0x10 + idx * 2, lo); self.write_reg(0x10 + idx * 2 + 1, hi); } pub fn max_redirection_table_entries(&mut self) -> u8 { let ver = self.read_ioapicver(); ((ver & 0x00FF_0000) >> 16) as u8 } pub fn id(&mut self) -> u8 { let id_reg = self.read_ioapicid(); ((id_reg & 0x0F00_0000) >> 24) as u8 } } pub struct IoApic { regs: Mutex<IoApicRegs>, gsi_start: u32, count: u8, } impl IoApic { pub fn new(regs_base: *const u32, gsi_start: u32) -> Self { let mut regs = IoApicRegs { pointer: regs_base }; let count = regs.max_redirection_table_entries(); Self { regs: Mutex::new(regs), gsi_start, count, } } /// Map an interrupt vector to a physical local APIC ID of a processor (thus physical mode). pub fn map(&self, idx: u8, info: MapInfo) { self.regs.lock().write_ioredtbl(idx, info.as_raw()) } pub fn set_mask(&self, gsi: u32, mask: bool) { let idx = (gsi - self.gsi_start) as u8; let mut guard = self.regs.lock(); let mut reg = guard.read_ioredtbl(idx); reg &=!(1 << 16); reg |= u64::from(mask) << 16; guard.write_ioredtbl(idx, reg); } } #[repr(u8)] #[derive(Clone, Copy, Debug)] pub enum ApicTriggerMode { Edge = 0, Level = 1, } #[repr(u8)] #[derive(Clone, Copy, Debug)] pub enum ApicPolarity { ActiveHigh = 0, ActiveLow = 1, } #[repr(u8)] #[derive(Clone, Copy, Debug)] pub enum DestinationMode { Physical = 0, Logical = 1, } #[repr(u8)] #[derive(Clone, Copy, Debug)] pub enum DeliveryMode { Fixed = 0b000, LowestPriority = 0b001, Smi = 0b010, Nmi = 0b100, Init = 0b101, ExtInt = 0b111, } #[derive(Clone, Copy, Debug)] pub struct MapInfo { pub dest: u8, pub mask: bool, pub trigger_mode: ApicTriggerMode, pub polarity: ApicPolarity, pub dest_mode: DestinationMode, pub delivery_mode: DeliveryMode, pub vector: u8, } impl MapInfo { pub fn as_raw(&self) -> u64 { assert!(self.vector >= 0x20); assert!(self.vector <= 0xFE); // TODO: Check for reserved fields. (u64::from(self.dest) << 56) | (u64::from(self.mask) << 16) | ((self.trigger_mode as u64) << 15) | ((self.polarity as u64) << 13) | ((self.dest_mode as u64) << 11) | ((self.delivery_mode as u64) << 8) | u64::from(self.vector) }
} impl fmt::Debug for IoApic { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { struct RedirTable<'a>(&'a Mutex<IoApicRegs>); impl<'a> fmt::Debug for RedirTable<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let mut guard = self.0.lock(); let count = guard.max_redirection_table_entries(); f.debug_list().entries((0..count).map(|i| guard.read_ioredtbl(i))).finish() } } f.debug_struct("IoApic") .field("redir_table", &RedirTable(&self.regs)) .field("gsi_start", &self.gsi_start) .field("count", &self.count) .finish() } } #[derive(Clone, Copy, Debug)] pub enum TriggerMode { ConformsToSpecs, Edge, Level, } #[derive(Clone, Copy, Debug)] pub enum Polarity { ConformsToSpecs, ActiveHigh, ActiveLow, } #[derive(Clone, Copy, Debug)] pub struct Override { bus_irq: u8, gsi: u32, trigger_mode: TriggerMode, polarity: Polarity, } // static mut because only the AP initializes the I/O Apic, and when that is done, it's solely // accessed immutably. static mut IOAPICS: Option<Vec<IoApic>> = None; // static mut for the same reason as above static mut SRC_OVERRIDES: Option<Vec<Override>> = None; pub fn ioapics() -> &'static [IoApic] { unsafe { IOAPICS.as_ref().map_or(&[], |vector| &vector[..]) } } pub fn src_overrides() -> &'static [Override] { unsafe { SRC_OVERRIDES.as_ref().map_or(&[], |vector| &vector[..]) } } #[cfg(feature = "acpi")] pub unsafe fn handle_ioapic(mapper: &mut KernelMapper, madt_ioapic: &'static MadtIoApic) { // map the I/O APIC registers let frame = Frame::containing_address(PhysicalAddress::new(madt_ioapic.address as usize)); let page = Page::containing_address(VirtualAddress::new(crate::IOAPIC_OFFSET)); assert!(mapper.translate(page.start_address()).is_none()); mapper .get_mut() .expect("expected KernelMapper not to be locked re-entrant while mapping I/O APIC memory") .map_phys(page.start_address(), frame.start_address(), PageFlags::new().write(true).custom_flag(EntryFlags::NO_CACHE.bits(), true)) .expect("failed to map I/O APIC") .flush(); let ioapic_registers = page.start_address().data() as *const u32; let ioapic = IoApic::new(ioapic_registers, madt_ioapic.gsi_base); assert_eq!(ioapic.regs.lock().id(), madt_ioapic.id, "mismatched ACPI MADT I/O APIC ID, and the ID reported by the I/O APIC"); IOAPICS.get_or_insert_with(Vec::new).push(ioapic); } #[cfg(feature = "acpi")] pub unsafe fn handle_src_override(src_override: &'static MadtIntSrcOverride) { let flags = src_override.flags; let polarity_raw = (flags & 0x0003) as u8; let trigger_mode_raw = ((flags & 0x000C) >> 2) as u8; let polarity = match polarity_raw { 0b00 => Polarity::ConformsToSpecs, 0b01 => Polarity::ActiveHigh, 0b10 => return, // reserved 0b11 => Polarity::ActiveLow, _ => unreachable!(), }; let trigger_mode = match trigger_mode_raw { 0b00 => TriggerMode::ConformsToSpecs, 0b01 => TriggerMode::Edge, 0b10 => return, // reserved 0b11 => TriggerMode::Level, _ => unreachable!(), }; let over = Override { bus_irq: src_override.irq_source, gsi: src_override.gsi_base, polarity, trigger_mode, }; SRC_OVERRIDES.get_or_insert_with(Vec::new).push(over); } pub unsafe fn init(active_table: &mut KernelMapper) { let bsp_apic_id = cpuid().unwrap().get_feature_info().unwrap().initial_local_apic_id(); // TODO: remove unwraps // search the madt for all IOAPICs. #[cfg(feature = "acpi")] { let madt: &'static Madt = match madt::MADT.as_ref() { Some(m) => m, // TODO: Parse MP tables too. None => return, }; if madt.flags & madt::FLAG_PCAT!= 0 { pic::disable(); } // find all I/O APICs (usually one). for entry in madt.iter() { match entry { MadtEntry::IoApic(ioapic) => handle_ioapic(active_table, ioapic), MadtEntry::IntSrcOverride(src_override) => handle_src_override(src_override), _ => (), } } } println!("I/O APICs: {:?}, overrides: {:?}", ioapics(), src_overrides()); // map the legacy PC-compatible IRQs (0-15) to 32-47, just like we did with 8259 PIC (if it // wouldn't have been disabled due to this I/O APIC) for legacy_irq in 0..=15 { let (gsi, trigger_mode, polarity) = match get_override(legacy_irq) { Some(over) => (over.gsi, over.trigger_mode, over.polarity), None => { if src_overrides().iter().any(|over| over.gsi == u32::from(legacy_irq) && over.bus_irq!= legacy_irq) &&!src_overrides().iter().any(|over| over.bus_irq == legacy_irq) { // there's an IRQ conflict, making this legacy IRQ inaccessible. continue; } (legacy_irq.into(), TriggerMode::ConformsToSpecs, Polarity::ConformsToSpecs) } }; let apic = match find_ioapic(gsi) { Some(ioapic) => ioapic, None => { println!("Unable to find a suitable APIC for legacy IRQ {} (GSI {}). It will not be mapped.", legacy_irq, gsi); continue; } }; let redir_tbl_index = (gsi - apic.gsi_start) as u8; let map_info = MapInfo { // only send to the BSP dest: bsp_apic_id, dest_mode: DestinationMode::Physical, delivery_mode: DeliveryMode::Fixed, mask: false, polarity: match polarity { Polarity::ActiveHigh => ApicPolarity::ActiveHigh, Polarity::ActiveLow => ApicPolarity::ActiveLow, Polarity::ConformsToSpecs => ApicPolarity::ActiveHigh, }, trigger_mode: match trigger_mode { TriggerMode::Edge => ApicTriggerMode::Edge, TriggerMode::Level => ApicTriggerMode::Level, TriggerMode::ConformsToSpecs => ApicTriggerMode::Edge, }, vector: 32 + legacy_irq, }; apic.map(redir_tbl_index, map_info); } println!("I/O APICs: {:?}, overrides: {:?}", ioapics(), src_overrides()); irq::set_irq_method(irq::IrqMethod::Apic); // tell the firmware that we're using APIC rather than the default 8259 PIC. // FIXME: With ACPI moved to userspace, we should instead allow userspace to check whether the // IOAPIC has been initialized, and then subsequently let some ACPI driver call the AML from // userspace. /*#[cfg(feature = "acpi")] { let method = { let namespace_guard = crate::acpi::ACPI_TABLE.namespace.read(); if let Some(value) = namespace_guard.as_ref().unwrap().get("\\_PIC") { value.get_as_method().ok() } else { None } }; if let Some(m) = method { m.execute("\\_PIC".into(), vec!(crate::acpi::aml::AmlValue::Integer(1))); } }*/ } fn get_override(irq: u8) -> Option<&'static Override> { src_overrides().iter().find(|over| over.bus_irq == irq) } fn resolve(irq: u8) -> u32 { get_override(irq).map_or(u32::from(irq), |over| over.gsi) } fn find_ioapic(gsi: u32) -> Option<&'static IoApic> { ioapics().iter().find(|apic| gsi >= apic.gsi_start && gsi < apic.gsi_start + u32::from(apic.count)) } pub unsafe fn mask(irq: u8) { let gsi = resolve(irq); let apic = match find_ioapic(gsi) { Some(a) => a, None => return, }; apic.set_mask(gsi, true); } pub unsafe fn unmask(irq: u8) { let gsi = resolve(irq); let apic = match find_ioapic(gsi) { Some(a) => a, None => return, }; apic.set_mask(gsi, false); }
random_line_split
ioapic.rs
use core::{fmt, ptr}; use alloc::vec::Vec; use spin::Mutex; #[cfg(feature = "acpi")] use crate::acpi::madt::{self, Madt, MadtEntry, MadtIoApic, MadtIntSrcOverride}; use crate::arch::interrupt::irq; use crate::memory::Frame; use crate::paging::{KernelMapper, Page, PageFlags, PhysicalAddress, RmmA, RmmArch, VirtualAddress}; use crate::paging::entry::EntryFlags; use super::super::cpuid::cpuid; use super::pic; pub struct IoApicRegs { pointer: *const u32, } impl IoApicRegs { fn ioregsel(&self) -> *const u32 { self.pointer } fn iowin(&self) -> *const u32 { // offset 0x10 unsafe { self.pointer.offset(4) } } fn write_ioregsel(&mut self, value: u32) { unsafe { ptr::write_volatile::<u32>(self.ioregsel() as *mut u32, value) } } fn read_iowin(&self) -> u32 { unsafe { ptr::read_volatile::<u32>(self.iowin()) } } fn write_iowin(&mut self, value: u32) { unsafe { ptr::write_volatile::<u32>(self.iowin() as *mut u32, value) } } fn read_reg(&mut self, reg: u8) -> u32 { self.write_ioregsel(reg.into()); self.read_iowin() } fn write_reg(&mut self, reg: u8, value: u32) { self.write_ioregsel(reg.into()); self.write_iowin(value); } pub fn read_ioapicid(&mut self) -> u32 { self.read_reg(0x00) } pub fn write_ioapicid(&mut self, value: u32) { self.write_reg(0x00, value); } pub fn read_ioapicver(&mut self) -> u32 { self.read_reg(0x01) } pub fn read_ioapicarb(&mut self) -> u32 { self.read_reg(0x02) } pub fn read_ioredtbl(&mut self, idx: u8) -> u64 { assert!(idx < 24); let lo = self.read_reg(0x10 + idx * 2); let hi = self.read_reg(0x10 + idx * 2 + 1); u64::from(lo) | (u64::from(hi) << 32) } pub fn write_ioredtbl(&mut self, idx: u8, value: u64) { assert!(idx < 24); let lo = value as u32; let hi = (value >> 32) as u32; self.write_reg(0x10 + idx * 2, lo); self.write_reg(0x10 + idx * 2 + 1, hi); } pub fn max_redirection_table_entries(&mut self) -> u8 { let ver = self.read_ioapicver(); ((ver & 0x00FF_0000) >> 16) as u8 } pub fn id(&mut self) -> u8 { let id_reg = self.read_ioapicid(); ((id_reg & 0x0F00_0000) >> 24) as u8 } } pub struct IoApic { regs: Mutex<IoApicRegs>, gsi_start: u32, count: u8, } impl IoApic { pub fn new(regs_base: *const u32, gsi_start: u32) -> Self { let mut regs = IoApicRegs { pointer: regs_base }; let count = regs.max_redirection_table_entries(); Self { regs: Mutex::new(regs), gsi_start, count, } } /// Map an interrupt vector to a physical local APIC ID of a processor (thus physical mode). pub fn map(&self, idx: u8, info: MapInfo) { self.regs.lock().write_ioredtbl(idx, info.as_raw()) } pub fn set_mask(&self, gsi: u32, mask: bool) { let idx = (gsi - self.gsi_start) as u8; let mut guard = self.regs.lock(); let mut reg = guard.read_ioredtbl(idx); reg &=!(1 << 16); reg |= u64::from(mask) << 16; guard.write_ioredtbl(idx, reg); } } #[repr(u8)] #[derive(Clone, Copy, Debug)] pub enum ApicTriggerMode { Edge = 0, Level = 1, } #[repr(u8)] #[derive(Clone, Copy, Debug)] pub enum ApicPolarity { ActiveHigh = 0, ActiveLow = 1, } #[repr(u8)] #[derive(Clone, Copy, Debug)] pub enum DestinationMode { Physical = 0, Logical = 1, } #[repr(u8)] #[derive(Clone, Copy, Debug)] pub enum DeliveryMode { Fixed = 0b000, LowestPriority = 0b001, Smi = 0b010, Nmi = 0b100, Init = 0b101, ExtInt = 0b111, } #[derive(Clone, Copy, Debug)] pub struct MapInfo { pub dest: u8, pub mask: bool, pub trigger_mode: ApicTriggerMode, pub polarity: ApicPolarity, pub dest_mode: DestinationMode, pub delivery_mode: DeliveryMode, pub vector: u8, } impl MapInfo { pub fn as_raw(&self) -> u64 { assert!(self.vector >= 0x20); assert!(self.vector <= 0xFE); // TODO: Check for reserved fields. (u64::from(self.dest) << 56) | (u64::from(self.mask) << 16) | ((self.trigger_mode as u64) << 15) | ((self.polarity as u64) << 13) | ((self.dest_mode as u64) << 11) | ((self.delivery_mode as u64) << 8) | u64::from(self.vector) } } impl fmt::Debug for IoApic { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { struct RedirTable<'a>(&'a Mutex<IoApicRegs>); impl<'a> fmt::Debug for RedirTable<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let mut guard = self.0.lock(); let count = guard.max_redirection_table_entries(); f.debug_list().entries((0..count).map(|i| guard.read_ioredtbl(i))).finish() } } f.debug_struct("IoApic") .field("redir_table", &RedirTable(&self.regs)) .field("gsi_start", &self.gsi_start) .field("count", &self.count) .finish() } } #[derive(Clone, Copy, Debug)] pub enum TriggerMode { ConformsToSpecs, Edge, Level, } #[derive(Clone, Copy, Debug)] pub enum Polarity { ConformsToSpecs, ActiveHigh, ActiveLow, } #[derive(Clone, Copy, Debug)] pub struct Override { bus_irq: u8, gsi: u32, trigger_mode: TriggerMode, polarity: Polarity, } // static mut because only the AP initializes the I/O Apic, and when that is done, it's solely // accessed immutably. static mut IOAPICS: Option<Vec<IoApic>> = None; // static mut for the same reason as above static mut SRC_OVERRIDES: Option<Vec<Override>> = None; pub fn ioapics() -> &'static [IoApic] { unsafe { IOAPICS.as_ref().map_or(&[], |vector| &vector[..]) } } pub fn src_overrides() -> &'static [Override] { unsafe { SRC_OVERRIDES.as_ref().map_or(&[], |vector| &vector[..]) } } #[cfg(feature = "acpi")] pub unsafe fn handle_ioapic(mapper: &mut KernelMapper, madt_ioapic: &'static MadtIoApic) { // map the I/O APIC registers let frame = Frame::containing_address(PhysicalAddress::new(madt_ioapic.address as usize)); let page = Page::containing_address(VirtualAddress::new(crate::IOAPIC_OFFSET)); assert!(mapper.translate(page.start_address()).is_none()); mapper .get_mut() .expect("expected KernelMapper not to be locked re-entrant while mapping I/O APIC memory") .map_phys(page.start_address(), frame.start_address(), PageFlags::new().write(true).custom_flag(EntryFlags::NO_CACHE.bits(), true)) .expect("failed to map I/O APIC") .flush(); let ioapic_registers = page.start_address().data() as *const u32; let ioapic = IoApic::new(ioapic_registers, madt_ioapic.gsi_base); assert_eq!(ioapic.regs.lock().id(), madt_ioapic.id, "mismatched ACPI MADT I/O APIC ID, and the ID reported by the I/O APIC"); IOAPICS.get_or_insert_with(Vec::new).push(ioapic); } #[cfg(feature = "acpi")] pub unsafe fn handle_src_override(src_override: &'static MadtIntSrcOverride) { let flags = src_override.flags; let polarity_raw = (flags & 0x0003) as u8; let trigger_mode_raw = ((flags & 0x000C) >> 2) as u8; let polarity = match polarity_raw { 0b00 => Polarity::ConformsToSpecs, 0b01 => Polarity::ActiveHigh, 0b10 => return, // reserved 0b11 => Polarity::ActiveLow, _ => unreachable!(), }; let trigger_mode = match trigger_mode_raw { 0b00 => TriggerMode::ConformsToSpecs, 0b01 => TriggerMode::Edge, 0b10 => return, // reserved 0b11 => TriggerMode::Level, _ => unreachable!(), }; let over = Override { bus_irq: src_override.irq_source, gsi: src_override.gsi_base, polarity, trigger_mode, }; SRC_OVERRIDES.get_or_insert_with(Vec::new).push(over); } pub unsafe fn init(active_table: &mut KernelMapper) { let bsp_apic_id = cpuid().unwrap().get_feature_info().unwrap().initial_local_apic_id(); // TODO: remove unwraps // search the madt for all IOAPICs. #[cfg(feature = "acpi")] { let madt: &'static Madt = match madt::MADT.as_ref() { Some(m) => m, // TODO: Parse MP tables too. None => return, }; if madt.flags & madt::FLAG_PCAT!= 0 { pic::disable(); } // find all I/O APICs (usually one). for entry in madt.iter() { match entry { MadtEntry::IoApic(ioapic) => handle_ioapic(active_table, ioapic), MadtEntry::IntSrcOverride(src_override) => handle_src_override(src_override), _ => (), } } } println!("I/O APICs: {:?}, overrides: {:?}", ioapics(), src_overrides()); // map the legacy PC-compatible IRQs (0-15) to 32-47, just like we did with 8259 PIC (if it // wouldn't have been disabled due to this I/O APIC) for legacy_irq in 0..=15 { let (gsi, trigger_mode, polarity) = match get_override(legacy_irq) { Some(over) => (over.gsi, over.trigger_mode, over.polarity), None => { if src_overrides().iter().any(|over| over.gsi == u32::from(legacy_irq) && over.bus_irq!= legacy_irq) &&!src_overrides().iter().any(|over| over.bus_irq == legacy_irq) { // there's an IRQ conflict, making this legacy IRQ inaccessible. continue; } (legacy_irq.into(), TriggerMode::ConformsToSpecs, Polarity::ConformsToSpecs) } }; let apic = match find_ioapic(gsi) { Some(ioapic) => ioapic, None => { println!("Unable to find a suitable APIC for legacy IRQ {} (GSI {}). It will not be mapped.", legacy_irq, gsi); continue; } }; let redir_tbl_index = (gsi - apic.gsi_start) as u8; let map_info = MapInfo { // only send to the BSP dest: bsp_apic_id, dest_mode: DestinationMode::Physical, delivery_mode: DeliveryMode::Fixed, mask: false, polarity: match polarity { Polarity::ActiveHigh => ApicPolarity::ActiveHigh, Polarity::ActiveLow => ApicPolarity::ActiveLow, Polarity::ConformsToSpecs => ApicPolarity::ActiveHigh, }, trigger_mode: match trigger_mode { TriggerMode::Edge => ApicTriggerMode::Edge, TriggerMode::Level => ApicTriggerMode::Level, TriggerMode::ConformsToSpecs => ApicTriggerMode::Edge, }, vector: 32 + legacy_irq, }; apic.map(redir_tbl_index, map_info); } println!("I/O APICs: {:?}, overrides: {:?}", ioapics(), src_overrides()); irq::set_irq_method(irq::IrqMethod::Apic); // tell the firmware that we're using APIC rather than the default 8259 PIC. // FIXME: With ACPI moved to userspace, we should instead allow userspace to check whether the // IOAPIC has been initialized, and then subsequently let some ACPI driver call the AML from // userspace. /*#[cfg(feature = "acpi")] { let method = { let namespace_guard = crate::acpi::ACPI_TABLE.namespace.read(); if let Some(value) = namespace_guard.as_ref().unwrap().get("\\_PIC") { value.get_as_method().ok() } else { None } }; if let Some(m) = method { m.execute("\\_PIC".into(), vec!(crate::acpi::aml::AmlValue::Integer(1))); } }*/ } fn get_override(irq: u8) -> Option<&'static Override>
fn resolve(irq: u8) -> u32 { get_override(irq).map_or(u32::from(irq), |over| over.gsi) } fn find_ioapic(gsi: u32) -> Option<&'static IoApic> { ioapics().iter().find(|apic| gsi >= apic.gsi_start && gsi < apic.gsi_start + u32::from(apic.count)) } pub unsafe fn mask(irq: u8) { let gsi = resolve(irq); let apic = match find_ioapic(gsi) { Some(a) => a, None => return, }; apic.set_mask(gsi, true); } pub unsafe fn unmask(irq: u8) { let gsi = resolve(irq); let apic = match find_ioapic(gsi) { Some(a) => a, None => return, }; apic.set_mask(gsi, false); }
{ src_overrides().iter().find(|over| over.bus_irq == irq) }
identifier_body
ioapic.rs
use core::{fmt, ptr}; use alloc::vec::Vec; use spin::Mutex; #[cfg(feature = "acpi")] use crate::acpi::madt::{self, Madt, MadtEntry, MadtIoApic, MadtIntSrcOverride}; use crate::arch::interrupt::irq; use crate::memory::Frame; use crate::paging::{KernelMapper, Page, PageFlags, PhysicalAddress, RmmA, RmmArch, VirtualAddress}; use crate::paging::entry::EntryFlags; use super::super::cpuid::cpuid; use super::pic; pub struct IoApicRegs { pointer: *const u32, } impl IoApicRegs { fn ioregsel(&self) -> *const u32 { self.pointer } fn iowin(&self) -> *const u32 { // offset 0x10 unsafe { self.pointer.offset(4) } } fn write_ioregsel(&mut self, value: u32) { unsafe { ptr::write_volatile::<u32>(self.ioregsel() as *mut u32, value) } } fn read_iowin(&self) -> u32 { unsafe { ptr::read_volatile::<u32>(self.iowin()) } } fn write_iowin(&mut self, value: u32) { unsafe { ptr::write_volatile::<u32>(self.iowin() as *mut u32, value) } } fn read_reg(&mut self, reg: u8) -> u32 { self.write_ioregsel(reg.into()); self.read_iowin() } fn write_reg(&mut self, reg: u8, value: u32) { self.write_ioregsel(reg.into()); self.write_iowin(value); } pub fn read_ioapicid(&mut self) -> u32 { self.read_reg(0x00) } pub fn write_ioapicid(&mut self, value: u32) { self.write_reg(0x00, value); } pub fn read_ioapicver(&mut self) -> u32 { self.read_reg(0x01) } pub fn read_ioapicarb(&mut self) -> u32 { self.read_reg(0x02) } pub fn read_ioredtbl(&mut self, idx: u8) -> u64 { assert!(idx < 24); let lo = self.read_reg(0x10 + idx * 2); let hi = self.read_reg(0x10 + idx * 2 + 1); u64::from(lo) | (u64::from(hi) << 32) } pub fn write_ioredtbl(&mut self, idx: u8, value: u64) { assert!(idx < 24); let lo = value as u32; let hi = (value >> 32) as u32; self.write_reg(0x10 + idx * 2, lo); self.write_reg(0x10 + idx * 2 + 1, hi); } pub fn max_redirection_table_entries(&mut self) -> u8 { let ver = self.read_ioapicver(); ((ver & 0x00FF_0000) >> 16) as u8 } pub fn id(&mut self) -> u8 { let id_reg = self.read_ioapicid(); ((id_reg & 0x0F00_0000) >> 24) as u8 } } pub struct IoApic { regs: Mutex<IoApicRegs>, gsi_start: u32, count: u8, } impl IoApic { pub fn new(regs_base: *const u32, gsi_start: u32) -> Self { let mut regs = IoApicRegs { pointer: regs_base }; let count = regs.max_redirection_table_entries(); Self { regs: Mutex::new(regs), gsi_start, count, } } /// Map an interrupt vector to a physical local APIC ID of a processor (thus physical mode). pub fn map(&self, idx: u8, info: MapInfo) { self.regs.lock().write_ioredtbl(idx, info.as_raw()) } pub fn set_mask(&self, gsi: u32, mask: bool) { let idx = (gsi - self.gsi_start) as u8; let mut guard = self.regs.lock(); let mut reg = guard.read_ioredtbl(idx); reg &=!(1 << 16); reg |= u64::from(mask) << 16; guard.write_ioredtbl(idx, reg); } } #[repr(u8)] #[derive(Clone, Copy, Debug)] pub enum ApicTriggerMode { Edge = 0, Level = 1, } #[repr(u8)] #[derive(Clone, Copy, Debug)] pub enum ApicPolarity { ActiveHigh = 0, ActiveLow = 1, } #[repr(u8)] #[derive(Clone, Copy, Debug)] pub enum DestinationMode { Physical = 0, Logical = 1, } #[repr(u8)] #[derive(Clone, Copy, Debug)] pub enum DeliveryMode { Fixed = 0b000, LowestPriority = 0b001, Smi = 0b010, Nmi = 0b100, Init = 0b101, ExtInt = 0b111, } #[derive(Clone, Copy, Debug)] pub struct MapInfo { pub dest: u8, pub mask: bool, pub trigger_mode: ApicTriggerMode, pub polarity: ApicPolarity, pub dest_mode: DestinationMode, pub delivery_mode: DeliveryMode, pub vector: u8, } impl MapInfo { pub fn as_raw(&self) -> u64 { assert!(self.vector >= 0x20); assert!(self.vector <= 0xFE); // TODO: Check for reserved fields. (u64::from(self.dest) << 56) | (u64::from(self.mask) << 16) | ((self.trigger_mode as u64) << 15) | ((self.polarity as u64) << 13) | ((self.dest_mode as u64) << 11) | ((self.delivery_mode as u64) << 8) | u64::from(self.vector) } } impl fmt::Debug for IoApic { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { struct
<'a>(&'a Mutex<IoApicRegs>); impl<'a> fmt::Debug for RedirTable<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let mut guard = self.0.lock(); let count = guard.max_redirection_table_entries(); f.debug_list().entries((0..count).map(|i| guard.read_ioredtbl(i))).finish() } } f.debug_struct("IoApic") .field("redir_table", &RedirTable(&self.regs)) .field("gsi_start", &self.gsi_start) .field("count", &self.count) .finish() } } #[derive(Clone, Copy, Debug)] pub enum TriggerMode { ConformsToSpecs, Edge, Level, } #[derive(Clone, Copy, Debug)] pub enum Polarity { ConformsToSpecs, ActiveHigh, ActiveLow, } #[derive(Clone, Copy, Debug)] pub struct Override { bus_irq: u8, gsi: u32, trigger_mode: TriggerMode, polarity: Polarity, } // static mut because only the AP initializes the I/O Apic, and when that is done, it's solely // accessed immutably. static mut IOAPICS: Option<Vec<IoApic>> = None; // static mut for the same reason as above static mut SRC_OVERRIDES: Option<Vec<Override>> = None; pub fn ioapics() -> &'static [IoApic] { unsafe { IOAPICS.as_ref().map_or(&[], |vector| &vector[..]) } } pub fn src_overrides() -> &'static [Override] { unsafe { SRC_OVERRIDES.as_ref().map_or(&[], |vector| &vector[..]) } } #[cfg(feature = "acpi")] pub unsafe fn handle_ioapic(mapper: &mut KernelMapper, madt_ioapic: &'static MadtIoApic) { // map the I/O APIC registers let frame = Frame::containing_address(PhysicalAddress::new(madt_ioapic.address as usize)); let page = Page::containing_address(VirtualAddress::new(crate::IOAPIC_OFFSET)); assert!(mapper.translate(page.start_address()).is_none()); mapper .get_mut() .expect("expected KernelMapper not to be locked re-entrant while mapping I/O APIC memory") .map_phys(page.start_address(), frame.start_address(), PageFlags::new().write(true).custom_flag(EntryFlags::NO_CACHE.bits(), true)) .expect("failed to map I/O APIC") .flush(); let ioapic_registers = page.start_address().data() as *const u32; let ioapic = IoApic::new(ioapic_registers, madt_ioapic.gsi_base); assert_eq!(ioapic.regs.lock().id(), madt_ioapic.id, "mismatched ACPI MADT I/O APIC ID, and the ID reported by the I/O APIC"); IOAPICS.get_or_insert_with(Vec::new).push(ioapic); } #[cfg(feature = "acpi")] pub unsafe fn handle_src_override(src_override: &'static MadtIntSrcOverride) { let flags = src_override.flags; let polarity_raw = (flags & 0x0003) as u8; let trigger_mode_raw = ((flags & 0x000C) >> 2) as u8; let polarity = match polarity_raw { 0b00 => Polarity::ConformsToSpecs, 0b01 => Polarity::ActiveHigh, 0b10 => return, // reserved 0b11 => Polarity::ActiveLow, _ => unreachable!(), }; let trigger_mode = match trigger_mode_raw { 0b00 => TriggerMode::ConformsToSpecs, 0b01 => TriggerMode::Edge, 0b10 => return, // reserved 0b11 => TriggerMode::Level, _ => unreachable!(), }; let over = Override { bus_irq: src_override.irq_source, gsi: src_override.gsi_base, polarity, trigger_mode, }; SRC_OVERRIDES.get_or_insert_with(Vec::new).push(over); } pub unsafe fn init(active_table: &mut KernelMapper) { let bsp_apic_id = cpuid().unwrap().get_feature_info().unwrap().initial_local_apic_id(); // TODO: remove unwraps // search the madt for all IOAPICs. #[cfg(feature = "acpi")] { let madt: &'static Madt = match madt::MADT.as_ref() { Some(m) => m, // TODO: Parse MP tables too. None => return, }; if madt.flags & madt::FLAG_PCAT!= 0 { pic::disable(); } // find all I/O APICs (usually one). for entry in madt.iter() { match entry { MadtEntry::IoApic(ioapic) => handle_ioapic(active_table, ioapic), MadtEntry::IntSrcOverride(src_override) => handle_src_override(src_override), _ => (), } } } println!("I/O APICs: {:?}, overrides: {:?}", ioapics(), src_overrides()); // map the legacy PC-compatible IRQs (0-15) to 32-47, just like we did with 8259 PIC (if it // wouldn't have been disabled due to this I/O APIC) for legacy_irq in 0..=15 { let (gsi, trigger_mode, polarity) = match get_override(legacy_irq) { Some(over) => (over.gsi, over.trigger_mode, over.polarity), None => { if src_overrides().iter().any(|over| over.gsi == u32::from(legacy_irq) && over.bus_irq!= legacy_irq) &&!src_overrides().iter().any(|over| over.bus_irq == legacy_irq) { // there's an IRQ conflict, making this legacy IRQ inaccessible. continue; } (legacy_irq.into(), TriggerMode::ConformsToSpecs, Polarity::ConformsToSpecs) } }; let apic = match find_ioapic(gsi) { Some(ioapic) => ioapic, None => { println!("Unable to find a suitable APIC for legacy IRQ {} (GSI {}). It will not be mapped.", legacy_irq, gsi); continue; } }; let redir_tbl_index = (gsi - apic.gsi_start) as u8; let map_info = MapInfo { // only send to the BSP dest: bsp_apic_id, dest_mode: DestinationMode::Physical, delivery_mode: DeliveryMode::Fixed, mask: false, polarity: match polarity { Polarity::ActiveHigh => ApicPolarity::ActiveHigh, Polarity::ActiveLow => ApicPolarity::ActiveLow, Polarity::ConformsToSpecs => ApicPolarity::ActiveHigh, }, trigger_mode: match trigger_mode { TriggerMode::Edge => ApicTriggerMode::Edge, TriggerMode::Level => ApicTriggerMode::Level, TriggerMode::ConformsToSpecs => ApicTriggerMode::Edge, }, vector: 32 + legacy_irq, }; apic.map(redir_tbl_index, map_info); } println!("I/O APICs: {:?}, overrides: {:?}", ioapics(), src_overrides()); irq::set_irq_method(irq::IrqMethod::Apic); // tell the firmware that we're using APIC rather than the default 8259 PIC. // FIXME: With ACPI moved to userspace, we should instead allow userspace to check whether the // IOAPIC has been initialized, and then subsequently let some ACPI driver call the AML from // userspace. /*#[cfg(feature = "acpi")] { let method = { let namespace_guard = crate::acpi::ACPI_TABLE.namespace.read(); if let Some(value) = namespace_guard.as_ref().unwrap().get("\\_PIC") { value.get_as_method().ok() } else { None } }; if let Some(m) = method { m.execute("\\_PIC".into(), vec!(crate::acpi::aml::AmlValue::Integer(1))); } }*/ } fn get_override(irq: u8) -> Option<&'static Override> { src_overrides().iter().find(|over| over.bus_irq == irq) } fn resolve(irq: u8) -> u32 { get_override(irq).map_or(u32::from(irq), |over| over.gsi) } fn find_ioapic(gsi: u32) -> Option<&'static IoApic> { ioapics().iter().find(|apic| gsi >= apic.gsi_start && gsi < apic.gsi_start + u32::from(apic.count)) } pub unsafe fn mask(irq: u8) { let gsi = resolve(irq); let apic = match find_ioapic(gsi) { Some(a) => a, None => return, }; apic.set_mask(gsi, true); } pub unsafe fn unmask(irq: u8) { let gsi = resolve(irq); let apic = match find_ioapic(gsi) { Some(a) => a, None => return, }; apic.set_mask(gsi, false); }
RedirTable
identifier_name
binomial.rs
// Copyright 2018 Developers of the Rand project. // Copyright 2016-2017 The Rust Project Developers. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // https://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! The binomial distribution. #![allow(deprecated)] #![allow(clippy::all)] use crate::distributions::{Distribution, Uniform}; use crate::Rng; /// The binomial distribution `Binomial(n, p)`. /// /// This distribution has density function: /// `f(k) = n!/(k! (n-k)!) p^k (1-p)^(n-k)` for `k >= 0`. #[deprecated(since = "0.7.0", note = "moved to rand_distr crate")] #[derive(Clone, Copy, Debug)] pub struct Binomial { /// Number of trials. n: u64, /// Probability of success. p: f64, } impl Binomial { /// Construct a new `Binomial` with the given shape parameters `n` (number /// of trials) and `p` (probability of success). /// /// Panics if `p < 0` or `p > 1`. pub fn new(n: u64, p: f64) -> Binomial { assert!(p >= 0.0, "Binomial::new called with p < 0"); assert!(p <= 1.0, "Binomial::new called with p > 1"); Binomial { n, p } } } /// Convert a `f64` to an `i64`, panicing on overflow. // In the future (Rust 1.34), this might be replaced with `TryFrom`. fn f64_to_i64(x: f64) -> i64 { assert!(x < (::std::i64::MAX as f64)); x as i64 } impl Distribution<u64> for Binomial { fn sample<R: Rng +?Sized>(&self, rng: &mut R) -> u64 { // Handle these values directly. if self.p == 0.0 { return 0; } else if self.p == 1.0 { return self.n; } // The binomial distribution is symmetrical with respect to p -> 1-p, // k -> n-k switch p so that it is less than 0.5 - this allows for lower // expected values we will just invert the result at the end let p = if self.p <= 0.5 { self.p } else { 1.0 - self.p }; let result; let q = 1. - p; // For small n * min(p, 1 - p), the BINV algorithm based on the inverse // transformation of the binomial distribution is efficient. Otherwise, // the BTPE algorithm is used. // // Voratas Kachitvichyanukul and Bruce W. Schmeiser. 1988. Binomial // random variate generation. Commun. ACM 31, 2 (February 1988), // 216-222. http://dx.doi.org/10.1145/42372.42381 // Threshold for prefering the BINV algorithm. The paper suggests 10, // Ranlib uses 30, and GSL uses 14. const BINV_THRESHOLD: f64 = 10.; if (self.n as f64) * p < BINV_THRESHOLD && self.n <= (::std::i32::MAX as u64) { // Use the BINV algorithm. let s = p / q; let a = ((self.n + 1) as f64) * s; let mut r = q.powi(self.n as i32); let mut u: f64 = rng.gen(); let mut x = 0; while u > r as f64 { u -= r; x += 1; r *= a / (x as f64) - s; } result = x; } else { // Use the BTPE algorithm. // Threshold for using the squeeze algorithm. This can be freely // chosen based on performance. Ranlib and GSL use 20. const SQUEEZE_THRESHOLD: i64 = 20; // Step 0: Calculate constants as functions of `n` and `p`. let n = self.n as f64; let np = n * p; let npq = np * q; let f_m = np + p; let m = f64_to_i64(f_m); // radius of triangle region, since height=1 also area of region let p1 = (2.195 * npq.sqrt() - 4.6 * q).floor() + 0.5; // tip of triangle let x_m = (m as f64) + 0.5; // left edge of triangle let x_l = x_m - p1; // right edge of triangle let x_r = x_m + p1; let c = 0.134 + 20.5 / (15.3 + (m as f64)); // p1 + area of parallelogram region let p2 = p1 * (1. + 2. * c); fn lambda(a: f64) -> f64 { a * (1. + 0.5 * a) } let lambda_l = lambda((f_m - x_l) / (f_m - x_l * p)); let lambda_r = lambda((x_r - f_m) / (x_r * q)); // p1 + area of left tail let p3 = p2 + c / lambda_l; // p1 + area of right tail let p4 = p3 + c / lambda_r; // return value let mut y: i64; let gen_u = Uniform::new(0., p4); let gen_v = Uniform::new(0., 1.); loop { // Step 1: Generate `u` for selecting the region. If region 1 is // selected, generate a triangularly distributed variate. let u = gen_u.sample(rng); let mut v = gen_v.sample(rng); if!(u > p1) { y = f64_to_i64(x_m - p1 * v + u); break; } if!(u > p2) { // Step 2: Region 2, parallelograms. Check if region 2 is // used. If so, generate `y`. let x = x_l + (u - p1) / c; v = v * c + 1.0 - (x - x_m).abs() / p1; if v > 1. { continue; } else { y = f64_to_i64(x); } } else if!(u > p3) { // Step 3: Region 3, left exponential tail. y = f64_to_i64(x_l + v.ln() / lambda_l); if y < 0 { continue; } else { v *= (u - p2) * lambda_l; } } else { // Step 4: Region 4, right exponential tail. y = f64_to_i64(x_r - v.ln() / lambda_r); if y > 0 && (y as u64) > self.n { continue; } else { v *= (u - p3) * lambda_r; } } // Step 5: Acceptance/rejection comparison. // Step 5.0: Test for appropriate method of evaluating f(y). let k = (y - m).abs(); if!(k > SQUEEZE_THRESHOLD && (k as f64) < 0.5 * npq - 1.) { // Step 5.1: Evaluate f(y) via the recursive relationship. Start the // search from the mode. let s = p / q; let a = s * (n + 1.); let mut f = 1.0; if m < y { let mut i = m; loop { i += 1; f *= a / (i as f64) - s; if i == y { break; } } } else if m > y { let mut i = y; loop { i += 1; f /= a / (i as f64) - s; if i == m { break; } } } if v > f { continue; } else { break; } } // Step 5.2: Squeezing. Check the value of ln(v) againts upper and // lower bound of ln(f(y)). let k = k as f64; let rho = (k / npq) * ((k * (k / 3. + 0.625) + 1. / 6.) / npq + 0.5); let t = -0.5 * k * k / npq; let alpha = v.ln(); if alpha < t - rho { break; } if alpha > t + rho { continue; } // Step 5.3: Final acceptance/rejection test. let x1 = (y + 1) as f64; let f1 = (m + 1) as f64; let z = (f64_to_i64(n) + 1 - m) as f64; let w = (f64_to_i64(n) - y + 1) as f64; fn stirling(a: f64) -> f64 { let a2 = a * a; (13860. - (462. - (132. - (99. - 140. / a2) / a2) / a2) / a2) / a / 166320. } if alpha > x_m * (f1 / x1).ln() + (n - (m as f64) + 0.5) * (z / w).ln() + ((y - m) as f64) * (w * p / (x1 * q)).ln() // We use the signs from the GSL implementation, which are // different than the ones in the reference. According to // the GSL authors, the new signs were verified to be // correct by one of the original designers of the // algorithm. + stirling(f1) + stirling(z) - stirling(x1) - stirling(w) { continue; } break; } assert!(y >= 0); result = y as u64; } // Invert the result for p < 0.5. if p!= self.p { self.n - result } else { result } } } #[cfg(test)] mod test { use super::Binomial; use crate::distributions::Distribution; use crate::Rng; fn test_binomial_mean_and_variance<R: Rng>(n: u64, p: f64, rng: &mut R) { let binomial = Binomial::new(n, p); let expected_mean = n as f64 * p; let expected_variance = n as f64 * p * (1.0 - p);
for i in results.iter_mut() { *i = binomial.sample(rng) as f64; } let mean = results.iter().sum::<f64>() / results.len() as f64; assert!( (mean as f64 - expected_mean).abs() < expected_mean / 50.0, "mean: {}, expected_mean: {}", mean, expected_mean ); let variance = results.iter().map(|x| (x - mean) * (x - mean)).sum::<f64>() / results.len() as f64; assert!( (variance - expected_variance).abs() < expected_variance / 10.0, "variance: {}, expected_variance: {}", variance, expected_variance ); } #[test] #[cfg_attr(miri, ignore)] // Miri is too slow fn test_binomial() { let mut rng = crate::test::rng(351); test_binomial_mean_and_variance(150, 0.1, &mut rng); test_binomial_mean_and_variance(70, 0.6, &mut rng); test_binomial_mean_and_variance(40, 0.5, &mut rng); test_binomial_mean_and_variance(20, 0.7, &mut rng); test_binomial_mean_and_variance(20, 0.5, &mut rng); } #[test] fn test_binomial_end_points() { let mut rng = crate::test::rng(352); assert_eq!(rng.sample(Binomial::new(20, 0.0)), 0); assert_eq!(rng.sample(Binomial::new(20, 1.0)), 20); } #[test] #[should_panic] fn test_binomial_invalid_lambda_neg() { Binomial::new(20, -10.0); } }
let mut results = [0.0; 1000];
random_line_split
binomial.rs
// Copyright 2018 Developers of the Rand project. // Copyright 2016-2017 The Rust Project Developers. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // https://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! The binomial distribution. #![allow(deprecated)] #![allow(clippy::all)] use crate::distributions::{Distribution, Uniform}; use crate::Rng; /// The binomial distribution `Binomial(n, p)`. /// /// This distribution has density function: /// `f(k) = n!/(k! (n-k)!) p^k (1-p)^(n-k)` for `k >= 0`. #[deprecated(since = "0.7.0", note = "moved to rand_distr crate")] #[derive(Clone, Copy, Debug)] pub struct Binomial { /// Number of trials. n: u64, /// Probability of success. p: f64, } impl Binomial { /// Construct a new `Binomial` with the given shape parameters `n` (number /// of trials) and `p` (probability of success). /// /// Panics if `p < 0` or `p > 1`. pub fn new(n: u64, p: f64) -> Binomial { assert!(p >= 0.0, "Binomial::new called with p < 0"); assert!(p <= 1.0, "Binomial::new called with p > 1"); Binomial { n, p } } } /// Convert a `f64` to an `i64`, panicing on overflow. // In the future (Rust 1.34), this might be replaced with `TryFrom`. fn f64_to_i64(x: f64) -> i64 { assert!(x < (::std::i64::MAX as f64)); x as i64 } impl Distribution<u64> for Binomial { fn sample<R: Rng +?Sized>(&self, rng: &mut R) -> u64 { // Handle these values directly. if self.p == 0.0 { return 0; } else if self.p == 1.0 { return self.n; } // The binomial distribution is symmetrical with respect to p -> 1-p, // k -> n-k switch p so that it is less than 0.5 - this allows for lower // expected values we will just invert the result at the end let p = if self.p <= 0.5 { self.p } else { 1.0 - self.p }; let result; let q = 1. - p; // For small n * min(p, 1 - p), the BINV algorithm based on the inverse // transformation of the binomial distribution is efficient. Otherwise, // the BTPE algorithm is used. // // Voratas Kachitvichyanukul and Bruce W. Schmeiser. 1988. Binomial // random variate generation. Commun. ACM 31, 2 (February 1988), // 216-222. http://dx.doi.org/10.1145/42372.42381 // Threshold for prefering the BINV algorithm. The paper suggests 10, // Ranlib uses 30, and GSL uses 14. const BINV_THRESHOLD: f64 = 10.; if (self.n as f64) * p < BINV_THRESHOLD && self.n <= (::std::i32::MAX as u64) { // Use the BINV algorithm. let s = p / q; let a = ((self.n + 1) as f64) * s; let mut r = q.powi(self.n as i32); let mut u: f64 = rng.gen(); let mut x = 0; while u > r as f64 { u -= r; x += 1; r *= a / (x as f64) - s; } result = x; } else { // Use the BTPE algorithm. // Threshold for using the squeeze algorithm. This can be freely // chosen based on performance. Ranlib and GSL use 20. const SQUEEZE_THRESHOLD: i64 = 20; // Step 0: Calculate constants as functions of `n` and `p`. let n = self.n as f64; let np = n * p; let npq = np * q; let f_m = np + p; let m = f64_to_i64(f_m); // radius of triangle region, since height=1 also area of region let p1 = (2.195 * npq.sqrt() - 4.6 * q).floor() + 0.5; // tip of triangle let x_m = (m as f64) + 0.5; // left edge of triangle let x_l = x_m - p1; // right edge of triangle let x_r = x_m + p1; let c = 0.134 + 20.5 / (15.3 + (m as f64)); // p1 + area of parallelogram region let p2 = p1 * (1. + 2. * c); fn lambda(a: f64) -> f64 { a * (1. + 0.5 * a) } let lambda_l = lambda((f_m - x_l) / (f_m - x_l * p)); let lambda_r = lambda((x_r - f_m) / (x_r * q)); // p1 + area of left tail let p3 = p2 + c / lambda_l; // p1 + area of right tail let p4 = p3 + c / lambda_r; // return value let mut y: i64; let gen_u = Uniform::new(0., p4); let gen_v = Uniform::new(0., 1.); loop { // Step 1: Generate `u` for selecting the region. If region 1 is // selected, generate a triangularly distributed variate. let u = gen_u.sample(rng); let mut v = gen_v.sample(rng); if!(u > p1) { y = f64_to_i64(x_m - p1 * v + u); break; } if!(u > p2) { // Step 2: Region 2, parallelograms. Check if region 2 is // used. If so, generate `y`. let x = x_l + (u - p1) / c; v = v * c + 1.0 - (x - x_m).abs() / p1; if v > 1. { continue; } else { y = f64_to_i64(x); } } else if!(u > p3) { // Step 3: Region 3, left exponential tail. y = f64_to_i64(x_l + v.ln() / lambda_l); if y < 0 { continue; } else { v *= (u - p2) * lambda_l; } } else { // Step 4: Region 4, right exponential tail. y = f64_to_i64(x_r - v.ln() / lambda_r); if y > 0 && (y as u64) > self.n { continue; } else { v *= (u - p3) * lambda_r; } } // Step 5: Acceptance/rejection comparison. // Step 5.0: Test for appropriate method of evaluating f(y). let k = (y - m).abs(); if!(k > SQUEEZE_THRESHOLD && (k as f64) < 0.5 * npq - 1.) { // Step 5.1: Evaluate f(y) via the recursive relationship. Start the // search from the mode. let s = p / q; let a = s * (n + 1.); let mut f = 1.0; if m < y { let mut i = m; loop { i += 1; f *= a / (i as f64) - s; if i == y { break; } } } else if m > y { let mut i = y; loop { i += 1; f /= a / (i as f64) - s; if i == m { break; } } } if v > f { continue; } else { break; } } // Step 5.2: Squeezing. Check the value of ln(v) againts upper and // lower bound of ln(f(y)). let k = k as f64; let rho = (k / npq) * ((k * (k / 3. + 0.625) + 1. / 6.) / npq + 0.5); let t = -0.5 * k * k / npq; let alpha = v.ln(); if alpha < t - rho { break; } if alpha > t + rho { continue; } // Step 5.3: Final acceptance/rejection test. let x1 = (y + 1) as f64; let f1 = (m + 1) as f64; let z = (f64_to_i64(n) + 1 - m) as f64; let w = (f64_to_i64(n) - y + 1) as f64; fn stirling(a: f64) -> f64 { let a2 = a * a; (13860. - (462. - (132. - (99. - 140. / a2) / a2) / a2) / a2) / a / 166320. } if alpha > x_m * (f1 / x1).ln() + (n - (m as f64) + 0.5) * (z / w).ln() + ((y - m) as f64) * (w * p / (x1 * q)).ln() // We use the signs from the GSL implementation, which are // different than the ones in the reference. According to // the GSL authors, the new signs were verified to be // correct by one of the original designers of the // algorithm. + stirling(f1) + stirling(z) - stirling(x1) - stirling(w) { continue; } break; } assert!(y >= 0); result = y as u64; } // Invert the result for p < 0.5. if p!= self.p
else { result } } } #[cfg(test)] mod test { use super::Binomial; use crate::distributions::Distribution; use crate::Rng; fn test_binomial_mean_and_variance<R: Rng>(n: u64, p: f64, rng: &mut R) { let binomial = Binomial::new(n, p); let expected_mean = n as f64 * p; let expected_variance = n as f64 * p * (1.0 - p); let mut results = [0.0; 1000]; for i in results.iter_mut() { *i = binomial.sample(rng) as f64; } let mean = results.iter().sum::<f64>() / results.len() as f64; assert!( (mean as f64 - expected_mean).abs() < expected_mean / 50.0, "mean: {}, expected_mean: {}", mean, expected_mean ); let variance = results.iter().map(|x| (x - mean) * (x - mean)).sum::<f64>() / results.len() as f64; assert!( (variance - expected_variance).abs() < expected_variance / 10.0, "variance: {}, expected_variance: {}", variance, expected_variance ); } #[test] #[cfg_attr(miri, ignore)] // Miri is too slow fn test_binomial() { let mut rng = crate::test::rng(351); test_binomial_mean_and_variance(150, 0.1, &mut rng); test_binomial_mean_and_variance(70, 0.6, &mut rng); test_binomial_mean_and_variance(40, 0.5, &mut rng); test_binomial_mean_and_variance(20, 0.7, &mut rng); test_binomial_mean_and_variance(20, 0.5, &mut rng); } #[test] fn test_binomial_end_points() { let mut rng = crate::test::rng(352); assert_eq!(rng.sample(Binomial::new(20, 0.0)), 0); assert_eq!(rng.sample(Binomial::new(20, 1.0)), 20); } #[test] #[should_panic] fn test_binomial_invalid_lambda_neg() { Binomial::new(20, -10.0); } }
{ self.n - result }
conditional_block
binomial.rs
// Copyright 2018 Developers of the Rand project. // Copyright 2016-2017 The Rust Project Developers. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // https://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! The binomial distribution. #![allow(deprecated)] #![allow(clippy::all)] use crate::distributions::{Distribution, Uniform}; use crate::Rng; /// The binomial distribution `Binomial(n, p)`. /// /// This distribution has density function: /// `f(k) = n!/(k! (n-k)!) p^k (1-p)^(n-k)` for `k >= 0`. #[deprecated(since = "0.7.0", note = "moved to rand_distr crate")] #[derive(Clone, Copy, Debug)] pub struct Binomial { /// Number of trials. n: u64, /// Probability of success. p: f64, } impl Binomial { /// Construct a new `Binomial` with the given shape parameters `n` (number /// of trials) and `p` (probability of success). /// /// Panics if `p < 0` or `p > 1`. pub fn new(n: u64, p: f64) -> Binomial { assert!(p >= 0.0, "Binomial::new called with p < 0"); assert!(p <= 1.0, "Binomial::new called with p > 1"); Binomial { n, p } } } /// Convert a `f64` to an `i64`, panicing on overflow. // In the future (Rust 1.34), this might be replaced with `TryFrom`. fn f64_to_i64(x: f64) -> i64 { assert!(x < (::std::i64::MAX as f64)); x as i64 } impl Distribution<u64> for Binomial { fn sample<R: Rng +?Sized>(&self, rng: &mut R) -> u64 { // Handle these values directly. if self.p == 0.0 { return 0; } else if self.p == 1.0 { return self.n; } // The binomial distribution is symmetrical with respect to p -> 1-p, // k -> n-k switch p so that it is less than 0.5 - this allows for lower // expected values we will just invert the result at the end let p = if self.p <= 0.5 { self.p } else { 1.0 - self.p }; let result; let q = 1. - p; // For small n * min(p, 1 - p), the BINV algorithm based on the inverse // transformation of the binomial distribution is efficient. Otherwise, // the BTPE algorithm is used. // // Voratas Kachitvichyanukul and Bruce W. Schmeiser. 1988. Binomial // random variate generation. Commun. ACM 31, 2 (February 1988), // 216-222. http://dx.doi.org/10.1145/42372.42381 // Threshold for prefering the BINV algorithm. The paper suggests 10, // Ranlib uses 30, and GSL uses 14. const BINV_THRESHOLD: f64 = 10.; if (self.n as f64) * p < BINV_THRESHOLD && self.n <= (::std::i32::MAX as u64) { // Use the BINV algorithm. let s = p / q; let a = ((self.n + 1) as f64) * s; let mut r = q.powi(self.n as i32); let mut u: f64 = rng.gen(); let mut x = 0; while u > r as f64 { u -= r; x += 1; r *= a / (x as f64) - s; } result = x; } else { // Use the BTPE algorithm. // Threshold for using the squeeze algorithm. This can be freely // chosen based on performance. Ranlib and GSL use 20. const SQUEEZE_THRESHOLD: i64 = 20; // Step 0: Calculate constants as functions of `n` and `p`. let n = self.n as f64; let np = n * p; let npq = np * q; let f_m = np + p; let m = f64_to_i64(f_m); // radius of triangle region, since height=1 also area of region let p1 = (2.195 * npq.sqrt() - 4.6 * q).floor() + 0.5; // tip of triangle let x_m = (m as f64) + 0.5; // left edge of triangle let x_l = x_m - p1; // right edge of triangle let x_r = x_m + p1; let c = 0.134 + 20.5 / (15.3 + (m as f64)); // p1 + area of parallelogram region let p2 = p1 * (1. + 2. * c); fn lambda(a: f64) -> f64 { a * (1. + 0.5 * a) } let lambda_l = lambda((f_m - x_l) / (f_m - x_l * p)); let lambda_r = lambda((x_r - f_m) / (x_r * q)); // p1 + area of left tail let p3 = p2 + c / lambda_l; // p1 + area of right tail let p4 = p3 + c / lambda_r; // return value let mut y: i64; let gen_u = Uniform::new(0., p4); let gen_v = Uniform::new(0., 1.); loop { // Step 1: Generate `u` for selecting the region. If region 1 is // selected, generate a triangularly distributed variate. let u = gen_u.sample(rng); let mut v = gen_v.sample(rng); if!(u > p1) { y = f64_to_i64(x_m - p1 * v + u); break; } if!(u > p2) { // Step 2: Region 2, parallelograms. Check if region 2 is // used. If so, generate `y`. let x = x_l + (u - p1) / c; v = v * c + 1.0 - (x - x_m).abs() / p1; if v > 1. { continue; } else { y = f64_to_i64(x); } } else if!(u > p3) { // Step 3: Region 3, left exponential tail. y = f64_to_i64(x_l + v.ln() / lambda_l); if y < 0 { continue; } else { v *= (u - p2) * lambda_l; } } else { // Step 4: Region 4, right exponential tail. y = f64_to_i64(x_r - v.ln() / lambda_r); if y > 0 && (y as u64) > self.n { continue; } else { v *= (u - p3) * lambda_r; } } // Step 5: Acceptance/rejection comparison. // Step 5.0: Test for appropriate method of evaluating f(y). let k = (y - m).abs(); if!(k > SQUEEZE_THRESHOLD && (k as f64) < 0.5 * npq - 1.) { // Step 5.1: Evaluate f(y) via the recursive relationship. Start the // search from the mode. let s = p / q; let a = s * (n + 1.); let mut f = 1.0; if m < y { let mut i = m; loop { i += 1; f *= a / (i as f64) - s; if i == y { break; } } } else if m > y { let mut i = y; loop { i += 1; f /= a / (i as f64) - s; if i == m { break; } } } if v > f { continue; } else { break; } } // Step 5.2: Squeezing. Check the value of ln(v) againts upper and // lower bound of ln(f(y)). let k = k as f64; let rho = (k / npq) * ((k * (k / 3. + 0.625) + 1. / 6.) / npq + 0.5); let t = -0.5 * k * k / npq; let alpha = v.ln(); if alpha < t - rho { break; } if alpha > t + rho { continue; } // Step 5.3: Final acceptance/rejection test. let x1 = (y + 1) as f64; let f1 = (m + 1) as f64; let z = (f64_to_i64(n) + 1 - m) as f64; let w = (f64_to_i64(n) - y + 1) as f64; fn stirling(a: f64) -> f64 { let a2 = a * a; (13860. - (462. - (132. - (99. - 140. / a2) / a2) / a2) / a2) / a / 166320. } if alpha > x_m * (f1 / x1).ln() + (n - (m as f64) + 0.5) * (z / w).ln() + ((y - m) as f64) * (w * p / (x1 * q)).ln() // We use the signs from the GSL implementation, which are // different than the ones in the reference. According to // the GSL authors, the new signs were verified to be // correct by one of the original designers of the // algorithm. + stirling(f1) + stirling(z) - stirling(x1) - stirling(w) { continue; } break; } assert!(y >= 0); result = y as u64; } // Invert the result for p < 0.5. if p!= self.p { self.n - result } else { result } } } #[cfg(test)] mod test { use super::Binomial; use crate::distributions::Distribution; use crate::Rng; fn test_binomial_mean_and_variance<R: Rng>(n: u64, p: f64, rng: &mut R) { let binomial = Binomial::new(n, p); let expected_mean = n as f64 * p; let expected_variance = n as f64 * p * (1.0 - p); let mut results = [0.0; 1000]; for i in results.iter_mut() { *i = binomial.sample(rng) as f64; } let mean = results.iter().sum::<f64>() / results.len() as f64; assert!( (mean as f64 - expected_mean).abs() < expected_mean / 50.0, "mean: {}, expected_mean: {}", mean, expected_mean ); let variance = results.iter().map(|x| (x - mean) * (x - mean)).sum::<f64>() / results.len() as f64; assert!( (variance - expected_variance).abs() < expected_variance / 10.0, "variance: {}, expected_variance: {}", variance, expected_variance ); } #[test] #[cfg_attr(miri, ignore)] // Miri is too slow fn
() { let mut rng = crate::test::rng(351); test_binomial_mean_and_variance(150, 0.1, &mut rng); test_binomial_mean_and_variance(70, 0.6, &mut rng); test_binomial_mean_and_variance(40, 0.5, &mut rng); test_binomial_mean_and_variance(20, 0.7, &mut rng); test_binomial_mean_and_variance(20, 0.5, &mut rng); } #[test] fn test_binomial_end_points() { let mut rng = crate::test::rng(352); assert_eq!(rng.sample(Binomial::new(20, 0.0)), 0); assert_eq!(rng.sample(Binomial::new(20, 1.0)), 20); } #[test] #[should_panic] fn test_binomial_invalid_lambda_neg() { Binomial::new(20, -10.0); } }
test_binomial
identifier_name
binomial.rs
// Copyright 2018 Developers of the Rand project. // Copyright 2016-2017 The Rust Project Developers. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // https://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! The binomial distribution. #![allow(deprecated)] #![allow(clippy::all)] use crate::distributions::{Distribution, Uniform}; use crate::Rng; /// The binomial distribution `Binomial(n, p)`. /// /// This distribution has density function: /// `f(k) = n!/(k! (n-k)!) p^k (1-p)^(n-k)` for `k >= 0`. #[deprecated(since = "0.7.0", note = "moved to rand_distr crate")] #[derive(Clone, Copy, Debug)] pub struct Binomial { /// Number of trials. n: u64, /// Probability of success. p: f64, } impl Binomial { /// Construct a new `Binomial` with the given shape parameters `n` (number /// of trials) and `p` (probability of success). /// /// Panics if `p < 0` or `p > 1`. pub fn new(n: u64, p: f64) -> Binomial { assert!(p >= 0.0, "Binomial::new called with p < 0"); assert!(p <= 1.0, "Binomial::new called with p > 1"); Binomial { n, p } } } /// Convert a `f64` to an `i64`, panicing on overflow. // In the future (Rust 1.34), this might be replaced with `TryFrom`. fn f64_to_i64(x: f64) -> i64 { assert!(x < (::std::i64::MAX as f64)); x as i64 } impl Distribution<u64> for Binomial { fn sample<R: Rng +?Sized>(&self, rng: &mut R) -> u64 { // Handle these values directly. if self.p == 0.0 { return 0; } else if self.p == 1.0 { return self.n; } // The binomial distribution is symmetrical with respect to p -> 1-p, // k -> n-k switch p so that it is less than 0.5 - this allows for lower // expected values we will just invert the result at the end let p = if self.p <= 0.5 { self.p } else { 1.0 - self.p }; let result; let q = 1. - p; // For small n * min(p, 1 - p), the BINV algorithm based on the inverse // transformation of the binomial distribution is efficient. Otherwise, // the BTPE algorithm is used. // // Voratas Kachitvichyanukul and Bruce W. Schmeiser. 1988. Binomial // random variate generation. Commun. ACM 31, 2 (February 1988), // 216-222. http://dx.doi.org/10.1145/42372.42381 // Threshold for prefering the BINV algorithm. The paper suggests 10, // Ranlib uses 30, and GSL uses 14. const BINV_THRESHOLD: f64 = 10.; if (self.n as f64) * p < BINV_THRESHOLD && self.n <= (::std::i32::MAX as u64) { // Use the BINV algorithm. let s = p / q; let a = ((self.n + 1) as f64) * s; let mut r = q.powi(self.n as i32); let mut u: f64 = rng.gen(); let mut x = 0; while u > r as f64 { u -= r; x += 1; r *= a / (x as f64) - s; } result = x; } else { // Use the BTPE algorithm. // Threshold for using the squeeze algorithm. This can be freely // chosen based on performance. Ranlib and GSL use 20. const SQUEEZE_THRESHOLD: i64 = 20; // Step 0: Calculate constants as functions of `n` and `p`. let n = self.n as f64; let np = n * p; let npq = np * q; let f_m = np + p; let m = f64_to_i64(f_m); // radius of triangle region, since height=1 also area of region let p1 = (2.195 * npq.sqrt() - 4.6 * q).floor() + 0.5; // tip of triangle let x_m = (m as f64) + 0.5; // left edge of triangle let x_l = x_m - p1; // right edge of triangle let x_r = x_m + p1; let c = 0.134 + 20.5 / (15.3 + (m as f64)); // p1 + area of parallelogram region let p2 = p1 * (1. + 2. * c); fn lambda(a: f64) -> f64
let lambda_l = lambda((f_m - x_l) / (f_m - x_l * p)); let lambda_r = lambda((x_r - f_m) / (x_r * q)); // p1 + area of left tail let p3 = p2 + c / lambda_l; // p1 + area of right tail let p4 = p3 + c / lambda_r; // return value let mut y: i64; let gen_u = Uniform::new(0., p4); let gen_v = Uniform::new(0., 1.); loop { // Step 1: Generate `u` for selecting the region. If region 1 is // selected, generate a triangularly distributed variate. let u = gen_u.sample(rng); let mut v = gen_v.sample(rng); if!(u > p1) { y = f64_to_i64(x_m - p1 * v + u); break; } if!(u > p2) { // Step 2: Region 2, parallelograms. Check if region 2 is // used. If so, generate `y`. let x = x_l + (u - p1) / c; v = v * c + 1.0 - (x - x_m).abs() / p1; if v > 1. { continue; } else { y = f64_to_i64(x); } } else if!(u > p3) { // Step 3: Region 3, left exponential tail. y = f64_to_i64(x_l + v.ln() / lambda_l); if y < 0 { continue; } else { v *= (u - p2) * lambda_l; } } else { // Step 4: Region 4, right exponential tail. y = f64_to_i64(x_r - v.ln() / lambda_r); if y > 0 && (y as u64) > self.n { continue; } else { v *= (u - p3) * lambda_r; } } // Step 5: Acceptance/rejection comparison. // Step 5.0: Test for appropriate method of evaluating f(y). let k = (y - m).abs(); if!(k > SQUEEZE_THRESHOLD && (k as f64) < 0.5 * npq - 1.) { // Step 5.1: Evaluate f(y) via the recursive relationship. Start the // search from the mode. let s = p / q; let a = s * (n + 1.); let mut f = 1.0; if m < y { let mut i = m; loop { i += 1; f *= a / (i as f64) - s; if i == y { break; } } } else if m > y { let mut i = y; loop { i += 1; f /= a / (i as f64) - s; if i == m { break; } } } if v > f { continue; } else { break; } } // Step 5.2: Squeezing. Check the value of ln(v) againts upper and // lower bound of ln(f(y)). let k = k as f64; let rho = (k / npq) * ((k * (k / 3. + 0.625) + 1. / 6.) / npq + 0.5); let t = -0.5 * k * k / npq; let alpha = v.ln(); if alpha < t - rho { break; } if alpha > t + rho { continue; } // Step 5.3: Final acceptance/rejection test. let x1 = (y + 1) as f64; let f1 = (m + 1) as f64; let z = (f64_to_i64(n) + 1 - m) as f64; let w = (f64_to_i64(n) - y + 1) as f64; fn stirling(a: f64) -> f64 { let a2 = a * a; (13860. - (462. - (132. - (99. - 140. / a2) / a2) / a2) / a2) / a / 166320. } if alpha > x_m * (f1 / x1).ln() + (n - (m as f64) + 0.5) * (z / w).ln() + ((y - m) as f64) * (w * p / (x1 * q)).ln() // We use the signs from the GSL implementation, which are // different than the ones in the reference. According to // the GSL authors, the new signs were verified to be // correct by one of the original designers of the // algorithm. + stirling(f1) + stirling(z) - stirling(x1) - stirling(w) { continue; } break; } assert!(y >= 0); result = y as u64; } // Invert the result for p < 0.5. if p!= self.p { self.n - result } else { result } } } #[cfg(test)] mod test { use super::Binomial; use crate::distributions::Distribution; use crate::Rng; fn test_binomial_mean_and_variance<R: Rng>(n: u64, p: f64, rng: &mut R) { let binomial = Binomial::new(n, p); let expected_mean = n as f64 * p; let expected_variance = n as f64 * p * (1.0 - p); let mut results = [0.0; 1000]; for i in results.iter_mut() { *i = binomial.sample(rng) as f64; } let mean = results.iter().sum::<f64>() / results.len() as f64; assert!( (mean as f64 - expected_mean).abs() < expected_mean / 50.0, "mean: {}, expected_mean: {}", mean, expected_mean ); let variance = results.iter().map(|x| (x - mean) * (x - mean)).sum::<f64>() / results.len() as f64; assert!( (variance - expected_variance).abs() < expected_variance / 10.0, "variance: {}, expected_variance: {}", variance, expected_variance ); } #[test] #[cfg_attr(miri, ignore)] // Miri is too slow fn test_binomial() { let mut rng = crate::test::rng(351); test_binomial_mean_and_variance(150, 0.1, &mut rng); test_binomial_mean_and_variance(70, 0.6, &mut rng); test_binomial_mean_and_variance(40, 0.5, &mut rng); test_binomial_mean_and_variance(20, 0.7, &mut rng); test_binomial_mean_and_variance(20, 0.5, &mut rng); } #[test] fn test_binomial_end_points() { let mut rng = crate::test::rng(352); assert_eq!(rng.sample(Binomial::new(20, 0.0)), 0); assert_eq!(rng.sample(Binomial::new(20, 1.0)), 20); } #[test] #[should_panic] fn test_binomial_invalid_lambda_neg() { Binomial::new(20, -10.0); } }
{ a * (1. + 0.5 * a) }
identifier_body
main.rs
use anyhow::{Result, bail}; use futures::{FutureExt, StreamExt}; use warp::Filter; use warp::ws::{Message, WebSocket}; use tokio::sync::{mpsc, RwLock}; use std::collections::{HashMap, hash_map}; use std::sync::{ Arc, atomic::{AtomicUsize, Ordering}, }; use rand::seq::IteratorRandom; use std::convert::Infallible; use schema::{Message as WsMsg, Role, Prompt, Answer, LoginRejectedReason}; mod util; mod deck; use util::expand_underscores; use deck::Deck; #[derive(Default)] struct Game { prompts: Deck<Prompt>, answers: Deck<Answer>, round: Option<Round>, clients: HashMap<usize, mpsc::UnboundedSender<schema::Message>>, players: HashMap<usize, Player>, } static N_CARDS_IN_HAND: usize = 4; static MIN_N_PLAYERS: usize = 3; static MAX_N_PLAYERS: usize = 3; static N_UNDERSCORES: usize = 5; impl Game { fn distribute_cards(&mut self) { for player in &mut self.players.values_mut() { if player.hand.len() < N_CARDS_IN_HAND { player.hand.extend(self.answers.draw(N_CARDS_IN_HAND - player.hand.len())); } } } fn new_round(&mut self) -> Result<()> { if self.players.len() == 0 { bail!("There are no players!"); } let mut next_czar = 0; // Discard current round if let Some(Round{ prompt, answers, czar,.. }) = self.round.take() { next_czar = czar+1; self.prompts.discard(&[prompt]); for cards in answers.values() { self.answers.discard(cards); } } // Find next czar let mut player_ids = self.players.keys().collect::<Vec<_>>(); player_ids.sort_unstable(); if let Err(idx) = player_ids.binary_search(&&next_czar) { // There's no player with ID next_czar if idx == player_ids.len() { // There isn't a greater key next_czar = *player_ids[0]; } else { // There is a key greater than next_czar next_czar = *player_ids[idx]; } } // Create new round println!("Players to choose from: {:?}", self.players.keys().map(|u| u.to_string()).collect::<Vec<_>>().join(", ")); let round = Round { prompt: self.prompts.draw_once(), // TODO cycle Czars czar: next_czar, answers: Default::default(), state: RoundState::Answering, }; println!("Next czar is Player #{}", round.czar); // Distribute cards and notify players self.distribute_cards(); for (id, player) in &mut self.players { let role = if *id == round.czar { Role::Czar } else { Role::Player }; self.clients[id].send(WsMsg::NewRound { role, prompt: round.prompt.clone(), hand: player.hand.clone(), })?; } // Set new round self.round = Some(round); Ok(()) } fn broadcast_to_players(&mut self, msg: &WsMsg) -> Result<()> { for id in self.players.keys() { self.clients[id].send(msg.clone())?; } Ok(()) } } #[derive(PartialEq)] enum RoundState { Answering, Judging, } struct Round { prompt: Prompt, czar: usize, answers: HashMap<usize, Vec<Answer>>, state: RoundState, } struct Player { name: String, hand: Vec<Answer>, score: u64, } static NEXT_USER_ID: AtomicUsize = AtomicUsize::new(1); async fn process_message( game: &Arc<RwLock<Game>>, user_id: usize, msg: WsMsg, tx: &mpsc::UnboundedSender<WsMsg> ) -> Result<()> { match msg { WsMsg::Login(username) => { if game.read().await.players.len() >= MAX_N_PLAYERS { tx.send(WsMsg::LoginRejected(LoginRejectedReason::GameIsFull))?; return Ok(()) } if game.read().await.players.values().any(|player| player.name == username) { tx.send(WsMsg::LoginRejected(LoginRejectedReason::UsernameIsTaken))?; return Ok(()) } tx.send(WsMsg::LoginAccepted)?; let hand = game.write().await.answers.draw(N_CARDS_IN_HAND); let player = Player { name: username.clone(), hand: hand.clone(), score: 0, }; game.write().await.players.insert(user_id, player); // Notify other players game.write().await.broadcast_to_players(&WsMsg::PlayerJoined { name: username })?; // Only start new round if there are enough players if game.read().await.players.len() >= MIN_N_PLAYERS { let game = &mut game.write().await; let round = if let Some(round) = &game.round { round } else { // TODO lobby println!("Starting new round"); game.new_round()?; game.round.as_ref().unwrap() }; // If in judgement, don't send NewRound if round.state == RoundState::Answering { let role = if round.czar == user_id { Role::Czar } else { Role::Player }; tx.send(WsMsg::NewRound { role, prompt: round.prompt.clone(), hand: hand, })?; } } Ok(()) }, // WsMsg::Register(name) => todo!(), // WsMsg::Ready => todo!(), // WsMsg::NotReady => todo!(), WsMsg::SubmitAnswer(answers) => { if let Game { clients, players, round: Some(round), .. } = &mut *game.write().await { if round.state!= RoundState::Answering { eprintln!("invalid query SubmitAnswer: round is in judgement phase"); return Ok(()) } if round.czar == user_id { eprintln!("invalid query SubmitAnswer: player is Czar"); return Ok(()) } match round.answers.entry(user_id) { hash_map::Entry::Occupied(_) => { eprintln!("invalid query SubmitAnswer: player already submitted answer") }, hash_map::Entry::Vacant(entry) => { let hand = &mut players.get_mut(&user_id).unwrap().hand; if!answers.iter().all(|x| hand.contains(x)) { eprintln!("invalid query SubmitAnswer: cards are not in player's deck"); return Ok(()) } println!("SubmitAnswer({})", answers.iter().map(Answer::to_string).collect::<Vec<_>>().join(", ")); // Remove cards from player's hand hand.retain(|x|!answers.contains(x)); // Insert cards into submitted answers entry.insert(answers); tx.send(WsMsg::AnswerAccepted)?; }, } // Check whether all players have answered if round.answers.len() == players.len() - 1 { round.state = RoundState::Judging; // If so, notify them that JUDGEMENT HAS BEGUN // TODO maybe obfuscate the player IDs before sending for id in players.keys() { clients[id].send(WsMsg::ReadyToJudge(round.answers.clone()))?; } } } else { eprintln!("invalid query SubmitAnswer: there is no ongoing round"); } // TODO send AnswerAccepted/Rejected messages Ok(()) }, WsMsg::SubmitJudgement(answer_id) => { let mut new_round = false; if let Game { clients, players, round: Some(round), .. } = &mut *game.write().await { if round.state!= RoundState::Judging { eprintln!("invalid query SubmitAnswer: round is in judgement phase"); return Ok(()) } if round.czar!= user_id { eprintln!("invalid query SubmitJudgement: player isn't Czar"); return Ok(()) } match round.answers.get(&answer_id) { None => { eprintln!("invalid query SubmitJudgement: user ID does not exist"); }, Some(winning_answers) => { let winner = { // Increment winner's scores let winner = players.get_mut(&answer_id).unwrap(); winner.score += 1; // Get winner's name winner.name.clone() }; let scores = players.values().map(|player| (player.name.clone(), player.score)).collect(); let msg = WsMsg::RoundEnded { winner, winning_answers: winning_answers.clone(), scores, }; // Notify end of round, provide winner and scores for id in players.keys() { clients[id].send(msg.clone())?; } new_round = true; } } } else { eprintln!("invalid query SubmitAnswer: there is no ongoing round"); } if new_round { game.write().await.new_round()?; } // TODO send JudgementAccepted/Rejected messages Ok(()) }, _ => unreachable!(), } } async fn user_connected(game: Arc<RwLock<Game>>, socket: WebSocket) { let my_id = NEXT_USER_ID.fetch_add(1, Ordering::Relaxed); println!("User connected: #{}", my_id); let (tx, mut rx) = socket.split(); // Manage outgoing messages to this user let tx = { let (tx2, rx) = mpsc::unbounded_channel(); tokio::task::spawn(rx.map(|msg| { Ok(Message::text(serde_json::to_string(&msg).unwrap())) }).forward(tx).map(move |result| { if let Err(e) = result { eprintln!("websocket send error: {}", e); } })); tx2 }; game.write().await.clients.insert(my_id, tx.clone()); // Manage incoming messages from this user while let Some(result) = rx.next().await { let msg = match result { Ok(msg) => msg, Err(e) => { eprintln!("websocket error with user {}: {}", my_id, e); break; } }; if let Ok(text) = msg.to_str() { if let Ok(response) = serde_json::from_str::<WsMsg>(text) { if let Err(_) = process_message(&game, my_id, response, &tx).await { eprintln!("Error while processing message from player #{}", my_id); break; } } else { eprintln!("cannot read message"); } } } println!("Client #{} disconnected", my_id); user_disconnected(game, my_id).await; } async fn user_disconnected(game: Arc<RwLock<Game>>, user_id: usize) { let game = &mut *game.write().await; game.clients.remove(&user_id); if let Some(player) = game.players.remove(&user_id) { // Discard player's answers game.answers.discard(&player.hand); // Discard player's submitted answers, if any let mut user_is_czar = false; if let Game { answers, round: Some(Round { answers: submitted_answers, czar,.. }), .. } = game { if let Some(cards) = submitted_answers.remove(&user_id) { answers.discard(&cards); } user_is_czar = *czar == user_id; } // If player is Czar, return submitted answers to owners and restart round if user_is_czar { let mut round = game.round.take().unwrap(); game.prompts.discard(&[round.prompt]); for (id, player) in game.players.iter_mut() { player.hand.extend(round.answers.remove(id).into_iter().flatten()); } if game.players.len() > 0 { game.new_round().expect("Couldn't start new round"); } } // Notify other players game.broadcast_to_players(&WsMsg::PlayerLeft { name: player.name.clone() }); } // If not enough players, cancel round if game.players.len() < MIN_N_PLAYERS { game.round = None; game.answers.reset(); game.prompts.reset(); for id in game.players.keys() { game.clients[id].send(WsMsg::GameEnded); } // Clear player hands, to avoid double-discard for player in game.players.values_mut() { player.hand.clear(); } } } use ron; use std::fs::File; use serde::de::DeserializeOwned; fn
<Card: DeserializeOwned>(filename: &str) -> Result<Vec<Card>, Box<dyn std::error::Error>> { let file = File::open(filename)?; Ok(ron::de::from_reader(file)?) } fn load_prompts(filename: &str) -> Result<impl Iterator<Item=Prompt>, Box<dyn std::error::Error>> { Ok(load_deck::<Prompt>(filename)? .into_iter() .map(|prompt| { Prompt::new( expand_underscores(&prompt.content, N_UNDERSCORES), prompt.n_answers ) })) } // async fn login(username: String, game: Arc<RwLock<Game>>) -> Result<impl warp::Reply, Infallible> { // Ok(warp::reply::json(&WsMsg::LoginAccepted)); // Ok(warp::reply::json(&WsMsg::LoginRejected(LoginRejectedReason::GameIsFull))) // } #[tokio::main] async fn main() { let mut game_state = Game::default(); game_state.prompts.extend(load_prompts("assets/prompts.ron").unwrap()); game_state.answers.extend(load_deck("assets/answers.ron").unwrap()); let game_state = Arc::new(RwLock::new(game_state)); let game_state = warp::any().map(move || game_state.clone()); // warp::path!("login") // .and(warp::post()) // .and(warp::body::json()) // .and(game_state.clone()) // .and_then(login); let login = warp::path::end() .map(|| { "Hello World!" }); let game = warp::path::end() .and(warp::ws()) .and(game_state) .map(|ws: warp::ws::Ws, game| { ws.on_upgrade(move |socket| user_connected(game, socket)) }); // Match any request and return hello world! let routes = game.or(login); warp::serve(routes).run(([0, 0, 0, 0], 8000)).await; }
load_deck
identifier_name
main.rs
use anyhow::{Result, bail}; use futures::{FutureExt, StreamExt}; use warp::Filter; use warp::ws::{Message, WebSocket}; use tokio::sync::{mpsc, RwLock}; use std::collections::{HashMap, hash_map}; use std::sync::{ Arc, atomic::{AtomicUsize, Ordering}, }; use rand::seq::IteratorRandom; use std::convert::Infallible; use schema::{Message as WsMsg, Role, Prompt, Answer, LoginRejectedReason}; mod util; mod deck; use util::expand_underscores; use deck::Deck; #[derive(Default)] struct Game { prompts: Deck<Prompt>, answers: Deck<Answer>, round: Option<Round>, clients: HashMap<usize, mpsc::UnboundedSender<schema::Message>>, players: HashMap<usize, Player>, } static N_CARDS_IN_HAND: usize = 4; static MIN_N_PLAYERS: usize = 3; static MAX_N_PLAYERS: usize = 3; static N_UNDERSCORES: usize = 5; impl Game { fn distribute_cards(&mut self) { for player in &mut self.players.values_mut() { if player.hand.len() < N_CARDS_IN_HAND { player.hand.extend(self.answers.draw(N_CARDS_IN_HAND - player.hand.len())); } } } fn new_round(&mut self) -> Result<()> { if self.players.len() == 0 { bail!("There are no players!"); } let mut next_czar = 0; // Discard current round if let Some(Round{ prompt, answers, czar,.. }) = self.round.take() { next_czar = czar+1; self.prompts.discard(&[prompt]); for cards in answers.values() { self.answers.discard(cards); } } // Find next czar let mut player_ids = self.players.keys().collect::<Vec<_>>(); player_ids.sort_unstable(); if let Err(idx) = player_ids.binary_search(&&next_czar) { // There's no player with ID next_czar if idx == player_ids.len() { // There isn't a greater key next_czar = *player_ids[0]; } else { // There is a key greater than next_czar next_czar = *player_ids[idx]; } } // Create new round println!("Players to choose from: {:?}", self.players.keys().map(|u| u.to_string()).collect::<Vec<_>>().join(", ")); let round = Round { prompt: self.prompts.draw_once(), // TODO cycle Czars czar: next_czar, answers: Default::default(), state: RoundState::Answering, }; println!("Next czar is Player #{}", round.czar); // Distribute cards and notify players self.distribute_cards(); for (id, player) in &mut self.players { let role = if *id == round.czar { Role::Czar } else { Role::Player }; self.clients[id].send(WsMsg::NewRound { role, prompt: round.prompt.clone(), hand: player.hand.clone(), })?; } // Set new round self.round = Some(round); Ok(()) } fn broadcast_to_players(&mut self, msg: &WsMsg) -> Result<()> { for id in self.players.keys() { self.clients[id].send(msg.clone())?; } Ok(()) } } #[derive(PartialEq)] enum RoundState { Answering, Judging, } struct Round { prompt: Prompt, czar: usize, answers: HashMap<usize, Vec<Answer>>, state: RoundState, } struct Player { name: String, hand: Vec<Answer>, score: u64, } static NEXT_USER_ID: AtomicUsize = AtomicUsize::new(1); async fn process_message( game: &Arc<RwLock<Game>>, user_id: usize, msg: WsMsg, tx: &mpsc::UnboundedSender<WsMsg> ) -> Result<()> { match msg { WsMsg::Login(username) => { if game.read().await.players.len() >= MAX_N_PLAYERS { tx.send(WsMsg::LoginRejected(LoginRejectedReason::GameIsFull))?; return Ok(()) } if game.read().await.players.values().any(|player| player.name == username) { tx.send(WsMsg::LoginRejected(LoginRejectedReason::UsernameIsTaken))?; return Ok(()) } tx.send(WsMsg::LoginAccepted)?; let hand = game.write().await.answers.draw(N_CARDS_IN_HAND); let player = Player { name: username.clone(), hand: hand.clone(), score: 0, }; game.write().await.players.insert(user_id, player); // Notify other players game.write().await.broadcast_to_players(&WsMsg::PlayerJoined { name: username })?; // Only start new round if there are enough players if game.read().await.players.len() >= MIN_N_PLAYERS { let game = &mut game.write().await; let round = if let Some(round) = &game.round { round } else { // TODO lobby println!("Starting new round"); game.new_round()?; game.round.as_ref().unwrap() }; // If in judgement, don't send NewRound if round.state == RoundState::Answering { let role = if round.czar == user_id { Role::Czar } else { Role::Player }; tx.send(WsMsg::NewRound { role, prompt: round.prompt.clone(), hand: hand, })?; } } Ok(()) }, // WsMsg::Register(name) => todo!(), // WsMsg::Ready => todo!(), // WsMsg::NotReady => todo!(), WsMsg::SubmitAnswer(answers) => { if let Game { clients, players, round: Some(round), .. } = &mut *game.write().await { if round.state!= RoundState::Answering { eprintln!("invalid query SubmitAnswer: round is in judgement phase"); return Ok(()) } if round.czar == user_id { eprintln!("invalid query SubmitAnswer: player is Czar"); return Ok(()) } match round.answers.entry(user_id) { hash_map::Entry::Occupied(_) => { eprintln!("invalid query SubmitAnswer: player already submitted answer") }, hash_map::Entry::Vacant(entry) => { let hand = &mut players.get_mut(&user_id).unwrap().hand; if!answers.iter().all(|x| hand.contains(x)) { eprintln!("invalid query SubmitAnswer: cards are not in player's deck"); return Ok(()) } println!("SubmitAnswer({})", answers.iter().map(Answer::to_string).collect::<Vec<_>>().join(", ")); // Remove cards from player's hand hand.retain(|x|!answers.contains(x)); // Insert cards into submitted answers entry.insert(answers); tx.send(WsMsg::AnswerAccepted)?; }, } // Check whether all players have answered if round.answers.len() == players.len() - 1 { round.state = RoundState::Judging; // If so, notify them that JUDGEMENT HAS BEGUN // TODO maybe obfuscate the player IDs before sending for id in players.keys() { clients[id].send(WsMsg::ReadyToJudge(round.answers.clone()))?; } } } else { eprintln!("invalid query SubmitAnswer: there is no ongoing round"); } // TODO send AnswerAccepted/Rejected messages Ok(()) }, WsMsg::SubmitJudgement(answer_id) => { let mut new_round = false; if let Game { clients, players, round: Some(round), .. } = &mut *game.write().await { if round.state!= RoundState::Judging { eprintln!("invalid query SubmitAnswer: round is in judgement phase"); return Ok(()) } if round.czar!= user_id { eprintln!("invalid query SubmitJudgement: player isn't Czar"); return Ok(()) } match round.answers.get(&answer_id) { None => { eprintln!("invalid query SubmitJudgement: user ID does not exist"); }, Some(winning_answers) => { let winner = { // Increment winner's scores let winner = players.get_mut(&answer_id).unwrap(); winner.score += 1; // Get winner's name winner.name.clone() }; let scores = players.values().map(|player| (player.name.clone(), player.score)).collect(); let msg = WsMsg::RoundEnded { winner, winning_answers: winning_answers.clone(), scores, }; // Notify end of round, provide winner and scores for id in players.keys() { clients[id].send(msg.clone())?; } new_round = true; } } } else { eprintln!("invalid query SubmitAnswer: there is no ongoing round"); } if new_round { game.write().await.new_round()?; } // TODO send JudgementAccepted/Rejected messages Ok(()) }, _ => unreachable!(), } } async fn user_connected(game: Arc<RwLock<Game>>, socket: WebSocket) { let my_id = NEXT_USER_ID.fetch_add(1, Ordering::Relaxed); println!("User connected: #{}", my_id); let (tx, mut rx) = socket.split(); // Manage outgoing messages to this user let tx = { let (tx2, rx) = mpsc::unbounded_channel(); tokio::task::spawn(rx.map(|msg| { Ok(Message::text(serde_json::to_string(&msg).unwrap())) }).forward(tx).map(move |result| { if let Err(e) = result { eprintln!("websocket send error: {}", e); } })); tx2 }; game.write().await.clients.insert(my_id, tx.clone()); // Manage incoming messages from this user while let Some(result) = rx.next().await { let msg = match result { Ok(msg) => msg, Err(e) => { eprintln!("websocket error with user {}: {}", my_id, e); break; } }; if let Ok(text) = msg.to_str() { if let Ok(response) = serde_json::from_str::<WsMsg>(text) { if let Err(_) = process_message(&game, my_id, response, &tx).await { eprintln!("Error while processing message from player #{}", my_id); break; } } else { eprintln!("cannot read message"); } } } println!("Client #{} disconnected", my_id); user_disconnected(game, my_id).await; } async fn user_disconnected(game: Arc<RwLock<Game>>, user_id: usize)
// If player is Czar, return submitted answers to owners and restart round if user_is_czar { let mut round = game.round.take().unwrap(); game.prompts.discard(&[round.prompt]); for (id, player) in game.players.iter_mut() { player.hand.extend(round.answers.remove(id).into_iter().flatten()); } if game.players.len() > 0 { game.new_round().expect("Couldn't start new round"); } } // Notify other players game.broadcast_to_players(&WsMsg::PlayerLeft { name: player.name.clone() }); } // If not enough players, cancel round if game.players.len() < MIN_N_PLAYERS { game.round = None; game.answers.reset(); game.prompts.reset(); for id in game.players.keys() { game.clients[id].send(WsMsg::GameEnded); } // Clear player hands, to avoid double-discard for player in game.players.values_mut() { player.hand.clear(); } } } use ron; use std::fs::File; use serde::de::DeserializeOwned; fn load_deck<Card: DeserializeOwned>(filename: &str) -> Result<Vec<Card>, Box<dyn std::error::Error>> { let file = File::open(filename)?; Ok(ron::de::from_reader(file)?) } fn load_prompts(filename: &str) -> Result<impl Iterator<Item=Prompt>, Box<dyn std::error::Error>> { Ok(load_deck::<Prompt>(filename)? .into_iter() .map(|prompt| { Prompt::new( expand_underscores(&prompt.content, N_UNDERSCORES), prompt.n_answers ) })) } // async fn login(username: String, game: Arc<RwLock<Game>>) -> Result<impl warp::Reply, Infallible> { // Ok(warp::reply::json(&WsMsg::LoginAccepted)); // Ok(warp::reply::json(&WsMsg::LoginRejected(LoginRejectedReason::GameIsFull))) // } #[tokio::main] async fn main() { let mut game_state = Game::default(); game_state.prompts.extend(load_prompts("assets/prompts.ron").unwrap()); game_state.answers.extend(load_deck("assets/answers.ron").unwrap()); let game_state = Arc::new(RwLock::new(game_state)); let game_state = warp::any().map(move || game_state.clone()); // warp::path!("login") // .and(warp::post()) // .and(warp::body::json()) // .and(game_state.clone()) // .and_then(login); let login = warp::path::end() .map(|| { "Hello World!" }); let game = warp::path::end() .and(warp::ws()) .and(game_state) .map(|ws: warp::ws::Ws, game| { ws.on_upgrade(move |socket| user_connected(game, socket)) }); // Match any request and return hello world! let routes = game.or(login); warp::serve(routes).run(([0, 0, 0, 0], 8000)).await; }
{ let game = &mut *game.write().await; game.clients.remove(&user_id); if let Some(player) = game.players.remove(&user_id) { // Discard player's answers game.answers.discard(&player.hand); // Discard player's submitted answers, if any let mut user_is_czar = false; if let Game { answers, round: Some(Round { answers: submitted_answers, czar, .. }), .. } = game { if let Some(cards) = submitted_answers.remove(&user_id) { answers.discard(&cards); } user_is_czar = *czar == user_id; }
identifier_body
main.rs
use anyhow::{Result, bail}; use futures::{FutureExt, StreamExt}; use warp::Filter; use warp::ws::{Message, WebSocket}; use tokio::sync::{mpsc, RwLock}; use std::collections::{HashMap, hash_map}; use std::sync::{ Arc, atomic::{AtomicUsize, Ordering}, }; use rand::seq::IteratorRandom; use std::convert::Infallible; use schema::{Message as WsMsg, Role, Prompt, Answer, LoginRejectedReason}; mod util; mod deck; use util::expand_underscores; use deck::Deck; #[derive(Default)] struct Game { prompts: Deck<Prompt>, answers: Deck<Answer>, round: Option<Round>, clients: HashMap<usize, mpsc::UnboundedSender<schema::Message>>, players: HashMap<usize, Player>, } static N_CARDS_IN_HAND: usize = 4; static MIN_N_PLAYERS: usize = 3; static MAX_N_PLAYERS: usize = 3; static N_UNDERSCORES: usize = 5; impl Game { fn distribute_cards(&mut self) { for player in &mut self.players.values_mut() { if player.hand.len() < N_CARDS_IN_HAND { player.hand.extend(self.answers.draw(N_CARDS_IN_HAND - player.hand.len())); } } } fn new_round(&mut self) -> Result<()> { if self.players.len() == 0 { bail!("There are no players!"); } let mut next_czar = 0; // Discard current round if let Some(Round{ prompt, answers, czar,.. }) = self.round.take() { next_czar = czar+1; self.prompts.discard(&[prompt]); for cards in answers.values() { self.answers.discard(cards); } } // Find next czar let mut player_ids = self.players.keys().collect::<Vec<_>>(); player_ids.sort_unstable(); if let Err(idx) = player_ids.binary_search(&&next_czar) { // There's no player with ID next_czar if idx == player_ids.len() { // There isn't a greater key next_czar = *player_ids[0]; } else { // There is a key greater than next_czar next_czar = *player_ids[idx]; } } // Create new round println!("Players to choose from: {:?}", self.players.keys().map(|u| u.to_string()).collect::<Vec<_>>().join(", ")); let round = Round { prompt: self.prompts.draw_once(), // TODO cycle Czars czar: next_czar, answers: Default::default(), state: RoundState::Answering, }; println!("Next czar is Player #{}", round.czar); // Distribute cards and notify players self.distribute_cards(); for (id, player) in &mut self.players { let role = if *id == round.czar { Role::Czar } else { Role::Player }; self.clients[id].send(WsMsg::NewRound { role, prompt: round.prompt.clone(), hand: player.hand.clone(), })?; } // Set new round self.round = Some(round); Ok(()) } fn broadcast_to_players(&mut self, msg: &WsMsg) -> Result<()> { for id in self.players.keys() { self.clients[id].send(msg.clone())?; } Ok(()) } } #[derive(PartialEq)] enum RoundState { Answering, Judging, } struct Round { prompt: Prompt, czar: usize, answers: HashMap<usize, Vec<Answer>>, state: RoundState, } struct Player { name: String, hand: Vec<Answer>, score: u64, } static NEXT_USER_ID: AtomicUsize = AtomicUsize::new(1); async fn process_message( game: &Arc<RwLock<Game>>, user_id: usize, msg: WsMsg, tx: &mpsc::UnboundedSender<WsMsg> ) -> Result<()> { match msg { WsMsg::Login(username) => { if game.read().await.players.len() >= MAX_N_PLAYERS { tx.send(WsMsg::LoginRejected(LoginRejectedReason::GameIsFull))?; return Ok(()) } if game.read().await.players.values().any(|player| player.name == username) { tx.send(WsMsg::LoginRejected(LoginRejectedReason::UsernameIsTaken))?; return Ok(()) } tx.send(WsMsg::LoginAccepted)?; let hand = game.write().await.answers.draw(N_CARDS_IN_HAND); let player = Player { name: username.clone(), hand: hand.clone(), score: 0, }; game.write().await.players.insert(user_id, player); // Notify other players game.write().await.broadcast_to_players(&WsMsg::PlayerJoined { name: username })?; // Only start new round if there are enough players if game.read().await.players.len() >= MIN_N_PLAYERS { let game = &mut game.write().await; let round = if let Some(round) = &game.round { round } else { // TODO lobby println!("Starting new round"); game.new_round()?; game.round.as_ref().unwrap() }; // If in judgement, don't send NewRound if round.state == RoundState::Answering { let role = if round.czar == user_id { Role::Czar } else { Role::Player }; tx.send(WsMsg::NewRound { role, prompt: round.prompt.clone(), hand: hand, })?; } } Ok(()) }, // WsMsg::Register(name) => todo!(), // WsMsg::Ready => todo!(), // WsMsg::NotReady => todo!(), WsMsg::SubmitAnswer(answers) => { if let Game { clients, players, round: Some(round), .. } = &mut *game.write().await { if round.state!= RoundState::Answering { eprintln!("invalid query SubmitAnswer: round is in judgement phase"); return Ok(()) } if round.czar == user_id { eprintln!("invalid query SubmitAnswer: player is Czar"); return Ok(()) } match round.answers.entry(user_id) { hash_map::Entry::Occupied(_) => { eprintln!("invalid query SubmitAnswer: player already submitted answer") }, hash_map::Entry::Vacant(entry) => { let hand = &mut players.get_mut(&user_id).unwrap().hand; if!answers.iter().all(|x| hand.contains(x)) { eprintln!("invalid query SubmitAnswer: cards are not in player's deck"); return Ok(()) } println!("SubmitAnswer({})", answers.iter().map(Answer::to_string).collect::<Vec<_>>().join(", ")); // Remove cards from player's hand hand.retain(|x|!answers.contains(x)); // Insert cards into submitted answers entry.insert(answers); tx.send(WsMsg::AnswerAccepted)?;
}, } // Check whether all players have answered if round.answers.len() == players.len() - 1 { round.state = RoundState::Judging; // If so, notify them that JUDGEMENT HAS BEGUN // TODO maybe obfuscate the player IDs before sending for id in players.keys() { clients[id].send(WsMsg::ReadyToJudge(round.answers.clone()))?; } } } else { eprintln!("invalid query SubmitAnswer: there is no ongoing round"); } // TODO send AnswerAccepted/Rejected messages Ok(()) }, WsMsg::SubmitJudgement(answer_id) => { let mut new_round = false; if let Game { clients, players, round: Some(round), .. } = &mut *game.write().await { if round.state!= RoundState::Judging { eprintln!("invalid query SubmitAnswer: round is in judgement phase"); return Ok(()) } if round.czar!= user_id { eprintln!("invalid query SubmitJudgement: player isn't Czar"); return Ok(()) } match round.answers.get(&answer_id) { None => { eprintln!("invalid query SubmitJudgement: user ID does not exist"); }, Some(winning_answers) => { let winner = { // Increment winner's scores let winner = players.get_mut(&answer_id).unwrap(); winner.score += 1; // Get winner's name winner.name.clone() }; let scores = players.values().map(|player| (player.name.clone(), player.score)).collect(); let msg = WsMsg::RoundEnded { winner, winning_answers: winning_answers.clone(), scores, }; // Notify end of round, provide winner and scores for id in players.keys() { clients[id].send(msg.clone())?; } new_round = true; } } } else { eprintln!("invalid query SubmitAnswer: there is no ongoing round"); } if new_round { game.write().await.new_round()?; } // TODO send JudgementAccepted/Rejected messages Ok(()) }, _ => unreachable!(), } } async fn user_connected(game: Arc<RwLock<Game>>, socket: WebSocket) { let my_id = NEXT_USER_ID.fetch_add(1, Ordering::Relaxed); println!("User connected: #{}", my_id); let (tx, mut rx) = socket.split(); // Manage outgoing messages to this user let tx = { let (tx2, rx) = mpsc::unbounded_channel(); tokio::task::spawn(rx.map(|msg| { Ok(Message::text(serde_json::to_string(&msg).unwrap())) }).forward(tx).map(move |result| { if let Err(e) = result { eprintln!("websocket send error: {}", e); } })); tx2 }; game.write().await.clients.insert(my_id, tx.clone()); // Manage incoming messages from this user while let Some(result) = rx.next().await { let msg = match result { Ok(msg) => msg, Err(e) => { eprintln!("websocket error with user {}: {}", my_id, e); break; } }; if let Ok(text) = msg.to_str() { if let Ok(response) = serde_json::from_str::<WsMsg>(text) { if let Err(_) = process_message(&game, my_id, response, &tx).await { eprintln!("Error while processing message from player #{}", my_id); break; } } else { eprintln!("cannot read message"); } } } println!("Client #{} disconnected", my_id); user_disconnected(game, my_id).await; } async fn user_disconnected(game: Arc<RwLock<Game>>, user_id: usize) { let game = &mut *game.write().await; game.clients.remove(&user_id); if let Some(player) = game.players.remove(&user_id) { // Discard player's answers game.answers.discard(&player.hand); // Discard player's submitted answers, if any let mut user_is_czar = false; if let Game { answers, round: Some(Round { answers: submitted_answers, czar,.. }), .. } = game { if let Some(cards) = submitted_answers.remove(&user_id) { answers.discard(&cards); } user_is_czar = *czar == user_id; } // If player is Czar, return submitted answers to owners and restart round if user_is_czar { let mut round = game.round.take().unwrap(); game.prompts.discard(&[round.prompt]); for (id, player) in game.players.iter_mut() { player.hand.extend(round.answers.remove(id).into_iter().flatten()); } if game.players.len() > 0 { game.new_round().expect("Couldn't start new round"); } } // Notify other players game.broadcast_to_players(&WsMsg::PlayerLeft { name: player.name.clone() }); } // If not enough players, cancel round if game.players.len() < MIN_N_PLAYERS { game.round = None; game.answers.reset(); game.prompts.reset(); for id in game.players.keys() { game.clients[id].send(WsMsg::GameEnded); } // Clear player hands, to avoid double-discard for player in game.players.values_mut() { player.hand.clear(); } } } use ron; use std::fs::File; use serde::de::DeserializeOwned; fn load_deck<Card: DeserializeOwned>(filename: &str) -> Result<Vec<Card>, Box<dyn std::error::Error>> { let file = File::open(filename)?; Ok(ron::de::from_reader(file)?) } fn load_prompts(filename: &str) -> Result<impl Iterator<Item=Prompt>, Box<dyn std::error::Error>> { Ok(load_deck::<Prompt>(filename)? .into_iter() .map(|prompt| { Prompt::new( expand_underscores(&prompt.content, N_UNDERSCORES), prompt.n_answers ) })) } // async fn login(username: String, game: Arc<RwLock<Game>>) -> Result<impl warp::Reply, Infallible> { // Ok(warp::reply::json(&WsMsg::LoginAccepted)); // Ok(warp::reply::json(&WsMsg::LoginRejected(LoginRejectedReason::GameIsFull))) // } #[tokio::main] async fn main() { let mut game_state = Game::default(); game_state.prompts.extend(load_prompts("assets/prompts.ron").unwrap()); game_state.answers.extend(load_deck("assets/answers.ron").unwrap()); let game_state = Arc::new(RwLock::new(game_state)); let game_state = warp::any().map(move || game_state.clone()); // warp::path!("login") // .and(warp::post()) // .and(warp::body::json()) // .and(game_state.clone()) // .and_then(login); let login = warp::path::end() .map(|| { "Hello World!" }); let game = warp::path::end() .and(warp::ws()) .and(game_state) .map(|ws: warp::ws::Ws, game| { ws.on_upgrade(move |socket| user_connected(game, socket)) }); // Match any request and return hello world! let routes = game.or(login); warp::serve(routes).run(([0, 0, 0, 0], 8000)).await; }
random_line_split
combat.rs
use crate::components::*; use crate::map::*; use crate::NewState; use bracket_lib::prelude::*; use legion::systems::CommandBuffer; use legion::*; use std::collections::HashSet; pub fn player_open_fire_at_target(ecs: &mut World, map: &mut Map) -> NewState { let mut player_entity = None; let mut target = None; <(Entity, &Player, &Targeting)>::query() .iter(ecs) .for_each(|(entity, _, targeting)| { target = targeting.current_target; player_entity = Some(*entity); }); // If there's nothing to fire at, return to waiting if target.is_none() { return NewState::Wait; } ranged_attack(ecs, map, player_entity.unwrap(), target.unwrap(), 20); NewState::Player } pub fn ranged_attack( ecs: &mut World, map: &mut Map, attacker: Entity, victim: Entity, ranged_power: i32, ) { let mut attacker_pos = None; let mut victim_pos = None; // Find positions for the start and end if let Ok(ae) = ecs.entry_ref(attacker) { if let Ok(pos) = ae.get_component::<Position>() { attacker_pos = Some(pos.clone()); } } if let Ok(ae) = ecs.entry_ref(victim) { if let Ok(pos) = ae.get_component::<Position>() { victim_pos = Some(pos.clone()); } } if attacker_pos.is_none() || victim_pos.is_none() { return; } let attacker_pos = attacker_pos.unwrap(); let victim_pos = victim_pos.unwrap(); // Set state for the projectile path let mut power = ranged_power; let mut range = 0; let mut projectile_path = Vec::new(); let mut splatter = None; let mut commands = CommandBuffer::new(ecs); let current_layer = attacker_pos.layer; // Map of entity locations. Rebuilt every time because it might change. let pos_map = <(&Position, &Health)>::query() .iter(ecs) .map(|(pos, _)| pos.pt) .collect::<HashSet<Point>>(); // Plot the initial trajectory line2d_bresenham(attacker_pos.pt, victim_pos.pt) .iter() .skip(1) .for_each(|pt| { projectile_path.push(*pt); if pos_map.contains(&pt) { power -= hit_tile_contents(ecs, *pt, current_layer, &mut commands, &mut splatter, power); if power < 1 { power = 1; range += 200; } } if let Some(bsplatter) = &mut splatter { let idx = map.get_current().point2d_to_index(*pt); map.get_current_mut().tiles[idx].color.fg = bsplatter.to_rgba(1.0); bsplatter.r = f32::max(0.0, bsplatter.r - 0.1); bsplatter.g = f32::max(0.0, bsplatter.g - 0.1); bsplatter.b = f32::max(0.0, bsplatter.b - 0.1); if bsplatter.r + bsplatter.g + bsplatter.b < 0.1 { splatter = None; } } range += 1; if range > 5 { power -= 1; if power < 1 { power = 1; } } }); // The trajectory can continue if we have power left use ultraviolet::Vec2; let mut projectile_pos: Vec2 = Vec2::new(victim_pos.pt.x as f32, victim_pos.pt.y as f32); let slope = (projectile_pos - Vec2::new(attacker_pos.pt.x as f32, attacker_pos.pt.y as f32)) .normalized(); while range < 25 && power > 0 { projectile_pos += slope; let pt = Point::new(projectile_pos.x as i32, projectile_pos.y as i32); projectile_path.push(pt); if pos_map.contains(&pt) { power -= hit_tile_contents(ecs, pt, current_layer, &mut commands, &mut splatter, power); if power < 1 { power = 1; range += 200; } } if let Some(bsplatter) = &mut splatter { let idx = map.get_current().point2d_to_index(pt); map.get_current_mut().tiles[idx].color.fg = bsplatter.to_rgba(1.0); bsplatter.r = f32::max(0.0, bsplatter.r - 0.1); bsplatter.g = f32::max(0.0, bsplatter.g - 0.1); bsplatter.b = f32::max(0.0, bsplatter.b - 0.1); if bsplatter.r + bsplatter.g + bsplatter.b < 0.1 { splatter = None; } } let idx = map.get_current().point2d_to_index(pt); if map.get_current().tiles[idx].tile_type == TileType::Wall { range += 100; power = 0; } range += 1; if range > 5 { power -= 1; if power < 1 { power = 1; range += 100; } } } commands.push(( Projectile { path: projectile_path, layer: current_layer as usize, }, Glyph { glyph: to_cp437('*'), color: ColorPair::new(RED, BLACK), }, )); commands.flush(ecs); } pub fn hit_tile_contents( ecs: &mut World, pt: Point, layer: u32, commands: &mut CommandBuffer, splatter: &mut Option<RGB>, power: i32, ) -> i32 { let mut rng_lock = crate::RNG.lock(); let rng = rng_lock.as_mut().unwrap(); let mut power_loss = 0; let mut dead_entities = Vec::new(); <(Entity, &Position, &mut Health)>::query() .iter_mut(ecs) .filter(|(_, pos, _)| pos.layer == layer && pos.pt == pt) .for_each(|(entity, _, hp)| { power_loss += hp.current; if power_loss < 0 { power_loss = 0; } let damage = i32::max(0, power + rng.roll_dice(1, 4) - 2); //println!("{}", damage); hp.current -= damage; if hp.current < 0 { hp.current = 0; dead_entities.push(*entity); } }); dead_entities.iter().for_each(|e| { if let Ok(er) = ecs.entry_ref(*e) { if let Ok(boom) = er.get_component::<Explosive>() { if let Ok(pos) = er.get_component::<Position>() { commands.push(( Position::with_pt(pos.pt, pos.layer), Boom { range: boom.range }, )); } } } }); kill_things(ecs, commands, dead_entities, splatter); power_loss } pub fn melee(ecs: &mut World, map: &mut Map, attacker: Entity, victim: Entity, melee_power: i32) { // Check range and validity let mut attacker_pos = None; let mut defender_pos = None; if let Ok(e) = ecs.entry_ref(attacker) { if let Ok(pos) = e.get_component::<Position>() { attacker_pos = Some(*pos); } } if let Ok(e) = ecs.entry_ref(victim) { if let Ok(pos) = e.get_component::<Position>() { defender_pos = Some(*pos); } } if attacker_pos.is_none() || defender_pos.is_none() { return; // Bail out - invalid data arrived } let apos = attacker_pos.unwrap(); let dpos = defender_pos.unwrap(); if apos.layer!= dpos.layer { return; // Bail out - can't attack across layers } let d = DistanceAlg::Pythagoras.distance2d(apos.pt, dpos.pt); if d > 1.5 { return; // Too far away, bail } // Inflict damage upon the hapless victim let mut dead_entities = Vec::new(); if let Ok(mut v) = ecs.entry_mut(victim) { if let Ok(hp) = v.get_component_mut::<Health>() { hp.current = i32::max(0, hp.current - melee_power); if hp.current == 0 { dead_entities.push(victim); } } if let Ok(blood) = v.get_component::<Blood>() { let idx = map.get_layer(dpos.layer as usize).point2d_to_index(dpos.pt); map.get_layer_mut(dpos.layer as usize).tiles[idx].color.fg = blood.0.into(); } } // If necessary, kill them. let mut commands = CommandBuffer::new(ecs); let mut splatter = None; kill_things(ecs, &mut commands, dead_entities, &mut splatter); // Splatter blood. It's good for you. } fn
( ecs: &mut World, commands: &mut CommandBuffer, dead_entities: Vec<Entity>, splatter: &mut Option<RGB>, ) { dead_entities.iter().for_each(|entity| { crate::stats::record_death(); let mut was_decor = false; let mut was_player = false; if let Ok(mut er) = ecs.entry_mut(*entity) { let mut was_colonist = false; if let Ok(_colonist) = er.get_component_mut::<ColonistStatus>() { commands.add_component(*entity, ColonistStatus::DiedAfterStart); was_colonist = true; } if let Ok(g) = er.get_component_mut::<Glyph>() { g.color.bg = DARK_RED.into(); g.color.fg = DARK_GRAY.into(); } if let Ok(n) = er.get_component_mut::<Name>() { n.0 = format!("Corpse: {}", n.0); } if was_colonist { if let Ok(d) = er.get_component_mut::<Description>() { let mut rng = RandomNumberGenerator::new(); if rng.range(0, 10) < 5 { d.0 = format!( "{} They left behind a spouse and {} children.", d.0, rng.range(1, 8) ); } } } if er.get_component::<Hostile>().is_ok() { crate::stats::record_monster_death(); } if let Ok(b) = er.get_component::<Blood>() { *splatter = Some(b.0); } if let Ok(_) = er.get_component::<SetDecoration>() { was_decor = true; } if let Ok(_) = er.get_component::<Player>() { was_player = true; } } if!was_player { commands.remove_component::<Health>(*entity); commands.remove_component::<Active>(*entity); commands.remove_component::<CanBeActivated>(*entity); commands.remove_component::<Blood>(*entity); commands.remove_component::<Targetable>(*entity); commands.remove_component::<Explosive>(*entity); commands.remove_component::<TimedEvent>(*entity); } if was_decor { crate::stats::record_prop_death(); commands.remove_component::<Glyph>(*entity); commands.remove_component::<Description>(*entity); } }); }
kill_things
identifier_name
combat.rs
use crate::components::*; use crate::map::*; use crate::NewState; use bracket_lib::prelude::*; use legion::systems::CommandBuffer; use legion::*; use std::collections::HashSet; pub fn player_open_fire_at_target(ecs: &mut World, map: &mut Map) -> NewState { let mut player_entity = None; let mut target = None; <(Entity, &Player, &Targeting)>::query() .iter(ecs) .for_each(|(entity, _, targeting)| { target = targeting.current_target; player_entity = Some(*entity); }); // If there's nothing to fire at, return to waiting if target.is_none() { return NewState::Wait; } ranged_attack(ecs, map, player_entity.unwrap(), target.unwrap(), 20); NewState::Player } pub fn ranged_attack( ecs: &mut World, map: &mut Map, attacker: Entity, victim: Entity, ranged_power: i32, )
// Set state for the projectile path let mut power = ranged_power; let mut range = 0; let mut projectile_path = Vec::new(); let mut splatter = None; let mut commands = CommandBuffer::new(ecs); let current_layer = attacker_pos.layer; // Map of entity locations. Rebuilt every time because it might change. let pos_map = <(&Position, &Health)>::query() .iter(ecs) .map(|(pos, _)| pos.pt) .collect::<HashSet<Point>>(); // Plot the initial trajectory line2d_bresenham(attacker_pos.pt, victim_pos.pt) .iter() .skip(1) .for_each(|pt| { projectile_path.push(*pt); if pos_map.contains(&pt) { power -= hit_tile_contents(ecs, *pt, current_layer, &mut commands, &mut splatter, power); if power < 1 { power = 1; range += 200; } } if let Some(bsplatter) = &mut splatter { let idx = map.get_current().point2d_to_index(*pt); map.get_current_mut().tiles[idx].color.fg = bsplatter.to_rgba(1.0); bsplatter.r = f32::max(0.0, bsplatter.r - 0.1); bsplatter.g = f32::max(0.0, bsplatter.g - 0.1); bsplatter.b = f32::max(0.0, bsplatter.b - 0.1); if bsplatter.r + bsplatter.g + bsplatter.b < 0.1 { splatter = None; } } range += 1; if range > 5 { power -= 1; if power < 1 { power = 1; } } }); // The trajectory can continue if we have power left use ultraviolet::Vec2; let mut projectile_pos: Vec2 = Vec2::new(victim_pos.pt.x as f32, victim_pos.pt.y as f32); let slope = (projectile_pos - Vec2::new(attacker_pos.pt.x as f32, attacker_pos.pt.y as f32)) .normalized(); while range < 25 && power > 0 { projectile_pos += slope; let pt = Point::new(projectile_pos.x as i32, projectile_pos.y as i32); projectile_path.push(pt); if pos_map.contains(&pt) { power -= hit_tile_contents(ecs, pt, current_layer, &mut commands, &mut splatter, power); if power < 1 { power = 1; range += 200; } } if let Some(bsplatter) = &mut splatter { let idx = map.get_current().point2d_to_index(pt); map.get_current_mut().tiles[idx].color.fg = bsplatter.to_rgba(1.0); bsplatter.r = f32::max(0.0, bsplatter.r - 0.1); bsplatter.g = f32::max(0.0, bsplatter.g - 0.1); bsplatter.b = f32::max(0.0, bsplatter.b - 0.1); if bsplatter.r + bsplatter.g + bsplatter.b < 0.1 { splatter = None; } } let idx = map.get_current().point2d_to_index(pt); if map.get_current().tiles[idx].tile_type == TileType::Wall { range += 100; power = 0; } range += 1; if range > 5 { power -= 1; if power < 1 { power = 1; range += 100; } } } commands.push(( Projectile { path: projectile_path, layer: current_layer as usize, }, Glyph { glyph: to_cp437('*'), color: ColorPair::new(RED, BLACK), }, )); commands.flush(ecs); } pub fn hit_tile_contents( ecs: &mut World, pt: Point, layer: u32, commands: &mut CommandBuffer, splatter: &mut Option<RGB>, power: i32, ) -> i32 { let mut rng_lock = crate::RNG.lock(); let rng = rng_lock.as_mut().unwrap(); let mut power_loss = 0; let mut dead_entities = Vec::new(); <(Entity, &Position, &mut Health)>::query() .iter_mut(ecs) .filter(|(_, pos, _)| pos.layer == layer && pos.pt == pt) .for_each(|(entity, _, hp)| { power_loss += hp.current; if power_loss < 0 { power_loss = 0; } let damage = i32::max(0, power + rng.roll_dice(1, 4) - 2); //println!("{}", damage); hp.current -= damage; if hp.current < 0 { hp.current = 0; dead_entities.push(*entity); } }); dead_entities.iter().for_each(|e| { if let Ok(er) = ecs.entry_ref(*e) { if let Ok(boom) = er.get_component::<Explosive>() { if let Ok(pos) = er.get_component::<Position>() { commands.push(( Position::with_pt(pos.pt, pos.layer), Boom { range: boom.range }, )); } } } }); kill_things(ecs, commands, dead_entities, splatter); power_loss } pub fn melee(ecs: &mut World, map: &mut Map, attacker: Entity, victim: Entity, melee_power: i32) { // Check range and validity let mut attacker_pos = None; let mut defender_pos = None; if let Ok(e) = ecs.entry_ref(attacker) { if let Ok(pos) = e.get_component::<Position>() { attacker_pos = Some(*pos); } } if let Ok(e) = ecs.entry_ref(victim) { if let Ok(pos) = e.get_component::<Position>() { defender_pos = Some(*pos); } } if attacker_pos.is_none() || defender_pos.is_none() { return; // Bail out - invalid data arrived } let apos = attacker_pos.unwrap(); let dpos = defender_pos.unwrap(); if apos.layer!= dpos.layer { return; // Bail out - can't attack across layers } let d = DistanceAlg::Pythagoras.distance2d(apos.pt, dpos.pt); if d > 1.5 { return; // Too far away, bail } // Inflict damage upon the hapless victim let mut dead_entities = Vec::new(); if let Ok(mut v) = ecs.entry_mut(victim) { if let Ok(hp) = v.get_component_mut::<Health>() { hp.current = i32::max(0, hp.current - melee_power); if hp.current == 0 { dead_entities.push(victim); } } if let Ok(blood) = v.get_component::<Blood>() { let idx = map.get_layer(dpos.layer as usize).point2d_to_index(dpos.pt); map.get_layer_mut(dpos.layer as usize).tiles[idx].color.fg = blood.0.into(); } } // If necessary, kill them. let mut commands = CommandBuffer::new(ecs); let mut splatter = None; kill_things(ecs, &mut commands, dead_entities, &mut splatter); // Splatter blood. It's good for you. } fn kill_things( ecs: &mut World, commands: &mut CommandBuffer, dead_entities: Vec<Entity>, splatter: &mut Option<RGB>, ) { dead_entities.iter().for_each(|entity| { crate::stats::record_death(); let mut was_decor = false; let mut was_player = false; if let Ok(mut er) = ecs.entry_mut(*entity) { let mut was_colonist = false; if let Ok(_colonist) = er.get_component_mut::<ColonistStatus>() { commands.add_component(*entity, ColonistStatus::DiedAfterStart); was_colonist = true; } if let Ok(g) = er.get_component_mut::<Glyph>() { g.color.bg = DARK_RED.into(); g.color.fg = DARK_GRAY.into(); } if let Ok(n) = er.get_component_mut::<Name>() { n.0 = format!("Corpse: {}", n.0); } if was_colonist { if let Ok(d) = er.get_component_mut::<Description>() { let mut rng = RandomNumberGenerator::new(); if rng.range(0, 10) < 5 { d.0 = format!( "{} They left behind a spouse and {} children.", d.0, rng.range(1, 8) ); } } } if er.get_component::<Hostile>().is_ok() { crate::stats::record_monster_death(); } if let Ok(b) = er.get_component::<Blood>() { *splatter = Some(b.0); } if let Ok(_) = er.get_component::<SetDecoration>() { was_decor = true; } if let Ok(_) = er.get_component::<Player>() { was_player = true; } } if!was_player { commands.remove_component::<Health>(*entity); commands.remove_component::<Active>(*entity); commands.remove_component::<CanBeActivated>(*entity); commands.remove_component::<Blood>(*entity); commands.remove_component::<Targetable>(*entity); commands.remove_component::<Explosive>(*entity); commands.remove_component::<TimedEvent>(*entity); } if was_decor { crate::stats::record_prop_death(); commands.remove_component::<Glyph>(*entity); commands.remove_component::<Description>(*entity); } }); }
{ let mut attacker_pos = None; let mut victim_pos = None; // Find positions for the start and end if let Ok(ae) = ecs.entry_ref(attacker) { if let Ok(pos) = ae.get_component::<Position>() { attacker_pos = Some(pos.clone()); } } if let Ok(ae) = ecs.entry_ref(victim) { if let Ok(pos) = ae.get_component::<Position>() { victim_pos = Some(pos.clone()); } } if attacker_pos.is_none() || victim_pos.is_none() { return; } let attacker_pos = attacker_pos.unwrap(); let victim_pos = victim_pos.unwrap();
identifier_body
combat.rs
use crate::components::*; use crate::map::*; use crate::NewState; use bracket_lib::prelude::*; use legion::systems::CommandBuffer; use legion::*; use std::collections::HashSet; pub fn player_open_fire_at_target(ecs: &mut World, map: &mut Map) -> NewState { let mut player_entity = None; let mut target = None; <(Entity, &Player, &Targeting)>::query() .iter(ecs) .for_each(|(entity, _, targeting)| { target = targeting.current_target; player_entity = Some(*entity); }); // If there's nothing to fire at, return to waiting if target.is_none() { return NewState::Wait; } ranged_attack(ecs, map, player_entity.unwrap(), target.unwrap(), 20); NewState::Player } pub fn ranged_attack( ecs: &mut World, map: &mut Map, attacker: Entity, victim: Entity, ranged_power: i32, ) { let mut attacker_pos = None; let mut victim_pos = None; // Find positions for the start and end if let Ok(ae) = ecs.entry_ref(attacker) { if let Ok(pos) = ae.get_component::<Position>() { attacker_pos = Some(pos.clone()); } } if let Ok(ae) = ecs.entry_ref(victim) { if let Ok(pos) = ae.get_component::<Position>() { victim_pos = Some(pos.clone()); } } if attacker_pos.is_none() || victim_pos.is_none() { return; } let attacker_pos = attacker_pos.unwrap(); let victim_pos = victim_pos.unwrap(); // Set state for the projectile path let mut power = ranged_power; let mut range = 0; let mut projectile_path = Vec::new(); let mut splatter = None; let mut commands = CommandBuffer::new(ecs); let current_layer = attacker_pos.layer; // Map of entity locations. Rebuilt every time because it might change. let pos_map = <(&Position, &Health)>::query() .iter(ecs) .map(|(pos, _)| pos.pt) .collect::<HashSet<Point>>(); // Plot the initial trajectory line2d_bresenham(attacker_pos.pt, victim_pos.pt) .iter() .skip(1) .for_each(|pt| { projectile_path.push(*pt); if pos_map.contains(&pt) { power -= hit_tile_contents(ecs, *pt, current_layer, &mut commands, &mut splatter, power); if power < 1 { power = 1; range += 200; } } if let Some(bsplatter) = &mut splatter { let idx = map.get_current().point2d_to_index(*pt); map.get_current_mut().tiles[idx].color.fg = bsplatter.to_rgba(1.0); bsplatter.r = f32::max(0.0, bsplatter.r - 0.1); bsplatter.g = f32::max(0.0, bsplatter.g - 0.1); bsplatter.b = f32::max(0.0, bsplatter.b - 0.1); if bsplatter.r + bsplatter.g + bsplatter.b < 0.1 { splatter = None; } } range += 1; if range > 5 { power -= 1; if power < 1 { power = 1; } } }); // The trajectory can continue if we have power left use ultraviolet::Vec2; let mut projectile_pos: Vec2 = Vec2::new(victim_pos.pt.x as f32, victim_pos.pt.y as f32); let slope = (projectile_pos - Vec2::new(attacker_pos.pt.x as f32, attacker_pos.pt.y as f32)) .normalized(); while range < 25 && power > 0 { projectile_pos += slope; let pt = Point::new(projectile_pos.x as i32, projectile_pos.y as i32); projectile_path.push(pt); if pos_map.contains(&pt) { power -= hit_tile_contents(ecs, pt, current_layer, &mut commands, &mut splatter, power); if power < 1 { power = 1; range += 200; } } if let Some(bsplatter) = &mut splatter { let idx = map.get_current().point2d_to_index(pt); map.get_current_mut().tiles[idx].color.fg = bsplatter.to_rgba(1.0); bsplatter.r = f32::max(0.0, bsplatter.r - 0.1); bsplatter.g = f32::max(0.0, bsplatter.g - 0.1); bsplatter.b = f32::max(0.0, bsplatter.b - 0.1); if bsplatter.r + bsplatter.g + bsplatter.b < 0.1 { splatter = None; } } let idx = map.get_current().point2d_to_index(pt); if map.get_current().tiles[idx].tile_type == TileType::Wall { range += 100; power = 0; } range += 1; if range > 5 { power -= 1; if power < 1 { power = 1; range += 100; } } } commands.push(( Projectile { path: projectile_path, layer: current_layer as usize, }, Glyph { glyph: to_cp437('*'), color: ColorPair::new(RED, BLACK), }, )); commands.flush(ecs); } pub fn hit_tile_contents( ecs: &mut World, pt: Point, layer: u32, commands: &mut CommandBuffer, splatter: &mut Option<RGB>, power: i32, ) -> i32 { let mut rng_lock = crate::RNG.lock(); let rng = rng_lock.as_mut().unwrap(); let mut power_loss = 0; let mut dead_entities = Vec::new(); <(Entity, &Position, &mut Health)>::query() .iter_mut(ecs) .filter(|(_, pos, _)| pos.layer == layer && pos.pt == pt) .for_each(|(entity, _, hp)| { power_loss += hp.current; if power_loss < 0 { power_loss = 0; } let damage = i32::max(0, power + rng.roll_dice(1, 4) - 2); //println!("{}", damage); hp.current -= damage; if hp.current < 0 { hp.current = 0; dead_entities.push(*entity); } }); dead_entities.iter().for_each(|e| { if let Ok(er) = ecs.entry_ref(*e) { if let Ok(boom) = er.get_component::<Explosive>() { if let Ok(pos) = er.get_component::<Position>() { commands.push(( Position::with_pt(pos.pt, pos.layer), Boom { range: boom.range }, )); } } } }); kill_things(ecs, commands, dead_entities, splatter); power_loss } pub fn melee(ecs: &mut World, map: &mut Map, attacker: Entity, victim: Entity, melee_power: i32) { // Check range and validity let mut attacker_pos = None; let mut defender_pos = None; if let Ok(e) = ecs.entry_ref(attacker) { if let Ok(pos) = e.get_component::<Position>() { attacker_pos = Some(*pos); } } if let Ok(e) = ecs.entry_ref(victim) { if let Ok(pos) = e.get_component::<Position>() { defender_pos = Some(*pos); } } if attacker_pos.is_none() || defender_pos.is_none() { return; // Bail out - invalid data arrived } let apos = attacker_pos.unwrap(); let dpos = defender_pos.unwrap(); if apos.layer!= dpos.layer { return; // Bail out - can't attack across layers } let d = DistanceAlg::Pythagoras.distance2d(apos.pt, dpos.pt); if d > 1.5 { return; // Too far away, bail } // Inflict damage upon the hapless victim let mut dead_entities = Vec::new(); if let Ok(mut v) = ecs.entry_mut(victim)
// If necessary, kill them. let mut commands = CommandBuffer::new(ecs); let mut splatter = None; kill_things(ecs, &mut commands, dead_entities, &mut splatter); // Splatter blood. It's good for you. } fn kill_things( ecs: &mut World, commands: &mut CommandBuffer, dead_entities: Vec<Entity>, splatter: &mut Option<RGB>, ) { dead_entities.iter().for_each(|entity| { crate::stats::record_death(); let mut was_decor = false; let mut was_player = false; if let Ok(mut er) = ecs.entry_mut(*entity) { let mut was_colonist = false; if let Ok(_colonist) = er.get_component_mut::<ColonistStatus>() { commands.add_component(*entity, ColonistStatus::DiedAfterStart); was_colonist = true; } if let Ok(g) = er.get_component_mut::<Glyph>() { g.color.bg = DARK_RED.into(); g.color.fg = DARK_GRAY.into(); } if let Ok(n) = er.get_component_mut::<Name>() { n.0 = format!("Corpse: {}", n.0); } if was_colonist { if let Ok(d) = er.get_component_mut::<Description>() { let mut rng = RandomNumberGenerator::new(); if rng.range(0, 10) < 5 { d.0 = format!( "{} They left behind a spouse and {} children.", d.0, rng.range(1, 8) ); } } } if er.get_component::<Hostile>().is_ok() { crate::stats::record_monster_death(); } if let Ok(b) = er.get_component::<Blood>() { *splatter = Some(b.0); } if let Ok(_) = er.get_component::<SetDecoration>() { was_decor = true; } if let Ok(_) = er.get_component::<Player>() { was_player = true; } } if!was_player { commands.remove_component::<Health>(*entity); commands.remove_component::<Active>(*entity); commands.remove_component::<CanBeActivated>(*entity); commands.remove_component::<Blood>(*entity); commands.remove_component::<Targetable>(*entity); commands.remove_component::<Explosive>(*entity); commands.remove_component::<TimedEvent>(*entity); } if was_decor { crate::stats::record_prop_death(); commands.remove_component::<Glyph>(*entity); commands.remove_component::<Description>(*entity); } }); }
{ if let Ok(hp) = v.get_component_mut::<Health>() { hp.current = i32::max(0, hp.current - melee_power); if hp.current == 0 { dead_entities.push(victim); } } if let Ok(blood) = v.get_component::<Blood>() { let idx = map.get_layer(dpos.layer as usize).point2d_to_index(dpos.pt); map.get_layer_mut(dpos.layer as usize).tiles[idx].color.fg = blood.0.into(); } }
conditional_block
combat.rs
use crate::components::*; use crate::map::*; use crate::NewState; use bracket_lib::prelude::*; use legion::systems::CommandBuffer; use legion::*; use std::collections::HashSet; pub fn player_open_fire_at_target(ecs: &mut World, map: &mut Map) -> NewState { let mut player_entity = None; let mut target = None; <(Entity, &Player, &Targeting)>::query() .iter(ecs) .for_each(|(entity, _, targeting)| { target = targeting.current_target; player_entity = Some(*entity); }); // If there's nothing to fire at, return to waiting if target.is_none() { return NewState::Wait; } ranged_attack(ecs, map, player_entity.unwrap(), target.unwrap(), 20); NewState::Player } pub fn ranged_attack( ecs: &mut World, map: &mut Map, attacker: Entity, victim: Entity, ranged_power: i32, ) { let mut attacker_pos = None; let mut victim_pos = None; // Find positions for the start and end if let Ok(ae) = ecs.entry_ref(attacker) { if let Ok(pos) = ae.get_component::<Position>() { attacker_pos = Some(pos.clone()); } } if let Ok(ae) = ecs.entry_ref(victim) { if let Ok(pos) = ae.get_component::<Position>() { victim_pos = Some(pos.clone()); } } if attacker_pos.is_none() || victim_pos.is_none() { return; } let attacker_pos = attacker_pos.unwrap(); let victim_pos = victim_pos.unwrap(); // Set state for the projectile path let mut power = ranged_power; let mut range = 0; let mut projectile_path = Vec::new(); let mut splatter = None; let mut commands = CommandBuffer::new(ecs); let current_layer = attacker_pos.layer; // Map of entity locations. Rebuilt every time because it might change. let pos_map = <(&Position, &Health)>::query() .iter(ecs) .map(|(pos, _)| pos.pt) .collect::<HashSet<Point>>(); // Plot the initial trajectory line2d_bresenham(attacker_pos.pt, victim_pos.pt) .iter() .skip(1) .for_each(|pt| { projectile_path.push(*pt); if pos_map.contains(&pt) { power -= hit_tile_contents(ecs, *pt, current_layer, &mut commands, &mut splatter, power); if power < 1 { power = 1; range += 200; } } if let Some(bsplatter) = &mut splatter { let idx = map.get_current().point2d_to_index(*pt); map.get_current_mut().tiles[idx].color.fg = bsplatter.to_rgba(1.0); bsplatter.r = f32::max(0.0, bsplatter.r - 0.1); bsplatter.g = f32::max(0.0, bsplatter.g - 0.1); bsplatter.b = f32::max(0.0, bsplatter.b - 0.1); if bsplatter.r + bsplatter.g + bsplatter.b < 0.1 { splatter = None; } } range += 1; if range > 5 { power -= 1; if power < 1 { power = 1; } } }); // The trajectory can continue if we have power left use ultraviolet::Vec2; let mut projectile_pos: Vec2 = Vec2::new(victim_pos.pt.x as f32, victim_pos.pt.y as f32); let slope = (projectile_pos - Vec2::new(attacker_pos.pt.x as f32, attacker_pos.pt.y as f32)) .normalized(); while range < 25 && power > 0 { projectile_pos += slope; let pt = Point::new(projectile_pos.x as i32, projectile_pos.y as i32); projectile_path.push(pt); if pos_map.contains(&pt) { power -= hit_tile_contents(ecs, pt, current_layer, &mut commands, &mut splatter, power); if power < 1 { power = 1; range += 200; } } if let Some(bsplatter) = &mut splatter { let idx = map.get_current().point2d_to_index(pt); map.get_current_mut().tiles[idx].color.fg = bsplatter.to_rgba(1.0); bsplatter.r = f32::max(0.0, bsplatter.r - 0.1); bsplatter.g = f32::max(0.0, bsplatter.g - 0.1); bsplatter.b = f32::max(0.0, bsplatter.b - 0.1); if bsplatter.r + bsplatter.g + bsplatter.b < 0.1 { splatter = None; } } let idx = map.get_current().point2d_to_index(pt); if map.get_current().tiles[idx].tile_type == TileType::Wall { range += 100; power = 0; } range += 1; if range > 5 { power -= 1; if power < 1 { power = 1; range += 100; } } } commands.push(( Projectile { path: projectile_path,
}, Glyph { glyph: to_cp437('*'), color: ColorPair::new(RED, BLACK), }, )); commands.flush(ecs); } pub fn hit_tile_contents( ecs: &mut World, pt: Point, layer: u32, commands: &mut CommandBuffer, splatter: &mut Option<RGB>, power: i32, ) -> i32 { let mut rng_lock = crate::RNG.lock(); let rng = rng_lock.as_mut().unwrap(); let mut power_loss = 0; let mut dead_entities = Vec::new(); <(Entity, &Position, &mut Health)>::query() .iter_mut(ecs) .filter(|(_, pos, _)| pos.layer == layer && pos.pt == pt) .for_each(|(entity, _, hp)| { power_loss += hp.current; if power_loss < 0 { power_loss = 0; } let damage = i32::max(0, power + rng.roll_dice(1, 4) - 2); //println!("{}", damage); hp.current -= damage; if hp.current < 0 { hp.current = 0; dead_entities.push(*entity); } }); dead_entities.iter().for_each(|e| { if let Ok(er) = ecs.entry_ref(*e) { if let Ok(boom) = er.get_component::<Explosive>() { if let Ok(pos) = er.get_component::<Position>() { commands.push(( Position::with_pt(pos.pt, pos.layer), Boom { range: boom.range }, )); } } } }); kill_things(ecs, commands, dead_entities, splatter); power_loss } pub fn melee(ecs: &mut World, map: &mut Map, attacker: Entity, victim: Entity, melee_power: i32) { // Check range and validity let mut attacker_pos = None; let mut defender_pos = None; if let Ok(e) = ecs.entry_ref(attacker) { if let Ok(pos) = e.get_component::<Position>() { attacker_pos = Some(*pos); } } if let Ok(e) = ecs.entry_ref(victim) { if let Ok(pos) = e.get_component::<Position>() { defender_pos = Some(*pos); } } if attacker_pos.is_none() || defender_pos.is_none() { return; // Bail out - invalid data arrived } let apos = attacker_pos.unwrap(); let dpos = defender_pos.unwrap(); if apos.layer!= dpos.layer { return; // Bail out - can't attack across layers } let d = DistanceAlg::Pythagoras.distance2d(apos.pt, dpos.pt); if d > 1.5 { return; // Too far away, bail } // Inflict damage upon the hapless victim let mut dead_entities = Vec::new(); if let Ok(mut v) = ecs.entry_mut(victim) { if let Ok(hp) = v.get_component_mut::<Health>() { hp.current = i32::max(0, hp.current - melee_power); if hp.current == 0 { dead_entities.push(victim); } } if let Ok(blood) = v.get_component::<Blood>() { let idx = map.get_layer(dpos.layer as usize).point2d_to_index(dpos.pt); map.get_layer_mut(dpos.layer as usize).tiles[idx].color.fg = blood.0.into(); } } // If necessary, kill them. let mut commands = CommandBuffer::new(ecs); let mut splatter = None; kill_things(ecs, &mut commands, dead_entities, &mut splatter); // Splatter blood. It's good for you. } fn kill_things( ecs: &mut World, commands: &mut CommandBuffer, dead_entities: Vec<Entity>, splatter: &mut Option<RGB>, ) { dead_entities.iter().for_each(|entity| { crate::stats::record_death(); let mut was_decor = false; let mut was_player = false; if let Ok(mut er) = ecs.entry_mut(*entity) { let mut was_colonist = false; if let Ok(_colonist) = er.get_component_mut::<ColonistStatus>() { commands.add_component(*entity, ColonistStatus::DiedAfterStart); was_colonist = true; } if let Ok(g) = er.get_component_mut::<Glyph>() { g.color.bg = DARK_RED.into(); g.color.fg = DARK_GRAY.into(); } if let Ok(n) = er.get_component_mut::<Name>() { n.0 = format!("Corpse: {}", n.0); } if was_colonist { if let Ok(d) = er.get_component_mut::<Description>() { let mut rng = RandomNumberGenerator::new(); if rng.range(0, 10) < 5 { d.0 = format!( "{} They left behind a spouse and {} children.", d.0, rng.range(1, 8) ); } } } if er.get_component::<Hostile>().is_ok() { crate::stats::record_monster_death(); } if let Ok(b) = er.get_component::<Blood>() { *splatter = Some(b.0); } if let Ok(_) = er.get_component::<SetDecoration>() { was_decor = true; } if let Ok(_) = er.get_component::<Player>() { was_player = true; } } if!was_player { commands.remove_component::<Health>(*entity); commands.remove_component::<Active>(*entity); commands.remove_component::<CanBeActivated>(*entity); commands.remove_component::<Blood>(*entity); commands.remove_component::<Targetable>(*entity); commands.remove_component::<Explosive>(*entity); commands.remove_component::<TimedEvent>(*entity); } if was_decor { crate::stats::record_prop_death(); commands.remove_component::<Glyph>(*entity); commands.remove_component::<Description>(*entity); } }); }
layer: current_layer as usize,
random_line_split
idempotent.rs
//! mut_aliasing -- several links, AT_LEAST one of them is MUTABLE //! BTW: bunch_of_closures_with_mut_refs is like obj which alias through its params, which is //! mut_aliased refs on some another obj, or shared data //! that_is: CLOSURE_CAPUTRING == OBJ.MUT_ALIASED_REFS | 0 // fns with side-effs: --== IDEMPOTENT VS NON_IDEMPONTENT ==-- // /// fn is idempotent because its caused side-effs SIMULTANEOUSLY fulfill (2-former:wrong) 1 cond: /// 1. base on "input" or "immutable free-vars".. NO mut_aliasing /// .. /// (here was 2nd statement) Just change value.. not ADD. /// .. BUT.. it's NEVERHTHELESS.. 1-statement(MUT_alising) // // (small caveat: JUST REMINDER) var x; fn some_fn(n) { x += n*x } // not IDEMPOTENT because: *WRONG: we update, and/but not completly rewrite `x`, // *RIGHT: mut_aliasing (our computed value for `x` rely on mut_aliased `x`) // (BUT) // BTW(p.s.)--v: `some_fn` break rule: /// "mutate only TREE_in_the_WOOD, emit "own_copied/immutabl" value" // (TREE_in_the_WOOD is accesed or through "self/this", or "closure"-capturing) // fn some_fn(a = [], n) { a.push(n) } // ^-- here was: "ADD value, not just change." // BUT actually.. it's also can be considered as MUT_alising.. since result of `push` // depends of `a`,.. and if we call 2 times `some_fn` of course it's gives different sideeff, // since its computation based on MUTated value, ("EU ZHE") // .. // From the other hand.. `some_fn` can be considered as IDEMPONENT, since it's always gives // the same side-eff for the same input-VALUE.. that is if we alway will give `[x] as a`.. // we always receive `[x, n] as a` // .. // (v-- chut' ne udalil :lol:, podumal wo hn9, A NE-NE-NE) //> ... SO, if "fn" mutate own args, and computation which "generate new value, // to update old value in args (in case of [] is some "next-empty-cell" in arr, and `len`) // is based ON THIS ARG",.. /// we (most likely) will consider it as NOT IDEMPONENT /// .. SO.. WHAT IS IMPORTANT?? // despite to be NOT IDEMPOTENT (from "caller" perspective).. since we have // 2 refs (caller and callee) and "our"(callee) is `mut`.. WE HAVE ADVANTAGE // of EXPLICIT PASSING THIS REF(to callee), BUT unfortunatly in JS we can't write // `&mut reff`.. // IT'S (1) PREVENT "ORDER"-PROBLEM described above (2) makes MORE OBVIOUS for // "reviewer" that "a" can be mutated (he at least SEE this "a" is passsed).. // ..but `some_fn(num)` is MUCH WORSE // /// TRY TO MAKE ALL EFFECTFULL-FN TO BE IDEMPOTENT | 1 // ALSO: (p.s. JS here, ONLY SINGLE-threaded programs and (in this post) SYNC) { fn calculateAverage(list) { // << obviously IDEMPOTENT sum = list.reduce((sum, x) => x + sum, 0); return sum / list.length; } var sum, nums = [1,2,4,7,11,16,22]; var avg = calculateAverage( nums ); } // Getify said that (if `sum` not mutably-aliased some another closure) // mutation of `sum` here it's "UNOBSERVED SIDE-EFF" .. // (.. although, such "UNOBSERVED MUTATIONS" easy can be eliminated, and we can use // pure-style easily here (but actually here it's just MATTER OF TASTE) // ) // ... SO.. what reasons we have for IDEMPOTENT MUTATIONS aka "unobserved side-eff"? // ... either NONE or "OWNED DATA"(P.Graham) //.. and further author cite Hickey: /// "If a tree falls in the forest, but no one is around to hear it, does it still make a sound?" // (^-- NO SHARED MUTABLE ALIASING.. or.. // .. we INCAPSULATE some data to MAINTAIN invariant [like in // exmps/js_state.rs:state_shraing] ) // // .. so it "like" pure-fn, or in term of P.Graham fn what used "owned data" fn get_cached_fn() { /// AS-OPPOSED to "`a` in `some_fn`"(above) `cache` is not "mut aliased"(only one ref which /// mutate and read) var cache = {}; // << "owned data", "unheard tree in the forest" return fn XX(n) { // "unobserved mutation", "like-pure", "right incapsultaion" if (cache[n]!== undefined) return cache[n] //.... NAZYVAI KAK HOCHEW' ..... /* do computation */ cache[n] = res_of_comutation(); } } // author: "The point is that if XX(..) is the only part of the program that accesses // and updates the cache side cause/effect, so it's "like"-pure" | 2.0 // ALSO: ORDER/FREQUENCY DEPENDENCY { var users = {}, userOrders = {}; fn fetchUserData(userId) { ajax( "http://some.api/user/" + userId, fn onUserData(userData) {
} fn fetchOrders(userId) { ajax( "http://some.api/orders/" + userId, fn onOrders(orders) { for (let i = 0; i < orders.length; i++) { // keep a reference to latest order for each user users[userId].latestOrder = orders[i]; userOrders[orders[i].orderId] = orders[i]; } }); } } // `fetchUserData` should be called before `fetchOrders`... AVOID SUCH "LOCAL STATE MACHINES" /// [GIST] there is should NOT BE ANY DEPENDENCY between ORDER/FREQUENCY OF CALL to /// "getters/setters"..(that is (kind of) SHOULD BE ONLY IDEMPOTENT-EFFECTFUL-FN).. /// of some "local state machine" aka "class instance" aka "object"(with incapsulation) // .. // ...So.. in this exmp, (also Miwko: initializing DB, which depends on "glob-state" - that is // "aliasing").. `fetchOrders` depends on ///| to be called.. IN SOME PARTICULAR STATE.. and this state is reached through ///| "PARAMS-REF"(aliasing)... SO.. in such case, ///| -=! SUCH STATE SHOULD BE PASSED DIRECTLY!=-.. /// (as in Miwko db-inital we refactor too) /// ..to AVOID "ORDER/FREQUENCY-OF-CALL(getter/setter) DEPENDENCY"(to set "needed" state) // ... any Getter/Setter should be designed in such way to BE ABLE to be called in ANY STATE! //>> OR.. THIS "ORDER_DEPENDENCY/COUPLING" SHOULD BE INCAPSULATED IN fn /// (BUT EXPLICIT PASSING OF MUT_ALISASED DEPENDENCY AS ARG /// IF IT POSSIBLE /// IS BETTER) // (in Miwko db-exmp: if we don't pass explicitly "mut-aliased"-state, then we should // incapsulate all COUPLED fns in single fn.. that is prepare NEEDED STATE.. // BUT.. IF THIS CHAIN OF COUPLED-fns is too long.. // |> WE RETURN TO THE PROBLEM.. // since we refactoring of fn-that-incapsulate-coupling is ERROR PRONE.. SO /// THIS CHAIN OF COUPLED_FNs SHOULD BE SHORT.. USUALLY === 2 ) // .. // Of course to achieve some "desired side-effs"(without them programm is useless) we // OFTEN need call "getters/setters" in some particular order..BUT.. that DOESN'T mean that // this order should become SPECIAL(HARDCODED) aka ORDER DEPENDENCY.. we just peek that order, // but it's should NOT BE SPECIAL for our "get/set-ters". // | 2.1 // So.. why I looked at ::exmps/js_state.rs::state_sharing fn.. and though: "why I need // "immutable-world", clojure, etc.. "ved'" this fn pretty good, and do its job well" // .. // .... BECAUSE: this "local-state-machine" don't rely on PARTICULAR STATE and ORDER/FREQUENCY.. // so IN ANY STATE... we can call "get/set-ters" in ANY ORDER .. AND IT'S OK, IT DO EXACTLY // WHAT WE WANT, EXECTLY SIDE-EFF WHAT WE WANT. /// After createing an object we can start do ANY "STATE_TRANSITION" which this /// object has, BUT, if only some STATE_TRANSITIONS allowed, IT'S ERRORPRONE. //...> whether "produce" or "consume" be called first.. WE DON'T CARE, //...> what the state we have in the moment of call to any fn(cons/prod).. WE DON'T CARE... // ..(some particular-state doesn't have special meaning for us) //..... ///|"consume"(as a getter[but it aslo a setter]) is NOT IDEMPOTENT.. because.. // for this I need pass the list-for-consuming EXPLICITLY.. // (the main condition for IDEMPOTENCY - absence of MUT_ALIASING[here `list`]) /// .. BUT: /// It INCAPSULATE "INVARIANT" of "prefiex is chenged only when we "splavili" old values in a /// list and clean it up" ///>>.. INCUPSULATEs IN ONE STATE_TRANSITION // .. SO.. it's let's both (`consume` and `produce`) "fns" works without FEAR about shared // (between them ) STATE(and INCAPSULATED) on which the relie(mut_aliased) since it doesn't // aliased elsewhere("tree in the wood").. and PROPERLY changed (INVARIANT) in `consumer`, and // this change INCAPSULATED in right place /// that_is: WE DEFINE ATOMIC_STATE_TRANSITIONs, why atomic, since state mutation/transaction /// can't be "interrupted" (here exmp: "prefix" changed BUT we not yet "splavili" values from /// `list` -- IT'S INTERRUPTION of STATE_TRANSITION) /// .. // .. also.. it doesn't rely on any particular state of `list` when we need "splavit'", so // we doesn't need MAINTAIN THIS INVARIANT. /// .. /// | SO.. we may say, that every "local-state-mach/obj" has some "patterns" of state_changing /// | .. let's call it "STATE_TRANSITIONS", and we should properly "FORM" this /// | state_transitions:.. incapsulate "INVARIANTS" in ONE_MOVE_PHASE, and incapsulate /// | "DATA-ACCESS" ...!!! TO MAKE THEM ATOMIC!!! /// .. /// AGAIN: (1) PROPER DEFINE (2) MAKE ATOMIC .. UNIT-test those 2-RULES is ACCOMPLISHED // .. // | moreover: list consuming, and set-new-prefix is (temporary) COUPLED.. // | .. that is ORDER DEPENDENCY.. // | ..BUT.. we INCAPSULATE it in "consume" - WE CANNOT INDEPENDENTLY SET PREFIX.. since // | it COUPLED.. and if we could(set pref independently) that would CREATE ABILITY to write // | code with ORDER/FREQUENCY DEPENDENCY(or call it temporal-coupling) BL99, da "STATE_TRANSITION" eto prosto well-defined API u obecta kotoryi incapsuliruet TREE_in_the_WOOD | 2.2 /// |about STATE_TRANSITION : since I invented this term after written bellow--v) // | to achive any goal with "response" object.. we need pass some STATE_TRANSITION, // and every this STATE_TRANSITION make sense (OFF_COURSE) only in ATOMIC form // ... `req, method, action` <<- THIS-IS main STATE_TRANSITION of our object, so // we need INCAPSULATE(ATOMICALLY_BOUND) it, ... i.e. MAKE SURE it's ATOMIC // .. // .. in expm of Bugaenko-request.. we can either do.. // 1. *** Request req = new Request("http://exmp.com", POST); //.. // .. and NO `self.method`-setter.. that is we create API that EXCLUDE possibility of // "INCONSISTENT STATE"(where getters can be "buggy" with wrong ORDER-dependency) /// AGAIN: we INCAPSULATE this "ORDER_DEPENDENCY/COUPLING" // (in some sense `req` "like" immutable, that is to use "GET"-req we NEED CREATE NEW REQUEST) // 2. *** res = req.fetch("POST", body) // we talk about SYNC calls in this post //.. // METHOD should be passed explicitly to `fetch`.. REALLY! why "requst"-obj should contain in // its state a METHOD param?.. (also `body`) // .. that is AGAIN: we incapsulate "coupled" effectful-methods( firstly set METHOD, secondly // fetch result), and explicitly pass the state of which effectful method is depend.. that is // make method IDEMPOTENT // .. // p.s. if we want "bind"(set object to state where it's use some-particul. METHOD) to some // particular METHOD in JS we should just use "bind"(aka Carrying) // .. or maybe in Java-like create some OBJECT-WRAPPER(here Fetcher).. which AGAIN // configured(INCAPUSLATE-COUPLING)-on-initialization(that is IMMUTABLE) let res_obj: Fetcher = req.fetch("POST", body); /*... somewhere.. >>> */ res_obj.get_result(); /// { // after 1/2 year: also '+' of such aproach as opposed to req.fetch(POST, body, &mut res_obj) // because if we create `res_obj`(res_buf) inside // `fetch` we know that we have no aliasing SINCE: only in rust we can know that if we pass // `&mut res_obj` then there is not aliasing.... BUT.. in Java it's just impossible... // so it's another trick how BY MEANS of api-design we can eliminate problem of // aliasing/mutability /// } // .. and for now: we "BIND" our req to particular state.. but INCAPSULATE this // "COUPLED MUTATIONS" like "consume" in "exmp/js_state.rs::state_sharing" /// { // after 1/2-year: OR: If we even store `fetch`-result in `req` object... we should // use `check / throw-excpe` that we can do next `fetch` only after we consume already // fetched body /// } //.. // |... so you can see how undestanding "Mut-aliasing"+"order/frequency-dependency" lead us // | TO CHANGING THE DESIGN(API) of our programm. // | 2.3 //// .......... MUST_SEE_ALSO: FunLight-ch5-Purifying // (note: closure-captur == obj.param-ref, // tags: "local-state-machine".. INCAPSULATE mutation!= HIDE mutation) // INCAPSULATE mutation == LOCALIZE mutation)
users[userId] = userData; });
random_line_split
idempotent.rs
//! mut_aliasing -- several links, AT_LEAST one of them is MUTABLE //! BTW: bunch_of_closures_with_mut_refs is like obj which alias through its params, which is //! mut_aliased refs on some another obj, or shared data //! that_is: CLOSURE_CAPUTRING == OBJ.MUT_ALIASED_REFS | 0 // fns with side-effs: --== IDEMPOTENT VS NON_IDEMPONTENT ==-- // /// fn is idempotent because its caused side-effs SIMULTANEOUSLY fulfill (2-former:wrong) 1 cond: /// 1. base on "input" or "immutable free-vars".. NO mut_aliasing /// .. /// (here was 2nd statement) Just change value.. not ADD. /// .. BUT.. it's NEVERHTHELESS.. 1-statement(MUT_alising) // // (small caveat: JUST REMINDER) var x; fn some_fn(n)
// not IDEMPOTENT because: *WRONG: we update, and/but not completly rewrite `x`, // *RIGHT: mut_aliasing (our computed value for `x` rely on mut_aliased `x`) // (BUT) // BTW(p.s.)--v: `some_fn` break rule: /// "mutate only TREE_in_the_WOOD, emit "own_copied/immutabl" value" // (TREE_in_the_WOOD is accesed or through "self/this", or "closure"-capturing) // fn some_fn(a = [], n) { a.push(n) } // ^-- here was: "ADD value, not just change." // BUT actually.. it's also can be considered as MUT_alising.. since result of `push` // depends of `a`,.. and if we call 2 times `some_fn` of course it's gives different sideeff, // since its computation based on MUTated value, ("EU ZHE") // .. // From the other hand.. `some_fn` can be considered as IDEMPONENT, since it's always gives // the same side-eff for the same input-VALUE.. that is if we alway will give `[x] as a`.. // we always receive `[x, n] as a` // .. // (v-- chut' ne udalil :lol:, podumal wo hn9, A NE-NE-NE) //> ... SO, if "fn" mutate own args, and computation which "generate new value, // to update old value in args (in case of [] is some "next-empty-cell" in arr, and `len`) // is based ON THIS ARG",.. /// we (most likely) will consider it as NOT IDEMPONENT /// .. SO.. WHAT IS IMPORTANT?? // despite to be NOT IDEMPOTENT (from "caller" perspective).. since we have // 2 refs (caller and callee) and "our"(callee) is `mut`.. WE HAVE ADVANTAGE // of EXPLICIT PASSING THIS REF(to callee), BUT unfortunatly in JS we can't write // `&mut reff`.. // IT'S (1) PREVENT "ORDER"-PROBLEM described above (2) makes MORE OBVIOUS for // "reviewer" that "a" can be mutated (he at least SEE this "a" is passsed).. // ..but `some_fn(num)` is MUCH WORSE // /// TRY TO MAKE ALL EFFECTFULL-FN TO BE IDEMPOTENT | 1 // ALSO: (p.s. JS here, ONLY SINGLE-threaded programs and (in this post) SYNC) { fn calculateAverage(list) { // << obviously IDEMPOTENT sum = list.reduce((sum, x) => x + sum, 0); return sum / list.length; } var sum, nums = [1,2,4,7,11,16,22]; var avg = calculateAverage( nums ); } // Getify said that (if `sum` not mutably-aliased some another closure) // mutation of `sum` here it's "UNOBSERVED SIDE-EFF" .. // (.. although, such "UNOBSERVED MUTATIONS" easy can be eliminated, and we can use // pure-style easily here (but actually here it's just MATTER OF TASTE) // ) // ... SO.. what reasons we have for IDEMPOTENT MUTATIONS aka "unobserved side-eff"? // ... either NONE or "OWNED DATA"(P.Graham) //.. and further author cite Hickey: /// "If a tree falls in the forest, but no one is around to hear it, does it still make a sound?" // (^-- NO SHARED MUTABLE ALIASING.. or.. // .. we INCAPSULATE some data to MAINTAIN invariant [like in // exmps/js_state.rs:state_shraing] ) // // .. so it "like" pure-fn, or in term of P.Graham fn what used "owned data" fn get_cached_fn() { /// AS-OPPOSED to "`a` in `some_fn`"(above) `cache` is not "mut aliased"(only one ref which /// mutate and read) var cache = {}; // << "owned data", "unheard tree in the forest" return fn XX(n) { // "unobserved mutation", "like-pure", "right incapsultaion" if (cache[n]!== undefined) return cache[n] //.... NAZYVAI KAK HOCHEW' ..... /* do computation */ cache[n] = res_of_comutation(); } } // author: "The point is that if XX(..) is the only part of the program that accesses // and updates the cache side cause/effect, so it's "like"-pure" | 2.0 // ALSO: ORDER/FREQUENCY DEPENDENCY { var users = {}, userOrders = {}; fn fetchUserData(userId) { ajax( "http://some.api/user/" + userId, fn onUserData(userData) { users[userId] = userData; }); } fn fetchOrders(userId) { ajax( "http://some.api/orders/" + userId, fn onOrders(orders) { for (let i = 0; i < orders.length; i++) { // keep a reference to latest order for each user users[userId].latestOrder = orders[i]; userOrders[orders[i].orderId] = orders[i]; } }); } } // `fetchUserData` should be called before `fetchOrders`... AVOID SUCH "LOCAL STATE MACHINES" /// [GIST] there is should NOT BE ANY DEPENDENCY between ORDER/FREQUENCY OF CALL to /// "getters/setters"..(that is (kind of) SHOULD BE ONLY IDEMPOTENT-EFFECTFUL-FN).. /// of some "local state machine" aka "class instance" aka "object"(with incapsulation) // .. // ...So.. in this exmp, (also Miwko: initializing DB, which depends on "glob-state" - that is // "aliasing").. `fetchOrders` depends on ///| to be called.. IN SOME PARTICULAR STATE.. and this state is reached through ///| "PARAMS-REF"(aliasing)... SO.. in such case, ///| -=! SUCH STATE SHOULD BE PASSED DIRECTLY!=-.. /// (as in Miwko db-inital we refactor too) /// ..to AVOID "ORDER/FREQUENCY-OF-CALL(getter/setter) DEPENDENCY"(to set "needed" state) // ... any Getter/Setter should be designed in such way to BE ABLE to be called in ANY STATE! //>> OR.. THIS "ORDER_DEPENDENCY/COUPLING" SHOULD BE INCAPSULATED IN fn /// (BUT EXPLICIT PASSING OF MUT_ALISASED DEPENDENCY AS ARG /// IF IT POSSIBLE /// IS BETTER) // (in Miwko db-exmp: if we don't pass explicitly "mut-aliased"-state, then we should // incapsulate all COUPLED fns in single fn.. that is prepare NEEDED STATE.. // BUT.. IF THIS CHAIN OF COUPLED-fns is too long.. // |> WE RETURN TO THE PROBLEM.. // since we refactoring of fn-that-incapsulate-coupling is ERROR PRONE.. SO /// THIS CHAIN OF COUPLED_FNs SHOULD BE SHORT.. USUALLY === 2 ) // .. // Of course to achieve some "desired side-effs"(without them programm is useless) we // OFTEN need call "getters/setters" in some particular order..BUT.. that DOESN'T mean that // this order should become SPECIAL(HARDCODED) aka ORDER DEPENDENCY.. we just peek that order, // but it's should NOT BE SPECIAL for our "get/set-ters". // | 2.1 // So.. why I looked at ::exmps/js_state.rs::state_sharing fn.. and though: "why I need // "immutable-world", clojure, etc.. "ved'" this fn pretty good, and do its job well" // .. // .... BECAUSE: this "local-state-machine" don't rely on PARTICULAR STATE and ORDER/FREQUENCY.. // so IN ANY STATE... we can call "get/set-ters" in ANY ORDER .. AND IT'S OK, IT DO EXACTLY // WHAT WE WANT, EXECTLY SIDE-EFF WHAT WE WANT. /// After createing an object we can start do ANY "STATE_TRANSITION" which this /// object has, BUT, if only some STATE_TRANSITIONS allowed, IT'S ERRORPRONE. //...> whether "produce" or "consume" be called first.. WE DON'T CARE, //...> what the state we have in the moment of call to any fn(cons/prod).. WE DON'T CARE... // ..(some particular-state doesn't have special meaning for us) //..... ///|"consume"(as a getter[but it aslo a setter]) is NOT IDEMPOTENT.. because.. // for this I need pass the list-for-consuming EXPLICITLY.. // (the main condition for IDEMPOTENCY - absence of MUT_ALIASING[here `list`]) /// .. BUT: /// It INCAPSULATE "INVARIANT" of "prefiex is chenged only when we "splavili" old values in a /// list and clean it up" ///>>.. INCUPSULATEs IN ONE STATE_TRANSITION // .. SO.. it's let's both (`consume` and `produce`) "fns" works without FEAR about shared // (between them ) STATE(and INCAPSULATED) on which the relie(mut_aliased) since it doesn't // aliased elsewhere("tree in the wood").. and PROPERLY changed (INVARIANT) in `consumer`, and // this change INCAPSULATED in right place /// that_is: WE DEFINE ATOMIC_STATE_TRANSITIONs, why atomic, since state mutation/transaction /// can't be "interrupted" (here exmp: "prefix" changed BUT we not yet "splavili" values from /// `list` -- IT'S INTERRUPTION of STATE_TRANSITION) /// .. // .. also.. it doesn't rely on any particular state of `list` when we need "splavit'", so // we doesn't need MAINTAIN THIS INVARIANT. /// .. /// | SO.. we may say, that every "local-state-mach/obj" has some "patterns" of state_changing /// | .. let's call it "STATE_TRANSITIONS", and we should properly "FORM" this /// | state_transitions:.. incapsulate "INVARIANTS" in ONE_MOVE_PHASE, and incapsulate /// | "DATA-ACCESS" ...!!! TO MAKE THEM ATOMIC!!! /// .. /// AGAIN: (1) PROPER DEFINE (2) MAKE ATOMIC .. UNIT-test those 2-RULES is ACCOMPLISHED // .. // | moreover: list consuming, and set-new-prefix is (temporary) COUPLED.. // | .. that is ORDER DEPENDENCY.. // | ..BUT.. we INCAPSULATE it in "consume" - WE CANNOT INDEPENDENTLY SET PREFIX.. since // | it COUPLED.. and if we could(set pref independently) that would CREATE ABILITY to write // | code with ORDER/FREQUENCY DEPENDENCY(or call it temporal-coupling) BL99, da "STATE_TRANSITION" eto prosto well-defined API u obecta kotoryi incapsuliruet TREE_in_the_WOOD | 2.2 /// |about STATE_TRANSITION : since I invented this term after written bellow--v) // | to achive any goal with "response" object.. we need pass some STATE_TRANSITION, // and every this STATE_TRANSITION make sense (OFF_COURSE) only in ATOMIC form // ... `req, method, action` <<- THIS-IS main STATE_TRANSITION of our object, so // we need INCAPSULATE(ATOMICALLY_BOUND) it, ... i.e. MAKE SURE it's ATOMIC // .. // .. in expm of Bugaenko-request.. we can either do.. // 1. *** Request req = new Request("http://exmp.com", POST); //.. // .. and NO `self.method`-setter.. that is we create API that EXCLUDE possibility of // "INCONSISTENT STATE"(where getters can be "buggy" with wrong ORDER-dependency) /// AGAIN: we INCAPSULATE this "ORDER_DEPENDENCY/COUPLING" // (in some sense `req` "like" immutable, that is to use "GET"-req we NEED CREATE NEW REQUEST) // 2. *** res = req.fetch("POST", body) // we talk about SYNC calls in this post //.. // METHOD should be passed explicitly to `fetch`.. REALLY! why "requst"-obj should contain in // its state a METHOD param?.. (also `body`) // .. that is AGAIN: we incapsulate "coupled" effectful-methods( firstly set METHOD, secondly // fetch result), and explicitly pass the state of which effectful method is depend.. that is // make method IDEMPOTENT // .. // p.s. if we want "bind"(set object to state where it's use some-particul. METHOD) to some // particular METHOD in JS we should just use "bind"(aka Carrying) // .. or maybe in Java-like create some OBJECT-WRAPPER(here Fetcher).. which AGAIN // configured(INCAPUSLATE-COUPLING)-on-initialization(that is IMMUTABLE) let res_obj: Fetcher = req.fetch("POST", body); /*... somewhere.. >>> */ res_obj.get_result(); /// { // after 1/2 year: also '+' of such aproach as opposed to req.fetch(POST, body, &mut res_obj) // because if we create `res_obj`(res_buf) inside // `fetch` we know that we have no aliasing SINCE: only in rust we can know that if we pass // `&mut res_obj` then there is not aliasing.... BUT.. in Java it's just impossible... // so it's another trick how BY MEANS of api-design we can eliminate problem of // aliasing/mutability /// } // .. and for now: we "BIND" our req to particular state.. but INCAPSULATE this // "COUPLED MUTATIONS" like "consume" in "exmp/js_state.rs::state_sharing" /// { // after 1/2-year: OR: If we even store `fetch`-result in `req` object... we should // use `check / throw-excpe` that we can do next `fetch` only after we consume already // fetched body /// } //.. // |... so you can see how undestanding "Mut-aliasing"+"order/frequency-dependency" lead us // | TO CHANGING THE DESIGN(API) of our programm. // | 2.3 //// .......... MUST_SEE_ALSO: FunLight-ch5-Purifying // (note: closure-captur == obj.param-ref, // tags: "local-state-machine".. INCAPSULATE mutation!= HIDE mutation) // INCAPSULATE mutation == LOCALIZE mutation)
{ x += n*x }
identifier_body
idempotent.rs
//! mut_aliasing -- several links, AT_LEAST one of them is MUTABLE //! BTW: bunch_of_closures_with_mut_refs is like obj which alias through its params, which is //! mut_aliased refs on some another obj, or shared data //! that_is: CLOSURE_CAPUTRING == OBJ.MUT_ALIASED_REFS | 0 // fns with side-effs: --== IDEMPOTENT VS NON_IDEMPONTENT ==-- // /// fn is idempotent because its caused side-effs SIMULTANEOUSLY fulfill (2-former:wrong) 1 cond: /// 1. base on "input" or "immutable free-vars".. NO mut_aliasing /// .. /// (here was 2nd statement) Just change value.. not ADD. /// .. BUT.. it's NEVERHTHELESS.. 1-statement(MUT_alising) // // (small caveat: JUST REMINDER) var x; fn some_fn(n) { x += n*x } // not IDEMPOTENT because: *WRONG: we update, and/but not completly rewrite `x`, // *RIGHT: mut_aliasing (our computed value for `x` rely on mut_aliased `x`) // (BUT) // BTW(p.s.)--v: `some_fn` break rule: /// "mutate only TREE_in_the_WOOD, emit "own_copied/immutabl" value" // (TREE_in_the_WOOD is accesed or through "self/this", or "closure"-capturing) // fn
(a = [], n) { a.push(n) } // ^-- here was: "ADD value, not just change." // BUT actually.. it's also can be considered as MUT_alising.. since result of `push` // depends of `a`,.. and if we call 2 times `some_fn` of course it's gives different sideeff, // since its computation based on MUTated value, ("EU ZHE") // .. // From the other hand.. `some_fn` can be considered as IDEMPONENT, since it's always gives // the same side-eff for the same input-VALUE.. that is if we alway will give `[x] as a`.. // we always receive `[x, n] as a` // .. // (v-- chut' ne udalil :lol:, podumal wo hn9, A NE-NE-NE) //> ... SO, if "fn" mutate own args, and computation which "generate new value, // to update old value in args (in case of [] is some "next-empty-cell" in arr, and `len`) // is based ON THIS ARG",.. /// we (most likely) will consider it as NOT IDEMPONENT /// .. SO.. WHAT IS IMPORTANT?? // despite to be NOT IDEMPOTENT (from "caller" perspective).. since we have // 2 refs (caller and callee) and "our"(callee) is `mut`.. WE HAVE ADVANTAGE // of EXPLICIT PASSING THIS REF(to callee), BUT unfortunatly in JS we can't write // `&mut reff`.. // IT'S (1) PREVENT "ORDER"-PROBLEM described above (2) makes MORE OBVIOUS for // "reviewer" that "a" can be mutated (he at least SEE this "a" is passsed).. // ..but `some_fn(num)` is MUCH WORSE // /// TRY TO MAKE ALL EFFECTFULL-FN TO BE IDEMPOTENT | 1 // ALSO: (p.s. JS here, ONLY SINGLE-threaded programs and (in this post) SYNC) { fn calculateAverage(list) { // << obviously IDEMPOTENT sum = list.reduce((sum, x) => x + sum, 0); return sum / list.length; } var sum, nums = [1,2,4,7,11,16,22]; var avg = calculateAverage( nums ); } // Getify said that (if `sum` not mutably-aliased some another closure) // mutation of `sum` here it's "UNOBSERVED SIDE-EFF" .. // (.. although, such "UNOBSERVED MUTATIONS" easy can be eliminated, and we can use // pure-style easily here (but actually here it's just MATTER OF TASTE) // ) // ... SO.. what reasons we have for IDEMPOTENT MUTATIONS aka "unobserved side-eff"? // ... either NONE or "OWNED DATA"(P.Graham) //.. and further author cite Hickey: /// "If a tree falls in the forest, but no one is around to hear it, does it still make a sound?" // (^-- NO SHARED MUTABLE ALIASING.. or.. // .. we INCAPSULATE some data to MAINTAIN invariant [like in // exmps/js_state.rs:state_shraing] ) // // .. so it "like" pure-fn, or in term of P.Graham fn what used "owned data" fn get_cached_fn() { /// AS-OPPOSED to "`a` in `some_fn`"(above) `cache` is not "mut aliased"(only one ref which /// mutate and read) var cache = {}; // << "owned data", "unheard tree in the forest" return fn XX(n) { // "unobserved mutation", "like-pure", "right incapsultaion" if (cache[n]!== undefined) return cache[n] //.... NAZYVAI KAK HOCHEW' ..... /* do computation */ cache[n] = res_of_comutation(); } } // author: "The point is that if XX(..) is the only part of the program that accesses // and updates the cache side cause/effect, so it's "like"-pure" | 2.0 // ALSO: ORDER/FREQUENCY DEPENDENCY { var users = {}, userOrders = {}; fn fetchUserData(userId) { ajax( "http://some.api/user/" + userId, fn onUserData(userData) { users[userId] = userData; }); } fn fetchOrders(userId) { ajax( "http://some.api/orders/" + userId, fn onOrders(orders) { for (let i = 0; i < orders.length; i++) { // keep a reference to latest order for each user users[userId].latestOrder = orders[i]; userOrders[orders[i].orderId] = orders[i]; } }); } } // `fetchUserData` should be called before `fetchOrders`... AVOID SUCH "LOCAL STATE MACHINES" /// [GIST] there is should NOT BE ANY DEPENDENCY between ORDER/FREQUENCY OF CALL to /// "getters/setters"..(that is (kind of) SHOULD BE ONLY IDEMPOTENT-EFFECTFUL-FN).. /// of some "local state machine" aka "class instance" aka "object"(with incapsulation) // .. // ...So.. in this exmp, (also Miwko: initializing DB, which depends on "glob-state" - that is // "aliasing").. `fetchOrders` depends on ///| to be called.. IN SOME PARTICULAR STATE.. and this state is reached through ///| "PARAMS-REF"(aliasing)... SO.. in such case, ///| -=! SUCH STATE SHOULD BE PASSED DIRECTLY!=-.. /// (as in Miwko db-inital we refactor too) /// ..to AVOID "ORDER/FREQUENCY-OF-CALL(getter/setter) DEPENDENCY"(to set "needed" state) // ... any Getter/Setter should be designed in such way to BE ABLE to be called in ANY STATE! //>> OR.. THIS "ORDER_DEPENDENCY/COUPLING" SHOULD BE INCAPSULATED IN fn /// (BUT EXPLICIT PASSING OF MUT_ALISASED DEPENDENCY AS ARG /// IF IT POSSIBLE /// IS BETTER) // (in Miwko db-exmp: if we don't pass explicitly "mut-aliased"-state, then we should // incapsulate all COUPLED fns in single fn.. that is prepare NEEDED STATE.. // BUT.. IF THIS CHAIN OF COUPLED-fns is too long.. // |> WE RETURN TO THE PROBLEM.. // since we refactoring of fn-that-incapsulate-coupling is ERROR PRONE.. SO /// THIS CHAIN OF COUPLED_FNs SHOULD BE SHORT.. USUALLY === 2 ) // .. // Of course to achieve some "desired side-effs"(without them programm is useless) we // OFTEN need call "getters/setters" in some particular order..BUT.. that DOESN'T mean that // this order should become SPECIAL(HARDCODED) aka ORDER DEPENDENCY.. we just peek that order, // but it's should NOT BE SPECIAL for our "get/set-ters". // | 2.1 // So.. why I looked at ::exmps/js_state.rs::state_sharing fn.. and though: "why I need // "immutable-world", clojure, etc.. "ved'" this fn pretty good, and do its job well" // .. // .... BECAUSE: this "local-state-machine" don't rely on PARTICULAR STATE and ORDER/FREQUENCY.. // so IN ANY STATE... we can call "get/set-ters" in ANY ORDER .. AND IT'S OK, IT DO EXACTLY // WHAT WE WANT, EXECTLY SIDE-EFF WHAT WE WANT. /// After createing an object we can start do ANY "STATE_TRANSITION" which this /// object has, BUT, if only some STATE_TRANSITIONS allowed, IT'S ERRORPRONE. //...> whether "produce" or "consume" be called first.. WE DON'T CARE, //...> what the state we have in the moment of call to any fn(cons/prod).. WE DON'T CARE... // ..(some particular-state doesn't have special meaning for us) //..... ///|"consume"(as a getter[but it aslo a setter]) is NOT IDEMPOTENT.. because.. // for this I need pass the list-for-consuming EXPLICITLY.. // (the main condition for IDEMPOTENCY - absence of MUT_ALIASING[here `list`]) /// .. BUT: /// It INCAPSULATE "INVARIANT" of "prefiex is chenged only when we "splavili" old values in a /// list and clean it up" ///>>.. INCUPSULATEs IN ONE STATE_TRANSITION // .. SO.. it's let's both (`consume` and `produce`) "fns" works without FEAR about shared // (between them ) STATE(and INCAPSULATED) on which the relie(mut_aliased) since it doesn't // aliased elsewhere("tree in the wood").. and PROPERLY changed (INVARIANT) in `consumer`, and // this change INCAPSULATED in right place /// that_is: WE DEFINE ATOMIC_STATE_TRANSITIONs, why atomic, since state mutation/transaction /// can't be "interrupted" (here exmp: "prefix" changed BUT we not yet "splavili" values from /// `list` -- IT'S INTERRUPTION of STATE_TRANSITION) /// .. // .. also.. it doesn't rely on any particular state of `list` when we need "splavit'", so // we doesn't need MAINTAIN THIS INVARIANT. /// .. /// | SO.. we may say, that every "local-state-mach/obj" has some "patterns" of state_changing /// | .. let's call it "STATE_TRANSITIONS", and we should properly "FORM" this /// | state_transitions:.. incapsulate "INVARIANTS" in ONE_MOVE_PHASE, and incapsulate /// | "DATA-ACCESS" ...!!! TO MAKE THEM ATOMIC!!! /// .. /// AGAIN: (1) PROPER DEFINE (2) MAKE ATOMIC .. UNIT-test those 2-RULES is ACCOMPLISHED // .. // | moreover: list consuming, and set-new-prefix is (temporary) COUPLED.. // | .. that is ORDER DEPENDENCY.. // | ..BUT.. we INCAPSULATE it in "consume" - WE CANNOT INDEPENDENTLY SET PREFIX.. since // | it COUPLED.. and if we could(set pref independently) that would CREATE ABILITY to write // | code with ORDER/FREQUENCY DEPENDENCY(or call it temporal-coupling) BL99, da "STATE_TRANSITION" eto prosto well-defined API u obecta kotoryi incapsuliruet TREE_in_the_WOOD | 2.2 /// |about STATE_TRANSITION : since I invented this term after written bellow--v) // | to achive any goal with "response" object.. we need pass some STATE_TRANSITION, // and every this STATE_TRANSITION make sense (OFF_COURSE) only in ATOMIC form // ... `req, method, action` <<- THIS-IS main STATE_TRANSITION of our object, so // we need INCAPSULATE(ATOMICALLY_BOUND) it, ... i.e. MAKE SURE it's ATOMIC // .. // .. in expm of Bugaenko-request.. we can either do.. // 1. *** Request req = new Request("http://exmp.com", POST); //.. // .. and NO `self.method`-setter.. that is we create API that EXCLUDE possibility of // "INCONSISTENT STATE"(where getters can be "buggy" with wrong ORDER-dependency) /// AGAIN: we INCAPSULATE this "ORDER_DEPENDENCY/COUPLING" // (in some sense `req` "like" immutable, that is to use "GET"-req we NEED CREATE NEW REQUEST) // 2. *** res = req.fetch("POST", body) // we talk about SYNC calls in this post //.. // METHOD should be passed explicitly to `fetch`.. REALLY! why "requst"-obj should contain in // its state a METHOD param?.. (also `body`) // .. that is AGAIN: we incapsulate "coupled" effectful-methods( firstly set METHOD, secondly // fetch result), and explicitly pass the state of which effectful method is depend.. that is // make method IDEMPOTENT // .. // p.s. if we want "bind"(set object to state where it's use some-particul. METHOD) to some // particular METHOD in JS we should just use "bind"(aka Carrying) // .. or maybe in Java-like create some OBJECT-WRAPPER(here Fetcher).. which AGAIN // configured(INCAPUSLATE-COUPLING)-on-initialization(that is IMMUTABLE) let res_obj: Fetcher = req.fetch("POST", body); /*... somewhere.. >>> */ res_obj.get_result(); /// { // after 1/2 year: also '+' of such aproach as opposed to req.fetch(POST, body, &mut res_obj) // because if we create `res_obj`(res_buf) inside // `fetch` we know that we have no aliasing SINCE: only in rust we can know that if we pass // `&mut res_obj` then there is not aliasing.... BUT.. in Java it's just impossible... // so it's another trick how BY MEANS of api-design we can eliminate problem of // aliasing/mutability /// } // .. and for now: we "BIND" our req to particular state.. but INCAPSULATE this // "COUPLED MUTATIONS" like "consume" in "exmp/js_state.rs::state_sharing" /// { // after 1/2-year: OR: If we even store `fetch`-result in `req` object... we should // use `check / throw-excpe` that we can do next `fetch` only after we consume already // fetched body /// } //.. // |... so you can see how undestanding "Mut-aliasing"+"order/frequency-dependency" lead us // | TO CHANGING THE DESIGN(API) of our programm. // | 2.3 //// .......... MUST_SEE_ALSO: FunLight-ch5-Purifying // (note: closure-captur == obj.param-ref, // tags: "local-state-machine".. INCAPSULATE mutation!= HIDE mutation) // INCAPSULATE mutation == LOCALIZE mutation)
some_fn
identifier_name
routing.rs
//! Functions for adding ingress/egress nodes. //! //! In particular: //! //! - New nodes that are children of nodes in a different domain must be preceeded by an ingress //! - Egress nodes must be added to nodes that now have children in a different domain //! - Egress nodes that gain new children must gain channels to facilitate forwarding //! - Timestamp ingress nodes for existing domains must be connected to new base nodes //! - Timestamp ingress nodes must be added to all new domains use flow::prelude::*; use flow::domain; use flow::node; use petgraph; use petgraph::graph::NodeIndex; use std::collections::{HashSet, HashMap}; use std::sync::mpsc; use slog::Logger; /// Add in ingress and egress nodes as appropriate in the graph to facilitate cross-domain /// communication. pub fn add(log: &Logger, graph: &mut Graph, source: NodeIndex, new: &mut HashSet<NodeIndex>) -> HashMap<domain::Index, HashMap<NodeIndex, NodeIndex>> { // find all new nodes in topological order. we collect first since we'll be mutating the graph // below. it's convenient to have the nodes in topological order, because we then know that // we'll first add egress nodes, and then the related ingress nodes. if we're ever required to // add an ingress node, and its parent isn't an egress node, we know that we're seeing a // connection between an old node in one domain, and a new node in a different domain. let mut topo_list = Vec::with_capacity(new.len()); let mut topo = petgraph::visit::Topo::new(&*graph); while let Some(node) = topo.next(&*graph) { if node == source { continue; } if!new.contains(&node) { continue; } topo_list.push(node); } // we need to keep track of all the times we change the parent of a node (by replacing it with // an egress, and then with an ingress), since this remapping must be communicated to the nodes // so they know the true identifier of their parent in the graph. let mut swaps = HashMap::new(); // we also need to keep track of the ingress nodes we've added to each domain so that we don't // end up with two ingress nodes for a given egress node. that would cause unnecessary // cross-domain communication. this is domain => source => NodeIndex (of ingress). note that // `source` here is actually the *egress* node. this is because by the time we add ingress // nodes, we know our incoming edges have already been updated to point to the egress nodes. let mut ingresses = HashMap::new(); for node in topo_list { let domain = graph[node].domain(); // First, we add egress nodes for any of our cross-domain children let children: Vec<_> = graph.neighbors_directed(node, petgraph::EdgeDirection::Outgoing) .collect(); // collect so we can mutate graph // We then need to make sure that we're acting on up-to-date information about existing // egress/ingress pairs. In particular, we want to know about egresses this node already // has (and to which domains). In the process we also populate the information about // ingress nodes in other domains that point here (those shouldn't be re-created if new // nodes are created in the corresponding domains). let mut egresses = HashMap::new(); for child in &children { if!new.contains(child) { continue; } if let node::Type::Egress {.. } = *graph[*child] { for ingress in graph.neighbors_directed(*child, petgraph::EdgeDirection::Outgoing) { // this egress already contains this node to the ingress' domain egresses.insert(graph[ingress].domain(), *child); // also keep track of the corresponding ingress node so we can re-use it ingresses.entry(graph[ingress].domain()) .or_insert_with(HashMap::new) .insert(node, ingress); } } } for child in children { let cdomain = graph[child].domain(); if domain!= cdomain { // child is in a different domain if!egresses.contains_key(&cdomain) { // create an egress node to handle that // NOTE: technically, this doesn't need to mirror its parent, but meh let proxy = graph[node].mirror(node::Type::Egress { tags: Default::default(), txs: Default::default(), }); let egress = graph.add_node(proxy); graph.add_edge(node, egress, false); new.insert(egress); egresses.insert(cdomain, egress); trace!(log, "adding cross-domain egress to new node"; "node" => node.index(), "egress" => egress.index()); } else { trace!(log, "re-using cross-domain egress to new node"; "node" => node.index(), "egress" => egresses[&cdomain].index()); } // we need to hook that node in between us and this child let egress = egresses[&cdomain]; let old = graph.find_edge(node, child).unwrap(); let was_materialized = graph.remove_edge(old).unwrap(); graph.add_edge(egress, child, was_materialized); // this ends up being re-executed, but that's okay swaps.entry(cdomain).or_insert_with(HashMap::new).insert(node, egress); } } // Then, we look for any parents in the graph that // // a) are in a different domain, and // b) aren't egress nodes // // This situation arises whenever a cross-domain edge is added as the result of a // migration. We need to find or make an egress domain in that other domain, and hook that // up as the parent of this node instead of the original internal foreign domain node. // // Note that same-domain parents are never interesting to us for this purpose. let mut parents: Vec<_> = graph.neighbors_directed(node, petgraph::EdgeDirection::Incoming) .filter(|&ni| ni == source || graph[ni].domain()!= domain) .collect(); // collect so we can mutate graph for parent in &mut parents { if *parent == source { // no egress needed continue; } // since we are traversing in topological order, egress nodes should have been added to // all our parents, and our incoming edges should have been updated. if that *isn't* // the case for a given parent, it must be a pre-existing parent. if let node::Type::Egress {.. } = *graph[*parent] { continue; } // let's first see if this parent already has an egress we can use let egress = graph.neighbors_directed(*parent, petgraph::EdgeDirection::Outgoing) .find(|&ni| graph[ni].is_egress()); let egress = egress.unwrap_or_else(|| { // no, okay, so we need to add an egress for that other node, let proxy = graph[*parent].mirror(node::Type::Egress{ txs: Default::default(), tags: Default::default() }); let egress = graph.add_node(proxy); trace!(log, "adding cross-domain egress to existing node"; "node" => parent.index(), "egress" => egress.index()); graph.add_edge(*parent, egress, false); new.insert(egress); egress }); // now, let's use that egress as our parent instead let old = graph.find_edge(*parent, node).unwrap(); let was_materialized = graph.remove_edge(old).unwrap(); graph.add_edge(egress, node, was_materialized); // all references to our original parent should now refer to the egress swaps.entry(domain).or_insert_with(HashMap::new).insert(*parent, egress); // and we should now just consider the egress our parent instead *parent = egress; } // Now that we know all our foreign parents are egress nodes, we can add ingress nodes. // Note that by this time (due to the topological walk), we know that `ingresses` has been // sufficiently populated to contain any relevant existing ingress nodes. for parent in parents { // is there already an ingress node we can re-use? let mut ingress = ingresses.get(&domain).and_then(|ingresses| ingresses.get(&parent)).map(|ni| *ni); if ingress.is_none() { // nope -- create our new ingress node let mut i = graph[parent].mirror(node::Type::Ingress); i.add_to(domain); // it belongs to this domain, not that of the parent let i = graph.add_node(i); graph.add_edge(parent, i, false); // we also now need to deal with this ingress node new.insert(i); if parent == source { trace!(log, "adding source ingress"; "base" => node.index(), "ingress" => i.index()); // we don't re-use source ingress nodes } else { trace!(log, "adding cross-domain ingress"; "to" => node.index(), "from" => parent.index(), "ingress" => i.index()); ingresses.entry(domain).or_insert_with(HashMap::new).insert(parent, i); } ingress = Some(i); } else { trace!(log, "re-using cross-domain ingress"; "to" => node.index(), "from" => parent.index(), "ingress" => ingress.unwrap().index()); } let ingress = ingress.unwrap(); // we need to hook the ingress node in between us and the parent let old = graph.find_edge(parent, node).unwrap(); let was_materialized = graph.remove_edge(old).unwrap(); graph.add_edge(ingress, node, was_materialized); // tracking swaps here is a bit tricky because we've already swapped the "true" parents // of `node` with the ids of the egress nodes. thus, we actually need to do swaps on // the values in `swaps`, not insert new entries (that, or we'd need to change the // resolution process to be recursive, which is painful and unnecessary). note that we // *also* need to special-case handing base nodes, because there there *won't* be a // parent egress swap if parent!= source { for (_, to) in swaps.get_mut(&domain).unwrap().iter_mut() { if *to == parent { *to = ingress; } } } } } swaps } pub fn connect(log: &Logger, graph: &mut Graph, main_txs: &HashMap<domain::Index, mpsc::SyncSender<Packet>>, new: &HashSet<NodeIndex>)
node::Type::Source => continue, _ => unreachable!("ingress parent is not egress"), } } } }
{ // ensure all egress nodes contain the tx channel of the domains of their child ingress nodes for &node in new { let n = &graph[node]; if let node::Type::Ingress = **n { // check the egress connected to this ingress } else { continue; } for egress in graph.neighbors_directed(node, petgraph::EdgeDirection::Incoming) { match *graph[egress] { node::Type::Egress { ref txs, .. } => { trace!(log, "connecting"; "egress" => egress.index(), "ingress" => node.index()); txs.lock() .unwrap() .push((node.into(), n.addr(), main_txs[&n.domain()].clone())); continue; }
identifier_body
routing.rs
//! Functions for adding ingress/egress nodes. //! //! In particular: //! //! - New nodes that are children of nodes in a different domain must be preceeded by an ingress //! - Egress nodes must be added to nodes that now have children in a different domain //! - Egress nodes that gain new children must gain channels to facilitate forwarding //! - Timestamp ingress nodes for existing domains must be connected to new base nodes //! - Timestamp ingress nodes must be added to all new domains use flow::prelude::*; use flow::domain; use flow::node; use petgraph; use petgraph::graph::NodeIndex; use std::collections::{HashSet, HashMap}; use std::sync::mpsc; use slog::Logger; /// Add in ingress and egress nodes as appropriate in the graph to facilitate cross-domain /// communication. pub fn add(log: &Logger, graph: &mut Graph, source: NodeIndex, new: &mut HashSet<NodeIndex>) -> HashMap<domain::Index, HashMap<NodeIndex, NodeIndex>> { // find all new nodes in topological order. we collect first since we'll be mutating the graph // below. it's convenient to have the nodes in topological order, because we then know that // we'll first add egress nodes, and then the related ingress nodes. if we're ever required to // add an ingress node, and its parent isn't an egress node, we know that we're seeing a // connection between an old node in one domain, and a new node in a different domain. let mut topo_list = Vec::with_capacity(new.len()); let mut topo = petgraph::visit::Topo::new(&*graph); while let Some(node) = topo.next(&*graph) { if node == source { continue; } if!new.contains(&node) { continue; } topo_list.push(node); } // we need to keep track of all the times we change the parent of a node (by replacing it with // an egress, and then with an ingress), since this remapping must be communicated to the nodes // so they know the true identifier of their parent in the graph. let mut swaps = HashMap::new(); // we also need to keep track of the ingress nodes we've added to each domain so that we don't // end up with two ingress nodes for a given egress node. that would cause unnecessary // cross-domain communication. this is domain => source => NodeIndex (of ingress). note that // `source` here is actually the *egress* node. this is because by the time we add ingress // nodes, we know our incoming edges have already been updated to point to the egress nodes. let mut ingresses = HashMap::new(); for node in topo_list { let domain = graph[node].domain(); // First, we add egress nodes for any of our cross-domain children let children: Vec<_> = graph.neighbors_directed(node, petgraph::EdgeDirection::Outgoing) .collect(); // collect so we can mutate graph // We then need to make sure that we're acting on up-to-date information about existing // egress/ingress pairs. In particular, we want to know about egresses this node already // has (and to which domains). In the process we also populate the information about // ingress nodes in other domains that point here (those shouldn't be re-created if new // nodes are created in the corresponding domains). let mut egresses = HashMap::new(); for child in &children { if!new.contains(child) { continue; } if let node::Type::Egress {.. } = *graph[*child] { for ingress in graph.neighbors_directed(*child, petgraph::EdgeDirection::Outgoing) { // this egress already contains this node to the ingress' domain egresses.insert(graph[ingress].domain(), *child); // also keep track of the corresponding ingress node so we can re-use it ingresses.entry(graph[ingress].domain()) .or_insert_with(HashMap::new) .insert(node, ingress); } } } for child in children { let cdomain = graph[child].domain(); if domain!= cdomain { // child is in a different domain if!egresses.contains_key(&cdomain) { // create an egress node to handle that // NOTE: technically, this doesn't need to mirror its parent, but meh let proxy = graph[node].mirror(node::Type::Egress { tags: Default::default(), txs: Default::default(), }); let egress = graph.add_node(proxy); graph.add_edge(node, egress, false); new.insert(egress); egresses.insert(cdomain, egress); trace!(log, "adding cross-domain egress to new node"; "node" => node.index(), "egress" => egress.index()); } else { trace!(log, "re-using cross-domain egress to new node"; "node" => node.index(), "egress" => egresses[&cdomain].index()); } // we need to hook that node in between us and this child let egress = egresses[&cdomain]; let old = graph.find_edge(node, child).unwrap(); let was_materialized = graph.remove_edge(old).unwrap(); graph.add_edge(egress, child, was_materialized); // this ends up being re-executed, but that's okay swaps.entry(cdomain).or_insert_with(HashMap::new).insert(node, egress); } } // Then, we look for any parents in the graph that // // a) are in a different domain, and // b) aren't egress nodes // // This situation arises whenever a cross-domain edge is added as the result of a // migration. We need to find or make an egress domain in that other domain, and hook that // up as the parent of this node instead of the original internal foreign domain node. // // Note that same-domain parents are never interesting to us for this purpose. let mut parents: Vec<_> = graph.neighbors_directed(node, petgraph::EdgeDirection::Incoming) .filter(|&ni| ni == source || graph[ni].domain()!= domain) .collect(); // collect so we can mutate graph for parent in &mut parents { if *parent == source { // no egress needed continue; } // since we are traversing in topological order, egress nodes should have been added to // all our parents, and our incoming edges should have been updated. if that *isn't* // the case for a given parent, it must be a pre-existing parent. if let node::Type::Egress {.. } = *graph[*parent] { continue; } // let's first see if this parent already has an egress we can use let egress = graph.neighbors_directed(*parent, petgraph::EdgeDirection::Outgoing) .find(|&ni| graph[ni].is_egress()); let egress = egress.unwrap_or_else(|| { // no, okay, so we need to add an egress for that other node, let proxy = graph[*parent].mirror(node::Type::Egress{ txs: Default::default(), tags: Default::default() }); let egress = graph.add_node(proxy); trace!(log, "adding cross-domain egress to existing node"; "node" => parent.index(), "egress" => egress.index()); graph.add_edge(*parent, egress, false); new.insert(egress); egress }); // now, let's use that egress as our parent instead let old = graph.find_edge(*parent, node).unwrap(); let was_materialized = graph.remove_edge(old).unwrap(); graph.add_edge(egress, node, was_materialized); // all references to our original parent should now refer to the egress swaps.entry(domain).or_insert_with(HashMap::new).insert(*parent, egress); // and we should now just consider the egress our parent instead *parent = egress; } // Now that we know all our foreign parents are egress nodes, we can add ingress nodes. // Note that by this time (due to the topological walk), we know that `ingresses` has been // sufficiently populated to contain any relevant existing ingress nodes. for parent in parents { // is there already an ingress node we can re-use? let mut ingress = ingresses.get(&domain).and_then(|ingresses| ingresses.get(&parent)).map(|ni| *ni); if ingress.is_none() { // nope -- create our new ingress node let mut i = graph[parent].mirror(node::Type::Ingress); i.add_to(domain); // it belongs to this domain, not that of the parent let i = graph.add_node(i); graph.add_edge(parent, i, false); // we also now need to deal with this ingress node new.insert(i); if parent == source { trace!(log, "adding source ingress"; "base" => node.index(), "ingress" => i.index()); // we don't re-use source ingress nodes } else { trace!(log, "adding cross-domain ingress"; "to" => node.index(), "from" => parent.index(), "ingress" => i.index()); ingresses.entry(domain).or_insert_with(HashMap::new).insert(parent, i); } ingress = Some(i); } else { trace!(log, "re-using cross-domain ingress"; "to" => node.index(), "from" => parent.index(), "ingress" => ingress.unwrap().index()); } let ingress = ingress.unwrap(); // we need to hook the ingress node in between us and the parent let old = graph.find_edge(parent, node).unwrap(); let was_materialized = graph.remove_edge(old).unwrap(); graph.add_edge(ingress, node, was_materialized); // tracking swaps here is a bit tricky because we've already swapped the "true" parents // of `node` with the ids of the egress nodes. thus, we actually need to do swaps on // the values in `swaps`, not insert new entries (that, or we'd need to change the // resolution process to be recursive, which is painful and unnecessary). note that we // *also* need to special-case handing base nodes, because there there *won't* be a // parent egress swap if parent!= source { for (_, to) in swaps.get_mut(&domain).unwrap().iter_mut() { if *to == parent { *to = ingress; } } } } } swaps } pub fn
(log: &Logger, graph: &mut Graph, main_txs: &HashMap<domain::Index, mpsc::SyncSender<Packet>>, new: &HashSet<NodeIndex>) { // ensure all egress nodes contain the tx channel of the domains of their child ingress nodes for &node in new { let n = &graph[node]; if let node::Type::Ingress = **n { // check the egress connected to this ingress } else { continue; } for egress in graph.neighbors_directed(node, petgraph::EdgeDirection::Incoming) { match *graph[egress] { node::Type::Egress { ref txs,.. } => { trace!(log, "connecting"; "egress" => egress.index(), "ingress" => node.index()); txs.lock() .unwrap() .push((node.into(), n.addr(), main_txs[&n.domain()].clone())); continue; } node::Type::Source => continue, _ => unreachable!("ingress parent is not egress"), } } } }
connect
identifier_name
routing.rs
//! Functions for adding ingress/egress nodes. //! //! In particular: //! //! - New nodes that are children of nodes in a different domain must be preceeded by an ingress //! - Egress nodes must be added to nodes that now have children in a different domain //! - Egress nodes that gain new children must gain channels to facilitate forwarding //! - Timestamp ingress nodes for existing domains must be connected to new base nodes //! - Timestamp ingress nodes must be added to all new domains use flow::prelude::*; use flow::domain; use flow::node; use petgraph; use petgraph::graph::NodeIndex; use std::collections::{HashSet, HashMap}; use std::sync::mpsc; use slog::Logger; /// Add in ingress and egress nodes as appropriate in the graph to facilitate cross-domain /// communication. pub fn add(log: &Logger, graph: &mut Graph, source: NodeIndex, new: &mut HashSet<NodeIndex>) -> HashMap<domain::Index, HashMap<NodeIndex, NodeIndex>> { // find all new nodes in topological order. we collect first since we'll be mutating the graph // below. it's convenient to have the nodes in topological order, because we then know that // we'll first add egress nodes, and then the related ingress nodes. if we're ever required to // add an ingress node, and its parent isn't an egress node, we know that we're seeing a // connection between an old node in one domain, and a new node in a different domain. let mut topo_list = Vec::with_capacity(new.len()); let mut topo = petgraph::visit::Topo::new(&*graph); while let Some(node) = topo.next(&*graph) { if node == source { continue; } if!new.contains(&node) { continue; } topo_list.push(node); } // we need to keep track of all the times we change the parent of a node (by replacing it with // an egress, and then with an ingress), since this remapping must be communicated to the nodes // so they know the true identifier of their parent in the graph. let mut swaps = HashMap::new(); // we also need to keep track of the ingress nodes we've added to each domain so that we don't // end up with two ingress nodes for a given egress node. that would cause unnecessary // cross-domain communication. this is domain => source => NodeIndex (of ingress). note that // `source` here is actually the *egress* node. this is because by the time we add ingress // nodes, we know our incoming edges have already been updated to point to the egress nodes. let mut ingresses = HashMap::new(); for node in topo_list { let domain = graph[node].domain(); // First, we add egress nodes for any of our cross-domain children let children: Vec<_> = graph.neighbors_directed(node, petgraph::EdgeDirection::Outgoing) .collect(); // collect so we can mutate graph // We then need to make sure that we're acting on up-to-date information about existing // egress/ingress pairs. In particular, we want to know about egresses this node already // has (and to which domains). In the process we also populate the information about // ingress nodes in other domains that point here (those shouldn't be re-created if new // nodes are created in the corresponding domains). let mut egresses = HashMap::new(); for child in &children { if!new.contains(child) { continue; } if let node::Type::Egress {.. } = *graph[*child] { for ingress in graph.neighbors_directed(*child, petgraph::EdgeDirection::Outgoing) { // this egress already contains this node to the ingress' domain egresses.insert(graph[ingress].domain(), *child); // also keep track of the corresponding ingress node so we can re-use it ingresses.entry(graph[ingress].domain()) .or_insert_with(HashMap::new) .insert(node, ingress); } } } for child in children { let cdomain = graph[child].domain(); if domain!= cdomain { // child is in a different domain if!egresses.contains_key(&cdomain) { // create an egress node to handle that // NOTE: technically, this doesn't need to mirror its parent, but meh let proxy = graph[node].mirror(node::Type::Egress { tags: Default::default(), txs: Default::default(), }); let egress = graph.add_node(proxy); graph.add_edge(node, egress, false); new.insert(egress); egresses.insert(cdomain, egress); trace!(log, "adding cross-domain egress to new node"; "node" => node.index(), "egress" => egress.index()); } else { trace!(log, "re-using cross-domain egress to new node"; "node" => node.index(), "egress" => egresses[&cdomain].index()); } // we need to hook that node in between us and this child let egress = egresses[&cdomain]; let old = graph.find_edge(node, child).unwrap(); let was_materialized = graph.remove_edge(old).unwrap(); graph.add_edge(egress, child, was_materialized); // this ends up being re-executed, but that's okay swaps.entry(cdomain).or_insert_with(HashMap::new).insert(node, egress); } } // Then, we look for any parents in the graph that // // a) are in a different domain, and // b) aren't egress nodes // // This situation arises whenever a cross-domain edge is added as the result of a // migration. We need to find or make an egress domain in that other domain, and hook that // up as the parent of this node instead of the original internal foreign domain node. // // Note that same-domain parents are never interesting to us for this purpose. let mut parents: Vec<_> = graph.neighbors_directed(node, petgraph::EdgeDirection::Incoming) .filter(|&ni| ni == source || graph[ni].domain()!= domain) .collect(); // collect so we can mutate graph for parent in &mut parents { if *parent == source { // no egress needed continue; } // since we are traversing in topological order, egress nodes should have been added to // all our parents, and our incoming edges should have been updated. if that *isn't* // the case for a given parent, it must be a pre-existing parent. if let node::Type::Egress {.. } = *graph[*parent] { continue; } // let's first see if this parent already has an egress we can use let egress = graph.neighbors_directed(*parent, petgraph::EdgeDirection::Outgoing) .find(|&ni| graph[ni].is_egress()); let egress = egress.unwrap_or_else(|| { // no, okay, so we need to add an egress for that other node, let proxy = graph[*parent].mirror(node::Type::Egress{ txs: Default::default(), tags: Default::default() }); let egress = graph.add_node(proxy); trace!(log, "adding cross-domain egress to existing node"; "node" => parent.index(), "egress" => egress.index()); graph.add_edge(*parent, egress, false); new.insert(egress); egress }); // now, let's use that egress as our parent instead let old = graph.find_edge(*parent, node).unwrap(); let was_materialized = graph.remove_edge(old).unwrap(); graph.add_edge(egress, node, was_materialized); // all references to our original parent should now refer to the egress swaps.entry(domain).or_insert_with(HashMap::new).insert(*parent, egress); // and we should now just consider the egress our parent instead *parent = egress; } // Now that we know all our foreign parents are egress nodes, we can add ingress nodes. // Note that by this time (due to the topological walk), we know that `ingresses` has been // sufficiently populated to contain any relevant existing ingress nodes. for parent in parents { // is there already an ingress node we can re-use? let mut ingress = ingresses.get(&domain).and_then(|ingresses| ingresses.get(&parent)).map(|ni| *ni); if ingress.is_none() { // nope -- create our new ingress node let mut i = graph[parent].mirror(node::Type::Ingress); i.add_to(domain); // it belongs to this domain, not that of the parent let i = graph.add_node(i); graph.add_edge(parent, i, false); // we also now need to deal with this ingress node new.insert(i); if parent == source { trace!(log, "adding source ingress"; "base" => node.index(), "ingress" => i.index()); // we don't re-use source ingress nodes } else { trace!(log, "adding cross-domain ingress"; "to" => node.index(), "from" => parent.index(), "ingress" => i.index()); ingresses.entry(domain).or_insert_with(HashMap::new).insert(parent, i); } ingress = Some(i); } else { trace!(log, "re-using cross-domain ingress"; "to" => node.index(), "from" => parent.index(), "ingress" => ingress.unwrap().index()); } let ingress = ingress.unwrap(); // we need to hook the ingress node in between us and the parent let old = graph.find_edge(parent, node).unwrap();
// of `node` with the ids of the egress nodes. thus, we actually need to do swaps on // the values in `swaps`, not insert new entries (that, or we'd need to change the // resolution process to be recursive, which is painful and unnecessary). note that we // *also* need to special-case handing base nodes, because there there *won't* be a // parent egress swap if parent!= source { for (_, to) in swaps.get_mut(&domain).unwrap().iter_mut() { if *to == parent { *to = ingress; } } } } } swaps } pub fn connect(log: &Logger, graph: &mut Graph, main_txs: &HashMap<domain::Index, mpsc::SyncSender<Packet>>, new: &HashSet<NodeIndex>) { // ensure all egress nodes contain the tx channel of the domains of their child ingress nodes for &node in new { let n = &graph[node]; if let node::Type::Ingress = **n { // check the egress connected to this ingress } else { continue; } for egress in graph.neighbors_directed(node, petgraph::EdgeDirection::Incoming) { match *graph[egress] { node::Type::Egress { ref txs,.. } => { trace!(log, "connecting"; "egress" => egress.index(), "ingress" => node.index()); txs.lock() .unwrap() .push((node.into(), n.addr(), main_txs[&n.domain()].clone())); continue; } node::Type::Source => continue, _ => unreachable!("ingress parent is not egress"), } } } }
let was_materialized = graph.remove_edge(old).unwrap(); graph.add_edge(ingress, node, was_materialized); // tracking swaps here is a bit tricky because we've already swapped the "true" parents
random_line_split
main.rs
.danger_accept_invalid_certs(true) .build() .unwrap() .get("https://www.google.de/") .send() .unwrap() .text() .unwrap();*/ println!("body = {}", body.lines().take(3).collect::<String>()); /*let re_weburl = Regex::new( r"/^(?:(?:(?:https?|ftp):)?\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u00a1-\uffff][a-z0-9\u00a1-\uffff_-]{0,62})?[a-z0-9\u00a1-\uffff]\.)+(?:[a-z\u00a1-\uffff]{2,}\.?))(?::\d{2,5})?(?:[/?#]\S*)?$/i" );*/ // check if there is an alternative to the ogg-vorbis stream // when true, then prioritize the mp3 over it // else create a reference to the mp3 forwarding endpoint // SSL Certificates on the host are important. make shure: // ENV SSL_CERT_FILE=/etc/ssl/certs/ca-certificates.crt // ENV SSL_CERT_DIR=/etc/ssl/certs // are set. let after = reformat_dates(&body); //println!("body = {}", after); //let chunk = Chunk::from(after); //*response.body_mut() = Body::from(after.to_string()); *response.body_mut() = Body::from(after.to_string()); //*response.body_mut() = Body::from("got regex"); return Box::new(future::ok(response)); } } _ => {} } match (req.method(), req.uri().path()) { // Serve some instructions at / (&Method::GET, "/") => { //command_name = 'ffmpeg', //command_opts = ['-i', 'pipe:0', '-f','mp3', '-acodec', 'libvorbis', '-ab', '128k', '-aq', '60', '-f', 'ogg', '-']; /* let command_name = "ffmpeg"; //let command_opts = ["-i", "pipe:0", "-f", "mp3", "-acodec", "libvorbis", "-ab", "128k", "-aq", "60", "-f", "ogg", "-"]; //"D:\Program Files\ffmpeg\bin\ffmpeg" -re -i "https://cdn.netzpolitik.org/wp-upload/2019/02/NPP169-Worum-geht-es-eigentlich-bei-der-ePrivacy-Reform.ogg" // -acodec libmp3lame -ab 128k -aq 60 -f mp3 - > bla.mp3 //let media_addr = "https://cdn.netzpolitik.org/wp-upload/2019/02/NPP169-Worum-geht-es-eigentlich-bei-der-ePrivacy-Reform.ogg"; let media_addr = "https://upload.wikimedia.org/wikipedia/commons/f/f2/Median_test.ogg"; let command_opts = ["-i", media_addr, "-acodec", "libmp3lame", "-ab", "128k", "-aq", "60", "-f", "mp3", "-"]; let mut ffmpeg_path = command_name; if cfg!(target_os = "windows") { ffmpeg_path = "D:/Program Files/ffmpeg/bin/ffmpeg.exe"; } // Spawn the `wc` command let process = match Command::new(ffmpeg_path) .args(&command_opts) .stdin(Stdio::piped()) .stdout(Stdio::piped()) .spawn() { Err(why) => panic!("couldn't spawn {}: {}", command_name, why.description()), Ok(process) => process, }; // The `stdout` field also has type `Option<ChildStdout>` so must be unwrapped. let mut buffer: Vec<u8> = Vec::new(); match process.stdout.unwrap().read_to_end(&mut buffer) { Err(why) => panic!("couldn't read {} stdout: {}", command_name, why.description()), Ok(_) => println!("buffer size:[{}]", buffer.len()), } *response.body_mut() = Body::from(buffer); return Box::new( future::ok(response)); */ /*let mapping = || -> Vec(u8) { }*/ //let chunks = vec!["hello", " ", "world"]; //let stream = futures::stream::iter_ok::<_, ::std::io::Error>(chunks); /*let mapping = req .into_body() .map(|chunk| { chunk.iter() .map(|byte| byte.to_ascii_uppercase()) .collect::<Vec<u8>>() });*/ let mapping1 = req.into_body().map(|chunk| { chunk .iter() .map(|byte| { println!("chunk {}", byte.to_ascii_uppercase()); byte.to_ascii_uppercase() }) .collect::<Vec<u8>>() }); let data_fuck = vec!["FUCK", " ", "YOU!"]; let chunk_fuck = Chunk::from("fuck"); let stream_fuck = futures::stream::iter_ok::<_, ::std::io::Error>(data_fuck); /* //let data2 = vec!["hello", " ", "world"]; let data2: Vec<u8> = vec![0x55, 0x20, 0x66]; //let chunk2 = Chunk::from(data2); //let conv = |x: Vec<u8>| x.iter(); let stream2 = futures::stream::iter_ok::<_, ::std::io::Error>(data2); //let stream2 = futures::stream::iter_ok::<_, ::std::io::Error>(data2); let chunks = fileio::load_local_mp3_buffer(); let c: &[u8] = &chunks; // c: &[u8] //let chunk = Chunk::from(c); let stream = futures::stream::iter_ok::<_, ::std::io::Error>(c); *response.body_mut() = Body::from(chunks); return Box::new( future::ok(response)); */ // type BoxFut = Box<Future<Item = Response<Body>, Error = hyper::Error> + Send>; //let bbb = Box::new(future::ok(Response::new("Fuck YOU"))); //let xxx: BoxFut = Box::new(future::ok(response)); //xxx let my_stream = MyStream::new(5); //let xstream = futures::stream::iter_ok::<_, ::std::io::Error>(my_stream.iter()); //let mut file = &get_local_mp3_path(); let mut filepath = "/media/hdd/jedzia/rust/p.mp3"; if cfg!(target_os = "windows") { filepath = "p.mp3"; } //let file = File::open(filepath).map(file_response).or_else(|_| status_response(StatusCode::NOT_FOUND)); //.expect("failed to open file") //let file = tokio::fs::File::open(filepath).catch_unwind(); //let fstream = FramedRead::new(file, ChunkDecoder); /*fn decode(buf: Vec<u8>) -> Result<Option<Chunk>, io::Error> { let len = buf.len(); if len > 0 { //Ok(Some(buf.iter().take(32).freeze().into())) Ok(Some(buf.iter().take(32).into())) } else { Ok(None) } } let akjsd = decode(chunks);*/ use bytes::{BigEndian, Buf, BufMut, BytesMut, IntoBuf}; let bytes = b"\x00\x01hello world"; let mut bytes_buf = bytes.into_buf(); let bytes_stream = futures::stream::iter_ok::<_, ::std::io::Error>(bytes); //*response.body_mut() = Body::wrap_stream(bytes_stream); *response.body_mut() = Body::wrap_stream(stream_fuck); //*response.body_mut() = Body::empty(); //*response.set_body(Box::new(stream)); // type BoxFut = Box<Future<Item = Response<Body>, Error = hyper::Error> + Send>; //let future_result = future::ok(response); // let mut buf = BytesMut::with_capacity(1024); // buf.put(&b"hello world"[..]); //let mut response1 = Response::new("Fuck"); // let mut response1 = Response::new(Body::from(buf.freeze())); // let future_result: FutureResult<Response<Body>, hyper::Error> = future::ok(response1); //return Box::new( future_result); //let (method, uri, version, headers, body) = req.deconstruct(); let myresp = chunk::handle_request(Request::new(Body::from("Fuck ya to chunk::handle_request"))); return Box::new(myresp); //let future_result: FutureResult<Response<Body>, hyper::Error> = future::ok(response); //return Box::new(future_result); } // Simply echo the body back to the client. (&Method::POST, "/echo") => { *response.body_mut() = req.into_body(); } //(&Method::GET, Some("/fwd/")) => { // *response.body_mut() = Body::from("Jahahahahaha"); //} // Convert to uppercase before sending back to client. (&Method::POST, "/echo/uppercase") => { let mapping = req.into_body().map(|chunk| { chunk .iter() .map(|byte| byte.to_ascii_uppercase()) .collect::<Vec<u8>>() }); *response.body_mut() = Body::wrap_stream(mapping); } // Reverse the entire body before sending back to the client. // // Since we don't know the end yet, we can't simply stream // the chunks as they arrive. So, this returns a different // future, waiting on concatenating the full body, so that // it can be reversed. Only then can we return a `Response`. (&Method::POST, "/echo/reversed") => { let reversed = req.into_body().concat2().map(move |chunk| { let body = chunk.iter().rev().cloned().collect::<Vec<u8>>(); *response.body_mut() = Body::from(body); response }); return Box::new(reversed); } // The 404 Not Found route... _ => { println!("404 not found."); *response.status_mut() = StatusCode::NOT_FOUND; } }; Box::new(future::ok(response)) } /*struct ChunkDecoder; impl Decoder for ChunkDecoder { type Item = Chunk; type Error = io::Error; fn decode(&mut self, buf: &mut bytes::BytesMut) -> Result<Option<Chunk>, io::Error> { let len = buf.len(); if len > 0 { Ok(Some(buf.take().freeze().into())) } else { Ok(None) } } }*/ struct MyStream { current: u32, max: u32, } impl MyStream { pub fn new(max: u32) -> MyStream { MyStream { current: 0, max: max, } } } impl Stream for MyStream { type Item = u32; type Error = Box<Error>; fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> { match self.current { ref mut x if *x < self.max => { *x = *x + 1; Ok(Async::Ready(Some(*x))) } _ => Ok(Async::Ready(None)), } } } /*fn get_local_mp3_path() -> &str { //let mut f = File::open("./p.mp3").expect("failed to open mp3 file!"); let mut filepath = "/media/hdd/jedzia/rust/p.mp3"; if cfg!(target_os = "windows") { filepath = "p.mp3"; } filepath }*/ fn main() -> Result<(), Box<dyn Error>> { println!("Hello, lovely VU Duo!"); let y: f32 = 5.0; if y < 4.0 { // https://stackoverflow.com/questions/51550167/how-to-manually-return-a-result-boxerror return Err("Bad request".into()); } // http://192.168.2.43:3000/ //let addr = ([0, 0, 0, 0], 3000).into(); //let addr = ([127, 0, 0, 1], 3000).into(); //let addr = ([192, 168, 2, 43], 3000).into(); pretty_env_logger::init(); //fun_with_ssl(); //return Ok(()); /* // helps when certificates are not found extern crate openssl_probe; let ssl = openssl_probe::init_ssl_cert_env_vars(); */ //let mut buffer = String::new(); //f.read_to_string(&mut buffer)?; //let in_addr: SocketAddr = ([127, 0, 0, 1], 3333).into(); let in_addr = get_in_addr(); /*let out_addr: SocketAddr = ([127, 0, 0, 1], 3000).into(); // google.de 216.58.208.35 //let out_addr: SocketAddr = ([216, 58, 208, 35], 443).into(); let client_main = Client::new(); let out_addr_clone = out_addr.clone(); // new_service is run for each connection, creating a'service' // to handle requests for that specific connection. let new_service = move || { let client = client_main.clone(); // This is the `Service` that will handle the connection. // `service_fn_ok` is a helper to convert a function that // returns a Response into a `Service`. service_fn(move |mut req| { let uri_string = format!( "http://{}/{}", out_addr_clone, req.uri().path_and_query().map(|x| x.as_str()).unwrap_or("") ); let uri = uri_string.parse().unwrap(); let in_uri_string = format!("http://{}/{}", in_addr, req.uri()); let in_remove_string = format!("http://{}//", in_addr); println!("req.uri(): {}", in_uri_string); let result = in_uri_string.replace(&in_remove_string, ""); //let result = in_uri_string.split(in_remove_string.unwrap_or("")).take(1).next().unwrap_or(""); println!("result: {}", result); *req.uri_mut() = uri; client.request(req) }) }; let server = Server::bind(&in_addr) .serve(new_service) .map_err(|e| eprintln!("server error: {}", e)); println!("Listening on http://{}", in_addr); println!("Proxying on http://{}", out_addr); rt::run(server);*/ //let mut f = File::open("p.mp3")?; //let mut buffer: Vec<u8> = Vec::new(); //f.read_to_end(&mut buffer)?; //let b = buffer.clone(); let server = Server::bind(&in_addr) //.serve(|| service_fn(|req| echo(req, Vec::new()))) .serve(|| service_fn(echo)) .map_err(|e| eprintln!("server error: {}", e)); println!("Listening on http://{}", in_addr); hyper::rt::run(server); println!("finished."); Ok(()) } /*//#cfg!(target_os = "windows") fn testOpenSSL1() { extern crate openssl; use openssl::rsa::{Padding, Rsa}; let rsa = Rsa::generate(2048).unwrap(); let data = b"foobar"; println!("data {:?}", data); let mut buf = vec![0; rsa.size() as usize]; let encrypted_len = rsa.public_encrypt(data, &mut buf, Padding::PKCS1).unwrap(); println!("encripted {:?}", buf); }*/ fn testOpenSSL()
{ /* extern crate openssl; println!("===== testOpenSSL ====="); use openssl::ssl::{SslConnector, SslMethod}; use std::io::{Read, Write}; use std::net::TcpStream; let connector = SslConnector::builder(SslMethod::tls()).unwrap().build(); let stream = TcpStream::connect("google.com:443").unwrap(); let mut stream = connector.connect("google.com", stream).unwrap(); stream.write_all(b"GET / HTTP/1.0\r\n\r\n").unwrap(); let mut res = vec![]; stream.read_to_end(&mut res).unwrap(); println!( "{}", String::from_utf8_lossy(&res) .lines()
identifier_body
main.rs
(uri: &Uri) -> String { //let in_addr: SocketAddr = get_in_addr(); let uri_string = uri.path_and_query().map(|x| x.as_str()).unwrap_or(""); //let uri: String = uri_string.parse().unwrap(); //let in_uri_string = format!("http://{}/{}", in_addr, req.uri()); let in_remove_string = "/fwd/"; debug!("uri_string: {}", uri_string); let result = uri_string.replace(&in_remove_string, ""); debug!("result: {}", result); //let result = in_uri_string.split(in_remove_string.unwrap_or("")).take(1).next().unwrap_or(""); result } fn reformat_dates(before: &str) -> Cow<str> { lazy_static! { static ref ISO8601_DATE_REGEX : Regex = Regex::new( //r"(?P<y>\d{4})-(?P<m>\d{2})-(?P<d>\d{2})" //r"/^(?:(?:(?:https?|ftp):)?\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u00a1-\uffff][a-z0-9\u00a1-\uffff_-]{0,62})?[a-z0-9\u00a1-\uffff]\.)+(?:[a-z\u00a1-\uffff]{2,}\.?))(?::\d{2,5})?(?:[/?#]\S*)?$/i" //r"(?:(?:(?:https?|ftp):)?\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u00a1-\uffff][a-z0-9\u00a1-\uffff_-]{0,62})?[a-z0-9\u00a1-\uffff]\.)+(?:[a-z\u00a1-\uffff]{2,}\.?))(?::\d{2,5})?(?:[/?#]\S*)?$/i" r"(https?://(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)*.(\.ogg))" ).unwrap(); } ISO8601_DATE_REGEX.replace_all(before, "FUCK YA") } /// We need to return different futures depending on the route matched, /// and we can do that with an enum, such as `futures::Either`, or with /// trait objects. /// /// A boxed Future (trait object) is used as it is easier to understand /// and extend with more types. Advanced users could switch to `Either`. type BoxFut = Box<Future<Item = Response<Body>, Error = hyper::Error> + Send>; /// This is our service handler. It receives a Request, routes on its /// path, and returns a Future of a Response. //fn echo(req: Request<Body>, buf: Vec<u8>) -> BoxFut { fn echo(req: Request<Body>) -> BoxFut { let mut response = Response::new(Body::empty()); debug!("method: {}, uri: {}", req.method(), req.uri()); match req.method() { &Method::GET => { if req.uri().path().starts_with("/fwd/") { let req_uri = reduce_forwarded_uri(req.uri()); //let forwarded_uri = Uri::from_static(&req_uri); *response.body_mut() = Body::from("Lets forward: ".to_owned() + &req_uri); let body = reqwest::get(req_uri.as_str()) //.unwrap(); //.danger_disable_certs_verification() .expect(&format!("cannot get '{}'", &req_uri)) .text() //.unwrap(); .expect(&format!("cannot get text for '{}'", &req_uri)); /*let body = reqwest::Client::builder() .danger_accept_invalid_hostnames(true) .danger_accept_invalid_certs(true) .build() .unwrap() .get("https://www.google.de/") .send() .unwrap() .text() .unwrap();*/ println!("body = {}", body.lines().take(3).collect::<String>()); /*let re_weburl = Regex::new( r"/^(?:(?:(?:https?|ftp):)?\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u00a1-\uffff][a-z0-9\u00a1-\uffff_-]{0,62})?[a-z0-9\u00a1-\uffff]\.)+(?:[a-z\u00a1-\uffff]{2,}\.?))(?::\d{2,5})?(?:[/?#]\S*)?$/i" );*/ // check if there is an alternative to the ogg-vorbis stream // when true, then prioritize the mp3 over it // else create a reference to the mp3 forwarding endpoint // SSL Certificates on the host are important. make shure: // ENV SSL_CERT_FILE=/etc/ssl/certs/ca-certificates.crt // ENV SSL_CERT_DIR=/etc/ssl/certs // are set. let after = reformat_dates(&body); //println!("body = {}", after); //let chunk = Chunk::from(after); //*response.body_mut() = Body::from(after.to_string()); *response.body_mut() = Body::from(after.to_string()); //*response.body_mut() = Body::from("got regex"); return Box::new(future::ok(response)); } } _ => {} } match (req.method(), req.uri().path()) { // Serve some instructions at / (&Method::GET, "/") => { //command_name = 'ffmpeg', //command_opts = ['-i', 'pipe:0', '-f','mp3', '-acodec', 'libvorbis', '-ab', '128k', '-aq', '60', '-f', 'ogg', '-']; /* let command_name = "ffmpeg"; //let command_opts = ["-i", "pipe:0", "-f", "mp3", "-acodec", "libvorbis", "-ab", "128k", "-aq", "60", "-f", "ogg", "-"]; //"D:\Program Files\ffmpeg\bin\ffmpeg" -re -i "https://cdn.netzpolitik.org/wp-upload/2019/02/NPP169-Worum-geht-es-eigentlich-bei-der-ePrivacy-Reform.ogg" // -acodec libmp3lame -ab 128k -aq 60 -f mp3 - > bla.mp3 //let media_addr = "https://cdn.netzpolitik.org/wp-upload/2019/02/NPP169-Worum-geht-es-eigentlich-bei-der-ePrivacy-Reform.ogg"; let media_addr = "https://upload.wikimedia.org/wikipedia/commons/f/f2/Median_test.ogg"; let command_opts = ["-i", media_addr, "-acodec", "libmp3lame", "-ab", "128k", "-aq", "60", "-f", "mp3", "-"]; let mut ffmpeg_path = command_name; if cfg!(target_os = "windows") { ffmpeg_path = "D:/Program Files/ffmpeg/bin/ffmpeg.exe"; } // Spawn the `wc` command let process = match Command::new(ffmpeg_path) .args(&command_opts) .stdin(Stdio::piped()) .stdout(Stdio::piped()) .spawn() { Err(why) => panic!("couldn't spawn {}: {}", command_name, why.description()), Ok(process) => process, }; // The `stdout` field also has type `Option<ChildStdout>` so must be unwrapped. let mut buffer: Vec<u8> = Vec::new(); match process.stdout.unwrap().read_to_end(&mut buffer) { Err(why) => panic!("couldn't read {} stdout: {}", command_name, why.description()), Ok(_) => println!("buffer size:[{}]", buffer.len()), } *response.body_mut() = Body::from(buffer); return Box::new( future::ok(response)); */ /*let mapping = || -> Vec(u8) { }*/ //let chunks = vec!["hello", " ", "world"]; //let stream = futures::stream::iter_ok::<_, ::std::io::Error>(chunks); /*let mapping = req .into_body() .map(|chunk| { chunk.iter() .map(|byte| byte.to_ascii_uppercase()) .collect::<Vec<u8>>() });*/ let mapping1 = req.into_body().map(|chunk| { chunk .iter() .map(|byte| { println!("chunk {}", byte.to_ascii_uppercase()); byte.to_ascii_uppercase() }) .collect::<Vec<u8>>() }); let data_fuck = vec!["FUCK", " ", "YOU!"]; let chunk_fuck = Chunk::from("fuck"); let stream_fuck = futures::stream::iter_ok::<_, ::std::io::Error>(data_fuck); /* //let data2 = vec!["hello", " ", "world"]; let data2: Vec<u8> = vec![0x55, 0x20, 0x66]; //let chunk2 = Chunk::from(data2); //let conv = |x: Vec<u8>| x.iter(); let stream2 = futures::stream::iter_ok::<_, ::std::io::Error>(data2); //let stream2 = futures::stream::iter_ok::<_, ::std::io::Error>(data2); let chunks = fileio::load_local_mp3_buffer(); let c: &[u8] = &chunks; // c: &[u8] //let chunk = Chunk::from(c); let stream = futures::stream::iter_ok::<_, ::std::io::Error>(c); *response.body_mut() = Body::from(chunks); return Box::new( future::ok(response)); */ // type BoxFut = Box<Future<Item = Response<Body>, Error = hyper::Error> + Send>; //let bbb = Box::new(future::ok(Response::new("Fuck YOU"))); //let xxx: BoxFut = Box::new(future::ok(response)); //xxx let my_stream = MyStream::new(5); //let xstream = futures::stream::iter_ok::<_, ::std::io::Error>(my_stream.iter()); //let mut file = &get_local_mp3_path(); let mut filepath = "/media/hdd/jedzia/rust/p.mp3"; if cfg!(target_os = "windows") { filepath = "p.mp3"; } //let file = File::open(filepath).map(file_response).or_else(|_| status_response(StatusCode::NOT_FOUND)); //.expect("failed to open file") //let file = tokio::fs::File::open(filepath).catch_unwind(); //let fstream = FramedRead::new(file, ChunkDecoder); /*fn decode(buf: Vec<u8>) -> Result<Option<Chunk>, io::Error> { let len = buf.len(); if len > 0 { //Ok(Some(buf.iter().take(32).freeze().into())) Ok(Some(buf.iter().take(32).into())) } else { Ok(None) } } let akjsd = decode(chunks);*/ use bytes::{BigEndian, Buf, BufMut, BytesMut, IntoBuf}; let bytes = b"\x00\x01hello world"; let mut bytes_buf = bytes.into_buf(); let bytes_stream = futures::stream::iter_ok::<_, ::std::io::Error>(bytes); //*response.body_mut() = Body::wrap_stream(bytes_stream); *response.body_mut() = Body::wrap_stream(stream_fuck); //*response.body_mut() = Body::empty(); //*response.set_body(Box::new(stream)); // type BoxFut = Box<Future<Item = Response<Body>, Error = hyper::Error> + Send>; //let future_result = future::ok(response); // let mut buf = BytesMut::with_capacity(1024); // buf.put(&b"hello world"[..]); //let mut response1 = Response::new("Fuck"); // let mut response1 = Response::new(Body::from(buf.freeze())); // let future_result: FutureResult<Response<Body>, hyper::Error> = future::ok(response1); //return Box::new( future_result); //let (method, uri, version, headers, body) = req.deconstruct(); let myresp = chunk::handle_request(Request::new(Body::from("Fuck ya to chunk::handle_request"))); return Box::new(myresp); //let future_result: FutureResult<Response<Body>, hyper::Error> = future::ok(response); //return Box::new(future_result); } // Simply echo the body back to the client. (&Method::POST, "/echo") => { *response.body_mut() = req.into_body(); } //(&Method::GET, Some("/fwd/")) => { // *response.body_mut() = Body::from("Jahahahahaha"); //} // Convert to uppercase before sending back to client. (&Method::POST, "/echo/uppercase") => { let mapping = req.into_body().map(|chunk| { chunk .iter() .map(|byte| byte.to_ascii_uppercase()) .collect::<Vec<u8>>() }); *response.body_mut() = Body::wrap_stream(mapping); } // Reverse the entire body before sending back to the client. // // Since we don't know the end yet, we can't simply stream // the chunks as they arrive. So, this returns a different // future, waiting on concatenating the full body, so that // it can be reversed. Only then can we return a `Response`. (&Method::POST, "/echo/reversed") => { let reversed = req.into_body().concat2().map(move |chunk| { let body = chunk.iter().rev().cloned().collect::<Vec<u8>>(); *response.body_mut() = Body::from(body); response }); return Box::new(reversed); } // The 404 Not Found route... _ => { println!("404 not found."); *response.status_mut() = StatusCode::NOT_FOUND; } }; Box::new(future::ok(response)) } /*struct ChunkDecoder; impl Decoder for ChunkDecoder { type Item = Chunk; type Error = io::Error; fn decode(&mut self, buf: &mut bytes::BytesMut) -> Result<Option<Chunk>, io::Error> { let len = buf.len(); if len > 0 { Ok(Some(buf.take().freeze().into())) } else { Ok(None) } } }*/ struct MyStream { current: u32, max: u32, } impl MyStream { pub fn new(max: u32) -> MyStream { MyStream { current: 0, max: max, } } } impl Stream for MyStream { type Item = u32; type Error = Box<Error>; fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> { match self.current { ref mut x if *x < self.max => { *x = *x + 1; Ok(Async::Ready(Some(*x))) } _ => Ok(Async::Ready(None)), } } } /*fn get_local_mp3_path() -> &str { //let mut f = File::open("./p.mp3").expect("failed to open mp3 file!"); let mut filepath = "/media/hdd/jedzia/rust/p.mp3"; if cfg!(target_os = "windows") { filepath = "p.mp3"; } filepath }*/ fn main() -> Result<(), Box<dyn Error>> { println!("Hello, lovely VU Duo!"); let y: f32 = 5.0; if y < 4.0 { // https://stackoverflow.com/questions/51550167/how-
reduce_forwarded_uri
identifier_name
main.rs
u00a1-\uffff_-]{0,62})?[a-z0-9\u00a1-\uffff]\.)+(?:[a-z\u00a1-\uffff]{2,}\.?))(?::\d{2,5})?(?:[/?#]\S*)?$/i" //r"(?:(?:(?:https?|ftp):)?\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u00a1-\uffff][a-z0-9\u00a1-\uffff_-]{0,62})?[a-z0-9\u00a1-\uffff]\.)+(?:[a-z\u00a1-\uffff]{2,}\.?))(?::\d{2,5})?(?:[/?#]\S*)?$/i" r"(https?://(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)*.(\.ogg))" ).unwrap(); } ISO8601_DATE_REGEX.replace_all(before, "FUCK YA") } /// We need to return different futures depending on the route matched, /// and we can do that with an enum, such as `futures::Either`, or with /// trait objects. /// /// A boxed Future (trait object) is used as it is easier to understand /// and extend with more types. Advanced users could switch to `Either`. type BoxFut = Box<Future<Item = Response<Body>, Error = hyper::Error> + Send>; /// This is our service handler. It receives a Request, routes on its /// path, and returns a Future of a Response. //fn echo(req: Request<Body>, buf: Vec<u8>) -> BoxFut { fn echo(req: Request<Body>) -> BoxFut { let mut response = Response::new(Body::empty()); debug!("method: {}, uri: {}", req.method(), req.uri()); match req.method() { &Method::GET => { if req.uri().path().starts_with("/fwd/") { let req_uri = reduce_forwarded_uri(req.uri()); //let forwarded_uri = Uri::from_static(&req_uri); *response.body_mut() = Body::from("Lets forward: ".to_owned() + &req_uri); let body = reqwest::get(req_uri.as_str()) //.unwrap(); //.danger_disable_certs_verification() .expect(&format!("cannot get '{}'", &req_uri)) .text() //.unwrap(); .expect(&format!("cannot get text for '{}'", &req_uri)); /*let body = reqwest::Client::builder() .danger_accept_invalid_hostnames(true) .danger_accept_invalid_certs(true) .build() .unwrap() .get("https://www.google.de/") .send() .unwrap() .text() .unwrap();*/ println!("body = {}", body.lines().take(3).collect::<String>()); /*let re_weburl = Regex::new( r"/^(?:(?:(?:https?|ftp):)?\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u00a1-\uffff][a-z0-9\u00a1-\uffff_-]{0,62})?[a-z0-9\u00a1-\uffff]\.)+(?:[a-z\u00a1-\uffff]{2,}\.?))(?::\d{2,5})?(?:[/?#]\S*)?$/i" );*/ // check if there is an alternative to the ogg-vorbis stream // when true, then prioritize the mp3 over it // else create a reference to the mp3 forwarding endpoint // SSL Certificates on the host are important. make shure: // ENV SSL_CERT_FILE=/etc/ssl/certs/ca-certificates.crt // ENV SSL_CERT_DIR=/etc/ssl/certs // are set. let after = reformat_dates(&body); //println!("body = {}", after); //let chunk = Chunk::from(after); //*response.body_mut() = Body::from(after.to_string()); *response.body_mut() = Body::from(after.to_string()); //*response.body_mut() = Body::from("got regex"); return Box::new(future::ok(response)); } } _ => {} } match (req.method(), req.uri().path()) { // Serve some instructions at / (&Method::GET, "/") => { //command_name = 'ffmpeg', //command_opts = ['-i', 'pipe:0', '-f','mp3', '-acodec', 'libvorbis', '-ab', '128k', '-aq', '60', '-f', 'ogg', '-']; /* let command_name = "ffmpeg"; //let command_opts = ["-i", "pipe:0", "-f", "mp3", "-acodec", "libvorbis", "-ab", "128k", "-aq", "60", "-f", "ogg", "-"]; //"D:\Program Files\ffmpeg\bin\ffmpeg" -re -i "https://cdn.netzpolitik.org/wp-upload/2019/02/NPP169-Worum-geht-es-eigentlich-bei-der-ePrivacy-Reform.ogg" // -acodec libmp3lame -ab 128k -aq 60 -f mp3 - > bla.mp3 //let media_addr = "https://cdn.netzpolitik.org/wp-upload/2019/02/NPP169-Worum-geht-es-eigentlich-bei-der-ePrivacy-Reform.ogg"; let media_addr = "https://upload.wikimedia.org/wikipedia/commons/f/f2/Median_test.ogg"; let command_opts = ["-i", media_addr, "-acodec", "libmp3lame", "-ab", "128k", "-aq", "60", "-f", "mp3", "-"]; let mut ffmpeg_path = command_name; if cfg!(target_os = "windows") { ffmpeg_path = "D:/Program Files/ffmpeg/bin/ffmpeg.exe"; } // Spawn the `wc` command let process = match Command::new(ffmpeg_path) .args(&command_opts) .stdin(Stdio::piped()) .stdout(Stdio::piped()) .spawn() { Err(why) => panic!("couldn't spawn {}: {}", command_name, why.description()), Ok(process) => process, }; // The `stdout` field also has type `Option<ChildStdout>` so must be unwrapped. let mut buffer: Vec<u8> = Vec::new(); match process.stdout.unwrap().read_to_end(&mut buffer) { Err(why) => panic!("couldn't read {} stdout: {}", command_name, why.description()), Ok(_) => println!("buffer size:[{}]", buffer.len()), } *response.body_mut() = Body::from(buffer); return Box::new( future::ok(response)); */ /*let mapping = || -> Vec(u8) { }*/ //let chunks = vec!["hello", " ", "world"]; //let stream = futures::stream::iter_ok::<_, ::std::io::Error>(chunks); /*let mapping = req .into_body() .map(|chunk| { chunk.iter() .map(|byte| byte.to_ascii_uppercase()) .collect::<Vec<u8>>() });*/ let mapping1 = req.into_body().map(|chunk| { chunk .iter() .map(|byte| { println!("chunk {}", byte.to_ascii_uppercase()); byte.to_ascii_uppercase() }) .collect::<Vec<u8>>() }); let data_fuck = vec!["FUCK", " ", "YOU!"]; let chunk_fuck = Chunk::from("fuck"); let stream_fuck = futures::stream::iter_ok::<_, ::std::io::Error>(data_fuck); /* //let data2 = vec!["hello", " ", "world"]; let data2: Vec<u8> = vec![0x55, 0x20, 0x66]; //let chunk2 = Chunk::from(data2); //let conv = |x: Vec<u8>| x.iter(); let stream2 = futures::stream::iter_ok::<_, ::std::io::Error>(data2); //let stream2 = futures::stream::iter_ok::<_, ::std::io::Error>(data2); let chunks = fileio::load_local_mp3_buffer(); let c: &[u8] = &chunks; // c: &[u8] //let chunk = Chunk::from(c); let stream = futures::stream::iter_ok::<_, ::std::io::Error>(c); *response.body_mut() = Body::from(chunks); return Box::new( future::ok(response)); */ // type BoxFut = Box<Future<Item = Response<Body>, Error = hyper::Error> + Send>; //let bbb = Box::new(future::ok(Response::new("Fuck YOU"))); //let xxx: BoxFut = Box::new(future::ok(response)); //xxx let my_stream = MyStream::new(5); //let xstream = futures::stream::iter_ok::<_, ::std::io::Error>(my_stream.iter()); //let mut file = &get_local_mp3_path(); let mut filepath = "/media/hdd/jedzia/rust/p.mp3"; if cfg!(target_os = "windows") { filepath = "p.mp3"; } //let file = File::open(filepath).map(file_response).or_else(|_| status_response(StatusCode::NOT_FOUND)); //.expect("failed to open file") //let file = tokio::fs::File::open(filepath).catch_unwind(); //let fstream = FramedRead::new(file, ChunkDecoder); /*fn decode(buf: Vec<u8>) -> Result<Option<Chunk>, io::Error> { let len = buf.len();
if len > 0 { //Ok(Some(buf.iter().take(32).freeze().into())) Ok(Some(buf.iter().take(32).into())) } else { Ok(None) } } let akjsd = decode(chunks);*/ use bytes::{BigEndian, Buf, BufMut, BytesMut, IntoBuf}; let bytes = b"\x00\x01hello world"; let mut bytes_buf = bytes.into_buf(); let bytes_stream = futures::stream::iter_ok::<_, ::std::io::Error>(bytes); //*response.body_mut() = Body::wrap_stream(bytes_stream); *response.body_mut() = Body::wrap_stream(stream_fuck); //*response.body_mut() = Body::empty(); //*response.set_body(Box::new(stream)); // type BoxFut = Box<Future<Item = Response<Body>, Error = hyper::Error> + Send>; //let future_result = future::ok(response); // let mut buf = BytesMut::with_capacity(1024); // buf.put(&b"hello world"[..]); //let mut response1 = Response::new("Fuck"); // let mut response1 = Response::new(Body::from(buf.freeze())); // let future_result: FutureResult<Response<Body>, hyper::Error> = future::ok(response1); //return Box::new( future_result); //let (method, uri, version, headers, body) = req.deconstruct(); let myresp = chunk::handle_request(Request::new(Body::from("Fuck ya to chunk::handle_request"))); return Box::new(myresp); //let future_result: FutureResult<Response<Body>, hyper::Error> = future::ok(response); //return Box::new(future_result); } // Simply echo the body back to the client. (&Method::POST, "/echo") => { *response.body_mut() = req.into_body(); } //(&Method::GET, Some("/fwd/")) => { // *response.body_mut() = Body::from("Jahahahahaha"); //} // Convert to uppercase before sending back to client. (&Method::POST, "/echo/uppercase") => { let mapping = req.into_body().map(|chunk| { chunk .iter() .map(|byte| byte.to_ascii_uppercase()) .collect::<Vec<u8>>() }); *response.body_mut() = Body::wrap_stream(mapping); } // Reverse the entire body before sending back to the client. // // Since we don't know the end yet, we can't simply stream // the chunks as they arrive. So, this returns a different // future, waiting on concatenating the full body, so that // it can be reversed. Only then can we return a `Response`. (&Method::POST, "/echo/reversed") => { let reversed = req.into_body().concat2().map(move |chunk| { let body = chunk.iter().rev().cloned().collect::<Vec<u8>>(); *response.body_mut() = Body::from(body); response }); return Box::new(reversed); } // The 404 Not Found route... _ => { println!("404 not found."); *response.status_mut() = StatusCode::NOT_FOUND; } }; Box::new(future::ok(response)) } /*struct ChunkDecoder; impl Decoder for ChunkDecoder { type Item = Chunk; type Error = io::Error; fn decode(&mut self, buf: &mut bytes::BytesMut) -> Result<Option<Chunk>, io::Error> { let len = buf.len(); if len > 0 { Ok(Some(buf.take().freeze().into())) } else { Ok(None) } } }*/ struct MyStream { current: u32, max: u32, } impl MyStream { pub fn new(max: u32) -> MyStream { MyStream { current: 0, max: max, } } } impl Stream for MyStream { type Item = u32; type Error = Box<Error>; fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> { match self.current { ref mut x if *x < self.max => { *x = *x + 1; Ok(Async::Ready(Some(*x))) } _ => Ok(Async::Ready(None)), } } } /*fn get_local_mp3_path() -> &str { //let mut f = File::open("./p.mp3").expect("failed to open mp3 file!"); let mut filepath = "/media/hdd/jedzia/rust/p.mp3"; if cfg!(target_os = "windows") { filepath = "p.mp3"; } filepath }*/ fn main() -> Result<(), Box<dyn Error>> { println!("Hello, lovely VU Duo!"); let y: f32 = 5.0; if y < 4.0 { // https://stackoverflow.com/questions/51550167/how-to-manually-return-a-result-boxerror return Err("Bad request".into()); } // http://192.168.2.43:3000/ //let addr = ([0, 0, 0, 0], 3000).into(); //let addr = ([127, 0, 0, 1], 3000).into(); //let addr = ([192, 168, 2, 43], 3000).into(); pretty_env_logger::init(); //fun_with_ssl(); //return Ok(()); /* // helps when certificates are not found extern crate openssl_probe; let ssl = openssl_probe::init_ssl_cert_env_vars(); */ //let mut buffer = String::new(); //f.read_to_string(&mut buffer)?; //let in_addr: SocketAddr = ([127, 0, 0, 1], 3333).into(); let in_addr = get_in_addr(); /*let out_addr: SocketAddr = ([127, 0, 0, 1], 3000).into(); // google.de 216.58.208.35 //let out_addr: SocketAddr = ([216, 58, 208, 35], 443).into(); let client_main = Client::new(); let out_addr_clone = out_addr.clone(); // new_service is run for each connection, creating a'service' // to handle requests for that specific connection. let new_service = move || { let client = client_main.clone(); // This is the `Service` that will handle the connection. // `service_fn_ok` is a helper to convert a function that // returns a Response into a `Service`. service_fn(move |mut req| { let uri_string = format
random_line_split
mod.rs
memory::ByteValued; use crate::abi::linux_abi as fuse; use crate::api::filesystem::Entry; use crate::api::{BackendFileSystem, VFS_MAX_INO}; #[cfg(feature = "async-io")] mod async_io; mod sync_io; mod multikey; use multikey::MultikeyBTreeMap; use crate::async_util::AsyncDrive; const CURRENT_DIR_CSTR: &[u8] = b".\0"; const PARENT_DIR_CSTR: &[u8] = b"..\0"; const EMPTY_CSTR: &[u8] = b"\0"; const PROC_CSTR: &[u8] = b"/proc\0"; type Inode = u64; type Handle = u64; #[derive(Clone, Copy, Debug, PartialOrd, Ord, PartialEq, Eq)] struct InodeAltKey { ino: libc::ino64_t, dev: libc::dev_t, } impl InodeAltKey { fn from_stat(st: &libc::stat64) -> Self { InodeAltKey { ino: st.st_ino, dev: st.st_dev, } } } struct InodeData { inode: Inode, // Most of these aren't actually files but ¯\_(ツ)_/¯. file: File, refcount: AtomicU64, } impl InodeData { fn new(inode: Inode, file: File, refcount: u64) -> Self { InodeData { inode, file, refcount: AtomicU64::new(refcount), } } // When making use of the underlying RawFd, the caller must ensure that the Arc<InodeData> // object is within scope. Otherwise it may cause race window to access wrong target fd. // By introducing this method, we could explicitly audit all callers making use of the // underlying RawFd. fn get_raw_fd(&self) -> RawFd { self.file.as_raw_fd() } } /// Data structures to manage accessed inodes. struct InodeMap { inodes: RwLock<MultikeyBTreeMap<Inode, InodeAltKey, Arc<InodeData>>>, } impl InodeMap { fn new() -> Self { InodeMap { inodes: RwLock::new(MultikeyBTreeMap::new()), } } fn clear(&self) { self.inodes.write().unwrap().clear(); } fn get(&self, inode: Inode) -> io::Result<Arc<InodeData>> { self.inodes .read() .unwrap() .get(&inode) .map(Arc::clone) .ok_or_else(ebadf) } fn get_alt(&self, altkey: &InodeAltKey) -> Option<Arc<InodeData>> { self.inodes.read().unwrap().get_alt(altkey).map(Arc::clone) } fn get_map_mut( &self, ) -> RwLockWriteGuard<MultikeyBTreeMap<Inode, InodeAltKey, Arc<InodeData>>> { self.inodes.write().unwrap() } fn insert(&self, inode: Inode, altkey: InodeAltKey, data: InodeData) { self.inodes .write() .unwrap() .insert(inode, altkey, Arc::new(data)); } } struct HandleData { inode: Inode, file: File, lock: Mutex<()>, } impl HandleData { fn new(inode: Inode, file: File) -> Self { HandleData { inode, file, lock: Mutex::new(()), } } fn get_file_mut(&self) -> (MutexGuard<()>, &File) { (self.lock.lock().unwrap(), &self.file) } // When making use of the underlying RawFd, the caller must ensure that the Arc<HandleData> // object is within scope. Otherwise it may cause race window to access wrong target fd. // By introducing this method, we could explicitly audit all callers making use of the // underlying RawFd. fn get_handle_raw_fd(&self) -> RawFd { self.file.as_raw_fd() } } struct HandleMap { handles: RwLock<BTreeMap<Handle, Arc<HandleData>>>, } impl HandleMap { fn new() -> Self { HandleMap { handles: RwLock::new(BTreeMap::new()), } } fn clear(&self) { self.handles.write().unwrap().clear(); } fn insert(&self, handle: Handle, data: HandleData) { self.handles.write().unwrap().insert(handle, Arc::new(data)); } fn release(&self, handle: Handle, inode: Inode) -> io::Result<()> { let mut handles = self.handles.write().unwrap(); if let btree_map::Entry::Occupied(e) = handles.entry(handle) { if e.get().inode == inode { // We don't need to close the file here because that will happen automatically when // the last `Arc` is dropped. e.remove(); return Ok(()); } } Err(ebadf()) } fn get(&self, handle: Handle, inode: Inode) -> io::Result<Arc<HandleData>> { self.handles .read() .unwrap() .get(&handle) .filter(|hd| hd.inode == inode) .map(Arc::clone) .ok_or_else(ebadf) } } #[repr(C, packed)] #[derive(Clone, Copy, Debug, Default)] struct LinuxDirent64 { d_ino: libc::ino64_t, d_off: libc::off64_t, d_reclen: libc::c_ushort, d_ty: libc::c_uchar, } unsafe impl ByteValued for LinuxDirent64 {} /// The caching policy that the file system should report to the FUSE client. By default the FUSE /// protocol uses close-to-open consistency. This means that any cached contents of the file are /// invalidated the next time that file is opened. #[derive(Debug, Clone, PartialEq)] pub enum CachePolicy { /// The client should never cache file data and all I/O should be directly forwarded to the /// server. This policy must be selected when file contents may change without the knowledge of /// the FUSE client (i.e., the file system does not have exclusive access to the directory). Never, /// The client is free to choose when and how to cache file data. This is the default policy and /// uses close-to-open consistency as described in the enum documentation. Auto, /// The client should always cache file data. This means that the FUSE client will not /// invalidate any cached data that was returned by the file system the last time the file was /// opened. This policy should only be selected when the file system has exclusive access to the /// directory. Always, } impl FromStr for CachePolicy { type Err = &'static str; fn from_str(s: &str) -> Result<Self, Self::Err> { match s { "never" | "Never" | "NEVER" | "none" | "None" | "NONE" => Ok(CachePolicy::Never), "auto" | "Auto" | "AUTO" => Ok(CachePolicy::Auto), "always" | "Always" | "ALWAYS" => Ok(CachePolicy::Always), _ => Err("invalid cache policy"), } } } impl Default for CachePolicy { fn default() -> Self { CachePolicy::Auto } } /// Options that configure the behavior of the passthrough fuse file system. #[derive(Debug, Clone, PartialEq)] pub struct Config { /// How long the FUSE client should consider directory entries to be valid. If the contents of a /// directory can only be modified by the FUSE client (i.e., the file system has exclusive /// access), then this should be a large value. /// /// The default value for this option is 5 seconds. pub entry_timeout: Duration, /// How long the FUSE client should consider file and directory attributes to be valid. If the /// attributes of a file or directory can only be modified by the FUSE client (i.e., the file /// system has exclusive access), then this should be set to a large value. /// /// The default value for this option is 5 seconds. pub attr_timeout: Duration, /// The caching policy the file system should use. See the documentation of `CachePolicy` for /// more details. pub cache_policy: CachePolicy, /// Whether the file system should enabled writeback caching. This can improve performance as it /// allows the FUSE client to cache and coalesce multiple writes before sending them to the file /// system. However, enabling this option can increase the risk of data corruption if the file /// contents can change without the knowledge of the FUSE client (i.e., the server does **NOT** /// have exclusive access). Additionally, the file system should have read access to all files /// in the directory it is serving as the FUSE client may send read requests even for files /// opened with `O_WRONLY`. /// /// Therefore callers should only enable this option when they can guarantee that: 1) the file /// system has exclusive access to the directory and 2) the file system has read permissions for /// all files in that directory. /// /// The default value for this option is `false`. pub writeback: bool, /// The path of the root directory. /// /// The default is `/`. pub root_dir: String, /// Whether the file system should support Extended Attributes (xattr). Enabling this feature may /// have a significant impact on performance, especially on write parallelism. This is the result /// of FUSE attempting to remove the special file privileges after each write request. /// /// The default value for this options is `false`. pub xattr: bool, /// To be compatible with Vfs and PseudoFs, PassthroughFs needs to prepare /// root inode before accepting INIT request. /// /// The default value for this option is `true`. pub do_import: bool, /// Control whether no_open is allowed. /// /// The default value for this option is `false`. pub no_open: bool, /// Control whether no_opendir is allowed. /// /// The default value for this option is `false`. pub no_opendir: bool, } impl Default for Config { fn default() -> Self { Config { entry_timeout: Duration::from_secs(5), attr_timeout: Duration::from_secs(5), cache_policy: Default::default(), writeback: false, root_dir: String::from("/"), xattr: false, do_import: true, no_open: false, no_opendir: false, } } } /// A file system that simply "passes through" all requests it receives to the underlying file /// system. /// /// To keep the implementation simple it servers the contents of its root directory. Users /// that wish to serve only a specific directory should set up the environment so that that /// directory ends up as the root of the file system process. One way to accomplish this is via a /// combination of mount namespaces and the pivot_root system call. pub struct PassthroughFs<D> { // File descriptors for various points in the file system tree. These fds are always opened with // the `O_PATH` option so they cannot be used for reading or writing any data. See the // documentation of the `O_PATH` flag in `open(2)` for more details on what one can and cannot // do with an fd opened with this flag. inode_map: InodeMap, next_inode: AtomicU64, // File descriptors for open files and directories. Unlike the fds in `inodes`, these _can_ be // used for reading and writing data. handle_map: HandleMap, next_handle: AtomicU64, // File descriptor pointing to the `/proc` directory. This is used to convert an fd from // `inodes` into one that can go into `handles`. This is accomplished by reading the // `self/fd/{}` symlink. We keep an open fd here in case the file system tree that we are meant // to be serving doesn't have access to `/proc`. proc: File, // Whether writeback caching is enabled for this directory. This will only be true when // `cfg.writeback` is true and `init` was called with `FsOptions::WRITEBACK_CACHE`. writeback: AtomicBool, // Whether no_open is enabled. no_open: AtomicBool, // Whether no_opendir is enabled. no_opendir: AtomicBool, cfg: Config, phantom: PhantomData<D>, } impl<D: AsyncDrive> PassthroughFs<D> { /// Create a Passthrough file system instance. pub fn new(cfg: Config) -> io::Result<PassthroughFs<D>> { // Safe because this is a constant value and a valid C string. let proc_cstr = unsafe { CStr::from_bytes_with_nul_unchecked(PROC_CSTR) }; let proc = Self::open_file( libc::AT_FDCWD, proc_cstr, libc::O_PATH | libc::O_NOFOLLOW | libc::O_CLOEXEC, 0, )?; Ok(PassthroughFs { inode_map: InodeMap::new(), next_inode: AtomicU64::new(fuse::ROOT_ID + 1), handle_map: HandleMap::new(), next_handle: AtomicU64::new(1), proc, writeback: AtomicBool::new(false), no_open: AtomicBool::new(false), no_opendir: AtomicBool::new(false), cfg, phantom: PhantomData, }) } /// Initialize the Passthrough file system. pub fn import(&self) -> io::Result<()> { let root = CString::new(self.cfg.root_dir.as_str()).expect("CString::new failed"); // We use `O_PATH` because we just want this for traversing the directory tree // and not for actually reading the contents. let f = Self::open_file( libc::AT_FDCWD, &root, libc::O_PATH | libc::O_NOFOLLOW | libc::O_CLOEXEC, 0, )?; let st = Self::stat(&f)?; // Safe because this doesn't modify any memory and there is no need to check the return // value because this system call always succeeds. We need to clear the umask here because // we want the client to be able to set all the bits in the mode. unsafe { libc::umask(0o000) }; // Not sure why the root inode gets a refcount of 2 but that's what libfuse does. self.inode_map.insert( fuse::ROOT_ID, InodeAltKey::from_stat(&st), InodeData::new(fuse::ROOT_ID, f, 2), ); Ok(()) } /// Get the list of file descriptors which should be reserved across live upgrade. pub fn keep_fds(&self) -> Vec<RawFd> { vec![self.proc.as_raw_fd()] } fn stat(f: &File) -> io::Result<libc::stat64> { // Safe because this is a constant value and a valid C string. let pathname = unsafe { CStr::from_bytes_with_nul_unchecked(EMPTY_CSTR) }; let mut st = MaybeUninit::<libc::stat64>::zeroed(); // Safe because the kernel will only write data in `st` and we check the return value. let res = unsafe { libc::fstatat64( f.as_raw_fd(), pathname.as_ptr(), st.as_mut_ptr(), libc::AT_EMPTY_PATH | libc::AT_SYMLINK_NOFOLLOW, ) }; if res >= 0 { // Safe because the kernel guarantees that the struct is now fully initialized. Ok(unsafe { st.assume_init() }) } else { Err(io::Error::last_os_error()) } } fn open_file(dfd: i32, pathname: &CStr, flags: i32, mode: u32) -> io::Result<File> { let fd = if flags & libc::O_CREAT == libc::O_CREAT { unsafe { libc::openat(dfd, pathname.as_ptr(), flags, mode) } } else {
if fd < 0 { return Err(io::Error::last_os_error()); } // Safe because we just opened this fd. Ok(unsafe { File::from_raw_fd(fd) }) } fn do_lookup(&self, parent: Inode, name: &CStr) -> io::Result<Entry> { let p = self.inode_map.get(parent)?; let f = Self::open_file( p.get_raw_fd(), name, libc::O_PATH | libc::O_NOFOLLOW | libc::O_CLOEXEC, 0, )?; let st = Self::stat(&f)?; let altkey = InodeAltKey::from_stat(&st); let mut found = None; 'search: loop { match self.inode_map.get_alt(&altkey) { // No existing entry found None => break'search, Some(data) => { let curr = data.refcount.load(Ordering::Acquire); // forgot_one() has just destroyed the entry, retry... if curr == 0 { continue'search; } // Saturating add to avoid integer overflow, it's not realistic to saturate u64. let new = curr.saturating_add(1); // Synchronizes with the forgot_one() if data .refcount .compare_exchange(curr, new, Ordering::AcqRel, Ordering::Acquire) .is_ok() { found = Some(data.inode); break; } } } } let inode = if let Some(v) = found { v } else { let mut inodes = self.inode_map.get_map_mut(); // Lookup inode_map again after acquiring the inode_map lock, as there might be another // racing thread already added an inode with the same altkey while we're not holding // the lock. If so just use the newly added inode, otherwise the inode will be replaced // and results in EBADF. match inodes.get_alt(&altkey).map(Arc::clone) { Some(data) => { trace!( "fuse: do_lookup sees existing inode {} altkey {:?}", data.inode, altkey ); data.refcount.fetch_add(1, Ordering::Relaxed); data.inode } None => { let inode = self.next_inode.fetch_add(1, Ordering::Relaxed); if inode > VFS_MAX_INO { return Err(io::Error::new( io::ErrorKind::Other, format!("max inode number reached: {}", VFS_MAX_INO), )); } trace!( "fuse: do_lookup adds new inode {} altkey {:?}", inode, altkey ); inodes.insert(inode, altkey, Arc::new(InodeData::new(inode, f, 1))); inode } } }; Ok(Entry { inode, generation: 0, attr: st, attr_timeout: self.cfg.attr_timeout, entry_timeout: self.cfg.entry_timeout, }) } fn forget_one( inodes: &mut MultikeyBTreeMap<Inode, InodeAltKey, Arc<InodeData>>, inode: Inode, count: u64, ) { // ROOT_ID should not be forgotten, or we're not able to access to files any more. if inode == fuse::ROOT_ID { return; } if let Some(data) = inodes.get(&inode) { // Acquiring the write lock on the inode map prevents new lookups from incrementing the // refcount but there is the possibility that a previous lookup already acquired a // reference to the inode data and is in the process of updating the refcount so we need // to loop here until we can decrement successfully. loop { let curr = data.refcount.load(Ordering::Acquire); // Saturating sub because it doesn't make sense for a refcount to go below zero and // we don't want misbehaving clients to cause integer overflow. let new = curr.saturating_sub(count); trace!( "fuse: forget inode {} refcount {}, count {}, new_count {}",
unsafe { libc::openat(dfd, pathname.as_ptr(), flags) } };
conditional_block
mod.rs
use std::mem::MaybeUninit; use std::os::unix::io::{AsRawFd, FromRawFd, RawFd}; use std::str::FromStr; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::{Arc, Mutex, MutexGuard, RwLock, RwLockWriteGuard}; use std::time::Duration; use vm_memory::ByteValued; use crate::abi::linux_abi as fuse; use crate::api::filesystem::Entry; use crate::api::{BackendFileSystem, VFS_MAX_INO}; #[cfg(feature = "async-io")] mod async_io; mod sync_io; mod multikey; use multikey::MultikeyBTreeMap; use crate::async_util::AsyncDrive; const CURRENT_DIR_CSTR: &[u8] = b".\0"; const PARENT_DIR_CSTR: &[u8] = b"..\0"; const EMPTY_CSTR: &[u8] = b"\0"; const PROC_CSTR: &[u8] = b"/proc\0"; type Inode = u64; type Handle = u64; #[derive(Clone, Copy, Debug, PartialOrd, Ord, PartialEq, Eq)] struct InodeAltKey { ino: libc::ino64_t, dev: libc::dev_t, } impl InodeAltKey { fn from_stat(st: &libc::stat64) -> Self { InodeAltKey { ino: st.st_ino, dev: st.st_dev, } } } struct InodeData { inode: Inode, // Most of these aren't actually files but ¯\_(ツ)_/¯. file: File, refcount: AtomicU64, } impl InodeData { fn new(inode: Inode, file: File, refcount: u64) -> Self { InodeData { inode, file, refcount: AtomicU64::new(refcount), } } // When making use of the underlying RawFd, the caller must ensure that the Arc<InodeData> // object is within scope. Otherwise it may cause race window to access wrong target fd. // By introducing this method, we could explicitly audit all callers making use of the // underlying RawFd. fn get_raw_fd(&self) -> RawFd { self.file.as_raw_fd() } } /// Data structures to manage accessed inodes. struct InodeMap { inodes: RwLock<MultikeyBTreeMap<Inode, InodeAltKey, Arc<InodeData>>>, } impl InodeMap { fn new() -> Self { InodeMap { inodes: RwLock::new(MultikeyBTreeMap::new()), } } fn clear(&self) { self.inodes.write().unwrap().clear(); } fn get(&self, inode: Inode) -> io::Result<Arc<InodeData>> { self.inodes .read() .unwrap() .get(&inode) .map(Arc::clone) .ok_or_else(ebadf) } fn get_alt(&self, altkey: &InodeAltKey) -> Option<Arc<InodeData>> { self.inodes.read().unwrap().get_alt(altkey).map(Arc::clone) } fn get_map_mut( &self, ) -> RwLockWriteGuard<MultikeyBTreeMap<Inode, InodeAltKey, Arc<InodeData>>> { self.inodes.write().unwrap() } fn insert(&self, inode: Inode, altkey: InodeAltKey, data: InodeData) { self.inodes .write() .unwrap() .insert(inode, altkey, Arc::new(data)); } } struct HandleData { inode: Inode, file: File, lock: Mutex<()>, } impl HandleData { fn new(inode: Inode, file: File) -> Self { HandleData { inode, file, lock: Mutex::new(()), } } fn get_file_mut(&self) -> (MutexGuard<()>, &File) { (self.lock.lock().unwrap(), &self.file) } // When making use of the underlying RawFd, the caller must ensure that the Arc<HandleData> // object is within scope. Otherwise it may cause race window to access wrong target fd. // By introducing this method, we could explicitly audit all callers making use of the // underlying RawFd. fn get_handle_raw_fd(&self) -> RawFd { self.file.as_raw_fd() } } struct HandleMap { handles: RwLock<BTreeMap<Handle, Arc<HandleData>>>, } impl HandleMap { fn new() -> Self { HandleMap { handles: RwLock::new(BTreeMap::new()), } } fn clear(&self) { self.handles.write().unwrap().clear(); } fn insert(&self, handle: Handle, data: HandleData) { self.handles.write().unwrap().insert(handle, Arc::new(data)); } fn release(&self, handle: Handle, inode: Inode) -> io::Result<()> { let mut handles = self.handles.write().unwrap(); if let btree_map::Entry::Occupied(e) = handles.entry(handle) { if e.get().inode == inode { // We don't need to close the file here because that will happen automatically when // the last `Arc` is dropped. e.remove(); return Ok(()); } } Err(ebadf()) } fn get(&self, handle: Handle, inode: Inode) -> io::Result<Arc<HandleData>> { self.handles .read() .unwrap() .get(&handle) .filter(|hd| hd.inode == inode) .map(Arc::clone) .ok_or_else(ebadf) } } #[repr(C, packed)] #[derive(Clone, Copy, Debug, Default)] struct LinuxDirent64 { d_ino: libc::ino64_t, d_off: libc::off64_t, d_reclen: libc::c_ushort, d_ty: libc::c_uchar, } unsafe impl ByteValued for LinuxDirent64 {} /// The caching policy that the file system should report to the FUSE client. By default the FUSE /// protocol uses close-to-open consistency. This means that any cached contents of the file are /// invalidated the next time that file is opened. #[derive(Debug, Clone, PartialEq)] pub enum CachePolicy { /// The client should never cache file data and all I/O should be directly forwarded to the /// server. This policy must be selected when file contents may change without the knowledge of /// the FUSE client (i.e., the file system does not have exclusive access to the directory). Never, /// The client is free to choose when and how to cache file data. This is the default policy and /// uses close-to-open consistency as described in the enum documentation. Auto, /// The client should always cache file data. This means that the FUSE client will not /// invalidate any cached data that was returned by the file system the last time the file was /// opened. This policy should only be selected when the file system has exclusive access to the /// directory. Always, } impl FromStr for CachePolicy { type Err = &'static str; fn from_str(s: &str) -> Result<Self, Self::Err> { match s { "never" | "Never" | "NEVER" | "none" | "None" | "NONE" => Ok(CachePolicy::Never), "auto" | "Auto" | "AUTO" => Ok(CachePolicy::Auto), "always" | "Always" | "ALWAYS" => Ok(CachePolicy::Always), _ => Err("invalid cache policy"), } } } impl Default for CachePolicy { fn default() -> Self { CachePolicy::Auto } } /// Options that configure the behavior of the passthrough fuse file system. #[derive(Debug, Clone, PartialEq)] pub struct Config { /// How long the FUSE client should consider directory entries to be valid. If the contents of a /// directory can only be modified by the FUSE client (i.e., the file system has exclusive /// access), then this should be a large value. /// /// The default value for this option is 5 seconds. pub entry_timeout: Duration, /// How long the FUSE client should consider file and directory attributes to be valid. If the /// attributes of a file or directory can only be modified by the FUSE client (i.e., the file /// system has exclusive access), then this should be set to a large value. /// /// The default value for this option is 5 seconds. pub attr_timeout: Duration, /// The caching policy the file system should use. See the documentation of `CachePolicy` for /// more details. pub cache_policy: CachePolicy, /// Whether the file system should enabled writeback caching. This can improve performance as it /// allows the FUSE client to cache and coalesce multiple writes before sending them to the file /// system. However, enabling this option can increase the risk of data corruption if the file /// contents can change without the knowledge of the FUSE client (i.e., the server does **NOT** /// have exclusive access). Additionally, the file system should have read access to all files /// in the directory it is serving as the FUSE client may send read requests even for files /// opened with `O_WRONLY`. /// /// Therefore callers should only enable this option when they can guarantee that: 1) the file /// system has exclusive access to the directory and 2) the file system has read permissions for /// all files in that directory. /// /// The default value for this option is `false`. pub writeback: bool, /// The path of the root directory. /// /// The default is `/`. pub root_dir: String, /// Whether the file system should support Extended Attributes (xattr). Enabling this feature may /// have a significant impact on performance, especially on write parallelism. This is the result /// of FUSE attempting to remove the special file privileges after each write request. /// /// The default value for this options is `false`. pub xattr: bool, /// To be compatible with Vfs and PseudoFs, PassthroughFs needs to prepare /// root inode before accepting INIT request. /// /// The default value for this option is `true`. pub do_import: bool, /// Control whether no_open is allowed. /// /// The default value for this option is `false`. pub no_open: bool, /// Control whether no_opendir is allowed. /// /// The default value for this option is `false`. pub no_opendir: bool, } impl Default for Config { fn default() -> Self { Config { entry_timeout: Duration::from_secs(5), attr_timeout: Duration::from_secs(5), cache_policy: Default::default(), writeback: false, root_dir: String::from("/"), xattr: false, do_import: true, no_open: false, no_opendir: false, } } } /// A file system that simply "passes through" all requests it receives to the underlying file /// system. /// /// To keep the implementation simple it servers the contents of its root directory. Users /// that wish to serve only a specific directory should set up the environment so that that /// directory ends up as the root of the file system process. One way to accomplish this is via a /// combination of mount namespaces and the pivot_root system call. pub struct PassthroughFs<D> { // File descriptors for various points in the file system tree. These fds are always opened with // the `O_PATH` option so they cannot be used for reading or writing any data. See the // documentation of the `O_PATH` flag in `open(2)` for more details on what one can and cannot // do with an fd opened with this flag. inode_map: InodeMap, next_inode: AtomicU64, // File descriptors for open files and directories. Unlike the fds in `inodes`, these _can_ be // used for reading and writing data. handle_map: HandleMap, next_handle: AtomicU64, // File descriptor pointing to the `/proc` directory. This is used to convert an fd from // `inodes` into one that can go into `handles`. This is accomplished by reading the // `self/fd/{}` symlink. We keep an open fd here in case the file system tree that we are meant // to be serving doesn't have access to `/proc`. proc: File, // Whether writeback caching is enabled for this directory. This will only be true when // `cfg.writeback` is true and `init` was called with `FsOptions::WRITEBACK_CACHE`. writeback: AtomicBool, // Whether no_open is enabled. no_open: AtomicBool, // Whether no_opendir is enabled. no_opendir: AtomicBool, cfg: Config, phantom: PhantomData<D>, } impl<D: AsyncDrive> PassthroughFs<D> { /// Create a Passthrough file system instance. pub fn new(cfg: Config) -> io::Result<PassthroughFs<D>> { // Safe because this is a constant value and a valid C string. let proc_cstr = unsafe { CStr::from_bytes_with_nul_unchecked(PROC_CSTR) }; let proc = Self::open_file( libc::AT_FDCWD, proc_cstr, libc::O_PATH | libc::O_NOFOLLOW | libc::O_CLOEXEC, 0, )?; Ok(PassthroughFs { inode_map: InodeMap::new(), next_inode: AtomicU64::new(fuse::ROOT_ID + 1), handle_map: HandleMap::new(), next_handle: AtomicU64::new(1), proc, writeback: AtomicBool::new(false), no_open: AtomicBool::new(false), no_opendir: AtomicBool::new(false), cfg, phantom: PhantomData, }) } /// Initialize the Passthrough file system. pub fn import(&self) -> io::Result<()> { let root = CString::new(self.cfg.root_dir.as_str()).expect("CString::new failed"); // We use `O_PATH` because we just want this for traversing the directory tree // and not for actually reading the contents. let f = Self::open_file( libc::AT_FDCWD, &root, libc::O_PATH | libc::O_NOFOLLOW | libc::O_CLOEXEC, 0, )?; let st = Self::stat(&f)?; // Safe because this doesn't modify any memory and there is no need to check the return // value because this system call always succeeds. We need to clear the umask here because // we want the client to be able to set all the bits in the mode. unsafe { libc::umask(0o000) }; // Not sure why the root inode gets a refcount of 2 but that's what libfuse does. self.inode_map.insert( fuse::ROOT_ID, InodeAltKey::from_stat(&st), InodeData::new(fuse::ROOT_ID, f, 2), ); Ok(()) } /// Get the list of file descriptors which should be reserved across live upgrade. pub fn keep_fds(&self) -> Vec<RawFd> { vec![self.proc.as_raw_fd()] } fn stat(f: &File) -> io::Result<libc::stat64> { // Safe because this is a constant value and a valid C string. let pathname = unsafe { CStr::from_bytes_with_nul_unchecked(EMPTY_CSTR) }; let mut st = MaybeUninit::<libc::stat64>::zeroed(); // Safe because the kernel will only write data in `st` and we check the return value. let res = unsafe { libc::fstatat64( f.as_raw_fd(), pathname.as_ptr(), st.as_mut_ptr(), libc::AT_EMPTY_PATH | libc::AT_SYMLINK_NOFOLLOW, ) }; if res >= 0 { // Safe because the kernel guarantees that the struct is now fully initialized. Ok(unsafe { st.assume_init() }) } else { Err(io::Error::last_os_error()) } } fn open_file(dfd: i32, pathname: &CStr, flags: i32, mode: u32) -> io::Result<File> { let fd = if flags & libc::O_CREAT == libc::O_CREAT { unsafe { libc::openat(dfd, pathname.as_ptr(), flags, mode) } } else { unsafe { libc::openat(dfd, pathname.as_ptr(), flags) } }; if fd < 0 { return Err(io::Error::last_os_error()); } // Safe because we just opened this fd. Ok(unsafe { File::from_raw_fd(fd) }) } fn do_lookup(&self, parent: Inode, name: &CStr) -> io::Result<Entry> { let p = self.inode_map.get(parent)?; let f = Self::open_file( p.get_raw_fd(), name, libc::O_PATH | libc::O_NOFOLLOW | libc::O_CLOEXEC, 0, )?; let st = Self::stat(&f)?; let altkey = InodeAltKey::from_stat(&st); let mut found = None; 'search: loop { match self.inode_map.get_alt(&altkey) { // No existing entry found None => break'search, Some(data) => { let curr = data.refcount.load(Ordering::Acquire); // forgot_one() has just destroyed the entry, retry... if curr == 0 { continue'search; } // Saturating add to avoid integer overflow, it's not realistic to saturate u64. let new = curr.saturating_add(1); // Synchronizes with the forgot_one() if data .refcount .compare_exchange(curr, new, Ordering::AcqRel, Ordering::Acquire) .is_ok() { found = Some(data.inode); break; } } } } let inode = if let Some(v) = found { v } else { let mut inodes = self.inode_map.get_map_mut(); // Lookup inode_map again after acquiring the inode_map lock, as there might be another // racing thread already added an inode with the same altkey while we're not holding // the lock. If so just use the newly added inode, otherwise the inode will be replaced // and results in EBADF. match inodes.get_alt(&altkey).map(Arc::clone) { Some(data) => { trace!( "fuse: do_lookup sees existing inode {} altkey {:?}", data.inode, altkey ); data.refcount.fetch_add(1, Ordering::Relaxed); data.inode } None => { let inode = self.next_inode.fetch_add(1, Ordering::Relaxed); if inode > VFS_MAX_INO { return Err(io::Error::new( io::ErrorKind::Other, format!("max inode number reached: {}", VFS_MAX_INO), )); } trace!( "fuse: do_lookup adds new inode {} altkey {:?}", inode, altkey ); inodes.insert(inode, altkey, Arc::new(InodeData::new(inode, f, 1))); inode } } }; Ok(Entry { inode, generation: 0, attr: st, attr_timeout: self.cfg.attr_timeout, entry_timeout: self.cfg.entry_timeout, }) } fn forget_one( inodes: &mut MultikeyBTreeMap<Inode, InodeAltKey, Arc<InodeData>>, inode: Inode, count: u64, ) { // ROOT_ID should not be forgotten, or we're not able to access to files any more. if inode == fuse::ROOT_ID { return; } if let Some(data) = inodes.get(&inode) { // Acquiring the write lock on the inode map prevents new lookups from incrementing the // refcount but there is the possibility that a previous lookup already acquired a // reference to the inode data and is in the process of updating the refcount so we need // to loop here until we can decrement successfully. loop { let curr = data.refcount.load(Ordering::Acquire); // Saturating sub because it doesn't make sense for a refcount to go
use std::ffi::{CStr, CString}; use std::fs::File; use std::io; use std::marker::PhantomData;
random_line_split
mod.rs
{ inode, file, refcount: AtomicU64::new(refcount), } } // When making use of the underlying RawFd, the caller must ensure that the Arc<InodeData> // object is within scope. Otherwise it may cause race window to access wrong target fd. // By introducing this method, we could explicitly audit all callers making use of the // underlying RawFd. fn get_raw_fd(&self) -> RawFd { self.file.as_raw_fd() } } /// Data structures to manage accessed inodes. struct InodeMap { inodes: RwLock<MultikeyBTreeMap<Inode, InodeAltKey, Arc<InodeData>>>, } impl InodeMap { fn new() -> Self { InodeMap { inodes: RwLock::new(MultikeyBTreeMap::new()), } } fn clear(&self) { self.inodes.write().unwrap().clear(); } fn get(&self, inode: Inode) -> io::Result<Arc<InodeData>> { self.inodes .read() .unwrap() .get(&inode) .map(Arc::clone) .ok_or_else(ebadf) } fn get_alt(&self, altkey: &InodeAltKey) -> Option<Arc<InodeData>> { self.inodes.read().unwrap().get_alt(altkey).map(Arc::clone) } fn get_map_mut( &self, ) -> RwLockWriteGuard<MultikeyBTreeMap<Inode, InodeAltKey, Arc<InodeData>>> { self.inodes.write().unwrap() } fn insert(&self, inode: Inode, altkey: InodeAltKey, data: InodeData) { self.inodes .write() .unwrap() .insert(inode, altkey, Arc::new(data)); } } struct HandleData { inode: Inode, file: File, lock: Mutex<()>, } impl HandleData { fn new(inode: Inode, file: File) -> Self { HandleData { inode, file, lock: Mutex::new(()), } } fn get_file_mut(&self) -> (MutexGuard<()>, &File) { (self.lock.lock().unwrap(), &self.file) } // When making use of the underlying RawFd, the caller must ensure that the Arc<HandleData> // object is within scope. Otherwise it may cause race window to access wrong target fd. // By introducing this method, we could explicitly audit all callers making use of the // underlying RawFd. fn get_handle_raw_fd(&self) -> RawFd { self.file.as_raw_fd() } } struct HandleMap { handles: RwLock<BTreeMap<Handle, Arc<HandleData>>>, } impl HandleMap { fn new() -> Self { HandleMap { handles: RwLock::new(BTreeMap::new()), } } fn clear(&self) { self.handles.write().unwrap().clear(); } fn insert(&self, handle: Handle, data: HandleData) { self.handles.write().unwrap().insert(handle, Arc::new(data)); } fn release(&self, handle: Handle, inode: Inode) -> io::Result<()> { let mut handles = self.handles.write().unwrap(); if let btree_map::Entry::Occupied(e) = handles.entry(handle) { if e.get().inode == inode { // We don't need to close the file here because that will happen automatically when // the last `Arc` is dropped. e.remove(); return Ok(()); } } Err(ebadf()) } fn get(&self, handle: Handle, inode: Inode) -> io::Result<Arc<HandleData>> { self.handles .read() .unwrap() .get(&handle) .filter(|hd| hd.inode == inode) .map(Arc::clone) .ok_or_else(ebadf) } } #[repr(C, packed)] #[derive(Clone, Copy, Debug, Default)] struct LinuxDirent64 { d_ino: libc::ino64_t, d_off: libc::off64_t, d_reclen: libc::c_ushort, d_ty: libc::c_uchar, } unsafe impl ByteValued for LinuxDirent64 {} /// The caching policy that the file system should report to the FUSE client. By default the FUSE /// protocol uses close-to-open consistency. This means that any cached contents of the file are /// invalidated the next time that file is opened. #[derive(Debug, Clone, PartialEq)] pub enum CachePolicy { /// The client should never cache file data and all I/O should be directly forwarded to the /// server. This policy must be selected when file contents may change without the knowledge of /// the FUSE client (i.e., the file system does not have exclusive access to the directory). Never, /// The client is free to choose when and how to cache file data. This is the default policy and /// uses close-to-open consistency as described in the enum documentation. Auto, /// The client should always cache file data. This means that the FUSE client will not /// invalidate any cached data that was returned by the file system the last time the file was /// opened. This policy should only be selected when the file system has exclusive access to the /// directory. Always, } impl FromStr for CachePolicy { type Err = &'static str; fn from_str(s: &str) -> Result<Self, Self::Err> { match s { "never" | "Never" | "NEVER" | "none" | "None" | "NONE" => Ok(CachePolicy::Never), "auto" | "Auto" | "AUTO" => Ok(CachePolicy::Auto), "always" | "Always" | "ALWAYS" => Ok(CachePolicy::Always), _ => Err("invalid cache policy"), } } } impl Default for CachePolicy { fn default() -> Self { CachePolicy::Auto } } /// Options that configure the behavior of the passthrough fuse file system. #[derive(Debug, Clone, PartialEq)] pub struct Config { /// How long the FUSE client should consider directory entries to be valid. If the contents of a /// directory can only be modified by the FUSE client (i.e., the file system has exclusive /// access), then this should be a large value. /// /// The default value for this option is 5 seconds. pub entry_timeout: Duration, /// How long the FUSE client should consider file and directory attributes to be valid. If the /// attributes of a file or directory can only be modified by the FUSE client (i.e., the file /// system has exclusive access), then this should be set to a large value. /// /// The default value for this option is 5 seconds. pub attr_timeout: Duration, /// The caching policy the file system should use. See the documentation of `CachePolicy` for /// more details. pub cache_policy: CachePolicy, /// Whether the file system should enabled writeback caching. This can improve performance as it /// allows the FUSE client to cache and coalesce multiple writes before sending them to the file /// system. However, enabling this option can increase the risk of data corruption if the file /// contents can change without the knowledge of the FUSE client (i.e., the server does **NOT** /// have exclusive access). Additionally, the file system should have read access to all files /// in the directory it is serving as the FUSE client may send read requests even for files /// opened with `O_WRONLY`. /// /// Therefore callers should only enable this option when they can guarantee that: 1) the file /// system has exclusive access to the directory and 2) the file system has read permissions for /// all files in that directory. /// /// The default value for this option is `false`. pub writeback: bool, /// The path of the root directory. /// /// The default is `/`. pub root_dir: String, /// Whether the file system should support Extended Attributes (xattr). Enabling this feature may /// have a significant impact on performance, especially on write parallelism. This is the result /// of FUSE attempting to remove the special file privileges after each write request. /// /// The default value for this options is `false`. pub xattr: bool, /// To be compatible with Vfs and PseudoFs, PassthroughFs needs to prepare /// root inode before accepting INIT request. /// /// The default value for this option is `true`. pub do_import: bool, /// Control whether no_open is allowed. /// /// The default value for this option is `false`. pub no_open: bool, /// Control whether no_opendir is allowed. /// /// The default value for this option is `false`. pub no_opendir: bool, } impl Default for Config { fn default() -> Self { Config { entry_timeout: Duration::from_secs(5), attr_timeout: Duration::from_secs(5), cache_policy: Default::default(), writeback: false, root_dir: String::from("/"), xattr: false, do_import: true, no_open: false, no_opendir: false, } } } /// A file system that simply "passes through" all requests it receives to the underlying file /// system. /// /// To keep the implementation simple it servers the contents of its root directory. Users /// that wish to serve only a specific directory should set up the environment so that that /// directory ends up as the root of the file system process. One way to accomplish this is via a /// combination of mount namespaces and the pivot_root system call. pub struct PassthroughFs<D> { // File descriptors for various points in the file system tree. These fds are always opened with // the `O_PATH` option so they cannot be used for reading or writing any data. See the // documentation of the `O_PATH` flag in `open(2)` for more details on what one can and cannot // do with an fd opened with this flag. inode_map: InodeMap, next_inode: AtomicU64, // File descriptors for open files and directories. Unlike the fds in `inodes`, these _can_ be // used for reading and writing data. handle_map: HandleMap, next_handle: AtomicU64, // File descriptor pointing to the `/proc` directory. This is used to convert an fd from // `inodes` into one that can go into `handles`. This is accomplished by reading the // `self/fd/{}` symlink. We keep an open fd here in case the file system tree that we are meant // to be serving doesn't have access to `/proc`. proc: File, // Whether writeback caching is enabled for this directory. This will only be true when // `cfg.writeback` is true and `init` was called with `FsOptions::WRITEBACK_CACHE`. writeback: AtomicBool, // Whether no_open is enabled. no_open: AtomicBool, // Whether no_opendir is enabled. no_opendir: AtomicBool, cfg: Config, phantom: PhantomData<D>, } impl<D: AsyncDrive> PassthroughFs<D> { /// Create a Passthrough file system instance. pub fn new(cfg: Config) -> io::Result<PassthroughFs<D>> { // Safe because this is a constant value and a valid C string. let proc_cstr = unsafe { CStr::from_bytes_with_nul_unchecked(PROC_CSTR) }; let proc = Self::open_file( libc::AT_FDCWD, proc_cstr, libc::O_PATH | libc::O_NOFOLLOW | libc::O_CLOEXEC, 0, )?; Ok(PassthroughFs { inode_map: InodeMap::new(), next_inode: AtomicU64::new(fuse::ROOT_ID + 1), handle_map: HandleMap::new(), next_handle: AtomicU64::new(1), proc, writeback: AtomicBool::new(false), no_open: AtomicBool::new(false), no_opendir: AtomicBool::new(false), cfg, phantom: PhantomData, }) } /// Initialize the Passthrough file system. pub fn import(&self) -> io::Result<()> { let root = CString::new(self.cfg.root_dir.as_str()).expect("CString::new failed"); // We use `O_PATH` because we just want this for traversing the directory tree // and not for actually reading the contents. let f = Self::open_file( libc::AT_FDCWD, &root, libc::O_PATH | libc::O_NOFOLLOW | libc::O_CLOEXEC, 0, )?; let st = Self::stat(&f)?; // Safe because this doesn't modify any memory and there is no need to check the return // value because this system call always succeeds. We need to clear the umask here because // we want the client to be able to set all the bits in the mode. unsafe { libc::umask(0o000) }; // Not sure why the root inode gets a refcount of 2 but that's what libfuse does. self.inode_map.insert( fuse::ROOT_ID, InodeAltKey::from_stat(&st), InodeData::new(fuse::ROOT_ID, f, 2), ); Ok(()) } /// Get the list of file descriptors which should be reserved across live upgrade. pub fn keep_fds(&self) -> Vec<RawFd> { vec![self.proc.as_raw_fd()] } fn stat(f: &File) -> io::Result<libc::stat64> { // Safe because this is a constant value and a valid C string. let pathname = unsafe { CStr::from_bytes_with_nul_unchecked(EMPTY_CSTR) }; let mut st = MaybeUninit::<libc::stat64>::zeroed(); // Safe because the kernel will only write data in `st` and we check the return value. let res = unsafe { libc::fstatat64( f.as_raw_fd(), pathname.as_ptr(), st.as_mut_ptr(), libc::AT_EMPTY_PATH | libc::AT_SYMLINK_NOFOLLOW, ) }; if res >= 0 { // Safe because the kernel guarantees that the struct is now fully initialized. Ok(unsafe { st.assume_init() }) } else { Err(io::Error::last_os_error()) } } fn open_file(dfd: i32, pathname: &CStr, flags: i32, mode: u32) -> io::Result<File> { let fd = if flags & libc::O_CREAT == libc::O_CREAT { unsafe { libc::openat(dfd, pathname.as_ptr(), flags, mode) } } else { unsafe { libc::openat(dfd, pathname.as_ptr(), flags) } }; if fd < 0 { return Err(io::Error::last_os_error()); } // Safe because we just opened this fd. Ok(unsafe { File::from_raw_fd(fd) }) } fn do_lookup(&self, parent: Inode, name: &CStr) -> io::Result<Entry> { let p = self.inode_map.get(parent)?; let f = Self::open_file( p.get_raw_fd(), name, libc::O_PATH | libc::O_NOFOLLOW | libc::O_CLOEXEC, 0, )?; let st = Self::stat(&f)?; let altkey = InodeAltKey::from_stat(&st); let mut found = None; 'search: loop { match self.inode_map.get_alt(&altkey) { // No existing entry found None => break'search, Some(data) => { let curr = data.refcount.load(Ordering::Acquire); // forgot_one() has just destroyed the entry, retry... if curr == 0 { continue'search; } // Saturating add to avoid integer overflow, it's not realistic to saturate u64. let new = curr.saturating_add(1); // Synchronizes with the forgot_one() if data .refcount .compare_exchange(curr, new, Ordering::AcqRel, Ordering::Acquire) .is_ok() { found = Some(data.inode); break; } } } } let inode = if let Some(v) = found { v } else { let mut inodes = self.inode_map.get_map_mut(); // Lookup inode_map again after acquiring the inode_map lock, as there might be another // racing thread already added an inode with the same altkey while we're not holding // the lock. If so just use the newly added inode, otherwise the inode will be replaced // and results in EBADF. match inodes.get_alt(&altkey).map(Arc::clone) { Some(data) => { trace!( "fuse: do_lookup sees existing inode {} altkey {:?}", data.inode, altkey ); data.refcount.fetch_add(1, Ordering::Relaxed); data.inode } None => { let inode = self.next_inode.fetch_add(1, Ordering::Relaxed); if inode > VFS_MAX_INO { return Err(io::Error::new( io::ErrorKind::Other, format!("max inode number reached: {}", VFS_MAX_INO), )); } trace!( "fuse: do_lookup adds new inode {} altkey {:?}", inode, altkey ); inodes.insert(inode, altkey, Arc::new(InodeData::new(inode, f, 1))); inode } } }; Ok(Entry { inode, generation: 0, attr: st, attr_timeout: self.cfg.attr_timeout, entry_timeout: self.cfg.entry_timeout, }) } fn forget_one( inodes: &mut MultikeyBTreeMap<Inode, InodeAltKey, Arc<InodeData>>, inode: Inode, count: u64, ) { // ROOT_ID should not be forgotten, or we're not able to access to files any more. if inode == fuse::ROOT_ID { return; } if let Some(data) = inodes.get(&inode) { // Acquiring the write lock on the inode map prevents new lookups from incrementing the // refcount but there is the possibility that a previous lookup already acquired a // reference to the inode data and is in the process of updating the refcount so we need // to loop here until we can decrement successfully. loop { let curr = data.refcount.load(Ordering::Acquire); // Saturating sub because it doesn't make sense for a refcount to go below zero and // we don't want misbehaving clients to cause integer overflow. let new = curr.saturating_sub(count); trace!( "fuse: forget inode {} refcount {}, count {}, new_count {}", inode, curr, count, new ); // Synchronizes with the acquire load in `do_lookup`. if data .refcount .compare_exchange(curr, new, Ordering::AcqRel, Ordering::Acquire) .is_ok() { if new == 0 { // We just removed the last refcount for this inode. inodes.remove(&inode); } break; } } } } fn do_r
elease(&se
identifier_name
mod.rs
memory::ByteValued; use crate::abi::linux_abi as fuse; use crate::api::filesystem::Entry; use crate::api::{BackendFileSystem, VFS_MAX_INO}; #[cfg(feature = "async-io")] mod async_io; mod sync_io; mod multikey; use multikey::MultikeyBTreeMap; use crate::async_util::AsyncDrive; const CURRENT_DIR_CSTR: &[u8] = b".\0"; const PARENT_DIR_CSTR: &[u8] = b"..\0"; const EMPTY_CSTR: &[u8] = b"\0"; const PROC_CSTR: &[u8] = b"/proc\0"; type Inode = u64; type Handle = u64; #[derive(Clone, Copy, Debug, PartialOrd, Ord, PartialEq, Eq)] struct InodeAltKey { ino: libc::ino64_t, dev: libc::dev_t, } impl InodeAltKey { fn from_stat(st: &libc::stat64) -> Self { InodeAltKey { ino: st.st_ino, dev: st.st_dev, } } } struct InodeData { inode: Inode, // Most of these aren't actually files but ¯\_(ツ)_/¯. file: File, refcount: AtomicU64, } impl InodeData { fn new(inode: Inode, file: File, refcount: u64) -> Self { InodeData { inode, file, refcount: AtomicU64::new(refcount), } } // When making use of the underlying RawFd, the caller must ensure that the Arc<InodeData> // object is within scope. Otherwise it may cause race window to access wrong target fd. // By introducing this method, we could explicitly audit all callers making use of the // underlying RawFd. fn get_raw_fd(&self) -> RawFd { self.file.as_raw_fd() } } /// Data structures to manage accessed inodes. struct InodeMap { inodes: RwLock<MultikeyBTreeMap<Inode, InodeAltKey, Arc<InodeData>>>, } impl InodeMap { fn new() -> Self { InodeMap { inodes: RwLock::new(MultikeyBTreeMap::new()), } } fn clear(&self) { self.inodes.write().unwrap().clear(); } fn get(&self, inode: Inode) -> io::Result<Arc<InodeData>> { self.inodes .read() .unwrap() .get(&inode) .map(Arc::clone) .ok_or_else(ebadf) } fn get_alt(&self, altkey: &InodeAltKey) -> Option<Arc<InodeData>> { self.inodes.read().unwrap().get_alt(altkey).map(Arc::clone) } fn get_map_mut( &self, ) -> RwLockWriteGuard<MultikeyBTreeMap<Inode, InodeAltKey, Arc<InodeData>>> { self.inodes.write().unwrap() } fn insert(&self, inode: Inode, altkey: InodeAltKey, data: InodeData) { self.inodes .write() .unwrap() .insert(inode, altkey, Arc::new(data)); } } struct HandleData { inode: Inode, file: File, lock: Mutex<()>, } impl HandleData { fn new(inode: Inode, file: File) -> Self { HandleData { inode, file, lock: Mutex::new(()), } } fn get_file_mut(&self) -> (MutexGuard<()>, &File) { (self.lock.lock().unwrap(), &self.file) } // When making use of the underlying RawFd, the caller must ensure that the Arc<HandleData> // object is within scope. Otherwise it may cause race window to access wrong target fd. // By introducing this method, we could explicitly audit all callers making use of the // underlying RawFd. fn get_handle_raw_fd(&self) -> RawFd { self.file.as_raw_fd() } } struct HandleMap { handles: RwLock<BTreeMap<Handle, Arc<HandleData>>>, } impl HandleMap { fn new() -> Self { HandleMap { handles: RwLock::new(BTreeMap::new()), } } fn clear(&self) { self.handles.write().unwrap().clear(); } fn insert(&self, handle: Handle, data: HandleData) { self.handles.write().unwrap().insert(handle, Arc::new(data)); } fn release(&self, handle: Handle, inode: Inode) -> io::Result<()> { let mut handles = self.handles.write().unwrap(); if let btree_map::Entry::Occupied(e) = handles.entry(handle) { if e.get().inode == inode { // We don't need to close the file here because that will happen automatically when // the last `Arc` is dropped. e.remove(); return Ok(()); } } Err(ebadf()) } fn get(&self, handle: Handle, inode: Inode) -> io::Result<Arc<HandleData>> { self.handles .read() .unwrap() .get(&handle) .filter(|hd| hd.inode == inode) .map(Arc::clone) .ok_or_else(ebadf) } } #[repr(C, packed)] #[derive(Clone, Copy, Debug, Default)] struct LinuxDirent64 { d_ino: libc::ino64_t, d_off: libc::off64_t, d_reclen: libc::c_ushort, d_ty: libc::c_uchar, } unsafe impl ByteValued for LinuxDirent64 {} /// The caching policy that the file system should report to the FUSE client. By default the FUSE /// protocol uses close-to-open consistency. This means that any cached contents of the file are /// invalidated the next time that file is opened. #[derive(Debug, Clone, PartialEq)] pub enum CachePolicy { /// The client should never cache file data and all I/O should be directly forwarded to the /// server. This policy must be selected when file contents may change without the knowledge of /// the FUSE client (i.e., the file system does not have exclusive access to the directory). Never, /// The client is free to choose when and how to cache file data. This is the default policy and /// uses close-to-open consistency as described in the enum documentation. Auto, /// The client should always cache file data. This means that the FUSE client will not /// invalidate any cached data that was returned by the file system the last time the file was /// opened. This policy should only be selected when the file system has exclusive access to the /// directory. Always, } impl FromStr for CachePolicy { type Err = &'static str; fn from_str(s: &str) -> Result<Self, Self::Err> {
impl Default for CachePolicy { fn default() -> Self { CachePolicy::Auto } } /// Options that configure the behavior of the passthrough fuse file system. #[derive(Debug, Clone, PartialEq)] pub struct Config { /// How long the FUSE client should consider directory entries to be valid. If the contents of a /// directory can only be modified by the FUSE client (i.e., the file system has exclusive /// access), then this should be a large value. /// /// The default value for this option is 5 seconds. pub entry_timeout: Duration, /// How long the FUSE client should consider file and directory attributes to be valid. If the /// attributes of a file or directory can only be modified by the FUSE client (i.e., the file /// system has exclusive access), then this should be set to a large value. /// /// The default value for this option is 5 seconds. pub attr_timeout: Duration, /// The caching policy the file system should use. See the documentation of `CachePolicy` for /// more details. pub cache_policy: CachePolicy, /// Whether the file system should enabled writeback caching. This can improve performance as it /// allows the FUSE client to cache and coalesce multiple writes before sending them to the file /// system. However, enabling this option can increase the risk of data corruption if the file /// contents can change without the knowledge of the FUSE client (i.e., the server does **NOT** /// have exclusive access). Additionally, the file system should have read access to all files /// in the directory it is serving as the FUSE client may send read requests even for files /// opened with `O_WRONLY`. /// /// Therefore callers should only enable this option when they can guarantee that: 1) the file /// system has exclusive access to the directory and 2) the file system has read permissions for /// all files in that directory. /// /// The default value for this option is `false`. pub writeback: bool, /// The path of the root directory. /// /// The default is `/`. pub root_dir: String, /// Whether the file system should support Extended Attributes (xattr). Enabling this feature may /// have a significant impact on performance, especially on write parallelism. This is the result /// of FUSE attempting to remove the special file privileges after each write request. /// /// The default value for this options is `false`. pub xattr: bool, /// To be compatible with Vfs and PseudoFs, PassthroughFs needs to prepare /// root inode before accepting INIT request. /// /// The default value for this option is `true`. pub do_import: bool, /// Control whether no_open is allowed. /// /// The default value for this option is `false`. pub no_open: bool, /// Control whether no_opendir is allowed. /// /// The default value for this option is `false`. pub no_opendir: bool, } impl Default for Config { fn default() -> Self { Config { entry_timeout: Duration::from_secs(5), attr_timeout: Duration::from_secs(5), cache_policy: Default::default(), writeback: false, root_dir: String::from("/"), xattr: false, do_import: true, no_open: false, no_opendir: false, } } } /// A file system that simply "passes through" all requests it receives to the underlying file /// system. /// /// To keep the implementation simple it servers the contents of its root directory. Users /// that wish to serve only a specific directory should set up the environment so that that /// directory ends up as the root of the file system process. One way to accomplish this is via a /// combination of mount namespaces and the pivot_root system call. pub struct PassthroughFs<D> { // File descriptors for various points in the file system tree. These fds are always opened with // the `O_PATH` option so they cannot be used for reading or writing any data. See the // documentation of the `O_PATH` flag in `open(2)` for more details on what one can and cannot // do with an fd opened with this flag. inode_map: InodeMap, next_inode: AtomicU64, // File descriptors for open files and directories. Unlike the fds in `inodes`, these _can_ be // used for reading and writing data. handle_map: HandleMap, next_handle: AtomicU64, // File descriptor pointing to the `/proc` directory. This is used to convert an fd from // `inodes` into one that can go into `handles`. This is accomplished by reading the // `self/fd/{}` symlink. We keep an open fd here in case the file system tree that we are meant // to be serving doesn't have access to `/proc`. proc: File, // Whether writeback caching is enabled for this directory. This will only be true when // `cfg.writeback` is true and `init` was called with `FsOptions::WRITEBACK_CACHE`. writeback: AtomicBool, // Whether no_open is enabled. no_open: AtomicBool, // Whether no_opendir is enabled. no_opendir: AtomicBool, cfg: Config, phantom: PhantomData<D>, } impl<D: AsyncDrive> PassthroughFs<D> { /// Create a Passthrough file system instance. pub fn new(cfg: Config) -> io::Result<PassthroughFs<D>> { // Safe because this is a constant value and a valid C string. let proc_cstr = unsafe { CStr::from_bytes_with_nul_unchecked(PROC_CSTR) }; let proc = Self::open_file( libc::AT_FDCWD, proc_cstr, libc::O_PATH | libc::O_NOFOLLOW | libc::O_CLOEXEC, 0, )?; Ok(PassthroughFs { inode_map: InodeMap::new(), next_inode: AtomicU64::new(fuse::ROOT_ID + 1), handle_map: HandleMap::new(), next_handle: AtomicU64::new(1), proc, writeback: AtomicBool::new(false), no_open: AtomicBool::new(false), no_opendir: AtomicBool::new(false), cfg, phantom: PhantomData, }) } /// Initialize the Passthrough file system. pub fn import(&self) -> io::Result<()> { let root = CString::new(self.cfg.root_dir.as_str()).expect("CString::new failed"); // We use `O_PATH` because we just want this for traversing the directory tree // and not for actually reading the contents. let f = Self::open_file( libc::AT_FDCWD, &root, libc::O_PATH | libc::O_NOFOLLOW | libc::O_CLOEXEC, 0, )?; let st = Self::stat(&f)?; // Safe because this doesn't modify any memory and there is no need to check the return // value because this system call always succeeds. We need to clear the umask here because // we want the client to be able to set all the bits in the mode. unsafe { libc::umask(0o000) }; // Not sure why the root inode gets a refcount of 2 but that's what libfuse does. self.inode_map.insert( fuse::ROOT_ID, InodeAltKey::from_stat(&st), InodeData::new(fuse::ROOT_ID, f, 2), ); Ok(()) } /// Get the list of file descriptors which should be reserved across live upgrade. pub fn keep_fds(&self) -> Vec<RawFd> { vec![self.proc.as_raw_fd()] } fn stat(f: &File) -> io::Result<libc::stat64> { // Safe because this is a constant value and a valid C string. let pathname = unsafe { CStr::from_bytes_with_nul_unchecked(EMPTY_CSTR) }; let mut st = MaybeUninit::<libc::stat64>::zeroed(); // Safe because the kernel will only write data in `st` and we check the return value. let res = unsafe { libc::fstatat64( f.as_raw_fd(), pathname.as_ptr(), st.as_mut_ptr(), libc::AT_EMPTY_PATH | libc::AT_SYMLINK_NOFOLLOW, ) }; if res >= 0 { // Safe because the kernel guarantees that the struct is now fully initialized. Ok(unsafe { st.assume_init() }) } else { Err(io::Error::last_os_error()) } } fn open_file(dfd: i32, pathname: &CStr, flags: i32, mode: u32) -> io::Result<File> { let fd = if flags & libc::O_CREAT == libc::O_CREAT { unsafe { libc::openat(dfd, pathname.as_ptr(), flags, mode) } } else { unsafe { libc::openat(dfd, pathname.as_ptr(), flags) } }; if fd < 0 { return Err(io::Error::last_os_error()); } // Safe because we just opened this fd. Ok(unsafe { File::from_raw_fd(fd) }) } fn do_lookup(&self, parent: Inode, name: &CStr) -> io::Result<Entry> { let p = self.inode_map.get(parent)?; let f = Self::open_file( p.get_raw_fd(), name, libc::O_PATH | libc::O_NOFOLLOW | libc::O_CLOEXEC, 0, )?; let st = Self::stat(&f)?; let altkey = InodeAltKey::from_stat(&st); let mut found = None; 'search: loop { match self.inode_map.get_alt(&altkey) { // No existing entry found None => break'search, Some(data) => { let curr = data.refcount.load(Ordering::Acquire); // forgot_one() has just destroyed the entry, retry... if curr == 0 { continue'search; } // Saturating add to avoid integer overflow, it's not realistic to saturate u64. let new = curr.saturating_add(1); // Synchronizes with the forgot_one() if data .refcount .compare_exchange(curr, new, Ordering::AcqRel, Ordering::Acquire) .is_ok() { found = Some(data.inode); break; } } } } let inode = if let Some(v) = found { v } else { let mut inodes = self.inode_map.get_map_mut(); // Lookup inode_map again after acquiring the inode_map lock, as there might be another // racing thread already added an inode with the same altkey while we're not holding // the lock. If so just use the newly added inode, otherwise the inode will be replaced // and results in EBADF. match inodes.get_alt(&altkey).map(Arc::clone) { Some(data) => { trace!( "fuse: do_lookup sees existing inode {} altkey {:?}", data.inode, altkey ); data.refcount.fetch_add(1, Ordering::Relaxed); data.inode } None => { let inode = self.next_inode.fetch_add(1, Ordering::Relaxed); if inode > VFS_MAX_INO { return Err(io::Error::new( io::ErrorKind::Other, format!("max inode number reached: {}", VFS_MAX_INO), )); } trace!( "fuse: do_lookup adds new inode {} altkey {:?}", inode, altkey ); inodes.insert(inode, altkey, Arc::new(InodeData::new(inode, f, 1))); inode } } }; Ok(Entry { inode, generation: 0, attr: st, attr_timeout: self.cfg.attr_timeout, entry_timeout: self.cfg.entry_timeout, }) } fn forget_one( inodes: &mut MultikeyBTreeMap<Inode, InodeAltKey, Arc<InodeData>>, inode: Inode, count: u64, ) { // ROOT_ID should not be forgotten, or we're not able to access to files any more. if inode == fuse::ROOT_ID { return; } if let Some(data) = inodes.get(&inode) { // Acquiring the write lock on the inode map prevents new lookups from incrementing the // refcount but there is the possibility that a previous lookup already acquired a // reference to the inode data and is in the process of updating the refcount so we need // to loop here until we can decrement successfully. loop { let curr = data.refcount.load(Ordering::Acquire); // Saturating sub because it doesn't make sense for a refcount to go below zero and // we don't want misbehaving clients to cause integer overflow. let new = curr.saturating_sub(count); trace!( "fuse: forget inode {} refcount {}, count {}, new_count {}",
match s { "never" | "Never" | "NEVER" | "none" | "None" | "NONE" => Ok(CachePolicy::Never), "auto" | "Auto" | "AUTO" => Ok(CachePolicy::Auto), "always" | "Always" | "ALWAYS" => Ok(CachePolicy::Always), _ => Err("invalid cache policy"), } } }
identifier_body
mod.rs
//! A builder for a Fletcher-like algorithm. //! //! The basic functionality of this algorithm is: //! * there is a sum which is just the bytes summed modulo some number //! * there is also a second sum which the sum of all of the normal sums (modulo the same number) //! //! Note that text word sizes are currently only `u8`. //! //! It works roughly like this: //! ``` //! # fn check(file: &[u8]) -> u32 { //! # let module = 0xfff1u32; //! # let init = 1; //! # let (addout1, addout2) = (0, 0); //! # let hwidth = 16; //! let mut sum1 = init; //! let mut sum2 = 0; //! for byte in file { //! sum1 = (sum1 + *byte as u32) % module; //! sum2 = (sum2 + sum1) % module; //! } //! return (sum2 + addout2) % module << hwidth | (sum1 + addout1) % module; //! # } //! ``` //! Normally, the sum is represented as the cumulative sum bitshifted to be above the regular sum. //! This representation will be referred to as "compact". //! //! These are the parameters: //! * width: Total number of bits of the checksum (twice the amount of bits of the individual sums) //! * module: The number by which both sums get reduced //! * init: The initial value of the regular sum //! * addout: The value that gets added at the end, compact //! * swap: Whether to swap the values in the compact representation, i.e. put the regular sum above the cumulative sum //! * check: The checksum of the bytes "123456789", checked to be correct on build //! * name: The name to be used when displaying the algorithm (optional) //! //! Note that the `init` parameter, unlike the `addout` parameter, is not compact and is only added to the regular sum, //! as for the cumulative sum, it is equivalent to the addout (so you can just add the cumulative `init` to the cumulative `addout`). mod rev; use crate::bitnum::{BitNum, Modnum}; use crate::checksum::{CheckBuilderErr, Digest, LinearCheck}; use crate::endian::{Endian, WordSpec}; use crate::keyval::KeyValIter; use num_traits::{One, Zero}; pub use rev::reverse_fletcher; #[cfg(feature = "parallel")] pub use rev::reverse_fletcher_para; use std::fmt::Display; use std::str::FromStr; /// A builder for a fletcher. /// /// One can use it for specifying a fletcher algorithm, which can be used for checksumming. /// /// Example: /// ``` /// # use delsum_lib::fletcher::Fletcher; /// let adler32 = Fletcher::<u32>::with_options() /// .width(32) /// .init(1) /// .module(65521) /// .check(0x091e01de) /// .name("adler32") /// .build() /// .is_ok(); /// ``` #[derive(Clone, Debug)] pub struct FletcherBuilder<Sum: Modnum> { width: Option<usize>, module: Option<Sum>, init: Option<Sum>, addout: Option<Sum::Double>, swap: Option<bool>, input_endian: Option<Endian>, output_endian: Option<Endian>, wordsize: Option<usize>, check: Option<Sum::Double>, name: Option<String>, } impl<S: Modnum> FletcherBuilder<S> { /// Sets the width of the type (both sums included, must be even, mandatory) pub fn width(&mut self, w: usize) -> &mut Self { self.width = Some(w); self } /// Sets the module of both sums (mandatory) pub fn module(&mut self, m: S) -> &mut Self { self.module = Some(m); self } /// Sets the initial value /// /// Contains one value for the regular sum. pub fn init(&mut self, i: S) -> &mut Self { self.init = Some(i); self } /// Sets a value that gets added after the checksum is finished /// /// Contains separate values for both sums, the cumulative one is bitshifted pub fn addout(&mut self, o: S::Double) -> &mut Self { self.addout = Some(o); self } /// Normally, the cumulative sum is saved on the higher bits and the normal sum in the lower bits. /// Setting this option to true swaps the positions. pub fn swap(&mut self, s: bool) -> &mut Self
/// The endian of the words of the input file pub fn inendian(&mut self, e: Endian) -> &mut Self { self.input_endian = Some(e); self } /// The number of bits in a word of the input file pub fn wordsize(&mut self, n: usize) -> &mut Self { self.wordsize = Some(n); self } /// The endian of the checksum pub fn outendian(&mut self, e: Endian) -> &mut Self { self.output_endian = Some(e); self } /// Checks whether c is the same as the checksum of "123456789" on creation pub fn check(&mut self, c: S::Double) -> &mut Self { self.check = Some(c); self } /// A name to be displayed pub fn name(&mut self, n: &str) -> &mut Self { self.name = Some(String::from(n)); self } /// Returns the Fletcher object after verifying correctness pub fn build(&self) -> Result<Fletcher<S>, CheckBuilderErr> { let init = self.init.unwrap_or_else(S::zero); let addout = self.addout.unwrap_or_else(S::Double::zero); // note: we only store the half width because it is more useful to us let hwidth = match self.width { None => return Err(CheckBuilderErr::MissingParameter("width")), Some(w) => { if w % 2!= 0 || w > addout.bits() { return Err(CheckBuilderErr::ValueOutOfRange("width")); } else { w / 2 } } }; let mask = (S::Double::one() << hwidth) - S::Double::one(); let module = self.module.unwrap_or_else(S::zero); let wordsize = self.wordsize.unwrap_or(8); if wordsize == 0 || wordsize % 8!= 0 || wordsize > 64 { return Err(CheckBuilderErr::ValueOutOfRange("wordsize")); } let wordspec = WordSpec { input_endian: self.input_endian.unwrap_or(Endian::Big), wordsize, output_endian: self.output_endian.unwrap_or(Endian::Big), }; let mut fletch = Fletcher { hwidth, module, init, addout, swap: self.swap.unwrap_or(false), wordspec, mask, name: self.name.clone(), }; let (mut s, mut c) = fletch.from_compact(addout); if!module.is_zero() { s = s % module; c = c % module; fletch.init = init % module; } else { fletch.init = init; }; fletch.addout = fletch.to_compact((s, c)); match self.check { Some(chk) => { if fletch.digest(&b"123456789"[..]).unwrap()!= chk { println!("{:x?}", fletch.digest(&b"123456789"[..]).unwrap()); Err(CheckBuilderErr::CheckFail) } else { Ok(fletch) } } None => Ok(fletch), } } } #[derive(Clone, Debug, Eq, PartialEq)] pub struct Fletcher<Sum: Modnum> { hwidth: usize, module: Sum, init: Sum, addout: Sum::Double, swap: bool, wordspec: WordSpec, mask: Sum::Double, name: Option<String>, } impl<Sum: Modnum> Display for Fletcher<Sum> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.name { Some(n) => write!(f, "{}", n), None => { write!( f, "fletcher width={} module={:#x} init={:#x} addout={:#x} swap={}", 2 * self.hwidth, self.module, self.init, self.addout, self.swap )?; if self.wordspec.word_bytes()!= 1 { write!( f, " in_endian={} wordsize={}", self.wordspec.input_endian, self.wordspec.wordsize )?; }; if self.hwidth * 2 > 8 { write!(f, " out_endian={}", self.wordspec.output_endian)?; }; Ok(()) } } } } impl<Sum: Modnum> Fletcher<Sum> { /// Creates a `FletcherBuilder`, see `FletcherBuilder` documentation for more details. pub fn with_options() -> FletcherBuilder<Sum> { FletcherBuilder { width: None, module: None, init: None, addout: None, swap: None, input_endian: None, output_endian: None, wordsize: None, check: None, name: None, } } fn from_compact(&self, x: Sum::Double) -> (Sum, Sum) { let l = Sum::from_double(x & self.mask); let h = Sum::from_double((x >> self.hwidth) & self.mask); if self.swap { (h, l) } else { (l, h) } } fn to_compact(&self, (s, c): (Sum, Sum)) -> Sum::Double { let (l, h) = if self.swap { (c, s) } else { (s, c) }; (Sum::Double::from(l) & self.mask) ^ (Sum::Double::from(h) & self.mask) << self.hwidth } } impl<Sum: Modnum> FromStr for FletcherBuilder<Sum> { /// See documentation of FromStr on Fletcher<Sum> fn from_str(s: &str) -> Result<FletcherBuilder<Sum>, CheckBuilderErr> { let mut fletch = Fletcher::<Sum>::with_options(); for x in KeyValIter::new(s) { let (current_key, current_val) = match x { Err(key) => return Err(CheckBuilderErr::MalformedString(key)), Ok(s) => s, }; let fletch_op = match current_key.as_str() { "width" => usize::from_str(&current_val).ok().map(|x| fletch.width(x)), "module" => Sum::from_hex(&current_val).ok().map(|x| fletch.module(x)), "init" => Sum::from_hex(&current_val).ok().map(|x| fletch.init(x)), "addout" => Sum::Double::from_hex(&current_val) .ok() .map(|x| fletch.addout(x)), "swap" => bool::from_str(&current_val).ok().map(|x| fletch.swap(x)), "in_endian" => Endian::from_str(&current_val) .ok() .map(|x| fletch.inendian(x)), "wordsize" => usize::from_str(&current_val) .ok() .map(|x| fletch.wordsize(x)), "out_endian" => Endian::from_str(&current_val) .ok() .map(|x| fletch.outendian(x)), "check" => Sum::Double::from_hex(&current_val) .ok() .map(|x| fletch.check(x)), "name" => Some(fletch.name(&current_val)), _ => return Err(CheckBuilderErr::UnknownKey(current_key)), }; match fletch_op { Some(f) => fletch = f.clone(), None => return Err(CheckBuilderErr::MalformedString(current_key)), } } Ok(fletch) } type Err = CheckBuilderErr; } impl<Sum: Modnum> FromStr for Fletcher<Sum> { /// Construct a new fletcher sum algorithm from a string. /// Note that all parameters except width are in hexadecimal. /// /// Example: /// /// ``` /// # use delsum_lib::fletcher::Fletcher; /// # use std::str::FromStr; /// Fletcher::<u32>::from_str("width=32 init=1 module=0xfff1 name=\"adler-32\"").is_ok(); /// ``` fn from_str(s: &str) -> Result<Fletcher<Sum>, CheckBuilderErr> { FletcherBuilder::<Sum>::from_str(s)?.build() } type Err = CheckBuilderErr; } impl<S: Modnum> Digest for Fletcher<S> { type Sum = S::Double; fn init(&self) -> Self::Sum { self.to_compact((self.init, S::zero())) } fn dig_word(&self, sum: Self::Sum, word: u64) -> Self::Sum { let (mut s, mut c) = self.from_compact(sum); let modword = S::mod_from(word, &self.module); s = S::add_mod(s, &modword, &self.module); c = S::add_mod(c, &s, &self.module); self.to_compact((s, c)) } fn finalize(&self, sum: Self::Sum) -> Self::Sum { self.add(sum, &self.addout) } fn to_bytes(&self, s: Self::Sum) -> Vec<u8> { self.wordspec.output_to_bytes(s, 2 * self.hwidth) } fn wordspec(&self) -> WordSpec { self.wordspec } } impl<S: Modnum> LinearCheck for Fletcher<S> { type Shift = S; fn init_shift(&self) -> Self::Shift { S::zero() } fn inc_shift(&self, shift: Self::Shift) -> Self::Shift { S::add_mod(shift, &S::one(), &self.module) } fn shift(&self, sum: Self::Sum, shift: &Self::Shift) -> Self::Sum { let (s, mut c) = self.from_compact(sum); let shift_diff = S::mul_mod(s, shift, &self.module); c = S::add_mod(c, &shift_diff, &self.module); self.to_compact((s, c)) } fn add(&self, sum_a: Self::Sum, sum_b: &Self::Sum) -> Self::Sum { let (sa, ca) = self.from_compact(sum_a); let (sb, cb) = self.from_compact(*sum_b); let sum_s = sa.add_mod(&sb, &self.module); let sum_c = ca.add_mod(&cb, &self.module); self.to_compact((sum_s, sum_c)) } fn negate(&self, sum: Self::Sum) -> Self::Sum { let (s, c) = self.from_compact(sum); self.to_compact((s.neg_mod(&self.module), c.neg_mod(&self.module))) } } #[cfg(test)] mod tests { use super::*; use crate::checksum::tests::{check_example, test_find, test_prop, test_shifts}; use std::str::FromStr; #[test] fn adler32() { let adel = Fletcher::<u16>::with_options() .width(32) .init(1) .module(65521) .check(0x091e01de) .build() .unwrap(); test_shifts(&adel); test_find(&adel); test_prop(&adel); check_example(&adel, 0x81bfd25f); let nobel = Fletcher::with_options() .width(32) .init(1u32) .module(65521) .check(0x091e01de) .build() .unwrap(); test_shifts(&nobel); test_find(&nobel); test_prop(&adel); check_example(&nobel, 0x81bfd25f); } #[test] fn fletcher16() { let f16 = Fletcher::with_options() .width(16) .module(0xffu8) .check(0x1ede) .build() .unwrap(); test_shifts(&f16); test_find(&f16); test_prop(&f16); check_example(&f16, 0x7815); } #[test] fn fletcher8() { let f8 = Fletcher::<u8>::from_str("width=8 module=f init=0 addout=0 swap=false check=0xc") .unwrap(); test_shifts(&f8); test_prop(&f8); check_example(&f8, 0x6); } }
{ self.swap = Some(s); self }
identifier_body
mod.rs
//! A builder for a Fletcher-like algorithm. //! //! The basic functionality of this algorithm is: //! * there is a sum which is just the bytes summed modulo some number //! * there is also a second sum which the sum of all of the normal sums (modulo the same number) //! //! Note that text word sizes are currently only `u8`. //! //! It works roughly like this: //! ``` //! # fn check(file: &[u8]) -> u32 { //! # let module = 0xfff1u32; //! # let init = 1; //! # let (addout1, addout2) = (0, 0); //! # let hwidth = 16; //! let mut sum1 = init; //! let mut sum2 = 0; //! for byte in file { //! sum1 = (sum1 + *byte as u32) % module; //! sum2 = (sum2 + sum1) % module; //! } //! return (sum2 + addout2) % module << hwidth | (sum1 + addout1) % module; //! # } //! ``` //! Normally, the sum is represented as the cumulative sum bitshifted to be above the regular sum. //! This representation will be referred to as "compact". //! //! These are the parameters: //! * width: Total number of bits of the checksum (twice the amount of bits of the individual sums) //! * module: The number by which both sums get reduced //! * init: The initial value of the regular sum //! * addout: The value that gets added at the end, compact //! * swap: Whether to swap the values in the compact representation, i.e. put the regular sum above the cumulative sum //! * check: The checksum of the bytes "123456789", checked to be correct on build //! * name: The name to be used when displaying the algorithm (optional) //! //! Note that the `init` parameter, unlike the `addout` parameter, is not compact and is only added to the regular sum, //! as for the cumulative sum, it is equivalent to the addout (so you can just add the cumulative `init` to the cumulative `addout`). mod rev; use crate::bitnum::{BitNum, Modnum}; use crate::checksum::{CheckBuilderErr, Digest, LinearCheck}; use crate::endian::{Endian, WordSpec}; use crate::keyval::KeyValIter; use num_traits::{One, Zero}; pub use rev::reverse_fletcher; #[cfg(feature = "parallel")] pub use rev::reverse_fletcher_para; use std::fmt::Display; use std::str::FromStr; /// A builder for a fletcher. /// /// One can use it for specifying a fletcher algorithm, which can be used for checksumming. /// /// Example: /// ``` /// # use delsum_lib::fletcher::Fletcher; /// let adler32 = Fletcher::<u32>::with_options() /// .width(32) /// .init(1) /// .module(65521) /// .check(0x091e01de) /// .name("adler32") /// .build() /// .is_ok(); /// ``` #[derive(Clone, Debug)] pub struct FletcherBuilder<Sum: Modnum> { width: Option<usize>, module: Option<Sum>, init: Option<Sum>, addout: Option<Sum::Double>, swap: Option<bool>, input_endian: Option<Endian>, output_endian: Option<Endian>, wordsize: Option<usize>, check: Option<Sum::Double>, name: Option<String>, } impl<S: Modnum> FletcherBuilder<S> { /// Sets the width of the type (both sums included, must be even, mandatory) pub fn width(&mut self, w: usize) -> &mut Self { self.width = Some(w); self } /// Sets the module of both sums (mandatory) pub fn module(&mut self, m: S) -> &mut Self { self.module = Some(m); self } /// Sets the initial value /// /// Contains one value for the regular sum. pub fn init(&mut self, i: S) -> &mut Self { self.init = Some(i); self } /// Sets a value that gets added after the checksum is finished /// /// Contains separate values for both sums, the cumulative one is bitshifted pub fn addout(&mut self, o: S::Double) -> &mut Self { self.addout = Some(o); self } /// Normally, the cumulative sum is saved on the higher bits and the normal sum in the lower bits. /// Setting this option to true swaps the positions. pub fn swap(&mut self, s: bool) -> &mut Self { self.swap = Some(s); self } /// The endian of the words of the input file pub fn
(&mut self, e: Endian) -> &mut Self { self.input_endian = Some(e); self } /// The number of bits in a word of the input file pub fn wordsize(&mut self, n: usize) -> &mut Self { self.wordsize = Some(n); self } /// The endian of the checksum pub fn outendian(&mut self, e: Endian) -> &mut Self { self.output_endian = Some(e); self } /// Checks whether c is the same as the checksum of "123456789" on creation pub fn check(&mut self, c: S::Double) -> &mut Self { self.check = Some(c); self } /// A name to be displayed pub fn name(&mut self, n: &str) -> &mut Self { self.name = Some(String::from(n)); self } /// Returns the Fletcher object after verifying correctness pub fn build(&self) -> Result<Fletcher<S>, CheckBuilderErr> { let init = self.init.unwrap_or_else(S::zero); let addout = self.addout.unwrap_or_else(S::Double::zero); // note: we only store the half width because it is more useful to us let hwidth = match self.width { None => return Err(CheckBuilderErr::MissingParameter("width")), Some(w) => { if w % 2!= 0 || w > addout.bits() { return Err(CheckBuilderErr::ValueOutOfRange("width")); } else { w / 2 } } }; let mask = (S::Double::one() << hwidth) - S::Double::one(); let module = self.module.unwrap_or_else(S::zero); let wordsize = self.wordsize.unwrap_or(8); if wordsize == 0 || wordsize % 8!= 0 || wordsize > 64 { return Err(CheckBuilderErr::ValueOutOfRange("wordsize")); } let wordspec = WordSpec { input_endian: self.input_endian.unwrap_or(Endian::Big), wordsize, output_endian: self.output_endian.unwrap_or(Endian::Big), }; let mut fletch = Fletcher { hwidth, module, init, addout, swap: self.swap.unwrap_or(false), wordspec, mask, name: self.name.clone(), }; let (mut s, mut c) = fletch.from_compact(addout); if!module.is_zero() { s = s % module; c = c % module; fletch.init = init % module; } else { fletch.init = init; }; fletch.addout = fletch.to_compact((s, c)); match self.check { Some(chk) => { if fletch.digest(&b"123456789"[..]).unwrap()!= chk { println!("{:x?}", fletch.digest(&b"123456789"[..]).unwrap()); Err(CheckBuilderErr::CheckFail) } else { Ok(fletch) } } None => Ok(fletch), } } } #[derive(Clone, Debug, Eq, PartialEq)] pub struct Fletcher<Sum: Modnum> { hwidth: usize, module: Sum, init: Sum, addout: Sum::Double, swap: bool, wordspec: WordSpec, mask: Sum::Double, name: Option<String>, } impl<Sum: Modnum> Display for Fletcher<Sum> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.name { Some(n) => write!(f, "{}", n), None => { write!( f, "fletcher width={} module={:#x} init={:#x} addout={:#x} swap={}", 2 * self.hwidth, self.module, self.init, self.addout, self.swap )?; if self.wordspec.word_bytes()!= 1 { write!( f, " in_endian={} wordsize={}", self.wordspec.input_endian, self.wordspec.wordsize )?; }; if self.hwidth * 2 > 8 { write!(f, " out_endian={}", self.wordspec.output_endian)?; }; Ok(()) } } } } impl<Sum: Modnum> Fletcher<Sum> { /// Creates a `FletcherBuilder`, see `FletcherBuilder` documentation for more details. pub fn with_options() -> FletcherBuilder<Sum> { FletcherBuilder { width: None, module: None, init: None, addout: None, swap: None, input_endian: None, output_endian: None, wordsize: None, check: None, name: None, } } fn from_compact(&self, x: Sum::Double) -> (Sum, Sum) { let l = Sum::from_double(x & self.mask); let h = Sum::from_double((x >> self.hwidth) & self.mask); if self.swap { (h, l) } else { (l, h) } } fn to_compact(&self, (s, c): (Sum, Sum)) -> Sum::Double { let (l, h) = if self.swap { (c, s) } else { (s, c) }; (Sum::Double::from(l) & self.mask) ^ (Sum::Double::from(h) & self.mask) << self.hwidth } } impl<Sum: Modnum> FromStr for FletcherBuilder<Sum> { /// See documentation of FromStr on Fletcher<Sum> fn from_str(s: &str) -> Result<FletcherBuilder<Sum>, CheckBuilderErr> { let mut fletch = Fletcher::<Sum>::with_options(); for x in KeyValIter::new(s) { let (current_key, current_val) = match x { Err(key) => return Err(CheckBuilderErr::MalformedString(key)), Ok(s) => s, }; let fletch_op = match current_key.as_str() { "width" => usize::from_str(&current_val).ok().map(|x| fletch.width(x)), "module" => Sum::from_hex(&current_val).ok().map(|x| fletch.module(x)), "init" => Sum::from_hex(&current_val).ok().map(|x| fletch.init(x)), "addout" => Sum::Double::from_hex(&current_val) .ok() .map(|x| fletch.addout(x)), "swap" => bool::from_str(&current_val).ok().map(|x| fletch.swap(x)), "in_endian" => Endian::from_str(&current_val) .ok() .map(|x| fletch.inendian(x)), "wordsize" => usize::from_str(&current_val) .ok() .map(|x| fletch.wordsize(x)), "out_endian" => Endian::from_str(&current_val) .ok() .map(|x| fletch.outendian(x)), "check" => Sum::Double::from_hex(&current_val) .ok() .map(|x| fletch.check(x)), "name" => Some(fletch.name(&current_val)), _ => return Err(CheckBuilderErr::UnknownKey(current_key)), }; match fletch_op { Some(f) => fletch = f.clone(), None => return Err(CheckBuilderErr::MalformedString(current_key)), } } Ok(fletch) } type Err = CheckBuilderErr; } impl<Sum: Modnum> FromStr for Fletcher<Sum> { /// Construct a new fletcher sum algorithm from a string. /// Note that all parameters except width are in hexadecimal. /// /// Example: /// /// ``` /// # use delsum_lib::fletcher::Fletcher; /// # use std::str::FromStr; /// Fletcher::<u32>::from_str("width=32 init=1 module=0xfff1 name=\"adler-32\"").is_ok(); /// ``` fn from_str(s: &str) -> Result<Fletcher<Sum>, CheckBuilderErr> { FletcherBuilder::<Sum>::from_str(s)?.build() } type Err = CheckBuilderErr; } impl<S: Modnum> Digest for Fletcher<S> { type Sum = S::Double; fn init(&self) -> Self::Sum { self.to_compact((self.init, S::zero())) } fn dig_word(&self, sum: Self::Sum, word: u64) -> Self::Sum { let (mut s, mut c) = self.from_compact(sum); let modword = S::mod_from(word, &self.module); s = S::add_mod(s, &modword, &self.module); c = S::add_mod(c, &s, &self.module); self.to_compact((s, c)) } fn finalize(&self, sum: Self::Sum) -> Self::Sum { self.add(sum, &self.addout) } fn to_bytes(&self, s: Self::Sum) -> Vec<u8> { self.wordspec.output_to_bytes(s, 2 * self.hwidth) } fn wordspec(&self) -> WordSpec { self.wordspec } } impl<S: Modnum> LinearCheck for Fletcher<S> { type Shift = S; fn init_shift(&self) -> Self::Shift { S::zero() } fn inc_shift(&self, shift: Self::Shift) -> Self::Shift { S::add_mod(shift, &S::one(), &self.module) } fn shift(&self, sum: Self::Sum, shift: &Self::Shift) -> Self::Sum { let (s, mut c) = self.from_compact(sum); let shift_diff = S::mul_mod(s, shift, &self.module); c = S::add_mod(c, &shift_diff, &self.module); self.to_compact((s, c)) } fn add(&self, sum_a: Self::Sum, sum_b: &Self::Sum) -> Self::Sum { let (sa, ca) = self.from_compact(sum_a); let (sb, cb) = self.from_compact(*sum_b); let sum_s = sa.add_mod(&sb, &self.module); let sum_c = ca.add_mod(&cb, &self.module); self.to_compact((sum_s, sum_c)) } fn negate(&self, sum: Self::Sum) -> Self::Sum { let (s, c) = self.from_compact(sum); self.to_compact((s.neg_mod(&self.module), c.neg_mod(&self.module))) } } #[cfg(test)] mod tests { use super::*; use crate::checksum::tests::{check_example, test_find, test_prop, test_shifts}; use std::str::FromStr; #[test] fn adler32() { let adel = Fletcher::<u16>::with_options() .width(32) .init(1) .module(65521) .check(0x091e01de) .build() .unwrap(); test_shifts(&adel); test_find(&adel); test_prop(&adel); check_example(&adel, 0x81bfd25f); let nobel = Fletcher::with_options() .width(32) .init(1u32) .module(65521) .check(0x091e01de) .build() .unwrap(); test_shifts(&nobel); test_find(&nobel); test_prop(&adel); check_example(&nobel, 0x81bfd25f); } #[test] fn fletcher16() { let f16 = Fletcher::with_options() .width(16) .module(0xffu8) .check(0x1ede) .build() .unwrap(); test_shifts(&f16); test_find(&f16); test_prop(&f16); check_example(&f16, 0x7815); } #[test] fn fletcher8() { let f8 = Fletcher::<u8>::from_str("width=8 module=f init=0 addout=0 swap=false check=0xc") .unwrap(); test_shifts(&f8); test_prop(&f8); check_example(&f8, 0x6); } }
inendian
identifier_name
mod.rs
//! A builder for a Fletcher-like algorithm. //! //! The basic functionality of this algorithm is: //! * there is a sum which is just the bytes summed modulo some number //! * there is also a second sum which the sum of all of the normal sums (modulo the same number) //! //! Note that text word sizes are currently only `u8`. //! //! It works roughly like this: //! ``` //! # fn check(file: &[u8]) -> u32 { //! # let module = 0xfff1u32; //! # let init = 1; //! # let (addout1, addout2) = (0, 0); //! # let hwidth = 16; //! let mut sum1 = init; //! let mut sum2 = 0; //! for byte in file { //! sum1 = (sum1 + *byte as u32) % module; //! sum2 = (sum2 + sum1) % module; //! } //! return (sum2 + addout2) % module << hwidth | (sum1 + addout1) % module; //! # } //! ``` //! Normally, the sum is represented as the cumulative sum bitshifted to be above the regular sum. //! This representation will be referred to as "compact". //! //! These are the parameters: //! * width: Total number of bits of the checksum (twice the amount of bits of the individual sums) //! * module: The number by which both sums get reduced //! * init: The initial value of the regular sum //! * addout: The value that gets added at the end, compact //! * swap: Whether to swap the values in the compact representation, i.e. put the regular sum above the cumulative sum //! * check: The checksum of the bytes "123456789", checked to be correct on build //! * name: The name to be used when displaying the algorithm (optional) //! //! Note that the `init` parameter, unlike the `addout` parameter, is not compact and is only added to the regular sum, //! as for the cumulative sum, it is equivalent to the addout (so you can just add the cumulative `init` to the cumulative `addout`). mod rev; use crate::bitnum::{BitNum, Modnum}; use crate::checksum::{CheckBuilderErr, Digest, LinearCheck}; use crate::endian::{Endian, WordSpec}; use crate::keyval::KeyValIter; use num_traits::{One, Zero}; pub use rev::reverse_fletcher; #[cfg(feature = "parallel")] pub use rev::reverse_fletcher_para; use std::fmt::Display; use std::str::FromStr; /// A builder for a fletcher. /// /// One can use it for specifying a fletcher algorithm, which can be used for checksumming. /// /// Example: /// ``` /// # use delsum_lib::fletcher::Fletcher; /// let adler32 = Fletcher::<u32>::with_options() /// .width(32) /// .init(1) /// .module(65521) /// .check(0x091e01de) /// .name("adler32") /// .build() /// .is_ok(); /// ``` #[derive(Clone, Debug)] pub struct FletcherBuilder<Sum: Modnum> { width: Option<usize>, module: Option<Sum>, init: Option<Sum>, addout: Option<Sum::Double>, swap: Option<bool>, input_endian: Option<Endian>, output_endian: Option<Endian>, wordsize: Option<usize>, check: Option<Sum::Double>, name: Option<String>, } impl<S: Modnum> FletcherBuilder<S> { /// Sets the width of the type (both sums included, must be even, mandatory) pub fn width(&mut self, w: usize) -> &mut Self { self.width = Some(w); self } /// Sets the module of both sums (mandatory) pub fn module(&mut self, m: S) -> &mut Self { self.module = Some(m); self } /// Sets the initial value /// /// Contains one value for the regular sum. pub fn init(&mut self, i: S) -> &mut Self { self.init = Some(i); self } /// Sets a value that gets added after the checksum is finished /// /// Contains separate values for both sums, the cumulative one is bitshifted pub fn addout(&mut self, o: S::Double) -> &mut Self { self.addout = Some(o); self } /// Normally, the cumulative sum is saved on the higher bits and the normal sum in the lower bits. /// Setting this option to true swaps the positions. pub fn swap(&mut self, s: bool) -> &mut Self { self.swap = Some(s); self } /// The endian of the words of the input file pub fn inendian(&mut self, e: Endian) -> &mut Self { self.input_endian = Some(e); self } /// The number of bits in a word of the input file pub fn wordsize(&mut self, n: usize) -> &mut Self { self.wordsize = Some(n); self } /// The endian of the checksum pub fn outendian(&mut self, e: Endian) -> &mut Self { self.output_endian = Some(e); self } /// Checks whether c is the same as the checksum of "123456789" on creation pub fn check(&mut self, c: S::Double) -> &mut Self { self.check = Some(c); self } /// A name to be displayed pub fn name(&mut self, n: &str) -> &mut Self { self.name = Some(String::from(n)); self } /// Returns the Fletcher object after verifying correctness pub fn build(&self) -> Result<Fletcher<S>, CheckBuilderErr> { let init = self.init.unwrap_or_else(S::zero); let addout = self.addout.unwrap_or_else(S::Double::zero); // note: we only store the half width because it is more useful to us let hwidth = match self.width { None => return Err(CheckBuilderErr::MissingParameter("width")), Some(w) => { if w % 2!= 0 || w > addout.bits() { return Err(CheckBuilderErr::ValueOutOfRange("width")); } else { w / 2 } } }; let mask = (S::Double::one() << hwidth) - S::Double::one(); let module = self.module.unwrap_or_else(S::zero); let wordsize = self.wordsize.unwrap_or(8); if wordsize == 0 || wordsize % 8!= 0 || wordsize > 64 { return Err(CheckBuilderErr::ValueOutOfRange("wordsize")); } let wordspec = WordSpec { input_endian: self.input_endian.unwrap_or(Endian::Big), wordsize, output_endian: self.output_endian.unwrap_or(Endian::Big), }; let mut fletch = Fletcher { hwidth, module, init, addout, swap: self.swap.unwrap_or(false), wordspec, mask, name: self.name.clone(), }; let (mut s, mut c) = fletch.from_compact(addout); if!module.is_zero() { s = s % module; c = c % module; fletch.init = init % module; } else { fletch.init = init; }; fletch.addout = fletch.to_compact((s, c)); match self.check { Some(chk) => { if fletch.digest(&b"123456789"[..]).unwrap()!= chk { println!("{:x?}", fletch.digest(&b"123456789"[..]).unwrap()); Err(CheckBuilderErr::CheckFail) } else { Ok(fletch) } } None => Ok(fletch), } } } #[derive(Clone, Debug, Eq, PartialEq)] pub struct Fletcher<Sum: Modnum> { hwidth: usize, module: Sum, init: Sum, addout: Sum::Double, swap: bool, wordspec: WordSpec, mask: Sum::Double, name: Option<String>, } impl<Sum: Modnum> Display for Fletcher<Sum> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.name { Some(n) => write!(f, "{}", n), None => { write!( f, "fletcher width={} module={:#x} init={:#x} addout={:#x} swap={}", 2 * self.hwidth, self.module, self.init, self.addout, self.swap )?; if self.wordspec.word_bytes()!= 1 { write!( f, " in_endian={} wordsize={}", self.wordspec.input_endian, self.wordspec.wordsize )?; }; if self.hwidth * 2 > 8 { write!(f, " out_endian={}", self.wordspec.output_endian)?; }; Ok(()) } } } } impl<Sum: Modnum> Fletcher<Sum> { /// Creates a `FletcherBuilder`, see `FletcherBuilder` documentation for more details. pub fn with_options() -> FletcherBuilder<Sum> { FletcherBuilder { width: None, module: None, init: None, addout: None, swap: None, input_endian: None, output_endian: None, wordsize: None, check: None, name: None, } } fn from_compact(&self, x: Sum::Double) -> (Sum, Sum) { let l = Sum::from_double(x & self.mask); let h = Sum::from_double((x >> self.hwidth) & self.mask); if self.swap { (h, l) } else { (l, h) } } fn to_compact(&self, (s, c): (Sum, Sum)) -> Sum::Double { let (l, h) = if self.swap { (c, s) } else { (s, c) }; (Sum::Double::from(l) & self.mask) ^ (Sum::Double::from(h) & self.mask) << self.hwidth } } impl<Sum: Modnum> FromStr for FletcherBuilder<Sum> { /// See documentation of FromStr on Fletcher<Sum> fn from_str(s: &str) -> Result<FletcherBuilder<Sum>, CheckBuilderErr> { let mut fletch = Fletcher::<Sum>::with_options(); for x in KeyValIter::new(s) { let (current_key, current_val) = match x { Err(key) => return Err(CheckBuilderErr::MalformedString(key)), Ok(s) => s, }; let fletch_op = match current_key.as_str() { "width" => usize::from_str(&current_val).ok().map(|x| fletch.width(x)), "module" => Sum::from_hex(&current_val).ok().map(|x| fletch.module(x)), "init" => Sum::from_hex(&current_val).ok().map(|x| fletch.init(x)), "addout" => Sum::Double::from_hex(&current_val) .ok() .map(|x| fletch.addout(x)), "swap" => bool::from_str(&current_val).ok().map(|x| fletch.swap(x)), "in_endian" => Endian::from_str(&current_val) .ok() .map(|x| fletch.inendian(x)), "wordsize" => usize::from_str(&current_val) .ok() .map(|x| fletch.wordsize(x)), "out_endian" => Endian::from_str(&current_val) .ok() .map(|x| fletch.outendian(x)), "check" => Sum::Double::from_hex(&current_val) .ok() .map(|x| fletch.check(x)), "name" => Some(fletch.name(&current_val)), _ => return Err(CheckBuilderErr::UnknownKey(current_key)), }; match fletch_op { Some(f) => fletch = f.clone(), None => return Err(CheckBuilderErr::MalformedString(current_key)), } } Ok(fletch) } type Err = CheckBuilderErr; } impl<Sum: Modnum> FromStr for Fletcher<Sum> { /// Construct a new fletcher sum algorithm from a string. /// Note that all parameters except width are in hexadecimal. /// /// Example: /// /// ``` /// # use delsum_lib::fletcher::Fletcher; /// # use std::str::FromStr; /// Fletcher::<u32>::from_str("width=32 init=1 module=0xfff1 name=\"adler-32\"").is_ok(); /// ``` fn from_str(s: &str) -> Result<Fletcher<Sum>, CheckBuilderErr> { FletcherBuilder::<Sum>::from_str(s)?.build() } type Err = CheckBuilderErr; } impl<S: Modnum> Digest for Fletcher<S> { type Sum = S::Double; fn init(&self) -> Self::Sum { self.to_compact((self.init, S::zero())) } fn dig_word(&self, sum: Self::Sum, word: u64) -> Self::Sum { let (mut s, mut c) = self.from_compact(sum); let modword = S::mod_from(word, &self.module); s = S::add_mod(s, &modword, &self.module); c = S::add_mod(c, &s, &self.module); self.to_compact((s, c)) } fn finalize(&self, sum: Self::Sum) -> Self::Sum { self.add(sum, &self.addout) } fn to_bytes(&self, s: Self::Sum) -> Vec<u8> { self.wordspec.output_to_bytes(s, 2 * self.hwidth) } fn wordspec(&self) -> WordSpec { self.wordspec } } impl<S: Modnum> LinearCheck for Fletcher<S> { type Shift = S; fn init_shift(&self) -> Self::Shift { S::zero() } fn inc_shift(&self, shift: Self::Shift) -> Self::Shift { S::add_mod(shift, &S::one(), &self.module) } fn shift(&self, sum: Self::Sum, shift: &Self::Shift) -> Self::Sum { let (s, mut c) = self.from_compact(sum); let shift_diff = S::mul_mod(s, shift, &self.module); c = S::add_mod(c, &shift_diff, &self.module); self.to_compact((s, c)) } fn add(&self, sum_a: Self::Sum, sum_b: &Self::Sum) -> Self::Sum { let (sa, ca) = self.from_compact(sum_a); let (sb, cb) = self.from_compact(*sum_b); let sum_s = sa.add_mod(&sb, &self.module); let sum_c = ca.add_mod(&cb, &self.module); self.to_compact((sum_s, sum_c)) } fn negate(&self, sum: Self::Sum) -> Self::Sum { let (s, c) = self.from_compact(sum); self.to_compact((s.neg_mod(&self.module), c.neg_mod(&self.module))) } } #[cfg(test)] mod tests { use super::*; use crate::checksum::tests::{check_example, test_find, test_prop, test_shifts}; use std::str::FromStr; #[test] fn adler32() { let adel = Fletcher::<u16>::with_options() .width(32) .init(1) .module(65521) .check(0x091e01de) .build() .unwrap(); test_shifts(&adel); test_find(&adel); test_prop(&adel); check_example(&adel, 0x81bfd25f); let nobel = Fletcher::with_options() .width(32) .init(1u32) .module(65521) .check(0x091e01de) .build() .unwrap(); test_shifts(&nobel); test_find(&nobel); test_prop(&adel); check_example(&nobel, 0x81bfd25f); } #[test] fn fletcher16() { let f16 = Fletcher::with_options() .width(16) .module(0xffu8) .check(0x1ede) .build() .unwrap(); test_shifts(&f16); test_find(&f16); test_prop(&f16); check_example(&f16, 0x7815); } #[test] fn fletcher8() { let f8 = Fletcher::<u8>::from_str("width=8 module=f init=0 addout=0 swap=false check=0xc") .unwrap(); test_shifts(&f8); test_prop(&f8); check_example(&f8, 0x6);
} }
random_line_split
mod.rs
//! A builder for a Fletcher-like algorithm. //! //! The basic functionality of this algorithm is: //! * there is a sum which is just the bytes summed modulo some number //! * there is also a second sum which the sum of all of the normal sums (modulo the same number) //! //! Note that text word sizes are currently only `u8`. //! //! It works roughly like this: //! ``` //! # fn check(file: &[u8]) -> u32 { //! # let module = 0xfff1u32; //! # let init = 1; //! # let (addout1, addout2) = (0, 0); //! # let hwidth = 16; //! let mut sum1 = init; //! let mut sum2 = 0; //! for byte in file { //! sum1 = (sum1 + *byte as u32) % module; //! sum2 = (sum2 + sum1) % module; //! } //! return (sum2 + addout2) % module << hwidth | (sum1 + addout1) % module; //! # } //! ``` //! Normally, the sum is represented as the cumulative sum bitshifted to be above the regular sum. //! This representation will be referred to as "compact". //! //! These are the parameters: //! * width: Total number of bits of the checksum (twice the amount of bits of the individual sums) //! * module: The number by which both sums get reduced //! * init: The initial value of the regular sum //! * addout: The value that gets added at the end, compact //! * swap: Whether to swap the values in the compact representation, i.e. put the regular sum above the cumulative sum //! * check: The checksum of the bytes "123456789", checked to be correct on build //! * name: The name to be used when displaying the algorithm (optional) //! //! Note that the `init` parameter, unlike the `addout` parameter, is not compact and is only added to the regular sum, //! as for the cumulative sum, it is equivalent to the addout (so you can just add the cumulative `init` to the cumulative `addout`). mod rev; use crate::bitnum::{BitNum, Modnum}; use crate::checksum::{CheckBuilderErr, Digest, LinearCheck}; use crate::endian::{Endian, WordSpec}; use crate::keyval::KeyValIter; use num_traits::{One, Zero}; pub use rev::reverse_fletcher; #[cfg(feature = "parallel")] pub use rev::reverse_fletcher_para; use std::fmt::Display; use std::str::FromStr; /// A builder for a fletcher. /// /// One can use it for specifying a fletcher algorithm, which can be used for checksumming. /// /// Example: /// ``` /// # use delsum_lib::fletcher::Fletcher; /// let adler32 = Fletcher::<u32>::with_options() /// .width(32) /// .init(1) /// .module(65521) /// .check(0x091e01de) /// .name("adler32") /// .build() /// .is_ok(); /// ``` #[derive(Clone, Debug)] pub struct FletcherBuilder<Sum: Modnum> { width: Option<usize>, module: Option<Sum>, init: Option<Sum>, addout: Option<Sum::Double>, swap: Option<bool>, input_endian: Option<Endian>, output_endian: Option<Endian>, wordsize: Option<usize>, check: Option<Sum::Double>, name: Option<String>, } impl<S: Modnum> FletcherBuilder<S> { /// Sets the width of the type (both sums included, must be even, mandatory) pub fn width(&mut self, w: usize) -> &mut Self { self.width = Some(w); self } /// Sets the module of both sums (mandatory) pub fn module(&mut self, m: S) -> &mut Self { self.module = Some(m); self } /// Sets the initial value /// /// Contains one value for the regular sum. pub fn init(&mut self, i: S) -> &mut Self { self.init = Some(i); self } /// Sets a value that gets added after the checksum is finished /// /// Contains separate values for both sums, the cumulative one is bitshifted pub fn addout(&mut self, o: S::Double) -> &mut Self { self.addout = Some(o); self } /// Normally, the cumulative sum is saved on the higher bits and the normal sum in the lower bits. /// Setting this option to true swaps the positions. pub fn swap(&mut self, s: bool) -> &mut Self { self.swap = Some(s); self } /// The endian of the words of the input file pub fn inendian(&mut self, e: Endian) -> &mut Self { self.input_endian = Some(e); self } /// The number of bits in a word of the input file pub fn wordsize(&mut self, n: usize) -> &mut Self { self.wordsize = Some(n); self } /// The endian of the checksum pub fn outendian(&mut self, e: Endian) -> &mut Self { self.output_endian = Some(e); self } /// Checks whether c is the same as the checksum of "123456789" on creation pub fn check(&mut self, c: S::Double) -> &mut Self { self.check = Some(c); self } /// A name to be displayed pub fn name(&mut self, n: &str) -> &mut Self { self.name = Some(String::from(n)); self } /// Returns the Fletcher object after verifying correctness pub fn build(&self) -> Result<Fletcher<S>, CheckBuilderErr> { let init = self.init.unwrap_or_else(S::zero); let addout = self.addout.unwrap_or_else(S::Double::zero); // note: we only store the half width because it is more useful to us let hwidth = match self.width { None => return Err(CheckBuilderErr::MissingParameter("width")), Some(w) => { if w % 2!= 0 || w > addout.bits() { return Err(CheckBuilderErr::ValueOutOfRange("width")); } else { w / 2 } } }; let mask = (S::Double::one() << hwidth) - S::Double::one(); let module = self.module.unwrap_or_else(S::zero); let wordsize = self.wordsize.unwrap_or(8); if wordsize == 0 || wordsize % 8!= 0 || wordsize > 64 { return Err(CheckBuilderErr::ValueOutOfRange("wordsize")); } let wordspec = WordSpec { input_endian: self.input_endian.unwrap_or(Endian::Big), wordsize, output_endian: self.output_endian.unwrap_or(Endian::Big), }; let mut fletch = Fletcher { hwidth, module, init, addout, swap: self.swap.unwrap_or(false), wordspec, mask, name: self.name.clone(), }; let (mut s, mut c) = fletch.from_compact(addout); if!module.is_zero() { s = s % module; c = c % module; fletch.init = init % module; } else
; fletch.addout = fletch.to_compact((s, c)); match self.check { Some(chk) => { if fletch.digest(&b"123456789"[..]).unwrap()!= chk { println!("{:x?}", fletch.digest(&b"123456789"[..]).unwrap()); Err(CheckBuilderErr::CheckFail) } else { Ok(fletch) } } None => Ok(fletch), } } } #[derive(Clone, Debug, Eq, PartialEq)] pub struct Fletcher<Sum: Modnum> { hwidth: usize, module: Sum, init: Sum, addout: Sum::Double, swap: bool, wordspec: WordSpec, mask: Sum::Double, name: Option<String>, } impl<Sum: Modnum> Display for Fletcher<Sum> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.name { Some(n) => write!(f, "{}", n), None => { write!( f, "fletcher width={} module={:#x} init={:#x} addout={:#x} swap={}", 2 * self.hwidth, self.module, self.init, self.addout, self.swap )?; if self.wordspec.word_bytes()!= 1 { write!( f, " in_endian={} wordsize={}", self.wordspec.input_endian, self.wordspec.wordsize )?; }; if self.hwidth * 2 > 8 { write!(f, " out_endian={}", self.wordspec.output_endian)?; }; Ok(()) } } } } impl<Sum: Modnum> Fletcher<Sum> { /// Creates a `FletcherBuilder`, see `FletcherBuilder` documentation for more details. pub fn with_options() -> FletcherBuilder<Sum> { FletcherBuilder { width: None, module: None, init: None, addout: None, swap: None, input_endian: None, output_endian: None, wordsize: None, check: None, name: None, } } fn from_compact(&self, x: Sum::Double) -> (Sum, Sum) { let l = Sum::from_double(x & self.mask); let h = Sum::from_double((x >> self.hwidth) & self.mask); if self.swap { (h, l) } else { (l, h) } } fn to_compact(&self, (s, c): (Sum, Sum)) -> Sum::Double { let (l, h) = if self.swap { (c, s) } else { (s, c) }; (Sum::Double::from(l) & self.mask) ^ (Sum::Double::from(h) & self.mask) << self.hwidth } } impl<Sum: Modnum> FromStr for FletcherBuilder<Sum> { /// See documentation of FromStr on Fletcher<Sum> fn from_str(s: &str) -> Result<FletcherBuilder<Sum>, CheckBuilderErr> { let mut fletch = Fletcher::<Sum>::with_options(); for x in KeyValIter::new(s) { let (current_key, current_val) = match x { Err(key) => return Err(CheckBuilderErr::MalformedString(key)), Ok(s) => s, }; let fletch_op = match current_key.as_str() { "width" => usize::from_str(&current_val).ok().map(|x| fletch.width(x)), "module" => Sum::from_hex(&current_val).ok().map(|x| fletch.module(x)), "init" => Sum::from_hex(&current_val).ok().map(|x| fletch.init(x)), "addout" => Sum::Double::from_hex(&current_val) .ok() .map(|x| fletch.addout(x)), "swap" => bool::from_str(&current_val).ok().map(|x| fletch.swap(x)), "in_endian" => Endian::from_str(&current_val) .ok() .map(|x| fletch.inendian(x)), "wordsize" => usize::from_str(&current_val) .ok() .map(|x| fletch.wordsize(x)), "out_endian" => Endian::from_str(&current_val) .ok() .map(|x| fletch.outendian(x)), "check" => Sum::Double::from_hex(&current_val) .ok() .map(|x| fletch.check(x)), "name" => Some(fletch.name(&current_val)), _ => return Err(CheckBuilderErr::UnknownKey(current_key)), }; match fletch_op { Some(f) => fletch = f.clone(), None => return Err(CheckBuilderErr::MalformedString(current_key)), } } Ok(fletch) } type Err = CheckBuilderErr; } impl<Sum: Modnum> FromStr for Fletcher<Sum> { /// Construct a new fletcher sum algorithm from a string. /// Note that all parameters except width are in hexadecimal. /// /// Example: /// /// ``` /// # use delsum_lib::fletcher::Fletcher; /// # use std::str::FromStr; /// Fletcher::<u32>::from_str("width=32 init=1 module=0xfff1 name=\"adler-32\"").is_ok(); /// ``` fn from_str(s: &str) -> Result<Fletcher<Sum>, CheckBuilderErr> { FletcherBuilder::<Sum>::from_str(s)?.build() } type Err = CheckBuilderErr; } impl<S: Modnum> Digest for Fletcher<S> { type Sum = S::Double; fn init(&self) -> Self::Sum { self.to_compact((self.init, S::zero())) } fn dig_word(&self, sum: Self::Sum, word: u64) -> Self::Sum { let (mut s, mut c) = self.from_compact(sum); let modword = S::mod_from(word, &self.module); s = S::add_mod(s, &modword, &self.module); c = S::add_mod(c, &s, &self.module); self.to_compact((s, c)) } fn finalize(&self, sum: Self::Sum) -> Self::Sum { self.add(sum, &self.addout) } fn to_bytes(&self, s: Self::Sum) -> Vec<u8> { self.wordspec.output_to_bytes(s, 2 * self.hwidth) } fn wordspec(&self) -> WordSpec { self.wordspec } } impl<S: Modnum> LinearCheck for Fletcher<S> { type Shift = S; fn init_shift(&self) -> Self::Shift { S::zero() } fn inc_shift(&self, shift: Self::Shift) -> Self::Shift { S::add_mod(shift, &S::one(), &self.module) } fn shift(&self, sum: Self::Sum, shift: &Self::Shift) -> Self::Sum { let (s, mut c) = self.from_compact(sum); let shift_diff = S::mul_mod(s, shift, &self.module); c = S::add_mod(c, &shift_diff, &self.module); self.to_compact((s, c)) } fn add(&self, sum_a: Self::Sum, sum_b: &Self::Sum) -> Self::Sum { let (sa, ca) = self.from_compact(sum_a); let (sb, cb) = self.from_compact(*sum_b); let sum_s = sa.add_mod(&sb, &self.module); let sum_c = ca.add_mod(&cb, &self.module); self.to_compact((sum_s, sum_c)) } fn negate(&self, sum: Self::Sum) -> Self::Sum { let (s, c) = self.from_compact(sum); self.to_compact((s.neg_mod(&self.module), c.neg_mod(&self.module))) } } #[cfg(test)] mod tests { use super::*; use crate::checksum::tests::{check_example, test_find, test_prop, test_shifts}; use std::str::FromStr; #[test] fn adler32() { let adel = Fletcher::<u16>::with_options() .width(32) .init(1) .module(65521) .check(0x091e01de) .build() .unwrap(); test_shifts(&adel); test_find(&adel); test_prop(&adel); check_example(&adel, 0x81bfd25f); let nobel = Fletcher::with_options() .width(32) .init(1u32) .module(65521) .check(0x091e01de) .build() .unwrap(); test_shifts(&nobel); test_find(&nobel); test_prop(&adel); check_example(&nobel, 0x81bfd25f); } #[test] fn fletcher16() { let f16 = Fletcher::with_options() .width(16) .module(0xffu8) .check(0x1ede) .build() .unwrap(); test_shifts(&f16); test_find(&f16); test_prop(&f16); check_example(&f16, 0x7815); } #[test] fn fletcher8() { let f8 = Fletcher::<u8>::from_str("width=8 module=f init=0 addout=0 swap=false check=0xc") .unwrap(); test_shifts(&f8); test_prop(&f8); check_example(&f8, 0x6); } }
{ fletch.init = init; }
conditional_block
rainstorm.rs
#![feature(macro_rules, intrinsics, lang_items, globs)] #![no_std] extern crate libc; extern crate core; extern crate alloc; extern crate collections; extern crate rand; pub use core::prelude::*; pub use cheats::{Cheat, CheatManager}; pub use alloc::owned::Box; pub use collections::Vec; use core::raw::Repr; mod logging; pub mod sdk; mod vmthook; pub mod utils; mod cheats; mod std { pub use core::fmt; //lol pub use core::option; pub use core::num; } #[allow(dead_code)] pub mod cmath { use libc::{c_float, c_int}; #[link_name = "m"] extern { pub fn acosf(n: c_float) -> c_float; pub fn asinf(n: c_float) -> c_float; pub fn atanf(n: c_float) -> c_float; pub fn atan2f(a: c_float, b: c_float) -> c_float; pub fn cbrtf(n: c_float) -> c_float; pub fn coshf(n: c_float) -> c_float; pub fn erff(n: c_float) -> c_float; pub fn erfcf(n: c_float) -> c_float; pub fn expm1f(n: c_float) -> c_float; pub fn fdimf(a: c_float, b: c_float) -> c_float; pub fn frexpf(n: c_float, value: &mut c_int) -> c_float; pub fn fmaxf(a: c_float, b: c_float) -> c_float; pub fn fminf(a: c_float, b: c_float) -> c_float; pub fn fmodf(a: c_float, b: c_float) -> c_float; pub fn nextafterf(x: c_float, y: c_float) -> c_float; pub fn hypotf(x: c_float, y: c_float) -> c_float; pub fn ldexpf(x: c_float, n: c_int) -> c_float; pub fn logbf(n: c_float) -> c_float; pub fn log1pf(n: c_float) -> c_float; pub fn ilogbf(n: c_float) -> c_int; pub fn modff(n: c_float, iptr: &mut c_float) -> c_float; pub fn sinhf(n: c_float) -> c_float; pub fn tanf(n: c_float) -> c_float; pub fn tanhf(n: c_float) -> c_float; pub fn tgammaf(n: c_float) -> c_float; /*#[cfg(unix)] pub fn lgammaf_r(n: c_float, sign: &mut c_int) -> c_float; #[cfg(windows)] #[link_name="__lgammaf_r"] pub fn lgammaf_r(n: c_float, sign: &mut c_int) -> c_float;*/ } } #[no_mangle] pub static mut NOCMD_ENABLED: bool = false; #[no_mangle] pub static mut REAL_INIT: *const () = 0 as *const(); #[no_mangle] pub static mut REAL_CREATEMOVE: *const () = 0 as *const (); #[no_mangle] pub static mut REAL_EXTRAMOUSESAMPLE: *const () = 0 as *const (); #[no_mangle] pub static mut REAL_RUNCOMMAND: *const () = 0 as *const (); #[no_mangle] pub static mut REAL_SERVERCMDKEYVALUES: *const () = 0 as *const (); #[no_mangle] pub static mut REAL_NETCHANNEL_SENDDATAGRAM: *const () = 0 as *const (); #[no_mangle] pub static mut CINPUT_PTR: *mut sdk::CInput = 0 as *mut sdk::CInput; struct CString(*const libc::c_char); impl CString { pub fn new(src: &'static [u8]) -> Option<CString> { let slice = src.repr(); if unsafe { *((slice.data as uint + (slice.len - 1)) as *const u8) == 0 } { Some(CString(slice.data as *const libc::c_char)) } else { None } } pub unsafe fn new_raw(src: *const u8) -> CString { CString(src as *const libc::c_char) } } #[no_mangle] pub extern "C" fn rainstorm_getivengineclient() -> sdk::raw::IVEngineClientPtr { unsafe { (*(cheats::CHEAT_MANAGER)).get_gamepointers().ivengineclient.get_ptr() } } pub struct GamePointers { ivengineclient: sdk::IVEngineClient, icliententitylist: sdk::IClientEntityList, ibaseclientdll: sdk::IBaseClientDLL, ienginetrace: sdk::IEngineTrace, appsysfactory: Option<sdk::AppSysFactory>, ivmodelinfo: sdk::IVModelInfo, icvar: Option<sdk::ICvar>, iuniformrandomstream: sdk::IUniformRandomStream, globals: Option<*mut sdk::CGlobalVarsBase> } impl GamePointers { pub fn load() -> GamePointers { log!("Loading GamePointers...\n"); GamePointers { ivengineclient: sdk::get_ivengineclient(), ibaseclientdll: sdk::get_ibaseclientdll(), icliententitylist: sdk::get_icliententitylist(), ienginetrace: sdk::get_ienginetrace(), ivmodelinfo: sdk::get_ivmodelinfo(), appsysfactory: None, icvar: None, iuniformrandomstream: sdk::get_iuniformrandomstream(), globals: None } } } pub unsafe fn locate_cinput() -> Option<*mut sdk::CInput> { let start_addr = REAL_CREATEMOVE as *const (); log!("Locating CInput from CreateMove at {}\n", start_addr); let result = utils::search_memory(start_addr, 100, &[0x8B, 0x0D]); //let result = utils::search_memory(((result1 as uint) + 2) as *const (), 100, &[0x8B, 0x0D]); match result { Some(ptr) => { let load_instruction_operand = ((ptr as uint) + 2) as *const *const *mut sdk::CInput; log!("CInput load found at {}\n", load_instruction_operand); let cinput_ptr_ptr = *load_instruction_operand; log!("CInput pointer: {}\n", cinput_ptr_ptr); log!("CInput found at {}\n", *cinput_ptr_ptr); Some((*cinput_ptr_ptr)) }, None => { log!("CInput not found?!?\n"); None } } } #[no_mangle] pub unsafe extern "C" fn rainstorm_preinithook(app_sys_factory: sdk::AppSysFactoryPtr, _physics_factory: *mut (), globals: *mut sdk::CGlobalVarsBase) { log!("pre-init hook running\n"); if cheats::CHEAT_MANAGER.is_not_null() { (*cheats::CHEAT_MANAGER).preinit(app_sys_factory, globals); } else { quit!("Cheat manager not found!\n"); }; } #[no_mangle] pub unsafe extern "C" fn rainstorm_postinithook() { log!("Post-init hook running...\n"); if cheats::CHEAT_MANAGER.is_not_null() { (*cheats::CHEAT_MANAGER).postinit(); } else { log!("Cheat manager not found!\n"); libc::exit(1); }; } #[no_mangle] pub unsafe extern "C" fn rainstorm_pre_createmove(sequence_number: *mut libc::c_int, input_sample_frametime: *mut libc::c_float, active: *mut bool) { if cheats::CHEAT_MANAGER.is_not_null() { (*cheats::CHEAT_MANAGER).pre_createmove(sequence_number, input_sample_frametime, active); } else { quit!("Cheat manager not found!\n"); }; } #[no_mangle] pub unsafe extern "C" fn rainstorm_process_usercmd(cmd: &mut sdk::CUserCmd) { if cheats::CHEAT_MANAGER.is_not_null() { maybe_hook_inetchannel((*cheats::CHEAT_MANAGER).get_gamepointers()); (*cheats::CHEAT_MANAGER).process_usercmd(cmd); } else { quit!("Cheat manager not found!\n"); };
#[no_mangle] pub unsafe extern "C" fn rainstorm_extramousesample(input_sample_frametime: libc::c_float, active: bool) { if cheats::CHEAT_MANAGER.is_not_null() { (*cheats::CHEAT_MANAGER).extramousesample(input_sample_frametime, active); } else { quit!("Cheat manager not found!\n"); }; } #[no_mangle] pub extern "C" fn rainstorm_command_cb(c_arguments: *const libc::c_char) { let arguments_str = unsafe { core::str::raw::c_str_to_static_slice(c_arguments) }; log!("Command callback: {}\n", arguments_str); let mut parts_iter = arguments_str.split(' '); let command = parts_iter.next().expect("No command type specified!"); let parts: collections::Vec<&str> = parts_iter.collect(); unsafe { if cheats::CHEAT_MANAGER.is_not_null() { (*cheats::CHEAT_MANAGER).handle_command(command, parts.as_slice()); } } } #[no_mangle] pub extern "C" fn rainstorm_init(log_fd: libc::c_int, hooked_init_trampoline: *const (), hooked_createmove_trampoline: *const (), hooked_extramousesample_trampoline: *const (), hooked_runcommand_trampoline: *const ()) { unsafe { let _ = logging::set_fd(log_fd).unwrap(); } log!("Rainstorm starting up!\n"); cheats::cheatmgr_setup(); unsafe { let mut ibaseclientdll_hooker = vmthook::VMTHooker::new((*cheats::CHEAT_MANAGER).get_gamepointers().ibaseclientdll.get_ptr().to_uint() as *mut *const ()); REAL_INIT = ibaseclientdll_hooker.get_orig_method(0); REAL_CREATEMOVE = ibaseclientdll_hooker.get_orig_method(21); REAL_EXTRAMOUSESAMPLE = ibaseclientdll_hooker.get_orig_method(22); ibaseclientdll_hooker.hook(0, hooked_init_trampoline); ibaseclientdll_hooker.hook(21, hooked_createmove_trampoline); ibaseclientdll_hooker.hook(22, hooked_extramousesample_trampoline); // let mut ivengineclient_hooker = vmthook::VMTHooker::new((*cheats::CHEAT_MANAGER).get_gamepointers().ivengineclient.get_ptr().to_uint() as *mut *const ()); // REAL_SERVERCMDKEYVALUES = ivengineclient_hooker.get_orig_method(185); // ivengineclient_hooker.hook(185, sdk::raw::get_hooked_servercmdkeyvalues()); CINPUT_PTR = locate_cinput().expect("Failed to locate CInput pointer (signature not found)"); let mut hooker = vmthook::VMTHooker::new(CINPUT_PTR as *mut *const ()); hooker.hook(8, sdk::get_hooked_getusercmd()); let mut iprediction_hooker = vmthook::VMTHooker::new(sdk::raw::getptr_iprediction().to_uint() as *mut *const ()); REAL_RUNCOMMAND = iprediction_hooker.get_orig_method(17); iprediction_hooker.hook(17, sdk::raw::get_hooked_runcommand()); }; } /// If we haven't seen this INetChannel before, hook it. fn maybe_hook_inetchannel(ptrs: &GamePointers) { static mut LAST_NETCHANNEL: Option<sdk::raw::INetChannelPtr> = None; unsafe { let inetchannel = sdk::raw::get_current_inetchannel(ptrs.ivengineclient.get_ptr()); //log!("chan: {}\n", inetchannel.to_uint()); let is_new_channel = match LAST_NETCHANNEL { Some(last) => { inetchannel!= last }, None => true }; LAST_NETCHANNEL = Some(inetchannel); if!is_new_channel { //log!("Not patching old netchannel"); return; } let mut hooker = vmthook::VMTHooker::new(inetchannel.to_uint() as *mut *const ()); REAL_NETCHANNEL_SENDDATAGRAM = hooker.get_orig_method(46); hooker.hook(46, ::sdk::raw::get_netchannel_senddatagram_trampoline().to_uint() as *const ()); log!("senddatagram: {}\n", hooker.get_orig_method(46)); }; } #[lang = "stack_exhausted"] extern fn stack_exhausted() {} #[lang = "eh_personality"] extern fn eh_personality() {} #[lang = "begin_unwind"] extern fn begin_unwind(fmt: &core::fmt::Arguments, file: &str, line: uint) ->! { log!("Failed at line {} of {}!\n", line, file); let _ = logging::log_fmt(fmt).ok(); // if we fail here, god help us unsafe { libc::exit(42); } } #[allow(non_snake_case_functions)] #[no_mangle] pub extern "C" fn _imp___onexit() { } #[no_mangle] pub extern "C" fn __dllonexit() { } #[no_mangle] pub extern "C" fn __setusermatherr() { }
}
random_line_split
rainstorm.rs
#![feature(macro_rules, intrinsics, lang_items, globs)] #![no_std] extern crate libc; extern crate core; extern crate alloc; extern crate collections; extern crate rand; pub use core::prelude::*; pub use cheats::{Cheat, CheatManager}; pub use alloc::owned::Box; pub use collections::Vec; use core::raw::Repr; mod logging; pub mod sdk; mod vmthook; pub mod utils; mod cheats; mod std { pub use core::fmt; //lol pub use core::option; pub use core::num; } #[allow(dead_code)] pub mod cmath { use libc::{c_float, c_int}; #[link_name = "m"] extern { pub fn acosf(n: c_float) -> c_float; pub fn asinf(n: c_float) -> c_float; pub fn atanf(n: c_float) -> c_float; pub fn atan2f(a: c_float, b: c_float) -> c_float; pub fn cbrtf(n: c_float) -> c_float; pub fn coshf(n: c_float) -> c_float; pub fn erff(n: c_float) -> c_float; pub fn erfcf(n: c_float) -> c_float; pub fn expm1f(n: c_float) -> c_float; pub fn fdimf(a: c_float, b: c_float) -> c_float; pub fn frexpf(n: c_float, value: &mut c_int) -> c_float; pub fn fmaxf(a: c_float, b: c_float) -> c_float; pub fn fminf(a: c_float, b: c_float) -> c_float; pub fn fmodf(a: c_float, b: c_float) -> c_float; pub fn nextafterf(x: c_float, y: c_float) -> c_float; pub fn hypotf(x: c_float, y: c_float) -> c_float; pub fn ldexpf(x: c_float, n: c_int) -> c_float; pub fn logbf(n: c_float) -> c_float; pub fn log1pf(n: c_float) -> c_float; pub fn ilogbf(n: c_float) -> c_int; pub fn modff(n: c_float, iptr: &mut c_float) -> c_float; pub fn sinhf(n: c_float) -> c_float; pub fn tanf(n: c_float) -> c_float; pub fn tanhf(n: c_float) -> c_float; pub fn tgammaf(n: c_float) -> c_float; /*#[cfg(unix)] pub fn lgammaf_r(n: c_float, sign: &mut c_int) -> c_float; #[cfg(windows)] #[link_name="__lgammaf_r"] pub fn lgammaf_r(n: c_float, sign: &mut c_int) -> c_float;*/ } } #[no_mangle] pub static mut NOCMD_ENABLED: bool = false; #[no_mangle] pub static mut REAL_INIT: *const () = 0 as *const(); #[no_mangle] pub static mut REAL_CREATEMOVE: *const () = 0 as *const (); #[no_mangle] pub static mut REAL_EXTRAMOUSESAMPLE: *const () = 0 as *const (); #[no_mangle] pub static mut REAL_RUNCOMMAND: *const () = 0 as *const (); #[no_mangle] pub static mut REAL_SERVERCMDKEYVALUES: *const () = 0 as *const (); #[no_mangle] pub static mut REAL_NETCHANNEL_SENDDATAGRAM: *const () = 0 as *const (); #[no_mangle] pub static mut CINPUT_PTR: *mut sdk::CInput = 0 as *mut sdk::CInput; struct CString(*const libc::c_char); impl CString { pub fn new(src: &'static [u8]) -> Option<CString> { let slice = src.repr(); if unsafe { *((slice.data as uint + (slice.len - 1)) as *const u8) == 0 } { Some(CString(slice.data as *const libc::c_char)) } else { None } } pub unsafe fn new_raw(src: *const u8) -> CString { CString(src as *const libc::c_char) } } #[no_mangle] pub extern "C" fn rainstorm_getivengineclient() -> sdk::raw::IVEngineClientPtr { unsafe { (*(cheats::CHEAT_MANAGER)).get_gamepointers().ivengineclient.get_ptr() } } pub struct GamePointers { ivengineclient: sdk::IVEngineClient, icliententitylist: sdk::IClientEntityList, ibaseclientdll: sdk::IBaseClientDLL, ienginetrace: sdk::IEngineTrace, appsysfactory: Option<sdk::AppSysFactory>, ivmodelinfo: sdk::IVModelInfo, icvar: Option<sdk::ICvar>, iuniformrandomstream: sdk::IUniformRandomStream, globals: Option<*mut sdk::CGlobalVarsBase> } impl GamePointers { pub fn load() -> GamePointers { log!("Loading GamePointers...\n"); GamePointers { ivengineclient: sdk::get_ivengineclient(), ibaseclientdll: sdk::get_ibaseclientdll(), icliententitylist: sdk::get_icliententitylist(), ienginetrace: sdk::get_ienginetrace(), ivmodelinfo: sdk::get_ivmodelinfo(), appsysfactory: None, icvar: None, iuniformrandomstream: sdk::get_iuniformrandomstream(), globals: None } } } pub unsafe fn locate_cinput() -> Option<*mut sdk::CInput> { let start_addr = REAL_CREATEMOVE as *const (); log!("Locating CInput from CreateMove at {}\n", start_addr); let result = utils::search_memory(start_addr, 100, &[0x8B, 0x0D]); //let result = utils::search_memory(((result1 as uint) + 2) as *const (), 100, &[0x8B, 0x0D]); match result { Some(ptr) => { let load_instruction_operand = ((ptr as uint) + 2) as *const *const *mut sdk::CInput; log!("CInput load found at {}\n", load_instruction_operand); let cinput_ptr_ptr = *load_instruction_operand; log!("CInput pointer: {}\n", cinput_ptr_ptr); log!("CInput found at {}\n", *cinput_ptr_ptr); Some((*cinput_ptr_ptr)) }, None => { log!("CInput not found?!?\n"); None } } } #[no_mangle] pub unsafe extern "C" fn rainstorm_preinithook(app_sys_factory: sdk::AppSysFactoryPtr, _physics_factory: *mut (), globals: *mut sdk::CGlobalVarsBase) { log!("pre-init hook running\n"); if cheats::CHEAT_MANAGER.is_not_null() { (*cheats::CHEAT_MANAGER).preinit(app_sys_factory, globals); } else { quit!("Cheat manager not found!\n"); }; } #[no_mangle] pub unsafe extern "C" fn rainstorm_postinithook() { log!("Post-init hook running...\n"); if cheats::CHEAT_MANAGER.is_not_null() { (*cheats::CHEAT_MANAGER).postinit(); } else { log!("Cheat manager not found!\n"); libc::exit(1); }; } #[no_mangle] pub unsafe extern "C" fn rainstorm_pre_createmove(sequence_number: *mut libc::c_int, input_sample_frametime: *mut libc::c_float, active: *mut bool) { if cheats::CHEAT_MANAGER.is_not_null() { (*cheats::CHEAT_MANAGER).pre_createmove(sequence_number, input_sample_frametime, active); } else { quit!("Cheat manager not found!\n"); }; } #[no_mangle] pub unsafe extern "C" fn rainstorm_process_usercmd(cmd: &mut sdk::CUserCmd) { if cheats::CHEAT_MANAGER.is_not_null() { maybe_hook_inetchannel((*cheats::CHEAT_MANAGER).get_gamepointers()); (*cheats::CHEAT_MANAGER).process_usercmd(cmd); } else { quit!("Cheat manager not found!\n"); }; } #[no_mangle] pub unsafe extern "C" fn rainstorm_extramousesample(input_sample_frametime: libc::c_float, active: bool) { if cheats::CHEAT_MANAGER.is_not_null() { (*cheats::CHEAT_MANAGER).extramousesample(input_sample_frametime, active); } else { quit!("Cheat manager not found!\n"); }; } #[no_mangle] pub extern "C" fn rainstorm_command_cb(c_arguments: *const libc::c_char) { let arguments_str = unsafe { core::str::raw::c_str_to_static_slice(c_arguments) }; log!("Command callback: {}\n", arguments_str); let mut parts_iter = arguments_str.split(' '); let command = parts_iter.next().expect("No command type specified!"); let parts: collections::Vec<&str> = parts_iter.collect(); unsafe { if cheats::CHEAT_MANAGER.is_not_null() { (*cheats::CHEAT_MANAGER).handle_command(command, parts.as_slice()); } } } #[no_mangle] pub extern "C" fn rainstorm_init(log_fd: libc::c_int, hooked_init_trampoline: *const (), hooked_createmove_trampoline: *const (), hooked_extramousesample_trampoline: *const (), hooked_runcommand_trampoline: *const ()) { unsafe { let _ = logging::set_fd(log_fd).unwrap(); } log!("Rainstorm starting up!\n"); cheats::cheatmgr_setup(); unsafe { let mut ibaseclientdll_hooker = vmthook::VMTHooker::new((*cheats::CHEAT_MANAGER).get_gamepointers().ibaseclientdll.get_ptr().to_uint() as *mut *const ()); REAL_INIT = ibaseclientdll_hooker.get_orig_method(0); REAL_CREATEMOVE = ibaseclientdll_hooker.get_orig_method(21); REAL_EXTRAMOUSESAMPLE = ibaseclientdll_hooker.get_orig_method(22); ibaseclientdll_hooker.hook(0, hooked_init_trampoline); ibaseclientdll_hooker.hook(21, hooked_createmove_trampoline); ibaseclientdll_hooker.hook(22, hooked_extramousesample_trampoline); // let mut ivengineclient_hooker = vmthook::VMTHooker::new((*cheats::CHEAT_MANAGER).get_gamepointers().ivengineclient.get_ptr().to_uint() as *mut *const ()); // REAL_SERVERCMDKEYVALUES = ivengineclient_hooker.get_orig_method(185); // ivengineclient_hooker.hook(185, sdk::raw::get_hooked_servercmdkeyvalues()); CINPUT_PTR = locate_cinput().expect("Failed to locate CInput pointer (signature not found)"); let mut hooker = vmthook::VMTHooker::new(CINPUT_PTR as *mut *const ()); hooker.hook(8, sdk::get_hooked_getusercmd()); let mut iprediction_hooker = vmthook::VMTHooker::new(sdk::raw::getptr_iprediction().to_uint() as *mut *const ()); REAL_RUNCOMMAND = iprediction_hooker.get_orig_method(17); iprediction_hooker.hook(17, sdk::raw::get_hooked_runcommand()); }; } /// If we haven't seen this INetChannel before, hook it. fn maybe_hook_inetchannel(ptrs: &GamePointers) { static mut LAST_NETCHANNEL: Option<sdk::raw::INetChannelPtr> = None; unsafe { let inetchannel = sdk::raw::get_current_inetchannel(ptrs.ivengineclient.get_ptr()); //log!("chan: {}\n", inetchannel.to_uint()); let is_new_channel = match LAST_NETCHANNEL { Some(last) => { inetchannel!= last }, None => true }; LAST_NETCHANNEL = Some(inetchannel); if!is_new_channel { //log!("Not patching old netchannel"); return; } let mut hooker = vmthook::VMTHooker::new(inetchannel.to_uint() as *mut *const ()); REAL_NETCHANNEL_SENDDATAGRAM = hooker.get_orig_method(46); hooker.hook(46, ::sdk::raw::get_netchannel_senddatagram_trampoline().to_uint() as *const ()); log!("senddatagram: {}\n", hooker.get_orig_method(46)); }; } #[lang = "stack_exhausted"] extern fn stack_exhausted() {} #[lang = "eh_personality"] extern fn eh_personality() {} #[lang = "begin_unwind"] extern fn begin_unwind(fmt: &core::fmt::Arguments, file: &str, line: uint) ->!
#[allow(non_snake_case_functions)] #[no_mangle] pub extern "C" fn _imp___onexit() { } #[no_mangle] pub extern "C" fn __dllonexit() { } #[no_mangle] pub extern "C" fn __setusermatherr() { }
{ log!("Failed at line {} of {}!\n", line, file); let _ = logging::log_fmt(fmt).ok(); // if we fail here, god help us unsafe { libc::exit(42); } }
identifier_body
rainstorm.rs
#![feature(macro_rules, intrinsics, lang_items, globs)] #![no_std] extern crate libc; extern crate core; extern crate alloc; extern crate collections; extern crate rand; pub use core::prelude::*; pub use cheats::{Cheat, CheatManager}; pub use alloc::owned::Box; pub use collections::Vec; use core::raw::Repr; mod logging; pub mod sdk; mod vmthook; pub mod utils; mod cheats; mod std { pub use core::fmt; //lol pub use core::option; pub use core::num; } #[allow(dead_code)] pub mod cmath { use libc::{c_float, c_int}; #[link_name = "m"] extern { pub fn acosf(n: c_float) -> c_float; pub fn asinf(n: c_float) -> c_float; pub fn atanf(n: c_float) -> c_float; pub fn atan2f(a: c_float, b: c_float) -> c_float; pub fn cbrtf(n: c_float) -> c_float; pub fn coshf(n: c_float) -> c_float; pub fn erff(n: c_float) -> c_float; pub fn erfcf(n: c_float) -> c_float; pub fn expm1f(n: c_float) -> c_float; pub fn fdimf(a: c_float, b: c_float) -> c_float; pub fn frexpf(n: c_float, value: &mut c_int) -> c_float; pub fn fmaxf(a: c_float, b: c_float) -> c_float; pub fn fminf(a: c_float, b: c_float) -> c_float; pub fn fmodf(a: c_float, b: c_float) -> c_float; pub fn nextafterf(x: c_float, y: c_float) -> c_float; pub fn hypotf(x: c_float, y: c_float) -> c_float; pub fn ldexpf(x: c_float, n: c_int) -> c_float; pub fn logbf(n: c_float) -> c_float; pub fn log1pf(n: c_float) -> c_float; pub fn ilogbf(n: c_float) -> c_int; pub fn modff(n: c_float, iptr: &mut c_float) -> c_float; pub fn sinhf(n: c_float) -> c_float; pub fn tanf(n: c_float) -> c_float; pub fn tanhf(n: c_float) -> c_float; pub fn tgammaf(n: c_float) -> c_float; /*#[cfg(unix)] pub fn lgammaf_r(n: c_float, sign: &mut c_int) -> c_float; #[cfg(windows)] #[link_name="__lgammaf_r"] pub fn lgammaf_r(n: c_float, sign: &mut c_int) -> c_float;*/ } } #[no_mangle] pub static mut NOCMD_ENABLED: bool = false; #[no_mangle] pub static mut REAL_INIT: *const () = 0 as *const(); #[no_mangle] pub static mut REAL_CREATEMOVE: *const () = 0 as *const (); #[no_mangle] pub static mut REAL_EXTRAMOUSESAMPLE: *const () = 0 as *const (); #[no_mangle] pub static mut REAL_RUNCOMMAND: *const () = 0 as *const (); #[no_mangle] pub static mut REAL_SERVERCMDKEYVALUES: *const () = 0 as *const (); #[no_mangle] pub static mut REAL_NETCHANNEL_SENDDATAGRAM: *const () = 0 as *const (); #[no_mangle] pub static mut CINPUT_PTR: *mut sdk::CInput = 0 as *mut sdk::CInput; struct CString(*const libc::c_char); impl CString { pub fn new(src: &'static [u8]) -> Option<CString> { let slice = src.repr(); if unsafe { *((slice.data as uint + (slice.len - 1)) as *const u8) == 0 } { Some(CString(slice.data as *const libc::c_char)) } else { None } } pub unsafe fn new_raw(src: *const u8) -> CString { CString(src as *const libc::c_char) } } #[no_mangle] pub extern "C" fn rainstorm_getivengineclient() -> sdk::raw::IVEngineClientPtr { unsafe { (*(cheats::CHEAT_MANAGER)).get_gamepointers().ivengineclient.get_ptr() } } pub struct GamePointers { ivengineclient: sdk::IVEngineClient, icliententitylist: sdk::IClientEntityList, ibaseclientdll: sdk::IBaseClientDLL, ienginetrace: sdk::IEngineTrace, appsysfactory: Option<sdk::AppSysFactory>, ivmodelinfo: sdk::IVModelInfo, icvar: Option<sdk::ICvar>, iuniformrandomstream: sdk::IUniformRandomStream, globals: Option<*mut sdk::CGlobalVarsBase> } impl GamePointers { pub fn load() -> GamePointers { log!("Loading GamePointers...\n"); GamePointers { ivengineclient: sdk::get_ivengineclient(), ibaseclientdll: sdk::get_ibaseclientdll(), icliententitylist: sdk::get_icliententitylist(), ienginetrace: sdk::get_ienginetrace(), ivmodelinfo: sdk::get_ivmodelinfo(), appsysfactory: None, icvar: None, iuniformrandomstream: sdk::get_iuniformrandomstream(), globals: None } } } pub unsafe fn locate_cinput() -> Option<*mut sdk::CInput> { let start_addr = REAL_CREATEMOVE as *const (); log!("Locating CInput from CreateMove at {}\n", start_addr); let result = utils::search_memory(start_addr, 100, &[0x8B, 0x0D]); //let result = utils::search_memory(((result1 as uint) + 2) as *const (), 100, &[0x8B, 0x0D]); match result { Some(ptr) => { let load_instruction_operand = ((ptr as uint) + 2) as *const *const *mut sdk::CInput; log!("CInput load found at {}\n", load_instruction_operand); let cinput_ptr_ptr = *load_instruction_operand; log!("CInput pointer: {}\n", cinput_ptr_ptr); log!("CInput found at {}\n", *cinput_ptr_ptr); Some((*cinput_ptr_ptr)) }, None => { log!("CInput not found?!?\n"); None } } } #[no_mangle] pub unsafe extern "C" fn rainstorm_preinithook(app_sys_factory: sdk::AppSysFactoryPtr, _physics_factory: *mut (), globals: *mut sdk::CGlobalVarsBase) { log!("pre-init hook running\n"); if cheats::CHEAT_MANAGER.is_not_null() { (*cheats::CHEAT_MANAGER).preinit(app_sys_factory, globals); } else { quit!("Cheat manager not found!\n"); }; } #[no_mangle] pub unsafe extern "C" fn rainstorm_postinithook() { log!("Post-init hook running...\n"); if cheats::CHEAT_MANAGER.is_not_null() { (*cheats::CHEAT_MANAGER).postinit(); } else { log!("Cheat manager not found!\n"); libc::exit(1); }; } #[no_mangle] pub unsafe extern "C" fn rainstorm_pre_createmove(sequence_number: *mut libc::c_int, input_sample_frametime: *mut libc::c_float, active: *mut bool) { if cheats::CHEAT_MANAGER.is_not_null() { (*cheats::CHEAT_MANAGER).pre_createmove(sequence_number, input_sample_frametime, active); } else { quit!("Cheat manager not found!\n"); }; } #[no_mangle] pub unsafe extern "C" fn rainstorm_process_usercmd(cmd: &mut sdk::CUserCmd) { if cheats::CHEAT_MANAGER.is_not_null() { maybe_hook_inetchannel((*cheats::CHEAT_MANAGER).get_gamepointers()); (*cheats::CHEAT_MANAGER).process_usercmd(cmd); } else { quit!("Cheat manager not found!\n"); }; } #[no_mangle] pub unsafe extern "C" fn rainstorm_extramousesample(input_sample_frametime: libc::c_float, active: bool) { if cheats::CHEAT_MANAGER.is_not_null() { (*cheats::CHEAT_MANAGER).extramousesample(input_sample_frametime, active); } else { quit!("Cheat manager not found!\n"); }; } #[no_mangle] pub extern "C" fn
(c_arguments: *const libc::c_char) { let arguments_str = unsafe { core::str::raw::c_str_to_static_slice(c_arguments) }; log!("Command callback: {}\n", arguments_str); let mut parts_iter = arguments_str.split(' '); let command = parts_iter.next().expect("No command type specified!"); let parts: collections::Vec<&str> = parts_iter.collect(); unsafe { if cheats::CHEAT_MANAGER.is_not_null() { (*cheats::CHEAT_MANAGER).handle_command(command, parts.as_slice()); } } } #[no_mangle] pub extern "C" fn rainstorm_init(log_fd: libc::c_int, hooked_init_trampoline: *const (), hooked_createmove_trampoline: *const (), hooked_extramousesample_trampoline: *const (), hooked_runcommand_trampoline: *const ()) { unsafe { let _ = logging::set_fd(log_fd).unwrap(); } log!("Rainstorm starting up!\n"); cheats::cheatmgr_setup(); unsafe { let mut ibaseclientdll_hooker = vmthook::VMTHooker::new((*cheats::CHEAT_MANAGER).get_gamepointers().ibaseclientdll.get_ptr().to_uint() as *mut *const ()); REAL_INIT = ibaseclientdll_hooker.get_orig_method(0); REAL_CREATEMOVE = ibaseclientdll_hooker.get_orig_method(21); REAL_EXTRAMOUSESAMPLE = ibaseclientdll_hooker.get_orig_method(22); ibaseclientdll_hooker.hook(0, hooked_init_trampoline); ibaseclientdll_hooker.hook(21, hooked_createmove_trampoline); ibaseclientdll_hooker.hook(22, hooked_extramousesample_trampoline); // let mut ivengineclient_hooker = vmthook::VMTHooker::new((*cheats::CHEAT_MANAGER).get_gamepointers().ivengineclient.get_ptr().to_uint() as *mut *const ()); // REAL_SERVERCMDKEYVALUES = ivengineclient_hooker.get_orig_method(185); // ivengineclient_hooker.hook(185, sdk::raw::get_hooked_servercmdkeyvalues()); CINPUT_PTR = locate_cinput().expect("Failed to locate CInput pointer (signature not found)"); let mut hooker = vmthook::VMTHooker::new(CINPUT_PTR as *mut *const ()); hooker.hook(8, sdk::get_hooked_getusercmd()); let mut iprediction_hooker = vmthook::VMTHooker::new(sdk::raw::getptr_iprediction().to_uint() as *mut *const ()); REAL_RUNCOMMAND = iprediction_hooker.get_orig_method(17); iprediction_hooker.hook(17, sdk::raw::get_hooked_runcommand()); }; } /// If we haven't seen this INetChannel before, hook it. fn maybe_hook_inetchannel(ptrs: &GamePointers) { static mut LAST_NETCHANNEL: Option<sdk::raw::INetChannelPtr> = None; unsafe { let inetchannel = sdk::raw::get_current_inetchannel(ptrs.ivengineclient.get_ptr()); //log!("chan: {}\n", inetchannel.to_uint()); let is_new_channel = match LAST_NETCHANNEL { Some(last) => { inetchannel!= last }, None => true }; LAST_NETCHANNEL = Some(inetchannel); if!is_new_channel { //log!("Not patching old netchannel"); return; } let mut hooker = vmthook::VMTHooker::new(inetchannel.to_uint() as *mut *const ()); REAL_NETCHANNEL_SENDDATAGRAM = hooker.get_orig_method(46); hooker.hook(46, ::sdk::raw::get_netchannel_senddatagram_trampoline().to_uint() as *const ()); log!("senddatagram: {}\n", hooker.get_orig_method(46)); }; } #[lang = "stack_exhausted"] extern fn stack_exhausted() {} #[lang = "eh_personality"] extern fn eh_personality() {} #[lang = "begin_unwind"] extern fn begin_unwind(fmt: &core::fmt::Arguments, file: &str, line: uint) ->! { log!("Failed at line {} of {}!\n", line, file); let _ = logging::log_fmt(fmt).ok(); // if we fail here, god help us unsafe { libc::exit(42); } } #[allow(non_snake_case_functions)] #[no_mangle] pub extern "C" fn _imp___onexit() { } #[no_mangle] pub extern "C" fn __dllonexit() { } #[no_mangle] pub extern "C" fn __setusermatherr() { }
rainstorm_command_cb
identifier_name
rainstorm.rs
#![feature(macro_rules, intrinsics, lang_items, globs)] #![no_std] extern crate libc; extern crate core; extern crate alloc; extern crate collections; extern crate rand; pub use core::prelude::*; pub use cheats::{Cheat, CheatManager}; pub use alloc::owned::Box; pub use collections::Vec; use core::raw::Repr; mod logging; pub mod sdk; mod vmthook; pub mod utils; mod cheats; mod std { pub use core::fmt; //lol pub use core::option; pub use core::num; } #[allow(dead_code)] pub mod cmath { use libc::{c_float, c_int}; #[link_name = "m"] extern { pub fn acosf(n: c_float) -> c_float; pub fn asinf(n: c_float) -> c_float; pub fn atanf(n: c_float) -> c_float; pub fn atan2f(a: c_float, b: c_float) -> c_float; pub fn cbrtf(n: c_float) -> c_float; pub fn coshf(n: c_float) -> c_float; pub fn erff(n: c_float) -> c_float; pub fn erfcf(n: c_float) -> c_float; pub fn expm1f(n: c_float) -> c_float; pub fn fdimf(a: c_float, b: c_float) -> c_float; pub fn frexpf(n: c_float, value: &mut c_int) -> c_float; pub fn fmaxf(a: c_float, b: c_float) -> c_float; pub fn fminf(a: c_float, b: c_float) -> c_float; pub fn fmodf(a: c_float, b: c_float) -> c_float; pub fn nextafterf(x: c_float, y: c_float) -> c_float; pub fn hypotf(x: c_float, y: c_float) -> c_float; pub fn ldexpf(x: c_float, n: c_int) -> c_float; pub fn logbf(n: c_float) -> c_float; pub fn log1pf(n: c_float) -> c_float; pub fn ilogbf(n: c_float) -> c_int; pub fn modff(n: c_float, iptr: &mut c_float) -> c_float; pub fn sinhf(n: c_float) -> c_float; pub fn tanf(n: c_float) -> c_float; pub fn tanhf(n: c_float) -> c_float; pub fn tgammaf(n: c_float) -> c_float; /*#[cfg(unix)] pub fn lgammaf_r(n: c_float, sign: &mut c_int) -> c_float; #[cfg(windows)] #[link_name="__lgammaf_r"] pub fn lgammaf_r(n: c_float, sign: &mut c_int) -> c_float;*/ } } #[no_mangle] pub static mut NOCMD_ENABLED: bool = false; #[no_mangle] pub static mut REAL_INIT: *const () = 0 as *const(); #[no_mangle] pub static mut REAL_CREATEMOVE: *const () = 0 as *const (); #[no_mangle] pub static mut REAL_EXTRAMOUSESAMPLE: *const () = 0 as *const (); #[no_mangle] pub static mut REAL_RUNCOMMAND: *const () = 0 as *const (); #[no_mangle] pub static mut REAL_SERVERCMDKEYVALUES: *const () = 0 as *const (); #[no_mangle] pub static mut REAL_NETCHANNEL_SENDDATAGRAM: *const () = 0 as *const (); #[no_mangle] pub static mut CINPUT_PTR: *mut sdk::CInput = 0 as *mut sdk::CInput; struct CString(*const libc::c_char); impl CString { pub fn new(src: &'static [u8]) -> Option<CString> { let slice = src.repr(); if unsafe { *((slice.data as uint + (slice.len - 1)) as *const u8) == 0 } { Some(CString(slice.data as *const libc::c_char)) } else { None } } pub unsafe fn new_raw(src: *const u8) -> CString { CString(src as *const libc::c_char) } } #[no_mangle] pub extern "C" fn rainstorm_getivengineclient() -> sdk::raw::IVEngineClientPtr { unsafe { (*(cheats::CHEAT_MANAGER)).get_gamepointers().ivengineclient.get_ptr() } } pub struct GamePointers { ivengineclient: sdk::IVEngineClient, icliententitylist: sdk::IClientEntityList, ibaseclientdll: sdk::IBaseClientDLL, ienginetrace: sdk::IEngineTrace, appsysfactory: Option<sdk::AppSysFactory>, ivmodelinfo: sdk::IVModelInfo, icvar: Option<sdk::ICvar>, iuniformrandomstream: sdk::IUniformRandomStream, globals: Option<*mut sdk::CGlobalVarsBase> } impl GamePointers { pub fn load() -> GamePointers { log!("Loading GamePointers...\n"); GamePointers { ivengineclient: sdk::get_ivengineclient(), ibaseclientdll: sdk::get_ibaseclientdll(), icliententitylist: sdk::get_icliententitylist(), ienginetrace: sdk::get_ienginetrace(), ivmodelinfo: sdk::get_ivmodelinfo(), appsysfactory: None, icvar: None, iuniformrandomstream: sdk::get_iuniformrandomstream(), globals: None } } } pub unsafe fn locate_cinput() -> Option<*mut sdk::CInput> { let start_addr = REAL_CREATEMOVE as *const (); log!("Locating CInput from CreateMove at {}\n", start_addr); let result = utils::search_memory(start_addr, 100, &[0x8B, 0x0D]); //let result = utils::search_memory(((result1 as uint) + 2) as *const (), 100, &[0x8B, 0x0D]); match result { Some(ptr) => { let load_instruction_operand = ((ptr as uint) + 2) as *const *const *mut sdk::CInput; log!("CInput load found at {}\n", load_instruction_operand); let cinput_ptr_ptr = *load_instruction_operand; log!("CInput pointer: {}\n", cinput_ptr_ptr); log!("CInput found at {}\n", *cinput_ptr_ptr); Some((*cinput_ptr_ptr)) }, None => { log!("CInput not found?!?\n"); None } } } #[no_mangle] pub unsafe extern "C" fn rainstorm_preinithook(app_sys_factory: sdk::AppSysFactoryPtr, _physics_factory: *mut (), globals: *mut sdk::CGlobalVarsBase) { log!("pre-init hook running\n"); if cheats::CHEAT_MANAGER.is_not_null() { (*cheats::CHEAT_MANAGER).preinit(app_sys_factory, globals); } else { quit!("Cheat manager not found!\n"); }; } #[no_mangle] pub unsafe extern "C" fn rainstorm_postinithook() { log!("Post-init hook running...\n"); if cheats::CHEAT_MANAGER.is_not_null() { (*cheats::CHEAT_MANAGER).postinit(); } else { log!("Cheat manager not found!\n"); libc::exit(1); }; } #[no_mangle] pub unsafe extern "C" fn rainstorm_pre_createmove(sequence_number: *mut libc::c_int, input_sample_frametime: *mut libc::c_float, active: *mut bool) { if cheats::CHEAT_MANAGER.is_not_null()
else { quit!("Cheat manager not found!\n"); }; } #[no_mangle] pub unsafe extern "C" fn rainstorm_process_usercmd(cmd: &mut sdk::CUserCmd) { if cheats::CHEAT_MANAGER.is_not_null() { maybe_hook_inetchannel((*cheats::CHEAT_MANAGER).get_gamepointers()); (*cheats::CHEAT_MANAGER).process_usercmd(cmd); } else { quit!("Cheat manager not found!\n"); }; } #[no_mangle] pub unsafe extern "C" fn rainstorm_extramousesample(input_sample_frametime: libc::c_float, active: bool) { if cheats::CHEAT_MANAGER.is_not_null() { (*cheats::CHEAT_MANAGER).extramousesample(input_sample_frametime, active); } else { quit!("Cheat manager not found!\n"); }; } #[no_mangle] pub extern "C" fn rainstorm_command_cb(c_arguments: *const libc::c_char) { let arguments_str = unsafe { core::str::raw::c_str_to_static_slice(c_arguments) }; log!("Command callback: {}\n", arguments_str); let mut parts_iter = arguments_str.split(' '); let command = parts_iter.next().expect("No command type specified!"); let parts: collections::Vec<&str> = parts_iter.collect(); unsafe { if cheats::CHEAT_MANAGER.is_not_null() { (*cheats::CHEAT_MANAGER).handle_command(command, parts.as_slice()); } } } #[no_mangle] pub extern "C" fn rainstorm_init(log_fd: libc::c_int, hooked_init_trampoline: *const (), hooked_createmove_trampoline: *const (), hooked_extramousesample_trampoline: *const (), hooked_runcommand_trampoline: *const ()) { unsafe { let _ = logging::set_fd(log_fd).unwrap(); } log!("Rainstorm starting up!\n"); cheats::cheatmgr_setup(); unsafe { let mut ibaseclientdll_hooker = vmthook::VMTHooker::new((*cheats::CHEAT_MANAGER).get_gamepointers().ibaseclientdll.get_ptr().to_uint() as *mut *const ()); REAL_INIT = ibaseclientdll_hooker.get_orig_method(0); REAL_CREATEMOVE = ibaseclientdll_hooker.get_orig_method(21); REAL_EXTRAMOUSESAMPLE = ibaseclientdll_hooker.get_orig_method(22); ibaseclientdll_hooker.hook(0, hooked_init_trampoline); ibaseclientdll_hooker.hook(21, hooked_createmove_trampoline); ibaseclientdll_hooker.hook(22, hooked_extramousesample_trampoline); // let mut ivengineclient_hooker = vmthook::VMTHooker::new((*cheats::CHEAT_MANAGER).get_gamepointers().ivengineclient.get_ptr().to_uint() as *mut *const ()); // REAL_SERVERCMDKEYVALUES = ivengineclient_hooker.get_orig_method(185); // ivengineclient_hooker.hook(185, sdk::raw::get_hooked_servercmdkeyvalues()); CINPUT_PTR = locate_cinput().expect("Failed to locate CInput pointer (signature not found)"); let mut hooker = vmthook::VMTHooker::new(CINPUT_PTR as *mut *const ()); hooker.hook(8, sdk::get_hooked_getusercmd()); let mut iprediction_hooker = vmthook::VMTHooker::new(sdk::raw::getptr_iprediction().to_uint() as *mut *const ()); REAL_RUNCOMMAND = iprediction_hooker.get_orig_method(17); iprediction_hooker.hook(17, sdk::raw::get_hooked_runcommand()); }; } /// If we haven't seen this INetChannel before, hook it. fn maybe_hook_inetchannel(ptrs: &GamePointers) { static mut LAST_NETCHANNEL: Option<sdk::raw::INetChannelPtr> = None; unsafe { let inetchannel = sdk::raw::get_current_inetchannel(ptrs.ivengineclient.get_ptr()); //log!("chan: {}\n", inetchannel.to_uint()); let is_new_channel = match LAST_NETCHANNEL { Some(last) => { inetchannel!= last }, None => true }; LAST_NETCHANNEL = Some(inetchannel); if!is_new_channel { //log!("Not patching old netchannel"); return; } let mut hooker = vmthook::VMTHooker::new(inetchannel.to_uint() as *mut *const ()); REAL_NETCHANNEL_SENDDATAGRAM = hooker.get_orig_method(46); hooker.hook(46, ::sdk::raw::get_netchannel_senddatagram_trampoline().to_uint() as *const ()); log!("senddatagram: {}\n", hooker.get_orig_method(46)); }; } #[lang = "stack_exhausted"] extern fn stack_exhausted() {} #[lang = "eh_personality"] extern fn eh_personality() {} #[lang = "begin_unwind"] extern fn begin_unwind(fmt: &core::fmt::Arguments, file: &str, line: uint) ->! { log!("Failed at line {} of {}!\n", line, file); let _ = logging::log_fmt(fmt).ok(); // if we fail here, god help us unsafe { libc::exit(42); } } #[allow(non_snake_case_functions)] #[no_mangle] pub extern "C" fn _imp___onexit() { } #[no_mangle] pub extern "C" fn __dllonexit() { } #[no_mangle] pub extern "C" fn __setusermatherr() { }
{ (*cheats::CHEAT_MANAGER).pre_createmove(sequence_number, input_sample_frametime, active); }
conditional_block
cli.rs
// Copyright (c) 2016 Chef Software Inc. and/or applicable contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. pub mod setup { use std::io::{self, Write}; use std::path::Path; use std::process; use ansi_term::Colour::{Cyan, Green, White}; use hcore::crypto::SigKeyPair; use hcore::env; use analytics; use command; use config; use error::Result; pub fn start(cache_path: &Path, analytics_path: &Path) -> Result<()> { let mut generated_origin = false; println!(""); title("Habitat CLI Setup"); para("Welcome to hab setup. Let's get started."); heading("Set up a default origin"); para("Every package in Habitat belongs to an origin, which indicates the person or \ organization responsible for maintaining that package. Each origin also has \ a key used to cryptographically sign packages in that origin."); para("Selecting a default origin tells package building operations such as 'hab pkg \ build' what key should be used to sign the packages produced. If you do not \ set a default origin now, you will have to tell package building commands each \ time what origin to use."); para("For more information on origins and how they are used in building packages, \ please consult the docs at https://www.habitat.sh/docs/create-packages-overview/"); if try!(ask_default_origin()) { println!(""); para("Enter the name of your origin. If you plan to publish your packages publicly, \ we recommend that you select one that is not already in use on the Habitat \ build service found at https://app.habitat.sh/."); let origin = try!(prompt_origin()); try!(write_cli_config_origin(&origin)); println!(""); if is_origin_in_cache(&origin, cache_path) { para(&format!("You already have an origin key for {} created and installed. \ Great work!", &origin)); } else { heading("Create origin key pair"); para(&format!("It doesn't look like you have a signing key for the origin `{}'. \ Without it, you won't be able to build new packages successfully.", &origin)); para("You can either create a new signing key now, or, if you are building \ packages for an origin that already exists, ask the owner to give you the \ signing key."); para("For more information on the use of origin keys, please consult the \ documentation at https://www.habitat.sh/docs/concepts-keys/#origin-keys"); if try!(ask_create_origin(&origin))
else { para(&format!("You might want to create an origin key later with: `hab \ origin key generate {}'", &origin)); } } } else { para("Okay, maybe another time."); } heading("GitHub Access Token"); para("While you can build and run Habitat packages without sharing them on the public \ depot, doing so allows you to collaborate with the Habitat community. In addition, \ it is how you can perform continuous deployment with Habitat."); para("The depot uses GitHub authentication with an access token \ (https://help.github.com/articles/creating-an-access-token-for-command-line-use/)."); para("If you would like to share your packages on the depot, please enter your GitHub \ access token. Otherwise, just enter No."); para("For more information on sharing packages on the depot, please read the \ documentation at https://www.habitat.sh/docs/share-packages-overview/"); if try!(ask_default_auth_token()) { println!(""); para("Enter your GitHub access token."); let auth_token = try!(prompt_auth_token()); try!(write_cli_config_auth_token(&auth_token)); } else { para("Okay, maybe another time."); } heading("Analytics"); para("The `hab` command-line tool will optionally send anonymous usage data to Habitat's \ Google Analytics account. This is a strictly opt-in activity and no tracking will \ occur unless you respond affirmatively to the question below."); para("We collect this data to help improve Habitat's user experience. For example, we \ would like to know the category of tasks users are performing, and which ones they \ are having trouble with (e.g. mistyping command line arguments)."); para("To see what kinds of data are sent and how they are anonymized, please read more \ about our analytics here: https://www.habitat.sh/docs/about-analytics/"); if try!(ask_enable_analytics(analytics_path)) { try!(opt_in_analytics(analytics_path, generated_origin)); } else { try!(opt_out_analytics(analytics_path)); } heading("CLI Setup Complete"); para("That's all for now. Thanks for using Habitat!"); Ok(()) } fn ask_default_origin() -> Result<bool> { prompt_yes_no("Set up a default origin?", Some(true)) } fn ask_create_origin(origin: &str) -> Result<bool> { prompt_yes_no(&format!("Create an origin key for `{}'?", origin), Some(true)) } fn write_cli_config_origin(origin: &str) -> Result<()> { let mut config = try!(config::load()); config.origin = Some(origin.to_string()); config::save(&config) } fn write_cli_config_auth_token(auth_token: &str) -> Result<()> { let mut config = try!(config::load()); config.auth_token = Some(auth_token.to_string()); config::save(&config) } fn is_origin_in_cache(origin: &str, cache_path: &Path) -> bool { match SigKeyPair::get_latest_pair_for(origin, cache_path) { Ok(pair) => { match pair.secret() { Ok(_) => true, _ => false, } } _ => false, } } fn create_origin(origin: &str, cache_path: &Path) -> Result<()> { let result = command::origin::key::generate::start(&origin, cache_path); println!(""); result } fn prompt_origin() -> Result<String> { let config = try!(config::load()); let default = match config.origin { Some(o) => { para(&format!("You already have a default origin set up as `{}', but feel free \ to change it if you wish.", &o)); Some(o) } None => env::var("USER").ok(), }; prompt_ask("Default origin name", default.as_ref().map(|x| &**x)) } fn ask_default_auth_token() -> Result<bool> { prompt_yes_no("Set up a default GitHub access token?", Some(true)) } fn prompt_auth_token() -> Result<String> { let config = try!(config::load()); let default = match config.auth_token { Some(o) => { para("You already have a default auth token set up, but feel free to change it \ if you wish."); Some(o) } None => None, }; prompt_ask("GitHub access token", default.as_ref().map(|x| &**x)) } fn ask_enable_analytics(analytics_path: &Path) -> Result<bool> { let default = match analytics::is_opted_in(analytics_path) { Some(val) => Some(val), None => Some(true), }; prompt_yes_no("Enable analytics?", default) } fn opt_in_analytics(analytics_path: &Path, generated_origin: bool) -> Result<()> { let result = analytics::opt_in(analytics_path, generated_origin); println!(""); result } fn opt_out_analytics(analytics_path: &Path) -> Result<()> { let result = analytics::opt_out(analytics_path); println!(""); result } fn title(text: &str) { println!("{}", Green.bold().paint(text)); println!("{}\n", Green.bold().paint(format!("{:=<width$}", "", width = text.chars().count()))); } fn heading(text: &str) { println!("{}\n", Green.bold().paint(text)); } fn para(text: &str) { print_wrapped(text, 75, 2) } fn print_wrapped(text: &str, wrap_width: usize, left_indent: usize) { for line in text.split("\n\n") { let mut buffer = String::new(); let mut width = 0; for word in line.split_whitespace() { let wl = word.chars().count(); if (width + wl + 1) > (wrap_width - left_indent) { println!("{:<width$}{}", " ", buffer, width = left_indent); buffer.clear(); width = 0; } width = width + wl + 1; buffer.push_str(word); buffer.push(' '); } if!buffer.is_empty() { println!("{:<width$}{}", " ", buffer, width = left_indent); } println!(""); } } fn prompt_yes_no(question: &str, default: Option<bool>) -> Result<bool> { let choice = match default { Some(yes) => { if yes { format!("{}{}{}", White.paint("["), White.bold().paint("Yes"), White.paint("/no/quit]")) } else { format!("{}{}{}", White.paint("[yes/"), White.bold().paint("No"), White.paint("/quit]")) } } None => format!("{}", White.paint("[yes/no/quit]")), }; loop { try!(io::stdout().flush()); print!("{} {} ", Cyan.paint(question), choice); try!(io::stdout().flush()); let mut response = String::new(); try!(io::stdin().read_line(&mut response)); match response.trim().chars().next().unwrap_or('\n') { 'y' | 'Y' => return Ok(true), 'n' | 'N' => return Ok(false), 'q' | 'Q' => process::exit(0), '\n' => { match default { Some(default) => return Ok(default), None => continue, } } _ => continue, } } } fn prompt_ask(question: &str, default: Option<&str>) -> Result<String> { let choice = match default { Some(d) => { format!(" {}{}{}", White.paint("[default: "), White.bold().paint(d), White.paint("]")) } None => "".to_string(), }; loop { try!(io::stdout().flush()); print!("{}{} ", Cyan.paint(format!("{}:", question)), choice); try!(io::stdout().flush()); let mut response = String::new(); try!(io::stdin().read_line(&mut response)); if response.trim().is_empty() { match default { Some(d) => return Ok(d.to_string()), None => continue, } } return Ok(response.trim().to_string()); } } }
{ try!(create_origin(&origin, cache_path)); generated_origin = true; }
conditional_block
cli.rs
// Copyright (c) 2016 Chef Software Inc. and/or applicable contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. pub mod setup { use std::io::{self, Write}; use std::path::Path; use std::process; use ansi_term::Colour::{Cyan, Green, White}; use hcore::crypto::SigKeyPair; use hcore::env; use analytics; use command; use config; use error::Result; pub fn start(cache_path: &Path, analytics_path: &Path) -> Result<()> { let mut generated_origin = false; println!(""); title("Habitat CLI Setup"); para("Welcome to hab setup. Let's get started."); heading("Set up a default origin"); para("Every package in Habitat belongs to an origin, which indicates the person or \ organization responsible for maintaining that package. Each origin also has \ a key used to cryptographically sign packages in that origin."); para("Selecting a default origin tells package building operations such as 'hab pkg \ build' what key should be used to sign the packages produced. If you do not \ set a default origin now, you will have to tell package building commands each \ time what origin to use."); para("For more information on origins and how they are used in building packages, \ please consult the docs at https://www.habitat.sh/docs/create-packages-overview/"); if try!(ask_default_origin()) { println!(""); para("Enter the name of your origin. If you plan to publish your packages publicly, \ we recommend that you select one that is not already in use on the Habitat \ build service found at https://app.habitat.sh/."); let origin = try!(prompt_origin()); try!(write_cli_config_origin(&origin)); println!(""); if is_origin_in_cache(&origin, cache_path) { para(&format!("You already have an origin key for {} created and installed. \ Great work!", &origin)); } else { heading("Create origin key pair"); para(&format!("It doesn't look like you have a signing key for the origin `{}'. \ Without it, you won't be able to build new packages successfully.", &origin)); para("You can either create a new signing key now, or, if you are building \ packages for an origin that already exists, ask the owner to give you the \ signing key."); para("For more information on the use of origin keys, please consult the \ documentation at https://www.habitat.sh/docs/concepts-keys/#origin-keys"); if try!(ask_create_origin(&origin)) { try!(create_origin(&origin, cache_path)); generated_origin = true; } else { para(&format!("You might want to create an origin key later with: `hab \ origin key generate {}'", &origin)); } } } else { para("Okay, maybe another time."); } heading("GitHub Access Token"); para("While you can build and run Habitat packages without sharing them on the public \ depot, doing so allows you to collaborate with the Habitat community. In addition, \ it is how you can perform continuous deployment with Habitat."); para("The depot uses GitHub authentication with an access token \ (https://help.github.com/articles/creating-an-access-token-for-command-line-use/)."); para("If you would like to share your packages on the depot, please enter your GitHub \ access token. Otherwise, just enter No."); para("For more information on sharing packages on the depot, please read the \ documentation at https://www.habitat.sh/docs/share-packages-overview/"); if try!(ask_default_auth_token()) { println!(""); para("Enter your GitHub access token."); let auth_token = try!(prompt_auth_token()); try!(write_cli_config_auth_token(&auth_token)); } else { para("Okay, maybe another time."); } heading("Analytics"); para("The `hab` command-line tool will optionally send anonymous usage data to Habitat's \ Google Analytics account. This is a strictly opt-in activity and no tracking will \ occur unless you respond affirmatively to the question below."); para("We collect this data to help improve Habitat's user experience. For example, we \ would like to know the category of tasks users are performing, and which ones they \ are having trouble with (e.g. mistyping command line arguments)."); para("To see what kinds of data are sent and how they are anonymized, please read more \ about our analytics here: https://www.habitat.sh/docs/about-analytics/"); if try!(ask_enable_analytics(analytics_path)) { try!(opt_in_analytics(analytics_path, generated_origin)); } else { try!(opt_out_analytics(analytics_path)); } heading("CLI Setup Complete"); para("That's all for now. Thanks for using Habitat!"); Ok(()) } fn ask_default_origin() -> Result<bool> { prompt_yes_no("Set up a default origin?", Some(true)) } fn ask_create_origin(origin: &str) -> Result<bool> { prompt_yes_no(&format!("Create an origin key for `{}'?", origin), Some(true)) } fn write_cli_config_origin(origin: &str) -> Result<()> { let mut config = try!(config::load()); config.origin = Some(origin.to_string()); config::save(&config) } fn write_cli_config_auth_token(auth_token: &str) -> Result<()> { let mut config = try!(config::load()); config.auth_token = Some(auth_token.to_string()); config::save(&config) } fn
(origin: &str, cache_path: &Path) -> bool { match SigKeyPair::get_latest_pair_for(origin, cache_path) { Ok(pair) => { match pair.secret() { Ok(_) => true, _ => false, } } _ => false, } } fn create_origin(origin: &str, cache_path: &Path) -> Result<()> { let result = command::origin::key::generate::start(&origin, cache_path); println!(""); result } fn prompt_origin() -> Result<String> { let config = try!(config::load()); let default = match config.origin { Some(o) => { para(&format!("You already have a default origin set up as `{}', but feel free \ to change it if you wish.", &o)); Some(o) } None => env::var("USER").ok(), }; prompt_ask("Default origin name", default.as_ref().map(|x| &**x)) } fn ask_default_auth_token() -> Result<bool> { prompt_yes_no("Set up a default GitHub access token?", Some(true)) } fn prompt_auth_token() -> Result<String> { let config = try!(config::load()); let default = match config.auth_token { Some(o) => { para("You already have a default auth token set up, but feel free to change it \ if you wish."); Some(o) } None => None, }; prompt_ask("GitHub access token", default.as_ref().map(|x| &**x)) } fn ask_enable_analytics(analytics_path: &Path) -> Result<bool> { let default = match analytics::is_opted_in(analytics_path) { Some(val) => Some(val), None => Some(true), }; prompt_yes_no("Enable analytics?", default) } fn opt_in_analytics(analytics_path: &Path, generated_origin: bool) -> Result<()> { let result = analytics::opt_in(analytics_path, generated_origin); println!(""); result } fn opt_out_analytics(analytics_path: &Path) -> Result<()> { let result = analytics::opt_out(analytics_path); println!(""); result } fn title(text: &str) { println!("{}", Green.bold().paint(text)); println!("{}\n", Green.bold().paint(format!("{:=<width$}", "", width = text.chars().count()))); } fn heading(text: &str) { println!("{}\n", Green.bold().paint(text)); } fn para(text: &str) { print_wrapped(text, 75, 2) } fn print_wrapped(text: &str, wrap_width: usize, left_indent: usize) { for line in text.split("\n\n") { let mut buffer = String::new(); let mut width = 0; for word in line.split_whitespace() { let wl = word.chars().count(); if (width + wl + 1) > (wrap_width - left_indent) { println!("{:<width$}{}", " ", buffer, width = left_indent); buffer.clear(); width = 0; } width = width + wl + 1; buffer.push_str(word); buffer.push(' '); } if!buffer.is_empty() { println!("{:<width$}{}", " ", buffer, width = left_indent); } println!(""); } } fn prompt_yes_no(question: &str, default: Option<bool>) -> Result<bool> { let choice = match default { Some(yes) => { if yes { format!("{}{}{}", White.paint("["), White.bold().paint("Yes"), White.paint("/no/quit]")) } else { format!("{}{}{}", White.paint("[yes/"), White.bold().paint("No"), White.paint("/quit]")) } } None => format!("{}", White.paint("[yes/no/quit]")), }; loop { try!(io::stdout().flush()); print!("{} {} ", Cyan.paint(question), choice); try!(io::stdout().flush()); let mut response = String::new(); try!(io::stdin().read_line(&mut response)); match response.trim().chars().next().unwrap_or('\n') { 'y' | 'Y' => return Ok(true), 'n' | 'N' => return Ok(false), 'q' | 'Q' => process::exit(0), '\n' => { match default { Some(default) => return Ok(default), None => continue, } } _ => continue, } } } fn prompt_ask(question: &str, default: Option<&str>) -> Result<String> { let choice = match default { Some(d) => { format!(" {}{}{}", White.paint("[default: "), White.bold().paint(d), White.paint("]")) } None => "".to_string(), }; loop { try!(io::stdout().flush()); print!("{}{} ", Cyan.paint(format!("{}:", question)), choice); try!(io::stdout().flush()); let mut response = String::new(); try!(io::stdin().read_line(&mut response)); if response.trim().is_empty() { match default { Some(d) => return Ok(d.to_string()), None => continue, } } return Ok(response.trim().to_string()); } } }
is_origin_in_cache
identifier_name
cli.rs
// Copyright (c) 2016 Chef Software Inc. and/or applicable contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. pub mod setup { use std::io::{self, Write}; use std::path::Path; use std::process; use ansi_term::Colour::{Cyan, Green, White}; use hcore::crypto::SigKeyPair; use hcore::env; use analytics; use command; use config; use error::Result; pub fn start(cache_path: &Path, analytics_path: &Path) -> Result<()> { let mut generated_origin = false; println!(""); title("Habitat CLI Setup"); para("Welcome to hab setup. Let's get started."); heading("Set up a default origin"); para("Every package in Habitat belongs to an origin, which indicates the person or \ organization responsible for maintaining that package. Each origin also has \ a key used to cryptographically sign packages in that origin."); para("Selecting a default origin tells package building operations such as 'hab pkg \ build' what key should be used to sign the packages produced. If you do not \ set a default origin now, you will have to tell package building commands each \ time what origin to use."); para("For more information on origins and how they are used in building packages, \ please consult the docs at https://www.habitat.sh/docs/create-packages-overview/"); if try!(ask_default_origin()) { println!(""); para("Enter the name of your origin. If you plan to publish your packages publicly, \ we recommend that you select one that is not already in use on the Habitat \ build service found at https://app.habitat.sh/."); let origin = try!(prompt_origin()); try!(write_cli_config_origin(&origin)); println!(""); if is_origin_in_cache(&origin, cache_path) { para(&format!("You already have an origin key for {} created and installed. \ Great work!", &origin)); } else { heading("Create origin key pair"); para(&format!("It doesn't look like you have a signing key for the origin `{}'. \ Without it, you won't be able to build new packages successfully.", &origin)); para("You can either create a new signing key now, or, if you are building \ packages for an origin that already exists, ask the owner to give you the \ signing key."); para("For more information on the use of origin keys, please consult the \ documentation at https://www.habitat.sh/docs/concepts-keys/#origin-keys"); if try!(ask_create_origin(&origin)) { try!(create_origin(&origin, cache_path)); generated_origin = true; } else { para(&format!("You might want to create an origin key later with: `hab \ origin key generate {}'", &origin)); } } } else { para("Okay, maybe another time."); } heading("GitHub Access Token"); para("While you can build and run Habitat packages without sharing them on the public \ depot, doing so allows you to collaborate with the Habitat community. In addition, \ it is how you can perform continuous deployment with Habitat."); para("The depot uses GitHub authentication with an access token \ (https://help.github.com/articles/creating-an-access-token-for-command-line-use/)."); para("If you would like to share your packages on the depot, please enter your GitHub \ access token. Otherwise, just enter No."); para("For more information on sharing packages on the depot, please read the \ documentation at https://www.habitat.sh/docs/share-packages-overview/"); if try!(ask_default_auth_token()) { println!(""); para("Enter your GitHub access token."); let auth_token = try!(prompt_auth_token()); try!(write_cli_config_auth_token(&auth_token)); } else { para("Okay, maybe another time."); } heading("Analytics"); para("The `hab` command-line tool will optionally send anonymous usage data to Habitat's \ Google Analytics account. This is a strictly opt-in activity and no tracking will \ occur unless you respond affirmatively to the question below."); para("We collect this data to help improve Habitat's user experience. For example, we \ would like to know the category of tasks users are performing, and which ones they \ are having trouble with (e.g. mistyping command line arguments)."); para("To see what kinds of data are sent and how they are anonymized, please read more \ about our analytics here: https://www.habitat.sh/docs/about-analytics/"); if try!(ask_enable_analytics(analytics_path)) { try!(opt_in_analytics(analytics_path, generated_origin)); } else { try!(opt_out_analytics(analytics_path)); } heading("CLI Setup Complete"); para("That's all for now. Thanks for using Habitat!"); Ok(()) } fn ask_default_origin() -> Result<bool> { prompt_yes_no("Set up a default origin?", Some(true)) } fn ask_create_origin(origin: &str) -> Result<bool> { prompt_yes_no(&format!("Create an origin key for `{}'?", origin), Some(true)) } fn write_cli_config_origin(origin: &str) -> Result<()> { let mut config = try!(config::load()); config.origin = Some(origin.to_string()); config::save(&config) } fn write_cli_config_auth_token(auth_token: &str) -> Result<()> { let mut config = try!(config::load()); config.auth_token = Some(auth_token.to_string()); config::save(&config) } fn is_origin_in_cache(origin: &str, cache_path: &Path) -> bool { match SigKeyPair::get_latest_pair_for(origin, cache_path) { Ok(pair) => { match pair.secret() { Ok(_) => true, _ => false, } } _ => false, } } fn create_origin(origin: &str, cache_path: &Path) -> Result<()> { let result = command::origin::key::generate::start(&origin, cache_path); println!(""); result } fn prompt_origin() -> Result<String> { let config = try!(config::load()); let default = match config.origin { Some(o) => { para(&format!("You already have a default origin set up as `{}', but feel free \ to change it if you wish.", &o)); Some(o) } None => env::var("USER").ok(), }; prompt_ask("Default origin name", default.as_ref().map(|x| &**x)) } fn ask_default_auth_token() -> Result<bool> { prompt_yes_no("Set up a default GitHub access token?", Some(true)) } fn prompt_auth_token() -> Result<String> { let config = try!(config::load()); let default = match config.auth_token { Some(o) => { para("You already have a default auth token set up, but feel free to change it \ if you wish."); Some(o) } None => None, }; prompt_ask("GitHub access token", default.as_ref().map(|x| &**x)) } fn ask_enable_analytics(analytics_path: &Path) -> Result<bool> { let default = match analytics::is_opted_in(analytics_path) { Some(val) => Some(val), None => Some(true), }; prompt_yes_no("Enable analytics?", default) } fn opt_in_analytics(analytics_path: &Path, generated_origin: bool) -> Result<()> { let result = analytics::opt_in(analytics_path, generated_origin); println!(""); result } fn opt_out_analytics(analytics_path: &Path) -> Result<()> { let result = analytics::opt_out(analytics_path); println!(""); result } fn title(text: &str) { println!("{}", Green.bold().paint(text)); println!("{}\n", Green.bold().paint(format!("{:=<width$}", "", width = text.chars().count()))); } fn heading(text: &str) { println!("{}\n", Green.bold().paint(text)); } fn para(text: &str) { print_wrapped(text, 75, 2) } fn print_wrapped(text: &str, wrap_width: usize, left_indent: usize) { for line in text.split("\n\n") { let mut buffer = String::new(); let mut width = 0; for word in line.split_whitespace() { let wl = word.chars().count(); if (width + wl + 1) > (wrap_width - left_indent) { println!("{:<width$}{}", " ", buffer, width = left_indent); buffer.clear(); width = 0; } width = width + wl + 1; buffer.push_str(word); buffer.push(' '); } if!buffer.is_empty() { println!("{:<width$}{}", " ", buffer, width = left_indent); } println!(""); } } fn prompt_yes_no(question: &str, default: Option<bool>) -> Result<bool> { let choice = match default { Some(yes) => { if yes { format!("{}{}{}", White.paint("["), White.bold().paint("Yes"), White.paint("/no/quit]")) } else { format!("{}{}{}", White.paint("[yes/"), White.bold().paint("No"), White.paint("/quit]")) } } None => format!("{}", White.paint("[yes/no/quit]")), }; loop { try!(io::stdout().flush()); print!("{} {} ", Cyan.paint(question), choice); try!(io::stdout().flush());
try!(io::stdin().read_line(&mut response)); match response.trim().chars().next().unwrap_or('\n') { 'y' | 'Y' => return Ok(true), 'n' | 'N' => return Ok(false), 'q' | 'Q' => process::exit(0), '\n' => { match default { Some(default) => return Ok(default), None => continue, } } _ => continue, } } } fn prompt_ask(question: &str, default: Option<&str>) -> Result<String> { let choice = match default { Some(d) => { format!(" {}{}{}", White.paint("[default: "), White.bold().paint(d), White.paint("]")) } None => "".to_string(), }; loop { try!(io::stdout().flush()); print!("{}{} ", Cyan.paint(format!("{}:", question)), choice); try!(io::stdout().flush()); let mut response = String::new(); try!(io::stdin().read_line(&mut response)); if response.trim().is_empty() { match default { Some(d) => return Ok(d.to_string()), None => continue, } } return Ok(response.trim().to_string()); } } }
let mut response = String::new();
random_line_split
cli.rs
// Copyright (c) 2016 Chef Software Inc. and/or applicable contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. pub mod setup { use std::io::{self, Write}; use std::path::Path; use std::process; use ansi_term::Colour::{Cyan, Green, White}; use hcore::crypto::SigKeyPair; use hcore::env; use analytics; use command; use config; use error::Result; pub fn start(cache_path: &Path, analytics_path: &Path) -> Result<()> { let mut generated_origin = false; println!(""); title("Habitat CLI Setup"); para("Welcome to hab setup. Let's get started."); heading("Set up a default origin"); para("Every package in Habitat belongs to an origin, which indicates the person or \ organization responsible for maintaining that package. Each origin also has \ a key used to cryptographically sign packages in that origin."); para("Selecting a default origin tells package building operations such as 'hab pkg \ build' what key should be used to sign the packages produced. If you do not \ set a default origin now, you will have to tell package building commands each \ time what origin to use."); para("For more information on origins and how they are used in building packages, \ please consult the docs at https://www.habitat.sh/docs/create-packages-overview/"); if try!(ask_default_origin()) { println!(""); para("Enter the name of your origin. If you plan to publish your packages publicly, \ we recommend that you select one that is not already in use on the Habitat \ build service found at https://app.habitat.sh/."); let origin = try!(prompt_origin()); try!(write_cli_config_origin(&origin)); println!(""); if is_origin_in_cache(&origin, cache_path) { para(&format!("You already have an origin key for {} created and installed. \ Great work!", &origin)); } else { heading("Create origin key pair"); para(&format!("It doesn't look like you have a signing key for the origin `{}'. \ Without it, you won't be able to build new packages successfully.", &origin)); para("You can either create a new signing key now, or, if you are building \ packages for an origin that already exists, ask the owner to give you the \ signing key."); para("For more information on the use of origin keys, please consult the \ documentation at https://www.habitat.sh/docs/concepts-keys/#origin-keys"); if try!(ask_create_origin(&origin)) { try!(create_origin(&origin, cache_path)); generated_origin = true; } else { para(&format!("You might want to create an origin key later with: `hab \ origin key generate {}'", &origin)); } } } else { para("Okay, maybe another time."); } heading("GitHub Access Token"); para("While you can build and run Habitat packages without sharing them on the public \ depot, doing so allows you to collaborate with the Habitat community. In addition, \ it is how you can perform continuous deployment with Habitat."); para("The depot uses GitHub authentication with an access token \ (https://help.github.com/articles/creating-an-access-token-for-command-line-use/)."); para("If you would like to share your packages on the depot, please enter your GitHub \ access token. Otherwise, just enter No."); para("For more information on sharing packages on the depot, please read the \ documentation at https://www.habitat.sh/docs/share-packages-overview/"); if try!(ask_default_auth_token()) { println!(""); para("Enter your GitHub access token."); let auth_token = try!(prompt_auth_token()); try!(write_cli_config_auth_token(&auth_token)); } else { para("Okay, maybe another time."); } heading("Analytics"); para("The `hab` command-line tool will optionally send anonymous usage data to Habitat's \ Google Analytics account. This is a strictly opt-in activity and no tracking will \ occur unless you respond affirmatively to the question below."); para("We collect this data to help improve Habitat's user experience. For example, we \ would like to know the category of tasks users are performing, and which ones they \ are having trouble with (e.g. mistyping command line arguments)."); para("To see what kinds of data are sent and how they are anonymized, please read more \ about our analytics here: https://www.habitat.sh/docs/about-analytics/"); if try!(ask_enable_analytics(analytics_path)) { try!(opt_in_analytics(analytics_path, generated_origin)); } else { try!(opt_out_analytics(analytics_path)); } heading("CLI Setup Complete"); para("That's all for now. Thanks for using Habitat!"); Ok(()) } fn ask_default_origin() -> Result<bool> { prompt_yes_no("Set up a default origin?", Some(true)) } fn ask_create_origin(origin: &str) -> Result<bool> { prompt_yes_no(&format!("Create an origin key for `{}'?", origin), Some(true)) } fn write_cli_config_origin(origin: &str) -> Result<()> { let mut config = try!(config::load()); config.origin = Some(origin.to_string()); config::save(&config) } fn write_cli_config_auth_token(auth_token: &str) -> Result<()> { let mut config = try!(config::load()); config.auth_token = Some(auth_token.to_string()); config::save(&config) } fn is_origin_in_cache(origin: &str, cache_path: &Path) -> bool { match SigKeyPair::get_latest_pair_for(origin, cache_path) { Ok(pair) => { match pair.secret() { Ok(_) => true, _ => false, } } _ => false, } } fn create_origin(origin: &str, cache_path: &Path) -> Result<()> { let result = command::origin::key::generate::start(&origin, cache_path); println!(""); result } fn prompt_origin() -> Result<String> { let config = try!(config::load()); let default = match config.origin { Some(o) => { para(&format!("You already have a default origin set up as `{}', but feel free \ to change it if you wish.", &o)); Some(o) } None => env::var("USER").ok(), }; prompt_ask("Default origin name", default.as_ref().map(|x| &**x)) } fn ask_default_auth_token() -> Result<bool> { prompt_yes_no("Set up a default GitHub access token?", Some(true)) } fn prompt_auth_token() -> Result<String> { let config = try!(config::load()); let default = match config.auth_token { Some(o) => { para("You already have a default auth token set up, but feel free to change it \ if you wish."); Some(o) } None => None, }; prompt_ask("GitHub access token", default.as_ref().map(|x| &**x)) } fn ask_enable_analytics(analytics_path: &Path) -> Result<bool>
fn opt_in_analytics(analytics_path: &Path, generated_origin: bool) -> Result<()> { let result = analytics::opt_in(analytics_path, generated_origin); println!(""); result } fn opt_out_analytics(analytics_path: &Path) -> Result<()> { let result = analytics::opt_out(analytics_path); println!(""); result } fn title(text: &str) { println!("{}", Green.bold().paint(text)); println!("{}\n", Green.bold().paint(format!("{:=<width$}", "", width = text.chars().count()))); } fn heading(text: &str) { println!("{}\n", Green.bold().paint(text)); } fn para(text: &str) { print_wrapped(text, 75, 2) } fn print_wrapped(text: &str, wrap_width: usize, left_indent: usize) { for line in text.split("\n\n") { let mut buffer = String::new(); let mut width = 0; for word in line.split_whitespace() { let wl = word.chars().count(); if (width + wl + 1) > (wrap_width - left_indent) { println!("{:<width$}{}", " ", buffer, width = left_indent); buffer.clear(); width = 0; } width = width + wl + 1; buffer.push_str(word); buffer.push(' '); } if!buffer.is_empty() { println!("{:<width$}{}", " ", buffer, width = left_indent); } println!(""); } } fn prompt_yes_no(question: &str, default: Option<bool>) -> Result<bool> { let choice = match default { Some(yes) => { if yes { format!("{}{}{}", White.paint("["), White.bold().paint("Yes"), White.paint("/no/quit]")) } else { format!("{}{}{}", White.paint("[yes/"), White.bold().paint("No"), White.paint("/quit]")) } } None => format!("{}", White.paint("[yes/no/quit]")), }; loop { try!(io::stdout().flush()); print!("{} {} ", Cyan.paint(question), choice); try!(io::stdout().flush()); let mut response = String::new(); try!(io::stdin().read_line(&mut response)); match response.trim().chars().next().unwrap_or('\n') { 'y' | 'Y' => return Ok(true), 'n' | 'N' => return Ok(false), 'q' | 'Q' => process::exit(0), '\n' => { match default { Some(default) => return Ok(default), None => continue, } } _ => continue, } } } fn prompt_ask(question: &str, default: Option<&str>) -> Result<String> { let choice = match default { Some(d) => { format!(" {}{}{}", White.paint("[default: "), White.bold().paint(d), White.paint("]")) } None => "".to_string(), }; loop { try!(io::stdout().flush()); print!("{}{} ", Cyan.paint(format!("{}:", question)), choice); try!(io::stdout().flush()); let mut response = String::new(); try!(io::stdin().read_line(&mut response)); if response.trim().is_empty() { match default { Some(d) => return Ok(d.to_string()), None => continue, } } return Ok(response.trim().to_string()); } } }
{ let default = match analytics::is_opted_in(analytics_path) { Some(val) => Some(val), None => Some(true), }; prompt_yes_no("Enable analytics?", default) }
identifier_body
main.rs
#![allow(dead_code)] extern crate libc; extern crate time; extern crate rand; extern crate toml; extern crate serde_json; #[macro_use] extern crate serde_derive; extern crate colored; #[macro_use] extern crate prettytable; extern crate ctrlc; extern crate clap; use clap::{Arg, App}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; mod config; mod run; mod mutation; mod analysis; mod queue; mod test; mod stats; use run::buffered::{ find_one_fuzz_server, BufferedFuzzServerConfig }; use run::{ FuzzServer, Run }; const APP_NAME: &'static str = env!("CARGO_PKG_NAME"); const VERSION: &'static str = env!("CARGO_PKG_VERSION"); const AUTHOR: &'static str = env!("CARGO_PKG_AUTHORS"); const FPGA_DIR: &'static str = "/tmp/fpga"; const WORD_SIZE : usize = 8; #[derive(Debug)] struct Args { toml_config: String, print_queue: bool, print_total_cov: bool, skip_deterministic: bool, skip_non_deterministic: bool, random: bool, input_directory: Option<String>, output_directory: String, test_mode: bool, jqf: analysis::JQFLevel, fuzz_server_id: String, seed_cycles: usize, } fn main() { let matches = App::new(APP_NAME).version(VERSION).author(AUTHOR) .about("AFL-style fuzzer specialized for fuzzing RTL circuits.") .version_short("v") .arg(Arg::with_name("TOML") .help("TOML file describing the circuit being fuzzed") .required(true).index(1)) .arg(Arg::with_name("print_queue") .long("print-queue").short("q") .help("Prints queue content at the end of a fuzzing run.")) .arg(Arg::with_name("print_total_cov") .long("print-total-cov").short("c") .help("Prints the union coverage at the end of a fuzzing run.")) .arg(Arg::with_name("skip_deterministic") .long("skip-deterministic").short("d") .help("Skip all deterministic mutation strategies.")) .arg(Arg::with_name("skip_non_deterministic") .long("skip-non-deterministic").short("n") .help("Skip all non-deterministic mutation strategies.")) .arg(Arg::with_name("random") .long("random").short("r") .help("Generate independent random inputs instead of using the fuzzing algorithm.")) .arg(Arg::with_name("jqf_level") .long("jqf-level").short("j") .help("Select which level of JQF to apply.") .takes_value(true).possible_values(&["0", "1", "2"]) .default_value("2")) .arg(Arg::with_name("seed_cycles") .long("seed-cycles") .help("The starting seed consits of all zeros for N cycles.") .takes_value(true) .default_value("5")) .arg(Arg::with_name("input_directory") .long("input-directory").short("i").value_name("DIR") .takes_value(true) .help("The output directory of a previous run from which to resume.")) .arg(Arg::with_name("output_directory") .long("output-directory").short("o").value_name("DIR") .takes_value(true) .help("Used to log this session. Must be empty!") .required(true)) .arg(Arg::with_name("test_mode") .long("test-mode").short("t") .help("Test the fuzz server with known input/coverage pairs.")) .arg(Arg::with_name("fuzz_server_id") .long("server-id").short("s") .help("The id of the fuzz server isntance to connect to.") .takes_value(true).default_value("0")) .get_matches(); let args = Args { toml_config: matches.value_of("TOML").unwrap().to_string(), print_queue: matches.is_present("print_queue"), print_total_cov: matches.is_present("print_total_cov"), skip_deterministic: matches.is_present("skip_deterministic"), skip_non_deterministic: matches.is_present("skip_non_deterministic"), random: matches.is_present("random"), input_directory: matches.value_of("input_directory").map(|s| s.to_string()), output_directory: matches.value_of("output_directory").unwrap().to_string(), test_mode: matches.is_present("test_mode"), jqf: analysis::JQFLevel::from_arg(matches.value_of("jqf_level").unwrap()), fuzz_server_id: matches.value_of("fuzz_server_id").unwrap().to_string(), seed_cycles: matches.value_of("seed_cycles").unwrap().parse::<usize>().unwrap(), }; // "Ctrl + C" handling let canceled = Arc::new(AtomicBool::new(false)); let c = canceled.clone(); ctrlc::set_handler(move || { c.store(true, Ordering::SeqCst); }) .expect("Error setting Ctrl-C handler"); // load test config let config = config::Config::from_file(WORD_SIZE, &args.toml_config); let test_size = config.get_test_size(); config.print_header(); // test runner let srv_config = BufferedFuzzServerConfig { test_size : test_size, max_cycles : 200, test_buffer_size : 64 * 1024 * 16, coverage_buffer_size : 64 * 1024 * 16, buffer_count: 3, max_runs: 1024 * 16, }; println!("Test Buffer: {} KiB", srv_config.test_buffer_size / 1024); println!("Coverage Buffer: {} KiB", srv_config.coverage_buffer_size / 1024); println!("Max Inputs: {}", srv_config.test_buffer_size / 16 / 3); let server_dir = format!("{}/{}", FPGA_DIR, args.fuzz_server_id); let mut server = find_one_fuzz_server(&server_dir, srv_config).expect("failed to find a fuzz server"); if args.test_mode { test_mode(&mut server, &config); } else { fuzzer(args, canceled, config, test_size, &mut server); } } fn test_mode(server: &mut FuzzServer, config: &config::Config) { println!("⚠️ Test mode selected! ⚠️"); test::test_fuzz_server(server, config); } fn fuzzer(args: Args, canceled: Arc<AtomicBool>, config: config::Config, test_size: run::TestSize, server: &mut FuzzServer) { // starting seed let start_cycles = args.seed_cycles; let starting_seed = vec![0u8; test_size.input * start_cycles]; // analysis let ranges = config.gen_ranges(); //println!("ranges:]\n{:?}", ranges); let mut analysis = analysis::Analysis::new(test_size, ranges, args.jqf); let seed_coverage = fuzz_one(server, &starting_seed); let seed_analysis_res = analysis.run(start_cycles as u16, &seed_coverage); if seed_analysis_res.is_invalid { println!("❌ Invalid seed!"); } if!seed_analysis_res.is_interesting { println!("⚠️ Uninteresting seed! Might be 🐟!"); } // TODO: support multiple seeds // mutation let mut_config = mutation::MutationScheduleConfig { skip_deterministic: args.skip_deterministic, skip_non_deterministic: args.skip_non_deterministic, independent_random: args.random, }; if mut_config.independent_random { println!("⚠️ Mutation disabled. Generating independent random inputs! ⚠️"); } let mutations = mutation::MutationSchedule::initialize(mut_config, test_size, config.get_inputs()); // statistics let start_ts = get_time(); let mut statistics = stats::Stats::new(mutations.get_names(), start_ts.clone(), analysis.get_bitmap()); // queue let mut q = queue::Queue::create( &args.output_directory, &starting_seed, seed_analysis_res.new_cov, !seed_analysis_res.is_invalid, start_ts, config.to_json(), statistics.take_snapshot(), &seed_coverage); let max_entries = 1_000_000; let max_children = 100_000; // TODO: better mechanism to determine length of the havoc stage println!("fuzzing a maximum of {} queue entries", max_entries); for _ in 0..max_entries { let active_test = q.get_next_test(); let mut history = active_test.mutation_history; let mut new_runs : u64 = 0; q.print_entry_summary(active_test.id, &mutations); while let Some(mut mutator) = mutations.get_mutator(&mut history, &active_test.inputs) { // println!("running {} mutation", mutations.get_name(mutator.id())); let mut done = false; let mut start = 0; while!done { match server.run(&mut mutator, start) { Run::Done(runs, cycles) => { statistics.update_test_count(mutator.id().id, runs as u64, cycles); new_runs += runs as u64; done = true; } Run::Yield(ii) => { start = ii; } } while let Some(feedback) = server.pop_coverage() { let rr = analysis.run(feedback.cycles, &feedback.data); if rr.is_interesting { if rr.is_invalid
s >= max_children { break; } } q.return_test(active_test.id, history); q.save_latest(statistics.take_snapshot()); if canceled.load(Ordering::SeqCst) { println!("User interrupted fuzzing. Going to shut down...."); break; } } server.sync(); while let Some(feedback) = server.pop_coverage() { let rr = analysis.run(feedback.cycles, &feedback.data); if rr.is_interesting { if rr.is_invalid { println!("invalid input...."); } let (info, interesting_input) = server.get_info(feedback.id); let now = get_time(); statistics.update_new_discovery(info.mutator.id, now, analysis.get_bitmap()); q.add_new_test(interesting_input, info, rr.new_cov, !rr.is_invalid, now, statistics.take_snapshot(), &feedback.data); } } q.save_latest(statistics.take_snapshot()); // done with the main fuzzing part statistics.done(); // final bitmap let bitmap = analysis.get_bitmap(); // print inputs from queue if args.print_queue { println!("\n"); println!("Formated Inputs and Coverage!"); for entry in q.entries() { q.print_entry_summary(entry.id, &mutations); config.print_inputs(&entry.inputs); println!("Achieved Coverage:"); let coverage = fuzz_one(server, &entry.inputs); config.print_test_coverage(&coverage); println!("\n"); } } if args.print_total_cov { println!("Total Coverage:"); config.print_bitmap(&bitmap); } // print statistics print!("{}", statistics.get_final_snapshot().unwrap()); println!("Bitmap: {:?}", bitmap); } fn fuzz_one(server: &mut FuzzServer, input: &[u8]) -> Vec<u8> { let mut mutator = mutation::identity(input); if let Run::Done(count, _) = server.run(&mut mutator, 0) { assert_eq!(count, 1); } else { assert!(false); } server.sync(); let feedback = server.pop_coverage().expect("should get exactly one coverage back!"); feedback.data.to_vec() } fn get_time() -> std::time::Duration { let raw = time::get_time(); std::time::Duration::new(raw.sec as u64, raw.nsec as u32) }
{ println!("invalid input...."); } let (info, interesting_input) = server.get_info(feedback.id); let now = get_time(); statistics.update_new_discovery(info.mutator.id, now, analysis.get_bitmap()); q.add_new_test(interesting_input, info, rr.new_cov, !rr.is_invalid, now, statistics.take_snapshot(), &feedback.data); } } } if new_run
conditional_block
main.rs
#![allow(dead_code)] extern crate libc; extern crate time; extern crate rand; extern crate toml; extern crate serde_json; #[macro_use] extern crate serde_derive; extern crate colored; #[macro_use] extern crate prettytable; extern crate ctrlc; extern crate clap; use clap::{Arg, App}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; mod config; mod run; mod mutation; mod analysis; mod queue; mod test; mod stats; use run::buffered::{ find_one_fuzz_server, BufferedFuzzServerConfig }; use run::{ FuzzServer, Run }; const APP_NAME: &'static str = env!("CARGO_PKG_NAME"); const VERSION: &'static str = env!("CARGO_PKG_VERSION"); const AUTHOR: &'static str = env!("CARGO_PKG_AUTHORS"); const FPGA_DIR: &'static str = "/tmp/fpga"; const WORD_SIZE : usize = 8; #[derive(Debug)] struct Args { toml_config: String, print_queue: bool, print_total_cov: bool, skip_deterministic: bool, skip_non_deterministic: bool, random: bool, input_directory: Option<String>, output_directory: String, test_mode: bool, jqf: analysis::JQFLevel, fuzz_server_id: String, seed_cycles: usize, } fn main() { let matches = App::new(APP_NAME).version(VERSION).author(AUTHOR) .about("AFL-style fuzzer specialized for fuzzing RTL circuits.") .version_short("v") .arg(Arg::with_name("TOML") .help("TOML file describing the circuit being fuzzed") .required(true).index(1)) .arg(Arg::with_name("print_queue") .long("print-queue").short("q") .help("Prints queue content at the end of a fuzzing run.")) .arg(Arg::with_name("print_total_cov") .long("print-total-cov").short("c") .help("Prints the union coverage at the end of a fuzzing run.")) .arg(Arg::with_name("skip_deterministic") .long("skip-deterministic").short("d") .help("Skip all deterministic mutation strategies.")) .arg(Arg::with_name("skip_non_deterministic") .long("skip-non-deterministic").short("n") .help("Skip all non-deterministic mutation strategies.")) .arg(Arg::with_name("random") .long("random").short("r") .help("Generate independent random inputs instead of using the fuzzing algorithm.")) .arg(Arg::with_name("jqf_level") .long("jqf-level").short("j") .help("Select which level of JQF to apply.") .takes_value(true).possible_values(&["0", "1", "2"]) .default_value("2")) .arg(Arg::with_name("seed_cycles") .long("seed-cycles") .help("The starting seed consits of all zeros for N cycles.") .takes_value(true) .default_value("5")) .arg(Arg::with_name("input_directory") .long("input-directory").short("i").value_name("DIR") .takes_value(true) .help("The output directory of a previous run from which to resume.")) .arg(Arg::with_name("output_directory") .long("output-directory").short("o").value_name("DIR") .takes_value(true) .help("Used to log this session. Must be empty!") .required(true)) .arg(Arg::with_name("test_mode") .long("test-mode").short("t") .help("Test the fuzz server with known input/coverage pairs.")) .arg(Arg::with_name("fuzz_server_id") .long("server-id").short("s") .help("The id of the fuzz server isntance to connect to.") .takes_value(true).default_value("0")) .get_matches(); let args = Args { toml_config: matches.value_of("TOML").unwrap().to_string(), print_queue: matches.is_present("print_queue"), print_total_cov: matches.is_present("print_total_cov"), skip_deterministic: matches.is_present("skip_deterministic"), skip_non_deterministic: matches.is_present("skip_non_deterministic"), random: matches.is_present("random"), input_directory: matches.value_of("input_directory").map(|s| s.to_string()), output_directory: matches.value_of("output_directory").unwrap().to_string(), test_mode: matches.is_present("test_mode"), jqf: analysis::JQFLevel::from_arg(matches.value_of("jqf_level").unwrap()), fuzz_server_id: matches.value_of("fuzz_server_id").unwrap().to_string(), seed_cycles: matches.value_of("seed_cycles").unwrap().parse::<usize>().unwrap(), }; // "Ctrl + C" handling let canceled = Arc::new(AtomicBool::new(false)); let c = canceled.clone(); ctrlc::set_handler(move || { c.store(true, Ordering::SeqCst); }) .expect("Error setting Ctrl-C handler"); // load test config let config = config::Config::from_file(WORD_SIZE, &args.toml_config); let test_size = config.get_test_size(); config.print_header(); // test runner let srv_config = BufferedFuzzServerConfig { test_size : test_size, max_cycles : 200, test_buffer_size : 64 * 1024 * 16, coverage_buffer_size : 64 * 1024 * 16, buffer_count: 3, max_runs: 1024 * 16, }; println!("Test Buffer: {} KiB", srv_config.test_buffer_size / 1024); println!("Coverage Buffer: {} KiB", srv_config.coverage_buffer_size / 1024); println!("Max Inputs: {}", srv_config.test_buffer_size / 16 / 3); let server_dir = format!("{}/{}", FPGA_DIR, args.fuzz_server_id); let mut server = find_one_fuzz_server(&server_dir, srv_config).expect("failed to find a fuzz server"); if args.test_mode { test_mode(&mut server, &config); } else { fuzzer(args, canceled, config, test_size, &mut server); } } fn test_mode(server: &mut FuzzServer, config: &config::Config) { println!("⚠️ Test mode selected! ⚠️"); test::test_fuzz_server(server, config); } fn fuzzer(args: Args, canceled: Arc<AtomicBool>, config: config::Config, test_size: run::TestSize, server: &mut FuzzServer) { // starting seed let start_cycles = args.seed_cycles; let starting_seed = vec![0u8; test_size.input * start_cycles]; // analysis let ranges = config.gen_ranges(); //println!("ranges:]\n{:?}", ranges); let mut analysis = analysis::Analysis::new(test_size, ranges, args.jqf); let seed_coverage = fuzz_one(server, &starting_seed); let seed_analysis_res = analysis.run(start_cycles as u16, &seed_coverage); if seed_analysis_res.is_invalid { println!("❌ Invalid seed!"); } if!seed_analysis_res.is_interesting { println!("⚠️ Uninteresting seed! Might be 🐟!"); } // TODO: support multiple seeds // mutation let mut_config = mutation::MutationScheduleConfig { skip_deterministic: args.skip_deterministic, skip_non_deterministic: args.skip_non_deterministic, independent_random: args.random, }; if mut_config.independent_random { println!("⚠️ Mutation disabled. Generating independent random inputs! ⚠️"); } let mutations = mutation::MutationSchedule::initialize(mut_config, test_size, config.get_inputs()); // statistics let start_ts = get_time(); let mut statistics = stats::Stats::new(mutations.get_names(), start_ts.clone(), analysis.get_bitmap()); // queue let mut q = queue::Queue::create( &args.output_directory, &starting_seed, seed_analysis_res.new_cov, !seed_analysis_res.is_invalid, start_ts, config.to_json(), statistics.take_snapshot(), &seed_coverage); let max_entries = 1_000_000; let max_children = 100_000; // TODO: better mechanism to determine length of the havoc stage println!("fuzzing a maximum of {} queue entries", max_entries); for _ in 0..max_entries { let active_test = q.get_next_test(); let mut history = active_test.mutation_history; let mut new_runs : u64 = 0; q.print_entry_summary(active_test.id, &mutations); while let Some(mut mutator) = mutations.get_mutator(&mut history, &active_test.inputs) { // println!("running {} mutation", mutations.get_name(mutator.id())); let mut done = false; let mut start = 0; while!done { match server.run(&mut mutator, start) { Run::Done(runs, cycles) => { statistics.update_test_count(mutator.id().id, runs as u64, cycles); new_runs += runs as u64; done = true; } Run::Yield(ii) => { start = ii; } } while let Some(feedback) = server.pop_coverage() { let rr = analysis.run(feedback.cycles, &feedback.data); if rr.is_interesting { if rr.is_invalid { println!("invalid input...."); } let (info, interesting_input) = server.get_info(feedback.id); let now = get_time(); statistics.update_new_discovery(info.mutator.id, now, analysis.get_bitmap()); q.add_new_test(interesting_input, info, rr.new_cov, !rr.is_invalid, now, statistics.take_snapshot(), &feedback.data); } } } if new_runs >= max_children { break; } } q.return_test(active_test.id, history); q.save_latest(statistics.take_snapshot()); if canceled.load(Ordering::SeqCst) { println!("User interrupted fuzzing. Going to shut down...."); break; } } server.sync(); while let Some(feedback) = server.pop_coverage() { let rr = analysis.run(feedback.cycles, &feedback.data); if rr.is_interesting { if rr.is_invalid { println!("invalid input...."); } let (info, interesting_input) = server.get_info(feedback.id); let now = get_time(); statistics.update_new_discovery(info.mutator.id, now, analysis.get_bitmap()); q.add_new_test(interesting_input, info, rr.new_cov, !rr.is_invalid, now, statistics.take_snapshot(), &feedback.data); } } q.save_latest(statistics.take_snapshot()); // done with the main fuzzing part statistics.done(); // final bitmap let bitmap = analysis.get_bitmap(); // print inputs from queue if args.print_queue { println!("\n"); println!("Formated Inputs and Coverage!"); for entry in q.entries() { q.print_entry_summary(entry.id, &mutations); config.print_inputs(&entry.inputs); println!("Achieved Coverage:"); let coverage = fuzz_one(server, &entry.inputs); config.print_test_coverage(&coverage); println!("\n"); } } if args.print_total_cov { println!("Total Coverage:"); config.print_bitmap(&bitmap); } // print statistics print!("{}", statistics.get_final_snapshot().unwrap()); println!("Bitmap: {:?}", bitmap); } fn fuzz_one(server: &mut FuzzServer, input: &[u8]) -> Vec<u8> { let mut mutator = mutation::identity(input); if let Run::Done(count, _) = server.run(&mut mutator, 0) { assert_eq!(count, 1); } else { assert!(false); } server.sync(); let feedback = server.pop_coverage().expect("should get exactly one coverage back!"); feedback.data.to_vec() } fn get_time() -> std::time::Duration { let raw = time::get_ti
me(); std::time::Duration::new(raw.sec as u64, raw.nsec as u32) }
identifier_body
main.rs
#![allow(dead_code)] extern crate libc; extern crate time; extern crate rand; extern crate toml; extern crate serde_json; #[macro_use] extern crate serde_derive; extern crate colored; #[macro_use] extern crate prettytable; extern crate ctrlc; extern crate clap; use clap::{Arg, App}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; mod config; mod run; mod mutation; mod analysis; mod queue; mod test; mod stats; use run::buffered::{ find_one_fuzz_server, BufferedFuzzServerConfig }; use run::{ FuzzServer, Run }; const APP_NAME: &'static str = env!("CARGO_PKG_NAME"); const VERSION: &'static str = env!("CARGO_PKG_VERSION"); const AUTHOR: &'static str = env!("CARGO_PKG_AUTHORS"); const FPGA_DIR: &'static str = "/tmp/fpga"; const WORD_SIZE : usize = 8; #[derive(Debug)] struct
{ toml_config: String, print_queue: bool, print_total_cov: bool, skip_deterministic: bool, skip_non_deterministic: bool, random: bool, input_directory: Option<String>, output_directory: String, test_mode: bool, jqf: analysis::JQFLevel, fuzz_server_id: String, seed_cycles: usize, } fn main() { let matches = App::new(APP_NAME).version(VERSION).author(AUTHOR) .about("AFL-style fuzzer specialized for fuzzing RTL circuits.") .version_short("v") .arg(Arg::with_name("TOML") .help("TOML file describing the circuit being fuzzed") .required(true).index(1)) .arg(Arg::with_name("print_queue") .long("print-queue").short("q") .help("Prints queue content at the end of a fuzzing run.")) .arg(Arg::with_name("print_total_cov") .long("print-total-cov").short("c") .help("Prints the union coverage at the end of a fuzzing run.")) .arg(Arg::with_name("skip_deterministic") .long("skip-deterministic").short("d") .help("Skip all deterministic mutation strategies.")) .arg(Arg::with_name("skip_non_deterministic") .long("skip-non-deterministic").short("n") .help("Skip all non-deterministic mutation strategies.")) .arg(Arg::with_name("random") .long("random").short("r") .help("Generate independent random inputs instead of using the fuzzing algorithm.")) .arg(Arg::with_name("jqf_level") .long("jqf-level").short("j") .help("Select which level of JQF to apply.") .takes_value(true).possible_values(&["0", "1", "2"]) .default_value("2")) .arg(Arg::with_name("seed_cycles") .long("seed-cycles") .help("The starting seed consits of all zeros for N cycles.") .takes_value(true) .default_value("5")) .arg(Arg::with_name("input_directory") .long("input-directory").short("i").value_name("DIR") .takes_value(true) .help("The output directory of a previous run from which to resume.")) .arg(Arg::with_name("output_directory") .long("output-directory").short("o").value_name("DIR") .takes_value(true) .help("Used to log this session. Must be empty!") .required(true)) .arg(Arg::with_name("test_mode") .long("test-mode").short("t") .help("Test the fuzz server with known input/coverage pairs.")) .arg(Arg::with_name("fuzz_server_id") .long("server-id").short("s") .help("The id of the fuzz server isntance to connect to.") .takes_value(true).default_value("0")) .get_matches(); let args = Args { toml_config: matches.value_of("TOML").unwrap().to_string(), print_queue: matches.is_present("print_queue"), print_total_cov: matches.is_present("print_total_cov"), skip_deterministic: matches.is_present("skip_deterministic"), skip_non_deterministic: matches.is_present("skip_non_deterministic"), random: matches.is_present("random"), input_directory: matches.value_of("input_directory").map(|s| s.to_string()), output_directory: matches.value_of("output_directory").unwrap().to_string(), test_mode: matches.is_present("test_mode"), jqf: analysis::JQFLevel::from_arg(matches.value_of("jqf_level").unwrap()), fuzz_server_id: matches.value_of("fuzz_server_id").unwrap().to_string(), seed_cycles: matches.value_of("seed_cycles").unwrap().parse::<usize>().unwrap(), }; // "Ctrl + C" handling let canceled = Arc::new(AtomicBool::new(false)); let c = canceled.clone(); ctrlc::set_handler(move || { c.store(true, Ordering::SeqCst); }) .expect("Error setting Ctrl-C handler"); // load test config let config = config::Config::from_file(WORD_SIZE, &args.toml_config); let test_size = config.get_test_size(); config.print_header(); // test runner let srv_config = BufferedFuzzServerConfig { test_size : test_size, max_cycles : 200, test_buffer_size : 64 * 1024 * 16, coverage_buffer_size : 64 * 1024 * 16, buffer_count: 3, max_runs: 1024 * 16, }; println!("Test Buffer: {} KiB", srv_config.test_buffer_size / 1024); println!("Coverage Buffer: {} KiB", srv_config.coverage_buffer_size / 1024); println!("Max Inputs: {}", srv_config.test_buffer_size / 16 / 3); let server_dir = format!("{}/{}", FPGA_DIR, args.fuzz_server_id); let mut server = find_one_fuzz_server(&server_dir, srv_config).expect("failed to find a fuzz server"); if args.test_mode { test_mode(&mut server, &config); } else { fuzzer(args, canceled, config, test_size, &mut server); } } fn test_mode(server: &mut FuzzServer, config: &config::Config) { println!("⚠️ Test mode selected! ⚠️"); test::test_fuzz_server(server, config); } fn fuzzer(args: Args, canceled: Arc<AtomicBool>, config: config::Config, test_size: run::TestSize, server: &mut FuzzServer) { // starting seed let start_cycles = args.seed_cycles; let starting_seed = vec![0u8; test_size.input * start_cycles]; // analysis let ranges = config.gen_ranges(); //println!("ranges:]\n{:?}", ranges); let mut analysis = analysis::Analysis::new(test_size, ranges, args.jqf); let seed_coverage = fuzz_one(server, &starting_seed); let seed_analysis_res = analysis.run(start_cycles as u16, &seed_coverage); if seed_analysis_res.is_invalid { println!("❌ Invalid seed!"); } if!seed_analysis_res.is_interesting { println!("⚠️ Uninteresting seed! Might be 🐟!"); } // TODO: support multiple seeds // mutation let mut_config = mutation::MutationScheduleConfig { skip_deterministic: args.skip_deterministic, skip_non_deterministic: args.skip_non_deterministic, independent_random: args.random, }; if mut_config.independent_random { println!("⚠️ Mutation disabled. Generating independent random inputs! ⚠️"); } let mutations = mutation::MutationSchedule::initialize(mut_config, test_size, config.get_inputs()); // statistics let start_ts = get_time(); let mut statistics = stats::Stats::new(mutations.get_names(), start_ts.clone(), analysis.get_bitmap()); // queue let mut q = queue::Queue::create( &args.output_directory, &starting_seed, seed_analysis_res.new_cov, !seed_analysis_res.is_invalid, start_ts, config.to_json(), statistics.take_snapshot(), &seed_coverage); let max_entries = 1_000_000; let max_children = 100_000; // TODO: better mechanism to determine length of the havoc stage println!("fuzzing a maximum of {} queue entries", max_entries); for _ in 0..max_entries { let active_test = q.get_next_test(); let mut history = active_test.mutation_history; let mut new_runs : u64 = 0; q.print_entry_summary(active_test.id, &mutations); while let Some(mut mutator) = mutations.get_mutator(&mut history, &active_test.inputs) { // println!("running {} mutation", mutations.get_name(mutator.id())); let mut done = false; let mut start = 0; while!done { match server.run(&mut mutator, start) { Run::Done(runs, cycles) => { statistics.update_test_count(mutator.id().id, runs as u64, cycles); new_runs += runs as u64; done = true; } Run::Yield(ii) => { start = ii; } } while let Some(feedback) = server.pop_coverage() { let rr = analysis.run(feedback.cycles, &feedback.data); if rr.is_interesting { if rr.is_invalid { println!("invalid input...."); } let (info, interesting_input) = server.get_info(feedback.id); let now = get_time(); statistics.update_new_discovery(info.mutator.id, now, analysis.get_bitmap()); q.add_new_test(interesting_input, info, rr.new_cov, !rr.is_invalid, now, statistics.take_snapshot(), &feedback.data); } } } if new_runs >= max_children { break; } } q.return_test(active_test.id, history); q.save_latest(statistics.take_snapshot()); if canceled.load(Ordering::SeqCst) { println!("User interrupted fuzzing. Going to shut down...."); break; } } server.sync(); while let Some(feedback) = server.pop_coverage() { let rr = analysis.run(feedback.cycles, &feedback.data); if rr.is_interesting { if rr.is_invalid { println!("invalid input...."); } let (info, interesting_input) = server.get_info(feedback.id); let now = get_time(); statistics.update_new_discovery(info.mutator.id, now, analysis.get_bitmap()); q.add_new_test(interesting_input, info, rr.new_cov, !rr.is_invalid, now, statistics.take_snapshot(), &feedback.data); } } q.save_latest(statistics.take_snapshot()); // done with the main fuzzing part statistics.done(); // final bitmap let bitmap = analysis.get_bitmap(); // print inputs from queue if args.print_queue { println!("\n"); println!("Formated Inputs and Coverage!"); for entry in q.entries() { q.print_entry_summary(entry.id, &mutations); config.print_inputs(&entry.inputs); println!("Achieved Coverage:"); let coverage = fuzz_one(server, &entry.inputs); config.print_test_coverage(&coverage); println!("\n"); } } if args.print_total_cov { println!("Total Coverage:"); config.print_bitmap(&bitmap); } // print statistics print!("{}", statistics.get_final_snapshot().unwrap()); println!("Bitmap: {:?}", bitmap); } fn fuzz_one(server: &mut FuzzServer, input: &[u8]) -> Vec<u8> { let mut mutator = mutation::identity(input); if let Run::Done(count, _) = server.run(&mut mutator, 0) { assert_eq!(count, 1); } else { assert!(false); } server.sync(); let feedback = server.pop_coverage().expect("should get exactly one coverage back!"); feedback.data.to_vec() } fn get_time() -> std::time::Duration { let raw = time::get_time(); std::time::Duration::new(raw.sec as u64, raw.nsec as u32) }
Args
identifier_name
main.rs
#![allow(dead_code)] extern crate libc; extern crate time; extern crate rand; extern crate toml; extern crate serde_json; #[macro_use] extern crate serde_derive; extern crate colored; #[macro_use] extern crate prettytable; extern crate ctrlc; extern crate clap; use clap::{Arg, App}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; mod config; mod run; mod mutation; mod analysis; mod queue; mod test; mod stats; use run::buffered::{ find_one_fuzz_server, BufferedFuzzServerConfig }; use run::{ FuzzServer, Run }; const APP_NAME: &'static str = env!("CARGO_PKG_NAME"); const VERSION: &'static str = env!("CARGO_PKG_VERSION"); const AUTHOR: &'static str = env!("CARGO_PKG_AUTHORS"); const FPGA_DIR: &'static str = "/tmp/fpga"; const WORD_SIZE : usize = 8; #[derive(Debug)] struct Args { toml_config: String, print_queue: bool, print_total_cov: bool, skip_deterministic: bool, skip_non_deterministic: bool, random: bool, input_directory: Option<String>, output_directory: String, test_mode: bool, jqf: analysis::JQFLevel, fuzz_server_id: String, seed_cycles: usize, } fn main() { let matches = App::new(APP_NAME).version(VERSION).author(AUTHOR) .about("AFL-style fuzzer specialized for fuzzing RTL circuits.") .version_short("v") .arg(Arg::with_name("TOML") .help("TOML file describing the circuit being fuzzed") .required(true).index(1)) .arg(Arg::with_name("print_queue") .long("print-queue").short("q") .help("Prints queue content at the end of a fuzzing run.")) .arg(Arg::with_name("print_total_cov") .long("print-total-cov").short("c") .help("Prints the union coverage at the end of a fuzzing run.")) .arg(Arg::with_name("skip_deterministic") .long("skip-deterministic").short("d") .help("Skip all deterministic mutation strategies.")) .arg(Arg::with_name("skip_non_deterministic") .long("skip-non-deterministic").short("n") .help("Skip all non-deterministic mutation strategies.")) .arg(Arg::with_name("random") .long("random").short("r") .help("Generate independent random inputs instead of using the fuzzing algorithm.")) .arg(Arg::with_name("jqf_level") .long("jqf-level").short("j") .help("Select which level of JQF to apply.") .takes_value(true).possible_values(&["0", "1", "2"]) .default_value("2")) .arg(Arg::with_name("seed_cycles") .long("seed-cycles") .help("The starting seed consits of all zeros for N cycles.") .takes_value(true) .default_value("5")) .arg(Arg::with_name("input_directory") .long("input-directory").short("i").value_name("DIR") .takes_value(true) .help("The output directory of a previous run from which to resume.")) .arg(Arg::with_name("output_directory") .long("output-directory").short("o").value_name("DIR") .takes_value(true) .help("Used to log this session. Must be empty!") .required(true)) .arg(Arg::with_name("test_mode") .long("test-mode").short("t") .help("Test the fuzz server with known input/coverage pairs.")) .arg(Arg::with_name("fuzz_server_id") .long("server-id").short("s") .help("The id of the fuzz server isntance to connect to.") .takes_value(true).default_value("0")) .get_matches(); let args = Args { toml_config: matches.value_of("TOML").unwrap().to_string(), print_queue: matches.is_present("print_queue"), print_total_cov: matches.is_present("print_total_cov"), skip_deterministic: matches.is_present("skip_deterministic"), skip_non_deterministic: matches.is_present("skip_non_deterministic"), random: matches.is_present("random"), input_directory: matches.value_of("input_directory").map(|s| s.to_string()), output_directory: matches.value_of("output_directory").unwrap().to_string(), test_mode: matches.is_present("test_mode"), jqf: analysis::JQFLevel::from_arg(matches.value_of("jqf_level").unwrap()), fuzz_server_id: matches.value_of("fuzz_server_id").unwrap().to_string(), seed_cycles: matches.value_of("seed_cycles").unwrap().parse::<usize>().unwrap(), }; // "Ctrl + C" handling let canceled = Arc::new(AtomicBool::new(false)); let c = canceled.clone(); ctrlc::set_handler(move || { c.store(true, Ordering::SeqCst); }) .expect("Error setting Ctrl-C handler"); // load test config let config = config::Config::from_file(WORD_SIZE, &args.toml_config); let test_size = config.get_test_size(); config.print_header(); // test runner let srv_config = BufferedFuzzServerConfig { test_size : test_size, max_cycles : 200, test_buffer_size : 64 * 1024 * 16, coverage_buffer_size : 64 * 1024 * 16, buffer_count: 3, max_runs: 1024 * 16, }; println!("Test Buffer: {} KiB", srv_config.test_buffer_size / 1024); println!("Coverage Buffer: {} KiB", srv_config.coverage_buffer_size / 1024); println!("Max Inputs: {}", srv_config.test_buffer_size / 16 / 3);
} else { fuzzer(args, canceled, config, test_size, &mut server); } } fn test_mode(server: &mut FuzzServer, config: &config::Config) { println!("⚠️ Test mode selected! ⚠️"); test::test_fuzz_server(server, config); } fn fuzzer(args: Args, canceled: Arc<AtomicBool>, config: config::Config, test_size: run::TestSize, server: &mut FuzzServer) { // starting seed let start_cycles = args.seed_cycles; let starting_seed = vec![0u8; test_size.input * start_cycles]; // analysis let ranges = config.gen_ranges(); //println!("ranges:]\n{:?}", ranges); let mut analysis = analysis::Analysis::new(test_size, ranges, args.jqf); let seed_coverage = fuzz_one(server, &starting_seed); let seed_analysis_res = analysis.run(start_cycles as u16, &seed_coverage); if seed_analysis_res.is_invalid { println!("❌ Invalid seed!"); } if!seed_analysis_res.is_interesting { println!("⚠️ Uninteresting seed! Might be 🐟!"); } // TODO: support multiple seeds // mutation let mut_config = mutation::MutationScheduleConfig { skip_deterministic: args.skip_deterministic, skip_non_deterministic: args.skip_non_deterministic, independent_random: args.random, }; if mut_config.independent_random { println!("⚠️ Mutation disabled. Generating independent random inputs! ⚠️"); } let mutations = mutation::MutationSchedule::initialize(mut_config, test_size, config.get_inputs()); // statistics let start_ts = get_time(); let mut statistics = stats::Stats::new(mutations.get_names(), start_ts.clone(), analysis.get_bitmap()); // queue let mut q = queue::Queue::create( &args.output_directory, &starting_seed, seed_analysis_res.new_cov, !seed_analysis_res.is_invalid, start_ts, config.to_json(), statistics.take_snapshot(), &seed_coverage); let max_entries = 1_000_000; let max_children = 100_000; // TODO: better mechanism to determine length of the havoc stage println!("fuzzing a maximum of {} queue entries", max_entries); for _ in 0..max_entries { let active_test = q.get_next_test(); let mut history = active_test.mutation_history; let mut new_runs : u64 = 0; q.print_entry_summary(active_test.id, &mutations); while let Some(mut mutator) = mutations.get_mutator(&mut history, &active_test.inputs) { // println!("running {} mutation", mutations.get_name(mutator.id())); let mut done = false; let mut start = 0; while!done { match server.run(&mut mutator, start) { Run::Done(runs, cycles) => { statistics.update_test_count(mutator.id().id, runs as u64, cycles); new_runs += runs as u64; done = true; } Run::Yield(ii) => { start = ii; } } while let Some(feedback) = server.pop_coverage() { let rr = analysis.run(feedback.cycles, &feedback.data); if rr.is_interesting { if rr.is_invalid { println!("invalid input...."); } let (info, interesting_input) = server.get_info(feedback.id); let now = get_time(); statistics.update_new_discovery(info.mutator.id, now, analysis.get_bitmap()); q.add_new_test(interesting_input, info, rr.new_cov, !rr.is_invalid, now, statistics.take_snapshot(), &feedback.data); } } } if new_runs >= max_children { break; } } q.return_test(active_test.id, history); q.save_latest(statistics.take_snapshot()); if canceled.load(Ordering::SeqCst) { println!("User interrupted fuzzing. Going to shut down...."); break; } } server.sync(); while let Some(feedback) = server.pop_coverage() { let rr = analysis.run(feedback.cycles, &feedback.data); if rr.is_interesting { if rr.is_invalid { println!("invalid input...."); } let (info, interesting_input) = server.get_info(feedback.id); let now = get_time(); statistics.update_new_discovery(info.mutator.id, now, analysis.get_bitmap()); q.add_new_test(interesting_input, info, rr.new_cov, !rr.is_invalid, now, statistics.take_snapshot(), &feedback.data); } } q.save_latest(statistics.take_snapshot()); // done with the main fuzzing part statistics.done(); // final bitmap let bitmap = analysis.get_bitmap(); // print inputs from queue if args.print_queue { println!("\n"); println!("Formated Inputs and Coverage!"); for entry in q.entries() { q.print_entry_summary(entry.id, &mutations); config.print_inputs(&entry.inputs); println!("Achieved Coverage:"); let coverage = fuzz_one(server, &entry.inputs); config.print_test_coverage(&coverage); println!("\n"); } } if args.print_total_cov { println!("Total Coverage:"); config.print_bitmap(&bitmap); } // print statistics print!("{}", statistics.get_final_snapshot().unwrap()); println!("Bitmap: {:?}", bitmap); } fn fuzz_one(server: &mut FuzzServer, input: &[u8]) -> Vec<u8> { let mut mutator = mutation::identity(input); if let Run::Done(count, _) = server.run(&mut mutator, 0) { assert_eq!(count, 1); } else { assert!(false); } server.sync(); let feedback = server.pop_coverage().expect("should get exactly one coverage back!"); feedback.data.to_vec() } fn get_time() -> std::time::Duration { let raw = time::get_time(); std::time::Duration::new(raw.sec as u64, raw.nsec as u32) }
let server_dir = format!("{}/{}", FPGA_DIR, args.fuzz_server_id); let mut server = find_one_fuzz_server(&server_dir, srv_config).expect("failed to find a fuzz server"); if args.test_mode { test_mode(&mut server, &config);
random_line_split
http_remote.rs
stripped should still be valid"); Ok(HttpRegistry { index_path: config.registry_index_path().join(name), cache_path: config.registry_cache_path().join(name), source_id, config, url, multi: Multi::new(), multiplexing: false, downloads: Downloads { next: 0, pending: HashMap::new(), pending_paths: HashSet::new(), sleeping: SleepTracker::new(), results: HashMap::new(), progress: RefCell::new(Some(Progress::with_style( "Fetch", ProgressStyle::Indeterminate, config, ))), downloads_finished: 0, blocking_calls: 0, }, fresh: HashSet::new(), requested_update: false, fetch_started: false, registry_config: None, auth_required: false, login_url: None, auth_error_headers: vec![], quiet: false, }) } /// Splits HTTP `HEADER: VALUE` to a tuple. fn
(buf: &[u8]) -> Option<(&str, &str)> { if buf.is_empty() { return None; } let buf = std::str::from_utf8(buf).ok()?.trim_end(); // Don't let server sneak extra lines anywhere. if buf.contains('\n') { return None; } let (tag, value) = buf.split_once(':')?; let value = value.trim(); Some((tag, value)) } /// Setup the necessary works before the first fetch gets started. /// /// This is a no-op if called more than one time. fn start_fetch(&mut self) -> CargoResult<()> { if self.fetch_started { // We only need to run the setup code once. return Ok(()); } self.fetch_started = true; // We've enabled the `http2` feature of `curl` in Cargo, so treat // failures here as fatal as it would indicate a build-time problem. self.multiplexing = self.config.http_config()?.multiplexing.unwrap_or(true); self.multi .pipelining(false, self.multiplexing) .with_context(|| "failed to enable multiplexing/pipelining in curl")?; // let's not flood the server with connections self.multi.set_max_host_connections(2)?; if!self.quiet { self.config .shell() .status("Updating", self.source_id.display_index())?; } Ok(()) } /// Checks the results inside the [`HttpRegistry::multi`] handle, and /// updates relevant state in [`HttpRegistry::downloads`] accordingly. fn handle_completed_downloads(&mut self) -> CargoResult<()> { assert_eq!( self.downloads.pending.len(), self.downloads.pending_paths.len() ); // Collect the results from the Multi handle. let results = { let mut results = Vec::new(); let pending = &mut self.downloads.pending; self.multi.messages(|msg| { let token = msg.token().expect("failed to read token"); let (_, handle) = &pending[&token]; if let Some(result) = msg.result_for(handle) { results.push((token, result)); }; }); results }; for (token, result) in results { let (mut download, handle) = self.downloads.pending.remove(&token).unwrap(); let was_present = self.downloads.pending_paths.remove(&download.path); assert!( was_present, "expected pending_paths to contain {:?}", download.path ); let mut handle = self.multi.remove(handle)?; let data = download.data.take(); let url = self.full_url(&download.path); let result = match download.retry.r#try(|| { result.with_context(|| format!("failed to download from `{}`", url))?; let code = handle.response_code()?; // Keep this list of expected status codes in sync with the codes handled in `load` let code = match code { 200 => StatusCode::Success, 304 => StatusCode::NotModified, 401 => StatusCode::Unauthorized, 404 | 410 | 451 => StatusCode::NotFound, _ => { return Err(HttpNotSuccessful::new_from_handle( &mut handle, &url, data, download.header_map.take().all, ) .into()); } }; Ok((data, code)) }) { RetryResult::Success((data, code)) => Ok(CompletedDownload { response_code: code, data, header_map: download.header_map.take(), }), RetryResult::Err(e) => Err(e), RetryResult::Retry(sleep) => { debug!(target: "network", "download retry {:?} for {sleep}ms", download.path); self.downloads.sleeping.push(sleep, (download, handle)); continue; } }; self.downloads.results.insert(download.path, result); self.downloads.downloads_finished += 1; } self.downloads.tick()?; Ok(()) } /// Constructs the full URL to download a index file. fn full_url(&self, path: &Path) -> String { // self.url always ends with a slash. format!("{}{}", self.url, path.display()) } /// Check if an index file of `path` is up-to-date. /// /// The `path` argument is the same as in [`RegistryData::load`]. fn is_fresh(&self, path: &Path) -> bool { if!self.requested_update { trace!( "using local {} as user did not request update", path.display() ); true } else if self.config.cli_unstable().no_index_update { trace!("using local {} in no_index_update mode", path.display()); true } else if self.config.offline() { trace!("using local {} in offline mode", path.display()); true } else if self.fresh.contains(path) { trace!("using local {} as it was already fetched", path.display()); true } else { debug!("checking freshness of {}", path.display()); false } } /// Get the cached registry configuration, if it exists. fn config_cached(&mut self) -> CargoResult<Option<&RegistryConfig>> { if self.registry_config.is_some() { return Ok(self.registry_config.as_ref()); } let config_json_path = self .assert_index_locked(&self.index_path) .join(RegistryConfig::NAME); match fs::read(&config_json_path) { Ok(raw_data) => match serde_json::from_slice(&raw_data) { Ok(json) => { self.registry_config = Some(json); } Err(e) => tracing::debug!("failed to decode cached config.json: {}", e), }, Err(e) => { if e.kind()!= ErrorKind::NotFound { tracing::debug!("failed to read config.json cache: {}", e) } } } Ok(self.registry_config.as_ref()) } /// Get the registry configuration from either cache or remote. fn config(&mut self) -> Poll<CargoResult<&RegistryConfig>> { debug!("loading config"); let index_path = self.assert_index_locked(&self.index_path); let config_json_path = index_path.join(RegistryConfig::NAME); if self.is_fresh(Path::new(RegistryConfig::NAME)) && self.config_cached()?.is_some() { return Poll::Ready(Ok(self.registry_config.as_ref().unwrap())); } match ready!(self.load(Path::new(""), Path::new(RegistryConfig::NAME), None)?) { LoadResponse::Data { raw_data, index_version: _, } => { trace!("config loaded"); self.registry_config = Some(serde_json::from_slice(&raw_data)?); if paths::create_dir_all(&config_json_path.parent().unwrap()).is_ok() { if let Err(e) = fs::write(&config_json_path, &raw_data) { tracing::debug!("failed to write config.json cache: {}", e); } } Poll::Ready(Ok(self.registry_config.as_ref().unwrap())) } LoadResponse::NotFound => { Poll::Ready(Err(anyhow::anyhow!("config.json not found in registry"))) } LoadResponse::CacheValid => Poll::Ready(Err(crate::util::internal( "config.json is never stored in the index cache", ))), } } /// Moves failed [`Download`]s that are ready to retry to the pending queue. fn add_sleepers(&mut self) -> CargoResult<()> { for (dl, handle) in self.downloads.sleeping.to_retry() { let mut handle = self.multi.add(handle)?; handle.set_token(dl.token)?; let is_new = self.downloads.pending_paths.insert(dl.path.to_path_buf()); assert!(is_new, "path queued for download more than once"); let previous = self.downloads.pending.insert(dl.token, (dl, handle)); assert!(previous.is_none(), "dl token queued more than once"); } Ok(()) } } impl<'cfg> RegistryData for HttpRegistry<'cfg> { fn prepare(&self) -> CargoResult<()> { Ok(()) } fn index_path(&self) -> &Filesystem { &self.index_path } fn assert_index_locked<'a>(&self, path: &'a Filesystem) -> &'a Path { self.config.assert_package_cache_locked(path) } fn is_updated(&self) -> bool { self.requested_update } fn load( &mut self, _root: &Path, path: &Path, index_version: Option<&str>, ) -> Poll<CargoResult<LoadResponse>> { trace!("load: {}", path.display()); if let Some(_token) = self.downloads.pending_paths.get(path) { debug!("dependency is still pending: {}", path.display()); return Poll::Pending; } if let Some(index_version) = index_version { trace!( "local cache of {} is available at version `{}`", path.display(), index_version ); if self.is_fresh(path) { return Poll::Ready(Ok(LoadResponse::CacheValid)); } } else if self.fresh.contains(path) { // We have no cached copy of this file, and we already downloaded it. debug!( "cache did not contain previously downloaded file {}", path.display() ); return Poll::Ready(Ok(LoadResponse::NotFound)); } if self.config.offline() || self.config.cli_unstable().no_index_update { // Return NotFound in offline mode when the file doesn't exist in the cache. // If this results in resolution failure, the resolver will suggest // removing the --offline flag. return Poll::Ready(Ok(LoadResponse::NotFound)); } if let Some(result) = self.downloads.results.remove(path) { let result = result.with_context(|| format!("download of {} failed", path.display()))?; let is_new = self.fresh.insert(path.to_path_buf()); assert!( is_new, "downloaded the index file `{}` twice", path.display() ); // The status handled here need to be kept in sync with the codes handled // in `handle_completed_downloads` match result.response_code { StatusCode::Success => { let response_index_version = if let Some(etag) = result.header_map.etag { format!("{}: {}", ETAG, etag) } else if let Some(lm) = result.header_map.last_modified { format!("{}: {}", LAST_MODIFIED, lm) } else { UNKNOWN.to_string() }; trace!("index file version: {}", response_index_version); return Poll::Ready(Ok(LoadResponse::Data { raw_data: result.data, index_version: Some(response_index_version), })); } StatusCode::NotModified => { // Not Modified: the data in the cache is still the latest. if index_version.is_none() { return Poll::Ready(Err(anyhow::anyhow!( "server said not modified (HTTP 304) when no local cache exists" ))); } return Poll::Ready(Ok(LoadResponse::CacheValid)); } StatusCode::NotFound => { // The crate was not found or deleted from the registry. return Poll::Ready(Ok(LoadResponse::NotFound)); } StatusCode::Unauthorized if!self.auth_required && path == Path::new(RegistryConfig::NAME) && self.config.cli_unstable().registry_auth => { debug!(target: "network", "re-attempting request for config.json with authorization included."); self.fresh.remove(path); self.auth_required = true; // Look for a `www-authenticate` header with the `Cargo` scheme. for header in &result.header_map.www_authenticate { for challenge in http_auth::ChallengeParser::new(header) { match challenge { Ok(challenge) if challenge.scheme.eq_ignore_ascii_case("Cargo") => { // Look for the `login_url` parameter. for (param, value) in challenge.params { if param.eq_ignore_ascii_case("login_url") { self.login_url = Some(value.to_unescaped().into_url()?); } } } Ok(challenge) => { debug!(target: "network", "ignoring non-Cargo challenge: {}", challenge.scheme) } Err(e) => { debug!(target: "network", "failed to parse challenge: {}", e) } } } } self.auth_error_headers = result.header_map.all; } StatusCode::Unauthorized => { let err = Err(HttpNotSuccessful { code: 401, body: result.data, url: self.full_url(path), ip: None, headers: result.header_map.all, } .into()); if self.auth_required { return Poll::Ready(err.context(auth::AuthorizationError { sid: self.source_id.clone(), default_registry: self.config.default_registry()?,
handle_http_header
identifier_name
http_remote.rs
+ stripped should still be valid"); Ok(HttpRegistry { index_path: config.registry_index_path().join(name), cache_path: config.registry_cache_path().join(name), source_id, config, url, multi: Multi::new(), multiplexing: false, downloads: Downloads { next: 0, pending: HashMap::new(), pending_paths: HashSet::new(), sleeping: SleepTracker::new(), results: HashMap::new(), progress: RefCell::new(Some(Progress::with_style( "Fetch", ProgressStyle::Indeterminate, config, ))), downloads_finished: 0, blocking_calls: 0, }, fresh: HashSet::new(), requested_update: false, fetch_started: false, registry_config: None, auth_required: false, login_url: None, auth_error_headers: vec![], quiet: false, }) } /// Splits HTTP `HEADER: VALUE` to a tuple. fn handle_http_header(buf: &[u8]) -> Option<(&str, &str)> { if buf.is_empty() { return None; } let buf = std::str::from_utf8(buf).ok()?.trim_end(); // Don't let server sneak extra lines anywhere. if buf.contains('\n') { return None; } let (tag, value) = buf.split_once(':')?; let value = value.trim(); Some((tag, value)) } /// Setup the necessary works before the first fetch gets started. /// /// This is a no-op if called more than one time. fn start_fetch(&mut self) -> CargoResult<()> { if self.fetch_started { // We only need to run the setup code once. return Ok(()); } self.fetch_started = true; // We've enabled the `http2` feature of `curl` in Cargo, so treat // failures here as fatal as it would indicate a build-time problem. self.multiplexing = self.config.http_config()?.multiplexing.unwrap_or(true); self.multi .pipelining(false, self.multiplexing) .with_context(|| "failed to enable multiplexing/pipelining in curl")?; // let's not flood the server with connections self.multi.set_max_host_connections(2)?; if!self.quiet { self.config .shell() .status("Updating", self.source_id.display_index())?; } Ok(()) } /// Checks the results inside the [`HttpRegistry::multi`] handle, and /// updates relevant state in [`HttpRegistry::downloads`] accordingly. fn handle_completed_downloads(&mut self) -> CargoResult<()> { assert_eq!( self.downloads.pending.len(), self.downloads.pending_paths.len() ); // Collect the results from the Multi handle. let results = { let mut results = Vec::new(); let pending = &mut self.downloads.pending; self.multi.messages(|msg| { let token = msg.token().expect("failed to read token"); let (_, handle) = &pending[&token]; if let Some(result) = msg.result_for(handle) { results.push((token, result)); }; }); results }; for (token, result) in results { let (mut download, handle) = self.downloads.pending.remove(&token).unwrap(); let was_present = self.downloads.pending_paths.remove(&download.path); assert!( was_present, "expected pending_paths to contain {:?}", download.path ); let mut handle = self.multi.remove(handle)?; let data = download.data.take(); let url = self.full_url(&download.path); let result = match download.retry.r#try(|| { result.with_context(|| format!("failed to download from `{}`", url))?; let code = handle.response_code()?; // Keep this list of expected status codes in sync with the codes handled in `load` let code = match code { 200 => StatusCode::Success, 304 => StatusCode::NotModified, 401 => StatusCode::Unauthorized, 404 | 410 | 451 => StatusCode::NotFound, _ => { return Err(HttpNotSuccessful::new_from_handle( &mut handle, &url, data, download.header_map.take().all, ) .into()); } }; Ok((data, code)) }) { RetryResult::Success((data, code)) => Ok(CompletedDownload { response_code: code, data, header_map: download.header_map.take(), }), RetryResult::Err(e) => Err(e), RetryResult::Retry(sleep) => { debug!(target: "network", "download retry {:?} for {sleep}ms", download.path); self.downloads.sleeping.push(sleep, (download, handle)); continue; } }; self.downloads.results.insert(download.path, result); self.downloads.downloads_finished += 1; } self.downloads.tick()?; Ok(()) } /// Constructs the full URL to download a index file. fn full_url(&self, path: &Path) -> String { // self.url always ends with a slash. format!("{}{}", self.url, path.display()) } /// Check if an index file of `path` is up-to-date. /// /// The `path` argument is the same as in [`RegistryData::load`]. fn is_fresh(&self, path: &Path) -> bool { if!self.requested_update { trace!( "using local {} as user did not request update", path.display() ); true } else if self.config.cli_unstable().no_index_update { trace!("using local {} in no_index_update mode", path.display()); true } else if self.config.offline() { trace!("using local {} in offline mode", path.display()); true } else if self.fresh.contains(path) { trace!("using local {} as it was already fetched", path.display()); true } else { debug!("checking freshness of {}", path.display()); false } } /// Get the cached registry configuration, if it exists. fn config_cached(&mut self) -> CargoResult<Option<&RegistryConfig>> { if self.registry_config.is_some() { return Ok(self.registry_config.as_ref()); } let config_json_path = self .assert_index_locked(&self.index_path) .join(RegistryConfig::NAME); match fs::read(&config_json_path) { Ok(raw_data) => match serde_json::from_slice(&raw_data) { Ok(json) => { self.registry_config = Some(json); } Err(e) => tracing::debug!("failed to decode cached config.json: {}", e), }, Err(e) => { if e.kind()!= ErrorKind::NotFound { tracing::debug!("failed to read config.json cache: {}", e) } } } Ok(self.registry_config.as_ref()) } /// Get the registry configuration from either cache or remote. fn config(&mut self) -> Poll<CargoResult<&RegistryConfig>> { debug!("loading config"); let index_path = self.assert_index_locked(&self.index_path); let config_json_path = index_path.join(RegistryConfig::NAME); if self.is_fresh(Path::new(RegistryConfig::NAME)) && self.config_cached()?.is_some() { return Poll::Ready(Ok(self.registry_config.as_ref().unwrap())); } match ready!(self.load(Path::new(""), Path::new(RegistryConfig::NAME), None)?) { LoadResponse::Data { raw_data, index_version: _, } => { trace!("config loaded"); self.registry_config = Some(serde_json::from_slice(&raw_data)?); if paths::create_dir_all(&config_json_path.parent().unwrap()).is_ok() { if let Err(e) = fs::write(&config_json_path, &raw_data) { tracing::debug!("failed to write config.json cache: {}", e); } } Poll::Ready(Ok(self.registry_config.as_ref().unwrap())) } LoadResponse::NotFound => { Poll::Ready(Err(anyhow::anyhow!("config.json not found in registry"))) } LoadResponse::CacheValid => Poll::Ready(Err(crate::util::internal( "config.json is never stored in the index cache", ))), } } /// Moves failed [`Download`]s that are ready to retry to the pending queue. fn add_sleepers(&mut self) -> CargoResult<()> { for (dl, handle) in self.downloads.sleeping.to_retry() { let mut handle = self.multi.add(handle)?; handle.set_token(dl.token)?; let is_new = self.downloads.pending_paths.insert(dl.path.to_path_buf()); assert!(is_new, "path queued for download more than once"); let previous = self.downloads.pending.insert(dl.token, (dl, handle)); assert!(previous.is_none(), "dl token queued more than once"); } Ok(()) } } impl<'cfg> RegistryData for HttpRegistry<'cfg> { fn prepare(&self) -> CargoResult<()> { Ok(()) } fn index_path(&self) -> &Filesystem { &self.index_path } fn assert_index_locked<'a>(&self, path: &'a Filesystem) -> &'a Path { self.config.assert_package_cache_locked(path) } fn is_updated(&self) -> bool { self.requested_update } fn load( &mut self, _root: &Path, path: &Path, index_version: Option<&str>, ) -> Poll<CargoResult<LoadResponse>> { trace!("load: {}", path.display()); if let Some(_token) = self.downloads.pending_paths.get(path) { debug!("dependency is still pending: {}", path.display()); return Poll::Pending; } if let Some(index_version) = index_version { trace!( "local cache of {} is available at version `{}`", path.display(), index_version ); if self.is_fresh(path) { return Poll::Ready(Ok(LoadResponse::CacheValid)); } } else if self.fresh.contains(path) { // We have no cached copy of this file, and we already downloaded it. debug!( "cache did not contain previously downloaded file {}", path.display() ); return Poll::Ready(Ok(LoadResponse::NotFound)); } if self.config.offline() || self.config.cli_unstable().no_index_update { // Return NotFound in offline mode when the file doesn't exist in the cache. // If this results in resolution failure, the resolver will suggest // removing the --offline flag. return Poll::Ready(Ok(LoadResponse::NotFound)); } if let Some(result) = self.downloads.results.remove(path) { let result = result.with_context(|| format!("download of {} failed", path.display()))?; let is_new = self.fresh.insert(path.to_path_buf()); assert!( is_new, "downloaded the index file `{}` twice", path.display() ); // The status handled here need to be kept in sync with the codes handled // in `handle_completed_downloads` match result.response_code { StatusCode::Success => { let response_index_version = if let Some(etag) = result.header_map.etag {
} else { UNKNOWN.to_string() }; trace!("index file version: {}", response_index_version); return Poll::Ready(Ok(LoadResponse::Data { raw_data: result.data, index_version: Some(response_index_version), })); } StatusCode::NotModified => { // Not Modified: the data in the cache is still the latest. if index_version.is_none() { return Poll::Ready(Err(anyhow::anyhow!( "server said not modified (HTTP 304) when no local cache exists" ))); } return Poll::Ready(Ok(LoadResponse::CacheValid)); } StatusCode::NotFound => { // The crate was not found or deleted from the registry. return Poll::Ready(Ok(LoadResponse::NotFound)); } StatusCode::Unauthorized if!self.auth_required && path == Path::new(RegistryConfig::NAME) && self.config.cli_unstable().registry_auth => { debug!(target: "network", "re-attempting request for config.json with authorization included."); self.fresh.remove(path); self.auth_required = true; // Look for a `www-authenticate` header with the `Cargo` scheme. for header in &result.header_map.www_authenticate { for challenge in http_auth::ChallengeParser::new(header) { match challenge { Ok(challenge) if challenge.scheme.eq_ignore_ascii_case("Cargo") => { // Look for the `login_url` parameter. for (param, value) in challenge.params { if param.eq_ignore_ascii_case("login_url") { self.login_url = Some(value.to_unescaped().into_url()?); } } } Ok(challenge) => { debug!(target: "network", "ignoring non-Cargo challenge: {}", challenge.scheme) } Err(e) => { debug!(target: "network", "failed to parse challenge: {}", e) } } } } self.auth_error_headers = result.header_map.all; } StatusCode::Unauthorized => { let err = Err(HttpNotSuccessful { code: 401, body: result.data, url: self.full_url(path), ip: None, headers: result.header_map.all, } .into()); if self.auth_required { return Poll::Ready(err.context(auth::AuthorizationError { sid: self.source_id.clone(), default_registry: self.config.default_registry()?,
format!("{}: {}", ETAG, etag) } else if let Some(lm) = result.header_map.last_modified { format!("{}: {}", LAST_MODIFIED, lm)
random_line_split
http_remote.rs
stripped should still be valid"); Ok(HttpRegistry { index_path: config.registry_index_path().join(name), cache_path: config.registry_cache_path().join(name), source_id, config, url, multi: Multi::new(), multiplexing: false, downloads: Downloads { next: 0, pending: HashMap::new(), pending_paths: HashSet::new(), sleeping: SleepTracker::new(), results: HashMap::new(), progress: RefCell::new(Some(Progress::with_style( "Fetch", ProgressStyle::Indeterminate, config, ))), downloads_finished: 0, blocking_calls: 0, }, fresh: HashSet::new(), requested_update: false, fetch_started: false, registry_config: None, auth_required: false, login_url: None, auth_error_headers: vec![], quiet: false, }) } /// Splits HTTP `HEADER: VALUE` to a tuple. fn handle_http_header(buf: &[u8]) -> Option<(&str, &str)> { if buf.is_empty() { return None; } let buf = std::str::from_utf8(buf).ok()?.trim_end(); // Don't let server sneak extra lines anywhere. if buf.contains('\n') { return None; } let (tag, value) = buf.split_once(':')?; let value = value.trim(); Some((tag, value)) } /// Setup the necessary works before the first fetch gets started. /// /// This is a no-op if called more than one time. fn start_fetch(&mut self) -> CargoResult<()> { if self.fetch_started { // We only need to run the setup code once. return Ok(()); } self.fetch_started = true; // We've enabled the `http2` feature of `curl` in Cargo, so treat // failures here as fatal as it would indicate a build-time problem. self.multiplexing = self.config.http_config()?.multiplexing.unwrap_or(true); self.multi .pipelining(false, self.multiplexing) .with_context(|| "failed to enable multiplexing/pipelining in curl")?; // let's not flood the server with connections self.multi.set_max_host_connections(2)?; if!self.quiet { self.config .shell() .status("Updating", self.source_id.display_index())?; } Ok(()) } /// Checks the results inside the [`HttpRegistry::multi`] handle, and /// updates relevant state in [`HttpRegistry::downloads`] accordingly. fn handle_completed_downloads(&mut self) -> CargoResult<()>
let (mut download, handle) = self.downloads.pending.remove(&token).unwrap(); let was_present = self.downloads.pending_paths.remove(&download.path); assert!( was_present, "expected pending_paths to contain {:?}", download.path ); let mut handle = self.multi.remove(handle)?; let data = download.data.take(); let url = self.full_url(&download.path); let result = match download.retry.r#try(|| { result.with_context(|| format!("failed to download from `{}`", url))?; let code = handle.response_code()?; // Keep this list of expected status codes in sync with the codes handled in `load` let code = match code { 200 => StatusCode::Success, 304 => StatusCode::NotModified, 401 => StatusCode::Unauthorized, 404 | 410 | 451 => StatusCode::NotFound, _ => { return Err(HttpNotSuccessful::new_from_handle( &mut handle, &url, data, download.header_map.take().all, ) .into()); } }; Ok((data, code)) }) { RetryResult::Success((data, code)) => Ok(CompletedDownload { response_code: code, data, header_map: download.header_map.take(), }), RetryResult::Err(e) => Err(e), RetryResult::Retry(sleep) => { debug!(target: "network", "download retry {:?} for {sleep}ms", download.path); self.downloads.sleeping.push(sleep, (download, handle)); continue; } }; self.downloads.results.insert(download.path, result); self.downloads.downloads_finished += 1; } self.downloads.tick()?; Ok(()) } /// Constructs the full URL to download a index file. fn full_url(&self, path: &Path) -> String { // self.url always ends with a slash. format!("{}{}", self.url, path.display()) } /// Check if an index file of `path` is up-to-date. /// /// The `path` argument is the same as in [`RegistryData::load`]. fn is_fresh(&self, path: &Path) -> bool { if!self.requested_update { trace!( "using local {} as user did not request update", path.display() ); true } else if self.config.cli_unstable().no_index_update { trace!("using local {} in no_index_update mode", path.display()); true } else if self.config.offline() { trace!("using local {} in offline mode", path.display()); true } else if self.fresh.contains(path) { trace!("using local {} as it was already fetched", path.display()); true } else { debug!("checking freshness of {}", path.display()); false } } /// Get the cached registry configuration, if it exists. fn config_cached(&mut self) -> CargoResult<Option<&RegistryConfig>> { if self.registry_config.is_some() { return Ok(self.registry_config.as_ref()); } let config_json_path = self .assert_index_locked(&self.index_path) .join(RegistryConfig::NAME); match fs::read(&config_json_path) { Ok(raw_data) => match serde_json::from_slice(&raw_data) { Ok(json) => { self.registry_config = Some(json); } Err(e) => tracing::debug!("failed to decode cached config.json: {}", e), }, Err(e) => { if e.kind()!= ErrorKind::NotFound { tracing::debug!("failed to read config.json cache: {}", e) } } } Ok(self.registry_config.as_ref()) } /// Get the registry configuration from either cache or remote. fn config(&mut self) -> Poll<CargoResult<&RegistryConfig>> { debug!("loading config"); let index_path = self.assert_index_locked(&self.index_path); let config_json_path = index_path.join(RegistryConfig::NAME); if self.is_fresh(Path::new(RegistryConfig::NAME)) && self.config_cached()?.is_some() { return Poll::Ready(Ok(self.registry_config.as_ref().unwrap())); } match ready!(self.load(Path::new(""), Path::new(RegistryConfig::NAME), None)?) { LoadResponse::Data { raw_data, index_version: _, } => { trace!("config loaded"); self.registry_config = Some(serde_json::from_slice(&raw_data)?); if paths::create_dir_all(&config_json_path.parent().unwrap()).is_ok() { if let Err(e) = fs::write(&config_json_path, &raw_data) { tracing::debug!("failed to write config.json cache: {}", e); } } Poll::Ready(Ok(self.registry_config.as_ref().unwrap())) } LoadResponse::NotFound => { Poll::Ready(Err(anyhow::anyhow!("config.json not found in registry"))) } LoadResponse::CacheValid => Poll::Ready(Err(crate::util::internal( "config.json is never stored in the index cache", ))), } } /// Moves failed [`Download`]s that are ready to retry to the pending queue. fn add_sleepers(&mut self) -> CargoResult<()> { for (dl, handle) in self.downloads.sleeping.to_retry() { let mut handle = self.multi.add(handle)?; handle.set_token(dl.token)?; let is_new = self.downloads.pending_paths.insert(dl.path.to_path_buf()); assert!(is_new, "path queued for download more than once"); let previous = self.downloads.pending.insert(dl.token, (dl, handle)); assert!(previous.is_none(), "dl token queued more than once"); } Ok(()) } } impl<'cfg> RegistryData for HttpRegistry<'cfg> { fn prepare(&self) -> CargoResult<()> { Ok(()) } fn index_path(&self) -> &Filesystem { &self.index_path } fn assert_index_locked<'a>(&self, path: &'a Filesystem) -> &'a Path { self.config.assert_package_cache_locked(path) } fn is_updated(&self) -> bool { self.requested_update } fn load( &mut self, _root: &Path, path: &Path, index_version: Option<&str>, ) -> Poll<CargoResult<LoadResponse>> { trace!("load: {}", path.display()); if let Some(_token) = self.downloads.pending_paths.get(path) { debug!("dependency is still pending: {}", path.display()); return Poll::Pending; } if let Some(index_version) = index_version { trace!( "local cache of {} is available at version `{}`", path.display(), index_version ); if self.is_fresh(path) { return Poll::Ready(Ok(LoadResponse::CacheValid)); } } else if self.fresh.contains(path) { // We have no cached copy of this file, and we already downloaded it. debug!( "cache did not contain previously downloaded file {}", path.display() ); return Poll::Ready(Ok(LoadResponse::NotFound)); } if self.config.offline() || self.config.cli_unstable().no_index_update { // Return NotFound in offline mode when the file doesn't exist in the cache. // If this results in resolution failure, the resolver will suggest // removing the --offline flag. return Poll::Ready(Ok(LoadResponse::NotFound)); } if let Some(result) = self.downloads.results.remove(path) { let result = result.with_context(|| format!("download of {} failed", path.display()))?; let is_new = self.fresh.insert(path.to_path_buf()); assert!( is_new, "downloaded the index file `{}` twice", path.display() ); // The status handled here need to be kept in sync with the codes handled // in `handle_completed_downloads` match result.response_code { StatusCode::Success => { let response_index_version = if let Some(etag) = result.header_map.etag { format!("{}: {}", ETAG, etag) } else if let Some(lm) = result.header_map.last_modified { format!("{}: {}", LAST_MODIFIED, lm) } else { UNKNOWN.to_string() }; trace!("index file version: {}", response_index_version); return Poll::Ready(Ok(LoadResponse::Data { raw_data: result.data, index_version: Some(response_index_version), })); } StatusCode::NotModified => { // Not Modified: the data in the cache is still the latest. if index_version.is_none() { return Poll::Ready(Err(anyhow::anyhow!( "server said not modified (HTTP 304) when no local cache exists" ))); } return Poll::Ready(Ok(LoadResponse::CacheValid)); } StatusCode::NotFound => { // The crate was not found or deleted from the registry. return Poll::Ready(Ok(LoadResponse::NotFound)); } StatusCode::Unauthorized if!self.auth_required && path == Path::new(RegistryConfig::NAME) && self.config.cli_unstable().registry_auth => { debug!(target: "network", "re-attempting request for config.json with authorization included."); self.fresh.remove(path); self.auth_required = true; // Look for a `www-authenticate` header with the `Cargo` scheme. for header in &result.header_map.www_authenticate { for challenge in http_auth::ChallengeParser::new(header) { match challenge { Ok(challenge) if challenge.scheme.eq_ignore_ascii_case("Cargo") => { // Look for the `login_url` parameter. for (param, value) in challenge.params { if param.eq_ignore_ascii_case("login_url") { self.login_url = Some(value.to_unescaped().into_url()?); } } } Ok(challenge) => { debug!(target: "network", "ignoring non-Cargo challenge: {}", challenge.scheme) } Err(e) => { debug!(target: "network", "failed to parse challenge: {}", e) } } } } self.auth_error_headers = result.header_map.all; } StatusCode::Unauthorized => { let err = Err(HttpNotSuccessful { code: 401, body: result.data, url: self.full_url(path), ip: None, headers: result.header_map.all, } .into()); if self.auth_required { return Poll::Ready(err.context(auth::AuthorizationError { sid: self.source_id.clone(), default_registry: self.config.default_registry()?,
{ assert_eq!( self.downloads.pending.len(), self.downloads.pending_paths.len() ); // Collect the results from the Multi handle. let results = { let mut results = Vec::new(); let pending = &mut self.downloads.pending; self.multi.messages(|msg| { let token = msg.token().expect("failed to read token"); let (_, handle) = &pending[&token]; if let Some(result) = msg.result_for(handle) { results.push((token, result)); }; }); results }; for (token, result) in results {
identifier_body
lexer.rs
//! Lexer implementation use std::borrow::Cow::Borrowed; use std::borrow::{Borrow, Cow}; use std::cell::{Cell, RefCell}; use std::rc::Rc; use crate::char_stream::{CharStream, InputData}; use crate::error_listener::{ConsoleErrorListener, ErrorListener}; use crate::errors::ANTLRError; use crate::int_stream::IntStream; use crate::lexer_atn_simulator::{ILexerATNSimulator, LexerATNSimulator}; use crate::parser::ParserNodeType; use crate::recognizer::{Actions, Recognizer}; use crate::rule_context::EmptyContextType; use crate::token::TOKEN_INVALID_TYPE; use crate::token_factory::{CommonTokenFactory, TokenAware, TokenFactory}; use crate::token_source::TokenSource; use std::ops::{Deref, DerefMut}; /// Lexer functionality required by `LexerATNSimulator` to work properly pub trait Lexer<'input>: TokenSource<'input> + Recognizer<'input, Node = EmptyContextType<'input, <Self as TokenAware<'input>>::TF>> { /// Concrete input stream used by this parser type Input: IntStream; /// Same as `TokenStream::get_input_stream` but returns concrete type instance /// important for proper inlining in hot code of `LexerATNSimulator` fn input(&mut self) -> &mut Self::Input; /// Sets channel where current token will be pushed /// /// By default two channels are available: /// - `LEXER_DEFAULT_TOKEN_CHANNEL` /// - `LEXER_HIDDEN` fn set_channel(&mut self, v: isize); /// Pushes current mode to internal mode stack and sets `m` as current lexer mode /// `pop_mode should be used to recover previous mode fn push_mode(&mut self, m: usize); /// Pops mode from internal mode stack fn pop_mode(&mut self) -> Option<usize>; /// Sets type of the current token /// Called from action to override token that will be emitted by lexer fn set_type(&mut self, t: isize); /// Sets lexer mode discarding current one fn set_mode(&mut self, m: usize); /// Used to informs lexer that it should consider next token as a continuation of the current one fn more(&mut self); /// Tells lexer to completely ignore and not emit current token. fn skip(&mut self); #[doc(hidden)] fn reset(&mut self); #[doc(hidden)] fn get_interpreter(&self) -> Option<&LexerATNSimulator>; } /// **! Usually generated by ANTLR!** /// /// This trait combines everything that can be used to extend Lexer behavior pub trait LexerRecog<'a, T: Recognizer<'a>>: Actions<'a, T> + Sized +'static { /// Callback to extend emit behavior fn before_emit(_lexer: &mut T) {} } /// Default implementation of Lexer /// /// Public fields in this struct are intended to be used by embedded actions #[allow(missing_docs)] pub struct BaseLexer< 'input, T: LexerRecog<'input, Self> +'static, Input: CharStream<TF::From>, TF: TokenFactory<'input> = CommonTokenFactory, > { /// `LexerATNSimulator` instance of this lexer pub interpreter: Option<Box<LexerATNSimulator>>, /// `CharStream` used by this lexer pub input: Option<Input>, recog: T, factory: &'input TF, error_listeners: RefCell<Vec<Box<dyn ErrorListener<'input, Self>>>>, pub token_start_char_index: isize, pub token_start_line: isize, pub token_start_column: isize, current_pos: Rc<LexerPosition>, /// Overrides token type emitted by lexer for current token pub token_type: isize, /// Make it `Some` to override token that is currently being generated by lexer pub token: Option<TF::Tok>, hit_eof: bool, /// Channel lexer is currently assigning tokens to pub channel: isize, /// stack of modes, which is used for pushMode,popMode lexer actions pub mode_stack: Vec<usize>, /// Mode lexer is currently in pub mode: usize, /// Make it `Some` to override text for token that is currently being generated by lexer pub text: Option<<TF::Data as ToOwned>::Owned>, } #[derive(Debug)] pub(crate) struct LexerPosition { pub(crate) line: Cell<isize>, pub(crate) char_position_in_line: Cell<isize>, } impl<'input, T, Input, TF> Deref for BaseLexer<'input, T, Input, TF> where T: LexerRecog<'input, Self> +'static, Input: CharStream<TF::From>, TF: TokenFactory<'input>, { type Target = T; fn deref(&self) -> &Self::Target
} impl<'input, T, Input, TF> DerefMut for BaseLexer<'input, T, Input, TF> where T: LexerRecog<'input, Self> +'static, Input: CharStream<TF::From>, TF: TokenFactory<'input>, { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.recog } } impl<'input, T, Input, TF> Recognizer<'input> for BaseLexer<'input, T, Input, TF> where T: LexerRecog<'input, Self> +'static, Input: CharStream<TF::From>, TF: TokenFactory<'input>, { type Node = EmptyContextType<'input, TF>; fn sempred( &mut self, _localctx: Option<&<Self::Node as ParserNodeType<'input>>::Type>, rule_index: isize, action_index: isize, ) -> bool { <T as Actions<'input, Self>>::sempred(_localctx, rule_index, action_index, self) } fn action( &mut self, _localctx: Option<&<Self::Node as ParserNodeType<'input>>::Type>, rule_index: isize, action_index: isize, ) { <T as Actions<'input, Self>>::action(_localctx, rule_index, action_index, self) } } /// Default lexer mode id pub const LEXER_DEFAULT_MODE: usize = 0; /// Special token type to indicate that lexer should continue current token on next iteration /// see `Lexer::more()` pub const LEXER_MORE: isize = -2; /// Special token type to indicate that lexer should not return current token /// usually used to skip whitespaces and comments /// see `Lexer::skip()` pub const LEXER_SKIP: isize = -3; #[doc(inline)] pub use super::token::TOKEN_DEFAULT_CHANNEL as LEXER_DEFAULT_TOKEN_CHANNEL; #[doc(inline)] pub use super::token::TOKEN_HIDDEN_CHANNEL as LEXER_HIDDEN; pub(crate) const LEXER_MIN_CHAR_VALUE: isize = 0x0000; pub(crate) const LEXER_MAX_CHAR_VALUE: isize = 0x10FFFF; impl<'input, T, Input, TF> BaseLexer<'input, T, Input, TF> where T: LexerRecog<'input, Self> +'static, Input: CharStream<TF::From>, TF: TokenFactory<'input>, { fn emit_token(&mut self, token: TF::Tok) { self.token = Some(token); } fn emit(&mut self) { <T as LexerRecog<Self>>::before_emit(self); let stop = self.get_char_index() - 1; let token = self.factory.create( Some(self.input.as_mut().unwrap()), self.token_type, self.text.take(), self.channel, self.token_start_char_index, stop, self.token_start_line, self.token_start_column, ); self.emit_token(token); } fn emit_eof(&mut self) { let token = self.factory.create( None::<&mut Input>, super::int_stream::EOF, None, LEXER_DEFAULT_TOKEN_CHANNEL, self.get_char_index(), self.get_char_index() - 1, self.get_line(), self.get_char_position_in_line(), ); self.emit_token(token) } /// Current position in input stream pub fn get_char_index(&self) -> isize { self.input.as_ref().unwrap().index() } /// Current token text pub fn get_text<'a>(&'a self) -> Cow<'a, TF::Data> where 'input: 'a, { self.text .as_ref() .map(|it| Borrowed(it.borrow())) //.unwrap_or("") .unwrap_or_else(|| { let text = self .input .as_ref() .unwrap() .get_text(self.token_start_char_index, self.get_char_index() - 1); TF::get_data(text) }) } /// Used from lexer actions to override text of the token that will be emitted next pub fn set_text(&mut self, _text: <TF::Data as ToOwned>::Owned) { self.text = Some(_text); } // fn get_all_tokens(&mut self) -> Vec<TF::Tok> { unimplemented!() } // fn get_char_error_display(&self, _c: char) -> String { unimplemented!() } /// Add error listener pub fn add_error_listener(&mut self, listener: Box<dyn ErrorListener<'input, Self>>) { self.error_listeners.borrow_mut().push(listener); } /// Remove and drop all error listeners pub fn remove_error_listeners(&mut self) { self.error_listeners.borrow_mut().clear(); } /// Creates new lexer instance pub fn new_base_lexer( input: Input, interpreter: LexerATNSimulator, recog: T, factory: &'input TF, ) -> Self { let mut lexer = Self { interpreter: Some(Box::new(interpreter)), input: Some(input), recog, factory, error_listeners: RefCell::new(vec![Box::new(ConsoleErrorListener {})]), token_start_char_index: 0, token_start_line: 0, token_start_column: 0, current_pos: Rc::new(LexerPosition { line: Cell::new(1), char_position_in_line: Cell::new(0), }), token_type: super::token::TOKEN_INVALID_TYPE, text: None, token: None, hit_eof: false, channel: super::token::TOKEN_DEFAULT_CHANNEL, // token_factory_source_pair: None, mode_stack: Vec::new(), mode: self::LEXER_DEFAULT_MODE, }; let pos = lexer.current_pos.clone(); lexer.interpreter.as_mut().unwrap().current_pos = pos; lexer } } impl<'input, T, Input, TF> TokenAware<'input> for BaseLexer<'input, T, Input, TF> where T: LexerRecog<'input, Self> +'static, Input: CharStream<TF::From>, TF: TokenFactory<'input>, { type TF = TF; } impl<'input, T, Input, TF> TokenSource<'input> for BaseLexer<'input, T, Input, TF> where T: LexerRecog<'input, Self> +'static, Input: CharStream<TF::From>, TF: TokenFactory<'input>, { type TF = TF; #[inline] #[allow(unused_labels)] fn next_token(&mut self) -> <Self::TF as TokenFactory<'input>>::Tok { assert!(self.input.is_some()); let _marker = self.input().mark(); 'outer: loop { if self.hit_eof { self.emit_eof(); break; } self.token = None; self.channel = LEXER_DEFAULT_TOKEN_CHANNEL; self.token_start_column = self .interpreter .as_ref() .unwrap() .get_char_position_in_line(); self.token_start_line = self.interpreter.as_ref().unwrap().get_line(); self.text = None; let index = self.input().index(); self.token_start_char_index = index; 'inner: loop { self.token_type = TOKEN_INVALID_TYPE; // detach from self, to allow self to be passed deeper let mut interpreter = self.interpreter.take().unwrap(); // let mut input = self.input.take().unwrap(); let result = interpreter.match_token(self.mode, self); self.interpreter = Some(interpreter); let ttype = result.unwrap_or_else(|err| { // println!("error, recovering"); notify_listeners(&mut self.error_listeners.borrow_mut(), &err, self); self.interpreter .as_mut() .unwrap() .recover(err, self.input.as_mut().unwrap()); LEXER_SKIP }); // self.input = Some(input) if self.input().la(1) == super::int_stream::EOF { self.hit_eof = true; } if self.token_type == TOKEN_INVALID_TYPE { self.token_type = ttype; } if self.token_type == LEXER_SKIP { continue 'outer; } if self.token_type!= LEXER_MORE { break; } } if self.token.is_none() { self.emit(); break; } } self.input().release(_marker); self.token.take().unwrap() } fn get_line(&self) -> isize { self.current_pos.line.get() } fn get_char_position_in_line(&self) -> isize { self.current_pos.char_position_in_line.get() } fn get_input_stream(&mut self) -> Option<&mut dyn IntStream> { match &mut self.input { None => None, Some(x) => Some(x as _), } } fn get_source_name(&self) -> String { self.input .as_ref() .map(|it| it.get_source_name()) .unwrap_or("<none>".to_string()) } // fn set_token_factory<'c: 'b>(&mut self, f: &'c TokenFactory) { // self.factory = f; // } fn get_token_factory(&self) -> &'input TF { self.factory } } #[cold] #[inline(never)] fn notify_listeners<'input, T, Input, TF>( liseners: &mut Vec<Box<dyn ErrorListener<'input, BaseLexer<'input, T, Input, TF>>>>, e: &ANTLRError, lexer: &BaseLexer<'input, T, Input, TF>, ) where T: LexerRecog<'input, BaseLexer<'input, T, Input, TF>> +'static, Input: CharStream<TF::From>, TF: TokenFactory<'input>, { let inner = lexer .input .as_ref() .unwrap() .get_text(lexer.token_start_char_index, lexer.get_char_index()); let text = format!( "token recognition error at: '{}'", TF::get_data(inner).to_display() ); for listener in liseners.iter_mut() { listener.syntax_error( lexer, None, lexer.token_start_line, lexer.token_start_column, &text, Some(e), ) } } impl<'input, T, Input, TF> Lexer<'input> for BaseLexer<'input, T, Input, TF> where T: LexerRecog<'input, Self> +'static, Input: CharStream<TF::From>, TF: TokenFactory<'input>, { type Input = Input; fn input(&mut self) -> &mut Self::Input { self.input.as_mut().unwrap() } fn set_channel(&mut self, v: isize) { self.channel = v; } fn push_mode(&mut self, m: usize) { self.mode_stack.push(self.mode); self.mode = m; } fn pop_mode(&mut self) -> Option<usize> { self.mode_stack.pop().map(|mode| { self.mode = mode; mode }) } fn set_type(&mut self, t: isize) { self.token_type = t; } fn set_mode(&mut self, m: usize) { self.mode = m; } fn more(&mut self) { self.set_type(LEXER_MORE) } fn skip(&mut self) { self.set_type(LEXER_SKIP) } fn reset(&mut self) { unimplemented!() } fn get_interpreter(&self) -> Option<&LexerATNSimulator> { self.interpreter.as_deref() } }
{ &self.recog }
identifier_body
lexer.rs
//! Lexer implementation use std::borrow::Cow::Borrowed; use std::borrow::{Borrow, Cow}; use std::cell::{Cell, RefCell}; use std::rc::Rc; use crate::char_stream::{CharStream, InputData}; use crate::error_listener::{ConsoleErrorListener, ErrorListener}; use crate::errors::ANTLRError; use crate::int_stream::IntStream; use crate::lexer_atn_simulator::{ILexerATNSimulator, LexerATNSimulator}; use crate::parser::ParserNodeType; use crate::recognizer::{Actions, Recognizer}; use crate::rule_context::EmptyContextType; use crate::token::TOKEN_INVALID_TYPE; use crate::token_factory::{CommonTokenFactory, TokenAware, TokenFactory}; use crate::token_source::TokenSource; use std::ops::{Deref, DerefMut}; /// Lexer functionality required by `LexerATNSimulator` to work properly pub trait Lexer<'input>: TokenSource<'input> + Recognizer<'input, Node = EmptyContextType<'input, <Self as TokenAware<'input>>::TF>> { /// Concrete input stream used by this parser type Input: IntStream; /// Same as `TokenStream::get_input_stream` but returns concrete type instance /// important for proper inlining in hot code of `LexerATNSimulator` fn input(&mut self) -> &mut Self::Input; /// Sets channel where current token will be pushed /// /// By default two channels are available: /// - `LEXER_DEFAULT_TOKEN_CHANNEL` /// - `LEXER_HIDDEN` fn set_channel(&mut self, v: isize); /// Pushes current mode to internal mode stack and sets `m` as current lexer mode /// `pop_mode should be used to recover previous mode fn push_mode(&mut self, m: usize); /// Pops mode from internal mode stack fn pop_mode(&mut self) -> Option<usize>; /// Sets type of the current token /// Called from action to override token that will be emitted by lexer fn set_type(&mut self, t: isize); /// Sets lexer mode discarding current one fn set_mode(&mut self, m: usize); /// Used to informs lexer that it should consider next token as a continuation of the current one fn more(&mut self); /// Tells lexer to completely ignore and not emit current token. fn skip(&mut self); #[doc(hidden)] fn reset(&mut self); #[doc(hidden)] fn get_interpreter(&self) -> Option<&LexerATNSimulator>; } /// **! Usually generated by ANTLR!** /// /// This trait combines everything that can be used to extend Lexer behavior pub trait LexerRecog<'a, T: Recognizer<'a>>: Actions<'a, T> + Sized +'static { /// Callback to extend emit behavior fn before_emit(_lexer: &mut T) {} } /// Default implementation of Lexer /// /// Public fields in this struct are intended to be used by embedded actions #[allow(missing_docs)] pub struct BaseLexer< 'input, T: LexerRecog<'input, Self> +'static, Input: CharStream<TF::From>, TF: TokenFactory<'input> = CommonTokenFactory, > { /// `LexerATNSimulator` instance of this lexer pub interpreter: Option<Box<LexerATNSimulator>>, /// `CharStream` used by this lexer pub input: Option<Input>, recog: T, factory: &'input TF, error_listeners: RefCell<Vec<Box<dyn ErrorListener<'input, Self>>>>, pub token_start_char_index: isize, pub token_start_line: isize, pub token_start_column: isize, current_pos: Rc<LexerPosition>, /// Overrides token type emitted by lexer for current token pub token_type: isize, /// Make it `Some` to override token that is currently being generated by lexer pub token: Option<TF::Tok>, hit_eof: bool, /// Channel lexer is currently assigning tokens to pub channel: isize, /// stack of modes, which is used for pushMode,popMode lexer actions pub mode_stack: Vec<usize>, /// Mode lexer is currently in pub mode: usize, /// Make it `Some` to override text for token that is currently being generated by lexer pub text: Option<<TF::Data as ToOwned>::Owned>, } #[derive(Debug)] pub(crate) struct LexerPosition { pub(crate) line: Cell<isize>, pub(crate) char_position_in_line: Cell<isize>, } impl<'input, T, Input, TF> Deref for BaseLexer<'input, T, Input, TF> where T: LexerRecog<'input, Self> +'static, Input: CharStream<TF::From>, TF: TokenFactory<'input>, { type Target = T; fn deref(&self) -> &Self::Target { &self.recog } } impl<'input, T, Input, TF> DerefMut for BaseLexer<'input, T, Input, TF> where T: LexerRecog<'input, Self> +'static, Input: CharStream<TF::From>, TF: TokenFactory<'input>, { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.recog } } impl<'input, T, Input, TF> Recognizer<'input> for BaseLexer<'input, T, Input, TF> where T: LexerRecog<'input, Self> +'static, Input: CharStream<TF::From>, TF: TokenFactory<'input>, { type Node = EmptyContextType<'input, TF>; fn sempred( &mut self, _localctx: Option<&<Self::Node as ParserNodeType<'input>>::Type>, rule_index: isize, action_index: isize, ) -> bool { <T as Actions<'input, Self>>::sempred(_localctx, rule_index, action_index, self) } fn action( &mut self, _localctx: Option<&<Self::Node as ParserNodeType<'input>>::Type>, rule_index: isize, action_index: isize, ) { <T as Actions<'input, Self>>::action(_localctx, rule_index, action_index, self) } } /// Default lexer mode id pub const LEXER_DEFAULT_MODE: usize = 0; /// Special token type to indicate that lexer should continue current token on next iteration /// see `Lexer::more()` pub const LEXER_MORE: isize = -2; /// Special token type to indicate that lexer should not return current token /// usually used to skip whitespaces and comments /// see `Lexer::skip()` pub const LEXER_SKIP: isize = -3; #[doc(inline)] pub use super::token::TOKEN_DEFAULT_CHANNEL as LEXER_DEFAULT_TOKEN_CHANNEL; #[doc(inline)] pub use super::token::TOKEN_HIDDEN_CHANNEL as LEXER_HIDDEN; pub(crate) const LEXER_MIN_CHAR_VALUE: isize = 0x0000; pub(crate) const LEXER_MAX_CHAR_VALUE: isize = 0x10FFFF; impl<'input, T, Input, TF> BaseLexer<'input, T, Input, TF> where T: LexerRecog<'input, Self> +'static, Input: CharStream<TF::From>, TF: TokenFactory<'input>, { fn emit_token(&mut self, token: TF::Tok) { self.token = Some(token); } fn emit(&mut self) { <T as LexerRecog<Self>>::before_emit(self); let stop = self.get_char_index() - 1; let token = self.factory.create( Some(self.input.as_mut().unwrap()), self.token_type, self.text.take(), self.channel, self.token_start_char_index, stop, self.token_start_line, self.token_start_column, ); self.emit_token(token); } fn emit_eof(&mut self) { let token = self.factory.create( None::<&mut Input>, super::int_stream::EOF, None, LEXER_DEFAULT_TOKEN_CHANNEL, self.get_char_index(), self.get_char_index() - 1, self.get_line(), self.get_char_position_in_line(), ); self.emit_token(token) } /// Current position in input stream pub fn get_char_index(&self) -> isize { self.input.as_ref().unwrap().index() } /// Current token text pub fn get_text<'a>(&'a self) -> Cow<'a, TF::Data> where 'input: 'a, { self.text .as_ref() .map(|it| Borrowed(it.borrow())) //.unwrap_or("") .unwrap_or_else(|| { let text = self .input .as_ref() .unwrap() .get_text(self.token_start_char_index, self.get_char_index() - 1); TF::get_data(text) }) } /// Used from lexer actions to override text of the token that will be emitted next pub fn set_text(&mut self, _text: <TF::Data as ToOwned>::Owned) { self.text = Some(_text); } // fn get_all_tokens(&mut self) -> Vec<TF::Tok> { unimplemented!() } // fn get_char_error_display(&self, _c: char) -> String { unimplemented!() } /// Add error listener pub fn add_error_listener(&mut self, listener: Box<dyn ErrorListener<'input, Self>>) { self.error_listeners.borrow_mut().push(listener); } /// Remove and drop all error listeners pub fn remove_error_listeners(&mut self) { self.error_listeners.borrow_mut().clear(); } /// Creates new lexer instance pub fn new_base_lexer( input: Input, interpreter: LexerATNSimulator, recog: T, factory: &'input TF, ) -> Self { let mut lexer = Self { interpreter: Some(Box::new(interpreter)), input: Some(input), recog, factory, error_listeners: RefCell::new(vec![Box::new(ConsoleErrorListener {})]), token_start_char_index: 0, token_start_line: 0, token_start_column: 0, current_pos: Rc::new(LexerPosition { line: Cell::new(1), char_position_in_line: Cell::new(0), }), token_type: super::token::TOKEN_INVALID_TYPE, text: None, token: None, hit_eof: false, channel: super::token::TOKEN_DEFAULT_CHANNEL, // token_factory_source_pair: None, mode_stack: Vec::new(), mode: self::LEXER_DEFAULT_MODE, }; let pos = lexer.current_pos.clone(); lexer.interpreter.as_mut().unwrap().current_pos = pos; lexer } } impl<'input, T, Input, TF> TokenAware<'input> for BaseLexer<'input, T, Input, TF> where T: LexerRecog<'input, Self> +'static, Input: CharStream<TF::From>, TF: TokenFactory<'input>, { type TF = TF; } impl<'input, T, Input, TF> TokenSource<'input> for BaseLexer<'input, T, Input, TF> where T: LexerRecog<'input, Self> +'static, Input: CharStream<TF::From>, TF: TokenFactory<'input>, { type TF = TF; #[inline] #[allow(unused_labels)] fn next_token(&mut self) -> <Self::TF as TokenFactory<'input>>::Tok { assert!(self.input.is_some()); let _marker = self.input().mark(); 'outer: loop { if self.hit_eof { self.emit_eof(); break; } self.token = None; self.channel = LEXER_DEFAULT_TOKEN_CHANNEL; self.token_start_column = self .interpreter .as_ref() .unwrap() .get_char_position_in_line(); self.token_start_line = self.interpreter.as_ref().unwrap().get_line(); self.text = None; let index = self.input().index(); self.token_start_char_index = index; 'inner: loop { self.token_type = TOKEN_INVALID_TYPE; // detach from self, to allow self to be passed deeper let mut interpreter = self.interpreter.take().unwrap(); // let mut input = self.input.take().unwrap(); let result = interpreter.match_token(self.mode, self); self.interpreter = Some(interpreter); let ttype = result.unwrap_or_else(|err| { // println!("error, recovering"); notify_listeners(&mut self.error_listeners.borrow_mut(), &err, self); self.interpreter .as_mut() .unwrap() .recover(err, self.input.as_mut().unwrap()); LEXER_SKIP }); // self.input = Some(input) if self.input().la(1) == super::int_stream::EOF
if self.token_type == TOKEN_INVALID_TYPE { self.token_type = ttype; } if self.token_type == LEXER_SKIP { continue 'outer; } if self.token_type!= LEXER_MORE { break; } } if self.token.is_none() { self.emit(); break; } } self.input().release(_marker); self.token.take().unwrap() } fn get_line(&self) -> isize { self.current_pos.line.get() } fn get_char_position_in_line(&self) -> isize { self.current_pos.char_position_in_line.get() } fn get_input_stream(&mut self) -> Option<&mut dyn IntStream> { match &mut self.input { None => None, Some(x) => Some(x as _), } } fn get_source_name(&self) -> String { self.input .as_ref() .map(|it| it.get_source_name()) .unwrap_or("<none>".to_string()) } // fn set_token_factory<'c: 'b>(&mut self, f: &'c TokenFactory) { // self.factory = f; // } fn get_token_factory(&self) -> &'input TF { self.factory } } #[cold] #[inline(never)] fn notify_listeners<'input, T, Input, TF>( liseners: &mut Vec<Box<dyn ErrorListener<'input, BaseLexer<'input, T, Input, TF>>>>, e: &ANTLRError, lexer: &BaseLexer<'input, T, Input, TF>, ) where T: LexerRecog<'input, BaseLexer<'input, T, Input, TF>> +'static, Input: CharStream<TF::From>, TF: TokenFactory<'input>, { let inner = lexer .input .as_ref() .unwrap() .get_text(lexer.token_start_char_index, lexer.get_char_index()); let text = format!( "token recognition error at: '{}'", TF::get_data(inner).to_display() ); for listener in liseners.iter_mut() { listener.syntax_error( lexer, None, lexer.token_start_line, lexer.token_start_column, &text, Some(e), ) } } impl<'input, T, Input, TF> Lexer<'input> for BaseLexer<'input, T, Input, TF> where T: LexerRecog<'input, Self> +'static, Input: CharStream<TF::From>, TF: TokenFactory<'input>, { type Input = Input; fn input(&mut self) -> &mut Self::Input { self.input.as_mut().unwrap() } fn set_channel(&mut self, v: isize) { self.channel = v; } fn push_mode(&mut self, m: usize) { self.mode_stack.push(self.mode); self.mode = m; } fn pop_mode(&mut self) -> Option<usize> { self.mode_stack.pop().map(|mode| { self.mode = mode; mode }) } fn set_type(&mut self, t: isize) { self.token_type = t; } fn set_mode(&mut self, m: usize) { self.mode = m; } fn more(&mut self) { self.set_type(LEXER_MORE) } fn skip(&mut self) { self.set_type(LEXER_SKIP) } fn reset(&mut self) { unimplemented!() } fn get_interpreter(&self) -> Option<&LexerATNSimulator> { self.interpreter.as_deref() } }
{ self.hit_eof = true; }
conditional_block
lexer.rs
//! Lexer implementation use std::borrow::Cow::Borrowed; use std::borrow::{Borrow, Cow}; use std::cell::{Cell, RefCell}; use std::rc::Rc; use crate::char_stream::{CharStream, InputData}; use crate::error_listener::{ConsoleErrorListener, ErrorListener}; use crate::errors::ANTLRError; use crate::int_stream::IntStream; use crate::lexer_atn_simulator::{ILexerATNSimulator, LexerATNSimulator}; use crate::parser::ParserNodeType; use crate::recognizer::{Actions, Recognizer}; use crate::rule_context::EmptyContextType; use crate::token::TOKEN_INVALID_TYPE; use crate::token_factory::{CommonTokenFactory, TokenAware, TokenFactory}; use crate::token_source::TokenSource; use std::ops::{Deref, DerefMut}; /// Lexer functionality required by `LexerATNSimulator` to work properly pub trait Lexer<'input>: TokenSource<'input> + Recognizer<'input, Node = EmptyContextType<'input, <Self as TokenAware<'input>>::TF>> { /// Concrete input stream used by this parser type Input: IntStream; /// Same as `TokenStream::get_input_stream` but returns concrete type instance /// important for proper inlining in hot code of `LexerATNSimulator` fn input(&mut self) -> &mut Self::Input; /// Sets channel where current token will be pushed /// /// By default two channels are available: /// - `LEXER_DEFAULT_TOKEN_CHANNEL` /// - `LEXER_HIDDEN` fn set_channel(&mut self, v: isize); /// Pushes current mode to internal mode stack and sets `m` as current lexer mode /// `pop_mode should be used to recover previous mode fn push_mode(&mut self, m: usize); /// Pops mode from internal mode stack fn pop_mode(&mut self) -> Option<usize>; /// Sets type of the current token /// Called from action to override token that will be emitted by lexer fn set_type(&mut self, t: isize); /// Sets lexer mode discarding current one fn set_mode(&mut self, m: usize); /// Used to informs lexer that it should consider next token as a continuation of the current one fn more(&mut self); /// Tells lexer to completely ignore and not emit current token. fn skip(&mut self); #[doc(hidden)] fn reset(&mut self); #[doc(hidden)] fn get_interpreter(&self) -> Option<&LexerATNSimulator>; } /// **! Usually generated by ANTLR!** /// /// This trait combines everything that can be used to extend Lexer behavior pub trait LexerRecog<'a, T: Recognizer<'a>>: Actions<'a, T> + Sized +'static { /// Callback to extend emit behavior fn before_emit(_lexer: &mut T) {} } /// Default implementation of Lexer /// /// Public fields in this struct are intended to be used by embedded actions #[allow(missing_docs)] pub struct BaseLexer< 'input, T: LexerRecog<'input, Self> +'static, Input: CharStream<TF::From>, TF: TokenFactory<'input> = CommonTokenFactory, > { /// `LexerATNSimulator` instance of this lexer pub interpreter: Option<Box<LexerATNSimulator>>, /// `CharStream` used by this lexer pub input: Option<Input>, recog: T, factory: &'input TF, error_listeners: RefCell<Vec<Box<dyn ErrorListener<'input, Self>>>>, pub token_start_char_index: isize, pub token_start_line: isize, pub token_start_column: isize, current_pos: Rc<LexerPosition>, /// Overrides token type emitted by lexer for current token pub token_type: isize, /// Make it `Some` to override token that is currently being generated by lexer pub token: Option<TF::Tok>, hit_eof: bool, /// Channel lexer is currently assigning tokens to pub channel: isize, /// stack of modes, which is used for pushMode,popMode lexer actions pub mode_stack: Vec<usize>, /// Mode lexer is currently in pub mode: usize, /// Make it `Some` to override text for token that is currently being generated by lexer pub text: Option<<TF::Data as ToOwned>::Owned>, } #[derive(Debug)] pub(crate) struct LexerPosition { pub(crate) line: Cell<isize>, pub(crate) char_position_in_line: Cell<isize>, } impl<'input, T, Input, TF> Deref for BaseLexer<'input, T, Input, TF> where T: LexerRecog<'input, Self> +'static, Input: CharStream<TF::From>, TF: TokenFactory<'input>, { type Target = T; fn deref(&self) -> &Self::Target { &self.recog } } impl<'input, T, Input, TF> DerefMut for BaseLexer<'input, T, Input, TF> where T: LexerRecog<'input, Self> +'static, Input: CharStream<TF::From>, TF: TokenFactory<'input>, { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.recog } } impl<'input, T, Input, TF> Recognizer<'input> for BaseLexer<'input, T, Input, TF> where T: LexerRecog<'input, Self> +'static, Input: CharStream<TF::From>, TF: TokenFactory<'input>, { type Node = EmptyContextType<'input, TF>; fn sempred( &mut self, _localctx: Option<&<Self::Node as ParserNodeType<'input>>::Type>, rule_index: isize, action_index: isize, ) -> bool { <T as Actions<'input, Self>>::sempred(_localctx, rule_index, action_index, self) } fn action( &mut self, _localctx: Option<&<Self::Node as ParserNodeType<'input>>::Type>, rule_index: isize, action_index: isize, ) { <T as Actions<'input, Self>>::action(_localctx, rule_index, action_index, self) } } /// Default lexer mode id pub const LEXER_DEFAULT_MODE: usize = 0; /// Special token type to indicate that lexer should continue current token on next iteration /// see `Lexer::more()` pub const LEXER_MORE: isize = -2; /// Special token type to indicate that lexer should not return current token /// usually used to skip whitespaces and comments /// see `Lexer::skip()` pub const LEXER_SKIP: isize = -3; #[doc(inline)] pub use super::token::TOKEN_DEFAULT_CHANNEL as LEXER_DEFAULT_TOKEN_CHANNEL; #[doc(inline)] pub use super::token::TOKEN_HIDDEN_CHANNEL as LEXER_HIDDEN; pub(crate) const LEXER_MIN_CHAR_VALUE: isize = 0x0000; pub(crate) const LEXER_MAX_CHAR_VALUE: isize = 0x10FFFF; impl<'input, T, Input, TF> BaseLexer<'input, T, Input, TF> where T: LexerRecog<'input, Self> +'static, Input: CharStream<TF::From>, TF: TokenFactory<'input>, { fn emit_token(&mut self, token: TF::Tok) { self.token = Some(token); } fn emit(&mut self) { <T as LexerRecog<Self>>::before_emit(self); let stop = self.get_char_index() - 1; let token = self.factory.create( Some(self.input.as_mut().unwrap()), self.token_type, self.text.take(), self.channel, self.token_start_char_index, stop, self.token_start_line, self.token_start_column, ); self.emit_token(token); } fn emit_eof(&mut self) { let token = self.factory.create( None::<&mut Input>, super::int_stream::EOF, None, LEXER_DEFAULT_TOKEN_CHANNEL, self.get_char_index(), self.get_char_index() - 1, self.get_line(), self.get_char_position_in_line(), ); self.emit_token(token) } /// Current position in input stream pub fn get_char_index(&self) -> isize { self.input.as_ref().unwrap().index() } /// Current token text pub fn get_text<'a>(&'a self) -> Cow<'a, TF::Data> where 'input: 'a, { self.text .as_ref() .map(|it| Borrowed(it.borrow())) //.unwrap_or("") .unwrap_or_else(|| { let text = self .input .as_ref() .unwrap() .get_text(self.token_start_char_index, self.get_char_index() - 1); TF::get_data(text) }) } /// Used from lexer actions to override text of the token that will be emitted next pub fn set_text(&mut self, _text: <TF::Data as ToOwned>::Owned) { self.text = Some(_text); } // fn get_all_tokens(&mut self) -> Vec<TF::Tok> { unimplemented!() } // fn get_char_error_display(&self, _c: char) -> String { unimplemented!() } /// Add error listener pub fn add_error_listener(&mut self, listener: Box<dyn ErrorListener<'input, Self>>) { self.error_listeners.borrow_mut().push(listener); } /// Remove and drop all error listeners pub fn remove_error_listeners(&mut self) { self.error_listeners.borrow_mut().clear(); } /// Creates new lexer instance pub fn new_base_lexer( input: Input, interpreter: LexerATNSimulator, recog: T, factory: &'input TF, ) -> Self { let mut lexer = Self { interpreter: Some(Box::new(interpreter)), input: Some(input), recog, factory, error_listeners: RefCell::new(vec![Box::new(ConsoleErrorListener {})]), token_start_char_index: 0, token_start_line: 0, token_start_column: 0, current_pos: Rc::new(LexerPosition { line: Cell::new(1), char_position_in_line: Cell::new(0), }), token_type: super::token::TOKEN_INVALID_TYPE, text: None, token: None, hit_eof: false, channel: super::token::TOKEN_DEFAULT_CHANNEL, // token_factory_source_pair: None, mode_stack: Vec::new(), mode: self::LEXER_DEFAULT_MODE, }; let pos = lexer.current_pos.clone(); lexer.interpreter.as_mut().unwrap().current_pos = pos; lexer } } impl<'input, T, Input, TF> TokenAware<'input> for BaseLexer<'input, T, Input, TF> where T: LexerRecog<'input, Self> +'static, Input: CharStream<TF::From>, TF: TokenFactory<'input>, { type TF = TF; } impl<'input, T, Input, TF> TokenSource<'input> for BaseLexer<'input, T, Input, TF> where T: LexerRecog<'input, Self> +'static, Input: CharStream<TF::From>, TF: TokenFactory<'input>, { type TF = TF; #[inline] #[allow(unused_labels)] fn next_token(&mut self) -> <Self::TF as TokenFactory<'input>>::Tok { assert!(self.input.is_some()); let _marker = self.input().mark(); 'outer: loop { if self.hit_eof { self.emit_eof(); break; } self.token = None; self.channel = LEXER_DEFAULT_TOKEN_CHANNEL; self.token_start_column = self .interpreter .as_ref() .unwrap() .get_char_position_in_line(); self.token_start_line = self.interpreter.as_ref().unwrap().get_line(); self.text = None; let index = self.input().index(); self.token_start_char_index = index; 'inner: loop { self.token_type = TOKEN_INVALID_TYPE; // detach from self, to allow self to be passed deeper let mut interpreter = self.interpreter.take().unwrap(); // let mut input = self.input.take().unwrap(); let result = interpreter.match_token(self.mode, self); self.interpreter = Some(interpreter); let ttype = result.unwrap_or_else(|err| { // println!("error, recovering"); notify_listeners(&mut self.error_listeners.borrow_mut(), &err, self); self.interpreter .as_mut() .unwrap() .recover(err, self.input.as_mut().unwrap()); LEXER_SKIP }); // self.input = Some(input) if self.input().la(1) == super::int_stream::EOF { self.hit_eof = true; } if self.token_type == TOKEN_INVALID_TYPE { self.token_type = ttype; } if self.token_type == LEXER_SKIP { continue 'outer; } if self.token_type!= LEXER_MORE { break; } } if self.token.is_none() { self.emit(); break; } } self.input().release(_marker); self.token.take().unwrap() } fn get_line(&self) -> isize { self.current_pos.line.get() } fn get_char_position_in_line(&self) -> isize { self.current_pos.char_position_in_line.get() } fn get_input_stream(&mut self) -> Option<&mut dyn IntStream> { match &mut self.input { None => None, Some(x) => Some(x as _), } } fn get_source_name(&self) -> String { self.input .as_ref() .map(|it| it.get_source_name()) .unwrap_or("<none>".to_string()) } // fn set_token_factory<'c: 'b>(&mut self, f: &'c TokenFactory) { // self.factory = f; // } fn get_token_factory(&self) -> &'input TF { self.factory } } #[cold] #[inline(never)] fn notify_listeners<'input, T, Input, TF>( liseners: &mut Vec<Box<dyn ErrorListener<'input, BaseLexer<'input, T, Input, TF>>>>, e: &ANTLRError, lexer: &BaseLexer<'input, T, Input, TF>, ) where T: LexerRecog<'input, BaseLexer<'input, T, Input, TF>> +'static, Input: CharStream<TF::From>, TF: TokenFactory<'input>, { let inner = lexer .input .as_ref() .unwrap() .get_text(lexer.token_start_char_index, lexer.get_char_index()); let text = format!( "token recognition error at: '{}'", TF::get_data(inner).to_display() ); for listener in liseners.iter_mut() {
lexer.token_start_column, &text, Some(e), ) } } impl<'input, T, Input, TF> Lexer<'input> for BaseLexer<'input, T, Input, TF> where T: LexerRecog<'input, Self> +'static, Input: CharStream<TF::From>, TF: TokenFactory<'input>, { type Input = Input; fn input(&mut self) -> &mut Self::Input { self.input.as_mut().unwrap() } fn set_channel(&mut self, v: isize) { self.channel = v; } fn push_mode(&mut self, m: usize) { self.mode_stack.push(self.mode); self.mode = m; } fn pop_mode(&mut self) -> Option<usize> { self.mode_stack.pop().map(|mode| { self.mode = mode; mode }) } fn set_type(&mut self, t: isize) { self.token_type = t; } fn set_mode(&mut self, m: usize) { self.mode = m; } fn more(&mut self) { self.set_type(LEXER_MORE) } fn skip(&mut self) { self.set_type(LEXER_SKIP) } fn reset(&mut self) { unimplemented!() } fn get_interpreter(&self) -> Option<&LexerATNSimulator> { self.interpreter.as_deref() } }
listener.syntax_error( lexer, None, lexer.token_start_line,
random_line_split
lexer.rs
//! Lexer implementation use std::borrow::Cow::Borrowed; use std::borrow::{Borrow, Cow}; use std::cell::{Cell, RefCell}; use std::rc::Rc; use crate::char_stream::{CharStream, InputData}; use crate::error_listener::{ConsoleErrorListener, ErrorListener}; use crate::errors::ANTLRError; use crate::int_stream::IntStream; use crate::lexer_atn_simulator::{ILexerATNSimulator, LexerATNSimulator}; use crate::parser::ParserNodeType; use crate::recognizer::{Actions, Recognizer}; use crate::rule_context::EmptyContextType; use crate::token::TOKEN_INVALID_TYPE; use crate::token_factory::{CommonTokenFactory, TokenAware, TokenFactory}; use crate::token_source::TokenSource; use std::ops::{Deref, DerefMut}; /// Lexer functionality required by `LexerATNSimulator` to work properly pub trait Lexer<'input>: TokenSource<'input> + Recognizer<'input, Node = EmptyContextType<'input, <Self as TokenAware<'input>>::TF>> { /// Concrete input stream used by this parser type Input: IntStream; /// Same as `TokenStream::get_input_stream` but returns concrete type instance /// important for proper inlining in hot code of `LexerATNSimulator` fn input(&mut self) -> &mut Self::Input; /// Sets channel where current token will be pushed /// /// By default two channels are available: /// - `LEXER_DEFAULT_TOKEN_CHANNEL` /// - `LEXER_HIDDEN` fn set_channel(&mut self, v: isize); /// Pushes current mode to internal mode stack and sets `m` as current lexer mode /// `pop_mode should be used to recover previous mode fn push_mode(&mut self, m: usize); /// Pops mode from internal mode stack fn pop_mode(&mut self) -> Option<usize>; /// Sets type of the current token /// Called from action to override token that will be emitted by lexer fn set_type(&mut self, t: isize); /// Sets lexer mode discarding current one fn set_mode(&mut self, m: usize); /// Used to informs lexer that it should consider next token as a continuation of the current one fn more(&mut self); /// Tells lexer to completely ignore and not emit current token. fn skip(&mut self); #[doc(hidden)] fn reset(&mut self); #[doc(hidden)] fn get_interpreter(&self) -> Option<&LexerATNSimulator>; } /// **! Usually generated by ANTLR!** /// /// This trait combines everything that can be used to extend Lexer behavior pub trait LexerRecog<'a, T: Recognizer<'a>>: Actions<'a, T> + Sized +'static { /// Callback to extend emit behavior fn before_emit(_lexer: &mut T) {} } /// Default implementation of Lexer /// /// Public fields in this struct are intended to be used by embedded actions #[allow(missing_docs)] pub struct BaseLexer< 'input, T: LexerRecog<'input, Self> +'static, Input: CharStream<TF::From>, TF: TokenFactory<'input> = CommonTokenFactory, > { /// `LexerATNSimulator` instance of this lexer pub interpreter: Option<Box<LexerATNSimulator>>, /// `CharStream` used by this lexer pub input: Option<Input>, recog: T, factory: &'input TF, error_listeners: RefCell<Vec<Box<dyn ErrorListener<'input, Self>>>>, pub token_start_char_index: isize, pub token_start_line: isize, pub token_start_column: isize, current_pos: Rc<LexerPosition>, /// Overrides token type emitted by lexer for current token pub token_type: isize, /// Make it `Some` to override token that is currently being generated by lexer pub token: Option<TF::Tok>, hit_eof: bool, /// Channel lexer is currently assigning tokens to pub channel: isize, /// stack of modes, which is used for pushMode,popMode lexer actions pub mode_stack: Vec<usize>, /// Mode lexer is currently in pub mode: usize, /// Make it `Some` to override text for token that is currently being generated by lexer pub text: Option<<TF::Data as ToOwned>::Owned>, } #[derive(Debug)] pub(crate) struct LexerPosition { pub(crate) line: Cell<isize>, pub(crate) char_position_in_line: Cell<isize>, } impl<'input, T, Input, TF> Deref for BaseLexer<'input, T, Input, TF> where T: LexerRecog<'input, Self> +'static, Input: CharStream<TF::From>, TF: TokenFactory<'input>, { type Target = T; fn deref(&self) -> &Self::Target { &self.recog } } impl<'input, T, Input, TF> DerefMut for BaseLexer<'input, T, Input, TF> where T: LexerRecog<'input, Self> +'static, Input: CharStream<TF::From>, TF: TokenFactory<'input>, { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.recog } } impl<'input, T, Input, TF> Recognizer<'input> for BaseLexer<'input, T, Input, TF> where T: LexerRecog<'input, Self> +'static, Input: CharStream<TF::From>, TF: TokenFactory<'input>, { type Node = EmptyContextType<'input, TF>; fn sempred( &mut self, _localctx: Option<&<Self::Node as ParserNodeType<'input>>::Type>, rule_index: isize, action_index: isize, ) -> bool { <T as Actions<'input, Self>>::sempred(_localctx, rule_index, action_index, self) } fn action( &mut self, _localctx: Option<&<Self::Node as ParserNodeType<'input>>::Type>, rule_index: isize, action_index: isize, ) { <T as Actions<'input, Self>>::action(_localctx, rule_index, action_index, self) } } /// Default lexer mode id pub const LEXER_DEFAULT_MODE: usize = 0; /// Special token type to indicate that lexer should continue current token on next iteration /// see `Lexer::more()` pub const LEXER_MORE: isize = -2; /// Special token type to indicate that lexer should not return current token /// usually used to skip whitespaces and comments /// see `Lexer::skip()` pub const LEXER_SKIP: isize = -3; #[doc(inline)] pub use super::token::TOKEN_DEFAULT_CHANNEL as LEXER_DEFAULT_TOKEN_CHANNEL; #[doc(inline)] pub use super::token::TOKEN_HIDDEN_CHANNEL as LEXER_HIDDEN; pub(crate) const LEXER_MIN_CHAR_VALUE: isize = 0x0000; pub(crate) const LEXER_MAX_CHAR_VALUE: isize = 0x10FFFF; impl<'input, T, Input, TF> BaseLexer<'input, T, Input, TF> where T: LexerRecog<'input, Self> +'static, Input: CharStream<TF::From>, TF: TokenFactory<'input>, { fn emit_token(&mut self, token: TF::Tok) { self.token = Some(token); } fn emit(&mut self) { <T as LexerRecog<Self>>::before_emit(self); let stop = self.get_char_index() - 1; let token = self.factory.create( Some(self.input.as_mut().unwrap()), self.token_type, self.text.take(), self.channel, self.token_start_char_index, stop, self.token_start_line, self.token_start_column, ); self.emit_token(token); } fn emit_eof(&mut self) { let token = self.factory.create( None::<&mut Input>, super::int_stream::EOF, None, LEXER_DEFAULT_TOKEN_CHANNEL, self.get_char_index(), self.get_char_index() - 1, self.get_line(), self.get_char_position_in_line(), ); self.emit_token(token) } /// Current position in input stream pub fn get_char_index(&self) -> isize { self.input.as_ref().unwrap().index() } /// Current token text pub fn get_text<'a>(&'a self) -> Cow<'a, TF::Data> where 'input: 'a, { self.text .as_ref() .map(|it| Borrowed(it.borrow())) //.unwrap_or("") .unwrap_or_else(|| { let text = self .input .as_ref() .unwrap() .get_text(self.token_start_char_index, self.get_char_index() - 1); TF::get_data(text) }) } /// Used from lexer actions to override text of the token that will be emitted next pub fn
(&mut self, _text: <TF::Data as ToOwned>::Owned) { self.text = Some(_text); } // fn get_all_tokens(&mut self) -> Vec<TF::Tok> { unimplemented!() } // fn get_char_error_display(&self, _c: char) -> String { unimplemented!() } /// Add error listener pub fn add_error_listener(&mut self, listener: Box<dyn ErrorListener<'input, Self>>) { self.error_listeners.borrow_mut().push(listener); } /// Remove and drop all error listeners pub fn remove_error_listeners(&mut self) { self.error_listeners.borrow_mut().clear(); } /// Creates new lexer instance pub fn new_base_lexer( input: Input, interpreter: LexerATNSimulator, recog: T, factory: &'input TF, ) -> Self { let mut lexer = Self { interpreter: Some(Box::new(interpreter)), input: Some(input), recog, factory, error_listeners: RefCell::new(vec![Box::new(ConsoleErrorListener {})]), token_start_char_index: 0, token_start_line: 0, token_start_column: 0, current_pos: Rc::new(LexerPosition { line: Cell::new(1), char_position_in_line: Cell::new(0), }), token_type: super::token::TOKEN_INVALID_TYPE, text: None, token: None, hit_eof: false, channel: super::token::TOKEN_DEFAULT_CHANNEL, // token_factory_source_pair: None, mode_stack: Vec::new(), mode: self::LEXER_DEFAULT_MODE, }; let pos = lexer.current_pos.clone(); lexer.interpreter.as_mut().unwrap().current_pos = pos; lexer } } impl<'input, T, Input, TF> TokenAware<'input> for BaseLexer<'input, T, Input, TF> where T: LexerRecog<'input, Self> +'static, Input: CharStream<TF::From>, TF: TokenFactory<'input>, { type TF = TF; } impl<'input, T, Input, TF> TokenSource<'input> for BaseLexer<'input, T, Input, TF> where T: LexerRecog<'input, Self> +'static, Input: CharStream<TF::From>, TF: TokenFactory<'input>, { type TF = TF; #[inline] #[allow(unused_labels)] fn next_token(&mut self) -> <Self::TF as TokenFactory<'input>>::Tok { assert!(self.input.is_some()); let _marker = self.input().mark(); 'outer: loop { if self.hit_eof { self.emit_eof(); break; } self.token = None; self.channel = LEXER_DEFAULT_TOKEN_CHANNEL; self.token_start_column = self .interpreter .as_ref() .unwrap() .get_char_position_in_line(); self.token_start_line = self.interpreter.as_ref().unwrap().get_line(); self.text = None; let index = self.input().index(); self.token_start_char_index = index; 'inner: loop { self.token_type = TOKEN_INVALID_TYPE; // detach from self, to allow self to be passed deeper let mut interpreter = self.interpreter.take().unwrap(); // let mut input = self.input.take().unwrap(); let result = interpreter.match_token(self.mode, self); self.interpreter = Some(interpreter); let ttype = result.unwrap_or_else(|err| { // println!("error, recovering"); notify_listeners(&mut self.error_listeners.borrow_mut(), &err, self); self.interpreter .as_mut() .unwrap() .recover(err, self.input.as_mut().unwrap()); LEXER_SKIP }); // self.input = Some(input) if self.input().la(1) == super::int_stream::EOF { self.hit_eof = true; } if self.token_type == TOKEN_INVALID_TYPE { self.token_type = ttype; } if self.token_type == LEXER_SKIP { continue 'outer; } if self.token_type!= LEXER_MORE { break; } } if self.token.is_none() { self.emit(); break; } } self.input().release(_marker); self.token.take().unwrap() } fn get_line(&self) -> isize { self.current_pos.line.get() } fn get_char_position_in_line(&self) -> isize { self.current_pos.char_position_in_line.get() } fn get_input_stream(&mut self) -> Option<&mut dyn IntStream> { match &mut self.input { None => None, Some(x) => Some(x as _), } } fn get_source_name(&self) -> String { self.input .as_ref() .map(|it| it.get_source_name()) .unwrap_or("<none>".to_string()) } // fn set_token_factory<'c: 'b>(&mut self, f: &'c TokenFactory) { // self.factory = f; // } fn get_token_factory(&self) -> &'input TF { self.factory } } #[cold] #[inline(never)] fn notify_listeners<'input, T, Input, TF>( liseners: &mut Vec<Box<dyn ErrorListener<'input, BaseLexer<'input, T, Input, TF>>>>, e: &ANTLRError, lexer: &BaseLexer<'input, T, Input, TF>, ) where T: LexerRecog<'input, BaseLexer<'input, T, Input, TF>> +'static, Input: CharStream<TF::From>, TF: TokenFactory<'input>, { let inner = lexer .input .as_ref() .unwrap() .get_text(lexer.token_start_char_index, lexer.get_char_index()); let text = format!( "token recognition error at: '{}'", TF::get_data(inner).to_display() ); for listener in liseners.iter_mut() { listener.syntax_error( lexer, None, lexer.token_start_line, lexer.token_start_column, &text, Some(e), ) } } impl<'input, T, Input, TF> Lexer<'input> for BaseLexer<'input, T, Input, TF> where T: LexerRecog<'input, Self> +'static, Input: CharStream<TF::From>, TF: TokenFactory<'input>, { type Input = Input; fn input(&mut self) -> &mut Self::Input { self.input.as_mut().unwrap() } fn set_channel(&mut self, v: isize) { self.channel = v; } fn push_mode(&mut self, m: usize) { self.mode_stack.push(self.mode); self.mode = m; } fn pop_mode(&mut self) -> Option<usize> { self.mode_stack.pop().map(|mode| { self.mode = mode; mode }) } fn set_type(&mut self, t: isize) { self.token_type = t; } fn set_mode(&mut self, m: usize) { self.mode = m; } fn more(&mut self) { self.set_type(LEXER_MORE) } fn skip(&mut self) { self.set_type(LEXER_SKIP) } fn reset(&mut self) { unimplemented!() } fn get_interpreter(&self) -> Option<&LexerATNSimulator> { self.interpreter.as_deref() } }
set_text
identifier_name
dwarfdebuginfo.rs
// Copyright 2021-2023 Vector 35 Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use crate::helpers::{get_uid, resolve_specification, DieReference}; use binaryninja::{ binaryview::{BinaryView, BinaryViewBase}, debuginfo::{DebugFunctionInfo, DebugInfo}, rc::*, templatesimplifier::simplify_str_to_str, types::{Conf, FunctionParameter, Type}, }; use gimli::{DebuggingInformationEntry, Dwarf, Reader, Unit}; use log::error; use std::{ collections::{hash_map::Values, HashMap}, ffi::CString, hash::Hash, }; pub(crate) type TypeUID = usize; ///////////////////////// // FunctionInfoBuilder // TODO : Function local variables #[derive(PartialEq, Eq, Hash)] pub struct FunctionInfoBuilder { pub full_name: Option<CString>, pub raw_name: Option<CString>, pub return_type: Option<TypeUID>, pub address: Option<u64>, pub parameters: Vec<Option<(CString, TypeUID)>>, } impl FunctionInfoBuilder { pub fn update( &mut self, full_name: Option<CString>, raw_name: Option<CString>, return_type: Option<TypeUID>, address: Option<u64>, parameters: Vec<Option<(CString, TypeUID)>>, ) { if full_name.is_some() { self.full_name = full_name; } if raw_name.is_some() { self.raw_name = raw_name; } if return_type.is_some() { self.return_type = return_type; } if address.is_some() { self.address = address; } for (i, new_parameter) in parameters.into_iter().enumerate() { if let Some(old_parameter) = self.parameters.get(i) { if old_parameter.is_none() { self.parameters[i] = new_parameter; } } else { self.parameters.push(new_parameter); } } } } ////////////////////// // DebugInfoBuilder // TODO : Don't make this pub...fix the value thing pub(crate) struct DebugType { name: CString, t: Ref<Type>, commit: bool, } // DWARF info is stored and displayed in a tree, but is really a graph // The purpose of this builder is to help resolve those graph edges by mapping partial function // info and types to one DIE's UID (T) before adding the completed info to BN's debug info pub struct DebugInfoBuilder { functions: Vec<FunctionInfoBuilder>, types: HashMap<TypeUID, DebugType>, data_variables: HashMap<u64, (Option<CString>, TypeUID)>, names: HashMap<TypeUID, CString>, default_address_size: usize, } impl DebugInfoBuilder { pub fn new(view: &BinaryView) -> Self { DebugInfoBuilder { functions: vec![], types: HashMap::new(), data_variables: HashMap::new(), names: HashMap::new(), default_address_size: view.address_size(), } } pub fn default_address_size(&self) -> usize { self.default_address_size } #[allow(clippy::too_many_arguments)] pub fn insert_function( &mut self, full_name: Option<CString>, raw_name: Option<CString>, return_type: Option<TypeUID>, address: Option<u64>, parameters: Vec<Option<(CString, TypeUID)>>, ) { if let Some(function) = self.functions.iter_mut().find(|func| { (func.raw_name.is_some() && func.raw_name == raw_name) || (func.full_name.is_some() && func.full_name == full_name) }) { function.update(full_name, raw_name, return_type, address, parameters); } else { self.functions.push(FunctionInfoBuilder { full_name, raw_name, return_type, address, parameters, }); } } pub fn functions(&self) -> &[FunctionInfoBuilder] { &self.functions } pub(crate) fn types(&self) -> Values<'_, TypeUID, DebugType> { self.types.values() } pub fn add_type(&mut self, type_uid: TypeUID, name: CString, t: Ref<Type>, commit: bool) { if let Some(DebugType { name: existing_name, t: existing_type, commit: _, }) = self.types.insert( type_uid, DebugType { name: name.clone(), t: t.clone(), commit, }, ) { if existing_type!= t { error!("DWARF info contains duplicate type definition. Overwriting type `{}` (named `{:?}`) with `{}` (named `{:?}`)", existing_type, existing_name, t, name ); } } } pub fn remove_type(&mut self, type_uid: TypeUID) { self.types.remove(&type_uid); } // TODO : Non-copy? pub fn get_type(&self, type_uid: TypeUID) -> Option<(CString, Ref<Type>)> { self.types .get(&type_uid) .map(|type_ref_ref| (type_ref_ref.name.clone(), type_ref_ref.t.clone())) } pub fn contains_type(&self, type_uid: TypeUID) -> bool { self.types.get(&type_uid).is_some() } pub fn add_data_variable(&mut self, address: u64, name: Option<CString>, type_uid: TypeUID) { if let Some((_existing_name, existing_type_uid)) = self.data_variables.insert(address, (name, type_uid)) { let existing_type = self.get_type(existing_type_uid).unwrap().1; let new_type = self.get_type(type_uid).unwrap().1; if existing_type_uid!= type_uid || existing_type!= new_type { error!("DWARF info contains duplicate data variable definition. Overwriting data variable at 0x{:08x} (`{}`) with `{}`", address, self.get_type(existing_type_uid).unwrap().1, self.get_type(type_uid).unwrap().1 ); } } } pub fn set_name(&mut self, die_uid: TypeUID, name: CString) { assert!(self.names.insert(die_uid, name).is_none()); } pub fn get_name<R: Reader<Offset = usize>>( &self, dwarf: &Dwarf<R>, unit: &Unit<R>, entry: &DebuggingInformationEntry<R>, ) -> Option<CString> { match resolve_specification(dwarf, unit, entry) { DieReference::Offset(entry_offset) => self .names .get(&get_uid(unit, &unit.entry(entry_offset).unwrap())) .cloned(), DieReference::UnitAndOffset((entry_unit, entry_offset)) => self .names .get(&get_uid( &entry_unit, &entry_unit.entry(entry_offset).unwrap(), )) .cloned(), } } fn commit_types(&self, debug_info: &mut DebugInfo) { for debug_type in self.types() { if debug_type.commit { debug_info.add_type(debug_type.name.clone(), debug_type.t.as_ref()); } } } // TODO : Consume data? fn commit_data_variables(&self, debug_info: &mut DebugInfo) { for (&address, (name, type_uid)) in &self.data_variables { assert!(debug_info.add_data_variable( address, &self.get_type(*type_uid).unwrap().1, name.clone() )); } } fn commit_functions(&self, debug_info: &mut DebugInfo) { for function in self.functions() { let return_type = match function.return_type { Some(return_type_id) => { Conf::new(self.get_type(return_type_id).unwrap().1.clone(), 0) } _ => Conf::new(binaryninja::types::Type::void(), 0), }; let parameters: Vec<FunctionParameter<CString>> = function .parameters .iter() .filter_map(|parameter| match parameter { Some((name, 0)) =>
Some((name, uid)) => Some(FunctionParameter::new( self.get_type(*uid).unwrap().1, name.clone(), None, )), _ => None, }) .collect(); // TODO : Handle let platform = None; let variable_parameters = false; // let calling_convention: Option<Ref<CallingConvention<CoreArchitecture>>> = None; let function_type = binaryninja::types::Type::function(&return_type, &parameters, variable_parameters); let simplified_full_name = function .full_name .as_ref() .map(|name| simplify_str_to_str(name.as_ref()).as_str().to_owned()) .map(|simp| CString::new(simp).unwrap()); debug_info.add_function(DebugFunctionInfo::new( simplified_full_name.clone(), simplified_full_name, // TODO : This should eventually be changed, but the "full_name" should probably be the unsimplified version, and the "short_name" should be the simplified version...currently the symbols view shows the full version, so changing it here too makes it look bad in the UI function.raw_name.clone(), Some(function_type), function.address, platform, )); } } pub fn commit_info(&self, debug_info: &mut DebugInfo) { self.commit_types(debug_info); self.commit_data_variables(debug_info); self.commit_functions(debug_info); } }
{ Some(FunctionParameter::new(Type::void(), name.clone(), None)) }
conditional_block
dwarfdebuginfo.rs
// Copyright 2021-2023 Vector 35 Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use crate::helpers::{get_uid, resolve_specification, DieReference}; use binaryninja::{ binaryview::{BinaryView, BinaryViewBase}, debuginfo::{DebugFunctionInfo, DebugInfo}, rc::*, templatesimplifier::simplify_str_to_str, types::{Conf, FunctionParameter, Type}, }; use gimli::{DebuggingInformationEntry, Dwarf, Reader, Unit}; use log::error; use std::{ collections::{hash_map::Values, HashMap}, ffi::CString, hash::Hash, }; pub(crate) type TypeUID = usize; ///////////////////////// // FunctionInfoBuilder // TODO : Function local variables #[derive(PartialEq, Eq, Hash)] pub struct FunctionInfoBuilder { pub full_name: Option<CString>, pub raw_name: Option<CString>, pub return_type: Option<TypeUID>, pub address: Option<u64>, pub parameters: Vec<Option<(CString, TypeUID)>>, } impl FunctionInfoBuilder { pub fn update( &mut self, full_name: Option<CString>, raw_name: Option<CString>, return_type: Option<TypeUID>, address: Option<u64>, parameters: Vec<Option<(CString, TypeUID)>>, ) { if full_name.is_some() { self.full_name = full_name; } if raw_name.is_some() { self.raw_name = raw_name; } if return_type.is_some() { self.return_type = return_type; } if address.is_some() { self.address = address; } for (i, new_parameter) in parameters.into_iter().enumerate() { if let Some(old_parameter) = self.parameters.get(i) { if old_parameter.is_none() { self.parameters[i] = new_parameter; } } else { self.parameters.push(new_parameter); } } } } ////////////////////// // DebugInfoBuilder // TODO : Don't make this pub...fix the value thing pub(crate) struct DebugType { name: CString, t: Ref<Type>, commit: bool, } // DWARF info is stored and displayed in a tree, but is really a graph // The purpose of this builder is to help resolve those graph edges by mapping partial function // info and types to one DIE's UID (T) before adding the completed info to BN's debug info pub struct DebugInfoBuilder { functions: Vec<FunctionInfoBuilder>, types: HashMap<TypeUID, DebugType>, data_variables: HashMap<u64, (Option<CString>, TypeUID)>, names: HashMap<TypeUID, CString>, default_address_size: usize, } impl DebugInfoBuilder { pub fn new(view: &BinaryView) -> Self { DebugInfoBuilder { functions: vec![], types: HashMap::new(), data_variables: HashMap::new(), names: HashMap::new(), default_address_size: view.address_size(), } } pub fn default_address_size(&self) -> usize { self.default_address_size } #[allow(clippy::too_many_arguments)] pub fn insert_function( &mut self, full_name: Option<CString>, raw_name: Option<CString>, return_type: Option<TypeUID>, address: Option<u64>, parameters: Vec<Option<(CString, TypeUID)>>, ) { if let Some(function) = self.functions.iter_mut().find(|func| { (func.raw_name.is_some() && func.raw_name == raw_name) || (func.full_name.is_some() && func.full_name == full_name) }) { function.update(full_name, raw_name, return_type, address, parameters); } else { self.functions.push(FunctionInfoBuilder { full_name, raw_name, return_type, address, parameters, }); } } pub fn functions(&self) -> &[FunctionInfoBuilder] { &self.functions } pub(crate) fn types(&self) -> Values<'_, TypeUID, DebugType> { self.types.values() } pub fn add_type(&mut self, type_uid: TypeUID, name: CString, t: Ref<Type>, commit: bool) { if let Some(DebugType { name: existing_name, t: existing_type, commit: _, }) = self.types.insert( type_uid, DebugType { name: name.clone(), t: t.clone(), commit, }, ) { if existing_type!= t { error!("DWARF info contains duplicate type definition. Overwriting type `{}` (named `{:?}`) with `{}` (named `{:?}`)", existing_type, existing_name, t, name ); } } } pub fn remove_type(&mut self, type_uid: TypeUID) { self.types.remove(&type_uid); } // TODO : Non-copy? pub fn get_type(&self, type_uid: TypeUID) -> Option<(CString, Ref<Type>)> { self.types .get(&type_uid) .map(|type_ref_ref| (type_ref_ref.name.clone(), type_ref_ref.t.clone())) } pub fn contains_type(&self, type_uid: TypeUID) -> bool { self.types.get(&type_uid).is_some() } pub fn add_data_variable(&mut self, address: u64, name: Option<CString>, type_uid: TypeUID)
pub fn set_name(&mut self, die_uid: TypeUID, name: CString) { assert!(self.names.insert(die_uid, name).is_none()); } pub fn get_name<R: Reader<Offset = usize>>( &self, dwarf: &Dwarf<R>, unit: &Unit<R>, entry: &DebuggingInformationEntry<R>, ) -> Option<CString> { match resolve_specification(dwarf, unit, entry) { DieReference::Offset(entry_offset) => self .names .get(&get_uid(unit, &unit.entry(entry_offset).unwrap())) .cloned(), DieReference::UnitAndOffset((entry_unit, entry_offset)) => self .names .get(&get_uid( &entry_unit, &entry_unit.entry(entry_offset).unwrap(), )) .cloned(), } } fn commit_types(&self, debug_info: &mut DebugInfo) { for debug_type in self.types() { if debug_type.commit { debug_info.add_type(debug_type.name.clone(), debug_type.t.as_ref()); } } } // TODO : Consume data? fn commit_data_variables(&self, debug_info: &mut DebugInfo) { for (&address, (name, type_uid)) in &self.data_variables { assert!(debug_info.add_data_variable( address, &self.get_type(*type_uid).unwrap().1, name.clone() )); } } fn commit_functions(&self, debug_info: &mut DebugInfo) { for function in self.functions() { let return_type = match function.return_type { Some(return_type_id) => { Conf::new(self.get_type(return_type_id).unwrap().1.clone(), 0) } _ => Conf::new(binaryninja::types::Type::void(), 0), }; let parameters: Vec<FunctionParameter<CString>> = function .parameters .iter() .filter_map(|parameter| match parameter { Some((name, 0)) => { Some(FunctionParameter::new(Type::void(), name.clone(), None)) } Some((name, uid)) => Some(FunctionParameter::new( self.get_type(*uid).unwrap().1, name.clone(), None, )), _ => None, }) .collect(); // TODO : Handle let platform = None; let variable_parameters = false; // let calling_convention: Option<Ref<CallingConvention<CoreArchitecture>>> = None; let function_type = binaryninja::types::Type::function(&return_type, &parameters, variable_parameters); let simplified_full_name = function .full_name .as_ref() .map(|name| simplify_str_to_str(name.as_ref()).as_str().to_owned()) .map(|simp| CString::new(simp).unwrap()); debug_info.add_function(DebugFunctionInfo::new( simplified_full_name.clone(), simplified_full_name, // TODO : This should eventually be changed, but the "full_name" should probably be the unsimplified version, and the "short_name" should be the simplified version...currently the symbols view shows the full version, so changing it here too makes it look bad in the UI function.raw_name.clone(), Some(function_type), function.address, platform, )); } } pub fn commit_info(&self, debug_info: &mut DebugInfo) { self.commit_types(debug_info); self.commit_data_variables(debug_info); self.commit_functions(debug_info); } }
{ if let Some((_existing_name, existing_type_uid)) = self.data_variables.insert(address, (name, type_uid)) { let existing_type = self.get_type(existing_type_uid).unwrap().1; let new_type = self.get_type(type_uid).unwrap().1; if existing_type_uid != type_uid || existing_type != new_type { error!("DWARF info contains duplicate data variable definition. Overwriting data variable at 0x{:08x} (`{}`) with `{}`", address, self.get_type(existing_type_uid).unwrap().1, self.get_type(type_uid).unwrap().1 ); } } }
identifier_body
dwarfdebuginfo.rs
// Copyright 2021-2023 Vector 35 Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use crate::helpers::{get_uid, resolve_specification, DieReference}; use binaryninja::{ binaryview::{BinaryView, BinaryViewBase}, debuginfo::{DebugFunctionInfo, DebugInfo}, rc::*, templatesimplifier::simplify_str_to_str, types::{Conf, FunctionParameter, Type}, }; use gimli::{DebuggingInformationEntry, Dwarf, Reader, Unit}; use log::error; use std::{ collections::{hash_map::Values, HashMap}, ffi::CString, hash::Hash, }; pub(crate) type TypeUID = usize; ///////////////////////// // FunctionInfoBuilder // TODO : Function local variables #[derive(PartialEq, Eq, Hash)] pub struct FunctionInfoBuilder { pub full_name: Option<CString>, pub raw_name: Option<CString>, pub return_type: Option<TypeUID>, pub address: Option<u64>, pub parameters: Vec<Option<(CString, TypeUID)>>, } impl FunctionInfoBuilder { pub fn update( &mut self, full_name: Option<CString>, raw_name: Option<CString>, return_type: Option<TypeUID>, address: Option<u64>, parameters: Vec<Option<(CString, TypeUID)>>, ) { if full_name.is_some() { self.full_name = full_name; } if raw_name.is_some() { self.raw_name = raw_name; } if return_type.is_some() { self.return_type = return_type; } if address.is_some() { self.address = address; } for (i, new_parameter) in parameters.into_iter().enumerate() { if let Some(old_parameter) = self.parameters.get(i) { if old_parameter.is_none() { self.parameters[i] = new_parameter; } } else { self.parameters.push(new_parameter); } } } } ////////////////////// // DebugInfoBuilder // TODO : Don't make this pub...fix the value thing pub(crate) struct DebugType { name: CString, t: Ref<Type>, commit: bool, } // DWARF info is stored and displayed in a tree, but is really a graph // The purpose of this builder is to help resolve those graph edges by mapping partial function // info and types to one DIE's UID (T) before adding the completed info to BN's debug info pub struct DebugInfoBuilder { functions: Vec<FunctionInfoBuilder>, types: HashMap<TypeUID, DebugType>, data_variables: HashMap<u64, (Option<CString>, TypeUID)>, names: HashMap<TypeUID, CString>, default_address_size: usize, } impl DebugInfoBuilder { pub fn
(view: &BinaryView) -> Self { DebugInfoBuilder { functions: vec![], types: HashMap::new(), data_variables: HashMap::new(), names: HashMap::new(), default_address_size: view.address_size(), } } pub fn default_address_size(&self) -> usize { self.default_address_size } #[allow(clippy::too_many_arguments)] pub fn insert_function( &mut self, full_name: Option<CString>, raw_name: Option<CString>, return_type: Option<TypeUID>, address: Option<u64>, parameters: Vec<Option<(CString, TypeUID)>>, ) { if let Some(function) = self.functions.iter_mut().find(|func| { (func.raw_name.is_some() && func.raw_name == raw_name) || (func.full_name.is_some() && func.full_name == full_name) }) { function.update(full_name, raw_name, return_type, address, parameters); } else { self.functions.push(FunctionInfoBuilder { full_name, raw_name, return_type, address, parameters, }); } } pub fn functions(&self) -> &[FunctionInfoBuilder] { &self.functions } pub(crate) fn types(&self) -> Values<'_, TypeUID, DebugType> { self.types.values() } pub fn add_type(&mut self, type_uid: TypeUID, name: CString, t: Ref<Type>, commit: bool) { if let Some(DebugType { name: existing_name, t: existing_type, commit: _, }) = self.types.insert( type_uid, DebugType { name: name.clone(), t: t.clone(), commit, }, ) { if existing_type!= t { error!("DWARF info contains duplicate type definition. Overwriting type `{}` (named `{:?}`) with `{}` (named `{:?}`)", existing_type, existing_name, t, name ); } } } pub fn remove_type(&mut self, type_uid: TypeUID) { self.types.remove(&type_uid); } // TODO : Non-copy? pub fn get_type(&self, type_uid: TypeUID) -> Option<(CString, Ref<Type>)> { self.types .get(&type_uid) .map(|type_ref_ref| (type_ref_ref.name.clone(), type_ref_ref.t.clone())) } pub fn contains_type(&self, type_uid: TypeUID) -> bool { self.types.get(&type_uid).is_some() } pub fn add_data_variable(&mut self, address: u64, name: Option<CString>, type_uid: TypeUID) { if let Some((_existing_name, existing_type_uid)) = self.data_variables.insert(address, (name, type_uid)) { let existing_type = self.get_type(existing_type_uid).unwrap().1; let new_type = self.get_type(type_uid).unwrap().1; if existing_type_uid!= type_uid || existing_type!= new_type { error!("DWARF info contains duplicate data variable definition. Overwriting data variable at 0x{:08x} (`{}`) with `{}`", address, self.get_type(existing_type_uid).unwrap().1, self.get_type(type_uid).unwrap().1 ); } } } pub fn set_name(&mut self, die_uid: TypeUID, name: CString) { assert!(self.names.insert(die_uid, name).is_none()); } pub fn get_name<R: Reader<Offset = usize>>( &self, dwarf: &Dwarf<R>, unit: &Unit<R>, entry: &DebuggingInformationEntry<R>, ) -> Option<CString> { match resolve_specification(dwarf, unit, entry) { DieReference::Offset(entry_offset) => self .names .get(&get_uid(unit, &unit.entry(entry_offset).unwrap())) .cloned(), DieReference::UnitAndOffset((entry_unit, entry_offset)) => self .names .get(&get_uid( &entry_unit, &entry_unit.entry(entry_offset).unwrap(), )) .cloned(), } } fn commit_types(&self, debug_info: &mut DebugInfo) { for debug_type in self.types() { if debug_type.commit { debug_info.add_type(debug_type.name.clone(), debug_type.t.as_ref()); } } } // TODO : Consume data? fn commit_data_variables(&self, debug_info: &mut DebugInfo) { for (&address, (name, type_uid)) in &self.data_variables { assert!(debug_info.add_data_variable( address, &self.get_type(*type_uid).unwrap().1, name.clone() )); } } fn commit_functions(&self, debug_info: &mut DebugInfo) { for function in self.functions() { let return_type = match function.return_type { Some(return_type_id) => { Conf::new(self.get_type(return_type_id).unwrap().1.clone(), 0) } _ => Conf::new(binaryninja::types::Type::void(), 0), }; let parameters: Vec<FunctionParameter<CString>> = function .parameters .iter() .filter_map(|parameter| match parameter { Some((name, 0)) => { Some(FunctionParameter::new(Type::void(), name.clone(), None)) } Some((name, uid)) => Some(FunctionParameter::new( self.get_type(*uid).unwrap().1, name.clone(), None, )), _ => None, }) .collect(); // TODO : Handle let platform = None; let variable_parameters = false; // let calling_convention: Option<Ref<CallingConvention<CoreArchitecture>>> = None; let function_type = binaryninja::types::Type::function(&return_type, &parameters, variable_parameters); let simplified_full_name = function .full_name .as_ref() .map(|name| simplify_str_to_str(name.as_ref()).as_str().to_owned()) .map(|simp| CString::new(simp).unwrap()); debug_info.add_function(DebugFunctionInfo::new( simplified_full_name.clone(), simplified_full_name, // TODO : This should eventually be changed, but the "full_name" should probably be the unsimplified version, and the "short_name" should be the simplified version...currently the symbols view shows the full version, so changing it here too makes it look bad in the UI function.raw_name.clone(), Some(function_type), function.address, platform, )); } } pub fn commit_info(&self, debug_info: &mut DebugInfo) { self.commit_types(debug_info); self.commit_data_variables(debug_info); self.commit_functions(debug_info); } }
new
identifier_name
dwarfdebuginfo.rs
// Copyright 2021-2023 Vector 35 Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use crate::helpers::{get_uid, resolve_specification, DieReference}; use binaryninja::{ binaryview::{BinaryView, BinaryViewBase}, debuginfo::{DebugFunctionInfo, DebugInfo}, rc::*, templatesimplifier::simplify_str_to_str, types::{Conf, FunctionParameter, Type}, }; use gimli::{DebuggingInformationEntry, Dwarf, Reader, Unit}; use log::error; use std::{ collections::{hash_map::Values, HashMap}, ffi::CString, hash::Hash, }; pub(crate) type TypeUID = usize; ///////////////////////// // FunctionInfoBuilder // TODO : Function local variables #[derive(PartialEq, Eq, Hash)] pub struct FunctionInfoBuilder { pub full_name: Option<CString>, pub raw_name: Option<CString>, pub return_type: Option<TypeUID>, pub address: Option<u64>, pub parameters: Vec<Option<(CString, TypeUID)>>, } impl FunctionInfoBuilder { pub fn update( &mut self, full_name: Option<CString>, raw_name: Option<CString>, return_type: Option<TypeUID>, address: Option<u64>, parameters: Vec<Option<(CString, TypeUID)>>, ) { if full_name.is_some() { self.full_name = full_name; } if raw_name.is_some() { self.raw_name = raw_name; } if return_type.is_some() { self.return_type = return_type; } if address.is_some() { self.address = address; } for (i, new_parameter) in parameters.into_iter().enumerate() { if let Some(old_parameter) = self.parameters.get(i) { if old_parameter.is_none() { self.parameters[i] = new_parameter; } } else { self.parameters.push(new_parameter); } } } } ////////////////////// // DebugInfoBuilder // TODO : Don't make this pub...fix the value thing pub(crate) struct DebugType { name: CString, t: Ref<Type>, commit: bool, } // DWARF info is stored and displayed in a tree, but is really a graph // The purpose of this builder is to help resolve those graph edges by mapping partial function // info and types to one DIE's UID (T) before adding the completed info to BN's debug info pub struct DebugInfoBuilder { functions: Vec<FunctionInfoBuilder>, types: HashMap<TypeUID, DebugType>, data_variables: HashMap<u64, (Option<CString>, TypeUID)>, names: HashMap<TypeUID, CString>, default_address_size: usize, } impl DebugInfoBuilder { pub fn new(view: &BinaryView) -> Self { DebugInfoBuilder { functions: vec![], types: HashMap::new(), data_variables: HashMap::new(), names: HashMap::new(), default_address_size: view.address_size(), } } pub fn default_address_size(&self) -> usize { self.default_address_size } #[allow(clippy::too_many_arguments)] pub fn insert_function(
raw_name: Option<CString>, return_type: Option<TypeUID>, address: Option<u64>, parameters: Vec<Option<(CString, TypeUID)>>, ) { if let Some(function) = self.functions.iter_mut().find(|func| { (func.raw_name.is_some() && func.raw_name == raw_name) || (func.full_name.is_some() && func.full_name == full_name) }) { function.update(full_name, raw_name, return_type, address, parameters); } else { self.functions.push(FunctionInfoBuilder { full_name, raw_name, return_type, address, parameters, }); } } pub fn functions(&self) -> &[FunctionInfoBuilder] { &self.functions } pub(crate) fn types(&self) -> Values<'_, TypeUID, DebugType> { self.types.values() } pub fn add_type(&mut self, type_uid: TypeUID, name: CString, t: Ref<Type>, commit: bool) { if let Some(DebugType { name: existing_name, t: existing_type, commit: _, }) = self.types.insert( type_uid, DebugType { name: name.clone(), t: t.clone(), commit, }, ) { if existing_type!= t { error!("DWARF info contains duplicate type definition. Overwriting type `{}` (named `{:?}`) with `{}` (named `{:?}`)", existing_type, existing_name, t, name ); } } } pub fn remove_type(&mut self, type_uid: TypeUID) { self.types.remove(&type_uid); } // TODO : Non-copy? pub fn get_type(&self, type_uid: TypeUID) -> Option<(CString, Ref<Type>)> { self.types .get(&type_uid) .map(|type_ref_ref| (type_ref_ref.name.clone(), type_ref_ref.t.clone())) } pub fn contains_type(&self, type_uid: TypeUID) -> bool { self.types.get(&type_uid).is_some() } pub fn add_data_variable(&mut self, address: u64, name: Option<CString>, type_uid: TypeUID) { if let Some((_existing_name, existing_type_uid)) = self.data_variables.insert(address, (name, type_uid)) { let existing_type = self.get_type(existing_type_uid).unwrap().1; let new_type = self.get_type(type_uid).unwrap().1; if existing_type_uid!= type_uid || existing_type!= new_type { error!("DWARF info contains duplicate data variable definition. Overwriting data variable at 0x{:08x} (`{}`) with `{}`", address, self.get_type(existing_type_uid).unwrap().1, self.get_type(type_uid).unwrap().1 ); } } } pub fn set_name(&mut self, die_uid: TypeUID, name: CString) { assert!(self.names.insert(die_uid, name).is_none()); } pub fn get_name<R: Reader<Offset = usize>>( &self, dwarf: &Dwarf<R>, unit: &Unit<R>, entry: &DebuggingInformationEntry<R>, ) -> Option<CString> { match resolve_specification(dwarf, unit, entry) { DieReference::Offset(entry_offset) => self .names .get(&get_uid(unit, &unit.entry(entry_offset).unwrap())) .cloned(), DieReference::UnitAndOffset((entry_unit, entry_offset)) => self .names .get(&get_uid( &entry_unit, &entry_unit.entry(entry_offset).unwrap(), )) .cloned(), } } fn commit_types(&self, debug_info: &mut DebugInfo) { for debug_type in self.types() { if debug_type.commit { debug_info.add_type(debug_type.name.clone(), debug_type.t.as_ref()); } } } // TODO : Consume data? fn commit_data_variables(&self, debug_info: &mut DebugInfo) { for (&address, (name, type_uid)) in &self.data_variables { assert!(debug_info.add_data_variable( address, &self.get_type(*type_uid).unwrap().1, name.clone() )); } } fn commit_functions(&self, debug_info: &mut DebugInfo) { for function in self.functions() { let return_type = match function.return_type { Some(return_type_id) => { Conf::new(self.get_type(return_type_id).unwrap().1.clone(), 0) } _ => Conf::new(binaryninja::types::Type::void(), 0), }; let parameters: Vec<FunctionParameter<CString>> = function .parameters .iter() .filter_map(|parameter| match parameter { Some((name, 0)) => { Some(FunctionParameter::new(Type::void(), name.clone(), None)) } Some((name, uid)) => Some(FunctionParameter::new( self.get_type(*uid).unwrap().1, name.clone(), None, )), _ => None, }) .collect(); // TODO : Handle let platform = None; let variable_parameters = false; // let calling_convention: Option<Ref<CallingConvention<CoreArchitecture>>> = None; let function_type = binaryninja::types::Type::function(&return_type, &parameters, variable_parameters); let simplified_full_name = function .full_name .as_ref() .map(|name| simplify_str_to_str(name.as_ref()).as_str().to_owned()) .map(|simp| CString::new(simp).unwrap()); debug_info.add_function(DebugFunctionInfo::new( simplified_full_name.clone(), simplified_full_name, // TODO : This should eventually be changed, but the "full_name" should probably be the unsimplified version, and the "short_name" should be the simplified version...currently the symbols view shows the full version, so changing it here too makes it look bad in the UI function.raw_name.clone(), Some(function_type), function.address, platform, )); } } pub fn commit_info(&self, debug_info: &mut DebugInfo) { self.commit_types(debug_info); self.commit_data_variables(debug_info); self.commit_functions(debug_info); } }
&mut self, full_name: Option<CString>,
random_line_split
intcode.rs
//! # Day 2 1202 Program Alarm //! //! ## Part 1 //! //! On the way to your gravity assist around the Moon, your ship computer beeps //! angrily about a "1202 program alarm". On the radio, an Elf is already //! explaining how to handle the situation: "Don't worry, that's perfectly norma--" //! //! The ship computer bursts into flames. //! //! You notify the Elves that the computer's magic smoke seems to have escaped. //! //! "That computer ran Intcode programs like the gravity assist program it was //! working on; surely there are enough spare parts up there to build a new //! Intcode computer!" //! //! An Intcode program is a list of integers separated by commas (like 1,0,0,3,99). //! To run one, start by looking at the first integer (called position 0). Here, //! you will find an opcode - either 1, 2, or 99. The opcode indicates what to do; //! for example, 99 means that the program is finished and should immediately halt. //! Encountering an unknown opcode means something went wrong. //! //! Opcode 1 adds together numbers read from two positions and stores the result //! in a third position. The three integers immediately after the opcode tell you //! these three positions - the first two indicate the positions from which you //! should read the input values, and the third indicates the position at which //! the output should be stored. //! //! For example, if your Intcode computer encounters 1,10,20,30, it should read //! the values at positions 10 and 20, add those values, and then overwrite the //! value at position 30 with their sum. //! //! Opcode 2 works exactly like opcode 1, except it multiplies the two inputs //! instead of adding them. Again, the three integers after the opcode indicate //! where the inputs and outputs are, not their values. //! //! Once you're done processing an opcode, move to the next one by stepping //! forward 4 positions. //! //! For example, suppose you have the following program: //! //! ```text //! 1,9,10,3,2,3,11,0,99,30,40,50 //! ``` //! //! For the purposes of illustration, here is the same program split into //! multiple lines: //! //! ```text //! 1,9,10,3, //! 2,3,11,0, //! 99, //! 30,40,50 //! ``` //! //! The first four integers, `1,9,10,3`, are at positions `0`, `1`, `2`, and `3`. //! Together, they represent the first opcode (`1`, addition), the positions of //! the two inputs (`9` and `10`), and the position of the output (`3`). //! To handle this opcode, you first need to get the values at the input positions: //! position `9` contains `30`, and position `10` contains `40`. Add these numbers //! together to get `70`. Then, store this value at the output position; here, //! the output position (`3`) is at position `3`, so it overwrites itself. //! Afterward, the program looks like this: //! //! ```text //! 1,9,10,70, //! 2,3,11,0, //! 99, //! 30,40,50 //! ``` //! //! Step forward 4 positions to reach the next opcode, `2`. //! This opcode works just like the previous, but it multiplies instead of adding. //! The inputs are at positions `3` and `11`; these positions contain `70` and //! `50` respectively. Multiplying these produces `3500`; this is stored at //! position `0`: //! //! ```text //! 3500,9,10,70, //! 2,3,11,0, //! 99, //! 30,40,50 //! ``` //! //! Stepping forward 4 more positions arrives at opcode `99`, halting the //! program. //! //! Here are the initial and final states of a few more small programs: //! //! - `1,0,0,0,99` becomes `2,0,0,0,99` (1 + 1 = 2). //! - `2,3,0,3,99` becomes `2,3,0,6,99` (3 * 2 = 6). //! - `2,4,4,5,99,0` becomes `2,4,4,5,99,9801` (99 * 99 = 9801). //! - `1,1,1,4,99,5,6,0,99` becomes `30,1,1,4,2,5,6,0,99`. //! //! Once you have a working computer, the first step is to restore the gravity //! assist program (your puzzle input) to the "1202 program alarm" state it had //! just before the last computer caught fire. //! To do this, before running the program, replace position `1` with the value //! `12` and replace position `2` with the value `2`. What value is left at //! position `0` after the program halts? //! //! ## Part 2 //! //! "Good, the new computer seems to be working correctly! Keep it nearby during //! this mission - you'll probably use it again. Real Intcode computers support //! many more features than your new one, but we'll let you know what they are //! as you need them." //! //! "However, your current priority should be to complete your gravity assist //! around the Moon. For this mission to succeed, we should settle on some //! terminology for the parts you've already built." //! //! Intcode programs are given as a list of integers; these values are used as //! the initial state for the computer's memory. When you run an Intcode program, //! make sure to start by initializing memory to the program's values. A position //! in memory is called an address (for example, the first value in memory is at //! "address 0"). //! //! Opcodes (like 1, 2, or 99) mark the beginning of an instruction. The values //! used immediately after an opcode, if any, are called the instruction's //! parameters. For example, in the instruction 1,2,3,4, 1 is the opcode; 2, 3, //! and 4 are the parameters. The instruction 99 contains only an opcode and has //! no parameters. //! //! The address of the current instruction is called the instruction pointer; it //! starts at 0. After an instruction finishes, the instruction pointer increases //! by the number of values in the instruction; until you add more instructions //! to the computer, this is always 4 (1 opcode + 3 parameters) for the add and //! multiply instructions. (The halt instruction would increase the instruction //! pointer by 1, but it halts the program instead.) //! //! "With terminology out of the way, we're ready to proceed. To complete the //! gravity assist, you need to determine what pair of inputs produces the //! output 19690720." //! //! The inputs should still be provided to the program by replacing the values //! at addresses 1 and 2, just like before. In this program, the value placed in //! address 1 is called the noun, and the value placed in address 2 is called //! the verb. Each of the two input values will be between 0 and 99, inclusive. //! //! Once the program has halted, its output is available at address 0, also just
//! other words, don't reuse memory from a previous attempt. //! //! Find the input noun and verb that cause the program to produce the output //! 19690720. What is 100 * noun + verb? (For example, if noun=12 and verb=2, //! the answer would be 1202.) //! //! # Day 5: Sunny with a Chance of Asteroids //! //! ## Part 1 //! //! You're starting to sweat as the ship makes its way toward Mercury. The Elves //! suggest that you get the air conditioner working by upgrading your ship //! computer to support the Thermal Environment Supervision Terminal. //! //! The Thermal Environment Supervision Terminal (TEST) starts by running a //! diagnostic program (your puzzle input). The TEST diagnostic program will run //! on your existing Intcode computer after a few modifications: //! //! First, you'll need to add **two new instructions**: //! //! - Opcode `3` takes a single integer as **input** and saves it to the position //! given by its only parameter. For example, the instruction `3,50` would take //! an input value and store it at address `50`. //! - Opcode `4` **outputs** the value of its only parameter. For example, the //! instruction `4,50` would output the value at address `50`. //! //! Programs that use these instructions will come with documentation that //! explains what should be connected to the input and output. //! The program `3,0,4,0,99` outputs whatever it gets as input, then halts. //! //! Second, you'll need to add support for parameter modes: //! //! Each parameter of an instruction is handled based on its parameter mode. //! Right now, your ship computer already understands parameter mode 0, position //! mode, which causes the parameter to be interpreted as a position - if the //! parameter is 50, its value is the value stored at address 50 in memory. //! Until now, all parameters have been in position mode. //! //! Now, your ship computer will also need to handle parameters in mode 1, //! immediate mode. In immediate mode, a parameter is interpreted as a value - if //! the parameter is 50, its value is simply 50. //! //! Parameter modes are stored in the same value as the instruction's opcode. //! The opcode is a two-digit number based only on the ones and tens digit of the //! value, that is, the opcode is the rightmost two digits of the first value in //! an instruction. Parameter modes are single digits, one per parameter, read //! right-to-left from the opcode: the first parameter's mode is in the hundreds //! digit, the second parameter's mode is in the thousands digit, the third //! parameter's mode is in the ten-thousands digit, and so on. //! Any missing modes are 0. //! //! For example, consider the program `1002,4,3,4,33`. //! //! The first instruction, `1002,4,3,4`, is a multiply instruction - the rightmost //! two digits of the first value, 02, indicate opcode 2, multiplication. //! Then, going right to left, the parameter modes are 0 (hundreds digit), //! 1 (thousands digit), and 0 (ten-thousands digit, not present and therefore //! zero): //! //! ```text //! ABCDE //! 1002 //! //! DE - two-digit opcode, 02 == opcode 2 //! C - mode of 1st parameter, 0 == position mode //! B - mode of 2nd parameter, 1 == immediate mode //! A - mode of 3rd parameter, 0 == position mode, //! omitted due to being a leading zero //! ``` //! //! This instruction multiplies its first two parameters. //! The first parameter, 4 in position mode, works like it did before - its value //! is the value stored at address 4 (33). The second parameter, 3 in immediate //! mode, simply has value 3. The result of this operation, 33 * 3 = 99, is written //! according to the third parameter, 4 in position mode, which also works like //! it did before - 99 is written to address 4. //! //! Parameters that an instruction writes to will never be in immediate mode. //! //! Finally, some notes: //! //! - It is important to remember that the instruction pointer should increase by //! the number of values in the instruction after the instruction finishes. //! Because of the new instructions, this amount is no longer always `4`. //! - Integers can be negative: `1101,100,-1,4,0` is a valid program (find //! `100 + -1`, store the result in position `4`). //! //! The TEST diagnostic program will start by requesting from the user the ID of //! the system to test by running an input instruction - provide it 1, the ID for //! the ship's air conditioner unit. //! //! It will then perform a series of diagnostic tests confirming that various //! parts of the Intcode computer, like parameter modes, function correctly. //! For each test, it will run an output instruction indicating how far the result //! of the test was from the expected value, where 0 means the test was successful. //! Non-zero outputs mean that a function is not working correctly; check the //! instructions that were run before the output instruction to see which one //! failed. //! //! Finally, the program will output a diagnostic code and immediately halt. //! This final output isn't an error; an output followed immediately by a halt //! means the program finished. If all outputs were zero except the diagnostic //! code, the diagnostic program ran successfully. //! //! After providing 1 to the only input instruction and passing all the tests, //! what diagnostic code does the program produce? use std::convert::TryFrom; use std::str::FromStr; #[derive(Debug, PartialEq)] struct OpHeader { mode1: usize, mode2: usize, mode3: usize, opcode: usize, } impl FromStr for OpHeader { type Err = (); fn from_str(s: &str) -> Result<Self, Self::Err> { // initial string should not be larger than 5 or smaller than 1 chars. if s.len() > 5 || s.len() < 1 { return Err(()); } let padded = format!("{:0>5}", s.chars().take(5).collect::<String>()); let (modes, opcode) = padded.split_at(3); let modes: Vec<u32> = modes.chars().filter_map(|c| c.to_digit(10)).collect(); let opcode: usize = opcode.parse().map_err(|_| ())?; Ok(OpHeader { mode1: modes[2] as usize, mode2: modes[1] as usize, mode3: modes[0] as usize, opcode, }) } } impl TryFrom<i32> for OpHeader { type Error = (); fn try_from(value: i32) -> Result<Self, Self::Error> { value.to_string().parse() } } #[derive(Debug)] enum Param { Immediate(i32), Position(usize), } impl Param { pub fn from_pair((mode, value): (usize, i32)) -> Self { match mode { 0 => Param::Position(value as usize), 1 => Param::Immediate(value), _ => unreachable!(), } } } #[derive(Debug)] enum Op { Add { a: Param, b: Param, out: usize }, Multiply { a: Param, b: Param, out: usize }, Input { out: usize }, Output { value: Param }, Halt, Unknown, } /// Builds an `Op` from `data` by reading up to 4 items from a given offset. fn read_instruction(offset: usize, data: &[i32]) -> Op { // FIXME: add support for Input/Output let header: Option<OpHeader> = data.get(offset).and_then(|x| OpHeader::try_from(*x).ok()); match ( header, data.get(offset + 1).map(|x| *x), data.get(offset + 2).map(|x| *x), data.get(offset + 3).map(|x| *x), ) { ( Some(OpHeader { opcode: 1, mode1, mode2, mode3, }), Some(a), Some(b), Some(out), ) => Op::Add { a: Param::from_pair((mode1, a)), b: Param::from_pair((mode2, b)), out: match Param::from_pair((mode3, out)) { Param::Position(out) => out, _ => unreachable!("output params cannot be immediate"), }, }, ( Some(OpHeader { opcode: 2, mode1, mode2, mode3, }), Some(a), Some(b), Some(out), ) => Op::Multiply { a: Param::from_pair((mode1, a)), b: Param::from_pair((mode2, b)), out: match Param::from_pair((mode3, out)) { Param::Position(out) => out, _ => unreachable!("output params cannot be immediate"), }, }, (Some(OpHeader { opcode: 3,.. }), Some(out), _, _) => Op::Input { out: out as usize }, ( Some(OpHeader { opcode: 4, mode1,.. }), Some(value), _, _, ) => Op::Output { value: Param::from_pair((mode1, value)), }, (Some(OpHeader { opcode: 99,.. }), _, _, _) => Op::Halt, _ => Op::Unknown, } } fn read_value(param: Param, data: &[i32]) -> Option<i32> { match param { Param::Position(idx) => data.get(idx).map(|x| *x), Param::Immediate(val) => Some(val), } } use std::io::BufRead; fn prompt_for_input() -> Result<i32, ()> { let mut buf = String::new(); println!("Waiting for input... >"); std::io::stdin() .lock() .read_line(&mut buf) .expect("input read"); buf.trim().parse().map_err(|e| { eprintln!("{}", e); }) } /// Run an intcode program. pub fn compute(data: &mut [i32]) { let mut i = 0; loop { // FIXME: make read_instruction an iterator so it can manage the increment internally match read_instruction(i, &data) { Op::Add { a, b, out } => { let a = read_value(a, data).unwrap(); let b = read_value(b, data).unwrap(); data[out] = a + b; i += 4; } Op::Multiply { a, b, out } => { let a = read_value(a, data).unwrap(); let b = read_value(b, data).unwrap(); data[out] = a * b; i += 4; } Op::Input { out } => { let value = prompt_for_input().unwrap(); data[out] = value; i += 2; } Op::Output { value } => { let value = read_value(value, data).unwrap(); println!("offset={}, value={}", i, value); i += 2; } Op::Halt => break, _ => unreachable!(), } } } /// Attempt to identify the noun and verb (injected header values) which will /// yield a certain target from a source intcode program by way of permutations. pub fn solve(target: i32, data: &[i32]) -> Result<(i32, i32), ()> { for (noun, verb) in (0..=99).flat_map(|i| (0..=99).map(move |j| (i, j))) { let mut input = data.to_vec(); input[1] = noun; input[2] = verb; compute(&mut input); if input[0] == target { return Ok((noun, verb)); } } Err(()) } #[cfg(test)] mod day02_1_tests { use super::compute; #[test] fn test_example_1() { let mut input = vec![1, 0, 0, 0, 99]; compute(&mut input); assert_eq!(&input, &[2, 0, 0, 0, 99]); } #[test] fn test_example_2() { let mut input = vec![2, 3, 0, 3, 99]; compute(&mut input); assert_eq!(&input, &[2, 3, 0, 6, 99]); } #[test] fn test_example_3() { let mut input = vec![2, 4, 4, 5, 99, 0]; compute(&mut input); assert_eq!(&input, &[2, 4, 4, 5, 99, 9801]); } #[test] fn test_example_4() { let mut input = vec![1, 1, 1, 4, 99, 5, 6, 0, 99]; compute(&mut input); assert_eq!(&input, &[30, 1, 1, 4, 2, 5, 6, 0, 99]); } } #[cfg(test)] mod day05_1_tests { use super::{compute, OpHeader}; #[test] fn test_header_pad() { // when the header is "short" it should be padded on the left with zeros assert_eq!( "102".parse::<OpHeader>().unwrap(), OpHeader { mode1: 1, mode2: 0, mode3: 0, opcode: 2 } ); } #[test] fn test_header_parse_two_digit_opcode() { assert_eq!( "1022".parse::<OpHeader>().unwrap(), OpHeader { mode1: 0, mode2: 1, mode3: 0, opcode: 22 } ); } #[test] fn test_example_1() { let mut input = vec![1002, 4, 3, 4, 33]; compute(&mut input); assert_eq!(&input, &[1002, 4, 3, 4, 99]); } }
//! like before. Each time you try a pair of inputs, make sure you first reset //! the computer's memory to the values in the program (your puzzle input) - in
random_line_split
intcode.rs
//! # Day 2 1202 Program Alarm //! //! ## Part 1 //! //! On the way to your gravity assist around the Moon, your ship computer beeps //! angrily about a "1202 program alarm". On the radio, an Elf is already //! explaining how to handle the situation: "Don't worry, that's perfectly norma--" //! //! The ship computer bursts into flames. //! //! You notify the Elves that the computer's magic smoke seems to have escaped. //! //! "That computer ran Intcode programs like the gravity assist program it was //! working on; surely there are enough spare parts up there to build a new //! Intcode computer!" //! //! An Intcode program is a list of integers separated by commas (like 1,0,0,3,99). //! To run one, start by looking at the first integer (called position 0). Here, //! you will find an opcode - either 1, 2, or 99. The opcode indicates what to do; //! for example, 99 means that the program is finished and should immediately halt. //! Encountering an unknown opcode means something went wrong. //! //! Opcode 1 adds together numbers read from two positions and stores the result //! in a third position. The three integers immediately after the opcode tell you //! these three positions - the first two indicate the positions from which you //! should read the input values, and the third indicates the position at which //! the output should be stored. //! //! For example, if your Intcode computer encounters 1,10,20,30, it should read //! the values at positions 10 and 20, add those values, and then overwrite the //! value at position 30 with their sum. //! //! Opcode 2 works exactly like opcode 1, except it multiplies the two inputs //! instead of adding them. Again, the three integers after the opcode indicate //! where the inputs and outputs are, not their values. //! //! Once you're done processing an opcode, move to the next one by stepping //! forward 4 positions. //! //! For example, suppose you have the following program: //! //! ```text //! 1,9,10,3,2,3,11,0,99,30,40,50 //! ``` //! //! For the purposes of illustration, here is the same program split into //! multiple lines: //! //! ```text //! 1,9,10,3, //! 2,3,11,0, //! 99, //! 30,40,50 //! ``` //! //! The first four integers, `1,9,10,3`, are at positions `0`, `1`, `2`, and `3`. //! Together, they represent the first opcode (`1`, addition), the positions of //! the two inputs (`9` and `10`), and the position of the output (`3`). //! To handle this opcode, you first need to get the values at the input positions: //! position `9` contains `30`, and position `10` contains `40`. Add these numbers //! together to get `70`. Then, store this value at the output position; here, //! the output position (`3`) is at position `3`, so it overwrites itself. //! Afterward, the program looks like this: //! //! ```text //! 1,9,10,70, //! 2,3,11,0, //! 99, //! 30,40,50 //! ``` //! //! Step forward 4 positions to reach the next opcode, `2`. //! This opcode works just like the previous, but it multiplies instead of adding. //! The inputs are at positions `3` and `11`; these positions contain `70` and //! `50` respectively. Multiplying these produces `3500`; this is stored at //! position `0`: //! //! ```text //! 3500,9,10,70, //! 2,3,11,0, //! 99, //! 30,40,50 //! ``` //! //! Stepping forward 4 more positions arrives at opcode `99`, halting the //! program. //! //! Here are the initial and final states of a few more small programs: //! //! - `1,0,0,0,99` becomes `2,0,0,0,99` (1 + 1 = 2). //! - `2,3,0,3,99` becomes `2,3,0,6,99` (3 * 2 = 6). //! - `2,4,4,5,99,0` becomes `2,4,4,5,99,9801` (99 * 99 = 9801). //! - `1,1,1,4,99,5,6,0,99` becomes `30,1,1,4,2,5,6,0,99`. //! //! Once you have a working computer, the first step is to restore the gravity //! assist program (your puzzle input) to the "1202 program alarm" state it had //! just before the last computer caught fire. //! To do this, before running the program, replace position `1` with the value //! `12` and replace position `2` with the value `2`. What value is left at //! position `0` after the program halts? //! //! ## Part 2 //! //! "Good, the new computer seems to be working correctly! Keep it nearby during //! this mission - you'll probably use it again. Real Intcode computers support //! many more features than your new one, but we'll let you know what they are //! as you need them." //! //! "However, your current priority should be to complete your gravity assist //! around the Moon. For this mission to succeed, we should settle on some //! terminology for the parts you've already built." //! //! Intcode programs are given as a list of integers; these values are used as //! the initial state for the computer's memory. When you run an Intcode program, //! make sure to start by initializing memory to the program's values. A position //! in memory is called an address (for example, the first value in memory is at //! "address 0"). //! //! Opcodes (like 1, 2, or 99) mark the beginning of an instruction. The values //! used immediately after an opcode, if any, are called the instruction's //! parameters. For example, in the instruction 1,2,3,4, 1 is the opcode; 2, 3, //! and 4 are the parameters. The instruction 99 contains only an opcode and has //! no parameters. //! //! The address of the current instruction is called the instruction pointer; it //! starts at 0. After an instruction finishes, the instruction pointer increases //! by the number of values in the instruction; until you add more instructions //! to the computer, this is always 4 (1 opcode + 3 parameters) for the add and //! multiply instructions. (The halt instruction would increase the instruction //! pointer by 1, but it halts the program instead.) //! //! "With terminology out of the way, we're ready to proceed. To complete the //! gravity assist, you need to determine what pair of inputs produces the //! output 19690720." //! //! The inputs should still be provided to the program by replacing the values //! at addresses 1 and 2, just like before. In this program, the value placed in //! address 1 is called the noun, and the value placed in address 2 is called //! the verb. Each of the two input values will be between 0 and 99, inclusive. //! //! Once the program has halted, its output is available at address 0, also just //! like before. Each time you try a pair of inputs, make sure you first reset //! the computer's memory to the values in the program (your puzzle input) - in //! other words, don't reuse memory from a previous attempt. //! //! Find the input noun and verb that cause the program to produce the output //! 19690720. What is 100 * noun + verb? (For example, if noun=12 and verb=2, //! the answer would be 1202.) //! //! # Day 5: Sunny with a Chance of Asteroids //! //! ## Part 1 //! //! You're starting to sweat as the ship makes its way toward Mercury. The Elves //! suggest that you get the air conditioner working by upgrading your ship //! computer to support the Thermal Environment Supervision Terminal. //! //! The Thermal Environment Supervision Terminal (TEST) starts by running a //! diagnostic program (your puzzle input). The TEST diagnostic program will run //! on your existing Intcode computer after a few modifications: //! //! First, you'll need to add **two new instructions**: //! //! - Opcode `3` takes a single integer as **input** and saves it to the position //! given by its only parameter. For example, the instruction `3,50` would take //! an input value and store it at address `50`. //! - Opcode `4` **outputs** the value of its only parameter. For example, the //! instruction `4,50` would output the value at address `50`. //! //! Programs that use these instructions will come with documentation that //! explains what should be connected to the input and output. //! The program `3,0,4,0,99` outputs whatever it gets as input, then halts. //! //! Second, you'll need to add support for parameter modes: //! //! Each parameter of an instruction is handled based on its parameter mode. //! Right now, your ship computer already understands parameter mode 0, position //! mode, which causes the parameter to be interpreted as a position - if the //! parameter is 50, its value is the value stored at address 50 in memory. //! Until now, all parameters have been in position mode. //! //! Now, your ship computer will also need to handle parameters in mode 1, //! immediate mode. In immediate mode, a parameter is interpreted as a value - if //! the parameter is 50, its value is simply 50. //! //! Parameter modes are stored in the same value as the instruction's opcode. //! The opcode is a two-digit number based only on the ones and tens digit of the //! value, that is, the opcode is the rightmost two digits of the first value in //! an instruction. Parameter modes are single digits, one per parameter, read //! right-to-left from the opcode: the first parameter's mode is in the hundreds //! digit, the second parameter's mode is in the thousands digit, the third //! parameter's mode is in the ten-thousands digit, and so on. //! Any missing modes are 0. //! //! For example, consider the program `1002,4,3,4,33`. //! //! The first instruction, `1002,4,3,4`, is a multiply instruction - the rightmost //! two digits of the first value, 02, indicate opcode 2, multiplication. //! Then, going right to left, the parameter modes are 0 (hundreds digit), //! 1 (thousands digit), and 0 (ten-thousands digit, not present and therefore //! zero): //! //! ```text //! ABCDE //! 1002 //! //! DE - two-digit opcode, 02 == opcode 2 //! C - mode of 1st parameter, 0 == position mode //! B - mode of 2nd parameter, 1 == immediate mode //! A - mode of 3rd parameter, 0 == position mode, //! omitted due to being a leading zero //! ``` //! //! This instruction multiplies its first two parameters. //! The first parameter, 4 in position mode, works like it did before - its value //! is the value stored at address 4 (33). The second parameter, 3 in immediate //! mode, simply has value 3. The result of this operation, 33 * 3 = 99, is written //! according to the third parameter, 4 in position mode, which also works like //! it did before - 99 is written to address 4. //! //! Parameters that an instruction writes to will never be in immediate mode. //! //! Finally, some notes: //! //! - It is important to remember that the instruction pointer should increase by //! the number of values in the instruction after the instruction finishes. //! Because of the new instructions, this amount is no longer always `4`. //! - Integers can be negative: `1101,100,-1,4,0` is a valid program (find //! `100 + -1`, store the result in position `4`). //! //! The TEST diagnostic program will start by requesting from the user the ID of //! the system to test by running an input instruction - provide it 1, the ID for //! the ship's air conditioner unit. //! //! It will then perform a series of diagnostic tests confirming that various //! parts of the Intcode computer, like parameter modes, function correctly. //! For each test, it will run an output instruction indicating how far the result //! of the test was from the expected value, where 0 means the test was successful. //! Non-zero outputs mean that a function is not working correctly; check the //! instructions that were run before the output instruction to see which one //! failed. //! //! Finally, the program will output a diagnostic code and immediately halt. //! This final output isn't an error; an output followed immediately by a halt //! means the program finished. If all outputs were zero except the diagnostic //! code, the diagnostic program ran successfully. //! //! After providing 1 to the only input instruction and passing all the tests, //! what diagnostic code does the program produce? use std::convert::TryFrom; use std::str::FromStr; #[derive(Debug, PartialEq)] struct OpHeader { mode1: usize, mode2: usize, mode3: usize, opcode: usize, } impl FromStr for OpHeader { type Err = (); fn from_str(s: &str) -> Result<Self, Self::Err> { // initial string should not be larger than 5 or smaller than 1 chars. if s.len() > 5 || s.len() < 1 { return Err(()); } let padded = format!("{:0>5}", s.chars().take(5).collect::<String>()); let (modes, opcode) = padded.split_at(3); let modes: Vec<u32> = modes.chars().filter_map(|c| c.to_digit(10)).collect(); let opcode: usize = opcode.parse().map_err(|_| ())?; Ok(OpHeader { mode1: modes[2] as usize, mode2: modes[1] as usize, mode3: modes[0] as usize, opcode, }) } } impl TryFrom<i32> for OpHeader { type Error = (); fn try_from(value: i32) -> Result<Self, Self::Error> { value.to_string().parse() } } #[derive(Debug)] enum Param { Immediate(i32), Position(usize), } impl Param { pub fn
((mode, value): (usize, i32)) -> Self { match mode { 0 => Param::Position(value as usize), 1 => Param::Immediate(value), _ => unreachable!(), } } } #[derive(Debug)] enum Op { Add { a: Param, b: Param, out: usize }, Multiply { a: Param, b: Param, out: usize }, Input { out: usize }, Output { value: Param }, Halt, Unknown, } /// Builds an `Op` from `data` by reading up to 4 items from a given offset. fn read_instruction(offset: usize, data: &[i32]) -> Op { // FIXME: add support for Input/Output let header: Option<OpHeader> = data.get(offset).and_then(|x| OpHeader::try_from(*x).ok()); match ( header, data.get(offset + 1).map(|x| *x), data.get(offset + 2).map(|x| *x), data.get(offset + 3).map(|x| *x), ) { ( Some(OpHeader { opcode: 1, mode1, mode2, mode3, }), Some(a), Some(b), Some(out), ) => Op::Add { a: Param::from_pair((mode1, a)), b: Param::from_pair((mode2, b)), out: match Param::from_pair((mode3, out)) { Param::Position(out) => out, _ => unreachable!("output params cannot be immediate"), }, }, ( Some(OpHeader { opcode: 2, mode1, mode2, mode3, }), Some(a), Some(b), Some(out), ) => Op::Multiply { a: Param::from_pair((mode1, a)), b: Param::from_pair((mode2, b)), out: match Param::from_pair((mode3, out)) { Param::Position(out) => out, _ => unreachable!("output params cannot be immediate"), }, }, (Some(OpHeader { opcode: 3,.. }), Some(out), _, _) => Op::Input { out: out as usize }, ( Some(OpHeader { opcode: 4, mode1,.. }), Some(value), _, _, ) => Op::Output { value: Param::from_pair((mode1, value)), }, (Some(OpHeader { opcode: 99,.. }), _, _, _) => Op::Halt, _ => Op::Unknown, } } fn read_value(param: Param, data: &[i32]) -> Option<i32> { match param { Param::Position(idx) => data.get(idx).map(|x| *x), Param::Immediate(val) => Some(val), } } use std::io::BufRead; fn prompt_for_input() -> Result<i32, ()> { let mut buf = String::new(); println!("Waiting for input... >"); std::io::stdin() .lock() .read_line(&mut buf) .expect("input read"); buf.trim().parse().map_err(|e| { eprintln!("{}", e); }) } /// Run an intcode program. pub fn compute(data: &mut [i32]) { let mut i = 0; loop { // FIXME: make read_instruction an iterator so it can manage the increment internally match read_instruction(i, &data) { Op::Add { a, b, out } => { let a = read_value(a, data).unwrap(); let b = read_value(b, data).unwrap(); data[out] = a + b; i += 4; } Op::Multiply { a, b, out } => { let a = read_value(a, data).unwrap(); let b = read_value(b, data).unwrap(); data[out] = a * b; i += 4; } Op::Input { out } => { let value = prompt_for_input().unwrap(); data[out] = value; i += 2; } Op::Output { value } => { let value = read_value(value, data).unwrap(); println!("offset={}, value={}", i, value); i += 2; } Op::Halt => break, _ => unreachable!(), } } } /// Attempt to identify the noun and verb (injected header values) which will /// yield a certain target from a source intcode program by way of permutations. pub fn solve(target: i32, data: &[i32]) -> Result<(i32, i32), ()> { for (noun, verb) in (0..=99).flat_map(|i| (0..=99).map(move |j| (i, j))) { let mut input = data.to_vec(); input[1] = noun; input[2] = verb; compute(&mut input); if input[0] == target { return Ok((noun, verb)); } } Err(()) } #[cfg(test)] mod day02_1_tests { use super::compute; #[test] fn test_example_1() { let mut input = vec![1, 0, 0, 0, 99]; compute(&mut input); assert_eq!(&input, &[2, 0, 0, 0, 99]); } #[test] fn test_example_2() { let mut input = vec![2, 3, 0, 3, 99]; compute(&mut input); assert_eq!(&input, &[2, 3, 0, 6, 99]); } #[test] fn test_example_3() { let mut input = vec![2, 4, 4, 5, 99, 0]; compute(&mut input); assert_eq!(&input, &[2, 4, 4, 5, 99, 9801]); } #[test] fn test_example_4() { let mut input = vec![1, 1, 1, 4, 99, 5, 6, 0, 99]; compute(&mut input); assert_eq!(&input, &[30, 1, 1, 4, 2, 5, 6, 0, 99]); } } #[cfg(test)] mod day05_1_tests { use super::{compute, OpHeader}; #[test] fn test_header_pad() { // when the header is "short" it should be padded on the left with zeros assert_eq!( "102".parse::<OpHeader>().unwrap(), OpHeader { mode1: 1, mode2: 0, mode3: 0, opcode: 2 } ); } #[test] fn test_header_parse_two_digit_opcode() { assert_eq!( "1022".parse::<OpHeader>().unwrap(), OpHeader { mode1: 0, mode2: 1, mode3: 0, opcode: 22 } ); } #[test] fn test_example_1() { let mut input = vec![1002, 4, 3, 4, 33]; compute(&mut input); assert_eq!(&input, &[1002, 4, 3, 4, 99]); } }
from_pair
identifier_name
intcode.rs
//! # Day 2 1202 Program Alarm //! //! ## Part 1 //! //! On the way to your gravity assist around the Moon, your ship computer beeps //! angrily about a "1202 program alarm". On the radio, an Elf is already //! explaining how to handle the situation: "Don't worry, that's perfectly norma--" //! //! The ship computer bursts into flames. //! //! You notify the Elves that the computer's magic smoke seems to have escaped. //! //! "That computer ran Intcode programs like the gravity assist program it was //! working on; surely there are enough spare parts up there to build a new //! Intcode computer!" //! //! An Intcode program is a list of integers separated by commas (like 1,0,0,3,99). //! To run one, start by looking at the first integer (called position 0). Here, //! you will find an opcode - either 1, 2, or 99. The opcode indicates what to do; //! for example, 99 means that the program is finished and should immediately halt. //! Encountering an unknown opcode means something went wrong. //! //! Opcode 1 adds together numbers read from two positions and stores the result //! in a third position. The three integers immediately after the opcode tell you //! these three positions - the first two indicate the positions from which you //! should read the input values, and the third indicates the position at which //! the output should be stored. //! //! For example, if your Intcode computer encounters 1,10,20,30, it should read //! the values at positions 10 and 20, add those values, and then overwrite the //! value at position 30 with their sum. //! //! Opcode 2 works exactly like opcode 1, except it multiplies the two inputs //! instead of adding them. Again, the three integers after the opcode indicate //! where the inputs and outputs are, not their values. //! //! Once you're done processing an opcode, move to the next one by stepping //! forward 4 positions. //! //! For example, suppose you have the following program: //! //! ```text //! 1,9,10,3,2,3,11,0,99,30,40,50 //! ``` //! //! For the purposes of illustration, here is the same program split into //! multiple lines: //! //! ```text //! 1,9,10,3, //! 2,3,11,0, //! 99, //! 30,40,50 //! ``` //! //! The first four integers, `1,9,10,3`, are at positions `0`, `1`, `2`, and `3`. //! Together, they represent the first opcode (`1`, addition), the positions of //! the two inputs (`9` and `10`), and the position of the output (`3`). //! To handle this opcode, you first need to get the values at the input positions: //! position `9` contains `30`, and position `10` contains `40`. Add these numbers //! together to get `70`. Then, store this value at the output position; here, //! the output position (`3`) is at position `3`, so it overwrites itself. //! Afterward, the program looks like this: //! //! ```text //! 1,9,10,70, //! 2,3,11,0, //! 99, //! 30,40,50 //! ``` //! //! Step forward 4 positions to reach the next opcode, `2`. //! This opcode works just like the previous, but it multiplies instead of adding. //! The inputs are at positions `3` and `11`; these positions contain `70` and //! `50` respectively. Multiplying these produces `3500`; this is stored at //! position `0`: //! //! ```text //! 3500,9,10,70, //! 2,3,11,0, //! 99, //! 30,40,50 //! ``` //! //! Stepping forward 4 more positions arrives at opcode `99`, halting the //! program. //! //! Here are the initial and final states of a few more small programs: //! //! - `1,0,0,0,99` becomes `2,0,0,0,99` (1 + 1 = 2). //! - `2,3,0,3,99` becomes `2,3,0,6,99` (3 * 2 = 6). //! - `2,4,4,5,99,0` becomes `2,4,4,5,99,9801` (99 * 99 = 9801). //! - `1,1,1,4,99,5,6,0,99` becomes `30,1,1,4,2,5,6,0,99`. //! //! Once you have a working computer, the first step is to restore the gravity //! assist program (your puzzle input) to the "1202 program alarm" state it had //! just before the last computer caught fire. //! To do this, before running the program, replace position `1` with the value //! `12` and replace position `2` with the value `2`. What value is left at //! position `0` after the program halts? //! //! ## Part 2 //! //! "Good, the new computer seems to be working correctly! Keep it nearby during //! this mission - you'll probably use it again. Real Intcode computers support //! many more features than your new one, but we'll let you know what they are //! as you need them." //! //! "However, your current priority should be to complete your gravity assist //! around the Moon. For this mission to succeed, we should settle on some //! terminology for the parts you've already built." //! //! Intcode programs are given as a list of integers; these values are used as //! the initial state for the computer's memory. When you run an Intcode program, //! make sure to start by initializing memory to the program's values. A position //! in memory is called an address (for example, the first value in memory is at //! "address 0"). //! //! Opcodes (like 1, 2, or 99) mark the beginning of an instruction. The values //! used immediately after an opcode, if any, are called the instruction's //! parameters. For example, in the instruction 1,2,3,4, 1 is the opcode; 2, 3, //! and 4 are the parameters. The instruction 99 contains only an opcode and has //! no parameters. //! //! The address of the current instruction is called the instruction pointer; it //! starts at 0. After an instruction finishes, the instruction pointer increases //! by the number of values in the instruction; until you add more instructions //! to the computer, this is always 4 (1 opcode + 3 parameters) for the add and //! multiply instructions. (The halt instruction would increase the instruction //! pointer by 1, but it halts the program instead.) //! //! "With terminology out of the way, we're ready to proceed. To complete the //! gravity assist, you need to determine what pair of inputs produces the //! output 19690720." //! //! The inputs should still be provided to the program by replacing the values //! at addresses 1 and 2, just like before. In this program, the value placed in //! address 1 is called the noun, and the value placed in address 2 is called //! the verb. Each of the two input values will be between 0 and 99, inclusive. //! //! Once the program has halted, its output is available at address 0, also just //! like before. Each time you try a pair of inputs, make sure you first reset //! the computer's memory to the values in the program (your puzzle input) - in //! other words, don't reuse memory from a previous attempt. //! //! Find the input noun and verb that cause the program to produce the output //! 19690720. What is 100 * noun + verb? (For example, if noun=12 and verb=2, //! the answer would be 1202.) //! //! # Day 5: Sunny with a Chance of Asteroids //! //! ## Part 1 //! //! You're starting to sweat as the ship makes its way toward Mercury. The Elves //! suggest that you get the air conditioner working by upgrading your ship //! computer to support the Thermal Environment Supervision Terminal. //! //! The Thermal Environment Supervision Terminal (TEST) starts by running a //! diagnostic program (your puzzle input). The TEST diagnostic program will run //! on your existing Intcode computer after a few modifications: //! //! First, you'll need to add **two new instructions**: //! //! - Opcode `3` takes a single integer as **input** and saves it to the position //! given by its only parameter. For example, the instruction `3,50` would take //! an input value and store it at address `50`. //! - Opcode `4` **outputs** the value of its only parameter. For example, the //! instruction `4,50` would output the value at address `50`. //! //! Programs that use these instructions will come with documentation that //! explains what should be connected to the input and output. //! The program `3,0,4,0,99` outputs whatever it gets as input, then halts. //! //! Second, you'll need to add support for parameter modes: //! //! Each parameter of an instruction is handled based on its parameter mode. //! Right now, your ship computer already understands parameter mode 0, position //! mode, which causes the parameter to be interpreted as a position - if the //! parameter is 50, its value is the value stored at address 50 in memory. //! Until now, all parameters have been in position mode. //! //! Now, your ship computer will also need to handle parameters in mode 1, //! immediate mode. In immediate mode, a parameter is interpreted as a value - if //! the parameter is 50, its value is simply 50. //! //! Parameter modes are stored in the same value as the instruction's opcode. //! The opcode is a two-digit number based only on the ones and tens digit of the //! value, that is, the opcode is the rightmost two digits of the first value in //! an instruction. Parameter modes are single digits, one per parameter, read //! right-to-left from the opcode: the first parameter's mode is in the hundreds //! digit, the second parameter's mode is in the thousands digit, the third //! parameter's mode is in the ten-thousands digit, and so on. //! Any missing modes are 0. //! //! For example, consider the program `1002,4,3,4,33`. //! //! The first instruction, `1002,4,3,4`, is a multiply instruction - the rightmost //! two digits of the first value, 02, indicate opcode 2, multiplication. //! Then, going right to left, the parameter modes are 0 (hundreds digit), //! 1 (thousands digit), and 0 (ten-thousands digit, not present and therefore //! zero): //! //! ```text //! ABCDE //! 1002 //! //! DE - two-digit opcode, 02 == opcode 2 //! C - mode of 1st parameter, 0 == position mode //! B - mode of 2nd parameter, 1 == immediate mode //! A - mode of 3rd parameter, 0 == position mode, //! omitted due to being a leading zero //! ``` //! //! This instruction multiplies its first two parameters. //! The first parameter, 4 in position mode, works like it did before - its value //! is the value stored at address 4 (33). The second parameter, 3 in immediate //! mode, simply has value 3. The result of this operation, 33 * 3 = 99, is written //! according to the third parameter, 4 in position mode, which also works like //! it did before - 99 is written to address 4. //! //! Parameters that an instruction writes to will never be in immediate mode. //! //! Finally, some notes: //! //! - It is important to remember that the instruction pointer should increase by //! the number of values in the instruction after the instruction finishes. //! Because of the new instructions, this amount is no longer always `4`. //! - Integers can be negative: `1101,100,-1,4,0` is a valid program (find //! `100 + -1`, store the result in position `4`). //! //! The TEST diagnostic program will start by requesting from the user the ID of //! the system to test by running an input instruction - provide it 1, the ID for //! the ship's air conditioner unit. //! //! It will then perform a series of diagnostic tests confirming that various //! parts of the Intcode computer, like parameter modes, function correctly. //! For each test, it will run an output instruction indicating how far the result //! of the test was from the expected value, where 0 means the test was successful. //! Non-zero outputs mean that a function is not working correctly; check the //! instructions that were run before the output instruction to see which one //! failed. //! //! Finally, the program will output a diagnostic code and immediately halt. //! This final output isn't an error; an output followed immediately by a halt //! means the program finished. If all outputs were zero except the diagnostic //! code, the diagnostic program ran successfully. //! //! After providing 1 to the only input instruction and passing all the tests, //! what diagnostic code does the program produce? use std::convert::TryFrom; use std::str::FromStr; #[derive(Debug, PartialEq)] struct OpHeader { mode1: usize, mode2: usize, mode3: usize, opcode: usize, } impl FromStr for OpHeader { type Err = (); fn from_str(s: &str) -> Result<Self, Self::Err> { // initial string should not be larger than 5 or smaller than 1 chars. if s.len() > 5 || s.len() < 1 { return Err(()); } let padded = format!("{:0>5}", s.chars().take(5).collect::<String>()); let (modes, opcode) = padded.split_at(3); let modes: Vec<u32> = modes.chars().filter_map(|c| c.to_digit(10)).collect(); let opcode: usize = opcode.parse().map_err(|_| ())?; Ok(OpHeader { mode1: modes[2] as usize, mode2: modes[1] as usize, mode3: modes[0] as usize, opcode, }) } } impl TryFrom<i32> for OpHeader { type Error = (); fn try_from(value: i32) -> Result<Self, Self::Error> { value.to_string().parse() } } #[derive(Debug)] enum Param { Immediate(i32), Position(usize), } impl Param { pub fn from_pair((mode, value): (usize, i32)) -> Self { match mode { 0 => Param::Position(value as usize), 1 => Param::Immediate(value), _ => unreachable!(), } } } #[derive(Debug)] enum Op { Add { a: Param, b: Param, out: usize }, Multiply { a: Param, b: Param, out: usize }, Input { out: usize }, Output { value: Param }, Halt, Unknown, } /// Builds an `Op` from `data` by reading up to 4 items from a given offset. fn read_instruction(offset: usize, data: &[i32]) -> Op { // FIXME: add support for Input/Output let header: Option<OpHeader> = data.get(offset).and_then(|x| OpHeader::try_from(*x).ok()); match ( header, data.get(offset + 1).map(|x| *x), data.get(offset + 2).map(|x| *x), data.get(offset + 3).map(|x| *x), ) { ( Some(OpHeader { opcode: 1, mode1, mode2, mode3, }), Some(a), Some(b), Some(out), ) => Op::Add { a: Param::from_pair((mode1, a)), b: Param::from_pair((mode2, b)), out: match Param::from_pair((mode3, out)) { Param::Position(out) => out, _ => unreachable!("output params cannot be immediate"), }, }, ( Some(OpHeader { opcode: 2, mode1, mode2, mode3, }), Some(a), Some(b), Some(out), ) => Op::Multiply { a: Param::from_pair((mode1, a)), b: Param::from_pair((mode2, b)), out: match Param::from_pair((mode3, out)) { Param::Position(out) => out, _ => unreachable!("output params cannot be immediate"), }, }, (Some(OpHeader { opcode: 3,.. }), Some(out), _, _) => Op::Input { out: out as usize }, ( Some(OpHeader { opcode: 4, mode1,.. }), Some(value), _, _, ) => Op::Output { value: Param::from_pair((mode1, value)), }, (Some(OpHeader { opcode: 99,.. }), _, _, _) => Op::Halt, _ => Op::Unknown, } } fn read_value(param: Param, data: &[i32]) -> Option<i32> { match param { Param::Position(idx) => data.get(idx).map(|x| *x), Param::Immediate(val) => Some(val), } } use std::io::BufRead; fn prompt_for_input() -> Result<i32, ()> { let mut buf = String::new(); println!("Waiting for input... >"); std::io::stdin() .lock() .read_line(&mut buf) .expect("input read"); buf.trim().parse().map_err(|e| { eprintln!("{}", e); }) } /// Run an intcode program. pub fn compute(data: &mut [i32])
i += 2; } Op::Output { value } => { let value = read_value(value, data).unwrap(); println!("offset={}, value={}", i, value); i += 2; } Op::Halt => break, _ => unreachable!(), } } } /// Attempt to identify the noun and verb (injected header values) which will /// yield a certain target from a source intcode program by way of permutations. pub fn solve(target: i32, data: &[i32]) -> Result<(i32, i32), ()> { for (noun, verb) in (0..=99).flat_map(|i| (0..=99).map(move |j| (i, j))) { let mut input = data.to_vec(); input[1] = noun; input[2] = verb; compute(&mut input); if input[0] == target { return Ok((noun, verb)); } } Err(()) } #[cfg(test)] mod day02_1_tests { use super::compute; #[test] fn test_example_1() { let mut input = vec![1, 0, 0, 0, 99]; compute(&mut input); assert_eq!(&input, &[2, 0, 0, 0, 99]); } #[test] fn test_example_2() { let mut input = vec![2, 3, 0, 3, 99]; compute(&mut input); assert_eq!(&input, &[2, 3, 0, 6, 99]); } #[test] fn test_example_3() { let mut input = vec![2, 4, 4, 5, 99, 0]; compute(&mut input); assert_eq!(&input, &[2, 4, 4, 5, 99, 9801]); } #[test] fn test_example_4() { let mut input = vec![1, 1, 1, 4, 99, 5, 6, 0, 99]; compute(&mut input); assert_eq!(&input, &[30, 1, 1, 4, 2, 5, 6, 0, 99]); } } #[cfg(test)] mod day05_1_tests { use super::{compute, OpHeader}; #[test] fn test_header_pad() { // when the header is "short" it should be padded on the left with zeros assert_eq!( "102".parse::<OpHeader>().unwrap(), OpHeader { mode1: 1, mode2: 0, mode3: 0, opcode: 2 } ); } #[test] fn test_header_parse_two_digit_opcode() { assert_eq!( "1022".parse::<OpHeader>().unwrap(), OpHeader { mode1: 0, mode2: 1, mode3: 0, opcode: 22 } ); } #[test] fn test_example_1() { let mut input = vec![1002, 4, 3, 4, 33]; compute(&mut input); assert_eq!(&input, &[1002, 4, 3, 4, 99]); } }
{ let mut i = 0; loop { // FIXME: make read_instruction an iterator so it can manage the increment internally match read_instruction(i, &data) { Op::Add { a, b, out } => { let a = read_value(a, data).unwrap(); let b = read_value(b, data).unwrap(); data[out] = a + b; i += 4; } Op::Multiply { a, b, out } => { let a = read_value(a, data).unwrap(); let b = read_value(b, data).unwrap(); data[out] = a * b; i += 4; } Op::Input { out } => { let value = prompt_for_input().unwrap(); data[out] = value;
identifier_body
com.rs
//! Common utilities //! //! A standard vocabulary used throughout the code. use std::{self, cmp, convert, fmt, hash, iter, marker, num, ops, sync}; use crate::basic::sea::TableIndex; /// A fragment of source code. #[derive(Clone)] pub struct CodeFragment(sync::Arc<Vec<u8>>); impl CodeFragment { /// Creates a new `CodeFragment`. pub fn new(code: Vec<u8>) -> CodeFragment { CodeFragment(sync::Arc::new(code)) } } impl ops::Deref for CodeFragment { type Target = [u8]; fn deref(&self) -> &[u8] { &*self.0 } } /// The core implementation of a u32-based ID. /// /// The ID can be any number in the `[0, u32::MAX - 2]` range: /// - `u32::MAX` is reserved to enable size optimizations (Option). /// - `u32::MAX - 1` is reserved to denote Default constructed IDs. /// /// IDs built on top of `CoreId` may reserve further numbers for their own ends. #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)] pub struct CoreId(num::NonZeroU32); impl CoreId { /// Creates a new instance. /// /// # Panics /// /// Panics if the integer provided is `u32::MAX`. pub fn new(id: u32) -> CoreId { if id == std::u32::MAX { panic!("Unsuitable ID: {}", id); } unsafe { CoreId(num::NonZeroU32::new_unchecked(id + 1)) } } /// Get the raw ID. pub fn raw(&self) -> u32 { self.0.get() - 1 } } impl fmt::Debug for CoreId { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(f, "{}", self.raw()) } } impl Default for CoreId { fn default() -> CoreId { unsafe { CoreId(num::NonZeroU32::new_unchecked(std::u32::MAX)) } } } impl fmt::Display for CoreId { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(f, "{}", self.raw()) } } impl convert::From<CoreId> for u32 { fn from(core_id: CoreId) -> u32 { core_id.raw() } } /// An Id implementation based on CoreId. /// /// It contains a default empty state, to represent empty streams. // #[manual(Clone, Copy, Debug, Default, PartialEq, PartialOrd, Eq, Ord, Hash)] pub struct Id<T:?Sized>(CoreId, marker::PhantomData<*const T>); impl<T:?Sized> Id<T> { /// Creates a new instance. pub fn new(id: u32) -> Self { Id(CoreId::new(id), marker::PhantomData) } /// Creates an empty instance. pub fn empty() -> Self { Self::new(std::u32::MAX - 2) } /// Returns whether the corresponding list is empty. pub fn is_empty(&self) -> bool { *self == Self::empty() } /// Returns the inner ID. pub fn value(&self) -> u32 { self.0.raw() } } impl<T:?Sized> Clone for Id<T> { fn clone(&self) -> Self { *self } } impl<T:?Sized> Copy for Id<T> {} impl<T:?Sized> fmt::Debug for Id<T> { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { const MODULE_OFFSET: usize = 1usize << 30; const REPOSITORY_OFFSET: usize = 1usize << 31; // More compact representation for `{:#?}`. // // FIXME(matthieum): consider adding `std::intrinsics::type_name<T>()` // once it stabilizes. if *self == Default::default() { write!(f, "Id(default)") } else if *self == Self::empty() { write!(f, "Id(empty)") } else { match self.index() { index if index < MODULE_OFFSET => write!(f, "Id({})", index), index if index < REPOSITORY_OFFSET => write!(f, "Id(M-{})", index - MODULE_OFFSET), index => write!(f, "Id(R-{})", index - REPOSITORY_OFFSET), } } } } impl<T:?Sized> Default for Id<T> { fn default() -> Self { Id(Default::default(), marker::PhantomData) } } impl<T:?Sized> cmp::Eq for Id<T> {} impl<T:?Sized> hash::Hash for Id<T> { fn hash<H: hash::Hasher>(&self, state: &mut H) { self.0.hash(state); } } impl<T:?Sized> cmp::Ord for Id<T> { fn cmp(&self, other: &Self) -> cmp::Ordering { self.0.cmp(&other.0) } } impl<T:?Sized> cmp::PartialEq for Id<T> { fn eq(&self, other: &Self) -> bool { self.0.eq(&other.0) } } impl<T:?Sized> cmp::PartialOrd for Id<T> { fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> { self.0.partial_cmp(&other.0) } } impl<T:?Sized> TableIndex for Id<T> { fn from_index(index: usize) -> Self { Id::new(index as u32) } fn index(&self) -> usize { self.value() as usize } } /// IdIterator. /// /// An Iterator over consecutive IDs. // #[manual(Clone, Copy, Debug, Default, PartialEq, PartialOrd, Eq, Ord, Hash)] pub struct IdIterator<T:?Sized> { start: u32, end: u32, _marker: marker::PhantomData<*const T>, } impl<T:?Sized> IdIterator<T> { /// Creates an instance. pub fn new(start: u32, end: u32) -> Self { IdIterator { start, end, _marker: marker::PhantomData } } } impl<T:?Sized> Clone for IdIterator<T> { fn clone(&self) -> Self { *self } } impl<T:?Sized> Copy for IdIterator<T> {} impl<T:?Sized> fmt::Debug for IdIterator<T> { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { // FIXME(matthieum): consider adding `std::intrinsics::type_name<T>()` // once it stabilizes. write!(f, "IdIterator({}, {})", self.start, self.end) } } impl<T:?Sized> Default for IdIterator<T> { fn default() -> Self { IdIterator::new(0, 0) } } impl<T:?Sized> cmp::Eq for IdIterator<T> {} impl<T:?Sized> hash::Hash for IdIterator<T> { fn hash<H: hash::Hasher>(&self, state: &mut H) { self.start.hash(state); self.end.hash(state); } } impl<T:?Sized> iter::Iterator for IdIterator<T> { type Item = Id<T>; fn next(&mut self) -> Option<Id<T>> { if self.start < self.end { let result = Id::new(self.start); self.start += 1; Some(result) } else { None } } fn size_hint(&self) -> (usize, Option<usize>) { let difference = self.len(); (difference, Some(difference)) } fn count(self) -> usize { self.len() } fn last(self) -> Option<Id<T>> { if self.start < self.end { Some(Id::new(self.end - 1)) } else { None } } fn nth(&mut self, n: usize) -> Option<Id<T>> { let result = self.start.saturating_add(n as u32); if result < self.end { self.start = result + 1; Some(Id::new(result)) } else { self.start = self.end; None } } fn max(self) -> Option<Id<T>> { self.last() } fn min(mut self) -> Option<Id<T>> { self.next() } } impl<T:?Sized> iter::DoubleEndedIterator for IdIterator<T> { fn next_back(&mut self) -> Option<Id<T>> { if self.start < self.end { self.end -= 1; Some(Id::new(self.end)) } else { None } } } impl<T:?Sized> iter::ExactSizeIterator for IdIterator<T> { fn len(&self) -> usize { self.end.saturating_sub(self.start) as usize } } impl<T:?Sized> cmp::Ord for IdIterator<T> { fn cmp(&self, other: &Self) -> cmp::Ordering { (self.start, self.end).cmp(&(other.start, other.end)) } } impl<T:?Sized> cmp::PartialEq for IdIterator<T> { fn eq(&self, other: &Self) -> bool { (self.start, self.end).eq(&(other.start, other.end)) } } impl<T:?Sized> cmp::PartialOrd for IdIterator<T> { fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> { (self.start, self.end).partial_cmp(&(other.start, other.end)) } } /// A Range represents a start and end position in a buffer. /// /// Note: the `Range` does not know which buffer it indexes in. /// /// Note: a `Range` cannot index past 4GB. #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)] pub struct Range { offset: u32, length: u32, } impl Range { /// Creates a new `Range` from a start position and length. /// /// In Debug, it is checked that the end position will not exceed 4GB. pub fn new(offset: usize, length: usize) -> Range { debug_assert!(offset <= std::u32::MAX as usize); debug_assert!(length <= std::u32::MAX as usize); debug_assert!(offset <= (std::u32::MAX as usize - length)); Range { offset: offset as u32, length: length as u32 } } /// Creates a new `Range` from a start and end position. /// /// As the name implies, this creates a half-open range, similar to `start..end`. pub fn half_open(start: u32, end: u32) -> Range { debug_assert!(start <= end); Range { offset: start, length: end - start } } /// Returns the start position of the range. pub fn offset(self) -> usize { self.offset as usize } /// Returns the end position of the range (excluded). pub fn end_offset(self) -> usize { self.offset() + self.length() } /// Returns the length of the range. pub fn length(self) -> usize { self.length as usize } /// Shifts range to the left. pub fn shift_left(self, n: usize) -> Range { self.shift_to(self.offset() - n) } /// Shifts range to the right. pub fn shift_right(self, n: usize) -> Range { self.shift_to(self.offset() + n) }
} /// Skips n from the left. pub fn skip_left(self, n: usize) -> Range { Range { offset: self.offset + (n as u32), length: self.length - (n as u32), } } /// Skips n from the right. pub fn skip_right(self, n: usize) -> Range { Range { offset: self.offset, length: self.length - (n as u32), } } /// Extend one range with another, the resulting range spans both ranges, /// and in the case they were discontiguous also spans the interval. pub fn extend(self, other: Range) -> Range { if self.offset > other.offset { other.extend(self) } else if self.end_offset() >= other.end_offset() { self } else { Range { offset: self.offset, length: (other.end_offset() - self.offset()) as u32 } } } } impl fmt::Debug for Range { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(f, "{}@{}", self.length, self.offset) } } impl Default for Range { fn default() -> Range { Range::new(0, 0) } } impl fmt::Display for Range { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(f, "{}@{}", self.length, self.offset) } } impl ops::Index<Range> for [u8] { type Output = [u8]; fn index(&self, index: Range) -> &[u8] { &self[index.offset()..index.end_offset()] } } /// A Slice of bytes, printed more pleasantly #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)] pub struct Slice<'a>(pub &'a [u8]); impl<'a> Slice<'a> { /// Returns true if empty, false otherwise. pub fn is_empty(&self) -> bool { self.0.is_empty() } /// Returns the length of the slice. pub fn len(&self) -> usize { self.0.len() } /// Returns the byte at the indicated position, or None if it is invalid. pub fn get(&self, pos: usize) -> Option<&u8> { self.0.get(pos) } } impl<'a> fmt::Debug for Slice<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(f, "{}", self) } } impl<'a> fmt::Display for Slice<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { let mut start = 0; while start < self.0.len() { let end = self.0[start..].iter().position(|&b| b < 32 || b > 126) .unwrap_or(self.len()); f.write_str( std::str::from_utf8(&self.0[start..end]).expect("Valid UTF-8") )?; start = end; let end = self.0[start..].iter().position(|&b| b >= 32 && b <= 126) .unwrap_or(self.len()); for &byte in &self.0[start..end] { write!(f, "{{0x{:X}}}", byte)?; } start = end; } Ok(()) } } /// Span pub trait Span { /// Returns the Range spanned by the element. fn span(&self) -> Range; } /// A Store trait, to abstract over the actual storage of individual elements. pub trait Store<T, I = Id<T>> { /// Returns the number of items. fn len(&self) -> usize; /// Returns a copy of the item. fn get(&self, id: I) -> T; /// Returns the range of the item. fn get_range(&self, id: I) -> Range; /// Pushes an item. fn push(&mut self, item: T, range: Range) -> I; } /// A MultiStore trait, to abstract over the actual storage of slices. pub trait MultiStore<T, I = Id<[T]>> { /// Returns the slice of items. fn get_slice(&self, id: I) -> &[T]; // TODO(matthieum): A more efficient interface would take IntoIterator<Item = T> /// Pushes a slice of element. fn push_slice(&mut self, items: &[T]) -> I; } // // Tests // #[cfg(test)] mod tests { use super::{CoreId, Range}; #[test] fn core_id_roundtrip() { for i in 0..10 { assert_eq!(i, CoreId::new(i).raw()); } } #[test] fn core_id_default() { let core: CoreId = Default::default(); assert_eq!(std::u32::MAX - 1, core.raw()); } #[test] #[should_panic] fn core_id_reserved_size_optimization() { CoreId::new(std::u32::MAX); } #[test] fn range_extend_contiguous() { let result = Range::new(3, 4).extend(Range::new(7, 2)); assert_eq!(result, Range::new(3, 6)); } #[test] fn range_extend_separated() { let result = Range::new(3, 4).extend(Range::new(11, 3)); assert_eq!(result, Range::new(3, 11)); } #[test] fn range_extend_partially_overlapping() { let result = Range::new(3, 4).extend(Range::new(5, 3)); assert_eq!(result, Range::new(3, 5)); } #[test] fn range_extend_totally_overlapping() { let result = Range::new(3, 4).extend(Range::new(5, 2)); assert_eq!(result, Range::new(3, 4)); } #[test] fn range_extend_reversed() { let result = Range::new(5, 3).extend(Range::new(3, 4)); assert_eq!(result, Range::new(3, 5)); } }
/// Shifts range to specified offset. pub fn shift_to(self, offset: usize) -> Range { Range { offset: offset as u32, ..self }
random_line_split
com.rs
//! Common utilities //! //! A standard vocabulary used throughout the code. use std::{self, cmp, convert, fmt, hash, iter, marker, num, ops, sync}; use crate::basic::sea::TableIndex; /// A fragment of source code. #[derive(Clone)] pub struct CodeFragment(sync::Arc<Vec<u8>>); impl CodeFragment { /// Creates a new `CodeFragment`. pub fn new(code: Vec<u8>) -> CodeFragment { CodeFragment(sync::Arc::new(code)) } } impl ops::Deref for CodeFragment { type Target = [u8]; fn deref(&self) -> &[u8] { &*self.0 } } /// The core implementation of a u32-based ID. /// /// The ID can be any number in the `[0, u32::MAX - 2]` range: /// - `u32::MAX` is reserved to enable size optimizations (Option). /// - `u32::MAX - 1` is reserved to denote Default constructed IDs. /// /// IDs built on top of `CoreId` may reserve further numbers for their own ends. #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)] pub struct CoreId(num::NonZeroU32); impl CoreId { /// Creates a new instance. /// /// # Panics /// /// Panics if the integer provided is `u32::MAX`. pub fn new(id: u32) -> CoreId { if id == std::u32::MAX { panic!("Unsuitable ID: {}", id); } unsafe { CoreId(num::NonZeroU32::new_unchecked(id + 1)) } } /// Get the raw ID. pub fn
(&self) -> u32 { self.0.get() - 1 } } impl fmt::Debug for CoreId { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(f, "{}", self.raw()) } } impl Default for CoreId { fn default() -> CoreId { unsafe { CoreId(num::NonZeroU32::new_unchecked(std::u32::MAX)) } } } impl fmt::Display for CoreId { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(f, "{}", self.raw()) } } impl convert::From<CoreId> for u32 { fn from(core_id: CoreId) -> u32 { core_id.raw() } } /// An Id implementation based on CoreId. /// /// It contains a default empty state, to represent empty streams. // #[manual(Clone, Copy, Debug, Default, PartialEq, PartialOrd, Eq, Ord, Hash)] pub struct Id<T:?Sized>(CoreId, marker::PhantomData<*const T>); impl<T:?Sized> Id<T> { /// Creates a new instance. pub fn new(id: u32) -> Self { Id(CoreId::new(id), marker::PhantomData) } /// Creates an empty instance. pub fn empty() -> Self { Self::new(std::u32::MAX - 2) } /// Returns whether the corresponding list is empty. pub fn is_empty(&self) -> bool { *self == Self::empty() } /// Returns the inner ID. pub fn value(&self) -> u32 { self.0.raw() } } impl<T:?Sized> Clone for Id<T> { fn clone(&self) -> Self { *self } } impl<T:?Sized> Copy for Id<T> {} impl<T:?Sized> fmt::Debug for Id<T> { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { const MODULE_OFFSET: usize = 1usize << 30; const REPOSITORY_OFFSET: usize = 1usize << 31; // More compact representation for `{:#?}`. // // FIXME(matthieum): consider adding `std::intrinsics::type_name<T>()` // once it stabilizes. if *self == Default::default() { write!(f, "Id(default)") } else if *self == Self::empty() { write!(f, "Id(empty)") } else { match self.index() { index if index < MODULE_OFFSET => write!(f, "Id({})", index), index if index < REPOSITORY_OFFSET => write!(f, "Id(M-{})", index - MODULE_OFFSET), index => write!(f, "Id(R-{})", index - REPOSITORY_OFFSET), } } } } impl<T:?Sized> Default for Id<T> { fn default() -> Self { Id(Default::default(), marker::PhantomData) } } impl<T:?Sized> cmp::Eq for Id<T> {} impl<T:?Sized> hash::Hash for Id<T> { fn hash<H: hash::Hasher>(&self, state: &mut H) { self.0.hash(state); } } impl<T:?Sized> cmp::Ord for Id<T> { fn cmp(&self, other: &Self) -> cmp::Ordering { self.0.cmp(&other.0) } } impl<T:?Sized> cmp::PartialEq for Id<T> { fn eq(&self, other: &Self) -> bool { self.0.eq(&other.0) } } impl<T:?Sized> cmp::PartialOrd for Id<T> { fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> { self.0.partial_cmp(&other.0) } } impl<T:?Sized> TableIndex for Id<T> { fn from_index(index: usize) -> Self { Id::new(index as u32) } fn index(&self) -> usize { self.value() as usize } } /// IdIterator. /// /// An Iterator over consecutive IDs. // #[manual(Clone, Copy, Debug, Default, PartialEq, PartialOrd, Eq, Ord, Hash)] pub struct IdIterator<T:?Sized> { start: u32, end: u32, _marker: marker::PhantomData<*const T>, } impl<T:?Sized> IdIterator<T> { /// Creates an instance. pub fn new(start: u32, end: u32) -> Self { IdIterator { start, end, _marker: marker::PhantomData } } } impl<T:?Sized> Clone for IdIterator<T> { fn clone(&self) -> Self { *self } } impl<T:?Sized> Copy for IdIterator<T> {} impl<T:?Sized> fmt::Debug for IdIterator<T> { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { // FIXME(matthieum): consider adding `std::intrinsics::type_name<T>()` // once it stabilizes. write!(f, "IdIterator({}, {})", self.start, self.end) } } impl<T:?Sized> Default for IdIterator<T> { fn default() -> Self { IdIterator::new(0, 0) } } impl<T:?Sized> cmp::Eq for IdIterator<T> {} impl<T:?Sized> hash::Hash for IdIterator<T> { fn hash<H: hash::Hasher>(&self, state: &mut H) { self.start.hash(state); self.end.hash(state); } } impl<T:?Sized> iter::Iterator for IdIterator<T> { type Item = Id<T>; fn next(&mut self) -> Option<Id<T>> { if self.start < self.end { let result = Id::new(self.start); self.start += 1; Some(result) } else { None } } fn size_hint(&self) -> (usize, Option<usize>) { let difference = self.len(); (difference, Some(difference)) } fn count(self) -> usize { self.len() } fn last(self) -> Option<Id<T>> { if self.start < self.end { Some(Id::new(self.end - 1)) } else { None } } fn nth(&mut self, n: usize) -> Option<Id<T>> { let result = self.start.saturating_add(n as u32); if result < self.end { self.start = result + 1; Some(Id::new(result)) } else { self.start = self.end; None } } fn max(self) -> Option<Id<T>> { self.last() } fn min(mut self) -> Option<Id<T>> { self.next() } } impl<T:?Sized> iter::DoubleEndedIterator for IdIterator<T> { fn next_back(&mut self) -> Option<Id<T>> { if self.start < self.end { self.end -= 1; Some(Id::new(self.end)) } else { None } } } impl<T:?Sized> iter::ExactSizeIterator for IdIterator<T> { fn len(&self) -> usize { self.end.saturating_sub(self.start) as usize } } impl<T:?Sized> cmp::Ord for IdIterator<T> { fn cmp(&self, other: &Self) -> cmp::Ordering { (self.start, self.end).cmp(&(other.start, other.end)) } } impl<T:?Sized> cmp::PartialEq for IdIterator<T> { fn eq(&self, other: &Self) -> bool { (self.start, self.end).eq(&(other.start, other.end)) } } impl<T:?Sized> cmp::PartialOrd for IdIterator<T> { fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> { (self.start, self.end).partial_cmp(&(other.start, other.end)) } } /// A Range represents a start and end position in a buffer. /// /// Note: the `Range` does not know which buffer it indexes in. /// /// Note: a `Range` cannot index past 4GB. #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)] pub struct Range { offset: u32, length: u32, } impl Range { /// Creates a new `Range` from a start position and length. /// /// In Debug, it is checked that the end position will not exceed 4GB. pub fn new(offset: usize, length: usize) -> Range { debug_assert!(offset <= std::u32::MAX as usize); debug_assert!(length <= std::u32::MAX as usize); debug_assert!(offset <= (std::u32::MAX as usize - length)); Range { offset: offset as u32, length: length as u32 } } /// Creates a new `Range` from a start and end position. /// /// As the name implies, this creates a half-open range, similar to `start..end`. pub fn half_open(start: u32, end: u32) -> Range { debug_assert!(start <= end); Range { offset: start, length: end - start } } /// Returns the start position of the range. pub fn offset(self) -> usize { self.offset as usize } /// Returns the end position of the range (excluded). pub fn end_offset(self) -> usize { self.offset() + self.length() } /// Returns the length of the range. pub fn length(self) -> usize { self.length as usize } /// Shifts range to the left. pub fn shift_left(self, n: usize) -> Range { self.shift_to(self.offset() - n) } /// Shifts range to the right. pub fn shift_right(self, n: usize) -> Range { self.shift_to(self.offset() + n) } /// Shifts range to specified offset. pub fn shift_to(self, offset: usize) -> Range { Range { offset: offset as u32,..self } } /// Skips n from the left. pub fn skip_left(self, n: usize) -> Range { Range { offset: self.offset + (n as u32), length: self.length - (n as u32), } } /// Skips n from the right. pub fn skip_right(self, n: usize) -> Range { Range { offset: self.offset, length: self.length - (n as u32), } } /// Extend one range with another, the resulting range spans both ranges, /// and in the case they were discontiguous also spans the interval. pub fn extend(self, other: Range) -> Range { if self.offset > other.offset { other.extend(self) } else if self.end_offset() >= other.end_offset() { self } else { Range { offset: self.offset, length: (other.end_offset() - self.offset()) as u32 } } } } impl fmt::Debug for Range { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(f, "{}@{}", self.length, self.offset) } } impl Default for Range { fn default() -> Range { Range::new(0, 0) } } impl fmt::Display for Range { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(f, "{}@{}", self.length, self.offset) } } impl ops::Index<Range> for [u8] { type Output = [u8]; fn index(&self, index: Range) -> &[u8] { &self[index.offset()..index.end_offset()] } } /// A Slice of bytes, printed more pleasantly #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)] pub struct Slice<'a>(pub &'a [u8]); impl<'a> Slice<'a> { /// Returns true if empty, false otherwise. pub fn is_empty(&self) -> bool { self.0.is_empty() } /// Returns the length of the slice. pub fn len(&self) -> usize { self.0.len() } /// Returns the byte at the indicated position, or None if it is invalid. pub fn get(&self, pos: usize) -> Option<&u8> { self.0.get(pos) } } impl<'a> fmt::Debug for Slice<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(f, "{}", self) } } impl<'a> fmt::Display for Slice<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { let mut start = 0; while start < self.0.len() { let end = self.0[start..].iter().position(|&b| b < 32 || b > 126) .unwrap_or(self.len()); f.write_str( std::str::from_utf8(&self.0[start..end]).expect("Valid UTF-8") )?; start = end; let end = self.0[start..].iter().position(|&b| b >= 32 && b <= 126) .unwrap_or(self.len()); for &byte in &self.0[start..end] { write!(f, "{{0x{:X}}}", byte)?; } start = end; } Ok(()) } } /// Span pub trait Span { /// Returns the Range spanned by the element. fn span(&self) -> Range; } /// A Store trait, to abstract over the actual storage of individual elements. pub trait Store<T, I = Id<T>> { /// Returns the number of items. fn len(&self) -> usize; /// Returns a copy of the item. fn get(&self, id: I) -> T; /// Returns the range of the item. fn get_range(&self, id: I) -> Range; /// Pushes an item. fn push(&mut self, item: T, range: Range) -> I; } /// A MultiStore trait, to abstract over the actual storage of slices. pub trait MultiStore<T, I = Id<[T]>> { /// Returns the slice of items. fn get_slice(&self, id: I) -> &[T]; // TODO(matthieum): A more efficient interface would take IntoIterator<Item = T> /// Pushes a slice of element. fn push_slice(&mut self, items: &[T]) -> I; } // // Tests // #[cfg(test)] mod tests { use super::{CoreId, Range}; #[test] fn core_id_roundtrip() { for i in 0..10 { assert_eq!(i, CoreId::new(i).raw()); } } #[test] fn core_id_default() { let core: CoreId = Default::default(); assert_eq!(std::u32::MAX - 1, core.raw()); } #[test] #[should_panic] fn core_id_reserved_size_optimization() { CoreId::new(std::u32::MAX); } #[test] fn range_extend_contiguous() { let result = Range::new(3, 4).extend(Range::new(7, 2)); assert_eq!(result, Range::new(3, 6)); } #[test] fn range_extend_separated() { let result = Range::new(3, 4).extend(Range::new(11, 3)); assert_eq!(result, Range::new(3, 11)); } #[test] fn range_extend_partially_overlapping() { let result = Range::new(3, 4).extend(Range::new(5, 3)); assert_eq!(result, Range::new(3, 5)); } #[test] fn range_extend_totally_overlapping() { let result = Range::new(3, 4).extend(Range::new(5, 2)); assert_eq!(result, Range::new(3, 4)); } #[test] fn range_extend_reversed() { let result = Range::new(5, 3).extend(Range::new(3, 4)); assert_eq!(result, Range::new(3, 5)); } }
raw
identifier_name
com.rs
//! Common utilities //! //! A standard vocabulary used throughout the code. use std::{self, cmp, convert, fmt, hash, iter, marker, num, ops, sync}; use crate::basic::sea::TableIndex; /// A fragment of source code. #[derive(Clone)] pub struct CodeFragment(sync::Arc<Vec<u8>>); impl CodeFragment { /// Creates a new `CodeFragment`. pub fn new(code: Vec<u8>) -> CodeFragment { CodeFragment(sync::Arc::new(code)) } } impl ops::Deref for CodeFragment { type Target = [u8]; fn deref(&self) -> &[u8] { &*self.0 } } /// The core implementation of a u32-based ID. /// /// The ID can be any number in the `[0, u32::MAX - 2]` range: /// - `u32::MAX` is reserved to enable size optimizations (Option). /// - `u32::MAX - 1` is reserved to denote Default constructed IDs. /// /// IDs built on top of `CoreId` may reserve further numbers for their own ends. #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)] pub struct CoreId(num::NonZeroU32); impl CoreId { /// Creates a new instance. /// /// # Panics /// /// Panics if the integer provided is `u32::MAX`. pub fn new(id: u32) -> CoreId { if id == std::u32::MAX { panic!("Unsuitable ID: {}", id); } unsafe { CoreId(num::NonZeroU32::new_unchecked(id + 1)) } } /// Get the raw ID. pub fn raw(&self) -> u32 { self.0.get() - 1 } } impl fmt::Debug for CoreId { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(f, "{}", self.raw()) } } impl Default for CoreId { fn default() -> CoreId { unsafe { CoreId(num::NonZeroU32::new_unchecked(std::u32::MAX)) } } } impl fmt::Display for CoreId { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(f, "{}", self.raw()) } } impl convert::From<CoreId> for u32 { fn from(core_id: CoreId) -> u32 { core_id.raw() } } /// An Id implementation based on CoreId. /// /// It contains a default empty state, to represent empty streams. // #[manual(Clone, Copy, Debug, Default, PartialEq, PartialOrd, Eq, Ord, Hash)] pub struct Id<T:?Sized>(CoreId, marker::PhantomData<*const T>); impl<T:?Sized> Id<T> { /// Creates a new instance. pub fn new(id: u32) -> Self { Id(CoreId::new(id), marker::PhantomData) } /// Creates an empty instance. pub fn empty() -> Self { Self::new(std::u32::MAX - 2) } /// Returns whether the corresponding list is empty. pub fn is_empty(&self) -> bool { *self == Self::empty() } /// Returns the inner ID. pub fn value(&self) -> u32 { self.0.raw() } } impl<T:?Sized> Clone for Id<T> { fn clone(&self) -> Self { *self } } impl<T:?Sized> Copy for Id<T> {} impl<T:?Sized> fmt::Debug for Id<T> { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { const MODULE_OFFSET: usize = 1usize << 30; const REPOSITORY_OFFSET: usize = 1usize << 31; // More compact representation for `{:#?}`. // // FIXME(matthieum): consider adding `std::intrinsics::type_name<T>()` // once it stabilizes. if *self == Default::default() { write!(f, "Id(default)") } else if *self == Self::empty() { write!(f, "Id(empty)") } else { match self.index() { index if index < MODULE_OFFSET => write!(f, "Id({})", index), index if index < REPOSITORY_OFFSET => write!(f, "Id(M-{})", index - MODULE_OFFSET), index => write!(f, "Id(R-{})", index - REPOSITORY_OFFSET), } } } } impl<T:?Sized> Default for Id<T> { fn default() -> Self { Id(Default::default(), marker::PhantomData) } } impl<T:?Sized> cmp::Eq for Id<T> {} impl<T:?Sized> hash::Hash for Id<T> { fn hash<H: hash::Hasher>(&self, state: &mut H) { self.0.hash(state); } } impl<T:?Sized> cmp::Ord for Id<T> { fn cmp(&self, other: &Self) -> cmp::Ordering { self.0.cmp(&other.0) } } impl<T:?Sized> cmp::PartialEq for Id<T> { fn eq(&self, other: &Self) -> bool { self.0.eq(&other.0) } } impl<T:?Sized> cmp::PartialOrd for Id<T> { fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> { self.0.partial_cmp(&other.0) } } impl<T:?Sized> TableIndex for Id<T> { fn from_index(index: usize) -> Self { Id::new(index as u32) } fn index(&self) -> usize { self.value() as usize } } /// IdIterator. /// /// An Iterator over consecutive IDs. // #[manual(Clone, Copy, Debug, Default, PartialEq, PartialOrd, Eq, Ord, Hash)] pub struct IdIterator<T:?Sized> { start: u32, end: u32, _marker: marker::PhantomData<*const T>, } impl<T:?Sized> IdIterator<T> { /// Creates an instance. pub fn new(start: u32, end: u32) -> Self { IdIterator { start, end, _marker: marker::PhantomData } } } impl<T:?Sized> Clone for IdIterator<T> { fn clone(&self) -> Self { *self } } impl<T:?Sized> Copy for IdIterator<T> {} impl<T:?Sized> fmt::Debug for IdIterator<T> { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { // FIXME(matthieum): consider adding `std::intrinsics::type_name<T>()` // once it stabilizes. write!(f, "IdIterator({}, {})", self.start, self.end) } } impl<T:?Sized> Default for IdIterator<T> { fn default() -> Self { IdIterator::new(0, 0) } } impl<T:?Sized> cmp::Eq for IdIterator<T> {} impl<T:?Sized> hash::Hash for IdIterator<T> { fn hash<H: hash::Hasher>(&self, state: &mut H) { self.start.hash(state); self.end.hash(state); } } impl<T:?Sized> iter::Iterator for IdIterator<T> { type Item = Id<T>; fn next(&mut self) -> Option<Id<T>> { if self.start < self.end { let result = Id::new(self.start); self.start += 1; Some(result) } else { None } } fn size_hint(&self) -> (usize, Option<usize>) { let difference = self.len(); (difference, Some(difference)) } fn count(self) -> usize { self.len() } fn last(self) -> Option<Id<T>> { if self.start < self.end { Some(Id::new(self.end - 1)) } else { None } } fn nth(&mut self, n: usize) -> Option<Id<T>> { let result = self.start.saturating_add(n as u32); if result < self.end { self.start = result + 1; Some(Id::new(result)) } else { self.start = self.end; None } } fn max(self) -> Option<Id<T>> { self.last() } fn min(mut self) -> Option<Id<T>> { self.next() } } impl<T:?Sized> iter::DoubleEndedIterator for IdIterator<T> { fn next_back(&mut self) -> Option<Id<T>> { if self.start < self.end { self.end -= 1; Some(Id::new(self.end)) } else { None } } } impl<T:?Sized> iter::ExactSizeIterator for IdIterator<T> { fn len(&self) -> usize { self.end.saturating_sub(self.start) as usize } } impl<T:?Sized> cmp::Ord for IdIterator<T> { fn cmp(&self, other: &Self) -> cmp::Ordering { (self.start, self.end).cmp(&(other.start, other.end)) } } impl<T:?Sized> cmp::PartialEq for IdIterator<T> { fn eq(&self, other: &Self) -> bool { (self.start, self.end).eq(&(other.start, other.end)) } } impl<T:?Sized> cmp::PartialOrd for IdIterator<T> { fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> { (self.start, self.end).partial_cmp(&(other.start, other.end)) } } /// A Range represents a start and end position in a buffer. /// /// Note: the `Range` does not know which buffer it indexes in. /// /// Note: a `Range` cannot index past 4GB. #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)] pub struct Range { offset: u32, length: u32, } impl Range { /// Creates a new `Range` from a start position and length. /// /// In Debug, it is checked that the end position will not exceed 4GB. pub fn new(offset: usize, length: usize) -> Range { debug_assert!(offset <= std::u32::MAX as usize); debug_assert!(length <= std::u32::MAX as usize); debug_assert!(offset <= (std::u32::MAX as usize - length)); Range { offset: offset as u32, length: length as u32 } } /// Creates a new `Range` from a start and end position. /// /// As the name implies, this creates a half-open range, similar to `start..end`. pub fn half_open(start: u32, end: u32) -> Range { debug_assert!(start <= end); Range { offset: start, length: end - start } } /// Returns the start position of the range. pub fn offset(self) -> usize { self.offset as usize } /// Returns the end position of the range (excluded). pub fn end_offset(self) -> usize { self.offset() + self.length() } /// Returns the length of the range. pub fn length(self) -> usize { self.length as usize } /// Shifts range to the left. pub fn shift_left(self, n: usize) -> Range { self.shift_to(self.offset() - n) } /// Shifts range to the right. pub fn shift_right(self, n: usize) -> Range { self.shift_to(self.offset() + n) } /// Shifts range to specified offset. pub fn shift_to(self, offset: usize) -> Range { Range { offset: offset as u32,..self } } /// Skips n from the left. pub fn skip_left(self, n: usize) -> Range { Range { offset: self.offset + (n as u32), length: self.length - (n as u32), } } /// Skips n from the right. pub fn skip_right(self, n: usize) -> Range { Range { offset: self.offset, length: self.length - (n as u32), } } /// Extend one range with another, the resulting range spans both ranges, /// and in the case they were discontiguous also spans the interval. pub fn extend(self, other: Range) -> Range { if self.offset > other.offset { other.extend(self) } else if self.end_offset() >= other.end_offset() { self } else { Range { offset: self.offset, length: (other.end_offset() - self.offset()) as u32 } } } } impl fmt::Debug for Range { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(f, "{}@{}", self.length, self.offset) } } impl Default for Range { fn default() -> Range { Range::new(0, 0) } } impl fmt::Display for Range { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(f, "{}@{}", self.length, self.offset) } } impl ops::Index<Range> for [u8] { type Output = [u8]; fn index(&self, index: Range) -> &[u8] { &self[index.offset()..index.end_offset()] } } /// A Slice of bytes, printed more pleasantly #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)] pub struct Slice<'a>(pub &'a [u8]); impl<'a> Slice<'a> { /// Returns true if empty, false otherwise. pub fn is_empty(&self) -> bool { self.0.is_empty() } /// Returns the length of the slice. pub fn len(&self) -> usize { self.0.len() } /// Returns the byte at the indicated position, or None if it is invalid. pub fn get(&self, pos: usize) -> Option<&u8> { self.0.get(pos) } } impl<'a> fmt::Debug for Slice<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(f, "{}", self) } } impl<'a> fmt::Display for Slice<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { let mut start = 0; while start < self.0.len() { let end = self.0[start..].iter().position(|&b| b < 32 || b > 126) .unwrap_or(self.len()); f.write_str( std::str::from_utf8(&self.0[start..end]).expect("Valid UTF-8") )?; start = end; let end = self.0[start..].iter().position(|&b| b >= 32 && b <= 126) .unwrap_or(self.len()); for &byte in &self.0[start..end] { write!(f, "{{0x{:X}}}", byte)?; } start = end; } Ok(()) } } /// Span pub trait Span { /// Returns the Range spanned by the element. fn span(&self) -> Range; } /// A Store trait, to abstract over the actual storage of individual elements. pub trait Store<T, I = Id<T>> { /// Returns the number of items. fn len(&self) -> usize; /// Returns a copy of the item. fn get(&self, id: I) -> T; /// Returns the range of the item. fn get_range(&self, id: I) -> Range; /// Pushes an item. fn push(&mut self, item: T, range: Range) -> I; } /// A MultiStore trait, to abstract over the actual storage of slices. pub trait MultiStore<T, I = Id<[T]>> { /// Returns the slice of items. fn get_slice(&self, id: I) -> &[T]; // TODO(matthieum): A more efficient interface would take IntoIterator<Item = T> /// Pushes a slice of element. fn push_slice(&mut self, items: &[T]) -> I; } // // Tests // #[cfg(test)] mod tests { use super::{CoreId, Range}; #[test] fn core_id_roundtrip() { for i in 0..10 { assert_eq!(i, CoreId::new(i).raw()); } } #[test] fn core_id_default() { let core: CoreId = Default::default(); assert_eq!(std::u32::MAX - 1, core.raw()); } #[test] #[should_panic] fn core_id_reserved_size_optimization() { CoreId::new(std::u32::MAX); } #[test] fn range_extend_contiguous() { let result = Range::new(3, 4).extend(Range::new(7, 2)); assert_eq!(result, Range::new(3, 6)); } #[test] fn range_extend_separated() { let result = Range::new(3, 4).extend(Range::new(11, 3)); assert_eq!(result, Range::new(3, 11)); } #[test] fn range_extend_partially_overlapping() { let result = Range::new(3, 4).extend(Range::new(5, 3)); assert_eq!(result, Range::new(3, 5)); } #[test] fn range_extend_totally_overlapping()
#[test] fn range_extend_reversed() { let result = Range::new(5, 3).extend(Range::new(3, 4)); assert_eq!(result, Range::new(3, 5)); } }
{ let result = Range::new(3, 4).extend(Range::new(5, 2)); assert_eq!(result, Range::new(3, 4)); }
identifier_body