text
stringlengths
8
4.13M
pub mod lru_list; pub mod object_id; pub const fn align_up(val: usize, align: usize) -> usize { (val + align - 1) / align * align } pub const fn align_down(val: usize, align: usize) -> usize { val / align * align }
use std::sync::Arc; use crossbeam_channel::Receiver; use ring::aead::{Aad, LessSafeKey, Nonce, UnboundKey, CHACHA20_POLY1305}; use zerocopy::{AsBytes, LayoutVerified}; use super::constants::MAX_INORDER_CONSUME; use super::device::Device; use super::messages::{TransportHeader, TYPE_TRANSPORT}; use super::peer::Peer; use super::pool::*; use super::types::Callbacks; use super::KeyPair; use super::{tun, udp, Endpoint}; use super::{REJECT_AFTER_MESSAGES, SIZE_TAG}; pub struct Outbound { msg: Vec<u8>, keypair: Arc<KeyPair>, counter: u64, } impl Outbound { pub fn new(msg: Vec<u8>, keypair: Arc<KeyPair>, counter: u64) -> Outbound { Outbound { msg, keypair, counter, } } } #[inline(always)] pub fn parallel<E: Endpoint, C: Callbacks, T: tun::Writer, B: udp::Writer<E>>( device: Device<E, C, T, B>, receiver: Receiver<Job<Peer<E, C, T, B>, Outbound>>, ) { #[inline(always)] fn work<E: Endpoint, C: Callbacks, T: tun::Writer, B: udp::Writer<E>>( _peer: &Peer<E, C, T, B>, body: &mut Outbound, ) { log::trace!("worker, parallel section, obtained job"); // make space for the tag body.msg.extend([0u8; SIZE_TAG].iter()); // cast to header (should never fail) let (mut header, packet): (LayoutVerified<&mut [u8], TransportHeader>, &mut [u8]) = LayoutVerified::new_from_prefix(&mut body.msg[..]) .expect("earlier code should ensure that there is ample space"); // set header fields debug_assert!( body.counter < REJECT_AFTER_MESSAGES, "should be checked when assigning counters" ); header.f_type.set(TYPE_TRANSPORT); header.f_receiver.set(body.keypair.send.id); header.f_counter.set(body.counter); // create a nonce object let mut nonce = [0u8; 12]; debug_assert_eq!(nonce.len(), CHACHA20_POLY1305.nonce_len()); nonce[4..].copy_from_slice(header.f_counter.as_bytes()); let nonce = Nonce::assume_unique_for_key(nonce); // do the weird ring AEAD dance let key = LessSafeKey::new( UnboundKey::new(&CHACHA20_POLY1305, &body.keypair.send.key[..]).unwrap(), ); // encrypt content of transport message in-place let end = packet.len() - SIZE_TAG; let tag = key .seal_in_place_separate_tag(nonce, Aad::empty(), &mut packet[..end]) .unwrap(); // append tag packet[end..].copy_from_slice(tag.as_ref()); } worker_parallel(device, |dev| &dev.run_outbound, receiver, work); } #[inline(always)] pub fn sequential<E: Endpoint, C: Callbacks, T: tun::Writer, B: udp::Writer<E>>( device: Device<E, C, T, B>, ) { device.run_outbound.run(|peer| { peer.outbound.handle( |body| { log::trace!("worker, sequential section, obtained job"); // send to peer let xmit = peer.send(&body.msg[..]).is_ok(); // trigger callback C::send( &peer.opaque, body.msg.len(), xmit, &body.keypair, body.counter, ); }, MAX_INORDER_CONSUME, ) }); }
use std::env; use std::ffi::OsStr; use std::time::{Duration, SystemTime}; use libc::{ENOENT, ENOSYS}; use fuse::{FileType, FileAttr, Filesystem, Request}; use fuse::{ReplyData, ReplyEntry, ReplyAttr, ReplyDirectory}; use fuse::{ReplyWrite, ReplyOpen, ReplyEmpty, ReplyXattr}; mod hello_inode; use hello_inode::{INVALID_INO, INVALID_BLOCK_ID}; mod hello_block_info; use hello_block_info::{BlockInfo, INVALID_FH}; mod hello_blocks; const TTL: Duration = Duration::from_secs(1); // 1 second const HELLO_DATA: [u8; 18] = [ 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x77, 0x6f, 0x72, 0x6c, 0x64, 0x0a]; const HELLO_DIR_INO: u64 = 1; struct HelloFS { // inode相当 pub dir_inode: FileAttr, pub file_inode: Vec::<FileAttr>, // Directory Infomation 相当 pub block_infos: Vec::<BlockInfo>, // block pub fs_size: i32, } impl Filesystem for HelloFS { fn lookup(&mut self, _req: &Request, _parent: u64, name: &OsStr, reply: ReplyEntry) { println!("[D] -- lookup --"); let node_idx = self.nid_get_from_name(name); if node_idx != INVALID_INO { reply.entry(&TTL, &(self.file_inode[node_idx]), 0); } else { reply.error(ENOENT); } } fn getattr(&mut self, _req: &Request, ino: u64, reply: ReplyAttr) { println!("[D] -- getattr for {} --", ino); if ino == HELLO_DIR_INO { reply.attr(&TTL, &(self.dir_inode)); } else { let node_idx = hello_inode::exists_ino(&self.file_inode, ino); if node_idx != INVALID_INO { reply.attr(&TTL, &(self.file_inode[node_idx])); } else { reply.error(ENOENT); } } } fn read(&mut self, _req: &Request, ino: u64, _fh: u64, offset: i64, size: u32, reply: ReplyData) { println!("[D] -- read [ino: {}]--", ino); if ino >= 2 && offset >= 0 { let info_idx = hello_inode::info_idx_get(&self.file_inode, ino); println!("[D] < {} of {}", info_idx, ino); reply.data(self.block_infos[info_idx].bbox.read(offset, size)); } else { reply.error(ENOENT); } } fn mknod(&mut self, _req: &Request<'_>, parent: u64, name: &OsStr, mode: u32, rdev: u32, reply: ReplyEntry) { let fname = name.to_str().unwrap(); println!("[D] -- mknod --"); println!("[D] parent: {}\n name: {}\n mode: {}\n rdev: {}", parent, fname, mode, rdev); let ret = self.mknod_impl(1, fname, 0, 0); if ret.0 != HELLO_DIR_INO { reply.entry(&TTL, &(self.file_inode[ret.1]), 0); } else { reply.error(ENOENT); } } fn readdir(&mut self, _req: &Request, ino: u64, _fh: u64, offset: i64, mut reply: ReplyDirectory) { println!("[D] -- readdir [ino: {}] --", ino); if ino != 1 { reply.error(ENOENT); return; } let mut entries = vec![ (1, FileType::Directory, "."), (1, FileType::Directory, ".."), //(2, FileType::RegularFile, "hello.txt"), ]; hello_block_info::readdir(&mut entries, &(self.block_infos)); //println!("{:?}", entries2); for (i, entry) in entries.into_iter().enumerate().skip(offset as usize) { // i + 1 means the index of the next entry reply.add(entry.0, (i + 1) as i64, entry.1, entry.2); } reply.ok(); } fn open(&mut self, _req: &Request<'_>, ino: u64, flags: u32, reply: ReplyOpen) { println!("[D] -- open [ino: {} / flag: {}] --", ino, flags); let info_idx = hello_inode::info_idx_get(&self.file_inode, ino); let fh = self.block_infos[info_idx].open(flags); if fh == INVALID_FH { reply.error(libc::EBUSY); } else { reply.opened(fh as u64, 0); } } // なくても良い fn flush(&mut self, _req: &Request<'_>, ino: u64, _fh: u64, _lock_owner: u64, reply: ReplyEmpty) { println!("[D] -- flush [ino: {}] ---", ino); reply.ok(); } // なくても良い(でもファイルハンドラーの制御をするなら必要) fn release(&mut self, _req: &Request<'_>, ino: u64, fh: u64, _flags: u32, _lock_owner: u64, _flush: bool, reply: ReplyEmpty) { println!("[D] -- release [ino: {}] --", ino); let info_idx = hello_inode::info_idx_get(&self.file_inode, ino); self.block_infos[info_idx].close(fh); reply.ok(); } fn write(&mut self, _req: &Request<'_>, ino: u64, _fh: u64, offset: i64, data: &[u8], _flags: u32, reply: ReplyWrite) { println!("[D] -- write [ino: {}] --", ino); println!("[D] offset = {}", offset); if ino >= 2 && offset >= 0 { let node_idx = hello_inode::exists_ino(&self.file_inode, ino); let info_idx = (self.file_inode[node_idx].blocks) as usize; debug_assert!(info_idx != INVALID_BLOCK_ID, "ino={} is invalid !?", ino); let fsize = self.write_impl(info_idx, node_idx, offset, data); reply.written(fsize); } else { reply.error(ENOSYS); } } // なくても良い fn getxattr(&mut self, _req: &Request<'_>, _ino: u64, _name: &OsStr, _size: u32, reply: ReplyXattr) { println!("[D] -- getxattr (not support) ---"); reply.error(ENOSYS); } fn setattr(&mut self, _req: &Request<'_>, ino: u64, _mode: Option<u32>, _uid: Option<u32>, _gid: Option<u32>, _size: Option<u64>, _atime: Option<SystemTime>, _mtime: Option<SystemTime>, _fh: Option<u64>, _crtime: Option<SystemTime>, _chgtime: Option<SystemTime>, _bkuptime: Option<SystemTime>, _flags: Option<u32>, reply: ReplyAttr) { println!("[D] -- setattr [ino: {}] --", ino); let node_idx = hello_inode::exists_ino(&self.file_inode, ino); reply.attr(&TTL, &(self.file_inode[node_idx])); } fn unlink(&mut self, _req: &Request<'_>, _parent: u64, name: &OsStr, reply: ReplyEmpty) { println!("[D] -- unlink ---"); let node_idx = self.nid_get_from_name(name); let info_idx = (self.file_inode[node_idx].blocks) as usize; let block_num = self.block_infos.len(); let is_end_block = {info_idx == block_num-1}; let rm_size = self.block_infos[info_idx].size(); self.file_inode.remove(node_idx); self.block_infos.swap_remove(info_idx); // update block ID if block_num > 1 && !is_end_block { let ino = self.block_infos[info_idx].ino; let node_idx = hello_inode::exists_ino(&self.file_inode, ino); self.file_inode[node_idx].blocks = info_idx as u64; self.file_inode[node_idx].size = self.block_infos[info_idx].size() as u64; } self.fs_size_update(-(rm_size as i32)); reply.ok(); } } impl HelloFS { fn nid_get_from_name(&self, name: &OsStr) -> usize { //println!("[D] < {}", name.to_str().unwrap()); let fname = String::from(name.to_str().unwrap()); let ino = hello_block_info::lookup(&self.block_infos, fname); hello_inode::exists_ino(&self.file_inode, ino) } fn mknod_impl(&mut self, parent: u64, name: &str, _mode: u32, _rdev: u32) -> (u64, usize) { if parent != HELLO_DIR_INO { return (HELLO_DIR_INO, 0) } let next_info = hello_inode::next_ino(&self.file_inode); let ino: u64 = *next_info.get("ino").unwrap() as u64; println!("new ino = {}", ino); let fname: String = String::from(name); self.block_infos.push(hello_block_info::create(fname, ino)); let info_idx = self.block_infos.len() - 1; self.file_inode.push(hello_inode::inode_data_create(ino, 1, info_idx)); self.fs_size_update(self.block_infos[info_idx].size() as i32); (ino, info_idx) } fn fs_size_update(&mut self, size: i32) { self.fs_size += size; } fn write_impl(&mut self, info_idx: usize, node_idx: usize, offset: i64, data: &[u8]) -> u32 { let ret = self.block_infos[info_idx].bbox.write(self.fs_size, data, offset); debug_assert!(true == ret.0, "write failed"); self.fs_size_update(ret.1); self.file_inode[node_idx].size = ret.2 as u64; ret.2 } } fn main() { //env_logger::init(); let mountpoint = env::args_os().nth(1).unwrap(); //let options = ["-o", "ro", "-o", "fsname=hello"] let options = ["-o", "fsname=hello"] .iter() .map(|o| o.as_ref()) .collect::<Vec<&OsStr>>(); let first_ino :u64 = HELLO_DIR_INO + 1; let first_info_idx :usize = 0; let first_node_idx :usize = 0; let mut hello_fs = HelloFS { dir_inode: hello_inode::dir_attr_get(), file_inode: vec![hello_inode::inode_data_create(first_ino, 1, first_info_idx)], block_infos: vec![hello_block_info::create(String::from("hello.txt"), first_ino)], fs_size: 0, }; hello_fs.fs_size_update(hello_fs.block_infos[first_info_idx].size() as i32); let written_size = hello_fs.write_impl(first_info_idx, first_node_idx, 0, &HELLO_DATA); hello_fs.file_inode[first_node_idx].size = written_size as u64; fuse::mount(hello_fs, mountpoint, &options).unwrap(); }
// 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::string::String; use alloc::string::ToString; use super::super::kernel::time::*; use super::super::qlib::linux::time::*; use super::super::task::*; use super::super::qlib::auth::*; use super::super::qlib::auth::id::*; use super::super::qlib::auth::cap_set::*; use super::super::util::cstring::*; use super::super::qlib::range::*; use super::super::qlib::common::*; use super::super::qlib::linux_def::*; use super::super::qlib::path::*; use super::super::qlib::linux::fcntl::*; use super::super::fs::dirent::*; use super::super::fs::file::*; use super::super::fs::flags::*; use super::super::fs::inode::*; use super::super::fs::lock::*; use super::super::kernel::fd_table::*; use super::super::kernel::fasync::*; use super::super::kernel::pipe::reader::*; use super::super::kernel::pipe::writer::*; use super::super::kernel::pipe::reader_writer::*; use super::super::syscalls::syscalls::*; use super::super::perflog::*; fn fileOpAt(task: &Task, dirFd: i32, path: &str, func: &mut FnMut(&Dirent, &Dirent, &str, u32) -> Result<()>) -> Result<()> { let (dir, name) = SplitLast(path); if dir == "/" { return func(&task.Root(), &task.Root(), &name.to_string(), MAX_SYMLINK_TRAVERSALS); } else if dir == "." && dirFd == AT_FDCWD { return func(&task.Root(), &task.Workdir(), &name.to_string(), MAX_SYMLINK_TRAVERSALS); } return fileOpOn(task, dirFd, &dir.to_string(), true, &mut |root: &Dirent, d: &Dirent, remainingTraversals: u32| -> Result<()> { return func(root, d, &name.to_string(), remainingTraversals) }); } pub fn fileOpOn(task: &Task, dirFd: i32, path: &str, resolve: bool, func: &mut FnMut(&Dirent, &Dirent, u32) -> Result<()>) -> Result<()> { let d: Dirent; let wd: Dirent; let mut rel: Option<Dirent> = None; if path.len() > 0 && path.as_bytes()[0] == '/' as u8 { // Absolute path; rel can be nil. } else if dirFd == ATType::AT_FDCWD { wd = task.Workdir(); rel = Some(wd.clone()); } else { let file = task.GetFile(dirFd)?; let dirent = file.Dirent.clone(); let inode = dirent.Inode(); if !inode.StableAttr().IsDir() { return Err(Error::SysError(SysErr::ENOTDIR)); } rel = Some(file.Dirent.clone()); } let root = task.Root(); let mut remainTraversals = MAX_SYMLINK_TRAVERSALS; if resolve { d = task.mountNS.FindInode(task, &root, rel, path, &mut remainTraversals)?; } else { d = task.mountNS.FindLink(task, &root, rel, path, &mut remainTraversals)? } return func(&root, &d, remainTraversals) } //return (path, whether it is dir) pub fn copyInPath(task: &Task, addr: u64, allowEmpty: bool) -> Result<(String, bool)> { let str = CString::ToString(task, addr)?; if &str == "" && !allowEmpty { return Err(Error::SysError(SysErr::ENOENT)) } let (path, dirPath) = TrimTrailingSlashes(&str); return Ok((path.to_string(), dirPath)) } pub fn SysOpenAt(task: &mut Task, args: &SyscallArguments) -> Result<i64> { let dirFd = args.arg0 as i32; let addr = args.arg1 as u64; let flags = args.arg2 as u32; let mode = args.arg3 as u16 as u32; if flags & Flags::O_CREAT as u32 != 0 { let res = createAt(task, dirFd, addr, flags, FileMode(mode as u16))?; return Ok(res as i64) } let res = openAt(task, dirFd, addr, flags)?; return Ok(res as i64) } pub fn SysOpen(task: &mut Task, args: &SyscallArguments) -> Result<i64> { let addr = args.arg0 as u64; let flags = args.arg1 as u32; let mode = args.arg2 as u16 as u32; if flags & Flags::O_CREAT as u32 != 0 { let res = createAt(task, ATType::AT_FDCWD, addr, flags, FileMode(mode as u16))?; return Ok(res as i64) } let res = openAt(task, ATType::AT_FDCWD, addr, flags)?; return Ok(res as i64) } pub fn SysCreate(task: &mut Task, args: &SyscallArguments) -> Result<i64> { let addr = args.arg0 as u64; let mode = args.arg1 as u16 as u32; let res = createAt(task, ATType::AT_FDCWD, addr, (Flags::O_WRONLY | Flags::O_TRUNC) as u32, FileMode(mode as u16))?; return Ok(res as i64) } pub fn openAt(task: &Task, dirFd: i32, addr: u64, flags: u32) -> Result<i32> { task.PerfGoto(PerfType::Open); defer!(task.PerfGofrom(PerfType::Open)); let (path, dirPath) = copyInPath(task, addr, false)?; info!("openat path is {}, the perm is {:?}, , current is {}", &path, &PermMask::FromFlags(flags), task.fsContext.WorkDirectory().MyFullName()); let resolve = (flags & Flags::O_NOFOLLOW as u32) == 0; let mut fd = -1; fileOpOn(task, dirFd, &path, resolve, &mut |_root: &Dirent, d: &Dirent, _remainingTraversals: u32| -> Result<()> { let mut inode = d.Inode(); inode.CheckPermission(task, &PermMask::FromFlags(flags))?; if inode.StableAttr().IsSymlink() && !resolve { return Err(Error::SysError(SysErr::ELOOP)) } let mut fileFlags = FileFlags::FromFlags(flags); fileFlags.LargeFile = true; if inode.StableAttr().IsDir() { if fileFlags.Write { return Err(Error::SysError(SysErr::EISDIR)) } } else { if fileFlags.Directory { return Err(Error::SysError(SysErr::ENOTDIR)) } if dirPath { return Err(Error::SysError(SysErr::ENOTDIR)) } } if inode.StableAttr().IsSocket() { if !fileFlags.Path { return Err(Error::SysError(SysErr::ENXIO)) } else if fileFlags.Read || fileFlags.Write { return Err(Error::SysError(SysErr::ENXIO)) } } if flags & Flags::O_TRUNC as u32 != 0 { if inode.StableAttr().IsDir() { return Err(Error::SysError(SysErr::EISDIR)) } inode.Truncate(task, d, 0)?; } let file = match inode.GetFile(task, &d, &fileFlags) { Err(err) => return Err(ConvertIntr(err, Error::ERESTARTSYS)), Ok(f) => f, }; let newFd = task.NewFDFrom(0, &file, &FDFlags { CloseOnExec: flags & Flags::O_CLOEXEC as u32 != 0 })?; fd = newFd; return Ok(()) })?; return Ok(fd) } // Mknod implements the linux syscall mknod(2). pub fn SysMknode(task: &mut Task, args: &SyscallArguments) -> Result<i64> { let path = args.arg0 as u64; let mode = args.arg1 as u16; // We don't need this argument until we support creation of device nodes. //let _dev = args.arg2 as u16 as u32; mknodeAt(task, ATType::AT_FDCWD, path, FileMode(mode))?; return Ok(0) } // Mknodat implements the linux syscall mknodat(2). pub fn SysMknodeat(task: &mut Task, args: &SyscallArguments) -> Result<i64> { let dirFD = args.arg0 as i32; let path = args.arg1 as u64; let mode = args.arg2 as u16; // We don't need this argument until we support creation of device nodes. //let _dev = args.arg3 as u16 as u32; mknodeAt(task, dirFD, path, FileMode(mode))?; return Ok(0) } pub fn mknodeAt(task: &Task, dirFd: i32, addr: u64, mode: FileMode) -> Result<()> { let (path, dirPath) = copyInPath(task, addr, false)?; if dirPath { return Err(Error::SysError(SysErr::ENOENT)) } return fileOpAt(task, dirFd, &path, &mut |root: &Dirent, d: &Dirent, name: &str, _remainingTraversals: u32| -> Result<()> { let inode = d.Inode(); inode.CheckPermission(task, &PermMask { write: true, execute: true, ..Default::default() })?; let perms = FilePermissions::FromMode(FileMode(mode.0 & !task.Umask() as u16)); match mode.FileType().0 { 0 | ModeType::MODE_REGULAR => { let flags = FileFlags { Read: true, Write: true, ..Default::default() }; let _file = d.Create(task, root, name, &flags, &perms)?; return Ok(()) } ModeType::MODE_NAMED_PIPE => { return d.CreateFifo(task, root, name, &perms); } ModeType::MODE_SOCKET => { return Err(Error::SysError(SysErr::EOPNOTSUPP)) } ModeType::MODE_CHARACTER_DEVICE | ModeType::MODE_BLOCK_DEVICE => { return Err(Error::SysError(SysErr::EPERM)) } _ => return Err(Error::SysError(SysErr::EINVAL)) } }) } pub fn createAt(task: &Task, dirFd: i32, addr: u64, flags: u32, mode: FileMode) -> Result<i32> { let (path, dirPath) = copyInPath(task, addr, false)?; info!("createAt path is {}, current is {}", &path, task.fsContext.WorkDirectory().MyFullName()); if dirPath { return Err(Error::SysError(SysErr::EISDIR)) } let mut fileFlags = FileFlags::FromFlags(flags); fileFlags.LargeFile = true; let mut fd = 0; let mnt = task.mountNS.clone(); fileOpAt(task, dirFd, &path, &mut |root: &Dirent, parent: &Dirent, name: &str, remainingTraversals: u32| -> Result<()> { let mut found = parent.clone(); let mut remainingTraversals = remainingTraversals; let mut parent = parent.clone(); let mut name = name.to_string(); let mut err = Error::None; loop { let parentInode = parent.Inode(); if !parentInode.StableAttr().IsDir() { return Err(Error::SysError(SysErr::ENOTDIR)) } found = match mnt.FindLink(task, root, Some(parent.clone()), &name, &mut remainingTraversals) { Ok(d) => d, Err(e) => { err = e; break } }; if flags & Flags::O_EXCL as u32 != 0 { return Err(Error::SysError(SysErr::EEXIST)) } let foundInode = found.Inode(); if foundInode.StableAttr().IsDir() && fileFlags.Write { return Err(Error::SysError(SysErr::EISDIR)) } if !foundInode.StableAttr().IsSymlink() { break; } if flags & Flags::O_NOFOLLOW as u32 != 0 { return Err(Error::SysError(SysErr::ELOOP)) } match foundInode.GetLink(task) { Err(Error::ErrResolveViaReadlink) => (), Err(e) => return Err(e), Ok(_) => { break } }; if remainingTraversals == 0 { return Err(Error::SysError(SysErr::ELOOP)) } let path = match foundInode.ReadLink(task) { Err(e) => { err = e; break } Ok(p) => p, }; remainingTraversals -= 1; let (newParentPath, newName) = SplitLast(&path); let newParent = match mnt.FindInode(task, root, Some(parent.clone()), &newParentPath.to_string(), &mut remainingTraversals) { Err(e) => { err = e; break } Ok(p) => p, }; parent = newParent; name = newName.to_string(); } let newFile = match err { Error::None => { let mut foundInode = found.Inode(); if flags & Flags::O_TRUNC as u32 != 0 { if foundInode.StableAttr().IsDir() { return Err(Error::SysError(SysErr::EISDIR)) } foundInode.Truncate(task, &found, 0)?; } let inode = found.Inode(); let newFile = match inode.GetFile(task, &found, &fileFlags) { Err(e) => { return Err(ConvertIntr(e, Error::SysError(SysErr::ERESTARTSYS))) }, Ok(f) => { f }, }; newFile } Error::SysError(SysErr::ENOENT) | //todo: this is a workaround, we can only get EPERM failure instead of ENOENT, fix this later Error::SysError(SysErr::EPERM) => { // File does not exist. Proceed with creation. // Do we have write permissions on the parent? let parentInode = parent.Inode(); parentInode.CheckPermission(task, &PermMask { write: true, execute: true, ..Default::default() })?; let perms = FilePermissions::FromMode(FileMode(mode.0 & !task.Umask() as u16)); let newFile = parent.Create(task, root, &name, &fileFlags, &perms)?; //found = newFile.lock().Dirent.clone()(); newFile } e => return Err(e) }; let newFd = task.NewFDFrom(0, &newFile, &FDFlags { CloseOnExec: flags & Flags::O_CLOEXEC as u32 != 0, })?; fd = newFd; // Queue the open inotify event. The creation event is // automatically queued when the dirent is found. The open // events are implemented at the syscall layer so we need to // manually queue one here. //found.InotifyEvent(linux.IN_OPEN, 0) return Ok(()) })?; return Ok(fd) } pub fn SysAccess(task: &mut Task, args: &SyscallArguments) -> Result<i64> { let pathName = args.arg0 as u64; let mode = args.arg1 as u32; accessAt(task, ATType::AT_FDCWD, pathName, true, mode)?; return Ok(0); } pub fn SysFaccessat(task: &mut Task, args: &SyscallArguments) -> Result<i64> { let dirfd = args.arg0 as i32; let addr = args.arg1 as u64; let mode = args.arg2 as u16 as u32; let flags = args.arg3 as i32; accessAt(task, dirfd, addr, flags & ATType::AT_SYMLINK_NOFOLLOW == 0, mode)?; return Ok(0) } pub fn accessAt(task: &Task, dirFd: i32, addr: u64, resolve: bool, mode: u32) -> Result<()> { const R_OK: u32 = 4; const W_OK: u32 = 2; const X_OK: u32 = 1; let (path, _) = copyInPath(task, addr, false)?; info!("accessAt dirfd is {}, path is {}", dirFd, &path); if mode & !(R_OK | W_OK | X_OK) != 0 { return Err(Error::SysError(SysErr::EINVAL)) } return fileOpOn(task, dirFd, &path.to_string(), resolve, &mut |_root: &Dirent, d: &Dirent, _remainingTraversals: u32| -> Result<()> { { let creds = task.Creds().Fork(); let mut creds = creds.lock(); creds.EffectiveKUID = creds.RealKUID; creds.EffectiveKGID = creds.RealKGID; if creds.EffectiveKGID.In(&creds.UserNamespace).0 == ROOT_UID.0 { creds.EffectiveCaps = creds.PermittedCaps } else { creds.EffectiveCaps = CapSet::New(0) } } let inode = d.Inode(); return inode.CheckPermission(task, &PermMask { read: mode & R_OK != 0, write: mode & W_OK != 0, execute: mode & X_OK != 0, }) }) } pub fn SysIoctl(task: &mut Task, args: &SyscallArguments) -> Result<i64> { let fd = args.arg0 as i32; let request = args.arg1 as u64; let val = args.arg2 as u64; Ioctl(task, fd, request, val)?; return Ok(0) } pub fn Ioctl(task: &mut Task, fd: i32, request: u64, val: u64) -> Result<()> { let file = task.GetFile(fd)?; //let fops = file.FileOp.clone(); //let inode = file.Dirent.Inode(); //error!("Ioctl inodetype is {:?}, fopstype is {:?}", inode.InodeType(), fops.FopsType()); match request { IoCtlCmd::FIONCLEX => { task.SetFlags(fd, &FDFlags { CloseOnExec: false, })?; return Ok(()) } IoCtlCmd::FIOCLEX => { task.SetFlags(fd, &FDFlags { CloseOnExec: true, })?; return Ok(()) } IoCtlCmd::FIONBIO => { let set: u32 = task.CopyInObj(val)?; let mut flags = file.Flags(); if set != 0 { flags.NonBlocking = true; } else { flags.NonBlocking = false; } file.SetFlags(task, flags.SettableFileFlags()); return Ok(()) } IoCtlCmd::FIOASYNC => { let set: u32 = task.CopyInObj(val)?; let mut flags = file.Flags(); if set != 0 { flags.Async = true; } else { flags.Async = false; } file.SetFlags(task, flags.SettableFileFlags()); return Ok(()) } IoCtlCmd::FIOSETOWN | IoCtlCmd::SIOCSPGRP => { let set : i32 = task.CopyInObj(val)?; FSetOwner(task, &file, set)?; return Ok(()) } IoCtlCmd::FIOGETOWN | IoCtlCmd::SIOCGPGRP => { let who = FGetOwn(task, &file); //*task.GetTypeMut(val)? = who; task.CopyOutObj(&who, val)?; return Ok(()) } _ => { return file.Ioctl(task, fd, request, val) } } } pub fn SysGetcwd(task: &mut Task, args: &SyscallArguments) -> Result<i64> { let addr = args.arg0 as u64; let size = args.arg1 as usize; let cwd = task.Workdir(); let root = task.Root(); let (mut s, reachable) = cwd.FullName(&root); if !reachable { s = "(unreachable)".to_string() + &s } if s.len() >= size { return Err(Error::SysError(SysErr::ERANGE)) } let len = if s.len() + 1 > size { size } else { s.len() + 1 }; task.CopyOutString(addr, len, &s)?; return Ok(len as i64) } pub fn SysChroot(task: &mut Task, args: &SyscallArguments) -> Result<i64> { let addr = args.arg0 as u64; if task.Creds().HasCapability(Capability::CAP_SYS_CHROOT) { return Err(Error::SysError(SysErr::EPERM)) } let (path, _) = copyInPath(task, addr, false)?; let mut dir = task.Root(); let res = fileOpOn(task, ATType::AT_FDCWD, &path, true, &mut |_root: &Dirent, d: &Dirent, _remainingTraversals: u32| -> Result<()> { let inode = d.Inode(); if !inode.StableAttr().IsDir() { return Err(Error::SysError(SysErr::ENOTDIR)) } inode.CheckPermission(task, &PermMask { execute: true, ..Default::default() })?; dir = d.clone(); Ok(()) }); match res { Err(e) => return Err(e), Ok(_) => { task.fsContext.SetRootDirectory(&dir); return Ok(0) } } } pub fn SysChdir(task: &mut Task, args: &SyscallArguments) -> Result<i64> { let addr = args.arg0 as u64; let (path, _) = copyInPath(task, addr, false)?; info!("SysChdir path is {}", &path); let mut dir = task.Workdir(); let res = fileOpOn(task, ATType::AT_FDCWD, &path, true, &mut |_root: &Dirent, d: &Dirent, _remainingTraversals: u32| -> Result<()> { let inode = d.Inode(); if !inode.StableAttr().IsDir() { return Err(Error::SysError(SysErr::ENOTDIR)) } inode.CheckPermission(task, &PermMask { execute: true, ..Default::default() })?; dir = d.clone(); Ok(()) }); match res { Err(e) => Err(e), Ok(_) => { task.fsContext.SetWorkDirectory(&dir); return Ok(0) } } } pub fn SysFchdir(task: &mut Task, args: &SyscallArguments) -> Result<i64> { let fd = args.arg0 as i32; let file = task.GetFile(fd)?; let dirent = file.Dirent.clone(); info!("SysFchdir dir is {}", dirent.MyFullName()); let inode = dirent.Inode(); if !inode.StableAttr().IsDir() { return Err(Error::SysError(SysErr::ENOTDIR)) } inode.CheckPermission(task, &PermMask { execute: true, ..Default::default() })?; task.fsContext.SetWorkDirectory(&dirent); return Ok(0) } pub fn SysClose(task: &mut Task, args: &SyscallArguments) -> Result<i64> { let fd = args.arg0 as i32; close(task, fd)?; return Ok(0); } pub fn close(task: &Task, fd: i32) -> Result<()> { let file = task.RemoveFile(fd)?; file.Flush(task)?; Ok(()) } pub fn SysDup(task: &mut Task, args: &SyscallArguments) -> Result<i64> { let fd = args.arg0 as i32; let file = task.GetFile(fd)?; let newfd = task.NewFDFrom(0, &file, &FDFlags::default())?; return Ok(newfd as i64) } pub fn SysDup2(task: &mut Task, args: &SyscallArguments) -> Result<i64> { let oldfd = args.arg0 as i32; let newfd = args.arg1 as i32; if oldfd == newfd { let _oldfile = task.GetFile(oldfd)?; return Ok(newfd as i64); } return Dup3(task, oldfd, newfd, 0) } pub fn SysDup3(task: &mut Task, args: &SyscallArguments) -> Result<i64> { let oldfd = args.arg0 as i32; let newfd = args.arg1 as i32; let flags = args.arg2 as u32; if oldfd == newfd { return Err(Error::SysError(SysErr::EINVAL)); } return Dup3(task, oldfd, newfd, flags) } pub fn Dup3(task: &mut Task, oldfd: i32, newfd: i32, flags: u32) -> Result<i64> { let oldFile = task.GetFile(oldfd)?; task.NewFDAt(newfd, &oldFile, &FDFlags { CloseOnExec: flags & Flags::O_CLOEXEC as u32 != 0 })?; return Ok(newfd as i64) } pub fn SysLseek(task: &mut Task, args: &SyscallArguments) -> Result<i64> { let fd = args.arg0 as i32; let offset = args.arg1 as i64; let whence = args.arg2 as i32; let res = Lseek(task, fd, offset, whence)?; return Ok(res as i64) } pub fn Lseek(task: &mut Task, fd: i32, offset: i64, whence: i32) -> Result<i64> { let file = task.GetFile(fd)?; if whence < SeekWhence::SEEK_SET || whence > SeekWhence::SEEK_END { return Err(Error::SysError(SysErr::EINVAL)); } let res = file.Seek(task, whence, offset); return res; } pub fn FGetOwnEx(task: &mut Task, file: &File) -> FOwnerEx { let ma = match file.Async(task, None) { None => return FOwnerEx::default(), Some(a) => a, }; let (ot, otg, opg) = ma.Owner(); match ot { None => (), Some(thread) => { return FOwnerEx { Type: F_OWNER_TID, PID: task.Thread().PIDNamespace().IDOfTask(&thread), } } } match otg { None => (), Some(threadgroup) => { return FOwnerEx { Type: F_OWNER_PID, PID: task.Thread().PIDNamespace().IDOfThreadGroup(&threadgroup), } } } match opg { None => (), Some(processgroup) => { return FOwnerEx { Type: F_OWNER_PGRP, PID: task.Thread().PIDNamespace().IDOfProcessGroup(&processgroup), } } } return FOwnerEx::default(); } pub fn FGetOwn(task: &mut Task, file: &File) -> i32 { let owner = FGetOwnEx(task, file); if owner.Type == F_OWNER_PGRP { return -owner.PID; } return owner.PID; } // fSetOwn sets the file's owner with the semantics of F_SETOWN in Linux. // // If who is positive, it represents a PID. If negative, it represents a PGID. // If the PID or PGID is invalid, the owner is silently unset. pub fn FSetOwner(task: &Task, file: &File, who: i32) -> Result<()> { // F_SETOWN flips the sign of negative values, an operation that is guarded // against overflow. if who == core::i32::MIN { return Err(Error::SysError(SysErr::EINVAL)); } let a = file.Async(task, Some(FileAsync::default())).unwrap(); if who == 0 { a.Unset(task); return Ok(()); } if who < 0 { let pg = task.Thread().PIDNamespace().ProcessGroupWithID(-who); if pg.is_none() { return Err(Error::SysError(SysErr::ESRCH)); } a.SetOwnerProcessGroup(task, pg); return Ok(()) } let tg = task.Thread().PIDNamespace().ThreadGroupWithID(who); if tg.is_none() { return Err(Error::SysError(SysErr::ESRCH)); } a.SetOwnerThreadGroup(task, tg); return Ok(()) } pub fn SysFcntl(task: &mut Task, args: &SyscallArguments) -> Result<i64> { let fd = args.arg0 as i32; let cmd = args.arg1 as i32; let val = args.arg2 as u64; let (file, flags) = task.GetFileAll(fd)?; match cmd { Cmd::F_DUPFD | Cmd::F_DUPFD_CLOEXEC => { let from = val as i32; let fd = task.NewFDFrom(from, &file, &FDFlags { CloseOnExec: cmd == Cmd::F_DUPFD_CLOEXEC })?; return Ok(fd as i64) } Cmd::F_GETFD => { Ok(flags.ToLinuxFDFlags() as i64) } Cmd::F_SETFD => { let flags = val as u32; task.SetFlags(fd, &FDFlags { CloseOnExec: flags & LibcConst::FD_CLOEXEC as u32 != 0 })?; Ok(0) } Cmd::F_GETFL => { Ok(file.Flags().ToLinux() as i64) } Cmd::F_SETFL => { let flags = val as u32; file.SetFlags(task, FileFlags::FromFlags(flags).SettableFileFlags()); Ok(0) } Cmd::F_SETLK | Cmd::F_SETLKW => { let inode = file.Dirent.Inode(); // In Linux the file system can choose to provide lock operations for an inode. // Normally pipe and socket types lack lock operations. We diverge and use a heavy // hammer by only allowing locks on files and directories. //todo: fix this. We can handle if the file is a symbol link fix this if !inode.StableAttr().IsFile() && !inode.StableAttr().IsDir() { return Err(Error::SysError(SysErr::EBADF)) } let flockAddr = val; let flock : FlockStruct = task.CopyInObj(flockAddr)?; let sw = match flock.l_whence { 0 => SeekWhence::SEEK_SET, 1 => SeekWhence::SEEK_CUR, 2 => SeekWhence::SEEK_END, _ => return Err(Error::SysError(SysErr::EINVAL)) }; let offset = match sw { SeekWhence::SEEK_SET => 0, SeekWhence::SEEK_CUR => file.Offset(task)?, SeekWhence::SEEK_END => { let uattr = inode.UnstableAttr(task)?; uattr.Size } _ => return Err(Error::SysError(SysErr::EINVAL)) }; // Compute the lock range. let rng = ComputeRange(flock.l_start, flock.l_len, offset)?; // The lock uid is that of the Task's FDTable. let lockUniqueID = task.fdTbl.ID(); // These locks don't block; execute the non-blocking operation using the inode's lock // context directly. let fflags = file.Flags(); match flock.l_type as u64 { LibcConst::F_RDLCK => { if !fflags.Read { return Err(Error::SysError(SysErr::EBADF)) } let lock = inode.lock().LockCtx.Posix.clone(); if cmd == Cmd::F_SETLK { // Non-blocking lock, provide a nil lock.Blocker. if !lock.LockRegion(task, lockUniqueID, LockType::ReadLock, &rng, false)? { return Err(Error::SysError(SysErr::EAGAIN)) } } else { // Blocking lock, pass in the task to satisfy the lock.Blocker interface. if !lock.LockRegion(task, lockUniqueID, LockType::ReadLock, &rng, true)? { return Err(Error::SysError(SysErr::EINTR)) } } return Ok(0) } LibcConst::F_WRLCK => { if !fflags.Write { return Err(Error::SysError(SysErr::EBADF)) } let lock = inode.lock().LockCtx.Posix.clone(); if cmd == Cmd::F_SETLK { // Non-blocking lock, provide a nil lock.Blocker. if !lock.LockRegion(task, lockUniqueID, LockType::WriteLock, &rng, false)? { return Err(Error::SysError(SysErr::EAGAIN)) } } else { // Blocking lock, pass in the task to satisfy the lock.Blocker interface. if !lock.LockRegion(task, lockUniqueID, LockType::WriteLock, &rng, true)? { return Err(Error::SysError(SysErr::EINTR)) } } return Ok(0) } LibcConst::F_UNLCK => { let lock = inode.lock().LockCtx.Posix.clone(); lock.UnlockRegion(task, lockUniqueID, &rng); return Ok(0) } _ => { return Err(Error::SysError(SysErr::EINVAL)) } } } Cmd::F_GETOWN => { return Ok(FGetOwn(task, &file) as i64) } Cmd::F_SETOWN => { FSetOwner(task, &file, val as i32)?; return Ok(0) } Cmd::F_GETOWN_EX => { let addr = val; let owner = FGetOwnEx(task, &file); //*task.GetTypeMut(addr)? = owner; task.CopyOutObj(&owner, addr)?; return Ok(0) } Cmd::F_SETOWN_EX => { let addr = val; let owner : FOwnerEx = task.CopyInObj(addr)?; let a = file.Async(task, Some(FileAsync::default())).unwrap(); match owner.Type { F_OWNER_TID => { if owner.PID == 0 { a.Unset(task); return Ok(0) } let thread = task.Thread().PIDNamespace().TaskWithID(owner.PID); match thread { None => return Err(Error::SysError(SysErr::ESRCH)), Some(thread) => { a.SetOwnerTask(task, Some(thread)); return Ok(0) } } } F_OWNER_PID => { if owner.PID == 0 { a.Unset(task); return Ok(0) } let tg = task.Thread().PIDNamespace().ThreadGroupWithID(owner.PID); match tg { None => return Err(Error::SysError(SysErr::ESRCH)), Some(tg) => { a.SetOwnerThreadGroup(task, Some(tg)); return Ok(0) } } } F_OWNER_PGRP => { if owner.PID == 0 { a.Unset(task); return Ok(0) } let pg = task.Thread().PIDNamespace().ProcessGroupWithID(owner.PID); match pg { None => return Err(Error::SysError(SysErr::ESRCH)), Some(pg) => { a.SetOwnerProcessGroup(task, Some(pg)); return Ok(0) } } } _ => return Err(Error::SysError(SysErr::EINVAL)) } } Cmd::F_GET_SEALS => { panic!("Fcntl: F_GET_SEALS not implement") } Cmd::F_ADD_SEALS => { panic!("Fcntl: F_ADD_SEALS not implement") } Cmd::F_GETPIPE_SZ => { let fops = file.FileOp.clone(); let pipe = if let Some(ops) = fops.as_any().downcast_ref::<Reader>() { ops.pipe.clone() } else if let Some(ops) = fops.as_any().downcast_ref::<Writer>() { ops.pipe.clone() } else if let Some(ops) = fops.as_any().downcast_ref::<ReaderWriter>() { ops.pipe.clone() } else { return Err(Error::SysError(SysErr::EINVAL)) }; let n = pipe.PipeSize(); return Ok(n as i64) } Cmd::F_SETPIPE_SZ => { let fops = file.FileOp.clone(); let pipe = if let Some(ops) = fops.as_any().downcast_ref::<Reader>() { ops.pipe.clone() } else if let Some(ops) = fops.as_any().downcast_ref::<Writer>() { ops.pipe.clone() } else if let Some(ops) = fops.as_any().downcast_ref::<ReaderWriter>() { ops.pipe.clone() } else { return Err(Error::SysError(SysErr::EINVAL)) }; let n = pipe.SetPipeSize(val as i64)?; return Ok(n as i64) } _ => { return Err(Error::SysError(SysErr::EINVAL)) } } } const _FADV_NORMAL: i32 = 0; const _FADV_RANDOM: i32 = 1; const _FADV_SEQUENTIAL: i32 = 2; const _FADV_WILLNEED: i32 = 3; const _FADV_DONTNEED: i32 = 4; const _FADV_NOREUSE: i32 = 5; pub fn SysFadvise64(task: &mut Task, args: &SyscallArguments) -> Result<i64> { let fd = args.arg0 as i32; let _offset = args.arg1 as i64; let len = args.arg2 as i64; let advice = args.arg3 as i32; if len < 0 { return Err(Error::SysError(SysErr::EINVAL)) } let file = task.GetFile(fd)?; let inode = file.Dirent.Inode(); if inode.StableAttr().IsPipe() { return Err(Error::SysError(SysErr::ESPIPE)) } match advice { _FADV_NORMAL | _FADV_RANDOM | _FADV_SEQUENTIAL | _FADV_WILLNEED | _FADV_DONTNEED | _FADV_NOREUSE => { return Ok(0) } _ => return Err(Error::SysError(SysErr::EINVAL)) } } fn mkdirAt(task: &Task, dirFd: i32, addr: u64, mode: FileMode) -> Result<i64> { let (path, _) = copyInPath(task, addr, false)?; info!("mkdirAt path is {}", &path); fileOpAt(task, dirFd, &path.to_string(), &mut |root: &Dirent, d: &Dirent, name: &str, _remainingTraversals: u32| -> Result<()> { let inode = d.Inode(); if !inode.StableAttr().IsDir() { return Err(Error::SysError(SysErr::ENOTDIR)) } let mut remainingTraversals = MAX_SYMLINK_TRAVERSALS; let res = task.mountNS.FindInode(task, root, Some(d.clone()), name, &mut remainingTraversals); match res { Ok(_) => Err(Error::SysError(SysErr::EEXIST)), Err(Error::SysError(SysErr::EACCES)) => return Err(Error::SysError(SysErr::EACCES)), _ => { let perms = { inode.CheckPermission(task, &PermMask { write: true, execute: true, ..Default::default() })?; FilePermissions::FromMode(FileMode(mode.0 & !task.Umask() as u16)) }; return d.CreateDirectory(task, root, name, &perms) } } })?; return Ok(0) } pub fn SysMkdir(task: &mut Task, args: &SyscallArguments) -> Result<i64> { let addr = args.arg0 as u64; let mode = args.arg1 as u16; return mkdirAt(task, ATType::AT_FDCWD, addr, FileMode(mode)) } pub fn SysMkdirat(task: &mut Task, args: &SyscallArguments) -> Result<i64> { let dirfd = args.arg0 as i32; let addr = args.arg1 as u64; let mode = args.arg2 as u16; return mkdirAt(task, dirfd, addr, FileMode(mode)) } fn rmdirAt(task: &Task, dirFd: i32, addr: u64) -> Result<i64> { let (path, _) = copyInPath(task, addr, false)?; info!("rmdirAt path is {}", &path); if path.as_str() == "/" { return Err(Error::SysError(SysErr::EBUSY)) } fileOpAt(task, dirFd, &path.to_string(), &mut |root: &Dirent, d: &Dirent, name: &str, _remainingTraversals: u32| -> Result<()> { let inode = d.Inode(); if !inode.StableAttr().IsDir() { return Err(Error::SysError(SysErr::ENOTDIR)) } match name { "." => return Err(Error::SysError(SysErr::EINVAL)), ".." => return Err(Error::SysError(SysErr::ENOTEMPTY)), _ => () } d.MayDelete(task, root, name)?; return d.RemoveDirectory(task, root, name) })?; return Ok(0) } pub fn SysRmdir(task: &mut Task, args: &SyscallArguments) -> Result<i64> { let addr = args.arg0 as u64; return rmdirAt(task, ATType::AT_FDCWD, addr) } fn symlinkAt(task: &Task, newAddr: u64, dirFd: i32, oldAddr: u64) -> Result<u64> { let (newPath, dirPath) = copyInPath(task, newAddr, false)?; if dirPath { return Err(Error::SysError(SysErr::ENOENT)) } let (oldPath, err) = task.CopyInString(oldAddr, PATH_MAX); match err { Err(e) => return Err(e), _ => () } if oldPath.as_str() == "" { return Err(Error::SysError(SysErr::ENOENT)) } info!("symlinkAt newpath is {}, oldpath is {}", &newPath, &oldPath); fileOpAt(task, dirFd, &newPath.to_string(), &mut |root: &Dirent, d: &Dirent, name: &str, _remainingTraversals: u32| -> Result<()> { let inode = d.Inode(); if !inode.StableAttr().IsDir() { return Err(Error::SysError(SysErr::ENOTDIR)) } inode.CheckPermission(task, &PermMask { write: true, execute: true, ..Default::default() })?; return d.CreateLink(task, root, &oldPath, name) })?; return Ok(0) } pub fn SysSymlink(task: &mut Task, args: &SyscallArguments) -> Result<i64> { let oldAddr = args.arg0 as u64; let newAddr = args.arg1 as u64; symlinkAt(task, newAddr, ATType::AT_FDCWD, oldAddr)?; return Ok(0); } pub fn SysSymlinkat(task: &mut Task, args: &SyscallArguments) -> Result<i64> { let oldAddr = args.arg0 as u64; let dirfd = args.arg1 as i32; let newAddr = args.arg2 as u64; symlinkAt(task, newAddr, dirfd, oldAddr)?; return Ok(0); } fn mayLinkAt(task: &Task, target: &mut Inode) -> Result<()> { if target.CheckOwnership(task) { return Ok(()) } if !target.StableAttr().IsRegular() { return Err(Error::SysError(SysErr::EPERM)) } let res = target.CheckPermission(task, &PermMask { write: true, execute: true, ..Default::default() }); match res { Err(_) => Err(Error::SysError(SysErr::EPERM)), _ => Ok(()) } } fn linkAt(task: &Task, oldDirfd: i32, oldAddr: u64, newDirfd: i32, newAddr: u64, resolve: bool, allowEmpty: bool) -> Result<i64> { let (oldPath, _) = copyInPath(task, oldAddr, allowEmpty)?; let (newPath, dirPath) = copyInPath(task, newAddr, false)?; if dirPath { return Err(Error::SysError(SysErr::ENOENT)) } if allowEmpty && oldPath == "" { let target = task.GetFile(oldDirfd)?; let mut inode = target.Dirent.Inode(); mayLinkAt(task, &mut inode)?; fileOpAt(task, newDirfd, &newPath.to_string(), &mut |root: &Dirent, newParent: &Dirent, name: &str, _remainingTraversals: u32| -> Result<()> { let inode = newParent.Inode(); if !inode.StableAttr().IsDir() { return Err(Error::SysError(SysErr::ENOTDIR)) } inode.CheckPermission(task, &PermMask { write: true, execute: true, ..Default::default() })?; return newParent.CreateHardLink(task, root, &target.Dirent.clone(), name) })?; return Ok(0) }; fileOpOn(task, oldDirfd, &oldPath.to_string(), resolve, &mut |_root: &Dirent, target: &Dirent, _remainingTraversals: u32| -> Result<()> { let mut inode = target.Inode(); mayLinkAt(task, &mut inode)?; return fileOpAt(task, newDirfd, &newPath.to_string(), &mut |root: &Dirent, newParent: &Dirent, newName: &str, _remainingTraversals: u32| -> Result<()> { let inode = newParent.Inode(); if !inode.StableAttr().IsDir() { return Err(Error::SysError(SysErr::ENOTDIR)) } inode.CheckPermission(task, &PermMask { write: true, execute: true, ..Default::default() })?; return newParent.CreateHardLink(task, root, target, newName) }); })?; return Ok(0) } pub fn SysLink(task: &mut Task, args: &SyscallArguments) -> Result<i64> { let oldAddr = args.arg0 as u64; let newAddr = args.arg1 as u64; let resolve = false; return linkAt(task, ATType::AT_FDCWD, oldAddr, ATType::AT_FDCWD, newAddr, resolve, false) } pub fn SysLinkat(task: &mut Task, args: &SyscallArguments) -> Result<i64> { let oldDirfd = args.arg0 as i32; let oldAddr = args.arg1 as u64; let newDirfd = args.arg2 as i32; let newAddr = args.arg3 as u64; // man linkat(2): // By default, linkat(), does not dereference oldpath if it is a // symbolic link (like link(2)). Since Linux 2.6.18, the flag // AT_SYMLINK_FOLLOW can be specified in flags to cause oldpath to be // dereferenced if it is a symbolic link. let flags = args.arg4 as i32; if flags & !(ATType::AT_SYMLINK_FOLLOW | ATType::AT_EMPTY_PATH) != 0 { return Err(Error::SysError(SysErr::EINVAL)) } let resolve = flags & ATType::AT_SYMLINK_FOLLOW == ATType::AT_SYMLINK_FOLLOW; let allowEmpty = flags & ATType::AT_EMPTY_PATH == ATType::AT_EMPTY_PATH; { let creds = task.Creds(); let userNS = creds.lock().UserNamespace.clone(); if allowEmpty && !creds.HasCapabilityIn(Capability::CAP_DAC_READ_SEARCH, &userNS) { return Err(Error::SysError(SysErr::ENOENT)) } } return linkAt(task, oldDirfd, oldAddr, newDirfd, newAddr, resolve, allowEmpty) } fn readlinkAt(task: &Task, dirFd: i32, addr: u64, bufAddr: u64, size: u32) -> Result<i64> { let (path, dirPath) = copyInPath(task, addr, false)?; if dirPath { return Err(Error::SysError(SysErr::ENOENT)) } info!("readlinkAt path is {}", &path); let mut copied = 0; let size = size as usize; fileOpOn(task, dirFd, &path, false, &mut |_root: &Dirent, d: &Dirent, _remainingTraversals: u32| -> Result<()> { let inode = d.Inode(); inode.CheckPermission(task, &PermMask { read: true, ..Default::default() })?; let s = match inode.ReadLink(task) { Err(Error::SysError(SysErr::ENOLINK)) => return Err(Error::SysError(SysErr::EINVAL)), Err(e) => return Err(e), Ok(s) => s, }; info!("readlinkAt 1 path is {}, target is {}", &path, &s); let mut buffer = s.as_bytes(); if buffer.len() > size { buffer = &buffer[..size] } task.CopyOutSlice(buffer, bufAddr, buffer.len())?; copied = buffer.len(); Ok(()) })?; return Ok(copied as i64) } // Readlink implements linux syscall readlink(2). pub fn SysReadLink(task: &mut Task, args: &SyscallArguments) -> Result<i64> { let addr = args.arg0 as u64; let bufAddr = args.arg1 as u64; let size = args.arg2 as u64; let size = size as u32; return readlinkAt(task, ATType::AT_FDCWD, addr, bufAddr, size) } // Readlinkat implements linux syscall readlinkat(2). pub fn SysReadLinkAt(task: &mut Task, args: &SyscallArguments) -> Result<i64> { let dirfd = args.arg0 as i32; let addr = args.arg1 as u64; let bufAddr = args.arg2 as u64; let size = args.arg3 as u64; let size = size as u32; return readlinkAt(task, dirfd, addr, bufAddr, size) } pub fn ReadLinkAt(task: &Task, dirFd: i32, addr: u64, bufAddr: u64, size: u64) -> Result<i64> { let size = size as u32; return readlinkAt(task, dirFd, addr, bufAddr, size) } fn unlinkAt(task: &Task, dirFd: i32, addr: u64) -> Result<i64> { let (path, dirPath) = copyInPath(task, addr, false)?; info!("unlinkAt path is {}", &path); if dirPath { return Err(Error::SysError(SysErr::ENOTDIR)) } fileOpAt(task, dirFd, &path.to_string(), &mut |root: &Dirent, d: &Dirent, name: &str, _remainingTraversals: u32| -> Result<()> { let inode = d.Inode(); if !inode.StableAttr().IsDir() { return Err(Error::SysError(SysErr::ENOTDIR)) } d.MayDelete(task, root, name)?; return d.Remove(task, root, name, dirPath) })?; return Ok(0) } pub fn SysUnlink(task: &mut Task, args: &SyscallArguments) -> Result<i64> { let addr = args.arg0 as u64; return unlinkAt(task, ATType::AT_FDCWD, addr) } pub fn SysUnlinkat(task: &mut Task, args: &SyscallArguments) -> Result<i64> { let dirfd = args.arg0 as i32; let addr = args.arg1 as u64; let flags = args.arg2 as u32; if flags & ATType::AT_REMOVEDIR as u32 != 0 { return rmdirAt(task, dirfd, addr) } return unlinkAt(task, dirfd, addr) } pub fn SysTruncate(task: &mut Task, args: &SyscallArguments) -> Result<i64> { let addr = args.arg0 as u64; let len = args.arg1 as i64; if len < 0 { return Err(Error::SysError(SysErr::EINVAL)) } let (path, dirPath) = copyInPath(task, addr, false)?; if dirPath { return Err(Error::SysError(SysErr::EINVAL)) } fileOpOn(task, ATType::AT_FDCWD, &path, true, &mut |_root: &Dirent, d: &Dirent, _remainingTraversals: u32| -> Result<()> { let mut inode = d.Inode(); if inode.StableAttr().IsDir() { return Err(Error::SysError(SysErr::EISDIR)) } if !inode.StableAttr().IsFile() { return Err(Error::SysError(SysErr::EINVAL)) } inode.CheckPermission(task, &PermMask { write: true, ..Default::default() })?; return inode.Truncate(task, d, len) })?; return Ok(0) } pub fn SysFtruncate(task: &mut Task, args: &SyscallArguments) -> Result<i64> { let fd = args.arg0 as i32; let len = args.arg1 as i64; let file = task.GetFile(fd)?; if !file.Flags().Write { return Err(Error::SysError(SysErr::EINVAL)) } let mut inode = file.Dirent.Inode(); if !inode.StableAttr().IsFile() { return Err(Error::SysError(SysErr::EINVAL)) } if len < 0 { return Err(Error::SysError(SysErr::EINVAL)) } let dirent = file.Dirent.clone(); inode.Truncate(task, &dirent, len)?; return Ok(0) } pub fn SysUmask(task: &mut Task, args: &SyscallArguments) -> Result<i64> { let mask = args.arg0 as u32; let mask = task.fsContext.SwapUmask(mask & 0o777); return Ok(mask as i64) } fn chown(task: &Task, d: &Dirent, uid: UID, gid: GID) -> Result<i64> { let mut owner = FileOwner { UID: KUID(NO_ID), GID: KGID(NO_ID), }; let creds = task.Creds(); let inode = d.Inode(); let uattr = inode.UnstableAttr(task)?; let hasCap = CheckCapability(&creds, Capability::CAP_CHOWN, &uattr); let c = creds.lock(); let isOwner = uattr.Owner.UID == c.EffectiveKUID; if uid.Ok() { let kuid = c.UserNamespace.MapToKUID(uid); if !kuid.Ok() { return Err(Error::SysError(SysErr::EINVAL)) } let isNoop = uattr.Owner.UID == kuid; if !(hasCap || (isOwner && isNoop)) { return Err(Error::SysError(SysErr::EPERM)) } owner.UID = kuid; } if gid.Ok() { let kgid = c.UserNamespace.MapToKGID(gid); if !kgid.Ok() { return Err(Error::SysError(SysErr::EINVAL)) } let isNoop = uattr.Owner.GID == kgid; let isMemberGroup = c.InGroup(kgid); if !(hasCap || (isOwner && (isNoop || isMemberGroup))) { return Err(Error::SysError(SysErr::EPERM)) } owner.GID = kgid; } // This is racy; the inode's owner may have changed in // the meantime. (Linux holds i_mutex while calling // fs/attr.c:notify_change() => inode_operations::setattr => // inode_change_ok().) info!("workaround enable setowner for host inode, the owner is {:?}", &owner); let mut inode = d.Inode(); inode.SetOwner(task, d, &owner)?; // When the owner or group are changed by an unprivileged user, // chown(2) also clears the set-user-ID and set-group-ID bits, but // we do not support them. return Ok(0) } fn chownAt(task: &Task, fd: i32, addr: u64, resolve: bool, allowEmpty: bool, uid: UID, gid: GID) -> Result<i64> { let (path, _) = copyInPath(task, addr, allowEmpty)?; if path == "" { let file = task.GetFile(fd)?; let dirent = file.Dirent.clone(); chown(task, &dirent, uid, gid)?; return Ok(0) } fileOpOn(task, fd, &path, resolve, &mut |_root: &Dirent, d: &Dirent, _remainingTraversals: u32| -> Result<()> { chown(task, d, uid, gid)?; Ok(()) })?; return Ok(0) } pub fn SysChown(task: &mut Task, args: &SyscallArguments) -> Result<i64> { let addr = args.arg0 as u64; let uid = args.arg1 as u32; let gid = args.arg2 as u32; let uid = UID(uid as u32); let gid = GID(gid as u32); let ret = chownAt(task, ATType::AT_FDCWD, addr, true, false, uid, gid)?; return Ok(ret as i64) } pub fn SysLchown(task: &mut Task, args: &SyscallArguments) -> Result<i64> { let addr = args.arg0 as u64; let uid = args.arg1 as u32; let gid = args.arg2 as u32; let uid = UID(uid as u32); let gid = GID(gid as u32); return chownAt(task, ATType::AT_FDCWD, addr, false, false, uid, gid) } pub fn SysFchown(task: &mut Task, args: &SyscallArguments) -> Result<i64> { let fd = args.arg0 as i32; let uid = UID(args.arg1 as u32); let gid = GID(args.arg2 as u32); let file = task.GetFile(fd)?; let dirent = file.Dirent.clone(); return chown(task, &dirent, uid, gid) } pub fn SysFchownat(task: &mut Task, args: &SyscallArguments) -> Result<i64> { let dirfd = args.arg0 as i32; let addr = args.arg1 as u64; let uid = UID(args.arg2 as u32); let gid = GID(args.arg3 as u32); let flags = args.arg4 as i32; if flags & !(ATType::AT_EMPTY_PATH | ATType::AT_SYMLINK_NOFOLLOW) != 0 { return Err(Error::SysError(SysErr::EINVAL)) } return chownAt(task, dirfd, addr, flags & ATType::AT_SYMLINK_NOFOLLOW == 0, flags & ATType::AT_EMPTY_PATH != 0, uid, gid); } fn utime(task: &Task, dirfd: i32, addr: u64, ts: &InterTimeSpec, resolve: bool) -> Result<i64> { let setTimestamp = &mut |_root: &Dirent, d: &Dirent, _remainingTraversals: u32| -> Result<()> { let mut inode = d.Inode(); if !inode.CheckOwnership(task) { if (ts.ATimeOmit || !ts.ATimeSetSystemTime) && (ts.MTimeOmit || !ts.MTimeSetSystemTime) { return Err(Error::SysError(SysErr::EPERM)) } inode.CheckPermission(task, &PermMask { write: true, ..Default::default() })?; } inode.SetTimestamps(task, d, ts)?; return Ok(()) }; if addr == 0 && dirfd != ATType::AT_FDCWD { if !resolve { return Err(Error::SysError(SysErr::EINVAL)) } let f = task.GetFile(dirfd)?; let root = task.Root().clone(); setTimestamp(&root, &f.Dirent.clone(), MAX_SYMLINK_TRAVERSALS)?; return Ok(0) } let (path, _) = copyInPath(task, addr, false)?; fileOpOn(task, dirfd, &path.to_string(), resolve, setTimestamp)?; return Ok(0) } pub fn SysUtime(task: &mut Task, args: &SyscallArguments) -> Result<i64> { let filenameAddr = args.arg0 as u64; let timesAddr = args.arg1 as u64; let mut ts = InterTimeSpec::default(); if timesAddr != 0 { let times: Utime = task.CopyInObj(timesAddr)?; ts.ATime = Time::FromSec(times.Actime); ts.ATimeSetSystemTime = false; ts.MTime = Time::FromSec(times.Modtime); ts.MTimeSetSystemTime = false; } return utime(task, ATType::AT_FDCWD, filenameAddr, &ts, true) } pub fn SysUtimes(task: &mut Task, args: &SyscallArguments) -> Result<i64> { let filenameAddr = args.arg0 as u64; let timesAddr = args.arg1 as u64; let mut ts = InterTimeSpec::default(); if timesAddr != 0 { let times: [Timeval; 2] = task.CopyInObj(timesAddr)?; ts.ATime = Time::FromTimeval(&times[0]); ts.ATimeSetSystemTime = false; ts.MTime = Time::FromTimeval(&times[1]); ts.MTimeSetSystemTime = false; } return utime(task, ATType::AT_FDCWD, filenameAddr, &ts, true) } // timespecIsValid checks that the timespec is valid for use in utimensat. pub fn TimespecIsValid(ts: &Timespec) -> bool { return ts.tv_nsec == Utime::UTIME_OMIT || ts.tv_nsec == Utime::UTIME_NOW || ts.tv_nsec < 1_000_000_000; } pub fn SysUtimensat(task: &mut Task, args: &SyscallArguments) -> Result<i64> { let dirfd = args.arg0 as i32; let filenameAddr = args.arg1 as u64; let timesAddr = args.arg2 as u64; let flags = args.arg3 as i32; let mut ts = InterTimeSpec::default(); if timesAddr != 0 { let times: [Timespec; 2] = task.CopyInObj(timesAddr)?; if !TimespecIsValid(&times[0]) || !TimespecIsValid(&times[1]) { return Err(Error::SysError(SysErr::EINVAL)) } // If both are UTIME_OMIT, this is a noop. if times[0].tv_nsec == Utime::UTIME_OMIT && times[1].tv_nsec == Utime::UTIME_OMIT { return Ok(0) } ts = InterTimeSpec { ATime: Time::FromTimespec(&times[0]), ATimeOmit: times[0].tv_nsec == Utime::UTIME_OMIT, ATimeSetSystemTime: times[0].tv_nsec == Utime::UTIME_NOW, MTime: Time::FromTimespec(&times[1]), MTimeOmit: times[1].tv_nsec == Utime::UTIME_OMIT, MTimeSetSystemTime: times[1].tv_nsec == Utime::UTIME_NOW, } } return utime(task, dirfd, filenameAddr, &ts, flags & ATType::AT_SYMLINK_NOFOLLOW == 0) } pub fn SysFutimesat(task: &mut Task, args: &SyscallArguments) -> Result<i64> { let dirfd = args.arg0 as i32; let filenameAddr = args.arg1 as u64; let timesAddr = args.arg2 as u64; let mut ts = InterTimeSpec::default(); const E6: i64 = 1_000_000; if timesAddr != 0 { let times: [Timeval; 2] = task.CopyInObj(timesAddr)?; if times[0].Usec > E6 || times[0].Usec < 0 || times[1].Usec > E6 || times[1].Usec < 0 { return Err(Error::SysError(SysErr::EINVAL)) } ts.ATime = Time::FromTimeval(&times[0]); ts.ATimeSetSystemTime = false; ts.MTime = Time::FromTimeval(&times[1]); ts.MTimeSetSystemTime = false; } return utime(task, dirfd, filenameAddr, &ts, true) } fn renameAt(task: &Task, oldDirfd: i32, oldAddr: u64, newDirfd: i32, newAddr: u64) -> Result<i64> { let (newPath, _) = copyInPath(task, newAddr, false)?; let (oldPath, _) = copyInPath(task, oldAddr, false)?; fileOpAt(task, oldDirfd, &oldPath.to_string(), &mut |_root: &Dirent, oldParent: &Dirent, oldName: &str, _remainingTraversals: u32| -> Result<()> { let inode = oldParent.Inode(); if !inode.StableAttr().IsDir() { return Err(Error::SysError(SysErr::ENOTDIR)) } match oldName { "" | "." | ".." => return Err(Error::SysError(SysErr::EBUSY)), _ => (), } return fileOpAt(task, newDirfd, &newPath.to_string(), &mut |root: &Dirent, newParent: &Dirent, newName: &str, _remainingTraversals: u32| -> Result<()> { let inode = newParent.Inode(); if !inode.StableAttr().IsDir() { return Err(Error::SysError(SysErr::ENOTDIR)) } match newName { "" | "." | ".." => return Err(Error::SysError(SysErr::EBUSY)), _ => (), } return Dirent::Rename(task, root, oldParent, oldName, newParent, newName) }) })?; Ok(0) } pub fn SysRename(task: &mut Task, args: &SyscallArguments) -> Result<i64> { let oldAddr = args.arg0 as u64; let newAddr = args.arg1 as u64; return renameAt(task, ATType::AT_FDCWD, oldAddr, ATType::AT_FDCWD, newAddr) } pub fn SysRenameat(task: &mut Task, args: &SyscallArguments) -> Result<i64> { let oldDirfd = args.arg0 as i32; let oldAddr = args.arg1 as u64; let newDirfd = args.arg2 as i32; let newAddr = args.arg3 as u64; return renameAt(task, oldDirfd, oldAddr, newDirfd, newAddr) } // Fallocate implements linux system call fallocate(2). pub fn SysFallocate(task: &mut Task, args: &SyscallArguments) -> Result<i64> { let fd = args.arg0 as i32; let mode = args.arg1 as i64; let offset = args.arg2 as i64; let len = args.arg3 as i64; let file = task.GetFile(fd)?; if offset < 0 || len <= 0 { return Err(Error::SysError(SysErr::EINVAL)) } if mode != 0 { //t.Kernel().EmitUnimplementedEvent(t) return Err(Error::SysError(SysErr::ENOTSUP)) } if !file.Flags().Write { return Err(Error::SysError(SysErr::EBADF)) } let mut inode = file.Dirent.Inode(); if inode.StableAttr().IsPipe() { return Err(Error::SysError(SysErr::ESPIPE)) } if inode.StableAttr().IsDir() { return Err(Error::SysError(SysErr::EISDIR)) } if !inode.StableAttr().IsRegular() { return Err(Error::SysError(SysErr::ENODEV)) } let size = offset + len; if size < 0 { return Err(Error::SysError(SysErr::EFBIG)) } let dirent = file.Dirent.clone(); inode.Allocate(task, &dirent, offset, len)?; Ok(0) } pub fn SysFlock(task: &mut Task, args: &SyscallArguments) -> Result<i64> { let fd = args.arg0 as i32; let mut operation = args.arg1 as i32; let file = task.GetFile(fd)?; let nonblocking = operation & LibcConst::LOCK_NB as i32 != 0; operation &= !(LibcConst::LOCK_NB as i32); // flock(2): // Locks created by flock() are associated with an open file table entry. This means that // duplicate file descriptors (created by, for example, fork(2) or dup(2)) refer to the // same lock, and this lock may be modified or released using any of these descriptors. Furthermore, // the lock is released either by an explicit LOCK_UN operation on any of these duplicate // descriptors, or when all such descriptors have been closed. // // If a process uses open(2) (or similar) to obtain more than one descriptor for the same file, // these descriptors are treated independently by flock(). An attempt to lock the file using // one of these file descriptors may be denied by a lock that the calling process has already placed via // another descriptor. // // We use the File UniqueID as the lock UniqueID because it needs to reference the same lock across dup(2) // and fork(2). let lockUniqueId = file.UniqueId(); let rng = Range::New(0, MAX_RANGE); let inode = file.Dirent.Inode(); let bsd = inode.lock().LockCtx.BSD.clone(); match operation as u64 { LibcConst::LOCK_EX => { if nonblocking { // Since we're nonblocking we pass a nil lock.Blocker implementation. if !bsd.LockRegion(task, lockUniqueId, LockType::WriteLock, &rng, false)? { return Err(Error::SysError(SysErr::EWOULDBLOCK)) } } else { // Because we're blocking we will pass the task to satisfy the lock.Blocker interface. if !bsd.LockRegion(task, lockUniqueId, LockType::WriteLock, &rng, true)? { return Err(Error::SysError(SysErr::EINTR)) } } } LibcConst::LOCK_SH => { if nonblocking { // Since we're nonblocking we pass a nil lock.Blocker implementation. if !bsd.LockRegion(task, lockUniqueId, LockType::ReadLock, &rng, false)? { return Err(Error::SysError(SysErr::EWOULDBLOCK)) } } else { // Because we're blocking we will pass the task to satisfy the lock.Blocker interface. if !bsd.LockRegion(task, lockUniqueId, LockType::ReadLock, &rng, true)? { return Err(Error::SysError(SysErr::EINTR)) } } } LibcConst::LOCK_UN => { bsd.UnlockRegion(task, lockUniqueId, &rng) } _ => { // flock(2): EINVAL operation is invalid. return Err(Error::SysError(SysErr::EINVAL)) } } return Ok(0) } /* pub fn MemfdCreate(task: &Task, addr: u64, flags: u64) -> Result<u64> { let memfdPrefix = "/memfd:"; let memfdAllFlags = MfdType::MFD_CLOEXEC | MfdType::MFD_ALLOW_SEALING; let memfdMaxNameLen = NAME_MAX - memfdPrefix.len() + 1; let flags = flags as u32; if flags & !memfdAllFlags != 0 { return Err(Error::SysError(SysErr::EINVAL)) } let allowSeals = flags & MfdType::MFD_ALLOW_SEALING != 0; let cloExec = flags & MfdType::MFD_CLOEXEC != 0; let name = task.CopyInString(addr, PATH_MAX - memfdPrefix.len())?; if name.len() > memfdMaxNameLen { return Err(Error::SysError(SysErr::EINVAL)) } let name = memfdPrefix.to_string() + &name; }*/
pub fn main() { println!("\n-- 19.2 advanced traits\n"); specifying_placeholder_types_in_trait_defs_with_associated_types(); default_generic_type_parameters_and_operator_overloading(); fully_qualified_syntax_for_disambiguation(); supertraits_to_inception_traits(); newtype_pattern_for_ext_traits_on_ext_types(); } /// "newtype" is a term that originates from Haskell /// - the wrapper type is "elided" at compile time fn newtype_pattern_for_ext_traits_on_ext_types() { println!("\n- using the newtype pattern to implement external traints on external types\n"); // EXAMPLE: // - we want to implement Display on Vec<T> // - orphan rule prevents us from doing directly because the Display trait and Vec<T> are // defined outside of our crate // - we can instead, make a Wrapper struct that holds an instance of Vec<T> // - then we implement Display on the Wrapper and use the Vec<T> value use std::fmt; struct Wrapper(Vec<String>); impl fmt::Display for Wrapper { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "[{}]", self.0.join(", ")) // Vec<T> is the item at index zero (in the tuple) } } let w = Wrapper(vec![String::from("hello"), String::from("world")]); println!("w = {}", w); } fn supertraits_to_inception_traits() { println!("\n- using supertraits to require one trait's functionality within another trait\n"); use std::fmt; trait OutlinePrint: fmt::Display { fn outline_print(&self) { let output = self.to_string(); let len = output.len(); println!("{}", "*".repeat(len + 4)); println!("*{}*", " ".repeat(len + 2)); println!("* {} *", output); println!("*{}*", " ".repeat(len + 2)); println!("{}", "*".repeat(len + 4)); } } struct Point { x: i32, y: i32, } impl OutlinePrint for Point {} impl fmt::Display for Point { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "({}, {})", self.x, self.y) } } } /// fully qualified syntax for disambiguation: calling methods with the same name fn fully_qualified_syntax_for_disambiguation() { trait Pilot { fn fly(&self); } trait Wizard { fn fly(&self); } struct Human; impl Pilot for Human { fn fly(&self) { println!("This is your captain speaking."); } } impl Wizard for Human { fn fly(&self) { println!("Up!"); } } impl Human { fn fly(&self) { println!("*flapping arms furiously*"); } } let person = Human; // specifying trait name specifies which implementation we want Pilot::fly(&person); Wizard::fly(&person); person.fly(); // Human::fly // NOTE: associated functions that are a part of traits don't have a `self` parameter println!("\n- trait associated functions\n"); trait Animal { fn baby_name() -> String; // associated function (no self) } struct Dog; #[allow(dead_code)] impl Dog { fn baby_name() -> String { String::from("Spot") } } impl Animal for Dog { fn baby_name() -> String { String::from("puppy") } } // use of fully-qualified name for an associated function with no self param // NOTE: no receiver for associated functions, only other arguments println!("A baby dog is called a {}", <Dog as Animal>::baby_name()); } fn default_generic_type_parameters_and_operator_overloading() { println!("\n- default generic type parameters and operator overloading\n"); // operator overloading : customizing the behavior of an operator such as `+` // - we can overload the operations corresponding to traits listed in `std::ops` // we overload the `+` to add two `Point` instances together use std::ops::Add; #[derive(Debug, PartialEq)] struct Point { x: i32, y: i32, } impl Add for Point { type Output = Point; fn add(self, other: Point) -> Point { Point { x: self.x + other.x, y: self.y + other.y, } } } let composite_point = Point { x: 1, y: 0 } + Point { x: 2, y: 3 }; println!( "\n- overloading the `+` operator | adding two points: \nfirst point: {:?}\nsecond point: {:?}\ncomposite: {:?}\n", Point { x: 1, y: 0 }, Point { x: 2, y: 3 }, composite_point, ); assert_eq!(composite_point, Point { x: 3, y: 3 }); // customized default type parameters // // NOTE: 2 primary uses for default type params // 1. extend a type without breaking existing code // 2. allow customization in specific cases where most users won't need // * standard library Add trait is an example of customiztion in specific use cases where we're // adding two similar types // // - implementing Add trait where we customize `Rhs` struct Millimeters(u32); struct Meters(u32); impl Add<Meters> for Millimeters { type Output = Millimeters; fn add(self, other: Meters) -> Millimeters { Millimeters(self.0 + (other.0 * 1000)) } } } fn specifying_placeholder_types_in_trait_defs_with_associated_types() { println!("\n- specifying placeholder types in trait definitions with associated types\n"); pub trait Iterator { type Item; // placeholder type // implementors of Iterator must specify a concrete type for Item // NOTE: with associated types, we don't need to annotate types because we can't implement // a trait on a type multiple times fn next(&mut self) -> Option<Self::Item>; } }
use std::net::{IpAddr, SocketAddr}; use uuid::Uuid; #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] pub struct NetId(Uuid); impl NetId { pub fn new() -> Self { NetId(Uuid::new_v4()) } } /// Network error type #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] pub enum NetError { UnknownError, OpenError, CloseError, SendError, ReceiveError, AcceptError, QuitError, } pub type SocketAddress = SocketAddr; pub type IpAddress = IpAddr; pub type Port = u16; pub type SocketId = NetId; pub type ListenerId = NetId; /// Connection protocol /// TCP has sockets/listeners, but UDP can use sockets/listeners interchangeably #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] pub enum NetProtocol { /// UDP (User Datagram Protocol) Udp, /// TCP (Transmission Control Protocol) Tcp, }
use std::rc::Rc; use self::mesh::Mesh; use super::material::Material; pub mod mesh; // TODO: model should be owned by the user not scene. then every rendercomponent has a ref (rc) to the model pub struct Model { pub material: Rc<Material>, pub mesh: Rc<Mesh>, }
use crate::util::IndexDomain; use crate::{Cell, Owner, SearchNode}; use super::NodePool; pub struct IndexPool { search_num: usize, pool: Box<[Cell<SearchNode<usize>>]>, } impl IndexPool { pub fn new(size: usize) -> Self { let mut pool = Vec::with_capacity(size); for id in 0..size { pool.push(Cell::new(SearchNode { search_num: 0, id, expansions: 0, g: 0.0, lb: 0.0, parent: None, pqueue_location: 0, })); } IndexPool { search_num: 0, pool: pool.into_boxed_slice(), } } } impl NodePool<usize> for IndexPool { fn reset(&mut self, owner: &mut Owner) { match self.search_num.checked_add(1) { Some(ok) => self.search_num = ok, None => { // on the off chance we do a search while there are still nodes with search nums // equal to the new search num after an overflow, it would be a *really* hard to // diagnose logic bug, so we nip it in the bud by resetting everything on overflow. self.search_num = 1; for node in self.pool.iter() { owner.rw(node).search_num = 0; } } } } fn generate(&self, id: usize, owner: &mut Owner) -> &Cell<SearchNode<usize>> { assert!(id < self.pool.len()); unsafe { // SAFETY: bounds checked above self.generate_unchecked(id, owner) } } unsafe fn generate_unchecked( &self, id: usize, owner: &mut Owner, ) -> &Cell<SearchNode<usize>> { let cell = self.pool.get_unchecked(id); if owner.ro(cell).search_num == self.search_num { cell } else { let n = owner.rw(cell); n.lb = f64::INFINITY; n.g = f64::INFINITY; n.expansions = 0; n.search_num = self.search_num; n.parent = None; cell } } } unsafe impl IndexDomain for IndexPool { fn len(&self) -> usize { self.pool.len() } }
//计算成功概率用的 use std::collections::HashMap; use std::collections::HashSet; use rand::Rng; pub fn b1(a: f64, r: f64) -> f64 { let b = r + 2.0 * a; b } pub fn hb(x: f64) -> f64 { //二元熵函数 let y = -x * (x.log2()) - (1.0 - x) * ((1.0 - x).log2()); y } pub fn creat_permutation(n: i64, a: f64, r: f64) -> HashMap<i64, HashSet<i64>> { let mut map1: HashMap<i64, HashSet<i64>> = HashMap::new(); let mut rng = rand::thread_rng(); let b = b1(a, r); //生成a,b的(0,1)的随机数 let k = (hb(a) + hb(b)) / (hb(a) - b * hb(a / b)); //取k临界值 let d = k.ceil() as i64; for j in 0..d * n { let i = rng.gen_range(0, d * n); if map1.get(&(j % n)) == None { let set: HashSet<i64> = HashSet::new(); map1.insert(j % n, set); } map1.get_mut(&(j % n)).unwrap().insert(i % n); } map1 } pub fn count_pr(n: i64, b: f64, map: HashMap<i64, HashSet<i64>>) -> f64 { let mut count_bad = 0; let mut count_good = 0; for oi in 0..n { for ii in oi + 1..n { let mut nset = HashSet::new(); for v in map.get(&oi).unwrap().iter() { nset.insert(v); } for v in map.get(&ii).unwrap().iter() { nset.insert(v); } let l = nset.len(); if l >= b as usize { count_good += 1; } else { count_bad += 1; } } } let pr = count_good as f64 / (count_good as f64 + count_bad as f64); println!("good pr is {:?}", pr); pr }
extern crate specs; use crate::types::{GameState}; pub use nalgebra::Vector2; use nphysics2d::math::Velocity; use nphysics2d::object::{ BodyPartHandle, BodyStatus, ColliderDesc, DefaultBodyHandle, DefaultBodySet, DefaultColliderSet, RigidBodyDesc }; use nphysics2d::joint::{DefaultJointConstraintSet}; use nphysics2d::world::{DefaultGeometricalWorld, DefaultMechanicalWorld}; use nphysics2d::force_generator::{DefaultForceGeneratorSet}; use specs::{System, Read}; pub type Vec2 = Vector2<f32>; pub type Handle = DefaultBodyHandle; pub struct PhysicsSystem { gworld: DefaultGeometricalWorld<f32>, mworld: DefaultMechanicalWorld<f32>, bodies: DefaultBodySet<f32>, colliders: DefaultColliderSet<f32>, constraints: DefaultJointConstraintSet<f32>, forces: DefaultForceGeneratorSet<f32>, } impl<'a> System<'a> for PhysicsSystem { type SystemData = Read<'a, GameState>; fn run(&mut self, gs: Self::SystemData) { self.step_for(gs.delta); println!("Last iteration: {}", self.mworld.counters.step_time) } } impl PhysicsSystem { pub fn new() -> PhysicsSystem { let mut sys = PhysicsSystem { gworld: DefaultGeometricalWorld::new(), mworld: DefaultMechanicalWorld::new(Vec2::new(0., 9.8)), bodies: DefaultBodySet::new(), colliders: DefaultColliderSet::new(), constraints: DefaultJointConstraintSet::new(), forces: DefaultForceGeneratorSet::new(), }; sys.mworld.counters.enable(); sys.gworld.maintain(&mut sys.bodies, &mut sys.colliders); sys.mworld.maintain(&mut sys.gworld, &mut sys.bodies, &mut sys.colliders, &mut sys.constraints); sys } fn step_for(&mut self, _update_dt: f64) { self.mworld.step( &mut self.gworld, &mut self.bodies, &mut self.colliders, &mut self.constraints, &mut self.forces); } pub fn add_box(&mut self, pos: Vec2) -> Handle { use ncollide2d::shape::{Cuboid, ShapeHandle}; let shape = ShapeHandle::new(Cuboid::new(Vector2::new(25., 25.))); let body = RigidBodyDesc::new() .translation(pos) .velocity(Velocity::linear(1., 0.)) .status(BodyStatus::Kinematic) .build(); let handle = self.bodies.insert(body); self.colliders.insert( ColliderDesc::new(shape) .density(1.) .build(BodyPartHandle(handle, 0)), ); handle } }
pub type LazyResult<T> = Result<T, Box<dyn std::error::Error>>;
pub enum Operator { Addition, Subtraction, Multiplication, Division, Unknown(char), } pub fn is_operator(symbol: &char) -> bool { match symbol { '+' | '-' | '/' | '*' => true, _ => false, } } pub fn as_operator(symbol: &char) -> Operator { match symbol { '+' => Operator::Addition, '-' => Operator::Subtraction, '/' => Operator::Division, '*' => Operator::Multiplication, symbol => Operator::Unknown(symbol.clone()), } }
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // 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. #[cfg(target_arch = "aarch64")] mod hos { use alloc_crate::boxed::FnBox; use cmp; use ffi::CStr; use io; use mem; use ptr; use sys_common::thread::start_thread; use time::Duration; use cell::UnsafeCell; use libnx::Thread as HosThread; use libc; #[repr(C)] pub struct ThreadHandle { handle: HosThread, rc : i32 } pub struct Thread { handle : UnsafeCell<ThreadHandle> } unsafe impl Send for Thread {} unsafe impl Sync for Thread {} pub const DEFAULT_MIN_STACK_SIZE: usize = 4096; #[repr(C)] struct C_TimeSpec { tv_sec : u64, tv_nsec : u64 } extern { fn thrd_create(thr : *mut *mut ThreadHandle, func : extern fn(*mut libc::c_void) -> i32, arg : *mut libc::c_void) -> i32; fn thrd_yield(); fn thrd_sleep(dur : *const C_TimeSpec, rem : *mut C_TimeSpec) -> i32; fn thrd_exit(res : i32); fn thrd_join(thr : *mut ThreadHandle, res : *mut i32) -> i32; } impl Thread { pub unsafe fn new<'a>(stack: usize, p: Box<FnBox() + 'a>) -> io::Result<Thread> { let handle_mem : UnsafeCell<ThreadHandle> = UnsafeCell::new(mem::zeroed()); let mut handle_ptr = handle_mem.get(); let rs = thrd_create(&mut handle_ptr as *mut *mut ThreadHandle, thread_func, &p as *const Box<FnBox() + 'a> as *mut Box<FnBox() + 'a> as *mut libc::c_void); return match rs { 1 => { Err(io::Error::new(io::ErrorKind::Other, "Thread busy!")) }, 2 => { Err(io::Error::new(io::ErrorKind::Other, "Thread error!")) }, 3 => { Err(io::Error::new(io::ErrorKind::Other, "Thread nomem!")) }, 4 => { mem::forget(p); // ownership passed to the new thread Ok(Thread { handle: handle_mem }) }, 5 => { Err(io::Error::new(io::ErrorKind::Other, "Thread timeout!")) }, e => { Err(io::Error::new(io::ErrorKind::Other, format!("Thread create retval: {}!", e))) } }; extern "C" fn thread_func(start: *mut libc::c_void) -> i32 { unsafe { start_thread(start as *mut u8) }; 0 } } pub fn yield_now() { unsafe {thrd_yield()}; } pub fn set_name(_name: &CStr) { // threads aren't named in libnx } pub fn sleep(dur: Duration) { unsafe { let dur = C_TimeSpec { tv_sec : dur.as_secs(), tv_nsec : dur.subsec_nanos() as u64 }; thrd_sleep(&dur as *const C_TimeSpec, ptr::null_mut()); } } pub fn join(mut self) { unsafe { let mut res = 0; thrd_join(self.handle.get(), &mut res as *mut i32); } } #[allow(dead_code)] pub fn id(&self) -> ThreadHandle { unsafe { mem::transmute_copy(&self.handle) } } #[allow(dead_code)] pub fn into_id(self) -> ThreadHandle { let handle = unsafe { mem::transmute_copy(&self.handle) }; mem::forget(self); handle } } impl Drop for Thread { fn drop(&mut self) { //TODO: kill the thread } } pub mod guard { pub unsafe fn current() -> Option<usize> { None } pub unsafe fn init() -> Option<usize> { None } } } #[cfg(target_arch = "aarch64")] pub use self::hos::*;
use rand::distributions::Distribution; fn generate_random_name() -> String { let mut rng = rand::thread_rng(); let mut res = String::new(); let letter = rand::distributions::Uniform::from(0..26); let number = rand::distributions::Uniform::from(0..1000); for _ in 0..2 { let i: u8 = letter.sample(&mut rng); let c = (65 + i) as char; res.push(c); } let n = number.sample(&mut rng); format!("{}{:03}", res, n) } pub struct NamedRobot { name: String, } pub struct UnnamedRobot {} pub fn new_robot() -> UnnamedRobot { UnnamedRobot {} } impl NamedRobot { pub fn name(&self) -> &str { &self.name } pub fn stop(&self) {} pub fn start(&self) {} pub fn reset(self) -> UnnamedRobot { UnnamedRobot {} } } impl UnnamedRobot { pub fn start(self) -> NamedRobot { NamedRobot { name: generate_random_name(), } } } #[cfg(test)] mod tests { use super::*; #[test] fn name_is_not_set_at_frst() { let _robot = new_robot(); // robot.name() // does not compile: method name() not found for UnnamedRobot } #[test] fn started_robots_have_a_name() { let robot = new_robot(); let robot = robot.start(); assert!(robot.name() != ""); } #[test] fn name_does_not_change_when_rebooted() { let robot = new_robot(); let named_robot = robot.start(); let name1 = named_robot.name(); named_robot.stop(); named_robot.start(); let name2 = named_robot.name(); assert_eq!(name1, name2); } #[test] fn name_changes_after_a_reset() { let robot = new_robot(); let robot = robot.start(); let name1 = robot.name().to_string(); // robot.reset(); // robot.name(); // does not compile: value moved in reset() let robot = robot.reset(); // robot.name() does not compile: method name() not found for UnnamedRobot let robot = robot.start(); let name2 = robot.name().to_string(); assert_ne!(name1, name2); } }
use crate::prelude::*; use super::super::raw_to_slice; #[repr(C)] #[derive(Debug)] pub struct VkPhysicalDeviceMemoryProperties { pub memoryTypeCount: u32, pub memoryTypes: [VkMemoryType; VK_MAX_MEMORY_TYPES as usize], pub memoryHeapCount: u32, pub memoryHeaps: [VkMemoryHeap; VK_MAX_MEMORY_HEAPS as usize], } impl VkPhysicalDeviceMemoryProperties { pub fn memory_types(&self) -> &[VkMemoryType] { raw_to_slice(self.memoryTypes.as_ptr(), self.memoryTypeCount) } pub fn memory_heaps(&self) -> &[VkMemoryHeap] { raw_to_slice(self.memoryHeaps.as_ptr(), self.memoryHeapCount) } } impl Default for VkPhysicalDeviceMemoryProperties { fn default() -> Self { VkPhysicalDeviceMemoryProperties { memoryTypeCount: 0, memoryTypes: [VkMemoryType::default(); VK_MAX_MEMORY_TYPES as usize], memoryHeapCount: 0, memoryHeaps: [VkMemoryHeap::default(); VK_MAX_MEMORY_HEAPS as usize], } } }
use async_std::{prelude::FutureExt, sync::RwLock, task}; use std::{ops::Deref, sync::Arc, time::Duration}; fn main() { println!("Hello, world!"); env_logger::init(); task::block_on(async { let lock = Arc::new(RwLock::new(true)); { let lock = lock.clone(); task::spawn(async move { loop { task::sleep(Duration::from_secs(1)) .timeout(Duration::from_secs(5)) .await .unwrap(); let x = lock.write().await.deref() == &true; println!("awaken 1 {}", x); } }); } { let lock = lock.clone(); task::spawn(async move { loop { task::sleep(Duration::from_secs(1)) .timeout(Duration::from_secs(5)) .await .unwrap(); let x = lock.write().await.deref() == &true; println!("awaken 2 {}", x); } }); } task::spawn(async move { println!("finishin..."); task::sleep(Duration::from_secs(10)).await; let x = lock.write().await.deref() == &true; println!("closing {}", x); }) .await }); println!("Bye, world!"); }
mod cli; mod modmg; mod sessionapp; mod sm_xdg; mod wmmanager; use clap::{App, Arg}; use sessionapp::SessionApplication; #[tokio::main] async fn main() { let matches = App::new("LDE SESSION") .version("1.0") .author("KOOMPI. koompi@gmail.com") .about("Sesssion Manager. ") .arg( Arg::with_name("config") .short("c") .long("--config") .value_name("FILE") .help("Configuration file path.") .takes_value(true), ) .arg( Arg::with_name("find") .short("-f") .long("--find") .value_name("program") .help("Find a program in a system"), ) .arg( Arg::with_name("wm") .short("-w") .long("--window-manager") .value_name("FILE") .help("Window manager to use."), ) .get_matches(); if let Some(val) = matches.value_of("find") { println!("find program: {}", val); let status = if wmmanager::find_program(val) { println!("found program "); true } else { println!("program not found"); false }; println!("Status: {}", status); } let mut session = SessionApplication::new(); session.startup(); session.exec(); }
mod read_util; use std::collections::HashMap; use std::io::{Read, Error as IOError}; use crate::read_util::RawDataRead; pub const SHADER_LIGHT_MAPPED_GENERIC: &str = "lightmappedgeneric"; pub const SHADER_VERTEX_LIT_GENERIC: &str = "vertexlitgeneric"; pub const SHADER_UNLIT_GENERIC: &str = "unlitgeneric"; pub const SHADER_ENVMAP_TINT: &str = "envmaptint"; pub const SHADER_WORLD_VERTEX_TRANSITION: &str = "worldvertextransition"; pub const SHADER_WATER: &str = "water"; pub const BASE_TEXTURE_NAME: &str = "basetexture"; pub const PATCH: &str = "patch"; pub const PATCH_INCLUDE: &str = "include"; #[allow(dead_code)] const PATCH_INSERT: &str = "insert"; #[derive(Debug)] pub enum VMTError { IOError(IOError), FileError(String) } pub struct VMTMaterial { shader_name: String, values: HashMap<String, String> } impl VMTMaterial { pub fn new(reader: &mut dyn Read, length: u32) -> Result<Self, VMTError> { let mut values = HashMap::<String, String>::new(); let data = reader.read_data(length as usize).map_err(VMTError::IOError)?; let mut text = String::from_utf8(data.to_vec()).map_err(|_e| VMTError::FileError("Could not read text".to_string()))?; text = text.replace("\r\n", "\n"); text = text.replace('\t', " "); text = text.trim_end_matches('\0').to_string(); let block_start = text.find('{').ok_or_else(|| VMTError::FileError("Could not find start of material block".to_string()))?; let mut shader_name: String = String::new(); let shader_name_lines = (&text[..block_start]).split('\n'); for line in shader_name_lines { let line = remove_line_comments(line); if !line.trim().is_empty() { shader_name = line.replace("\"", "").trim().to_lowercase(); } } if shader_name != SHADER_LIGHT_MAPPED_GENERIC && shader_name != PATCH && shader_name != SHADER_UNLIT_GENERIC && shader_name != SHADER_VERTEX_LIT_GENERIC && shader_name != SHADER_ENVMAP_TINT && shader_name != SHADER_WORLD_VERTEX_TRANSITION && shader_name != SHADER_WATER { println!("Found unsupported shader: \"{}\"", shader_name); } let block_end = text.find('}').ok_or_else(|| VMTError::FileError("Could not find end of material block".to_string()))?; let block = &text[block_start .. block_end]; let lines = block.split('\n'); for line in lines { let trimmed_line = line.trim().replace(&['$', '%', '"', '\''][..], ""); if trimmed_line.is_empty() || trimmed_line == "{" || trimmed_line == "}" || trimmed_line == PATCH_INCLUDE { continue; } let key_end_opt = trimmed_line.find(' '); if key_end_opt.is_none() { continue; } let key_end = key_end_opt.unwrap(); let key = (&trimmed_line[.. key_end]).trim().to_lowercase(); let value = remove_line_comments(&trimmed_line[key_end + 1 ..]).trim().to_string(); values.insert(key, value); } Ok(Self { shader_name, values }) } pub fn get_value(&self, key: &str) -> Option<&str> { self.values.get(key).map(|v| v.as_str()) } pub fn get_shader(&self) -> &str { self.shader_name.as_str() } pub fn get_base_texture_name(&self) -> Option<&str> { self.get_value(BASE_TEXTURE_NAME) } pub fn get_patch_base(&self) -> Option<&str> { self.get_value(PATCH_INCLUDE) } pub fn is_patch(&self) -> bool { self.shader_name == PATCH } pub fn apply_patch(&mut self, patch: &VMTMaterial) { if !patch.is_patch() { panic!("Material must be a patch"); } self.values.extend(patch.values.iter().map(|(key, value)| (key.clone(), value.clone()))); } } fn remove_line_comments(text: &str) -> &str { let comment_start = text.find("//"); if comment_start.is_none() { return text; } &text[..comment_start.unwrap()] }
use crate::utils; use regex::Regex; struct Passport { byr: Option<String>, iyr: Option<String>, eyr: Option<String>, hgt: Option<String>, hcl: Option<String>, ecl: Option<String>, pid: Option<String>, cid: Option<String>, } impl Passport { fn new() -> Passport { return Passport { byr: None, iyr: None, eyr: None, hgt: None, hcl: None, ecl: None, pid: None, cid: None, }; } fn is_valid(&self) -> bool { return self.byr.is_some() && self.iyr.is_some() && self.eyr.is_some() && self.hgt.is_some() && self.hcl.is_some() && self.ecl.is_some() && self.pid.is_some(); } fn is_strict_valid(&self) -> bool { if !self.is_valid() { return false; } if !utils::is_numeric_string_in_range(self.byr.as_ref().unwrap(), 1920, 2002) { return false; } if !utils::is_numeric_string_in_range(self.iyr.as_ref().unwrap(), 2010, 2020) { return false; } if !utils::is_numeric_string_in_range(self.eyr.as_ref().unwrap(), 2020, 2030) { return false; } if let Some(height) = self.hgt.as_ref() { if height.ends_with("cm") { if let Some(height_value_str) = height.strip_suffix("cm") { if !utils::is_numeric_string_in_range(height_value_str, 150, 193) { return false; } } else { return false; } } else if height.ends_with("in") { if let Some(height_value_str) = height.strip_suffix("in") { if !utils::is_numeric_string_in_range(height_value_str, 59, 76) { return false; } } else { return false; } } else { return false; } } if let Some(hair_colour) = self.hcl.as_ref() { let re = Regex::new(r"#[0-9a-f]").unwrap(); if !re.is_match(hair_colour) { return false; } } if let Some(eye_colour) = self.ecl.as_ref() { match eye_colour.as_str() { "amb" | "blu" | "brn" | "gry" | "grn" | "hzl" | "oth" => {} _ => return false, } } if let Some(passport_id) = self.pid.as_ref() { if passport_id.len() != 9 { return false; } if let Err(_) = passport_id.parse::<i32>() { return false; } } return true; } } #[allow(dead_code)] pub fn problem1() { println!("running problem 4.1:"); if let Ok(lines) = utils::read_lines("data/day4.txt") { let mut passport = Passport::new(); let mut num_valid = 0; for res in lines { if let Ok(line) = res { // end of passport, so check if we got everything if line == "" { if passport.is_valid() { num_valid += 1; } passport = Passport::new(); continue; } for data in line.split(" ") { let pair: Vec<&str> = data.split(":").collect(); let value = String::from(pair[1]); match pair[0] { "byr" => passport.byr = Some(value), "iyr" => passport.iyr = Some(value), "eyr" => passport.eyr = Some(value), "hgt" => passport.hgt = Some(value), "hcl" => passport.hcl = Some(value), "ecl" => passport.ecl = Some(value), "pid" => passport.pid = Some(value), "cid" => passport.cid = Some(value), _ => {} } } } } // check the last passport if passport.is_valid() { num_valid += 1; } println!("Found valid: {}", num_valid); } } #[allow(dead_code)] pub fn problem2() { println!("running problem 4.2:"); if let Ok(lines) = utils::read_lines("data/day4.txt") { let mut passport = Passport::new(); let mut num_valid = 0; for res in lines { if let Ok(line) = res { // end of passport, so check if we got everything if line == "" { if passport.is_strict_valid() { num_valid += 1; } passport = Passport::new(); continue; } for data in line.split(" ") { let pair: Vec<&str> = data.split(":").collect(); let value = String::from(pair[1]); match pair[0] { "byr" => passport.byr = Some(value), "iyr" => passport.iyr = Some(value), "eyr" => passport.eyr = Some(value), "hgt" => passport.hgt = Some(value), "hcl" => passport.hcl = Some(value), "ecl" => passport.ecl = Some(value), "pid" => passport.pid = Some(value), "cid" => passport.cid = Some(value), _ => {} } } } } // check the last passport if passport.is_valid() { num_valid += 1; } println!("Found valid: {}", num_valid); } }
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct FindSimilarFileIndexResults { pub m_FileIndex: u32, pub m_MatchCount: u32, } impl FindSimilarFileIndexResults {} impl ::core::default::Default for FindSimilarFileIndexResults { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for FindSimilarFileIndexResults { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("FindSimilarFileIndexResults").field("m_FileIndex", &self.m_FileIndex).field("m_MatchCount", &self.m_MatchCount).finish() } } impl ::core::cmp::PartialEq for FindSimilarFileIndexResults { fn eq(&self, other: &Self) -> bool { self.m_FileIndex == other.m_FileIndex && self.m_MatchCount == other.m_MatchCount } } impl ::core::cmp::Eq for FindSimilarFileIndexResults {} unsafe impl ::windows::core::Abi for FindSimilarFileIndexResults { type Abi = Self; } pub const FindSimilarResults: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x96236a93_9dbc_11da_9e3f_0011114ae311); #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct GeneratorParametersType(pub i32); pub const RDCGENTYPE_Unused: GeneratorParametersType = GeneratorParametersType(0i32); pub const RDCGENTYPE_FilterMax: GeneratorParametersType = GeneratorParametersType(1i32); impl ::core::convert::From<i32> for GeneratorParametersType { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for GeneratorParametersType { type Abi = Self; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IFindSimilarResults(pub ::windows::core::IUnknown); impl IFindSimilarResults { pub unsafe fn GetSize(&self) -> ::windows::core::Result<u32> { let mut result__: <u32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), &mut result__).from_abi::<u32>(result__) } pub unsafe fn GetNextFileId(&self, numtraitsmatched: *mut u32, similarityfileid: *mut SimilarityFileId) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(numtraitsmatched), ::core::mem::transmute(similarityfileid)).ok() } } unsafe impl ::windows::core::Interface for IFindSimilarResults { type Vtable = IFindSimilarResults_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x96236a81_9dbc_11da_9e3f_0011114ae311); } impl ::core::convert::From<IFindSimilarResults> for ::windows::core::IUnknown { fn from(value: IFindSimilarResults) -> Self { value.0 } } impl ::core::convert::From<&IFindSimilarResults> for ::windows::core::IUnknown { fn from(value: &IFindSimilarResults) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IFindSimilarResults { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IFindSimilarResults { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IFindSimilarResults_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, size: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, numtraitsmatched: *mut u32, similarityfileid: *mut SimilarityFileId) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IRdcComparator(pub ::windows::core::IUnknown); impl IRdcComparator { #[cfg(feature = "Win32_Foundation")] pub unsafe fn Process<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::BOOL>>(&self, endofinput: Param0, endofoutput: *mut super::super::Foundation::BOOL, inputbuffer: *mut RdcBufferPointer, outputbuffer: *mut RdcNeedPointer, rdc_errorcode: *mut RDC_ErrorCode) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), endofinput.into_param().abi(), ::core::mem::transmute(endofoutput), ::core::mem::transmute(inputbuffer), ::core::mem::transmute(outputbuffer), ::core::mem::transmute(rdc_errorcode)).ok() } } unsafe impl ::windows::core::Interface for IRdcComparator { type Vtable = IRdcComparator_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x96236a77_9dbc_11da_9e3f_0011114ae311); } impl ::core::convert::From<IRdcComparator> for ::windows::core::IUnknown { fn from(value: IRdcComparator) -> Self { value.0 } } impl ::core::convert::From<&IRdcComparator> for ::windows::core::IUnknown { fn from(value: &IRdcComparator) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IRdcComparator { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IRdcComparator { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IRdcComparator_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, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, endofinput: super::super::Foundation::BOOL, endofoutput: *mut super::super::Foundation::BOOL, inputbuffer: *mut RdcBufferPointer, outputbuffer: *mut RdcNeedPointer, rdc_errorcode: *mut RDC_ErrorCode) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IRdcFileReader(pub ::windows::core::IUnknown); impl IRdcFileReader { pub unsafe fn GetFileSize(&self) -> ::windows::core::Result<u64> { let mut result__: <u64 as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), &mut result__).from_abi::<u64>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn Read(&self, offsetfilestart: u64, bytestoread: u32, bytesactuallyread: *mut u32, buffer: *mut u8, eof: *mut super::super::Foundation::BOOL) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(offsetfilestart), ::core::mem::transmute(bytestoread), ::core::mem::transmute(bytesactuallyread), ::core::mem::transmute(buffer), ::core::mem::transmute(eof)).ok() } pub unsafe fn GetFilePosition(&self) -> ::windows::core::Result<u64> { let mut result__: <u64 as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), &mut result__).from_abi::<u64>(result__) } } unsafe impl ::windows::core::Interface for IRdcFileReader { type Vtable = IRdcFileReader_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x96236a74_9dbc_11da_9e3f_0011114ae311); } impl ::core::convert::From<IRdcFileReader> for ::windows::core::IUnknown { fn from(value: IRdcFileReader) -> Self { value.0 } } impl ::core::convert::From<&IRdcFileReader> for ::windows::core::IUnknown { fn from(value: &IRdcFileReader) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IRdcFileReader { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IRdcFileReader { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IRdcFileReader_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, filesize: *mut u64) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, offsetfilestart: u64, bytestoread: u32, bytesactuallyread: *mut u32, buffer: *mut u8, eof: *mut super::super::Foundation::BOOL) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, offsetfromstart: *mut u64) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IRdcFileWriter(pub ::windows::core::IUnknown); impl IRdcFileWriter { pub unsafe fn GetFileSize(&self) -> ::windows::core::Result<u64> { let mut result__: <u64 as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), &mut result__).from_abi::<u64>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn Read(&self, offsetfilestart: u64, bytestoread: u32, bytesactuallyread: *mut u32, buffer: *mut u8, eof: *mut super::super::Foundation::BOOL) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(offsetfilestart), ::core::mem::transmute(bytestoread), ::core::mem::transmute(bytesactuallyread), ::core::mem::transmute(buffer), ::core::mem::transmute(eof)).ok() } pub unsafe fn GetFilePosition(&self) -> ::windows::core::Result<u64> { let mut result__: <u64 as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), &mut result__).from_abi::<u64>(result__) } pub unsafe fn Write(&self, offsetfilestart: u64, bytestowrite: u32) -> ::windows::core::Result<u8> { let mut result__: <u8 as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), ::core::mem::transmute(offsetfilestart), ::core::mem::transmute(bytestowrite), &mut result__).from_abi::<u8>(result__) } pub unsafe fn Truncate(&self) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self)).ok() } pub unsafe fn DeleteOnClose(&self) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self)).ok() } } unsafe impl ::windows::core::Interface for IRdcFileWriter { type Vtable = IRdcFileWriter_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x96236a75_9dbc_11da_9e3f_0011114ae311); } impl ::core::convert::From<IRdcFileWriter> for ::windows::core::IUnknown { fn from(value: IRdcFileWriter) -> Self { value.0 } } impl ::core::convert::From<&IRdcFileWriter> for ::windows::core::IUnknown { fn from(value: &IRdcFileWriter) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IRdcFileWriter { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IRdcFileWriter { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } impl ::core::convert::From<IRdcFileWriter> for IRdcFileReader { fn from(value: IRdcFileWriter) -> Self { unsafe { ::core::mem::transmute(value) } } } impl ::core::convert::From<&IRdcFileWriter> for IRdcFileReader { fn from(value: &IRdcFileWriter) -> Self { ::core::convert::From::from(::core::clone::Clone::clone(value)) } } impl<'a> ::windows::core::IntoParam<'a, IRdcFileReader> for IRdcFileWriter { fn into_param(self) -> ::windows::core::Param<'a, IRdcFileReader> { ::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) }) } } impl<'a> ::windows::core::IntoParam<'a, IRdcFileReader> for &IRdcFileWriter { fn into_param(self) -> ::windows::core::Param<'a, IRdcFileReader> { ::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) }) } } #[repr(C)] #[doc(hidden)] pub struct IRdcFileWriter_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, filesize: *mut u64) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, offsetfilestart: u64, bytestoread: u32, bytesactuallyread: *mut u32, buffer: *mut u8, eof: *mut super::super::Foundation::BOOL) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, offsetfromstart: *mut u64) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, offsetfilestart: u64, bytestowrite: u32, buffer: *mut u8) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IRdcGenerator(pub ::windows::core::IUnknown); impl IRdcGenerator { pub unsafe fn GetGeneratorParameters(&self, level: u32) -> ::windows::core::Result<IRdcGeneratorParameters> { let mut result__: <IRdcGeneratorParameters as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(level), &mut result__).from_abi::<IRdcGeneratorParameters>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn Process<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::BOOL>>(&self, endofinput: Param0, endofoutput: *mut super::super::Foundation::BOOL, inputbuffer: *mut RdcBufferPointer, depth: u32, outputbuffers: *mut *mut RdcBufferPointer, rdc_errorcode: *mut RDC_ErrorCode) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), endofinput.into_param().abi(), ::core::mem::transmute(endofoutput), ::core::mem::transmute(inputbuffer), ::core::mem::transmute(depth), ::core::mem::transmute(outputbuffers), ::core::mem::transmute(rdc_errorcode)).ok() } } unsafe impl ::windows::core::Interface for IRdcGenerator { type Vtable = IRdcGenerator_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x96236a73_9dbc_11da_9e3f_0011114ae311); } impl ::core::convert::From<IRdcGenerator> for ::windows::core::IUnknown { fn from(value: IRdcGenerator) -> Self { value.0 } } impl ::core::convert::From<&IRdcGenerator> for ::windows::core::IUnknown { fn from(value: &IRdcGenerator) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IRdcGenerator { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IRdcGenerator { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IRdcGenerator_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, level: u32, igeneratorparameters: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, endofinput: super::super::Foundation::BOOL, endofoutput: *mut super::super::Foundation::BOOL, inputbuffer: *mut RdcBufferPointer, depth: u32, outputbuffers: *mut *mut RdcBufferPointer, rdc_errorcode: *mut RDC_ErrorCode) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IRdcGeneratorFilterMaxParameters(pub ::windows::core::IUnknown); impl IRdcGeneratorFilterMaxParameters { pub unsafe fn GetHorizonSize(&self) -> ::windows::core::Result<u32> { let mut result__: <u32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), &mut result__).from_abi::<u32>(result__) } pub unsafe fn SetHorizonSize(&self, horizonsize: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(horizonsize)).ok() } pub unsafe fn GetHashWindowSize(&self) -> ::windows::core::Result<u32> { let mut result__: <u32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), &mut result__).from_abi::<u32>(result__) } pub unsafe fn SetHashWindowSize(&self, hashwindowsize: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), ::core::mem::transmute(hashwindowsize)).ok() } } unsafe impl ::windows::core::Interface for IRdcGeneratorFilterMaxParameters { type Vtable = IRdcGeneratorFilterMaxParameters_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x96236a72_9dbc_11da_9e3f_0011114ae311); } impl ::core::convert::From<IRdcGeneratorFilterMaxParameters> for ::windows::core::IUnknown { fn from(value: IRdcGeneratorFilterMaxParameters) -> Self { value.0 } } impl ::core::convert::From<&IRdcGeneratorFilterMaxParameters> for ::windows::core::IUnknown { fn from(value: &IRdcGeneratorFilterMaxParameters) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IRdcGeneratorFilterMaxParameters { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IRdcGeneratorFilterMaxParameters { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IRdcGeneratorFilterMaxParameters_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, horizonsize: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, horizonsize: u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, hashwindowsize: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, hashwindowsize: u32) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IRdcGeneratorParameters(pub ::windows::core::IUnknown); impl IRdcGeneratorParameters { pub unsafe fn GetGeneratorParametersType(&self) -> ::windows::core::Result<GeneratorParametersType> { let mut result__: <GeneratorParametersType as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), &mut result__).from_abi::<GeneratorParametersType>(result__) } pub unsafe fn GetParametersVersion(&self, currentversion: *mut u32, minimumcompatibleappversion: *mut u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(currentversion), ::core::mem::transmute(minimumcompatibleappversion)).ok() } pub unsafe fn GetSerializeSize(&self) -> ::windows::core::Result<u32> { let mut result__: <u32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), &mut result__).from_abi::<u32>(result__) } pub unsafe fn Serialize(&self, size: u32, parametersblob: *mut u8, byteswritten: *mut u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), ::core::mem::transmute(size), ::core::mem::transmute(parametersblob), ::core::mem::transmute(byteswritten)).ok() } } unsafe impl ::windows::core::Interface for IRdcGeneratorParameters { type Vtable = IRdcGeneratorParameters_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x96236a71_9dbc_11da_9e3f_0011114ae311); } impl ::core::convert::From<IRdcGeneratorParameters> for ::windows::core::IUnknown { fn from(value: IRdcGeneratorParameters) -> Self { value.0 } } impl ::core::convert::From<&IRdcGeneratorParameters> for ::windows::core::IUnknown { fn from(value: &IRdcGeneratorParameters) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IRdcGeneratorParameters { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IRdcGeneratorParameters { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IRdcGeneratorParameters_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, parameterstype: *mut GeneratorParametersType) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, currentversion: *mut u32, minimumcompatibleappversion: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, size: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, size: u32, parametersblob: *mut u8, byteswritten: *mut u32) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IRdcLibrary(pub ::windows::core::IUnknown); impl IRdcLibrary { pub unsafe fn ComputeDefaultRecursionDepth(&self, filesize: u64) -> ::windows::core::Result<u32> { let mut result__: <u32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(filesize), &mut result__).from_abi::<u32>(result__) } pub unsafe fn CreateGeneratorParameters(&self, parameterstype: GeneratorParametersType, level: u32) -> ::windows::core::Result<IRdcGeneratorParameters> { let mut result__: <IRdcGeneratorParameters as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(parameterstype), ::core::mem::transmute(level), &mut result__).from_abi::<IRdcGeneratorParameters>(result__) } pub unsafe fn OpenGeneratorParameters(&self, size: u32, parametersblob: *const u8) -> ::windows::core::Result<IRdcGeneratorParameters> { let mut result__: <IRdcGeneratorParameters as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), ::core::mem::transmute(size), ::core::mem::transmute(parametersblob), &mut result__).from_abi::<IRdcGeneratorParameters>(result__) } pub unsafe fn CreateGenerator(&self, depth: u32, igeneratorparametersarray: *const ::core::option::Option<IRdcGeneratorParameters>) -> ::windows::core::Result<IRdcGenerator> { let mut result__: <IRdcGenerator as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), ::core::mem::transmute(depth), ::core::mem::transmute(igeneratorparametersarray), &mut result__).from_abi::<IRdcGenerator>(result__) } pub unsafe fn CreateComparator<'a, Param0: ::windows::core::IntoParam<'a, IRdcFileReader>>(&self, iseedsignaturesfile: Param0, comparatorbuffersize: u32) -> ::windows::core::Result<IRdcComparator> { let mut result__: <IRdcComparator as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), iseedsignaturesfile.into_param().abi(), ::core::mem::transmute(comparatorbuffersize), &mut result__).from_abi::<IRdcComparator>(result__) } pub unsafe fn CreateSignatureReader<'a, Param0: ::windows::core::IntoParam<'a, IRdcFileReader>>(&self, ifilereader: Param0) -> ::windows::core::Result<IRdcSignatureReader> { let mut result__: <IRdcSignatureReader as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), ifilereader.into_param().abi(), &mut result__).from_abi::<IRdcSignatureReader>(result__) } pub unsafe fn GetRDCVersion(&self, currentversion: *mut u32, minimumcompatibleappversion: *mut u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).9)(::core::mem::transmute_copy(self), ::core::mem::transmute(currentversion), ::core::mem::transmute(minimumcompatibleappversion)).ok() } } unsafe impl ::windows::core::Interface for IRdcLibrary { type Vtable = IRdcLibrary_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x96236a78_9dbc_11da_9e3f_0011114ae311); } impl ::core::convert::From<IRdcLibrary> for ::windows::core::IUnknown { fn from(value: IRdcLibrary) -> Self { value.0 } } impl ::core::convert::From<&IRdcLibrary> for ::windows::core::IUnknown { fn from(value: &IRdcLibrary) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IRdcLibrary { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IRdcLibrary { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IRdcLibrary_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, filesize: u64, depth: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, parameterstype: GeneratorParametersType, level: u32, igeneratorparameters: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, size: u32, parametersblob: *const u8, igeneratorparameters: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, depth: u32, igeneratorparametersarray: *const ::windows::core::RawPtr, igenerator: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iseedsignaturesfile: ::windows::core::RawPtr, comparatorbuffersize: u32, icomparator: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ifilereader: ::windows::core::RawPtr, isignaturereader: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, currentversion: *mut u32, minimumcompatibleappversion: *mut u32) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IRdcSignatureReader(pub ::windows::core::IUnknown); impl IRdcSignatureReader { pub unsafe fn ReadHeader(&self) -> ::windows::core::Result<RDC_ErrorCode> { let mut result__: <RDC_ErrorCode as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), &mut result__).from_abi::<RDC_ErrorCode>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn ReadSignatures(&self, rdcsignaturepointer: *mut RdcSignaturePointer, endofoutput: *mut super::super::Foundation::BOOL) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(rdcsignaturepointer), ::core::mem::transmute(endofoutput)).ok() } } unsafe impl ::windows::core::Interface for IRdcSignatureReader { type Vtable = IRdcSignatureReader_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x96236a76_9dbc_11da_9e3f_0011114ae311); } impl ::core::convert::From<IRdcSignatureReader> for ::windows::core::IUnknown { fn from(value: IRdcSignatureReader) -> Self { value.0 } } impl ::core::convert::From<&IRdcSignatureReader> for ::windows::core::IUnknown { fn from(value: &IRdcSignatureReader) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IRdcSignatureReader { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IRdcSignatureReader { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IRdcSignatureReader_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, rdc_errorcode: *mut RDC_ErrorCode) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, rdcsignaturepointer: *mut RdcSignaturePointer, endofoutput: *mut super::super::Foundation::BOOL) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IRdcSimilarityGenerator(pub ::windows::core::IUnknown); impl IRdcSimilarityGenerator { pub unsafe fn EnableSimilarity(&self) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self)).ok() } pub unsafe fn Results(&self) -> ::windows::core::Result<SimilarityData> { let mut result__: <SimilarityData as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), &mut result__).from_abi::<SimilarityData>(result__) } } unsafe impl ::windows::core::Interface for IRdcSimilarityGenerator { type Vtable = IRdcSimilarityGenerator_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x96236a80_9dbc_11da_9e3f_0011114ae311); } impl ::core::convert::From<IRdcSimilarityGenerator> for ::windows::core::IUnknown { fn from(value: IRdcSimilarityGenerator) -> Self { value.0 } } impl ::core::convert::From<&IRdcSimilarityGenerator> for ::windows::core::IUnknown { fn from(value: &IRdcSimilarityGenerator) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IRdcSimilarityGenerator { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IRdcSimilarityGenerator { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IRdcSimilarityGenerator_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) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, similaritydata: *mut SimilarityData) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct ISimilarity(pub ::windows::core::IUnknown); impl ISimilarity { #[cfg(feature = "Win32_Foundation")] pub unsafe fn CreateTable<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::BOOL>>(&self, path: Param0, truncate: Param1, securitydescriptor: *const u8, recordsize: u32) -> ::windows::core::Result<RdcCreatedTables> { let mut result__: <RdcCreatedTables as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), path.into_param().abi(), truncate.into_param().abi(), ::core::mem::transmute(securitydescriptor), ::core::mem::transmute(recordsize), &mut result__).from_abi::<RdcCreatedTables>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn CreateTableIndirect<'a, Param0: ::windows::core::IntoParam<'a, ISimilarityTraitsMapping>, Param1: ::windows::core::IntoParam<'a, IRdcFileWriter>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::BOOL>>(&self, mapping: Param0, fileidfile: Param1, truncate: Param2, recordsize: u32) -> ::windows::core::Result<RdcCreatedTables> { let mut result__: <RdcCreatedTables as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), mapping.into_param().abi(), fileidfile.into_param().abi(), truncate.into_param().abi(), ::core::mem::transmute(recordsize), &mut result__).from_abi::<RdcCreatedTables>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn CloseTable<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::BOOL>>(&self, isvalid: Param0) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), isvalid.into_param().abi()).ok() } pub unsafe fn Append(&self, similarityfileid: *const SimilarityFileId, similaritydata: *const SimilarityData) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), ::core::mem::transmute(similarityfileid), ::core::mem::transmute(similaritydata)).ok() } pub unsafe fn FindSimilarFileId(&self, similaritydata: *const SimilarityData, numberofmatchesrequired: u16, resultssize: u32) -> ::windows::core::Result<IFindSimilarResults> { let mut result__: <IFindSimilarResults as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), ::core::mem::transmute(similaritydata), ::core::mem::transmute(numberofmatchesrequired), ::core::mem::transmute(resultssize), &mut result__).from_abi::<IFindSimilarResults>(result__) } pub unsafe fn CopyAndSwap<'a, Param0: ::windows::core::IntoParam<'a, ISimilarity>, Param1: ::windows::core::IntoParam<'a, ISimilarityReportProgress>>(&self, newsimilaritytables: Param0, reportprogress: Param1) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), newsimilaritytables.into_param().abi(), reportprogress.into_param().abi()).ok() } pub unsafe fn GetRecordCount(&self) -> ::windows::core::Result<u32> { let mut result__: <u32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).9)(::core::mem::transmute_copy(self), &mut result__).from_abi::<u32>(result__) } } unsafe impl ::windows::core::Interface for ISimilarity { type Vtable = ISimilarity_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x96236a83_9dbc_11da_9e3f_0011114ae311); } impl ::core::convert::From<ISimilarity> for ::windows::core::IUnknown { fn from(value: ISimilarity) -> Self { value.0 } } impl ::core::convert::From<&ISimilarity> for ::windows::core::IUnknown { fn from(value: &ISimilarity) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ISimilarity { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a ISimilarity { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct ISimilarity_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, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, path: super::super::Foundation::PWSTR, truncate: super::super::Foundation::BOOL, securitydescriptor: *const u8, recordsize: u32, isnew: *mut RdcCreatedTables) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, mapping: ::windows::core::RawPtr, fileidfile: ::windows::core::RawPtr, truncate: super::super::Foundation::BOOL, recordsize: u32, isnew: *mut RdcCreatedTables) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, isvalid: super::super::Foundation::BOOL) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, similarityfileid: *const SimilarityFileId, similaritydata: *const SimilarityData) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, similaritydata: *const SimilarityData, numberofmatchesrequired: u16, resultssize: u32, findsimilarresults: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, newsimilaritytables: ::windows::core::RawPtr, reportprogress: ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, recordcount: *mut u32) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct ISimilarityFileIdTable(pub ::windows::core::IUnknown); impl ISimilarityFileIdTable { #[cfg(feature = "Win32_Foundation")] pub unsafe fn CreateTable<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::BOOL>>(&self, path: Param0, truncate: Param1, securitydescriptor: *const u8, recordsize: u32) -> ::windows::core::Result<RdcCreatedTables> { let mut result__: <RdcCreatedTables as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), path.into_param().abi(), truncate.into_param().abi(), ::core::mem::transmute(securitydescriptor), ::core::mem::transmute(recordsize), &mut result__).from_abi::<RdcCreatedTables>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn CreateTableIndirect<'a, Param0: ::windows::core::IntoParam<'a, IRdcFileWriter>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::BOOL>>(&self, fileidfile: Param0, truncate: Param1, recordsize: u32) -> ::windows::core::Result<RdcCreatedTables> { let mut result__: <RdcCreatedTables as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), fileidfile.into_param().abi(), truncate.into_param().abi(), ::core::mem::transmute(recordsize), &mut result__).from_abi::<RdcCreatedTables>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn CloseTable<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::BOOL>>(&self, isvalid: Param0) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), isvalid.into_param().abi()).ok() } pub unsafe fn Append(&self, similarityfileid: *const SimilarityFileId) -> ::windows::core::Result<u32> { let mut result__: <u32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), ::core::mem::transmute(similarityfileid), &mut result__).from_abi::<u32>(result__) } pub unsafe fn Lookup(&self, similarityfileindex: u32) -> ::windows::core::Result<SimilarityFileId> { let mut result__: <SimilarityFileId as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), ::core::mem::transmute(similarityfileindex), &mut result__).from_abi::<SimilarityFileId>(result__) } pub unsafe fn Invalidate(&self, similarityfileindex: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), ::core::mem::transmute(similarityfileindex)).ok() } pub unsafe fn GetRecordCount(&self) -> ::windows::core::Result<u32> { let mut result__: <u32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).9)(::core::mem::transmute_copy(self), &mut result__).from_abi::<u32>(result__) } } unsafe impl ::windows::core::Interface for ISimilarityFileIdTable { type Vtable = ISimilarityFileIdTable_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x96236a7f_9dbc_11da_9e3f_0011114ae311); } impl ::core::convert::From<ISimilarityFileIdTable> for ::windows::core::IUnknown { fn from(value: ISimilarityFileIdTable) -> Self { value.0 } } impl ::core::convert::From<&ISimilarityFileIdTable> for ::windows::core::IUnknown { fn from(value: &ISimilarityFileIdTable) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ISimilarityFileIdTable { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a ISimilarityFileIdTable { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct ISimilarityFileIdTable_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, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, path: super::super::Foundation::PWSTR, truncate: super::super::Foundation::BOOL, securitydescriptor: *const u8, recordsize: u32, isnew: *mut RdcCreatedTables) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, fileidfile: ::windows::core::RawPtr, truncate: super::super::Foundation::BOOL, recordsize: u32, isnew: *mut RdcCreatedTables) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, isvalid: super::super::Foundation::BOOL) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, similarityfileid: *const SimilarityFileId, similarityfileindex: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, similarityfileindex: u32, similarityfileid: *mut SimilarityFileId) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, similarityfileindex: u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, recordcount: *mut u32) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct ISimilarityReportProgress(pub ::windows::core::IUnknown); impl ISimilarityReportProgress { pub unsafe fn ReportProgress(&self, percentcompleted: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(percentcompleted)).ok() } } unsafe impl ::windows::core::Interface for ISimilarityReportProgress { type Vtable = ISimilarityReportProgress_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x96236a7a_9dbc_11da_9e3f_0011114ae311); } impl ::core::convert::From<ISimilarityReportProgress> for ::windows::core::IUnknown { fn from(value: ISimilarityReportProgress) -> Self { value.0 } } impl ::core::convert::From<&ISimilarityReportProgress> for ::windows::core::IUnknown { fn from(value: &ISimilarityReportProgress) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ISimilarityReportProgress { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a ISimilarityReportProgress { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct ISimilarityReportProgress_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, percentcompleted: u32) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct ISimilarityTableDumpState(pub ::windows::core::IUnknown); impl ISimilarityTableDumpState { #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetNextData(&self, resultssize: u32, resultsused: *mut u32, eof: *mut super::super::Foundation::BOOL, results: *mut SimilarityDumpData) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(resultssize), ::core::mem::transmute(resultsused), ::core::mem::transmute(eof), ::core::mem::transmute(results)).ok() } } unsafe impl ::windows::core::Interface for ISimilarityTableDumpState { type Vtable = ISimilarityTableDumpState_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x96236a7b_9dbc_11da_9e3f_0011114ae311); } impl ::core::convert::From<ISimilarityTableDumpState> for ::windows::core::IUnknown { fn from(value: ISimilarityTableDumpState) -> Self { value.0 } } impl ::core::convert::From<&ISimilarityTableDumpState> for ::windows::core::IUnknown { fn from(value: &ISimilarityTableDumpState) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ISimilarityTableDumpState { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a ISimilarityTableDumpState { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct ISimilarityTableDumpState_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, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, resultssize: u32, resultsused: *mut u32, eof: *mut super::super::Foundation::BOOL, results: *mut SimilarityDumpData) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct ISimilarityTraitsMappedView(pub ::windows::core::IUnknown); impl ISimilarityTraitsMappedView { pub unsafe fn Flush(&self) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self)).ok() } pub unsafe fn Unmap(&self) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn Get<'a, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::BOOL>>(&self, index: u64, dirty: Param1, numelements: u32) -> ::windows::core::Result<SimilarityMappedViewInfo> { let mut result__: <SimilarityMappedViewInfo as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), ::core::mem::transmute(index), dirty.into_param().abi(), ::core::mem::transmute(numelements), &mut result__).from_abi::<SimilarityMappedViewInfo>(result__) } pub unsafe fn GetView(&self, mappedpagebegin: *mut *mut u8, mappedpageend: *mut *mut u8) { ::core::mem::transmute((::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), ::core::mem::transmute(mappedpagebegin), ::core::mem::transmute(mappedpageend))) } } unsafe impl ::windows::core::Interface for ISimilarityTraitsMappedView { type Vtable = ISimilarityTraitsMappedView_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x96236a7c_9dbc_11da_9e3f_0011114ae311); } impl ::core::convert::From<ISimilarityTraitsMappedView> for ::windows::core::IUnknown { fn from(value: ISimilarityTraitsMappedView) -> Self { value.0 } } impl ::core::convert::From<&ISimilarityTraitsMappedView> for ::windows::core::IUnknown { fn from(value: &ISimilarityTraitsMappedView) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ISimilarityTraitsMappedView { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a ISimilarityTraitsMappedView { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct ISimilarityTraitsMappedView_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) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, index: u64, dirty: super::super::Foundation::BOOL, numelements: u32, viewinfo: *mut SimilarityMappedViewInfo) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, mappedpagebegin: *mut *mut u8, mappedpageend: *mut *mut u8), ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct ISimilarityTraitsMapping(pub ::windows::core::IUnknown); impl ISimilarityTraitsMapping { pub unsafe fn CloseMapping(&self) { ::core::mem::transmute((::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self))) } pub unsafe fn SetFileSize(&self, filesize: u64) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(filesize)).ok() } pub unsafe fn GetFileSize(&self) -> ::windows::core::Result<u64> { let mut result__: <u64 as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), &mut result__).from_abi::<u64>(result__) } pub unsafe fn OpenMapping(&self, accessmode: RdcMappingAccessMode, begin: u64, end: u64) -> ::windows::core::Result<u64> { let mut result__: <u64 as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), ::core::mem::transmute(accessmode), ::core::mem::transmute(begin), ::core::mem::transmute(end), &mut result__).from_abi::<u64>(result__) } pub unsafe fn ResizeMapping(&self, accessmode: RdcMappingAccessMode, begin: u64, end: u64) -> ::windows::core::Result<u64> { let mut result__: <u64 as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), ::core::mem::transmute(accessmode), ::core::mem::transmute(begin), ::core::mem::transmute(end), &mut result__).from_abi::<u64>(result__) } pub unsafe fn GetPageSize(&self, pagesize: *mut u32) { ::core::mem::transmute((::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), ::core::mem::transmute(pagesize))) } pub unsafe fn CreateView(&self, minimummappedpages: u32, accessmode: RdcMappingAccessMode) -> ::windows::core::Result<ISimilarityTraitsMappedView> { let mut result__: <ISimilarityTraitsMappedView as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).9)(::core::mem::transmute_copy(self), ::core::mem::transmute(minimummappedpages), ::core::mem::transmute(accessmode), &mut result__).from_abi::<ISimilarityTraitsMappedView>(result__) } } unsafe impl ::windows::core::Interface for ISimilarityTraitsMapping { type Vtable = ISimilarityTraitsMapping_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x96236a7d_9dbc_11da_9e3f_0011114ae311); } impl ::core::convert::From<ISimilarityTraitsMapping> for ::windows::core::IUnknown { fn from(value: ISimilarityTraitsMapping) -> Self { value.0 } } impl ::core::convert::From<&ISimilarityTraitsMapping> for ::windows::core::IUnknown { fn from(value: &ISimilarityTraitsMapping) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ISimilarityTraitsMapping { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a ISimilarityTraitsMapping { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct ISimilarityTraitsMapping_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), pub unsafe extern "system" fn(this: ::windows::core::RawPtr, filesize: u64) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, filesize: *mut u64) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, accessmode: RdcMappingAccessMode, begin: u64, end: u64, actualend: *mut u64) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, accessmode: RdcMappingAccessMode, begin: u64, end: u64, actualend: *mut u64) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pagesize: *mut u32), pub unsafe extern "system" fn(this: ::windows::core::RawPtr, minimummappedpages: u32, accessmode: RdcMappingAccessMode, mappedview: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct ISimilarityTraitsTable(pub ::windows::core::IUnknown); impl ISimilarityTraitsTable { #[cfg(feature = "Win32_Foundation")] pub unsafe fn CreateTable<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::BOOL>>(&self, path: Param0, truncate: Param1, securitydescriptor: *const u8) -> ::windows::core::Result<RdcCreatedTables> { let mut result__: <RdcCreatedTables as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), path.into_param().abi(), truncate.into_param().abi(), ::core::mem::transmute(securitydescriptor), &mut result__).from_abi::<RdcCreatedTables>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn CreateTableIndirect<'a, Param0: ::windows::core::IntoParam<'a, ISimilarityTraitsMapping>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::BOOL>>(&self, mapping: Param0, truncate: Param1) -> ::windows::core::Result<RdcCreatedTables> { let mut result__: <RdcCreatedTables as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), mapping.into_param().abi(), truncate.into_param().abi(), &mut result__).from_abi::<RdcCreatedTables>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn CloseTable<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::BOOL>>(&self, isvalid: Param0) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), isvalid.into_param().abi()).ok() } pub unsafe fn Append(&self, data: *const SimilarityData, fileindex: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), ::core::mem::transmute(data), ::core::mem::transmute(fileindex)).ok() } pub unsafe fn FindSimilarFileIndex(&self, similaritydata: *const SimilarityData, numberofmatchesrequired: u16, findsimilarfileindexresults: *mut FindSimilarFileIndexResults, resultssize: u32, resultsused: *mut u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), ::core::mem::transmute(similaritydata), ::core::mem::transmute(numberofmatchesrequired), ::core::mem::transmute(findsimilarfileindexresults), ::core::mem::transmute(resultssize), ::core::mem::transmute(resultsused)).ok() } pub unsafe fn BeginDump(&self) -> ::windows::core::Result<ISimilarityTableDumpState> { let mut result__: <ISimilarityTableDumpState as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), &mut result__).from_abi::<ISimilarityTableDumpState>(result__) } pub unsafe fn GetLastIndex(&self) -> ::windows::core::Result<u32> { let mut result__: <u32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).9)(::core::mem::transmute_copy(self), &mut result__).from_abi::<u32>(result__) } } unsafe impl ::windows::core::Interface for ISimilarityTraitsTable { type Vtable = ISimilarityTraitsTable_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x96236a7e_9dbc_11da_9e3f_0011114ae311); } impl ::core::convert::From<ISimilarityTraitsTable> for ::windows::core::IUnknown { fn from(value: ISimilarityTraitsTable) -> Self { value.0 } } impl ::core::convert::From<&ISimilarityTraitsTable> for ::windows::core::IUnknown { fn from(value: &ISimilarityTraitsTable) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ISimilarityTraitsTable { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a ISimilarityTraitsTable { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct ISimilarityTraitsTable_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, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, path: super::super::Foundation::PWSTR, truncate: super::super::Foundation::BOOL, securitydescriptor: *const u8, isnew: *mut RdcCreatedTables) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, mapping: ::windows::core::RawPtr, truncate: super::super::Foundation::BOOL, isnew: *mut RdcCreatedTables) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, isvalid: super::super::Foundation::BOOL) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, data: *const SimilarityData, fileindex: u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, similaritydata: *const SimilarityData, numberofmatchesrequired: u16, findsimilarfileindexresults: *mut FindSimilarFileIndexResults, resultssize: u32, resultsused: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, similaritytabledumpstate: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, fileindex: *mut u32) -> ::windows::core::HRESULT, ); pub const MSRDC_DEFAULT_COMPAREBUFFER: u32 = 3200000u32; pub const MSRDC_DEFAULT_HASHWINDOWSIZE_1: u32 = 48u32; pub const MSRDC_DEFAULT_HASHWINDOWSIZE_N: u32 = 2u32; pub const MSRDC_DEFAULT_HORIZONSIZE_1: u32 = 1024u32; pub const MSRDC_DEFAULT_HORIZONSIZE_N: u32 = 128u32; pub const MSRDC_MAXIMUM_COMPAREBUFFER: u32 = 1073741824u32; pub const MSRDC_MAXIMUM_DEPTH: u32 = 8u32; pub const MSRDC_MAXIMUM_HASHWINDOWSIZE: u32 = 96u32; pub const MSRDC_MAXIMUM_HORIZONSIZE: u32 = 16384u32; pub const MSRDC_MAXIMUM_MATCHESREQUIRED: u32 = 16u32; pub const MSRDC_MAXIMUM_TRAITVALUE: u32 = 63u32; pub const MSRDC_MINIMUM_COMPAREBUFFER: u32 = 100000u32; pub const MSRDC_MINIMUM_COMPATIBLE_APP_VERSION: u32 = 65536u32; pub const MSRDC_MINIMUM_DEPTH: u32 = 1u32; pub const MSRDC_MINIMUM_HASHWINDOWSIZE: u32 = 2u32; pub const MSRDC_MINIMUM_HORIZONSIZE: u32 = 128u32; pub const MSRDC_MINIMUM_INPUTBUFFERSIZE: u32 = 1024u32; pub const MSRDC_MINIMUM_MATCHESREQUIRED: u32 = 1u32; pub const MSRDC_SIGNATURE_HASHSIZE: u32 = 16u32; pub const MSRDC_VERSION: u32 = 65536u32; pub const RDCE_TABLE_CORRUPT: u32 = 2147745794u32; pub const RDCE_TABLE_FULL: u32 = 2147745793u32; #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct RDC_ErrorCode(pub i32); pub const RDC_NoError: RDC_ErrorCode = RDC_ErrorCode(0i32); pub const RDC_HeaderVersionNewer: RDC_ErrorCode = RDC_ErrorCode(1i32); pub const RDC_HeaderVersionOlder: RDC_ErrorCode = RDC_ErrorCode(2i32); pub const RDC_HeaderMissingOrCorrupt: RDC_ErrorCode = RDC_ErrorCode(3i32); pub const RDC_HeaderWrongType: RDC_ErrorCode = RDC_ErrorCode(4i32); pub const RDC_DataMissingOrCorrupt: RDC_ErrorCode = RDC_ErrorCode(5i32); pub const RDC_DataTooManyRecords: RDC_ErrorCode = RDC_ErrorCode(6i32); pub const RDC_FileChecksumMismatch: RDC_ErrorCode = RDC_ErrorCode(7i32); pub const RDC_ApplicationError: RDC_ErrorCode = RDC_ErrorCode(8i32); pub const RDC_Aborted: RDC_ErrorCode = RDC_ErrorCode(9i32); pub const RDC_Win32Error: RDC_ErrorCode = RDC_ErrorCode(10i32); impl ::core::convert::From<i32> for RDC_ErrorCode { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for RDC_ErrorCode { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct RdcBufferPointer { pub m_Size: u32, pub m_Used: u32, pub m_Data: *mut u8, } impl RdcBufferPointer {} impl ::core::default::Default for RdcBufferPointer { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for RdcBufferPointer { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("RdcBufferPointer").field("m_Size", &self.m_Size).field("m_Used", &self.m_Used).field("m_Data", &self.m_Data).finish() } } impl ::core::cmp::PartialEq for RdcBufferPointer { fn eq(&self, other: &Self) -> bool { self.m_Size == other.m_Size && self.m_Used == other.m_Used && self.m_Data == other.m_Data } } impl ::core::cmp::Eq for RdcBufferPointer {} unsafe impl ::windows::core::Abi for RdcBufferPointer { type Abi = Self; } pub const RdcComparator: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x96236a8b_9dbc_11da_9e3f_0011114ae311); #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct RdcCreatedTables(pub i32); pub const RDCTABLE_InvalidOrUnknown: RdcCreatedTables = RdcCreatedTables(0i32); pub const RDCTABLE_Existing: RdcCreatedTables = RdcCreatedTables(1i32); pub const RDCTABLE_New: RdcCreatedTables = RdcCreatedTables(2i32); impl ::core::convert::From<i32> for RdcCreatedTables { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for RdcCreatedTables { type Abi = Self; } pub const RdcFileReader: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x96236a89_9dbc_11da_9e3f_0011114ae311); pub const RdcGenerator: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x96236a88_9dbc_11da_9e3f_0011114ae311); pub const RdcGeneratorFilterMaxParameters: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x96236a87_9dbc_11da_9e3f_0011114ae311); pub const RdcGeneratorParameters: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x96236a86_9dbc_11da_9e3f_0011114ae311); pub const RdcLibrary: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x96236a85_9dbc_11da_9e3f_0011114ae311); #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct RdcMappingAccessMode(pub i32); pub const RDCMAPPING_Undefined: RdcMappingAccessMode = RdcMappingAccessMode(0i32); pub const RDCMAPPING_ReadOnly: RdcMappingAccessMode = RdcMappingAccessMode(1i32); pub const RDCMAPPING_ReadWrite: RdcMappingAccessMode = RdcMappingAccessMode(2i32); impl ::core::convert::From<i32> for RdcMappingAccessMode { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for RdcMappingAccessMode { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct RdcNeed { pub m_BlockType: RdcNeedType, pub m_FileOffset: u64, pub m_BlockLength: u64, } impl RdcNeed {} impl ::core::default::Default for RdcNeed { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for RdcNeed { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("RdcNeed").field("m_BlockType", &self.m_BlockType).field("m_FileOffset", &self.m_FileOffset).field("m_BlockLength", &self.m_BlockLength).finish() } } impl ::core::cmp::PartialEq for RdcNeed { fn eq(&self, other: &Self) -> bool { self.m_BlockType == other.m_BlockType && self.m_FileOffset == other.m_FileOffset && self.m_BlockLength == other.m_BlockLength } } impl ::core::cmp::Eq for RdcNeed {} unsafe impl ::windows::core::Abi for RdcNeed { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct RdcNeedPointer { pub m_Size: u32, pub m_Used: u32, pub m_Data: *mut RdcNeed, } impl RdcNeedPointer {} impl ::core::default::Default for RdcNeedPointer { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for RdcNeedPointer { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("RdcNeedPointer").field("m_Size", &self.m_Size).field("m_Used", &self.m_Used).field("m_Data", &self.m_Data).finish() } } impl ::core::cmp::PartialEq for RdcNeedPointer { fn eq(&self, other: &Self) -> bool { self.m_Size == other.m_Size && self.m_Used == other.m_Used && self.m_Data == other.m_Data } } impl ::core::cmp::Eq for RdcNeedPointer {} unsafe impl ::windows::core::Abi for RdcNeedPointer { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct RdcNeedType(pub i32); pub const RDCNEED_SOURCE: RdcNeedType = RdcNeedType(0i32); pub const RDCNEED_TARGET: RdcNeedType = RdcNeedType(1i32); pub const RDCNEED_SEED: RdcNeedType = RdcNeedType(2i32); pub const RDCNEED_SEED_MAX: RdcNeedType = RdcNeedType(255i32); impl ::core::convert::From<i32> for RdcNeedType { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for RdcNeedType { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct RdcSignature { pub m_Signature: [u8; 16], pub m_BlockLength: u16, } impl RdcSignature {} impl ::core::default::Default for RdcSignature { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for RdcSignature { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("RdcSignature").field("m_Signature", &self.m_Signature).field("m_BlockLength", &self.m_BlockLength).finish() } } impl ::core::cmp::PartialEq for RdcSignature { fn eq(&self, other: &Self) -> bool { self.m_Signature == other.m_Signature && self.m_BlockLength == other.m_BlockLength } } impl ::core::cmp::Eq for RdcSignature {} unsafe impl ::windows::core::Abi for RdcSignature { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct RdcSignaturePointer { pub m_Size: u32, pub m_Used: u32, pub m_Data: *mut RdcSignature, } impl RdcSignaturePointer {} impl ::core::default::Default for RdcSignaturePointer { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for RdcSignaturePointer { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("RdcSignaturePointer").field("m_Size", &self.m_Size).field("m_Used", &self.m_Used).field("m_Data", &self.m_Data).finish() } } impl ::core::cmp::PartialEq for RdcSignaturePointer { fn eq(&self, other: &Self) -> bool { self.m_Size == other.m_Size && self.m_Used == other.m_Used && self.m_Data == other.m_Data } } impl ::core::cmp::Eq for RdcSignaturePointer {} unsafe impl ::windows::core::Abi for RdcSignaturePointer { type Abi = Self; } pub const RdcSignatureReader: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x96236a8a_9dbc_11da_9e3f_0011114ae311); pub const RdcSimilarityGenerator: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x96236a92_9dbc_11da_9e3f_0011114ae311); pub const Similarity: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x96236a91_9dbc_11da_9e3f_0011114ae311); #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct SimilarityData { pub m_Data: [u8; 16], } impl SimilarityData {} impl ::core::default::Default for SimilarityData { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for SimilarityData { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("SimilarityData").field("m_Data", &self.m_Data).finish() } } impl ::core::cmp::PartialEq for SimilarityData { fn eq(&self, other: &Self) -> bool { self.m_Data == other.m_Data } } impl ::core::cmp::Eq for SimilarityData {} unsafe impl ::windows::core::Abi for SimilarityData { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct SimilarityDumpData { pub m_FileIndex: u32, pub m_Data: SimilarityData, } impl SimilarityDumpData {} impl ::core::default::Default for SimilarityDumpData { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for SimilarityDumpData { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("SimilarityDumpData").field("m_FileIndex", &self.m_FileIndex).field("m_Data", &self.m_Data).finish() } } impl ::core::cmp::PartialEq for SimilarityDumpData { fn eq(&self, other: &Self) -> bool { self.m_FileIndex == other.m_FileIndex && self.m_Data == other.m_Data } } impl ::core::cmp::Eq for SimilarityDumpData {} unsafe impl ::windows::core::Abi for SimilarityDumpData { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct SimilarityFileId { pub m_FileId: [u8; 32], } impl SimilarityFileId {} impl ::core::default::Default for SimilarityFileId { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for SimilarityFileId { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("SimilarityFileId").field("m_FileId", &self.m_FileId).finish() } } impl ::core::cmp::PartialEq for SimilarityFileId { fn eq(&self, other: &Self) -> bool { self.m_FileId == other.m_FileId } } impl ::core::cmp::Eq for SimilarityFileId {} unsafe impl ::windows::core::Abi for SimilarityFileId { type Abi = Self; } pub const SimilarityFileIdMaxSize: u32 = 32u32; pub const SimilarityFileIdMinSize: u32 = 4u32; pub const SimilarityFileIdTable: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x96236a90_9dbc_11da_9e3f_0011114ae311); #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct SimilarityMappedViewInfo { pub m_Data: *mut u8, pub m_Length: u32, } impl SimilarityMappedViewInfo {} impl ::core::default::Default for SimilarityMappedViewInfo { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for SimilarityMappedViewInfo { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("SimilarityMappedViewInfo").field("m_Data", &self.m_Data).field("m_Length", &self.m_Length).finish() } } impl ::core::cmp::PartialEq for SimilarityMappedViewInfo { fn eq(&self, other: &Self) -> bool { self.m_Data == other.m_Data && self.m_Length == other.m_Length } } impl ::core::cmp::Eq for SimilarityMappedViewInfo {} unsafe impl ::windows::core::Abi for SimilarityMappedViewInfo { type Abi = Self; } pub const SimilarityReportProgress: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x96236a8d_9dbc_11da_9e3f_0011114ae311); pub const SimilarityTableDumpState: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x96236a8e_9dbc_11da_9e3f_0011114ae311); pub const SimilarityTraitsMappedView: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x96236a95_9dbc_11da_9e3f_0011114ae311); pub const SimilarityTraitsMapping: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x96236a94_9dbc_11da_9e3f_0011114ae311); pub const SimilarityTraitsTable: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x96236a8f_9dbc_11da_9e3f_0011114ae311);
// This file is part of linux-epoll. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/linux-epoll/master/COPYRIGHT. No part of linux-epoll, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file. // Copyright © 2019 The developers of linux-epoll. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/linux-epoll/master/COPYRIGHT. // /// Error occuring on completion of a coroutine. #[derive(Debug)] pub enum CompleteError { /// An `io::Error` was converted from some other cause (eg from using a third-party library that wraps implementations of `io::Read` and `io::Write`). Undifferentiated(io::Error), /// A socket read failed with an irrecoverable `io::Error` (not `Interupted` or `WouldBlock`). SocketRead(io::Error), /// A socket write failed with an irrecoverable `io::Error` (not `Interupted` or `WouldBlock`). SocketWrite(io::Error), /// A socket vectored read failed with an irrecoverable `io::Error` (not `Interupted` or `WouldBlock`). SocketVectoredRead(io::Error), /// A socket vectored write failed with an irrecoverable `io::Error` (not `Interupted` or `WouldBlock`). SocketVectoredWrite(io::Error), /// A socket read, socket write, socket vectored read or socket vectored write would have blocked; after waiting for input or output to become available with epoll (Event Poll), the connection closed with an error. ClosedWithError, /// A socket read, socket write, socket vectored read or socket vectored write would have blocked; after waiting for input or output to become available with epoll (Event Poll), the remote peer cleanly closed the connection. /// /// This can also happen for TCP 'half-close' shutdowns (which are near useless on modern socket protocols that use TLS). RemotePeerClosedCleanly, /// The coroutine managing the socket was killed. /// /// Typically this is because the parent that owns it is being dropped. Killed, /// An error relating to TLS occurred. Tls(TlsInputOutputError), /// Invalid data was supplied. InvalidDataSupplied(String), /// A protocol violation or error occurred. ProtocolViolation(Box<dyn error::Error + 'static>), } impl Display for CompleteError { #[inline(always)] fn fmt(&self, f: &mut Formatter) -> fmt::Result { Debug::fmt(self, f) } } impl error::Error for CompleteError { #[inline(always)] fn source(&self) -> Option<&(error::Error + 'static)> { use self::CompleteError::*; match self { &Undifferentiated(ref error) => Some(error), &SocketVectoredRead(ref error) => Some(error), &SocketVectoredWrite(ref error) => Some(error), &SocketRead(ref error) => Some(error), &SocketWrite(ref error) => Some(error), &ClosedWithError => None, &RemotePeerClosedCleanly => None, &Killed => None, &Tls(ref error) => Some(error), &InvalidDataSupplied(..) => None, &ProtocolViolation(ref error) => Some(error.deref()), } } } impl From<io::Error> for CompleteError { #[inline(always)] fn from(error: io::Error) -> Self { CompleteError::Undifferentiated(error) } } impl From<TlsInputOutputError> for CompleteError { #[inline(always)] fn from(error: TlsInputOutputError) -> Self { CompleteError::Tls(error) } } impl CompleteError { #[inline(always)] pub(crate) fn convert_to_io_error<T>(result: Result<T, CompleteError>) -> Result<T, io::Error> { use self::CompleteError::*; use self::ErrorKind::*; match result { Ok(value) => Ok(value), Err(complete_error) => Err ( match complete_error { Killed => io::Error::from(ConnectionAborted), Undifferentiated(io_error) | SocketRead(io_error) | SocketWrite(io_error) | SocketVectoredRead(io_error) | SocketVectoredWrite(io_error) => io_error, _ => io::Error::from(Other), } ) } } }
#![allow(dead_code)] use crate::{aocbail, utils}; use utils::{AOCResult, AOCError}; use std::collections::HashSet; use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; pub struct CombatGame { p1: Vec<usize>, p2: Vec<usize>, cache: HashSet<u64>, recurse: bool, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Player { P1, P2 } impl CombatGame { pub fn subgame(&self, p1: usize, p2: usize) -> CombatGame { CombatGame { p1: self.p1[..p1].to_vec(), p2: self.p2[..p2].to_vec(), cache: HashSet::new(), recurse: true, } } pub fn load(filename: &str, recurse: bool) -> AOCResult<CombatGame> { let mut game = CombatGame { p1: Vec::new(), p2: Vec::new(), cache: HashSet::new(), recurse, }; let mut player_ref = &mut game.p1; let input = utils::get_input(filename); for line in input { match line.as_str() { "Player 1:" => { player_ref = &mut game.p1; }, "Player 2:" => { player_ref = &mut game.p2; }, "" => {}, _ => { player_ref.push(line.parse::<usize>()?) } } } Ok(game) } pub fn step(&mut self) -> Option<Player> { if self.p1.len() == 0 { return Some(Player::P2); } else if self.p2.len() == 0 { return Some(Player::P1); } let mut s = DefaultHasher::new(); self.p1.hash(&mut s); self.p2.hash(&mut s); let round_hash = s.finish(); if self.cache.contains(&round_hash) { return Some(Player::P1) } self.cache.insert(round_hash); let card1 = self.p1.remove(0); let card2 = self.p2.remove(0); match if self.recurse && self.p1.len() >= card1 && self.p2.len() >= card2 { self.subgame(card1, card2).play().0 } else if card1 > card2 { Player::P1 } else { Player::P2 } { Player::P1 => {self.p1.push(card1); self.p1.push(card2);}, Player::P2 => {self.p2.push(card2); self.p2.push(card1);}, }; None } fn score(&self, player: Player) -> usize { let winner = match player { Player::P1 => &self.p1, Player::P2 => &self.p2, }; winner.iter().enumerate().fold(0, |a, (i,card)| a + card * (winner.len()-i)) } pub fn play(&mut self) -> (Player, usize) { loop { match self.step() { Some(s) => {return (s, self.score(s));}, None => () } } } } pub fn day22() { let mut game = CombatGame::load("day22", false).unwrap(); println!("crab_combat part 1: {:?}", game.play()); let mut game = CombatGame::load("day22", true).unwrap(); println!("crab_combat part 2: {:?}", game.play()); } #[cfg(test)] mod tests { use crate::day22::*; #[test] pub fn test_day22() { let mut game = CombatGame::load("test_day22", false).unwrap(); assert_eq!( game.play(), (Player::P2, 306), ); let mut game = CombatGame::load("test_day22", true).unwrap(); assert_eq!( game.play(), (Player::P2, 291) ); } }
use super::*; use miniquad::*; use std::{mem, str}; mod pipeline; #[repr(C)] #[derive(Debug, Clone, Copy)] pub struct Vertex { pos: [f32; 2], uv: [f32; 2], color: [u8; 4], } pub fn vertex(pos: glam::Vec2, uv: glam::Vec2, color: Color) -> Vertex { Vertex { pos: [pos.x, pos.y], uv: [uv.x, uv.y], color: [color.r, color.g, color.b, color.a], } } pub struct Gfx2dContext { pipeline: Pipeline, bindings: Bindings, white_texture: Texture, } impl Gfx2dContext { pub fn new(ctx: &mut Context) -> Gfx2dContext { let white_texture = Texture::from_rgba8(ctx, 1, 1, &[255, 255, 255, 255]); let shader = Shader::new( ctx, pipeline::VERT_SOURCE, pipeline::FRAG_SOURCE, pipeline::meta(), ) .unwrap(); let pipeline = Pipeline::with_params( ctx, &[BufferLayout::default()], &[ VertexAttribute::new("in_position", VertexFormat::Float2), VertexAttribute::new("in_texcoords", VertexFormat::Float2), VertexAttribute::new("in_color", VertexFormat::Byte4), ], shader, pipeline::params(), ); let bindings = Bindings { vertex_buffers: vec![], index_buffer: Buffer::index_stream(ctx, IndexType::Int, 0), images: vec![white_texture], }; Gfx2dContext { pipeline, bindings, white_texture, } } pub fn draw(&mut self, ctx: &mut Context, slice: &mut DrawSlice, transform: &Mat2d) { ctx.apply_pipeline(&self.pipeline); slice.batch.update(ctx); let buffer = slice.buffer(); self.bindings.vertex_buffers = vec![buffer]; let uniforms = pipeline::Uniforms { transform: glam::Mat4::from_cols_array_2d(&[ [(transform.0).0, (transform.1).0, 0.0, 0.0], [(transform.0).1, (transform.1).1, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [(transform.0).2, (transform.1).2, 0.0, 1.0], ]), }; ctx.apply_uniforms(&uniforms); let mut draws: Vec<(Texture, Vec<u32>)> = Vec::new(); for cmd in slice.commands() { let indices = cmd .vertex_range .clone() .map(|i| i as u32) .collect::<Vec<u32>>(); let texture = match cmd.texture { None => self.white_texture, Some(t) => t, }; if let Some(found) = draws .iter_mut() .find(|(tex, _)| tex.gl_internal_id() == texture.gl_internal_id()) { found.1.extend(indices); } else { draws.push((texture, indices)); }; } for (texture, indices) in draws.iter() { let size = indices.len() * mem::size_of::<u32>(); let mut delete_buffer = None; if self.bindings.index_buffer.size() < size { delete_buffer.replace(self.bindings.index_buffer); self.bindings.index_buffer = Buffer::index_stream(ctx, IndexType::Int, size); }; self.bindings.index_buffer.update(ctx, indices.as_slice()); self.bindings.images[0] = *texture; ctx.apply_bindings(&self.bindings); ctx.draw(0, indices.len() as i32, 1); if let Some(buffer) = delete_buffer { buffer.delete(); } } } }
use crate::{harddisk::pata, svec::SVec}; // Layouts from OSDev wiki: https://wiki.osdev.org/GPT // // GPT partitioned media layout: // LBA0: Protective Master Boot Record. Kept for backward comptibility. // LBA1: Partition header, identified by 8 bytes "EFI PART", [0x45 0x46 0x49 0x20 0x50 0x41 0x52 0x54] // LBA2..33: Partition table entries // LBA-2: Mirror of partition table // LBA-1: Mirror of partition header // // Partition Table Header layout: // 0x00 (8) - Signature "EFI PART", [0x45 0x46 0x49 0x20 0x50 0x41 0x52 0x54] // 0x08 (4) - GPT Revision // 0x0C (4) - Header size // 0x10 (4) - CRC32 Checksum // 0x14 (4) - Reserved // 0x18 (8) - The LBA containing this header // 0x20 (8) - The LBA of the alternative GPT header // 0x28 (8) - First usable LBA // 0x30 (8) - Last usable LBA // 0x38 (16) - Disk GUID // 0x48 (8) - Starting LBA of Partition Entry array // 0x50 (4) - Number of Partition Entries // 0x54 (4) - Size of a Partition Entry (multiple of 8, usually 0x80 or 0x128) // 0x58 (4) - CRC32 Checksum of Partition Entry array // 0x5C (*) - Reserved, must be zeroed (420 bytes for a 512 byte sector size) // // Partition Entires layout // 0x00 (16) - Partition Type GUID // 0x10 (16) - Unique partition GUID // 0x20 (8) - First LBA // 0x28 (8) - Last LBA // 0x30 (8) - Attribute flags // 0x38 (72) - Partition name const NUM_PARTITIONS: usize = 16; static mut PARTITIONS: SVec<Partition, NUM_PARTITIONS> = SVec::new(); pub struct Partition { index: u8, partition_guid: [u8; 16], start_sector: usize, sector_count: usize, name: SVec<char, 36>, } impl Partition { pub fn index(&self) -> u8 { self.index } pub fn partition_guid(&self) -> &[u8] { &self.partition_guid } pub fn start_sector(&self) -> usize { self.sector_count } pub fn sector_count(&self) -> usize { self.sector_count } pub fn name(&self) -> &SVec<char, 36> { &self.name } } /// Initializes and populates the partition information array for disk 0 /// /// # Safety /// /// Assumes sector size is 512 bytes /// /// The module 'pata' must be initialized before this function is called pub unsafe fn initialize() { let mut buf = [0 as u8; 512]; // Read GPT Header from disk (sector 1) pata::read_sectors(0, 1, &mut buf); // Make sure it's a GPT header if !buf.starts_with(&[0x45, 0x46, 0x49, 0x20, 0x50, 0x41, 0x52, 0x54]) { panic!("No GUID Partition Table found on disk"); } // Assuming the data exists and that it's correct for now // Might want to compare checksums etc // Start sector for partition entries let start_sector = usize::from_le_bytes([ buf[0x48], buf[0x49], buf[0x4A], buf[0x4B], buf[0x4C], buf[0x4D], buf[0x4E], buf[0x4F], ]); // Number of partition entries. Currently not used.. hard coded to max 16 partitions for now //let num_partition_entries = u32::from_le_bytes([buf[0x50], buf[0x51], buf[0x52], buf[0x53]]); // Size of partition entry let partition_entry_size = u32::from_le_bytes([buf[0x54], buf[0x55], buf[0x56], buf[0x57]]); //println!("Start sector for partition entries: {}", start_sector); //println!("Number of partition entries: {}", num_partition_entries); //println!("Size of a partition entry: {}", partition_entry_size); //print!("\n"); // Read partition entries (only the first 16 for now) let num_entries_per_slice = 512 / partition_entry_size; let last_sector = start_sector + (NUM_PARTITIONS / num_entries_per_slice as usize); let mut partition_index: u8 = 0; for s in start_sector..last_sector { // Read disk sector pata::read_sectors(0, s, &mut buf); // Read individual partition entry for p in 0..num_entries_per_slice { let base_offset: usize = (partition_entry_size * p) as usize; let mut offset = base_offset; // Read partition type let mut partition_type_guid = [0 as u8; 16]; partition_type_guid.copy_from_slice(&buf[offset..offset + 0x10]); // Skip unused entries if partition_type_guid == [0; 16] { continue; } // Read partition guid offset = base_offset + 0x10; let mut partition_guid = [0 as u8; 16]; partition_guid.copy_from_slice(&buf[offset..offset + 0x10]); // Read first and last sector offset = base_offset + 0x20; let start_sector = usize::from_le_bytes([ buf[offset], buf[offset + 1], buf[offset + 2], buf[offset + 3], buf[offset + 4], buf[offset + 5], buf[offset + 6], buf[offset + 7], ]); offset = base_offset + 0x28; let last_sector = usize::from_le_bytes([ buf[offset], buf[offset + 1], buf[offset + 2], buf[offset + 3], buf[offset + 4], buf[offset + 5], buf[offset + 6], buf[offset + 7], ]); // Read name let mut name: SVec<char, 36> = SVec::new(); offset = base_offset + 0x38; // EFI spec says 72 bytes (36 characters), however OSDev wiki says never to hardcode this and use {partition_entry_size - offset} instead. // Since we don't support dynamic allocation, use the shortest length. let name_length = core::cmp::min(36, partition_entry_size - 0x38); for _n in 0..name_length { let c = u16::from_le_bytes([buf[offset], buf[offset + 1]]); if c == 0x0000 { break; } offset += 2; name.push(char::from_u32(c as u32).unwrap()); } // Make partition entry let entry = Partition { index: partition_index, partition_guid, start_sector, sector_count: (last_sector - start_sector), name, }; //println!("drive: {}", drive); //println!("partition guid: {:X?}", partition_guid); //println!("start sector: {}", start_sector); //println!("sector count: {}", last_sector-start_sector); //print!("Name: "); //for i in 0..entry.name.len() { // print!("{}", entry.name[i]); //} //print!("\n"); // Push to partition list PARTITIONS.push(entry); // Increase drive index partition_index += 1; } } } pub unsafe fn list_partitions() -> &'static [Partition] { return PARTITIONS.get_slice(); } /// Reads sectors from specified partition /// start_sector starts at 0 pub unsafe fn read_sectors(partition: u8, start_sector: usize, buffer: &mut [u8]) { if buffer.len() % 512 != 0 { panic!("Buffer must be a multiple of 512 bytes"); } let sector_count = PARTITIONS[partition as usize].sector_count; if start_sector >= sector_count { panic!("sector out of range"); } let sector = PARTITIONS[partition as usize].start_sector + start_sector; pata::read_sectors(partition, sector, buffer); } // Writes sectors to specified partition /// start_sector starts at 0 pub unsafe fn write_sectors(partition: u8, start_sector: usize, buffer: &[u8]) { if buffer.len() % 512 != 0 { panic!("Buffer must be a multiple of 512 bytes"); } if buffer.len() % 512 != 0 { panic!("Buffer must be a multiple of 512 bytes"); } let sector_count = PARTITIONS[partition as usize].sector_count; if start_sector >= sector_count { panic!("sector out of range"); } let sector = PARTITIONS[partition as usize].start_sector + start_sector; pata::write_sectors(partition, sector, buffer); }
pub mod mutations; pub mod queries; pub mod service; use std::collections::HashMap; use crate::{ datastore::{prelude::*, Value}, users::service::get_user_path, }; use chrono::prelude::*; use juniper::ID; #[derive(juniper::GraphQLObject)] #[graphql(description = "Story contains tasks that needs to be done for one feature")] pub struct Story { id: ID, /// story title name: String, /// story text description: String, /// story type (Bug, Feature, etc) story_type_id: ID, /// story status (In Progress, Deploy, etc) story_status_id: ID, /// story author creator_id: ID, created_at: DateTime<Utc>, updated_at: DateTime<Utc>, } impl From<Entity> for Story { fn from(entity: Entity) -> Self { Self { id: DbValue::Id(&entity).into(), name: DbValue::Str("name", &entity).into(), description: DbValue::Str("description", &entity).into(), story_type_id: DbValue::Key("story_type_id", &entity).into(), story_status_id: DbValue::Key("story_status_id", &entity).into(), creator_id: DbValue::Key("creator_id", &entity).into(), created_at: DbValue::Timestamp("created_at", &entity).into(), updated_at: DbValue::Timestamp("updated_at", &entity).into(), } } } #[derive(juniper::GraphQLInputObject)] pub struct NewStoryInput { name: String, description: String, story_type_id: ID, story_status_id: ID, creator_id: ID, project_id: ID, } #[derive(juniper::GraphQLInputObject)] pub struct UpdateStoryInput { name: Option<String>, description: Option<String>, story_type_id: Option<ID>, story_status_id: Option<ID>, } impl Story { fn new(story: NewStoryInput) -> DbProperties { fields_to_db_values(&[ AppValue::Str("name", Some(story.name)), AppValue::Str("description", Some(story.description)), // AppValue::Ref("story_type_id", Some(&story.story_type_id)), // AppValue::Ref("story_status_id", Some(&story.story_status_id)), AppValue::Ref("creator_id", Some(&get_user_path(&story.creator_id))), ]) } fn update(story: UpdateStoryInput) -> DbProperties { fields_to_db_values(&[ AppValue::Str("name", story.name), AppValue::Str("description", story.description), // AppValue::Ref("story_type_id", story.story_type_id), // AppValue::Ref("story_status_id", story.story_status_id), ]) } }
// Copyright 2017 Dasein Phaos aka. Luxko // // 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. //! describes a shader resource view use format::DxgiFormat; use super::Shader4ComponentMapping; /// describes a shader resource view #[derive(Copy, Clone, Debug)] pub struct SrvDesc { pub format: DxgiFormat, pub dimension: SrvDimension, pub component_mapping: Shader4ComponentMapping, } impl SrvDesc { #[inline] pub fn into_cstruct(self) -> SrvDescBindHelper { self.into() } } #[derive(Copy, Clone, Debug)] pub enum SrvDimension { Unknown, Buffer(SrvBufferDesc), Tex1D(SrvTex1DDesc), Tex1DArray(SrvTex1DArrayDesc), Tex2D(SrvTex2DDesc), Tex2DArray(SrvTex2DArrayDesc), Tex2DMs, Tex2DMsArray(SrvTex2DMsArrayDesc), Tex3D(SrvTex3DDesc), TexCube(SrvTexCubeDesc), TexCubeArray(SrvTexCubeArrayDesc), } #[repr(C)] #[derive(Copy, Clone, Debug)] pub struct SrvBufferDesc { /// first element to be accessed by the view pub offset: u64, /// number of elements pub num_elements: u32, /// size of each element in the buffer pub byte_stride: u32, /// whether to view it as a raw buffer, 1 means raw, 0 means not pub raw: u32, } #[repr(C)] #[derive(Copy, Clone, Debug)] pub struct SrvTex1DDesc { /// index of the most detailed mipmap to use pub most_detailed_mip: u32, /// levels of mipmap to use, `-1` means up until the least detailed pub mip_levels: i32, /// minimum sampled lod clamp value pub mip_lod_clamp: f32, } #[repr(C)] #[derive(Copy, Clone, Debug)] pub struct SrvTex1DArrayDesc{ /// index of the most detailed mipmap to use pub most_detailed_mip: u32, /// levels of mipmap to use, `-1` means up until the least detailed pub mip_levels: i32, /// first array slice to use pub first_slice: u32, /// number of slices in the array pub array_size: u32, /// minimum sampled lod clamp value pub mip_lod_clamp: f32, } #[repr(C)] #[derive(Copy, Clone, Debug)] pub struct SrvTex2DDesc{ /// index of the most detailed mipmap to use pub most_detailed_mip: u32, /// levels of mipmap to use, `-1` means up until the least detailed pub mip_levels: i32, /// index of the plane slice to use pub plane_slice: u32, /// minimum sampled lod clamp value pub mip_lod_clamp: f32, } #[repr(C)] #[derive(Copy, Clone, Debug)] pub struct SrvTex2DArrayDesc{ /// index of the most detailed mipmap to use pub most_detailed_mip: u32, /// levels of mipmap to use, `-1` means up until the least detailed pub mip_levels: i32, /// first array slice to use pub first_slice: u32, /// number of slices in the array pub array_size: u32, /// index of the plane slice to use pub plane_slice: u32, /// minimum sampled lod clamp value pub mip_lod_clamp: f32, } #[repr(C)] #[derive(Copy, Clone, Debug)] pub struct SrvTex2DMsArrayDesc{ /// first array slice to use pub first_slice: u32, /// number of slices in the array pub array_size: u32, } #[repr(C)] #[derive(Copy, Clone, Debug)] pub struct SrvTex3DDesc{ /// index of the most detailed mipmap to use pub most_detailed_mip: u32, /// levels of mipmap to use, `-1` means up until the least detailed pub mip_levels: i32, /// minimum sampled lod clamp value pub mip_lod_clamp: f32, } #[repr(C)] #[derive(Copy, Clone, Debug)] pub struct SrvTexCubeDesc{ /// index of the most detailed mipmap to use pub most_detailed_mip: u32, /// levels of mipmap to use, `-1` means up until the least detailed pub mip_levels: i32, /// minimum sampled lod clamp value pub mip_lod_clamp: f32, } #[repr(C)] #[derive(Copy, Clone, Debug)] pub struct SrvTexCubeArrayDesc{ /// index of the most detailed mipmap to use pub most_detailed_mip: u32, /// levels of mipmap to use, `-1` means up until the least detailed pub mip_levels: i32, /// first 2D slice to use pub first_slice: u32, /// number of cube textures to use pub num_cubes: u32, /// minimum sampled lod clamp value pub mip_lod_clamp: f32, } /// helper struct for ffi, not intended for application user /// TODO: remove from public interface #[repr(C)] #[derive(Copy, Clone, Debug)] pub struct SrvDescBindHelper { format: DxgiFormat, view_dimension: ::winapi::D3D12_SRV_DIMENSION, component_mapping: u32, a: [u32; 6], } impl From<SrvDesc> for SrvDescBindHelper{ #[inline] fn from(desc: SrvDesc) -> SrvDescBindHelper { unsafe { let mut ret: SrvDescBindHelper = ::std::mem::zeroed(); ret.format = desc.format; ret.component_mapping = ::std::mem::transmute(desc.component_mapping); match desc.dimension { SrvDimension::Unknown => ret.view_dimension = ::winapi::D3D12_SRV_DIMENSION_UNKNOWN, SrvDimension::Buffer(content) => { ret.view_dimension = ::winapi::D3D12_SRV_DIMENSION_BUFFER; ret.a = ::std::mem::transmute_copy(&content); }, SrvDimension::Tex1D(content) => { ret.view_dimension = ::winapi::D3D12_SRV_DIMENSION_TEXTURE1D; ret.a = ::std::mem::transmute_copy(&content); }, SrvDimension::Tex1DArray(content) => { ret.view_dimension = ::winapi::D3D12_SRV_DIMENSION_TEXTURE1DARRAY; ret.a = ::std::mem::transmute_copy(&content); }, SrvDimension::Tex2D(content) => { ret.view_dimension = ::winapi::D3D12_SRV_DIMENSION_TEXTURE2D; ret.a = ::std::mem::transmute_copy(&content); }, SrvDimension::Tex2DArray(content) => { ret.view_dimension = ::winapi::D3D12_SRV_DIMENSION_TEXTURE2DARRAY; ret.a = ::std::mem::transmute_copy(&content); }, SrvDimension::Tex2DMs => ret.view_dimension = ::winapi::D3D12_SRV_DIMENSION_TEXTURE2DMS, SrvDimension::Tex2DMsArray(content) => { ret.view_dimension = ::winapi::D3D12_SRV_DIMENSION_TEXTURE2DMSARRAY; ret.a = ::std::mem::transmute_copy(&content); }, SrvDimension::Tex3D(content) => { ret.view_dimension = ::winapi::D3D12_SRV_DIMENSION_TEXTURE3D; ret.a = ::std::mem::transmute_copy(&content); }, SrvDimension::TexCube(content) => { ret.view_dimension = ::winapi::D3D12_SRV_DIMENSION_TEXTURECUBE; ret.a = ::std::mem::transmute_copy(&content); }, SrvDimension::TexCubeArray(content) => { ret.view_dimension = ::winapi::D3D12_SRV_DIMENSION_TEXTURECUBEARRAY; ret.a = ::std::mem::transmute_copy(&content); }, } ret } } }
extern crate dredd_hooks; use std::env; use dredd_hooks::IntegrationServer; fn main() { let arguments: Vec<String> = env::args().collect(); let hookfiles = arguments[1..].to_vec(); let server = IntegrationServer::new(); IntegrationServer::start(server, hookfiles); }
extern crate amethyst; extern crate backtrace; extern crate chrono; extern crate climer; extern crate deathframe; extern crate dirs; extern crate json; extern crate ron; #[macro_use] extern crate serde; extern crate serde_json; extern crate serde_plain; mod audio; mod components; mod helpers; mod input; mod level_manager; mod meta; mod panic_hook; mod resources; mod savefile_data; mod settings; mod solid_tag; mod states; mod systems; use amethyst::audio::{AudioBundle, DjSystemDesc}; use amethyst::config::Config; use amethyst::core::frame_limiter::FrameRateLimitConfig; use amethyst::core::transform::TransformBundle; use amethyst::renderer::types::DefaultBackend; use amethyst::renderer::{RenderFlat2D, RenderToWindow, RenderingBundle}; use amethyst::ui::{RenderUi, UiBundle}; use amethyst::utils::fps_counter::FpsCounterBundle; use amethyst::{ApplicationBuilder, LogLevelFilter, LoggerConfig}; use deathframe::custom_game_data::prelude::*; fn main() -> Result<(), String> { set_panic_hook(); print_welcome_mesage(); init_game().map_err(|e| e.to_string()) } fn set_panic_hook() { std::panic::set_hook(Box::new(panic_hook::on_panic)); } fn print_welcome_mesage() { let first_line = format!("{} v{}", meta::NAME, meta::VERSION); println!( "{}\n{}\n{}\nThanks for playing! <3", first_line, meta::GITHUB, "-".repeat(first_line.len().max(meta::GITHUB.len())) ); } fn init_game() -> amethyst::Result<()> { use amethyst::utils::app_root_dir::application_root_dir; use helpers::resource; start_logger(); let game_data = build_game_data()?; let mut game: amethyst::CoreApplication<CustomGameData<CustomData>> = ApplicationBuilder::new( application_root_dir().unwrap(), states::prelude::Startup::default(), )? .with_frame_limit_config(FrameRateLimitConfig::load(resource( "config/frame_limiter.ron", ))) .build(game_data)?; game.run(); Ok(()) } fn start_logger() { amethyst::start_logger(LoggerConfig { level_filter: LogLevelFilter::Error, ..Default::default() }); } fn build_game_data<'a, 'b>( ) -> amethyst::Result<CustomGameDataBuilder<'a, 'b, CustomData>> { use audio::prelude::*; use deathframe::systems::InputManagerSystem; use helpers::resource; use systems::prelude::*; let display_config_file = resource("config/display.ron"); // Bundles let rendering_bundle = RenderingBundle::<DefaultBackend>::new() .with_plugin( RenderToWindow::from_config_path(display_config_file) .with_clear([0.8, 0.8, 0.8, 1.0]), ) .with_plugin(RenderFlat2D::default()) .with_plugin(RenderUi::default()); let transform_bundle = TransformBundle::new(); let ingame_input_bundle = input::ingame_input_bundle(); let menu_input_bundle = input::menu_input_bundle(); let ui_bundle = UiBundle::<input::IngameBindings>::new(); let audio_bundle = AudioBundle::default(); let fps_bundle = FpsCounterBundle; let custom_game_data = CustomGameDataBuilder::<'a, 'b, CustomData>::default() .custom(CustomData::default()) .dispatcher("startup")? .dispatcher("menu")? .dispatcher("level_load")? .dispatcher("ingame")? .dispatcher("paused")? .dispatcher("win")? .with_core_bundle(rendering_bundle)? .with_core_bundle(transform_bundle)? .with_core_bundle(ui_bundle)? .with_core_bundle(audio_bundle)? .with_core_bundle(fps_bundle)? .with_core_bundle(ingame_input_bundle)? .with_bundle("menu", menu_input_bundle)? .with_core_desc( DjSystemDesc::new(|music: &mut Music| music.current()), "dj_system", &[], )? .with_core(CameraOrthoSystem::default(), "camera_ortho_system", &[ ])? .with_core(DebugSystem::default(), "debug_system", &[])? .with_core( InputManagerSystem::<input::IngameBindings>::default(), "ingame_input_manager_system", &[], )? .with_core(TimerSystem::default(), "timer_system", &[])? .with_core(AnimationSystem::default(), "animation_system", &[ // "feature_system", ])? .with_core( ScaleSpritesSystem::default(), "scale_sprites_system", &["animation_system"], )? .with( "menu", InputManagerSystem::<input::MenuBindings>::default(), "menu_input_manager_system", &[], )? .with( "ingame", PlayerRunSystem::default(), "player_run_system", &[], )? .with( "ingame", ControlPlayerSystem::default(), "control_player_system", &["player_run_system"], )? .with("ingame", GravitySystem::default(), "gravity_system", &[ "control_player_system", ])? .with("ingame", EnemyAiSystem::default(), "enemy_ai_system", &[])? .with( "ingame", MoveEntitiesSystem::<solid_tag::SolidTag>::default(), "move_entities_system", &["control_player_system", "gravity_system", "enemy_ai_system"], )? .with( "ingame", HandleSolidCollisionsSystem::default(), "handle_solid_collisions_system", &["control_player_system", "move_entities_system"], )? .with( "ingame", DecreaseVelocitiesSystem::default(), "decrease_velocities_system", &["move_entities_system"], )? .with("ingame", FollowSystem::default(), "follow_system", &[ "control_player_system", "move_entities_system", ])? .with( "ingame", ConfineEntitiesSystem::default(), "confine_entities_system", &["follow_system"], )? .with("ingame", CollisionSystem::default(), "collision_system", &[ ])? .with( "ingame", DynamicAnimationSystem::default(), "dynamic_animation_system", &["collision_system"], )? .with("ingame", FeatureSystem::default(), "feature_system", &[ "collision_system", ])? .with( "ingame", CheckpointSystem::default(), "checkpoint_system", &["collision_system"], )? .with( "ingame", KillEnemySystem::default(), "kill_enemy_system", &[ "collision_system", "control_player_system", "gravity_system", ], )? .with("ingame", SpikeSystem::default(), "spike_system", &[ "collision_system", "kill_enemy_system", ])? .with( "ingame", DeathFloorSystem::default(), "death_floor_system", &["move_entities_system"], )? .with( "ingame", BackgroundSystem::default(), "background_system", &["follow_system"], )? .with("ingame", LoadingSystem::default(), "loading_system", &[ "move_entities_system", "confine_entities_system", ])? .with("ingame", GoalSystem::default(), "goal_system", &[ "collision_system", ])? .with( "menu", MenuSelectionSystem::default(), "menu_selection_system", &[], )?; Ok(custom_game_data) } #[derive(Default)] pub struct CustomData;
extern crate nalgebra; pub mod clock_tracker; use super::dwt_utils::Timestamp; pub use clock_tracker::{ CONSTRUCTED, INITIALIZED }; pub use clock_tracker::ClockTracker;
use anyhow::bail; use reqwest::multipart; use crate::pushover::{Request, Response}; #[cfg(test)] fn endpoint_url() -> String { mockito::server_url() } #[cfg(not(test))] fn endpoint_url() -> String { "https://api.pushover.net".to_string() } #[derive(Debug)] pub struct Attachment { pub filename: String, pub mime_type: String, pub content: Vec<u8>, } impl Attachment { pub fn new<S: ToString>(filename: S, mime_type: S, content: Vec<u8>) -> Self { Attachment { filename: filename.to_string(), mime_type: mime_type.to_string(), content, } } } #[derive(Default)] pub struct Notification { pub request: Request, pub attachment: Option<Attachment>, } impl Notification { pub fn new(token: &str, user: &str, message: &str) -> Self { Self { request: Request { token: token.to_string(), user: user.to_string(), message: message.to_string(), ..Default::default() }, attachment: None, } } pub fn attach(self, attachment: Attachment) -> Self { Self { request: self.request, attachment: Some(attachment), } } pub async fn attach_url(self, url: &str) -> anyhow::Result<Self> { let res = reqwest::get(url).await?; let content = res.bytes().await?.to_vec(); let mime_type = match infer::get(&content) { Some(m) => m, None => bail!("MIME type of {} is unknown", url), }; let filename = format!("file.{}", mime_type.extension()); let attachment = Attachment::new(filename, mime_type.to_string(), content); Ok(Self { request: self.request, attachment: Some(attachment), }) } pub async fn send(&self) -> anyhow::Result<Response> { let client = reqwest::Client::new(); let parts = multipart::Form::new() .text("token", self.request.token.clone()) .text("user", self.request.user.clone()) .text("message", self.request.message.clone()); let r = &self.request; let parts = Self::append_part(parts, "device", r.device.as_ref()); let parts = Self::append_part(parts, "title", r.title.as_ref()); let parts = Self::append_part(parts, "html", r.html.as_ref()); let parts = Self::append_part(parts, "timestamp", r.timestamp.as_ref()); let parts = Self::append_part(parts, "priority", r.priority.as_ref()); let parts = Self::append_part(parts, "url", r.url.as_ref()); let parts = Self::append_part(parts, "url_title", r.url_title.as_ref()); let parts = Self::append_part(parts, "sound", r.sound.as_ref()); let parts = if let Some(ref a) = self.attachment { let part = multipart::Part::bytes(a.content.clone()) .file_name(a.filename.clone()) .mime_str(&a.mime_type)?; parts.part("attachment", part) } else { parts }; let url = format!("{0}/1/messages.json", endpoint_url()); let res = client.post(url).multipart(parts).send().await?; let res: Response = res.json::<Response>().await?; Ok(res) } fn append_part<T: ToString>( parts: multipart::Form, name: &'static str, value: Option<&T>, ) -> multipart::Form { if let Some(v) = value { parts.text(name, v.to_string()) } else { parts } } } #[cfg(test)] mod test { use mockito::mock; use crate::notification::Notification; use crate::pushover::Request; #[tokio::test] async fn test_send() -> anyhow::Result<()> { let _m = mock("POST", "/1/messages.json") .with_status(200) .with_body(r#"{"status":1,"request":"647d2300-702c-4b38-8b2f-d56326ae460b"}"#) .create(); let inner = Request { token: "token".to_string(), user: "user".to_string(), message: "message".to_string(), ..Default::default() }; let request = Notification { request: inner, ..Default::default() }; let res = request.send().await?; assert_eq!(1, res.status); assert_eq!("647d2300-702c-4b38-8b2f-d56326ae460b", res.request); Ok(()) } #[tokio::test] async fn test_device() -> anyhow::Result<()> { test_with_request(Request { token: "token".to_string(), user: "user".to_string(), message: "message".to_string(), device: Some("device".to_string()), ..Default::default() }) .await } #[tokio::test] async fn test_title() -> anyhow::Result<()> { test_with_request(Request { token: "token".to_string(), user: "user".to_string(), message: "message".to_string(), title: Some("title".to_string()), ..Default::default() }) .await } #[tokio::test] async fn test_html() -> anyhow::Result<()> { test_with_request(Request { token: "token".to_string(), user: "user".to_string(), message: "message".to_string(), html: Some(1), ..Default::default() }) .await } #[tokio::test] async fn test_timestamp() -> anyhow::Result<()> { test_with_request(Request { token: "token".to_string(), user: "user".to_string(), message: "message".to_string(), timestamp: Some(1), ..Default::default() }) .await } #[tokio::test] async fn test_priority() -> anyhow::Result<()> { test_with_request(Request { token: "token".to_string(), user: "user".to_string(), message: "message".to_string(), priority: Some(1), ..Default::default() }) .await } #[tokio::test] async fn test_url() -> anyhow::Result<()> { test_with_request(Request { token: "token".to_string(), user: "user".to_string(), message: "message".to_string(), url: Some("rust-lang.org".to_string()), ..Default::default() }) .await } #[tokio::test] async fn test_url_title() -> anyhow::Result<()> { test_with_request(Request { token: "token".to_string(), user: "user".to_string(), message: "message".to_string(), url_title: Some("url title".to_string()), ..Default::default() }) .await } async fn test_with_request(request: Request) -> anyhow::Result<()> { let _m = mock("POST", "/1/messages.json") .with_status(200) .with_body(r#"{"status":1,"request":"647d2300-702c-4b38-8b2f-d56326ae460b"}"#) .create(); let request = Notification { request, ..Default::default() }; let res = request.send().await?; assert_eq!(1, res.status); assert_eq!("647d2300-702c-4b38-8b2f-d56326ae460b", res.request); Ok(()) } }
#![feature(core)] #![feature(reflect_marker)] #![feature(unboxed_closures)] extern crate lua52_sys as ffi; extern crate libc; use std::ffi::{CStr, CString}; use std::io::Read; use std::io::Error as IoError; use std::borrow::Borrow; use std::marker::PhantomData; pub use functions_read::LuaFunction; pub use functions_write::{function, InsideCallback}; pub use lua_tables::LuaTable; pub mod any; pub mod functions_read; pub mod lua_tables; pub mod userdata; mod functions_write; mod macros; mod rust_tables; mod values; mod tuples; /// Main object of the library. /// /// The lifetime parameter corresponds to the lifetime of the content of the Lua context. pub struct Lua<'lua> { lua: LuaContext, must_be_closed: bool, marker: PhantomData<&'lua ()>, } /// RAII guard for a value pushed on the stack. pub struct PushGuard<L> where L: AsMutLua { lua: L, size: i32, } impl<L> PushGuard<L> where L: AsMutLua { /// Prevents the value from being poped when the `PushGuard` is destroyed, and returns the /// number of elements on the stack. fn forget(mut self) -> i32 { let size = self.size; self.size = 0; size } } /// Trait for objects that have access to a Lua context. When using a context returned by a /// `AsLua`, you are not allowed to modify the stack. pub unsafe trait AsLua { fn as_lua(&self) -> LuaContext; } /// Trait for objects that have access to a Lua context. You are allowed to modify the stack, but /// it must be in the same state as it was when you started. pub unsafe trait AsMutLua: AsLua { fn as_mut_lua(&mut self) -> LuaContext; } /// Opaque type that contains the raw Lua context. #[derive(Copy, Clone)] #[allow(raw_pointer_derive)] pub struct LuaContext(*mut ffi::lua_State); unsafe impl Send for LuaContext {} unsafe impl<'a, 'lua> AsLua for &'a Lua<'lua> { fn as_lua(&self) -> LuaContext { self.lua } } unsafe impl<'a, 'lua> AsLua for &'a mut Lua<'lua> { fn as_lua(&self) -> LuaContext { self.lua } } unsafe impl<'a, 'lua> AsMutLua for &'a mut Lua<'lua> { fn as_mut_lua(&mut self) -> LuaContext { self.lua } } unsafe impl<L> AsLua for PushGuard<L> where L: AsMutLua { fn as_lua(&self) -> LuaContext { self.lua.as_lua() } } unsafe impl<L> AsMutLua for PushGuard<L> where L: AsMutLua { fn as_mut_lua(&mut self) -> LuaContext { self.lua.as_mut_lua() } } unsafe impl<'a, L> AsLua for &'a L where L: AsLua { fn as_lua(&self) -> LuaContext { (**self).as_lua() } } unsafe impl<'a, L> AsLua for &'a mut L where L: AsLua { fn as_lua(&self) -> LuaContext { (**self).as_lua() } } unsafe impl<'a, L> AsMutLua for &'a mut L where L: AsMutLua { fn as_mut_lua(&mut self) -> LuaContext { (**self).as_mut_lua() } } /// Types that can be given to a Lua context, for example with `lua.set()` or as a return value /// of a function. pub trait Push<L> where L: AsMutLua { /// Pushes the value on the top of the stack. /// /// Must return a guard representing the elements that have been pushed. /// /// You can implement this for any type you want by redirecting to call to /// another implementation (for example `5.push_to_lua`) or by calling /// `userdata::push_userdata`. fn push_to_lua(self, lua: L) -> PushGuard<L>; } /// Types that can be obtained from a Lua context. /// /// Most types that implement `Push` also implement `LuaRead`, but this is not always the case /// (for example `&'static str` implements `Push` but not `LuaRead`). pub trait LuaRead<L>: Sized where L: AsLua { /// Reads the data from Lua. fn lua_read(lua: L) -> Result<Self, L> { LuaRead::lua_read_at_position(lua, -1) } /// Reads the data from Lua at a given position. fn lua_read_at_position(lua: L, index: i32) -> Result<Self, L>; } /// Error that can happen when executing Lua code. #[derive(Debug)] pub enum LuaError { /// There was a syntax error when parsing the Lua code. SyntaxError(String), /// There was an error during execution of the Lua code /// (for example not enough parameters for a function call). ExecutionError(String), /// There was an IoError while reading the source code to execute. ReadError(IoError), /// The call to `execute` has requested the wrong type of data. WrongType, } impl<'lua> Lua<'lua> { /// Builds a new Lua context. /// /// # Panic /// /// The function panics if the underlying call to `lua_newstate` fails /// (which indicates lack of memory). pub fn new() -> Lua<'lua> { let lua = unsafe { ffi::lua_newstate(alloc, std::ptr::null_mut()) }; if lua.is_null() { panic!("lua_newstate failed"); } // this alloc function is required to create a lua state. extern "C" fn alloc(_ud: *mut libc::c_void, ptr: *mut libc::c_void, _osize: libc::size_t, nsize: libc::size_t) -> *mut libc::c_void { unsafe { if nsize == 0 { libc::free(ptr as *mut libc::c_void); std::ptr::null_mut() } else { libc::realloc(ptr, nsize) } } } // called whenever lua encounters an unexpected error. extern "C" fn panic(lua: *mut ffi::lua_State) -> libc::c_int { let err = unsafe { ffi::lua_tostring(lua, -1) }; let err = unsafe { CStr::from_ptr(err) }; let err = String::from_utf8(err.to_bytes().to_vec()).unwrap(); panic!("PANIC: unprotected error in call to Lua API ({})\n", err); } unsafe { ffi::lua_atpanic(lua, panic) }; Lua { lua: LuaContext(lua), must_be_closed: true, marker: PhantomData, } } /// Takes an existing `lua_State` and build a Lua object from it. /// /// # Arguments /// /// * `close_at_the_end`: if true, lua_close will be called on the lua_State on the destructor pub unsafe fn from_existing_state<T>(lua: *mut T, close_at_the_end: bool) -> Lua<'lua> { Lua { lua: std::mem::transmute(lua), must_be_closed: close_at_the_end, marker: PhantomData, } } /// Opens all standard Lua libraries. /// This is done by calling `luaL_openlibs`. pub fn openlibs(&mut self) { unsafe { ffi::luaL_openlibs(self.lua.0) } } /// Executes some Lua code on the context. pub fn execute<'a, T>(&'a mut self, code: &str) -> Result<T, LuaError> where T: for<'g> LuaRead<&'g mut PushGuard<&'a mut Lua<'lua>>> + for<'g> LuaRead<PushGuard<&'g mut PushGuard<&'a mut Lua<'lua>>>> { let mut f = try!(functions_read::LuaFunction::load(self, code)); f.call() } /// Executes some Lua code on the context. pub fn execute_from_reader<'a, T, R>(&'a mut self, code: R) -> Result<T, LuaError> where T: for<'g> LuaRead<&'g mut PushGuard<&'a mut Lua<'lua>>> + for<'g> LuaRead<PushGuard<&'g mut PushGuard<&'a mut Lua<'lua>>>>, R: Read { let mut f = try!(functions_read::LuaFunction::load_from_reader(self, code)); f.call() } /// Reads the value of a global variable. pub fn get<'l, V, I>(&'l mut self, index: I) -> Option<V> where I: Borrow<str>, V: LuaRead<PushGuard<&'l mut Lua<'lua>>> { let index = CString::new(index.borrow()).unwrap(); unsafe { ffi::lua_getglobal(self.lua.0, index.as_ptr()); } let guard = PushGuard { lua: self, size: 1 }; LuaRead::lua_read(guard).ok() } /// Modifies the value of a global variable. pub fn set<I, V>(&mut self, index: I, value: V) where I: Borrow<str>, for<'a> V: Push<&'a mut Lua<'lua>> { let index = CString::new(index.borrow()).unwrap(); value.push_to_lua(self).forget(); unsafe { ffi::lua_setglobal(self.lua.0, index.as_ptr()); } } /// Inserts an empty array, then loads it. pub fn empty_array<'a, I>(&'a mut self, index: I) -> LuaTable<PushGuard<&'a mut Lua<'lua>>> where I: Borrow<str> { // TODO: cleaner implementation let mut me = self; let index2 = CString::new(index.borrow()).unwrap(); Vec::<u8>::with_capacity(0).push_to_lua(&mut me).forget(); unsafe { ffi::lua_setglobal(me.lua.0, index2.as_ptr()); } me.get(index).unwrap() } } impl<'lua> Drop for Lua<'lua> { fn drop(&mut self) { if self.must_be_closed { unsafe { ffi::lua_close(self.lua.0) } } } } impl<L> Drop for PushGuard<L> where L: AsMutLua { fn drop(&mut self) { if self.size != 0 { unsafe { ffi::lua_pop(self.lua.as_mut_lua().0, self.size); } } } }
use libc::{c_int}; use sdl::SDL_bool; // SDL_cpuinfo.h extern "C" { pub fn SDL_GetCPUCount() -> c_int; pub fn SDL_GetCPUCacheLineSize() -> c_int; pub fn SDL_HasRDTSC() -> SDL_bool; pub fn SDL_HasAltiVec() -> SDL_bool; pub fn SDL_HasMMX() -> SDL_bool; pub fn SDL_Has3DNow() -> SDL_bool; pub fn SDL_HasSSE() -> SDL_bool; pub fn SDL_HasSSE2() -> SDL_bool; pub fn SDL_HasSSE3() -> SDL_bool; pub fn SDL_HasSSE41() -> SDL_bool; pub fn SDL_HasSSE42() -> SDL_bool; pub fn SDL_HasAVX() -> SDL_bool; pub fn SDL_GetSystemRAM() -> c_int; }
//! Linux `mount` API. // The `mount` module includes the `mount` function and related // functions which were originally defined in `rustix::fs` but are // now replaced by deprecated aliases. After the next semver bump, // we can remove the aliases and all the `#[cfg(feature = "mount")]` // here and in src/backend/*/mount. // // The `fsopen` module includes `fsopen` and related functions. #[cfg(feature = "mount")] mod fsopen; mod mount_unmount; mod types; #[cfg(feature = "mount")] pub use fsopen::*; pub use mount_unmount::*; pub use types::*;
use crate::geometry::checks::*; use crate::geometry::entities::*; use crate::geometry::traits::rectangable::Rectangable; pub trait Relative: Rectangable { fn relate_entity(&self, entity: &Entity) -> Option<Relation>; fn relate_entities(&self, entities: &Entities) -> Option<Relation>; } #[derive(Debug, Clone, PartialEq)] pub enum Relation { Inside, Intersect, } impl Relative for Entities { /// logic fully similar to Entities::relate_entities fn relate_entity(&self, entity: &Entity) -> Option<Relation> { let mut checks = vec![]; for self_entity in self { let check = self_entity.relate_entity(entity); if let Some(Relation::Intersect) = check { debug!("intersect!"); return Some(Relation::Intersect); }; checks.push(check); } debug!("got checks: {:?}", checks); if checks.iter().all(|x| *x == None) { return None; }; Some(Relation::Inside) } /// logic fully similar to Entities::relate_entity fn relate_entities(&self, entities: &Entities) -> Option<Relation> { let mut checks = vec![]; for self_entity in self { let check = self_entity.relate_entities(entities); if let Some(Relation::Intersect) = check { debug!("intersect!"); return Some(Relation::Intersect); }; checks.push(check); } debug!("got checks: {:?}", checks); if checks.iter().all(|x| *x == None) { return None; }; Some(Relation::Inside) } } impl Relative for Entity { fn relate_entity(&self, entity: &Entity) -> Option<Relation> { if self.can_not_intersect(entity) { return None; }; match self { Entity::Point(ref self_point) => match entity { Entity::Point(ref other_point) => { if circle_inside_circle(self_point, other_point) { Some(Relation::Inside) } else if circle_intersect_circle(self_point, other_point) { Some(Relation::Intersect) } else { None } } Entity::Contur(ref other_contur) => { if circle_inside_contur(self_point, other_contur) { return Some(Relation::Inside); }; let other_points = &other_contur.points; let mut other_first = other_points.first().unwrap(); for other_p in other_points { if circle_relate_line(self_point, (other_first, other_p)) { return Some(Relation::Intersect); }; other_first = other_p; } None } }, Entity::Contur(ref self_contur) => { fn inpolygon_switch(inpolygon: &mut bool, condition: bool) { if *inpolygon { *inpolygon &= condition; } } fn intersect_switch(intersect: &mut bool, condition: bool) { if !*intersect { *intersect |= condition; }; } // true when ALL true, so we can not return from loops let mut inpolygon = true; // true when ANY true let mut intersect = false; let self_points = &self_contur.points; let mut self_first = self_points.first().unwrap(); for self_p in self_points { match entity { Entity::Point(ref other_point) => { if circle_inside_contur(other_point, self_contur) { return Some(Relation::Intersect); }; intersect_switch( &mut intersect, circle_relate_line(other_point, (self_first, self_p)), ); inpolygon_switch( &mut inpolygon, circle_inside_circle(&self_p, other_point), ); } Entity::Contur(ref other_contur) => { inpolygon_switch( &mut inpolygon, circle_inside_contur(self_p, other_contur), ); // If other contur lies inside self contur -> self contur is intersecting it let mut other_inpolygon = self_contur.is_closed(); let other_points = &other_contur.points; let mut other_first = other_points.first().unwrap(); for other_p in other_points { let self_segment = (self_first, self_p); let other_segment = (other_first, other_p); inpolygon_switch( &mut other_inpolygon, circle_inside_contur(other_p, self_contur), ); if lines_intersect(self_segment, other_segment) { return Some(Relation::Intersect); }; other_first = other_p; } if other_inpolygon { intersect = true }; } } self_first = self_p; } if inpolygon { Some(Relation::Inside) } else if intersect { Some(Relation::Intersect) } else { None } } } } fn relate_entities(&self, entities: &Entities) -> Option<Relation> { let mut in_hole_counter = 0; debug!("\nentities len: {}", entities.len()); for e in entities { let relate = self.relate_entity(e); debug!("got self.relate_entity {:?}", relate); match relate { Some(Relation::Intersect) => { return Some(Relation::Intersect); } Some(Relation::Inside) => in_hole_counter += 1, None => continue, } } debug!("in hole_counter: {}", in_hole_counter); if in_hole_counter % 2 == 1 { return Some(Relation::Inside); }; None } } #[cfg(test)] mod test { use super::*; #[test] fn entity_relate_entity_fig1() { let point = Entity::from_point(Point::new(0., 0., None)); let circle = Entity::from_point(Point::new(0., 0., Some(3.))); let closed_contur = Entity::from_contur(contur![ Point::new(-1., -1., None), Point::new(-1., 1., None), Point::new(1., 1., None), Point::new(1., -1., None), Point::new(-1., -1., None) ]) .unwrap(); // got closed rectangle let open_outer_contur = Entity::from_contur(contur![ Point::new(-1.5, -1.5, None), Point::new(-1.5, 1.5, None), Point::new(1.5, 1.5, None), Point::new(1.5, -1.5, None) ]) .unwrap(); let open_inner_contur = Entity::from_contur(contur![ Point::new(-0.5, -0.5, None), Point::new(-0.5, 0.5, None), Point::new(0.5, 0.5, None), Point::new(0.5, -0.5, None) ]) .unwrap(); assert_eq!(point.relate_entity(&point), Some(Relation::Intersect)); assert_eq!(point.relate_entity(&circle), Some(Relation::Inside)); assert_eq!(point.relate_entity(&closed_contur), Some(Relation::Inside)); assert_eq!(point.relate_entity(&open_outer_contur), None); assert_eq!(point.relate_entity(&open_inner_contur), None); assert_eq!(circle.relate_entity(&point), Some(Relation::Intersect)); assert_eq!(circle.relate_entity(&circle), Some(Relation::Intersect)); assert_eq!( circle.relate_entity(&closed_contur), Some(Relation::Intersect) ); assert_eq!( circle.relate_entity(&open_outer_contur), Some(Relation::Intersect) ); assert_eq!( circle.relate_entity(&open_inner_contur), Some(Relation::Intersect) ); assert_eq!( closed_contur.relate_entity(&point), Some(Relation::Intersect) ); assert_eq!(closed_contur.relate_entity(&circle), Some(Relation::Inside)); assert_eq!( closed_contur.relate_entity(&closed_contur), Some(Relation::Intersect) ); assert_eq!(closed_contur.relate_entity(&open_outer_contur), None); assert_eq!( closed_contur.relate_entity(&open_inner_contur), Some(Relation::Intersect) ); assert_eq!(open_outer_contur.relate_entity(&point), None); assert_eq!( open_outer_contur.relate_entity(&circle), Some(Relation::Inside) ); assert_eq!(open_outer_contur.relate_entity(&closed_contur), None); assert_eq!( open_outer_contur.relate_entity(&open_outer_contur), Some(Relation::Intersect) ); assert_eq!(open_outer_contur.relate_entity(&open_inner_contur), None); assert_eq!(open_inner_contur.relate_entity(&point), None); assert_eq!( open_inner_contur.relate_entity(&circle), Some(Relation::Inside) ); assert_eq!( open_inner_contur.relate_entity(&closed_contur), Some(Relation::Inside) ); assert_eq!(open_inner_contur.relate_entity(&open_outer_contur), None); assert_eq!( open_inner_contur.relate_entity(&open_inner_contur), Some(Relation::Intersect) ); } #[test] fn entity_relate_entity_fig2() { let point = Entity::from_point(Point::new(0., 0., None)); let circle = Entity::from_point(Point::new(0., -2., Some(3.))); let closed_contur = Entity::from_contur(contur![ Point::new(-1., -1., None), Point::new(-1., 1., None), Point::new(1., 1., None), Point::new(1., -1., None), Point::new(-1., -1., None) ]) .unwrap(); // got closed rectangle let open_outer_contur = Entity::from_contur(contur![ Point::new(0., -1.5, None), Point::new(0., 1.5, None), Point::new(3., 1.5, None), Point::new(3., -1.5, None) ]) .unwrap(); let open_inner_contur = Entity::from_contur(contur![ Point::new(-0.5, -1.5, None), Point::new(-0.5, -0.5, None), Point::new(0.5, -0.5, None), Point::new(0.5, -1.5, None) ]) .unwrap(); assert_eq!(point.relate_entity(&point), Some(Relation::Intersect)); assert_eq!(point.relate_entity(&circle), Some(Relation::Inside)); assert_eq!(point.relate_entity(&closed_contur), Some(Relation::Inside)); assert_eq!( point.relate_entity(&open_outer_contur), Some(Relation::Intersect) ); assert_eq!(point.relate_entity(&open_inner_contur), None); assert_eq!(circle.relate_entity(&point), Some(Relation::Intersect)); assert_eq!(circle.relate_entity(&circle), Some(Relation::Intersect)); assert_eq!( circle.relate_entity(&closed_contur), Some(Relation::Intersect) ); assert_eq!( circle.relate_entity(&open_outer_contur), Some(Relation::Intersect) ); assert_eq!( circle.relate_entity(&open_inner_contur), Some(Relation::Intersect) ); assert_eq!( closed_contur.relate_entity(&point), Some(Relation::Intersect) ); assert_eq!( closed_contur.relate_entity(&circle), Some(Relation::Intersect) ); assert_eq!( closed_contur.relate_entity(&closed_contur), Some(Relation::Intersect) ); assert_eq!( closed_contur.relate_entity(&open_outer_contur), Some(Relation::Intersect) ); assert_eq!( closed_contur.relate_entity(&open_inner_contur), Some(Relation::Intersect) ); assert_eq!( open_outer_contur.relate_entity(&point), Some(Relation::Intersect) ); assert_eq!( open_outer_contur.relate_entity(&circle), Some(Relation::Intersect) ); assert_eq!( open_outer_contur.relate_entity(&closed_contur), Some(Relation::Intersect) ); assert_eq!( open_outer_contur.relate_entity(&open_outer_contur), Some(Relation::Intersect) ); assert_eq!( open_outer_contur.relate_entity(&open_inner_contur), Some(Relation::Intersect) ); assert_eq!(open_inner_contur.relate_entity(&point), None); assert_eq!( open_inner_contur.relate_entity(&circle), Some(Relation::Inside) ); assert_eq!( open_inner_contur.relate_entity(&closed_contur), Some(Relation::Intersect) ); assert_eq!( open_inner_contur.relate_entity(&open_outer_contur), Some(Relation::Intersect) ); assert_eq!( open_inner_contur.relate_entity(&open_inner_contur), Some(Relation::Intersect) ); } #[test] fn relate_entities_fig3() { let outer = Entity::from_contur(contur![ Point::new(-9., -9., None), Point::new(-9., 8., None), Point::new(10., 10., None), Point::new(11., -6., None), Point::new(-4., -12., None), Point::new(-9., -9., None) ]) .unwrap(); let inner1 = Entity::from_contur(contur![ Point::new(-6., 0., None), Point::new(-9., 8., None), Point::new(-2., 0., None), Point::new(3., -6., None), Point::new(-5., -7., None), Point::new(-6., 0., None) ]) .unwrap(); let inner1_inner = Entity::from_contur(contur![ Point::new(-4., -2., None), Point::new(-2., -1., None), Point::new(0., -5., None), Point::new(-4., -5., None), Point::new(-4., -2., None) ]) .unwrap(); let inner2 = Entity::from_contur(contur![ Point::new(3., 2., None), Point::new(7., 2., None), Point::new(9., -1., None), Point::new(4., -3., None), Point::new(3., 2., None) ]) .unwrap(); let entities: Entities = vec![outer, inner1, inner1_inner, inner2]; let red_line = Entity::from_contur(contur![ Point::new(-3., -3., None), Point::new(-2., -3., None), Point::new(-2., -4., None), Point::new(-3., -4., None) ]) .unwrap(); assert_eq!(red_line.relate_entities(&entities), Some(Relation::Inside)); let green_line = Entity::from_contur(contur![ Point::new(-1., -6., None), Point::new(-4., -6., None), Point::new(-5., -4., None), Point::new(-5., -1., None), Point::new(-3., -1., None) ]) .unwrap(); assert_eq!(green_line.relate_entities(&entities), None); let red_circle = Entity::from_point(Point::new(-2.5, -3.5, Some(1.))); assert_eq!( red_circle.relate_entities(&entities), Some(Relation::Inside) ); let blue_circle = Entity::from_point(Point::new(6., 0., Some(4.))); assert_eq!( blue_circle.relate_entities(&entities), Some(Relation::Intersect) ); let green_circle = Entity::from_point(Point::new(6., 0., Some(1.))); assert_eq!(green_circle.relate_entities(&entities), None); let blue_line = Entity::from_contur(contur![ Point::new(6., -3., None), Point::new(6., -2., None) ]) .unwrap(); assert_eq!( blue_line.relate_entities(&entities), Some(Relation::Intersect) ); let faraway_line = Entity::from_contur(contur![ Point::new(1000., 1000., None), Point::new(2000., 2000., None) ]) .unwrap(); assert_eq!(faraway_line.relate_entities(&entities), None); } #[test] fn entities_relate_entity_fig4() { let mut mydxf_mock = vec![Entity::from_contur(contur![ Point::new(-4., -9., None), Point::new(-0.9, -7.2, None), Point::new(-0.9, -10., None), Point::new(-3., -10., None) ]) .unwrap()]; let outer = Entity::from_contur(contur![ Point::new(-8., -1., None), Point::new(14., -1., None), Point::new(7., -20., None), Point::new(-8., -15., None), Point::new(-8., -1., None) ]) .unwrap(); assert_eq!(mydxf_mock.relate_entity(&outer), Some(Relation::Inside)); let mut rrxml_mock = vec![outer]; rrxml_mock.push( Entity::from_contur(contur![ Point::new(-6., -5., None), Point::new(2.2, -4.3, None), Point::new(-0., -14., None), Point::new(-6., -10., None), Point::new(-6., -5., None) ]) .unwrap(), ); assert_eq!(mydxf_mock.relate_entities(&rrxml_mock), None); rrxml_mock.push( Entity::from_contur(contur![ Point::new(-4., -6., None), Point::new(1., -6., None), Point::new(-1., -12., None), Point::new(-5., -10., None), Point::new(-4., -6., None) ]) .unwrap(), ); assert_eq!( mydxf_mock.relate_entities(&rrxml_mock), Some(Relation::Inside) ); rrxml_mock.push( Entity::from_contur(contur![ Point::new(5., -4., None), Point::new(11., -4., None), Point::new(9., -11., None), Point::new(4., -11., None), Point::new(5., -4., None) ]) .unwrap(), ); assert_eq!( mydxf_mock.relate_entities(&rrxml_mock), Some(Relation::Inside) ); // pushing some circle outside contur (but within "hole" contur) mydxf_mock.push(Entity::from_point(Point::new(8., -7., Some(1.)))); assert_eq!( mydxf_mock.relate_entities(&rrxml_mock), Some(Relation::Inside) ); // pushing some circle outside outer contur mydxf_mock.pop(); mydxf_mock.push(Entity::from_point(Point::new(23., -7., Some(1.)))); assert_eq!( mydxf_mock.relate_entities(&rrxml_mock), Some(Relation::Inside) ); // pushing some circle inside outer mydxf_mock.pop(); mydxf_mock.push(Entity::from_point(Point::new(5., -15., Some(1.)))); assert_eq!( mydxf_mock.relate_entities(&rrxml_mock), Some(Relation::Inside) ); let faraway_line = vec![Entity::from_contur(contur![ Point::new(20., 20., None), Point::new(20., 20., None) ]) .unwrap()]; assert_eq!(faraway_line.relate_entities(&rrxml_mock), None); } }
use super::*; #[derive(Serialize, Deserialize, Debug, Clone)] pub struct Host { pub id: Uuid, pub name: String, pub address: String, pub port: i32, pub status: Status, pub host_user: String, #[serde(skip_deserializing)] pub password: String, } #[derive(Serialize, Deserialize, Debug, Clone)] pub struct NewHost { pub name: String, pub address: String, pub port: i32, pub host_user: String, pub password: String, } #[derive(Deserialize, Serialize, Debug, Clone, Eq, PartialEq, Type, EnumString, Display)] #[sqlx(rename_all = "lowercase")] #[sqlx(type_name = "varchar")] #[serde(rename_all = "lowercase")] #[strum(serialize_all = "snake_case")] pub enum Status { Unknown, Down, Installing, InstallationFailed, Initializing, Up, } #[derive(Error, Debug)] pub enum HostError { #[error("Failed to list hosts: {0}")] List(#[from] sqlx::Error), #[error("Failed to add host: {0}, error: {1}")] Add(String, sqlx::Error), #[error("Can't find host: {0}, error: {1}")] Find(Uuid, sqlx::Error), #[error("Can't update host: {0}, error: {1}")] Update(Uuid, sqlx::Error), #[error("{0}")] Other(sqlx::Error), } pub async fn list(pool: &PgPool) -> Result<Vec<Host>, HostError> { let hosts = sqlx::query_as!( Host, r#" SELECT id, name, address, port, status as "status: _", host_user, password FROM hosts "# ) .fetch_all(pool) .await .map_err(HostError::List)?; Ok(hosts) } pub async fn add(pool: &PgPool, host: &NewHost) -> Result<Uuid, HostError> { let rec = sqlx::query!( r#" INSERT INTO hosts (name, address, port, status, host_user, password) VALUES ( $1, $2, $3, $4, $5, $6 ) RETURNING id "#, host.name, host.address, host.port, Status::Down as Status, host.host_user, host.password ) .fetch_one(pool) .await .map_err(|e| HostError::Add(host.name.to_owned(), e))?; Ok(rec.id) } pub async fn by_id(pool: &PgPool, host_id: &Uuid) -> Result<Host, HostError> { let host = sqlx::query_as!( Host, r#" SELECT id, name, address, port, status as "status: _", host_user, password FROM hosts WHERE id = $1 "#, host_id ) .fetch_one(pool) .await .map_err(|e| HostError::Find(*host_id, e))?; Ok(host) } pub async fn by_address(pool: &PgPool, address: &str) -> Result<Host, HostError> { let host = sqlx::query_as!( Host, r#" SELECT id, name, address, port, status as "status: _", host_user, password FROM hosts WHERE address = $1 "#, address ) .fetch_one(pool) .await?; Ok(host) } pub async fn by_name(pool: &PgPool, host_name: &str) -> Result<Host, HostError> { let host = sqlx::query_as!( Host, r#" SELECT id, name, address, port, status as "status: _", host_user, password FROM hosts WHERE name = $1 "#, host_name ) .fetch_one(pool) .await?; Ok(host) } pub async fn by_status(pool: &PgPool, status: Status) -> Result<Vec<Host>, HostError> { let hosts = sqlx::query_as!( Host, r#" SELECT id, name, address, port, status as "status: _", host_user, password FROM hosts WHERE status = $1 "#, status.to_string() ) .fetch_all(pool) .await .map_err(HostError::Other)?; Ok(hosts) } pub async fn update_status( pool: &PgPool, host_id: Uuid, status: Status, ) -> Result<bool, HostError> { let row_affected = sqlx::query!( r#" UPDATE hosts SET status = $1 WHERE id = $2 "#, status as Status, host_id ) .execute(pool) .await .map_err(|e| HostError::Update(host_id, e))? .rows_affected(); Ok(row_affected > 0) }
//! console is a library for Rust that provides access to various terminal //! features so you can build nicer looking command line interfaces. It //! comes with various tools and utilities for working with Terminals and //! formatting text. //! //! Best paired with other libraries in the family: //! //! * [dialoguer](https://docs.rs/dialoguer) //! * [indicatif](https://docs.rs/indicatif) //! //! # Terminal Access //! //! The terminal is abstracted through the `console::Term` type. It can //! either directly provide access to the connected terminal or by buffering //! up commands. A buffered terminal will however not be completely buffered //! on windows where cursor movements are currently directly passed through. //! //! Example usage: //! //! ``` //! # fn test() -> Result<(), Box<dyn std::error::Error>> { //! use std::thread; //! use std::time::Duration; //! //! use console::Term; //! //! let term = Term::stdout(); //! term.write_line("Hello World!")?; //! thread::sleep(Duration::from_millis(2000)); //! term.clear_line()?; //! # Ok(()) } test().unwrap(); //! ``` //! //! # Colors and Styles //! //! `console` automaticaly detects when to use colors based on the tty flag. It also //! provides higher level wrappers for styling text and other things that can be //! displayed with the `style` function and utility types. //! //! Example usage: //! //! ``` //! use console::style; //! //! println!("This is {} neat", style("quite").cyan()); //! ``` //! //! You can also store styles and apply them to text later: //! //! ``` //! use console::Style; //! //! let cyan = Style::new().cyan(); //! println!("This is {} neat", cyan.apply_to("quite")); //! ``` //! //! # Working with ANSI Codes //! //! The crate provids the function `strip_ansi_codes` to remove ANSI codes //! from a string as well as `measure_text_width` to calculate the width of a //! string as it would be displayed by the terminal. Both of those together //! are useful for more complex formatting. //! //! # Unicode Width Support //! //! By default this crate depends on the `unicode-width` crate to calculate //! the width of terminal characters. If you do not need this you can disable //! the `unicode-width` feature which will cut down on dependencies. //! //! # Features //! //! By default all features are enabled. The following features exist: //! //! * `unicode-width`: adds support for unicode width calculations //! * `ansi-parsing`: adds support for parsing ansi codes (this adds support //! for stripping and taking ansi escape codes into account for length //! calculations). pub use crate::kb::Key; pub use crate::term::{ user_attended, user_attended_stderr, Term, TermFamily, TermFeatures, TermTarget, }; pub use crate::utils::{ colors_enabled, colors_enabled_stderr, measure_text_width, pad_str, pad_str_with, set_colors_enabled, set_colors_enabled_stderr, style, truncate_str, Alignment, Attribute, Color, Emoji, Style, StyledObject, }; #[cfg(feature = "ansi-parsing")] pub use crate::ansi::{strip_ansi_codes, AnsiCodeIterator}; mod common_term; mod kb; mod term; #[cfg(unix)] mod unix_term; mod utils; #[cfg(target_arch = "wasm32")] mod wasm_term; #[cfg(windows)] mod windows_term; #[cfg(feature = "ansi-parsing")] mod ansi;
//! Definitions for the base Cranelift language. pub mod formats; pub mod immediates; pub mod predicates; pub mod settings; pub mod types;
//! A reference to a channel in a buffer. use std::cmp; use std::fmt; use std::hash; use std::marker; /// A reference to a channel in a buffer. /// /// See [crate::Interleaved::get]. #[derive(Clone, Copy)] pub struct Channel<'a, T> { pub(crate) inner: RawChannelRef<T>, pub(crate) _marker: marker::PhantomData<&'a T>, } // Safety: the iterator is simply a container of references to T's, any // Send/Sync properties are inherited. unsafe impl<T> Send for Channel<'_, T> where T: Sync {} unsafe impl<T> Sync for Channel<'_, T> where T: Sync {} impl<'a, T> Channel<'a, T> { /// Get a reference to a frame. pub fn get(&self, frame: usize) -> Option<T> where T: Copy, { Some(unsafe { *self.inner.frame_ref(frame)? }) } /// Construct an iterator over the current channel. pub fn iter(&self) -> ChannelIter<'_, T> { ChannelIter { inner: self.inner, frame: 0, _marker: marker::PhantomData, } } } impl<T> fmt::Debug for Channel<'_, T> where T: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_list().entries(self.iter()).finish() } } impl<T> cmp::PartialEq for Channel<'_, T> where T: cmp::PartialEq, { fn eq(&self, other: &Self) -> bool { self.iter().eq(other.iter()) } } impl<T> cmp::Eq for Channel<'_, T> where T: cmp::Eq {} impl<T> cmp::PartialOrd for Channel<'_, T> where T: cmp::PartialOrd, { fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> { self.iter().partial_cmp(other.iter()) } } impl<T> cmp::Ord for Channel<'_, T> where T: cmp::Ord, { fn cmp(&self, other: &Self) -> cmp::Ordering { self.iter().cmp(other.iter()) } } impl<T> hash::Hash for Channel<'_, T> where T: hash::Hash, { fn hash<H: hash::Hasher>(&self, state: &mut H) { for frame in self.iter() { frame.hash(state); } } } /// An iterator over a channel. /// /// Created with [Channel::iter]. pub struct ChannelIter<'a, T> { inner: RawChannelRef<T>, frame: usize, _marker: marker::PhantomData<&'a T>, } // Safety: the iterator is simply a container of references to T's, any // Send/Sync properties are inherited. unsafe impl<T> Send for ChannelIter<'_, T> where T: Sync {} unsafe impl<T> Sync for ChannelIter<'_, T> where T: Sync {} impl<'a, T> Iterator for ChannelIter<'a, T> { type Item = &'a T; fn next(&mut self) -> Option<Self::Item> { let item = unsafe { &*self.inner.frame_ref(self.frame)? }; self.frame += 1; Some(item) } } pub(crate) struct RawChannelRef<T: ?Sized> { pub(crate) buffer: *const T, pub(crate) channel: usize, pub(crate) channels: usize, pub(crate) frames: usize, } impl<T> RawChannelRef<T> { /// Get a pointer to the given frame. /// /// This performs bounds checking to make sure that the frame is in bounds /// with the underlying collection. #[inline] fn frame_ref(self, frame: usize) -> Option<*const T> { if frame < self.frames { let offset = self.channels * frame + self.channel; // Safety: We hold all the parameters necessary to perform bounds // checking. let frame = unsafe { self.buffer.add(offset) }; Some(frame) } else { None } } } // Note: can't auto impl because `T`. impl<T: ?Sized> Clone for RawChannelRef<T> { fn clone(&self) -> Self { *self } } impl<T: ?Sized> Copy for RawChannelRef<T> {} pub(crate) struct RawChannelMut<T: ?Sized> { pub(crate) buffer: *mut T, pub(crate) channel: usize, pub(crate) channels: usize, pub(crate) frames: usize, } impl<T> RawChannelMut<T> { #[inline] fn into_ref(self) -> RawChannelRef<T> { RawChannelRef { buffer: self.buffer as *const _, channel: self.channel, channels: self.channels, frames: self.frames, } } /// Get a mutable pointer to the given frame. /// /// This performs bounds checking to make sure that the frame is in bounds /// with the underlying collection. #[inline] fn frame_mut(self, frame: usize) -> Option<*mut T> { if frame < self.frames { let offset = self.channels * frame + self.channel; // Safety: We hold all the parameters necessary to perform bounds // checking. let frame = unsafe { self.buffer.add(offset) }; Some(frame) } else { None } } } // Note: can't auto impl because `T`. impl<T: ?Sized> Clone for RawChannelMut<T> { fn clone(&self) -> Self { *self } } impl<T: ?Sized> Copy for RawChannelMut<T> {} /// A mutable reference to a channel in a buffer. /// /// See [crate::Interleaved::get_mut]. pub struct ChannelMut<'a, T> { pub(crate) inner: RawChannelMut<T>, pub(crate) _marker: marker::PhantomData<&'a mut T>, } // Safety: the iterator is simply a container of mutable references to T's, any // Send/Sync properties are inherited. unsafe impl<T> Send for ChannelMut<'_, T> where T: Send {} unsafe impl<T> Sync for ChannelMut<'_, T> where T: Sync {} impl<'a, T> ChannelMut<'a, T> { /// Get a reference to a frame. /// /// # Examples /// /// ```rust /// let mut buffer = audio::Interleaved::<f32>::with_topology(2, 256); /// /// let left = buffer.get(0).unwrap(); /// /// assert_eq!(left.get(64), Some(0.0)); /// assert_eq!(left.get(255), Some(0.0)); /// assert_eq!(left.get(256), None); /// ``` pub fn get(&self, frame: usize) -> Option<T> where T: Copy, { // Safety: The lifetime created is associated with the structure that // constructed this abstraction. unsafe { Some(*self.inner.into_ref().frame_ref(frame)?) } } /// Get a mutable reference to a frame. /// /// # Examples /// /// ```rust /// let mut buffer = audio::Interleaved::<f32>::with_topology(2, 256); /// /// let mut left = buffer.get_mut(0).unwrap(); /// /// assert_eq!(left.get(64), Some(0.0)); /// *left.get_mut(64).unwrap() = 1.0; /// assert_eq!(left.get(64), Some(1.0)); /// ``` pub fn get_mut(&mut self, frame: usize) -> Option<&mut T> { // Safety: The lifetime created is associated with the structure that // constructed this abstraction. unsafe { Some(&mut *self.inner.frame_mut(frame)?) } } /// Convert the mutable channel into a single mutable frame. /// /// This is necessary in case you need to build a structure which wraps a /// mutable channel and you want it to return the same lifetime as the /// mutable channel is associated with. /// /// # Examples /// /// This does not build: /// /// ```rust,compile_fail /// struct Foo<'a> { /// left: audio::interleaved::ChannelMut<'a, f32>, /// } /// /// impl<'a> Foo<'a> { /// fn get_mut(&mut self, frame: usize) -> Option<&'a mut f32> { /// self.left.get_mut(frame) /// } /// } /// /// let mut buffer = audio::Interleaved::<f32>::with_topology(2, 256); /// /// let mut foo = Foo { /// left: buffer.get_mut(0).unwrap(), /// }; /// /// *foo.get_mut(64).unwrap() = 1.0; /// assert_eq!(buffer.frame(0, 64), Some(1.0)); /// ``` /// /// ```text /// error[E0495]: cannot infer an appropriate lifetime for autoref due to conflicting requirements /// --> examples\compile-fail.rs:7:19 /// | /// 7 | self.left.get_mut(frame) /// | ^^^^^^^ /// | /// ``` /// /// Because if it did, it would be permitted to extract multiple mutable /// references to potentially the same frame with the lifetime `'a`, because /// `Foo` holds onto the mutable channel. /// /// The way we can work around this is by allowing a function to consume the /// mutable channel. And we can do that with [ChannelMut::into_mut]. /// /// ```rust /// # struct Foo<'a> { /// # left: audio::interleaved::ChannelMut<'a, f32>, /// # } /// /// impl<'a> Foo<'a> { /// fn into_mut(self, frame: usize) -> Option<&'a mut f32> { /// self.left.into_mut(frame) /// } /// } /// /// let mut buffer = audio::Interleaved::<f32>::with_topology(2, 256); /// /// let mut foo = Foo { /// left: buffer.get_mut(0).unwrap(), /// }; /// /// *foo.into_mut(64).unwrap() = 1.0; /// assert_eq!(buffer.frame(0, 64), Some(1.0)); /// ``` pub fn into_mut(self, frame: usize) -> Option<&'a mut T> { // Safety: The lifetime created is associated with the structure that // constructed this abstraction. // // We also discard the current channel, which would otherwise allow us // to create more `&'a mut T` references, which would be illegal. unsafe { Some(&mut *self.inner.frame_mut(frame)?) } } /// Construct an iterator over the current channel. pub fn iter(&self) -> ChannelIter<'_, T> { ChannelIter { inner: self.inner.into_ref(), frame: 0, _marker: marker::PhantomData, } } /// Construct a mutable iterator over the current channel. pub fn iter_mut(&mut self) -> ChannelIterMut<'_, T> { ChannelIterMut { inner: self.inner, frame: 0, _marker: marker::PhantomData, } } } impl<T> fmt::Debug for ChannelMut<'_, T> where T: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_list().entries(self.iter()).finish() } } impl<T> cmp::PartialEq for ChannelMut<'_, T> where T: cmp::PartialEq, { fn eq(&self, other: &Self) -> bool { self.iter().eq(other.iter()) } } impl<T> cmp::Eq for ChannelMut<'_, T> where T: cmp::Eq {} impl<T> cmp::PartialOrd for ChannelMut<'_, T> where T: cmp::PartialOrd, { fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> { self.iter().partial_cmp(other.iter()) } } impl<T> cmp::Ord for ChannelMut<'_, T> where T: cmp::Ord, { fn cmp(&self, other: &Self) -> cmp::Ordering { self.iter().cmp(other.iter()) } } impl<T> hash::Hash for ChannelMut<'_, T> where T: hash::Hash, { fn hash<H: hash::Hasher>(&self, state: &mut H) { for frame in self.iter() { frame.hash(state); } } } /// A mutable iterator over a channel. /// /// Created with [ChannelMut::iter_mut]. pub struct ChannelIterMut<'a, T> { inner: RawChannelMut<T>, frame: usize, _marker: marker::PhantomData<&'a mut T>, } // Safety: the iterator is simply a container of references to T's, any // Send/Sync properties are inherited. unsafe impl<T> Send for ChannelIterMut<'_, T> where T: Send {} unsafe impl<T> Sync for ChannelIterMut<'_, T> where T: Sync {} impl<'a, T> Iterator for ChannelIterMut<'a, T> { type Item = &'a mut T; fn next(&mut self) -> Option<Self::Item> { let item = unsafe { &mut *self.inner.frame_mut(self.frame)? }; self.frame += 1; Some(item) } }
//! @brief Solana Native program entry point use crate::{ account::Account, account::KeyedAccount, instruction::CompiledInstruction, instruction::InstructionError, message::Message, pubkey::Pubkey, }; use std::{cell::RefCell, rc::Rc}; // Prototype of a native program entry point /// /// program_id: Program ID of the currently executing program /// keyed_accounts: Accounts passed as part of the instruction /// instruction_data: Instruction data pub type ProgramEntrypoint = unsafe extern "C" fn( program_id: &Pubkey, keyed_accounts: &[KeyedAccount], instruction_data: &[u8], ) -> Result<(), InstructionError>; // Prototype of a native loader entry point /// /// program_id: Program ID of the currently executing program /// keyed_accounts: Accounts passed as part of the instruction /// instruction_data: Instruction data /// invoke_context: Invocation context pub type LoaderEntrypoint = unsafe extern "C" fn( program_id: &Pubkey, keyed_accounts: &[KeyedAccount], instruction_data: &[u8], invoke_context: &dyn InvokeContext, ) -> Result<(), InstructionError>; /// Convenience macro to declare a native program /// /// bs58_string: bs58 string representation the program's id /// name: Name of the program, must match the library name in Cargo.toml /// entrypoint: Program's entrypoint, must be of `type Entrypoint` /// /// # Examples /// /// ``` /// use std::str::FromStr; /// # // wrapper is used so that the macro invocation occurs in the item position /// # // rather than in the statement position which isn't allowed. /// # mod item_wrapper { /// use solana_sdk::account::KeyedAccount; /// use solana_sdk::instruction::InstructionError; /// use solana_sdk::pubkey::Pubkey; /// use solana_sdk::declare_program; /// /// fn my_process_instruction( /// program_id: &Pubkey, /// keyed_accounts: &[KeyedAccount], /// instruction_data: &[u8], /// ) -> Result<(), InstructionError> { /// // Process an instruction /// Ok(()) /// } /// /// declare_program!( /// "My11111111111111111111111111111111111111111", /// solana_my_program, /// my_process_instruction /// ); /// /// # } /// # use solana_sdk::pubkey::Pubkey; /// # use item_wrapper::id; /// let my_id = Pubkey::from_str("My11111111111111111111111111111111111111111").unwrap(); /// assert_eq!(id(), my_id); /// ``` /// ``` /// use std::str::FromStr; /// # // wrapper is used so that the macro invocation occurs in the item position /// # // rather than in the statement position which isn't allowed. /// # mod item_wrapper { /// use solana_sdk::account::KeyedAccount; /// use solana_sdk::instruction::InstructionError; /// use solana_sdk::pubkey::Pubkey; /// use solana_sdk::declare_program; /// /// fn my_process_instruction( /// program_id: &Pubkey, /// keyed_accounts: &[KeyedAccount], /// instruction_data: &[u8], /// ) -> Result<(), InstructionError> { /// // Process an instruction /// Ok(()) /// } /// /// declare_program!( /// solana_sdk::system_program::ID, /// solana_my_program, /// my_process_instruction /// ); /// # } /// /// # use item_wrapper::id; /// assert_eq!(id(), solana_sdk::system_program::ID); /// ``` #[macro_export] macro_rules! declare_program( ($bs58_string:expr, $name:ident, $entrypoint:expr) => ( $crate::declare_id!($bs58_string); #[macro_export] macro_rules! $name { () => { (stringify!($name).to_string(), $crate::id()) }; } #[no_mangle] pub extern "C" fn $name( program_id: &$crate::pubkey::Pubkey, keyed_accounts: &[$crate::account::KeyedAccount], instruction_data: &[u8], ) -> Result<(), $crate::instruction::InstructionError> { $entrypoint(program_id, keyed_accounts, instruction_data) } ) ); /// Same as declare_program but for native loaders #[macro_export] macro_rules! declare_loader( ($bs58_string:expr, $name:ident, $entrypoint:expr) => ( $crate::declare_id!($bs58_string); #[macro_export] macro_rules! $name { () => { (stringify!($name).to_string(), $crate::id()) }; } #[no_mangle] pub extern "C" fn $name( program_id: &$crate::pubkey::Pubkey, keyed_accounts: &[$crate::account::KeyedAccount], instruction_data: &[u8], invoke_context: &mut dyn $crate::entrypoint_native::InvokeContext, ) -> Result<(), $crate::instruction::InstructionError> { $entrypoint(program_id, keyed_accounts, instruction_data, invoke_context) } ) ); /// Cross-program invocation context passed to loaders pub trait InvokeContext { fn push(&mut self, key: &Pubkey) -> Result<(), InstructionError>; fn pop(&mut self); fn verify_and_update( &mut self, message: &Message, instruction: &CompiledInstruction, signers: &[Pubkey], accounts: &[Rc<RefCell<Account>>], ) -> Result<(), InstructionError>; }
#[doc = "Reader of register C1_AHB1LPENR"] pub type R = crate::R<u32, super::C1_AHB1LPENR>; #[doc = "Writer for register C1_AHB1LPENR"] pub type W = crate::W<u32, super::C1_AHB1LPENR>; #[doc = "Register C1_AHB1LPENR `reset()`'s with value 0"] impl crate::ResetValue for super::C1_AHB1LPENR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "DMA1 Clock Enable During CSleep Mode\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum DMA1LPEN_A { #[doc = "0: The selected clock is disabled during csleep mode"] DISABLED = 0, #[doc = "1: The selected clock is enabled during csleep mode"] ENABLED = 1, } impl From<DMA1LPEN_A> for bool { #[inline(always)] fn from(variant: DMA1LPEN_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `DMA1LPEN`"] pub type DMA1LPEN_R = crate::R<bool, DMA1LPEN_A>; impl DMA1LPEN_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> DMA1LPEN_A { match self.bits { false => DMA1LPEN_A::DISABLED, true => DMA1LPEN_A::ENABLED, } } #[doc = "Checks if the value of the field is `DISABLED`"] #[inline(always)] pub fn is_disabled(&self) -> bool { *self == DMA1LPEN_A::DISABLED } #[doc = "Checks if the value of the field is `ENABLED`"] #[inline(always)] pub fn is_enabled(&self) -> bool { *self == DMA1LPEN_A::ENABLED } } #[doc = "Write proxy for field `DMA1LPEN`"] pub struct DMA1LPEN_W<'a> { w: &'a mut W, } impl<'a> DMA1LPEN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: DMA1LPEN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "The selected clock is disabled during csleep mode"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(DMA1LPEN_A::DISABLED) } #[doc = "The selected clock is enabled during csleep mode"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(DMA1LPEN_A::ENABLED) } #[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 = "DMA2 Clock Enable During CSleep Mode"] pub type DMA2LPEN_A = DMA1LPEN_A; #[doc = "Reader of field `DMA2LPEN`"] pub type DMA2LPEN_R = crate::R<bool, DMA1LPEN_A>; #[doc = "Write proxy for field `DMA2LPEN`"] pub struct DMA2LPEN_W<'a> { w: &'a mut W, } impl<'a> DMA2LPEN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: DMA2LPEN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "The selected clock is disabled during csleep mode"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(DMA1LPEN_A::DISABLED) } #[doc = "The selected clock is enabled during csleep mode"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(DMA1LPEN_A::ENABLED) } #[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 << 1)) | (((value as u32) & 0x01) << 1); self.w } } #[doc = "ADC1/2 Peripheral Clocks Enable During CSleep Mode"] pub type ADC12LPEN_A = DMA1LPEN_A; #[doc = "Reader of field `ADC12LPEN`"] pub type ADC12LPEN_R = crate::R<bool, DMA1LPEN_A>; #[doc = "Write proxy for field `ADC12LPEN`"] pub struct ADC12LPEN_W<'a> { w: &'a mut W, } impl<'a> ADC12LPEN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: ADC12LPEN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "The selected clock is disabled during csleep mode"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(DMA1LPEN_A::DISABLED) } #[doc = "The selected clock is enabled during csleep mode"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(DMA1LPEN_A::ENABLED) } #[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 = "Ethernet MAC bus interface Clock Enable During CSleep Mode"] pub type ETH1MACLPEN_A = DMA1LPEN_A; #[doc = "Reader of field `ETH1MACLPEN`"] pub type ETH1MACLPEN_R = crate::R<bool, DMA1LPEN_A>; #[doc = "Write proxy for field `ETH1MACLPEN`"] pub struct ETH1MACLPEN_W<'a> { w: &'a mut W, } impl<'a> ETH1MACLPEN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: ETH1MACLPEN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "The selected clock is disabled during csleep mode"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(DMA1LPEN_A::DISABLED) } #[doc = "The selected clock is enabled during csleep mode"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(DMA1LPEN_A::ENABLED) } #[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 << 15)) | (((value as u32) & 0x01) << 15); self.w } } #[doc = "Ethernet Transmission Clock Enable During CSleep Mode"] pub type ETH1TXLPEN_A = DMA1LPEN_A; #[doc = "Reader of field `ETH1TXLPEN`"] pub type ETH1TXLPEN_R = crate::R<bool, DMA1LPEN_A>; #[doc = "Write proxy for field `ETH1TXLPEN`"] pub struct ETH1TXLPEN_W<'a> { w: &'a mut W, } impl<'a> ETH1TXLPEN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: ETH1TXLPEN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "The selected clock is disabled during csleep mode"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(DMA1LPEN_A::DISABLED) } #[doc = "The selected clock is enabled during csleep mode"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(DMA1LPEN_A::ENABLED) } #[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 << 16)) | (((value as u32) & 0x01) << 16); self.w } } #[doc = "Ethernet Reception Clock Enable During CSleep Mode"] pub type ETH1RXLPEN_A = DMA1LPEN_A; #[doc = "Reader of field `ETH1RXLPEN`"] pub type ETH1RXLPEN_R = crate::R<bool, DMA1LPEN_A>; #[doc = "Write proxy for field `ETH1RXLPEN`"] pub struct ETH1RXLPEN_W<'a> { w: &'a mut W, } impl<'a> ETH1RXLPEN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: ETH1RXLPEN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "The selected clock is disabled during csleep mode"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(DMA1LPEN_A::DISABLED) } #[doc = "The selected clock is enabled during csleep mode"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(DMA1LPEN_A::ENABLED) } #[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 << 17)) | (((value as u32) & 0x01) << 17); self.w } } #[doc = "USB1OTG peripheral clock enable during CSleep mode"] pub type USB1OTGHSLPEN_A = DMA1LPEN_A; #[doc = "Reader of field `USB1OTGHSLPEN`"] pub type USB1OTGHSLPEN_R = crate::R<bool, DMA1LPEN_A>; #[doc = "Write proxy for field `USB1OTGHSLPEN`"] pub struct USB1OTGHSLPEN_W<'a> { w: &'a mut W, } impl<'a> USB1OTGHSLPEN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: USB1OTGHSLPEN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "The selected clock is disabled during csleep mode"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(DMA1LPEN_A::DISABLED) } #[doc = "The selected clock is enabled during csleep mode"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(DMA1LPEN_A::ENABLED) } #[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 << 25)) | (((value as u32) & 0x01) << 25); self.w } } #[doc = "USB_PHY1 clock enable during CSleep mode"] pub type USB1OTGHSULPILPEN_A = DMA1LPEN_A; #[doc = "Reader of field `USB1OTGHSULPILPEN`"] pub type USB1OTGHSULPILPEN_R = crate::R<bool, DMA1LPEN_A>; #[doc = "Write proxy for field `USB1OTGHSULPILPEN`"] pub struct USB1OTGHSULPILPEN_W<'a> { w: &'a mut W, } impl<'a> USB1OTGHSULPILPEN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: USB1OTGHSULPILPEN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "The selected clock is disabled during csleep mode"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(DMA1LPEN_A::DISABLED) } #[doc = "The selected clock is enabled during csleep mode"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(DMA1LPEN_A::ENABLED) } #[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 << 26)) | (((value as u32) & 0x01) << 26); self.w } } #[doc = "USB2OTG peripheral clock enable during CSleep mode"] pub type USB2OTGHSLPEN_A = DMA1LPEN_A; #[doc = "Reader of field `USB2OTGHSLPEN`"] pub type USB2OTGHSLPEN_R = crate::R<bool, DMA1LPEN_A>; #[doc = "Write proxy for field `USB2OTGHSLPEN`"] pub struct USB2OTGHSLPEN_W<'a> { w: &'a mut W, } impl<'a> USB2OTGHSLPEN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: USB2OTGHSLPEN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "The selected clock is disabled during csleep mode"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(DMA1LPEN_A::DISABLED) } #[doc = "The selected clock is enabled during csleep mode"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(DMA1LPEN_A::ENABLED) } #[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 << 27)) | (((value as u32) & 0x01) << 27); self.w } } #[doc = "USB_PHY2 clocks enable during CSleep mode"] pub type USB2OTGHSULPILPEN_A = DMA1LPEN_A; #[doc = "Reader of field `USB2OTGHSULPILPEN`"] pub type USB2OTGHSULPILPEN_R = crate::R<bool, DMA1LPEN_A>; #[doc = "Write proxy for field `USB2OTGHSULPILPEN`"] pub struct USB2OTGHSULPILPEN_W<'a> { w: &'a mut W, } impl<'a> USB2OTGHSULPILPEN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: USB2OTGHSULPILPEN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "The selected clock is disabled during csleep mode"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(DMA1LPEN_A::DISABLED) } #[doc = "The selected clock is enabled during csleep mode"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(DMA1LPEN_A::ENABLED) } #[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 << 28)) | (((value as u32) & 0x01) << 28); self.w } } #[doc = "ART Clock Enable During CSleep Mode"] pub type ARTLPEN_A = DMA1LPEN_A; #[doc = "Reader of field `ARTLPEN`"] pub type ARTLPEN_R = crate::R<bool, DMA1LPEN_A>; #[doc = "Write proxy for field `ARTLPEN`"] pub struct ARTLPEN_W<'a> { w: &'a mut W, } impl<'a> ARTLPEN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: ARTLPEN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "The selected clock is disabled during csleep mode"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(DMA1LPEN_A::DISABLED) } #[doc = "The selected clock is enabled during csleep mode"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(DMA1LPEN_A::ENABLED) } #[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 << 14)) | (((value as u32) & 0x01) << 14); self.w } } impl R { #[doc = "Bit 0 - DMA1 Clock Enable During CSleep Mode"] #[inline(always)] pub fn dma1lpen(&self) -> DMA1LPEN_R { DMA1LPEN_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 1 - DMA2 Clock Enable During CSleep Mode"] #[inline(always)] pub fn dma2lpen(&self) -> DMA2LPEN_R { DMA2LPEN_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 5 - ADC1/2 Peripheral Clocks Enable During CSleep Mode"] #[inline(always)] pub fn adc12lpen(&self) -> ADC12LPEN_R { ADC12LPEN_R::new(((self.bits >> 5) & 0x01) != 0) } #[doc = "Bit 15 - Ethernet MAC bus interface Clock Enable During CSleep Mode"] #[inline(always)] pub fn eth1maclpen(&self) -> ETH1MACLPEN_R { ETH1MACLPEN_R::new(((self.bits >> 15) & 0x01) != 0) } #[doc = "Bit 16 - Ethernet Transmission Clock Enable During CSleep Mode"] #[inline(always)] pub fn eth1txlpen(&self) -> ETH1TXLPEN_R { ETH1TXLPEN_R::new(((self.bits >> 16) & 0x01) != 0) } #[doc = "Bit 17 - Ethernet Reception Clock Enable During CSleep Mode"] #[inline(always)] pub fn eth1rxlpen(&self) -> ETH1RXLPEN_R { ETH1RXLPEN_R::new(((self.bits >> 17) & 0x01) != 0) } #[doc = "Bit 25 - USB1OTG peripheral clock enable during CSleep mode"] #[inline(always)] pub fn usb1otghslpen(&self) -> USB1OTGHSLPEN_R { USB1OTGHSLPEN_R::new(((self.bits >> 25) & 0x01) != 0) } #[doc = "Bit 26 - USB_PHY1 clock enable during CSleep mode"] #[inline(always)] pub fn usb1otghsulpilpen(&self) -> USB1OTGHSULPILPEN_R { USB1OTGHSULPILPEN_R::new(((self.bits >> 26) & 0x01) != 0) } #[doc = "Bit 27 - USB2OTG peripheral clock enable during CSleep mode"] #[inline(always)] pub fn usb2otghslpen(&self) -> USB2OTGHSLPEN_R { USB2OTGHSLPEN_R::new(((self.bits >> 27) & 0x01) != 0) } #[doc = "Bit 28 - USB_PHY2 clocks enable during CSleep mode"] #[inline(always)] pub fn usb2otghsulpilpen(&self) -> USB2OTGHSULPILPEN_R { USB2OTGHSULPILPEN_R::new(((self.bits >> 28) & 0x01) != 0) } #[doc = "Bit 14 - ART Clock Enable During CSleep Mode"] #[inline(always)] pub fn artlpen(&self) -> ARTLPEN_R { ARTLPEN_R::new(((self.bits >> 14) & 0x01) != 0) } } impl W { #[doc = "Bit 0 - DMA1 Clock Enable During CSleep Mode"] #[inline(always)] pub fn dma1lpen(&mut self) -> DMA1LPEN_W { DMA1LPEN_W { w: self } } #[doc = "Bit 1 - DMA2 Clock Enable During CSleep Mode"] #[inline(always)] pub fn dma2lpen(&mut self) -> DMA2LPEN_W { DMA2LPEN_W { w: self } } #[doc = "Bit 5 - ADC1/2 Peripheral Clocks Enable During CSleep Mode"] #[inline(always)] pub fn adc12lpen(&mut self) -> ADC12LPEN_W { ADC12LPEN_W { w: self } } #[doc = "Bit 15 - Ethernet MAC bus interface Clock Enable During CSleep Mode"] #[inline(always)] pub fn eth1maclpen(&mut self) -> ETH1MACLPEN_W { ETH1MACLPEN_W { w: self } } #[doc = "Bit 16 - Ethernet Transmission Clock Enable During CSleep Mode"] #[inline(always)] pub fn eth1txlpen(&mut self) -> ETH1TXLPEN_W { ETH1TXLPEN_W { w: self } } #[doc = "Bit 17 - Ethernet Reception Clock Enable During CSleep Mode"] #[inline(always)] pub fn eth1rxlpen(&mut self) -> ETH1RXLPEN_W { ETH1RXLPEN_W { w: self } } #[doc = "Bit 25 - USB1OTG peripheral clock enable during CSleep mode"] #[inline(always)] pub fn usb1otghslpen(&mut self) -> USB1OTGHSLPEN_W { USB1OTGHSLPEN_W { w: self } } #[doc = "Bit 26 - USB_PHY1 clock enable during CSleep mode"] #[inline(always)] pub fn usb1otghsulpilpen(&mut self) -> USB1OTGHSULPILPEN_W { USB1OTGHSULPILPEN_W { w: self } } #[doc = "Bit 27 - USB2OTG peripheral clock enable during CSleep mode"] #[inline(always)] pub fn usb2otghslpen(&mut self) -> USB2OTGHSLPEN_W { USB2OTGHSLPEN_W { w: self } } #[doc = "Bit 28 - USB_PHY2 clocks enable during CSleep mode"] #[inline(always)] pub fn usb2otghsulpilpen(&mut self) -> USB2OTGHSULPILPEN_W { USB2OTGHSULPILPEN_W { w: self } } #[doc = "Bit 14 - ART Clock Enable During CSleep Mode"] #[inline(always)] pub fn artlpen(&mut self) -> ARTLPEN_W { ARTLPEN_W { w: self } } }
// Copyright 2022 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 clap::Parser; use common_config::DATABEND_COMMIT_VERSION; use common_exception::Result; use serde::Deserialize; use serde::Serialize; use serfig::collectors::from_env; use serfig::collectors::from_self; use super::inner::Config as InnerConfig; #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Parser)] #[clap(name = "open-sharing", about, version = &**DATABEND_COMMIT_VERSION, author)] #[serde(default)] pub struct Config { #[clap(long, default_value = "")] pub tenant: String, #[clap(long, default_value = "127.0.0.1:33003")] pub share_endpoint_address: String, // Storage backend config. #[clap(flatten)] pub storage: common_config::StorageConfig, } impl Default for Config { fn default() -> Self { InnerConfig::default().into_outer() } } impl From<Config> for InnerConfig { fn from(x: Config) -> Self { InnerConfig { tenant: x.tenant, share_endpoint_address: x.share_endpoint_address, storage: x.storage.try_into().expect("StorageConfig"), } } } impl From<InnerConfig> for Config { fn from(inner: InnerConfig) -> Self { Self { tenant: inner.tenant, share_endpoint_address: inner.share_endpoint_address, storage: inner.storage.into(), } } } impl Config { /// Load will load config from file, env and args. /// /// - Load from file as default. /// - Load from env, will override config from file. /// - Load from args as finally override /// /// # Notes /// /// with_args is to control whether we need to load from args or not. /// We should set this to false during tests because we don't want /// our test binary to parse cargo's args. pub fn load(with_args: bool) -> Result<Self> { let mut arg_conf = Self::default(); if with_args { arg_conf = Self::parse(); } let mut builder: serfig::Builder<Self> = serfig::Builder::default(); // load from env. builder = builder.collect(from_env()); // Finally, load from args. if with_args { builder = builder.collect(from_self(arg_conf)); } Ok(builder.build()?) } }
pub const REGION_DATA: &'static str = "region_data"; pub const TEST_PASS: &'static str = "test_pass"; pub const TEST_PASS_CAMERA: &'static str = "test_pass_camera"; pub const TEST_PASS_TEXTURE: &'static str = "test_pass_texture"; pub const TEST_PASS_DEPTH_TEXTURE: &'static str = "test_pass_depth_texture";
mod searcher; use self::searcher::{SearchEngine, SearchWorker}; use crate::find_usages::{CtagsSearcher, GtagsSearcher, QueryType, Usage, UsageMatcher, Usages}; use crate::stdio_server::handler::CachedPreviewImpl; use crate::stdio_server::job; use crate::stdio_server::provider::{BaseArgs, ClapProvider, Context}; use crate::tools::ctags::{get_language, TagsGenerator, CTAGS_EXISTS}; use crate::tools::gtags::GTAGS_EXISTS; use anyhow::Result; use filter::Query; use futures::Future; use itertools::Itertools; use paths::AbsPathBuf; use rayon::prelude::*; use serde_json::json; use std::path::PathBuf; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; use tracing::Instrument; /// Internal reprentation of user input. #[derive(Debug, Clone, Default)] struct QueryInfo { /// Keyword for the tag or regex searching. keyword: String, /// Query type for `keyword`. query_type: QueryType, /// Search terms for further filtering. usage_matcher: UsageMatcher, } impl QueryInfo { /// Return `true` if the result of query info is a superset of the result of another, /// i.e., `self` contains all the search results of `other`. /// /// The rule is as follows: /// /// - the keyword is the same. /// - the new query is a subset of last query. fn is_superset(&self, other: &Self) -> bool { self.keyword == other.keyword && self.query_type == other.query_type && self.usage_matcher.is_superset(&other.usage_matcher) } } /// Parses the raw user input and returns the final keyword as well as the constraint terms. /// Currently, only one keyword is supported. /// /// `hel 'fn` => `keyword ++ exact_term/inverse_term`. /// /// # Argument /// /// - `query`: Initial query typed in the input window. fn parse_query_info(query: &str) -> QueryInfo { let Query { word_terms: _, // TODO: add word_terms to UsageMatcher exact_terms, fuzzy_terms, inverse_terms, } = Query::from(query); // If there is no fuzzy term, use the full query as the keyword, // otherwise restore the fuzzy query as the keyword we are going to search. let (keyword, query_type, usage_matcher) = if fuzzy_terms.is_empty() { if exact_terms.is_empty() { (query.into(), QueryType::StartWith, UsageMatcher::default()) } else { ( exact_terms[0].text.clone(), QueryType::Exact, UsageMatcher::new(exact_terms, inverse_terms), ) } } else { ( fuzzy_terms.iter().map(|term| &term.text).join(" "), QueryType::StartWith, UsageMatcher::new(exact_terms, inverse_terms), ) }; // TODO: Search syntax: // - 'foo // - foo* // - foo // // if let Some(stripped) = query.strip_suffix('*') { // (stripped, QueryType::Contain) // } else if let Some(stripped) = query.strip_prefix('\'') { // (stripped, QueryType::Exact) // } else { // (query, QueryType::StartWith) // }; QueryInfo { keyword, query_type, usage_matcher, } } #[derive(Debug, Clone, Default)] struct SearchResults { /// Last searching results. /// /// When passing the line content from Vim to Rust, the performance /// of Vim can become very bad because some lines are extremely long, /// we cache the last results on Rust to allow passing the line number /// from Vim later instead. usages: Usages, /// Last parsed query info. query_info: QueryInfo, } #[derive(Debug, Clone)] pub struct DumbJumpProvider { args: BaseArgs, /// Results from last searching. /// This might be a superset of searching results for the last query. cached_results: SearchResults, /// Current results from refiltering on `cached_results`. current_usages: Option<Usages>, /// Whether the tags file has been (re)-created. ctags_regenerated: Arc<AtomicBool>, /// Whether the GTAGS file has been (re)-created. gtags_regenerated: Arc<AtomicBool>, } async fn init_gtags(cwd: PathBuf, gtags_regenerated: Arc<AtomicBool>) { let gtags_searcher = GtagsSearcher::new(cwd); match gtags_searcher.create_or_update_tags() { Ok(()) => gtags_regenerated.store(true, Ordering::SeqCst), Err(e) => { tracing::error!(error = ?e, "[dumb_jump] 💔 Error at initializing GTAGS, attempting to recreate..."); // TODO: creating gtags may take 20s+ for large project match tokio::task::spawn_blocking({ let gtags_searcher = gtags_searcher.clone(); move || gtags_searcher.force_recreate() }) .await { Ok(_) => { gtags_regenerated.store(true, Ordering::SeqCst); tracing::debug!("[dumb_jump] Recreating gtags db successfully"); } Err(e) => { tracing::error!(error = ?e, "[dumb_jump] 💔 Failed to recreate gtags db"); } } } } } impl DumbJumpProvider { pub async fn new(ctx: &Context) -> Result<Self> { let args = ctx.parse_provider_args().await?; Ok(Self { args, cached_results: Default::default(), current_usages: None, ctags_regenerated: Arc::new(false.into()), gtags_regenerated: Arc::new(false.into()), }) } async fn initialize_tags(&self, extension: String, cwd: AbsPathBuf) -> Result<()> { let job_id = utils::calculate_hash(&(&cwd, "dumb_jump")); if job::reserve(job_id) { let ctags_future = { let cwd = cwd.clone(); let mut tags_generator = TagsGenerator::with_dir(cwd.clone()); if let Some(language) = get_language(&extension) { tags_generator.set_languages(language.into()); } let ctags_regenerated = self.ctags_regenerated.clone(); // Ctags initialization is usually pretty fast. async move { let now = std::time::Instant::now(); let ctags_searcher = CtagsSearcher::new(tags_generator); match ctags_searcher.generate_tags() { Ok(()) => ctags_regenerated.store(true, Ordering::SeqCst), Err(e) => { tracing::error!(error = ?e, "[dumb_jump] 💔 Error at initializing ctags") } } tracing::debug!(?cwd, "[dumb_jump] ⏱️ Ctags elapsed: {:?}", now.elapsed()); } }; let gtags_future = { let cwd: PathBuf = cwd.into(); let gtags_regenerated = self.gtags_regenerated.clone(); let span = tracing::span!(tracing::Level::INFO, "gtags"); async move { let _ = tokio::task::spawn(init_gtags(cwd, gtags_regenerated)).await; } .instrument(span) }; fn run(job_future: impl Send + Sync + 'static + Future<Output = ()>, job_id: u64) { tokio::task::spawn({ async move { let now = std::time::Instant::now(); job_future.await; tracing::debug!("[dumb_jump] ⏱️ Total elapsed: {:?}", now.elapsed()); job::unreserve(job_id); } }); } match (*CTAGS_EXISTS, *GTAGS_EXISTS) { (true, true) => run( async move { futures::future::join(ctags_future, gtags_future).await; }, job_id, ), (false, false) => {} (true, false) => run(ctags_future, job_id), (false, true) => run(gtags_future, job_id), } } Ok(()) } /// Starts a new searching task. async fn start_search( &self, search_worker: SearchWorker, query: &str, query_info: QueryInfo, ) -> Result<SearchResults> { if query.is_empty() { return Ok(Default::default()); } let search_engine = match ( self.ctags_regenerated.load(Ordering::Relaxed), self.gtags_regenerated.load(Ordering::Relaxed), ) { (true, true) => SearchEngine::All, (true, false) => SearchEngine::CtagsAndRegex, _ => SearchEngine::Regex, }; let usages = search_engine.run(search_worker).await?; Ok(SearchResults { usages, query_info }) } fn on_new_search_results( &mut self, search_results: SearchResults, ctx: &Context, ) -> Result<()> { let matched = search_results.usages.len(); // Only show the top 200 items. let (lines, indices): (Vec<_>, Vec<_>) = search_results .usages .iter() .take(200) .map(|usage| (usage.line.as_str(), usage.indices.as_slice())) .unzip(); let response = json!({ "lines": lines, "indices": indices, "matched": matched }); ctx.vim .exec("clap#state#process_response_on_typed", response)?; self.cached_results = search_results; self.current_usages.take(); Ok(()) } } #[async_trait::async_trait] impl ClapProvider for DumbJumpProvider { async fn on_initialize(&mut self, ctx: &mut Context) -> Result<()> { let cwd = ctx.vim.working_dir().await?; let source_file_extension = ctx.start_buffer_extension()?.to_string(); tokio::task::spawn({ let cwd = cwd.clone(); let extension = source_file_extension.clone(); let dumb_jump = self.clone(); async move { if let Err(err) = dumb_jump.initialize_tags(extension, cwd).await { tracing::error!(error = ?err, "Failed to initialize dumb_jump provider"); } } }); if let Some(query) = &self.args.query { let query_info = parse_query_info(query); let search_worker = SearchWorker { cwd, query_info: query_info.clone(), source_file_extension, }; let search_results = self.start_search(search_worker, query, query_info).await?; self.on_new_search_results(search_results, ctx)?; } Ok(()) } async fn on_move(&mut self, ctx: &mut Context) -> Result<()> { let current_lines = self .current_usages .as_ref() .unwrap_or(&self.cached_results.usages); if current_lines.is_empty() { return Ok(()); } let input = ctx.vim.input_get().await?; let lnum = ctx.vim.display_getcurlnum().await?; // lnum is 1-indexed let curline = current_lines .get_line(lnum - 1) .ok_or_else(|| anyhow::anyhow!("Can not find curline on Rust end for lnum: {lnum}"))?; let preview_height = ctx.preview_height().await?; let (preview_target, preview) = CachedPreviewImpl::new(curline.to_string(), preview_height, ctx)? .get_preview() .await?; let current_input = ctx.vim.input_get().await?; let current_lnum = ctx.vim.display_getcurlnum().await?; // Only send back the result if the request is not out-dated. if input == current_input && lnum == current_lnum { ctx.preview_manager.reset_scroll(); ctx.render_preview(preview)?; ctx.preview_manager.set_preview_target(preview_target); } Ok(()) } async fn on_typed(&mut self, ctx: &mut Context) -> Result<()> { let query = ctx.vim.input_get().await?; let query_info = parse_query_info(&query); // Try to refilter the cached results. if self.cached_results.query_info.is_superset(&query_info) { let refiltered = self .cached_results .usages .par_iter() .filter_map(|Usage { line, indices }| { query_info .usage_matcher .match_jump_line((line.clone(), indices.clone())) .map(|(line, indices)| Usage::new(line, indices)) }) .collect::<Vec<_>>(); let matched = refiltered.len(); let (lines, indices): (Vec<&str>, Vec<&[usize]>) = refiltered .iter() .take(200) .map(|Usage { line, indices }| (line.as_str(), indices.as_slice())) .unzip(); let response = json!({ "lines": lines, "indices": indices, "matched": matched }); ctx.vim .exec("clap#state#process_response_on_typed", response)?; self.current_usages.replace(refiltered.into()); return Ok(()); } let cwd: AbsPathBuf = ctx.vim.working_dir().await?; let search_worker = SearchWorker { cwd, query_info: query_info.clone(), source_file_extension: ctx.start_buffer_extension()?.to_string(), }; let search_results = self.start_search(search_worker, &query, query_info).await?; self.on_new_search_results(search_results, ctx)?; Ok(()) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_parse_search_info() { let query_info = parse_query_info("'foo"); println!("{query_info:?}"); } }
//! Type aliases for using `deadpool-diesel` with MySQL. /// Connection which is returned by the MySQL pool pub type Connection = crate::Connection<diesel::MysqlConnection>; /// Manager which is used to create MySQL connections pub type Manager = crate::manager::Manager<diesel::MysqlConnection>; /// Pool for using `deadpool-diesel` with MySQL pub type Pool = deadpool::managed::Pool<Manager>;
use crate::entities::*; use crate::logics::reduce_points; use async_trait::async_trait; use chrono::prelude::{DateTime, Utc}; use failure::Error; use std::collections::HashMap; use uuid::Uuid; #[async_trait] pub trait Filter<T> { type Key; async fn filter(&self, key: &Self::Key) -> Result<Vec<T>, Error>; } #[async_trait] pub trait Contain<T> { type Key; async fn contain(&self, key: &Self::Key) -> Result<Vec<T>, Error>; } #[async_trait] pub trait Get<T> { type Key; async fn get(&self, key: &Self::Key) -> Result<Option<T>, Error>; } #[async_trait] pub trait Create<T> { async fn create(&self, row: &T) -> Result<(), Error>; } #[async_trait] pub trait BulkInsert<T> { async fn bulk_insert(&self, row: &[T]) -> Result<(), Error>; } #[async_trait] pub trait Update<T> { async fn create(&self, row: &T) -> Result<(), Error>; } #[async_trait] pub trait Delete<T> { type Key; async fn delete(&self, key: &Self::Key) -> Result<(), Error>; } #[async_trait] pub trait TraceUsecase { async fn get_all(&self, keyword: &str) -> Result<Vec<Trace>, Error>; async fn add_scalars(&self, keyword: &str) -> Result<Vec<Trace>, Error>; } pub struct NameKey { pub name: String, } pub struct IdKey { pub id: Uuid, } pub struct RangeKey { pub id: Uuid, pub from_date: DateTime<Utc>, pub to_date: DateTime<Utc>, } pub trait Storage: Create<Trace> + Get<Trace, Key = NameKey> + Delete<Trace, Key = IdKey> + Contain<Trace, Key = NameKey> + BulkInsert<Point> + Filter<SlimPoint, Key = RangeKey> + Delete<Point, Key = IdKey> + Sync { } #[async_trait] pub trait SearchPoints: HasStorage { async fn search_points( &self, trace_id: &Uuid, from_date: &DateTime<Utc>, to_date: &DateTime<Utc>, ) -> Result<Vec<SlimPoint>, Error> { let points: Vec<SlimPoint> = self .storage() .filter(&RangeKey { id: trace_id.to_owned(), from_date: from_date.to_owned(), to_date: to_date.to_owned(), }) .await?; Ok(reduce_points(&points, 1000)) } } #[async_trait] pub trait SearchTraces: HasStorage { async fn search_traces(&self, keyword: &str) -> Result<Vec<Trace>, Error> { let name = keyword.trim(); let traces: Vec<Trace> = self .storage() .contain(&NameKey { name: name.to_owned(), }) .await?; Ok(traces) } } #[async_trait] pub trait CreateTrace: HasStorage { async fn create_trace(&self, name: &str) -> Result<Uuid, Error> { let id = match self .storage() .get(&NameKey { name: name.to_owned(), }) .await? { Some(x) => x.id, None => { let mut new_row: Trace = Default::default(); new_row.name = name.to_owned(); self.storage().create(&new_row).await?; new_row.id } }; Ok(id) } } pub trait HasStorage { fn storage(&self) -> &(dyn Storage); } #[async_trait] pub trait AddScalars: CreateTrace { async fn add_scalars( &self, values: &HashMap<String, f64>, ts: &DateTime<Utc>, ) -> Result<(), Error> { let mut points: Vec<Point> = vec![]; for (k, v) in values { let trace_id = self.create_trace(k).await?; let point = Point { trace_id: trace_id, ts: ts.to_owned(), value: v.to_owned(), }; points.push(point); } self.storage().bulk_insert(&points).await?; Ok(()) } } #[async_trait] pub trait DeleteTrace: HasStorage { async fn delete_trace(&self, id: &Uuid) -> Result<(), Error> { Delete::<Trace>::delete( self.storage(), &IdKey { id: id.to_owned(), }, ) .await?; Delete::<Point>::delete( self.storage(), &IdKey { id: id.to_owned(), }, ) .await?; Ok(()) } }
//! Code generation and candidate evaluation for specific targets. pub mod fake; mod argument; mod context; pub use self::argument::{ArrayArgument, ArrayArgumentExt, ScalarArgument}; pub use self::context::{ ArgMap, ArgMapExt, AsyncCallback, AsyncEvaluator, Context, EvalMode, KernelEvaluator, Stabilizer, }; use crate::codegen::Function; use crate::ir; use crate::model::{self, HwPressure, Nesting}; use crate::search_space::*; use fxhash::FxHashMap; use std::io::Write; /// Holds the specifications of a target. #[allow(clippy::trivially_copy_pass_by_ref)] pub trait Device: Send + Sync + 'static { /// Prints the code corresponding to a device `Function`. fn print(&self, function: &Function, out: &mut dyn Write); /// Indicates if a `Type` can be implemented on the device. fn check_type(&self, t: ir::Type) -> Result<(), ir::TypeError>; /// Returns the maximal number of block dimensions. fn max_block_dims(&self) -> u32; /// The maximal size inner block dimensions can have. fn max_inner_block_size(&self) -> u32; /// Returns the maximal number of threads. fn max_threads(&self) -> u32; /// Returns the maximal unrolling factor. fn max_unrolling(&self) -> u32; /// Indicates if the device uses vector registers or has imlicit gathers and scatters /// in vector instructions. fn has_vector_registers(&self) -> bool; /// Indicates if the operator can be vectorized along the dimension. fn can_vectorize(&self, dim: &ir::Dimension, op: &ir::Operator) -> bool; /// Indicates the maximal vectorization factor for the given operator. fn max_vectorization(&self, op: &ir::Operator) -> [u32; 2]; /// Returns the amount of shared memory available for each thread block. fn shared_mem(&self) -> u32; /// Indicates the type of the pointer for the given memory space. fn pointer_type(&self, mem_space: MemSpace) -> ir::Type; /// Indicates the memory flags supported by the operator. fn supported_mem_flags(&self, op: &ir::Operator) -> InstFlag; /// Returns the name of the device. fn name(&self) -> &str; /// Returns the pressure cause by a `Statement`. For a dimension, returns the pressure /// for the full loop execution. fn hw_pressure( &self, space: &SearchSpace, dim_sizes: &FxHashMap<ir::DimId, model::size::Range>, nesting: &FxHashMap<ir::StmtId, Nesting>, bb: &dyn ir::Statement, ctx: &dyn Context, ) -> HwPressure; /// Returns the pressure produced by a single iteration of a loop and the latency /// overhead of iterations. fn loop_iter_pressure(&self, kind: DimKind) -> (HwPressure, HwPressure); /// Returns the processing rates of a single thread, in units/ns fn thread_rates(&self) -> HwPressure; /// Returns the processing rates of a single block, in units/ns. fn block_rates(&self) -> HwPressure; /// Returns the processing rates of the whole accelerator un units/ns. fn total_rates(&self) -> HwPressure; /// Returns the names of potential bottlenecks. fn bottlenecks(&self) -> &[&'static str]; /// Returns the number of blocks that can be executed in parallel on the device. fn block_parallelism(&self, space: &SearchSpace) -> u32; /// Returns the pressure caused by an additive induction variable level. fn additive_indvar_pressure(&self, t: &ir::Type) -> HwPressure; /// Returns the pressure caused by a multiplicative induction variable level. fn multiplicative_indvar_pressure(&self, t: &ir::Type) -> HwPressure; /// Adds the overhead (per instance) due to partial wraps and predicated dimensions to /// the pressure. If the instruction is not predicated, `predicated_dims_size` should /// be `1`. fn add_block_overhead( &self, max_active_threads: model::size::FactorRange, max_threads: model::size::FactorRange, predication_factor: model::size::Range, pressure: &mut HwPressure, ); /// Lowers a type using the memory space information. Returns `None` if some /// information is not yet specified. fn lower_type(&self, t: ir::Type, space: &SearchSpace) -> Option<ir::Type>; /// Builds and outputs a constrained IR instance. fn gen_code(&self, implementation: &SearchSpace, out: &mut dyn Write) { let code = Function::build(implementation); self.print(&code, out); } }
use crate::concmap::*; use crate::memory::*; use crate::program::Program; use crate::{consistency, thread}; use std::sync::atomic::{AtomicU64, Ordering}; pub struct Cache { r: ConcurrentMap<Box<[u32]>, Future<Box<[thread::Promise]>>>, n_hits: AtomicU64, } impl Cache { #[inline] pub fn new() -> Self { Self { r: ConcurrentMap::new(), n_hits: AtomicU64::new(0), } } #[inline(always)] unsafe fn refcast<'a, 'b>(&'a self, r: &'b Box<[thread::Promise]>) -> &'a [thread::Promise] { &*(&**r as *const [_]) } pub fn get( &self, p: &Program, cc: &consistency::Cache, mem: &Memory, ts: &thread::State, ) -> &[thread::Promise] { debug_assert!(ts.updating.is_none() && cc.check_semi(p, mem, ts)); let mut ser = Vec::new(); ts.serialize_for_promises(&mut ser, p, mem); let ser = ser.into_boxed_slice(); let (ins, index) = self.r.insert(ser, Future::Pending); if !ins { self.n_hits.fetch_add(1, Ordering::Relaxed); return self.r.poll(index, |_, v| unsafe { self.refcast(v) }); } let mut r_promise = Vec::new(); thread::for_all_imaginable_promises(p, &mem, &ts, |pr| { let (ts2, mem2, _) = ts.with_promise(&mem, &pr); assert!(ts2.updating.is_none()); if cc.check_semi(p, &mem2, &ts2) { r_promise.push(pr); } }); r_promise.sort_unstable(); r_promise.dedup(); let r_promise = r_promise.into_boxed_slice(); self.r .with(index, |_, v| unsafe { self.refcast(v.set(r_promise)) }) } #[inline(always)] pub fn n_hits(&self) -> u64 { self.n_hits.load(Ordering::Relaxed) } #[inline(always)] pub fn n_misses(&self) -> u64 { self.r.len() as u64 } #[inline(always)] pub fn n_total(&self) -> u64 { self.n_hits() + self.n_misses() } }
pub struct CharStream { pub code: Vec<char>, pub index: usize, pub eof: bool } impl CharStream { pub fn peek (&self) -> char { self.code[self.index] } pub fn read (&mut self) -> char { let c = self.code[self.index]; if self.index >= self.code.len() - 1 { self.eof = true; // Continually reads the final char once eof self.index -= 1; } else { self.index += 1; } c } pub fn new (code: String) -> CharStream { CharStream { code: code.chars().collect(), index: 0, eof: false } } }
use termion::event::Key; use components::App; use models::Mode; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Outcome { Continue, Quit, } #[derive(Debug)] pub struct KeyManager {} impl KeyManager { pub fn new() -> Self { KeyManager {} } pub fn handle_key(&mut self, app: &mut App, input: Key) -> Outcome { match app.state().current_mode() { &Mode::History => self.handle_history_key(app, input), &Mode::SelectChannel => self.handle_select_channel_key(app, input), } } fn handle_history_key(&mut self, app: &mut App, input: Key) -> Outcome { match input { Key::Char('q') => return Outcome::Quit, Key::Char('j') => app.state_mut().scroll_down(1), Key::Char('k') => app.state_mut().scroll_up(1), Key::Ctrl('f') => { // Leave 2 lines from last page visible let page_size = app.state().chat_height().saturating_sub(2); app.state_mut().scroll_down(page_size as usize); } Key::Ctrl('b') => { // Leave 2 lines from last page visible let page_size = app.state().chat_height().saturating_sub(2); app.state_mut().scroll_up(page_size as usize) } Key::Char('G') => { let distance = app.state().current_history_scroll(); app.state_mut().scroll_down(distance) } Key::Char('b') => app.state_mut().add_fake_message(None), Key::Char('B') => app.state_mut().toggle_loading_state(), Key::Ctrl('k') => app.state_mut().enter_mode(Mode::SelectChannel), _ => {} } Outcome::Continue } fn handle_select_channel_key(&mut self, app: &mut App, input: Key) -> Outcome { match input { Key::Backspace => app.channel_selector.delete_character(), Key::Ctrl('w') => app.channel_selector.delete_word(), Key::Ctrl('a') => app.channel_selector.move_to_beginning(), Key::Ctrl('e') => app.channel_selector.move_to_end(), Key::Ctrl('k') => app.channel_selector.reset(), Key::Left => app.channel_selector.move_cursor_left(), Key::Right => app.channel_selector.move_cursor_right(), Key::Up => app.channel_selector.select_previous_match(), Key::Down => app.channel_selector.select_next_match(), Key::Char('\n') => { app.select_channel_from_selector(); app.channel_selector.reset(); app.state_mut().enter_mode(Mode::History); } Key::Esc => { app.channel_selector.reset(); app.state_mut().enter_mode(Mode::History); } Key::Char(chr) => app.channel_selector.add_character(chr), _ => {} } Outcome::Continue } }
extern crate gl; extern crate gl_loader; extern crate glfw; extern crate stb_image; use glfw::Context; use std::ffi::{c_void, CStr}; use std::ptr::null; use crate::helpers::log; use crate::ui; pub struct App { pub glfw: glfw::Glfw, pub imgui: imgui::Context, pub imgui_glfw: ui::ImguiGLFW, pub window: glfw::Window, pub events: std::sync::mpsc::Receiver<(f64, glfw::WindowEvent)>, pub width: u32, pub height: u32, pub resized: bool, } impl App { pub fn new() -> App { let mut glfw = glfw::init(glfw::FAIL_ON_ERRORS).unwrap(); let width: u32 = 1024; let height: u32 = 1024; glfw.window_hint(glfw::WindowHint::ContextVersion(4, 6)); glfw.window_hint(glfw::WindowHint::Resizable(true)); glfw.window_hint(glfw::WindowHint::OpenGlDebugContext(true)); let (mut window, events) = glfw .create_window(width, height, "Simple Renderer", glfw::WindowMode::Windowed) .expect("Failed to create GLFW window."); window.make_current(); window.set_key_polling(true); window.set_resizable(true); window.set_all_polling(true); gl_loader::init_gl(); gl::load_with(|symbol| gl_loader::get_proc_address(symbol) as *const _); initialize_gl_debug(); init_gl(); //Need to flip images because of the OpenGL coordinate system unsafe { stb_image::stb_image::bindgen::stbi_set_flip_vertically_on_load(1) }; let mut imgui = imgui::Context::create(); let imgui_glfw = ui::ImguiGLFW::new(&mut imgui, &mut window); imgui.io_mut().mouse_draw_cursor = false; App { glfw, imgui, imgui_glfw, window, events, width, height, resized: false, } } } impl Drop for App { fn drop(&mut self) { gl_loader::end_gl(); } } fn init_gl() { unsafe { gl::Enable(gl::TEXTURE_CUBE_MAP_SEAMLESS) }; } fn initialize_gl_debug() { unsafe { gl::Enable(gl::DEBUG_OUTPUT); gl::Enable(gl::DEBUG_OUTPUT_SYNCHRONOUS); gl::DebugMessageCallback(Some(gl_debug_callback), null()); gl::DebugMessageControl( gl::DONT_CARE, gl::DONT_CARE, gl::DONT_CARE, 0, null(), gl::TRUE, ); } } extern "system" fn gl_debug_callback( _source: u32, gltype: u32, _id: u32, _severity: u32, _length: i32, message: *const i8, _user_param: *mut c_void, ) { let c_str: &CStr = unsafe { CStr::from_ptr(message) }; if gltype == gl::DEBUG_TYPE_OTHER || gltype == gl::DEBUG_TYPE_MARKER { //log::log_info(c_str.to_str().unwrap().to_string()); } else { log::log_error(c_str.to_str().unwrap().to_string()); } }
use nabi; use abi; use handle::Handle; pub struct Wasm(pub(crate) Handle); impl Wasm { pub fn compile(wasm: &[u8]) -> nabi::Result<Wasm> { let res: nabi::Result<u32> = unsafe { abi::wasm_compile(wasm.as_ptr(), wasm.len()) }.into(); res.map(|index| Wasm(Handle(index))) } }
//! # [Functions] supported by InfluxQL //! //! [Functions]: https://docs.influxdata.com/influxdb/v1.8/query_language/functions/ use std::collections::HashSet; use once_cell::sync::Lazy; /// Returns `true` if `name` is a mathematical scalar function /// supported by InfluxQL. pub fn is_scalar_math_function(name: &str) -> bool { static FUNCTIONS: Lazy<HashSet<&'static str>> = Lazy::new(|| { HashSet::from([ "abs", "sin", "cos", "tan", "asin", "acos", "atan", "atan2", "exp", "log", "ln", "log2", "log10", "sqrt", "pow", "floor", "ceil", "round", ]) }); FUNCTIONS.contains(name) } /// Returns `true` if `name` is an aggregate or aggregate function /// supported by InfluxQL. pub fn is_aggregate_function(name: &str) -> bool { static FUNCTIONS: Lazy<HashSet<&'static str>> = Lazy::new(|| { HashSet::from([ // Scalar-like functions "cumulative_sum", "derivative", "difference", "elapsed", "moving_average", "non_negative_derivative", "non_negative_difference", // Selector functions "bottom", "first", "last", "max", "min", "percentile", "sample", "top", // Aggregate functions "count", "integral", "mean", "median", "mode", "spread", "stddev", "sum", // Prediction functions "holt_winters", "holt_winters_with_fit", // Technical analysis functions "chande_momentum_oscillator", "exponential_moving_average", "double_exponential_moving_average", "kaufmans_efficiency_ratio", "kaufmans_adaptive_moving_average", "triple_exponential_moving_average", "triple_exponential_derivative", "relative_strength_index", ]) }); FUNCTIONS.contains(name) } /// Returns `true` if `name` is `"now"`. pub fn is_now_function(name: &str) -> bool { name == "now" }
use floor_sqrt::floor_sqrt; use proconio::{input, marker::Usize1}; fn main() { input! { n: usize, q: usize, a: [usize; n], lr: [(Usize1, usize); q], }; let b = 1.max(n / floor_sqrt(q as u64) as usize); let mut lri = lr.into_iter().enumerate().collect::<Vec<_>>(); lri.sort_by_key(|&(_, (l, r))| (l / b, r)); let (mut l, mut r) = (0, 0); let mut f = [0_u64; 200001]; let mut c = 0; let mut ans = vec![0; q]; for (i, (ll, rr)) in lri { // ひろげる while ll < l { l -= 1; c += f[a[l]] * f[a[l]].saturating_sub(1) / 2; f[a[l]] += 1; } while r < rr { c += f[a[r]] * f[a[r]].saturating_sub(1) / 2; f[a[r]] += 1; r += 1; } // ちぢめる while l < ll { f[a[l]] -= 1; c -= f[a[l]] * f[a[l]].saturating_sub(1) / 2; l += 1; } while rr < r { r -= 1; f[a[r]] -= 1; c -= f[a[r]] * f[a[r]].saturating_sub(1) / 2; } ans[i] = c; } for i in 0..q { println!("{}", ans[i]); } }
pub mod addon; pub mod backup; pub mod cache; pub mod catalog; pub mod config; pub mod curse_api; pub mod error; pub mod fs; pub mod murmur2; pub mod network; pub mod parse; #[cfg(feature = "gui")] pub mod theme; pub mod tukui_api; pub mod utility; pub mod wowi_api; use crate::error::ClientError; pub type Result<T> = std::result::Result<T, ClientError>;
#[doc = "Reader of register MPCBB1_VCTR34"] pub type R = crate::R<u32, super::MPCBB1_VCTR34>; #[doc = "Writer for register MPCBB1_VCTR34"] pub type W = crate::W<u32, super::MPCBB1_VCTR34>; #[doc = "Register MPCBB1_VCTR34 `reset()`'s with value 0"] impl crate::ResetValue for super::MPCBB1_VCTR34 { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `B1088`"] pub type B1088_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1088`"] pub struct B1088_W<'a> { w: &'a mut W, } impl<'a> B1088_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 `B1089`"] pub type B1089_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1089`"] pub struct B1089_W<'a> { w: &'a mut W, } impl<'a> B1089_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 << 1)) | (((value as u32) & 0x01) << 1); self.w } } #[doc = "Reader of field `B1090`"] pub type B1090_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1090`"] pub struct B1090_W<'a> { w: &'a mut W, } impl<'a> B1090_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 << 2)) | (((value as u32) & 0x01) << 2); self.w } } #[doc = "Reader of field `B1091`"] pub type B1091_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1091`"] pub struct B1091_W<'a> { w: &'a mut W, } impl<'a> B1091_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 << 3)) | (((value as u32) & 0x01) << 3); self.w } } #[doc = "Reader of field `B1092`"] pub type B1092_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1092`"] pub struct B1092_W<'a> { w: &'a mut W, } impl<'a> B1092_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 `B1093`"] pub type B1093_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1093`"] pub struct B1093_W<'a> { w: &'a mut W, } impl<'a> B1093_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 `B1094`"] pub type B1094_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1094`"] pub struct B1094_W<'a> { w: &'a mut W, } impl<'a> B1094_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 } } #[doc = "Reader of field `B1095`"] pub type B1095_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1095`"] pub struct B1095_W<'a> { w: &'a mut W, } impl<'a> B1095_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 << 7)) | (((value as u32) & 0x01) << 7); self.w } } #[doc = "Reader of field `B1096`"] pub type B1096_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1096`"] pub struct B1096_W<'a> { w: &'a mut W, } impl<'a> B1096_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 << 8)) | (((value as u32) & 0x01) << 8); self.w } } #[doc = "Reader of field `B1097`"] pub type B1097_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1097`"] pub struct B1097_W<'a> { w: &'a mut W, } impl<'a> B1097_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 << 9)) | (((value as u32) & 0x01) << 9); self.w } } #[doc = "Reader of field `B1098`"] pub type B1098_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1098`"] pub struct B1098_W<'a> { w: &'a mut W, } impl<'a> B1098_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 << 10)) | (((value as u32) & 0x01) << 10); self.w } } #[doc = "Reader of field `B1099`"] pub type B1099_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1099`"] pub struct B1099_W<'a> { w: &'a mut W, } impl<'a> B1099_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 << 11)) | (((value as u32) & 0x01) << 11); self.w } } #[doc = "Reader of field `B1100`"] pub type B1100_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1100`"] pub struct B1100_W<'a> { w: &'a mut W, } impl<'a> B1100_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 << 12)) | (((value as u32) & 0x01) << 12); self.w } } #[doc = "Reader of field `B1101`"] pub type B1101_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1101`"] pub struct B1101_W<'a> { w: &'a mut W, } impl<'a> B1101_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 `B1102`"] pub type B1102_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1102`"] pub struct B1102_W<'a> { w: &'a mut W, } impl<'a> B1102_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 << 14)) | (((value as u32) & 0x01) << 14); self.w } } #[doc = "Reader of field `B1103`"] pub type B1103_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1103`"] pub struct B1103_W<'a> { w: &'a mut W, } impl<'a> B1103_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 << 15)) | (((value as u32) & 0x01) << 15); self.w } } #[doc = "Reader of field `B1104`"] pub type B1104_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1104`"] pub struct B1104_W<'a> { w: &'a mut W, } impl<'a> B1104_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 << 16)) | (((value as u32) & 0x01) << 16); self.w } } #[doc = "Reader of field `B1105`"] pub type B1105_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1105`"] pub struct B1105_W<'a> { w: &'a mut W, } impl<'a> B1105_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 << 17)) | (((value as u32) & 0x01) << 17); self.w } } #[doc = "Reader of field `B1106`"] pub type B1106_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1106`"] pub struct B1106_W<'a> { w: &'a mut W, } impl<'a> B1106_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 << 18)) | (((value as u32) & 0x01) << 18); self.w } } #[doc = "Reader of field `B1107`"] pub type B1107_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1107`"] pub struct B1107_W<'a> { w: &'a mut W, } impl<'a> B1107_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 << 19)) | (((value as u32) & 0x01) << 19); self.w } } #[doc = "Reader of field `B1108`"] pub type B1108_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1108`"] pub struct B1108_W<'a> { w: &'a mut W, } impl<'a> B1108_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 << 20)) | (((value as u32) & 0x01) << 20); self.w } } #[doc = "Reader of field `B1109`"] pub type B1109_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1109`"] pub struct B1109_W<'a> { w: &'a mut W, } impl<'a> B1109_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 << 21)) | (((value as u32) & 0x01) << 21); self.w } } #[doc = "Reader of field `B1110`"] pub type B1110_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1110`"] pub struct B1110_W<'a> { w: &'a mut W, } impl<'a> B1110_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 `B1111`"] pub type B1111_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1111`"] pub struct B1111_W<'a> { w: &'a mut W, } impl<'a> B1111_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 `B1112`"] pub type B1112_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1112`"] pub struct B1112_W<'a> { w: &'a mut W, } impl<'a> B1112_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 `B1113`"] pub type B1113_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1113`"] pub struct B1113_W<'a> { w: &'a mut W, } impl<'a> B1113_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 << 25)) | (((value as u32) & 0x01) << 25); self.w } } #[doc = "Reader of field `B1114`"] pub type B1114_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1114`"] pub struct B1114_W<'a> { w: &'a mut W, } impl<'a> B1114_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 << 26)) | (((value as u32) & 0x01) << 26); self.w } } #[doc = "Reader of field `B1115`"] pub type B1115_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1115`"] pub struct B1115_W<'a> { w: &'a mut W, } impl<'a> B1115_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 << 27)) | (((value as u32) & 0x01) << 27); self.w } } #[doc = "Reader of field `B1116`"] pub type B1116_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1116`"] pub struct B1116_W<'a> { w: &'a mut W, } impl<'a> B1116_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 << 28)) | (((value as u32) & 0x01) << 28); self.w } } #[doc = "Reader of field `B1117`"] pub type B1117_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1117`"] pub struct B1117_W<'a> { w: &'a mut W, } impl<'a> B1117_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 << 29)) | (((value as u32) & 0x01) << 29); self.w } } #[doc = "Reader of field `B1118`"] pub type B1118_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1118`"] pub struct B1118_W<'a> { w: &'a mut W, } impl<'a> B1118_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 << 30)) | (((value as u32) & 0x01) << 30); self.w } } #[doc = "Reader of field `B1119`"] pub type B1119_R = crate::R<bool, bool>; #[doc = "Write proxy for field `B1119`"] pub struct B1119_W<'a> { w: &'a mut W, } impl<'a> B1119_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 << 31)) | (((value as u32) & 0x01) << 31); self.w } } impl R { #[doc = "Bit 0 - B1088"] #[inline(always)] pub fn b1088(&self) -> B1088_R { B1088_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 1 - B1089"] #[inline(always)] pub fn b1089(&self) -> B1089_R { B1089_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 2 - B1090"] #[inline(always)] pub fn b1090(&self) -> B1090_R { B1090_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bit 3 - B1091"] #[inline(always)] pub fn b1091(&self) -> B1091_R { B1091_R::new(((self.bits >> 3) & 0x01) != 0) } #[doc = "Bit 4 - B1092"] #[inline(always)] pub fn b1092(&self) -> B1092_R { B1092_R::new(((self.bits >> 4) & 0x01) != 0) } #[doc = "Bit 5 - B1093"] #[inline(always)] pub fn b1093(&self) -> B1093_R { B1093_R::new(((self.bits >> 5) & 0x01) != 0) } #[doc = "Bit 6 - B1094"] #[inline(always)] pub fn b1094(&self) -> B1094_R { B1094_R::new(((self.bits >> 6) & 0x01) != 0) } #[doc = "Bit 7 - B1095"] #[inline(always)] pub fn b1095(&self) -> B1095_R { B1095_R::new(((self.bits >> 7) & 0x01) != 0) } #[doc = "Bit 8 - B1096"] #[inline(always)] pub fn b1096(&self) -> B1096_R { B1096_R::new(((self.bits >> 8) & 0x01) != 0) } #[doc = "Bit 9 - B1097"] #[inline(always)] pub fn b1097(&self) -> B1097_R { B1097_R::new(((self.bits >> 9) & 0x01) != 0) } #[doc = "Bit 10 - B1098"] #[inline(always)] pub fn b1098(&self) -> B1098_R { B1098_R::new(((self.bits >> 10) & 0x01) != 0) } #[doc = "Bit 11 - B1099"] #[inline(always)] pub fn b1099(&self) -> B1099_R { B1099_R::new(((self.bits >> 11) & 0x01) != 0) } #[doc = "Bit 12 - B1100"] #[inline(always)] pub fn b1100(&self) -> B1100_R { B1100_R::new(((self.bits >> 12) & 0x01) != 0) } #[doc = "Bit 13 - B1101"] #[inline(always)] pub fn b1101(&self) -> B1101_R { B1101_R::new(((self.bits >> 13) & 0x01) != 0) } #[doc = "Bit 14 - B1102"] #[inline(always)] pub fn b1102(&self) -> B1102_R { B1102_R::new(((self.bits >> 14) & 0x01) != 0) } #[doc = "Bit 15 - B1103"] #[inline(always)] pub fn b1103(&self) -> B1103_R { B1103_R::new(((self.bits >> 15) & 0x01) != 0) } #[doc = "Bit 16 - B1104"] #[inline(always)] pub fn b1104(&self) -> B1104_R { B1104_R::new(((self.bits >> 16) & 0x01) != 0) } #[doc = "Bit 17 - B1105"] #[inline(always)] pub fn b1105(&self) -> B1105_R { B1105_R::new(((self.bits >> 17) & 0x01) != 0) } #[doc = "Bit 18 - B1106"] #[inline(always)] pub fn b1106(&self) -> B1106_R { B1106_R::new(((self.bits >> 18) & 0x01) != 0) } #[doc = "Bit 19 - B1107"] #[inline(always)] pub fn b1107(&self) -> B1107_R { B1107_R::new(((self.bits >> 19) & 0x01) != 0) } #[doc = "Bit 20 - B1108"] #[inline(always)] pub fn b1108(&self) -> B1108_R { B1108_R::new(((self.bits >> 20) & 0x01) != 0) } #[doc = "Bit 21 - B1109"] #[inline(always)] pub fn b1109(&self) -> B1109_R { B1109_R::new(((self.bits >> 21) & 0x01) != 0) } #[doc = "Bit 22 - B1110"] #[inline(always)] pub fn b1110(&self) -> B1110_R { B1110_R::new(((self.bits >> 22) & 0x01) != 0) } #[doc = "Bit 23 - B1111"] #[inline(always)] pub fn b1111(&self) -> B1111_R { B1111_R::new(((self.bits >> 23) & 0x01) != 0) } #[doc = "Bit 24 - B1112"] #[inline(always)] pub fn b1112(&self) -> B1112_R { B1112_R::new(((self.bits >> 24) & 0x01) != 0) } #[doc = "Bit 25 - B1113"] #[inline(always)] pub fn b1113(&self) -> B1113_R { B1113_R::new(((self.bits >> 25) & 0x01) != 0) } #[doc = "Bit 26 - B1114"] #[inline(always)] pub fn b1114(&self) -> B1114_R { B1114_R::new(((self.bits >> 26) & 0x01) != 0) } #[doc = "Bit 27 - B1115"] #[inline(always)] pub fn b1115(&self) -> B1115_R { B1115_R::new(((self.bits >> 27) & 0x01) != 0) } #[doc = "Bit 28 - B1116"] #[inline(always)] pub fn b1116(&self) -> B1116_R { B1116_R::new(((self.bits >> 28) & 0x01) != 0) } #[doc = "Bit 29 - B1117"] #[inline(always)] pub fn b1117(&self) -> B1117_R { B1117_R::new(((self.bits >> 29) & 0x01) != 0) } #[doc = "Bit 30 - B1118"] #[inline(always)] pub fn b1118(&self) -> B1118_R { B1118_R::new(((self.bits >> 30) & 0x01) != 0) } #[doc = "Bit 31 - B1119"] #[inline(always)] pub fn b1119(&self) -> B1119_R { B1119_R::new(((self.bits >> 31) & 0x01) != 0) } } impl W { #[doc = "Bit 0 - B1088"] #[inline(always)] pub fn b1088(&mut self) -> B1088_W { B1088_W { w: self } } #[doc = "Bit 1 - B1089"] #[inline(always)] pub fn b1089(&mut self) -> B1089_W { B1089_W { w: self } } #[doc = "Bit 2 - B1090"] #[inline(always)] pub fn b1090(&mut self) -> B1090_W { B1090_W { w: self } } #[doc = "Bit 3 - B1091"] #[inline(always)] pub fn b1091(&mut self) -> B1091_W { B1091_W { w: self } } #[doc = "Bit 4 - B1092"] #[inline(always)] pub fn b1092(&mut self) -> B1092_W { B1092_W { w: self } } #[doc = "Bit 5 - B1093"] #[inline(always)] pub fn b1093(&mut self) -> B1093_W { B1093_W { w: self } } #[doc = "Bit 6 - B1094"] #[inline(always)] pub fn b1094(&mut self) -> B1094_W { B1094_W { w: self } } #[doc = "Bit 7 - B1095"] #[inline(always)] pub fn b1095(&mut self) -> B1095_W { B1095_W { w: self } } #[doc = "Bit 8 - B1096"] #[inline(always)] pub fn b1096(&mut self) -> B1096_W { B1096_W { w: self } } #[doc = "Bit 9 - B1097"] #[inline(always)] pub fn b1097(&mut self) -> B1097_W { B1097_W { w: self } } #[doc = "Bit 10 - B1098"] #[inline(always)] pub fn b1098(&mut self) -> B1098_W { B1098_W { w: self } } #[doc = "Bit 11 - B1099"] #[inline(always)] pub fn b1099(&mut self) -> B1099_W { B1099_W { w: self } } #[doc = "Bit 12 - B1100"] #[inline(always)] pub fn b1100(&mut self) -> B1100_W { B1100_W { w: self } } #[doc = "Bit 13 - B1101"] #[inline(always)] pub fn b1101(&mut self) -> B1101_W { B1101_W { w: self } } #[doc = "Bit 14 - B1102"] #[inline(always)] pub fn b1102(&mut self) -> B1102_W { B1102_W { w: self } } #[doc = "Bit 15 - B1103"] #[inline(always)] pub fn b1103(&mut self) -> B1103_W { B1103_W { w: self } } #[doc = "Bit 16 - B1104"] #[inline(always)] pub fn b1104(&mut self) -> B1104_W { B1104_W { w: self } } #[doc = "Bit 17 - B1105"] #[inline(always)] pub fn b1105(&mut self) -> B1105_W { B1105_W { w: self } } #[doc = "Bit 18 - B1106"] #[inline(always)] pub fn b1106(&mut self) -> B1106_W { B1106_W { w: self } } #[doc = "Bit 19 - B1107"] #[inline(always)] pub fn b1107(&mut self) -> B1107_W { B1107_W { w: self } } #[doc = "Bit 20 - B1108"] #[inline(always)] pub fn b1108(&mut self) -> B1108_W { B1108_W { w: self } } #[doc = "Bit 21 - B1109"] #[inline(always)] pub fn b1109(&mut self) -> B1109_W { B1109_W { w: self } } #[doc = "Bit 22 - B1110"] #[inline(always)] pub fn b1110(&mut self) -> B1110_W { B1110_W { w: self } } #[doc = "Bit 23 - B1111"] #[inline(always)] pub fn b1111(&mut self) -> B1111_W { B1111_W { w: self } } #[doc = "Bit 24 - B1112"] #[inline(always)] pub fn b1112(&mut self) -> B1112_W { B1112_W { w: self } } #[doc = "Bit 25 - B1113"] #[inline(always)] pub fn b1113(&mut self) -> B1113_W { B1113_W { w: self } } #[doc = "Bit 26 - B1114"] #[inline(always)] pub fn b1114(&mut self) -> B1114_W { B1114_W { w: self } } #[doc = "Bit 27 - B1115"] #[inline(always)] pub fn b1115(&mut self) -> B1115_W { B1115_W { w: self } } #[doc = "Bit 28 - B1116"] #[inline(always)] pub fn b1116(&mut self) -> B1116_W { B1116_W { w: self } } #[doc = "Bit 29 - B1117"] #[inline(always)] pub fn b1117(&mut self) -> B1117_W { B1117_W { w: self } } #[doc = "Bit 30 - B1118"] #[inline(always)] pub fn b1118(&mut self) -> B1118_W { B1118_W { w: self } } #[doc = "Bit 31 - B1119"] #[inline(always)] pub fn b1119(&mut self) -> B1119_W { B1119_W { w: self } } }
use derive_more::{Display, Error}; use actix_web::{HttpResponse, dev::HttpResponseBuilder, error, http::{StatusCode, header}}; #[derive(Debug, Display, Error)] pub enum MServerError { #[display(fmt = "internal error")] InternalError, #[display(fmt = "bad request")] BadClientData, #[display(fmt = "timeout")] Timeout, } impl error::ResponseError for MServerError { fn error_response(&self) -> HttpResponse { HttpResponseBuilder::new(self.status_code()) .set_header(header::CONTENT_TYPE, "text/html; charset=utf-8") .body(self.to_string()) } fn status_code(&self) -> StatusCode { match *self { MServerError::InternalError => StatusCode::INTERNAL_SERVER_ERROR, MServerError::BadClientData => StatusCode::BAD_REQUEST, MServerError::Timeout => StatusCode::GATEWAY_TIMEOUT, } } }
#[doc = "Reader of register OPAMP6_CSR"] pub type R = crate::R<u32, super::OPAMP6_CSR>; #[doc = "Writer for register OPAMP6_CSR"] pub type W = crate::W<u32, super::OPAMP6_CSR>; #[doc = "Register OPAMP6_CSR `reset()`'s with value 0"] impl crate::ResetValue for super::OPAMP6_CSR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `OPAEN`"] pub type OPAEN_R = crate::R<bool, bool>; #[doc = "Write proxy for field `OPAEN`"] pub struct OPAEN_W<'a> { w: &'a mut W, } impl<'a> OPAEN_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 `FORCE_VP`"] pub type FORCE_VP_R = crate::R<bool, bool>; #[doc = "Write proxy for field `FORCE_VP`"] pub struct FORCE_VP_W<'a> { w: &'a mut W, } impl<'a> FORCE_VP_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 << 1)) | (((value as u32) & 0x01) << 1); self.w } } #[doc = "Reader of field `VP_SEL`"] pub type VP_SEL_R = crate::R<u8, u8>; #[doc = "Write proxy for field `VP_SEL`"] pub struct VP_SEL_W<'a> { w: &'a mut W, } impl<'a> VP_SEL_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 << 2)) | (((value as u32) & 0x03) << 2); self.w } } #[doc = "Reader of field `USERTRIM`"] pub type USERTRIM_R = crate::R<bool, bool>; #[doc = "Write proxy for field `USERTRIM`"] pub struct USERTRIM_W<'a> { w: &'a mut W, } impl<'a> USERTRIM_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 `VM_SEL`"] pub type VM_SEL_R = crate::R<u8, u8>; #[doc = "Write proxy for field `VM_SEL`"] pub struct VM_SEL_W<'a> { w: &'a mut W, } impl<'a> VM_SEL_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 << 5)) | (((value as u32) & 0x03) << 5); self.w } } #[doc = "Reader of field `OPAHSM`"] pub type OPAHSM_R = crate::R<bool, bool>; #[doc = "Write proxy for field `OPAHSM`"] pub struct OPAHSM_W<'a> { w: &'a mut W, } impl<'a> OPAHSM_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 << 7)) | (((value as u32) & 0x01) << 7); self.w } } #[doc = "Reader of field `OPAINTOEN`"] pub type OPAINTOEN_R = crate::R<bool, bool>; #[doc = "Write proxy for field `OPAINTOEN`"] pub struct OPAINTOEN_W<'a> { w: &'a mut W, } impl<'a> OPAINTOEN_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 << 8)) | (((value as u32) & 0x01) << 8); self.w } } #[doc = "Reader of field `CALON`"] pub type CALON_R = crate::R<bool, bool>; #[doc = "Write proxy for field `CALON`"] pub struct CALON_W<'a> { w: &'a mut W, } impl<'a> CALON_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 << 11)) | (((value as u32) & 0x01) << 11); self.w } } #[doc = "Reader of field `CALSEL`"] pub type CALSEL_R = crate::R<u8, u8>; #[doc = "Write proxy for field `CALSEL`"] pub struct CALSEL_W<'a> { w: &'a mut W, } impl<'a> CALSEL_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 << 12)) | (((value as u32) & 0x03) << 12); self.w } } #[doc = "Reader of field `PGA_GAIN`"] pub type PGA_GAIN_R = crate::R<u8, u8>; #[doc = "Write proxy for field `PGA_GAIN`"] pub struct PGA_GAIN_W<'a> { w: &'a mut W, } impl<'a> PGA_GAIN_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 << 14)) | (((value as u32) & 0x1f) << 14); self.w } } #[doc = "Reader of field `TRIMOFFSETP`"] pub type TRIMOFFSETP_R = crate::R<u8, u8>; #[doc = "Write proxy for field `TRIMOFFSETP`"] pub struct TRIMOFFSETP_W<'a> { w: &'a mut W, } impl<'a> TRIMOFFSETP_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 << 19)) | (((value as u32) & 0x1f) << 19); self.w } } #[doc = "Reader of field `TRIMOFFSETN`"] pub type TRIMOFFSETN_R = crate::R<u8, u8>; #[doc = "Write proxy for field `TRIMOFFSETN`"] pub struct TRIMOFFSETN_W<'a> { w: &'a mut W, } impl<'a> TRIMOFFSETN_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 << 24)) | (((value as u32) & 0x1f) << 24); self.w } } #[doc = "Reader of field `CALOUT`"] pub type CALOUT_R = crate::R<bool, bool>; #[doc = "Write proxy for field `CALOUT`"] pub struct CALOUT_W<'a> { w: &'a mut W, } impl<'a> CALOUT_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 << 30)) | (((value as u32) & 0x01) << 30); self.w } } #[doc = "Reader of field `LOCK`"] pub type LOCK_R = crate::R<bool, bool>; #[doc = "Write proxy for field `LOCK`"] pub struct LOCK_W<'a> { w: &'a mut W, } impl<'a> LOCK_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 << 31)) | (((value as u32) & 0x01) << 31); self.w } } impl R { #[doc = "Bit 0 - Operational amplifier Enable"] #[inline(always)] pub fn opaen(&self) -> OPAEN_R { OPAEN_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 1 - FORCE_VP"] #[inline(always)] pub fn force_vp(&self) -> FORCE_VP_R { FORCE_VP_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bits 2:3 - VP_SEL"] #[inline(always)] pub fn vp_sel(&self) -> VP_SEL_R { VP_SEL_R::new(((self.bits >> 2) & 0x03) as u8) } #[doc = "Bit 4 - USERTRIM"] #[inline(always)] pub fn usertrim(&self) -> USERTRIM_R { USERTRIM_R::new(((self.bits >> 4) & 0x01) != 0) } #[doc = "Bits 5:6 - VM_SEL"] #[inline(always)] pub fn vm_sel(&self) -> VM_SEL_R { VM_SEL_R::new(((self.bits >> 5) & 0x03) as u8) } #[doc = "Bit 7 - OPAHSM"] #[inline(always)] pub fn opahsm(&self) -> OPAHSM_R { OPAHSM_R::new(((self.bits >> 7) & 0x01) != 0) } #[doc = "Bit 8 - OPAINTOEN"] #[inline(always)] pub fn opaintoen(&self) -> OPAINTOEN_R { OPAINTOEN_R::new(((self.bits >> 8) & 0x01) != 0) } #[doc = "Bit 11 - CALON"] #[inline(always)] pub fn calon(&self) -> CALON_R { CALON_R::new(((self.bits >> 11) & 0x01) != 0) } #[doc = "Bits 12:13 - CALSEL"] #[inline(always)] pub fn calsel(&self) -> CALSEL_R { CALSEL_R::new(((self.bits >> 12) & 0x03) as u8) } #[doc = "Bits 14:18 - PGA_GAIN"] #[inline(always)] pub fn pga_gain(&self) -> PGA_GAIN_R { PGA_GAIN_R::new(((self.bits >> 14) & 0x1f) as u8) } #[doc = "Bits 19:23 - TRIMOFFSETP"] #[inline(always)] pub fn trimoffsetp(&self) -> TRIMOFFSETP_R { TRIMOFFSETP_R::new(((self.bits >> 19) & 0x1f) as u8) } #[doc = "Bits 24:28 - TRIMOFFSETN"] #[inline(always)] pub fn trimoffsetn(&self) -> TRIMOFFSETN_R { TRIMOFFSETN_R::new(((self.bits >> 24) & 0x1f) as u8) } #[doc = "Bit 30 - CALOUT"] #[inline(always)] pub fn calout(&self) -> CALOUT_R { CALOUT_R::new(((self.bits >> 30) & 0x01) != 0) } #[doc = "Bit 31 - LOCK"] #[inline(always)] pub fn lock(&self) -> LOCK_R { LOCK_R::new(((self.bits >> 31) & 0x01) != 0) } } impl W { #[doc = "Bit 0 - Operational amplifier Enable"] #[inline(always)] pub fn opaen(&mut self) -> OPAEN_W { OPAEN_W { w: self } } #[doc = "Bit 1 - FORCE_VP"] #[inline(always)] pub fn force_vp(&mut self) -> FORCE_VP_W { FORCE_VP_W { w: self } } #[doc = "Bits 2:3 - VP_SEL"] #[inline(always)] pub fn vp_sel(&mut self) -> VP_SEL_W { VP_SEL_W { w: self } } #[doc = "Bit 4 - USERTRIM"] #[inline(always)] pub fn usertrim(&mut self) -> USERTRIM_W { USERTRIM_W { w: self } } #[doc = "Bits 5:6 - VM_SEL"] #[inline(always)] pub fn vm_sel(&mut self) -> VM_SEL_W { VM_SEL_W { w: self } } #[doc = "Bit 7 - OPAHSM"] #[inline(always)] pub fn opahsm(&mut self) -> OPAHSM_W { OPAHSM_W { w: self } } #[doc = "Bit 8 - OPAINTOEN"] #[inline(always)] pub fn opaintoen(&mut self) -> OPAINTOEN_W { OPAINTOEN_W { w: self } } #[doc = "Bit 11 - CALON"] #[inline(always)] pub fn calon(&mut self) -> CALON_W { CALON_W { w: self } } #[doc = "Bits 12:13 - CALSEL"] #[inline(always)] pub fn calsel(&mut self) -> CALSEL_W { CALSEL_W { w: self } } #[doc = "Bits 14:18 - PGA_GAIN"] #[inline(always)] pub fn pga_gain(&mut self) -> PGA_GAIN_W { PGA_GAIN_W { w: self } } #[doc = "Bits 19:23 - TRIMOFFSETP"] #[inline(always)] pub fn trimoffsetp(&mut self) -> TRIMOFFSETP_W { TRIMOFFSETP_W { w: self } } #[doc = "Bits 24:28 - TRIMOFFSETN"] #[inline(always)] pub fn trimoffsetn(&mut self) -> TRIMOFFSETN_W { TRIMOFFSETN_W { w: self } } #[doc = "Bit 30 - CALOUT"] #[inline(always)] pub fn calout(&mut self) -> CALOUT_W { CALOUT_W { w: self } } #[doc = "Bit 31 - LOCK"] #[inline(always)] pub fn lock(&mut self) -> LOCK_W { LOCK_W { w: self } } }
// Copyright 2019-2020 PolkaX. Licensed under MIT or Apache-2.0. use super::*; use bytes::Bytes; use cid::{Cid, IntoExt}; use ipld_core::struct_to_cbor_value; #[test] fn test_kv() { let b: Bytes = vec![1_u8, 2, 3].into(); let v = struct_to_cbor_value(&b).unwrap(); let kv: KVT = ("123".to_string(), v); let r = serde_cbor::to_vec(&kv).unwrap(); println!("{:?}", r); let result = vec![130_u8, 99, 49, 50, 51, 67, 1, 2, 3]; assert_eq!(r, result); let kv2: KVT = serde_cbor::from_slice(&r).unwrap(); assert_eq!(kv, kv2); } #[test] fn test_pointer_and_node() { let b: Bytes = vec![1_u8, 2, 3].into(); let v = struct_to_cbor_value(&b).unwrap(); let kv: KVT = ("123".to_string(), v.clone()); let kv2: KVT = ("124".to_string(), v); let pointer = Item::from_kvs(vec![kv, kv2]); let r = serde_cbor::to_vec(&pointer).unwrap(); println!("{:?}", r); assert_eq!( r, vec![161, 97, 49, 130, 130, 99, 49, 50, 51, 67, 1, 2, 3, 130, 99, 49, 50, 52, 67, 1, 2, 3] ); let p2: Item = serde_cbor::from_slice(&r).unwrap(); assert_eq!(p2, pointer); let cid = Cid::new_v0(multihash::Sha2_256::digest(b"something").into_ext()).unwrap(); let pointer2 = Item::from_link(cid); let r = serde_cbor::to_vec(&pointer2).unwrap(); println!("{:?}", r); assert_eq!( r, vec![ 161, 97, 48, 216, 42, 88, 35, 0, 18, 32, 63, 201, 182, 137, 69, 157, 115, 143, 140, 136, 163, 164, 138, 169, 227, 53, 66, 1, 107, 122, 64, 82, 224, 1, 170, 165, 54, 252, 167, 72, 19, 203 ] ); // bitfield is 0 let node = test_node("0", vec![pointer.clone(), pointer2.clone()]); let r = serde_cbor::to_vec(&node).unwrap(); println!("{:?}", r); assert_eq!( r, vec![ 130, 64, 130, 161, 97, 49, 130, 130, 99, 49, 50, 51, 67, 1, 2, 3, 130, 99, 49, 50, 52, 67, 1, 2, 3, 161, 97, 48, 216, 42, 88, 35, 0, 18, 32, 63, 201, 182, 137, 69, 157, 115, 143, 140, 136, 163, 164, 138, 169, 227, 53, 66, 1, 107, 122, 64, 82, 224, 1, 170, 165, 54, 252, 167, 72, 19, 203 ] ); let node: Node = serde_cbor::from_slice(&r).unwrap(); println!("{:?}", node); // bitfield is 9999 let node = test_node("9999", vec![pointer.clone(), pointer2.clone()]); let r = serde_cbor::to_vec(&node).unwrap(); println!("{:?}", r); assert_eq!( r, vec![ 130, 66, 39, 15, 130, 161, 97, 49, 130, 130, 99, 49, 50, 51, 67, 1, 2, 3, 130, 99, 49, 50, 52, 67, 1, 2, 3, 161, 97, 48, 216, 42, 88, 35, 0, 18, 32, 63, 201, 182, 137, 69, 157, 115, 143, 140, 136, 163, 164, 138, 169, 227, 53, 66, 1, 107, 122, 64, 82, 224, 1, 170, 165, 54, 252, 167, 72, 19, 203 ] ); let node: Node = serde_cbor::from_slice(&r).unwrap(); println!("{:?}", node); // bitfield is 0x12345678 let node = test_node("305419896", vec![pointer.clone(), pointer2.clone()]); let r = serde_cbor::to_vec(&node).unwrap(); println!("{:?}", r); assert_eq!( r, vec![ 130, 68, 18, 52, 86, 120, 130, 161, 97, 49, 130, 130, 99, 49, 50, 51, 67, 1, 2, 3, 130, 99, 49, 50, 52, 67, 1, 2, 3, 161, 97, 48, 216, 42, 88, 35, 0, 18, 32, 63, 201, 182, 137, 69, 157, 115, 143, 140, 136, 163, 164, 138, 169, 227, 53, 66, 1, 107, 122, 64, 82, 224, 1, 170, 165, 54, 252, 167, 72, 19, 203 ] ); let node: Node = serde_cbor::from_slice(&r).unwrap(); println!("{:?}", node); let node = test_node( "11579208923731619542357098500868790785326998466564056403945758400791312", vec![pointer, pointer2], ); let r = serde_cbor::to_vec(&node).unwrap(); let node: Node = serde_cbor::from_slice(&r).unwrap(); println!("{:?}", node); }
mod arrow_interop; mod clickhouse; mod error; mod frame; mod geom; mod utils; use pyo3::{prelude::*, wrap_pyfunction, Python}; use tracing_subscriber::EnvFilter; use crate::clickhouse::init_clickhouse_submodule; use crate::frame::{PyDataFrame, PyH3DataFrame}; use crate::geom::init_geom_submodule; /// version of the module #[pyfunction] fn version() -> String { env!("CARGO_PKG_VERSION").to_string() } /// Check if this module has been compiled in release mode. #[pyfunction] fn is_release_build() -> bool { #[cfg(debug_assertions)] return false; #[cfg(not(debug_assertions))] return true; } #[pymodule] fn ukis_h3cellstorepy(py: Python, m: &PyModule) -> PyResult<()> { tracing_subscriber::fmt() //.event_format(tracing_subscriber::fmt::format::json()) // requires json feature //.with_max_level(tracing::Level::TRACE) .with_env_filter(EnvFilter::from_default_env()) .with_timer(tracing_subscriber::fmt::time()) .init(); m.add_function(wrap_pyfunction!(version, m)?)?; m.add_function(wrap_pyfunction!(is_release_build, m)?)?; m.add("PyH3DataFrame", py.get_type::<PyH3DataFrame>())?; m.add("PyDataFrame", py.get_type::<PyDataFrame>())?; let clickhouse_submod = PyModule::new(py, "clickhouse")?; init_clickhouse_submodule(py, clickhouse_submod)?; m.add_submodule(clickhouse_submod)?; let geom_submod = PyModule::new(py, "geom")?; init_geom_submodule(py, geom_submod)?; m.add_submodule(geom_submod)?; Ok(()) }
use core::sync::atomic::{AtomicU32, Ordering}; static NEXT: AtomicU32 = AtomicU32::new(1); pub fn rand() -> u32 { loop { let cur = NEXT.load(Ordering::Relaxed); let next = cur * 214013 + 2531011; let old = NEXT.compare_and_swap(cur, next, Ordering::Relaxed); if old == cur { return (next >> 16) & 0x7fff; } } } pub fn srand(seed: u32) { NEXT.store(seed, Ordering::Relaxed); }
use std::path::Path; use std::process::Command; fn main() { let files = vec!["Message Passing and PubSub.mp4"]; let src_path = "/home/susilo/Videos"; for x in files { let path = Path::new(x); let path_name = format!("{}/{}", src_path.to_owned(), x); let ext = get_ext(&path); let out_filename = format!("{}/{}", &src_path.to_owned(), &x.replace(ext, "mp3")); println!("{}", x); let mut child = Command::new("ffmpeg") .arg("-i") .arg(path_name) .arg("-b:a") .arg("192K") .arg("-vn") .arg(out_filename) .spawn() .expect("failed to execute child"); let _ = child.wait().expect("failed to wait on child"); } } fn get_ext(file_name: &Path) -> &str { file_name.extension().unwrap().to_str().unwrap_or("") }
extern crate sfml; use sfml::graphics::{Color, RenderTarget, RenderWindow, Sprite, Texture, Transformable}; use sfml::window::{Event, Key, Style}; use std::thread::sleep; use std::time::Duration; use cpu::CPU; use machine::clock::Clock; mod clock; pub mod io; // 1 Billion nanoseconds divided by 2 million cycles a second const CYCLE_TIME_NANOS: u64 = 1_000_000_000 / 2_000_000; const INTERRUPT_TIME: Duration = Duration::from_micros(1_000_000 / 120); const SCALE: u32 = 8; pub struct Machine { cpu: CPU, interrupt_timer: Clock, cpu_timer: Clock, next_interrupt: u8, window: RenderWindow, keys: u8, } impl Machine { pub fn new(mut buffer: Vec<u8>) -> Machine { buffer.resize(0x10000, 0); let window = RenderWindow::new( (224 * SCALE, 256 * SCALE), "Rusty Invaders", Style::CLOSE, &Default::default(), ); Machine { cpu: CPU::new(buffer, true), interrupt_timer: Clock::new(), cpu_timer: Clock::new(), next_interrupt: 1, window, keys: 0, } } fn key_press(&mut self, key: Key) -> () { match key { Key::C => { self.keys |= 1; } Key::Return => { self.keys |= 1 << 2; } Key::Space => { self.keys |= 1 << 4; } Key::Left => { self.keys |= 1 << 5; } Key::Right => { self.keys |= 1 << 6; } _ => (), } self.cpu.set_input(1, self.keys); } fn key_release(&mut self, key: Key) -> () { match key { Key::C => { self.keys &= !1; } Key::Return => { self.keys &= !(1 << 2); } Key::Space => { self.keys &= !(1 << 4); } Key::Left => { self.keys &= !(1 << 5); } Key::Right => { self.keys &= !(1 << 6); } _ => (), } self.cpu.set_input(1, self.keys); } fn draw(&mut self) -> () { let mut texture = Texture::new(256, 224).expect("Unable to create texture"); let mut buffer = Vec::new(); for pixel in self.cpu.get_frame() { for i in 0..8 { let res = if (pixel & 1 << i) > 0 { 0xff } else { 0x00 }; buffer.push(res as u8); buffer.push(res as u8); buffer.push(res as u8); buffer.push(255); } } texture.update_from_pixels(&buffer, 256, 224, 0, 0); let mut sprite = Sprite::with_texture(&texture); sprite.set_rotation(270f32); sprite.set_position((0f32, SCALE as f32 * 256f32)); sprite.set_scale((SCALE as f32, SCALE as f32)); self.window.clear(&Color::BLACK); self.window.draw(&sprite); self.window.display(); } fn sync(&mut self, cycles: u8) -> () { let cycle_duration = Duration::from_nanos(u64::from(cycles) * CYCLE_TIME_NANOS); let elapsed = self.cpu_timer.elapsed(); if cycle_duration > elapsed { sleep(cycle_duration - elapsed); } self.cpu_timer.reset_last_time(); } pub fn emulate(&mut self) -> () { loop { if self.cpu.int_enabled && self.interrupt_timer.elapsed() > INTERRUPT_TIME { while let Some(event) = self.window.poll_event() { match event { Event::Closed | Event::KeyPressed { code: Key::Escape, .. } => return, Event::KeyPressed { code, .. } => self.key_press(code), Event::KeyReleased { code, .. } => self.key_release(code), _ => {} } } self.interrupt_timer.reset_last_time(); self.cpu.disable_interrupt(); match self.next_interrupt { 1 => { self.cpu.interrupt(1); self.next_interrupt = 2; } 2 => { self.draw(); self.cpu.interrupt(2); self.next_interrupt = 1; } _ => panic!("Invalid interrupt"), } } let cycles = match self.cpu.step() { None => break, Some(cycles) => cycles, }; self.sync(cycles); } } }
// This file is part of linux-epoll. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/linux-epoll/master/COPYRIGHT. No part of linux-epoll, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file. // Copyright © 2019 The developers of linux-epoll. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/linux-epoll/master/COPYRIGHT. /// Why was a digest algorithm rejected ignored? #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum DigestAlgorithmRejectedBecauseReason { /// SHA-1, although mandatory, is broken. Sha1IsBroken, /// GOST R 34.11-94 may been broken; it has been replaced in Russian standards with more a modern algorithm Gost94MayBeBroken, /// It is impossible to use unassigned values. Unassigned(u8), }
extern crate game_1; mod game; pub use game::*;
#![feature(test)] #![feature(specialization)] extern crate test; extern crate rand; extern crate num_traits; #[macro_use] mod macros; pub mod arithimpl; pub mod traits; pub mod core; pub mod coding; pub use traits::*; pub use coding::*; pub use core::Keypair; pub use core::standard::EncryptionKey; pub use core::crt::DecryptionKey; /// Parameterised type onto which all operations are added (see `Paillier`). pub struct AbstractPaillier<I> { junk: ::std::marker::PhantomData<I> } impl<I> AbstractScheme for AbstractPaillier<I> { type BigInteger=I; } /************************* Ramp instance *************************/ #[cfg(feature="inclramp")] mod rampinstance { pub use arithimpl::rampimpl::BigInteger as RampBigInteger; pub type RampPaillier = ::AbstractPaillier<RampBigInteger>; #[cfg(feature="defaultramp")] pub type BigInteger = RampBigInteger; #[cfg(feature="defaultramp")] pub type Paillier = RampPaillier; } #[cfg(feature="inclramp")] pub use self::rampinstance::*; /************************* Framp instance *************************/ #[cfg(feature="inclframp")] mod frampinstance { pub use arithimpl::frampimpl::BigInteger as FrampBigInteger; pub type FrampPaillier = ::AbstractPaillier<FrampBigInteger>; #[cfg(feature="defaultframp")] pub type BigInteger = FrampBigInteger; #[cfg(feature="defaultframp")] pub type Paillier = FrampPaillier; } #[cfg(feature="inclframp")] pub use self::frampinstance::*; /************** GMP instance **************/ #[cfg(feature="inclgmp")] mod gmpinstance { pub use arithimpl::gmpimpl::BigInteger as GmpBigInteger; pub type GmpPaillier = ::AbstractPaillier<GmpBigInteger>; #[cfg(feature="defaultgmp")] pub type BigInteger = GmpBigInteger; #[cfg(feature="defaultgmp")] pub type Paillier = GmpPaillier; } #[cfg(feature="inclgmp")] pub use self::gmpinstance::*; /************** Num instance **************/ #[cfg(feature="inclnum")] mod numinstance { pub use arithimpl::numimpl::BigInteger as NumBigInteger; pub type NumPaillier = ::AbstractPaillier<NumBigInteger>; #[cfg(feature="defaultnum")] pub type BigInteger = NumBigInteger; #[cfg(feature="defaultnum")] pub type Paillier = NumPaillier; } #[cfg(feature="inclnum")] pub use self::numinstance::*;
fn main() { cxx_build::bridge("src/main.rs") .file("src/blobstore.cc") .flag_if_supported("-std=c++14") .compile("cxx-demo") }
// Get Maximum in Generated Array // https://leetcode.com/explore/challenge/card/january-leetcoding-challenge-2021/581/week-3-january-15th-january-21st/3605/ pub struct Solution; const SIZE: usize = 101; impl Solution { pub fn get_maximum_generated(n: i32) -> i32 { let mut nums: [i32; SIZE] = [0; SIZE]; nums[1] = 1; if n < 2 { return nums[n as usize]; } let mut max = 1; for i in 2..=(n as usize) { let num = if i % 2 == 0 { nums[i / 2] } else { nums[i / 2] + nums[i / 2 + 1] }; nums[i] = num; max = max.max(num); } max } } #[cfg(test)] mod tests { use super::*; #[test] fn example1() { assert_eq!(Solution::get_maximum_generated(7), 3); } #[test] fn example2() { assert_eq!(Solution::get_maximum_generated(2), 1); } #[test] fn example3() { assert_eq!(Solution::get_maximum_generated(3), 2); } }
pub enum SVMError { InvalidMemory, InvalidRegister, InvalidOpCode, StackEmpty, WriteError, ReadError, }
use P80::graph_converters::{labeled, unlabeled}; pub fn main() { let g = unlabeled::from_string("[b-c, f-c, g-h, d, f-b, k-f, h-g]"); println!( "unlabeled graph (graph-term form)\n{:?}", unlabeled::to_term_form(&g) ); let g = labeled::from_string("[k, m-p/5, m-q/7, p-q/9]"); println!( "labeled graph (adjacency-list form)\n{:?}", labeled::to_adjacent_form(&g) ); }
#![no_std] #[macro_use] extern crate crypto_tests; extern crate rc2; use crypto_tests::block_cipher::{BlockCipherTest, encrypt_decrypt}; extern crate block_cipher_trait; use block_cipher_trait::generic_array::GenericArray; use block_cipher_trait::BlockCipher; #[test] fn rc2() { let tests = new_block_cipher_tests!("1", "2", "3", "7"); encrypt_decrypt::<rc2::RC2>(&tests); } #[test] fn rc2_effective_key_64() { let tests = new_block_cipher_tests!("4", "5", "6"); for test in &tests { let cipher = rc2::RC2::new_with_eff_key_len(test.key, 64); let mut buf = GenericArray::clone_from_slice(test.input); cipher.encrypt_block(&mut buf); assert_eq!(test.output, &buf[..]); let mut buf = GenericArray::clone_from_slice(test.output); cipher.decrypt_block(&mut buf); assert_eq!(test.input, &buf[..]); } } #[test] fn rc2_effective_key_129() { let tests = new_block_cipher_tests!("8"); for test in &tests { let cipher = rc2::RC2::new_with_eff_key_len(test.key, 129); let mut buf = GenericArray::clone_from_slice(test.input); cipher.encrypt_block(&mut buf); assert_eq!(test.output, &buf[..]); let mut buf = GenericArray::clone_from_slice(test.output); cipher.decrypt_block(&mut buf); assert_eq!(test.input, &buf[..]); } }
mod buf; pub(crate) mod drain; pub(crate) mod exec; pub(crate) mod io; mod lazy; mod never; pub(crate) use self::buf::StaticBuf; pub(crate) use self::exec::Exec; pub(crate) use self::lazy::{lazy, Started as Lazy}; pub use self::never::Never;
pub struct MemorySet { pub mapping: Mapping, pub segment: Vec<segment>, } impl MemorySet { pub fn new_kernel() -> MemoryResult<MemorySet> { extern "c" { fn text_start(); fn rodata_start(); fn data_start(); fn bss_start(); } let segment = vec![ Segment { map_type: MapType::Liner, range: Range::from((text_start as usize)..(rodata_start as usize)) flags: Flags::READABLE | Flags::EXECUTABLE, }, Segment { map_type: MapType::Liner, range: Range::from((rodata_start as usize)..(data_start as usize)), flags: Flags::READABLE }, Segment { map_type: MapType::Liner, range: Range::from(VirtualAddress::from(bss_start as usize)..*KERBEL_END_ADDRESS), flags: Flags::READABLE | Flags::WRITABLE, }, Segment { map_type: MapType::Liner, range: Range::from(*KERBEL_END_ADDRESS..VirtualAddress::from(MEMORY_END_ADDRESS)), flags: Flags::READABLE | Flags::WRITABLE, }, Segment { map_type: MapType::Linear, range: Range::from(*KERBEL_END_ADDRESS..VirtualAddress::from(MEMORY_END_ADDRESS)), flags: Flags::READABLE | Flags::WRITABLE, }, ]; let mut mapping = Mapping::new()?; for segment in segments.iter() { mapping.map(segment,None)?; } Ok(MemorySet{mapping,segemts}) } pub fn activate(&self) { self.mapping.activate() } }
use std::ptr; use std::mem; use std::alloc; use libc; fn alloc(size: usize) -> *mut u8 { let align = mem::align_of::<usize>(); let layout = alloc::Layout::from_size_align(size, align).unwrap(); unsafe { alloc::alloc(layout) } } fn dealloc(ptr: *mut u8, size: usize) { let align = mem::align_of::<usize>(); let layout = alloc::Layout::from_size_align(size, align).unwrap(); unsafe { ptr::drop_in_place(ptr); alloc::dealloc(ptr, layout); } } fn alloc_box(len: usize) -> *mut u8 { Box::into_raw(vec![0; len].into_boxed_slice()) as *mut u8 } fn alloc_box2(len: usize) -> *mut u8 { let mut v = Vec::<u8>::with_capacity(len); unsafe { v.set_len(len); } Box::into_raw(v.into_boxed_slice()) as *mut u8 } fn dealloc_box(ptr: *mut u8, _size: usize) { unsafe { drop(Box::from_raw(ptr)); } } fn alloc_libc(size: usize) -> *mut u8 { unsafe { libc::malloc(size) as *mut u8 } } fn dealloc_libc(ptr: *mut u8, _size: usize) { unsafe { libc::free(ptr as *mut libc::c_void) } } fn consume(ptr: *mut u8, len: usize) { unsafe { let s = std::slice::from_raw_parts(ptr, len); println!("{:?}", s); } } fn write(ptr: *mut u8, len: usize) { unsafe { for i in 0..len { ptr.add(i).write((i + 11) as u8); } } } fn exec(n: usize, alloc_f: fn (usize) -> *mut u8, dealloc_f: fn (*mut u8, usize)) { let p = alloc_f(n); write(p, n); consume(p, n); consume(p, n); dealloc_f(p, n); consume(p, n); } fn main() { println!("--- alloc, dealloc ---"); exec(5, alloc, dealloc); println!("--- Box ---"); exec(5, alloc_box, dealloc_box); println!("--- Box with_capacity ---"); exec(5, alloc_box2, dealloc_box); println!("--- libc::malloc, free ---"); exec(5, alloc_libc, dealloc_libc); }
use std::env; use std::fs::File; use std::io; use std::io::Read; fn main() { let file_content = open_file(); lex(&file_content); } fn open_file() -> String { let first_arg: String = env::args().nth(1).expect("Please enter a valid filename"); let file_content: String = read_to_string(&first_arg).expect("Failed to read the file"); file_content } fn read_to_string(filename: &str) -> Result<String, io::Error> { let mut file = match File::open(&filename) { Ok(f) => f, Err(e) => return Err(e), }; let mut file_content = String::new(); match file.read_to_string(&mut file_content) { Ok(_) => Ok(file_content), Err(e) => Err(e), } } fn lex(file_content: &str) { let mut tokens = String::new(); let mut state: i32 = 0; let mut to_print = String::new(); for c in file_content.chars() { tokens.push(c); if tokens == " " { tokens = "".to_string(); } else if tokens == "print" { println!("Found: \"print\""); tokens = "".to_string(); } else if tokens == "\"" { if state == 0 { state = 1; } else if state == 1 { println!("Found a string."); to_print = "".to_string(); state = 0; } } else if state == 1 { to_print.push(c); tokens = "".to_string(); } } }
use super::{all_fields, Value}; use std::collections::BTreeMap; /// Iterates over all paths in form "a.b[0].c[1]" in alphabetical order. /// It is implemented as a wrapper around `all_fields` to reduce code /// duplication. pub fn keys<'a>(fields: &'a BTreeMap<String, Value>) -> impl Iterator<Item = String> + 'a { all_fields(fields).map(|(k, _)| k) } #[cfg(test)] mod test { use super::super::test::fields_from_json; use super::*; use serde_json::json; #[test] fn keys_simple() { let fields = fields_from_json(json!({ "field2": 3, "field1": 4, "field3": 5 })); let expected: Vec<_> = vec!["field1", "field2", "field3"] .into_iter() .map(String::from) .collect(); let collected: Vec<_> = keys(&fields).collect(); assert_eq!(collected, expected); } #[test] fn keys_nested() { let fields = fields_from_json(json!({ "a": { "b": { "c": 5 }, "a": 4, "array": [null, 3, { "x": 1 }, [2]] } })); let expected: Vec<_> = vec![ "a.a", "a.array[0]", "a.array[1]", "a.array[2].x", "a.array[3][0]", "a.b.c", ] .into_iter() .map(String::from) .collect(); let collected: Vec<_> = keys(&fields).collect(); assert_eq!(collected, expected); } }
use crate::prelude::*; use std::os::raw::c_void; use std::ptr; #[repr(C)] #[derive(Debug)] pub struct VkRayTracingShaderGroupCreateInfoNV { pub sType: VkStructureType, pub pNext: *const c_void, pub r#type: VkRayTracingShaderGroupTypeNV, pub generalShader: u32, pub closestHitShader: u32, pub anyHitShader: u32, pub intersectionShader: u32, } impl VkRayTracingShaderGroupCreateInfoNV { pub fn new( r#type: VkRayTracingShaderGroupTypeNV, general_shader: u32, closest_hit_shader: u32, any_hit_shader: u32, intersection_shader: u32, ) -> Self { VkRayTracingShaderGroupCreateInfoNV { sType: VK_STRUCTURE_TYPE_RAY_TRACING_SHADER_GROUP_CREATE_INFO_NV, pNext: ptr::null(), r#type, generalShader: general_shader, closestHitShader: closest_hit_shader, anyHitShader: any_hit_shader, intersectionShader: intersection_shader, } } }
use std::{num::NonZeroU32, sync::mpsc, time::Instant}; use vulkayes_core::{ash::vk, log, memory::device::naive::NaiveDeviceMemoryAllocator, prelude::*, resource::image::params::ImageViewRange}; use vulkayes_window::winit::winit; use winit::window::Window; pub mod frame; pub mod input; pub mod setup; use std::ops::Deref; use input::InputEvent; use vulkayes_core::swapchain::SwapchainCreateInfo; use crate::{dirty_mark, state::frame::CommandState}; // Controls whether `NextFrame::submit_present` waits for the queue operations to finish. Useful for benchmarks. pub const WAIT_AFTER_FRAME: bool = true; pub trait ChildExampleState { fn render_pass(&self) -> vk::RenderPass; } #[derive(Debug)] pub struct BaseState { pub instance: Vrc<Instance>, pub device: Vrc<Device>, pub present_queue: Vrc<Queue> } #[derive(Debug)] pub struct SwapchainState { pub create_info: SwapchainCreateInfo<[u32; 1]>, pub swapchain: Vrc<Swapchain>, pub present_views: Vec<Vrc<ImageView>>, render_pass: Option<vk::RenderPass>, pub framebuffers: Vec<vk::Framebuffer>, pub scissors: vk::Rect2D, pub viewport: vk::Viewport, outdated: u8, was_recreated: bool } impl Drop for SwapchainState { fn drop(&mut self) { unsafe { for framebuffer in self.framebuffers.drain(..) { self.swapchain .device() .destroy_framebuffer(framebuffer, None); } } } } pub struct ApplicationState { pub base: BaseState, pub device_memory_allocator: NaiveDeviceMemoryAllocator, pub swapchain: SwapchainState, pub surface_size: [NonZeroU32; 2], pub depth_image_view: Vrc<ImageView>, pub command: frame::CommandState, input_receiver: mpsc::Receiver<InputEvent>, last_before: Option<Instant>, last_before_middle: Option<[Instant; 2]> } impl ApplicationState { fn create_present_views(images: Vec<Vrc<SwapchainImage>>) -> Vec<Vrc<ImageView>> { images .into_iter() .map(|image| { ImageView::new( image.into(), ImageViewRange::Type2D(0, NonZeroU32::new(1).unwrap(), 0), None, Default::default(), vk::ImageAspectFlags::COLOR, Default::default() ) .expect("Could not create image view") }) .collect() } fn create_depth_image_view( queue: &Queue, size: ImageSize, device_memory_allocator: &NaiveDeviceMemoryAllocator, command: &mut CommandState ) -> Vrc<ImageView> { let depth_image_view = { let depth_image = Image::new( queue.device().clone(), vk::Format::D16_UNORM, size.into(), Default::default(), vk::ImageUsageFlags::DEPTH_STENCIL_ATTACHMENT, queue.into(), vulkayes_core::resource::image::params::ImageAllocatorParams::Some { allocator: device_memory_allocator, requirements: vk::MemoryPropertyFlags::DEVICE_LOCAL }, Default::default() ) .expect("Could not create depth image"); ImageView::new( depth_image.into(), ImageViewRange::Type2D(0, NonZeroU32::new(1).unwrap(), 0), None, Default::default(), vk::ImageAspectFlags::DEPTH, Default::default() ) .expect("Chould not create depth image view") }; command.execute_setup_blocking(queue, |command_buffer| { let cb_lock = command_buffer.lock().expect("vutex poisoned"); let layout_transition_barriers = vk::ImageMemoryBarrier::builder() .image(*depth_image_view.image().deref().deref()) .old_layout(vk::ImageLayout::UNDEFINED) .dst_access_mask(vk::AccessFlags::DEPTH_STENCIL_ATTACHMENT_READ | vk::AccessFlags::DEPTH_STENCIL_ATTACHMENT_WRITE) .new_layout(vk::ImageLayout::DEPTH_STENCIL_ATTACHMENT_OPTIMAL) .subresource_range(vk::ImageSubresourceRangeBuilder::from(depth_image_view.subresource_range()).build()); unsafe { command_buffer.pool().device().cmd_pipeline_barrier( *cb_lock, vk::PipelineStageFlags::BOTTOM_OF_PIPE, vk::PipelineStageFlags::LATE_FRAGMENT_TESTS, vk::DependencyFlags::empty(), &[], &[], &[layout_transition_barriers.build()] ); } }); depth_image_view } fn create_framebuffers<'a>( renderpass: vk::RenderPass, present_image_views: impl Iterator<Item = &'a Vrc<ImageView>>, depth_image_view: &Vrc<ImageView> ) -> Vec<vk::Framebuffer> { let framebuffers: Vec<vk::Framebuffer> = present_image_views .map(|present_image_view| { let framebuffer_attachments = [*present_image_view.deref().deref(), *depth_image_view.deref().deref()]; let frame_buffer_create_info = vk::FramebufferCreateInfo::builder() .render_pass(renderpass) .attachments(&framebuffer_attachments) .width(present_image_view.subresource_image_size().width().get()) .height(present_image_view.subresource_image_size().height().get()) .layers(1); vulkayes_core::log::debug!( "Creating framebuffers for {:#?}", framebuffer_attachments ); unsafe { present_image_view .image() .device() .create_framebuffer(&frame_buffer_create_info, None) .unwrap() } }) .collect(); framebuffers } /// Checks `self.swapchain.outdated` and attempts to recreate the swapchain. fn check_and_recreate_swapchain(&mut self) { self.swapchain.was_recreated = false; if self.swapchain.outdated != 0 { self.swapchain.create_info.image_info.image_size = ImageSize::new_2d( self.surface_size[0], self.surface_size[1], NonZeroU32::new(1).unwrap(), MipmapLevels::One() ); let new_data = self.swapchain.swapchain.recreate( self.swapchain.create_info, Default::default() ); match new_data { Err(e) => { log::error!("Could not recreate swapchain {}", e); if self.swapchain.outdated > 200 { panic!("Could not recreate swapchain for 200 frames"); } } Ok(data) => { self.swapchain.swapchain = data.swapchain; self.swapchain.present_views = Self::create_present_views(data.images); self.depth_image_view = Self::create_depth_image_view( &self.base.present_queue, self.swapchain.create_info.image_info.image_size.into(), &self.device_memory_allocator, &mut self.command ); self.swapchain.scissors = vk::Rect2D { offset: vk::Offset2D { x: 0, y: 0 }, extent: vk::Extent2D { width: self.surface_size[0].get(), height: self.surface_size[1].get() } }; self.swapchain.viewport = vk::Viewport { x: 0.0, y: 0.0, width: self.surface_size[0].get() as f32, height: self.surface_size[1].get() as f32, min_depth: 0.0, max_depth: 1.0 }; self.swapchain.framebuffers = Self::create_framebuffers( self.swapchain.render_pass.unwrap(), self.swapchain.present_views.iter(), &self.depth_image_view ); self.swapchain.outdated = 0; self.swapchain.was_recreated = true; } } } } fn after_setup<T: ChildExampleState>(&mut self, child: &mut T) { self.swapchain.render_pass = Some(child.render_pass()); self.swapchain.framebuffers = Self::create_framebuffers( self.swapchain.render_pass.unwrap(), self.swapchain.present_views.iter(), &self.depth_image_view ); } pub fn new_input_thread<T: ChildExampleState>( window_size: [NonZeroU32; 2], setup_fn: impl FnOnce(&mut Self) -> T + Send + 'static, mut render_loop_fn: impl FnMut(&mut Self, &mut T) + Send + 'static, cleanup_fn: impl FnOnce(&mut Self, T) + Send + 'static ) { Self::new_input_thread_inner( window_size, move |window, input_receiver, oneoff_sender| { let before = Instant::now(); let mut me = Self::new(window, input_receiver, oneoff_sender); let mut t = setup_fn(&mut me); me.after_setup(&mut t); let after = Instant::now().duration_since(before); println!("SETUP: {}", after.as_nanos()); unsafe { dirty_mark::init(); } let before = Instant::now(); 'render: loop { // handle new events while let Ok(event) = me.input_receiver.try_recv() { log::trace!("Input event {:?}", event); match event { InputEvent::Exit => break 'render, InputEvent::WindowSize(size) => { me.surface_size = size; } } } // draw log::trace!("Draw frame before"); me.last_before = Some(dirty_mark::before()); render_loop_fn(&mut me, &mut t); if let Some(before_middle) = me.last_before_middle.take() { unsafe { dirty_mark::after(before_middle); } } log::trace!("Draw frame after\n"); } let after = Instant::now().duration_since(before); unsafe { dirty_mark::flush(); } println!("RENDER_LOOP: {}", after.as_nanos()); let before = Instant::now(); cleanup_fn(&mut me, t); let after = Instant::now().duration_since(before); println!("CLEANUP: {}", after.as_nanos()); } ) } fn new(window: Window, input_receiver: mpsc::Receiver<InputEvent>, oneoff_sender: mpsc::Sender<Window>) -> Self { let surface_size = [NonZeroU32::new(window.inner_size().width).unwrap(), NonZeroU32::new(window.inner_size().height).unwrap()]; let (base, surface) = Self::setup_base( IntoIterator::into_iter(vulkayes_window::winit::required_extensions(&window)), |instance| { let surface = vulkayes_window::winit::create_surface(instance, &window, Default::default()).expect("Could not create surface"); oneoff_sender.send(window).expect("could not send window"); surface } ); let device_memory_allocator = NaiveDeviceMemoryAllocator::new(base.device.clone()); let swapchain = Self::setup_swapchain( surface, &base.present_queue, surface_size ); let mut command = Self::setup_commands(&base.present_queue); let depth_image_view = Self::create_depth_image_view( &base.present_queue, swapchain.create_info.image_info.image_size.into(), &device_memory_allocator, &mut command ); ApplicationState { base, device_memory_allocator, swapchain, surface_size, depth_image_view, command, input_receiver, last_before: None, last_before_middle: None } } /// Returns true if the swapchain was recreated last frame. pub const fn swapchain_recreated(&self) -> bool { self.swapchain.was_recreated } }
use anyhow::Result; use reqwest::Error; use serde::{Deserialize, Serialize}; use std::time::{Duration, Instant}; #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct RootMatcha { pub price: String, pub guaranteed_price: String, pub to: String, pub data: String, pub value: String, pub gas: String, pub estimated_gas: String, pub gas_price: String, pub protocol_fee: String, pub minimum_protocol_fee: String, pub buy_token_address: String, pub sell_token_address: String, pub buy_amount: String, pub sell_amount: String, pub sources: Vec<Source>, pub orders: Vec<Order>, pub allowance_target: String, pub sell_token_to_eth_rate: String, pub buy_token_to_eth_rate: String, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Source { pub name: String, pub proportion: String, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Order { pub maker_token: String, pub taker_token: String, pub maker_amount: String, pub taker_amount: String, pub fill_data: FillData, pub source: String, pub source_path_id: String, #[serde(rename = "type")] pub type_field: i64, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct FillData { pub token_address_path: Option<Vec<String>>, pub router: Option<String>, pub pool_address: Option<String>, pub network_address: Option<String>, pub path: Option<Vec<String>>, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct RootInch { pub from_token: FromToken, pub to_token: ToToken, pub to_token_amount: String, pub from_token_amount: String, pub protocols: Vec<Vec<Vec<Protocol>>>, pub estimated_gas: i64, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct FromToken { pub symbol: String, pub name: String, pub address: String, pub decimals: i64, #[serde(rename = "logoURI")] pub logo_uri: String, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ToToken { pub symbol: String, pub name: String, pub address: String, pub decimals: i64, #[serde(rename = "logoURI")] pub logo_uri: String, } #[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Protocol { pub name: String, pub part: i64, pub from_token_address: String, pub to_token_address: String, } #[tokio::main] async fn main() -> Result<(), Error> { let mut price_change: u32 = 0; let mut previous_result_price = 0 as u128; let start = Instant::now(); let number_of_tests = 100u128; let mut sum_price_differences = 0_f64; for i in 0..number_of_tests { let new_matcha_price: u128 = get_matcha_price(i).await.unwrap(); let new_1inch_price: u128 = get_1inch_price(i).await.unwrap(); let new_price = u128::max(new_1inch_price, new_matcha_price); let price_diff = previous_result_price as f64 / new_price as f64; if i != 0 { if price_diff < 0.99999 as f64 || price_diff > 1.00001 as f64 { println!( "New price diff of {:?} with old price of {:?} and new price of {:?}", price_diff, previous_result_price, new_price ); price_change += 1; sum_price_differences = sum_price_differences + (1_f64 - price_diff).abs(); } } // if new_matcha_price > new_1inch_price { println!("Best price from matcha {:?}", new_matcha_price); // } else { println!("Best price from 1inch {:?}", new_1inch_price); // } previous_result_price = new_price.clone(); tokio::time::sleep(Duration::from_secs(2)).await; } let duration = start.elapsed(); println!( "On average the price changed by {:?} / {:?}", price_change, duration ); if price_change > 0 { println!( "Average price change is in {:?}", sum_price_differences as f64 / price_change as f64 ); } Ok(()) } async fn get_matcha_price(i: u128) -> Result<u128> { let request_url = format!( "https://api.0x.org/swap/v1/quote?buyToken=DAI&sellToken={token}&sellAmount={sellAmount}", token = "WETH", sellAmount = (100000000000000000000 + i) //<100 WETH> ); let response = reqwest::get(&request_url).await?; let result: RootMatcha = response.json().await?; let number = u128::from_str_radix(&result.buy_amount, 10)?; Ok(number) } async fn get_1inch_price(i: u128) -> Result<u128> { let request_url = format!( "https://api.1inch.exchange/v2.0/quote?fromTokenAddress={token}&toTokenAddress=0x6b175474e89094c44da98b954eedeac495271d0f&amount={sellAmount}", token = "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2", sellAmount = 100000000000000000000+i //<100 WETH> ); let response = reqwest::get(&request_url).await?; let result: RootInch = response.json().await?; let number = u128::from_str_radix(&result.to_token_amount, 10)?; Ok(number) }
/// CBOR len: either a fixed size or an indefinite length. #[derive(Debug, PartialEq, Eq, Copy, Clone)] pub enum Len { Indefinite, Len(u64), } impl Len { pub fn is_null(&self) -> bool { matches!(self, Self::Len(0)) } pub fn non_null(self) -> Option<Self> { if self.is_null() { None } else { Some(self) } } pub fn indefinite(&self) -> bool { self == &Len::Indefinite } } /// How many bytes are used in CBOR encoding for a major type/length #[derive(Debug, PartialEq, Eq, Copy, Clone)] pub enum Sz { /// Length/data is encoded inside of the type information Inline, /// Lnegth/data is in 1 byte following the type information One, /// Lnegth/data is in 2 bytes following the type information Two, /// Lnegth/data is in 4 bytes following the type information Four, /// Lnegth/data is in 8 bytes following the type information Eight, } impl Sz { pub fn canonical(len: u64) -> Self { if len <= super::MAX_INLINE_ENCODING { Sz::Inline } else if len < 0x1_00 { Sz::One } else if len < 0x1_00_00 { Sz::Two } else if len < 0x1_00_00_00_00 { Sz::Four } else { Sz::Eight } } pub fn bytes_following(&self) -> usize { match self { Self::Inline => 0, Self::One => 1, Self::Two => 2, Self::Four => 4, Self::Eight => 8, } } } /// CBOR length with encoding details /// /// Definite lengths can be encoded using a variable amount of bytes /// see `Sz` for more information #[derive(Debug, PartialEq, Eq, Copy, Clone)] pub enum LenSz { Indefinite, Len(u64, Sz), } impl LenSz { pub fn bytes_following(&self) -> usize { match self { Self::Indefinite => 0, Self::Len(_, sz) => sz.bytes_following(), } } } /// Encoding for the length of a string (text or bytes) /// /// Indefinite encoding strings contain the indefinite marker followed /// by a series of definite encoded strings and then a break /// /// Definite encoding strings can vary by how many bytes are used to encode /// the length e.g. 4 can be represented inline in the type, or in 1/2/4/8 /// additional bytes #[derive(Debug, PartialEq, Eq, Clone)] pub enum StringLenSz { Indefinite(Vec<(u64, Sz)>), Len(Sz), }
extern crate jlib; use jlib::api::account_tums::api::request; use jlib::api::account_tums::data::{RequestAccountTumsResponse, AccounTumSideKick}; use jlib::api::config::Config; static TEST_SERVER: &'static str = "ws://101.200.176.249:5040"; fn main() { let config = Config::new(TEST_SERVER, true); let account = "j9syYwWgtmjchcbqhVB18pmFqXUYahZvvg".to_string(); request(config, account, |x| match x { Ok(response) => { let res: RequestAccountTumsResponse = response; println!("account tums: \n{:?}", &res); }, Err(e) => { let err: AccounTumSideKick = e; println!("err: {:?}", err); } }); }
#[doc = "Reader of register DRIM"] pub type R = crate::R<u32, super::DRIM>; #[doc = "Writer for register DRIM"] pub type W = crate::W<u32, super::DRIM>; #[doc = "Register DRIM `reset()`'s with value 0"] impl crate::ResetValue for super::DRIM { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `RESUME`"] pub type RESUME_R = crate::R<bool, bool>; #[doc = "Write proxy for field `RESUME`"] pub struct RESUME_W<'a> { w: &'a mut W, } impl<'a> RESUME_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 } } impl R { #[doc = "Bit 0 - RESUME Interrupt Mask"] #[inline(always)] pub fn resume(&self) -> RESUME_R { RESUME_R::new((self.bits & 0x01) != 0) } } impl W { #[doc = "Bit 0 - RESUME Interrupt Mask"] #[inline(always)] pub fn resume(&mut self) -> RESUME_W { RESUME_W { w: self } } }
use crate::metrics::{self, SLASHER_DATABASE_SIZE, SLASHER_RUN_TIME}; use crate::Slasher; use directory::size_of_dir; use slog::{debug, error, info, trace}; use slot_clock::SlotClock; use std::sync::mpsc::{sync_channel, TrySendError}; use std::sync::Arc; use task_executor::TaskExecutor; use tokio::stream::StreamExt; use tokio::time::{interval_at, Duration, Instant}; use types::EthSpec; #[derive(Debug)] pub struct SlasherServer; impl SlasherServer { pub fn run<E: EthSpec, C: SlotClock + 'static>( slasher: Arc<Slasher<E>>, slot_clock: C, executor: &TaskExecutor, ) { info!(slasher.log, "Starting slasher to detect misbehaviour"); // Buffer just a single message in the channel. If the receiver is still processing, we // don't need to burden them with more work (we can wait). let (sender, receiver) = sync_channel(1); let log = slasher.log.clone(); let update_period = slasher.config().update_period; executor.spawn( async move { // NOTE: could align each run to some fixed point in each slot, see: // https://github.com/sigp/lighthouse/issues/1861 let slot_clock = Arc::new(slot_clock); let mut interval = interval_at(Instant::now(), Duration::from_secs(update_period)); while interval.next().await.is_some() { if let Some(current_slot) = slot_clock.clone().now() { let current_epoch = current_slot.epoch(E::slots_per_epoch()); if let Err(TrySendError::Disconnected(_)) = sender.try_send(current_epoch) { break; } } else { trace!(log, "Slasher has nothing to do: we are pre-genesis"); } } }, "slasher_server", ); executor.spawn_blocking( move || { while let Ok(current_epoch) = receiver.recv() { let t = Instant::now(); let num_attestations = slasher.attestation_queue.len(); let num_blocks = slasher.block_queue.len(); let batch_timer = metrics::start_timer(&SLASHER_RUN_TIME); if let Err(e) = slasher.process_queued(current_epoch) { error!( slasher.log, "Error during scheduled slasher processing"; "epoch" => current_epoch, "error" => format!("{:?}", e) ); } drop(batch_timer); // Prune the database, even in the case where batch processing failed. // If the LMDB database is full then pruning could help to free it up. if let Err(e) = slasher.prune_database(current_epoch) { error!( slasher.log, "Error during slasher database pruning"; "epoch" => current_epoch, "error" => format!("{:?}", e), ); continue; } debug!( slasher.log, "Completed slasher update"; "epoch" => current_epoch, "time_taken" => format!("{}ms", t.elapsed().as_millis()), "num_attestations" => num_attestations, "num_blocks" => num_blocks, ); let database_size = size_of_dir(&slasher.config().database_path); metrics::set_gauge(&SLASHER_DATABASE_SIZE, database_size as i64); } }, "slasher_server_process_queued", ); } }
pub mod binary_reader; pub mod binary_writer; pub mod huffman; pub mod compress; pub mod decompress; pub use compress::{compress_file, show_freq_and_dict}; pub use decompress::decompress_file; #[cfg(test)] mod tests { #[test] fn it_works() { assert_eq!(2 + 2, 4); } }
//! //! Utils Module //! pub mod payload; pub mod random_seed;
use rbatis::crud::CRUDTable; use rbatis_macro_driver::CRUDTable; use serde::Deserialize; use serde::Serialize; use strum_macros::EnumIter; use wallets_macro::{db_append_shared, DbBeforeSave, DbBeforeUpdate}; use crate::kits; use crate::ma::dao::{self, Shared}; use crate::ma::MTokenShared; #[derive(PartialEq, Clone, Debug, EnumIter)] pub enum BtcTokenType { Btc, } impl BtcTokenType { #[allow(dead_code)] fn from(token_type: &str) -> Result<Self, kits::Error> { match token_type { "Btc" => Ok(BtcTokenType::Btc), _ => { let err = format!("the str:{} can not be BtcTokenType", token_type); log::error!("{}", err); Err(kits::Error::from(err.as_str())) } } } } impl ToString for BtcTokenType { fn to_string(&self) -> String { match &self { BtcTokenType::Btc => "Btc".to_owned(), } } } //btc #[db_append_shared(CRUDTable)] #[derive(PartialEq, Serialize, Deserialize, Clone, Debug, Default, DbBeforeSave, DbBeforeUpdate)] pub struct MBtcChainTokenShared { #[serde(flatten)] pub token_shared: MTokenShared, #[serde(default)] pub token_type: String, #[serde(default)] pub fee_per_byte: i64, /// 精度 #[serde(default)] pub decimal: i32, } impl MBtcChainTokenShared { pub const fn create_table_script() -> &'static str { std::include_str!("../../../sql/m_btc_chain_token_shared.sql") } } #[db_append_shared] #[derive(PartialEq, Serialize, Deserialize, Clone, Debug, Default, CRUDTable, DbBeforeSave, DbBeforeUpdate)] pub struct MBtcChainTokenAuth { /// [BtcChainTokenShared] #[serde(default)] pub chain_token_shared_id: String, #[serde(default)] pub net_type: String, /// 显示位置,以此从小到大排列 #[serde(default)] pub position: i64, #[serde(default)] pub status:i64, } impl MBtcChainTokenAuth { pub const fn create_table_script() -> &'static str { std::include_str!("../../../sql/m_btc_chain_token_auth.sql") } } /// DefaultToken must be a [BtcChainTokenAuth] #[db_append_shared(CRUDTable)] #[derive(PartialEq, Serialize, Deserialize, Clone, Debug, Default, DbBeforeSave, DbBeforeUpdate)] pub struct MBtcChainTokenDefault { /// [BtcChainTokenShared] #[serde(default)] pub chain_token_shared_id: String, #[serde(default)] pub net_type: String, /// 显示位置,以此从小到大排列 #[serde(default)] pub position: i64, #[serde(default)] pub status:i64, #[serde(skip)] pub chain_token_shared: MBtcChainTokenShared, } impl MBtcChainTokenDefault { pub const fn create_table_script() -> &'static str { std::include_str!("../../../sql/m_btc_chain_token_default.sql") } } //murmel defined #[db_append_shared] #[derive(PartialEq, Serialize, Deserialize, Clone, Debug, Default, CRUDTable, DbBeforeSave, DbBeforeUpdate)] pub struct MProgress { #[serde(default)] pub header: String, #[serde(default)] pub timestamp: String, } impl MProgress { pub const fn create_table_script() -> &'static str { std::include_str!("../../../sql/m_progress.sql") } } #[db_append_shared] #[derive(PartialEq, Serialize, Deserialize, Clone, Debug, Default, CRUDTable, DbBeforeSave, DbBeforeUpdate)] pub struct MLocalTxLog { #[serde(default)] pub address_from: String, #[serde(default)] pub address_to: String, #[serde(default)] pub value: String, #[serde(default)] pub status: String, } impl MLocalTxLog { pub const fn create_table_script() -> &'static str { std::include_str!("../../../sql/m_local_tx_log.sql") } } //murmel end //btc end #[cfg(test)] mod tests { use futures::executor::block_on; use rbatis::crud::CRUDTable; use rbatis::rbatis::Rbatis; use strum::IntoEnumIterator; use crate::kits::test::make_memory_rbatis_test; use crate::ma::{BtcTokenType, Dao, Db, DbCreateType, MBtcChainTokenAuth, MBtcChainTokenDefault, MBtcChainTokenShared}; use crate::NetType; #[test] fn btc_token_type_test() { for it in BtcTokenType::iter() { assert_eq!(it, BtcTokenType::from(&it.to_string()).unwrap()); } } #[test] fn m_btc_chain_token_default_test() { let rb = block_on(init_memory()); let re = block_on(MBtcChainTokenDefault::list(&rb, "")); assert_eq!(false, re.is_err(), "{:?}", re); let mut token = MBtcChainTokenDefault::default(); token.chain_token_shared_id = "chain_token_shared_id".to_owned(); token.net_type = NetType::Main.to_string(); token.position = 1; let re = block_on(token.save(&rb, "")); assert_eq!(false, re.is_err(), "{:?}", re); let re = block_on(MBtcChainTokenDefault::list(&rb, "")); assert_eq!(false, re.is_err(), "{:?}", re); let tokens = re.unwrap(); assert_eq!(1, tokens.len(), "{:?}", tokens); let db_token = &tokens.as_slice()[0]; assert_eq!(&token, db_token); let re = block_on(MBtcChainTokenDefault::fetch_by_id(&rb, "", &token.id)); assert_eq!(false, re.is_err(), "{:?}", re); let db_token = re.unwrap().unwrap(); assert_eq!(token, db_token); } #[test] fn m_btc_chain_token_shared_test() { let rb = block_on(init_memory()); let re = block_on(MBtcChainTokenShared::list(&rb, "")); assert_eq!(false, re.is_err(), "{:?}", re); let mut token = MBtcChainTokenShared::default(); token.token_type = BtcTokenType::Btc.to_string(); token.decimal = 18; token.token_shared.project_name = "test".to_owned(); token.token_shared.project_home = "http://".to_owned(); token.token_shared.project_note = "test".to_owned(); token.token_shared.logo_bytes = "bytes".to_owned(); token.token_shared.logo_url = "http://".to_owned(); token.token_shared.symbol = "BTC".to_owned(); token.token_shared.name = "BTC".to_owned(); let re = block_on(token.save(&rb, "")); assert_eq!(false, re.is_err(), "{:?}", re); let re = block_on(MBtcChainTokenShared::list(&rb, "")); assert_eq!(false, re.is_err(), "{:?}", re); let tokens = re.unwrap(); assert_eq!(1, tokens.len(), "{:?}", tokens); let db_token = &tokens.as_slice()[0]; assert_eq!(&token, db_token); let re = block_on(MBtcChainTokenShared::fetch_by_id(&rb, "", &token.id)); assert_eq!(false, re.is_err(), "{:?}", re); let db_token = re.unwrap().unwrap(); assert_eq!(token, db_token); } #[test] fn m_btc_chain_token_auth_test() { let rb = block_on(init_memory()); let re = block_on(MBtcChainTokenAuth::list(&rb, "")); assert_eq!(false, re.is_err(), "{:?}", re); let mut token = MBtcChainTokenAuth::default(); token.chain_token_shared_id = "chain_token_shared_id".to_owned(); token.net_type = NetType::Main.to_string(); token.position = 1; let re = block_on(token.save(&rb, "")); assert_eq!(false, re.is_err(), "{:?}", re); let re = block_on(MBtcChainTokenAuth::list(&rb, "")); assert_eq!(false, re.is_err(), "{:?}", re); let tokens = re.unwrap(); assert_eq!(1, tokens.len(), "{:?}", tokens); let db_token = &tokens.as_slice()[0]; assert_eq!(&token, db_token); let re = block_on(MBtcChainTokenAuth::fetch_by_id(&rb, "", &token.id)); assert_eq!(false, re.is_err(), "{:?}", re); let db_token = re.unwrap().unwrap(); assert_eq!(token, db_token); } async fn init_memory() -> Rbatis { let rb = make_memory_rbatis_test().await; let r = Db::create_table(&rb, MBtcChainTokenDefault::create_table_script(), &MBtcChainTokenDefault::table_name(), &DbCreateType::Drop).await; assert_eq!(false, r.is_err(), "{:?}", r); let r = Db::create_table(&rb, MBtcChainTokenShared::create_table_script(), &MBtcChainTokenShared::table_name(), &DbCreateType::Drop).await; assert_eq!(false, r.is_err(), "{:?}", r); let r = Db::create_table(&rb, MBtcChainTokenAuth::create_table_script(), &MBtcChainTokenAuth::table_name(), &DbCreateType::Drop).await; assert_eq!(false, r.is_err(), "{:?}", r); rb } }
use std::{io, fmt::{self, Display, Formatter}, error::Error}; macro_rules! description { ($err : expr) => ( <String as AsRef<str>>::as_ref(&format!("{}", $err)) ); } #[derive(Debug)] /// The error type for operations of the `Decode` trait. pub enum DecodingError { /// A generic IO error. Io(io::Error), /// The decoder does not support a particular feature /// present in it's input. Unsupported(String) } impl Clone for DecodingError { fn clone(&self) -> Self { match self { Self::Io(err) => { Self::Io(io::Error::new(err.kind(), description!(err))) }, Self::Unsupported(msg) => Self::Unsupported(msg.clone()) } } } impl Display for DecodingError { fn fmt(&self, f: &mut Formatter) -> fmt::Result { match self { Self::Io(err) => err.fmt(f), Self::Unsupported(msg) => write!(f, "{}", msg) } } } impl Error for DecodingError { fn source(&self) -> Option<&(dyn Error + 'static)> { match self { Self::Io(err) => Some(err), _ => None } } } impl From<io::Error> for DecodingError { fn from(err: io::Error) -> Self { Self::Io(err) } } impl From<DecodingError> for io::Error { fn from(err: DecodingError) -> io::Error { match err { DecodingError::Io(err) => err, DecodingError::Unsupported(msg) => { io::Error::new(io::ErrorKind::InvalidInput, msg) } } } }
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)] #[link(name = "windows")] extern "system" { pub fn NdfCancelIncident(handle: *const ::core::ffi::c_void) -> ::windows_sys::core::HRESULT; pub fn NdfCloseIncident(handle: *mut ::core::ffi::c_void) -> ::windows_sys::core::HRESULT; pub fn NdfCreateConnectivityIncident(handle: *mut *mut ::core::ffi::c_void) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn NdfCreateDNSIncident(hostname: super::super::Foundation::PWSTR, querytype: u16, handle: *mut *mut ::core::ffi::c_void) -> ::windows_sys::core::HRESULT; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Networking_WinSock"))] pub fn NdfCreateGroupingIncident(cloudname: super::super::Foundation::PWSTR, groupname: super::super::Foundation::PWSTR, identity: super::super::Foundation::PWSTR, invitation: super::super::Foundation::PWSTR, addresses: *const super::super::Networking::WinSock::SOCKET_ADDRESS_LIST, appid: super::super::Foundation::PWSTR, handle: *mut *mut ::core::ffi::c_void) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn NdfCreateIncident(helperclassname: super::super::Foundation::PWSTR, celt: u32, attributes: *const HELPER_ATTRIBUTE, handle: *mut *mut ::core::ffi::c_void) -> ::windows_sys::core::HRESULT; pub fn NdfCreateNetConnectionIncident(handle: *mut *mut ::core::ffi::c_void, id: ::windows_sys::core::GUID) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn NdfCreatePnrpIncident(cloudname: super::super::Foundation::PWSTR, peername: super::super::Foundation::PWSTR, diagnosepublish: super::super::Foundation::BOOL, appid: super::super::Foundation::PWSTR, handle: *mut *mut ::core::ffi::c_void) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn NdfCreateSharingIncident(uncpath: super::super::Foundation::PWSTR, handle: *mut *mut ::core::ffi::c_void) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn NdfCreateWebIncident(url: super::super::Foundation::PWSTR, handle: *mut *mut ::core::ffi::c_void) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn NdfCreateWebIncidentEx(url: super::super::Foundation::PWSTR, usewinhttp: super::super::Foundation::BOOL, modulename: super::super::Foundation::PWSTR, handle: *mut *mut ::core::ffi::c_void) -> ::windows_sys::core::HRESULT; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Networking_WinSock", feature = "Win32_Security"))] pub fn NdfCreateWinSockIncident(sock: super::super::Networking::WinSock::SOCKET, host: super::super::Foundation::PWSTR, port: u16, appid: super::super::Foundation::PWSTR, userid: *const super::super::Security::SID, handle: *mut *mut ::core::ffi::c_void) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn NdfDiagnoseIncident(handle: *const ::core::ffi::c_void, rootcausecount: *mut u32, rootcauses: *mut *mut RootCauseInfo, dwwait: u32, dwflags: u32) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn NdfExecuteDiagnosis(handle: *const ::core::ffi::c_void, hwnd: super::super::Foundation::HWND) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn NdfGetTraceFile(handle: *const ::core::ffi::c_void, tracefilelocation: *mut super::super::Foundation::PWSTR) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn NdfRepairIncident(handle: *const ::core::ffi::c_void, repairex: *const RepairInfoEx, dwwait: u32) -> ::windows_sys::core::HRESULT; } pub type ATTRIBUTE_TYPE = i32; pub const AT_INVALID: ATTRIBUTE_TYPE = 0i32; pub const AT_BOOLEAN: ATTRIBUTE_TYPE = 1i32; pub const AT_INT8: ATTRIBUTE_TYPE = 2i32; pub const AT_UINT8: ATTRIBUTE_TYPE = 3i32; pub const AT_INT16: ATTRIBUTE_TYPE = 4i32; pub const AT_UINT16: ATTRIBUTE_TYPE = 5i32; pub const AT_INT32: ATTRIBUTE_TYPE = 6i32; pub const AT_UINT32: ATTRIBUTE_TYPE = 7i32; pub const AT_INT64: ATTRIBUTE_TYPE = 8i32; pub const AT_UINT64: ATTRIBUTE_TYPE = 9i32; pub const AT_STRING: ATTRIBUTE_TYPE = 10i32; pub const AT_GUID: ATTRIBUTE_TYPE = 11i32; pub const AT_LIFE_TIME: ATTRIBUTE_TYPE = 12i32; pub const AT_SOCKADDR: ATTRIBUTE_TYPE = 13i32; pub const AT_OCTET_STRING: ATTRIBUTE_TYPE = 14i32; pub const DF_IMPERSONATION: u32 = 2147483648u32; pub const DF_TRACELESS: u32 = 1073741824u32; pub type DIAGNOSIS_STATUS = i32; pub const DS_NOT_IMPLEMENTED: DIAGNOSIS_STATUS = 0i32; pub const DS_CONFIRMED: DIAGNOSIS_STATUS = 1i32; pub const DS_REJECTED: DIAGNOSIS_STATUS = 2i32; pub const DS_INDETERMINATE: DIAGNOSIS_STATUS = 3i32; pub const DS_DEFERRED: DIAGNOSIS_STATUS = 4i32; pub const DS_PASSTHROUGH: DIAGNOSIS_STATUS = 5i32; #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct DIAG_SOCKADDR { pub family: u16, pub data: [super::super::Foundation::CHAR; 126], } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for DIAG_SOCKADDR {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for DIAG_SOCKADDR { fn clone(&self) -> Self { *self } } #[repr(C)] pub struct DiagnosticsInfo { pub cost: i32, pub flags: u32, } impl ::core::marker::Copy for DiagnosticsInfo {} impl ::core::clone::Clone for DiagnosticsInfo { fn clone(&self) -> Self { *self } } #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct HELPER_ATTRIBUTE { pub pwszName: super::super::Foundation::PWSTR, pub r#type: ATTRIBUTE_TYPE, pub Anonymous: HELPER_ATTRIBUTE_0, } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for HELPER_ATTRIBUTE {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for HELPER_ATTRIBUTE { fn clone(&self) -> Self { *self } } #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub union HELPER_ATTRIBUTE_0 { pub Boolean: super::super::Foundation::BOOL, pub Char: u8, pub Byte: u8, pub Short: i16, pub Word: u16, pub Int: i32, pub DWord: u32, pub Int64: i64, pub UInt64: u64, pub PWStr: super::super::Foundation::PWSTR, pub Guid: ::windows_sys::core::GUID, pub LifeTime: LIFE_TIME, pub Address: DIAG_SOCKADDR, pub OctetString: OCTET_STRING, } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for HELPER_ATTRIBUTE_0 {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for HELPER_ATTRIBUTE_0 { fn clone(&self) -> Self { *self } } #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct HYPOTHESIS { pub pwszClassName: super::super::Foundation::PWSTR, pub pwszDescription: super::super::Foundation::PWSTR, pub celt: u32, pub rgAttributes: *mut HELPER_ATTRIBUTE, } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for HYPOTHESIS {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for HYPOTHESIS { fn clone(&self) -> Self { *self } } #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct HelperAttributeInfo { pub pwszName: super::super::Foundation::PWSTR, pub r#type: ATTRIBUTE_TYPE, } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for HelperAttributeInfo {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for HelperAttributeInfo { fn clone(&self) -> Self { *self } } #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct HypothesisResult { pub hypothesis: HYPOTHESIS, pub pathStatus: DIAGNOSIS_STATUS, } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for HypothesisResult {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for HypothesisResult { fn clone(&self) -> Self { *self } } pub type INetDiagExtensibleHelper = *mut ::core::ffi::c_void; pub type INetDiagHelper = *mut ::core::ffi::c_void; pub type INetDiagHelperEx = *mut ::core::ffi::c_void; pub type INetDiagHelperInfo = *mut ::core::ffi::c_void; pub type INetDiagHelperUtilFactory = *mut ::core::ffi::c_void; #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct LIFE_TIME { pub startTime: super::super::Foundation::FILETIME, pub endTime: super::super::Foundation::FILETIME, } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for LIFE_TIME {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for LIFE_TIME { fn clone(&self) -> Self { *self } } pub const NDF_ADD_CAPTURE_TRACE: u32 = 1u32; pub const NDF_APPLY_INCLUSION_LIST_FILTER: u32 = 2u32; pub const NDF_ERROR_START: u32 = 63744u32; pub const NDF_E_BAD_PARAM: ::windows_sys::core::HRESULT = -2146895611i32; pub const NDF_E_CANCELLED: ::windows_sys::core::HRESULT = -2146895614i32; pub const NDF_E_DISABLED: ::windows_sys::core::HRESULT = -2146895612i32; pub const NDF_E_LENGTH_EXCEEDED: ::windows_sys::core::HRESULT = -2146895616i32; pub const NDF_E_NOHELPERCLASS: ::windows_sys::core::HRESULT = -2146895615i32; pub const NDF_E_PROBLEM_PRESENT: ::windows_sys::core::HRESULT = -2146895608i32; pub const NDF_E_UNKNOWN: ::windows_sys::core::HRESULT = -2146895609i32; pub const NDF_E_VALIDATION: ::windows_sys::core::HRESULT = -2146895610i32; pub const NDF_INBOUND_FLAG_EDGETRAVERSAL: u32 = 1u32; pub const NDF_INBOUND_FLAG_HEALTHCHECK: u32 = 2u32; #[repr(C)] pub struct OCTET_STRING { pub dwLength: u32, pub lpValue: *mut u8, } impl ::core::marker::Copy for OCTET_STRING {} impl ::core::clone::Clone for OCTET_STRING { fn clone(&self) -> Self { *self } } pub type PROBLEM_TYPE = i32; pub const PT_INVALID: PROBLEM_TYPE = 0i32; pub const PT_LOW_HEALTH: PROBLEM_TYPE = 1i32; pub const PT_LOWER_HEALTH: PROBLEM_TYPE = 2i32; pub const PT_DOWN_STREAM_HEALTH: PROBLEM_TYPE = 4i32; pub const PT_HIGH_UTILIZATION: PROBLEM_TYPE = 8i32; pub const PT_HIGHER_UTILIZATION: PROBLEM_TYPE = 16i32; pub const PT_UP_STREAM_UTILIZATION: PROBLEM_TYPE = 32i32; pub const RCF_ISCONFIRMED: u32 = 2u32; pub const RCF_ISLEAF: u32 = 1u32; pub const RCF_ISTHIRDPARTY: u32 = 4u32; pub type REPAIR_RISK = i32; pub const RR_NOROLLBACK: REPAIR_RISK = 0i32; pub const RR_ROLLBACK: REPAIR_RISK = 1i32; pub const RR_NORISK: REPAIR_RISK = 2i32; pub type REPAIR_SCOPE = i32; pub const RS_SYSTEM: REPAIR_SCOPE = 0i32; pub const RS_USER: REPAIR_SCOPE = 1i32; pub const RS_APPLICATION: REPAIR_SCOPE = 2i32; pub const RS_PROCESS: REPAIR_SCOPE = 3i32; pub type REPAIR_STATUS = i32; pub const RS_NOT_IMPLEMENTED: REPAIR_STATUS = 0i32; pub const RS_REPAIRED: REPAIR_STATUS = 1i32; pub const RS_UNREPAIRED: REPAIR_STATUS = 2i32; pub const RS_DEFERRED: REPAIR_STATUS = 3i32; pub const RS_USER_ACTION: REPAIR_STATUS = 4i32; pub const RF_CONTACT_ADMIN: u32 = 131072u32; pub const RF_INFORMATION_ONLY: u32 = 33554432u32; pub const RF_REPRO: u32 = 2097152u32; pub const RF_RESERVED: u32 = 1073741824u32; pub const RF_RESERVED_CA: u32 = 2147483648u32; pub const RF_RESERVED_LNI: u32 = 65536u32; pub const RF_SHOW_EVENTS: u32 = 8388608u32; pub const RF_UI_ONLY: u32 = 16777216u32; pub const RF_USER_ACTION: u32 = 268435456u32; pub const RF_USER_CONFIRMATION: u32 = 134217728u32; pub const RF_VALIDATE_HELPTOPIC: u32 = 4194304u32; pub const RF_WORKAROUND: u32 = 536870912u32; #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct RepairInfo { pub guid: ::windows_sys::core::GUID, pub pwszClassName: super::super::Foundation::PWSTR, pub pwszDescription: super::super::Foundation::PWSTR, pub sidType: u32, pub cost: i32, pub flags: u32, pub scope: REPAIR_SCOPE, pub risk: REPAIR_RISK, pub UiInfo: UiInfo, pub rootCauseIndex: i32, } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for RepairInfo {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for RepairInfo { fn clone(&self) -> Self { *self } } #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct RepairInfoEx { pub repair: RepairInfo, pub repairRank: u16, } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for RepairInfoEx {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for RepairInfoEx { fn clone(&self) -> Self { *self } } #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct RootCauseInfo { pub pwszDescription: super::super::Foundation::PWSTR, pub rootCauseID: ::windows_sys::core::GUID, pub rootCauseFlags: u32, pub networkInterfaceID: ::windows_sys::core::GUID, pub pRepairs: *mut RepairInfoEx, pub repairCount: u16, } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for RootCauseInfo {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for RootCauseInfo { fn clone(&self) -> Self { *self } } #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct ShellCommandInfo { pub pwszOperation: super::super::Foundation::PWSTR, pub pwszFile: super::super::Foundation::PWSTR, pub pwszParameters: super::super::Foundation::PWSTR, pub pwszDirectory: super::super::Foundation::PWSTR, pub nShowCmd: u32, } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for ShellCommandInfo {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for ShellCommandInfo { fn clone(&self) -> Self { *self } } pub type UI_INFO_TYPE = i32; pub const UIT_INVALID: UI_INFO_TYPE = 0i32; pub const UIT_NONE: UI_INFO_TYPE = 1i32; pub const UIT_SHELL_COMMAND: UI_INFO_TYPE = 2i32; pub const UIT_HELP_PANE: UI_INFO_TYPE = 3i32; pub const UIT_DUI: UI_INFO_TYPE = 4i32; #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct UiInfo { pub r#type: UI_INFO_TYPE, pub Anonymous: UiInfo_0, } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for UiInfo {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for UiInfo { fn clone(&self) -> Self { *self } } #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub union UiInfo_0 { pub pwzNull: super::super::Foundation::PWSTR, pub ShellInfo: ShellCommandInfo, pub pwzHelpUrl: super::super::Foundation::PWSTR, pub pwzDui: super::super::Foundation::PWSTR, } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for UiInfo_0 {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for UiInfo_0 { fn clone(&self) -> Self { *self } }
use std::collections::HashMap; use std::env; use std::ffi::{CStr, CString}; use std::fs::*; use std::io::Write; use std::os::raw::{c_void, c_char}; use std::path::*; use std::io::Read; use build_util::*; use spirv_cross_sys; fn main() { let pkg_dir = env::var("CARGO_MANIFEST_DIR").unwrap(); let shader_dir = Path::new(&pkg_dir).join("..").join("..").join("..").join("engine").join("shaders"); let shader_dir_temp = Path::new(&pkg_dir).join("shaders_temp"); if !shader_dir_temp.exists() { std::fs::create_dir(&shader_dir_temp).expect("Failed to create shader temp directory."); } compile_shaders(&shader_dir, &shader_dir_temp, true, false, &HashMap::new(), |f| f.extension().and_then(|os_str| os_str.to_str()).unwrap_or("") == "glsl" && f.file_stem().and_then(|ext| ext.to_str()).map(|s| s.contains(".web.")).unwrap_or(false)); let compiled_file_folder = Path::new(&pkg_dir).join("..").join("www").join("dist").join("shaders"); if !compiled_file_folder.exists() { std::fs::create_dir_all(&compiled_file_folder).expect("Failed to create output shader directory"); } println!("cargo:rerun-if-changed={}", (&shader_dir_temp).to_str().unwrap()); let contents = read_dir(&shader_dir_temp).expect("Shader directory couldn't be opened."); contents .filter(|file_result| file_result.is_ok()) .map(|file_result| file_result.unwrap()) .filter(|f| f.path().extension().and_then(|os_str| os_str.to_str()).unwrap_or("") == "spv" && f.path().file_stem().and_then(|ext| ext.to_str()).map(|s| s.contains(".web.")).unwrap_or(false)) .for_each(|file| { println!("cargo:rerun-if-changed={}", (&file.path()).to_str().unwrap()); let is_ps = file.path().file_stem().and_then(|ext| ext.to_str()).map(|s| s.ends_with("frag")).unwrap_or(false); let mut buffer = Vec::<u8>::new(); let mut file_reader = File::open(file.path()).unwrap(); file_reader.read_to_end(&mut buffer).unwrap(); assert_eq!(buffer.len() % std::mem::size_of::<u32>(), 0); let words_len = buffer.len() / std::mem::size_of::<u32>(); let words = unsafe { std::slice::from_raw_parts(buffer.as_ptr() as *const u32, words_len) }; let mut context: spirv_cross_sys::spvc_context = std::ptr::null_mut(); let mut ir: spirv_cross_sys::spvc_parsed_ir = std::ptr::null_mut(); let mut compiler: spirv_cross_sys::spvc_compiler = std::ptr::null_mut(); let mut resources: spirv_cross_sys::spvc_resources = std::ptr::null_mut(); let mut options: spirv_cross_sys::spvc_compiler_options = std::ptr::null_mut(); unsafe { assert_eq!(spirv_cross_sys::spvc_context_create(&mut context), spirv_cross_sys::spvc_result_SPVC_SUCCESS); spirv_cross_sys::spvc_context_set_error_callback(context, Some(spvc_callback), std::ptr::null_mut()); assert_eq!(spirv_cross_sys::spvc_context_parse_spirv(context, words.as_ptr() as *const u32, words_len as u64, &mut ir), spirv_cross_sys::spvc_result_SPVC_SUCCESS); assert_eq!(spirv_cross_sys::spvc_context_create_compiler(context, spirv_cross_sys::spvc_backend_SPVC_BACKEND_GLSL, ir, spirv_cross_sys::spvc_capture_mode_SPVC_CAPTURE_MODE_COPY, &mut compiler), spirv_cross_sys::spvc_result_SPVC_SUCCESS); assert_eq!(spirv_cross_sys::spvc_compiler_create_shader_resources(compiler, &mut resources), spirv_cross_sys::spvc_result_SPVC_SUCCESS); assert_eq!(spirv_cross_sys::spvc_compiler_create_compiler_options(compiler, &mut options), spirv_cross_sys::spvc_result_SPVC_SUCCESS); assert_eq!(spirv_cross_sys::spvc_compiler_options_set_uint(options, spirv_cross_sys::spvc_compiler_option_SPVC_COMPILER_OPTION_GLSL_VERSION, 300), spirv_cross_sys::spvc_result_SPVC_SUCCESS); assert_eq!(spirv_cross_sys::spvc_compiler_options_set_bool(options, spirv_cross_sys::spvc_compiler_option_SPVC_COMPILER_OPTION_GLSL_ES, 1), spirv_cross_sys::spvc_result_SPVC_SUCCESS); assert_eq!(spirv_cross_sys::spvc_compiler_options_set_bool(options, spirv_cross_sys::spvc_compiler_option_SPVC_COMPILER_OPTION_GLSL_EMIT_PUSH_CONSTANT_AS_UNIFORM_BUFFER, 1), spirv_cross_sys::spvc_result_SPVC_SUCCESS); assert_eq!(spirv_cross_sys::spvc_compiler_options_set_bool(options, spirv_cross_sys::spvc_compiler_option_SPVC_COMPILER_OPTION_FIXUP_DEPTH_CONVENTION, 1), spirv_cross_sys::spvc_result_SPVC_SUCCESS); assert_eq!(spirv_cross_sys::spvc_compiler_install_compiler_options(compiler, options), spirv_cross_sys::spvc_result_SPVC_SUCCESS); } let input_prefix = if is_ps { "io" } else { "vs_input" }; let stage_inputs = unsafe { let mut resources_list: *const spirv_cross_sys::spvc_reflected_resource = std::ptr::null(); let mut resources_count: u64 = 0; assert_eq!(spirv_cross_sys::spvc_resources_get_resource_list_for_type(resources, spirv_cross_sys::spvc_resource_type_SPVC_RESOURCE_TYPE_STAGE_INPUT, &mut resources_list, &mut resources_count), spirv_cross_sys::spvc_result_SPVC_SUCCESS); std::slice::from_raw_parts(resources_list, resources_count as usize) }; for resource in stage_inputs { let location = unsafe { spirv_cross_sys::spvc_compiler_get_decoration(compiler, resource.id, spirv_cross_sys::SpvDecoration__SpvDecorationLocation) }; unsafe { let new_name = format!("{}_{}", input_prefix, location); let c_name = CString::new(new_name.as_str()).unwrap(); spirv_cross_sys::spvc_compiler_set_name(compiler, resource.id, c_name.as_ptr()); spirv_cross_sys::spvc_compiler_unset_decoration(compiler, resource.id, spirv_cross_sys::SpvDecoration__SpvDecorationLocation); } } let output_prefix = if is_ps { "ps_output" } else { "io" }; let stage_outputs = unsafe { let mut resources_list: *const spirv_cross_sys::spvc_reflected_resource = std::ptr::null(); let mut resources_count: u64 = 0; assert_eq!(spirv_cross_sys::spvc_resources_get_resource_list_for_type(resources, spirv_cross_sys::spvc_resource_type_SPVC_RESOURCE_TYPE_STAGE_OUTPUT, &mut resources_list, &mut resources_count), spirv_cross_sys::spvc_result_SPVC_SUCCESS); std::slice::from_raw_parts(resources_list, resources_count as usize) }; for resource in stage_outputs { let location = unsafe { spirv_cross_sys::spvc_compiler_get_decoration(compiler, resource.id, spirv_cross_sys::SpvDecoration__SpvDecorationLocation) }; unsafe { let new_name = format!("{}_{}", output_prefix, location); let c_name = CString::new(new_name.as_str()).unwrap(); spirv_cross_sys::spvc_compiler_set_name(compiler, resource.id, c_name.as_ptr()); spirv_cross_sys::spvc_compiler_unset_decoration(compiler, resource.id, spirv_cross_sys::SpvDecoration__SpvDecorationLocation); } } let uniform_buffers = unsafe { let mut resources_list: *const spirv_cross_sys::spvc_reflected_resource = std::ptr::null(); let mut resources_count: u64 = 0; assert_eq!(spirv_cross_sys::spvc_resources_get_resource_list_for_type(resources, spirv_cross_sys::spvc_resource_type_SPVC_RESOURCE_TYPE_UNIFORM_BUFFER, &mut resources_list, &mut resources_count), spirv_cross_sys::spvc_result_SPVC_SUCCESS); std::slice::from_raw_parts(resources_list, resources_count as usize) }; for resource in uniform_buffers { let set = unsafe { spirv_cross_sys::spvc_compiler_get_decoration(compiler, resource.id, spirv_cross_sys::SpvDecoration__SpvDecorationDescriptorSet) }; let binding = unsafe { spirv_cross_sys::spvc_compiler_get_decoration(compiler, resource.id, spirv_cross_sys::SpvDecoration__SpvDecorationBinding) }; let new_name = format!("res_{}_{}", set, binding); let c_name = CString::new(new_name.as_str()).unwrap(); let new_type_name = format!("res_{}_{}_t", set, binding); let c_type_name = CString::new(new_type_name.as_str()).unwrap(); unsafe { spirv_cross_sys::spvc_compiler_set_name(compiler, resource.id, c_name.as_ptr()); spirv_cross_sys::spvc_compiler_set_name(compiler, resource.base_type_id, c_type_name.as_ptr()); spirv_cross_sys::spvc_compiler_unset_decoration(compiler, resource.id, spirv_cross_sys::SpvDecoration__SpvDecorationDescriptorSet); spirv_cross_sys::spvc_compiler_unset_decoration(compiler, resource.id, spirv_cross_sys::SpvDecoration__SpvDecorationBinding); } } let sampled_images = unsafe { let mut resources_list: *const spirv_cross_sys::spvc_reflected_resource = std::ptr::null(); let mut resources_count: u64 = 0; assert_eq!(spirv_cross_sys::spvc_resources_get_resource_list_for_type(resources, spirv_cross_sys::spvc_resource_type_SPVC_RESOURCE_TYPE_SAMPLED_IMAGE, &mut resources_list, &mut resources_count), spirv_cross_sys::spvc_result_SPVC_SUCCESS); std::slice::from_raw_parts(resources_list, resources_count as usize) }; for resource in sampled_images { let set = unsafe { spirv_cross_sys::spvc_compiler_get_decoration(compiler, resource.id, spirv_cross_sys::SpvDecoration__SpvDecorationDescriptorSet) }; let binding = unsafe { spirv_cross_sys::spvc_compiler_get_decoration(compiler, resource.id, spirv_cross_sys::SpvDecoration__SpvDecorationBinding) }; let new_name = format!("res_{}_{}", set, binding); let c_name = CString::new(new_name.as_str()).unwrap(); unsafe { spirv_cross_sys::spvc_compiler_set_name(compiler, resource.id, c_name.as_ptr()); spirv_cross_sys::spvc_compiler_unset_decoration(compiler, resource.id, spirv_cross_sys::SpvDecoration__SpvDecorationDescriptorSet); spirv_cross_sys::spvc_compiler_unset_decoration(compiler, resource.id, spirv_cross_sys::SpvDecoration__SpvDecorationBinding); } } let push_constants = unsafe { let mut resources_list: *const spirv_cross_sys::spvc_reflected_resource = std::ptr::null(); let mut resources_count: u64 = 0; assert_eq!(spirv_cross_sys::spvc_resources_get_resource_list_for_type(resources, spirv_cross_sys::spvc_resource_type_SPVC_RESOURCE_TYPE_PUSH_CONSTANT, &mut resources_list, &mut resources_count), spirv_cross_sys::spvc_result_SPVC_SUCCESS); std::slice::from_raw_parts(resources_list, resources_count as usize) }; if let Some(push_constants) = push_constants.first() { unsafe { let push_constants_name = CString::new("push_constants").unwrap(); let push_constants_type_name = CString::new("push_constants_t").unwrap(); spirv_cross_sys::spvc_compiler_set_name(compiler, push_constants.id, push_constants_name.as_ptr()); spirv_cross_sys::spvc_compiler_set_name(compiler, push_constants.base_type_id, push_constants_type_name.as_ptr()); } } let mut code: *const std::os::raw::c_char = std::ptr::null(); unsafe { let result = spirv_cross_sys::spvc_compiler_compile(compiler, &mut code); if result != spirv_cross_sys::spvc_result_SPVC_SUCCESS { spirv_cross_sys::spvc_context_destroy(context); return; } } let compiled_file_path = compiled_file_folder.join([file.path().file_stem().unwrap().to_str().unwrap(), ".glsl"].concat()); let mut out_file = File::create(compiled_file_path).unwrap(); unsafe { write!(out_file, "{}", CStr::from_ptr(code).to_str().unwrap()).unwrap(); } unsafe { spirv_cross_sys::spvc_context_destroy(context); } } ); } unsafe extern "C" fn spvc_callback(user_data: *mut c_void, error: *const c_char) { panic!("SPIR-V-Cross Error: {}", CStr::from_ptr(error).to_str().unwrap()); }
#![deny(clippy::use_self)] use macros::serialize; #[derive(serialize)] pub enum Direction { East, }
/*! Validates strings and computes check digits using the Luhn algorithm. It's not a great checksum, but it's used in a bunch of places (credit card numbers, ISIN codes, etc.). More information is available on [wikipedia](https://en.wikipedia.org/wiki/Luhn_algorithm). */ use digits_iterator::DigitsExtension; /// Validates the given string using the Luhn algorithm. /// /// Typically such strings end in a check digit which is chosen in order /// to make the whole string validate. pub fn valid(pan: &str) -> bool { let mut numbers = string_to_ints(pan); numbers.reverse(); let mut is_odd: bool = true; let mut odd_sum: u32 = 0; let mut even_sum: u32 = 0; for digit in numbers { if is_odd { odd_sum += digit; } else { even_sum += digit / 5 + (2 * digit) % 10; } is_odd = !is_odd } (odd_sum + even_sum) % 10 == 0 } fn string_to_ints(string: &str) -> Vec<u32> { let mut numbers = vec![]; for c in string.chars() { let value = c.to_string().parse::<u32>(); match value { Ok(v) => numbers.push(v), Err(e) => println!("error parsing number: {:?}", e), } } numbers } /// Computes the Luhn check digit for the given string. /// /// The string formed by appending the check digit to the original string /// is guaranteed to be valid. Input must be uppercase alphanumeric /// ASCII; panics otherwise. pub fn checksum(input: &[u8]) -> u8 { // This implementation is based on the description found // [here](https://en.wikipedia.org/wiki/International_Securities_Identification_Number). // Convert a char into an index into the alphabet [0-9,A-Z]. fn encode_char(c: u8) -> u8 { match c { b'0'..=b'9' => c - b'0', b'A'..=b'Z' => c - b'A' + 10, _ => panic!("Not alphanumeric: {}", c), } } // Encode the chars in the input and concatenate them digit-wise. // Eg. "3C" => [3, 1, 2] // FIXME: This allocates. Is it necessary? // One char may become two digits => max length is input.len() * 2. let mut ds = Vec::<u8>::with_capacity(input.len() * 2); ds.extend( input .iter() .copied() .map(encode_char) .flat_map(DigitsExtension::digits), ); // The even-indexed digits, as numbered from the back, are added digit-wise. let checksum_even = ds .iter() .rev() .skip(1) .step_by(2) .copied() .flat_map(DigitsExtension::digits) .sum::<u8>(); // The odd-indexed digits, as numbered from the back, are doubled first. let checksum_odd = ds .iter() .rev() .step_by(2) .map(|&x| x * 2) .flat_map(DigitsExtension::digits) .sum::<u8>(); let checksum = checksum_even + checksum_odd; // (checksum + luhn digit) % 10 must be zero. Working backwards: let digit = (10 - (checksum % 10)) % 10; // convert to ASCII digit + 48 } #[cfg(test)] mod tests { use super::*; #[test] fn accepts_4111111111111111() { assert!(valid("4111111111111111")); } #[test] fn accepts_49927398716() { assert!(valid("49927398716")); } #[test] fn rejects_4111111111111112() { assert!(!valid("4111111111111112")); } #[test] fn rejects_234() { assert!(!valid("234")); } fn validate_isin(xs: [u8; 12]) -> bool { let digit = checksum(&xs[0..11]); digit == xs[11] } #[test] fn validate_some_good_isins() { // I got these from <http://www.isin.org>. assert!(validate_isin(*b"US5949181045")); // Microsoft assert!(validate_isin(*b"US38259P5089")); // Google assert!(validate_isin(*b"US0378331005")); // Apple assert!(validate_isin(*b"BMG491BT1088")); // Invesco assert!(validate_isin(*b"IE00B4BNMY34")); // Accenture assert!(validate_isin(*b"US0231351067")); // Amazon assert!(validate_isin(*b"US64110L1061")); // Netflix assert!(validate_isin(*b"US30303M1027")); // Facebook assert!(validate_isin(*b"CH0031240127")); // BMW Australia assert!(validate_isin(*b"CA9861913023")); // Yorbeau Res } #[test] fn fail_some_bad_isins() { assert!(!validate_isin(*b"US5949181040")); // Microsoft (checksum zeroed) assert!(!validate_isin(*b"US38259P5080")); // Google (checksum zeroed) assert!(!validate_isin(*b"US0378331000")); // Apple (checksum zeroed) assert!(!validate_isin(*b"BMG491BT1080")); // Invesco (checksum zeroed) assert!(!validate_isin(*b"IE00B4BNMY30")); // Accenture (checksum zeroed) assert!(!validate_isin(*b"US0231351060")); // Amazon (checksum zeroed) assert!(!validate_isin(*b"US64110L1060")); // Netflix (checksum zeroed) assert!(!validate_isin(*b"US30303M1020")); // Facebook (checksum zeroed) assert!(!validate_isin(*b"CH0031240120")); // BMW Australia (checksum zeroed) assert!(!validate_isin(*b"CA9861913020")); // Yorbeau Res (checksum zeroed) assert!(!validate_isin(*b"SU5941981045")); // Microsoft (two chars transposed) assert!(!validate_isin(*b"US3825P95089")); // Google (two chars transposed) assert!(!validate_isin(*b"US0378313005")); // Apple (two chars transposed) assert!(!validate_isin(*b"BMG491BT0188")); // Invesco (two chars transposed) assert!(!validate_isin(*b"IE00B4BNM3Y4")); // Accenture (two chars transposed) assert!(!validate_isin(*b"US2031351067")); // Amazon (two chars transposed) assert!(!validate_isin(*b"US61410L1061")); // Netflix (two chars transposed) assert!(!validate_isin(*b"US30033M1027")); // Facebook (two chars transposed) assert!(!validate_isin(*b"CH0032140127")); // BMW Australia (two chars transposed) assert!(!validate_isin(*b"CA9861193023")); // Yorbeau Res (two chars transposed) } #[test] fn readme() { // A string which doesn't validate let mut s = "11111111".to_string(); assert!(!valid(&s)); // Let's fix that s.push(checksum(s.as_bytes()) as char); assert_eq!(s, "111111118"); assert!(valid(&s)); } }
use std::error::Error; use std::fmt; #[derive(Debug)] pub enum GameError { IoError(Box<dyn Error>), InitError(Box<dyn Error>), StateError(Box<dyn Error>), RuntimeError(Box<dyn Error>), NotSupportedError(Box<dyn Error>), } impl Error for GameError { fn source(&self) -> Option<&(dyn Error + 'static)> { let source = match self { GameError::IoError(source) => source, GameError::InitError(source) => source, GameError::StateError(source) => source, GameError::RuntimeError(source) => source, GameError::NotSupportedError(source) => source, }; Some(source.as_ref()) } } impl fmt::Display for GameError { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { match self { GameError::IoError(source) => write!(fmt, "GameError::IoError: {}", source), GameError::InitError(source) => write!(fmt, "GameError::InitError: {}", source), GameError::StateError(source) => write!(fmt, "GameError::StateError: {}", source), GameError::RuntimeError(source) => write!(fmt, "GameError::RuntimeError: {}", source), GameError::NotSupportedError(source) => write!(fmt, "GameError::NotSupportedError: {}", source), } } } pub type GameResult<T = ()> = Result<T, GameError>;
use std::{fmt, io}; use crate::{tag::Tag, Identifier}; pub type Result<T, E = Error> = ::std::result::Result<T, E>; /// Points to a record data. #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub enum Pointer { /// Points to a record leader. Leader, /// Points to a filed. Field(Tag), /// Points to a subfield. Subfield(Tag, Identifier), } /// Errors of this crate. #[derive(Debug)] pub enum Error { UnexpectedByteInDecNum(u8), FieldTooLarge(Tag), RecordTooLarge(usize), RecordTooShort(usize), UnexpectedEofInDecNum, UnexpectedEof, UnexpectedEofInDirectory, NoRecordTerminator, UnexpectedSubfieldEnd, NonUnicodeSequence(Pointer), UnknownCharacterCodingScheme(u8), Utf8Error(std::str::Utf8Error), #[cfg(feature = "xml")] XmlError(xml::writer::Error), Io(io::ErrorKind), } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Error::UnexpectedByteInDecNum(byte) => { write!(f, "Unexpected byte in decimal string: {}", byte) } Error::FieldTooLarge(tag) => { write!(f, "Field byte length is greater than 9998 (tag={})", tag) } Error::RecordTooLarge(size) => { write!(f, "Record byte length {} is greater than 99999 limit", size) } Error::RecordTooShort(len) => { write!(f, "Record length {} specified in leader is too small", len) } Error::UnexpectedEofInDecNum => { write!(f, "Unexpected EOF while reading decimal number") } Error::UnexpectedEof => write!(f, "Unexpected EOF"), Error::UnexpectedEofInDirectory => write!(f, "Unexpected EOF while reading directory"), Error::NoRecordTerminator => write!(f, "No record terminator"), Error::UnexpectedSubfieldEnd => write!(f, "Unexpected end of a subfield"), Error::UnknownCharacterCodingScheme(val) => { write!(f, "Unknown character coding scheme 0x{val:02x}") } Error::NonUnicodeSequence(ptr) => match ptr { Pointer::Leader => write!(f, "Non unicode sequence in the record leater"), Pointer::Field(tag) => write!(f, "Non unicode sequence in field {}", tag), Pointer::Subfield(tag, id) => { write!(f, "Non unicode sequence in subfield {}${}", tag, id) } }, Error::Io(err) => write!(f, "IO error: {:?}", err), Error::Utf8Error(err) => write!(f, "UTF8 error: {}", err), #[cfg(feature = "xml")] Error::XmlError(err) => write!(f, "XML error: {}", err), } } } impl ::std::error::Error for Error { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match self { Error::UnexpectedByteInDecNum(_) | Error::FieldTooLarge(_) | Error::RecordTooLarge(_) | Error::RecordTooShort(_) | Error::UnexpectedEofInDecNum | Error::UnexpectedEof | Error::UnexpectedEofInDirectory | Error::NoRecordTerminator | Error::UnexpectedSubfieldEnd | Error::NonUnicodeSequence(_) | Error::UnknownCharacterCodingScheme(_) | Error::Io(_) => None, Error::Utf8Error(ref e) => Some(e as &_), #[cfg(feature = "xml")] Error::XmlError(ref e) => Some(e as &_), } } } impl From<io::Error> for Error { fn from(err: io::Error) -> Error { Error::Io(err.kind()) } } impl From<std::str::Utf8Error> for Error { fn from(err: std::str::Utf8Error) -> Error { Error::Utf8Error(err) } }
use std::str::FromStr; use oasis_core_runtime::{ common::{quantity::Quantity, versioned::Versioned}, consensus::{ roothash::{Message, StakingMessage}, staking, }, }; use crate::{ context::{BatchContext, Context}, modules::consensus::Module as Consensus, testing::{keys, mock}, types::{ message::MessageEventHookInvocation, token::{BaseUnits, Denomination}, }, }; use super::API as _; #[test] fn test_api_transfer_invalid_denomination() { let mut mock = mock::Mock::default(); let mut ctx = mock.create_ctx(); ctx.with_tx(0, mock::transaction(), |mut tx_ctx, _call| { let hook_name = "test_event_handler"; let amount = BaseUnits::new(1_000, Denomination::NATIVE); assert!(Consensus::transfer( &mut tx_ctx, keys::alice::address(), &amount, MessageEventHookInvocation::new(hook_name.to_string(), 0), ) .is_err()); }); } #[test] fn test_api_transfer() { let mut mock = mock::Mock::default(); let mut ctx = mock.create_ctx(); ctx.with_tx(0, mock::transaction(), |mut tx_ctx, _call| { let hook_name = "test_event_handler"; let amount = BaseUnits::new(1_000, Denomination::from_str("TEST").unwrap()); Consensus::transfer( &mut tx_ctx, keys::alice::address(), &amount, MessageEventHookInvocation::new(hook_name.to_string(), 0), ) .expect("transfer should succeed"); let (_, msgs) = tx_ctx.commit(); assert_eq!(1, msgs.len(), "one message should be emitted"); let (msg, hook) = msgs.first().unwrap(); assert_eq!( &Message::Staking(Versioned::new( 0, StakingMessage::Transfer(staking::Transfer { to: keys::alice::address().into(), amount: amount.amount().into(), }) )), msg, "emitted message should match" ); assert_eq!( hook_name.to_string(), hook.hook_name, "emitted hook should match" ) }); } #[test] fn test_api_withdraw() { let mut mock = mock::Mock::default(); let mut ctx = mock.create_ctx(); ctx.with_tx(0, mock::transaction(), |mut tx_ctx, _call| { let hook_name = "test_event_handler"; let amount = BaseUnits::new(1_000, Denomination::from_str("TEST").unwrap()); Consensus::withdraw( &mut tx_ctx, keys::alice::address(), &amount, MessageEventHookInvocation::new(hook_name.to_string(), 0), ) .expect("withdraw should succeed"); let (_, msgs) = tx_ctx.commit(); assert_eq!(1, msgs.len(), "one message should be emitted"); let (msg, hook) = msgs.first().unwrap(); assert_eq!( &Message::Staking(Versioned::new( 0, StakingMessage::Withdraw(staking::Withdraw { from: keys::alice::address().into(), amount: amount.amount().into(), }) )), msg, "emitted message should match" ); assert_eq!( hook_name.to_string(), hook.hook_name, "emitted hook should match" ) }); } #[test] fn test_api_escrow() { let mut mock = mock::Mock::default(); let mut ctx = mock.create_ctx(); ctx.with_tx(0, mock::transaction(), |mut tx_ctx, _call| { let hook_name = "test_event_handler"; let amount = BaseUnits::new(1_000, Denomination::from_str("TEST").unwrap()); Consensus::escrow( &mut tx_ctx, keys::alice::address(), &amount, MessageEventHookInvocation::new(hook_name.to_string(), 0), ) .expect("escrow should succeed"); let (_, msgs) = tx_ctx.commit(); assert_eq!(1, msgs.len(), "one message should be emitted"); let (msg, hook) = msgs.first().unwrap(); assert_eq!( &Message::Staking(Versioned::new( 0, StakingMessage::AddEscrow(staking::Escrow { account: keys::alice::address().into(), amount: amount.amount().into(), }) )), msg, "emitted message should match" ); assert_eq!( hook_name.to_string(), hook.hook_name, "emitted hook should match" ) }); } #[test] fn test_api_reclaim_escrow() { let mut mock = mock::Mock::default(); let mut ctx = mock.create_ctx(); ctx.with_tx(0, mock::transaction(), |mut tx_ctx, _call| { let hook_name = "test_event_handler"; let amount = BaseUnits::new(1_000, Denomination::from_str("TEST").unwrap()); // TODO: shares. Consensus::reclaim_escrow( &mut tx_ctx, keys::alice::address(), &amount, MessageEventHookInvocation::new(hook_name.to_string(), 0), ) .expect("reclaim escrow should succeed"); let (_, msgs) = tx_ctx.commit(); assert_eq!(1, msgs.len(), "one message should be emitted"); let (msg, hook) = msgs.first().unwrap(); assert_eq!( &Message::Staking(Versioned::new( 0, StakingMessage::ReclaimEscrow(staking::ReclaimEscrow { account: keys::alice::address().into(), shares: amount.amount().into(), }) )), msg, "emitted message should match" ); assert_eq!( hook_name.to_string(), hook.hook_name, "emitted hook should match" ) }); } #[test] fn test_api_account() { let mut mock = mock::Mock::default(); let ctx = mock.create_ctx(); // TODO: prepare mock consensus state. let acc = Consensus::account(&ctx, keys::alice::address()).expect("query should succeed"); assert_eq!( Quantity::from(0u128), acc.general.balance, "consensus balance should be zero" ) }
mod solver; mod brute_force; use prob1::solver::Solver; use prob1::brute_force::BruteForceSolver; pub fn demo(upper_limit: u32) { println!("Brute Force answer: {}", BruteForceSolver::new(upper_limit).solve()); }
use std::env; use std::path::PathBuf; use clap::{App, AppSettings, Arg, ArgGroup, ArgMatches, SubCommand}; use crate::templates; const NAME: &str = "cargo-eval"; #[inline(always)] const fn name() -> &'static str { NAME } #[inline(always)] fn subcommand_name() -> &'static str { &name()[6..] } pub fn data_dir() -> Option<PathBuf> { Some(dirs::data_local_dir()?.join(name())) } pub fn cache_dir() -> Option<PathBuf> { Some(dirs::cache_dir()?.join(name())) } fn app() -> App<'static, 'static> { let mut app = SubCommand::with_name(subcommand_name()) .version(env!("CARGO_PKG_VERSION")) .about("Compiles and runs “Cargoified Rust scripts”.") .usage("cargo eval [FLAGS OPTIONS] [--] <script> <args>...") /* Major script modes. */ .arg(Arg::with_name("script") .help("Script file (with or without extension) to execute.") .index(1) .required_unless("clear_cache") ) .arg(Arg::with_name("args") .help("Additional arguments passed to the script.") .index(2) .multiple(true) ) .arg(Arg::with_name("expr") .help("Execute <script> as a literal expression and display the result.") .long("expr") .short("e") .requires("script") ) .arg(Arg::with_name("loop") .help("Execute <script> as a literal closure once for each line from stdin.") .long("loop") .short("l") .requires("script") ) .group(ArgGroup::with_name("expr_or_loop") .args(&["expr", "loop"]) ) /* Options that impact the script being executed. */ .arg(Arg::with_name("count") .help("Invoke the loop closure with two arguments: line, and line number.") .long("count") .requires("loop") ) .arg(Arg::with_name("debug") .help("Build a debug executable, not an optimised one.") .long("debug") .requires("script") ) .arg(Arg::with_name("dep") .help("Add an additional Cargo dependency. Each SPEC can be either just the package name (which will assume the latest version) or a full `name=version` spec.") .long("dep") .short("d") .takes_value(true) .multiple(true) .number_of_values(1) .requires("script") ) .arg(Arg::with_name("features") .help("Cargo features to pass when building and running.") .long("features") .takes_value(true) ) .arg(Arg::with_name("unstable_features") .help("Add a #![feature] declaration to the crate.") .long("unstable-feature") .short("u") .takes_value(true) .multiple(true) .requires("expr_or_loop") ) /* Options that change how cargo eval itself behaves, and don't alter what the script will do. */ .arg(Arg::with_name("build_only") .help("Build the script, but don't run it.") .long("build-only") .requires("script") .conflicts_with_all(&["args"]) ) .arg(Arg::with_name("clear_cache") .help("Clears out the script cache.") .long("clear-cache") ) .arg(Arg::with_name("force") .help("Force the script to be rebuilt.") .long("force") .requires("script") ) .arg(Arg::with_name("gen_pkg_only") .help("Generate the Cargo package, but don't compile or run it.") .long("gen-pkg-only") .requires("script") .conflicts_with_all(&["args", "build_only", "debug", "force", "test", "bench"]) ) .arg(Arg::with_name("pkg_path") .help("Specify where to place the generated Cargo package.") .long("pkg-path") .takes_value(true) .requires("script") .conflicts_with_all(&["clear_cache", "force"]) ) .arg(Arg::with_name("use_bincache") .help("Override whether or not the shared binary cache will be used for compilation.") .long("use-shared-binary-cache") .takes_value(true) .possible_values(&["no", "yes"]) ) .arg(Arg::with_name("test") .help("Compile and run tests.") .long("test") .conflicts_with_all(&["bench", "debug", "args", "force"]) ) .arg(Arg::with_name("bench") .help("Compile and run benchmarks. Requires a nightly toolchain.") .long("bench") .conflicts_with_all(&["test", "debug", "args", "force"]) ) .arg(Arg::with_name("template") .help("Specify a template to use for expression scripts.") .long("template") .short("t") .takes_value(true) .requires("expr") ); #[cfg(windows)] { app = app.subcommand(crate::file_assoc::Args::subcommand()) } app = app.subcommand(templates::Args::subcommand()); app } pub fn get_matches() -> ArgMatches<'static> { let mut args = env::args().collect::<Vec<_>>(); let subcommand = app(); // Insert subcommand argument if called directly. if args.get(1).map(|s| *s == subcommand_name()) != Some(true) { args.insert(1, subcommand_name().into()); } // We have to wrap our command for the output to look right. App::new("cargo") .bin_name("cargo") .setting(AppSettings::SubcommandRequiredElseHelp) .subcommand(subcommand) .get_matches_from(args) .subcommand_matches(subcommand_name()) .unwrap() .clone() }
use std::fs; fn main() { let filename = "inputs/q13_input.txt"; let contents = fs::read_to_string(filename) .expect("Could not read the file") .lines() .take(2) .map(String::from) .collect::<Vec<String>>(); let earliest_depart = &contents[0].parse::<f32>().unwrap(); let busses = &contents[1] .split(',') .map(|x| { if x == "x" { -1.0 } else { x.parse::<f32>().unwrap() } }) .filter(|&x| x > 0.0) .collect::<Vec<f32>>(); let departures: Vec<(usize, f32, f32)> = busses .iter() .map(|&x| (x, (earliest_depart / x).ceil() * x - earliest_depart)) .enumerate() .map(|(i, (bus_id, value))| (i, bus_id, value)) .collect::<Vec<(usize, f32, f32)>>(); let mut min_wait = departures[0].2; let mut bus_id = departures[0].1; for (_, bus, value) in departures { if value < min_wait { min_wait = value; bus_id = bus; } } println!("{:?}", (bus_id * min_wait) as i32); }
use crate::backend::c; /// `sysinfo` #[cfg(linux_kernel)] pub type Sysinfo = c::sysinfo; #[cfg(not(target_os = "wasi"))] pub(crate) type RawUname = c::utsname;
use async_graphql::http::MultipartOptions; use poem::{ async_trait, error::BadRequest, http::{header, Method}, FromRequest, Request, RequestBody, Result, }; use tokio_util::compat::TokioAsyncReadCompatExt; /// An extractor for GraphQL request. /// /// You can just use the extractor as in the example below, but I would /// recommend using the [`GraphQL`](crate::GraphQL) endpoint because it is /// easier to integrate. /// /// # Example /// /// ``` /// use async_graphql::{EmptyMutation, EmptySubscription, Object, Schema}; /// use async_graphql_poem::GraphQLRequest; /// use poem::{ /// handler, /// middleware::AddData, /// post, /// web::{Data, Json}, /// EndpointExt, Route, /// }; /// /// struct Query; /// /// #[Object] /// impl Query { /// async fn value(&self) -> i32 { /// 100 /// } /// } /// /// type MySchema = Schema<Query, EmptyMutation, EmptySubscription>; /// /// #[handler] /// async fn index(req: GraphQLRequest, schema: Data<&MySchema>) -> Json<async_graphql::Response> { /// Json(schema.execute(req.0).await) /// } /// /// let schema = Schema::new(Query, EmptyMutation, EmptySubscription); /// let app = Route::new().at("/", post(index.with(AddData::new(schema)))); /// ``` pub struct GraphQLRequest(pub async_graphql::Request); #[async_trait] impl<'a> FromRequest<'a> for GraphQLRequest { async fn from_request(req: &'a Request, body: &mut RequestBody) -> Result<Self> { Ok(GraphQLRequest( GraphQLBatchRequest::from_request(req, body) .await? .0 .into_single() .map_err(BadRequest)?, )) } } /// An extractor for GraphQL batch request. pub struct GraphQLBatchRequest(pub async_graphql::BatchRequest); #[async_trait] impl<'a> FromRequest<'a> for GraphQLBatchRequest { async fn from_request(req: &'a Request, body: &mut RequestBody) -> Result<Self> { if req.method() == Method::GET { let req = async_graphql::http::parse_query_string(req.uri().query().unwrap_or_default()) .map_err(BadRequest)?; Ok(Self(async_graphql::BatchRequest::Single(req))) } else { let content_type = req .headers() .get(header::CONTENT_TYPE) .and_then(|value| value.to_str().ok()) .map(ToString::to_string); Ok(Self( async_graphql::http::receive_batch_body( content_type, body.take()?.into_async_read().compat(), MultipartOptions::default(), ) .await .map_err(BadRequest)?, )) } } }
use bitvec::prelude::*; use thiserror::Error; #[allow(clippy::identity_op)] // look, the << 0 makes it look neater IMO fn pop_u5_from_bitvec(x: &mut BitVec<Msb0, u8>) -> u8 { let mut v = 0; v |= (*x.get(0).unwrap_or(&false) as u8) << 4; v |= (*x.get(1).unwrap_or(&false) as u8) << 3; v |= (*x.get(2).unwrap_or(&false) as u8) << 2; v |= (*x.get(3).unwrap_or(&false) as u8) << 1; v |= (*x.get(4).unwrap_or(&false) as u8) << 0; for _ in 0..5 { if !x.is_empty() { x.remove(0_usize); } } debug_assert!(v <= 31); v } #[derive(Debug, Error)] pub enum FromBase32Error { #[error("found non-base32 char {0}")] UnknownByte(char), } /// Decodes the bits from `x` as a base32 string that was previously used with [`to_base32`] into a BitVec. /// /// `max_len` is used for when there were bits left over, and you do not want to decode them as /// zero bits. pub fn from_base32(x: &str, max_len: usize) -> Result<BitVec<Msb0, u8>, FromBase32Error> { let mut result = BitVec::<Msb0, u8>::new(); for mut ch in x.bytes() { if (b'A'..=b'Z').contains(&ch) { ch |= 0b0010_0000; // Convert to lowercase } let idx = TABLE .iter() .position(|&x| x == ch) .ok_or_else(|| FromBase32Error::UnknownByte(ch as char))?; debug_assert!((ch as char).is_ascii_lowercase() || (ch as char).is_ascii_digit()); result.push(idx & 0b10000 != 0); result.push(idx & 0b01000 != 0); result.push(idx & 0b00100 != 0); result.push(idx & 0b00010 != 0); result.push(idx & 0b00001 != 0); } result.truncate(max_len); Ok(result) } static TABLE: [u8; 32] = *b"abcdefghijklmnopqrstuvwxyz234567"; /// Converts `x` into a [`String`] as base32, using the table `"abcdefghijklmnopqrstuvwxyz234567"`. /// /// Each character represents 5 bits, and if there are any bits left over, they will be used in the /// high bits to select an index from the table. /// /// /// ```rust /// use snapcd::base32::to_base32; /// /// let table: [u8; 32] = *b"abcdefghijklmnopqrstuvwxyz234567"; /// /// let x = [0b10101_010__; 1]; /// /// let s = to_base32(&x); /// let s_bytes = s.as_bytes(); /// /// let first_char = table[0b10101]; /// assert_eq!(s_bytes[0], first_char); /// /// let second_char = table[0b01000]; /// assert_eq!(s_bytes[1], second_char); /// /// assert_eq!(s, "vi"); /// ``` pub fn to_base32(x: &[u8]) -> String { let mut scratch = BitVec::<Msb0, u8>::from_vec(x.to_vec()); let mut ret = String::new(); while !scratch.is_empty() { let v = pop_u5_from_bitvec(&mut scratch); ret.push(TABLE[v as usize] as char); } ret } #[cfg(test)] mod tests { use super::*; proptest::proptest! { #[test] fn round_trip_base32(bytes: Vec<u8>) { let b32 = to_base32(&bytes); let restored = from_base32(&b32, bytes.len() * 8).unwrap(); assert_eq!(restored.as_slice(), &*bytes); } #[test] fn from_base32_non_panicking(bytes: String, mul: usize) { let _ = from_base32(&bytes, bytes.len() * (mul % 10)); } } }
use std::num::Wrapping; use num::{ Integer, Float, cast, NumCast }; use std::ops::{ Mul, Div }; pub type Timestamp = u64; pub type TimestampDiff = i64; // UWB microsecond (uus) to device time unit (dtu, around 15.65 ps) conversion factor. // 1 uus = 512 / 499.2 µs and 1 µs = 499.2 * 128 dtu. pub const UUS_TO_DTU_TIME: f64 = 65536.0; pub const DTU_TO_UUS_TIME: f64 = 1.0 / 65536.0; pub const US_TO_DTU_TIME: f64 = 499.2 * 128.0; pub const DTU_TO_US_TIME: f64 = 1.0 / 128.0 / 499.2; pub fn dwt_uus_to_us<T>(uus: T) -> T where T: Float + Mul<f64, Output=T>, { // (65536.0 / 128.0 / 499.2) uus * (512.0 / 499.2) } pub fn dwt_us_to_uus<T>(us: T) -> T where T: Float + Mul<f64, Output=T>, { // (128.0 * 499.2 / 65536.0) us * 0.975 } pub fn dwt_uus_to_ticks<T, To>(uus: T) -> To where T: Float + Mul<f64, Output=T>, To: Integer + NumCast, { // uus * 65536.0 cast::<T, To>(uus * 65536.0).unwrap() } pub fn dwt_ticks_to_uus<T, To>(ticks: T) -> To where T: Integer + NumCast, To: Float + Div<f64, Output=To>, { // ticks / 65536.0 cast::<T, To>(ticks).unwrap() / 65536.0 } pub fn dwt_us_to_ticks<T, To>(us: T) -> To where T: Float + Mul<f64, Output=T>, To: Integer + NumCast, { // us * 63897.6 cast::<T, To>(us * 63897.6).unwrap() } pub fn dwt_ticks_to_us<T, To>(ticks: T) -> To where T: Integer + NumCast, To: Float + Div<f64, Output=To>, { // ticks / 63897.6 cast::<T, To>(ticks).unwrap() / 63897.6 } pub fn dwt_time_diff(t1: u64, t2: u64) -> i64 { let mut dt: i64 = (Wrapping(t1) - Wrapping(t2)).0 as i64; if dt >= 2i64.pow(39) { dt -= 2i64.pow(40); } if dt < -2i64.pow(39) { dt += 2i64.pow(40); } dt } #[cfg(test)] mod tests { use super::*; #[test] fn test_dwt_uus_to_us() { assert_eq!(dwt_uus_to_us(8.0), 8.0 * UUS_TO_DTU_TIME * DTU_TO_US_TIME); } #[test] fn test_dwt_us_to_uus() { assert_eq!(dwt_us_to_uus(8.0), 8.0 * US_TO_DTU_TIME * DTU_TO_UUS_TIME); } #[test] fn test_dwt_uus_to_ticks() { assert_eq!(dwt_uus_to_ticks::<_, u64>(8.0), (8.0 * UUS_TO_DTU_TIME) as u64); } #[test] fn test_dwt_ticks_to_uus() { assert_eq!(dwt_ticks_to_uus::<_, f64>(8), 8.0 * DTU_TO_UUS_TIME); } #[test] fn test_dwt_us_to_ticks() { assert_eq!(dwt_us_to_ticks::<_, u64>(8.0), (8.0 * US_TO_DTU_TIME) as u64); } #[test] fn test_dwt_ticks_to_us() { assert_eq!(dwt_ticks_to_us::<_, f64>(8), 8.0 * DTU_TO_US_TIME); } #[test] fn test_dwt_time_diff() { assert_eq!(dwt_time_diff(8, 0), 8); assert_eq!(dwt_time_diff(0, 8), -8); assert_eq!(dwt_time_diff(8, 2u64.pow(40)), 8); assert_eq!(dwt_time_diff(0, 2u64.pow(40) + 8), -8); } }