text
stringlengths
8
4.13M
use crate::{FunctionCtx, Backend}; use crate::ptr::Pointer; use crate::value::Value; use lowlang_syntax as syntax; use syntax::layout::TyLayout; use cranelift_codegen::ir; use cranelift_module::Module; pub enum PassMode { ByRef, ByVal(ir::Type), NoPass, } pub fn pass_mode<'t, 'l>(module: &Module<impl Backend>, layout: TyLayout<'t, 'l>) -> PassMode { match &*layout.ty { syntax::Type::Bool | syntax::Type::Char | syntax::Type::Int(_) | syntax::Type::UInt(_) | syntax::Type::Float(_) | syntax::Type::Ref(_) | syntax::Type::Proc(_) => PassMode::ByVal(crate::clif_type(module, layout).unwrap()), _ if layout.details.size == 0 => PassMode::NoPass, _ => PassMode::ByRef, } } pub fn value_for_param<'a, 't, 'l>( fx: &mut FunctionCtx<'a, 't, 'l, impl Backend>, start_ebb: ir::Ebb, layout: TyLayout<'t, 'l> ) -> Option<Value<'t, 'l>> { match pass_mode(fx.module, layout) { PassMode::NoPass => None, PassMode::ByVal(clif_type) => { let ebb_param = fx.builder.append_ebb_param(start_ebb, clif_type); Some(Value::new_val(ebb_param, layout)) }, PassMode::ByRef => { let ebb_param = fx.builder.append_ebb_param(start_ebb, fx.pointer_type); Some(Value::new_ref(Pointer::addr(ebb_param), layout)) }, } } pub fn value_for_arg<'a, 't, 'l>( fx: &mut FunctionCtx<'a, 't, 'l, impl Backend>, arg: Value<'t, 'l> ) -> Option<ir::Value> { match pass_mode(fx.module, arg.layout) { PassMode::ByVal(_) => Some(arg.load_scalar(fx)), PassMode::ByRef => Some(arg.on_stack(fx).get_addr(fx)), PassMode::NoPass => None, } } pub fn call_sig<'t, 'l>( module: &Module<impl Backend>, layouts: &syntax::layout::LayoutCtx<'t, 'l>, sig: &syntax::Signature<'t>, ) -> ir::Signature { let mut sign = module.make_signature(); for ret in &sig.2 { match pass_mode(module, ret.layout(layouts)) { PassMode::NoPass => {}, PassMode::ByVal(ty) => sign.returns.push(ir::AbiParam::new(ty)), PassMode::ByRef => sign.params.push(ir::AbiParam::new(module.target_config().pointer_type())), } } for param in &sig.1 { match pass_mode(module, param.layout(layouts)) { PassMode::NoPass => {}, PassMode::ByVal(ty) => sign.params.push(ir::AbiParam::new(ty)), PassMode::ByRef => sign.params.push(ir::AbiParam::new(module.target_config().pointer_type())), } } sign }
use libc; use crate::clist::*; use crate::mailimf_types::*; use crate::mailmime::*; use crate::mailmime_types::*; use crate::x::*; #[derive(Copy, Clone)] #[repr(C)] pub struct mailmime_single_fields { pub fld_content: *mut mailmime_content, pub fld_content_charset: *mut libc::c_char, pub fld_content_boundary: *mut libc::c_char, pub fld_content_name: *mut libc::c_char, pub fld_encoding: *mut mailmime_mechanism, pub fld_id: *mut libc::c_char, pub fld_description: *mut libc::c_char, pub fld_version: uint32_t, pub fld_disposition: *mut mailmime_disposition, pub fld_disposition_filename: *mut libc::c_char, pub fld_disposition_creation_date: *mut libc::c_char, pub fld_disposition_modification_date: *mut libc::c_char, pub fld_disposition_read_date: *mut libc::c_char, pub fld_disposition_size: size_t, pub fld_language: *mut mailmime_language, pub fld_location: *mut libc::c_char, } pub unsafe fn mailmime_transfer_encoding_get(mut fields: *mut mailmime_fields) -> libc::c_int { let mut cur: *mut clistiter = 0 as *mut clistiter; cur = (*(*fields).fld_list).first; while !cur.is_null() { let mut field: *mut mailmime_field = 0 as *mut mailmime_field; field = (if !cur.is_null() { (*cur).data } else { 0 as *mut libc::c_void }) as *mut mailmime_field; if (*field).fld_type == MAILMIME_FIELD_TRANSFER_ENCODING as libc::c_int { return (*(*field).fld_data.fld_encoding).enc_type; } cur = if !cur.is_null() { (*cur).next } else { 0 as *mut clistcell } } return MAILMIME_MECHANISM_8BIT as libc::c_int; } pub unsafe fn mailmime_disposition_new_filename( mut type_0: libc::c_int, mut filename: *mut libc::c_char, ) -> *mut mailmime_disposition { return mailmime_disposition_new_with_data( type_0, filename, 0 as *mut libc::c_char, 0 as *mut libc::c_char, 0 as *mut libc::c_char, -1i32 as size_t, ); } pub unsafe fn mailmime_disposition_new_with_data( mut type_0: libc::c_int, mut filename: *mut libc::c_char, mut creation_date: *mut libc::c_char, mut modification_date: *mut libc::c_char, mut read_date: *mut libc::c_char, mut size: size_t, ) -> *mut mailmime_disposition { let mut current_block: u64; let mut dsp_type: *mut mailmime_disposition_type = 0 as *mut mailmime_disposition_type; let mut list: *mut clist = 0 as *mut clist; let mut r: libc::c_int = 0; let mut parm: *mut mailmime_disposition_parm = 0 as *mut mailmime_disposition_parm; let mut dsp: *mut mailmime_disposition = 0 as *mut mailmime_disposition; dsp_type = mailmime_disposition_type_new(type_0, 0 as *mut libc::c_char); if !dsp_type.is_null() { list = clist_new(); if !list.is_null() { if !filename.is_null() { parm = mailmime_disposition_parm_new( MAILMIME_DISPOSITION_PARM_FILENAME as libc::c_int, filename, 0 as *mut libc::c_char, 0 as *mut libc::c_char, 0 as *mut libc::c_char, 0i32 as size_t, 0 as *mut mailmime_parameter, ); if parm.is_null() { current_block = 13210718484351940574; } else { r = clist_insert_after(list, (*list).last, parm as *mut libc::c_void); if r < 0i32 { mailmime_disposition_parm_free(parm); current_block = 13210718484351940574; } else { current_block = 4166486009154926805; } } } else { current_block = 4166486009154926805; } match current_block { 4166486009154926805 => { if !creation_date.is_null() { parm = mailmime_disposition_parm_new( MAILMIME_DISPOSITION_PARM_CREATION_DATE as libc::c_int, 0 as *mut libc::c_char, creation_date, 0 as *mut libc::c_char, 0 as *mut libc::c_char, 0i32 as size_t, 0 as *mut mailmime_parameter, ); if parm.is_null() { current_block = 13210718484351940574; } else { r = clist_insert_after(list, (*list).last, parm as *mut libc::c_void); if r < 0i32 { mailmime_disposition_parm_free(parm); current_block = 13210718484351940574; } else { current_block = 12147880666119273379; } } } else { current_block = 12147880666119273379; } match current_block { 13210718484351940574 => {} _ => { if !modification_date.is_null() { parm = mailmime_disposition_parm_new( MAILMIME_DISPOSITION_PARM_MODIFICATION_DATE as libc::c_int, 0 as *mut libc::c_char, 0 as *mut libc::c_char, modification_date, 0 as *mut libc::c_char, 0i32 as size_t, 0 as *mut mailmime_parameter, ); if parm.is_null() { current_block = 13210718484351940574; } else { r = clist_insert_after( list, (*list).last, parm as *mut libc::c_void, ); if r < 0i32 { mailmime_disposition_parm_free(parm); current_block = 13210718484351940574; } else { current_block = 13550086250199790493; } } } else { current_block = 13550086250199790493; } match current_block { 13210718484351940574 => {} _ => { if !read_date.is_null() { parm = mailmime_disposition_parm_new( MAILMIME_DISPOSITION_PARM_READ_DATE as libc::c_int, 0 as *mut libc::c_char, 0 as *mut libc::c_char, 0 as *mut libc::c_char, read_date, 0i32 as size_t, 0 as *mut mailmime_parameter, ); if parm.is_null() { current_block = 13210718484351940574; } else { r = clist_insert_after( list, (*list).last, parm as *mut libc::c_void, ); if r < 0i32 { mailmime_disposition_parm_free(parm); current_block = 13210718484351940574; } else { current_block = 9520865839495247062; } } } else { current_block = 9520865839495247062; } match current_block { 13210718484351940574 => {} _ => { if size != -1i32 as size_t { parm = mailmime_disposition_parm_new( MAILMIME_DISPOSITION_PARM_SIZE as libc::c_int, 0 as *mut libc::c_char, 0 as *mut libc::c_char, 0 as *mut libc::c_char, 0 as *mut libc::c_char, size, 0 as *mut mailmime_parameter, ); if parm.is_null() { current_block = 13210718484351940574; } else { r = clist_insert_after( list, (*list).last, parm as *mut libc::c_void, ); if r < 0i32 { mailmime_disposition_parm_free(parm); current_block = 13210718484351940574; } else { current_block = 12199444798915819164; } } } else { current_block = 12199444798915819164; } match current_block { 13210718484351940574 => {} _ => { dsp = mailmime_disposition_new(dsp_type, list); return dsp; } } } } } } } } } _ => {} } clist_foreach( list, ::std::mem::transmute::< Option<unsafe fn(_: *mut mailmime_disposition_parm) -> ()>, clist_func, >(Some(mailmime_disposition_parm_free)), 0 as *mut libc::c_void, ); clist_free(list); } mailmime_disposition_type_free(dsp_type); } return 0 as *mut mailmime_disposition; } pub unsafe fn mailmime_fields_new_empty() -> *mut mailmime_fields { let mut list: *mut clist = 0 as *mut clist; let mut fields: *mut mailmime_fields = 0 as *mut mailmime_fields; list = clist_new(); if !list.is_null() { fields = mailmime_fields_new(list); if fields.is_null() { clist_free(list); } else { return fields; } } return 0 as *mut mailmime_fields; } pub unsafe fn mailmime_fields_add( mut fields: *mut mailmime_fields, mut field: *mut mailmime_field, ) -> libc::c_int { let mut r: libc::c_int = 0; r = clist_insert_after( (*fields).fld_list, (*(*fields).fld_list).last, field as *mut libc::c_void, ); if r < 0i32 { return MAILIMF_ERROR_MEMORY as libc::c_int; } return MAILIMF_NO_ERROR as libc::c_int; } pub unsafe fn mailmime_fields_new_with_data( mut encoding: *mut mailmime_mechanism, mut id: *mut libc::c_char, mut description: *mut libc::c_char, mut disposition: *mut mailmime_disposition, mut language: *mut mailmime_language, ) -> *mut mailmime_fields { let mut current_block: u64; let mut field: *mut mailmime_field = 0 as *mut mailmime_field; let mut fields: *mut mailmime_fields = 0 as *mut mailmime_fields; let mut r: libc::c_int = 0; fields = mailmime_fields_new_empty(); if !fields.is_null() { if !encoding.is_null() { field = mailmime_field_new( MAILMIME_FIELD_TRANSFER_ENCODING as libc::c_int, 0 as *mut mailmime_content, encoding, 0 as *mut libc::c_char, 0 as *mut libc::c_char, 0i32 as uint32_t, 0 as *mut mailmime_disposition, 0 as *mut mailmime_language, 0 as *mut libc::c_char, ); if field.is_null() { current_block = 5039974454013832799; } else { r = mailmime_fields_add(fields, field); if r != MAILIMF_NO_ERROR as libc::c_int { mailmime_field_detach(field); mailmime_field_free(field); current_block = 5039974454013832799; } else { current_block = 7746791466490516765; } } } else { current_block = 7746791466490516765; } match current_block { 7746791466490516765 => { if !id.is_null() { field = mailmime_field_new( MAILMIME_FIELD_ID as libc::c_int, 0 as *mut mailmime_content, 0 as *mut mailmime_mechanism, id, 0 as *mut libc::c_char, 0i32 as uint32_t, 0 as *mut mailmime_disposition, 0 as *mut mailmime_language, 0 as *mut libc::c_char, ); if field.is_null() { current_block = 5039974454013832799; } else { r = mailmime_fields_add(fields, field); if r != MAILIMF_NO_ERROR as libc::c_int { mailmime_field_detach(field); mailmime_field_free(field); current_block = 5039974454013832799; } else { current_block = 13242334135786603907; } } } else { current_block = 13242334135786603907; } match current_block { 5039974454013832799 => {} _ => { if !description.is_null() { field = mailmime_field_new( MAILMIME_FIELD_DESCRIPTION as libc::c_int, 0 as *mut mailmime_content, 0 as *mut mailmime_mechanism, 0 as *mut libc::c_char, description, 0i32 as uint32_t, 0 as *mut mailmime_disposition, 0 as *mut mailmime_language, 0 as *mut libc::c_char, ); if field.is_null() { current_block = 5039974454013832799; } else { r = mailmime_fields_add(fields, field); if r != MAILIMF_NO_ERROR as libc::c_int { mailmime_field_detach(field); mailmime_field_free(field); current_block = 5039974454013832799; } else { current_block = 15125582407903384992; } } } else { current_block = 15125582407903384992; } match current_block { 5039974454013832799 => {} _ => { if !disposition.is_null() { field = mailmime_field_new( MAILMIME_FIELD_DISPOSITION as libc::c_int, 0 as *mut mailmime_content, 0 as *mut mailmime_mechanism, 0 as *mut libc::c_char, 0 as *mut libc::c_char, 0i32 as uint32_t, disposition, 0 as *mut mailmime_language, 0 as *mut libc::c_char, ); if field.is_null() { current_block = 5039974454013832799; } else { r = mailmime_fields_add(fields, field); if r != MAILIMF_NO_ERROR as libc::c_int { mailmime_field_detach(field); mailmime_field_free(field); current_block = 5039974454013832799; } else { current_block = 9520865839495247062; } } } else { current_block = 9520865839495247062; } match current_block { 5039974454013832799 => {} _ => { if !language.is_null() { field = mailmime_field_new( MAILMIME_FIELD_DISPOSITION as libc::c_int, 0 as *mut mailmime_content, 0 as *mut mailmime_mechanism, 0 as *mut libc::c_char, 0 as *mut libc::c_char, 0i32 as uint32_t, 0 as *mut mailmime_disposition, language, 0 as *mut libc::c_char, ); if field.is_null() { current_block = 5039974454013832799; } else { r = mailmime_fields_add(fields, field); if r != MAILIMF_NO_ERROR as libc::c_int { mailmime_field_detach(field); mailmime_field_free(field); current_block = 5039974454013832799; } else { current_block = 15512526488502093901; } } } else { current_block = 15512526488502093901; } match current_block { 5039974454013832799 => {} _ => return fields, } } } } } } } } _ => {} } clist_foreach( (*fields).fld_list, ::std::mem::transmute::<Option<unsafe fn(_: *mut mailmime_field) -> ()>, clist_func>( Some(mailmime_field_detach), ), 0 as *mut libc::c_void, ); mailmime_fields_free(fields); } return 0 as *mut mailmime_fields; } unsafe fn mailmime_field_detach(mut field: *mut mailmime_field) { match (*field).fld_type { 1 => (*field).fld_data.fld_content = 0 as *mut mailmime_content, 2 => (*field).fld_data.fld_encoding = 0 as *mut mailmime_mechanism, 3 => (*field).fld_data.fld_id = 0 as *mut libc::c_char, 4 => (*field).fld_data.fld_description = 0 as *mut libc::c_char, 6 => (*field).fld_data.fld_disposition = 0 as *mut mailmime_disposition, 7 => (*field).fld_data.fld_language = 0 as *mut mailmime_language, _ => {} }; } pub unsafe fn mailmime_fields_new_with_version( mut encoding: *mut mailmime_mechanism, mut id: *mut libc::c_char, mut description: *mut libc::c_char, mut disposition: *mut mailmime_disposition, mut language: *mut mailmime_language, ) -> *mut mailmime_fields { let mut field: *mut mailmime_field = 0 as *mut mailmime_field; let mut fields: *mut mailmime_fields = 0 as *mut mailmime_fields; let mut r: libc::c_int = 0; fields = mailmime_fields_new_with_data(encoding, id, description, disposition, language); if !fields.is_null() { field = mailmime_field_new( MAILMIME_FIELD_VERSION as libc::c_int, 0 as *mut mailmime_content, 0 as *mut mailmime_mechanism, 0 as *mut libc::c_char, 0 as *mut libc::c_char, (1i32 << 16i32) as uint32_t, 0 as *mut mailmime_disposition, 0 as *mut mailmime_language, 0 as *mut libc::c_char, ); if !field.is_null() { r = mailmime_fields_add(fields, field); if r != MAILIMF_NO_ERROR as libc::c_int { mailmime_field_detach(field); mailmime_field_free(field); } else { return fields; } } clist_foreach( (*fields).fld_list, ::std::mem::transmute::<Option<unsafe fn(_: *mut mailmime_field) -> ()>, clist_func>( Some(mailmime_field_detach), ), 0 as *mut libc::c_void, ); mailmime_fields_free(fields); } return 0 as *mut mailmime_fields; } pub unsafe fn mailmime_get_content_message() -> *mut mailmime_content { let mut list: *mut clist = 0 as *mut clist; let mut composite_type: *mut mailmime_composite_type = 0 as *mut mailmime_composite_type; let mut mime_type: *mut mailmime_type = 0 as *mut mailmime_type; let mut content: *mut mailmime_content = 0 as *mut mailmime_content; let mut subtype: *mut libc::c_char = 0 as *mut libc::c_char; composite_type = mailmime_composite_type_new( MAILMIME_COMPOSITE_TYPE_MESSAGE as libc::c_int, 0 as *mut libc::c_char, ); if !composite_type.is_null() { mime_type = mailmime_type_new( MAILMIME_TYPE_COMPOSITE_TYPE as libc::c_int, 0 as *mut mailmime_discrete_type, composite_type, ); if !mime_type.is_null() { composite_type = 0 as *mut mailmime_composite_type; list = clist_new(); if !list.is_null() { subtype = strdup(b"rfc822\x00" as *const u8 as *const libc::c_char); if !subtype.is_null() { content = mailmime_content_new(mime_type, subtype, list); if content.is_null() { free(subtype as *mut libc::c_void); } else { return content; } } clist_free(list); } mailmime_type_free(mime_type); } if !composite_type.is_null() { mailmime_composite_type_free(composite_type); } } return 0 as *mut mailmime_content; } pub unsafe fn mailmime_get_content_text() -> *mut mailmime_content { let mut list: *mut clist = 0 as *mut clist; let mut discrete_type: *mut mailmime_discrete_type = 0 as *mut mailmime_discrete_type; let mut mime_type: *mut mailmime_type = 0 as *mut mailmime_type; let mut content: *mut mailmime_content = 0 as *mut mailmime_content; let mut subtype: *mut libc::c_char = 0 as *mut libc::c_char; discrete_type = mailmime_discrete_type_new( MAILMIME_DISCRETE_TYPE_TEXT as libc::c_int, 0 as *mut libc::c_char, ); if !discrete_type.is_null() { mime_type = mailmime_type_new( MAILMIME_TYPE_DISCRETE_TYPE as libc::c_int, discrete_type, 0 as *mut mailmime_composite_type, ); if !mime_type.is_null() { discrete_type = 0 as *mut mailmime_discrete_type; list = clist_new(); if !list.is_null() { subtype = strdup(b"plain\x00" as *const u8 as *const libc::c_char); if !subtype.is_null() { content = mailmime_content_new(mime_type, subtype, list); if content.is_null() { free(subtype as *mut libc::c_void); } else { return content; } } clist_free(list); } mailmime_type_free(mime_type); } if !discrete_type.is_null() { mailmime_discrete_type_free(discrete_type); } } return 0 as *mut mailmime_content; } /* struct mailmime_content * mailmime_get_content(char * mime_type); */ pub unsafe fn mailmime_data_new_data( mut encoding: libc::c_int, mut encoded: libc::c_int, mut data: *const libc::c_char, mut length: size_t, ) -> *mut mailmime_data { return mailmime_data_new( MAILMIME_DATA_TEXT as libc::c_int, encoding, encoded, data, length, 0 as *mut libc::c_char, ); } pub unsafe fn mailmime_data_new_file( mut encoding: libc::c_int, mut encoded: libc::c_int, mut filename: *mut libc::c_char, ) -> *mut mailmime_data { return mailmime_data_new( MAILMIME_DATA_FILE as libc::c_int, encoding, encoded, 0 as *const libc::c_char, 0i32 as size_t, filename, ); } pub unsafe fn mailmime_new_message_data(mut msg_mime: *mut mailmime) -> *mut mailmime { let mut content: *mut mailmime_content = 0 as *mut mailmime_content; let mut build_info: *mut mailmime = 0 as *mut mailmime; let mut mime_fields: *mut mailmime_fields = 0 as *mut mailmime_fields; content = mailmime_get_content_message(); if !content.is_null() { mime_fields = mailmime_fields_new_with_version( 0 as *mut mailmime_mechanism, 0 as *mut libc::c_char, 0 as *mut libc::c_char, 0 as *mut mailmime_disposition, 0 as *mut mailmime_language, ); if !mime_fields.is_null() { build_info = mailmime_new( MAILMIME_MESSAGE as libc::c_int, 0 as *const libc::c_char, 0i32 as size_t, mime_fields, content, 0 as *mut mailmime_data, 0 as *mut mailmime_data, 0 as *mut mailmime_data, 0 as *mut clist, 0 as *mut mailimf_fields, msg_mime, ); if build_info.is_null() { mailmime_fields_free(mime_fields); } else { return build_info; } } mailmime_content_free(content); } return 0 as *mut mailmime; } pub unsafe fn mailmime_new_empty( mut content: *mut mailmime_content, mut mime_fields: *mut mailmime_fields, ) -> *mut mailmime { let mut current_block: u64; let mut build_info: *mut mailmime = 0 as *mut mailmime; let mut list: *mut clist = 0 as *mut clist; let mut r: libc::c_int = 0; let mut mime_type: libc::c_int = 0; list = 0 as *mut clist; match (*(*content).ct_type).tp_type { 1 => { mime_type = MAILMIME_SINGLE as libc::c_int; current_block = 12349973810996921269; } 2 => match (*(*(*content).ct_type).tp_data.tp_composite_type).ct_type { 2 => { current_block = 5822726848290245908; match current_block { 565197971715936940 => { if strcasecmp( (*content).ct_subtype, b"rfc822\x00" as *const u8 as *const libc::c_char, ) == 0i32 { mime_type = MAILMIME_MESSAGE as libc::c_int } else { mime_type = MAILMIME_SINGLE as libc::c_int } } _ => mime_type = MAILMIME_MULTIPLE as libc::c_int, } current_block = 12349973810996921269; } 1 => { current_block = 565197971715936940; match current_block { 565197971715936940 => { if strcasecmp( (*content).ct_subtype, b"rfc822\x00" as *const u8 as *const libc::c_char, ) == 0i32 { mime_type = MAILMIME_MESSAGE as libc::c_int } else { mime_type = MAILMIME_SINGLE as libc::c_int } } _ => mime_type = MAILMIME_MULTIPLE as libc::c_int, } current_block = 12349973810996921269; } _ => { current_block = 13576996419214490990; } }, _ => { current_block = 13576996419214490990; } } match current_block { 12349973810996921269 => { if mime_type == MAILMIME_MULTIPLE as libc::c_int { let mut attr_name: *mut libc::c_char = 0 as *mut libc::c_char; let mut attr_value: *mut libc::c_char = 0 as *mut libc::c_char; let mut param: *mut mailmime_parameter = 0 as *mut mailmime_parameter; let mut parameters: *mut clist = 0 as *mut clist; let mut boundary: *mut libc::c_char = 0 as *mut libc::c_char; list = clist_new(); if list.is_null() { current_block = 13576996419214490990; } else { attr_name = strdup(b"boundary\x00" as *const u8 as *const libc::c_char); if attr_name.is_null() { current_block = 13142422523813476356; } else { boundary = mailmime_generate_boundary(); attr_value = boundary; if attr_name.is_null() { free(attr_name as *mut libc::c_void); current_block = 13142422523813476356; } else { param = mailmime_parameter_new(attr_name, attr_value); if param.is_null() { free(attr_value as *mut libc::c_void); free(attr_name as *mut libc::c_void); current_block = 13142422523813476356; } else { if (*content).ct_parameters.is_null() { parameters = clist_new(); if parameters.is_null() { mailmime_parameter_free(param); current_block = 13142422523813476356; } else { current_block = 1836292691772056875; } } else { parameters = (*content).ct_parameters; current_block = 1836292691772056875; } match current_block { 13142422523813476356 => {} _ => { r = clist_insert_after( parameters, (*parameters).last, param as *mut libc::c_void, ); if r != 0i32 { clist_free(parameters); mailmime_parameter_free(param); current_block = 13142422523813476356; } else { if (*content).ct_parameters.is_null() { (*content).ct_parameters = parameters } current_block = 2543120759711851213; } } } } } } match current_block { 2543120759711851213 => {} _ => { clist_free(list); current_block = 13576996419214490990; } } } } else { current_block = 2543120759711851213; } match current_block { 13576996419214490990 => {} _ => { build_info = mailmime_new( mime_type, 0 as *const libc::c_char, 0i32 as size_t, mime_fields, content, 0 as *mut mailmime_data, 0 as *mut mailmime_data, 0 as *mut mailmime_data, list, 0 as *mut mailimf_fields, 0 as *mut mailmime, ); if build_info.is_null() { clist_free(list); return 0 as *mut mailmime; } return build_info; } } } _ => {} } return 0 as *mut mailmime; } pub unsafe fn mailmime_generate_boundary() -> *mut libc::c_char { let mut id: [libc::c_char; 512] = [0; 512]; let mut now: time_t = 0; let mut name: [libc::c_char; 512] = [0; 512]; let mut value: libc::c_long = 0; now = time(0 as *mut time_t); value = random(); libc::gethostname(name.as_mut_ptr(), 512); snprintf( id.as_mut_ptr(), 512i32 as libc::size_t, b"%llx_%lx_%x\x00" as *const u8 as *const libc::c_char, now as libc::c_longlong, value, getpid(), ); return strdup(id.as_mut_ptr()); } pub unsafe fn mailmime_new_with_content( mut content_type: *const libc::c_char, mut mime_fields: *mut mailmime_fields, mut result: *mut *mut mailmime, ) -> libc::c_int { let mut r: libc::c_int = 0; let mut cur_token: size_t = 0; let mut content: *mut mailmime_content = 0 as *mut mailmime_content; let mut build_info: *mut mailmime = 0 as *mut mailmime; let mut res: libc::c_int = 0; cur_token = 0i32 as size_t; r = mailmime_content_parse( content_type, strlen(content_type), &mut cur_token, &mut content, ); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { build_info = mailmime_new_empty(content, mime_fields); if build_info.is_null() { res = MAILIMF_ERROR_MEMORY as libc::c_int; mailmime_content_free(content); } else { *result = build_info; return MAILIMF_NO_ERROR as libc::c_int; } } return res; } pub unsafe fn mailmime_set_preamble_file( mut build_info: *mut mailmime, mut filename: *mut libc::c_char, ) -> libc::c_int { let mut data: *mut mailmime_data = 0 as *mut mailmime_data; data = mailmime_data_new( MAILMIME_DATA_FILE as libc::c_int, MAILMIME_MECHANISM_8BIT as libc::c_int, 0i32, 0 as *const libc::c_char, 0i32 as size_t, filename, ); if data.is_null() { return MAILIMF_ERROR_MEMORY as libc::c_int; } (*build_info).mm_data.mm_multipart.mm_preamble = data; return MAILIMF_NO_ERROR as libc::c_int; } pub unsafe fn mailmime_set_epilogue_file( mut build_info: *mut mailmime, mut filename: *mut libc::c_char, ) -> libc::c_int { let mut data: *mut mailmime_data = 0 as *mut mailmime_data; data = mailmime_data_new( MAILMIME_DATA_FILE as libc::c_int, MAILMIME_MECHANISM_8BIT as libc::c_int, 0i32, 0 as *const libc::c_char, 0i32 as size_t, filename, ); if data.is_null() { return MAILIMF_ERROR_MEMORY as libc::c_int; } (*build_info).mm_data.mm_multipart.mm_epilogue = data; return MAILIMF_NO_ERROR as libc::c_int; } pub unsafe fn mailmime_set_preamble_text( mut build_info: *mut mailmime, mut data_str: *mut libc::c_char, mut length: size_t, ) -> libc::c_int { let mut data: *mut mailmime_data = 0 as *mut mailmime_data; data = mailmime_data_new( MAILMIME_DATA_TEXT as libc::c_int, MAILMIME_MECHANISM_8BIT as libc::c_int, 0i32, data_str, length, 0 as *mut libc::c_char, ); if data.is_null() { return MAILIMF_ERROR_MEMORY as libc::c_int; } (*build_info).mm_data.mm_multipart.mm_preamble = data; return MAILIMF_NO_ERROR as libc::c_int; } pub unsafe fn mailmime_set_epilogue_text( mut build_info: *mut mailmime, mut data_str: *mut libc::c_char, mut length: size_t, ) -> libc::c_int { let mut data: *mut mailmime_data = 0 as *mut mailmime_data; data = mailmime_data_new( MAILMIME_DATA_TEXT as libc::c_int, MAILMIME_MECHANISM_8BIT as libc::c_int, 0i32, data_str, length, 0 as *mut libc::c_char, ); if data.is_null() { return MAILIMF_ERROR_MEMORY as libc::c_int; } (*build_info).mm_data.mm_multipart.mm_epilogue = data; return MAILIMF_NO_ERROR as libc::c_int; } pub unsafe fn mailmime_set_body_file( mut build_info: *mut mailmime, mut filename: *mut libc::c_char, ) -> libc::c_int { let mut encoding: libc::c_int = 0; let mut data: *mut mailmime_data = 0 as *mut mailmime_data; encoding = mailmime_transfer_encoding_get((*build_info).mm_mime_fields); data = mailmime_data_new( MAILMIME_DATA_FILE as libc::c_int, encoding, 0i32, 0 as *const libc::c_char, 0i32 as size_t, filename, ); if data.is_null() { return MAILIMF_ERROR_MEMORY as libc::c_int; } (*build_info).mm_data.mm_single = data; return MAILIMF_NO_ERROR as libc::c_int; } pub unsafe fn mailmime_set_body_text( mut build_info: *mut mailmime, mut data_str: *mut libc::c_char, mut length: size_t, ) -> libc::c_int { let mut encoding: libc::c_int = 0; let mut data: *mut mailmime_data = 0 as *mut mailmime_data; encoding = mailmime_transfer_encoding_get((*build_info).mm_mime_fields); data = mailmime_data_new( MAILMIME_DATA_TEXT as libc::c_int, encoding, 0i32, data_str, length, 0 as *mut libc::c_char, ); if data.is_null() { return MAILIMF_ERROR_MEMORY as libc::c_int; } (*build_info).mm_data.mm_single = data; return MAILIMF_NO_ERROR as libc::c_int; } pub unsafe fn mailmime_add_part( mut build_info: *mut mailmime, mut part: *mut mailmime, ) -> libc::c_int { let mut r: libc::c_int = 0; if (*build_info).mm_type == MAILMIME_MESSAGE as libc::c_int { (*build_info).mm_data.mm_message.mm_msg_mime = part; (*part).mm_parent_type = MAILMIME_MESSAGE as libc::c_int; (*part).mm_parent = build_info } else if (*build_info).mm_type == MAILMIME_MULTIPLE as libc::c_int { r = clist_insert_after( (*build_info).mm_data.mm_multipart.mm_mp_list, (*(*build_info).mm_data.mm_multipart.mm_mp_list).last, part as *mut libc::c_void, ); if r != 0i32 { return MAILIMF_ERROR_MEMORY as libc::c_int; } (*part).mm_parent_type = MAILMIME_MULTIPLE as libc::c_int; (*part).mm_parent = build_info; (*part).mm_multipart_pos = (*(*build_info).mm_data.mm_multipart.mm_mp_list).last } else { return MAILIMF_ERROR_INVAL as libc::c_int; } return MAILIMF_NO_ERROR as libc::c_int; } pub unsafe fn mailmime_remove_part(mut mime: *mut mailmime) { let mut parent: *mut mailmime = 0 as *mut mailmime; parent = (*mime).mm_parent; if parent.is_null() { return; } match (*mime).mm_parent_type { 3 => { (*mime).mm_parent = 0 as *mut mailmime; (*parent).mm_data.mm_message.mm_msg_mime = 0 as *mut mailmime } 2 => { (*mime).mm_parent = 0 as *mut mailmime; clist_delete( (*parent).mm_data.mm_multipart.mm_mp_list, (*mime).mm_multipart_pos, ); } _ => {} }; } pub unsafe fn mailmime_set_imf_fields( mut build_info: *mut mailmime, mut mm_fields: *mut mailimf_fields, ) { (*build_info).mm_data.mm_message.mm_fields = mm_fields; } pub unsafe fn mailmime_single_fields_init( mut single_fields: *mut mailmime_single_fields, mut fld_fields: *mut mailmime_fields, mut fld_content: *mut mailmime_content, ) { let mut cur: *mut clistiter = 0 as *mut clistiter; memset( single_fields as *mut libc::c_void, 0i32, ::std::mem::size_of::<mailmime_single_fields>() as libc::size_t, ); if !fld_content.is_null() { mailmime_content_single_fields_init(single_fields, fld_content); } if fld_fields.is_null() { return; } cur = (*(*fld_fields).fld_list).first; while !cur.is_null() { let mut field: *mut mailmime_field = 0 as *mut mailmime_field; field = (if !cur.is_null() { (*cur).data } else { 0 as *mut libc::c_void }) as *mut mailmime_field; match (*field).fld_type { 1 => { mailmime_content_single_fields_init(single_fields, (*field).fld_data.fld_content); } 2 => (*single_fields).fld_encoding = (*field).fld_data.fld_encoding, 3 => (*single_fields).fld_id = (*field).fld_data.fld_id, 4 => (*single_fields).fld_description = (*field).fld_data.fld_description, 5 => (*single_fields).fld_version = (*field).fld_data.fld_version, 6 => { mailmime_disposition_single_fields_init( single_fields, (*field).fld_data.fld_disposition, ); } 7 => (*single_fields).fld_language = (*field).fld_data.fld_language, 8 => (*single_fields).fld_location = (*field).fld_data.fld_location, _ => {} } cur = if !cur.is_null() { (*cur).next } else { 0 as *mut clistcell } } } unsafe fn mailmime_disposition_single_fields_init( mut single_fields: *mut mailmime_single_fields, mut fld_disposition: *mut mailmime_disposition, ) { let mut cur: *mut clistiter = 0 as *mut clistiter; (*single_fields).fld_disposition = fld_disposition; cur = (*(*fld_disposition).dsp_parms).first; while !cur.is_null() { let mut param: *mut mailmime_disposition_parm = 0 as *mut mailmime_disposition_parm; param = (if !cur.is_null() { (*cur).data } else { 0 as *mut libc::c_void }) as *mut mailmime_disposition_parm; match (*param).pa_type { 0 => (*single_fields).fld_disposition_filename = (*param).pa_data.pa_filename, 1 => (*single_fields).fld_disposition_creation_date = (*param).pa_data.pa_creation_date, 2 => { (*single_fields).fld_disposition_modification_date = (*param).pa_data.pa_modification_date } 3 => (*single_fields).fld_disposition_read_date = (*param).pa_data.pa_read_date, 4 => (*single_fields).fld_disposition_size = (*param).pa_data.pa_size, _ => {} } cur = if !cur.is_null() { (*cur).next } else { 0 as *mut clistcell } } } unsafe fn mailmime_content_single_fields_init( mut single_fields: *mut mailmime_single_fields, mut fld_content: *mut mailmime_content, ) { let mut cur: *mut clistiter = 0 as *mut clistiter; (*single_fields).fld_content = fld_content; cur = (*(*fld_content).ct_parameters).first; while !cur.is_null() { let mut param: *mut mailmime_parameter = 0 as *mut mailmime_parameter; param = (if !cur.is_null() { (*cur).data } else { 0 as *mut libc::c_void }) as *mut mailmime_parameter; if strcasecmp( (*param).pa_name, b"boundary\x00" as *const u8 as *const libc::c_char, ) == 0i32 { (*single_fields).fld_content_boundary = (*param).pa_value } if strcasecmp( (*param).pa_name, b"charset\x00" as *const u8 as *const libc::c_char, ) == 0i32 { (*single_fields).fld_content_charset = (*param).pa_value } if strcasecmp( (*param).pa_name, b"name\x00" as *const u8 as *const libc::c_char, ) == 0i32 { (*single_fields).fld_content_name = (*param).pa_value } cur = if !cur.is_null() { (*cur).next } else { 0 as *mut clistcell } } } pub unsafe fn mailmime_single_fields_new( mut fld_fields: *mut mailmime_fields, mut fld_content: *mut mailmime_content, ) -> *mut mailmime_single_fields { let mut single_fields: *mut mailmime_single_fields = 0 as *mut mailmime_single_fields; single_fields = malloc(::std::mem::size_of::<mailmime_single_fields>() as libc::size_t) as *mut mailmime_single_fields; if single_fields.is_null() { return 0 as *mut mailmime_single_fields; } else { mailmime_single_fields_init(single_fields, fld_fields, fld_content); return single_fields; }; } pub unsafe fn mailmime_single_fields_free(mut single_fields: *mut mailmime_single_fields) { free(single_fields as *mut libc::c_void); } pub unsafe fn mailmime_smart_add_part( mut mime: *mut mailmime, mut mime_sub: *mut mailmime, ) -> libc::c_int { let mut saved_sub: *mut mailmime = 0 as *mut mailmime; let mut mp: *mut mailmime = 0 as *mut mailmime; let mut res: libc::c_int = 0; let mut r: libc::c_int = 0; match (*mime).mm_type { 1 => res = MAILIMF_ERROR_INVAL as libc::c_int, 2 => { r = mailmime_add_part(mime, mime_sub); if r != MAILIMF_NO_ERROR as libc::c_int { res = MAILIMF_ERROR_MEMORY as libc::c_int } else { return MAILIMF_NO_ERROR as libc::c_int; } } _ => { /* MAILMIME_MESSAGE */ if (*mime).mm_data.mm_message.mm_msg_mime.is_null() { r = mailmime_add_part(mime, mime_sub); if r != MAILIMF_NO_ERROR as libc::c_int { res = MAILIMF_ERROR_MEMORY as libc::c_int } else { return MAILIMF_NO_ERROR as libc::c_int; } } else { if (*(*mime).mm_data.mm_message.mm_msg_mime).mm_type == MAILMIME_MULTIPLE as libc::c_int { return mailmime_add_part((*mime).mm_data.mm_message.mm_msg_mime, mime_sub); } saved_sub = (*mime).mm_data.mm_message.mm_msg_mime; mp = mailmime_multiple_new( b"multipart/mixed\x00" as *const u8 as *const libc::c_char, ); if mp.is_null() { res = MAILIMF_ERROR_MEMORY as libc::c_int } else { mailmime_remove_part(saved_sub); r = mailmime_add_part(mime, mp); if r != MAILIMF_NO_ERROR as libc::c_int { res = MAILIMF_ERROR_MEMORY as libc::c_int; mailmime_free(mp); } else { r = mailmime_add_part(mp, saved_sub); if r != MAILIMF_NO_ERROR as libc::c_int { res = MAILIMF_ERROR_MEMORY as libc::c_int } else { r = mailmime_add_part(mp, mime_sub); if r != MAILIMF_NO_ERROR as libc::c_int { res = MAILIMF_ERROR_MEMORY as libc::c_int } else { return MAILIMF_NO_ERROR as libc::c_int; } } } mailmime_free(saved_sub); } } } } return res; } pub unsafe fn mailmime_multiple_new(mut type_0: *const libc::c_char) -> *mut mailmime { let mut mime_fields: *mut mailmime_fields = 0 as *mut mailmime_fields; let mut content: *mut mailmime_content = 0 as *mut mailmime_content; let mut mp: *mut mailmime = 0 as *mut mailmime; mime_fields = mailmime_fields_new_empty(); if !mime_fields.is_null() { content = mailmime_content_new_with_str(type_0); if !content.is_null() { mp = mailmime_new_empty(content, mime_fields); if mp.is_null() { mailmime_content_free(content); } else { return mp; } } mailmime_fields_free(mime_fields); } return 0 as *mut mailmime; } pub unsafe fn mailmime_content_new_with_str(mut str: *const libc::c_char) -> *mut mailmime_content { let mut r: libc::c_int = 0; let mut cur_token: size_t = 0; let mut content: *mut mailmime_content = 0 as *mut mailmime_content; cur_token = 0i32 as size_t; r = mailmime_content_parse(str, strlen(str), &mut cur_token, &mut content); if r != MAILIMF_NO_ERROR as libc::c_int { return 0 as *mut mailmime_content; } return content; } pub unsafe fn mailmime_smart_remove_part(mut mime: *mut mailmime) -> libc::c_int { let mut parent: *mut mailmime = 0 as *mut mailmime; let mut res: libc::c_int = 0; parent = (*mime).mm_parent; if parent.is_null() { res = MAILIMF_ERROR_INVAL as libc::c_int } else { match (*mime).mm_type { 3 => { if !(*mime).mm_data.mm_message.mm_msg_mime.is_null() { res = MAILIMF_ERROR_INVAL as libc::c_int } else { mailmime_remove_part(mime); mailmime_free(mime); return MAILIMF_NO_ERROR as libc::c_int; } } 2 => { if !((*(*mime).mm_data.mm_multipart.mm_mp_list).first == (*(*mime).mm_data.mm_multipart.mm_mp_list).last && (*(*mime).mm_data.mm_multipart.mm_mp_list).last.is_null()) { res = MAILIMF_ERROR_INVAL as libc::c_int } else { mailmime_remove_part(mime); mailmime_free(mime); return MAILIMF_NO_ERROR as libc::c_int; } } 1 => { mailmime_remove_part(mime); mailmime_free(mime); return MAILIMF_NO_ERROR as libc::c_int; } _ => return MAILIMF_ERROR_INVAL as libc::c_int, } } return res; } pub unsafe fn mailmime_fields_new_encoding(mut type_0: libc::c_int) -> *mut mailmime_fields { let mut encoding: *mut mailmime_mechanism = 0 as *mut mailmime_mechanism; let mut mime_fields: *mut mailmime_fields = 0 as *mut mailmime_fields; encoding = mailmime_mechanism_new(type_0, 0 as *mut libc::c_char); if !encoding.is_null() { mime_fields = mailmime_fields_new_with_data( encoding, 0 as *mut libc::c_char, 0 as *mut libc::c_char, 0 as *mut mailmime_disposition, 0 as *mut mailmime_language, ); if mime_fields.is_null() { mailmime_mechanism_free(encoding); } else { return mime_fields; } } return 0 as *mut mailmime_fields; } pub unsafe fn mailmime_fields_new_filename( mut dsp_type: libc::c_int, mut filename: *mut libc::c_char, mut encoding_type: libc::c_int, ) -> *mut mailmime_fields { let mut dsp: *mut mailmime_disposition = 0 as *mut mailmime_disposition; let mut encoding: *mut mailmime_mechanism = 0 as *mut mailmime_mechanism; let mut mime_fields: *mut mailmime_fields = 0 as *mut mailmime_fields; dsp = mailmime_disposition_new_with_data( dsp_type, filename, 0 as *mut libc::c_char, 0 as *mut libc::c_char, 0 as *mut libc::c_char, -1i32 as size_t, ); if !dsp.is_null() { encoding = mailmime_mechanism_new(encoding_type, 0 as *mut libc::c_char); if !encoding.is_null() { mime_fields = mailmime_fields_new_with_data( encoding, 0 as *mut libc::c_char, 0 as *mut libc::c_char, dsp, 0 as *mut mailmime_language, ); if mime_fields.is_null() { mailmime_encoding_free(encoding); } else { return mime_fields; } } mailmime_disposition_free(dsp); } return 0 as *mut mailmime_fields; } pub unsafe fn mailmime_param_new_with_data( mut name: *mut libc::c_char, mut value: *mut libc::c_char, ) -> *mut mailmime_parameter { let mut param_name: *mut libc::c_char = 0 as *mut libc::c_char; let mut param_value: *mut libc::c_char = 0 as *mut libc::c_char; let mut param: *mut mailmime_parameter = 0 as *mut mailmime_parameter; param_name = strdup(name); if !param_name.is_null() { param_value = strdup(value); if !param_value.is_null() { param = mailmime_parameter_new(param_name, param_value); if param.is_null() { free(param_value as *mut libc::c_void); } else { return param; } } free(param_name as *mut libc::c_void); } return 0 as *mut mailmime_parameter; }
use std::any::Any; use super::CrossoverStep; use crate::{DefaultMutator, Mutator, CROSSOVER_RATE}; /// Default mutator of `Box<T>` #[derive(Default)] pub struct BoxMutator<M> { mutator: M, rng: fastrand::Rng, } impl<M> BoxMutator<M> { #[no_coverage] pub fn new(mutator: M) -> Self { Self { mutator, rng: fastrand::Rng::new(), } } } #[derive(Clone)] pub struct MutationStep<T, MS> { crossover_step: CrossoverStep<T>, inner: MS, } pub enum UnmutateToken<T, U> { Replace(T), Inner(U), } impl<T: Clone + 'static, M: Mutator<T>> Mutator<Box<T>> for BoxMutator<M> { #[doc(hidden)] type Cache = M::Cache; #[doc(hidden)] type MutationStep = MutationStep<T, M::MutationStep>; #[doc(hidden)] type ArbitraryStep = M::ArbitraryStep; #[doc(hidden)] type UnmutateToken = UnmutateToken<T, M::UnmutateToken>; #[doc(hidden)] #[no_coverage] fn initialize(&self) { self.mutator.initialize(); } #[doc(hidden)] #[no_coverage] fn default_arbitrary_step(&self) -> Self::ArbitraryStep { self.mutator.default_arbitrary_step() } #[doc(hidden)] #[no_coverage] fn is_valid(&self, value: &Box<T>) -> bool { self.mutator.is_valid(value) } #[doc(hidden)] #[no_coverage] fn validate_value(&self, value: &Box<T>) -> Option<Self::Cache> { self.mutator.validate_value(value) } #[doc(hidden)] #[no_coverage] fn default_mutation_step(&self, value: &Box<T>, cache: &Self::Cache) -> Self::MutationStep { MutationStep { crossover_step: CrossoverStep::default(), inner: self.mutator.default_mutation_step(value, cache), } } #[doc(hidden)] #[no_coverage] fn global_search_space_complexity(&self) -> f64 { self.mutator.global_search_space_complexity() } #[doc(hidden)] #[no_coverage] fn max_complexity(&self) -> f64 { self.mutator.max_complexity() } #[doc(hidden)] #[no_coverage] fn min_complexity(&self) -> f64 { self.mutator.min_complexity() } #[doc(hidden)] #[no_coverage] fn complexity(&self, value: &Box<T>, cache: &Self::Cache) -> f64 { self.mutator.complexity(value, cache) } #[doc(hidden)] #[no_coverage] fn ordered_arbitrary(&self, step: &mut Self::ArbitraryStep, max_cplx: f64) -> Option<(Box<T>, f64)> { if let Some((value, cache)) = self.mutator.ordered_arbitrary(step, max_cplx) { Some((Box::new(value), cache)) } else { None } } #[doc(hidden)] #[no_coverage] fn random_arbitrary(&self, max_cplx: f64) -> (Box<T>, f64) { let (value, cache) = self.mutator.random_arbitrary(max_cplx); (Box::new(value), cache) } #[doc(hidden)] #[no_coverage] fn ordered_mutate( &self, value: &mut Box<T>, cache: &mut Self::Cache, step: &mut Self::MutationStep, subvalue_provider: &dyn crate::SubValueProvider, max_cplx: f64, ) -> Option<(Self::UnmutateToken, f64)> { if self.rng.u8(..CROSSOVER_RATE) == 0 && let Some((subvalue, subcplx)) = step.crossover_step.get_next_subvalue(subvalue_provider, max_cplx) && self.mutator.is_valid(subvalue) { let mut replacer = subvalue.clone(); std::mem::swap(value.as_mut(), &mut replacer); return Some((UnmutateToken::Replace(replacer), subcplx)); } if let Some((t, cplx)) = self .mutator .ordered_mutate(value, cache, &mut step.inner, subvalue_provider, max_cplx) { Some((UnmutateToken::Inner(t), cplx)) } else { None } } #[doc(hidden)] #[no_coverage] fn random_mutate(&self, value: &mut Box<T>, cache: &mut Self::Cache, max_cplx: f64) -> (Self::UnmutateToken, f64) { let (t, cplx) = self.mutator.random_mutate(value, cache, max_cplx); (UnmutateToken::Inner(t), cplx) } #[doc(hidden)] #[no_coverage] fn unmutate(&self, value: &mut Box<T>, cache: &mut Self::Cache, t: Self::UnmutateToken) { match t { UnmutateToken::Replace(x) => **value = x, UnmutateToken::Inner(t) => self.mutator.unmutate(value, cache, t), } } #[doc(hidden)] #[no_coverage] fn visit_subvalues<'a>(&self, value: &'a Box<T>, cache: &'a Self::Cache, visit: &mut dyn FnMut(&'a dyn Any, f64)) { self.mutator.visit_subvalues(value, cache, visit) } } impl<T> DefaultMutator for Box<T> where T: DefaultMutator + 'static, { #[doc(hidden)] type Mutator = BoxMutator<<T as DefaultMutator>::Mutator>; #[doc(hidden)] #[no_coverage] fn default_mutator() -> Self::Mutator { Self::Mutator::new(T::default_mutator()) } }
use procon_reader::ProconReader; fn main() { let stdin = std::io::stdin(); let mut rd = ProconReader::new(stdin.lock()); let s: Vec<char> = rd.get_chars(); let n = s.len(); if n == 1 { println!("1"); return; } let mo: u64 = 1_000_000_000 + 7; let mut dp = vec![0; n]; dp[0] = 1; if s[0] != s[1] { dp[1] = 1; } for i in 2..n { if let Some(j) = (0..i).rev().find(|&j| s[j] == s[i]) { for k in j.saturating_sub(1)..=(i - 2) { dp[i] += dp[k]; dp[i] %= mo; } } else { dp[i] = 1; for k in 0..=(i - 2) { dp[i] += dp[k]; dp[i] %= mo; } } } let mut ans = 0; for dp in dp { ans += dp; ans %= mo; } println!("{}", ans); }
trait Train { fn get_name(&self) -> String; fn clone(&self) -> Box<Train>; } struct TrainProto { name: String, } struct OtherProto { name: String, } impl Train for TrainProto { fn get_name(&self) -> String { self.name.clone() } fn clone(&self) -> Box<Train> { Box::new(TrainProto { name: self.name.clone() }) } } impl Train for OtherProto { fn get_name(&self) -> String { self.name.clone() } fn clone(&self) -> Box<Train> { Box::new(TrainProto { name: self.name.clone() }) } } pub fn run() { println!("-------------------- {} --------------------", file!()); let protos: Vec<Box<Train>> = vec![ Box::new(TrainProto { name: "Military train".to_string() }), Box::new(TrainProto { name: "Civilian train".to_string() }), Box::new(OtherProto { name: "Other kind of train".to_string() }) ]; let mut clones: Vec<Box<Train>> = Vec::new(); for p in protos { let t = p.clone(); clones.push(t); println!("proto addr: {:p} ", Box::into_raw(p) as *const TrainProto); } for t in clones { println!("clone plyd: {}", t.get_name()); println!("clone addr: {:p}", Box::into_raw(t) as *const TrainProto); } }
//! Types for handling information about C++ library APIs. use crate::cpp_function::CppFunction; pub use crate::cpp_operator::CppOperator; use crate::cpp_type::{CppTemplateParameter, CppType}; use crate::database::DatabaseClient; use itertools::Itertools; use ritual_common::errors::{bail, ensure, Error, Result}; use ritual_common::utils::MapIfOk; use serde_derive::{Deserialize, Serialize}; use std::fmt; use std::str::FromStr; /// One item of a C++ enum declaration #[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize)] pub struct CppEnumValue { /// Full path containing enum path and variant name. pub path: CppPath, /// Corresponding value pub value: i64, } impl CppEnumValue { pub fn is_same(&self, other: &CppEnumValue) -> bool { self.path == other.path && self.value == other.value } pub fn unscoped_path(&self) -> CppPath { let mut name = self.path.clone(); if name.items.len() < 2 { panic!("enum path is too short: {:?}", name); } name.items.remove(name.items.len() - 2); name } } #[test] fn unscoped_path_should_work() { fn check(path: &str, result: &str) { let v = CppEnumValue { path: CppPath::from_good_str(path), value: 0, }; assert_eq!(v.unscoped_path(), CppPath::from_good_str(result)); } check("A::B::C::D", "A::B::D"); check("A::B", "B"); } /// Member field of a C++ class declaration #[derive(Debug, PartialEq, Eq, Clone, Hash, Serialize, Deserialize)] pub struct CppClassField { pub path: CppPath, /// Field type pub field_type: CppType, /// Visibility pub visibility: CppVisibility, pub is_static: bool, } impl CppClassField { pub fn is_same(&self, other: &CppClassField) -> bool { self.path == other.path && self.field_type == other.field_type && self.visibility == other.visibility && self.is_static == other.is_static } pub fn short_text(&self) -> String { let visibility_text = match self.visibility { CppVisibility::Public => "", CppVisibility::Protected => "protected ", CppVisibility::Private => "private ", }; format!( "{}{} {}", visibility_text, self.field_type.to_cpp_pseudo_code(), self.path.to_cpp_pseudo_code(), ) } } /// Item of base class list in a class declaration #[derive(Debug, PartialEq, Eq, Clone, Hash, Serialize, Deserialize)] pub struct CppBaseSpecifier { /// Base class type (can include template arguments) pub base_class_type: CppPath, /// Index of this base (for classes that have multiple base classes) pub base_index: usize, /// True if this base is virtual pub is_virtual: bool, /// Base visibility (public, protected or private) pub visibility: CppVisibility, /// Name and template arguments of the class type that /// inherits this base class pub derived_class_type: CppPath, } /// Location of a C++ type's definition in header files. #[derive(Debug, PartialEq, Eq, Clone, Hash, Serialize, Deserialize)] pub struct CppOriginLocation { // Full path to the include file pub include_file_path: String, /// Line of the file pub line: u32, /// Column of the file pub column: u32, } /// Visibility of a C++ entity. Defaults to `Public` /// for entities that can't have visibility (like free functions) #[derive(Debug, PartialEq, Eq, Clone, Hash, Serialize, Deserialize)] pub enum CppVisibility { Public, Protected, Private, } #[derive(PartialEq, Eq, Clone, Hash, Serialize, Deserialize)] pub struct CppPathItem { pub name: String, pub template_arguments: Option<Vec<CppType>>, } #[derive(Debug, PartialEq, Eq, Clone, Hash, Serialize, Deserialize)] pub struct CppPath { /// Parts of the path items: Vec<CppPathItem>, } impl CppPath { pub fn from_good_str(path: &str) -> Self { CppPath::from_str(path).unwrap() } pub fn from_item(item: CppPathItem) -> Self { CppPath { items: vec![item] } } pub fn from_items(items: Vec<CppPathItem>) -> Self { CppPath { items } } pub fn into_items(self) -> Vec<CppPathItem> { self.items } pub fn items(&self) -> &[CppPathItem] { &self.items } pub fn to_cpp_code(&self) -> Result<String> { Ok(self .items .iter() .map_if_ok(CppPathItem::to_cpp_code)? .join("::")) } pub fn to_cpp_pseudo_code(&self) -> String { self.items .iter() .map(CppPathItem::to_cpp_pseudo_code) .join("::") } pub fn join(&self, item: CppPathItem) -> CppPath { let mut result = self.clone(); result.items.push(item); result } pub fn last(&self) -> &CppPathItem { self.items.last().expect("empty CppPath encountered") } pub fn last_mut(&mut self) -> &mut CppPathItem { self.items.last_mut().expect("empty CppPath encountered") } pub fn has_parent(&self) -> bool { self.items.len() > 1 } pub fn parent(&self) -> Result<CppPath> { if self.items.len() > 1 { Ok(CppPath { items: self.items[..self.items.len() - 1].to_vec(), }) } else { bail!("failed to get parent path for {:?}", self) } } pub fn parent_parts(&self) -> Result<&[CppPathItem]> { if self.items.len() > 1 { Ok(&self.items[..self.items.len() - 1]) } else { bail!("failed to get parent path for {:?}", self) } } pub fn ascii_caption(&self) -> String { self.items .iter() .map(|item| { let name: String = item .name .chars() .map(|c| { if c == '~' { 'd' } else if !c.is_digit(36) && c != '_' { '_' } else { c } }) .collect(); if let Some(args) = &item.template_arguments { format!( "{}_{}", name, args.iter().map(CppType::ascii_caption).join("_") ) } else { name } }) .join("_") } /// Returns the identifier this method would be presented with /// in Qt documentation. pub fn doc_id(&self) -> String { self.to_templateless_string() } pub fn to_templateless_string(&self) -> String { self.items().iter().map(|item| &item.name).join("::") } /// Attempts to replace template types at `nested_level1` /// within this type with `template_arguments1`. pub fn instantiate( &self, nested_level1: usize, template_arguments1: &[CppType], ) -> Result<CppPath> { let mut new_path = self.clone(); for path_item in &mut new_path.items { if let Some(template_arguments) = &mut path_item.template_arguments { for arg in template_arguments { *arg = arg.instantiate(nested_level1, template_arguments1)?; } } } Ok(new_path) } pub fn deinstantiate(&self) -> CppPath { let mut path = self.clone(); let mut nested_level = 0; for item in &mut path.items { if let Some(args) = &mut item.template_arguments { *args = (0..args.len()) .map(|index| { CppType::TemplateParameter(CppTemplateParameter { nested_level, index, name: format!("T{}_{}", nested_level, index), }) }) .collect(); nested_level += 1; } } path } } impl FromStr for CppPath { type Err = Error; fn from_str(path: &str) -> Result<Self> { if path.contains('<') || path.contains('>') { bail!("attempted to add template arguments to CppPath"); } if path.is_empty() { bail!("attempted to construct an empty CppPath"); } let items = path .split("::") .map(|item| CppPathItem { name: item.into(), template_arguments: None, }) .collect(); Ok(CppPath { items }) } } impl CppPathItem { pub fn to_cpp_code(&self) -> Result<String> { let args = match &self.template_arguments { None => "".to_string(), Some(args) => format!( "< {} >", args.map_if_ok(|arg| arg.to_cpp_code(None))?.join(", ") ), }; Ok(format!("{}{}", self.name, args)) } pub fn to_cpp_pseudo_code(&self) -> String { let args = match &self.template_arguments { None => "".to_string(), Some(args) => format!( "<{}>", args.iter().map(CppType::to_cpp_pseudo_code).join(", ") ), }; format!("{}{}", self.name, args) } pub fn from_good_str(name: &str) -> Self { Self::from_str(name).unwrap() } } impl FromStr for CppPathItem { type Err = Error; fn from_str(name: &str) -> Result<CppPathItem> { ensure!( !name.contains('<'), "attempted to construct CppPathItem containing template arguments" ); ensure!( !name.contains('>'), "attempted to construct CppPathItem containing template arguments" ); ensure!(!name.is_empty(), "attempted to construct empty CppPathItem"); Ok(CppPathItem { name: name.into(), template_arguments: None, }) } } impl fmt::Debug for CppPathItem { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> std::result::Result<(), fmt::Error> { write!(f, "{:?}", self.name)?; if let Some(args) = &self.template_arguments { write!( f, "<{}>", args.iter().map(|arg| format!("{:?}", arg)).join(", ") )?; } Ok(()) } } /// Information about a C++ type declaration #[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize, Hash)] pub enum CppTypeDeclarationKind { Enum, Class, } /// Information about a C++ type declaration #[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize, Hash)] pub struct CppTypeDeclaration { /// Identifier, including namespaces and nested classes pub path: CppPath, pub kind: CppTypeDeclarationKind, } impl CppTypeDeclaration { pub fn is_same(&self, other: &CppTypeDeclaration) -> bool { self.path == other.path } } impl CppTypeDeclarationKind { /// Checks if the type is a class type. pub fn is_class(&self) -> bool { matches!(self, CppTypeDeclarationKind::Class { .. }) } pub fn is_enum(&self) -> bool { matches!(self, CppTypeDeclarationKind::Enum) } } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct CppNamespace { pub path: CppPath, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[allow(clippy::large_enum_variant)] pub enum CppItem { Namespace(CppNamespace), Type(CppTypeDeclaration), EnumValue(CppEnumValue), Function(CppFunction), ClassField(CppClassField), ClassBase(CppBaseSpecifier), } impl CppItem { pub fn is_same(&self, other: &CppItem) -> bool { use self::CppItem::*; match self { Namespace(v) => { if let Namespace(v2) = &other { v == v2 } else { false } } Type(v) => { if let Type(v2) = &other { v.is_same(v2) } else { false } } EnumValue(v) => { if let EnumValue(v2) = &other { v.is_same(v2) } else { false } } Function(v) => { if let Function(v2) = &other { v.is_same(v2) } else { false } } ClassField(v) => { if let ClassField(v2) = &other { v.is_same(v2) } else { false } } ClassBase(v) => { if let ClassBase(v2) = &other { v == v2 } else { false } } } } pub fn path(&self) -> Option<&CppPath> { let path = match self { CppItem::Namespace(data) => &data.path, CppItem::Type(data) => &data.path, CppItem::EnumValue(data) => &data.path, CppItem::Function(data) => &data.path, CppItem::ClassField(data) => &data.path, CppItem::ClassBase(_) => return None, }; Some(path) } pub fn all_involved_types(&self) -> Vec<CppType> { match self { CppItem::Type(t) => match t.kind { CppTypeDeclarationKind::Enum => vec![CppType::Enum { path: t.path.clone(), }], CppTypeDeclarationKind::Class { .. } => vec![CppType::Class(t.path.clone())], }, CppItem::EnumValue(enum_value) => vec![CppType::Enum { path: enum_value .path .parent() .expect("enum value must have parent path"), }], CppItem::Namespace(_) => Vec::new(), CppItem::Function(function) => function.all_involved_types(), CppItem::ClassField(field) => { let class_type = CppType::Class(field.path.parent().expect("field path must have parent")); vec![class_type, field.field_type.clone()] } CppItem::ClassBase(base) => vec![ CppType::Class(base.base_class_type.clone()), CppType::Class(base.derived_class_type.clone()), ], } } pub fn as_namespace_ref(&self) -> Option<&CppNamespace> { if let CppItem::Namespace(data) = self { Some(data) } else { None } } pub fn as_function_ref(&self) -> Option<&CppFunction> { if let CppItem::Function(data) = self { Some(data) } else { None } } pub fn as_field_ref(&self) -> Option<&CppClassField> { if let CppItem::ClassField(data) = self { Some(data) } else { None } } pub fn as_enum_value_ref(&self) -> Option<&CppEnumValue> { if let CppItem::EnumValue(data) = self { Some(data) } else { None } } pub fn as_base_ref(&self) -> Option<&CppBaseSpecifier> { if let CppItem::ClassBase(data) = self { Some(data) } else { None } } pub fn as_type_ref(&self) -> Option<&CppTypeDeclaration> { if let CppItem::Type(data) = self { Some(data) } else { None } } pub fn as_type_mut(&mut self) -> Option<&mut CppTypeDeclaration> { if let CppItem::Type(data) = self { Some(data) } else { None } } pub fn short_text(&self) -> String { match self { CppItem::Namespace(value) => format!("namespace {}", value.path.to_cpp_pseudo_code()), CppItem::Type(value) => format!("type {}", value.path.to_cpp_pseudo_code()), CppItem::EnumValue(value) => format!("enum value {}", value.path.to_cpp_pseudo_code()), CppItem::Function(value) => value.short_text(), CppItem::ClassField(value) => value.short_text(), CppItem::ClassBase(_) => format!("{:?}", self), } } } impl fmt::Display for CppItem { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let s = match self { CppItem::Namespace(namespace) => { format!("namespace {}", namespace.path.to_cpp_pseudo_code()) } CppItem::Type(type1) => match type1.kind { CppTypeDeclarationKind::Enum => format!("enum {}", type1.path.to_cpp_pseudo_code()), CppTypeDeclarationKind::Class { .. } => { format!("class {}", type1.path.to_cpp_pseudo_code()) } }, CppItem::Function(method) => method.short_text(), CppItem::EnumValue(value) => format!( "enum value {} = {}", value.path.to_cpp_pseudo_code(), value.value ), CppItem::ClassField(field) => field.short_text(), CppItem::ClassBase(class_base) => { let virtual_text = if class_base.is_virtual { "virtual " } else { "" }; let visibility_text = match class_base.visibility { CppVisibility::Public => "public", CppVisibility::Protected => "protected", CppVisibility::Private => "private", }; let index_text = if class_base.base_index > 0 { format!(" (index: {}", class_base.base_index) } else { String::new() }; format!( "class {} : {}{} {}{}", class_base.derived_class_type.to_cpp_pseudo_code(), virtual_text, visibility_text, class_base.base_class_type.to_cpp_pseudo_code(), index_text ) } }; f.write_str(&s) } } /// Checks if `class_name` types inherits `base_name` type directly or indirectly. pub fn inherits( db: &DatabaseClient, derived_class_name: &CppPath, base_class_name: &CppPath, ) -> bool { if derived_class_name == base_class_name { return true; } for item in db.all_cpp_items() { if let CppItem::ClassBase(base_data) = &item.item { if &base_data.derived_class_type == derived_class_name && inherits(db, &base_data.base_class_type, base_class_name) { return true; } } } false }
use super::{ PositionIterInternal, PyDictRef, PyIntRef, PyStrRef, PyTuple, PyTupleRef, PyType, PyTypeRef, }; use crate::{ anystr::{self, AnyStr}, atomic_func, bytesinner::{ bytes_decode, ByteInnerFindOptions, ByteInnerNewOptions, ByteInnerPaddingOptions, ByteInnerSplitOptions, ByteInnerTranslateOptions, DecodeArgs, PyBytesInner, }, class::PyClassImpl, common::{hash::PyHash, lock::PyMutex}, convert::{ToPyObject, ToPyResult}, function::{ ArgBytesLike, ArgIndex, ArgIterable, Either, OptionalArg, OptionalOption, PyComparisonValue, }, protocol::{ BufferDescriptor, BufferMethods, PyBuffer, PyIterReturn, PyMappingMethods, PyNumberMethods, PySequenceMethods, }, sliceable::{SequenceIndex, SliceableSequenceOp}, types::{ AsBuffer, AsMapping, AsNumber, AsSequence, Callable, Comparable, Constructor, Hashable, IterNext, Iterable, PyComparisonOp, Representable, SelfIter, Unconstructible, }, AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, TryFromBorrowedObject, TryFromObject, VirtualMachine, }; use bstr::ByteSlice; use once_cell::sync::Lazy; use std::{mem::size_of, ops::Deref}; #[pyclass(module = false, name = "bytes")] #[derive(Clone, Debug)] pub struct PyBytes { inner: PyBytesInner, } pub type PyBytesRef = PyRef<PyBytes>; impl From<Vec<u8>> for PyBytes { fn from(elements: Vec<u8>) -> Self { Self { inner: PyBytesInner { elements }, } } } impl From<PyBytesInner> for PyBytes { fn from(inner: PyBytesInner) -> Self { Self { inner } } } impl ToPyObject for Vec<u8> { fn to_pyobject(self, vm: &VirtualMachine) -> PyObjectRef { vm.ctx.new_bytes(self).into() } } impl Deref for PyBytes { type Target = [u8]; fn deref(&self) -> &[u8] { self.as_bytes() } } impl AsRef<[u8]> for PyBytes { fn as_ref(&self) -> &[u8] { self.as_bytes() } } impl AsRef<[u8]> for PyBytesRef { fn as_ref(&self) -> &[u8] { self.as_bytes() } } impl PyPayload for PyBytes { fn class(ctx: &Context) -> &'static Py<PyType> { ctx.types.bytes_type } } pub(crate) fn init(context: &Context) { PyBytes::extend_class(context, context.types.bytes_type); PyBytesIterator::extend_class(context, context.types.bytes_iterator_type); } impl Constructor for PyBytes { type Args = ByteInnerNewOptions; fn py_new(cls: PyTypeRef, options: Self::Args, vm: &VirtualMachine) -> PyResult { options.get_bytes(cls, vm).to_pyresult(vm) } } impl PyBytes { pub fn new_ref(data: Vec<u8>, ctx: &Context) -> PyRef<Self> { PyRef::new_ref(Self::from(data), ctx.types.bytes_type.to_owned(), None) } fn _getitem(&self, needle: &PyObject, vm: &VirtualMachine) -> PyResult { match SequenceIndex::try_from_borrowed_object(vm, needle, "byte")? { SequenceIndex::Int(i) => self .getitem_by_index(vm, i) .map(|x| vm.ctx.new_int(x).into()), SequenceIndex::Slice(slice) => self .getitem_by_slice(vm, slice) .map(|x| vm.ctx.new_bytes(x).into()), } } } impl PyRef<PyBytes> { fn repeat(self, count: isize, vm: &VirtualMachine) -> PyResult<PyRef<PyBytes>> { if count == 1 && self.class().is(vm.ctx.types.bytes_type) { // Special case: when some `bytes` is multiplied by `1`, // nothing really happens, we need to return an object itself // with the same `id()` to be compatible with CPython. // This only works for `bytes` itself, not its subclasses. return Ok(self); } self.inner .mul(count, vm) .map(|x| PyBytes::from(x).into_ref(&vm.ctx)) } } #[pyclass( flags(BASETYPE), with( Py, PyRef, AsMapping, AsSequence, Hashable, Comparable, AsBuffer, Iterable, Constructor, AsNumber, Representable, ) )] impl PyBytes { #[pymethod(magic)] #[inline] pub fn len(&self) -> usize { self.inner.len() } #[inline] pub fn is_empty(&self) -> bool { self.inner.is_empty() } #[inline] pub fn as_bytes(&self) -> &[u8] { self.inner.as_bytes() } #[pymethod(magic)] fn sizeof(&self) -> usize { size_of::<Self>() + self.len() * size_of::<u8>() } #[pymethod(magic)] fn add(&self, other: ArgBytesLike) -> Vec<u8> { self.inner.add(&other.borrow_buf()) } #[pymethod(magic)] fn contains( &self, needle: Either<PyBytesInner, PyIntRef>, vm: &VirtualMachine, ) -> PyResult<bool> { self.inner.contains(needle, vm) } #[pystaticmethod] fn maketrans(from: PyBytesInner, to: PyBytesInner, vm: &VirtualMachine) -> PyResult<Vec<u8>> { PyBytesInner::maketrans(from, to, vm) } #[pymethod(magic)] fn getitem(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult { self._getitem(&needle, vm) } #[pymethod] fn isalnum(&self) -> bool { self.inner.isalnum() } #[pymethod] fn isalpha(&self) -> bool { self.inner.isalpha() } #[pymethod] fn isascii(&self) -> bool { self.inner.isascii() } #[pymethod] fn isdigit(&self) -> bool { self.inner.isdigit() } #[pymethod] fn islower(&self) -> bool { self.inner.islower() } #[pymethod] fn isspace(&self) -> bool { self.inner.isspace() } #[pymethod] fn isupper(&self) -> bool { self.inner.isupper() } #[pymethod] fn istitle(&self) -> bool { self.inner.istitle() } #[pymethod] fn lower(&self) -> Self { self.inner.lower().into() } #[pymethod] fn upper(&self) -> Self { self.inner.upper().into() } #[pymethod] fn capitalize(&self) -> Self { self.inner.capitalize().into() } #[pymethod] fn swapcase(&self) -> Self { self.inner.swapcase().into() } #[pymethod] pub(crate) fn hex( &self, sep: OptionalArg<Either<PyStrRef, PyBytesRef>>, bytes_per_sep: OptionalArg<isize>, vm: &VirtualMachine, ) -> PyResult<String> { self.inner.hex(sep, bytes_per_sep, vm) } #[pyclassmethod] fn fromhex(cls: PyTypeRef, string: PyStrRef, vm: &VirtualMachine) -> PyResult { let bytes = PyBytesInner::fromhex(string.as_str(), vm)?; let bytes = vm.ctx.new_bytes(bytes).into(); PyType::call(&cls, vec![bytes].into(), vm) } #[pymethod] fn center(&self, options: ByteInnerPaddingOptions, vm: &VirtualMachine) -> PyResult<PyBytes> { Ok(self.inner.center(options, vm)?.into()) } #[pymethod] fn ljust(&self, options: ByteInnerPaddingOptions, vm: &VirtualMachine) -> PyResult<PyBytes> { Ok(self.inner.ljust(options, vm)?.into()) } #[pymethod] fn rjust(&self, options: ByteInnerPaddingOptions, vm: &VirtualMachine) -> PyResult<PyBytes> { Ok(self.inner.rjust(options, vm)?.into()) } #[pymethod] fn count(&self, options: ByteInnerFindOptions, vm: &VirtualMachine) -> PyResult<usize> { self.inner.count(options, vm) } #[pymethod] fn join(&self, iter: ArgIterable<PyBytesInner>, vm: &VirtualMachine) -> PyResult<PyBytes> { Ok(self.inner.join(iter, vm)?.into()) } #[pymethod] fn endswith(&self, options: anystr::StartsEndsWithArgs, vm: &VirtualMachine) -> PyResult<bool> { let (affix, substr) = match options.prepare(self.as_bytes(), self.len(), |s, r| s.get_bytes(r)) { Some(x) => x, None => return Ok(false), }; substr.py_startsendswith( &affix, "endswith", "bytes", |s, x: PyBytesInner| s.ends_with(x.as_bytes()), vm, ) } #[pymethod] fn startswith( &self, options: anystr::StartsEndsWithArgs, vm: &VirtualMachine, ) -> PyResult<bool> { let (affix, substr) = match options.prepare(self.as_bytes(), self.len(), |s, r| s.get_bytes(r)) { Some(x) => x, None => return Ok(false), }; substr.py_startsendswith( &affix, "startswith", "bytes", |s, x: PyBytesInner| s.starts_with(x.as_bytes()), vm, ) } #[pymethod] fn find(&self, options: ByteInnerFindOptions, vm: &VirtualMachine) -> PyResult<isize> { let index = self.inner.find(options, |h, n| h.find(n), vm)?; Ok(index.map_or(-1, |v| v as isize)) } #[pymethod] fn index(&self, options: ByteInnerFindOptions, vm: &VirtualMachine) -> PyResult<usize> { let index = self.inner.find(options, |h, n| h.find(n), vm)?; index.ok_or_else(|| vm.new_value_error("substring not found".to_owned())) } #[pymethod] fn rfind(&self, options: ByteInnerFindOptions, vm: &VirtualMachine) -> PyResult<isize> { let index = self.inner.find(options, |h, n| h.rfind(n), vm)?; Ok(index.map_or(-1, |v| v as isize)) } #[pymethod] fn rindex(&self, options: ByteInnerFindOptions, vm: &VirtualMachine) -> PyResult<usize> { let index = self.inner.find(options, |h, n| h.rfind(n), vm)?; index.ok_or_else(|| vm.new_value_error("substring not found".to_owned())) } #[pymethod] fn translate( &self, options: ByteInnerTranslateOptions, vm: &VirtualMachine, ) -> PyResult<PyBytes> { Ok(self.inner.translate(options, vm)?.into()) } #[pymethod] fn strip(&self, chars: OptionalOption<PyBytesInner>) -> Self { self.inner.strip(chars).into() } #[pymethod] fn removeprefix(&self, prefix: PyBytesInner) -> Self { self.inner.removeprefix(prefix).into() } #[pymethod] fn removesuffix(&self, suffix: PyBytesInner) -> Self { self.inner.removesuffix(suffix).into() } #[pymethod] fn split( &self, options: ByteInnerSplitOptions, vm: &VirtualMachine, ) -> PyResult<Vec<PyObjectRef>> { self.inner .split(options, |s, vm| vm.ctx.new_bytes(s.to_vec()).into(), vm) } #[pymethod] fn rsplit( &self, options: ByteInnerSplitOptions, vm: &VirtualMachine, ) -> PyResult<Vec<PyObjectRef>> { self.inner .rsplit(options, |s, vm| vm.ctx.new_bytes(s.to_vec()).into(), vm) } #[pymethod] fn partition(&self, sep: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyTupleRef> { let sub = PyBytesInner::try_from_borrowed_object(vm, &sep)?; let (front, has_mid, back) = self.inner.partition(&sub, vm)?; Ok(vm.new_tuple(( vm.ctx.new_bytes(front), if has_mid { sep } else { vm.ctx.new_bytes(Vec::new()).into() }, vm.ctx.new_bytes(back), ))) } #[pymethod] fn rpartition(&self, sep: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyTupleRef> { let sub = PyBytesInner::try_from_borrowed_object(vm, &sep)?; let (back, has_mid, front) = self.inner.rpartition(&sub, vm)?; Ok(vm.new_tuple(( vm.ctx.new_bytes(front), if has_mid { sep } else { vm.ctx.new_bytes(Vec::new()).into() }, vm.ctx.new_bytes(back), ))) } #[pymethod] fn expandtabs(&self, options: anystr::ExpandTabsArgs) -> Self { self.inner.expandtabs(options).into() } #[pymethod] fn splitlines(&self, options: anystr::SplitLinesArgs, vm: &VirtualMachine) -> Vec<PyObjectRef> { self.inner .splitlines(options, |x| vm.ctx.new_bytes(x.to_vec()).into()) } #[pymethod] fn zfill(&self, width: isize) -> Self { self.inner.zfill(width).into() } #[pymethod] fn replace( &self, old: PyBytesInner, new: PyBytesInner, count: OptionalArg<isize>, vm: &VirtualMachine, ) -> PyResult<PyBytes> { Ok(self.inner.replace(old, new, count, vm)?.into()) } #[pymethod] fn title(&self) -> Self { self.inner.title().into() } #[pymethod(name = "__rmul__")] #[pymethod(magic)] fn mul(zelf: PyRef<Self>, value: ArgIndex, vm: &VirtualMachine) -> PyResult<PyRef<Self>> { zelf.repeat(value.try_to_primitive(vm)?, vm) } #[pymethod(name = "__mod__")] fn mod_(&self, values: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyBytes> { let formatted = self.inner.cformat(values, vm)?; Ok(formatted.into()) } #[pymethod(magic)] fn rmod(&self, _values: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef { vm.ctx.not_implemented() } #[pymethod(magic)] fn getnewargs(&self, vm: &VirtualMachine) -> PyTupleRef { let param: Vec<PyObjectRef> = self.elements().map(|x| x.to_pyobject(vm)).collect(); PyTuple::new_ref(param, &vm.ctx) } } #[pyclass] impl Py<PyBytes> { #[pymethod(magic)] fn reduce_ex( &self, _proto: usize, vm: &VirtualMachine, ) -> (PyTypeRef, PyTupleRef, Option<PyDictRef>) { Self::reduce(self, vm) } #[pymethod(magic)] fn reduce(&self, vm: &VirtualMachine) -> (PyTypeRef, PyTupleRef, Option<PyDictRef>) { let bytes = PyBytes::from(self.to_vec()).to_pyobject(vm); ( self.class().to_owned(), PyTuple::new_ref(vec![bytes], &vm.ctx), self.as_object().dict(), ) } } #[pyclass] impl PyRef<PyBytes> { #[pymethod(magic)] fn bytes(self, vm: &VirtualMachine) -> PyRef<PyBytes> { if self.is(vm.ctx.types.bytes_type) { self } else { PyBytes::from(self.inner.clone()).into_ref(&vm.ctx) } } #[pymethod] fn lstrip(self, chars: OptionalOption<PyBytesInner>, vm: &VirtualMachine) -> PyRef<PyBytes> { let stripped = self.inner.lstrip(chars); if stripped == self.as_bytes() { self } else { vm.ctx.new_bytes(stripped.to_vec()) } } #[pymethod] fn rstrip(self, chars: OptionalOption<PyBytesInner>, vm: &VirtualMachine) -> PyRef<PyBytes> { let stripped = self.inner.rstrip(chars); if stripped == self.as_bytes() { self } else { vm.ctx.new_bytes(stripped.to_vec()) } } /// Return a string decoded from the given bytes. /// Default encoding is 'utf-8'. /// Default errors is 'strict', meaning that encoding errors raise a UnicodeError. /// Other possible values are 'ignore', 'replace' /// For a list of possible encodings, /// see https://docs.python.org/3/library/codecs.html#standard-encodings /// currently, only 'utf-8' and 'ascii' emplemented #[pymethod] fn decode(self, args: DecodeArgs, vm: &VirtualMachine) -> PyResult<PyStrRef> { bytes_decode(self.into(), args, vm) } } static BUFFER_METHODS: BufferMethods = BufferMethods { obj_bytes: |buffer| buffer.obj_as::<PyBytes>().as_bytes().into(), obj_bytes_mut: |_| panic!(), release: |_| {}, retain: |_| {}, }; impl AsBuffer for PyBytes { fn as_buffer(zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<PyBuffer> { let buf = PyBuffer::new( zelf.to_owned().into(), BufferDescriptor::simple(zelf.len(), true), &BUFFER_METHODS, ); Ok(buf) } } impl AsMapping for PyBytes { fn as_mapping() -> &'static PyMappingMethods { static AS_MAPPING: Lazy<PyMappingMethods> = Lazy::new(|| PyMappingMethods { length: atomic_func!(|mapping, _vm| Ok(PyBytes::mapping_downcast(mapping).len())), subscript: atomic_func!( |mapping, needle, vm| PyBytes::mapping_downcast(mapping)._getitem(needle, vm) ), ..PyMappingMethods::NOT_IMPLEMENTED }); &AS_MAPPING } } impl AsSequence for PyBytes { fn as_sequence() -> &'static PySequenceMethods { static AS_SEQUENCE: Lazy<PySequenceMethods> = Lazy::new(|| PySequenceMethods { length: atomic_func!(|seq, _vm| Ok(PyBytes::sequence_downcast(seq).len())), concat: atomic_func!(|seq, other, vm| { PyBytes::sequence_downcast(seq) .inner .concat(other, vm) .map(|x| vm.ctx.new_bytes(x).into()) }), repeat: atomic_func!(|seq, n, vm| { let zelf = seq.obj.to_owned().downcast::<PyBytes>().map_err(|_| { vm.new_type_error("bad argument type for built-in operation".to_owned()) })?; zelf.repeat(n, vm).to_pyresult(vm) }), item: atomic_func!(|seq, i, vm| { PyBytes::sequence_downcast(seq) .as_bytes() .getitem_by_index(vm, i) .map(|x| vm.ctx.new_bytes(vec![x]).into()) }), contains: atomic_func!(|seq, other, vm| { let other = <Either<PyBytesInner, PyIntRef>>::try_from_object(vm, other.to_owned())?; PyBytes::sequence_downcast(seq).contains(other, vm) }), ..PySequenceMethods::NOT_IMPLEMENTED }); &AS_SEQUENCE } } impl AsNumber for PyBytes { fn as_number() -> &'static PyNumberMethods { static AS_NUMBER: PyNumberMethods = PyNumberMethods { remainder: Some(|a, b, vm| { if let Some(a) = a.downcast_ref::<PyBytes>() { a.mod_(b.to_owned(), vm).to_pyresult(vm) } else { Ok(vm.ctx.not_implemented()) } }), ..PyNumberMethods::NOT_IMPLEMENTED }; &AS_NUMBER } } impl Hashable for PyBytes { #[inline] fn hash(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyHash> { Ok(zelf.inner.hash(vm)) } } impl Comparable for PyBytes { fn cmp( zelf: &Py<Self>, other: &PyObject, op: PyComparisonOp, vm: &VirtualMachine, ) -> PyResult<PyComparisonValue> { Ok(if let Some(res) = op.identical_optimization(zelf, other) { res.into() } else if other.fast_isinstance(vm.ctx.types.memoryview_type) && op != PyComparisonOp::Eq && op != PyComparisonOp::Ne { return Err(vm.new_type_error(format!( "'{}' not supported between instances of '{}' and '{}'", op.operator_token(), zelf.class().name(), other.class().name() ))); } else { zelf.inner.cmp(other, op, vm) }) } } impl Iterable for PyBytes { fn iter(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyResult { Ok(PyBytesIterator { internal: PyMutex::new(PositionIterInternal::new(zelf, 0)), } .into_pyobject(vm)) } } impl Representable for PyBytes { #[inline] fn repr_str(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<String> { zelf.inner.repr_bytes(vm) } } #[pyclass(module = false, name = "bytes_iterator")] #[derive(Debug)] pub struct PyBytesIterator { internal: PyMutex<PositionIterInternal<PyBytesRef>>, } impl PyPayload for PyBytesIterator { fn class(ctx: &Context) -> &'static Py<PyType> { ctx.types.bytes_iterator_type } } #[pyclass(with(Constructor, IterNext, Iterable))] impl PyBytesIterator { #[pymethod(magic)] fn length_hint(&self) -> usize { self.internal.lock().length_hint(|obj| obj.len()) } #[pymethod(magic)] fn reduce(&self, vm: &VirtualMachine) -> PyTupleRef { self.internal .lock() .builtins_iter_reduce(|x| x.clone().into(), vm) } #[pymethod(magic)] fn setstate(&self, state: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { self.internal .lock() .set_state(state, |obj, pos| pos.min(obj.len()), vm) } } impl Unconstructible for PyBytesIterator {} impl SelfIter for PyBytesIterator {} impl IterNext for PyBytesIterator { fn next(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> { zelf.internal.lock().next(|bytes, pos| { Ok(PyIterReturn::from_result( bytes .as_bytes() .get(pos) .map(|&x| vm.new_pyobj(x)) .ok_or(None), )) }) } } impl<'a> TryFromBorrowedObject<'a> for PyBytes { fn try_from_borrowed_object(vm: &VirtualMachine, obj: &'a PyObject) -> PyResult<Self> { PyBytesInner::try_from_borrowed_object(vm, obj).map(|x| x.into()) } }
use wasm_encoder::{ CodeSection, ExportKind, ExportSection, Function, FunctionSection, Instruction, Module, TypeSection, ValType, }; use std::env; use std::fs::File; use std::io::Write; fn main() -> std::io::Result<()> { let mut module = Module::new(); let mut types = TypeSection::new(); types.function(vec![ValType::I32], vec![ValType::I32]); let mut functions = FunctionSection::new(); functions.function(0); let mut exports = ExportSection::new(); exports.export("sample", ExportKind::Func, 0); let mut codes = CodeSection::new(); let mut sample = Function::new(vec![]); sample.instruction(&Instruction::LocalGet(0)); sample.instruction(&Instruction::I32Const(2)); sample.instruction(&Instruction::I32Mul); sample.instruction(&Instruction::End); codes.function(&sample); module.section(&types); module.section(&functions); module.section(&exports); module.section(&codes); let wasm_b = module.finish(); let file_name = env::args().nth(1).unwrap_or_default(); let mut file = File::create(file_name)?; file.write_all(&wasm_b)?; Ok(()) }
use std::cmp::max; use std::collections::{HashMap, HashSet}; use std::fmt; use std::iter; use super::super::matrix::Matrix; use super::levelset::LevelSet; // ____ _ // | _ \ __ _ _ __ __ _ _ __ ___ ___| |_ ___ _ __ ___ // | |_) / _` | '__/ _` | '_ ` _ \ / _ \ __/ _ \ '__/ __| // | __/ (_| | | | (_| | | | | | | __/ || __/ | \__ \ // |_| \__,_|_| \__,_|_| |_| |_|\___|\__\___|_| |___/ // /// Define wether the matrices should be computed during the precomputing. #[derive(Clone, Copy, Eq, PartialEq)] enum MatrixPolicy { Lazy, Precompute, } #[derive(Clone, Copy, Eq, PartialEq)] enum CleanPolicy { Clean, Skip, } // _ // | |_ _ _ __ ___ _ __ // _ | | | | | '_ ` _ \| '_ \ // | |_| | |_| | | | | | | |_) | // \___/ \__,_|_| |_| |_| .__/ // |_| /// Generic Jump function inside a product DAG. /// /// The DAG will be built layer by layer by specifying the adjacency matrix from /// one level to the next one, an adjancency matrix can specify the structure /// inside of a level, made of 'assignation edges'. The goal of the structure is /// to be able to be able to navigate quickly from the last to the first layer /// by being able to skip any path that do not contain any assignation edges. pub struct Jump { /// Represent levels in the levelset, which will be built on top of one /// another. levelset: LevelSet, /// Last level that was built. last_level: usize, /// Set of vertices that can't be jumped since it has an ingoing /// non-jumpable edge. NOTE: it may only be required to store it for the /// last level. nonjump_vertices: HashSet<(usize, usize)>, /// Keep track of number of jumps to a given vertex. count_ingoing_jumps: HashMap<(usize, usize), usize>, /// Closest level where an assignation is done accessible from any node. jl: HashMap<(usize, usize), usize>, /// Set of levels accessible from any level using `jl`. rlevel: HashMap<usize, HashSet<usize>>, /// Reverse of `rlevel`. rev_rlevel: HashMap<usize, HashSet<usize>>, /// For any pair of level `(i, j)` such that i is in the level `rlevel[j]`, /// `reach[i, j]` is the accessibility matrix of vertices from level i /// to level j. reach: HashMap<(usize, usize), Matrix<bool>>, /// Various computation parametters matrix_policy: MatrixPolicy, clean_policy: CleanPolicy, } impl Jump { pub fn new<T>(initial_level: T, nonjump_adj: &Vec<Vec<usize>>) -> Jump where T: Iterator<Item = usize>, { let mut jump = Jump { levelset: LevelSet::new(), last_level: 0, nonjump_vertices: HashSet::new(), count_ingoing_jumps: HashMap::new(), jl: HashMap::new(), rlevel: HashMap::new(), rev_rlevel: HashMap::new(), reach: HashMap::new(), matrix_policy: MatrixPolicy::Precompute, clean_policy: CleanPolicy::Clean, }; // TODO: implement cleaning without matrices if jump.matrix_policy == MatrixPolicy::Lazy && jump.clean_policy == CleanPolicy::Clean { eprintln!(r"/!\ Can't clean jump levels without precomputed matrices."); jump.clean_policy = CleanPolicy::Skip; } jump.rlevel.insert(0, HashSet::new()); jump.rev_rlevel.insert(0, HashSet::new()); for state in initial_level { jump.levelset.register(state, 0); jump.jl.insert((0, state), 0); if jump.clean_policy == CleanPolicy::Clean { jump.count_ingoing_jumps.insert((0, state), 0); } } // Init first level jump.extend_level(0, nonjump_adj); if jump.clean_policy == CleanPolicy::Clean { for &vertex in jump.levelset.get_level(0).unwrap() { jump.count_ingoing_jumps.insert((0, vertex), 0); } } jump } /// Compute next level given the adjacency list of jumpable edges from /// current level to the next one and adjacency list of non-jumpable /// edges inside the next level. pub fn init_next_level(&mut self, jump_adj: &Vec<Vec<usize>>, nonjump_adj: &Vec<Vec<usize>>) { let nonjump_vertices = &self.nonjump_vertices; let levelset = &mut self.levelset; let jl = &mut self.jl; let last_level = self.last_level; let next_level = self.last_level + 1; // NOTE: this clone is only necessary for the borrow checker. let last_level_vertices = levelset.get_level(last_level).unwrap().clone(); // Register jumpable transitions from this level to the next one for source in last_level_vertices { // Notice that `source_jl` can be None, however, if it is not in // nonjump_vertices it is sure that it is not None since it was // necessary added by following an atomic transition. let source_jl = jl.get(&(last_level, source)).cloned(); for &target in &jump_adj[source] { // Compute the level target will jump to, depending if there is already an // assigned jump level for target or not. let cmpt_jump_level = |previous_jl| { if nonjump_vertices.contains(&(last_level, source)) { last_level } else { match previous_jl { None => source_jl.unwrap(), Some(previous_jl) => max(source_jl.unwrap(), previous_jl), } } }; // Update the jump level in a single hashmap access. jl.entry((next_level, target)) .and_modify(|target_jl| { *target_jl = cmpt_jump_level(Some(*target_jl)); }) .or_insert_with(|| { levelset.register(next_level, target); cmpt_jump_level(None) }); } } // If at some point the next level is not reached, the output will be empty // anyway. if levelset.get_level(next_level) == None { return; } // NOTE: isn't there a better way of organizing this? self.extend_level(next_level, nonjump_adj); if self.matrix_policy == MatrixPolicy::Precompute { self.init_reach(next_level, jump_adj); } self.last_level = next_level; } pub fn is_disconnected(&self) -> bool { !self.levelset.has_level(self.last_level) } /// Jump to the next relevant level from vertices in gamma at a given level. /// A relevent level has a node from which there is a path to gamma and /// that has an ingoing assignation. /// /// NOTE: It may be possible to return an iterator to refs of usize, but the /// autoref seems to not do the work. pub fn jump<T>(&self, level: usize, gamma: T) -> Option<(usize, Vec<usize>)> where T: Clone + Iterator<Item = usize>, { let jump_level = gamma .clone() .filter_map(|vertex| self.jl.get(&(level, vertex))) .max(); let jump_level = match jump_level { None => return Some((level, Vec::new())), Some(&lvl) if lvl == level => return Some((level, Vec::new())), Some(&lvl) => lvl, }; // NOTE: could convince Rust that the lifetime of this iterator is ok to return // a map iterator. let jump_level_vertices = self.levelset.get_level(jump_level).unwrap(); let gamma2 = jump_level_vertices .iter() .enumerate() .filter(|&(l, _)| { // NOTE: Maybe it could be more efficient to compute indices `k` before the // filter. gamma.clone().any( |source| match self.levelset.get_vertex_index(level, source) { Some(k) => self.reach[&(jump_level, level)][(l, k)], None => false, }, ) }) .map(|(_, target)| *target) .collect(); Some((jump_level, gamma2)) } /// Get the vertices that are in the final layer pub fn finals(&self) -> HashSet<usize> { if self.is_disconnected() { return HashSet::new(); } self.levelset .get_level(self.last_level) .unwrap() .iter() .cloned() .collect() } pub fn get_nb_levels(&self) -> usize { self.levelset.get_nb_levels() } /// Extend current level by reading non-jumpable edges inside the given /// level. fn extend_level(&mut self, level: usize, nonjump_adj: &Vec<Vec<usize>>) { let levelset = &mut self.levelset; let nonjump_vertices = &mut self.nonjump_vertices; let old_level = levelset.get_level(level).unwrap().clone(); for source in old_level { for &target in &nonjump_adj[source] { levelset.register(level, target); nonjump_vertices.insert((level, target)); } } } // Compute reach and rlevel, that is the effective jump points to all levels // reachable from the current level. fn init_reach(&mut self, level: usize, jump_adj: &Vec<Vec<usize>>) { let reach = &mut self.reach; let rlevel = &mut self.rlevel; let rev_rlevel = &mut self.rev_rlevel; let jl = &self.jl; let count_ingoing_jumps = &mut self.count_ingoing_jumps; let curr_level = self.levelset.get_level(level).unwrap(); // Build rlevel as the image of current level by jl rlevel.insert( level, curr_level .iter() .filter_map(|&source| jl.get(&(level, source)).map(|&target| target)) .collect(), ); // Update rev_rlevel for sublevels rev_rlevel.insert(level, HashSet::new()); for sublevel in &rlevel[&level] { rev_rlevel.get_mut(sublevel).unwrap().insert(level); } // Compute the adjacency between current level and the previous one. let prev_level = self.levelset.get_level(level - 1).unwrap(); let mut new_reach = Matrix::new(prev_level.len(), curr_level.len(), false); for &source in prev_level { let id_source = self.levelset.get_vertex_index(level - 1, source).unwrap(); for &target in &jump_adj[source] { let id_target = self.levelset.get_vertex_index(level, target).unwrap(); *new_reach.at(id_source, id_target) = true; } } reach.insert((level - 1, level), new_reach); // Compute by a dynamic algorithm the adjacency of current level with all its // sublevels. for &sublevel in &rlevel[&level] { // This eliminates the stupid cast of level 0. // TODO: fix this hardcoded behaviour. if sublevel >= level - 1 { continue; } reach.insert( (sublevel, level), &reach[&(sublevel, level - 1)] * &reach[&(level - 1, level)], ); } if !rlevel[&level].contains(&(level - 1)) { reach.remove(&(level - 1, level)); } if self.clean_policy == CleanPolicy::Clean { // Init Jump counters for current level for &vertex in curr_level { count_ingoing_jumps.insert((level, vertex), 0); } // Update Jump counters to previous levels for &sublevel in &rlevel[&level] { let adjacency = &reach[&(sublevel, level)]; for (vertex, vertex_index) in self.levelset.iter_level(sublevel) { let nb_pointers: usize = adjacency .iter_row(vertex_index) .map(|&x| if x { 1 } else { 0 }) .sum(); if nb_pointers != 0 { *count_ingoing_jumps.get_mut(&(sublevel, vertex)).unwrap() += nb_pointers; } } } } } /// Remove all useless nodes inside current level. A useless node is a node /// from which there is no path of assignation to a node which can be jumped /// to. pub fn clean_level(&mut self, level: usize, jump_adj: &Vec<Vec<usize>>) -> bool { if self.clean_policy == CleanPolicy::Skip { return false; } if level == 0 { // TODO: fix the reach[(0, 0)] exception return false; } let curr_level = match self.levelset.get_level(level) { None => return false, Some(vertices) => vertices, }; // Run over the level and eliminate all path that are not usefull ie. paths that // don't access to a jumpable vertex let mut seen = HashSet::new(); let mut del_vertices: HashSet<_> = curr_level.iter().cloned().collect(); let lvl_vertices = del_vertices.clone(); for &start in curr_level { if seen.contains(&start) { continue; } let mut heap = vec![(start, vec![start])]; while let Some((source, mut path)) = heap.pop() { seen.insert(source); // If the path can be identified as usefull, remove it from the set of vertices // to delete. let usefull_path = self.count_ingoing_jumps[&(level, source)] > 0 || jump_adj[source].iter().any(|&vertex| { lvl_vertices.contains(&vertex) && !del_vertices.contains(&vertex) }); if usefull_path { for vertex in &path { del_vertices.remove(vertex); } path.clear(); } for target in &jump_adj[source] { if lvl_vertices.contains(target) && !seen.contains(target) { debug_assert!(del_vertices.contains(target)); let mut target_path = path.to_vec(); target_path.push(*target); heap.push((*target, target_path)); } } } } if del_vertices.is_empty() { return false; } let removed_columns: Vec<_> = del_vertices .iter() .map(|&vertex| self.levelset.get_vertex_index(level, vertex).unwrap()) .collect(); // Update the levelset and update borrowed value self.levelset.remove_from_level(level, &del_vertices); let default_level = Vec::new(); let curr_level = self.levelset.get_level(level).unwrap_or(&default_level); for &vertex in &del_vertices { self.jl.remove(&(level, vertex)); self.count_ingoing_jumps.remove(&(level, vertex)); } // Update jump counters to sublevels, if a sublevel is removed from rlevel, then // we need to remove jump pointers from any vertex of the level, overwise only // from removed vertices. let new_rlevel: HashSet<_> = curr_level .iter() .filter_map(|&vertex| self.jl.get(&(level, vertex)).cloned()) .collect(); for &sublevel in self.rlevel[&level].difference(&new_rlevel) { for &vertex in self.levelset.get_level(sublevel).unwrap() { let adjacency = &self.reach[&(sublevel, level)]; let vertex_index = self.levelset.get_vertex_index(sublevel, vertex).unwrap(); let nb_removed: usize = adjacency .iter_row(vertex_index) .map(|&val| if val { 1 } else { 0 }) .sum(); if nb_removed > 0 { *self .count_ingoing_jumps .get_mut(&(sublevel, vertex)) .unwrap() -= nb_removed; } } } for &sublevel in &new_rlevel { for &vertex in self.levelset.get_level(sublevel).unwrap() { let adjacency = &self.reach[&(sublevel, level)]; let vertex_index = self.levelset.get_vertex_index(sublevel, vertex).unwrap(); let nb_removed: usize = removed_columns .iter() .map(|&col| if adjacency[(vertex_index, col)] { 1 } else { 0 }) .sum(); if nb_removed > 0 { *self .count_ingoing_jumps .get_mut(&(sublevel, vertex)) .unwrap() -= nb_removed; } } } if !self.levelset.has_level(level) { for &uplevel in &self.rev_rlevel[&level] { self.reach.remove(&(level, uplevel)); self.rlevel.get_mut(&uplevel).unwrap().remove(&level); } for &sublevel in &self.rlevel[&level] { self.reach.remove(&(sublevel, level)); self.rev_rlevel.get_mut(&sublevel).unwrap().remove(&level); } self.rlevel.remove(&level); self.rev_rlevel.remove(&level); } else { // Remove deprecated links in reach and rlevel for &sublevel in self.rlevel[&level].difference(&new_rlevel) { self.rev_rlevel.get_mut(&sublevel).unwrap().remove(&level); self.reach.remove(&(sublevel, level)); } self.rlevel.insert(level, new_rlevel); // Update reach for &vertex in &del_vertices { self.count_ingoing_jumps.remove(&(level, vertex)); } for &uplevel in &self.rev_rlevel[&level] { self.reach.insert( (level, uplevel), self.reach[&(level, uplevel)] .truncate(removed_columns.iter().cloned(), iter::empty()), ); } for &sublevel in &self.rlevel[&level] { self.reach.insert( (sublevel, level), self.reach[&(sublevel, level)] .truncate(iter::empty(), removed_columns.iter().cloned()), ); } } true } } impl fmt::Debug for Jump { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { for ((level, vertex), count) in self.count_ingoing_jumps.iter() { write!(f, "{} at level {}: {} ingoing jumps", vertex, level, count)?; } Ok(()) } }
use crate::Result; use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize)] pub(crate) struct Response { pub image: Image, } #[derive(Serialize, Deserialize)] pub(crate) struct ResponseList { pub images: Vec<Image>, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct ImageMeta { pub description: String, pub tag_input: String, pub source_url: String, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct Image { pub name: String, pub faves: i64, pub format: String, pub updated_at: String, pub downvotes: i64, pub duplicate_of: Option<u64>, pub tag_count: i64, pub spoilered: Option<bool>, pub uploader: Option<String>, pub deletion_reason: Option<String>, pub width: i64, pub processed: bool, pub created_at: String, pub orig_sha512_hash: String, pub view_url: String, pub uploader_id: Option<i64>, pub intensities: Option<Intensities>, pub score: i64, pub height: i64, pub mime_type: String, pub tag_ids: Vec<i64>, pub wilson_score: f64, pub first_seen_at: String, pub tags: Vec<String>, pub id: i64, pub upvotes: i64, pub comment_count: i64, pub representations: Option<Representations>, pub thumbnails_generated: bool, pub aspect_ratio: f64, pub hidden_from_users: bool, pub sha512_hash: String, pub source_url: Option<String>, pub description: String, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct Intensities { pub ne: f64, pub nw: f64, pub se: f64, pub sw: f64, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct Representations { pub full: String, pub large: String, pub medium: String, pub small: String, pub tall: String, pub thumb: String, pub thumb_small: String, pub thumb_tiny: String, } impl crate::Client { /// Get information about the currently featured image. pub async fn featured_image(&self) -> Result<Image> { let resp: Response = self .request(reqwest::Method::GET, "api/v1/json/images/featured") .send() .await? .error_for_status()? .json() .await?; Ok(resp.image) } /// Get information about an image by ID. pub async fn image(&self, id: u64) -> Result<Image> { let resp: Response = self .request(reqwest::Method::GET, &format!("api/v1/json/images/{}", id)) .send() .await? .error_for_status()? .json() .await?; Ok(resp.image) } /// Search for images that match a set of tags. pub async fn image_search<T: Into<String>>(&self, q: T, page: u64) -> Result<Vec<Image>> { let mut req = self .request(reqwest::Method::GET, &format!("api/v1/json/search/images")) .query(&[("q", q.into())]); if page != 0 { req = req.query(&[("page", format!("{}", page))]); } let resp: ResponseList = req.send().await?.error_for_status()?.json().await?; Ok(resp.images) } /// Upload an image to the booru. /// /// Test this call with a custom instance of philomena. Abuse of this call will /// likely result in a ban from the booru you are posting things to. pub async fn post_image(&self, image_url: String, im: ImageMeta) -> Result<Image> { self.cli.get(&image_url).send().await?.error_for_status()?; #[derive(Serialize)] struct CreateImage { url: String, image: ImageMeta, } let resp = self .request(reqwest::Method::POST, "api/v1/json/images") .json(&CreateImage { url: image_url, image: im, }) .send() .await?; match (&resp).error_for_status_ref() { Ok(_) => { let bytes = resp.bytes().await?; log::debug!("body: {}", std::str::from_utf8(&bytes)?); Ok(serde_json::from_slice::<Response>(&bytes)?.image) } Err(why) => { log::debug!("error: {:?}", why); log::debug!("body: {}", resp.text().await?); Err(why.into()) } } } } #[cfg(test)] mod tests { use httptest::{matchers::*, responders::*, Expectation, Server}; #[tokio::test] async fn featured_image() { let _ = pretty_env_logger::try_init(); let data: serde_json::Value = serde_json::from_slice(include_bytes!("../testdata/featured.json")).unwrap(); let server = Server::run(); server.expect( Expectation::matching(request::method_path("GET", "/api/v1/json/images/featured")) .respond_with(json_encoded(data)), ); let cli = crate::Client::with_baseurl("test", "42069", &format!("{}", server.url("/"))).unwrap(); cli.featured_image().await.unwrap(); } #[tokio::test] async fn image() { let _ = pretty_env_logger::try_init(); let data: serde_json::Value = serde_json::from_slice(include_bytes!("../testdata/image_2336.json")).unwrap(); let server = Server::run(); server.expect( Expectation::matching(request::method_path("GET", "/api/v1/json/images/2336")) .respond_with(json_encoded(data)), ); let cli = crate::Client::with_baseurl("test", "42069", &format!("{}", server.url("/"))).unwrap(); cli.image(2336).await.unwrap(); } #[tokio::test] async fn image_search() { let _ = pretty_env_logger::try_init(); let data: serde_json::Value = serde_json::from_slice(include_bytes!("../testdata/search_images.json")).unwrap(); let server = Server::run(); server.expect( Expectation::matching(request::method_path("GET", "/api/v1/json/search/images")) .respond_with(json_encoded(data)), ); let cli = crate::Client::with_baseurl("test", "42069", &format!("{}", server.url("/"))).unwrap(); cli.image_search("orca", 0).await.unwrap(); } }
/** The `sabi_extern_fn` attribute macro allows defining `extern "C"` function that abort on unwind instead of causing undefined behavior. This macro is syntactic sugar to transform this: ```ignore <visibility> fn function_name( <params> ) -> <return type> { <code here> } ``` into this: ```ignore <visibility> extern "C" fn function_name( <params> ) -> <return type> { ::abi_stable::extern_fn_panic_handling!{ <code here> } } ``` What this attribute does is to give the function abort on unwind semantics (only when the unwinds doesn't stop inside the function). A user can still use [`std::panic::catch_unwind`] inside the function to catch panics and handle them appropriately. ### Basic examples ```rust use abi_stable::{sabi_extern_fn, std_types::RArc, traits::IntoReprC}; #[sabi_extern_fn] pub(crate) fn hello() -> RArc<u32> { RArc::new(100) } assert_eq!(hello(), RArc::new(100)); ``` ```rust use abi_stable::{ sabi_extern_fn, std_types::{RStr, RVec}, traits::IntoReprC, }; #[sabi_extern_fn] fn collect_into_lines(text: &str) -> RVec<RStr<'_>> { text.lines() .filter(|x| !x.is_empty()) .map(RStr::from) .collect() } assert_eq!( collect_into_lines("what\nis\nthat"), vec!["what".into_c(), "is".into(), "that".into()].into_c(), ); ``` # no_early_return You can use `#[sabi_extern_fn(no_early_return)]` to potentially improve the runtime performance of the annotated function (this has not been tested). This variant of the attribute removes an intermediate closure that is used to intercept early returns (`?`, `return`, etc), If this version of the attribute is used on a function which does have an early return, it will (incorrectly) abort the process when it attempts to return early. ### Example ```rust use abi_stable::{ sabi_extern_fn, std_types::{RStr, RVec}, traits::IntoReprC, }; #[sabi_extern_fn(no_early_return)] pub(crate) fn hello() -> RVec<RStr<'static>> { vec!["hello".into(), "world".into()].into() } assert_eq!(hello(), vec!["hello".into_c(), "world".into()].into_c(),); ``` */ #[doc(inline)] pub use abi_stable_derive::sabi_extern_fn;
use juniper::{ graphql_object, graphql_subscription, Context, GraphQLInputObject, GraphQLObject, RootNode, Variables, }; use juniper::futures::channel::mpsc; use juniper::futures::executor; use juniper::futures::{Stream, StreamExt}; use juniper_subscriptions::Connection; use std::pin::Pin; use std::sync::{Arc, RwLock}; #[derive(Debug, Clone, GraphQLInputObject)] struct CreateItem { value: i32, } #[derive(Debug, Clone, GraphQLObject)] struct Item { id: String, value: i32, } #[derive(Default)] struct Store { subscribes: Arc<RwLock<Vec<mpsc::Sender<Item>>>>, } impl Store { fn subscribe(&self, s: mpsc::Sender<Item>) { if let Ok(mut vs) = self.subscribes.write() { vs.push(s); } } fn publish(&self, msg: Item) { if let Ok(vs) = self.subscribes.read() { for mut s in vs.clone() { let r = s.try_send(msg.clone()); match r { Ok(s) => println!("send success: {:?}", s), Err(e) => println!("send ERROR: {:?}", e), } } } } } impl Context for Store {} struct Query; #[graphql_object(context = Store)] impl Query { fn new() -> Self { Self } } struct Mutation; #[graphql_object(context = Store)] impl Mutation { fn create(ctx: &Store, input: CreateItem) -> Item { let item = Item { id: "".to_string(), value: input.value, }; ctx.publish(item.clone()); item } } type ItemStream = Pin<Box<dyn Stream<Item = Item> + Send>>; struct Subscription; #[graphql_subscription(context = Store)] impl Subscription { async fn created(ctx: &Store) -> ItemStream { let (sender, receiver) = mpsc::channel::<Item>(5); ctx.subscribe(sender); Box::pin(receiver) } } type Schema = RootNode<'static, Query, Mutation, Subscription>; async fn run() { let ctx = Store::default(); let schema = Schema::new(Query, Mutation, Subscription); let s = r#" subscription { created { id value } } "#; let v = Variables::new(); let (r, e) = juniper::resolve_into_stream(s, None, &schema, &v, &ctx) .await .unwrap(); let mut con = Connection::from_stream(r, e); let m = r#" mutation { create(input: { value: 123 }) { id value } } "#; let (mr, _) = juniper::execute(m, None, &schema, &v, &ctx).await.unwrap(); println!("{}", serde_json::to_string(&mr).unwrap()); if let Some(res) = con.next().await { println!("*** received: {}", serde_json::to_string(&res).unwrap()); } } fn main() { executor::block_on(run()); }
use anyhow::Result; pub trait Parser { fn name(&self) -> String; fn parse_tokens_str<'a>(&self, input: &'a str) -> Result<()>; fn parse_tokens_string(&self, input: String) -> Result<()>; // This mutable reference results in unwind unsafe code fn parse_tokens_reader<'a>(&self, input: &'a mut dyn std::io::BufRead) -> Result<()>; } pub mod data; pub mod parser; pub mod matrix; pub mod tests; #[cfg(test)] pub mod parser_test;
use regex::Regex; use std::fs; #[test] fn validate_2_1() { assert_eq!(algorithm("src/day_2/input_test.txt"), (3, 2)); } fn parse_data(s: &str) -> Vec<&str> { let re = Regex::new(":? |-").unwrap(); re.split(s).collect() } fn algorithm(file_location: &str) -> (usize, usize) { let contents = fs::read_to_string(file_location).unwrap(); let values: Vec<Vec<&str>> = contents.lines().map(parse_data).collect(); let mut count = 0; for item in values.iter() { let (min, max, letter, password) = (item[0], item[1], item[2].chars().next().unwrap(), item[3]); let min_times: usize = min.parse().unwrap(); let max_times: usize = max.parse().unwrap(); let times: usize = password .chars() .filter(|c| c == &letter) .collect::<Vec<_>>() .len(); if min_times <= times && times <= max_times { count = count + 1; } } (values.len(), count) } pub fn run() { let (passwords, valid) = algorithm("src/day_2/input.txt"); println!("Out of {} passwords, {} are valid.", passwords, valid); }
use super::crc; use super::error; use std::io::prelude::*; #[derive(Clone, PartialEq, Eq, Debug, Default)] pub struct RawGenericChunk { pub data_length: [u8; 4], pub chunk_type: [u8; 4], pub data: Vec<u8>, pub crc: [u8; 4], } impl RawGenericChunk { pub fn load<R: Read>(reader: &mut R) -> Result<RawGenericChunk, error::DmiError> { let mut chunk_bytes = Vec::new(); reader.read_to_end(&mut chunk_bytes)?; // 4 bytes for the length. // 4 bytes for the type. // Data can be 0 bytes. // 4 bytes for the CRC. // Total minimum size for an undetermined PNG chunk: 12 bytes. let chunk_length = chunk_bytes.len(); if chunk_length < 12 { return Err(error::DmiError::Generic(format!("Failed to load Chunk. Supplied reader contained size of {} bytes, lower than the required 12.", chunk_length))); }; let data_length = [ chunk_bytes[0], chunk_bytes[1], chunk_bytes[2], chunk_bytes[3], ]; let chunk_type = [ chunk_bytes[4], chunk_bytes[5], chunk_bytes[6], chunk_bytes[7], ]; // The chunk type is made of four ascii characters. The valid ranges are A-Z and a-z. if !chunk_type .iter() .all(|c| (b'A' <= *c && *c <= b'Z') || (b'a' <= *c && *c <= b'z')) { return Err(error::DmiError::Generic(format!( "Failed to load Chunk. Type contained unlawful characters: {:#?}", chunk_type ))); }; let data: Vec<u8> = chunk_bytes[8..(chunk_length - 4)].to_vec(); let crc = [ chunk_bytes[chunk_length - 4], chunk_bytes[chunk_length - 3], chunk_bytes[chunk_length - 2], chunk_bytes[chunk_length - 1], ]; let recalculated_crc = crc::calculate_crc(chunk_type.iter().chain(data.iter())); if u32::from_be_bytes(crc) != recalculated_crc { let chunk_name = String::from_utf8(chunk_type.to_vec())?; return Err(error::DmiError::Generic(format!("Failed to load Chunk of type {}. Supplied CRC invalid: {:#?}. Its value ({}) does not match the recalculated one ({}).", chunk_name, crc, u32::from_be_bytes(crc), recalculated_crc))); } Ok(RawGenericChunk { data_length, chunk_type, data, crc, }) } pub fn save<W: Write>(&self, writter: &mut W) -> Result<usize, error::DmiError> { let bytes_written = writter.write(&self.data_length)?; let mut total_bytes_written = bytes_written; if bytes_written < self.data_length.len() { return Err(error::DmiError::Generic(format!( "Failed to save Chunk. Buffer unable to hold the data, only {} bytes written.", total_bytes_written ))); }; let bytes_written = writter.write(&self.chunk_type)?; total_bytes_written += bytes_written; if bytes_written < self.chunk_type.len() { return Err(error::DmiError::Generic(format!( "Failed to save Chunk. Buffer unable to hold the data, only {} bytes written.", total_bytes_written ))); }; let bytes_written = writter.write(&self.data)?; total_bytes_written += bytes_written; if bytes_written < self.data.len() { return Err(error::DmiError::Generic(format!( "Failed to save Chunk. Buffer unable to hold the data, only {} bytes written.", total_bytes_written ))); }; let bytes_written = writter.write(&self.crc)?; total_bytes_written += bytes_written; if bytes_written < self.crc.len() { return Err(error::DmiError::Generic(format!( "Failed to save Chunk. Buffer unable to hold the data, only {} bytes written.", total_bytes_written ))); }; Ok(total_bytes_written) } }
pub mod users; pub mod roles;
use std::{ fs::{File, OpenOptions}, io::BufReader, }; use crate::{bed::Bed, bedgraph::BedGraph, error::Error}; pub enum TrackVariant { Bed(Bed), BedGraph(BedGraph), } pub fn get_buf(filename: &str) -> Result<BufReader<File>, Error> { match OpenOptions::new().read(true).open(filename) { Err(io_error) => Err(Error::IO { why: format!("failed to open {}: {}", filename, io_error), io_error, }), Ok(f) => Ok(BufReader::new(f)), } } #[derive(Eq, PartialEq, Copy, Clone, Debug, Hash)] pub enum Strand { Positive, Negative, } impl Strand { pub fn new(strand: &str) -> Result<Option<Strand>, Error> { match strand { "+" => Ok(Some(Strand::Positive)), "-" => Ok(Some(Strand::Negative)), "." => Ok(None), s => Err(Error::BadFormat(format!( "unrecognized strand symbol: {}", s ))), } } }
use sltunnel::rustls::internal::pemfile::{certs, rsa_private_keys}; use sltunnel::rustls::{Certificate, NoClientAuth, PrivateKey, ServerConfig}; use sltunnel::Server; use std::env::args; use std::error::Error; use std::fs::File; use std::io::BufReader; use std::net::SocketAddr; use std::path::Path; use std::str::FromStr; fn load_certificates(path: &Path) -> std::io::Result<Vec<Certificate>> { certs(&mut BufReader::new(File::open(path)?)) .map_err(|_| std::io::Error::new(std::io::ErrorKind::InvalidInput, "invalid cert")) } fn load_private_keys(path: &Path) -> std::io::Result<Vec<PrivateKey>> { rsa_private_keys(&mut BufReader::new(File::open(path)?)) .map_err(|_| std::io::Error::new(std::io::ErrorKind::InvalidInput, "invalid key")) } #[tokio::main] async fn main() -> Result<(), Box<dyn Error>> { let args = args().into_iter().collect::<Vec<_>>(); if args.len() < 2 { eprintln!("Usage: {} [bind_to] [upstream]", &args[0]); return Ok(()); } let certificates = load_certificates(Path::new("./cert.pem"))?; let mut private_keys = load_private_keys(Path::new("./privkey.pem"))?; let mut server_config = ServerConfig::new(NoClientAuth::new()); let num_certificates = certificates.len(); let num_private_keys = private_keys.len(); server_config.set_single_cert(certificates, private_keys.remove(0))?; println!( "Loaded {} certificates and {} private keys.", num_certificates, num_private_keys, ); let bind_to = SocketAddr::from_str(&args[1])?; let upstream = SocketAddr::from_str(&args[2])?; let mut server = Server::start(bind_to, upstream, server_config).await?; println!("Listening on {} with upstream {}.", bind_to, upstream); loop { let (meta, pipes) = server.wait_for_session().await?; let (mut inbound, mut outbound) = pipes; tokio::spawn(async move { inbound.run().await }); tokio::spawn(async move { outbound.run().await }); println!( "Connection established: {} <-> {} (TLS).", upstream, meta.get_peer_addr(), ); } }
// Taken from https://github.com/rustwasm/wasm-bindgen/blob/master/crates/backend/src/error.rs // // Copyright (c) 2014 Alex Crichton // // Permission is hereby granted, free of charge, to any // person obtaining a copy of this software and associated // documentation files (the "Software"), to deal in the // Software without restriction, including without // limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software // is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice // shall be included in all copies or substantial portions // of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF // ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED // TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A // PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT // SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR // IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #![allow(dead_code)] use proc_macro2::*; use quote::{ToTokens, TokenStreamExt}; use syn::parse::Error; macro_rules! err_span { ($span:expr, $($msg:tt)*) => ( syn::Error::new_spanned(&$span, format_args!($($msg)*)) ) } macro_rules! bail_span { ($($t:tt)*) => ( return Err(err_span!($($t)*).into()) ) } // macro_rules! push_err_span { // ($diagnostics:expr, $($t:tt)*) => { // $diagnostics.push(err_span!($($t)*)) // }; // } // macro_rules! push_diag_result { // ($diags:expr, $x:expr $(,)?) => { // if let Err(e) = $x { // $diags.push(e); // } // }; // } #[derive(Debug)] pub struct Diagnostic { inner: Repr, } #[derive(Debug)] enum Repr { Single { text: String, span: Option<(Span, Span)>, }, SynError(Error), Multi { diagnostics: Vec<Diagnostic>, }, } impl Diagnostic { pub fn error<T: Into<String>>(text: T) -> Diagnostic { Diagnostic { inner: Repr::Single { text: text.into(), span: None, }, } } pub(crate) fn spans_error<T: Into<String>>(spans: (Span, Span), text: T) -> Diagnostic { Diagnostic { inner: Repr::Single { text: text.into(), span: Some(spans), }, } } pub fn from_vec(diagnostics: Vec<Diagnostic>) -> Result<(), Diagnostic> { if diagnostics.is_empty() { Ok(()) } else { Err(Diagnostic { inner: Repr::Multi { diagnostics }, }) } } pub fn panic(&self) -> ! { match &self.inner { Repr::Single { text, .. } => panic!("{}", text), Repr::SynError(error) => panic!("{}", error), Repr::Multi { diagnostics } => diagnostics[0].panic(), } } } impl From<Error> for Diagnostic { fn from(err: Error) -> Diagnostic { Diagnostic { inner: Repr::SynError(err), } } } pub fn extract_spans(node: &dyn ToTokens) -> Option<(Span, Span)> { let mut t = TokenStream::new(); node.to_tokens(&mut t); let mut tokens = t.into_iter(); let start = tokens.next().map(|t| t.span()); let end = tokens.last().map(|t| t.span()); start.map(|start| (start, end.unwrap_or(start))) } impl ToTokens for Diagnostic { fn to_tokens(&self, dst: &mut TokenStream) { match &self.inner { Repr::Single { text, span } => { let cs2 = (Span::call_site(), Span::call_site()); let (start, end) = span.unwrap_or(cs2); dst.append(Ident::new("compile_error", start)); dst.append(Punct::new('!', Spacing::Alone)); let mut message = TokenStream::new(); message.append(Literal::string(text)); let mut group = Group::new(Delimiter::Brace, message); group.set_span(end); dst.append(group); } Repr::Multi { diagnostics } => { for diagnostic in diagnostics { diagnostic.to_tokens(dst); } } Repr::SynError(err) => { err.to_compile_error().to_tokens(dst); } } } }
#![cfg_attr(feature = "nightly", feature(catch_panic))] extern crate disque; use std::collections::{HashMap, HashSet}; use std::sync::Arc; use std::sync::mpsc::{channel, Receiver, Sender}; use std::thread::{spawn, JoinHandle}; #[cfg(feature = "nightly")] use std::thread::catch_panic; use disque::Disque; /// Once a job execution finishes, change its status by performing one of this /// actions. #[derive(Clone)] pub enum JobStatus { /// Performs a best effort cluster wide deletion of the job. FastAck, /// Acknowledges the execution of the jobs. AckJob, /// Puts back the job in the queue ASAP. NAck, } /// Handles a job task. pub trait Handler { /// Process a job. fn process_job(&self, queue_name: &[u8], jobid: &String, body: Vec<u8>) -> JobStatus; /// Decides if a job that failed in the past should be re-executed. /// `nack` is the count of negatives acknowledges. /// `additional_deliveries` is the number of times the job was processed /// but it was not acknowledged. fn process_error(&self, _: &[u8], _: &String, _: u32, _: u32) -> bool { false } } /// A wrapper to send the handler to each worker thread. #[derive(Clone)] struct HandlerWrapper<H: Handler> { handler: Arc<H>, } unsafe impl<H: Handler> Send for HandlerWrapper<H> {} unsafe impl<H: Handler> Sync for HandlerWrapper<H> {} #[cfg(feature = "nightly")] macro_rules! spawn { ($func: expr, $err: expr) => { spawn(move || { match catch_panic(move || $func) { Ok(_) => (), Err(e) => ($err)(e), } }) } } #[cfg(not(feature = "nightly"))] macro_rules! spawn { ($func: expr, $err: expr) => { spawn(move || $func) } } #[allow(dead_code)] enum JobUpdate { Success(usize, String, JobStatus), Failure(usize), } /// Creates a worker to handle tasks coming from `task_rx`, reporting them back /// to `completion_tx` using the provided `handler_`. The `position` is the /// worker id. #[allow(unused_variables)] fn create_worker<H: Handler + Clone + 'static>(position: usize, task_rx: Receiver<Option<(Vec<u8>, String, Vec<u8>, u32, u32)>>, completion_tx: Sender<JobUpdate>, handler_: HandlerWrapper<H>, ) -> JoinHandle<()> { let handlerw = handler_.clone(); let completion_tx2 = completion_tx.clone(); spawn!({ let handler = handlerw.handler; loop { let (queue, jobid, job, nack, additional_deliveries) = match task_rx.recv() { Ok(o) => match o { Some(v) => v, None => break, }, Err(e) => { // TODO: better log println!("Error in worker thread {:?}", e); break; } }; if nack > 0 || additional_deliveries > 0 { if !handler.process_error(&*queue, &jobid, nack, additional_deliveries) { return; } } let status = handler.process_job(&*queue, &jobid, job); completion_tx.send(JobUpdate::Success(position, jobid, status)).unwrap(); } }, |e| { println!("handle panic {:?}", e); completion_tx2.send(JobUpdate::Failure(position)).unwrap(); }) } /// Workers manager. pub struct EventLoop<H: Handler + Clone + 'static> { /// The connection to pull the jobs. disque: Disque, /// The worker threads and their channels to send jobs. workers: Vec<(JoinHandle<()>, Sender<Option<(Vec<u8>, String, Vec<u8>, u32, u32)>>)>, /// The receiver when tasks are completed. completion_rx: Receiver<JobUpdate>, /// The sender for when tasks are completed. Keeping a reference just to /// provide to workers. completion_tx: Sender<JobUpdate>, /// Set of available workers. free_workers: HashSet<usize>, /// Watched queue names. queues: HashSet<Vec<u8>>, /// Server network layout. hello: (u8, String, Vec<(String, String, u16, u32)>), /// Counter for where the tasks are coming from. If most tasks are coming /// from a server that is not the one the connection is issued, it can be /// used to connect directly to the other one. node_counter: HashMap<Vec<u8>, usize>, /// The task processor. ahandler: HandlerWrapper<H> } impl<H: Handler + Clone + 'static> EventLoop<H> { pub fn new( disque: Disque, numworkers: usize, handler: H) -> Self { let mut workers = Vec::with_capacity(numworkers); let mut free_workers = HashSet::with_capacity(numworkers); let (completion_tx, completion_rx) = channel(); let ahandler = HandlerWrapper { handler: Arc::new(handler) }; for i in 0..numworkers { let (task_tx, task_rx) = channel(); let jg = create_worker(i, task_rx, completion_tx.clone(), ahandler.clone()); workers.push((jg, task_tx)); free_workers.insert(i); } let hello = disque.hello().unwrap(); EventLoop { disque: disque, completion_rx: completion_rx, workers: workers, hello: hello, free_workers: free_workers, queues: HashSet::new(), node_counter: HashMap::new(), completion_tx: completion_tx, ahandler: ahandler, } } /// Adds a queue to process its jobs. pub fn watch_queue(&mut self, queue_name: Vec<u8>) { self.queues.insert(queue_name); } /// Removes a queue from job processing. pub fn unwatch_queue(&mut self, queue_name: &Vec<u8>) { self.queues.remove(queue_name); } /// Marks a job as completed fn completed(&mut self, worker: usize, jobid: String, status: JobStatus) { self.free_workers.insert(worker); match status { JobStatus::FastAck => self.disque.fastackjob(jobid.as_bytes()), JobStatus::AckJob => self.disque.ackjob(jobid.as_bytes()), JobStatus::NAck => self.disque.nackjob(jobid.as_bytes()), }.unwrap(); } /// Creates a new worker to replace one that has entered into panic. fn handle_worker_panic(&mut self, worker: usize) { if self.workers.len() == 0 { // shutting down return; } let (task_tx, task_rx) = channel(); let jg = create_worker(worker, task_rx, self.completion_tx.clone(), self.ahandler.clone()); self.workers[worker] = (jg, task_tx); self.free_workers.insert(worker); } /// Checks workers to see if they have completed their jobs. /// If `blocking` it will wait until at least one new is available. fn mark_completed(&mut self, blocking: bool) { macro_rules! recv { ($func: ident) => { match self.completion_rx.$func() { Ok(c) => match c { JobUpdate::Success(worker, jobid, status) => { self.completed(worker, jobid, status); }, JobUpdate::Failure(worker) => self.handle_worker_panic(worker), }, Err(_) => return, } } } if blocking { recv!(recv); } loop { recv!(try_recv); } } /// Connects to the server that is issuing most of the jobs. pub fn choose_favorite_node(&self) -> (Vec<u8>, usize) { let mut r = (&Vec::new(), &0); for n in self.node_counter.iter() { if n.1 >= r.1 { r = n; } } (r.0.clone(), r.1.clone()) } /// Number of jobs produced by the current server. pub fn jobcount_current_node(&self) -> usize { let nodeid = self.hello.1.as_bytes()[0..8].to_vec(); self.node_counter.get(&nodeid).unwrap_or(&0).clone() } /// Identifier of the current server. pub fn current_node_id(&self) -> String { self.hello.1.clone() } /// Fetches a task and sends it to a worker. /// Returns true if a job was received and is processing. fn run_once(&mut self) -> bool { self.mark_completed(false); let worker = match self.free_workers.iter().next() { Some(w) => w.clone(), None => return false, }; let job = match self.disque.getjob_withcounters(false, None, &*self.queues.iter().map(|k| &**k).collect::<Vec<_>>() ).unwrap() { Some(j) => j, None => return false, }; let nodeid = job.1.as_bytes()[2..10].to_vec(); let v = self.node_counter.remove(&nodeid).unwrap_or(0); self.node_counter.insert(nodeid, v + 1); self.free_workers.remove(&worker); self.workers[worker].1.send(Some(job)).unwrap(); true } /// Connects to a new server. fn connect_to_node(&mut self, new_master: Vec<u8>) -> bool { let mut hello = None; for node in self.hello.2.iter() { if node.0.as_bytes()[..new_master.len()] == *new_master { match Disque::open(&*format!("redis://{}:{}/", node.1, node.2)) { Ok(disque) => { hello = Some(match disque.hello() { Ok(hello) => hello, Err(_) => break, }); self.disque = disque; break; }, Err(_) => (), } break; } } match hello { Some(h) => { self.hello = h; true } None => false, } } /// Connects to the server doing most jobs. pub fn do_cycle(&mut self) { let (fav_node, fav_count) = self.choose_favorite_node(); let current_count = self.jobcount_current_node(); // only change if it is at least 20% better than the current node if fav_count as f64 / current_count as f64 > 1.2 { self.connect_to_node(fav_node); } } /// Runs for ever. Every `cycle` jobs reevaluates which server to use. pub fn run(&mut self, cycle: usize) { self.run_times_cycle(0, cycle) } /// Runs until `times` jobs are received. pub fn run_times(&mut self, times: usize) { self.run_times_cycle(times, 0) } /// Runs `times` jobs and changes server every `cycle`. pub fn run_times_cycle(&mut self, times: usize, cycle: usize) { let mut c = 0; let mut counter = 0; loop { let did_run = self.run_once(); if did_run { if times > 0 { counter += 1; if counter == times { break; } } if cycle > 0 { c += 1; if c == cycle { self.do_cycle(); c = 0; } } } else { self.mark_completed(true); } } self.mark_completed(false); } /// Sends a kill signal to all workers and waits for them to finish their /// current job. pub fn stop(mut self) { for worker in std::mem::replace(&mut self.workers, vec![]).into_iter() { worker.1.send(None).unwrap(); worker.0.join().unwrap(); } self.mark_completed(false); } } #[test] fn favorite() { #[derive(Clone)] struct MyHandler; impl Handler for MyHandler { fn process_job(&self, _: &[u8], _: &String, _: Vec<u8>) -> JobStatus { JobStatus::AckJob } fn process_error(&self, _: &[u8], _: &String, _: u32, _: u32) -> bool { false } } let disque = Disque::open("redis://127.0.0.1:7711/").unwrap(); let mut el = EventLoop::new(disque, 1, MyHandler); el.node_counter.insert(vec![1, 2, 3], 123); el.node_counter.insert(vec![4, 5, 6], 456); el.node_counter.insert(vec![0, 0, 0], 0); assert_eq!(el.choose_favorite_node(), (vec![4, 5, 6], 456)); }
use actix_web_static_files::NpmBuild; fn main() -> std::io::Result<()> { NpmBuild::new("./pitunes-frontend") .executable("yarn") .install()? .run("build")? .target("./pitunes-frontend/build") .to_resource_dir() .build()?; Ok(()) }
mod config; #[macro_use] extern crate lazy_static; use serde_json::Value; use std::fs; use std::io::Write; pub fn send(channel: String, title: String, content: String) -> anyhow::Result<String> { use reqwest::blocking::multipart::Form; use reqwest::blocking::Client; let mut f = fs::File::create("buf.txt").unwrap(); f.write_all(content.as_bytes()).unwrap(); let form = Form::new().file("file", "buf.txt").unwrap(); let res = Client::new() .post("https://slack.com/api/files.upload") .multipart(form) .query(&[ ("token", config::config().slack_bot_token), ("title", title), ("channels", channel), ("pretty", "1".into()), ]) .send()?; let _ = fs::remove_file("buf.txt"); match res.text() { Err(e) => Ok(format!("アップロード失敗:{:?}", e)), Ok(result) => { let v: Value = serde_json::from_str(result.as_str()).unwrap(); match v["ok"].as_bool() { Some(true) => Ok("アップロード完了".to_string()), Some(false) => Ok(format!("アップロード失敗:{}", v["error"])), None => Ok(format!("アップロード失敗:{}", v["error"])), } } } } pub async fn send_async(content: String) -> anyhow::Result<String> { use reqwest::multipart::{Form, Part}; use reqwest::Client; let (channel, title) = ( config::config().slack_channel, config::config().slack_file_name, ); let fp = Part::text(content).file_name("buf.txt"); let form = Form::new().part("file", fp); let res = Client::new() .post("https://slack.com/api/files.upload") .multipart(form) .query(&[ ("token", config::config().slack_bot_token), ("title", title), ("channels", channel), ("pretty", "1".into()), ]) .send() .await? .text() .await?; let v: Value = serde_json::from_str(res.as_str()).unwrap(); match v["ok"].as_bool() { Some(true) => Ok("アップロード完了".to_string()), Some(false) => Ok(format!("アップロード失敗:{}", v["error"])), None => Ok(format!("アップロード失敗:{}", v["error"])), } } #[cfg(test)] mod tests { use super::*; #[test] fn it_works() { log::info! {"{}",send("テスト用".into(),"タイトル".into(), "内容内容内容".into()).unwrap()}; } #[tokio::test] async fn async_fn_works() { log::info!("{}", send_async("ほげほげ".into()).await.unwrap()); } }
use advent::helpers; use std::error::Error; type BoxedError = Box<dyn Error + Send + Sync>; type Res = Result<u8, BoxedError>; fn row_op_to_binary(c: &u8) -> Res { match *c as char { 'F' => Ok(b'0'), 'B' => Ok(b'1'), _ => Err(From::from(format!("Invalid row op: '{}'", *c as char))), } } fn col_op_to_binary(c: &u8) -> Res { match *c as char { 'L' => Ok(b'0'), 'R' => Ok(b'1'), _ => Err(From::from(format!("Invalid col op: '{}'", *c as char))), } } fn decode_string<F>(s: &str, r: std::ops::Range<usize>, op_mapper: F) -> Res where F: FnMut(&u8) -> Res, { let binary_vec = s.as_bytes()[r] .iter() .map(op_mapper) .collect::<Result<Vec<_>, _>>()?; let binary_string = std::str::from_utf8(&binary_vec)?; let decoded_number = u8::from_str_radix(binary_string, 2)?; Ok(decoded_number) } fn boarding_pass_to_seat_id(s: &str) -> Result<(u32, u32, u32), BoxedError> { let row = decode_string(s, 0..7, row_op_to_binary)? as u32; let column = decode_string(s, 7..10, col_op_to_binary)? as u32; Ok((row * 8 + column, row, column)) } #[test] fn test_p1() { assert_eq!( boarding_pass_to_seat_id("FBFBBFFRLR").ok(), Some((357, 44, 5)) ); assert_eq!( boarding_pass_to_seat_id("BFFFBBFRRR").ok(), Some((567, 70, 7)) ); assert_eq!( boarding_pass_to_seat_id("FFFBBBFRRR").ok(), Some((119, 14, 7)) ); assert_eq!( boarding_pass_to_seat_id("BBFFBBFRLL").ok(), Some((820, 102, 4)) ); } fn until_err<T, E>(err: &mut &mut Result<(), E>, item: Result<T, E>) -> Option<T> { match item { Ok(item) => Some(item), Err(e) => { **err = Err(e); None } } } fn solve_p1() -> Result<u32, BoxedError> { let data = helpers::get_data_from_file("d5").ok_or("Coudn't read file contents.")?; // https://morestina.net/blog/1607/fallible-iteration let mut err = Ok(()); let max_seat_id = data .split_ascii_whitespace() .map(|s| boarding_pass_to_seat_id(s)) .scan(&mut err, until_err) .map(|i| i.0) .max() .ok_or("No seats provided.")?; err?; println!("Max seat id is: {}", max_seat_id); Ok(max_seat_id) } fn solve_p2() -> Result<u32, BoxedError> { let data = helpers::get_data_from_file("d5").ok_or("Coudn't read file contents.")?; let mut err = Ok(()); let mut seat_vec = data .split_ascii_whitespace() .map(|s| boarding_pass_to_seat_id(s)) .scan(&mut err, until_err) .map(|i| i.0) .collect::<std::vec::Vec<u32>>(); err?; seat_vec.sort_unstable(); let seat_set: std::collections::HashSet<&u32> = seat_vec.iter().collect(); let missing_seats = seat_vec .iter() .rev() .skip(1) .rev() .fold(vec![], |mut missing_seats, i| { if !seat_set.contains(&(*i + 1)) { missing_seats.push(Some(*i + 1)); } missing_seats }); assert_eq!(missing_seats.len(), 1); let needle_seat = missing_seats[0]; println!("Your seat id is: {:?}", needle_seat); assert_eq!(needle_seat, Some(743)); needle_seat.ok_or_else(|| "No empty seat found.".into()) } fn handle_error<T>(r: Result<T, BoxedError>) { match r { Ok(_) => (), Err(e) => eprintln!("Error: {}", e), } } fn main() { handle_error(solve_p1()); handle_error(solve_p2()); }
use proconio::input; fn main() { input! { s: String, }; let words = ["ACE", "BDF", "CEG", "DFA", "EGB", "FAC", "GBD"]; if words.contains(&s.as_str()) { println!("Yes"); } else { println!("No"); } }
use std::ffi::c_void; use std::fmt; use std::path::{Path, PathBuf}; use firefly_diagnostics::Severity; use firefly_util::diagnostics::{DiagnosticsHandler, FileName, InFlightDiagnostic, LabelStyle}; use crate::support::MlirStringCallback; use crate::*; /// Register our global diagnostics handler as the diagnostic handler for the given /// MLIR context. Any MLIR-produced diagnostics will be translated to our own diagnostic /// system. pub fn register_diagnostics_handler(context: Context, handler: &DiagnosticsHandler) { unsafe { mlir_context_attach_diagnostic_handler( context, on_diagnostic, handler as *const DiagnosticsHandler as *const c_void, None, ); } } extern "C" { type MlirDiagnostic; } /// This type represents the callback invoked when diagnostics occurs pub type MlirDiagnosticHandler = extern "C" fn(Diagnostic, *const c_void) -> LogicalResult; /// This type represents the callback invoked when cleaning up a diagnostic handler pub type CleanupUserDataFunction = extern "C" fn(*const c_void); /// This type represents the unique identifier for a diagnostic handler pub type DiagnosticHandlerId = u64; /// This type is a wrapper for an MLIR-owned diagnostic, and it exposes /// functionality necessary to interrogate and print such diagnostics. #[repr(transparent)] #[derive(Copy, Clone)] pub struct Diagnostic(*mut MlirDiagnostic); impl Diagnostic { #[inline(always)] pub fn is_null(&self) -> bool { self.0.is_null() } pub fn severity(self) -> Severity { match unsafe { mlir_diagnostic_get_severity(self) } { MlirSeverity::Error => Severity::Error, MlirSeverity::Warning => Severity::Warning, MlirSeverity::Note | MlirSeverity::Remark => Severity::Note, } } pub fn location(self) -> Option<SourceLoc> { let loc = unsafe { mlir_diagnostic_get_file_line_col(self) }; if loc.filename.is_null() { return None; } Some(loc.into()) } pub fn notes(self) -> impl Iterator<Item = Diagnostic> { let len = unsafe { mlir_diagnostic_get_num_notes(self) }; DiagnosticNoteIter { diag: self, len, pos: 0, } } } impl fmt::Display for Diagnostic { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { unsafe { mlir_diagnostic_print( *self, support::write_to_formatter, f as *mut _ as *mut c_void, ); } Ok(()) } } /// Iterator for notes attached to a Diagnostic struct DiagnosticNoteIter { diag: Diagnostic, len: usize, pos: usize, } impl Iterator for DiagnosticNoteIter { type Item = Diagnostic; fn size_hint(&self) -> (usize, Option<usize>) { (self.len, Some(self.len)) } fn next(&mut self) -> Option<Self::Item> { if self.pos >= self.len { return None; } let diag = unsafe { mlir_diagnostic_get_note(self.diag, self.pos) }; if diag.is_null() { self.len = 0; return None; } self.pos += 1; Some(diag) } } impl std::iter::FusedIterator for DiagnosticNoteIter {} /// This is the severity level returned via FFI /// /// NOTE: rustc complains that the variants are never constructed, which /// is true for our Rust code, but since it is constructed in C++, we only /// ever match on it, hence the `#[allow(unused)]` below #[repr(u32)] enum MlirSeverity { #[allow(unused)] Error = 0, #[allow(unused)] Warning, #[allow(unused)] Note, #[allow(unused)] Remark, } /// This is the location value returned via FFI #[repr(C)] struct FileLineColLoc { pub line: u32, pub column: u32, pub filename_len: u32, pub filename: *const u8, } impl FileLineColLoc { #[inline] pub(super) fn filename(&self) -> String { let bytes = unsafe { core::slice::from_raw_parts(self.filename, self.filename_len as usize) }; String::from_utf8_lossy(&bytes).into_owned() } } /// This is the location value we produce from a `FileLineColLoc` pub struct SourceLoc { filename: FileName, line: u32, column: u32, } impl From<FileLineColLoc> for SourceLoc { fn from(loc: FileLineColLoc) -> Self { let filename = loc.filename(); let path = Path::new(&filename); if path.exists() { SourceLoc { filename: FileName::from(PathBuf::from(filename)), line: loc.line, column: loc.column, } } else { SourceLoc { filename: FileName::from(filename), line: loc.line, column: loc.column, } } } } /// This function is used as a callback for MLIR diagnostics pub(crate) extern "C" fn on_diagnostic(diag: Diagnostic, userdata: *const c_void) -> LogicalResult { let handler = unsafe { &*(userdata as *const DiagnosticsHandler) }; let mut ifd = handler.diagnostic(diag.severity()); ifd.with_message(diag.to_string()); if let Some(loc) = diag.location() { ifd.set_source_file(loc.filename); ifd.with_primary_label( loc.line, loc.column, Some("during generation of mlir associated with this source code".to_owned()), ); } for note in diag.notes() { append_note_to_diagnostic(note, &mut ifd); } ifd.emit(); LogicalResult::Success } fn append_note_to_diagnostic(note: Diagnostic, ifd: &mut InFlightDiagnostic) { let message = note.to_string(); if let Some(loc) = note.location() { ifd.with_label( LabelStyle::Secondary, Some(loc.filename), loc.line, loc.column, Some(message), ); } else { ifd.with_note(message); } } extern "C" { #[link_name = "mlirContextAttachDiagnosticHandler"] fn mlir_context_attach_diagnostic_handler( context: Context, callback: MlirDiagnosticHandler, userdata: *const c_void, cleanup: Option<CleanupUserDataFunction>, ) -> DiagnosticHandlerId; #[allow(unused)] #[link_name = "mlirContextDetachDiagnosticHandler"] fn mlir_context_detach_diagnostic_handler(context: Context, id: DiagnosticHandlerId); #[link_name = "mlirDiagnosticGetSeverity"] fn mlir_diagnostic_get_severity(diag: Diagnostic) -> MlirSeverity; #[link_name = "mlirDiagnosticGetNumNotes"] fn mlir_diagnostic_get_num_notes(diag: Diagnostic) -> usize; #[link_name = "mlirDiagnosticGetNote"] fn mlir_diagnostic_get_note(diag: Diagnostic, index: usize) -> Diagnostic; #[link_name = "mlirDiagnosticPrint"] fn mlir_diagnostic_print(diag: Diagnostic, callback: MlirStringCallback, userdata: *mut c_void); #[link_name = "mlirDiagnosticGetFileLineCol"] fn mlir_diagnostic_get_file_line_col(diag: Diagnostic) -> FileLineColLoc; }
use crate::interfaces::{Address, OldAddress, Value}; use chain_impl_mockchain::{ certificate, legacy::UtxoDeclaration, message::Message, transaction::{AuthenticatedTransaction, NoExtra, Output, Transaction}, }; use serde::{Deserialize, Deserializer, Serialize, Serializer}; #[derive(Clone, Serialize, Deserialize)] #[serde(rename_all = "snake_case", deny_unknown_fields)] pub enum Initial { Fund(Vec<InitialUTxO>), Cert(Certificate), LegacyFund(Vec<LegacyUTxO>), } #[derive(Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct InitialUTxO { pub address: Address, pub value: Value, } #[derive(Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct LegacyUTxO { pub address: OldAddress, pub value: Value, } #[derive(Clone, Debug)] pub struct Certificate(certificate::Certificate); /* ------------------- Serde ----------------------------------------------- */ impl Serialize for Certificate { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { use bech32::{Bech32, ToBase32 as _}; use chain_core::property::Serialize as _; use serde::ser::Error as _; let bytes = self.0.serialize_as_vec().map_err(S::Error::custom)?; let bech32 = Bech32::new("cert".to_string(), bytes.to_base32()).map_err(S::Error::custom)?; format!("{}", bech32).serialize(serializer) } } impl<'de> Deserialize<'de> for Certificate { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { use bech32::{Bech32, FromBase32 as _}; use chain_core::mempack::{ReadBuf, Readable as _}; use serde::de::Error as _; let bech32_str = String::deserialize(deserializer)?; let bech32: Bech32 = bech32_str.parse().map_err(D::Error::custom)?; if bech32.hrp() != "cert" { return Err(D::Error::custom(format!( "Expecting certificate in bech32, with HRP 'cert'" ))); } let bytes: Vec<u8> = Vec::from_base32(bech32.data()).map_err(D::Error::custom)?; let mut buf = ReadBuf::from(&bytes); certificate::Certificate::read(&mut buf) .map_err(D::Error::custom) .map(Certificate) } } custom_error! {pub Error FirstBlock0MessageNotInit = "first message of block 0 is not initial", Block0MessageUnexpected = "non-first message of block 0 has unexpected type", InitUtxoHasInput = "initial UTXO has input", } pub fn try_initials_vec_from_messages<'a>( messages: impl Iterator<Item = &'a Message>, ) -> Result<Vec<Initial>, Error> { let mut inits = Vec::new(); for message in messages { match message { Message::Transaction(tx) => try_extend_inits_with_tx(&mut inits, tx)?, Message::Certificate(tx) => extend_inits_with_cert(&mut inits, tx), Message::OldUtxoDeclaration(utxo) => extend_inits_with_legacy_utxo(&mut inits, utxo), _ => return Err(Error::Block0MessageUnexpected), } } Ok(inits) } fn try_extend_inits_with_tx( initials: &mut Vec<Initial>, tx: &AuthenticatedTransaction<chain_addr::Address, NoExtra>, ) -> Result<(), Error> { if !tx.transaction.inputs.is_empty() { return Err(Error::InitUtxoHasInput); } let inits_iter = tx.transaction.outputs.iter().map(|output| InitialUTxO { address: output.address.clone().into(), value: output.value.into(), }); initials.push(Initial::Fund(inits_iter.collect())); Ok(()) } fn extend_inits_with_cert( initials: &mut Vec<Initial>, tx: &AuthenticatedTransaction<chain_addr::Address, certificate::Certificate>, ) { let cert = Certificate(tx.transaction.extra.clone()); initials.push(Initial::Cert(cert)) } fn extend_inits_with_legacy_utxo(initials: &mut Vec<Initial>, utxo_decl: &UtxoDeclaration) { let inits_iter = utxo_decl.addrs.iter().map(|(address, value)| LegacyUTxO { address: address.clone().into(), value: value.clone().into(), }); initials.push(Initial::LegacyFund(inits_iter.collect())) } impl<'a> From<&'a Initial> for Message { fn from(initial: &'a Initial) -> Message { match initial { Initial::Fund(utxo) => pack_utxo_in_message(&utxo), Initial::Cert(cert) => cert.into(), Initial::LegacyFund(utxo) => pack_legacy_utxo_in_message(&utxo), } } } fn pack_utxo_in_message(v: &[InitialUTxO]) -> Message { let outputs = v .iter() .map(|utxo| Output { address: utxo.address.clone().into(), value: utxo.value.into(), }) .collect(); Message::Transaction(AuthenticatedTransaction { transaction: Transaction { inputs: vec![], outputs: outputs, extra: NoExtra, }, witnesses: vec![], }) } fn pack_legacy_utxo_in_message(v: &[LegacyUTxO]) -> Message { let addrs = v .iter() .map(|utxo| (utxo.address.clone().into(), utxo.value.into())) .collect(); Message::OldUtxoDeclaration(UtxoDeclaration { addrs: addrs }) } impl<'a> From<&'a Certificate> for Message { fn from(utxo: &'a Certificate) -> Message { Message::Certificate(AuthenticatedTransaction { transaction: Transaction { inputs: vec![], outputs: vec![], extra: utxo.0.clone(), }, witnesses: vec![], }) } } /* pub fn documented_example(now: std::time::SystemTime) -> String { let secs = now .duration_since(std::time::SystemTime::UNIX_EPOCH) .unwrap_or_default() .as_secs(); let sk: SecretKey<Ed25519Extended> = SecretKey::generate(&mut ChaChaRng::from_seed([0; 32])); let pk: PublicKey<Ed25519> = sk.to_public(); let leader_1: KeyPair<Ed25519> = KeyPair::generate(&mut ChaChaRng::from_seed([1; 32])); let leader_2: KeyPair<Ed25519> = KeyPair::generate(&mut ChaChaRng::from_seed([2; 32])); let initial_funds_address = Address(Discrimination::Test, Kind::Single(pk)); let initial_funds_address = AddressReadable::from_address(&initial_funds_address).to_string(); let leader_1_pk = leader_1.public_key().to_bech32_str(); let leader_2_pk = leader_2.public_key().to_bech32_str(); format!( include_str!("DOCUMENTED_EXAMPLE.yaml"), now = secs, leader_1 = leader_1_pk, leader_2 = leader_2_pk, initial_funds_address = initial_funds_address ) } #[cfg(test)] mod test { use super::*; use serde_yaml; #[test] fn conversion_to_and_from_message_preserves_data() { let sk: SecretKey<Ed25519Extended> = SecretKey::generate(&mut ChaChaRng::from_seed([0; 32])); let pk: PublicKey<Ed25519> = sk.to_public(); let leader_1: KeyPair<Ed25519> = KeyPair::generate(&mut ChaChaRng::from_seed([1; 32])); let leader_2: KeyPair<Ed25519> = KeyPair::generate(&mut ChaChaRng::from_seed([2; 32])); let initial_funds_address = Address(Discrimination::Test, Kind::Single(pk)); let initial_funds_address = AddressReadable::from_address(&initial_funds_address).to_string(); let leader_1_pk = leader_1.public_key().to_bech32_str(); let leader_2_pk = leader_2.public_key().to_bech32_str(); let genesis_yaml = format!(r#" --- blockchain_configuration: block0_date: 123456789 discrimination: test block0_consensus: bft slots_per_epoch: 5 slot_duration: 15 epoch_stability_depth: 10 consensus_leader_ids: - {} - {} consensus_genesis_praos_active_slot_coeff: "0.444" max_number_of_transactions_per_block: 255 bft_slots_ratio: "0.222" linear_fees: coefficient: 1 constant: 2 certificate: 4 kes_update_speed: 43200 initial: - cert: cert1qgqqqqqqqqqqqqqqqqqqq0p5avfqqmgurpe7s9k7933q0wj420jl5xqvx8lywcu5jcr7fwqa9qmdn93q4nm7c4fsay3mzeqgq3c0slnut9kns08yn2qn80famup7nvgtfuyszqzqrd4lxlt5ylplfu76p8f6ks0ggprzatp2c8rn6ev3hn9dgr38tzful4h0udlwa0536vyrrug7af9ujmrr869afs0yw9gj5x7z24l8sps3zzcmv - fund: - address: {} value: 10000"#, leader_1_pk, leader_2_pk, initial_funds_address); let genesis: Genesis = serde_yaml::from_str(genesis_yaml.as_str()).expect("Failed to deserialize YAML"); let block = genesis.to_block(); let new_genesis = Genesis::from_block(&block).expect("Failed to build genesis"); let new_genesis_yaml = serde_yaml::to_string(&new_genesis).expect("Failed to serialize YAML"); assert_eq!( genesis_yaml.trim(), new_genesis_yaml, "\nGenesis YAML has changed after conversions:\n{}\n", new_genesis_yaml ); } } */
use actix_web::{fs, Application}; use actix_web::middleware::Logger; use api::State; pub fn app(state: State) -> Application<State> { Application::with_state(state) .middleware(Logger::default()) .handler( "/", fs::StaticFiles::new("/www/", false).index_file("index.html"), ) }
use crate::{Cache, Flags, HashChain, Vm}; use std::sync::Arc; #[test] fn compute_hash() { let mut flags = Flags::recommended(); flags.set_full_mem(false); let cache = Arc::new(Cache::new(flags, &[0; 32], 16).unwrap()); let mut vm = Vm::new(cache).unwrap(); let hash = vm.hash(b"hello world"); assert_eq!( &hex::encode(hash), "f7956d0189fd2f6ca8f6a568447240b19cc381c37a203385dc3f2a8fbd567158", ); } #[test] fn compute_hash_chain() { let mut flags = Flags::recommended(); flags.set_full_mem(false); let cache = Arc::new(Cache::new(flags, &[0; 32], 16).unwrap()); let mut vm = Vm::new(cache).unwrap(); let mut chain = HashChain::new(&mut vm, b"hello world"); let hash0 = chain.next(b"foobar"); assert_eq!( &hex::encode(hash0), "f7956d0189fd2f6ca8f6a568447240b19cc381c37a203385dc3f2a8fbd567158", ); let hash1 = chain.last(); assert_eq!( &hex::encode(hash1), "d3337885b272abc0b44d8d23056e2ba64e095bc1bc3b195bd09d49089e14f1d2", ); }
use cpu::CPU; pub fn nop() -> u8 { 4 } pub fn hlt(cpu: &mut CPU) -> u8 { cpu.exit = true; 7 }
// Copyright 2020-2021, The Tremor Team // // 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. // mod test { <- this is for safety.sh #![allow(clippy::float_cmp)] use crate::op::prelude::trickle::window::{Actions, Trait}; use crate::query::window_decl_to_impl; use crate::EventId; use super::*; use tremor_script::ast::{Stmt, WindowDecl}; use tremor_script::{ast::Consts, Value}; use tremor_script::{ ast::{self, Ident, ImutExpr, Literal}, path::ModulePath, }; use tremor_value::literal; fn test_target<'test>() -> ast::ImutExpr<'test> { let target: ast::ImutExpr<'test> = ImutExpr::from(ast::Literal { mid: 0, value: Value::from(42), }); target } fn test_stmt(target: ast::ImutExpr) -> ast::Select { tremor_script::ast::Select { mid: 0, from: (Ident::from("in"), Ident::from("out")), into: (Ident::from("out"), Ident::from("in")), target, maybe_where: Some(ImutExpr::from(ast::Literal { mid: 0, value: Value::from(true), })), windows: vec![], maybe_group_by: None, maybe_having: None, } } fn test_query(stmt: ast::Stmt) -> ast::Query { ast::Query { stmts: vec![stmt.clone()], node_meta: ast::NodeMetas::new(Vec::new()), windows: HashMap::new(), scripts: HashMap::new(), operators: HashMap::new(), config: HashMap::new(), } } fn ingest_ns(s: u64) -> u64 { s * 1_000_000_000 } fn test_event(s: u64) -> Event { Event { id: (0, 0, s).into(), ingest_ns: ingest_ns(s), data: literal!({ "h2g2" : 42, }) .into(), ..Event::default() } } fn test_event_tx(s: u64, transactional: bool, group: u64) -> Event { Event { id: (0, 0, s).into(), ingest_ns: s + 100, data: literal!({ "group": group, "s": s }).into(), transactional, ..Event::default() } } fn test_select(uid: u64, stmt: srs::Stmt) -> Result<Select> { let windows = vec![ ( "w15s".into(), window::TumblingOnTime { max_groups: window::Impl::DEFAULT_MAX_GROUPS, interval: 15_000_000_000, ..Default::default() } .into(), ), ( "w30s".into(), window::TumblingOnTime { max_groups: window::Impl::DEFAULT_MAX_GROUPS, interval: 30_000_000_000, ..Default::default() } .into(), ), ]; let id = "select".to_string(); Select::with_stmt(uid, id, windows, &stmt) } fn try_enqueue(op: &mut Select, event: Event) -> Result<Option<(Cow<'static, str>, Event)>> { let mut state = Value::null(); let mut action = op.on_event(0, "in", &mut state, event)?; let first = action.events.pop(); if action.events.is_empty() { Ok(first) } else { Ok(None) } } fn try_enqueue_two( op: &mut Select, event: Event, ) -> Result<Option<[(Cow<'static, str>, Event); 2]>> { let mut state = Value::null(); let mut action = op.on_event(0, "in", &mut state, event)?; let r = action .events .pop() .and_then(|second| Some([action.events.pop()?, second])); if action.events.is_empty() { Ok(r) } else { Ok(None) } } fn parse_query(file_name: String, query: &str) -> Result<crate::op::trickle::select::Select> { let reg = tremor_script::registry(); let aggr_reg = tremor_script::aggr_registry(); let module_path = tremor_script::path::load(); let cus = vec![]; let query = tremor_script::query::Query::parse(&module_path, &file_name, query, cus, &reg, &aggr_reg) .map_err(tremor_script::errors::CompilerError::error)?; let stmt = srs::Stmt::try_new_from_query(&query.query, |q| { q.stmts .first() .cloned() .ok_or_else(|| Error::from("Invalid query")) })?; Ok(test_select(1, stmt)?) } #[test] fn test_sum() -> Result<()> { let mut op = parse_query( "test.trickle".to_string(), "select aggr::stats::sum(event.h2g2) from in[w15s, w30s] into out;", )?; assert!(try_enqueue(&mut op, test_event(0))?.is_none()); assert!(try_enqueue(&mut op, test_event(1))?.is_none()); let (out, event) = try_enqueue(&mut op, test_event(15))?.expect("no event emitted after aggregation"); assert_eq!("out", out); assert_eq!(*event.data.suffix().value(), 84.0); Ok(()) } #[test] fn test_count() -> Result<()> { let mut op = parse_query( "test.trickle".to_string(), "select aggr::stats::count() from in[w15s, w30s] into out;", )?; assert!(try_enqueue(&mut op, test_event(0))?.is_none()); assert!(try_enqueue(&mut op, test_event(1))?.is_none()); let (out, event) = try_enqueue(&mut op, test_event(15))?.expect("no event"); assert_eq!("out", out); assert_eq!(*event.data.suffix().value(), 2); Ok(()) } fn select_stmt_from_query(query_str: &str) -> Result<Select> { let reg = tremor_script::registry(); let aggr_reg = tremor_script::aggr_registry(); let module_path = tremor_script::path::load(); let cus = vec![]; let query = tremor_script::query::Query::parse(&module_path, "fake", query_str, cus, &reg, &aggr_reg) .map_err(tremor_script::errors::CompilerError::error)?; let window_decls: Vec<WindowDecl<'_>> = query .suffix() .stmts .iter() .filter_map(|stmt| match stmt { Stmt::WindowDecl(wd) => Some(wd.as_ref().clone()), _ => None, }) .collect(); let stmt = srs::Stmt::try_new_from_query(&query.query, |q| { q.stmts .iter() .find(|stmt| matches!(*stmt, Stmt::Select(_))) .cloned() .ok_or_else(|| Error::from("Invalid query, expected only 1 select statement")) })?; let windows: Vec<(String, window::Impl)> = window_decls .iter() .enumerate() .map(|(i, window_decl)| { ( i.to_string(), window_decl_to_impl(window_decl).unwrap(), // yes, indeed! ) }) .collect(); let id = "select".to_string(); Ok(Select::with_stmt(42, id, windows, &stmt)?) } fn test_tick(ns: u64) -> Event { Event { id: EventId::new(1, 1, ns), kind: Some(SignalKind::Tick), ingest_ns: ns, ..Event::default() } } #[test] fn select_single_win_with_script_on_signal() -> Result<()> { let mut select = select_stmt_from_query( r#" define tumbling window window1 with interval = 5 script event.time end; select aggr::stats::count() from in[window1] group by event.g into out having event > 0; "#, )?; let uid = 42; let mut state = Value::null(); let mut tick1 = test_tick(1); let mut eis = select.on_signal(uid, &mut state, &mut tick1)?; assert!(eis.insights.is_empty()); assert_eq!(0, eis.events.len()); let event = Event { id: (1, 1, 300).into(), ingest_ns: 1_000, data: literal!({ "time" : 4, "g": "group" }) .into(), ..Event::default() }; eis = select.on_event(uid, "in", &mut state, event)?; assert!(eis.insights.is_empty()); assert_eq!(0, eis.events.len()); // no emit on signal, although window interval would be passed let mut tick2 = test_tick(10); eis = select.on_signal(uid, &mut state, &mut tick2)?; assert!(eis.insights.is_empty()); assert_eq!(0, eis.events.len()); // only emit on event let event = Event { id: (1, 1, 300).into(), ingest_ns: 3_000, data: literal!({ "time" : 11, "g": "group" }) .into(), ..Event::default() }; eis = select.on_event(uid, "IN", &mut state, event)?; assert!(eis.insights.is_empty()); assert_eq!(1, eis.events.len()); assert_eq!("1", sorted_serialize(eis.events[0].1.data.parts().0)?); Ok(()) } #[test] fn select_single_win_on_signal() -> Result<()> { let mut select = select_stmt_from_query( r#" define tumbling window window1 with interval = 2 end; select aggr::win::collect_flattened(event) from in[window1] group by event.g into out; "#, )?; let uid = 42; let mut state = Value::null(); let mut tick1 = test_tick(1); let mut eis = select.on_signal(uid, &mut state, &mut tick1)?; assert!(eis.insights.is_empty()); assert_eq!(0, eis.events.len()); let event = Event { id: (1, 1, 300).into(), ingest_ns: 2, data: literal!({ "g": "group" }) .into(), ..Event::default() }; eis = select.on_event(uid, "IN", &mut state, event)?; assert!(eis.insights.is_empty()); assert_eq!(0, eis.events.len()); // no emit yet let mut tick2 = test_tick(3); eis = select.on_signal(uid, &mut state, &mut tick2)?; assert!(eis.insights.is_empty()); assert_eq!(0, eis.events.len()); // now emit let mut tick3 = test_tick(4); eis = select.on_signal(uid, &mut state, &mut tick3)?; assert!(eis.insights.is_empty()); assert_eq!(1, eis.events.len()); assert_eq!( r#"[{"g":"group"}]"#, sorted_serialize(eis.events[0].1.data.parts().0)? ); assert_eq!(false, eis.events[0].1.transactional); Ok(()) } #[test] fn select_multiple_wins_on_signal() -> Result<()> { let mut select = select_stmt_from_query( r#" define tumbling window window1 with interval = 100 end; define tumbling window window2 with size = 2 end; select aggr::win::collect_flattened(event) from in[window1, window2] group by event.cat into out; "#, )?; let uid = 42; let mut state = Value::null(); let mut tick1 = test_tick(1); let mut eis = select.on_signal(uid, &mut state, &mut tick1)?; assert!(eis.insights.is_empty()); assert_eq!(0, eis.events.len()); let mut tick2 = test_tick(100); eis = select.on_signal(uid, &mut state, &mut tick2)?; assert!(eis.insights.is_empty()); assert_eq!(0, eis.events.len()); // we have no groups, so no emit yet let mut tick3 = test_tick(201); eis = select.on_signal(uid, &mut state, &mut tick3)?; assert!(eis.insights.is_empty()); assert_eq!(0, eis.events.len()); // insert first event let event = Event { id: (1, 1, 300).into(), ingest_ns: 300, data: literal!({ "cat" : 42, }) .into(), transactional: true, ..Event::default() }; eis = select.on_event(uid, "in", &mut state, event)?; assert!(eis.insights.is_empty()); assert_eq!(0, eis.events.len()); // finish the window with the next tick let mut tick4 = test_tick(401); eis = select.on_signal(uid, &mut state, &mut tick4)?; assert!(eis.insights.is_empty()); assert_eq!(1, eis.events.len()); let (_port, event) = dbg!(eis).events.remove(0); assert_eq!(r#"[{"cat":42}]"#, sorted_serialize(event.data.parts().0)?); assert_eq!(true, event.transactional); let mut tick5 = test_tick(499); eis = select.on_signal(uid, &mut state, &mut tick5)?; assert!(eis.insights.is_empty()); assert_eq!(0, eis.events.len()); Ok(()) } #[test] fn test_transactional_single_window() -> Result<()> { let mut op = select_stmt_from_query( r#" define tumbling window w2 with size = 2 end; select aggr::stats::count() from in[w2] into out; "#, )?; let mut state = Value::null(); let event1 = test_event_tx(0, false, 0); let id1 = event1.id.clone(); let res = op.on_event(0, "in", &mut state, event1)?; assert!(res.events.is_empty()); let event2 = test_event_tx(1, true, 0); let id2 = event2.id.clone(); let mut res = op.on_event(0, "in", &mut state, event2)?; assert_eq!(1, res.events.len()); let (_, event) = res.events.pop().unwrap(); dbg!(&event); assert_eq!(true, event.transactional); assert_eq!(true, event.id.is_tracking(&id1)); assert_eq!(true, event.id.is_tracking(&id2)); let event3 = test_event_tx(2, false, 0); let id3 = event3.id.clone(); let res = op.on_event(0, "in", &mut state, event3)?; assert!(res.events.is_empty()); let event4 = test_event_tx(3, false, 0); let id4 = event4.id.clone(); let mut res = op.on_event(0, "in", &mut state, event4)?; assert_eq!(1, res.events.len()); let (_, event) = res.events.pop().unwrap(); assert_eq!(false, event.transactional); assert_eq!(true, event.id.is_tracking(&id3)); assert_eq!(true, event.id.is_tracking(&id4)); Ok(()) } #[test] fn test_transactional_multiple_windows() -> Result<()> { let mut op = select_stmt_from_query( r#" define tumbling window w2_1 with size = 2 end; define tumbling window w2_2 with size = 2 end; select aggr::win::collect_flattened(event) from in[w2_1, w2_2] group by set(event["group"]) into out; "#, )?; let mut state = Value::null(); let event0 = test_event_tx(0, true, 0); let id0 = event0.id.clone(); let res = op.on_event(0, "in", &mut state, event0)?; assert_eq!(0, res.len()); let event1 = test_event_tx(1, false, 1); let id1 = event1.id.clone(); let res = op.on_event(0, "in", &mut state, event1)?; assert_eq!(0, res.len()); let event2 = test_event_tx(2, false, 0); let id2 = event2.id.clone(); let mut res = op.on_event(0, "in", &mut state, event2)?; assert_eq!(1, res.len()); let (_, event) = res.events.pop().unwrap(); assert_eq!(true, event.transactional); assert_eq!(true, event.id.is_tracking(&id0)); assert_eq!(true, event.id.is_tracking(&id2)); let event3 = test_event_tx(3, false, 1); let id3 = event3.id.clone(); let mut res = op.on_event(0, "in", &mut state, event3)?; assert_eq!(1, res.len()); let (_, event) = res.events.remove(0); assert_eq!(false, event.transactional); assert_eq!(true, event.id.is_tracking(&id1)); assert_eq!(true, event.id.is_tracking(&id3)); let event4 = test_event_tx(4, false, 0); let id4 = event4.id.clone(); let res = op.on_event(0, "in", &mut state, event4)?; assert_eq!(0, res.len()); let event5 = test_event_tx(5, false, 0); let id5 = event5.id.clone(); let mut res = op.on_event(0, "in", &mut state, event5)?; assert_eq!(2, res.len()); // first event from event5 and event6 - none of the source events are transactional let (_, event_w1) = res.events.remove(0); assert!(!event_w1.transactional); assert!(event_w1.id.is_tracking(&id4)); assert!(event_w1.id.is_tracking(&id5)); let (_, event_w2) = res.events.remove(0); assert!(event_w2.transactional); assert!(event_w2.id.is_tracking(&id0)); assert!(event_w2.id.is_tracking(&id2)); assert!(event_w2.id.is_tracking(&id4)); assert!(event_w2.id.is_tracking(&id5)); Ok(()) } #[test] fn count_tilt() -> Result<()> { // Windows are 15s and 30s let mut op = select_stmt_from_query( r#" define tumbling window w15s with interval = 15 * 1000000000 end; define tumbling window w30s with interval = 30 * 1000000000 end; select aggr::stats::count() from in [w15s, w30s] into out; "#, )?; // Insert two events prior to 15 assert!(try_enqueue(&mut op, test_event(0))?.is_none()); assert!(try_enqueue(&mut op, test_event(1))?.is_none()); // Add one event at 15, this flushes the prior two and set this to one. // This is the first time the second frame sees an event so it's timer // starts at 15. let (out, event) = try_enqueue(&mut op, test_event(15))?.expect("no event 1"); assert_eq!("out", out); assert_eq!(*event.data.suffix().value(), 2); // Add another event prior to 30 assert!(try_enqueue(&mut op, test_event(16))?.is_none()); // This emits only the initial event since the rollup // will only be emitted once it gets the first event // of the next window let (out, event) = try_enqueue(&mut op, test_event(30))?.expect("no event 2"); assert_eq!("out", out); assert_eq!(*event.data.suffix().value(), 2); // Add another event prior to 45 to the first window assert!(try_enqueue(&mut op, test_event(31))?.is_none()); // At 45 the 15s window emits the rollup with the previous data let [(out1, event1), (out2, event2)] = try_enqueue_two(&mut op, test_event(45))?.expect("no event 3"); assert_eq!("out", out1); assert_eq!("out", out2); assert_eq!(*event1.data.suffix().value(), 2); assert_eq!(*event2.data.suffix().value(), 4); assert!(try_enqueue(&mut op, test_event(46))?.is_none()); // Add 60 only the 15s window emits let (out, event) = try_enqueue(&mut op, test_event(60))?.expect("no event 4"); assert_eq!("out", out); assert_eq!(*event.data.suffix().value(), 2); Ok(()) } #[test] fn select_nowin_nogrp_nowhr_nohav() -> Result<()> { let target = test_target(); let stmt_ast = test_stmt(target); let stmt_ast = test_select_stmt(stmt_ast); let script = "fake".to_string(); let query = srs::Query::try_new::<Error, _>(script, |_| Ok(test_query(stmt_ast.clone())))?; let stmt = srs::Stmt::try_new_from_query::<Error, _>(&query, |_| Ok(stmt_ast))?; let mut op = test_select(1, stmt)?; assert!(try_enqueue(&mut op, test_event(0))?.is_none()); assert!(try_enqueue(&mut op, test_event(1))?.is_none()); let (out, event) = try_enqueue(&mut op, test_event(15))?.expect("no event"); assert_eq!("out", out); assert_eq!(*event.data.suffix().value(), 42); Ok(()) } #[test] fn select_nowin_nogrp_whrt_nohav() -> Result<()> { let target = test_target(); let mut stmt_ast = test_stmt(target); stmt_ast.maybe_where = Some(ImutExpr::from(ast::Literal { mid: 0, value: Value::from(true), })); let stmt_ast = test_select_stmt(stmt_ast); let script = "fake".to_string(); let query = srs::Query::try_new::<Error, _>(script, |_| Ok(test_query(stmt_ast.clone())))?; let stmt = srs::Stmt::try_new_from_query::<Error, _>(&query, |_| Ok(stmt_ast))?; let mut op = test_select(2, stmt)?; assert!(try_enqueue(&mut op, test_event(0))?.is_none()); let (out, event) = try_enqueue(&mut op, test_event(15))?.expect("no event"); assert_eq!("out", out); assert_eq!(*event.data.suffix().value(), 42); Ok(()) } #[test] fn select_nowin_nogrp_whrf_nohav() -> Result<()> { let target = test_target(); let mut stmt_ast = test_stmt(target); let script = "fake".to_string(); stmt_ast.maybe_where = Some(ImutExpr::from(ast::Literal { mid: 0, value: Value::from(false), })); let stmt_ast = test_select_stmt(stmt_ast); let query = srs::Query::try_new::<Error, _>(script, |_| Ok(test_query(stmt_ast.clone())))?; let stmt = srs::Stmt::try_new_from_query::<Error, _>(&query, |_| Ok(stmt_ast))?; let mut op = test_select(3, stmt)?; let next = try_enqueue(&mut op, test_event(0))?; assert_eq!(None, next); Ok(()) } #[test] fn select_nowin_nogrp_whrbad_nohav() -> Result<()> { let target = test_target(); let mut stmt_ast = test_stmt(target); stmt_ast.maybe_where = Some(ImutExpr::from(ast::Literal { mid: 0, value: Value::from("snot"), })); let stmt_ast = test_select_stmt(stmt_ast); let script = "fake".to_string(); let query = srs::Query::try_new::<Error, _>(script, |_| Ok(test_query(stmt_ast.clone())))?; let stmt = srs::Stmt::try_new_from_query::<Error, _>(&query, |_| Ok(stmt_ast))?; let mut op = test_select(4, stmt)?; assert!(try_enqueue(&mut op, test_event(0)).is_err()); Ok(()) } #[test] fn select_nowin_nogrp_whrt_havt() -> Result<()> { let target = test_target(); let mut stmt_ast = test_stmt(target); stmt_ast.maybe_where = Some(ImutExpr::from(ast::Literal { mid: 0, value: Value::from(true), })); stmt_ast.maybe_having = Some(ImutExpr::from(ast::Literal { mid: 0, value: Value::from(true), })); let stmt_ast = test_select_stmt(stmt_ast); let script = "fake".to_string(); let query = srs::Query::try_new::<Error, _>(script, |_| Ok(test_query(stmt_ast.clone())))?; let stmt = srs::Stmt::try_new_from_query::<Error, _>(&query, |_| Ok(stmt_ast))?; let mut op = test_select(5, stmt)?; let event = test_event(0); assert!(try_enqueue(&mut op, event)?.is_none()); let event = test_event(15); let (out, event) = try_enqueue(&mut op, event)?.expect("no event"); assert_eq!("out", out); assert_eq!(*event.data.suffix().value(), 42); Ok(()) } #[test] fn select_nowin_nogrp_whrt_havf() -> Result<()> { let target = test_target(); let mut stmt_ast = test_stmt(target); stmt_ast.maybe_where = Some(ImutExpr::from(ast::Literal { mid: 0, value: Value::from(true), })); stmt_ast.maybe_having = Some(ImutExpr::from(ast::Literal { mid: 0, value: Value::from(false), })); let stmt_ast = test_select_stmt(stmt_ast); let script = "fake".to_string(); let query = srs::Query::try_new::<Error, _>(script, |_| Ok(test_query(stmt_ast.clone())))?; let stmt = srs::Stmt::try_new_from_query::<Error, _>(&query, |_| Ok(stmt_ast))?; let mut op = test_select(6, stmt)?; let event = test_event(0); let next = try_enqueue(&mut op, event)?; assert_eq!(None, next); Ok(()) } fn test_select_stmt(stmt: tremor_script::ast::Select) -> tremor_script::ast::Stmt { let aggregates = vec![]; ast::Stmt::Select(SelectStmt { stmt: Box::new(stmt), aggregates, consts: Consts::default(), locals: 0, node_meta: ast::NodeMetas::new(vec![]), }) } #[test] fn select_nowin_nogrp_whrt_havbad() -> Result<()> { use halfbrown::hashmap; let target = test_target(); let mut stmt_ast = test_stmt(target); stmt_ast.maybe_where = Some(ImutExpr::from(ast::Literal { mid: 0, value: Value::from(true), })); stmt_ast.maybe_having = Some(ImutExpr::from(Literal { mid: 0, value: Value::from(hashmap! { "snot".into() => "badger".into(), }), })); let stmt_ast = test_select_stmt(stmt_ast); let script = "fake".to_string(); let query = srs::Query::try_new::<Error, _>(script, |_| Ok(test_query(stmt_ast.clone())))?; let stmt = srs::Stmt::try_new_from_query::<Error, _>(&query, |_| Ok(stmt_ast))?; let mut op = test_select(7, stmt)?; let event = test_event(0); let next = try_enqueue(&mut op, event)?; assert_eq!(None, next); Ok(()) } #[test] fn tumbling_window_on_time_emit() -> Result<()> { // interval = 10 seconds let mut window = window::TumblingOnTime::from_stmt( 10 * 1_000_000_000, window::Impl::DEFAULT_MAX_GROUPS, None, ); let vm = literal!({ "h2g2" : 42, }) .into(); assert_eq!( Actions { include: false, emit: false }, window.on_event(&vm, ingest_ns(5), &None)? ); assert_eq!( Actions::all_false(), window.on_event(&vm, ingest_ns(10), &None)? ); assert_eq!( Actions { include: false, emit: true }, window.on_event(&vm, ingest_ns(15), &None)? // exactly on time ); assert_eq!( Actions { include: false, emit: true }, window.on_event(&vm, ingest_ns(26), &None)? // exactly on time ); Ok(()) } #[test] fn tumbling_window_on_time_from_script_emit() -> Result<()> { // create a WindowDecl with a custom script let reg = Registry::default(); let aggr_reg = AggrRegistry::default(); let module_path = ModulePath::load(); let q = tremor_script::query::Query::parse( &module_path, "bar", r#" define tumbling window my_window with interval = 1000000000 # 1 second script event.timestamp end;"#, vec![], &reg, &aggr_reg, ) .map_err(|ce| ce.error)?; let window_decl = match q.query.suffix().stmts.first() { Some(Stmt::WindowDecl(decl)) => decl.as_ref(), other => return Err(format!("Didnt get a window decl, got: {:?}", other).into()), }; let mut params = halfbrown::HashMap::with_capacity(1); params.insert("size".to_string(), Value::from(3)); let interval = window_decl .params .get("interval") .and_then(Value::as_u64) .ok_or(Error::from("no interval found"))?; let mut window = window::TumblingOnTime::from_stmt( interval, window::Impl::DEFAULT_MAX_GROUPS, Some(&window_decl), ); let json1 = literal!({ "timestamp": 1_000_000_000 }) .into(); assert_eq!( Actions { include: false, emit: false }, window.on_event(&json1, 1, &None)? ); let json2 = literal!({ "timestamp": 1_999_999_999 }) .into(); assert_eq!(Actions::all_false(), window.on_event(&json2, 2, &None)?); let json3 = literal!({ "timestamp": 2_000_000_000 }) .into(); // ignoring on_tick as we have a script assert_eq!(Actions::all_false(), window.on_tick(2_000_000_000)); assert_eq!( Actions { include: false, emit: true }, window.on_event(&json3, 3, &None)? ); Ok(()) } #[test] fn tumbling_window_on_time_on_tick() -> Result<()> { let mut window = window::TumblingOnTime::from_stmt(100, window::Impl::DEFAULT_MAX_GROUPS, None); assert_eq!( Actions { include: false, emit: false }, window.on_tick(0) ); assert_eq!(Actions::all_false(), window.on_tick(99)); assert_eq!( Actions { include: false, emit: true // we delete windows that do not have content so this is fine }, window.on_tick(100) ); assert_eq!( Actions::all_false(), window.on_event(&ValueAndMeta::default(), 101, &None)? ); assert_eq!(Actions::all_false(), window.on_tick(102)); assert_eq!( Actions { include: false, emit: true // we had an event yeah }, window.on_tick(200) ); Ok(()) } #[test] fn tumbling_window_on_time_emit_empty_windows() -> Result<()> { let mut window = window::TumblingOnTime::from_stmt(100, window::Impl::DEFAULT_MAX_GROUPS, None); assert_eq!( Actions { include: false, emit: false }, window.on_tick(0) ); assert_eq!(Actions::all_false(), window.on_tick(99)); assert_eq!( Actions { include: false, emit: true // we **DO** emit even if we had no event }, window.on_tick(100) ); assert_eq!( Actions::all_false(), window.on_event(&ValueAndMeta::default(), 101, &None)? ); assert_eq!(Actions::all_false(), window.on_tick(102)); assert_eq!( Actions { include: false, emit: true // we had an event yeah }, window.on_tick(200) ); Ok(()) } #[test] fn no_window_emit() -> Result<()> { let mut window = window::No::default(); let vm = literal!({ "h2g2" : 42, }) .into(); assert_eq!( Actions::all_true(), window.on_event(&vm, ingest_ns(0), &None)? ); assert_eq!(Actions::all_false(), window.on_tick(0)); assert_eq!( Actions::all_true(), window.on_event(&vm, ingest_ns(1), &None)? ); assert_eq!(Actions::all_false(), window.on_tick(1)); Ok(()) } #[test] fn tumbling_window_on_number_emit() -> Result<()> { let mut window = window::TumblingOnNumber::from_stmt(3, window::Impl::DEFAULT_MAX_GROUPS, None); let vm = literal!({ "h2g2" : 42, }) .into(); // do not emit yet assert_eq!( Actions::all_false(), window.on_event(&vm, ingest_ns(0), &None)? ); assert_eq!(Actions::all_false(), window.on_tick(1_000_000_000)); // do not emit yet assert_eq!( Actions::all_false(), window.on_event(&vm, ingest_ns(1), &None)? ); assert_eq!(Actions::all_false(), window.on_tick(2_000_000_000)); // emit and open on the third event assert_eq!( Actions::all_true(), window.on_event(&vm, ingest_ns(2), &None)? ); // no emit here, next window assert_eq!( Actions::all_false(), window.on_event(&vm, ingest_ns(3), &None)? ); Ok(()) }
use std::{ffi::OsStr, time::Duration}; use async_fuse::FileAttr; use menmos_client::{Meta, Type}; use super::{build_attributes, Error, Result}; use crate::{constants, MenmosFS}; pub struct CreateReply { pub ttl: Duration, pub attrs: FileAttr, pub generation: u64, pub file_handle: u64, } impl MenmosFS { pub async fn create_impl(&self, parent: u64, name: &OsStr) -> Result<CreateReply> { log::info!("create i{}/{:?}", parent, &name); let str_name = name.to_string_lossy().to_string(); if let Some(blob_id) = self.name_to_blobid.get(&(parent, str_name)).await { if let Err(e) = self.client.delete(blob_id).await { log::error!("client error: {}", e); } } let parent_id = self .inode_to_blobid .get(&parent) .await .ok_or(Error::Forbidden)?; let str_name = name.to_string_lossy().to_string(); let meta = Meta::new(&str_name, Type::File).with_parent(parent_id); let blob_id = self.client.create_empty(meta.clone()).await.map_err(|e| { log::error!("client error: {}", e); Error::IOError })?; let ino = self.get_inode(&blob_id).await; self.inode_to_blobid.insert(ino, blob_id.clone()).await; self.name_to_blobid .insert((parent, str_name), blob_id) .await; Ok(CreateReply { ttl: constants::TTL, attrs: build_attributes(ino, &meta, 0o764), generation: 0, // TODO: Implement. file_handle: 0, }) } }
use goose::prelude::*; use serde::{de::DeserializeOwned, Deserialize}; use serde_json::json; use stark_hash::Felt; use crate::types::{ Block, ContractClass, FeeEstimate, StateUpdate, Transaction, TransactionReceipt, }; type MethodResult<T> = Result<T, Box<goose::goose::TransactionError>>; pub async fn get_block_by_number(user: &mut GooseUser, block_number: u64) -> MethodResult<Block> { post_jsonrpc_request( user, "starknet_getBlockWithTxHashes", json!({ "block_id": { "block_number": block_number } }), ) .await } pub async fn get_block_by_hash(user: &mut GooseUser, block_hash: Felt) -> MethodResult<Block> { post_jsonrpc_request( user, "starknet_getBlockWithTxHashes", json!({ "block_id": { "block_hash": block_hash } }), ) .await } pub async fn get_state_update(user: &mut GooseUser, block_hash: Felt) -> MethodResult<StateUpdate> { post_jsonrpc_request( user, "starknet_getStateUpdate", json!({ "block_id": { "block_hash": block_hash }}), ) .await } pub async fn get_transaction_by_hash( user: &mut GooseUser, hash: Felt, ) -> MethodResult<Transaction> { post_jsonrpc_request( user, "starknet_getTransactionByHash", json!({ "transaction_hash": hash }), ) .await } pub async fn get_transaction_by_block_hash_and_index( user: &mut GooseUser, block_hash: Felt, index: usize, ) -> MethodResult<Transaction> { post_jsonrpc_request( user, "starknet_getTransactionByBlockIdAndIndex", json!({ "block_id": {"block_hash": block_hash}, "index": index }), ) .await } pub async fn get_transaction_by_block_number_and_index( user: &mut GooseUser, block_number: u64, index: usize, ) -> MethodResult<Transaction> { post_jsonrpc_request( user, "starknet_getTransactionByBlockIdAndIndex", json!({ "block_id": {"block_number": block_number}, "index": index }), ) .await } pub async fn get_transaction_receipt_by_hash( user: &mut GooseUser, hash: Felt, ) -> MethodResult<TransactionReceipt> { post_jsonrpc_request( user, "starknet_getTransactionReceipt", json!({ "transaction_hash": hash }), ) .await } pub async fn get_block_transaction_count_by_hash( user: &mut GooseUser, hash: Felt, ) -> MethodResult<u64> { post_jsonrpc_request( user, "starknet_getBlockTransactionCount", json!({ "block_id": { "block_hash": hash } }), ) .await } pub async fn get_block_transaction_count_by_number( user: &mut GooseUser, number: u64, ) -> MethodResult<u64> { post_jsonrpc_request( user, "starknet_getBlockTransactionCount", json!({ "block_id": { "block_number": number } }), ) .await } pub async fn get_class( user: &mut GooseUser, block_hash: Felt, class_hash: Felt, ) -> MethodResult<ContractClass> { post_jsonrpc_request( user, "starknet_getClass", json!({ "block_id": { "block_hash": block_hash }, "class_hash": class_hash }), ) .await } pub async fn get_class_hash_at( user: &mut GooseUser, block_hash: Felt, contract_address: Felt, ) -> MethodResult<Felt> { post_jsonrpc_request( user, "starknet_getClassHashAt", json!({ "block_id": { "block_hash": block_hash }, "contract_address": contract_address }), ) .await } pub async fn get_class_at( user: &mut GooseUser, block_hash: Felt, contract_address: Felt, ) -> MethodResult<ContractClass> { post_jsonrpc_request( user, "starknet_getClassAt", json!({ "block_id": { "block_hash": block_hash }, "contract_address": contract_address }), ) .await } pub async fn block_number(user: &mut GooseUser) -> MethodResult<u64> { post_jsonrpc_request(user, "starknet_blockNumber", json!({})).await } pub async fn syncing(user: &mut GooseUser) -> MethodResult<serde_json::Value> { post_jsonrpc_request(user, "starknet_syncing", json!({})).await } pub async fn chain_id(user: &mut GooseUser) -> MethodResult<String> { post_jsonrpc_request(user, "starknet_chainId", json!({})).await } pub async fn get_events( user: &mut GooseUser, filter: EventFilter, ) -> MethodResult<GetEventsResult> { let from_block = block_number_to_block_id(filter.from_block); let to_block = block_number_to_block_id(filter.to_block); post_jsonrpc_request( user, "starknet_getEvents", json!({ "filter": { "from_block": from_block, "to_block": to_block, "address": filter.address, "keys": vec![filter.keys], "chunk_size": 1000, }}), ) .await } pub struct EventFilter { pub from_block: Option<u64>, pub to_block: Option<u64>, pub address: Option<Felt>, pub keys: Vec<Felt>, pub page_size: u64, pub page_number: u64, } #[derive(Clone, Debug, serde::Deserialize, PartialEq, Eq)] pub struct GetEventsResult { pub events: Vec<serde_json::Value>, pub continuation_token: Option<String>, } fn block_number_to_block_id(number: Option<u64>) -> serde_json::Value { match number { Some(number) => json!({ "block_number": number }), None => serde_json::Value::Null, } } pub async fn get_storage_at( user: &mut GooseUser, contract_address: Felt, key: Felt, block_hash: Felt, ) -> MethodResult<Felt> { post_jsonrpc_request( user, "starknet_getStorageAt", json!({ "contract_address": contract_address, "key": key, "block_id": {"block_hash": block_hash} }), ) .await } pub async fn call( user: &mut GooseUser, contract_address: Felt, call_data: &[&str], entry_point_selector: &str, at_block: Felt, ) -> MethodResult<Vec<String>> { post_jsonrpc_request( user, "starknet_call", json!({ "request": { "contract_address": contract_address, "calldata": call_data, "entry_point_selector": entry_point_selector, }, "block_id": {"block_hash": at_block}, }), ) .await } pub async fn estimate_fee_for_invoke( user: &mut GooseUser, contract_address: Felt, call_data: &[Felt], entry_point_selector: Felt, max_fee: Felt, at_block: Felt, ) -> MethodResult<FeeEstimate> { post_jsonrpc_request( user, "starknet_estimateFee", json!({ "request": [{ "type": "INVOKE", "version": "0x0", "max_fee": max_fee, "signature": [], "contract_address": contract_address, "calldata": call_data, "entry_point_selector": entry_point_selector, }], "block_id": {"block_hash": at_block} }), ) .await } async fn post_jsonrpc_request<T: DeserializeOwned>( user: &mut GooseUser, method: &str, params: serde_json::Value, ) -> MethodResult<T> { let request = jsonrpc_request(method, params); let response = user .post_json("/rpc/v0.3", &request) .await? .response .map_err(|e| Box::new(e.into()))?; #[derive(Deserialize)] struct TransactionReceiptResponse<T> { result: T, } let response: TransactionReceiptResponse<T> = response.json().await.map_err(|e| Box::new(e.into()))?; Ok(response.result) } fn jsonrpc_request(method: &str, params: serde_json::Value) -> serde_json::Value { json!({ "jsonrpc": "2.0", "id": "0", "method": method, "params": params, }) }
// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. pub fn serialize_synthetic_batch_execute_statement_input_body( input: &crate::input::BatchExecuteStatementInput, ) -> Result<smithy_http::body::SdkBody, serde_json::error::Error> { let body = crate::serializer::BatchExecuteStatementInputBody { statements: &input.statements, }; serde_json::to_vec(&body).map(smithy_http::body::SdkBody::from) } pub fn serialize_synthetic_batch_get_item_input_body( input: &crate::input::BatchGetItemInput, ) -> Result<smithy_http::body::SdkBody, serde_json::error::Error> { let body = crate::serializer::BatchGetItemInputBody { request_items: &input.request_items, return_consumed_capacity: &input.return_consumed_capacity, }; serde_json::to_vec(&body).map(smithy_http::body::SdkBody::from) } pub fn serialize_synthetic_batch_write_item_input_body( input: &crate::input::BatchWriteItemInput, ) -> Result<smithy_http::body::SdkBody, serde_json::error::Error> { let body = crate::serializer::BatchWriteItemInputBody { request_items: &input.request_items, return_consumed_capacity: &input.return_consumed_capacity, return_item_collection_metrics: &input.return_item_collection_metrics, }; serde_json::to_vec(&body).map(smithy_http::body::SdkBody::from) } pub fn serialize_synthetic_create_backup_input_body( input: &crate::input::CreateBackupInput, ) -> Result<smithy_http::body::SdkBody, serde_json::error::Error> { let body = crate::serializer::CreateBackupInputBody { table_name: &input.table_name, backup_name: &input.backup_name, }; serde_json::to_vec(&body).map(smithy_http::body::SdkBody::from) } pub fn serialize_synthetic_create_global_table_input_body( input: &crate::input::CreateGlobalTableInput, ) -> Result<smithy_http::body::SdkBody, serde_json::error::Error> { let body = crate::serializer::CreateGlobalTableInputBody { global_table_name: &input.global_table_name, replication_group: &input.replication_group, }; serde_json::to_vec(&body).map(smithy_http::body::SdkBody::from) } pub fn serialize_synthetic_create_table_input_body( input: &crate::input::CreateTableInput, ) -> Result<smithy_http::body::SdkBody, serde_json::error::Error> { let body = crate::serializer::CreateTableInputBody { attribute_definitions: &input.attribute_definitions, table_name: &input.table_name, key_schema: &input.key_schema, local_secondary_indexes: &input.local_secondary_indexes, global_secondary_indexes: &input.global_secondary_indexes, billing_mode: &input.billing_mode, provisioned_throughput: &input.provisioned_throughput, stream_specification: &input.stream_specification, sse_specification: &input.sse_specification, tags: &input.tags, }; serde_json::to_vec(&body).map(smithy_http::body::SdkBody::from) } pub fn serialize_synthetic_delete_backup_input_body( input: &crate::input::DeleteBackupInput, ) -> Result<smithy_http::body::SdkBody, serde_json::error::Error> { let body = crate::serializer::DeleteBackupInputBody { backup_arn: &input.backup_arn, }; serde_json::to_vec(&body).map(smithy_http::body::SdkBody::from) } pub fn serialize_synthetic_delete_item_input_body( input: &crate::input::DeleteItemInput, ) -> Result<smithy_http::body::SdkBody, serde_json::error::Error> { let body = crate::serializer::DeleteItemInputBody { table_name: &input.table_name, key: &input.key, expected: &input.expected, conditional_operator: &input.conditional_operator, return_values: &input.return_values, return_consumed_capacity: &input.return_consumed_capacity, return_item_collection_metrics: &input.return_item_collection_metrics, condition_expression: &input.condition_expression, expression_attribute_names: &input.expression_attribute_names, expression_attribute_values: &input.expression_attribute_values, }; serde_json::to_vec(&body).map(smithy_http::body::SdkBody::from) } pub fn serialize_synthetic_delete_table_input_body( input: &crate::input::DeleteTableInput, ) -> Result<smithy_http::body::SdkBody, serde_json::error::Error> { let body = crate::serializer::DeleteTableInputBody { table_name: &input.table_name, }; serde_json::to_vec(&body).map(smithy_http::body::SdkBody::from) } pub fn serialize_synthetic_describe_backup_input_body( input: &crate::input::DescribeBackupInput, ) -> Result<smithy_http::body::SdkBody, serde_json::error::Error> { let body = crate::serializer::DescribeBackupInputBody { backup_arn: &input.backup_arn, }; serde_json::to_vec(&body).map(smithy_http::body::SdkBody::from) } pub fn serialize_synthetic_describe_continuous_backups_input_body( input: &crate::input::DescribeContinuousBackupsInput, ) -> Result<smithy_http::body::SdkBody, serde_json::error::Error> { let body = crate::serializer::DescribeContinuousBackupsInputBody { table_name: &input.table_name, }; serde_json::to_vec(&body).map(smithy_http::body::SdkBody::from) } pub fn serialize_synthetic_describe_contributor_insights_input_body( input: &crate::input::DescribeContributorInsightsInput, ) -> Result<smithy_http::body::SdkBody, serde_json::error::Error> { let body = crate::serializer::DescribeContributorInsightsInputBody { table_name: &input.table_name, index_name: &input.index_name, }; serde_json::to_vec(&body).map(smithy_http::body::SdkBody::from) } pub fn serialize_synthetic_describe_export_input_body( input: &crate::input::DescribeExportInput, ) -> Result<smithy_http::body::SdkBody, serde_json::error::Error> { let body = crate::serializer::DescribeExportInputBody { export_arn: &input.export_arn, }; serde_json::to_vec(&body).map(smithy_http::body::SdkBody::from) } pub fn serialize_synthetic_describe_global_table_input_body( input: &crate::input::DescribeGlobalTableInput, ) -> Result<smithy_http::body::SdkBody, serde_json::error::Error> { let body = crate::serializer::DescribeGlobalTableInputBody { global_table_name: &input.global_table_name, }; serde_json::to_vec(&body).map(smithy_http::body::SdkBody::from) } pub fn serialize_synthetic_describe_global_table_settings_input_body( input: &crate::input::DescribeGlobalTableSettingsInput, ) -> Result<smithy_http::body::SdkBody, serde_json::error::Error> { let body = crate::serializer::DescribeGlobalTableSettingsInputBody { global_table_name: &input.global_table_name, }; serde_json::to_vec(&body).map(smithy_http::body::SdkBody::from) } pub fn serialize_synthetic_describe_kinesis_streaming_destination_input_body( input: &crate::input::DescribeKinesisStreamingDestinationInput, ) -> Result<smithy_http::body::SdkBody, serde_json::error::Error> { let body = crate::serializer::DescribeKinesisStreamingDestinationInputBody { table_name: &input.table_name, }; serde_json::to_vec(&body).map(smithy_http::body::SdkBody::from) } pub fn serialize_synthetic_describe_table_input_body( input: &crate::input::DescribeTableInput, ) -> Result<smithy_http::body::SdkBody, serde_json::error::Error> { let body = crate::serializer::DescribeTableInputBody { table_name: &input.table_name, }; serde_json::to_vec(&body).map(smithy_http::body::SdkBody::from) } pub fn serialize_synthetic_describe_table_replica_auto_scaling_input_body( input: &crate::input::DescribeTableReplicaAutoScalingInput, ) -> Result<smithy_http::body::SdkBody, serde_json::error::Error> { let body = crate::serializer::DescribeTableReplicaAutoScalingInputBody { table_name: &input.table_name, }; serde_json::to_vec(&body).map(smithy_http::body::SdkBody::from) } pub fn serialize_synthetic_describe_time_to_live_input_body( input: &crate::input::DescribeTimeToLiveInput, ) -> Result<smithy_http::body::SdkBody, serde_json::error::Error> { let body = crate::serializer::DescribeTimeToLiveInputBody { table_name: &input.table_name, }; serde_json::to_vec(&body).map(smithy_http::body::SdkBody::from) } pub fn serialize_synthetic_disable_kinesis_streaming_destination_input_body( input: &crate::input::DisableKinesisStreamingDestinationInput, ) -> Result<smithy_http::body::SdkBody, serde_json::error::Error> { let body = crate::serializer::DisableKinesisStreamingDestinationInputBody { table_name: &input.table_name, stream_arn: &input.stream_arn, }; serde_json::to_vec(&body).map(smithy_http::body::SdkBody::from) } pub fn serialize_synthetic_enable_kinesis_streaming_destination_input_body( input: &crate::input::EnableKinesisStreamingDestinationInput, ) -> Result<smithy_http::body::SdkBody, serde_json::error::Error> { let body = crate::serializer::EnableKinesisStreamingDestinationInputBody { table_name: &input.table_name, stream_arn: &input.stream_arn, }; serde_json::to_vec(&body).map(smithy_http::body::SdkBody::from) } pub fn serialize_synthetic_execute_statement_input_body( input: &crate::input::ExecuteStatementInput, ) -> Result<smithy_http::body::SdkBody, serde_json::error::Error> { let body = crate::serializer::ExecuteStatementInputBody { statement: &input.statement, parameters: &input.parameters, consistent_read: &input.consistent_read, next_token: &input.next_token, }; serde_json::to_vec(&body).map(smithy_http::body::SdkBody::from) } pub fn serialize_synthetic_execute_transaction_input_body( input: &crate::input::ExecuteTransactionInput, ) -> Result<smithy_http::body::SdkBody, serde_json::error::Error> { let body = crate::serializer::ExecuteTransactionInputBody { transact_statements: &input.transact_statements, client_request_token: &input.client_request_token, }; serde_json::to_vec(&body).map(smithy_http::body::SdkBody::from) } pub fn serialize_synthetic_export_table_to_point_in_time_input_body( input: &crate::input::ExportTableToPointInTimeInput, ) -> Result<smithy_http::body::SdkBody, serde_json::error::Error> { let body = crate::serializer::ExportTableToPointInTimeInputBody { table_arn: &input.table_arn, export_time: &input.export_time, client_token: &input.client_token, s3_bucket: &input.s3_bucket, s3_bucket_owner: &input.s3_bucket_owner, s3_prefix: &input.s3_prefix, s3_sse_algorithm: &input.s3_sse_algorithm, s3_sse_kms_key_id: &input.s3_sse_kms_key_id, export_format: &input.export_format, }; serde_json::to_vec(&body).map(smithy_http::body::SdkBody::from) } pub fn serialize_synthetic_get_item_input_body( input: &crate::input::GetItemInput, ) -> Result<smithy_http::body::SdkBody, serde_json::error::Error> { let body = crate::serializer::GetItemInputBody { table_name: &input.table_name, key: &input.key, attributes_to_get: &input.attributes_to_get, consistent_read: &input.consistent_read, return_consumed_capacity: &input.return_consumed_capacity, projection_expression: &input.projection_expression, expression_attribute_names: &input.expression_attribute_names, }; serde_json::to_vec(&body).map(smithy_http::body::SdkBody::from) } pub fn serialize_synthetic_list_backups_input_body( input: &crate::input::ListBackupsInput, ) -> Result<smithy_http::body::SdkBody, serde_json::error::Error> { let body = crate::serializer::ListBackupsInputBody { table_name: &input.table_name, limit: &input.limit, time_range_lower_bound: &input.time_range_lower_bound, time_range_upper_bound: &input.time_range_upper_bound, exclusive_start_backup_arn: &input.exclusive_start_backup_arn, backup_type: &input.backup_type, }; serde_json::to_vec(&body).map(smithy_http::body::SdkBody::from) } pub fn serialize_synthetic_list_contributor_insights_input_body( input: &crate::input::ListContributorInsightsInput, ) -> Result<smithy_http::body::SdkBody, serde_json::error::Error> { let body = crate::serializer::ListContributorInsightsInputBody { table_name: &input.table_name, next_token: &input.next_token, max_results: &input.max_results, }; serde_json::to_vec(&body).map(smithy_http::body::SdkBody::from) } pub fn serialize_synthetic_list_exports_input_body( input: &crate::input::ListExportsInput, ) -> Result<smithy_http::body::SdkBody, serde_json::error::Error> { let body = crate::serializer::ListExportsInputBody { table_arn: &input.table_arn, max_results: &input.max_results, next_token: &input.next_token, }; serde_json::to_vec(&body).map(smithy_http::body::SdkBody::from) } pub fn serialize_synthetic_list_global_tables_input_body( input: &crate::input::ListGlobalTablesInput, ) -> Result<smithy_http::body::SdkBody, serde_json::error::Error> { let body = crate::serializer::ListGlobalTablesInputBody { exclusive_start_global_table_name: &input.exclusive_start_global_table_name, limit: &input.limit, region_name: &input.region_name, }; serde_json::to_vec(&body).map(smithy_http::body::SdkBody::from) } pub fn serialize_synthetic_list_tables_input_body( input: &crate::input::ListTablesInput, ) -> Result<smithy_http::body::SdkBody, serde_json::error::Error> { let body = crate::serializer::ListTablesInputBody { exclusive_start_table_name: &input.exclusive_start_table_name, limit: &input.limit, }; serde_json::to_vec(&body).map(smithy_http::body::SdkBody::from) } pub fn serialize_synthetic_list_tags_of_resource_input_body( input: &crate::input::ListTagsOfResourceInput, ) -> Result<smithy_http::body::SdkBody, serde_json::error::Error> { let body = crate::serializer::ListTagsOfResourceInputBody { resource_arn: &input.resource_arn, next_token: &input.next_token, }; serde_json::to_vec(&body).map(smithy_http::body::SdkBody::from) } pub fn serialize_synthetic_put_item_input_body( input: &crate::input::PutItemInput, ) -> Result<smithy_http::body::SdkBody, serde_json::error::Error> { let body = crate::serializer::PutItemInputBody { table_name: &input.table_name, item: &input.item, expected: &input.expected, return_values: &input.return_values, return_consumed_capacity: &input.return_consumed_capacity, return_item_collection_metrics: &input.return_item_collection_metrics, conditional_operator: &input.conditional_operator, condition_expression: &input.condition_expression, expression_attribute_names: &input.expression_attribute_names, expression_attribute_values: &input.expression_attribute_values, }; serde_json::to_vec(&body).map(smithy_http::body::SdkBody::from) } pub fn serialize_synthetic_query_input_body( input: &crate::input::QueryInput, ) -> Result<smithy_http::body::SdkBody, serde_json::error::Error> { let body = crate::serializer::QueryInputBody { table_name: &input.table_name, index_name: &input.index_name, select: &input.select, attributes_to_get: &input.attributes_to_get, limit: &input.limit, consistent_read: &input.consistent_read, key_conditions: &input.key_conditions, query_filter: &input.query_filter, conditional_operator: &input.conditional_operator, scan_index_forward: &input.scan_index_forward, exclusive_start_key: &input.exclusive_start_key, return_consumed_capacity: &input.return_consumed_capacity, projection_expression: &input.projection_expression, filter_expression: &input.filter_expression, key_condition_expression: &input.key_condition_expression, expression_attribute_names: &input.expression_attribute_names, expression_attribute_values: &input.expression_attribute_values, }; serde_json::to_vec(&body).map(smithy_http::body::SdkBody::from) } pub fn serialize_synthetic_restore_table_from_backup_input_body( input: &crate::input::RestoreTableFromBackupInput, ) -> Result<smithy_http::body::SdkBody, serde_json::error::Error> { let body = crate::serializer::RestoreTableFromBackupInputBody { target_table_name: &input.target_table_name, backup_arn: &input.backup_arn, billing_mode_override: &input.billing_mode_override, global_secondary_index_override: &input.global_secondary_index_override, local_secondary_index_override: &input.local_secondary_index_override, provisioned_throughput_override: &input.provisioned_throughput_override, sse_specification_override: &input.sse_specification_override, }; serde_json::to_vec(&body).map(smithy_http::body::SdkBody::from) } pub fn serialize_synthetic_restore_table_to_point_in_time_input_body( input: &crate::input::RestoreTableToPointInTimeInput, ) -> Result<smithy_http::body::SdkBody, serde_json::error::Error> { let body = crate::serializer::RestoreTableToPointInTimeInputBody { source_table_arn: &input.source_table_arn, source_table_name: &input.source_table_name, target_table_name: &input.target_table_name, use_latest_restorable_time: &input.use_latest_restorable_time, restore_date_time: &input.restore_date_time, billing_mode_override: &input.billing_mode_override, global_secondary_index_override: &input.global_secondary_index_override, local_secondary_index_override: &input.local_secondary_index_override, provisioned_throughput_override: &input.provisioned_throughput_override, sse_specification_override: &input.sse_specification_override, }; serde_json::to_vec(&body).map(smithy_http::body::SdkBody::from) } pub fn serialize_synthetic_scan_input_body( input: &crate::input::ScanInput, ) -> Result<smithy_http::body::SdkBody, serde_json::error::Error> { let body = crate::serializer::ScanInputBody { table_name: &input.table_name, index_name: &input.index_name, attributes_to_get: &input.attributes_to_get, limit: &input.limit, select: &input.select, scan_filter: &input.scan_filter, conditional_operator: &input.conditional_operator, exclusive_start_key: &input.exclusive_start_key, return_consumed_capacity: &input.return_consumed_capacity, total_segments: &input.total_segments, segment: &input.segment, projection_expression: &input.projection_expression, filter_expression: &input.filter_expression, expression_attribute_names: &input.expression_attribute_names, expression_attribute_values: &input.expression_attribute_values, consistent_read: &input.consistent_read, }; serde_json::to_vec(&body).map(smithy_http::body::SdkBody::from) } pub fn serialize_synthetic_tag_resource_input_body( input: &crate::input::TagResourceInput, ) -> Result<smithy_http::body::SdkBody, serde_json::error::Error> { let body = crate::serializer::TagResourceInputBody { resource_arn: &input.resource_arn, tags: &input.tags, }; serde_json::to_vec(&body).map(smithy_http::body::SdkBody::from) } pub fn serialize_synthetic_transact_get_items_input_body( input: &crate::input::TransactGetItemsInput, ) -> Result<smithy_http::body::SdkBody, serde_json::error::Error> { let body = crate::serializer::TransactGetItemsInputBody { transact_items: &input.transact_items, return_consumed_capacity: &input.return_consumed_capacity, }; serde_json::to_vec(&body).map(smithy_http::body::SdkBody::from) } pub fn serialize_synthetic_transact_write_items_input_body( input: &crate::input::TransactWriteItemsInput, ) -> Result<smithy_http::body::SdkBody, serde_json::error::Error> { let body = crate::serializer::TransactWriteItemsInputBody { transact_items: &input.transact_items, return_consumed_capacity: &input.return_consumed_capacity, return_item_collection_metrics: &input.return_item_collection_metrics, client_request_token: &input.client_request_token, }; serde_json::to_vec(&body).map(smithy_http::body::SdkBody::from) } pub fn serialize_synthetic_untag_resource_input_body( input: &crate::input::UntagResourceInput, ) -> Result<smithy_http::body::SdkBody, serde_json::error::Error> { let body = crate::serializer::UntagResourceInputBody { resource_arn: &input.resource_arn, tag_keys: &input.tag_keys, }; serde_json::to_vec(&body).map(smithy_http::body::SdkBody::from) } pub fn serialize_synthetic_update_continuous_backups_input_body( input: &crate::input::UpdateContinuousBackupsInput, ) -> Result<smithy_http::body::SdkBody, serde_json::error::Error> { let body = crate::serializer::UpdateContinuousBackupsInputBody { table_name: &input.table_name, point_in_time_recovery_specification: &input.point_in_time_recovery_specification, }; serde_json::to_vec(&body).map(smithy_http::body::SdkBody::from) } pub fn serialize_synthetic_update_contributor_insights_input_body( input: &crate::input::UpdateContributorInsightsInput, ) -> Result<smithy_http::body::SdkBody, serde_json::error::Error> { let body = crate::serializer::UpdateContributorInsightsInputBody { table_name: &input.table_name, index_name: &input.index_name, contributor_insights_action: &input.contributor_insights_action, }; serde_json::to_vec(&body).map(smithy_http::body::SdkBody::from) } pub fn serialize_synthetic_update_global_table_input_body( input: &crate::input::UpdateGlobalTableInput, ) -> Result<smithy_http::body::SdkBody, serde_json::error::Error> { let body = crate::serializer::UpdateGlobalTableInputBody { global_table_name: &input.global_table_name, replica_updates: &input.replica_updates, }; serde_json::to_vec(&body).map(smithy_http::body::SdkBody::from) } pub fn serialize_synthetic_update_global_table_settings_input_body( input: &crate::input::UpdateGlobalTableSettingsInput, ) -> Result<smithy_http::body::SdkBody, serde_json::error::Error> { let body = crate::serializer::UpdateGlobalTableSettingsInputBody { global_table_name: &input.global_table_name, global_table_billing_mode: &input.global_table_billing_mode, global_table_provisioned_write_capacity_units: &input .global_table_provisioned_write_capacity_units, global_table_provisioned_write_capacity_auto_scaling_settings_update: &input .global_table_provisioned_write_capacity_auto_scaling_settings_update, global_table_global_secondary_index_settings_update: &input .global_table_global_secondary_index_settings_update, replica_settings_update: &input.replica_settings_update, }; serde_json::to_vec(&body).map(smithy_http::body::SdkBody::from) } pub fn serialize_synthetic_update_item_input_body( input: &crate::input::UpdateItemInput, ) -> Result<smithy_http::body::SdkBody, serde_json::error::Error> { let body = crate::serializer::UpdateItemInputBody { table_name: &input.table_name, key: &input.key, attribute_updates: &input.attribute_updates, expected: &input.expected, conditional_operator: &input.conditional_operator, return_values: &input.return_values, return_consumed_capacity: &input.return_consumed_capacity, return_item_collection_metrics: &input.return_item_collection_metrics, update_expression: &input.update_expression, condition_expression: &input.condition_expression, expression_attribute_names: &input.expression_attribute_names, expression_attribute_values: &input.expression_attribute_values, }; serde_json::to_vec(&body).map(smithy_http::body::SdkBody::from) } pub fn serialize_synthetic_update_table_input_body( input: &crate::input::UpdateTableInput, ) -> Result<smithy_http::body::SdkBody, serde_json::error::Error> { let body = crate::serializer::UpdateTableInputBody { attribute_definitions: &input.attribute_definitions, table_name: &input.table_name, billing_mode: &input.billing_mode, provisioned_throughput: &input.provisioned_throughput, global_secondary_index_updates: &input.global_secondary_index_updates, stream_specification: &input.stream_specification, sse_specification: &input.sse_specification, replica_updates: &input.replica_updates, }; serde_json::to_vec(&body).map(smithy_http::body::SdkBody::from) } pub fn serialize_synthetic_update_table_replica_auto_scaling_input_body( input: &crate::input::UpdateTableReplicaAutoScalingInput, ) -> Result<smithy_http::body::SdkBody, serde_json::error::Error> { let body = crate::serializer::UpdateTableReplicaAutoScalingInputBody { global_secondary_index_updates: &input.global_secondary_index_updates, table_name: &input.table_name, provisioned_write_capacity_auto_scaling_update: &input .provisioned_write_capacity_auto_scaling_update, replica_updates: &input.replica_updates, }; serde_json::to_vec(&body).map(smithy_http::body::SdkBody::from) } pub fn serialize_synthetic_update_time_to_live_input_body( input: &crate::input::UpdateTimeToLiveInput, ) -> Result<smithy_http::body::SdkBody, serde_json::error::Error> { let body = crate::serializer::UpdateTimeToLiveInputBody { table_name: &input.table_name, time_to_live_specification: &input.time_to_live_specification, }; serde_json::to_vec(&body).map(smithy_http::body::SdkBody::from) }
#![feature(stmt_expr_attributes)] #![feature(proc_macro_hygiene)] #![feature(async_closure)] #![deny(rust_2018_idioms, deprecated)] mod commands; use std::collections::HashSet; use serenity::async_trait; use serenity::framework::standard::help_commands::with_embeds; use serenity::framework::standard::*; use serenity::model::prelude::*; use serenity::prelude::*; use commands::*; pub use log::{error, info}; pub use serenity::framework::standard::macros::*; use serde::Deserialize; struct Handler; #[async_trait] impl EventHandler for Handler { async fn ready(&self, ctx: Context, _: Ready) { ctx.set_activity(Activity::playing("charades")).await; info!("Running!"); } } #[group("Modern-Major General")] #[commands(ping, info, sort, today, avatar_url, force)] struct General; #[help] async fn my_help( ctx: &Context, msg: &Message, args: Args, help_options: &'static HelpOptions, groups: &[&'static CommandGroup], owners: HashSet<UserId>, ) -> CommandResult { let _ = with_embeds(ctx, msg, args, help_options, groups, owners).await; Ok(()) } #[hook] async fn dispatch_error(ctx: &Context, msg: &Message, error: DispatchError) { match error { DispatchError::CheckFailed(_, reason) => { let _ = msg.channel_id.say(&ctx.http, format!("{:?}", reason)).await; } _ => error!("dispatch error: {:?}", error), } } #[hook] async fn after(ctx: &Context, msg: &Message, command: &str, error: CommandResult) { info!("Command `{}` was used by {}", command, msg.author.name); if let Err(err) = error { let err = err.to_string(); if err.starts_with("user : ") { let without_user = &err["user: ".len()..]; let _ = msg.channel_id.say(&ctx.http, without_user).await; } else { error!( target: &format!("{}/{}", module_path!(), command), "`{:?}`", err ); } } } #[derive(Deserialize)] struct Config { token: String, prefix: String, } #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> { pretty_env_logger::init(); let config = tokio::fs::read_to_string("config.json").await?; let Config { token, prefix } = serde_json::from_str(&config)?; let framework = StandardFramework::new() .configure(|c| c.prefix(&prefix)) .on_dispatch_error(dispatch_error) .unrecognised_command(#[hook] async |_ctx, msg, cmd| { if cmd.starts_with('?') { return; } info!( "User `{}` tried to execute an unrecognised command `{}`", msg.author.name, cmd ); }) .after(after) .help(&MY_HELP) .group(&GENERAL_GROUP); let mut client = Client::new(token) .event_handler(Handler) .framework(framework) .await?; client.start_autosharded().await?; Ok(()) }
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use { component_manager_lib::{klog, model::AbsoluteMoniker, startup}, failure::{Error, ResultExt}, fuchsia_async as fasync, futures::prelude::*, log::*, std::process, }; const NUM_THREADS: usize = 2; fn main() -> Result<(), Error> { klog::KernelLogger::init().expect("Failed to initialize logger"); let args = match startup::Arguments::from_args() { Ok(args) => args, Err(err) => { error!("{}\n{}", err, startup::Arguments::usage()); return Err(err); } }; info!("Component manager is starting up..."); let mut executor = fasync::Executor::new().context("error creating executor")?; let fut = async { match run_root(args).await { Ok(()) => { // TODO: Exit the component manager when the root component's binding is lost // (when it terminates) or perhaps attempt to rebind automatically. // For now, the component manager just runs forever. future::pending::<()>().await } Err(err) => { error!("Component manager setup failed: {:?}", err); process::exit(1) } } }; executor.run(fut, NUM_THREADS); Ok(()) } async fn run_root(args: startup::Arguments) -> Result<(), Error> { let hub = startup::create_hub_if_possible(args.root_component_url.clone()) .await .context("failed to create hub")?; let model = startup::model_setup(&args, hub.hooks()).await.context("failed to set up model")?; model .look_up_and_bind_instance(AbsoluteMoniker::root()) .await .map_err(|e| Error::from(e)) .context(format!("failed to bind to root component {}", args.root_component_url))?; Ok(()) }
pub mod accounts; pub mod providers; pub mod transactions; use sqlx::PgPool; #[derive(Clone)] pub struct Db(PgPool); impl Db { pub async fn connect(url: &str) -> sqlx::Result<Db> { Ok(Db(PgPool::connect(url).await?)) } pub fn pool(&self) -> &PgPool { &self.0 } pub async fn close(self) { self.0.close().await } }
use winapi::shared::minwindef::DWORD; use winapi::shared::windef::{HWND}; use super::ControlHandle; use crate::win32::window::{build_hwnd_control, build_timer, build_notice}; use crate::{NwgError}; #[cfg(feature = "menu")] use crate::win32::menu::build_hmenu_control; #[cfg(feature = "menu")] use winapi::shared::windef::{HMENU}; const NOTICE: u32 = 1; const TRAY: u32 = 2; /** Control base is a low level interface to create base Windows handle (HWND, HMENU, TIMER, etc). This is used internally by every controls. ```rust use native_windows_gui as nwg; fn basic_stuff(window: &nwg::Window) -> Result<(), nwg::NwgError> { nwg::ControlBase::build_hwnd() .class_name("BUTTON") .forced_flags(0) .flags(0) .size((100, 100)) .position((100, 100)) .text("HELLO") .parent(Some(window.handle)) .build()?; #[cfg(feature = "menu")] nwg::ControlBase::build_hmenu() .text("Item") .item(true) .parent(window.handle) .build()?; Ok(()) } ``` */ #[derive(Debug, Clone)] pub struct ControlBase; impl ControlBase { pub fn build_hwnd() -> HwndBuilder { HwndBuilder::default() } #[cfg(feature = "menu")] pub fn build_hmenu() -> HmenuBuilder { HmenuBuilder::default() } pub fn build_timer() -> TimerBuilder { TimerBuilder::default() } pub fn build_notice() -> OtherBuilder { OtherBuilder { parent: None, ty: NOTICE } } pub fn build_tray_notification() -> OtherBuilder { OtherBuilder { parent: None, ty: TRAY } } } /// Low level HWND builder. Instanced by `ControlBase::build_hwnd`. #[derive(Default)] pub struct HwndBuilder { class_name: String, text: Option<String>, size: Option<(i32, i32)>, pos: Option<(i32, i32)>, forced_flags: DWORD, flags: Option<DWORD>, ex_flags: Option<DWORD>, parent: Option<HWND> } impl HwndBuilder { pub fn class_name<'a>(mut self, name: &'a str) -> HwndBuilder { self.class_name = name.to_string(); self } pub fn text<'a>(mut self, text: &'a str) -> HwndBuilder { self.text = Some(text.to_string()); self } pub fn size(mut self, size: (i32, i32)) -> HwndBuilder { self.size = Some(size); self } pub fn position(mut self, pos: (i32, i32)) -> HwndBuilder { self.pos = Some(pos); self } pub fn flags(mut self, flags: u32) -> HwndBuilder { self.flags = Some(flags as DWORD); self } pub fn ex_flags(mut self, flags: u32) -> HwndBuilder { self.ex_flags = Some(flags as DWORD); self } pub fn forced_flags(mut self, flags: u32) -> HwndBuilder { self.forced_flags = flags as DWORD; self } pub fn parent(mut self, parent: Option<ControlHandle>) -> HwndBuilder { match parent { Some(p) => { self.parent = p.hwnd(); } None => { self.parent = None; } } self } pub fn build(self) -> Result<ControlHandle, NwgError> { let handle = unsafe { build_hwnd_control( &self.class_name, self.text.as_ref().map(|v| v as &str), self.size, self.pos, self.flags, self.ex_flags, self.forced_flags, self.parent )? }; Ok(handle) } } /// Low level HMENU builder. Instanced by `ControlBase::build_hmenu`. #[derive(Default)] #[cfg(feature = "menu")] pub struct HmenuBuilder { text: Option<String>, item: bool, separator: bool, popup: bool, parent_menu: Option<HMENU>, parent_window: Option<HWND>, } #[cfg(feature = "menu")] impl HmenuBuilder { /// Set the text of the Menu pub fn text<'a>(mut self, text: &'a str) -> HmenuBuilder { self.text = Some(text.to_string()); self } /// Set if the menu should be an item or a menu pub fn item(mut self, i: bool) -> HmenuBuilder { self.item = i; self } /// Set if the menu item should be a separator pub fn separator(mut self, i: bool) -> HmenuBuilder { self.separator = i; self } /// Set if the menu item should be a separator pub fn popup(mut self, i: bool) -> HmenuBuilder { self.popup = i; self } /// Set the parent of the menu. Can be a window or another menu. pub fn parent(mut self, parent: ControlHandle) -> HmenuBuilder { match parent { ControlHandle::Hwnd(hwnd) => { self.parent_window = Some(hwnd); } ControlHandle::Menu(_parent, menu) => { self.parent_menu = Some(menu); } ControlHandle::PopMenu(_hwnd, menu) => { self.parent_menu = Some(menu); }, _ => {} } self } pub fn build(self) -> Result<ControlHandle, NwgError> { let handle = unsafe { build_hmenu_control( self.text, self.item, self.separator, self.popup, self.parent_menu, self.parent_window )? }; Ok(handle) } } /// Low level timer builder. Instanced by `ControlBase::build_timer`. #[derive(Default)] pub struct TimerBuilder { parent: Option<HWND>, interval: u32, stopped: bool } impl TimerBuilder { pub fn stopped(mut self, v: bool) -> TimerBuilder { self.stopped = v; self } pub fn interval(mut self, i: u32) -> TimerBuilder { self.interval = i; self } pub fn parent(mut self, parent: Option<ControlHandle>) -> TimerBuilder { match parent { Some(p) => { self.parent = p.hwnd(); } None => panic!("Timer parent must be HWND") } self } pub fn build(self) -> Result<ControlHandle, NwgError> { let handle = unsafe { build_timer( self.parent.expect("Internal error. Timer without window parent"), self.interval, self.stopped ) }; Ok(handle) } } /// Low level builder for controls without specific winapi contructors. /// Instanced by `ControlBase::build_notice` or `ControlBase::build_tray_notification`. #[derive(Default)] pub struct OtherBuilder { parent: Option<HWND>, ty: u32 } impl OtherBuilder { pub fn parent(mut self, parent: HWND) -> OtherBuilder { self.parent = Some(parent); self } pub fn build(self) -> Result<ControlHandle, NwgError> { let handle = self.parent.expect("Internal error. Control without window parent"); let base = match self.ty { NOTICE => build_notice(handle), TRAY => ControlHandle::SystemTray(handle), _ => unreachable!() }; Ok(base) } }
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use fidl_fuchsia_router_config::{RouterAdminRequest, RouterStateRequest}; /// The events that can trigger an action in the event loop. #[derive(Debug)] pub enum Event { /// A request from the fuchsia.router.config Admin FIDL interface FidlRouterAdminEvent(RouterAdminRequest), /// A request from the fuchsia.router.config State FIDL interface FidlRouterStateEvent(RouterStateRequest), /// An event coming from fuchsia.net.stack. StackEvent(fidl_fuchsia_net_stack::StackEvent), /// An event coming from fuchsia.netstack. NetstackEvent(fidl_fuchsia_netstack::NetstackEvent), }
// Copyright 2021 Datafuse Labs. // // 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 std::collections::BTreeMap; use std::fmt::Formatter; use common_exception::Result; use common_expression::FieldIndex; use common_expression::TableSchema; use common_storage::ColumnNode; use common_storage::ColumnNodes; #[derive(serde::Serialize, serde::Deserialize, Clone, PartialEq, Eq)] pub enum Projection { /// column indices of the table Columns(Vec<FieldIndex>), /// inner column indices for tuple data type with inner columns. /// the key is the column_index of ColumnEntry. /// the value is the path indices of inner columns. InnerColumns(BTreeMap<FieldIndex, Vec<FieldIndex>>), } impl Projection { pub fn len(&self) -> usize { match self { Projection::Columns(indices) => indices.len(), Projection::InnerColumns(path_indices) => path_indices.len(), } } pub fn is_empty(&self) -> bool { match self { Projection::Columns(indices) => indices.is_empty(), Projection::InnerColumns(path_indices) => path_indices.is_empty(), } } /// Use this projection to project a schema. pub fn project_schema(&self, schema: &TableSchema) -> TableSchema { match self { Projection::Columns(indices) => schema.project(indices), Projection::InnerColumns(path_indices) => schema.inner_project(path_indices), } } pub fn project_column_nodes<'a>( &'a self, column_nodes: &'a ColumnNodes, ) -> Result<Vec<&ColumnNode>> { let column_nodes = match self { Projection::Columns(indices) => indices .iter() .map(|idx| &column_nodes.column_nodes[*idx]) .collect(), Projection::InnerColumns(path_indices) => { let paths: Vec<&Vec<usize>> = path_indices.values().collect(); paths .iter() .map(|path| ColumnNodes::traverse_path(&column_nodes.column_nodes, path)) .collect::<Result<_>>()? } }; Ok(column_nodes) } pub fn add_col(&mut self, col: FieldIndex) { match self { Projection::Columns(indices) => { if indices.contains(&col) { return; } indices.push(col); indices.sort(); } Projection::InnerColumns(path_indices) => { path_indices.entry(col).or_insert(vec![col]); } } } pub fn remove_col(&mut self, col: FieldIndex) { match self { Projection::Columns(indices) => { if let Some(pos) = indices.iter().position(|x| *x == col) { indices.remove(pos); } } Projection::InnerColumns(path_indices) => { path_indices.remove(&col); } } } } impl core::fmt::Debug for Projection { fn fmt(&self, f: &mut Formatter) -> std::fmt::Result { match self { Projection::Columns(indices) => write!(f, "{:?}", indices), Projection::InnerColumns(path_indices) => { let paths: Vec<&Vec<usize>> = path_indices.values().collect(); write!(f, "{:?}", paths) } } } }
// revisions: base nll // ignore-compare-mode-nll //[nll] compile-flags: -Z borrowck=mir fn test<'x>(x: &'x isize) { drop::<Box<dyn for<'z> FnMut(&'z isize) -> &'z isize>>(Box::new(|z| { x //[base]~^ ERROR E0312 //[nll]~^^ ERROR lifetime may not live long enough })); } fn main() {}
extern crate chrono; #[macro_use] extern crate log; #[macro_use] extern crate error_chain; extern crate indextree; extern crate libc; extern crate nix; extern crate serde; extern crate spawn_ptrace; mod errors; pub use errors::*; use chrono::{Duration, Local, DateTime}; use indextree::{Arena, NodeId}; pub use indextree::NodeEdge; use libc::{c_long, pid_t}; use nix::c_void; use nix::sys::ptrace::{ptrace, ptrace_setoptions}; use nix::sys::ptrace::ptrace::{PTRACE_EVENT_FORK, PTRACE_EVENT_VFORK, PTRACE_EVENT_CLONE, PTRACE_EVENT_EXEC}; use nix::sys::ptrace::ptrace::{PTRACE_O_TRACECLONE, PTRACE_O_TRACEEXEC, PTRACE_O_TRACEFORK, PTRACE_O_TRACEVFORK, PTRACE_GETEVENTMSG, PTRACE_CONT}; use nix::sys::signal; use nix::sys::wait::{waitpid, WaitStatus}; use serde::{Serialize, Serializer}; use serde::ser::{SerializeSeq, SerializeStruct}; use spawn_ptrace::CommandPtraceSpawn; use std::collections::HashMap; use std::fs::File; use std::io::Read; use std::process::Command; use std::ptr; use std::time::Instant; /// Information about a spawned process. pub struct ProcessInfo { /// The process ID. pub pid: pid_t, /// When the process was started. pub started: Instant, /// When the process ended, or `None` if it is still running. pub ended: Option<Instant>, /// The commandline with which this process was executed. pub cmdline: Vec<String>, /// The working directory where the command was invoked. pub cwd: Option<String>, } impl Default for ProcessInfo { fn default() -> ProcessInfo { ProcessInfo { pid: 0, started: Instant::now(), ended: None, cmdline: vec!(), cwd: None, } } } /// A tree of processes. pub struct ProcessTree { arena: Arena<ProcessInfo>, pids: HashMap<pid_t, NodeId>, root: NodeId, started: DateTime<Local>, } impl ProcessTree { /// Execute `cmd`, tracking all child processes it spawns, and return a `ProcessTree` listing /// them. pub fn spawn<T>(mut cmd: Command, cmdline: &[T]) -> Result<ProcessTree> where T: AsRef<str> { let started = Local::now(); let child = cmd.spawn_ptrace().chain_err(|| "Error spawning process")?; let pid = child.id() as pid_t; trace!("Spawned process {}", pid); // Setup our ptrace options ptrace_setoptions(pid, PTRACE_O_TRACEEXEC | PTRACE_O_TRACEFORK | PTRACE_O_TRACEVFORK | PTRACE_O_TRACECLONE).chain_err(|| "Error setting ptrace options")?; let mut arena = Arena::new(); let mut pids = HashMap::new(); let root = get_or_insert_pid(pid, &mut arena, &mut pids); arena[root].data.cmdline = cmdline.iter().map(|s| s.as_ref().to_string()).collect(); arena[root].data.cwd = get_cwd(pid); continue_process(pid, None).chain_err(|| "Error continuing process")?; loop { if !root.descendants(&arena).any(|node| arena[node].data.ended.is_none()) { break } match waitpid(-1, None) { Ok(WaitStatus::Exited(pid, ret)) => { trace!("Process {} exited with status {}", pid, ret); let node = get_or_insert_pid(pid, &mut arena, &mut pids); arena[node].data.ended = Some(Instant::now()); } Ok(WaitStatus::Signaled(pid, sig, _)) => { trace!("Process {} exited with signal {:?}", pid, sig); let node = get_or_insert_pid(pid, &mut arena, &mut pids); arena[node].data.ended = Some(Instant::now()); } Ok(WaitStatus::PtraceEvent(pid, _sig, event)) => { match event { PTRACE_EVENT_FORK | PTRACE_EVENT_VFORK | PTRACE_EVENT_CLONE => { let mut new_pid: pid_t = 0; ptrace(PTRACE_GETEVENTMSG, pid, ptr::null_mut(), &mut new_pid as *mut pid_t as *mut c_void) .chain_err(|| "Failed to get pid of forked process")?; let name = match event { PTRACE_EVENT_FORK => "fork", PTRACE_EVENT_VFORK => "vfork", PTRACE_EVENT_CLONE => "clone", _ => unreachable!(), }; trace!("[{}] {} new process {}", pid, name, new_pid); match pids.get(&pid) { Some(&parent) => { let cmdline = { let parent_data = &arena[parent].data; if parent_data.cmdline.len() > 1 { parent_data.cmdline[..1].to_vec() } else { vec![] } }; let child = get_or_insert_pid(new_pid, &mut arena, &mut pids); arena[child].data.cmdline = cmdline; arena[child].data.cwd = get_cwd(new_pid); parent.append(child, &mut arena); } None => bail!("Got an {:?} event for unknown parent pid {}", event, pid), } } PTRACE_EVENT_EXEC => { let mut buf = vec!(); match pids.get(&pid) { Some(&node) => { File::open(format!("/proc/{}/cmdline", pid)) .and_then(|mut f| f.read_to_end(&mut buf)) .and_then(|_| { let mut cmdline = buf.split(|&b| b == 0).map(|bytes| String::from_utf8_lossy(bytes).into_owned()).collect::<Vec<_>>(); cmdline.pop(); debug!("[{}] exec {:?}", pid, cmdline); arena[node].data.cmdline = cmdline; Ok(()) }) .chain_err(|| "Couldn't read cmdline")?; } None => bail!("Got an exec event for unknown pid {}", pid), } } _ => panic!("Unexpected ptrace event: {:?}", event), } continue_process(pid, None).chain_err(|| "Error continuing process")?; } Ok(WaitStatus::Stopped(pid, sig)) => { trace!("[{}] stopped with {:?}", pid, sig); // Sometimes we get the SIGSTOP+exit from a child before we get the clone // stop from the parent, so insert any unknown pids here so we have a better // approximation of the process start time. get_or_insert_pid(pid, &mut arena, &mut pids); let continue_sig = if sig == signal::Signal::SIGSTOP { None } else { Some(sig) }; continue_process(pid, continue_sig).chain_err(|| "Error continuing process")?; } Ok(s) => bail!("Unexpected process status: {:?}", s), Err(e) => { match e { nix::Error::Sys(nix::Errno::EINTR) => { /*FIXME if SIGNAL_DELIVERED.swap(false, Ordering::Relaxed) { println!("Active processes:"); print_process_tree(root, arena, |info| info.ended.is_none()); } */ } _ => bail!("ptrace error: {:?}", e), } } } } Ok(ProcessTree { arena: arena, pids: pids, root: root, started: started, }) } /// Iterate over processes in the tree in tree order. pub fn traverse<'a>(&'a self) -> Traverse<'a> { Traverse { inner: self.root.traverse(&self.arena), arena: &self.arena, } } /// Look up a process in the tree by pid. pub fn get(&self, pid: pid_t) -> Option<&ProcessInfo> { match self.pids.get(&pid) { None => None, Some(&node) => Some(&self.arena[node].data), } } } pub struct Traverse<'a> { inner: indextree::Traverse<'a, ProcessInfo>, arena: &'a Arena<ProcessInfo>, } impl<'a> Iterator for Traverse<'a> { type Item = NodeEdge<&'a ProcessInfo>; fn next(&mut self) -> Option<NodeEdge<&'a ProcessInfo>> { match self.inner.next() { None => None, Some(NodeEdge::Start(node)) => { Some(NodeEdge::Start(&self.arena[node].data)) } Some(NodeEdge::End(node)) => { Some(NodeEdge::End(&self.arena[node].data)) } } } } struct ProcessInfoSerializable<'a>(NodeId, &'a Arena<ProcessInfo>, Instant, DateTime<Local>); struct ChildrenSerializable<'a>(NodeId, &'a Arena<ProcessInfo>, Instant, DateTime<Local>); fn dt(a: Instant, b: Instant, c: DateTime<Local>) -> String { let d = c + Duration::from_std(a - b).unwrap(); d.to_rfc3339() } impl<'a> Serialize for ProcessInfoSerializable<'a> { fn serialize<S>(&self, serializer: S) -> ::std::result::Result<S::Ok, S::Error> where S: Serializer { let mut state = serializer.serialize_struct("ProcessInfo", 5)?; { let info = &self.1[self.0].data; state.serialize_field("pid", &info.pid)?; state.serialize_field("started", &dt(info.started, self.2, self.3))?; state.serialize_field("ended", &info.ended.map(|i| dt(i, self.2, self.3)))?; state.serialize_field("cmdline", &info.cmdline)?; state.serialize_field("cwd", &info.cwd)?; } state.serialize_field("children", &ChildrenSerializable(self.0, self.1, self.2, self.3))?; state.end() } } impl<'a> Serialize for ChildrenSerializable<'a> { fn serialize<S>(&self, serializer: S) -> ::std::result::Result<S::Ok, S::Error> where S: Serializer { let len = self.0.children(self.1).count(); let mut seq = serializer.serialize_seq(Some(len))?; for c in self.0.children(self.1) { seq.serialize_element(&ProcessInfoSerializable(c, self.1, self.2, self.3))?; } seq.end() } } impl Serialize for ProcessTree { fn serialize<S>(&self, serializer: S) -> ::std::result::Result<S::Ok, S::Error> where S: Serializer { let started = self.arena[self.root].data.started; let root_pi = ProcessInfoSerializable(self.root, &self.arena, started, self.started); root_pi.serialize(serializer) } } fn get_or_insert_pid(pid: pid_t, arena: &mut Arena<ProcessInfo>, map: &mut HashMap<pid_t, NodeId>) -> NodeId { *map.entry(pid).or_insert_with(|| { arena.new_node(ProcessInfo { pid: pid, .. ProcessInfo::default() }) }) } fn continue_process(pid: pid_t, signal: Option<signal::Signal>) -> nix::Result<c_long> { let data = signal.map(|s| s as i32 as *mut c_void).unwrap_or(ptr::null_mut()); ptrace(PTRACE_CONT, pid, ptr::null_mut(), data) } fn get_cwd(pid: i32) -> Option<String> { let txt = format!("/proc/{}/cwd", pid); let path = std::path::Path::new(&txt); let abspath = std::fs::canonicalize(path); match abspath { Ok(abspath) => abspath.into_os_string().into_string().ok(), _ => None, } }
use crate::KafkaMessage; use rskafka_proto::{Record, RecordBatch}; use std::borrow::Cow; pub struct KafkaBatch<'a> { pub topic: String, pub partition_index: i32, pub base_offset: i64, pub records: Vec<KafkaBatchRecord<'a>>, } impl<'a> KafkaBatch<'a> { pub(crate) fn new(data: RecordBatch<'a>, topic: String, partition_index: i32) -> Self { KafkaBatch { topic, partition_index, base_offset: data.base_offset, records: data .records .into_owned() .into_iter() .map(KafkaBatchRecord::from) .collect(), } } pub fn messages(&'a self) -> impl Iterator<Item = KafkaMessage<'a>> + 'a { self.records.iter().map(move |r| KafkaMessage { topic: Cow::Borrowed(&self.topic), partition: self.partition_index, offset: self.base_offset + r.offset_delta as i64, key: r.key.as_ref().map(|key| Cow::Borrowed(key.as_ref())), value: r.value.as_ref().map(|value| Cow::Borrowed(value.as_ref())), }) } pub fn into_messages_owned(self) -> Vec<KafkaMessage<'static>> { let topic = self.topic; let partition_index = self.partition_index; let base_offset = self.base_offset; self.records .into_iter() .map(move |r| KafkaMessage { topic: topic.clone().into(), partition: partition_index, offset: base_offset + r.offset_delta as i64, key: r.key.map(|k| k.into_owned().into()), value: r.value.map(|v| v.into_owned().into()), }) .collect() } } pub struct KafkaBatchRecord<'a> { pub offset_delta: i32, pub key: Option<Cow<'a, [u8]>>, pub value: Option<Cow<'a, [u8]>>, } impl<'a> From<Record<'a>> for KafkaBatchRecord<'a> { fn from(v: Record<'a>) -> Self { KafkaBatchRecord { offset_delta: v.offset_delta.0, key: v.key, value: v.value, } } }
#[doc = "Reader of register MCR"] pub type R = crate::R<u32, super::MCR>; #[doc = "Writer for register MCR"] pub type W = crate::W<u32, super::MCR>; #[doc = "Register MCR `reset()`'s with value 0"] impl crate::ResetValue for super::MCR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `LPBK`"] pub type LPBK_R = crate::R<bool, bool>; #[doc = "Write proxy for field `LPBK`"] pub struct LPBK_W<'a> { w: &'a mut W, } impl<'a> LPBK_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01); self.w } } #[doc = "Reader of field `MFE`"] pub type MFE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `MFE`"] pub struct MFE_W<'a> { w: &'a mut W, } impl<'a> MFE_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 4)) | (((value as u32) & 0x01) << 4); self.w } } #[doc = "Reader of field `SFE`"] pub type SFE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `SFE`"] pub struct SFE_W<'a> { w: &'a mut W, } impl<'a> SFE_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 5)) | (((value as u32) & 0x01) << 5); self.w } } #[doc = "Reader of field `GFE`"] pub type GFE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `GFE`"] pub struct GFE_W<'a> { w: &'a mut W, } impl<'a> GFE_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 6)) | (((value as u32) & 0x01) << 6); self.w } } impl R { #[doc = "Bit 0 - I2C Loopback"] #[inline(always)] pub fn lpbk(&self) -> LPBK_R { LPBK_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 4 - I2C Master Function Enable"] #[inline(always)] pub fn mfe(&self) -> MFE_R { MFE_R::new(((self.bits >> 4) & 0x01) != 0) } #[doc = "Bit 5 - I2C Slave Function Enable"] #[inline(always)] pub fn sfe(&self) -> SFE_R { SFE_R::new(((self.bits >> 5) & 0x01) != 0) } #[doc = "Bit 6 - I2C Glitch Filter Enable"] #[inline(always)] pub fn gfe(&self) -> GFE_R { GFE_R::new(((self.bits >> 6) & 0x01) != 0) } } impl W { #[doc = "Bit 0 - I2C Loopback"] #[inline(always)] pub fn lpbk(&mut self) -> LPBK_W { LPBK_W { w: self } } #[doc = "Bit 4 - I2C Master Function Enable"] #[inline(always)] pub fn mfe(&mut self) -> MFE_W { MFE_W { w: self } } #[doc = "Bit 5 - I2C Slave Function Enable"] #[inline(always)] pub fn sfe(&mut self) -> SFE_W { SFE_W { w: self } } #[doc = "Bit 6 - I2C Glitch Filter Enable"] #[inline(always)] pub fn gfe(&mut self) -> GFE_W { GFE_W { w: self } } }
//! A module for controlling the fan speed of AMD GPUs. use std::string::String; use std::path::{PathBuf, Path}; use std::{io, fs, fmt}; use std::io::{BufRead}; #[derive(Debug)] pub enum GpuError { /// IO failure while accessing the GPU device files Io(io::Error), /// Unexpected data has been read from a GPU device file Parse(PathBuf, Option<String>), InvalidFanSpeed { min: Pwm, max: Pwm, percentage: f64 }, } impl fmt::Display for GpuError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match &self { &GpuError::Io(err) => write!(f, "{}", err), &GpuError::Parse(path, contents) => write!(f, "Could not parse {:?} from {}", contents, path.to_string_lossy()), &GpuError::InvalidFanSpeed {min, max, percentage} => write!(f, "Computation resulted in invalid fan speed (min={:?} max={:?} percentage={})", min, max, percentage), } } } impl From<io::Error> for GpuError { fn from(other: io::Error) -> GpuError { GpuError::Io(other) } } /// A GPU temperature in raw units (in thousandths of a degree celcius) #[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Copy, Clone)] pub struct Temperature(i32); impl Temperature { pub fn as_celcius(self) -> f64 { self.0 as f64 / 1000.0 } } impl fmt::Display for Temperature { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}°C", self.as_celcius()) } } /// GPU fan PWM value. The exact meaning depends on the min/max values that may or may not vary. #[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Copy, Clone)] pub struct Pwm(i32); impl Pwm { pub fn as_raw(self) -> i32 { self.0 } pub fn from_percentage(min: Pwm, max: Pwm, percentage: f64) -> Result<Pwm, GpuError> { let actual_percentage = percentage.min(1.0).max(0.0); let pwm_float = min.0 as f64 + (max.0 as f64 - min.0 as f64) * actual_percentage; if pwm_float.is_finite() { let pwm = pwm_float.floor() as i32; Ok(Pwm(pwm)) } else { Err(GpuError::InvalidFanSpeed { min, max, percentage }) } } } #[derive(Debug, Eq, PartialEq, Copy, Clone)] pub enum PwmMode { Manual, Automatic } pub struct Hwmon { path_temperature: PathBuf, path_pwm_enable: PathBuf, path_pwm: PathBuf, pwm_min: Pwm, pwm_max: Pwm, } impl Hwmon { pub fn for_device<P: AsRef<Path>>(device_path: P) -> Result<Vec<Hwmon>, GpuError> { let mut result = Vec::new(); let hwmons = device_path.as_ref().join("hwmon"); for entry in fs::read_dir(&hwmons)? { let entry = entry?; let path = entry.path(); if path.is_dir() { let hwmon = Hwmon::new(path)?; result.push(hwmon); } } Ok(result) } pub fn new<P: AsRef<Path>>(hwmon_path: P) -> Result<Self, GpuError> { let pwm_min_path = hwmon_path.as_ref().join("pwm1_min"); let pwm_max_path = hwmon_path.as_ref().join("pwm1_max"); let pwm_min_raw = Self::read_value(&pwm_min_path)?; let pwm_max_raw = Self::read_value(&pwm_max_path)?; Ok(Hwmon { path_temperature: hwmon_path.as_ref().join("temp1_input"), path_pwm_enable: hwmon_path.as_ref().join("pwm1_enable"), path_pwm: hwmon_path.as_ref().join("pwm1"), pwm_min: Pwm(pwm_min_raw), pwm_max: Pwm(pwm_max_raw), }) } pub fn get_temperature(&self) -> Result<Temperature, GpuError> { let temp_raw = Self::read_value(&self.path_temperature)?; Ok(Temperature(temp_raw)) } pub fn get_pwm_min(&self) -> Pwm { self.pwm_min } pub fn get_pwm_max(&self) -> Pwm { self.pwm_max } pub fn set_pwm_mode(&mut self, mode: PwmMode) -> Result<(), GpuError> { let value = match mode { PwmMode::Automatic => "2", PwmMode::Manual => "1", }; Self::write_value(&self.path_pwm_enable, value) } pub fn set_pwm(&mut self, value: Pwm) -> Result<(), GpuError> { let value_str = format!("{}\n", value.0); Self::write_value(&self.path_pwm, &value_str) } fn read_value<P: AsRef<Path>, V: std::str::FromStr>(path: P) -> Result<V, GpuError> { let file = fs::File::open(path.as_ref())?; let reader = io::BufReader::new(file); let contents = reader.lines().next().transpose()?; match contents.as_ref().map(|s| s.parse()) { Some(Ok(value)) => Ok(value), _ => Err(GpuError::Parse(path.as_ref().to_owned(), contents)), } } fn write_value<P: AsRef<Path>>(path: P, value: &str) -> Result<(), GpuError> { fs::write(path, value)?; Ok(()) } }
//! Type-safe units for buffers. //! //! It is often ambiguous what an index or offset means when dealing with text. This module //! provides types that include a strongly-typed unit to make the use of byte and codepoint //! indices more explicit. use euclid::{Length, Point2D}; #[derive(Debug)] pub struct ByteSpace; /// 1-dimensional index of a byte within a buffer. pub type ByteIndex = Length<usize, ByteSpace>; /// 2-dimensional Position of a byte in the buffer. /// /// `y` is the line number, `x` is the byte index within the line. pub type BytePosition = Point2D<usize, ByteSpace>; #[derive(Debug)] pub struct CharacterSpace; /// 2-dimensional position of a UTF-8 codepoint in the buffer. /// /// `y` is the line number, `x` is the character index within the line. pub type CharPosition = Point2D<usize, CharacterSpace>;
use super::button::Button; use seed::{prelude::*, *}; use std::{borrow::Cow, rc::Rc}; use uuid::Uuid; use wasm_bindgen::JsCast; use web_sys::{EventTarget, HtmlElement, MouseEvent}; type PopperInstance = JsValue; // ------ ------ // Init // ------ ------ pub fn init(orders: &mut impl Orders<Msg>) -> Model { Model { expanded: false, toggle: ElRef::default(), popup: ElRef::default(), popup_style: String::new(), id: Uuid::new_v4().to_string(), popper_data: None, _window_click_stream: orders .stream_with_handle(streams::window_event(Ev::Click, |event| { Msg::Collapse(Some(event.target().expect("event target"))) })), } } // ------ ------ // Model // ------ ------ pub struct Model { expanded: bool, toggle: ElRef<HtmlElement>, popup: ElRef<HtmlElement>, popup_style: String, id: String, popper_data: Option<PopperData>, _window_click_stream: StreamHandle, } // ------ PopperData ------ struct PopperData { popper_instance: PopperInstance, _on_apply_styles: Closure<dyn FnMut(String)>, } impl Drop for PopperData { fn drop(&mut self) { destroy_popper(&self.popper_instance) } } // ------ ------ // Update // ------ ------ #[derive(Debug)] pub enum Msg { ToggleClicked, UpdatePopper, Collapse(Option<EventTarget>), OnApplyStyles(String), } pub fn update(msg: Msg, model: &mut Model, orders: &mut impl Orders<Msg>) { match msg { Msg::ToggleClicked => { model.expanded = !model.expanded; if model.expanded { if model.popper_data.is_none() { model.popper_data = Some(show_popper(&model.toggle, &model.popup, orders)); } orders.after_next_render(|_| Msg::UpdatePopper); } } Msg::UpdatePopper => { if let Some(popper_data) = &model.popper_data { update_popper(&popper_data.popper_instance); } } Msg::Collapse(event_target) => { if model.expanded { match event_target { Some(event_target) => { let target = event_target .dyn_into::<web_sys::Node>() .expect("event_target into node"); let is_target_in_toggle = model .toggle .get() .expect("get dropdown toggle") .contains(Some(&target)); let is_target_in_popup = model .popup .get() .expect("get dropdopwn popup") .contains(Some(&target)); if !is_target_in_toggle && !is_target_in_popup { model.expanded = false; } } None => { model.expanded = false; } } } } Msg::OnApplyStyles(popup_style) => model.popup_style = popup_style, } } fn show_popper( toggle: &ElRef<HtmlElement>, popup: &ElRef<HtmlElement>, orders: &mut impl Orders<Msg>, ) -> PopperData { let (app, msg_mapper) = (orders.clone_app(), orders.msg_mapper()); let closure = Closure::new(move |popup_style| app.update(msg_mapper(Msg::OnApplyStyles(popup_style)))); let closure_as_js_value = closure.as_ref().clone(); let popper_instance = create_popper( toggle.get().expect("get toggle"), popup.get().expect("get popup"), closure_as_js_value, ); PopperData { popper_instance, _on_apply_styles: closure, } } #[wasm_bindgen(module = "/js/popper_wrapper.js")] extern "C" { fn create_popper( toggle_element: HtmlElement, popup_element: HtmlElement, _on_apply_styles: JsValue, ) -> PopperInstance; fn update_popper(popper_instance: &PopperInstance); fn destroy_popper(popper_instance: &PopperInstance); } // ------ ------ // View // ------ ------ // ------ Dropdown ------ pub struct Dropdown<Ms: 'static, ItemValue> { id: Option<Cow<'static, str>>, items: Vec<Item<ItemValue>>, on_item_clicks: Vec<Rc<dyn Fn(MouseEvent, ItemValue) -> Ms>>, toggle: Button<Ms>, } impl<Ms: 'static, ItemValue: Clone + 'static> Dropdown<Ms, ItemValue> { pub fn new(title: impl Into<Cow<'static, str>>) -> Self { Self::default().title(title) } pub fn title(mut self, title: impl Into<Cow<'static, str>>) -> Self { self.toggle = self.toggle.title(title); self } pub fn id(mut self, id: impl Into<Cow<'static, str>>) -> Self { self.id = Some(id.into()); self } pub fn items(mut self, items: Vec<Item<ItemValue>>) -> Self { self.items = items; self } pub fn add_on_item_click( mut self, on_item_click: impl FnOnce(MouseEvent, ItemValue) -> Ms + Clone + 'static, ) -> Self { self.on_item_clicks.push(Rc::new(move |event, item_value| { on_item_click.clone()(event, item_value) })); self } pub fn update_toggle(mut self, f: impl FnOnce(Button<Ms>) -> Button<Ms>) -> Self { self.toggle = f(self.toggle); self } pub fn view(self, model: &Model, to_msg: impl FnOnce(Msg) -> Ms + Clone + 'static) -> Node<Ms> { let to_msg = move |msg| to_msg.clone()(msg); let id = self.id.unwrap_or_else(|| model.id.clone().into()); let on_item_clicks = self.on_item_clicks.clone(); let toggle = self .toggle .add_attrs(id!(id.clone())) .add_attrs(C!["dropdown-toggle"]) .add_attrs(attrs! { At::from("aria-haspopup") => "true", At::from("aria-expanded") => model.expanded, }) .add_on_click({ let to_msg = to_msg.clone(); move |event| { event.prevent_default(); to_msg(Msg::ToggleClicked) } }) .el_ref(&model.toggle) .view_toggle(model.expanded); div![ C!["dropdown"], toggle, div![ el_ref(&model.popup), C!["dropdown-menu", IF!(model.expanded => "show")], attrs! { At::Style => model.popup_style, At::from("aria-labelledby") => id }, self.items .into_iter() .map(move |item| { item.into_element(to_msg.clone(), on_item_clicks.clone()) }) ], ] } pub fn view_in_nav( self, model: &Model, to_msg: impl FnOnce(Msg) -> Ms + Clone + 'static, ) -> Node<Ms> { let to_msg = move |msg| to_msg.clone()(msg); let id = self.id.unwrap_or_else(|| model.id.clone().into()); let on_item_clicks = self.on_item_clicks.clone(); let toggle = self .toggle .add_attrs(id!(id.clone())) .add_attrs(C!["nav-link", "dropdown-toggle"]) .add_attrs(attrs! { At::from("aria-haspopup") => "true", At::from("aria-expanded") => model.expanded, }) .add_on_click({ let to_msg = to_msg.clone(); move |event| { event.prevent_default(); to_msg(Msg::ToggleClicked) } }) .el_ref(&model.toggle) .link() .view_toggle(model.expanded); li![ C!["nav-item", "dropdown"], toggle, div![ el_ref(&model.popup), C!["dropdown-menu", IF!(model.expanded => "show")], attrs! { At::Style => model.popup_style, At::from("aria-labelledby") => id, }, self.items .into_iter() .map(move |item| { item.into_element(to_msg.clone(), on_item_clicks.clone()) }) ], ] } pub fn view_in_split_button( self, model: &Model, to_msg: impl FnOnce(Msg) -> Ms + Clone + 'static, scren_reader_title: &str, ) -> Vec<Node<Ms>> { let to_msg = move |msg| to_msg.clone()(msg); let id = self.id.unwrap_or_else(|| model.id.clone().into()); let on_item_clicks = self.on_item_clicks.clone(); let toggle = self .toggle .add_attrs(id!(id.clone())) .add_attrs(C!["dropdown-toggle"]) .add_attrs(attrs! { At::from("aria-haspopup") => "true", At::from("aria-expanded") => model.expanded, }) .add_attrs(C!["dropdown-toggle-split"]) .add_on_click({ let to_msg = to_msg.clone(); move |event| { event.prevent_default(); to_msg(Msg::ToggleClicked) } }) .content(span![C!["sr-only"], scren_reader_title]) .el_ref(&model.toggle) .view_toggle(model.expanded); vec![ toggle, div![ el_ref(&model.popup), C!["dropdown-menu", IF!(model.expanded => "show")], attrs! { At::Style => model.popup_style, At::from("aria-labelledby") => id }, self.items .into_iter() .map(move |item| { item.into_element(to_msg.clone(), on_item_clicks.clone()) }) ], ] } } impl<Ms, ItemValue> Default for Dropdown<Ms, ItemValue> { fn default() -> Self { Self { id: None, items: Vec::new(), on_item_clicks: Vec::new(), toggle: Button::default(), } } } // ------ Item ------ pub enum Item<ItemValue> { Button { title: Cow<'static, str>, value: ItemValue, }, A { title: Cow<'static, str>, value: ItemValue, href: Cow<'static, str>, }, Divider, } impl<ItemValue> Item<ItemValue> { pub fn button(title: impl Into<Cow<'static, str>>, value: ItemValue) -> Self { Self::Button { title: title.into(), value, } } pub fn a( title: impl Into<Cow<'static, str>>, value: ItemValue, href: impl Into<Cow<'static, str>>, ) -> Self { Self::A { title: title.into(), value, href: href.into(), } } pub fn divider() -> Self { Self::Divider } } impl<ItemValue: Clone + 'static> Item<ItemValue> { fn into_element<Ms: 'static>( self, to_msg: impl Fn(Msg) -> Ms + Clone + 'static, on_item_clicks: Vec<Rc<dyn Fn(MouseEvent, ItemValue) -> Ms>>, ) -> Node<Ms> { match self { Self::Button { title, value } => { let mut node = button![ C!["dropdown-item"], attrs! {At::Type => "button"}, title, ev(Ev::Click, move |_| to_msg(Msg::Collapse(None))), ]; for on_item_click in on_item_clicks { node.add_event_handler(mouse_ev(Ev::Click, { let value = value.clone(); move |event| on_item_click(event, value) })); } node } Self::A { title, value, href } => { let mut node = a![ C!["dropdown-item"], attrs! {At::Href => href}, title, ev(Ev::Click, move |_| to_msg(Msg::Collapse(None))), ]; for on_item_click in on_item_clicks { node.add_event_handler(mouse_ev(Ev::Click, { let value = value.clone(); move |event| on_item_click(event, value) })); } node } Self::Divider => div![C!["dropdown-divider"]], } } }
//! Rust bindings to libevdev, an wrapper for evdev devices. //! //! This library intends to provide a safe interface to the libevdev library. It //! will look for the library on the local system, and link to the installed copy. //! //! # Examples //! //! ## Intializing a evdev device //! //! ``` //! use evdev_rs::Device; //! use std::fs::File; //! //! let f = File::open("/dev/input/event0").unwrap(); //! //! let mut d = Device::new().unwrap(); //! d.set_fd(&f).unwrap(); //! ``` //! //! ## Getting the next event //! //! ```rust,no_run //! use evdev_rs::Device; //! use std::fs::File; //! //! let f = File::open("/dev/input/event0").unwrap(); //! //! let mut d = Device::new().unwrap(); //! d.set_fd(&f).unwrap(); //! //! loop { //! let a = d.next_event(evdev_rs::NORMAL | evdev_rs::BLOCKING); //! match a { //! Ok(k) => println!("Event: time {}.{}, ++++++++++++++++++++ {} +++++++++++++++", //! k.1.time.tv_sec, //! k.1.time.tv_usec, //! k.1.event_type), //! Err(e) => (), //! } //! } //! ``` extern crate evdev_sys as raw; extern crate nix; extern crate libc; #[macro_use] extern crate bitflags; #[macro_use] extern crate log; pub mod enums; pub mod logging; pub mod util; #[macro_use] mod macros; use libc::{c_char, c_int, c_long, c_uint, c_void}; use nix::errno::Errno; use std::any::Any; use std::ffi::{CStr, CString}; use std::fs::File; use std::os::unix::io::{AsRawFd, FromRawFd}; use enums::*; use util::*; pub enum GrabMode { /// Grab the device if not currently grabbed Grab = raw::LIBEVDEV_GRAB as isize, /// Ungrab the device if currently grabbed Ungrab = raw::LIBEVDEV_UNGRAB as isize, } bitflags! { pub flags ReadFlag: u32 { /// Process data in sync mode const SYNC = 1, /// Process data in normal mode const NORMAL = 2, /// Pretend the next event is a SYN_DROPPED and require the /// caller to sync const FORCE_SYNC = 4, /// The fd is not in O_NONBLOCK and a read may block const BLOCKING = 8, } } #[derive(PartialEq)] pub enum ReadStatus { /// `next_event` has finished without an error and an event is available /// for processing. Success = raw::LIBEVDEV_READ_STATUS_SUCCESS as isize, /// Depending on the `next_event` read flag: /// libevdev received a SYN_DROPPED from the device, and the caller should /// now resync the device, or, an event has been read in sync mode. Sync = raw::LIBEVDEV_READ_STATUS_SYNC as isize, } pub enum LedState { /// Turn the LED on On = raw::LIBEVDEV_LED_ON as isize, /// Turn the LED off Off = raw::LIBEVDEV_LED_OFF as isize, } pub struct DeviceId { pub bustype: BusType, pub vendor: u16, pub product: u16, pub version: u16, } /// used by EVIOCGABS/EVIOCSABS ioctls pub struct AbsInfo { /// latest reported value for the axis pub value: i32, /// specifies minimum value for the axis pub minimum: i32, /// specifies maximum value for the axis pub maximum: i32, /// specifies fuzz value that is used to filter noise from /// the event stream pub fuzz: i32, /// values that are within this value will be discarded by /// joydev interface and reported as 0 instead pub flat: i32, /// specifies resolution for the values reported for /// the axis pub resolution: i32, } /// Opaque struct representing an evdev device pub struct Device { raw: *mut raw::libevdev, } pub struct TimeVal { pub tv_sec: c_long, pub tv_usec: c_long, } /// The event structure itself pub struct InputEvent { /// The time at which event occured pub time: TimeVal, pub event_type: EventType, pub event_code: EventCode, pub value: i32, } fn ptr_to_str(ptr: *const c_char) -> Option<&'static str> { let slice : Option<&CStr> = unsafe { if ptr.is_null() { return None } Some(CStr::from_ptr(ptr)) }; match slice { None => None, Some(s) => { let buf : &[u8] = s.to_bytes(); Some(std::str::from_utf8(buf).unwrap()) } } } impl Device { /// Initialize a new libevdev device. /// /// This function only initializesthe struct to sane default values. /// To actually hook up the device to a kernel device, use `set_fd`. pub fn new() -> Option<Device> { let libevdev = unsafe { raw::libevdev_new() }; if libevdev.is_null() { None } else { Some(Device { raw: libevdev, }) } } /// Initialize a new libevdev device from the given fd. /// /// This is a shortcut for /// /// ``` /// use evdev_rs::Device; /// # use std::fs::File; /// /// let mut device = Device::new().unwrap(); /// # let fd = File::open("/dev/input/event0").unwrap(); /// device.set_fd(&fd); /// ``` pub fn new_from_fd(fd: &File) -> Result<Device, Errno> { let mut libevdev = 0 as *mut _; let result = unsafe { raw::libevdev_new_from_fd(fd.as_raw_fd(), &mut libevdev) }; match result { 0 => Ok(Device { raw: libevdev }), error => Err(Errno::from_i32(-error)), } } string_getter!(name, libevdev_get_name, phys, libevdev_get_phys, uniq, libevdev_get_uniq); string_setter!(set_name, libevdev_set_name, set_phys, libevdev_set_phys, set_uniq, libevdev_set_uniq); /// Returns the file associated with the device /// /// if the `set_fd` hasn't been called yet then it return `None` pub fn fd(&self) -> Option<File> { let result = unsafe { raw::libevdev_get_fd(self.raw) }; if result == 0 { None } else { unsafe { let f = File::from_raw_fd(result); Some(f) } } } /// Set the file for this struct and initialize internal data. /// /// This function may only be called once per device. If the device changed and /// you need to re-read a device, use `new` method. If you need to change the file after /// closing and re-opening the same device, use `change_fd`. /// /// Unless otherwise specified, evdev function behavior is undefined until /// a successfull call to `set_fd`. pub fn set_fd(&mut self, f: &File) -> Result<(), Errno> { let result = unsafe { raw::libevdev_set_fd(self.raw, f.as_raw_fd()) }; match result { 0 => Ok(()), error => Err(Errno::from_i32(-error)) } } /// Change the fd for this device, without re-reading the actual device. /// /// If the fd changes after initializing the device, for example after a /// VT-switch in the X.org X server, this function updates the internal fd /// to the newly opened. No check is made that new fd points to the same /// device. If the device has changed, evdev's behavior is undefined. /// /// evdev device does not sync itself after changing the fd and keeps the current /// device state. Use next_event with the FORCE_SYNC flag to force a re-sync. /// /// # Example /// /// ```rust,ignore /// dev.change_fd(new_fd); /// dev.next_event(evdev::FORCE_SYNC); /// while dev.next_event(evdev::SYNC).ok().unwrap().0 == ReadStatus::SYNC /// {} // noop /// ``` /// It is an error to call this function before calling set_fd(). pub fn change_fd(&mut self, f: &File) -> Result<(), Errno> { let result = unsafe { raw::libevdev_change_fd(self.raw, f.as_raw_fd()) }; match result { 0 => Ok(()), error => Err(Errno::from_i32(-error)) } } /// Grab or ungrab the device through a kernel EVIOCGRAB. /// /// This prevents other clients (including kernel-internal ones such as /// rfkill) from receiving events from this device. This is generally a /// bad idea. Don't do this.Grabbing an already grabbed device, or /// ungrabbing an ungrabbed device is a noop and always succeeds. pub fn grab(&mut self, grab: GrabMode) -> Result<(), Errno> { let result = unsafe { raw::libevdev_grab(self.raw, grab as c_int) }; match result { 0 => Ok(()), error => Err(Errno::from_i32(-error)), } } /// Get the axis info for the given axis, as advertised by the kernel. /// /// Returns the `AbsInfo` for the given the code or None if the device /// doesn't support this code pub fn abs_info(&self, code: &EventCode) -> Option<AbsInfo> { let (_, ev_code) = event_code_to_int(code); let a = unsafe { raw::libevdev_get_abs_info(self.raw, ev_code) }; if a.is_null() { return None } unsafe { let absinfo = AbsInfo { value: (*a).value, minimum: (*a).minimum, maximum: (*a).maximum, fuzz: (*a).fuzz, flat: (*a).flat, resolution: (*a).resolution, }; Some(absinfo) } } /// Change the abs info for the given EV_ABS event code, if the code exists. /// /// This function has no effect if `has_event_code` returns false for /// this code. pub fn set_abs_info(&self, code: &EventCode, absinfo: &AbsInfo) { let (_, ev_code) = event_code_to_int(code); let absinfo = raw::input_absinfo { value: absinfo.value, minimum: absinfo.minimum, maximum: absinfo.maximum, fuzz: absinfo.fuzz, flat: absinfo.flat, resolution: absinfo.resolution, }; unsafe { raw::libevdev_set_abs_info(self.raw, ev_code, &absinfo as *const _); } } /// Returns `true` if device support the InputProp/EventType/EventCode and false otherwise pub fn has(&self, blob: &Any) -> bool { if let Some(ev_type) = blob.downcast_ref::<EventType>() { self.has_event_type(ev_type) } else if let Some(ev_code) = blob.downcast_ref::<EventCode>() { self.has_event_code(ev_code) } else if let Some(prop) = blob.downcast_ref::<InputProp>() { self.has_property(prop) } else { false } } /// Forcibly enable an EventType/InputProp on this device, even if the underlying /// device does not support it. While this cannot make the device actually /// report such events, it will now return true for has(). /// /// This is a local modification only affecting only this representation of /// this device. pub fn enable(&self, blob: &Any) -> Result<(),Errno> { if let Some(ev_type) = blob.downcast_ref::<EventType>() { self.enable_event_type(ev_type) } else if let Some(ev_code) = blob.downcast_ref::<EventCode>() { self.enable_event_code(ev_code, &0) } else if let Some(prop) = blob.downcast_ref::<InputProp>() { self.enable_property(prop) } else { Err(Errno::from_i32(-1)) } } /// Returns `true` if device support the property and false otherwise fn has_property(&self, prop: &InputProp) -> bool { unsafe { raw::libevdev_has_property(self.raw, prop.clone() as c_uint) != 0 } } /// Enables this property, a call to `set_fd` will overwrite any previously set values fn enable_property(&self, prop: &InputProp) -> Result<(), Errno> { let result = unsafe { raw::libevdev_enable_property(self.raw, prop.clone() as c_uint) as i32 }; match result { 0 => Ok(()), error => Err(Errno::from_i32(-error)) } } /// Returns `true` is the device support this event type and `false` otherwise fn has_event_type(&self, ev_type: &EventType) -> bool { unsafe { raw::libevdev_has_event_type(self.raw, ev_type.clone() as c_uint) != 0 } } /// Return `true` is the device support this event type and code and `false` otherwise fn has_event_code(&self, code: &EventCode) -> bool { unsafe { let (ev_type, ev_code) = event_code_to_int(code); raw::libevdev_has_event_code(self.raw, ev_type, ev_code) != 0 } } /// Returns the current value of the event type. /// /// If the device supports this event type and code, the return value is /// set to the current value of this axis. Otherwise, `None` is returned. pub fn event_value(&self, code: &EventCode) -> Option<i32> { let mut value: i32 = 0; let (ev_type, ev_code) = event_code_to_int(code); let valid = unsafe { raw::libevdev_fetch_event_value(self.raw, ev_type, ev_code , &mut value) }; match valid { 0 => None, _ => Some(value), } } /// Set the value for a given event type and code. /// /// This only makes sense for some event types, e.g. setting the value for /// EV_REL is pointless. /// /// This is a local modification only affecting only this representation of /// this device. A future call to event_value() will return this /// value, unless the value was overwritten by an event. /// /// If the device supports ABS_MT_SLOT, the value set for any ABS_MT_* /// event code is the value of the currently active slot. You should use /// `set_slot_value` instead. /// /// If the device supports ABS_MT_SLOT and the type is EV_ABS and the code is /// ABS_MT_SLOT, the value must be a positive number less then the number of /// slots on the device. Otherwise, `set_event_value` returns Err. pub fn set_event_value(&self, code: &EventCode, val: i32) -> Result<(), Errno> { let (ev_type, ev_code) = event_code_to_int(code); let result = unsafe { raw::libevdev_set_event_value(self.raw, ev_type, ev_code, val as c_int) }; match result { 0 => Ok(()), error => Err(Errno::from_i32(-error)) } } /// Check if there are events waiting for us. /// /// This function does not read an event off the fd and may not access the /// fd at all. If there are events queued internally this function will /// return non-zero. If the internal queue is empty, this function will poll /// the file descriptor for data. /// /// This is a convenience function for simple processes, most complex programs /// are expected to use select(2) or poll(2) on the file descriptor. The kernel /// guarantees that if data is available, it is a multiple of sizeof(struct /// input_event), and thus calling `next_event` when select(2) or /// poll(2) return is safe. You do not need `has_event_pending` if /// you're using select(2) or poll(2). pub fn has_event_pending(&self) -> bool { unsafe { raw::libevdev_has_event_pending(self.raw) > 0 } } product_getter!(product_id, libevdev_get_id_product, vendor_id, libevdev_get_id_vendor, bustype, libevdev_get_id_bustype, version, libevdev_get_id_version); product_setter!(set_product_id, libevdev_set_id_product, set_vendor_id, libevdev_set_id_vendor, set_bustype, libevdev_set_id_bustype, set_version, libevdev_set_id_version); /// Return the driver version of a device already intialize with `set_fd` pub fn driver_version(&self) -> i32 { unsafe { raw::libevdev_get_driver_version(self.raw) as i32 } } abs_getter!(abs_minimum, libevdev_get_abs_minimum, abs_maximum, libevdev_get_abs_maximum, abs_fuzz, libevdev_get_abs_fuzz, abs_flat, libevdev_get_abs_flat, abs_resolution, libevdev_get_abs_resolution); abs_setter!(set_abs_minimum, libevdev_set_abs_minimum, set_abs_maximum, libevdev_set_abs_maximum, set_abs_fuzz, libevdev_set_abs_fuzz, set_abs_flat, libevdev_set_abs_flat, set_abs_resolution, libevdev_set_abs_resolution); /// Return the current value of the code for the given slot. /// /// If the device supports this event code, the return value is /// is set to the current value of this axis. Otherwise, or /// if the event code is not an ABS_MT_* event code, `None` is returned pub fn slot_value(&self, slot: u32, code: &EventCode) -> Option<i32> { let (_, ev_code) = event_code_to_int(code); let mut value: i32 = 0; let valid = unsafe { raw::libevdev_fetch_slot_value(self.raw, slot as c_uint, ev_code, &mut value) }; match valid { 0 => None, _ => Some(value), } } /// Set the value for a given code for the given slot. /// /// This is a local modification only affecting only this representation of /// this device. A future call to `slot_value` will return this value, /// unless the value was overwritten by an event. /// /// This function does not set event values for axes outside the ABS_MT range, /// use `set_event_value` instead. pub fn set_slot_value(&self, slot: u32, code: &EventCode, val: i32) -> Result<(), Errno> { let (_, ev_code) = event_code_to_int(code); let result = unsafe { raw::libevdev_set_slot_value(self.raw, slot as c_uint, ev_code, val as c_int) }; match result { 0 => Ok(()), error => Err(Errno::from_i32(-error)) } } /// Get the number of slots supported by this device. /// /// The number of slots supported, or `None` if the device does not provide /// any slots /// /// A device may provide ABS_MT_SLOT but a total number of 0 slots. Hence /// the return value of `None` for "device does not provide slots at all" pub fn num_slots(&self) -> Option<i32> { let result = unsafe { raw::libevdev_get_num_slots(self.raw) }; match result { -1 => None, slots => Some(slots), } } /// Get the currently active slot. /// /// This may differ from the value an ioctl may return at this time as /// events may have been read off the fd since changing the slot value /// but those events are still in the buffer waiting to be processed. /// The returned value is the value a caller would see if it were to /// process events manually one-by-one. pub fn current_slot(&self) -> Option<i32> { let result = unsafe { raw::libevdev_get_current_slot(self.raw) }; match result { -1 => None, slots => Some(slots), } } /// Forcibly enable an event type on this device, even if the underlying /// device does not support it. While this cannot make the device actually /// report such events, it will now return true for libevdev_has_event_type(). /// /// This is a local modification only affecting only this representation of /// this device. fn enable_event_type(&self, ev_type: &EventType) -> Result<(), Errno> { let result = unsafe { raw::libevdev_enable_event_type(self.raw, ev_type.clone() as c_uint) }; match result { 0 => Ok(()), error => Err(Errno::from_i32(-error)) } } fn enable_event_code(&self, ev_code: &EventCode, data: &Any) -> Result<(), Errno> { let (ev_type, ev_code) = event_code_to_int(ev_code); let result = unsafe { raw::libevdev_enable_event_code(self.raw, ev_type as c_uint, ev_code as c_uint, data as *const _ as *const c_void) }; match result { 0 => Ok(()), error => Err(Errno::from_i32(-error)) } } /// Forcibly disable an EventType/EventCode on this device, even if the /// underlying device provides it. This effectively mutes the respective set of /// events. has() will return false for this EventType/EventCode /// /// In most cases, a caller likely only wants to disable a single code, not /// the whole type. /// /// Disabling EV_SYN will not work. In Peter's Words "Don't shoot yourself /// in the foot. It hurts". /// /// This is a local modification only affecting only this representation of /// this device. pub fn disable(&self, blob: &Any) -> Result<(),Errno> { if let Some(ev_type) = blob.downcast_ref::<EventType>() { self.disable_event_type(ev_type) } else if let Some(ev_code) = blob.downcast_ref::<EventCode>() { self.disable_event_code(ev_code) } else { Err(Errno::from_i32(-1)) } } /// Forcibly disable an event type on this device, even if the underlying /// device provides it. This effectively mutes the respective set of /// events. libevdev will filter any events matching this type and none will /// reach the caller. libevdev_has_event_type() will return false for this /// type. /// /// In most cases, a caller likely only wants to disable a single code, not /// the whole type. Use `disable_event_code` for that. /// /// Disabling EV_SYN will not work. In Peter's Words "Don't shoot yourself /// in the foot. It hurts". /// /// This is a local modification only affecting only this representation of /// this device. fn disable_event_type(&self, ev_type: &EventType) -> Result<(), Errno> { let result = unsafe { raw::libevdev_disable_event_type(self.raw, ev_type.clone() as c_uint) }; match result { 0 => Ok(()), error => Err(Errno::from_i32(-error)) } } /// Forcibly disable an event code on this device, even if the underlying /// device provides it. This effectively mutes the respective set of /// events. libevdev will filter any events matching this type and code and /// none will reach the caller. `has_event_code` will return false for /// this code. /// /// Disabling all event codes for a given type will not disable the event /// type. Use `disable_event_type` for that. /// /// This is a local modification only affecting only this representation of /// this device. /// /// Disabling codes of type EV_SYN will not work. Don't shoot yourself in the /// foot. It hurts. fn disable_event_code(&self, code: &EventCode) -> Result<(), Errno> { let (ev_type, ev_code) = event_code_to_int(code); let result = unsafe { raw::libevdev_disable_event_code(self.raw, ev_type, ev_code) }; match result { 0 => Ok(()), error => Err(Errno::from_i32(-error)) } } /// Set the device's EV_ABS axis to the value defined in the abs /// parameter. This will be written to the kernel. pub fn set_kernel_abs_info(&self, code: &EventCode, absinfo: &AbsInfo) { let (_, ev_code) = event_code_to_int(code); let absinfo = raw::input_absinfo { value: absinfo.value, minimum: absinfo.minimum, maximum: absinfo.maximum, fuzz: absinfo.fuzz, flat: absinfo.flat, resolution: absinfo.resolution, }; unsafe { raw::libevdev_kernel_set_abs_info(self.raw, ev_code, &absinfo as *const _); } } /// Turn an LED on or off. /// /// enabling an LED requires write permissions on the device's file descriptor. pub fn kernel_set_led_value(&self, code: &EventCode, value: LedState) -> Result<(), Errno> { let (_, ev_code) = event_code_to_int(code); let result = unsafe { raw::libevdev_kernel_set_led_value(self.raw, ev_code, value as c_int) }; match result { 0 => Ok(()), error => Err(Errno::from_i32(-error)) } } /// Set the clock ID to be used for timestamps. Further events from this device /// will report an event time based on the given clock. /// /// This is a modification only affecting this representation of /// this device. pub fn set_clock_id(&self, clockid: i32) -> Result<(), Errno> { let result = unsafe { raw::libevdev_set_clock_id(self.raw, clockid as c_int) }; match result { 0 => Ok(()), error => Err(Errno::from_i32(-error)) } } /// Get the next event from the device. This function operates in two different /// modes: normal mode or sync mode. /// /// In normal mode (when flags has `evdev::NORMAL` set), this function returns /// `ReadStatus::Success` and returns the event. If no events are available at /// this time, it returns `-EAGAIN` as `Err`. /// /// If the current event is an `EV_SYN::SYN_DROPPED` event, this function returns /// `ReadStatus::Sync` and is set to the `EV_SYN` event.The caller should now call /// this function with the `evdev::SYNC` flag set, to get the set of events that /// make up the device state delta. This function returns ReadStatus::Sync for /// each event part of that delta, until it returns `-EAGAIN` once all events /// have been synced. /// /// If a device needs to be synced by the caller but the caller does not call /// with the `evdev::SYNC` flag set, all events from the diff are dropped after /// evdev updates its internal state and event processing continues as normal. /// Note that the current slot and the state of touch points may have updated /// during the `SYN_DROPPED` event, it is strongly recommended that a caller /// ignoring all sync events calls `current_slot` and checks the /// `ABS_MT_TRACKING_ID` values for all slots. /// /// If a device has changed state without events being enqueued in evdev, /// e.g. after changing the file descriptor, use the `evdev::FORCE_SYNC` flag. /// This triggers an internal sync of the device and `next_event` returns /// `ReadStatus::Sync`. pub fn next_event(&self, flags: ReadFlag) -> Result<(ReadStatus, InputEvent), Errno> { let mut ev = raw::input_event { time: raw::timeval { tv_sec: 0, tv_usec: 0, }, event_type: 0, event_code: 0, value: 0, }; let result = unsafe { raw::libevdev_next_event(self.raw, flags.bits as c_uint, &mut ev) }; let event = InputEvent { time: TimeVal { tv_sec: ev.time.tv_sec, tv_usec: ev.time.tv_usec, }, event_type: int_to_event_type(ev.event_type as u32).unwrap(), event_code: int_to_event_code(ev.event_type as u32, ev.event_code as u32).unwrap(), value: ev.value, }; match result { raw::LIBEVDEV_READ_STATUS_SUCCESS => Ok((ReadStatus::Success, event)), raw::LIBEVDEV_READ_STATUS_SYNC => Ok((ReadStatus::Sync, event)), error => Err(Errno::from_i32(-error)), } } } impl InputEvent { pub fn is_type(&self, ev_type: &EventType) -> bool { let ev = raw::input_event { time: raw::timeval { tv_sec: self.time.tv_sec, tv_usec: self.time.tv_usec, }, event_type: self.event_type.clone() as u16, event_code: event_code_to_int(&self.event_code).1 as u16, value: self.value, }; unsafe { raw::libevdev_event_is_type(&ev, ev_type.clone() as c_uint) == 1 } } pub fn is_code(&self, code: &EventCode) -> bool { let (ev_type, ev_code) = event_code_to_int(code); let ev = raw::input_event { time: raw::timeval { tv_sec: self.time.tv_sec, tv_usec: self.time.tv_usec, }, event_type: self.event_type.clone() as u16, event_code: event_code_to_int(&self.event_code).1 as u16, value: self.value, }; unsafe { raw::libevdev_event_is_code(&ev, ev_type, ev_code) == 1 } } } impl Drop for Device { fn drop(&mut self) { unsafe { raw::libevdev_free(self.raw); } } }
// auto generated, do not modify. // created: Mon Feb 22 23:57:02 2016 // src-file: /QtWidgets/qgridlayout.h // dst-file: /src/widgets/qgridlayout.rs // // header block begin => #![feature(libc)] #![feature(core)] #![feature(collections)] extern crate libc; use self::libc::*; // <= header block end // main block begin => // <= main block end // use block begin => use super::qlayout::*; // 773 use std::ops::Deref; use super::qlayoutitem::*; // 773 use super::super::core::qsize::*; // 771 use super::super::core::qrect::*; // 771 use super::qwidget::*; // 773 use super::super::core::qobjectdefs::*; // 771 // <= use block end // ext block begin => // #[link(name = "Qt5Core")] // #[link(name = "Qt5Gui")] // #[link(name = "Qt5Widgets")] // #[link(name = "QtInline")] extern { fn QGridLayout_Class_Size() -> c_int; // proto: void QGridLayout::setRowMinimumHeight(int row, int minSize); fn C_ZN11QGridLayout19setRowMinimumHeightEii(qthis: u64 /* *mut c_void*/, arg0: c_int, arg1: c_int); // proto: QLayoutItem * QGridLayout::takeAt(int index); fn C_ZN11QGridLayout6takeAtEi(qthis: u64 /* *mut c_void*/, arg0: c_int) -> *mut c_void; // proto: void QGridLayout::getItemPosition(int idx, int * row, int * column, int * rowSpan, int * columnSpan); fn C_ZNK11QGridLayout15getItemPositionEiPiS0_S0_S0_(qthis: u64 /* *mut c_void*/, arg0: c_int, arg1: *mut c_int, arg2: *mut c_int, arg3: *mut c_int, arg4: *mut c_int); // proto: int QGridLayout::minimumHeightForWidth(int ); fn C_ZNK11QGridLayout21minimumHeightForWidthEi(qthis: u64 /* *mut c_void*/, arg0: c_int) -> c_int; // proto: int QGridLayout::rowMinimumHeight(int row); fn C_ZNK11QGridLayout16rowMinimumHeightEi(qthis: u64 /* *mut c_void*/, arg0: c_int) -> c_int; // proto: void QGridLayout::invalidate(); fn C_ZN11QGridLayout10invalidateEv(qthis: u64 /* *mut c_void*/); // proto: int QGridLayout::count(); fn C_ZNK11QGridLayout5countEv(qthis: u64 /* *mut c_void*/) -> c_int; // proto: void QGridLayout::setColumnStretch(int column, int stretch); fn C_ZN11QGridLayout16setColumnStretchEii(qthis: u64 /* *mut c_void*/, arg0: c_int, arg1: c_int); // proto: int QGridLayout::spacing(); fn C_ZNK11QGridLayout7spacingEv(qthis: u64 /* *mut c_void*/) -> c_int; // proto: int QGridLayout::rowStretch(int row); fn C_ZNK11QGridLayout10rowStretchEi(qthis: u64 /* *mut c_void*/, arg0: c_int) -> c_int; // proto: QSize QGridLayout::sizeHint(); fn C_ZNK11QGridLayout8sizeHintEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: int QGridLayout::rowCount(); fn C_ZNK11QGridLayout8rowCountEv(qthis: u64 /* *mut c_void*/) -> c_int; // proto: void QGridLayout::setGeometry(const QRect & ); fn C_ZN11QGridLayout11setGeometryERK5QRect(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); // proto: void QGridLayout::setVerticalSpacing(int spacing); fn C_ZN11QGridLayout18setVerticalSpacingEi(qthis: u64 /* *mut c_void*/, arg0: c_int); // proto: void QGridLayout::setHorizontalSpacing(int spacing); fn C_ZN11QGridLayout20setHorizontalSpacingEi(qthis: u64 /* *mut c_void*/, arg0: c_int); // proto: int QGridLayout::columnStretch(int column); fn C_ZNK11QGridLayout13columnStretchEi(qthis: u64 /* *mut c_void*/, arg0: c_int) -> c_int; // proto: int QGridLayout::columnCount(); fn C_ZNK11QGridLayout11columnCountEv(qthis: u64 /* *mut c_void*/) -> c_int; // proto: int QGridLayout::columnMinimumWidth(int column); fn C_ZNK11QGridLayout18columnMinimumWidthEi(qthis: u64 /* *mut c_void*/, arg0: c_int) -> c_int; // proto: QSize QGridLayout::minimumSize(); fn C_ZNK11QGridLayout11minimumSizeEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: bool QGridLayout::hasHeightForWidth(); fn C_ZNK11QGridLayout17hasHeightForWidthEv(qthis: u64 /* *mut c_void*/) -> c_char; // proto: QRect QGridLayout::cellRect(int row, int column); fn C_ZNK11QGridLayout8cellRectEii(qthis: u64 /* *mut c_void*/, arg0: c_int, arg1: c_int) -> *mut c_void; // proto: void QGridLayout::setRowStretch(int row, int stretch); fn C_ZN11QGridLayout13setRowStretchEii(qthis: u64 /* *mut c_void*/, arg0: c_int, arg1: c_int); // proto: QLayoutItem * QGridLayout::itemAtPosition(int row, int column); fn C_ZNK11QGridLayout14itemAtPositionEii(qthis: u64 /* *mut c_void*/, arg0: c_int, arg1: c_int) -> *mut c_void; // proto: const QMetaObject * QGridLayout::metaObject(); fn C_ZNK11QGridLayout10metaObjectEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: int QGridLayout::verticalSpacing(); fn C_ZNK11QGridLayout15verticalSpacingEv(qthis: u64 /* *mut c_void*/) -> c_int; // proto: void QGridLayout::QGridLayout(QWidget * parent); fn C_ZN11QGridLayoutC2EP7QWidget(arg0: *mut c_void) -> u64; // proto: int QGridLayout::horizontalSpacing(); fn C_ZNK11QGridLayout17horizontalSpacingEv(qthis: u64 /* *mut c_void*/) -> c_int; // proto: void QGridLayout::setColumnMinimumWidth(int column, int minSize); fn C_ZN11QGridLayout21setColumnMinimumWidthEii(qthis: u64 /* *mut c_void*/, arg0: c_int, arg1: c_int); // proto: void QGridLayout::QGridLayout(); fn C_ZN11QGridLayoutC2Ev() -> u64; // proto: int QGridLayout::heightForWidth(int ); fn C_ZNK11QGridLayout14heightForWidthEi(qthis: u64 /* *mut c_void*/, arg0: c_int) -> c_int; // proto: void QGridLayout::~QGridLayout(); fn C_ZN11QGridLayoutD2Ev(qthis: u64 /* *mut c_void*/); // proto: void QGridLayout::setSpacing(int spacing); fn C_ZN11QGridLayout10setSpacingEi(qthis: u64 /* *mut c_void*/, arg0: c_int); // proto: void QGridLayout::addWidget(QWidget * w); fn C_ZN11QGridLayout9addWidgetEP7QWidget(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); // proto: QLayoutItem * QGridLayout::itemAt(int index); fn C_ZNK11QGridLayout6itemAtEi(qthis: u64 /* *mut c_void*/, arg0: c_int) -> *mut c_void; // proto: QSize QGridLayout::maximumSize(); fn C_ZNK11QGridLayout11maximumSizeEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; } // <= ext block end // body block begin => // class sizeof(QGridLayout)=1 #[derive(Default)] pub struct QGridLayout { qbase: QLayout, pub qclsinst: u64 /* *mut c_void*/, } impl /*struct*/ QGridLayout { pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QGridLayout { return QGridLayout{qbase: QLayout::inheritFrom(qthis), qclsinst: qthis, ..Default::default()}; } } impl Deref for QGridLayout { type Target = QLayout; fn deref(&self) -> &QLayout { return & self.qbase; } } impl AsRef<QLayout> for QGridLayout { fn as_ref(& self) -> & QLayout { return & self.qbase; } } // proto: void QGridLayout::setRowMinimumHeight(int row, int minSize); impl /*struct*/ QGridLayout { pub fn setRowMinimumHeight<RetType, T: QGridLayout_setRowMinimumHeight<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setRowMinimumHeight(self); // return 1; } } pub trait QGridLayout_setRowMinimumHeight<RetType> { fn setRowMinimumHeight(self , rsthis: & QGridLayout) -> RetType; } // proto: void QGridLayout::setRowMinimumHeight(int row, int minSize); impl<'a> /*trait*/ QGridLayout_setRowMinimumHeight<()> for (i32, i32) { fn setRowMinimumHeight(self , rsthis: & QGridLayout) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN11QGridLayout19setRowMinimumHeightEii()}; let arg0 = self.0 as c_int; let arg1 = self.1 as c_int; unsafe {C_ZN11QGridLayout19setRowMinimumHeightEii(rsthis.qclsinst, arg0, arg1)}; // return 1; } } // proto: QLayoutItem * QGridLayout::takeAt(int index); impl /*struct*/ QGridLayout { pub fn takeAt<RetType, T: QGridLayout_takeAt<RetType>>(& self, overload_args: T) -> RetType { return overload_args.takeAt(self); // return 1; } } pub trait QGridLayout_takeAt<RetType> { fn takeAt(self , rsthis: & QGridLayout) -> RetType; } // proto: QLayoutItem * QGridLayout::takeAt(int index); impl<'a> /*trait*/ QGridLayout_takeAt<QLayoutItem> for (i32) { fn takeAt(self , rsthis: & QGridLayout) -> QLayoutItem { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN11QGridLayout6takeAtEi()}; let arg0 = self as c_int; let mut ret = unsafe {C_ZN11QGridLayout6takeAtEi(rsthis.qclsinst, arg0)}; let mut ret1 = QLayoutItem::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QGridLayout::getItemPosition(int idx, int * row, int * column, int * rowSpan, int * columnSpan); impl /*struct*/ QGridLayout { pub fn getItemPosition<RetType, T: QGridLayout_getItemPosition<RetType>>(& self, overload_args: T) -> RetType { return overload_args.getItemPosition(self); // return 1; } } pub trait QGridLayout_getItemPosition<RetType> { fn getItemPosition(self , rsthis: & QGridLayout) -> RetType; } // proto: void QGridLayout::getItemPosition(int idx, int * row, int * column, int * rowSpan, int * columnSpan); impl<'a> /*trait*/ QGridLayout_getItemPosition<()> for (i32, &'a mut Vec<i32>, &'a mut Vec<i32>, &'a mut Vec<i32>, &'a mut Vec<i32>) { fn getItemPosition(self , rsthis: & QGridLayout) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK11QGridLayout15getItemPositionEiPiS0_S0_S0_()}; let arg0 = self.0 as c_int; let arg1 = self.1.as_ptr() as *mut c_int; let arg2 = self.2.as_ptr() as *mut c_int; let arg3 = self.3.as_ptr() as *mut c_int; let arg4 = self.4.as_ptr() as *mut c_int; unsafe {C_ZNK11QGridLayout15getItemPositionEiPiS0_S0_S0_(rsthis.qclsinst, arg0, arg1, arg2, arg3, arg4)}; // return 1; } } // proto: int QGridLayout::minimumHeightForWidth(int ); impl /*struct*/ QGridLayout { pub fn minimumHeightForWidth<RetType, T: QGridLayout_minimumHeightForWidth<RetType>>(& self, overload_args: T) -> RetType { return overload_args.minimumHeightForWidth(self); // return 1; } } pub trait QGridLayout_minimumHeightForWidth<RetType> { fn minimumHeightForWidth(self , rsthis: & QGridLayout) -> RetType; } // proto: int QGridLayout::minimumHeightForWidth(int ); impl<'a> /*trait*/ QGridLayout_minimumHeightForWidth<i32> for (i32) { fn minimumHeightForWidth(self , rsthis: & QGridLayout) -> i32 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK11QGridLayout21minimumHeightForWidthEi()}; let arg0 = self as c_int; let mut ret = unsafe {C_ZNK11QGridLayout21minimumHeightForWidthEi(rsthis.qclsinst, arg0)}; return ret as i32; // 1 // return 1; } } // proto: int QGridLayout::rowMinimumHeight(int row); impl /*struct*/ QGridLayout { pub fn rowMinimumHeight<RetType, T: QGridLayout_rowMinimumHeight<RetType>>(& self, overload_args: T) -> RetType { return overload_args.rowMinimumHeight(self); // return 1; } } pub trait QGridLayout_rowMinimumHeight<RetType> { fn rowMinimumHeight(self , rsthis: & QGridLayout) -> RetType; } // proto: int QGridLayout::rowMinimumHeight(int row); impl<'a> /*trait*/ QGridLayout_rowMinimumHeight<i32> for (i32) { fn rowMinimumHeight(self , rsthis: & QGridLayout) -> i32 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK11QGridLayout16rowMinimumHeightEi()}; let arg0 = self as c_int; let mut ret = unsafe {C_ZNK11QGridLayout16rowMinimumHeightEi(rsthis.qclsinst, arg0)}; return ret as i32; // 1 // return 1; } } // proto: void QGridLayout::invalidate(); impl /*struct*/ QGridLayout { pub fn invalidate<RetType, T: QGridLayout_invalidate<RetType>>(& self, overload_args: T) -> RetType { return overload_args.invalidate(self); // return 1; } } pub trait QGridLayout_invalidate<RetType> { fn invalidate(self , rsthis: & QGridLayout) -> RetType; } // proto: void QGridLayout::invalidate(); impl<'a> /*trait*/ QGridLayout_invalidate<()> for () { fn invalidate(self , rsthis: & QGridLayout) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN11QGridLayout10invalidateEv()}; unsafe {C_ZN11QGridLayout10invalidateEv(rsthis.qclsinst)}; // return 1; } } // proto: int QGridLayout::count(); impl /*struct*/ QGridLayout { pub fn count<RetType, T: QGridLayout_count<RetType>>(& self, overload_args: T) -> RetType { return overload_args.count(self); // return 1; } } pub trait QGridLayout_count<RetType> { fn count(self , rsthis: & QGridLayout) -> RetType; } // proto: int QGridLayout::count(); impl<'a> /*trait*/ QGridLayout_count<i32> for () { fn count(self , rsthis: & QGridLayout) -> i32 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK11QGridLayout5countEv()}; let mut ret = unsafe {C_ZNK11QGridLayout5countEv(rsthis.qclsinst)}; return ret as i32; // 1 // return 1; } } // proto: void QGridLayout::setColumnStretch(int column, int stretch); impl /*struct*/ QGridLayout { pub fn setColumnStretch<RetType, T: QGridLayout_setColumnStretch<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setColumnStretch(self); // return 1; } } pub trait QGridLayout_setColumnStretch<RetType> { fn setColumnStretch(self , rsthis: & QGridLayout) -> RetType; } // proto: void QGridLayout::setColumnStretch(int column, int stretch); impl<'a> /*trait*/ QGridLayout_setColumnStretch<()> for (i32, i32) { fn setColumnStretch(self , rsthis: & QGridLayout) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN11QGridLayout16setColumnStretchEii()}; let arg0 = self.0 as c_int; let arg1 = self.1 as c_int; unsafe {C_ZN11QGridLayout16setColumnStretchEii(rsthis.qclsinst, arg0, arg1)}; // return 1; } } // proto: int QGridLayout::spacing(); impl /*struct*/ QGridLayout { pub fn spacing<RetType, T: QGridLayout_spacing<RetType>>(& self, overload_args: T) -> RetType { return overload_args.spacing(self); // return 1; } } pub trait QGridLayout_spacing<RetType> { fn spacing(self , rsthis: & QGridLayout) -> RetType; } // proto: int QGridLayout::spacing(); impl<'a> /*trait*/ QGridLayout_spacing<i32> for () { fn spacing(self , rsthis: & QGridLayout) -> i32 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK11QGridLayout7spacingEv()}; let mut ret = unsafe {C_ZNK11QGridLayout7spacingEv(rsthis.qclsinst)}; return ret as i32; // 1 // return 1; } } // proto: int QGridLayout::rowStretch(int row); impl /*struct*/ QGridLayout { pub fn rowStretch<RetType, T: QGridLayout_rowStretch<RetType>>(& self, overload_args: T) -> RetType { return overload_args.rowStretch(self); // return 1; } } pub trait QGridLayout_rowStretch<RetType> { fn rowStretch(self , rsthis: & QGridLayout) -> RetType; } // proto: int QGridLayout::rowStretch(int row); impl<'a> /*trait*/ QGridLayout_rowStretch<i32> for (i32) { fn rowStretch(self , rsthis: & QGridLayout) -> i32 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK11QGridLayout10rowStretchEi()}; let arg0 = self as c_int; let mut ret = unsafe {C_ZNK11QGridLayout10rowStretchEi(rsthis.qclsinst, arg0)}; return ret as i32; // 1 // return 1; } } // proto: QSize QGridLayout::sizeHint(); impl /*struct*/ QGridLayout { pub fn sizeHint<RetType, T: QGridLayout_sizeHint<RetType>>(& self, overload_args: T) -> RetType { return overload_args.sizeHint(self); // return 1; } } pub trait QGridLayout_sizeHint<RetType> { fn sizeHint(self , rsthis: & QGridLayout) -> RetType; } // proto: QSize QGridLayout::sizeHint(); impl<'a> /*trait*/ QGridLayout_sizeHint<QSize> for () { fn sizeHint(self , rsthis: & QGridLayout) -> QSize { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK11QGridLayout8sizeHintEv()}; let mut ret = unsafe {C_ZNK11QGridLayout8sizeHintEv(rsthis.qclsinst)}; let mut ret1 = QSize::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: int QGridLayout::rowCount(); impl /*struct*/ QGridLayout { pub fn rowCount<RetType, T: QGridLayout_rowCount<RetType>>(& self, overload_args: T) -> RetType { return overload_args.rowCount(self); // return 1; } } pub trait QGridLayout_rowCount<RetType> { fn rowCount(self , rsthis: & QGridLayout) -> RetType; } // proto: int QGridLayout::rowCount(); impl<'a> /*trait*/ QGridLayout_rowCount<i32> for () { fn rowCount(self , rsthis: & QGridLayout) -> i32 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK11QGridLayout8rowCountEv()}; let mut ret = unsafe {C_ZNK11QGridLayout8rowCountEv(rsthis.qclsinst)}; return ret as i32; // 1 // return 1; } } // proto: void QGridLayout::setGeometry(const QRect & ); impl /*struct*/ QGridLayout { pub fn setGeometry<RetType, T: QGridLayout_setGeometry<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setGeometry(self); // return 1; } } pub trait QGridLayout_setGeometry<RetType> { fn setGeometry(self , rsthis: & QGridLayout) -> RetType; } // proto: void QGridLayout::setGeometry(const QRect & ); impl<'a> /*trait*/ QGridLayout_setGeometry<()> for (&'a QRect) { fn setGeometry(self , rsthis: & QGridLayout) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN11QGridLayout11setGeometryERK5QRect()}; let arg0 = self.qclsinst as *mut c_void; unsafe {C_ZN11QGridLayout11setGeometryERK5QRect(rsthis.qclsinst, arg0)}; // return 1; } } // proto: void QGridLayout::setVerticalSpacing(int spacing); impl /*struct*/ QGridLayout { pub fn setVerticalSpacing<RetType, T: QGridLayout_setVerticalSpacing<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setVerticalSpacing(self); // return 1; } } pub trait QGridLayout_setVerticalSpacing<RetType> { fn setVerticalSpacing(self , rsthis: & QGridLayout) -> RetType; } // proto: void QGridLayout::setVerticalSpacing(int spacing); impl<'a> /*trait*/ QGridLayout_setVerticalSpacing<()> for (i32) { fn setVerticalSpacing(self , rsthis: & QGridLayout) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN11QGridLayout18setVerticalSpacingEi()}; let arg0 = self as c_int; unsafe {C_ZN11QGridLayout18setVerticalSpacingEi(rsthis.qclsinst, arg0)}; // return 1; } } // proto: void QGridLayout::setHorizontalSpacing(int spacing); impl /*struct*/ QGridLayout { pub fn setHorizontalSpacing<RetType, T: QGridLayout_setHorizontalSpacing<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setHorizontalSpacing(self); // return 1; } } pub trait QGridLayout_setHorizontalSpacing<RetType> { fn setHorizontalSpacing(self , rsthis: & QGridLayout) -> RetType; } // proto: void QGridLayout::setHorizontalSpacing(int spacing); impl<'a> /*trait*/ QGridLayout_setHorizontalSpacing<()> for (i32) { fn setHorizontalSpacing(self , rsthis: & QGridLayout) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN11QGridLayout20setHorizontalSpacingEi()}; let arg0 = self as c_int; unsafe {C_ZN11QGridLayout20setHorizontalSpacingEi(rsthis.qclsinst, arg0)}; // return 1; } } // proto: int QGridLayout::columnStretch(int column); impl /*struct*/ QGridLayout { pub fn columnStretch<RetType, T: QGridLayout_columnStretch<RetType>>(& self, overload_args: T) -> RetType { return overload_args.columnStretch(self); // return 1; } } pub trait QGridLayout_columnStretch<RetType> { fn columnStretch(self , rsthis: & QGridLayout) -> RetType; } // proto: int QGridLayout::columnStretch(int column); impl<'a> /*trait*/ QGridLayout_columnStretch<i32> for (i32) { fn columnStretch(self , rsthis: & QGridLayout) -> i32 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK11QGridLayout13columnStretchEi()}; let arg0 = self as c_int; let mut ret = unsafe {C_ZNK11QGridLayout13columnStretchEi(rsthis.qclsinst, arg0)}; return ret as i32; // 1 // return 1; } } // proto: int QGridLayout::columnCount(); impl /*struct*/ QGridLayout { pub fn columnCount<RetType, T: QGridLayout_columnCount<RetType>>(& self, overload_args: T) -> RetType { return overload_args.columnCount(self); // return 1; } } pub trait QGridLayout_columnCount<RetType> { fn columnCount(self , rsthis: & QGridLayout) -> RetType; } // proto: int QGridLayout::columnCount(); impl<'a> /*trait*/ QGridLayout_columnCount<i32> for () { fn columnCount(self , rsthis: & QGridLayout) -> i32 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK11QGridLayout11columnCountEv()}; let mut ret = unsafe {C_ZNK11QGridLayout11columnCountEv(rsthis.qclsinst)}; return ret as i32; // 1 // return 1; } } // proto: int QGridLayout::columnMinimumWidth(int column); impl /*struct*/ QGridLayout { pub fn columnMinimumWidth<RetType, T: QGridLayout_columnMinimumWidth<RetType>>(& self, overload_args: T) -> RetType { return overload_args.columnMinimumWidth(self); // return 1; } } pub trait QGridLayout_columnMinimumWidth<RetType> { fn columnMinimumWidth(self , rsthis: & QGridLayout) -> RetType; } // proto: int QGridLayout::columnMinimumWidth(int column); impl<'a> /*trait*/ QGridLayout_columnMinimumWidth<i32> for (i32) { fn columnMinimumWidth(self , rsthis: & QGridLayout) -> i32 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK11QGridLayout18columnMinimumWidthEi()}; let arg0 = self as c_int; let mut ret = unsafe {C_ZNK11QGridLayout18columnMinimumWidthEi(rsthis.qclsinst, arg0)}; return ret as i32; // 1 // return 1; } } // proto: QSize QGridLayout::minimumSize(); impl /*struct*/ QGridLayout { pub fn minimumSize<RetType, T: QGridLayout_minimumSize<RetType>>(& self, overload_args: T) -> RetType { return overload_args.minimumSize(self); // return 1; } } pub trait QGridLayout_minimumSize<RetType> { fn minimumSize(self , rsthis: & QGridLayout) -> RetType; } // proto: QSize QGridLayout::minimumSize(); impl<'a> /*trait*/ QGridLayout_minimumSize<QSize> for () { fn minimumSize(self , rsthis: & QGridLayout) -> QSize { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK11QGridLayout11minimumSizeEv()}; let mut ret = unsafe {C_ZNK11QGridLayout11minimumSizeEv(rsthis.qclsinst)}; let mut ret1 = QSize::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: bool QGridLayout::hasHeightForWidth(); impl /*struct*/ QGridLayout { pub fn hasHeightForWidth<RetType, T: QGridLayout_hasHeightForWidth<RetType>>(& self, overload_args: T) -> RetType { return overload_args.hasHeightForWidth(self); // return 1; } } pub trait QGridLayout_hasHeightForWidth<RetType> { fn hasHeightForWidth(self , rsthis: & QGridLayout) -> RetType; } // proto: bool QGridLayout::hasHeightForWidth(); impl<'a> /*trait*/ QGridLayout_hasHeightForWidth<i8> for () { fn hasHeightForWidth(self , rsthis: & QGridLayout) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK11QGridLayout17hasHeightForWidthEv()}; let mut ret = unsafe {C_ZNK11QGridLayout17hasHeightForWidthEv(rsthis.qclsinst)}; return ret as i8; // 1 // return 1; } } // proto: QRect QGridLayout::cellRect(int row, int column); impl /*struct*/ QGridLayout { pub fn cellRect<RetType, T: QGridLayout_cellRect<RetType>>(& self, overload_args: T) -> RetType { return overload_args.cellRect(self); // return 1; } } pub trait QGridLayout_cellRect<RetType> { fn cellRect(self , rsthis: & QGridLayout) -> RetType; } // proto: QRect QGridLayout::cellRect(int row, int column); impl<'a> /*trait*/ QGridLayout_cellRect<QRect> for (i32, i32) { fn cellRect(self , rsthis: & QGridLayout) -> QRect { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK11QGridLayout8cellRectEii()}; let arg0 = self.0 as c_int; let arg1 = self.1 as c_int; let mut ret = unsafe {C_ZNK11QGridLayout8cellRectEii(rsthis.qclsinst, arg0, arg1)}; let mut ret1 = QRect::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QGridLayout::setRowStretch(int row, int stretch); impl /*struct*/ QGridLayout { pub fn setRowStretch<RetType, T: QGridLayout_setRowStretch<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setRowStretch(self); // return 1; } } pub trait QGridLayout_setRowStretch<RetType> { fn setRowStretch(self , rsthis: & QGridLayout) -> RetType; } // proto: void QGridLayout::setRowStretch(int row, int stretch); impl<'a> /*trait*/ QGridLayout_setRowStretch<()> for (i32, i32) { fn setRowStretch(self , rsthis: & QGridLayout) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN11QGridLayout13setRowStretchEii()}; let arg0 = self.0 as c_int; let arg1 = self.1 as c_int; unsafe {C_ZN11QGridLayout13setRowStretchEii(rsthis.qclsinst, arg0, arg1)}; // return 1; } } // proto: QLayoutItem * QGridLayout::itemAtPosition(int row, int column); impl /*struct*/ QGridLayout { pub fn itemAtPosition<RetType, T: QGridLayout_itemAtPosition<RetType>>(& self, overload_args: T) -> RetType { return overload_args.itemAtPosition(self); // return 1; } } pub trait QGridLayout_itemAtPosition<RetType> { fn itemAtPosition(self , rsthis: & QGridLayout) -> RetType; } // proto: QLayoutItem * QGridLayout::itemAtPosition(int row, int column); impl<'a> /*trait*/ QGridLayout_itemAtPosition<QLayoutItem> for (i32, i32) { fn itemAtPosition(self , rsthis: & QGridLayout) -> QLayoutItem { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK11QGridLayout14itemAtPositionEii()}; let arg0 = self.0 as c_int; let arg1 = self.1 as c_int; let mut ret = unsafe {C_ZNK11QGridLayout14itemAtPositionEii(rsthis.qclsinst, arg0, arg1)}; let mut ret1 = QLayoutItem::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: const QMetaObject * QGridLayout::metaObject(); impl /*struct*/ QGridLayout { pub fn metaObject<RetType, T: QGridLayout_metaObject<RetType>>(& self, overload_args: T) -> RetType { return overload_args.metaObject(self); // return 1; } } pub trait QGridLayout_metaObject<RetType> { fn metaObject(self , rsthis: & QGridLayout) -> RetType; } // proto: const QMetaObject * QGridLayout::metaObject(); impl<'a> /*trait*/ QGridLayout_metaObject<QMetaObject> for () { fn metaObject(self , rsthis: & QGridLayout) -> QMetaObject { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK11QGridLayout10metaObjectEv()}; let mut ret = unsafe {C_ZNK11QGridLayout10metaObjectEv(rsthis.qclsinst)}; let mut ret1 = QMetaObject::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: int QGridLayout::verticalSpacing(); impl /*struct*/ QGridLayout { pub fn verticalSpacing<RetType, T: QGridLayout_verticalSpacing<RetType>>(& self, overload_args: T) -> RetType { return overload_args.verticalSpacing(self); // return 1; } } pub trait QGridLayout_verticalSpacing<RetType> { fn verticalSpacing(self , rsthis: & QGridLayout) -> RetType; } // proto: int QGridLayout::verticalSpacing(); impl<'a> /*trait*/ QGridLayout_verticalSpacing<i32> for () { fn verticalSpacing(self , rsthis: & QGridLayout) -> i32 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK11QGridLayout15verticalSpacingEv()}; let mut ret = unsafe {C_ZNK11QGridLayout15verticalSpacingEv(rsthis.qclsinst)}; return ret as i32; // 1 // return 1; } } // proto: void QGridLayout::QGridLayout(QWidget * parent); impl /*struct*/ QGridLayout { pub fn new<T: QGridLayout_new>(value: T) -> QGridLayout { let rsthis = value.new(); return rsthis; // return 1; } } pub trait QGridLayout_new { fn new(self) -> QGridLayout; } // proto: void QGridLayout::QGridLayout(QWidget * parent); impl<'a> /*trait*/ QGridLayout_new for (&'a QWidget) { fn new(self) -> QGridLayout { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN11QGridLayoutC2EP7QWidget()}; let ctysz: c_int = unsafe{QGridLayout_Class_Size()}; let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64; let arg0 = self.qclsinst as *mut c_void; let qthis: u64 = unsafe {C_ZN11QGridLayoutC2EP7QWidget(arg0)}; let rsthis = QGridLayout{qbase: QLayout::inheritFrom(qthis), qclsinst: qthis, ..Default::default()}; return rsthis; // return 1; } } // proto: int QGridLayout::horizontalSpacing(); impl /*struct*/ QGridLayout { pub fn horizontalSpacing<RetType, T: QGridLayout_horizontalSpacing<RetType>>(& self, overload_args: T) -> RetType { return overload_args.horizontalSpacing(self); // return 1; } } pub trait QGridLayout_horizontalSpacing<RetType> { fn horizontalSpacing(self , rsthis: & QGridLayout) -> RetType; } // proto: int QGridLayout::horizontalSpacing(); impl<'a> /*trait*/ QGridLayout_horizontalSpacing<i32> for () { fn horizontalSpacing(self , rsthis: & QGridLayout) -> i32 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK11QGridLayout17horizontalSpacingEv()}; let mut ret = unsafe {C_ZNK11QGridLayout17horizontalSpacingEv(rsthis.qclsinst)}; return ret as i32; // 1 // return 1; } } // proto: void QGridLayout::setColumnMinimumWidth(int column, int minSize); impl /*struct*/ QGridLayout { pub fn setColumnMinimumWidth<RetType, T: QGridLayout_setColumnMinimumWidth<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setColumnMinimumWidth(self); // return 1; } } pub trait QGridLayout_setColumnMinimumWidth<RetType> { fn setColumnMinimumWidth(self , rsthis: & QGridLayout) -> RetType; } // proto: void QGridLayout::setColumnMinimumWidth(int column, int minSize); impl<'a> /*trait*/ QGridLayout_setColumnMinimumWidth<()> for (i32, i32) { fn setColumnMinimumWidth(self , rsthis: & QGridLayout) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN11QGridLayout21setColumnMinimumWidthEii()}; let arg0 = self.0 as c_int; let arg1 = self.1 as c_int; unsafe {C_ZN11QGridLayout21setColumnMinimumWidthEii(rsthis.qclsinst, arg0, arg1)}; // return 1; } } // proto: void QGridLayout::QGridLayout(); impl<'a> /*trait*/ QGridLayout_new for () { fn new(self) -> QGridLayout { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN11QGridLayoutC2Ev()}; let ctysz: c_int = unsafe{QGridLayout_Class_Size()}; let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64; let qthis: u64 = unsafe {C_ZN11QGridLayoutC2Ev()}; let rsthis = QGridLayout{qbase: QLayout::inheritFrom(qthis), qclsinst: qthis, ..Default::default()}; return rsthis; // return 1; } } // proto: int QGridLayout::heightForWidth(int ); impl /*struct*/ QGridLayout { pub fn heightForWidth<RetType, T: QGridLayout_heightForWidth<RetType>>(& self, overload_args: T) -> RetType { return overload_args.heightForWidth(self); // return 1; } } pub trait QGridLayout_heightForWidth<RetType> { fn heightForWidth(self , rsthis: & QGridLayout) -> RetType; } // proto: int QGridLayout::heightForWidth(int ); impl<'a> /*trait*/ QGridLayout_heightForWidth<i32> for (i32) { fn heightForWidth(self , rsthis: & QGridLayout) -> i32 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK11QGridLayout14heightForWidthEi()}; let arg0 = self as c_int; let mut ret = unsafe {C_ZNK11QGridLayout14heightForWidthEi(rsthis.qclsinst, arg0)}; return ret as i32; // 1 // return 1; } } // proto: void QGridLayout::~QGridLayout(); impl /*struct*/ QGridLayout { pub fn free<RetType, T: QGridLayout_free<RetType>>(& self, overload_args: T) -> RetType { return overload_args.free(self); // return 1; } } pub trait QGridLayout_free<RetType> { fn free(self , rsthis: & QGridLayout) -> RetType; } // proto: void QGridLayout::~QGridLayout(); impl<'a> /*trait*/ QGridLayout_free<()> for () { fn free(self , rsthis: & QGridLayout) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN11QGridLayoutD2Ev()}; unsafe {C_ZN11QGridLayoutD2Ev(rsthis.qclsinst)}; // return 1; } } // proto: void QGridLayout::setSpacing(int spacing); impl /*struct*/ QGridLayout { pub fn setSpacing<RetType, T: QGridLayout_setSpacing<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setSpacing(self); // return 1; } } pub trait QGridLayout_setSpacing<RetType> { fn setSpacing(self , rsthis: & QGridLayout) -> RetType; } // proto: void QGridLayout::setSpacing(int spacing); impl<'a> /*trait*/ QGridLayout_setSpacing<()> for (i32) { fn setSpacing(self , rsthis: & QGridLayout) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN11QGridLayout10setSpacingEi()}; let arg0 = self as c_int; unsafe {C_ZN11QGridLayout10setSpacingEi(rsthis.qclsinst, arg0)}; // return 1; } } // proto: void QGridLayout::addWidget(QWidget * w); impl /*struct*/ QGridLayout { pub fn addWidget<RetType, T: QGridLayout_addWidget<RetType>>(& self, overload_args: T) -> RetType { return overload_args.addWidget(self); // return 1; } } pub trait QGridLayout_addWidget<RetType> { fn addWidget(self , rsthis: & QGridLayout) -> RetType; } // proto: void QGridLayout::addWidget(QWidget * w); impl<'a> /*trait*/ QGridLayout_addWidget<()> for (&'a QWidget) { fn addWidget(self , rsthis: & QGridLayout) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN11QGridLayout9addWidgetEP7QWidget()}; let arg0 = self.qclsinst as *mut c_void; unsafe {C_ZN11QGridLayout9addWidgetEP7QWidget(rsthis.qclsinst, arg0)}; // return 1; } } // proto: QLayoutItem * QGridLayout::itemAt(int index); impl /*struct*/ QGridLayout { pub fn itemAt<RetType, T: QGridLayout_itemAt<RetType>>(& self, overload_args: T) -> RetType { return overload_args.itemAt(self); // return 1; } } pub trait QGridLayout_itemAt<RetType> { fn itemAt(self , rsthis: & QGridLayout) -> RetType; } // proto: QLayoutItem * QGridLayout::itemAt(int index); impl<'a> /*trait*/ QGridLayout_itemAt<QLayoutItem> for (i32) { fn itemAt(self , rsthis: & QGridLayout) -> QLayoutItem { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK11QGridLayout6itemAtEi()}; let arg0 = self as c_int; let mut ret = unsafe {C_ZNK11QGridLayout6itemAtEi(rsthis.qclsinst, arg0)}; let mut ret1 = QLayoutItem::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: QSize QGridLayout::maximumSize(); impl /*struct*/ QGridLayout { pub fn maximumSize<RetType, T: QGridLayout_maximumSize<RetType>>(& self, overload_args: T) -> RetType { return overload_args.maximumSize(self); // return 1; } } pub trait QGridLayout_maximumSize<RetType> { fn maximumSize(self , rsthis: & QGridLayout) -> RetType; } // proto: QSize QGridLayout::maximumSize(); impl<'a> /*trait*/ QGridLayout_maximumSize<QSize> for () { fn maximumSize(self , rsthis: & QGridLayout) -> QSize { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK11QGridLayout11maximumSizeEv()}; let mut ret = unsafe {C_ZNK11QGridLayout11maximumSizeEv(rsthis.qclsinst)}; let mut ret1 = QSize::inheritFrom(ret as u64); return ret1; // return 1; } } // <= body block end
use super::{crypto_util, Authenticator}; use crate::protocol::parts::AuthFields; use crate::{HdbError, HdbResult}; use byteorder::{LittleEndian, WriteBytesExt}; use rand::{thread_rng, RngCore}; use secstr::SecUtf8; use std::io::Write; const CLIENT_PROOF_SIZE: u8 = 32; pub struct ScramSha256 { client_challenge: Vec<u8>, server_proof: Option<Vec<u8>>, } impl ScramSha256 { pub fn boxed_authenticator() -> Box<dyn Authenticator + Send + Sync> { let mut client_challenge = [0_u8; 64]; let mut rng = thread_rng(); rng.fill_bytes(&mut client_challenge); Box::new(Self { client_challenge: client_challenge.to_vec(), server_proof: None, }) } } impl Authenticator for ScramSha256 { fn name(&self) -> &str { "SCRAMSHA256" } fn name_as_bytes(&self) -> Vec<u8> { self.name().as_bytes().to_owned() } fn client_challenge(&self) -> &[u8] { &(self.client_challenge) } fn client_proof(&mut self, server_data: &[u8], password: &SecUtf8) -> HdbResult<Vec<u8>> { const CONTEXT_CLIENT_PROOF: &str = "ClientProof"; let (salt, server_nonce) = parse_first_server_data(server_data)?; let (client_proof, server_proof) = crypto_util::scram_sha256(&salt, &server_nonce, &self.client_challenge, password) .map_err(|_| HdbError::Impl("crypto_common::InvalidLength"))?; self.client_challenge.clear(); self.server_proof = Some(server_proof); let mut buf = Vec::<u8>::with_capacity(3 + CLIENT_PROOF_SIZE as usize); buf.write_u16::<LittleEndian>(1_u16) .map_err(|_e| HdbError::Impl(CONTEXT_CLIENT_PROOF))?; buf.write_u8(CLIENT_PROOF_SIZE) .map_err(|_e| HdbError::Impl(CONTEXT_CLIENT_PROOF))?; buf.write_all(&client_proof) .map_err(|_e| HdbError::Impl(CONTEXT_CLIENT_PROOF))?; Ok(buf) } fn verify_server(&self, server_proof: &[u8]) -> HdbResult<()> { if server_proof.is_empty() { Ok(()) } else { Err(HdbError::ImplDetailed(format!( "verify_server(): non-empty server_proof: {server_proof:?}", ))) } } } // `server_data` is again an AuthFields; contains salt, and server_nonce fn parse_first_server_data(server_data: &[u8]) -> HdbResult<(Vec<u8>, Vec<u8>)> { let mut af = AuthFields::parse_sync(&mut std::io::Cursor::new(server_data))?; match (af.pop(), af.pop(), af.pop()) { (Some(server_nonce), Some(salt), None) => Ok((salt, server_nonce)), (_, _, _) => Err(HdbError::Impl("expected 2 auth fields")), } } #[cfg(test)] mod tests { use super::ScramSha256; use crate::conn::authentication::authenticator::Authenticator; use secstr::SecUtf8; // cargo // test authenticate::scram_sha256::tests::test_client_proof -- --nocapture #[test] fn test_client_proof() { info!("test calculation of client proof"); let client_challenge: Vec<u8> = b"\xb5\xab\x3a\x90\xc5\xad\xb8\x04\x15\x27\ \x37\x66\x54\xd7\x5c\x31\x94\xd8\x61\x50\ \x3f\xe0\x8d\xff\x8b\xea\xd5\x1b\xc3\x5a\ \x07\xcc\x63\xed\xbf\xa9\x5d\x03\x62\xf5\ \x6f\x1a\x48\x2e\x4c\x3f\xb8\x32\xe4\x1c\ \x89\x74\xf9\x02\xef\x87\x38\xcc\x74\xb6\ \xef\x99\x2e\x8e" .to_vec(); let server_challenge: Vec<u8> = b"\x02\x00\x10\x12\x41\xe5\x8f\x39\x23\x4e\ \xeb\x77\x3e\x90\x90\x33\xe5\xcb\x6e\x30\ \x1a\xce\xdc\xdd\x05\xc1\x90\xb0\xf0\xd0\ \x7d\x81\x1a\xdb\x0d\x6f\xed\xa8\x87\x59\ \xc2\x94\x06\x0d\xae\xab\x3f\x62\xea\x4b\ \x16\x6a\xc9\x7e\xfc\x9a\x6b\xde\x4f\xe9\ \xe5\xda\xcc\xb5\x0a\xcf\xce\x56" .to_vec(); let password = SecUtf8::from("manager"); let correct_client_proof: Vec<u8> = b"\x01\x00\x20\x17\x26\x25\xab\x29\x71\xd8\ \x58\x74\x32\x5d\x21\xbc\x3d\x68\x37\x71\ \x80\x5c\x9a\xfe\x38\xd0\x95\x1d\xad\x46\ \x53\x00\x9c\xc9\x21" .to_vec(); let mut a = ScramSha256 { client_challenge, server_proof: None, }; let my_client_proof = a.client_proof(&server_challenge, &password).unwrap(); assert_eq!(my_client_proof, correct_client_proof); } }
extern crate ndarray; use ndarray::prelude::*; fn testfunc(mut s: Array2<i64>) {} fn main() { let n = 3; let mut s = Array::<i64, _>::zeros(n * n).into_shape((n, n)).unwrap(); testfunc(s); }
// Copyright 2019 Liebi Technologies. // This file is part of Bifrost. // Bifrost is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Bifrost is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Bifrost. If not, see <http://www.gnu.org/licenses/>. use codec::alloc::string::FromUtf8Error; use log::{debug, info}; use metadata::{DecodeDifferent, RuntimeMetadata, RuntimeMetadataPrefixed}; use serde::{Deserialize, Serialize}; pub fn pretty_format(metadata: &RuntimeMetadataPrefixed) -> Result<String, FromUtf8Error> { let buf = Vec::new(); let formatter = serde_json::ser::PrettyFormatter::with_indent(b" "); let mut ser = serde_json::Serializer::with_formatter(buf, formatter); metadata.serialize(&mut ser).unwrap(); String::from_utf8(ser.into_inner()) } pub type NodeMetadata = Vec<Module>; pub trait Print { fn print_events(&self); fn print_calls(&self); } impl Print for NodeMetadata { fn print_events(&self) { for m in self { m.print_events(); } } fn print_calls(&self) { for m in self { m.print_calls() } } } #[derive(Serialize, Deserialize, Debug, Default, Clone)] pub struct Module { pub name: String, pub calls: Vec<Call>, pub events: Vec<Event>, } impl Module { fn new(name: &DecodeDifferent<&'static str, std::string::String>) -> Module { Module { name: format!("{:?}", name).replace("\"", ""), calls: Vec::<Call>::new(), events: Vec::<Event>::new() } } pub fn print_events(&self) { println!("----------------- Events for Module: {} -----------------\n", self.name); for e in &self.events { println!("{:?}", e); } println!() } pub fn print_calls(&self) { println!("----------------- Calls for Module: {} -----------------\n", self.name); for e in &self.calls { println!("{:?}", e); } println!() } } #[derive(Serialize, Deserialize, Debug, Clone, Default)] pub struct Call { pub name: String, pub args: Vec<Arg>, } impl Call { fn new(name: &DecodeDifferent<&'static str, std::string::String>) -> Call { Call { name: format!("{:?}", name).replace("\"", ""), args: Vec::<Arg>::new(), } } } #[derive(Serialize, Deserialize, Debug, Clone, Default)] pub struct Event { pub name: String, // in this case the only the argument types are provided as strings pub args: Vec<String>, } impl Event { fn new(name: &DecodeDifferent<&'static str, std::string::String>) -> Event { Event { name: format!("{:?}", name).replace("\"", ""), args: Vec::<String>::new() } } } #[derive(Serialize, Deserialize, Debug, Clone)] pub struct Arg { pub name: String, pub ty: String, } impl Arg { fn new( name: &DecodeDifferent<&'static str, std::string::String>, ty: &DecodeDifferent<&'static str, std::string::String>, ) -> Arg { Arg { name: format!("{:?}", name).replace("\"", ""), ty: format!("{:?}", ty).replace("\"", ""), } } } pub fn parse_metadata(metadata: &RuntimeMetadataPrefixed) -> Vec<Module> { let mut mod_vec = Vec::<Module>::new(); match &metadata.1 { RuntimeMetadata::V8(value) => { match &value.modules { DecodeDifferent::Decoded(mods) => { let modules = mods; debug!("-------------------- modules ----------------"); for module in modules { debug!("module: {:?}", module.name); let mut _mod = Module::new(&module.name); match &module.calls { Some(DecodeDifferent::Decoded(calls)) => { debug!("-------------------- calls ----------------"); if calls.is_empty() { // indices modules does for some reason list `Some([])' as calls and is thus counted in the call enum // there might be others doing the same. _mod.calls.push(Default::default()) } for call in calls { let mut _call = Call::new(&call.name); match &call.arguments { DecodeDifferent::Decoded(arguments) => { for arg in arguments { _call.args.push(Arg::new(&arg.name, &arg.ty)); } } _ => unreachable!( "All calls have at least the 'who' argument; qed" ), } _mod.calls.push(_call); } } _ => debug!("No calls for this module"), } match &module.event { Some(DecodeDifferent::Decoded(event)) => { debug!("-------------------- events ----------------"); debug!("{:?}", event); if event.is_empty() { // indices modules does for some reason list `Some([])' as calls and is thus counted in the call enum // there might be others doing the same. _mod.calls.push(Default::default()) } for e in event { let mut _event = Event::new(&e.name); match &e.arguments { DecodeDifferent::Decoded(arguments) => { for arg in arguments { _event.args.push(arg.to_string()); } }, _ => unreachable!("All calls have at least the 'who' argument; qed"), } _mod.events.push(_event); } }, _ => debug!("No calls for this module"), } mod_vec.push(_mod); } for m in &mod_vec { info!("{:?}", m); } debug!("successfully decoded metadata"); } _ => unreachable!("There are always modules present; qed"), } } _ => panic!("Unsupported metadata"), } mod_vec }
use n3_machine_ffi::WorkId; pub type Result<T> = std::result::Result<T, Error>; #[derive(Debug)] pub enum Error { BuildError(n3_builder::Error), MachineError(n3_machine_ffi::Error), NoSuchWork { id: WorkId }, RequireAKey, // Exposing database error can cause fatal security problem. DatabaseError, } impl From<n3_builder::Error> for Error { fn from(error: n3_builder::Error) -> Self { Self::BuildError(error) } } impl From<n3_machine_ffi::Error> for Error { fn from(error: n3_machine_ffi::Error) -> Self { Self::MachineError(error) } } impl From<diesel::result::Error> for Error { fn from(_: diesel::result::Error) -> Self { Self::DatabaseError } }
use clap::Parser; use cli::{Args, RunCmd}; use color_eyre::eyre::Result; const BUILD_TIME: &str = include!(concat!(env!("OUT_DIR"), "/compiled_at.txt")); mod built_info { include!(concat!(env!("OUT_DIR"), "/built.rs")); } #[derive(Parser, Debug)] pub enum Cmd { /// Display the current version. #[clap(name = "version")] Version, /// Upgrade the prebuilt binary to the latest GitHub release if any. /// /// Only available for the executable in `vim-clap/bin/maple`. #[clap(name = "upgrade")] Upgrade { /// Download if the local version mismatches the latest remote version. #[clap(long)] download: bool, /// Disable the downloading progress_bar #[clap(long)] no_progress_bar: bool, }, /// Run the maple. #[clap(flatten)] Run(Box<RunCmd>), } #[derive(Parser, Debug)] #[clap(name = "maple", disable_version_flag = true)] pub struct Maple { #[clap(flatten)] pub args: Args, #[clap(subcommand)] pub cmd: Cmd, } #[tokio::main] async fn main() -> Result<()> { color_eyre::install()?; let maple = Maple::parse(); match maple.cmd { Cmd::Version => { println!( "version {}{}, compiled at: {}, built for {} by {}.", built_info::PKG_VERSION, built_info::GIT_VERSION.map_or_else(|| "".to_owned(), |v| format!(" (git {v})")), BUILD_TIME, built_info::TARGET, built_info::RUSTC_VERSION ); } Cmd::Upgrade { download, no_progress_bar, } => { let local_git_tag = built_info::GIT_VERSION.expect("GIT_VERSION does not exist"); if let Err(e) = upgrade::Upgrade::new(download, no_progress_bar) .run(local_git_tag) .await { eprintln!("failed to upgrade: {e:?}"); std::process::exit(1); } } Cmd::Run(run_cmd) => { if let Err(e) = run_cmd.run(maple.args).await { eprintln!("error: {e:?}"); std::process::exit(1); } } } Ok(()) }
// Ignore me, I'm an empty Rust file that forces Docker to build the project dependencies during `docker build` // This allows Docker to cache the dependencies, so compilation happens only once instead of at every `docker run` fn main() {}
use stark_hash::Felt; pub mod proto { pub mod common { include!(concat!(env!("OUT_DIR"), "/starknet.common.rs")); } pub mod propagation { include!(concat!(env!("OUT_DIR"), "/starknet.propagation.rs")); } pub mod sync { include!(concat!(env!("OUT_DIR"), "/starknet.sync.rs")); } } pub trait ToProtobuf<Output> where Self: Sized, { fn to_protobuf(self) -> Output; } impl ToProtobuf<u64> for u64 { fn to_protobuf(self) -> u64 { self } } impl ToProtobuf<u32> for u32 { fn to_protobuf(self) -> u32 { self } } impl ToProtobuf<u8> for u8 { fn to_protobuf(self) -> u8 { self } } impl ToProtobuf<String> for String { fn to_protobuf(self) -> String { self } } impl ToProtobuf<proto::common::FieldElement> for Felt { fn to_protobuf(self) -> proto::common::FieldElement { proto::common::FieldElement { elements: self.to_be_bytes().into(), } } } impl ToProtobuf<proto::common::EthereumAddress> for primitive_types::H160 { fn to_protobuf(self) -> proto::common::EthereumAddress { proto::common::EthereumAddress { elements: self.to_fixed_bytes().into(), } } } impl<M, T: ToProtobuf<M>> ToProtobuf<Vec<M>> for Vec<T> { fn to_protobuf(self) -> Vec<M> { self.into_iter().map(ToProtobuf::to_protobuf).collect() } } impl<M, T: ToProtobuf<M>> ToProtobuf<Option<M>> for Option<T> { fn to_protobuf(self) -> Option<M> { self.map(ToProtobuf::to_protobuf) } } pub trait TryFromProtobuf<M> where Self: Sized, { fn try_from_protobuf(input: M, field_name: &'static str) -> Result<Self, std::io::Error>; } impl TryFromProtobuf<u64> for u64 { fn try_from_protobuf(input: u64, _field_name: &'static str) -> Result<Self, std::io::Error> { Ok(input) } } impl TryFromProtobuf<u32> for u32 { fn try_from_protobuf(input: u32, _field_name: &'static str) -> Result<Self, std::io::Error> { Ok(input) } } impl TryFromProtobuf<u8> for u8 { fn try_from_protobuf(input: u8, _field_name: &'static str) -> Result<Self, std::io::Error> { Ok(input) } } impl TryFromProtobuf<String> for String { fn try_from_protobuf(input: String, _field_name: &'static str) -> Result<Self, std::io::Error> { Ok(input) } } impl TryFromProtobuf<proto::common::FieldElement> for Felt { fn try_from_protobuf( input: proto::common::FieldElement, field_name: &'static str, ) -> Result<Self, std::io::Error> { let stark_hash = Felt::from_be_slice(&input.elements).map_err(|e| { std::io::Error::new( std::io::ErrorKind::InvalidData, format!("Invalid field element {field_name}: {e}"), ) })?; Ok(stark_hash) } } impl TryFromProtobuf<proto::common::EthereumAddress> for primitive_types::H160 { fn try_from_protobuf( input: proto::common::EthereumAddress, field_name: &'static str, ) -> Result<Self, std::io::Error> { if input.elements.len() != primitive_types::H160::len_bytes() { return Err(std::io::Error::new( std::io::ErrorKind::InvalidData, format!("Invalid length for Ethereum address {field_name}"), )); } // from_slice() panics if the input length is incorrect, but we've already checked that let address = primitive_types::H160::from_slice(&input.elements); Ok(address) } } impl<T: TryFromProtobuf<U>, U> TryFromProtobuf<Option<U>> for T { fn try_from_protobuf( input: Option<U>, field_name: &'static str, ) -> Result<Self, std::io::Error> { let input = input.ok_or_else(|| { std::io::Error::new( std::io::ErrorKind::InvalidData, format!("Missing field {field_name}"), ) })?; TryFromProtobuf::try_from_protobuf(input, field_name) } } impl<T: TryFromProtobuf<U>, U> TryFromProtobuf<Vec<U>> for Vec<T> { fn try_from_protobuf(input: Vec<U>, field_name: &'static str) -> Result<Self, std::io::Error> { input .into_iter() .map(|e| TryFromProtobuf::try_from_protobuf(e, field_name)) .collect::<Result<Vec<_>, _>>() .map_err(|e| { std::io::Error::new( std::io::ErrorKind::InvalidData, format!("Failed to parse {field_name}: {e}"), ) }) } } use p2p_proto_derive::*; #[derive(ToProtobuf)] #[protobuf(name = "crate::proto::common::Event")] struct Event { pub from_address: Felt, pub keys: Vec<Felt>, pub data: Vec<Felt>, } pub mod common; pub mod propagation; pub mod sync;
use audio_device::windows::AsyncEvent; use std::sync::Arc; #[tokio::main] async fn main() -> anyhow::Result<()> { let runtime = audio_device::runtime::Runtime::new()?; let guard = runtime.enter(); let event = Arc::new(AsyncEvent::new(false)?); let event2 = event.clone(); tokio::spawn(async move { tokio::time::sleep(std::time::Duration::from_secs(5)).await; event2.set(); }); println!("waiting for event..."); event.wait().await; println!("event woken up"); drop(guard); runtime.join(); Ok(()) }
pub fn gcd<T: Int>(a: T, b: T) -> T { use std::num::Zero; if b == Zero::zero() { a } else { gcd(b, a % b) } }
use ::amethyst::core::math::{Vector2, Vector3}; /// Accelerates the given `relative` vector by the given `acceleration` and `input`. /// The `maximum_velocity` is only taken into account for the projection of the acceleration vector on the `relative` vector. /// This allows going over the speed limit by performing what is called a "strafe". /// If your velocity is forward and have an input accelerating you to the right, the projection of /// the acceleration vector over your current velocity will be 0. This means that the acceleration vector will be applied fully, /// even if this makes the resulting vector's magnitude go over `max_velocity`. pub fn accelerate_vector( delta_time: f32, input: Vector2<f32>, rel: Vector3<f32>, acceleration: f32, max_velocity: f32, ) -> Vector3<f32> { let mut o = rel; let input3 = Vector3::new(input.x, 0.0, input.y); let rel_flat = Vector3::new(rel.x, 0.0, rel.z); if input3.magnitude() > 0.0 { let proj = rel_flat.dot(&input3.normalize()); let mut accel_velocity = acceleration * delta_time as f32; if proj + accel_velocity > max_velocity { accel_velocity = max_velocity - proj; } if accel_velocity > 0.0 { let add_speed = input3 * accel_velocity; o += add_speed; } } o } /// Completely negates the velocity of a specific axis if an input is performed in the opposite direction. pub fn counter_impulse(input: Vector2<f32>, relative_velocity: Vector3<f32>) -> Vector3<f32> { let mut o = relative_velocity; if (input.x < 0.0 && relative_velocity.x > 0.001) || (input.x > 0.0 && relative_velocity.x < -0.001) { o = Vector3::new(0.0, relative_velocity.y, relative_velocity.z); } if (input.y < 0.0 && relative_velocity.z < -0.001) || (input.y > 0.0 && relative_velocity.z > 0.001) { o = Vector3::new(relative_velocity.x, relative_velocity.y, 0.0); } o } /// Limits the total velocity so that its magnitude doesn't exceed `maximum_velocity`. /// If you are using the `accelerate_vector` function, calling this will ensure that air strafing /// doesn't allow you to go over the maximum velocity, while still keeping fluid controls. pub fn limit_velocity(vec: Vector3<f32>, maximum_velocity: f32) -> Vector3<f32> { let v_flat = Vector2::new(vec.x, vec.z).magnitude(); if v_flat > maximum_velocity && maximum_velocity != 0.0 { let ratio = maximum_velocity / v_flat; return Vector3::new(vec.x * ratio, vec.y, vec.z * ratio); } vec }
extern crate rand; use rand::Rng; fn main() { let months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; let month = rand::thread_rng().gen_range(1, months.len()); println!("The random month is: {}", months[month]); }
use super::*; pub fn gen_handle() -> TokenStream { quote! { #[derive(::core::clone::Clone, ::core::marker::Copy, ::core::default::Default, ::core::fmt::Debug, ::core::cmp::PartialEq, ::core::cmp::Eq)] #[repr(transparent)] pub struct HANDLE(pub isize); unsafe impl ::windows::core::Handle for HANDLE { fn is_invalid(&self) -> bool { self.0 == 0 || self.0 == -1 } fn ok(self) -> ::windows::core::Result<Self> { if self.is_invalid() { Err(::windows::core::Error::from_win32()) } else { Ok(self) } } } unsafe impl ::windows::core::Abi for HANDLE { type Abi = Self; } } }
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct HdmiDisplayColorSpace(pub i32); impl HdmiDisplayColorSpace { pub const RgbLimited: HdmiDisplayColorSpace = HdmiDisplayColorSpace(0i32); pub const RgbFull: HdmiDisplayColorSpace = HdmiDisplayColorSpace(1i32); pub const BT2020: HdmiDisplayColorSpace = HdmiDisplayColorSpace(2i32); pub const BT709: HdmiDisplayColorSpace = HdmiDisplayColorSpace(3i32); } impl ::core::convert::From<i32> for HdmiDisplayColorSpace { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for HdmiDisplayColorSpace { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for HdmiDisplayColorSpace { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Graphics.Display.Core.HdmiDisplayColorSpace;i4)"); } impl ::windows::core::DefaultType for HdmiDisplayColorSpace { type DefaultType = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct HdmiDisplayHdr2086Metadata { pub RedPrimaryX: u16, pub RedPrimaryY: u16, pub GreenPrimaryX: u16, pub GreenPrimaryY: u16, pub BluePrimaryX: u16, pub BluePrimaryY: u16, pub WhitePointX: u16, pub WhitePointY: u16, pub MaxMasteringLuminance: u16, pub MinMasteringLuminance: u16, pub MaxContentLightLevel: u16, pub MaxFrameAverageLightLevel: u16, } impl HdmiDisplayHdr2086Metadata {} impl ::core::default::Default for HdmiDisplayHdr2086Metadata { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for HdmiDisplayHdr2086Metadata { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("HdmiDisplayHdr2086Metadata") .field("RedPrimaryX", &self.RedPrimaryX) .field("RedPrimaryY", &self.RedPrimaryY) .field("GreenPrimaryX", &self.GreenPrimaryX) .field("GreenPrimaryY", &self.GreenPrimaryY) .field("BluePrimaryX", &self.BluePrimaryX) .field("BluePrimaryY", &self.BluePrimaryY) .field("WhitePointX", &self.WhitePointX) .field("WhitePointY", &self.WhitePointY) .field("MaxMasteringLuminance", &self.MaxMasteringLuminance) .field("MinMasteringLuminance", &self.MinMasteringLuminance) .field("MaxContentLightLevel", &self.MaxContentLightLevel) .field("MaxFrameAverageLightLevel", &self.MaxFrameAverageLightLevel) .finish() } } impl ::core::cmp::PartialEq for HdmiDisplayHdr2086Metadata { fn eq(&self, other: &Self) -> bool { self.RedPrimaryX == other.RedPrimaryX && self.RedPrimaryY == other.RedPrimaryY && self.GreenPrimaryX == other.GreenPrimaryX && self.GreenPrimaryY == other.GreenPrimaryY && self.BluePrimaryX == other.BluePrimaryX && self.BluePrimaryY == other.BluePrimaryY && self.WhitePointX == other.WhitePointX && self.WhitePointY == other.WhitePointY && self.MaxMasteringLuminance == other.MaxMasteringLuminance && self.MinMasteringLuminance == other.MinMasteringLuminance && self.MaxContentLightLevel == other.MaxContentLightLevel && self.MaxFrameAverageLightLevel == other.MaxFrameAverageLightLevel } } impl ::core::cmp::Eq for HdmiDisplayHdr2086Metadata {} unsafe impl ::windows::core::Abi for HdmiDisplayHdr2086Metadata { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for HdmiDisplayHdr2086Metadata { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"struct(Windows.Graphics.Display.Core.HdmiDisplayHdr2086Metadata;u2;u2;u2;u2;u2;u2;u2;u2;u2;u2;u2;u2)"); } impl ::windows::core::DefaultType for HdmiDisplayHdr2086Metadata { type DefaultType = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct HdmiDisplayHdrOption(pub i32); impl HdmiDisplayHdrOption { pub const None: HdmiDisplayHdrOption = HdmiDisplayHdrOption(0i32); pub const EotfSdr: HdmiDisplayHdrOption = HdmiDisplayHdrOption(1i32); pub const Eotf2084: HdmiDisplayHdrOption = HdmiDisplayHdrOption(2i32); pub const DolbyVisionLowLatency: HdmiDisplayHdrOption = HdmiDisplayHdrOption(3i32); } impl ::core::convert::From<i32> for HdmiDisplayHdrOption { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for HdmiDisplayHdrOption { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for HdmiDisplayHdrOption { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Graphics.Display.Core.HdmiDisplayHdrOption;i4)"); } impl ::windows::core::DefaultType for HdmiDisplayHdrOption { type DefaultType = Self; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct HdmiDisplayInformation(pub ::windows::core::IInspectable); impl HdmiDisplayInformation { #[cfg(feature = "Foundation_Collections")] pub fn GetSupportedDisplayModes(&self) -> ::windows::core::Result<super::super::super::Foundation::Collections::IVectorView<HdmiDisplayMode>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::Collections::IVectorView<HdmiDisplayMode>>(result__) } } pub fn GetCurrentDisplayMode(&self) -> ::windows::core::Result<HdmiDisplayMode> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<HdmiDisplayMode>(result__) } } #[cfg(feature = "Foundation")] pub fn SetDefaultDisplayModeAsync(&self) -> ::windows::core::Result<super::super::super::Foundation::IAsyncAction> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::IAsyncAction>(result__) } } #[cfg(feature = "Foundation")] pub fn RequestSetCurrentDisplayModeAsync<'a, Param0: ::windows::core::IntoParam<'a, HdmiDisplayMode>>(&self, mode: Param0) -> ::windows::core::Result<super::super::super::Foundation::IAsyncOperation<bool>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), mode.into_param().abi(), &mut result__).from_abi::<super::super::super::Foundation::IAsyncOperation<bool>>(result__) } } #[cfg(feature = "Foundation")] pub fn RequestSetCurrentDisplayModeWithHdrAsync<'a, Param0: ::windows::core::IntoParam<'a, HdmiDisplayMode>>(&self, mode: Param0, hdroption: HdmiDisplayHdrOption) -> ::windows::core::Result<super::super::super::Foundation::IAsyncOperation<bool>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), mode.into_param().abi(), hdroption, &mut result__).from_abi::<super::super::super::Foundation::IAsyncOperation<bool>>(result__) } } #[cfg(feature = "Foundation")] pub fn RequestSetCurrentDisplayModeWithHdrAndMetadataAsync<'a, Param0: ::windows::core::IntoParam<'a, HdmiDisplayMode>, Param2: ::windows::core::IntoParam<'a, HdmiDisplayHdr2086Metadata>>(&self, mode: Param0, hdroption: HdmiDisplayHdrOption, hdrmetadata: Param2) -> ::windows::core::Result<super::super::super::Foundation::IAsyncOperation<bool>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), mode.into_param().abi(), hdroption, hdrmetadata.into_param().abi(), &mut result__).from_abi::<super::super::super::Foundation::IAsyncOperation<bool>>(result__) } } #[cfg(feature = "Foundation")] pub fn DisplayModesChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::TypedEventHandler<HdmiDisplayInformation, ::windows::core::IInspectable>>>(&self, value: Param0) -> ::windows::core::Result<super::super::super::Foundation::EventRegistrationToken> { let this = self; unsafe { let mut result__: super::super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), value.into_param().abi(), &mut result__).from_abi::<super::super::super::Foundation::EventRegistrationToken>(result__) } } #[cfg(feature = "Foundation")] pub fn RemoveDisplayModesChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() } } pub fn GetForCurrentView() -> ::windows::core::Result<HdmiDisplayInformation> { Self::IHdmiDisplayInformationStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<HdmiDisplayInformation>(result__) }) } pub fn IHdmiDisplayInformationStatics<R, F: FnOnce(&IHdmiDisplayInformationStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<HdmiDisplayInformation, IHdmiDisplayInformationStatics> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for HdmiDisplayInformation { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Graphics.Display.Core.HdmiDisplayInformation;{130b3c0a-f565-476e-abd5-ea05aee74c69})"); } unsafe impl ::windows::core::Interface for HdmiDisplayInformation { type Vtable = IHdmiDisplayInformation_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x130b3c0a_f565_476e_abd5_ea05aee74c69); } impl ::windows::core::RuntimeName for HdmiDisplayInformation { const NAME: &'static str = "Windows.Graphics.Display.Core.HdmiDisplayInformation"; } impl ::core::convert::From<HdmiDisplayInformation> for ::windows::core::IUnknown { fn from(value: HdmiDisplayInformation) -> Self { value.0 .0 } } impl ::core::convert::From<&HdmiDisplayInformation> for ::windows::core::IUnknown { fn from(value: &HdmiDisplayInformation) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for HdmiDisplayInformation { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a HdmiDisplayInformation { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<HdmiDisplayInformation> for ::windows::core::IInspectable { fn from(value: HdmiDisplayInformation) -> Self { value.0 } } impl ::core::convert::From<&HdmiDisplayInformation> for ::windows::core::IInspectable { fn from(value: &HdmiDisplayInformation) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for HdmiDisplayInformation { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a HdmiDisplayInformation { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for HdmiDisplayInformation {} unsafe impl ::core::marker::Sync for HdmiDisplayInformation {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct HdmiDisplayMode(pub ::windows::core::IInspectable); impl HdmiDisplayMode { pub fn ResolutionWidthInRawPixels(&self) -> ::windows::core::Result<u32> { let this = self; unsafe { let mut result__: u32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__) } } pub fn ResolutionHeightInRawPixels(&self) -> ::windows::core::Result<u32> { let this = self; unsafe { let mut result__: u32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__) } } pub fn RefreshRate(&self) -> ::windows::core::Result<f64> { let this = self; unsafe { let mut result__: f64 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<f64>(result__) } } pub fn StereoEnabled(&self) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } pub fn BitsPerPixel(&self) -> ::windows::core::Result<u16> { let this = self; unsafe { let mut result__: u16 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u16>(result__) } } pub fn IsEqual<'a, Param0: ::windows::core::IntoParam<'a, HdmiDisplayMode>>(&self, mode: Param0) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), mode.into_param().abi(), &mut result__).from_abi::<bool>(result__) } } pub fn ColorSpace(&self) -> ::windows::core::Result<HdmiDisplayColorSpace> { let this = self; unsafe { let mut result__: HdmiDisplayColorSpace = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), &mut result__).from_abi::<HdmiDisplayColorSpace>(result__) } } pub fn PixelEncoding(&self) -> ::windows::core::Result<HdmiDisplayPixelEncoding> { let this = self; unsafe { let mut result__: HdmiDisplayPixelEncoding = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), &mut result__).from_abi::<HdmiDisplayPixelEncoding>(result__) } } pub fn IsSdrLuminanceSupported(&self) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } pub fn IsSmpte2084Supported(&self) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } pub fn Is2086MetadataSupported(&self) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).16)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } pub fn IsDolbyVisionLowLatencySupported(&self) -> ::windows::core::Result<bool> { let this = &::windows::core::Interface::cast::<IHdmiDisplayMode2>(self)?; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } } unsafe impl ::windows::core::RuntimeType for HdmiDisplayMode { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Graphics.Display.Core.HdmiDisplayMode;{0c06d5ad-1b90-4f51-9981-ef5a1c0ddf66})"); } unsafe impl ::windows::core::Interface for HdmiDisplayMode { type Vtable = IHdmiDisplayMode_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x0c06d5ad_1b90_4f51_9981_ef5a1c0ddf66); } impl ::windows::core::RuntimeName for HdmiDisplayMode { const NAME: &'static str = "Windows.Graphics.Display.Core.HdmiDisplayMode"; } impl ::core::convert::From<HdmiDisplayMode> for ::windows::core::IUnknown { fn from(value: HdmiDisplayMode) -> Self { value.0 .0 } } impl ::core::convert::From<&HdmiDisplayMode> for ::windows::core::IUnknown { fn from(value: &HdmiDisplayMode) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for HdmiDisplayMode { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a HdmiDisplayMode { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<HdmiDisplayMode> for ::windows::core::IInspectable { fn from(value: HdmiDisplayMode) -> Self { value.0 } } impl ::core::convert::From<&HdmiDisplayMode> for ::windows::core::IInspectable { fn from(value: &HdmiDisplayMode) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for HdmiDisplayMode { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a HdmiDisplayMode { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for HdmiDisplayMode {} unsafe impl ::core::marker::Sync for HdmiDisplayMode {} #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct HdmiDisplayPixelEncoding(pub i32); impl HdmiDisplayPixelEncoding { pub const Rgb444: HdmiDisplayPixelEncoding = HdmiDisplayPixelEncoding(0i32); pub const Ycc444: HdmiDisplayPixelEncoding = HdmiDisplayPixelEncoding(1i32); pub const Ycc422: HdmiDisplayPixelEncoding = HdmiDisplayPixelEncoding(2i32); pub const Ycc420: HdmiDisplayPixelEncoding = HdmiDisplayPixelEncoding(3i32); } impl ::core::convert::From<i32> for HdmiDisplayPixelEncoding { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for HdmiDisplayPixelEncoding { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for HdmiDisplayPixelEncoding { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Graphics.Display.Core.HdmiDisplayPixelEncoding;i4)"); } impl ::windows::core::DefaultType for HdmiDisplayPixelEncoding { type DefaultType = Self; } #[repr(transparent)] #[doc(hidden)] pub struct IHdmiDisplayInformation(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IHdmiDisplayInformation { type Vtable = IHdmiDisplayInformation_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x130b3c0a_f565_476e_abd5_ea05aee74c69); } #[repr(C)] #[doc(hidden)] pub struct IHdmiDisplayInformation_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, mode: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, mode: ::windows::core::RawPtr, hdroption: HdmiDisplayHdrOption, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, mode: ::windows::core::RawPtr, hdroption: HdmiDisplayHdrOption, hdrmetadata: HdmiDisplayHdr2086Metadata, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::windows::core::RawPtr, result__: *mut super::super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IHdmiDisplayInformationStatics(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IHdmiDisplayInformationStatics { type Vtable = IHdmiDisplayInformationStatics_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x6ce6b260_f42a_4a15_914c_7b8e2a5a65df); } #[repr(C)] #[doc(hidden)] pub struct IHdmiDisplayInformationStatics_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IHdmiDisplayMode(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IHdmiDisplayMode { type Vtable = IHdmiDisplayMode_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x0c06d5ad_1b90_4f51_9981_ef5a1c0ddf66); } #[repr(C)] #[doc(hidden)] pub struct IHdmiDisplayMode_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut f64) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u16) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, mode: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut HdmiDisplayColorSpace) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut HdmiDisplayPixelEncoding) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IHdmiDisplayMode2(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IHdmiDisplayMode2 { type Vtable = IHdmiDisplayMode2_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x07cd4e9f_4b3c_42b8_84e7_895368718af2); } #[repr(C)] #[doc(hidden)] pub struct IHdmiDisplayMode2_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, );
// This allows us to try and get constants from sets of ASTNodes // Useful, for example, for emmitting compile-time constant globals. use crate::parser::ast_utils::{ASTNode, ASTBinaryOperation}; pub fn get_constant_value_from_node(node: &ASTNode) -> isize { match node { ASTNode::IntegerLiteral(int) => *int, ASTNode::BinaryOperation(bin) => resolve_binary_operation(bin), _ => panic!("Constant propagation was not sophisticated enough to determine a value. OR you attempted to declare a constant value with a non-constant expression.") } } fn resolve_binary_operation (bin: &ASTBinaryOperation) -> isize { let left = get_constant_value_from_node(&bin.left_side); let right = get_constant_value_from_node(&bin.right_side); match &bin.operator[..] { "+" => left + right, "-" => left - right, "*" => left * right, "/" => left / right, "%" => left % right, _ => panic!("Binary operator {} unknown to constant propagation", bin.operator) } }
extern crate kiss3d; extern crate nalgebra as na; extern crate num; mod core; use na::{ Point3, Vector3, UnitQuaternion }; use kiss3d::window::Window; use kiss3d::light::Light; use kiss3d::window::State; use kiss3d::scene::SceneNode; fn main() { let mut window = Window::new("kiss"); let eye = Point3::new(10.0f32, 10.0, 10.0); let at = Point3::origin(); let mut cam = core::player_camera::PlayerCamera::new(eye, at); window.render_with_camera(&mut cam); let mut cube = window.add_cube(1.0, 1.0, 1.0); cube.set_color(0.0, 0.45, 0.30); window.set_light(Light::StickToCamera); let rot = UnitQuaternion::from_axis_angle(&Vector3::y_axis(), 0.014); let app = AppState{ root: cube, rot: rot }; window.render_loop(app); } struct AppState { root: SceneNode, rotation: UnitQuaternion<f32> } impl State for AppState { fn step(&mut self, _:&mut Window) { } }
#[doc = "Reader of register WRP2AR"] pub type R = crate::R<u32, super::WRP2AR>; #[doc = "Writer for register WRP2AR"] pub type W = crate::W<u32, super::WRP2AR>; #[doc = "Register WRP2AR `reset()`'s with value 0xff00_ff00"] impl crate::ResetValue for super::WRP2AR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0xff00_ff00 } } #[doc = "Reader of field `WRP2A_PSTRT`"] pub type WRP2A_PSTRT_R = crate::R<u8, u8>; #[doc = "Write proxy for field `WRP2A_PSTRT`"] pub struct WRP2A_PSTRT_W<'a> { w: &'a mut W, } impl<'a> WRP2A_PSTRT_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !0x7f) | ((value as u32) & 0x7f); self.w } } #[doc = "Reader of field `WRP2A_PEND`"] pub type WRP2A_PEND_R = crate::R<u8, u8>; #[doc = "Write proxy for field `WRP2A_PEND`"] pub struct WRP2A_PEND_W<'a> { w: &'a mut W, } impl<'a> WRP2A_PEND_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x7f << 16)) | (((value as u32) & 0x7f) << 16); self.w } } impl R { #[doc = "Bits 0:6 - WRP2A_PSTRT"] #[inline(always)] pub fn wrp2a_pstrt(&self) -> WRP2A_PSTRT_R { WRP2A_PSTRT_R::new((self.bits & 0x7f) as u8) } #[doc = "Bits 16:22 - WRP2A_PEND"] #[inline(always)] pub fn wrp2a_pend(&self) -> WRP2A_PEND_R { WRP2A_PEND_R::new(((self.bits >> 16) & 0x7f) as u8) } } impl W { #[doc = "Bits 0:6 - WRP2A_PSTRT"] #[inline(always)] pub fn wrp2a_pstrt(&mut self) -> WRP2A_PSTRT_W { WRP2A_PSTRT_W { w: self } } #[doc = "Bits 16:22 - WRP2A_PEND"] #[inline(always)] pub fn wrp2a_pend(&mut self) -> WRP2A_PEND_W { WRP2A_PEND_W { w: self } } }
pub mod material; pub mod mesh; pub mod model;
#[macro_use] mod common; use common::util::*; static UTIL_NAME: &'static str = "expr"; #[test] fn test_simple_arithmetic() { let (_, mut ucmd) = testing(UTIL_NAME); let out = ucmd.args(&["1", "+", "1"]).run().stdout; assert_eq!(out, "2\n"); let (_, mut ucmd) = testing(UTIL_NAME); let out = ucmd.args(&["1", "-", "1"]).run().stdout; assert_eq!(out, "0\n"); let (_, mut ucmd) = testing(UTIL_NAME); let out = ucmd.args(&["3", "*", "2"]).run().stdout; assert_eq!(out, "6\n"); let (_, mut ucmd) = testing(UTIL_NAME); let out = ucmd.args(&["4", "/", "2"]).run().stdout; assert_eq!(out, "2\n"); } #[test] fn test_parenthesis() { let (_, mut ucmd) = testing(UTIL_NAME); let out = ucmd.args(&["(", "1", "+", "1", ")", "*", "2"]).run().stdout; assert_eq!(out, "4\n"); } #[test] fn test_or() { let (_, mut ucmd) = testing(UTIL_NAME); let out = ucmd.args(&["0", "|", "foo"]).run().stdout; assert_eq!(out, "foo\n"); let (_, mut ucmd) = testing(UTIL_NAME); let out = ucmd.args(&["foo", "|", "bar"]).run().stdout; assert_eq!(out, "foo\n"); } #[test] fn test_and() { let (_, mut ucmd) = testing(UTIL_NAME); let out = ucmd.args(&["foo", "&", "1"]).run().stdout; assert_eq!(out, "foo\n"); let (_, mut ucmd) = testing(UTIL_NAME); let out = ucmd.args(&["", "&", "1"]).run().stdout; assert_eq!(out, "0\n"); }
use std::fmt::{Debug, Display}; use data_types::ParquetFile; pub mod and; pub mod level_range; pub trait FileFilter: Debug + Display + Send + Sync { fn apply(&self, file: &ParquetFile) -> bool; }
use rust_gpiozero::{LED, PWMLED, Button}; use std::thread::sleep; use std::time::Duration; use reqwest::Client; use std::thread; enum CallType{ InCall, InitiatingCall, Idle, } static ADDRESS_INFO: &str = "http://localhost:8080/callstatus"; static ADDRESS_CALL: &str = "http://localhost:8080/ring"; fn main() { println!("Starting... "); thread::spawn(light_loop); let mut button_call = Button::new(1); let client = Client::builder() .timeout(Duration::from_secs(3)) .connect_timeout(Duration:: from_secs(2)) .build().unwrap(); println!("Button loop started"); loop{ button_call.wait_for_press(None); match client.get(ADDRESS_CALL).send() { Err(x) => { println!("Error happened while sending request! {}", x); }, Ok(_) => { println!("Pressed!"); } } sleep(Duration::from_secs(5)); } } fn light_loop(){ println!("LED loop started"); let mut led_call = LED::new(7); let mut led_idle = PWMLED::new(18); let mut red: Vec<LED> = Vec::new(); red.push(LED::new(23)); red.push(LED::new(24)); red.push(LED::new(25)); red.push(LED::new(8)); led_idle.on(); led_call.on(); for i in 0..4{ red[i].on(); } sleep(Duration::from_millis(250)); led_idle.off(); led_call.off(); for i in 0..4{ red[i].off(); } let client = Client::new(); let mut last_call = false; let mut last_idle = false; let mut last_error = false; let mut last_calling = false; loop{ let response = get_status(&client); match response { Ok(call) => { match call { CallType::Idle => { if !last_idle{ println!("Idle"); last_idle = true; last_call = false; last_error = false; last_calling = false; led_call.on(); led_idle.set_value(0.0); led_idle.off(); for i in 0..4{ red[i].off(); } } }, CallType::InitiatingCall => { if !last_calling{ println!("Initiating call"); last_calling = true; last_idle = false; last_call = false; last_error = false; for i in 0..4{ red[i].off(); } led_call.off(); led_idle.set_value(0.0); led_idle.off(); for i in 0..4{ red[i].blink(2.0, 2.0); sleep(Duration::from_millis(250)); } } }, CallType::InCall => { if !last_call{ println!("In call"); last_call = true; last_idle = false; last_error = false; last_calling = false; led_call.off(); for i in 0..4{ red[i].off(); } led_idle.pulse(2.0, 2.0); } } } }, Err(_) => { if !last_error{ println!("There was an error!"); last_error = true; last_idle = false; last_call = false; last_calling = false; for i in 0..4{ red[i].off(); } led_call.off(); led_idle.off(); for i in 0..4{ red[i].blink(1.0, 1.0); } } } } sleep(Duration::from_secs(5)); } } fn get_status(client: &Client) -> Result<CallType, String>{ println!("Sending status request..."); let response = client.get(ADDRESS_INFO) .send().map_err(|_| { "Error sending"})? .text().map_err(|_| { "Error parsing response"})?; if response.contains("In call") || response.contains("In hold"){ Ok(CallType::InCall) }else if response.contains("Calling...") || response.contains("Ringing"){ Ok(CallType::InitiatingCall) }else{ Ok(CallType::Idle) } }
#[doc = "Reader of register CCR"] pub type R = crate::R<u32, super::CCR>; #[doc = "Writer for register CCR"] pub type W = crate::W<u32, super::CCR>; #[doc = "Register CCR `reset()`'s with value 0"] impl crate::ResetValue for super::CCR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `DUAL`"] pub type DUAL_R = crate::R<u8, u8>; #[doc = "Write proxy for field `DUAL`"] pub struct DUAL_W<'a> { w: &'a mut W, } impl<'a> DUAL_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !0x1f) | ((value as u32) & 0x1f); self.w } } #[doc = "Reader of field `DELAY`"] pub type DELAY_R = crate::R<u8, u8>; #[doc = "Write proxy for field `DELAY`"] pub struct DELAY_W<'a> { w: &'a mut W, } impl<'a> DELAY_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x0f << 8)) | (((value as u32) & 0x0f) << 8); self.w } } #[doc = "Reader of field `DMACFG`"] pub type DMACFG_R = crate::R<bool, bool>; #[doc = "Write proxy for field `DMACFG`"] pub struct DMACFG_W<'a> { w: &'a mut W, } impl<'a> DMACFG_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 13)) | (((value as u32) & 0x01) << 13); self.w } } #[doc = "Reader of field `MDMA`"] pub type MDMA_R = crate::R<u8, u8>; #[doc = "Write proxy for field `MDMA`"] pub struct MDMA_W<'a> { w: &'a mut W, } impl<'a> MDMA_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 14)) | (((value as u32) & 0x03) << 14); self.w } } #[doc = "Reader of field `CKMODE`"] pub type CKMODE_R = crate::R<u8, u8>; #[doc = "Write proxy for field `CKMODE`"] pub struct CKMODE_W<'a> { w: &'a mut W, } impl<'a> CKMODE_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 16)) | (((value as u32) & 0x03) << 16); self.w } } #[doc = "Reader of field `VREFEN`"] pub type VREFEN_R = crate::R<bool, bool>; #[doc = "Write proxy for field `VREFEN`"] pub struct VREFEN_W<'a> { w: &'a mut W, } impl<'a> VREFEN_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 22)) | (((value as u32) & 0x01) << 22); self.w } } #[doc = "Reader of field `CH17SEL`"] pub type CH17SEL_R = crate::R<bool, bool>; #[doc = "Write proxy for field `CH17SEL`"] pub struct CH17SEL_W<'a> { w: &'a mut W, } impl<'a> CH17SEL_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 23)) | (((value as u32) & 0x01) << 23); self.w } } #[doc = "Reader of field `CH18SEL`"] pub type CH18SEL_R = crate::R<bool, bool>; #[doc = "Write proxy for field `CH18SEL`"] pub struct CH18SEL_W<'a> { w: &'a mut W, } impl<'a> CH18SEL_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 24)) | (((value as u32) & 0x01) << 24); self.w } } #[doc = "Reader of field `PRESC`"] pub type PRESC_R = crate::R<u8, u8>; #[doc = "Write proxy for field `PRESC`"] pub struct PRESC_W<'a> { w: &'a mut W, } impl<'a> PRESC_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x0f << 18)) | (((value as u32) & 0x0f) << 18); self.w } } impl R { #[doc = "Bits 0:4 - Dual ADC mode selection"] #[inline(always)] pub fn dual(&self) -> DUAL_R { DUAL_R::new((self.bits & 0x1f) as u8) } #[doc = "Bits 8:11 - Delay between 2 sampling phases"] #[inline(always)] pub fn delay(&self) -> DELAY_R { DELAY_R::new(((self.bits >> 8) & 0x0f) as u8) } #[doc = "Bit 13 - DMA configuration (for multi-ADC mode)"] #[inline(always)] pub fn dmacfg(&self) -> DMACFG_R { DMACFG_R::new(((self.bits >> 13) & 0x01) != 0) } #[doc = "Bits 14:15 - Direct memory access mode for multi ADC mode"] #[inline(always)] pub fn mdma(&self) -> MDMA_R { MDMA_R::new(((self.bits >> 14) & 0x03) as u8) } #[doc = "Bits 16:17 - ADC clock mode"] #[inline(always)] pub fn ckmode(&self) -> CKMODE_R { CKMODE_R::new(((self.bits >> 16) & 0x03) as u8) } #[doc = "Bit 22 - VREFINT enable"] #[inline(always)] pub fn vrefen(&self) -> VREFEN_R { VREFEN_R::new(((self.bits >> 22) & 0x01) != 0) } #[doc = "Bit 23 - CH17 selection"] #[inline(always)] pub fn ch17sel(&self) -> CH17SEL_R { CH17SEL_R::new(((self.bits >> 23) & 0x01) != 0) } #[doc = "Bit 24 - CH18 selection"] #[inline(always)] pub fn ch18sel(&self) -> CH18SEL_R { CH18SEL_R::new(((self.bits >> 24) & 0x01) != 0) } #[doc = "Bits 18:21 - ADC prescaler"] #[inline(always)] pub fn presc(&self) -> PRESC_R { PRESC_R::new(((self.bits >> 18) & 0x0f) as u8) } } impl W { #[doc = "Bits 0:4 - Dual ADC mode selection"] #[inline(always)] pub fn dual(&mut self) -> DUAL_W { DUAL_W { w: self } } #[doc = "Bits 8:11 - Delay between 2 sampling phases"] #[inline(always)] pub fn delay(&mut self) -> DELAY_W { DELAY_W { w: self } } #[doc = "Bit 13 - DMA configuration (for multi-ADC mode)"] #[inline(always)] pub fn dmacfg(&mut self) -> DMACFG_W { DMACFG_W { w: self } } #[doc = "Bits 14:15 - Direct memory access mode for multi ADC mode"] #[inline(always)] pub fn mdma(&mut self) -> MDMA_W { MDMA_W { w: self } } #[doc = "Bits 16:17 - ADC clock mode"] #[inline(always)] pub fn ckmode(&mut self) -> CKMODE_W { CKMODE_W { w: self } } #[doc = "Bit 22 - VREFINT enable"] #[inline(always)] pub fn vrefen(&mut self) -> VREFEN_W { VREFEN_W { w: self } } #[doc = "Bit 23 - CH17 selection"] #[inline(always)] pub fn ch17sel(&mut self) -> CH17SEL_W { CH17SEL_W { w: self } } #[doc = "Bit 24 - CH18 selection"] #[inline(always)] pub fn ch18sel(&mut self) -> CH18SEL_W { CH18SEL_W { w: self } } #[doc = "Bits 18:21 - ADC prescaler"] #[inline(always)] pub fn presc(&mut self) -> PRESC_W { PRESC_W { w: self } } }
use libsm::sm3::hash::Sm3Hash; use crate::address::traits::checksum::ChecksumI; pub struct ChecksumSM2P256V1 {} impl ChecksumSM2P256V1 { pub fn new() -> Self { ChecksumSM2P256V1 { } } } // --------------------------------------------------------------------------------------------------------- // // 国密 sm3 算法的 checksum // // --------------------------------------------------------------------------------------------------------- impl ChecksumI for ChecksumSM2P256V1 { fn checksum(&self, digest: &Vec<u8>) -> Vec<u8> { // 第一次 hash 计算 let mut hash = Sm3Hash::new(digest.as_slice()); let hash1 = hash.get_hash(); // 第二次hash计算 let mut hash2 = Sm3Hash::new(&hash1); let digest = hash2.get_hash(); // 取前四个字节 digest.get(..4).unwrap().to_vec() } }
use nalgebra::{Scalar, SimdRealField}; use crate::odometry::OdometryModel; use crate::sensor_models::SensorModel; use crate::{Pose, PoseCovariance}; pub mod kalman_filter; pub mod particle_filter; pub trait StateFilter<N: Scalar + SimdRealField> { fn pose(&self) -> Pose<N>; fn covariance(&self) -> PoseCovariance<N>; fn apply_odom<T: OdometryModel<N>>(&mut self, odom: T, time: N); fn apply_sensor<T: SensorModel<N>>(&mut self, sensor: T) where N: Copy; }
extern crate progress_streams; use progress_streams::ProgressWriter; use std::io::{Write, sink}; fn main() { let mut total = 0; let mut file = sink(); let mut writer = ProgressWriter::new(&mut file, |progress: usize| { total += progress; println!("Written {} Kib", total / 1024); }); let buffer = [0u8; 8192]; for _ in 0..100_000 { writer.write(&buffer).unwrap(); } }
use actix_web::{middleware, web, App, Error, HttpResponse, HttpServer}; use anyhow::Result; use juniper_actix::{graphiql_handler, graphql_handler, playground_handler}; use log::*; use crate::db::Db; use crate::graphql::{schema, Context, Image, Schema}; async fn graphiql_route() -> Result<HttpResponse, Error> { graphiql_handler("/graphql", None).await } async fn playground_route() -> Result<HttpResponse, Error> { playground_handler("/graphql", None).await } async fn graphql_route( req: web::HttpRequest, payload: web::Payload, db: web::Data<Db>, schema: web::Data<Schema>, ) -> Result<HttpResponse, Error> { let context = Context::new(Db::clone(&db)); graphql_handler(&schema, &context, req, payload).await } async fn export(db: web::Data<Db>) -> Result<String, Error> { let imgs: Vec<Image> = db.list().map_err(|_| HttpResponse::InternalServerError())?; Ok(serde_json::to_string(&imgs)?) } async fn import(db: web::Data<Db>, imgs: web::Json<Vec<Image>>) -> Result<String, Error> { for img in &*imgs { db.set(&img.id, &img) .map_err(|_| HttpResponse::InternalServerError())?; } Ok("OK".into()) } fn json_cfg(limit_kb: usize) -> web::JsonConfig { web::JsonConfig::default() .limit(limit_kb * 1024) .error_handler(|e, _| { error!("{:?}", e); e.into() }) } pub async fn run(addr: &str, db: Db, limit_kb: usize) -> Result<()> { let server = HttpServer::new(move || { App::new() .data(db.clone()) .data(json_cfg(limit_kb)) .data(schema()) .wrap(middleware::Compress::default()) .wrap(middleware::Logger::default()) .service( web::resource("/graphql") .route(web::post().to(graphql_route)) .route(web::get().to(graphql_route)), ) .service(web::resource("/playground").route(web::get().to(playground_route))) .service(web::resource("/graphiql").route(web::get().to(graphiql_route))) .service(web::resource("/export").route(web::get().to(export))) .service(web::resource("/import").route(web::post().to(import))) }); server.bind(addr).unwrap().run().await?; Ok(()) }
use crate::prelude::*; use rstar::{RTreeObject, AABB}; pub struct My<T>(pub T); // https://docs.rs/rstar/0.9.1/rstar/trait.RTreeObject.html impl RTreeObject for My<Point2> { type Envelope = AABB<[f32; 2]>; fn envelope(&self) -> Self::Envelope { let point = self.0; AABB::from_point([point.x, point.y]) } }
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors. // // 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 alloc::sync::Arc; use spin::Mutex; use core::ops::Deref; use super::super::super::qlib::common::*; use super::super::super::task::*; use super::queue::*; use super::*; #[derive(Default)] pub struct CondInternal { pub queue: Queue, pub signaled: bool, } #[derive(Default, Clone)] pub struct Cond(Arc<Mutex<CondInternal>>); impl Deref for Cond { type Target = Arc<Mutex<CondInternal>>; fn deref(&self) -> &Arc<Mutex<CondInternal>> { &self.0 } } impl Cond { //return: Ok:get notification; Err: interrupted. pub fn Wait(&self, task: &Task) -> Result<()> { let e; { let c = self.lock(); if c.signaled { return Ok(()); } e = task.blocker.generalEntry.clone(); e.Clear(); c.queue.EventRegister(task, &e, !0); } let signal = self.lock().signaled; if signal { self.lock().queue.EventUnregister(task, &e); return Ok(()); } let res = task.blocker.block(true, None); self.lock().queue.EventUnregister(task, &e); return res; } pub fn Broadcast(&self) { let mut c = self.lock(); c.signaled = true; c.queue.Notify(!0); } pub fn Reset(&self) { let mut c = self.lock(); c.signaled = false; } }
use std::collections::HashMap; use std::sync::Arc; use smallvec::SmallVec; use sourcerenderer_core::graphics::{ AccelerationStructureInstance, AccelerationStructureMeshRange, Backend, Barrier, BarrierAccess, BarrierSync, BottomLevelAccelerationStructureInfo, BufferInfo, BufferUsage, CommandBuffer, Device, Format, FrontFace, IndexFormat, MemoryUsage, TopLevelAccelerationStructureInfo, }; use sourcerenderer_core::Platform; use crate::renderer::render_path::RenderPassParameters; use crate::renderer::renderer_assets::{ ModelHandle }; pub struct AccelerationStructureUpdatePass<P: Platform> { device: Arc<<P::GraphicsBackend as Backend>::Device>, blas_map: HashMap<ModelHandle, Arc<<P::GraphicsBackend as Backend>::AccelerationStructure>>, acceleration_structure: Arc<<P::GraphicsBackend as Backend>::AccelerationStructure>, } impl<P: Platform> AccelerationStructureUpdatePass<P> { pub fn new( device: &Arc<<P::GraphicsBackend as Backend>::Device>, init_cmd_buffer: &mut <P::GraphicsBackend as Backend>::CommandBuffer, ) -> Self { let instances_buffer = init_cmd_buffer.upload_top_level_instances(&[]); let info = TopLevelAccelerationStructureInfo { instances_buffer: &instances_buffer, instances: &[], }; let sizes = device.get_top_level_acceleration_structure_size(&info); let scratch_buffer = init_cmd_buffer.create_temporary_buffer( &BufferInfo { size: sizes.build_scratch_size as usize, usage: BufferUsage::ACCELERATION_STRUCTURE | BufferUsage::STORAGE, }, MemoryUsage::VRAM, ); let buffer = device.create_buffer( &BufferInfo { size: sizes.size as usize, usage: BufferUsage::ACCELERATION_STRUCTURE | BufferUsage::STORAGE, }, MemoryUsage::VRAM, Some("AccelerationStructure"), ); let acceleration_structure = init_cmd_buffer.create_top_level_acceleration_structure( &info, sizes.size as usize, &buffer, &scratch_buffer, ); Self { device: device.clone(), blas_map: HashMap::new(), acceleration_structure, } } pub fn execute( &mut self, cmd_buffer: &mut <P::GraphicsBackend as Backend>::CommandBuffer, pass_params: &RenderPassParameters<'_, P> ) { // We never reuse handles, so this works. let mut removed_models = SmallVec::<[ModelHandle; 4]>::new(); for (handle, _) in &self.blas_map { if !pass_params.assets.has_model(*handle) { removed_models.push(*handle); } } for handle in removed_models { self.blas_map.remove(&handle); } let static_drawables = pass_params.scene.scene.static_drawables(); let mut created_blas = false; let mut bl_acceleration_structures = Vec::<Arc<<P::GraphicsBackend as Backend>::AccelerationStructure>>::new(); for drawable in static_drawables { let blas = self.blas_map.get(&drawable.model).cloned().or_else(|| { let model = pass_params.assets.get_model(drawable.model); if model.is_none() { return None; } let model = model.unwrap(); let mesh = pass_params.assets.get_mesh(model.mesh_handle()); if mesh.is_none() { return None; } let mesh = mesh.unwrap(); let blas = { let parts: Vec<AccelerationStructureMeshRange> = mesh .parts .iter() .map(|p| { debug_assert_eq!(p.start % 3, 0); debug_assert_eq!(p.count % 3, 0); AccelerationStructureMeshRange { primitive_start: p.start / 3, primitive_count: p.count / 3, } }) .collect(); debug_assert_ne!(mesh.vertex_count, 0); let info = BottomLevelAccelerationStructureInfo { vertex_buffer: mesh.vertices.buffer(), vertex_buffer_offset: mesh.vertices.offset() as usize, index_buffer: mesh.indices.as_ref().unwrap().buffer(), index_buffer_offset: mesh.indices.as_ref().unwrap().offset() as usize, index_format: IndexFormat::U32, vertex_position_offset: 0, vertex_format: Format::RGB32Float, vertex_stride: std::mem::size_of::<crate::renderer::Vertex>() as u32, mesh_parts: &parts, opaque: true, max_vertex: mesh.vertex_count - 1, }; let sizes = self .device .get_bottom_level_acceleration_structure_size(&info); let scratch_buffer = cmd_buffer.create_temporary_buffer( &BufferInfo { size: sizes.build_scratch_size as usize, usage: BufferUsage::ACCELERATION_STRUCTURE | BufferUsage::STORAGE, }, MemoryUsage::VRAM, ); let buffer = self.device.create_buffer( &BufferInfo { size: sizes.size as usize, usage: BufferUsage::ACCELERATION_STRUCTURE | BufferUsage::STORAGE, }, MemoryUsage::VRAM, Some("AccelerationStructure"), ); cmd_buffer.create_bottom_level_acceleration_structure( &info, sizes.size as usize, &buffer, &scratch_buffer, ) }; self.blas_map.insert(drawable.model, blas.clone()); created_blas = true; Some(blas) }); if let Some(blas) = blas { bl_acceleration_structures.push(blas); } } if created_blas { cmd_buffer.barrier(&[Barrier::GlobalBarrier { old_sync: BarrierSync::ACCELERATION_STRUCTURE_BUILD, new_sync: BarrierSync::ACCELERATION_STRUCTURE_BUILD, old_access: BarrierAccess::ACCELERATION_STRUCTURE_WRITE, new_access: BarrierAccess::ACCELERATION_STRUCTURE_READ | BarrierAccess::ACCELERATION_STRUCTURE_WRITE, }]); cmd_buffer.flush_barriers(); } let mut instances = Vec::<AccelerationStructureInstance<P::GraphicsBackend>>::with_capacity( static_drawables.len(), ); for (bl, drawable) in bl_acceleration_structures .iter() .zip(static_drawables.iter()) { instances.push(AccelerationStructureInstance::<P::GraphicsBackend> { acceleration_structure: bl, transform: drawable.transform, front_face: FrontFace::Clockwise, }); } let tl_instances_buffer = cmd_buffer.upload_top_level_instances(&instances[..]); let tl_info = TopLevelAccelerationStructureInfo { instances_buffer: &tl_instances_buffer, instances: &instances[..], }; let sizes = self .device .get_top_level_acceleration_structure_size(&tl_info); let scratch_buffer = cmd_buffer.create_temporary_buffer( &BufferInfo { size: sizes.build_scratch_size as usize, usage: BufferUsage::ACCELERATION_STRUCTURE | BufferUsage::STORAGE, }, MemoryUsage::VRAM, ); let buffer = self.device.create_buffer( &BufferInfo { size: sizes.size as usize, usage: BufferUsage::ACCELERATION_STRUCTURE | BufferUsage::STORAGE, }, MemoryUsage::VRAM, Some("AccelerationStructure"), ); self.acceleration_structure = cmd_buffer.create_top_level_acceleration_structure( &tl_info, sizes.size as usize, &buffer, &scratch_buffer, ); cmd_buffer.barrier(&[Barrier::GlobalBarrier { old_sync: BarrierSync::ACCELERATION_STRUCTURE_BUILD, new_sync: BarrierSync::RAY_TRACING, old_access: BarrierAccess::ACCELERATION_STRUCTURE_WRITE, new_access: BarrierAccess::ACCELERATION_STRUCTURE_READ, }]); } pub fn acceleration_structure( &self, ) -> &Arc<<P::GraphicsBackend as Backend>::AccelerationStructure> { &self.acceleration_structure } }
use std::net::{TcpListener, TcpStream}; use std::io::{BufRead, BufReader, Write}; use std::{str, fmt, thread}; #[macro_use] extern crate tcpproxy; use tcpproxy::consts; #[allow(dead_code)] struct RequestLine { method: Option<String>, path: Option<String>, protocol: Option<String>, } #[derive(Debug)] struct ParseRequestError{ request: String } impl fmt::Display for ParseRequestError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "fail to parse the request: {}", self.request) } } fn gen_request_line<'a>(request_msg: &'a str) -> Result<RequestLine, ParseRequestError>{ let fst_line_tokens: Vec<&'a str>= request_msg.split_whitespace().collect(); if fst_line_tokens.len() != 3 { return Err(ParseRequestError{ request: format!("invalid request message {}", request_msg), }); } Ok(RequestLine{ method: Some(String::from(fst_line_tokens[0])), path: Some(String::from(fst_line_tokens[1])), protocol: Some(String::from(fst_line_tokens[2])), }) } fn parse_path<'a>(path: &'a str) -> Result<String, ParseRequestError> { let path_tokens: Vec<&'a str> = path.split('/').collect(); // e.g. /order/status/1 if path_tokens.len() != 4 || path_tokens[1] != "order" || path_tokens[2] != "status" || !is_string_numeric(path_tokens[3]){ return Err(ParseRequestError{ request: format!("invalid path {}", path), }); } Ok(format!("the order {} has been shipped", path_tokens[3])) } fn is_string_numeric<'a>(inp_str: &'a str) -> bool { for c in inp_str.chars() { if !c.is_numeric() { return false; } } true } fn gen_err_response<'a>(content: &'a str) -> String { format!("HTTP/1.1 404 Not Found Content-Type: text/html Content-Length:{} {}", content.len(), content) } fn gen_ok_response<'a>(content: &'a str) -> String { format!("HTTP/1.1 200 OK Content-Type: text/html Content-Length:{} {}", content.len(), content) } fn parse_request(rl: RequestLine) -> String { match rl.method.unwrap().as_ref() { "GET" => { match parse_path(&rl.path.unwrap()) { Ok(rep_msg) => gen_ok_response(rep_msg.as_ref()), Err(e) => gen_err_response(e.to_string().as_ref()), } }, invalid_method @ _ => { let err_content = format!("invalid method {}", invalid_method); gen_err_response(err_content.as_ref()) }, } } fn handle_conn(mut stream: TcpStream) { // 1. read the first line from the stream let mut fst_line = String::new(); let mut buf_reader = BufReader::new( stream.try_clone().expect("TODO")); buf_reader.read_line(&mut fst_line).expect("TODO"); let request_line = gen_request_line(fst_line.as_ref()).expect("TODO"); let response = parse_request(request_line); stream.write(response.as_bytes()).expect("TODO"); } fn main() { let listener = TcpListener::bind(consts::ORIG_SERVER_ADDR).unwrap(); log!("this"); log!("TCPServer is listening at {}", consts::ORIG_SERVER_ADDR); for stream in listener.incoming() { let stream = stream.expect(""); thread::spawn(move || handle_conn(stream)); } }
//! An implementation of the Observer pattern. use std::{ cell::RefCell, rc::Rc, }; /// A value that implements the Observer pattern. /// /// Consumers can connect to receive callbacks when the value changes. pub struct ObservableValue<T> where T: Clone { value: T, subs: Vec<Subscription<T>>, new_id: usize, } /// The identifier for a subscription, used to disconnect it when no longer required. #[derive(Clone, Copy, Eq, PartialEq)] pub struct SubscriptionId(usize); struct Subscription<T> { id: SubscriptionId, callback: Box<dyn Fn(&T)> } impl<T> ObservableValue<T> where T: Clone { /// Construct an `ObservableValue`. pub fn new(initial_value: T) -> ObservableValue<T> { ObservableValue { value: initial_value, new_id: 0, subs: Vec::with_capacity(0), } } /// Get the current value pub fn get(&self) -> &T { &self.value } /// Set a new value and notify all connected subscribers. pub fn set(&mut self, new_value: &T) { self.value = new_value.clone(); self.call_subscribers(); } fn call_subscribers(&self) { for sub in self.subs.iter() { (sub.callback)(&self.value) } } /// Connect a new subscriber that will receive callbacks when the /// value is set. /// /// Returns a SubscriptionId to disconnect the subscription when /// no longer required. pub fn connect<F>(&mut self, callback: F) -> SubscriptionId where F: (Fn(&T)) + 'static { let id = SubscriptionId(self.new_id); self.new_id = self.new_id.checked_add(1).expect("No overflow"); self.subs.push(Subscription { id, callback: Box::new(callback), }); self.subs.shrink_to_fit(); id } /// Disconnect an existing subscription. pub fn disconnect(&mut self, sub_id: SubscriptionId) { self.subs.retain(|sub| sub.id != sub_id); self.subs.shrink_to_fit(); } /// Divide this instance into a read half (can listen for updates, but cannot /// write new values) and a write half (can write new values). pub fn split(self) -> (ReadHalf<T>, WriteHalf<T>) { let inner = Rc::new(RefCell::new(self)); ( ReadHalf { inner: inner.clone(), }, WriteHalf { inner: inner } ) } } /// The read half of an `ObservableValue`, which can only listen for /// updates and read the current value. pub struct ReadHalf<T> where T: Clone { inner: Rc<RefCell<ObservableValue<T>>>, } /// The write half of an `ObservableValue`, which can write new values. pub struct WriteHalf<T> where T: Clone { inner: Rc<RefCell<ObservableValue<T>>>, } impl<T> ReadHalf<T> where T: Clone { /// Get the current value pub fn get(&self) -> T { self.inner.borrow().get().clone() } /// Connect a new subscriber that will receive callbacks when the /// value is set. /// /// Returns a SubscriptionId to disconnect the subscription when /// no longer required. pub fn connect<F>(&mut self, callback: F) -> SubscriptionId where F: (Fn(&T)) + 'static { self.inner.borrow_mut().connect(callback) } /// Disconnect an existing subscription. pub fn disconnect(&mut self, sub_id: SubscriptionId) { self.inner.borrow_mut().disconnect(sub_id) } } impl<T> WriteHalf<T> where T: Clone { /// Set a new value and notify all connected subscribers. pub fn set(&mut self, new_value: &T) { self.inner.borrow_mut().set(new_value) } } #[cfg(test)] mod test { use std::{ cell::Cell, rc::Rc, }; use super::ObservableValue; #[test] fn new_get_set() { let mut ov = ObservableValue::new(17); assert_eq!(*ov.get(), 17); ov.set(&18); assert_eq!(*ov.get(), 18); } #[test] fn connect_set() { let mut ov = ObservableValue::<u32>::new(17); let mirror: Rc<Cell<u32>> = Rc::new(Cell::new(0)); let mc = mirror.clone(); ov.connect(move |val| { mc.set(*val); }); // Check callback not yet called. assert_eq!(mirror.get(), 0); ov.set(&18); // Check the callback was called with the correct value. assert_eq!(mirror.get(), 18); } #[test] fn disconnect() { let mut ov = ObservableValue::<u32>::new(17); let mirror_1: Rc<Cell<u32>> = Rc::new(Cell::new(0)); let mirror_2: Rc<Cell<u32>> = Rc::new(Cell::new(0)); let mc1 = mirror_1.clone(); let sub_id_1 = ov.connect(move |val| { mc1.set(*val); }); let mc2 = mirror_2.clone(); let _sub_id_2 = ov.connect(move |val| { mc2.set(*val); }); // Both mirrors are connected with callbacks, set() updates both mirror values. ov.set(&18); assert_eq!(mirror_1.get(), 18); assert_eq!(mirror_2.get(), 18); ov.disconnect(sub_id_1); // Only sub_id_2 is still connected, set() only updates one mirror value. ov.set(&19); assert_eq!(mirror_1.get(), 18); assert_eq!(mirror_2.get(), 19); } #[test] fn split() { let ov = ObservableValue::<u32>::new(17); let (mut r, mut w) = ov.split(); let mirror: Rc<Cell<u32>> = Rc::new(Cell::new(0)); let mc = mirror.clone(); r.connect(move |val| { mc.set(*val); }); // Check callback not yet called. assert_eq!(mirror.get(), 0); w.set(&18); // Check the callback was called with the correct value. assert_eq!(mirror.get(), 18); } }
#[macro_use] extern crate failure; extern crate rayon; #[macro_use] extern crate lazy_static; mod cipher; mod interactif; use failure::Error; fn main() -> Result<(), Error> { let cipher_text = interactif::get_cipher_text() .map_err(|err| format_err!("could get cipher text: {}", err))?; let key = interactif::get_key().map_err(|err| format_err!("could get key: {}", err))?; println!("decoded text: {}", cipher::decode(cipher_text, key)); Ok(()) }
use std::collections::HashMap; fn main() { let mut string_hash_map: HashMap<String, i32> = HashMap::new(); string_hash_map.insert(String::from("hello world"), 1000); println!("{:?}", string_hash_map); let keys = vec![String::from("hello"), String::from("world")]; let values = vec![1, 2]; let scores: HashMap<_, _> = keys.iter().zip(values.iter()).collect(); println!("{:?}", scores); let v = scores.get(&String::from("hello")); match v { Some(values) => println!("v= {}", values), None => println!("NONE"), } for (key, val) in &scores { println!("key: {} val: {}\t", key, val); } // 插入 let mut str_map = HashMap::new(); str_map.insert(String::from("one"), 1); str_map.insert(String::from("two"), 2); str_map.insert(String::from("three"), 3); println!("{:?}", str_map); // 键值不存在则插入 let mut str_map1 = HashMap::new(); str_map1.insert(String::from("one"), 1); str_map1.insert(String::from("two"), 2); str_map1.insert(String::from("three"), 3); str_map1.entry(String::from("three")).or_insert(3); // 键值不存在则插入 println!("{:?}", str_map1); // 根据旧值来更新一个新值 let text = "hello world wonderful world"; let mut list_map = HashMap::new(); for word in text.split_ascii_whitespace() { let count = list_map.entry(word).or_insert(0); *count += 1; } println!("{:?}", list_map); println!("Hello, world!"); }
use std::fmt::{Result, Display, Formatter}; #[derive(Default, Eq, Ord, Copy, Clone, Debug, PartialEq, PartialOrd, Hash)] pub struct File(u8); impl File { pub fn from_bits(bits: u8) -> Self { debug_assert!(bits < 8); File(bits) } pub fn parse(input: char) -> Self { debug_assert!((input as u32) < 128, "it is not even an ASCII character!"); parse_file(&[input as u8]).unwrap().1 } pub fn char(self) -> char { FILE_SYMBOLS[self.0 as usize] as char } pub fn bits(self) -> u8 { self.0 } } static FILE_SYMBOLS: &'static [u8; 8] = b"abcdefgh"; named!(pub parse_file(&[u8]) -> File, map!(is_a!(FILE_SYMBOLS), |c: &[u8]| { File(c[0] - FILE_SYMBOLS[0]) })); impl Display for File { fn fmt(&self, f: &mut Formatter) -> Result { write!(f, "{}", self.char()) } } pub const ALL_FILES: File = File(0); pub const A: File = File(0); pub const B: File = File(1); pub const C: File = File(2); pub const D: File = File(3); pub const E: File = File(4); pub const F: File = File(5); pub const G: File = File(6); pub const H: File = File(7); impl Iterator for File { type Item = File; fn next(&mut self) -> Option<Self::Item> { if self.0 == 8 { None } else { let result = *self; self.0 += 1; Some(result) } } } #[cfg(test)] mod test { use super::*; use itertools::*; #[test] fn all_files() { assert_eq!(ALL_FILES.collect_vec(), [A, B, C, D, E, F, G, H]); } #[test] fn file_char() { assert_eq!(ALL_FILES.map(|f| f.char()).collect::<String>(), "abcdefgh"); } #[test] fn file_display() { assert_eq!(ALL_FILES.map(|f| format!("{}", f)).join(""), "abcdefgh"); } #[test] fn file_debug() { assert_eq!(format!("{:?}", A), "File(0)"); assert_eq!(format!("{:?}", H), "File(7)"); } #[test] fn file_parse() { assert_eq!(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'].into_iter(). map(|f| File::parse(*f)).collect_vec(), [A, B, C, D, E, F, G, H]); } }
fn main() { let x = 5; match x { 1..=5 => println!("satu sampai lima"), _ => println!("yang lain"), } match_char(); } fn match_char() { let x = 'c'; match x { 'a'..='j' => println!("awal huruf ASCII"), 'k'..='z' => println!("akhir huruf ASCII"), _ => println!("yang lain"), } }
use std::convert::TryFrom; pub(crate) type Score = i32; pub(crate) const SCORE_STARTER: Score = 0; pub(crate) const SCORE_DEFAULT_BONUS: Score = 0; pub(crate) const SCORE_MAX: Score = Score::MAX; pub(crate) const SCORE_MIN: Score = Score::MIN; pub(crate) const SCORE_GAP_LEADING: Score = -1; pub(crate) const SCORE_GAP_TRAILING: Score = -1; pub(crate) const SCORE_GAP_INNER: Score = -2; pub(crate) const SCORE_MATCH_CONSECUTIVE: Score = 200; pub(crate) const SCORE_MATCH_SLASH: Score = 180; pub(crate) const SCORE_MATCH_WORD: Score = 160; pub(crate) const SCORE_MATCH_CAPITAL: Score = 140; pub(crate) const SCORE_MATCH_DOT: Score = 120; /// Returns `true` if scores can be considered equal /// and `false` if not. #[inline] pub(crate) fn score_eq(score: Score, rhs: Score) -> bool { score == rhs } /// Adds `rhs` to the score and returns the result. #[inline] pub(crate) fn score_add(score: Score, rhs: Score) -> Score { score.saturating_add(rhs) } /// Subs `rhs` from the score and returns the result. #[inline] #[allow(dead_code)] pub(crate) fn score_sub(score: Score, rhs: Score) -> Score { score.saturating_sub(rhs) } /// Multiplies `score` by `rhs`. #[inline] pub(crate) fn score_mul(score: Score, rhs: Score) -> Score { score.saturating_mul(rhs) } #[inline] pub(crate) fn score_from_usize(u: usize) -> Score { Score::try_from(u).unwrap_or(SCORE_MAX) }
#![allow(non_camel_case_types)] #![cfg_attr(miri, allow(unused_imports))] mod layout_tests { #[cfg(all(test, not(feature = "only_new_tests")))] mod erased_types; #[cfg(all(test, not(feature = "only_new_tests")))] mod prefix_types; #[cfg(all(test, not(feature = "only_new_tests")))] mod value; #[cfg(all(test, not(feature = "only_new_tests")))] mod pointer_types; #[cfg(all(test, not(feature = "only_new_tests")))] mod repr_and_discr; #[cfg(all(test, not(feature = "only_new_tests")))] mod sabi_trait; mod nonexhaustive_enums; #[cfg(all(test, not(feature = "only_new_tests")))] mod get_static_equivalent; #[cfg(all(test, not(feature = "only_new_tests")))] mod extra_checks_combined; #[cfg(all(test, not(feature = "only_new_tests")))] mod stable_abi_attributes; #[cfg(all(test, not(feature = "only_new_tests")))] mod const_params; #[cfg(all(test, not(feature = "only_new_tests")))] mod lifetime_indices_tests; // #[cfg(test)] #[cfg(all(test, not(feature = "only_new_tests")))] mod get_type_layout; #[cfg(all(test, not(feature = "only_new_tests")))] mod shared_types; }
//! Types for the compiled format of a QVM. /// Size of procedure stack adjustment. pub type FrameSize = u32; /// Size of memory block to copy. pub type BlockSize = u32; /// Offset within stack frame. pub type FrameOffset = u32; /// Offset within the argument marshalling space. pub type ArgOffset = u8; /// Absolute instruction offset within code segment. pub type Address = u32; /// Literal value. pub type Literal = u32; // These should match their opcodes #[allow(non_camel_case_types)] /// A QVM instruction. #[derive(Debug,PartialEq, Copy, Clone)] pub enum Instruction { /// Undefined instruction. /// /// Used for padding the code segment. Should not occur at runtime. UNDEF, /// No-operation (NOP). IGNORE, /// Software breakpoint. BREAK, /// Enter a procedure, adjusting stack. ENTER(FrameSize), /// Leave a procedure, adjusting stack. LEAVE(FrameSize), /// Call a procedure. CALL, /// Push stack. PUSH, /// Pop stack. POP, /// Push constant onto stack. CONST(Literal), /// Get address of frame local variable or argument. LOCAL(FrameOffset), /// Jump to top of stack. JUMP, /// Check (signed integer) equality, jump to `Address` if true. EQ(Address), /// Check (signed integer) inequality, jump to `Address` if true. NE(Address), /// Check (signed integer) less-than, jump to `Address` if true. LTI(Address), /// Check (signed integer) less-than or equal-to, jump to `Address` if true. LEI(Address), /// Check (signed integer) greater-than, jump to `Address` if true. GTI(Address), /// Check (signed integer) greater-than or equal-to, jump to `Address` if true. GEI(Address), /// Check (unsigned integer) less-than, jump to `Address` if true. LTU(Address), /// Check (unsigned integer) less-than or equal-to, jump to `Address` if true. LEU(Address), /// Check (unsigned integer) greater-than, jump to `Address` if true. GTU(Address), /// Check (unsigned integer) greater-than or equal-to, jump to `Address` if true. GEU(Address), /// Check (float) equality, jump to `Address` if true. EQF(Address), /// Check (float) inequality, jump to `Address` if true. NEF(Address), /// Check (float) less-than, jump to `Address` if true. LTF(Address), /// Check (float) less-than or equal-to, jump to `Address` if true. LEF(Address), /// Check (float) greater-than, jump to `Address` if true. GTF(Address), /// Check (float) greater-than or equal-to, jump to `Address` if true. GEF(Address), /// Load 1-octet value. LOAD1, /// Load 2-octet value. LOAD2, /// Load 4-octet value. LOAD4, /// Store 1-octet value. STORE1, /// Store 2-octet value. STORE2, /// Store 4-octet value. STORE4, /// Store value into marshalling space. ARG(ArgOffset), /// Copy a block of memory. BLOCK_COPY(BlockSize), /// Sign-extend 8-bit. SEX8, /// Sign-extend 16-bit. SEX16, /// Negate (signed integer). NEGI, /// Add. ADD, /// Subtract. SUB, /// Divide (signed integer). DIVI, /// Divide (unsigned integer). DIVU, /// Modulo (signed integer). MODI, /// Modulo (unsigned integer). MODU, /// Multiply (signed integer). MULI, /// Multiply (unsigned integer). MULU, /// Bitwise AND. BAND, /// Bitwise OR. BOR, /// Bitwise XOR. BXOR, /// Bitwise complement. BCOM, /// Bitwise left-shift. LSH, /// Algebraic (signed) right-shift. RSHI, /// Bitwise (unsigned) right-shift. RSHU, /// Negate (float). NEGF, /// Add (float). ADDF, /// Subtract (float). SUBF, /// Divide (float). DIVF, /// Multiply (float). MULF, /// Convert signed integer to float. CVIF, /// Convert float to signed integer. CVFI, }
fn main() { println!("Sum result {}", sum(5,8)); } fn sum(x:i32, y:i32) -> i32 { let z = { x + y }; z }
#[unstable(feature = "stdsimd", issue = "0")] pub mod arch { pub use coresimd::arch::*; pub mod detect; } #[unstable(feature = "stdsimd", issue = "0")] pub use coresimd::simd;
use self::*; #[test] fn it_works() { assert_eq!(say_hello!([1,2,3]), 2); }
use std::path::PathBuf; use clap::ArgMatches; use app::{NodeConnection, AppConfig, NamedRelayAddress, NamedIndexServerAddress, load_relay_from_file, load_index_server_from_file, load_friend_from_file, PublicKey}; use app::report::{NodeReport, ChannelStatusReport}; #[derive(Debug)] pub enum ConfigError { /// No permissions to configure node NoPermissions, GetReportError, RelayNameAlreadyExists, RelayFileNotFound, LoadRelayFromFileError, AppConfigError, RelayNameNotFound, IndexNameAlreadyExists, IndexFileNotFound, LoadIndexFromFileError, FriendNameAlreadyExists, ParseBalanceError, FriendFileNotFound, LoadFriendFromFileError, FriendPublicKeyMismatch, FriendNameNotFound, ParseMaxDebtError, ChannelNotInconsistent, UnknownRemoteResetTerms, } async fn config_add_relay<'a>(matches: &'a ArgMatches<'a>, mut app_config: AppConfig, node_report: NodeReport) -> Result<(), ConfigError> { let relay_file = matches.value_of("relay_file").unwrap(); let relay_name = matches.value_of("relay_name").unwrap(); for named_relay_address in node_report.funder_report.relays { if named_relay_address.name == relay_name { return Err(ConfigError::RelayNameAlreadyExists); } } let relay_pathbuf = PathBuf::from(relay_file); if !relay_pathbuf.exists() { return Err(ConfigError::RelayFileNotFound); } let relay_address = load_relay_from_file(&relay_pathbuf) .map_err(|_| ConfigError::LoadRelayFromFileError)?; let named_relay_address = NamedRelayAddress { public_key: relay_address.public_key, address: relay_address.address, name: relay_name.to_owned(), }; await!(app_config.add_relay(named_relay_address)) .map_err(|_| ConfigError::AppConfigError) } async fn config_remove_relay<'a>(matches: &'a ArgMatches<'a>, mut app_config: AppConfig, node_report: NodeReport) -> Result<(), ConfigError> { let relay_name = matches.value_of("relay_name").unwrap(); let mut opt_relay_public_key = None; for named_relay_address in node_report.funder_report.relays { if named_relay_address.name == relay_name { opt_relay_public_key = Some(named_relay_address.public_key.clone()); } } let relay_public_key = opt_relay_public_key .ok_or(ConfigError::RelayNameNotFound)?; await!(app_config.remove_relay(relay_public_key)) .map_err(|_| ConfigError::AppConfigError) } async fn config_add_index<'a>(matches: &'a ArgMatches<'a>, mut app_config: AppConfig, node_report: NodeReport) -> Result<(), ConfigError> { let index_file = matches.value_of("index_file").unwrap(); let index_name = matches.value_of("index_name").unwrap(); for named_index_server_address in node_report.index_client_report.index_servers { if named_index_server_address.name == index_name { return Err(ConfigError::IndexNameAlreadyExists); } } let index_pathbuf = PathBuf::from(index_file); if !index_pathbuf.exists() { return Err(ConfigError::IndexFileNotFound); } let index_server_address = load_index_server_from_file(&index_pathbuf) .map_err(|_| ConfigError::LoadIndexFromFileError)?; let named_index_server_address = NamedIndexServerAddress { public_key: index_server_address.public_key, address: index_server_address.address, name: index_name.to_owned(), }; await!(app_config.add_index_server(named_index_server_address)) .map_err(|_| ConfigError::AppConfigError) } async fn config_remove_index<'a>(matches: &'a ArgMatches<'a>, mut app_config: AppConfig, node_report: NodeReport) -> Result<(), ConfigError> { let index_name = matches.value_of("index_name").unwrap(); let mut opt_index_public_key = None; for named_index_server_address in node_report.index_client_report.index_servers { if named_index_server_address.name == index_name { opt_index_public_key = Some(named_index_server_address.public_key.clone()); } } let index_public_key = opt_index_public_key .ok_or(ConfigError::RelayNameNotFound)?; await!(app_config.remove_index_server(index_public_key)) .map_err(|_| ConfigError::AppConfigError) } async fn config_add_friend<'a>(matches: &'a ArgMatches<'a>, mut app_config: AppConfig, node_report: NodeReport) -> Result<(), ConfigError> { let friend_file = matches.value_of("friend_file").unwrap(); let friend_name = matches.value_of("friend_name").unwrap(); let friend_balance_str = matches.value_of("friend_balance").unwrap(); let friend_balance = friend_balance_str.parse::<i128>() .map_err(|_| ConfigError::ParseBalanceError)?; for (_friend_public_key, friend_report) in node_report.funder_report.friends { if friend_report.name == friend_name { return Err(ConfigError::FriendNameAlreadyExists); } } let friend_pathbuf = PathBuf::from(friend_file); if !friend_pathbuf.exists() { return Err(ConfigError::FriendFileNotFound); } let friend_address = load_friend_from_file(&friend_pathbuf) .map_err(|_| ConfigError::LoadFriendFromFileError)?; await!(app_config.add_friend(friend_address.public_key, friend_address.relays, friend_name.to_owned(), friend_balance)) .map_err(|_| ConfigError::AppConfigError)?; Ok(()) } /// Find a friend's public key given his name fn friend_public_key_by_name<'a>(node_report: &'a NodeReport, friend_name: &str) -> Option<&'a PublicKey> { // Search for the friend: for (friend_public_key, friend_report) in &node_report.funder_report.friends { if friend_report.name == friend_name { return Some(friend_public_key) } } None } async fn config_set_friend_relays<'a>(matches: &'a ArgMatches<'a>, mut app_config: AppConfig, node_report: NodeReport) -> Result<(), ConfigError> { let friend_file = matches.value_of("friend_file").unwrap(); let friend_name = matches.value_of("friend_name").unwrap(); let friend_public_key = friend_public_key_by_name(&node_report, friend_name) .ok_or(ConfigError::FriendNameNotFound)? .clone(); let friend_pathbuf = PathBuf::from(friend_file); if !friend_pathbuf.exists() { return Err(ConfigError::FriendFileNotFound); } let friend_address = load_friend_from_file(&friend_pathbuf) .map_err(|_| ConfigError::LoadFriendFromFileError)?; // Just in case, make sure that the the friend we know with this name // has the same public key as inside the provided file. if friend_address.public_key != friend_public_key { return Err(ConfigError::FriendPublicKeyMismatch); } await!(app_config.set_friend_relays(friend_public_key, friend_address.relays)) .map_err(|_| ConfigError::AppConfigError)?; Ok(()) } async fn config_remove_friend<'a>(matches: &'a ArgMatches<'a>, mut app_config: AppConfig, node_report: NodeReport) -> Result<(), ConfigError> { let friend_name = matches.value_of("friend_name").unwrap(); let friend_public_key = friend_public_key_by_name(&node_report, friend_name) .ok_or(ConfigError::FriendNameNotFound)? .clone(); await!(app_config.remove_friend(friend_public_key)) .map_err(|_| ConfigError::AppConfigError) } async fn config_enable_friend<'a>(matches: &'a ArgMatches<'a>, mut app_config: AppConfig, node_report: NodeReport) -> Result<(), ConfigError> { let friend_name = matches.value_of("friend_name").unwrap(); let friend_public_key = friend_public_key_by_name(&node_report, friend_name) .ok_or(ConfigError::FriendNameNotFound)? .clone(); await!(app_config.enable_friend(friend_public_key)) .map_err(|_| ConfigError::AppConfigError) } async fn config_disable_friend<'a>(matches: &'a ArgMatches<'a>, mut app_config: AppConfig, node_report: NodeReport) -> Result<(), ConfigError> { let friend_name = matches.value_of("friend_name").unwrap(); let friend_public_key = friend_public_key_by_name(&node_report, friend_name) .ok_or(ConfigError::FriendNameNotFound)? .clone(); await!(app_config.disable_friend(friend_public_key)) .map_err(|_| ConfigError::AppConfigError) } async fn config_open_friend<'a>(matches: &'a ArgMatches<'a>, mut app_config: AppConfig, node_report: NodeReport) -> Result<(), ConfigError> { let friend_name = matches.value_of("friend_name").unwrap(); let friend_public_key = friend_public_key_by_name(&node_report, friend_name) .ok_or(ConfigError::FriendNameNotFound)? .clone(); await!(app_config.open_friend(friend_public_key)) .map_err(|_| ConfigError::AppConfigError) } async fn config_close_friend<'a>(matches: &'a ArgMatches<'a>, mut app_config: AppConfig, node_report: NodeReport) -> Result<(), ConfigError> { let friend_name = matches.value_of("friend_name").unwrap(); let friend_public_key = friend_public_key_by_name(&node_report, friend_name) .ok_or(ConfigError::FriendNameNotFound)? .clone(); await!(app_config.close_friend(friend_public_key)) .map_err(|_| ConfigError::AppConfigError) } async fn config_set_friend_max_debt<'a>(matches: &'a ArgMatches<'a>, mut app_config: AppConfig, node_report: NodeReport) -> Result<(), ConfigError> { let friend_name = matches.value_of("friend_name").unwrap(); let max_debt_str = matches.value_of("max_debt").unwrap(); let max_debt = max_debt_str.parse::<u128>() .map_err(|_| ConfigError::ParseMaxDebtError)?; let friend_public_key = friend_public_key_by_name(&node_report, friend_name) .ok_or(ConfigError::FriendNameNotFound)? .clone(); await!(app_config.set_friend_remote_max_debt(friend_public_key, max_debt)) .map_err(|_| ConfigError::AppConfigError) } async fn config_reset_friend<'a>(matches: &'a ArgMatches<'a>, mut app_config: AppConfig, node_report: NodeReport) -> Result<(), ConfigError> { let friend_name = matches.value_of("friend_name").unwrap(); let mut opt_friend_pk_report = None; for (friend_public_key, friend_report) in &node_report.funder_report.friends { if friend_report.name == friend_name { opt_friend_pk_report = Some((friend_public_key, friend_report)); } } let (friend_public_key, friend_report) = opt_friend_pk_report .ok_or(ConfigError::FriendNameNotFound)?; // Obtain the reset token // (Required as a proof that we already received the remote reset terms): let reset_token = match &friend_report.channel_status { ChannelStatusReport::Consistent(_) => return Err(ConfigError::ChannelNotInconsistent), ChannelStatusReport::Inconsistent(channel_inconsistent_report) => { if let Some(remote_reset_terms) = &channel_inconsistent_report.opt_remote_reset_terms { &remote_reset_terms.reset_token } else { return Err(ConfigError::UnknownRemoteResetTerms); } }, }; await!(app_config.reset_friend_channel(friend_public_key.clone(), reset_token.clone())) .map_err(|_| ConfigError::AppConfigError) } pub async fn config<'a>(matches: &'a ArgMatches<'a>, mut node_connection: NodeConnection) -> Result<(), ConfigError> { let app_config = node_connection.config() .ok_or(ConfigError::NoPermissions)? .clone(); // Obtain current report: let app_report = node_connection.report(); let (node_report, incoming_mutations) = await!(app_report.incoming_reports()) .map_err(|_| ConfigError::GetReportError)?; // We currently don't need live updates about report mutations: drop(incoming_mutations); drop(app_report); match matches.subcommand() { ("add-relay", Some(matches)) => await!(config_add_relay(matches, app_config, node_report))?, ("remove-relay", Some(matches)) => await!(config_remove_relay(matches, app_config, node_report))?, ("add-index", Some(matches)) => await!(config_add_index(matches, app_config, node_report))?, ("remove-index", Some(matches)) => await!(config_remove_index(matches, app_config, node_report))?, ("add-friend", Some(matches)) => await!(config_add_friend(matches, app_config, node_report))?, ("set-friend-relays", Some(matches)) => await!(config_set_friend_relays(matches, app_config, node_report))?, ("remove-friend", Some(matches)) => await!(config_remove_friend(matches, app_config, node_report))?, ("enable-friend", Some(matches)) => await!(config_enable_friend(matches, app_config, node_report))?, ("disable-friend", Some(matches)) => await!(config_disable_friend(matches, app_config, node_report))?, ("open-friend", Some(matches)) => await!(config_open_friend(matches, app_config, node_report))?, ("close-friend", Some(matches)) => await!(config_close_friend(matches, app_config, node_report))?, ("set-friend-max-debt", Some(matches)) => await!(config_set_friend_max_debt(matches, app_config, node_report))?, ("reset-friend", Some(matches)) => await!(config_reset_friend(matches, app_config, node_report))?, _ => unreachable!(), } Ok(()) }
extern crate serde_json; extern crate clap; use rocket::State; use rocket::response::{Responder, Response}; use rocket::http::{Status, ContentType}; use rocket::request::Request; use rocket::response; use rocket_contrib::json::{Json, JsonValue}; use crate::store::TinStore; #[derive(Deserialize)] pub struct Element { pub value: String, pub expiration: i64, } #[derive(Debug)] pub struct ApiResponse { result: JsonValue, status: Status, } impl<'r> Responder<'r> for ApiResponse { fn respond_to(self, req: &Request) -> response::Result<'r> { Response::build_from(self.result.respond_to(&req).unwrap()) .status(self.status) .header(ContentType::JSON) .ok() } } #[get("/", format = "application/json")] pub fn home() -> ApiResponse { ApiResponse { result: json!({"result": clap::crate_version!()}), status: Status::Ok, } } #[get("/get/<key>", format = "application/json")] pub fn get(key: String, store: State<TinStore>) -> ApiResponse { if let Some(value) = store.get(key) { ApiResponse { result: json!({"result": value}), status: Status::Ok, } } else { ApiResponse { result: json!({"result": "Key not found."}), status: Status::NotFound } } } #[post("/set/<key>", format = "application/json", data = "<body>")] pub fn set(key: String, body: Json<Element>, store: State<TinStore>) -> ApiResponse { if let Some(_) = store.set(key, body.value.clone()) { ApiResponse { result: json!({"result": "Success."}), status: Status::Ok, } } else { ApiResponse { result: json!({"result": "Error while inserting key/value pair."}), status: Status::InternalServerError, } } } #[post("/setexp/<key>", format = "application/json", data = "<body>")] pub fn set_exp(key: String, body: Json<Element>, store: State<TinStore>) -> ApiResponse { if let Some(_) = store.set_exp(key, body.value.clone(), body.expiration.clone()) { ApiResponse { result: json!({"result": "Success."}), status: Status::Ok, } } else { ApiResponse { result: json!({"result": "Error while inserting key/value pair."}), status: Status::InternalServerError, } } } #[delete("/delete/<key>")] pub fn delete(key: String, store: State<TinStore>) -> ApiResponse { if let Some(_) = store.get(key.clone()) { (*store).delete(key); ApiResponse { result: json!({"result": "Success."}), status: Status::Ok, } } else { ApiResponse { result: json!({"result": "Error while deleting key/value pair."}), status: Status::InternalServerError, } } }
use rand::Rng; use rayon::prelude::*; use std::{fs::File, io::BufWriter, sync::Arc}; #[macro_use] mod macros; mod camera; mod config; pub mod hittables; pub mod materials; mod ray; mod vec3; pub use camera::Camera; pub use config::{CameraConfig, ImgConfig, RunConfig, SceneConfig}; pub use hittables::Hittable; use hittables::{HitRecord, HittableList, Sphere, BVH}; pub use materials::Material; use materials::{Dielectric, Lambertian, Metal}; pub use ray::Ray; pub use vec3::{Color, Point, Vec3}; pub fn ray_color(ray: &Ray, world: &dyn Hittable, depth: i32) -> Vec3 { if depth <= 0 { return Color::ceros(); } let mut rec = HitRecord::new(); if world.hit(ray, 0.001, std::f64::INFINITY, &mut rec) { let mut scattered = Ray::new(Point::ceros(), Vec3::ceros()); let mut attenuation = Vec3::ceros(); if Arc::clone(&rec.material).scatter(ray, &mut rec, &mut attenuation, &mut scattered) { return attenuation * ray_color(&scattered, world, depth - 1); } return Color::ceros(); } let unit_dir = ray.direction().unit_vector(); let t = 0.5 * (unit_dir.y() + 1.0); Vec3::ones() * (1.0 - t) + Vec3::new(0.5, 0.7, 1.0) * t } pub fn write_to_file(x: u32, y: u32, data: &[u8], filename: &str) { let file = File::create(filename).expect("Failed creating file"); let ref mut w = BufWriter::new(file); let mut encoder = png::Encoder::new(w, x, y); encoder.set_color(png::ColorType::RGB); encoder.set_depth(png::BitDepth::Eight); encoder.set_compression(png::Compression::Best); let mut writer = encoder.write_header().expect("Couldn't create writer"); writer .write_image_data(data) .expect("Error while saving image data"); } pub fn random_scene(config: &SceneConfig) -> HittableList { config.validate(); let mut world = HittableList::new(); let ground_material = Arc::new(Lambertian::new(Color::new(0.5, 0.5, 0.5))); world.add(Arc::new(Sphere::new( Point::new(0.0, -1000.0, 0.0), 1000.0, ground_material, ))); let mut rng = rand::thread_rng(); let goal_count = config.small_sphere_count as f64; let mut current_count = 0.0; let mut iterations_remainig = 484.0; for a in -11..11 { let a = a as f64; for b in -11..11 { let b = b as f64; let keep_prob = ((goal_count - current_count) / iterations_remainig).min(1.0); iterations_remainig -= 1.0; if float_eq!(current_count, goal_count) { break; } if !rng.gen_bool(keep_prob) { continue; } let choose_mat: f64 = rng.gen(); let center = Point::new(a + 0.9 * rng.gen::<f64>(), 0.2, b + 0.9 * rng.gen::<f64>()); if (center - Point::new(4.0, 0.2, 0.0)).len() > 0.9 { let sphere_material: Arc<dyn Material>; if choose_mat < config.diffuse_prob { // diffuse let albedo = Color::random_in_unit_cube() * Color::random_in_unit_cube(); sphere_material = Arc::new(Lambertian::new(albedo)); } else if choose_mat < config.diffuse_prob + config.metal_prob { // metal let albedo = Color::random_in_range(0.5, 1.0); let fuzz = rng.gen_range(0.0..0.5); sphere_material = Arc::new(Metal::new(albedo, fuzz)); } else { // glass sphere_material = Arc::new(Dielectric::new(1.5)); } world.add(Arc::new(Sphere::new(center, 0.2, sphere_material))); current_count += 1.0; } } } let material1 = Arc::new(Dielectric::new(1.5)); world.add(Arc::new(Sphere::new( Point::new(0.0, 1.0, 0.0), 1.0, material1, ))); let material2 = Arc::new(Lambertian::new(Color::new(0.4, 0.2, 0.1))); world.add(Arc::new(Sphere::new( Point::new(-4.0, 1.0, 0.0), 1.0, material2, ))); let material3 = Arc::new(Metal::new(Color::new(0.7, 0.6, 0.5), 0.0)); world.add(Arc::new(Sphere::new( Point::new(4.0, 1.0, 0.0), 1.0, material3, ))); world } pub fn run(config: &RunConfig) { let RunConfig { img_config, cam_config, scene_config, filename, quiet, use_bvh, } = config; let img_height: u32 = (img_config.width as f64 / img_config.aspect_ratio) as u32; let camera = Camera::new( cam_config.lookfrom, cam_config.lookat, cam_config.vec_up, cam_config.vert_fov, img_config.aspect_ratio, cam_config.aperture, cam_config.focus_dist, ); let mut scene = random_scene(&scene_config); let world: Arc<dyn Hittable> = if *use_bvh { Arc::new(HittableList::with_objects(vec![Arc::new( BVH::from_hittable_list(&mut scene), )])) } else { Arc::new(scene) }; let mut buff = vec![0u8; (img_config.width * img_height * 3) as usize]; buff.par_chunks_mut(img_config.width as usize * 3) .rev() .enumerate() .for_each(|(j, row)| { row.par_chunks_mut(3).enumerate().for_each_init( || (rand::thread_rng(), world.clone()), |(rng, world), (i, pixel)| { let mut pixel_color = Color::ceros(); for _ in 0..img_config.samples_per_pixel { let u = (i as f64 + rng.gen::<f64>()) / (img_config.width - 1) as f64; let v = (j as f64 + rng.gen::<f64>()) / (img_height - 1) as f64; let ray = camera.get_ray(u, v); pixel_color += ray_color(&ray, &**world, img_config.max_depth); pixel[0] = pixel_color.r(img_config.samples_per_pixel); pixel[1] = pixel_color.g(img_config.samples_per_pixel); pixel[2] = pixel_color.b(img_config.samples_per_pixel); } }, ) }); if !quiet { write_to_file(img_config.width, img_height, &buff, filename); } } #[cfg(test)] mod tests { use super::*; fn run_scene_count(config: &SceneConfig) { let mut values = Vec::new(); for _ in 0..100 { let world = random_scene(config); values.push(world.count() - 4); } let avg = (values.iter().sum::<usize>() as f64 / values.len() as f64) as i64; assert!( (config.small_sphere_count as i64 - avg).abs() < (config.small_sphere_count / 20).max(1) as i64 ); } #[test] fn random_scene_count() { let mut conf = SceneConfig::default(); run_scene_count(&conf); for c in (0..=400).step_by(50) { conf.small_sphere_count = c; run_scene_count(&conf); } } }
#[doc = "Reader of register ISR"] pub type R = crate::R<u32, super::ISR>; #[doc = "Writer for register ISR"] pub type W = crate::W<u32, super::ISR>; #[doc = "Register ISR `reset()`'s with value 0"] impl crate::ResetValue for super::ISR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `BMPER`"] pub type BMPER_R = crate::R<bool, bool>; #[doc = "Reader of field `DLLRDY`"] pub type DLLRDY_R = crate::R<bool, bool>; #[doc = "Reader of field `SYSFLT`"] pub type SYSFLT_R = crate::R<bool, bool>; #[doc = "Write proxy for field `SYSFLT`"] pub struct SYSFLT_W<'a> { w: &'a mut W, } impl<'a> SYSFLT_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 5)) | (((value as u32) & 0x01) << 5); self.w } } #[doc = "Reader of field `FLT5`"] pub type FLT5_R = crate::R<bool, bool>; #[doc = "Reader of field `FLT4`"] pub type FLT4_R = crate::R<bool, bool>; #[doc = "Reader of field `FLT3`"] pub type FLT3_R = crate::R<bool, bool>; #[doc = "Reader of field `FLT2`"] pub type FLT2_R = crate::R<bool, bool>; #[doc = "Reader of field `FLT1`"] pub type FLT1_R = crate::R<bool, bool>; impl R { #[doc = "Bit 17 - Burst mode Period Interrupt Flag"] #[inline(always)] pub fn bmper(&self) -> BMPER_R { BMPER_R::new(((self.bits >> 17) & 0x01) != 0) } #[doc = "Bit 16 - DLL Ready Interrupt Flag"] #[inline(always)] pub fn dllrdy(&self) -> DLLRDY_R { DLLRDY_R::new(((self.bits >> 16) & 0x01) != 0) } #[doc = "Bit 5 - System Fault Interrupt Flag"] #[inline(always)] pub fn sysflt(&self) -> SYSFLT_R { SYSFLT_R::new(((self.bits >> 5) & 0x01) != 0) } #[doc = "Bit 4 - Fault 5 Interrupt Flag"] #[inline(always)] pub fn flt5(&self) -> FLT5_R { FLT5_R::new(((self.bits >> 4) & 0x01) != 0) } #[doc = "Bit 3 - Fault 4 Interrupt Flag"] #[inline(always)] pub fn flt4(&self) -> FLT4_R { FLT4_R::new(((self.bits >> 3) & 0x01) != 0) } #[doc = "Bit 2 - Fault 3 Interrupt Flag"] #[inline(always)] pub fn flt3(&self) -> FLT3_R { FLT3_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bit 1 - Fault 2 Interrupt Flag"] #[inline(always)] pub fn flt2(&self) -> FLT2_R { FLT2_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 0 - Fault 1 Interrupt Flag"] #[inline(always)] pub fn flt1(&self) -> FLT1_R { FLT1_R::new((self.bits & 0x01) != 0) } } impl W { #[doc = "Bit 5 - System Fault Interrupt Flag"] #[inline(always)] pub fn sysflt(&mut self) -> SYSFLT_W { SYSFLT_W { w: self } } }
use raylib::prelude::*; use std::io::{Read, Write}; use std::net::TcpStream; use crate::awaiting_opponent; use crate::imui::*; use crate::pong; use crate::scene::*; use common::{DEVEL_IP, PROD_IP}; pub struct TitleScreen { should_quit: bool, failed_to_connect_to_lobby: bool, production_url: bool, } impl TitleScreen { pub fn new() -> Self { TitleScreen { should_quit: false, failed_to_connect_to_lobby: false, production_url: false, } } } impl Scene for TitleScreen { fn process(&mut self, _s: &mut SceneAPI, rl: &mut RaylibHandle) { if rl.is_key_pressed(KeyboardKey::KEY_F6) { self.production_url = !self.production_url; } } fn draw(&mut self, _s: &mut SceneAPI, d: &mut RaylibDrawHandle) { d.clear_background(Color::GRAY); let ip_to_connect_to; if self.production_url { d.draw_text("PRODUCTION URL", 0, 0, 16, Color::RED); ip_to_connect_to = PROD_IP; } else { ip_to_connect_to = DEVEL_IP; } let screen_size = Vector2::new(d.get_screen_width() as f32, d.get_screen_height() as f32); if self.failed_to_connect_to_lobby { let err = "Failed to connect to lobby server"; d.draw_text( err, (screen_size.x / 2.0 - measure_text_ex(d.get_font_default(), err, 30.0, 1.0).x / 2.0) as i32, 30, 30, Color::WHITE, ); } let num_buttons = 3; let button_size = Vector2::new(700.0, 60.0); let set_of_buttons_size = button_size + Vector2::new(0.0, button_size.y * ((num_buttons - 1) as f32)); let spacing = 10.0; let mut cur_place_pos = screen_size / 2.0 - set_of_buttons_size / 2.0; if button(d, cur_place_pos, button_size, "HOST") { println!("Connecting to {}", ip_to_connect_to); match TcpStream::connect(ip_to_connect_to) { Ok(mut stream) => { println!("Successfully connected to server in port 3333"); let msg: [u8; 5] = [1, 0, 0, 0, 0]; stream.write(&msg).unwrap(); println!("Sent create lobby command, awaiting lobby code..."); let mut data = [0 as u8; 4]; // using 4 byte buffer match stream.read_exact(&mut data) { Ok(_) => { let response: i32 = i32::from_le_bytes(data); if response != 0 { println!("New lobby created! Lobby code: {}", response); _s.new_scene = Some(Box::new( awaiting_opponent::AwaitingOpponent::new(stream, response), )); } else { println!("Error creating lobby"); } } Err(e) => { println!("Failed to receive data: {}", e); } } } Err(e) => { println!("Failed to connect: {}", e); self.failed_to_connect_to_lobby = true; } } } cur_place_pos.y += button_size.y + spacing; if button(d, cur_place_pos, button_size, "JOIN FROM CLIPBOARD") { let lobby_code_string = d.get_clipboard_text().unwrap(); // TODO handle error where clipboard content is not a string, a utf8 error instead let lobby_code = lobby_code_string.parse::<i32>().unwrap(); // TODO handle error where clipboard content is not a proper lobby code match TcpStream::connect(ip_to_connect_to) { Ok(mut stream) => { println!("Successfully connected to server in port 3333"); println!("Requesting to join lobby {}", lobby_code); let lobby_code_bytes = lobby_code.to_le_bytes(); let msg: [u8; 5] = [ 2, lobby_code_bytes[0], lobby_code_bytes[1], lobby_code_bytes[2], lobby_code_bytes[3], ]; stream.write(&msg).unwrap(); println!("Sent join lobby command, awaiting lobby code..."); // TODO refactor this into a function based off of the host code let mut data = [0 as u8; 4]; // using 4 byte buffer match stream.read_exact(&mut data) { Ok(_) => { let response: i32 = i32::from_le_bytes(data); if response == 200 { println!("Joined Lobby!"); _s.new_scene = Some(Box::new(pong::PongGame::new(stream, false))); } else { println!( "Error creating lobby, response from server: {}", response ); } } Err(e) => { println!("Failed to receive data: {}", e); } } } Err(e) => { println!("Failed to connect: {}", e); self.failed_to_connect_to_lobby = true; } } } cur_place_pos.y += button_size.y + spacing; if button(d, cur_place_pos, button_size, "EXIT") { self.should_quit = true; } } fn should_quit(&self) -> bool { self.should_quit } }
use std::io::{Error, Read, Write};//引入IO口中的读、写、错误方法 use std::net::{TcpListener, TcpStream};//引入TCP监听和TCP数据流格式 use std::thread;//引用线程包 use std::time;//引入时间包 fn handle_client(mut stream: TcpStream) -> Result<(), Error>{ let mut buf = [0;512];//生成一个缓存数组 println!("服务器在等待客户端发送消息"); for _ in 0..1000{ //循环执行1000次 let byte_read = stream.read(&mut buf)?; //从数据流中读取数据存到buff println!("{}",std::str::from_utf8(&buf[..byte_read]).expect("Could not write buffer as string"));//打印接收的字符串 if byte_read == 0 { //如果数据流为0返回Ok return Ok(()); } stream.write(&buf[..byte_read])?; //将缓存的数组写回数据流并且发送 thread::sleep(time::Duration::from_secs(1 as u64));//休眠1s } Ok(())//返回ok } fn main() -> std::io::Result<()>{ let listener = TcpListener::bind("0.0.0.0:4444")?;//监听任意地址的4444端口,bind绑定端口 let mut thread_vec: Vec<thread::JoinHandle<()>> = Vec::new();//基于线程管理生成一个线程数组 for stream in listener.incoming(){//listener的incoming方法可以返回一个产生流序列的迭代器 let stream: TcpStream= match stream{ Ok(stream) => stream, Err(e)=>panic!("err"), }; let handle = thread::spawn(move||{ handle_client(stream)//对数据流进行处理 .unwrap_or_else(|Error| eprintln!("{:?}", Error)); }); thread_vec.push(handle); //将处理结果放在线程数组上 } for handle in thread_vec{ //依次执行处理结果,并加入到工作线程 handle.join().unwrap(); } Ok(()) }
use std::mem; use textwrap; #[derive(Debug, Clone)] /// A word wrapper. /// Takes input lines like a vector (with [WordWrapper::push]). /// The wrapped text (to the specified width) is returned with [WordWrapper::get_text]. /// The text is only rerendered, when the content was modified or marked dirty with [WordWrapper:mark_dirty] pub struct WordWrapper { screen_lines: Vec<String>, dirty: bool, input_lines: Vec<String>, termwidth: usize, } impl Default for WordWrapper { fn default() -> WordWrapper { WordWrapper { screen_lines: Vec::new(), dirty: true, input_lines: Vec::new(), termwidth: 80, } } } impl WordWrapper { /// Create a new instance of this object with the given wrap width. pub fn new(width: usize) -> Self { WordWrapper { screen_lines: Vec::new(), dirty: true, input_lines: Vec::new(), termwidth: width, } } /// Returns the amount of the rendered lines. /// This does **not** regenerate them if the input has been modified. pub fn len(&self) -> usize { self.screen_lines.len() } /// Returns the amount of the input lines. pub fn input_len(&self) -> usize { self.input_lines.len() } /// Sets the width to render for. /// Forces regeneration on next access. pub fn set_width(&mut self, w: usize) { self.termwidth = w; self.dirty = true; } /// Get the width that is rendered for. pub fn get_width(&mut self) -> usize { self.termwidth } /// Add a new line to the line list pub fn push(&mut self, s: String) { self.input_lines.push(s); self.dirty = true; } /// Forces the buffer to be regenerated, no matter what. pub fn mark_dirty(&mut self) { self.dirty = true; } fn check_dirty(&mut self) { if self.dirty { if self.input_lines.len() == 0 { let _ = mem::replace(&mut self.screen_lines, Vec::new()); } else { let mut nvec: Vec<String> = Vec::with_capacity(self.input_lines.len()); let wrapper = textwrap::Wrapper::new(self.termwidth); for line in &self.input_lines { for wrap in wrapper.wrap_iter(line) { nvec.push(wrap.to_string()); } } let _ = mem::replace(&mut self.screen_lines, nvec); } self.dirty = false; } } /// Return a "Window" of lines items with an offset of scroll. /// This is seen from the end /// /// # Example /// ```rust /// let mut textwrap = WordWrapper::new(10); /// textwrap.push("Hello World!"); /// textwrap.push("I am here!"); /// textwrap.push("YES"); /// /// let text = textwrap.get_text(2, 1); /// # let check = vec!["I am here!", "World!"].iter().map(|s| String::from(s)).collect<Vec<String>>(); /// assert_eq!(Ok(&check), text); /// ``` pub fn get_text(&mut self, lines: u16, scroll: u16) -> Result<&[String], String> { self.check_dirty(); // lines = amount of lines requested // scroll = offset if lines == 0 || self.screen_lines.len() == 0 { Ok(&[]) // We do not have data } else if scroll == 0 { // User just requests some lines with no offset if lines > self.screen_lines.len() as u16 { // Not a failure as you can "request" x lines, but not have them avaliable Ok(&self.screen_lines[..]) } else { Ok(&self.screen_lines[self.screen_lines.len() - lines as usize..]) } } else { if scroll >= self.screen_lines.len() as u16 { Err(String::from("Cannot scroll past end")) } else { let to = self.screen_lines.len() - scroll as usize; let from = match to.checked_sub(lines as usize) { Some(off) => off, None => 0, }; Ok(&self.screen_lines[from..to]) } } } }
extern crate num; // return true if the number is a palendrome in decimal pub fn is_dec_palendrome(x: u32) -> bool { let mut reverse: u32 = 0; let mut temp = x; while temp > 0 { reverse *= 10; reverse += temp % 10; temp /= 10; } reverse == x } // return true if the number is a palendrome in binary pub fn is_bin_palandrome(num: u32) -> bool { let num_bits = 32 - num.leading_zeros(); for i in 0..num_bits / 2 { if ((num >> i) & 1) != ((num >> (num_bits - (i + 1))) & 1) { return false; } } return true; } // return true if a BigUint is a decimal pallendrome pub fn bigint_is_dec_palendrome(value: &num::BigUint) -> bool { let dec_str: String = value.to_str_radix(10).to_string(); let dec_str_bytes: Vec<u8> = dec_str.into_bytes(); let iter_size = dec_str_bytes.len() / 2; let end = dec_str_bytes.len() - 1; for i in 0..iter_size { if dec_str_bytes[i] != dec_str_bytes[end - i] { return false; } } true }
#{script}
use regex::Regex; use std::collections::BTreeMap; use std::collections::HashMap; use std::fs; fn main() { let data = fs::read_to_string("input").expect("Error"); println!("Oy, oy, oy, the result is {}", run_input(data)); } fn run_input(data: String) -> u32 { let mut rules: BTreeMap<String, HashMap<String, u32>> = BTreeMap::new(); data.lines().for_each(|line| { let (bag, inside_bags) = parse_line(line); let containers = rules.entry(bag).or_insert(HashMap::new()); for (inside_bag, count) in inside_bags { let add_bag = containers.entry(inside_bag).or_insert(0); *add_bag += count; } }); count_for_bag(&"shiny gold".to_string(), &rules) } fn count_for_bag(bag_name: &String, rules: &BTreeMap<String, HashMap<String, u32>>) -> u32 { let mut count = 0; rules .get(bag_name) .unwrap() .iter() .for_each(|(name, number)| count += number + number * count_for_bag(name, rules)); count } fn parse_line(line: &str) -> (String, HashMap<String, u32>) { let re = Regex::new(r"(\d )?([a-z]+ [a-z]+) bag").unwrap(); let mut inside_bags: HashMap<String, u32> = HashMap::new(); let mut bags = re.captures_iter(line); let big_bag = &bags.next().unwrap()[2]; for cap in bags { let count = match cap.get(1) { Some(x) => x.as_str().trim().parse::<u32>().unwrap(), None => continue, }; inside_bags.insert(cap[2].to_string(), count); } (big_bag.to_string(), inside_bags) } #[cfg(test)] mod test { use super::*; #[test] fn test_main_process() { let entry_data: String = String::from( "shiny gold bags contain 2 dark red bags. dark red bags contain 2 dark orange bags. dark orange bags contain 2 dark yellow bags. dark yellow bags contain 2 dark green bags. dark green bags contain 2 dark blue bags. dark blue bags contain 2 dark violet bags. dark violet bags contain no other bags.", ); assert_eq!(126, run_input(entry_data)); } #[test] fn test_main_process_with_multiple_bags_inside() { let entry_data: String = String::from( "light red bags contain 1 bright white bag, 2 muted yellow bags. dark orange bags contain 3 bright white bags, 4 muted yellow bags. bright white bags contain 1 shiny gold bag. muted yellow bags contain 2 shiny gold bags, 9 faded blue bags. shiny gold bags contain 1 dark olive bag, 2 vibrant plum bags. dark olive bags contain 3 faded blue bags, 4 dotted black bags. vibrant plum bags contain 5 faded blue bags, 6 dotted black bags. faded blue bags contain no other bags. dotted black bags contain no other bags.", ); assert_eq!(32, run_input(entry_data)); } #[test] fn test_parse_line_with_two_inside() { let line = "light red bags contain 1 bright white bag, 2 muted yellow bags."; let mut inside_bags = HashMap::new(); inside_bags.insert(String::from("bright white"), 1); inside_bags.insert(String::from("muted yellow"), 2); let expected: (String, HashMap<String, u32>) = (String::from("light red"), inside_bags); assert_eq!(expected, parse_line(line)); } #[test] fn test_parse_line_with_one_inside() { let line = "bright white bags contain 1 shiny gold bag."; let mut inside_bags = HashMap::new(); inside_bags.insert(String::from("shiny gold"), 1); let expected: (String, HashMap<String, u32>) = (String::from("bright white"), inside_bags); assert_eq!(expected, parse_line(line)); } #[test] fn test_parse_line_with_nothing_inside() { let line = "dark violet bags contain no other bags."; let inside_bags = HashMap::new(); let expected: (String, HashMap<String, u32>) = (String::from("dark violet"), inside_bags); assert_eq!(expected, parse_line(line)); } #[test] fn test_parse_line_with_four_inside() { let line = "light red bags contain 1 bright white bag, 2 muted yellow bags, 5 faded blue bags, 6 dotted black bags."; let mut inside_bags = HashMap::new(); inside_bags.insert(String::from("bright white"), 1); inside_bags.insert(String::from("muted yellow"), 2); inside_bags.insert(String::from("faded blue"), 5); inside_bags.insert(String::from("dotted black"), 6); let expected: (String, HashMap<String, u32>) = (String::from("light red"), inside_bags); assert_eq!(expected, parse_line(line)); } }
// Copyright 2014 The Servo Project Developers. See the // COPYRIGHT file at the top-level directory of this distribution. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![crate_name="string_cache_plugin"] #![crate_type="dylib"] #![feature(plugin_registrar, quote, box_syntax)] #![feature(rustc_private, slice_patterns)] #![cfg_attr(test, deny(warnings))] #![allow(unused_imports)] // for quotes extern crate syntax; extern crate rustc; #[macro_use] extern crate lazy_static; #[macro_use] extern crate mac; extern crate string_cache_shared; use rustc::plugin::Registry; mod atom; // NB: This needs to be public or we get a linker error. #[plugin_registrar] pub fn plugin_registrar(reg: &mut Registry) { reg.register_macro("atom", atom::expand_atom); reg.register_macro("ns", atom::expand_ns); }
use derive_more::From; use futures::stream::BoxStream; use iso_country::Country as CountryBase; use serde::{ de::{self, Visitor}, Deserialize, Deserializer, Serialize, Serializer, }; use serde_json::Value; use std::{ collections::{BTreeMap, HashMap}, hash::Hash, net::SocketAddr, ops::Deref, str::FromStr, string::ToString, sync::Arc, time::Duration, }; #[derive(Clone, Debug)] pub struct ServerEntry { pub protocol: TProtocol, pub data: Server, } impl Hash for ServerEntry { fn hash<H: std::hash::Hasher>(&self, state: &mut H) { self.data.addr.hash(state) } } impl PartialEq for ServerEntry { fn eq(&self, other: &ServerEntry) -> bool { self.data.addr == other.data.addr } } impl Eq for ServerEntry {} impl ServerEntry { pub fn new(protocol: TProtocol, data: Server) -> ServerEntry { ServerEntry { protocol, data } } pub fn into_inner(self) -> (TProtocol, Server) { (self.protocol, self.data) } } pub type Config = HashMap<String, Value>; #[derive(Clone, Debug)] pub struct Packet { pub addr: SocketAddr, pub data: Vec<u8>, } #[derive(Clone, Debug, PartialEq, Eq)] pub struct StringAddr { pub host: String, pub port: u16, } #[derive(Clone, Debug, PartialEq, Eq)] pub enum Host { A(SocketAddr), S(StringAddr), } impl From<SocketAddr> for Host { fn from(addr: SocketAddr) -> Self { Host::A(addr) } } impl<S> From<(S, u16)> for Host where S: ToString, { fn from((host, port): (S, u16)) -> Self { Host::S(StringAddr { host: host.to_string(), port, }) } } #[derive(Clone, Debug)] pub struct UserQuery { pub protocol: TProtocol, pub host: Host, } #[allow(clippy::vtable_address_comparisons)] impl PartialEq for UserQuery { fn eq(&self, other: &Self) -> bool { self.host == other.host && Arc::ptr_eq(&self.protocol, &other.protocol) } } #[derive(Clone, Debug)] pub struct Query { pub protocol: TProtocol, pub host: Host, pub state: Option<Value>, } impl From<UserQuery> for Query { fn from(v: UserQuery) -> Self { Self { protocol: v.protocol, host: v.host, state: None, } } } impl From<Query> for UserQuery { fn from(v: Query) -> Self { Self { protocol: v.protocol, host: v.host, } } } #[derive(Clone, Debug, PartialEq)] pub struct ServerResponse { pub host: Host, pub protocol: TProtocol, pub data: Vec<u8>, } #[derive(Clone, Debug, PartialEq)] pub enum FollowUpQueryProtocol { This, Child(TProtocol), } #[derive(Clone, Debug, PartialEq)] pub struct FollowUpQuery { pub host: Host, pub state: Option<Value>, pub protocol: FollowUpQueryProtocol, } impl From<(FollowUpQuery, TProtocol)> for Query { fn from(v: (FollowUpQuery, TProtocol)) -> Query { Query { host: v.0.host, protocol: match v.0.protocol { FollowUpQueryProtocol::This => v.1, FollowUpQueryProtocol::Child(p) => p, }, state: v.0.state, } } } #[derive(Clone, Debug, PartialEq)] pub enum ParseResult { FollowUp(FollowUpQuery), Output(Server), } pub type ProtocolResultStream = BoxStream<'static, Result<ParseResult, (Option<Packet>, anyhow::Error)>>; /// Protocol defines a common way to communicate with queried servers of a single type. pub trait Protocol: std::fmt::Debug + Send + Sync + 'static { /// Creates a request packet. Can accept an optional state if there is any. fn make_request(&self, state: Option<Value>) -> Vec<u8>; /// Create a stream of parsed values out of incoming response. fn parse_response(&self, p: Packet) -> ProtocolResultStream; } #[derive(Clone, Debug)] pub struct TProtocol { inner: Arc<dyn Protocol>, } impl Deref for TProtocol { type Target = Arc<dyn Protocol>; fn deref(&self) -> &Self::Target { &self.inner } } #[allow(clippy::vtable_address_comparisons)] impl PartialEq for TProtocol { fn eq(&self, other: &TProtocol) -> bool { Arc::ptr_eq(self, other) } } impl<T> From<T> for TProtocol where T: Protocol, { fn from(v: T) -> Self { Self { inner: Arc::new(v) as Arc<dyn Protocol>, } } } pub type ProtocolConfig = std::collections::HashMap<String, TProtocol>; #[derive(Clone, Debug, PartialEq, Eq, From)] pub struct Country(pub CountryBase); impl Default for Country { fn default() -> Country { Country(CountryBase::Unspecified) } } impl Serialize for Country { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { serializer.serialize_str(self.0.to_string().as_str()) } } impl<'de> Deserialize<'de> for Country { fn deserialize<D>(deserializer: D) -> Result<Country, D::Error> where D: Deserializer<'de>, { struct CountryVisitor; impl<'de> Visitor<'de> for CountryVisitor { type Value = Country; fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { formatter.write_str("ISO country code") } fn visit_str<E>(self, value: &str) -> Result<Country, E> where E: de::Error, { Ok(Country( CountryBase::from_str(value).unwrap_or(CountryBase::Unspecified), )) } } deserializer.deserialize_str(CountryVisitor) } } #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] pub enum Status { #[default] Unspecified, Up, Down, } #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] pub struct Player { pub name: String, pub ping: Option<i64>, pub info: serde_json::Map<String, Value>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Server { // Mandatory parameters pub addr: std::net::SocketAddr, #[serde(default)] pub status: Status, #[serde(default)] pub country: Country, #[serde(default)] pub rules: BTreeMap<String, Value>, // Optional fields #[serde(skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] pub need_pass: Option<bool>, #[serde(skip_serializing_if = "Option::is_none")] pub mod_name: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] pub game_type: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] pub map: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] pub num_clients: Option<u64>, #[serde(skip_serializing_if = "Option::is_none")] pub max_clients: Option<u64>, #[serde(skip_serializing_if = "Option::is_none")] pub num_bots: Option<u64>, #[serde(skip_serializing_if = "Option::is_none")] pub secure: Option<bool>, #[serde(skip_serializing_if = "Option::is_none")] pub ping: Option<Duration>, #[serde(skip_serializing_if = "Option::is_none")] pub players: Option<Vec<Player>>, } impl Server { pub fn new(addr: SocketAddr) -> Server { Server { addr, status: Default::default(), country: Default::default(), rules: Default::default(), name: Default::default(), need_pass: Default::default(), mod_name: Default::default(), game_type: Default::default(), map: Default::default(), num_clients: Default::default(), max_clients: Default::default(), num_bots: Default::default(), secure: Default::default(), ping: Default::default(), players: Default::default(), } } } #[cfg(test)] mod tests { use super::*; use serde_json::json; fn fixtures() -> (Value, Server) { let mut srv = Server::new(std::net::SocketAddr::from_str("127.0.0.1:9000").unwrap()); srv.status = Status::Up; srv.country = Country(CountryBase::RU); srv.rules.insert("protocol-version".into(), 84.into()); let ser = json!({ "addr": "127.0.0.1:9000", "status": "Up", "country": "RU", "rules": { "protocol-version": 84, }, }); (ser, srv) } #[test] fn serialization() { let (expectation, fixture) = fixtures(); let result = serde_json::to_value(fixture).unwrap(); assert_eq!(expectation, result); } #[test] fn deserialization() { let (fixture, expectation) = fixtures(); let result = serde_json::from_value(fixture).unwrap(); assert_eq!(expectation, result); } }