blob_id
stringlengths 40
40
| language
stringclasses 1
value | repo_name
stringlengths 5
140
| path
stringlengths 5
183
| src_encoding
stringclasses 6
values | length_bytes
int64 12
5.32M
| score
float64 2.52
4.94
| int_score
int64 3
5
| detected_licenses
listlengths 0
47
| license_type
stringclasses 2
values | text
stringlengths 12
5.32M
| download_success
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
7854f0d243425d917f19d5b06fb07b00e228a64a
|
Rust
|
SnoozeTime/game-off-2019
|
/src/states/gameover.rs
|
UTF-8
| 3,391
| 3.046875
| 3
|
[] |
no_license
|
use crate::{
event::{AppEvent, MyEvent},
states::MyTrans,
util::delete_hierarchy,
};
use amethyst::{
ecs::prelude::Entity,
input::{is_close_requested, is_key_down},
prelude::*,
ui::{UiCreator, UiEvent, UiEventType, UiFinder},
winit::VirtualKeyCode,
};
use log::info;
const RETRY_BUTTON_ID: &str = "retry";
const EXIT_TO_MAIN_MENU_BUTTON_ID: &str = "exit_to_main_menu";
const EXIT_BUTTON_ID: &str = "exit";
/// Just display a text and then propose to start again or go back to main menu
#[derive(Debug, Default)]
pub struct GameOverState {
root: Option<Entity>,
// Buttons entities are created on_start and destroy on_stop()
retry_button: Option<Entity>,
exit_to_main_menu_button: Option<Entity>,
exit_button: Option<Entity>,
}
impl State<GameData<'static, 'static>, MyEvent> for GameOverState {
fn on_start(&mut self, data: StateData<GameData>) {
info!("Start gameover state");
let world = data.world;
self.root =
Some(world.exec(|mut creator: UiCreator<'_>| creator.create("ui/gameover.ron", ())));
}
fn on_stop(&mut self, data: StateData<GameData>) {
if let Some(handler) = self.root {
delete_hierarchy(handler, data.world).expect("Failed to remove GameOverScreen");
}
self.root = None;
}
fn handle_event(&mut self, _: StateData<GameData>, event: MyEvent) -> MyTrans {
match &event {
MyEvent::Window(event) => {
if is_close_requested(&event) || is_key_down(&event, VirtualKeyCode::Escape) {
info!("[Trans::Quit] Quitting Application!");
Trans::Quit
} else {
Trans::None
}
}
MyEvent::Ui(UiEvent {
event_type: UiEventType::Click,
target,
}) => {
if Some(*target) == self.retry_button {
info!("[Trans::Switch] Switching to Game!");
Trans::Switch(Box::new(crate::states::GameState::default()))
} else if Some(*target) == self.exit_button {
info!("[Trans::Quit] Quitting Application!");
Trans::Quit
} else {
Trans::None
}
}
MyEvent::App(e) => {
if let AppEvent::NewDialog {
dialog: sentences, ..
} = e
{
Trans::Push(Box::new(crate::states::DialogState::new(sentences.clone())))
} else {
Trans::None
}
}
_ => Trans::None,
}
}
/// Will get the entities for the UI elements from UiFinder.
fn update(&mut self, data: StateData<GameData>) -> MyTrans {
data.data.update(&data.world);
if self.retry_button.is_none()
|| self.exit_to_main_menu_button.is_none()
|| self.exit_button.is_none()
{
data.world.exec(|ui_finder: UiFinder<'_>| {
self.retry_button = ui_finder.find(RETRY_BUTTON_ID);
self.exit_button = ui_finder.find(EXIT_BUTTON_ID);
self.exit_to_main_menu_button = ui_finder.find(EXIT_TO_MAIN_MENU_BUTTON_ID);
});
}
MyTrans::None
}
}
| true
|
cae742176261447b0c1a2ff334fe9f14c465df71
|
Rust
|
cocagne/aspen-server
|
/src/crl/sweeper/log_file.rs
|
UTF-8
| 14,047
| 2.625
| 3
|
[] |
no_license
|
use std::collections::{HashMap, HashSet};
use std::fmt;
use std::ffi::CString;
use std::io::{Result, Error, ErrorKind};
use std::os::unix::ffi::OsStrExt;
use std::path::{Path, PathBuf};
use libc;
use log::{error, info, warn};
use crate::{Data, ArcDataSlice};
use super::*;
pub(super) struct LogFile {
file_path: Box<PathBuf>,
pub file_id: FileId,
fd: libc::c_int,
pub len: usize,
pub max_size: usize,
pub file_uuid: uuid::Uuid
}
impl Drop for LogFile {
fn drop(&mut self) {
unsafe {
libc::close(self.fd);
}
}
}
impl fmt::Display for LogFile {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "CRL Sweeper File: {}", self.file_path.as_path().display())
}
}
#[cfg(target_os="linux")]
fn open_synchronous_fd(path: &CString) -> libc::c_int {
const O_DIRECT: libc::c_int = 0x4000;
const O_DSYNC: libc::c_int = 4000;
unsafe {
libc::open(path.as_ptr(), libc::O_CREAT | libc::O_RDWR | O_DIRECT | O_DSYNC)
}
}
#[cfg(target_os="macos")]
fn open_synchronous_fd(path: &CString) -> libc::c_int {
const F_NOCACHE: libc::c_int = 0x30;
unsafe {
let mut fd = libc::open(path.as_ptr(), libc::O_CREAT | libc::O_RDWR);
if fd > 0 {
if libc::fchmod(fd, 0o644) < 0 {
fd = -1;
}
}
if fd > 0 {
if libc::fcntl(fd, F_NOCACHE, 1) < 0 {
fd = -1;
}
}
fd
}
}
#[cfg(not(any(target_os="linux", target_os="macos")))]
fn open_synchronous_fd(path: &CString) -> libc::c_int {
unsafe {
libc::open(path.as_ptr(), libc::O_CREAT | libc::O_RDWR)
}
}
impl LogFile {
fn new(
directory: &Path,
file_id: FileId,
max_file_size: usize) -> Result<(LogFile, Option<(LogEntrySerialNumber, usize)>)> {
let f = format!("{}", file_id.0);
let p = directory.join(f);
let fp = p.as_path();
let fd = open_synchronous_fd(&CString::new(fp.as_os_str().as_bytes()).unwrap());
if fd < 0 {
error!("Failed to open CRL file {}", fp.display());
return Err(Error::last_os_error());
}
let mut size = seek(fd, 0, libc::SEEK_END)?;
if size < (16 + STATIC_ENTRY_SIZE as usize) {
// Initialize
seek(fd, 0, libc::SEEK_SET)?;
unsafe {
libc::ftruncate(fd, 0);
}
let u = uuid::Uuid::new_v4();
write_bytes(fd, &u.as_bytes()[..])?;
}
let file_uuid = pread_uuid(fd, 0)?;
size = seek(fd, 0, libc::SEEK_END)?;
let last = find_last_valid_entry(fd, size, &file_uuid)?;
let lf = LogFile{
file_path: Box::new(p),
file_id,
fd,
len: size as usize,
max_size: max_file_size,
file_uuid
};
Ok((lf, last))
}
fn read(&self, offset: usize, nbytes: usize) -> Result<Data> {
let mut v = Vec::<u8>::with_capacity(nbytes);
if nbytes > 0 {
v.resize(nbytes, 0);
pread_bytes(self.fd, &mut v[..], offset)?;
}
Ok(Data::new(v))
}
pub(super) fn write(&mut self, data: &Vec<ArcDataSlice>) -> Result<()> {
let wsize: usize = data.iter().map(|d| d.len()).sum();
unsafe {
let iov: Vec<libc::iovec> = data.iter().map( |d| {
let p: *const u8 = &d.as_bytes()[0];
libc::iovec {
iov_base: p as *mut libc::c_void,
iov_len: d.len()
}
}).collect();
loop {
if libc::writev(self.fd, &iov[0], data.len() as libc::c_int) >= 0 {
break;
} else {
let err = Error::last_os_error();
match err.kind() {
ErrorKind::Interrupted => (),
_ => return {
warn!("Unexpected error occured during CRL file write: {}", err);
Err(err)
}
}
}
}
if !( cfg!(target_os="linux") || cfg!(target_os="macos") ) {
libc::fsync(self.fd);
}
}
self.len += wsize;
Ok(())
}
pub(super) fn recycle(&mut self) -> Result<()> {
info!("Recycling {}", self);
seek(self.fd, 0, libc::SEEK_SET)?;
unsafe {
libc::ftruncate(self.fd, 0);
}
self.file_uuid = uuid::Uuid::new_v4();
self.len = 16;
write_bytes(self.fd, &self.file_uuid.as_bytes()[..])?;
Ok(())
}
}
fn pread_bytes(fd: libc::c_int, s: &mut [u8], offset: usize) -> Result<()> {
if s.len() == 0 {
Ok(())
} else {
let p: *mut u8 = &mut s[0];
unsafe {
if libc::pread(fd, p as *mut libc::c_void, s.len(), offset as libc::off_t) < 0 {
Err(Error::last_os_error())
} else {
Ok(())
}
}
}
}
fn pread_uuid(fd: libc::c_int, offset: usize) -> Result<uuid::Uuid> {
let mut buf: [u8; 16] = [0; 16];
pread_bytes(fd, &mut buf[..], offset)?;
Ok(uuid::Uuid::from_bytes(buf))
}
fn write_bytes(fd: libc::c_int, s: &[u8]) -> Result<()> {
let p: *const u8 = &s[0];
unsafe {
if libc::write(fd, p as *const libc::c_void, s.len()) < 0 {
return Err(Error::last_os_error());
}
libc::fsync(fd);
}
Ok(())
}
fn seek(fd: libc::c_int, offset: i64, whence: libc::c_int) -> Result<usize> {
unsafe {
let sz = libc::lseek(fd, offset, whence);
if sz < 0 {
Err(Error::last_os_error())
} else {
Ok(sz as usize)
}
}
}
fn find_last_valid_entry(
fd: libc::c_int,
file_size: usize,
file_uuid: &uuid::Uuid) -> Result<Option<(LogEntrySerialNumber, usize)>> {
let mut offset = file_size - (file_size % 4096);
let mut last = None;
while offset > 32 && last.is_none() {
let test_uuid = pread_uuid(fd, offset - 16)?;
if test_uuid == *file_uuid {
let entry_offset = offset - STATIC_ENTRY_SIZE as usize;
let mut serial_bytes: [u8; 8] = [0; 8];
pread_bytes(fd, &mut serial_bytes[..], entry_offset)?;
let serial = u64::from_le_bytes(serial_bytes);
last = Some((LogEntrySerialNumber(serial), entry_offset));
break;
}
offset -= 4096;
}
//println!("LAST: {:?} file size {} offset {}", last, file_size, (file_size - (file_size % 4096)));
Ok(last)
}
pub(super) fn recover(
crl_directory: &Path,
max_file_size: usize,
num_streams: usize) -> Result<RecoveredCrlState> {
let mut raw_files = Vec::<(LogFile, Option<(LogEntrySerialNumber, usize)>)>::new();
for i in 0 .. num_streams * 3 {
let f = LogFile::new(crl_directory, FileId(i as u16), max_file_size)?;
raw_files.push(f);
}
let mut last: Option<(FileId, LogEntrySerialNumber, usize)> = None;
for t in &raw_files {
if let Some((serial, offset)) = &t.1 {
if let Some((_, cur_serial, _)) = &last {
if serial > cur_serial {
last = Some((t.0.file_id, *serial, *offset));
}
} else {
last = Some((t.0.file_id, *serial, *offset))
}
}
}
let mut files: Vec<(LogFile, Option<LogEntrySerialNumber>)> = Vec::new();
for t in raw_files {
files.push((t.0, t.1.map(|x| x.0)));
}
let mut tx: Vec<RecoveredTx> = Vec::new();
let mut alloc: Vec<RecoveredAlloc> = Vec::new();
let mut last_entry_serial = LogEntrySerialNumber(0);
let mut last_entry_location = FileLocation {
file_id: FileId(0),
offset: 0,
length: 0
};
if let Some((last_file_id, last_serial, last_offset)) = last {
last_entry_serial = last_serial;
last_entry_location = FileLocation {
file_id: last_file_id,
offset: last_offset as u64,
length: STATIC_ENTRY_SIZE as u32
};
let mut transactions: HashMap<TxId, RecoveringTx> = HashMap::new();
let mut allocations: HashMap<TxId, RecoveringAlloc> = HashMap::new();
let mut deleted_tx: HashSet<TxId> = HashSet::new();
let mut deleted_alloc: HashSet<TxId> = HashSet::new();
let mut file_id = last_file_id;
let mut entry_serial = last_serial;
let mut entry_block_offset = last_offset;
let earliest_serial_needed = {
let mut d = files[last_file_id.0 as usize].0.read(last_offset, STATIC_ENTRY_SIZE as usize)?;
let entry = encoding::decode_entry(&mut d)?;
LogEntrySerialNumber(entry.earliest_needed)
};
while entry_serial >= earliest_serial_needed {
let file = &files[file_id.0 as usize].0;
let mut d = file.read(entry_block_offset, STATIC_ENTRY_SIZE as usize)?;
let mut entry = encoding::decode_entry(&mut d)?;
entry_serial = entry.serial;
//println!("Reading Entry {:?} entry_block_offset {} entry offset {}", entry_serial, entry_block_offset, entry.entry_offset);
let entry_data_size = entry_block_offset - entry.entry_offset as usize;
let mut entry_data = file.read(entry.entry_offset as usize, entry_data_size)?;
encoding::load_entry_data(&mut entry_data, &mut entry, entry_serial)?;
for txid in &entry.tx_deletions {
deleted_tx.insert(*txid);
}
for txid in &entry.alloc_deletions {
deleted_alloc.insert(*txid);
}
for rtx in entry.transactions {
if ! deleted_tx.contains(&rtx.id) && ! transactions.contains_key(&rtx.id) {
transactions.insert(rtx.id, rtx);
}
}
for ra in entry.allocations {
if ! deleted_alloc.contains(&ra.id) && ! allocations.contains_key(&ra.id) {
allocations.insert(ra.id, ra);
}
}
if entry.previous_entry_location.offset < 16 {
break; // Cannot have an offset of 0 (first 16 bytes of the file are the UUID)
}
file_id = entry.previous_entry_location.file_id;
entry_block_offset = entry.previous_entry_location.offset as usize;
}
let get_data = |file_location: &FileLocation| -> Result<ArcData> {
let d = files[file_location.file_id.0 as usize].0.read(file_location.offset as usize, file_location.length as usize)?;
Ok(d.into())
};
let get_slice = |file_location: &FileLocation| -> Result<ArcDataSlice> {
let d = get_data(file_location)?;
Ok(d.into())
};
for (txid, rtx) in transactions {
let mut ou: Vec<transaction::ObjectUpdate> = Vec::with_capacity(rtx.object_updates.len());
for t in &rtx.object_updates {
ou.push(transaction::ObjectUpdate {
object_id: object::Id(t.0),
data: get_slice(&t.1)?
});
}
tx.push( RecoveredTx {
id: txid,
txd_location: rtx.serialized_transaction_description,
serialized_transaction_description: get_data(&rtx.serialized_transaction_description)?,
object_updates: ou,
update_locations: rtx.object_updates,
tx_disposition: rtx.tx_disposition,
paxos_state: rtx.paxos_state,
last_entry_serial: rtx.last_entry_serial
});
}
for (txid, ra) in allocations {
alloc.push(RecoveredAlloc{
id: txid,
store_pointer: ra.store_pointer,
object_id: ra.object_id,
kind: ra.kind,
size: ra.size,
data_location: ra.data,
data: get_data(&ra.data)?,
refcount: ra.refcount,
timestamp: ra.timestamp,
serialized_revision_guard: ra.serialized_revision_guard,
last_entry_serial: ra.last_entry_serial
});
}
};
Ok(RecoveredCrlState {
log_files: files,
transactions: tx,
allocations: alloc,
last_entry_serial,
last_entry_location
})
}
#[cfg(test)]
mod tests {
use tempdir::TempDir;
use super::*;
#[test]
fn initialization() {
let t = TempDir::new("test").unwrap();
let (l, o) = LogFile::new(t.path(), FileId(0), 50).unwrap();
let u = l.file_uuid;
assert!(o.is_none());
assert_eq!(l.len, 16);
let ru = pread_uuid(l.fd, 0).unwrap();
assert_eq!(u, ru);
unsafe {
let n = libc::lseek(l.fd, 0, libc::SEEK_END);
assert_eq!(n, 16);
}
}
#[test]
fn recycle() {
let t = TempDir::new("test").unwrap();
let (mut l, o) = LogFile::new(t.path(), FileId(0), 50).unwrap();
let u = l.file_uuid;
assert!(o.is_none());
assert_eq!(l.len, 16);
let ru = pread_uuid(l.fd, 0).unwrap();
assert_eq!(u, ru);
write_bytes(l.fd, &[1u8,2u8,3u8,4u8]).unwrap();
unsafe {
let n = libc::lseek(l.fd, 0, libc::SEEK_END);
assert_eq!(n, 20);
}
l.recycle().unwrap();
let ru = pread_uuid(l.fd, 0).unwrap();
assert_ne!(u, ru);
assert_eq!(l.file_uuid, ru);
unsafe {
let n = libc::lseek(l.fd, 0, libc::SEEK_END);
assert_eq!(n, 16);
}
}
}
| true
|
cd010b754bd21998db42eedafe1721e592bca7ca
|
Rust
|
zaeleus/noodles
|
/noodles-bam/src/lazy/record/cigar.rs
|
UTF-8
| 1,097
| 2.671875
| 3
|
[
"MIT"
] |
permissive
|
use std::io;
use noodles_sam as sam;
/// Raw BAM record CIGAR operations.
#[derive(Debug, Eq, PartialEq)]
pub struct Cigar<'a>(&'a [u8]);
impl<'a> Cigar<'a> {
pub(super) fn new(src: &'a [u8]) -> Self {
Self(src)
}
/// Returns whether there are any CIGAR operations.
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
/// Returns the number of CIGAR operations.
///
/// This is _not_ the length of the buffer.
pub fn len(&self) -> usize {
self.0.len() / 4
}
}
impl<'a> AsRef<[u8]> for Cigar<'a> {
fn as_ref(&self) -> &[u8] {
self.0
}
}
impl<'a> TryFrom<Cigar<'a>> for sam::record::Cigar {
type Error = io::Error;
fn try_from(bam_cigar: Cigar<'a>) -> Result<Self, Self::Error> {
use crate::record::codec::decoder::get_cigar;
let mut src = bam_cigar.0;
let mut cigar = Self::default();
let op_count = bam_cigar.len();
get_cigar(&mut src, &mut cigar, op_count)
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
Ok(cigar)
}
}
| true
|
7e266acac341196b63ca004e859f739310f9aca1
|
Rust
|
zeta1999/titik
|
/src/widget/image_control.rs
|
UTF-8
| 2,075
| 3.140625
| 3
|
[
"MIT"
] |
permissive
|
use crate::{
buffer::Buffer,
widget::traits::ImageTrait,
Cmd,
LayoutTree,
Widget,
};
use image::{
self,
DynamicImage,
};
use std::{
any::Any,
fmt,
marker::PhantomData,
};
use stretch::style::Style;
/// Image widget, supported formats: jpg, png
pub struct Image<MSG> {
image: DynamicImage,
/// the width of cells used for this image
width: Option<f32>,
/// the height of unit cells, will be divided by 2 when used for computing
/// style layout
height: Option<f32>,
id: Option<String>,
_phantom_msg: PhantomData<MSG>,
}
impl<MSG> Image<MSG> {
/// create a new image widget
pub fn new(bytes: Vec<u8>) -> Self {
let image = Image {
image: image::load_from_memory(&bytes)
.expect("unable to load from memory"),
width: None,
height: None,
id: None,
_phantom_msg: PhantomData,
};
image
}
}
impl<MSG> ImageTrait for Image<MSG> {
fn width(&self) -> Option<f32> {
self.width
}
fn height(&self) -> Option<f32> {
self.height
}
fn image(&self) -> &DynamicImage {
&self.image
}
}
impl<MSG> Widget<MSG> for Image<MSG>
where
MSG: 'static,
{
fn style(&self) -> Style {
self.image_style()
}
/// draw this button to the buffer, with the given computed layout
fn draw(&mut self, buf: &mut Buffer, layout_tree: &LayoutTree) -> Vec<Cmd> {
self.draw_image(buf, layout_tree)
}
fn as_any(&self) -> &dyn Any {
self
}
fn as_any_mut(&mut self) -> &mut dyn Any {
self
}
fn set_size(&mut self, width: Option<f32>, height: Option<f32>) {
self.width = width;
self.height = height;
}
fn set_id(&mut self, id: &str) {
self.id = Some(id.to_string());
}
fn get_id(&self) -> &Option<String> {
&self.id
}
}
impl<MSG> fmt::Debug for Image<MSG> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Image")
}
}
| true
|
221abfa7d36998dcdf0fed4b4e38b3c378632c0b
|
Rust
|
mattiasgronlund/cubemx-db-decoder
|
/src/cubemx_db/ip/bsp_dependency.rs
|
UTF-8
| 1,710
| 2.890625
| 3
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
use super::Condition;
use crate::{
decode::{AttributeMap, Decode},
error::Unexpected,
Config, Error,
};
#[derive(Debug)]
pub struct BspDependency {
pub name: String,
pub comment: String,
pub bsp_ip_name: String,
pub bsp_mode_name: Option<String>,
pub user_name: Option<String>,
pub api: Option<String>,
pub component: Option<String>,
pub condition: Vec<Condition>,
}
impl Decode for BspDependency {
type Object = BspDependency;
fn decode(config: Config, node: roxmltree::Node) -> Result<Self::Object, Error> {
let mut attributes = AttributeMap::from(node, config);
let mut condition = Vec::new();
for child in node.children() {
match child.node_type() {
roxmltree::NodeType::Element => match child.tag_name().name() {
"Condition" => condition.push(Condition::decode(config, child)?),
_ => Unexpected::element(config, &node, &child)?,
},
roxmltree::NodeType::Text => Unexpected::text(config, &node, &child)?,
_ => {}
}
}
let result = BspDependency {
name: attributes.take_required("Name")?,
comment: attributes.take_required("Comment")?,
bsp_ip_name: attributes.take_required("BspIpName")?,
bsp_mode_name: attributes.take_optional("BspModeName"),
user_name: attributes.take_optional("UserName"),
api: attributes.take_optional("Api"),
component: attributes.take_optional("Component"),
condition,
};
attributes.report_unexpected_if_not_empty()?;
Ok(result)
}
}
| true
|
94559e67a219d06cf3409cb5cd5b8878ca6f99e4
|
Rust
|
rust-lang/rustfmt
|
/tests/source/cfg_if/detect/os/freebsd/auxvec.rs
|
UTF-8
| 2,795
| 2.796875
| 3
|
[
"MIT",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
//! Parses ELF auxiliary vectors.
#![cfg_attr(any(target_arch = "arm", target_arch = "powerpc64"), allow(dead_code))]
/// Key to access the CPU Hardware capabilities bitfield.
pub(crate) const AT_HWCAP: usize = 25;
/// Key to access the CPU Hardware capabilities 2 bitfield.
pub(crate) const AT_HWCAP2: usize = 26;
/// Cache HWCAP bitfields of the ELF Auxiliary Vector.
///
/// If an entry cannot be read all the bits in the bitfield are set to zero.
/// This should be interpreted as all the features being disabled.
#[derive(Debug, Copy, Clone)]
pub(crate) struct AuxVec {
pub hwcap: usize,
pub hwcap2: usize,
}
/// ELF Auxiliary Vector
///
/// The auxiliary vector is a memory region in a running ELF program's stack
/// composed of (key: usize, value: usize) pairs.
///
/// The keys used in the aux vector are platform dependent. For FreeBSD, they are
/// defined in [sys/elf_common.h][elf_common_h]. The hardware capabilities of a given
/// CPU can be queried with the `AT_HWCAP` and `AT_HWCAP2` keys.
///
/// Note that run-time feature detection is not invoked for features that can
/// be detected at compile-time.
///
/// [elf_common.h]: https://svnweb.freebsd.org/base/release/12.0.0/sys/sys/elf_common.h?revision=341707
pub(crate) fn auxv() -> Result<AuxVec, ()> {
if let Ok(hwcap) = archauxv(AT_HWCAP) {
if let Ok(hwcap2) = archauxv(AT_HWCAP2) {
if hwcap != 0 && hwcap2 != 0 {
return Ok(AuxVec { hwcap, hwcap2 });
}
}
}
Err(())
}
/// Tries to read the `key` from the auxiliary vector.
fn archauxv(key: usize) -> Result<usize, ()> {
use crate::mem;
#[derive (Copy, Clone)]
#[repr(C)]
pub struct Elf_Auxinfo {
pub a_type: usize,
pub a_un: unnamed,
}
#[derive (Copy, Clone)]
#[repr(C)]
pub union unnamed {
pub a_val: libc::c_long,
pub a_ptr: *mut libc::c_void,
pub a_fcn: Option<unsafe extern "C" fn() -> ()>,
}
let mut auxv: [Elf_Auxinfo; 27] =
[Elf_Auxinfo{a_type: 0, a_un: unnamed{a_val: 0,},}; 27];
let mut len: libc::c_uint = mem::size_of_val(&auxv) as libc::c_uint;
unsafe {
let mut mib = [libc::CTL_KERN, libc::KERN_PROC, libc::KERN_PROC_AUXV, libc::getpid()];
let ret = libc::sysctl(mib.as_mut_ptr(),
mib.len() as u32,
&mut auxv as *mut _ as *mut _,
&mut len as *mut _ as *mut _,
0 as *mut libc::c_void,
0,
);
if ret != -1 {
for i in 0..auxv.len() {
if auxv[i].a_type == key {
return Ok(auxv[i].a_un.a_val as usize);
}
}
}
}
return Ok(0);
}
| true
|
76ef40415e911edbaeac5c53ffd27e73fae782fe
|
Rust
|
seanjensengrey/rust-copperline
|
/src/run.rs
|
UTF-8
| 3,187
| 3.25
| 3
|
[
"MIT"
] |
permissive
|
use error::Error;
use edit::{EditCtx, EditResult, edit};
use builder::Builder;
use parser::{parse_cursor_pos, ParseError, ParseSuccess};
pub trait RunIO {
fn write(&mut self, Vec<u8>) -> Result<(), Error>;
fn read_byte(&mut self) -> Result<u8, Error>;
fn prompt(&mut self, w: Vec<u8>) -> Result<u8, Error> {
try!(self.write(w));
self.read_byte()
}
}
fn query_cursor_pos(io: &mut RunIO) -> Result<(u64, u64), Error> {
let mut line = Builder::new();
line.ask_cursor_pos();
try!(io.write(line.build()));
let mut seq = vec![];
loop {
match parse_cursor_pos(&seq) {
Ok(ParseSuccess(pos, _)) => {
return Ok(pos);
},
Err(ParseError::Error(_)) => {
return Err(Error::ParseError);
},
Err(ParseError::Incomplete) => {
let byte = try!(io.read_byte());
seq.push(byte);
}
}
}
}
fn protect_newline(io: &mut RunIO) -> Result<(), Error> {
let (x, _) = try!(query_cursor_pos(io));
if x > 1 {
let mut line = Builder::new();
line.invert_color();
line.append("%\n");
line.reset_color();
try!(io.write(line.build()));
}
Ok(())
}
fn run_edit<'a>(mut ctx: EditCtx<'a>, io: &mut RunIO) -> Result<String, Error> {
loop {
match edit(&mut ctx) {
EditResult::Cont(line) => {
ctx.fill(try!(io.prompt(line)));
},
EditResult::Halt(res) => { return res; }
}
}
}
pub fn run<'a>(ctx: EditCtx<'a>, io: &mut RunIO) -> Result<String, Error> {
try!(protect_newline(io));
run_edit(ctx, io)
}
#[cfg(test)]
mod test {
use encoding::all::ASCII;
use super::super::error::Error;
use super::super::edit::EditCtx;
use super::super::history::History;
use super::{RunIO, run_edit};
pub struct TestIO {
input: Vec<u8>,
output: Vec<u8>
}
impl RunIO for TestIO {
fn write(&mut self, w: Vec<u8>) -> Result<(), Error> {
self.output.extend(w);
Ok(())
}
fn read_byte(&mut self) -> Result<u8, Error> {
if self.input.len() > 0 {
Ok(self.input.remove(0))
} else {
Err(Error::EndOfFile)
}
}
}
#[test]
fn error_eof_on_empty_input() {
let mut io = TestIO { input: vec![], output: vec![] };
let h = History::new();
let ctx = EditCtx::new("foo> ", &h, ASCII);
assert_eq!(run_edit(ctx, &mut io), Err(Error::EndOfFile));
}
#[test]
fn ok_empty_after_return() {
let mut io = TestIO { input: vec![13], output: vec![] };
let h = History::new();
let ctx = EditCtx::new("foo> ", &h, ASCII);
assert_eq!(run_edit(ctx, &mut io), Ok("".to_string()));
}
#[test]
fn ok_ascii_after_return() {
let mut io = TestIO { input: vec![65, 66, 67, 13], output: vec![] };
let h = History::new();
let ctx = EditCtx::new("foo> ", &h, ASCII);
assert_eq!(run_edit(ctx, &mut io), Ok("ABC".to_string()));
}
}
| true
|
b457c3384046d00e733c9e51404764c445d0053d
|
Rust
|
schell/todo_finder
|
/todo_finder_lib/src/parser.rs
|
UTF-8
| 11,540
| 2.890625
| 3
|
[
"MIT"
] |
permissive
|
use nom::{bytes::complete as bytes, character::complete as character, combinator, IResult};
use super::{
finder::FileSearcher,
github::{GitHubIssue, GitHubPatch},
};
use serde::Deserialize;
use std::{collections::HashMap, fs::File, io::prelude::*, path::Path};
pub mod issue;
pub mod langs;
pub mod source;
use issue::GitHubTodoLocation;
use source::ParsedTodo;
/// Eat a whole line and optionally its ending but don't return that ending.
pub fn take_to_eol(i: &str) -> IResult<&str, &str> {
let (i, ln) = bytes::take_till(|c| c == '\r' || c == '\n')(i)?;
let (i, _) = combinator::opt(character::line_ending)(i)?;
Ok((i, ln))
}
#[derive(Debug, Deserialize, Clone)]
pub enum IssueProvider {
GitHub,
}
#[derive(Debug, Clone)]
pub enum ParsingSource {
MarkdownFile,
SourceCode,
IssueAt(IssueProvider),
}
#[derive(Debug, Clone)]
pub struct IssueHead<K> {
pub title: String,
pub assignees: Vec<String>,
pub external_id: K,
}
#[derive(Debug, Clone, PartialEq)]
pub struct IssueBody<T> {
pub descs_and_srcs: Vec<(Vec<String>, T)>,
pub branches: Vec<String>,
}
impl IssueBody<FileTodoLocation> {
pub fn to_github_string(
&self,
cwd: &str,
owner: &str,
repo: &str,
checkout: &str,
) -> Result<String, String> {
let mut lines: Vec<String> = vec![];
for (desc_lines, loc) in self.descs_and_srcs.iter() {
let desc = desc_lines.clone().join("\n");
let link = loc.to_github_link(cwd, owner, repo, checkout)?;
lines.push(vec![desc, link].join("\n"));
}
Ok(lines.join("\n"))
}
}
#[derive(Debug, Clone)]
pub struct Issue<ExternalId, TodoLocation: PartialEq + Eq> {
pub head: IssueHead<ExternalId>,
pub body: IssueBody<TodoLocation>,
}
impl<ExId, Loc: PartialEq + Eq> Issue<ExId, Loc> {
pub fn new(id: ExId, title: String) -> Self {
Issue {
head: IssueHead {
title,
assignees: vec![],
external_id: id,
},
body: IssueBody {
descs_and_srcs: vec![],
branches: vec![],
},
}
}
}
#[derive(Debug, Clone)]
pub struct IssueMap<ExternalId, TodoLocation: PartialEq + Eq> {
pub parsed_from: ParsingSource,
pub todos: HashMap<String, Issue<ExternalId, TodoLocation>>,
}
/// A todo location in the local filesystem.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct FileTodoLocation {
pub file: String,
pub src_span: (usize, Option<usize>),
}
impl FileTodoLocation {
/// ```rust
/// use todo_finder_lib::parser::FileTodoLocation;
///
/// let loc = FileTodoLocation {
/// file: "/total/path/src/file.rs".into(),
/// src_span: (666, Some(1337)),
/// };
///
/// let string = loc
/// .to_github_link("/total/path", "schell", "my_repo", "1234567890")
/// .unwrap();
///
/// assert_eq!(
/// &string,
/// "https://github.com/schell/my_repo/blob/1234567890/src/file.rs#L666-L1337"
/// );
/// ```
pub fn to_github_link(
&self,
cwd: &str,
owner: &str,
repo: &str,
checkout: &str,
) -> Result<String, String> {
let path: &Path = Path::new(&self.file);
let relative: &Path = path
.strip_prefix(cwd)
.map_err(|e| format!("could not relativize path {:#?}: {}", path, e))?;
let file_and_range = vec![
format!("{}", relative.display()),
format!("#L{}", self.src_span.0),
if let Some(end) = self.src_span.1 {
format!("-L{}", end)
} else {
String::new()
},
]
.concat();
let parts = vec![
"https://github.com",
owner,
repo,
"blob",
checkout,
&file_and_range,
];
Ok(parts.join("/"))
}
}
impl<K, V: Eq> IssueMap<K, V> {
pub fn new(parsed_from: ParsingSource) -> IssueMap<K, V> {
IssueMap {
parsed_from,
todos: HashMap::new(),
}
}
}
impl IssueMap<u64, GitHubTodoLocation> {
pub fn new_github_todos() -> Self {
IssueMap {
parsed_from: ParsingSource::IssueAt(IssueProvider::GitHub),
todos: HashMap::new(),
}
}
pub fn add_issue(&mut self, github_issue: &GitHubIssue) {
if let Ok((_, body)) = issue::issue_body(&github_issue.body) {
let mut issue = Issue::new(github_issue.number, github_issue.title.clone());
issue.body = body;
self.todos.insert(github_issue.title.clone(), issue);
}
}
pub fn prepare_patch(&self, local: IssueMap<(), FileTodoLocation>) -> GitHubPatch {
let mut create = IssueMap::new_source_todos();
let mut edit: IssueMap<u64, FileTodoLocation> = IssueMap::new(ParsingSource::SourceCode);
let mut dont_delete = vec![];
for (title, local_issue) in local.todos.into_iter() {
if let Some(remote_issue) = self.todos.get(&title) {
// They both have it
let id = remote_issue.head.external_id.clone();
dont_delete.push(id);
let issue = Issue {
head: remote_issue.head.clone(),
body: local_issue.body,
};
edit.todos.insert(title, issue);
} else {
// Must be created
create.todos.insert(title, local_issue);
}
}
let delete = self
.todos
.values()
.filter_map(|issue| {
let id = issue.head.external_id;
if dont_delete.contains(&id) {
None
} else {
Some(id)
}
})
.collect::<Vec<_>>();
return GitHubPatch {
create,
edit,
delete,
};
}
}
impl IssueMap<(), FileTodoLocation> {
pub fn new_source_todos() -> Self {
IssueMap {
parsed_from: ParsingSource::SourceCode,
todos: HashMap::new(),
}
}
pub fn distinct_len(&self) -> usize {
self.todos.len()
}
pub fn add_parsed_todo(&mut self, todo: &ParsedTodo, loc: FileTodoLocation) {
let title = todo.title.to_string();
let issue = self
.todos
.entry(title.clone())
.or_insert(Issue::new((), title));
if let Some(assignee) = todo.assignee.map(|s| s.to_string()) {
if !issue.head.assignees.contains(&assignee) {
issue.head.assignees.push(assignee);
}
}
let desc_lines = todo
.desc_lines
.iter()
.map(|s| s.to_string())
.collect::<Vec<_>>();
issue.body.descs_and_srcs.push((desc_lines, loc));
}
pub fn from_files_in_directory(
dir: &str,
excludes: &Vec<String>,
) -> Result<IssueMap<(), FileTodoLocation>, String> {
let possible_todos = FileSearcher::find(dir, excludes)?;
let mut todos = IssueMap::new_source_todos();
let language_map = langs::language_map();
for possible_todo in possible_todos.into_iter() {
let path = Path::new(&possible_todo.file);
// Get our parser for this extension
let ext: Option<_> = path.extension();
if ext.is_none() {
continue;
}
let ext: &str = ext
.expect("impossible!")
.to_str()
.expect("could not get extension as str");
let languages = language_map.get(ext);
if languages.is_none() {
// TODO: Deadletter the file name as unsupported
println!("possible TODO found in unsupported file: {:#?}", path);
continue;
}
let languages = languages.expect("impossible!");
// Open the file and load the contents
let mut file = File::open(path)
.map_err(|e| format!("could not open file: {}\n{}", path.display(), e))?;
let mut contents = String::new();
file.read_to_string(&mut contents)
.map_err(|e| format!("could not read file {:#?}: {}", path, e))?;
let mut current_line = 1;
let mut i = contents.as_str();
for line in possible_todo.lines_to_search.into_iter() {
// Seek to the correct line...
while line > current_line {
let (j, _) =
take_to_eol(i).map_err(|e| format!("couldn't take line:\n{}", e))?;
i = j;
current_line += 1;
}
// Try parsing in each language until we get a match
for language in languages.iter() {
let parser_config = language.as_todo_parser_config();
let parser = source::parse_todo(parser_config);
if let Ok((j, parsed_todo)) = parser(i) {
let num_lines = i.trim_end_matches(j).lines().fold(0, |n, _| n + 1);
let loc = FileTodoLocation {
file: possible_todo.file.to_string(),
src_span: (
line,
if num_lines > 1 {
Some(line + num_lines - 1)
} else {
None
},
),
};
todos.add_parsed_todo(&parsed_todo, loc);
}
}
}
}
Ok(todos)
}
pub fn as_markdown(&self) -> String {
let num_distinct = self.todos.len();
let num_locs = self
.todos
.values()
.fold(0, |n, todo| n + todo.body.descs_and_srcs.len());
let mut lines = vec![];
lines.push("# TODOs".into());
lines.push(format!(
"Found {} distinct TODOs in {} file locations.\n",
num_distinct, num_locs
));
let mut todos = self.todos.clone().into_iter().collect::<Vec<_>>();
todos.sort_by(|a, b| a.0.cmp(&b.0));
for ((title, issue), n) in todos.into_iter().zip(1..) {
lines.push(format!("{}. {}", n, title));
for (descs, loc) in issue.body.descs_and_srcs.into_iter() {
for line in descs.into_iter() {
lines.push(format!(" {}", line));
}
lines.push(format!(
" file://{} ({})",
loc.file,
if let Some(end) = loc.src_span.1 {
format!("lines {} - {}", loc.src_span.0, end)
} else {
format!("line {}", loc.src_span.0)
},
));
lines.push("".into());
}
if issue.head.assignees.len() > 0 {
lines.push(format!(
" assignees: {}\n",
issue.head.assignees.join(", ")
));
}
}
lines.join("\n")
}
}
| true
|
190c6d70bc4a674d56a1a39ad3ac39e9ecf2a32a
|
Rust
|
gaotianyu1350/rCore_audio
|
/crate/thread/src/scheduler/o1.rs
|
UTF-8
| 1,673
| 3.484375
| 3
|
[
"MIT",
"Apache-2.0"
] |
permissive
|
//! O(1) scheduler introduced in Linux 2.6
//!
//! Two queues are maintained, one is active, another is inactive.
//! Take the first task from the active queue to run. When it is empty, swap active and inactive queues.
use super::*;
pub struct O1Scheduler {
inner: Mutex<O1SchedulerInner>,
}
struct O1SchedulerInner {
active_queue: usize,
queues: [Vec<Tid>; 2],
}
impl Scheduler for O1Scheduler {
fn push(&self, tid: usize) {
self.inner.lock().push(tid);
}
fn pop(&self, _cpu_id: usize) -> Option<usize> {
self.inner.lock().pop()
}
fn tick(&self, current_tid: usize) -> bool {
self.inner.lock().tick(current_tid)
}
fn set_priority(&self, _tid: usize, _priority: u8) {}
}
impl O1Scheduler {
pub fn new() -> Self {
let inner = O1SchedulerInner {
active_queue: 0,
queues: [Vec::new(), Vec::new()],
};
O1Scheduler {
inner: Mutex::new(inner),
}
}
}
impl O1SchedulerInner {
fn push(&mut self, tid: Tid) {
let inactive_queue = 1 - self.active_queue;
self.queues[inactive_queue].push(tid);
trace!("o1 push {}", tid - 1);
}
fn pop(&mut self) -> Option<Tid> {
let ret = match self.queues[self.active_queue].pop() {
Some(tid) => return Some(tid),
None => {
// active queue is empty, swap 'em
self.active_queue = 1 - self.active_queue;
self.queues[self.active_queue].pop()
}
};
trace!("o1 pop {:?}", ret);
ret
}
fn tick(&mut self, _current: Tid) -> bool {
true
}
}
| true
|
be1f3ec769de5dda41154a14246a8370e7bd9a90
|
Rust
|
arosspope/advent-of-code
|
/aoc_2020/src/day2.rs
|
UTF-8
| 1,771
| 3.4375
| 3
|
[
"Apache-2.0",
"MIT"
] |
permissive
|
//Day 2: Password Philosophy
//
#[derive(Debug, PartialEq)]
pub struct PasswordPolicy {
character: char,
max: usize,
min: usize,
}
#[derive(Debug, PartialEq)]
pub struct PasswordEntry {
policy: PasswordPolicy,
password: String
}
#[aoc_generator(day2)]
pub fn input_passwords(input: &str) -> Vec<PasswordEntry> {
input.lines().map(|l| PasswordEntry {
policy: PasswordPolicy {
character: l.split(" ").nth(1).unwrap().chars().nth(0).unwrap(),
min: l.split(" ").nth(0).unwrap().split('-').nth(0).unwrap().parse().unwrap(),
max: l.split(" ").nth(0).unwrap().split('-').nth(1).unwrap().parse().unwrap(),
},
password: l.split(" ").nth(2).unwrap().to_string(),
// String::from("abc"),
}).collect()
}
#[aoc(day2, part1)]
pub fn part1(input: &[PasswordEntry]) -> isize {
let mut valid = 0;
for entry in input.iter() {
let count = entry.password.matches(entry.policy.character).count();
if count >= entry.policy.min && count <= entry.policy.max {
valid += 1;
}
}
valid
}
#[aoc(day2, part2)]
pub fn part2(input: &[PasswordEntry]) -> isize {
let mut valid = 0;
for entry in input.iter() {
let pos0_matches = entry.password.chars().nth(entry.policy.min - 1).unwrap() == entry.policy.character;
let pos1_matches = entry.password.chars().nth(entry.policy.max - 1).unwrap() == entry.policy.character;
if pos0_matches ^ pos1_matches {
valid += 1;
}
}
valid
}
#[cfg(test)]
mod tests {
use super::{part1, part2, input_passwords};
#[test]
fn sample2() {
assert_eq!(part2(&input_passwords(&"1-3 a: abcde\n1-3 b: cdefg\n2-9 c: ccccccccc")), 1)
}
}
| true
|
2d8843b4a2f5d130c42e3d83cc0b3513518d4cff
|
Rust
|
frehberg/rtps-rs
|
/src/structure/locator_kind.rs
|
UTF-8
| 1,296
| 2.53125
| 3
|
[
"Apache-2.0"
] |
permissive
|
#[derive(Clone, Debug, Eq, PartialEq, Readable, Writable)]
pub struct LocatorKind_t {
value: i32,
}
impl LocatorKind_t {
pub const LOCATOR_KIND_INVALID: LocatorKind_t = LocatorKind_t { value: -1 };
pub const LOCATOR_KIND_RESERVED: LocatorKind_t = LocatorKind_t { value: 0 };
pub const LOCATOR_KIND_UDPv4: LocatorKind_t = LocatorKind_t { value: 1 };
pub const LOCATOR_KIND_UDPv6: LocatorKind_t = LocatorKind_t { value: 2 };
}
#[cfg(test)]
mod tests {
use super::*;
serialization_test!( type = LocatorKind_t,
{
locator_kind_invalid,
LocatorKind_t::LOCATOR_KIND_INVALID,
le = [0xFF, 0xFF, 0xFF, 0xFF],
be = [0xFF, 0xFF, 0xFF, 0xFF]
},
{
locator_kind_reserved,
LocatorKind_t::LOCATOR_KIND_RESERVED,
le = [0x00, 0x00, 0x00, 0x00],
be = [0x00, 0x00, 0x00, 0x00]
},
{
locator_kind_udpv4,
LocatorKind_t::LOCATOR_KIND_UDPv4,
le = [0x01, 0x00, 0x00, 0x00],
be = [0x00, 0x00, 0x00, 0x01]
},
{
locator_kind_udpv6,
LocatorKind_t::LOCATOR_KIND_UDPv6,
le = [0x02, 0x00, 0x00, 0x00],
be = [0x00, 0x00, 0x00, 0x02]
}
);
}
| true
|
0e12ee80148bc53d228c2e684528c76a5f20dc7b
|
Rust
|
tjni/offstage
|
/tests/repository.rs
|
UTF-8
| 2,535
| 3
| 3
|
[
"Apache-2.0"
] |
permissive
|
use anyhow::{anyhow, Result};
use git2::{Commit, ErrorCode, Repository, Signature};
use std::fs::File;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::slice;
pub const README: &str = "README";
pub const LICENSE: &str = "LICENSE";
pub struct TestRepository {
repository: Repository,
}
impl TestRepository {
pub fn new<P: AsRef<Path>>(working_dir: P) -> Result<Self> {
let repository = Repository::init(&working_dir)?;
Ok(Self { repository })
}
pub fn initial_commit(&mut self) -> Result<()> {
let readme = self.create_readme()?;
self.stage_path(&readme)?;
self.commit("Initial commit.")
}
pub fn create_readme(&self) -> Result<PathBuf> {
let path = self.get_working_dir()?.join(README);
writeln!(File::create(&path)?, "An example README.")?;
Ok(path)
}
pub fn create_license(&self) -> Result<PathBuf> {
let path = self.get_working_dir()?.join(LICENSE);
writeln!(File::create(&path)?, "Free as in freedom.")?;
Ok(path)
}
pub fn stage_path<P: AsRef<Path>>(&mut self, path: P) -> Result<()> {
let working_dir = self.get_working_dir()?;
let relative_path = path.as_ref().strip_prefix(working_dir)?;
let mut index = self.repository.index()?;
index.add_path(relative_path)?;
index.write()?;
Ok(())
}
pub fn commit(&mut self, message: &str) -> Result<()> {
let index = self.repository.index()?.write_tree()?;
let signature = Self::get_signature()?;
let head_commit = match self.repository.head() {
Ok(head) => Ok(Some(head.peel_to_commit()?)),
Err(error) if error.code() == ErrorCode::UnbornBranch => Ok(None),
Err(error) => Err(error),
}?;
let head_commit_ref = head_commit.as_ref();
let parents = match head_commit_ref {
Some(ref commit) => slice::from_ref(commit),
None => &[] as &[&Commit],
};
self.repository.commit(
Some("HEAD"),
&signature,
&signature,
message,
&self.repository.find_tree(index)?,
parents,
)?;
Ok(())
}
fn get_working_dir(&self) -> Result<&Path> {
self.repository
.workdir()
.ok_or_else(|| anyhow!("Could not find the working directory."))
}
fn get_signature<'a>() -> Result<Signature<'a>> {
Ok(Signature::now("me", "me@example.com")?)
}
}
| true
|
bfd8e04a874ea866f13cc650c980f72c1b70bda9
|
Rust
|
jjgz/server
|
/src/net.rs
|
UTF-8
| 13,740
| 3.03125
| 3
|
[] |
no_license
|
use std::io::{Read, Write};
use std::sync::mpsc::{channel, TryRecvError, Sender};
use std::time;
use std::sync::{Mutex, Arc};
use std::thread;
use std::net::TcpStream;
use serde_json;
use rnet::Netmessage;
struct Crc8 {
crc: u16,
}
impl Crc8 {
fn new() -> Crc8 {
Crc8 { crc: 0 }
}
fn add_byte(&mut self, byte: u8) {
self.crc ^= (byte as u16) << 8;
for _ in 0..8 {
if self.crc & 0x8000 != 0 {
self.crc ^= 0x1070 << 3;
}
self.crc <<= 1;
}
}
fn finish(self) -> u8 {
(self.crc >> 8) as u8
}
}
struct Message {
buffer: Vec<u8>,
}
#[derive(Debug, Clone)]
enum MessageError {
TooBig,
TooSmall,
}
impl Message {
fn new() -> Message {
Message { buffer: Vec::new() }
}
fn from_netmessage(nm: &Netmessage) -> Vec<u8> {
let mut message = Message::new();
message.add_message(nm);
message.finish()
.expect(&format!("Error: Failed to create message from netmessage: {:?}", nm))
}
fn append<I>(&mut self, i: I)
where I: IntoIterator<Item = u8>
{
self.buffer.extend(i);
}
fn add_message(&mut self, message: &Netmessage) {
let s = serde_json::to_string(message)
.unwrap_or_else(|e| panic!("Failed to serialize JSON: {}", e));
self.append(s.bytes());
}
fn finish(mut self) -> Result<Vec<u8>, MessageError> {
if self.buffer.len() > 256 {
Err(MessageError::TooBig)
} else if self.buffer.len() == 0 {
Err(MessageError::TooSmall)
} else {
let byte_len = (self.buffer.len() - 1) as u8;
// Create CRC.
let mut crc = Crc8::new();
// Add the length byte to the CRC.
crc.add_byte(byte_len);
// Add the payload to the CRC.
for b in &self.buffer {
crc.add_byte(*b);
}
// Add the magic sequence, CRC, and length to the message payload.
let mut v = vec![128, 37, 35, 46, crc.finish(), byte_len];
// Add the entire payload.
v.append(&mut self.buffer);
Ok(v)
}
}
}
pub type PSender = Arc<Mutex<Option<Sender<Netmessage>>>>;
fn route_message(ps: &PSender, m: Netmessage) {
match *ps.lock().unwrap() {
Some(ref c) => {
match c.send(m.clone()) {
Ok(_) => {}
Err(e) => {
println!("Error: Failed to send message on disconnected channel: {}",
e);
println!("Message: {:?}", m);
}
}
}
None => {
println!("Warning: Attempted to send a request before the module connected.");
println!("Message: {:?}", m);
}
}
}
pub fn handle_client(mut stream: TcpStream,
geordon_sender: PSender,
josh_sender: PSender,
joe_sender: PSender,
zach_sender: PSender,
debug_geordon_sender: PSender,
debug_josh_sender: PSender,
debug_joe_sender: PSender,
debug_zach_sender: PSender) {
println!("New connection.");
// The Wifly always sends this 7-byte sequence on connection.
let mut initialbuff = [0u8; 7];
stream.read_exact(&mut initialbuff).unwrap();
if initialbuff != [42, 72, 69, 76, 76, 79, 42] {
panic!("Didn't get magic values!");
} else {
println!("Got magic values, continuing.");
}
let json_iter = match stream.try_clone() {
Ok(s) => serde_json::StreamDeserializer::<Netmessage, _>::new(s.bytes()),
Err(e) => panic!("Unable to clone TCP stream: {}", e),
};
// Create a channel for sending back the Netmessages.
let (sender, receiver) = channel();
// Perform the JSON reading in a separate thread.
thread::spawn(move || {
for nmessage in json_iter {
sender.send(nmessage)
.unwrap_or_else(|e| panic!("Failed to send nmessage: {}", e));
}
});
// Create the Heartbeat message.
let heartbeat = Message::from_netmessage(&Netmessage::Heartbeat);
// Create the RequestNetstats message.
let request_netstats = Message::from_netmessage(&Netmessage::ReqNetstats);
// Create the RequestName message.
let request_name = Message::from_netmessage(&Netmessage::ReqName);
println!("##################");
// Create the time.
let mut prev_heartbeat = time::Instant::now();
let mut prev_request_netstats = time::Instant::now();
let mut prev_req_name = time::Instant::now();
let mut self_receiver = None;
let mut self_name = None;
loop {
// Perform a non-blocking read from the stream.
match receiver.try_recv() {
Ok(Ok(m)) => {
match m {
Netmessage::NameGeordon => {
let chan = channel::<Netmessage>();
self_receiver = Some(chan.1);
*geordon_sender.lock().unwrap() = Some(chan.0);
self_name = Some(Netmessage::NameGeordon);
println!("Geordon robot identified.");
}
Netmessage::NameJoe => {
let chan = channel();
self_receiver = Some(chan.1);
*joe_sender.lock().unwrap() = Some(chan.0);
self_name = Some(Netmessage::NameJoe);
println!("Joe robot identified.");
}
Netmessage::NameJosh => {
let chan = channel();
self_receiver = Some(chan.1);
*josh_sender.lock().unwrap() = Some(chan.0);
self_name = Some(Netmessage::NameJosh);
println!("It's Josh bitch.");
}
Netmessage::NameZach => {
let chan = channel();
self_receiver = Some(chan.1);
*zach_sender.lock().unwrap() = Some(chan.0);
self_name = Some(Netmessage::NameZach);
println!("Zach robot identified.");
}
Netmessage::NameDebugGeordon => {
let chan = channel::<Netmessage>();
self_receiver = Some(chan.1);
*debug_geordon_sender.lock().unwrap() = Some(chan.0);
self_name = Some(Netmessage::NameDebugGeordon);
println!("Debug Geordon robot identified.");
}
Netmessage::NameDebugJoe => {
let chan = channel();
self_receiver = Some(chan.1);
*debug_joe_sender.lock().unwrap() = Some(chan.0);
self_name = Some(Netmessage::NameDebugJoe);
println!("Debug Joe robot identified.");
}
Netmessage::NameDebugJosh => {
let chan = channel();
self_receiver = Some(chan.1);
*debug_josh_sender.lock().unwrap() = Some(chan.0);
self_name = Some(Netmessage::NameDebugJosh);
println!("It's Debug Josh bitch.");
}
Netmessage::NameDebugZach => {
let chan = channel();
self_receiver = Some(chan.1);
*debug_zach_sender.lock().unwrap() = Some(chan.0);
self_name = Some(Netmessage::NameDebugZach);
println!("Debug Zach robot identified.");
}
m @ Netmessage::Initialize{..} => {
route_message(&josh_sender, m.clone());
route_message(&joe_sender, m.clone());
route_message(&geordon_sender, m.clone());
route_message(&zach_sender, m);
}
m @ Netmessage::PDebugJosh(..) |
m @ Netmessage::ADebugJosh(..) |
m @ Netmessage::RDebugJosh(..) |
m @ Netmessage::GReqGrabbed |
m @ Netmessage::DReqDropped |
m @ Netmessage::HDebugJosh(..) => {
route_message(&debug_josh_sender, m);
}
m @ Netmessage::ReqMovement |
m @ Netmessage::DebugJoeUltra(..) |
m @ Netmessage::DebugJoeTread(..) |
m @ Netmessage::GDStartAlign |
m @ Netmessage::Assumed(..) |
m @ Netmessage::Proximity{..} => {
route_message(&joe_sender, m);
}
m @ Netmessage::Movement(..) => {
route_message(&debug_joe_sender, m.clone());
route_message(&debug_geordon_sender, m.clone());
route_message(&geordon_sender, m);
}
m @ Netmessage::DebugJoeDistance(..) |
m @ Netmessage::DebugJoeOC(..) => {
route_message(&debug_joe_sender, m);
}
m @ Netmessage::TestMove(..) |
m @ Netmessage::TestRotate(..) |
m @ Netmessage::ReqTestReset |
m @ Netmessage::Stopped(..) |
m @ Netmessage::ReqInPosition |
m @ Netmessage::Targets(..) |
m @ Netmessage::HalfRow(..) |
m @ Netmessage::EdgeDetect(..) |
m @ Netmessage::EdgeDropped(..) |
m @ Netmessage::Distance(..) |
m @ Netmessage::Grabbed(..) |
m @ Netmessage::TestRow(..) |
m @ Netmessage::Dropped(..) |
m @ Netmessage::JCHalfRow(..)=> {
route_message(&josh_sender, m);
}
m @ Netmessage::GDReqHalfRow(..) |
m @ Netmessage::ReqHalfRow(..) |
m @ Netmessage::ReqTargets |
m @ Netmessage::GDReqPing |
m @ Netmessage::ReqStopped |
m @ Netmessage::GDBuild |
m @ Netmessage::ReqAssumed |
m @ Netmessage::GDFinish |
m @ Netmessage::ReqProximity => {
route_message(&geordon_sender, m);
}
m @ Netmessage::GDAligned => {
route_message(&geordon_sender, m.clone());
route_message(&joe_sender, m);
}
m @ Netmessage::InPosition(..) |
m @ Netmessage::ReqEdgeDetectLeft |
m @ Netmessage::ReqEdgeDetectRight |
m @ Netmessage::ReqEdgeDropped |
m @ Netmessage::ReqDistance |
m @ Netmessage::ReqGrabbed |
m @ Netmessage::ReqDropped => {
route_message(&zach_sender, m);
}
m @ Netmessage::DebugGeordon(..) |
m @ Netmessage::GDPing |
m @ Netmessage::GDHalfRow(..) => {
route_message(&debug_geordon_sender, m);
}
m => {
println!("{}: {:?}",
self_name.as_ref()
.map(|o| o.bot_name())
.unwrap_or(String::from("Unnamed")),
m);
}
}
}
Ok(Err(e)) => panic!("Closing: Got invalid JSON: {}", e),
Err(TryRecvError::Empty) => {}
Err(TryRecvError::Disconnected) => panic!("Receiver disconnected."),
}
// Perform a non-blocking read from the stream.
if let Some(ref sr) = self_receiver {
match sr.try_recv() {
Ok(m) => {
stream.write_all(&Message::from_netmessage(&m)[..])
.unwrap_or_else(|e| {
panic!("Failed to route message from other bot: {}", e)
});
}
Err(TryRecvError::Empty) => {}
Err(TryRecvError::Disconnected) => panic!("Self receiver disconnected."),
}
}
let currtime = time::Instant::now();
if currtime - prev_heartbeat > time::Duration::from_secs(1) {
prev_heartbeat = currtime;
// Send Heartbeat.
stream.write_all(&heartbeat[..])
.unwrap_or_else(|e| panic!("Failed to send Heartbeat: {}", e));
}
if currtime - prev_request_netstats > time::Duration::from_secs(5) {
prev_request_netstats = currtime;
// Send RequestNetstats.
stream.write_all(&request_netstats[..])
.unwrap_or_else(|e| panic!("Failed to send RequestNetstats: {}", e));
}
if self_receiver.is_none() && currtime - prev_req_name > time::Duration::from_millis(100) {
prev_req_name = currtime;
// Send RequestNetstats.
stream.write_all(&request_name[..])
.unwrap_or_else(|e| panic!("Failed to send ReqName: {}", e));
}
stream.flush().unwrap();
}
}
| true
|
b898a0f053240a76a48f9fc04b601b28e3b8f7c0
|
Rust
|
CoiroTomas/voronoi
|
/src/main.rs
|
UTF-8
| 3,844
| 2.578125
| 3
|
[
"MIT"
] |
permissive
|
#![windows_subsystem = "windows"]
extern crate piston;
extern crate piston_window;
extern crate image;
use piston_window::*;
use std::path::Path;
static COLOURS : [[u8;4]; 16] = [[255, 255, 255, 255], [0, 255, 255, 255], [255, 0, 255, 255], [255, 255, 0, 255],
[192, 192, 192, 255], [255, 0, 0, 255], [0, 255, 0, 255], [0, 0, 255, 255],
[128, 128, 128, 255], [0, 128, 128, 255], [128, 0, 128, 255], [128, 128, 0, 255],
[0, 0, 0, 255], [128, 0, 0, 255], [0, 128, 0, 255], [0, 0, 128, 255]];
static WIDTH : u32 = 500;
static HEIGHT : u32 = 500;
fn main() {
let mut window: PistonWindow = WindowSettings::new("Voronoi", [WIDTH, HEIGHT])
.exit_on_esc(true)
.resizable(false)
.build()
.unwrap();
let mut voronoi = Voronoi::new();
voronoi.open_window(&mut window);
}
struct Voronoi {
points : Vec<(u32, u32)>,
distance_fn : u8,
dotted : bool,
}
impl Voronoi {
pub fn new() -> Self {
Self { points: Vec::new(), distance_fn: 0, dotted: true }
}
pub fn open_window(&mut self, window: &mut PistonWindow) -> () {
let mut cursor = [0.0, 0.0];
while let Some(e) = window.next() {
if let Some(_) = e.render_args() {
self.draw_screen(window, &e);
}
if let Some(Button::Mouse(_button)) = e.press_args() {
self.add_point((cursor[0] as u32, cursor[1] as u32));
}
if let Some(Button::Keyboard(key)) = e.press_args() {
match key {
Key::R => self.reset(),
Key::S => self.save(),
Key::D => self.change_dotted(),
Key::Left => self.distance_fn = if self.distance_fn==0 { 2 } else { self.distance_fn - 1 },
Key::Right => self.distance_fn = (self.distance_fn + 1) % 3,
_ => (),
}
}
e.mouse_cursor(|pos| {
cursor = pos;
});
}
}
pub fn change_dotted(&mut self) {
self.dotted = !self.dotted;
}
pub fn add_point(&mut self, point : (u32, u32)) {
self.points.push(point);
}
pub fn reset(&mut self) {
self.points = Vec::new();
self.distance_fn = 0;
}
pub fn save(&mut self) {
let mut path_string = "Voronoi-1.png".to_string();
let mut path = Path::new(&path_string);
let mut i = 2;
while path.exists() {
path_string = format!("Voronoi-{}.png", i);
path = Path::new(&path_string);
i += 1;
}
self.get_screen().save(path);
}
pub fn get_screen(&self) -> image::ImageBuffer<image::Rgba<u8>, std::vec::Vec<u8>> {
let mut buffer_image = image::ImageBuffer::new(WIDTH, HEIGHT);
for i in 0..(WIDTH*HEIGHT) {
let y: u32 = (i / WIDTH) as u32;
let x: u32 = (i % WIDTH) as u32;
let closest = self.closest_point((x, y));
buffer_image.put_pixel(x, y, image::Rgba(COLOURS[closest]));
}
return buffer_image;
}
pub fn closest_point(&self, (x, y): (u32, u32)) -> usize {
let mut closest = 0;
let mut distance = f64::MAX;
for ((w, z), i) in self.points.iter().zip(0..(self.points.len())) {
let new_distance = self.distance(x, y, *w, *z);
if new_distance < distance {
closest = i;
distance = new_distance;
}
}
if self.dotted {
if distance < 3.0 { 12 } else {closest % COLOURS.len()}
} else {
closest % COLOURS.len()
}
}
pub fn distance(&self, x: u32, y: u32, w: u32, z: u32) -> f64 {
match self.distance_fn {
0 => (((x as i32 - w as i32).pow(2) + (y as i32 - z as i32).pow(2)) as f64).sqrt(),
1 => ((x as i32 - w as i32).abs() + (y as i32 - z as i32).abs()) as f64,
2 => ((x as i32 - w as i32).abs().max((y as i32 - z as i32).abs())) as f64,
_ => 1.0,
}
}
pub fn draw_screen(&self, window: &mut PistonWindow, event: &Event) {
let buffer_image = self.get_screen();
let texture = Texture::from_image(
&mut window.create_texture_context(),
&buffer_image,
&TextureSettings::new(),
).unwrap();
window.draw_2d(event, |_c, g, _| {
image(&texture, _c.transform, g);
});
}
}
| true
|
aff514c685d46defd045eda63d0fb352c62c93e5
|
Rust
|
bouzuya/rust-atcoder
|
/cargo-atcoder/contests/past202010-open/src/bin/d.rs
|
UTF-8
| 699
| 3.015625
| 3
|
[] |
no_license
|
use proconio::input;
use proconio::marker::Chars;
use std::cmp::max;
fn main() {
input! {
n: usize,
s: Chars,
};
let mut counts = vec![0];
for i in 0..n {
match s[i] {
'.' => {
let l = counts.len();
counts[l - 1] += 1;
}
'#' => {
counts.push(0);
}
_ => unreachable!(),
}
}
let l = counts.len();
let count_l = counts[0];
let count_m = *counts[1..l - 1].iter().max().unwrap_or(&0);
let count_r = counts[l - 1];
let l = count_l;
let r = count_r + max(0, count_m - (count_l + count_r));
println!("{} {}", l, r);
}
| true
|
d8c581f00820fad6ad4b850d72e6990e9b8e4767
|
Rust
|
aticu/pre
|
/proc-macro/src/extern_crate.rs
|
UTF-8
| 11,093
| 2.859375
| 3
|
[
"MIT",
"Apache-2.0"
] |
permissive
|
//! Provides handling of `extern_crate` attributes.
//!
//! # What the generated code looks like
//!
//! ```rust,ignore
//! #[pre::extern_crate(std)]
//! mod pre_std {
//! mod ptr {
//! #[pre(valid_ptr(src, r))]
//! unsafe fn read<T>(src: *const T) -> T;
//!
//! impl<T> NonNull<T> {
//! #[pre(!ptr.is_null())]
//! const unsafe fn new_unchecked(ptr: *mut T) -> NonNull<T>;
//! }
//! }
//! }
//! ```
//!
//! turns into
//!
//! ```rust,ignore
//! #[doc = "..."]
//! mod pre_std {
//! #[allow(unused_imports)]
//! use pre::pre;
//! #[allow(unused_imports)]
//! #[doc(no_inline)]
//! pub(crate) use std::*;
//!
//! #[doc = "..."]
//! pub(crate) mod ptr {
//! #[allow(unused_imports)]
//! use pre::pre;
//! #[allow(unused_imports)]
//! #[doc(no_inline)]
//! pub(crate) use std::ptr::*;
//!
//! #[doc = "..."]
//! #[pre(!ptr.is_null())]
//! #[pre(no_doc)]
//! #[pre(no_debug_assert)]
//! #[inline(always)]
//! #[allow(non_snake_case)]
//! pub(crate) fn NonNull__impl__new_unchecked__() {}
//!
//! #[pre(valid_ptr(src, r))]
//! #[inline(always)]
//! pub(crate) unsafe fn read<T>(src: *const T) -> T {
//! std::ptr::read(src)
//! }
//! }
//! }
//! ```
use proc_macro2::{Span, TokenStream};
use quote::{quote, quote_spanned, TokenStreamExt};
use std::fmt;
use syn::{
braced,
parse::{Parse, ParseStream},
spanned::Spanned,
token::Brace,
Attribute, FnArg, ForeignItemFn, Ident, ItemUse, Path, PathArguments, PathSegment, Token,
Visibility,
};
use crate::{
documentation::{generate_extern_crate_fn_docs, generate_module_docs},
helpers::{visit_matching_attrs_parsed_mut, AttributeAction, CRATE_NAME},
pre_attr::PreAttr,
};
pub(crate) use impl_block::{impl_block_stub_name, ImplBlock};
mod impl_block;
/// The parsed version of the `extern_crate` attribute content.
pub(crate) struct ExternCrateAttr {
/// The path of the crate/module to which function calls will be forwarded.
path: Path,
}
impl fmt::Display for ExternCrateAttr {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "#[extern_crate(")?;
if self.path.leading_colon.is_some() {
write!(f, "::")?;
}
for segment in &self.path.segments {
write!(f, "{}", segment.ident)?;
}
write!(f, ")]")
}
}
impl Parse for ExternCrateAttr {
fn parse(input: ParseStream) -> syn::Result<Self> {
Ok(ExternCrateAttr {
path: input.call(Path::parse_mod_style)?,
})
}
}
/// A parsed `extern_crate` annotated module.
pub(crate) struct Module {
/// The attributes on the module.
attrs: Vec<Attribute>,
/// The visibility on the module.
visibility: Visibility,
/// The `mod` token.
mod_token: Token![mod],
/// The name of the module.
ident: Ident,
/// The braces surrounding the content.
braces: Brace,
/// The impl blocks contained in the module.
impl_blocks: Vec<ImplBlock>,
/// The imports contained in the module.
imports: Vec<ItemUse>,
/// The functions contained in the module.
functions: Vec<ForeignItemFn>,
/// The submodules contained in the module.
modules: Vec<Module>,
}
impl fmt::Display for Module {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.original_token_stream())
}
}
impl Spanned for Module {
fn span(&self) -> Span {
self.visibility
.span()
.join(self.braces.span)
.unwrap_or(self.braces.span)
}
}
impl Parse for Module {
fn parse(input: ParseStream) -> syn::Result<Self> {
let attrs = input.call(Attribute::parse_outer)?;
let visibility = input.parse()?;
let mod_token = input.parse()?;
let ident = input.parse()?;
let content;
let braces = braced!(content in input);
let mut impl_blocks = Vec::new();
let mut imports = Vec::new();
let mut functions = Vec::new();
let mut modules = Vec::new();
while !content.is_empty() {
if content.peek(Token![impl]) {
impl_blocks.push(content.parse()?);
} else if <ItemUse as Parse>::parse(&content.fork()).is_ok() {
imports.push(content.parse()?);
} else if <ForeignItemFn as Parse>::parse(&content.fork()).is_ok() {
functions.push(content.parse()?);
} else {
modules.push(content.parse().map_err(|err| {
syn::Error::new(
err.span(),
"expected a module, a function signature, an impl block or a use statement",
)
})?);
}
}
Ok(Module {
attrs,
visibility,
mod_token,
ident,
braces,
impl_blocks,
imports,
functions,
modules,
})
}
}
impl Module {
/// Renders this `extern_crate` annotated module to its final result.
pub(crate) fn render(&self, attr: ExternCrateAttr) -> TokenStream {
let mut tokens = TokenStream::new();
self.render_inner(attr.path, &mut tokens, None, &self.ident);
tokens
}
/// A helper function to generate the final token stream.
///
/// This allows passing the top level visibility and the updated path into recursive calls.
fn render_inner(
&self,
mut path: Path,
tokens: &mut TokenStream,
visibility: Option<&TokenStream>,
top_level_module: &Ident,
) {
if visibility.is_some() {
// Update the path only in recursive calls.
path.segments.push(PathSegment {
ident: self.ident.clone(),
arguments: PathArguments::None,
});
}
let mut attrs = self.attrs.clone();
let mut render_docs = true;
visit_matching_attrs_parsed_mut(&mut attrs, "pre", |attr| match attr.content() {
PreAttr::NoDoc(_) => {
render_docs = false;
AttributeAction::Remove
}
_ => AttributeAction::Keep,
});
if render_docs {
let docs = generate_module_docs(self, &path);
tokens.append_all(quote! { #docs });
}
tokens.append_all(attrs);
let visibility = if let Some(visibility) = visibility {
// We're in a recursive call.
// Use the visibility passed to us.
tokens.append_all(quote! { #visibility });
visibility.clone()
} else {
// We're in the outermost call.
// Use the original visibility and decide which visibility to use in recursive calls.
let local_vis = &self.visibility;
tokens.append_all(quote! { #local_vis });
if let Visibility::Public(pub_keyword) = local_vis {
quote! { #pub_keyword }
} else {
let span = match local_vis {
Visibility::Inherited => self.mod_token.span(),
_ => local_vis.span(),
};
quote_spanned! { span=> pub(crate) }
}
};
let mod_token = self.mod_token;
tokens.append_all(quote! { #mod_token });
tokens.append(self.ident.clone());
let mut brace_content = TokenStream::new();
let crate_name = Ident::new(&CRATE_NAME, Span::call_site());
brace_content.append_all(quote! {
#[allow(unused_imports)]
#[doc(no_inline)]
#visibility use #path::*;
#[allow(unused_imports)]
use #crate_name::pre;
});
for impl_block in &self.impl_blocks {
impl_block.render(&mut brace_content, &path, &visibility, top_level_module);
}
for import in &self.imports {
brace_content.append_all(quote! { #import });
}
for function in &self.functions {
render_function(function, &mut brace_content, &path, &visibility);
}
for module in &self.modules {
module.render_inner(
path.clone(),
&mut brace_content,
Some(&visibility),
top_level_module,
);
}
tokens.append_all(quote_spanned! { self.braces.span=> { #brace_content } });
}
/// Generates a token stream that is semantically equivalent to the original token stream.
///
/// This should only be used for debug purposes.
fn original_token_stream(&self) -> TokenStream {
let mut stream = TokenStream::new();
stream.append_all(&self.attrs);
let vis = &self.visibility;
stream.append_all(quote! { #vis });
stream.append_all(quote! { mod });
stream.append(self.ident.clone());
let mut content = TokenStream::new();
content.append_all(
self.impl_blocks
.iter()
.map(|impl_block| impl_block.original_token_stream()),
);
content.append_all(&self.imports);
content.append_all(&self.functions);
content.append_all(self.modules.iter().map(|m| m.original_token_stream()));
stream.append_all(quote! { { #content } });
stream
}
}
/// Generates the code for a function inside a `extern_crate` module.
fn render_function(
function: &ForeignItemFn,
tokens: &mut TokenStream,
path: &Path,
visibility: &TokenStream,
) {
tokens.append_all(&function.attrs);
let doc_header = generate_extern_crate_fn_docs(path, &function.sig, function.span());
tokens.append_all(quote! { #doc_header });
tokens.append_all(quote_spanned! { function.span()=> #[inline(always)] });
tokens.append_all(visibility.clone().into_iter().map(|mut token| {
token.set_span(function.span());
token
}));
let signature = &function.sig;
tokens.append_all(quote! { #signature });
let mut path = path.clone();
path.segments.push(PathSegment {
ident: function.sig.ident.clone(),
arguments: PathArguments::None,
});
// Update the spans of the `::` tokens to lie in the function
for punct in path
.segments
.pairs_mut()
.map(|p| p.into_tuple().1)
.flatten()
{
punct.spans = [function.span(); 2];
}
let mut args_list = TokenStream::new();
args_list.append_separated(
function.sig.inputs.iter().map(|arg| match arg {
FnArg::Receiver(_) => unreachable!("receiver is not valid in a function argument list"),
FnArg::Typed(pat) => &pat.pat,
}),
quote_spanned! { function.span()=> , },
);
tokens.append_all(quote_spanned! { function.span()=> { #path(#args_list) } });
}
| true
|
c3e7161eb645b6b2524066710a7d016f7b2a007e
|
Rust
|
chroussel/hdfs-cli
|
/walk/src/err.rs
|
UTF-8
| 575
| 2.625
| 3
|
[] |
no_license
|
#[derive(Debug)]
pub enum Error {
IoError(std::io::Error),
PathConversionError(std::ffi::OsString),
PatternError(glob::PatternError),
NoPathDefined,
PathFormatError,
}
impl From<std::io::Error> for Error {
fn from(err: std::io::Error) -> Self {
Error::IoError(err)
}
}
impl From<std::ffi::OsString> for Error {
fn from(err: std::ffi::OsString) -> Self {
Error::PathConversionError(err)
}
}
impl From<glob::PatternError> for Error {
fn from(err: glob::PatternError) -> Self {
Error::PatternError(err)
}
}
| true
|
d53362f508c65b559b3470a0f8eab72975f99112
|
Rust
|
AntonGepting/tmux-interface-rs
|
/src/formats/formats_output.rs
|
UTF-8
| 46,302
| 2.59375
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
use super::VariableOutput;
#[cfg(feature = "tmux_2_5")]
use crate::SessionStack;
#[cfg(feature = "tmux_1_6")]
use crate::{Layout, PaneTabs, WindowFlags};
#[derive(Debug)]
pub struct FormatsOutput<'a> {
pub separator: char,
pub variables: Vec<VariableOutput<'a>>,
}
impl<'a> Default for FormatsOutput<'a> {
fn default() -> Self {
FormatsOutput {
separator: '\'',
variables: Vec::new(),
}
}
}
impl<'a> FormatsOutput<'a> {
pub fn new() -> Self {
Default::default()
}
/// set separator character
pub fn separator(&mut self, c: char) -> &mut Self {
self.separator = c;
self
}
/// append with variable
pub fn push(&mut self, variable: VariableOutput<'a>) {
self.variables.push(variable)
}
// TODO: check vec same size, return type?
// XXX: mb from_string for default format too?
pub fn from_string_ext(s: &str, format: &'a mut FormatsOutput<'a>) {
let v: Vec<&str> = s.split(format.separator).collect();
for (i, variable) in v.iter().enumerate() {
VariableOutput::from_string_ext(variable, &mut format.variables[i]);
}
}
// pub fn custom_string(String) pub fn custom_usize(String)
// tmux variables
/// `alternate_on` - if pane is in alternate screen
#[cfg(feature = "tmux_1_8")]
pub fn alternate_on(&mut self, v: &'a mut Option<usize>) -> &mut Self {
self.push(VariableOutput::AlternateOn(v));
self
}
/// `alternate_saved_x` - Saved cursor X in alternate screen
#[cfg(feature = "tmux_1_8")]
pub fn alternate_saved_x(&mut self, v: &'a mut Option<usize>) -> &mut Self {
self.push(VariableOutput::AlternateSavedX(v));
self
}
/// `alternate_saved_y` - Saved cursor Y in alternate screen
#[cfg(feature = "tmux_1_8")]
pub fn alternate_saved_y(&mut self, v: &'a mut Option<usize>) -> &mut Self {
self.push(VariableOutput::AlternateSavedY(v));
self
}
// Buffer
/// `buffer_created` - Time buffer created
#[cfg(feature = "tmux_2_6")]
pub fn buffer_created(&mut self, v: &'a mut Option<u128>) -> &mut Self {
self.push(VariableOutput::BufferCreated(v));
self
}
/// `buffer_name` - Name of buffer
#[cfg(feature = "tmux_2_3")]
pub fn buffer_name(&mut self, v: &'a mut Option<String>) -> &mut Self {
self.push(VariableOutput::BufferName(v));
self
}
/// `buffer_sample` - First 50 characters from the specified buffer
#[cfg(feature = "tmux_1_7")]
pub fn buffer_sample(&mut self, v: &'a mut Option<String>) -> &mut Self {
self.push(VariableOutput::BufferSample(v));
self
}
/// `buffer_size` - Size of the specified buffer in bytes
#[cfg(feature = "tmux_1_7")]
pub fn buffer_size(&mut self, v: &'a mut Option<usize>) -> &mut Self {
self.push(VariableOutput::BufferSize(v));
self
}
// Client
/// `client_activity` - Integer time client last had activity
#[cfg(feature = "tmux_1_6")]
pub fn client_activity(&mut self, v: &'a mut Option<u128>) -> &mut Self {
self.push(VariableOutput::ClientActivity(v));
self
}
/// `client_cell_height` - Height of each client cell in pixels
#[cfg(feature = "tmux_3_1")]
pub fn client_cell_height(&mut self, v: &'a mut Option<usize>) -> &mut Self {
self.push(VariableOutput::ClientCellHeight(v));
self
}
/// `client_cell_width` - Width of each client cell in pixels
#[cfg(feature = "tmux_3_1")]
pub fn client_cell_width(&mut self, v: &'a mut Option<usize>) -> &mut Self {
self.push(VariableOutput::ClientCellWidth(v));
self
}
/// `client_activity_string` - Option<String> time client last had activity
#[cfg(all(feature = "tmux_1_6", not(feature = "tmux_2_2")))]
pub fn client_activity_string(&mut self, v: &'a mut Option<String>) -> &mut Self {
self.push(VariableOutput::ClientActivityString(v));
self
}
/// `client_created` - Integer time client created
#[cfg(feature = "tmux_1_6")]
pub fn client_created(&mut self, v: &'a mut Option<u128>) -> &mut Self {
self.push(VariableOutput::ClientCreated(v));
self
}
/// `client_created_string` - Option<String> time client created
#[cfg(all(feature = "tmux_1_6", not(feature = "tmux_2_2")))]
pub fn client_created_string(&mut self, v: &'a mut Option<String>) -> &mut Self {
self.push(VariableOutput::ClientCreatedString(v));
self
}
/// `client_control_mode` - 1 if client is in control mode
#[cfg(feature = "tmux_2_1")]
pub fn client_control_mode(&mut self, v: &'a mut Option<bool>) -> &mut Self {
self.push(VariableOutput::ClientControlMode(v));
self
}
/// `client_discarded` - Bytes discarded when client behind
#[cfg(feature = "tmux_2_1")]
pub fn client_discarded(&mut self, v: &'a mut Option<String>) -> &mut Self {
self.push(VariableOutput::ClientDiscarded(v));
self
}
/// `client_cwd` - Working directory of client
#[cfg(all(feature = "tmux_1_6", not(feature = "tmux_1_9")))]
pub fn client_cwd(&mut self, v: &'a mut Option<String>) -> &mut Self {
self.push(VariableOutput::ClientCwd(v));
self
}
/// `client_height` - Height of client
#[cfg(feature = "tmux_1_6")]
pub fn client_height(&mut self, v: &'a mut Option<usize>) -> &mut Self {
self.push(VariableOutput::ClientHeight(v));
self
}
/// `client_key_table` - Current key table
#[cfg(feature = "tmux_2_2")]
pub fn client_key_table(&mut self, v: &'a mut Option<String>) -> &mut Self {
self.push(VariableOutput::ClientKeyTable(v));
self
}
/// `client_last_session` - Name of the client's last session
#[cfg(feature = "tmux_1_8")]
pub fn client_last_session(&mut self, v: &'a mut Option<String>) -> &mut Self {
self.push(VariableOutput::ClientLastSession(v));
self
}
/// `client_name` - Name of client
#[cfg(feature = "tmux_2_4")]
pub fn client_name(&mut self, v: &'a mut Option<String>) -> &mut Self {
self.push(VariableOutput::ClientName(v));
self
}
/// `client_pid` - PID of client process
#[cfg(feature = "tmux_2_1")]
pub fn client_pid(&mut self, v: &'a mut Option<bool>) -> &mut Self {
self.push(VariableOutput::ClientPid(v));
self
}
/// `client_prefix` - 1 if prefix key has been pressed
#[cfg(feature = "tmux_1_8")]
pub fn client_prefix(&mut self, v: &'a mut Option<bool>) -> &mut Self {
self.push(VariableOutput::ClientPrefix(v));
self
}
/// `client_readonly` - 1 if client is readonly
#[cfg(feature = "tmux_1_6")]
pub fn client_readonly(&mut self, v: &'a mut Option<bool>) -> &mut Self {
self.push(VariableOutput::ClientReadonly(v));
self
}
/// `client_session` - Name of the client's session
#[cfg(feature = "tmux_1_8")]
pub fn client_session(&mut self, v: &'a mut Option<String>) -> &mut Self {
self.push(VariableOutput::ClientSession(v));
self
}
/// `client_termname` - Terminal name of client
#[cfg(feature = "tmux_1_6")]
pub fn client_termname(&mut self, v: &'a mut Option<String>) -> &mut Self {
self.push(VariableOutput::ClientTermname(v));
self
}
/// `client_termtype` - Terminal type of client
#[cfg(all(feature = "tmux_2_4", not(feature = "tmux_3_1")))]
pub fn client_termtype(&mut self, v: &'a mut Option<String>) -> &mut Self {
self.push(VariableOutput::ClientTermtype(v));
self
}
/// `client_tty` - Pseudo terminal of client
#[cfg(feature = "tmux_1_6")]
pub fn client_tty(&mut self, v: &'a mut Option<String>) -> &mut Self {
self.push(VariableOutput::ClientTty(v));
self
}
/// `client_utf8` - 1 if client supports UTF-8
#[cfg(feature = "tmux_1_6")]
pub fn client_utf8(&mut self, v: &'a mut Option<bool>) -> &mut Self {
self.push(VariableOutput::ClientUtf8(v));
self
}
/// `client_width` - Width of client
#[cfg(feature = "tmux_1_6")]
pub fn client_width(&mut self, v: &'a mut Option<usize>) -> &mut Self {
self.push(VariableOutput::ClientWidth(v));
self
}
/// `client_written` - Bytes written to client
#[cfg(feature = "tmux_2_4")]
pub fn client_written(&mut self, v: &'a mut Option<usize>) -> &mut Self {
self.push(VariableOutput::ClientWritten(v));
self
}
// Command
/// `command_hooked` - Name of command hooked, if any
#[cfg(feature = "tmux_2_3")]
pub fn command_hooked(&mut self, v: &'a mut Option<String>) -> &mut Self {
self.push(VariableOutput::CommandHooked(v));
self
}
/// `command_name` - Name of command in use, if any
#[cfg(all(feature = "tmux_2_2", not(feature = "tmux_2_4")))]
pub fn command_name(&mut self, v: &'a mut Option<String>) -> &mut Self {
self.push(VariableOutput::CommandName(v));
self
}
/// `command` - Name of command in use, if any
#[cfg(feature = "tmux_2_4")]
pub fn command(&mut self, v: &'a mut Option<String>) -> &mut Self {
self.push(VariableOutput::Command(v));
self
}
/// `command_list_name` - Command name if listing commands
#[cfg(feature = "tmux_2_3")]
pub fn command_list_name(&mut self, v: &'a mut Option<String>) -> &mut Self {
self.push(VariableOutput::CommandListName(v));
self
}
/// `command_list_alias` - Command alias if listing commands
#[cfg(feature = "tmux_2_3")]
pub fn command_list_alias(&mut self, v: &'a mut Option<String>) -> &mut Self {
self.push(VariableOutput::CommandListAlias(v));
self
}
/// `command_list_usage` - Command usage if listing commands
#[cfg(feature = "tmux_2_3")]
pub fn command_list_usage(&mut self, v: &'a mut Option<String>) -> &mut Self {
self.push(VariableOutput::CommandListUsage(v));
self
}
// Cursor
/// `cursor_flag` - Pane cursor flag
#[cfg(feature = "tmux_1_8")]
pub fn cursor_flag(&mut self, v: &'a mut Option<String>) -> &mut Self {
self.push(VariableOutput::CursorFlag(v));
self
}
/// `cursor_character` - Character at cursor in pane
#[cfg(feature = "tmux_2_9")]
pub fn cursor_character(&mut self, v: &'a mut Option<String>) -> &mut Self {
self.push(VariableOutput::CursorCharacter(v));
self
}
/// `cursor_x` - Cursor X position in pane
#[cfg(feature = "tmux_1_8")]
pub fn cursor_x(&mut self, v: &'a mut Option<usize>) -> &mut Self {
self.push(VariableOutput::CursorX(v));
self
}
/// `cursor_y` - Cursor Y position in pane
#[cfg(feature = "tmux_1_8")]
pub fn cursor_y(&mut self, v: &'a mut Option<usize>) -> &mut Self {
self.push(VariableOutput::CursorY(v));
self
}
/// `copy_cursor_line` - Line the cursor is on in copy mode
#[cfg(feature = "tmux_3_1")]
pub fn copy_cursor_line(&mut self, v: &'a mut Option<String>) -> &mut Self {
self.push(VariableOutput::CopyCursorLine(v));
self
}
/// `copy_cursor_word` - Word under cursor in copy mode
#[cfg(feature = "tmux_3_1")]
pub fn copy_cursor_word(&mut self, v: &'a mut Option<String>) -> &mut Self {
self.push(VariableOutput::CopyCursorWord(v));
self
}
/// `copy_cursor_x` - Cursor X position in copy mode
#[cfg(feature = "tmux_3_1")]
pub fn copy_cursor_x(&mut self, v: &'a mut Option<usize>) -> &mut Self {
self.push(VariableOutput::CopyCursorX(v));
self
}
/// `copy_cursor_y` - Cursor Y position in copy mode
#[cfg(feature = "tmux_3_1")]
pub fn copy_cursor_y(&mut self, v: &'a mut Option<usize>) -> &mut Self {
self.push(VariableOutput::CopyCursorY(v));
self
}
/// `current_file` - Current configuration file
#[cfg(feature = "tmux_3_2")]
pub fn current_file(&mut self, v: &'a mut Option<String>) -> &mut Self {
self.push(VariableOutput::CurrentFile(v));
self
}
// history
/// `history_bytes` Number of bytes in window history
#[cfg(feature = "tmux_1_7")]
pub fn histoty_bytes(&mut self, v: &'a mut Option<usize>) -> &mut Self {
self.push(VariableOutput::HistotyBytes(v));
self
}
/// `history_limit` Maximum window history lines
#[cfg(feature = "tmux_1_7")]
pub fn history_limit(&mut self, v: &'a mut Option<usize>) -> &mut Self {
self.push(VariableOutput::HistotyLimit(v));
self
}
/// `history_size` Size of history in bytes
#[cfg(feature = "tmux_1_7")]
pub fn history_size(&mut self, v: &'a mut Option<usize>) -> &mut Self {
self.push(VariableOutput::HistorySize(v));
self
}
// hook
/// `hook` - Name of running hook, if any
#[cfg(feature = "tmux_2_4")]
pub fn hook(&mut self, v: &'a mut Option<String>) -> &mut Self {
self.push(VariableOutput::Hook(v));
self
}
/// `hook_pane` - ID of pane where hook was run, if any
#[cfg(feature = "tmux_2_4")]
pub fn hook_pane(&mut self, v: &'a mut Option<usize>) -> &mut Self {
self.push(VariableOutput::HookPane(v));
self
}
/// `hook_session` - ID of session where hook was run, if any
#[cfg(feature = "tmux_2_4")]
pub fn hook_session(&mut self, v: &'a mut Option<usize>) -> &mut Self {
self.push(VariableOutput::HookSession(v));
self
}
/// `hook_session_name` - Name of session where hook was run, if any
#[cfg(feature = "tmux_2_4")]
pub fn hook_session_name(&mut self, v: &'a mut Option<String>) -> &mut Self {
self.push(VariableOutput::HookSessionName(v));
self
}
/// `hook_window` - ID of window where hook was run, if any
#[cfg(feature = "tmux_2_4")]
pub fn hook_window(&mut self, v: &'a mut Option<usize>) -> &mut Self {
self.push(VariableOutput::HookWindow(v));
self
}
/// `hook_window_name` - Name of window where hook was run, if any
#[cfg(feature = "tmux_2_4")]
pub fn hook_window_name(&mut self, v: &'a mut Option<String>) -> &mut Self {
self.push(VariableOutput::HookWindowName(v));
self
}
// host
/// `host` - Hostname of local host
#[cfg(feature = "tmux_1_6")]
pub fn host(&mut self, v: &'a mut Option<String>) -> &mut Self {
self.push(VariableOutput::Host(v));
self
}
/// `host_short` - #h Hostname of local host (no domain name)
#[cfg(feature = "tmux_1_9")]
pub fn host_short(&mut self, v: &'a mut Option<String>) -> &mut Self {
self.push(VariableOutput::HostShort(v));
self
}
/// `insert_flag` - Pane insert flag
#[cfg(feature = "tmux_1_8")]
pub fn insert_flag(&mut self, v: &'a mut Option<String>) -> &mut Self {
self.push(VariableOutput::InsertFlag(v));
self
}
/// `keypad_cursor_flag` - Pane keypad cursor flag
#[cfg(feature = "tmux_1_8")]
pub fn keypad_cursor_flag(&mut self, v: &'a mut Option<String>) -> &mut Self {
self.push(VariableOutput::KeypadCursorFlag(v));
self
}
/// `keypad_flag` - Pane keypad flag
#[cfg(feature = "tmux_1_8")]
pub fn keypad_flag(&mut self, v: &'a mut Option<String>) -> &mut Self {
self.push(VariableOutput::KeypadFlag(v));
self
}
/// `line` - Line number in the list
#[cfg(feature = "tmux_1_6")]
pub fn line(&mut self, v: &'a mut Option<usize>) -> &mut Self {
self.push(VariableOutput::Line(v));
self
}
// `mouse_all_flag` - Pane mouse all flag
//#[cfg(feature = "tmux_3_0")]
//pub fn mouse_all_flag(&mut self, v: &'a mut Option<bool>) -> &mut Self {
//self.push(VariableOutput::MouseAllFlag(v));
//self
//}
/// `mouse_any_flag` - Pane mouse any flag
#[cfg(feature = "tmux_1_8")]
pub fn mouse_any_flag(&mut self, v: &'a mut Option<String>) -> &mut Self {
self.push(VariableOutput::MouseAnyFlag(v));
self
}
/// `mouse_button_flag` - Pane mouse button flag
#[cfg(feature = "tmux_1_8")]
pub fn mouse_button_flag(&mut self, v: &'a mut Option<String>) -> &mut Self {
self.push(VariableOutput::MouseButtonFlag(v));
self
}
/// `mouse_line` - Line under mouse, if any
#[cfg(feature = "tmux_3_0")]
pub fn mouse_line(&mut self, v: &'a mut Option<String>) -> &mut Self {
self.push(VariableOutput::MouseLine(v));
self
}
/// `sgr_flag` - Pane mouse SGR flag
#[cfg(feature = "tmux_3_0")]
pub fn sgr_line(&mut self, v: &'a mut Option<String>) -> &mut Self {
self.push(VariableOutput::MouseSgrFlag(v));
self
}
/// `mouse_standard_flag` - Pane mouse standard flag
#[cfg(feature = "tmux_1_8")]
pub fn mouse_standard_flag(&mut self, v: &'a mut Option<String>) -> &mut Self {
self.push(VariableOutput::MouseStandardFlag(v));
self
}
/// `mouse_utf8_flag` - Pane mouse UTF-8 flag
#[cfg(all(feature = "tmux_1_8", not(feature = "tmux_2_2"), feature = "tmux_3_0"))]
pub fn mouse_utf8_flag(&mut self, v: &'a mut Option<bool>) -> &mut Self {
self.push(VariableOutput::MouseUtf8Flag(v));
self
}
/// `mouse_all_flag` - Pane mouse all flag
#[cfg(feature = "tmux_2_4")]
pub fn mouse_all_flag(&mut self, v: &'a mut Option<String>) -> &mut Self {
self.push(VariableOutput::MouseAllFlag(v));
self
}
/// `mouse_word` - Word under mouse, if any
#[cfg(feature = "tmux_3_0")]
pub fn mouse_word(&mut self, v: &'a mut Option<String>) -> &mut Self {
self.push(VariableOutput::MouseWord(v));
self
}
/// `mouse_x` - Mouse X position, if any
#[cfg(feature = "tmux_3_0")]
pub fn mouse_x(&mut self, v: &'a mut Option<usize>) -> &mut Self {
self.push(VariableOutput::MouseX(v));
self
}
/// `mouse_y` - Mouse Y position, if any
#[cfg(feature = "tmux_3_0")]
pub fn mouse_y(&mut self, v: &'a mut Option<usize>) -> &mut Self {
self.push(VariableOutput::MouseY(v));
self
}
/// `origin_flag` - Pane origin flag
#[cfg(feature = "tmux_3_0")]
pub fn origin_flag(&mut self, v: &'a mut Option<String>) -> &mut Self {
self.push(VariableOutput::OriginFlag(v));
self
}
// pane
/// `pane_active` - 1 if active pane
#[cfg(feature = "tmux_1_6")]
pub fn pane_active(&mut self, v: &'a mut Option<bool>) -> &mut Self {
self.push(VariableOutput::PaneActive(v));
self
}
/// `pane_at_bottom` - 1 if pane is at the bottom of window
#[cfg(feature = "tmux_2_6")]
pub fn pane_at_bottom(&mut self, v: &'a mut Option<bool>) -> &mut Self {
self.push(VariableOutput::PaneAtBottom(v));
self
}
/// `pane_at_left` - 1 if pane is at the left of window
#[cfg(feature = "tmux_2_6")]
pub fn pane_at_left(&mut self, v: &'a mut Option<bool>) -> &mut Self {
self.push(VariableOutput::PaneAtLeft(v));
self
}
/// `pane_at_right` - 1 if pane is at the right of window
#[cfg(feature = "tmux_2_6")]
pub fn pane_at_right(&mut self, v: &'a mut Option<bool>) -> &mut Self {
self.push(VariableOutput::PaneAtRight(v));
self
}
/// `pane_at_top` - 1 if pane is at the top of window
#[cfg(feature = "tmux_2_6")]
pub fn pane_at_top(&mut self, v: &'a mut Option<bool>) -> &mut Self {
self.push(VariableOutput::PaneAtTop(v));
self
}
/// `pane_bottom` - Bottom of pane
#[cfg(feature = "tmux_2_0")]
pub fn pane_bottom(&mut self, v: &'a mut Option<usize>) -> &mut Self {
self.push(VariableOutput::PaneBottom(v));
self
}
/// `pane_current_command` - Current command if available
#[cfg(feature = "tmux_1_8")]
pub fn pane_current_command(&mut self, v: &'a mut Option<String>) -> &mut Self {
self.push(VariableOutput::PaneCurrentCommand(v));
self
}
/// `pane_current_path` - Current path if available
#[cfg(feature = "tmux_1_7")]
pub fn pane_current_path(&mut self, v: &'a mut Option<String>) -> &mut Self {
self.push(VariableOutput::PaneCurrentPath(v));
self
}
/// `pane_dead` - 1 if pane is dead
#[cfg(feature = "tmux_1_6")]
pub fn pane_dead(&mut self, v: &'a mut Option<bool>) -> &mut Self {
self.push(VariableOutput::PaneDead(v));
self
}
/// `pane_dead_status` - Exit status of process in dead pane
#[cfg(feature = "tmux_2_0")]
pub fn pane_dead_status(&mut self, v: &'a mut Option<usize>) -> &mut Self {
self.push(VariableOutput::PaneDeadStatus(v));
self
}
/// `pane_format` - 1 if format is for a pane
#[cfg(feature = "tmux_2_6")]
pub fn pane_format(&mut self, v: &'a mut Option<bool>) -> &mut Self {
self.push(VariableOutput::PaneFormat(v));
self
}
/// `pane_height` - Height of pane
#[cfg(feature = "tmux_1_6")]
pub fn pane_height(&mut self, v: &'a mut Option<usize>) -> &mut Self {
self.push(VariableOutput::PaneHeight(v));
self
}
/// `pane_id` - #D Unique pane ID
#[cfg(feature = "tmux_1_6")]
pub fn pane_id(&mut self, v: &'a mut Option<usize>) -> &mut Self {
self.push(VariableOutput::PaneId(v));
self
}
/// `pane_in_mode` - 1 if pane is in a mode
#[cfg(feature = "tmux_1_8")]
pub fn pane_in_mode(&mut self, v: &'a mut Option<bool>) -> &mut Self {
self.push(VariableOutput::PaneInMode(v));
self
}
/// `pane_index` - #P Index of pane
#[cfg(feature = "tmux_1_7")]
pub fn pane_index(&mut self, v: &'a mut Option<usize>) -> &mut Self {
self.push(VariableOutput::PaneIndex(v));
self
}
/// `pane_input_off` - 1 if input to pane is disabled
#[cfg(feature = "tmux_2_0")]
pub fn pane_input_off(&mut self, v: &'a mut Option<bool>) -> &mut Self {
self.push(VariableOutput::PaneInputOff(v));
self
}
/// `pane_left` - Left of pane
#[cfg(feature = "tmux_2_0")]
pub fn pane_left(&mut self, v: &'a mut Option<usize>) -> &mut Self {
self.push(VariableOutput::PaneLeft(v));
self
}
/// `pane_marked` - 1 if this is the marked pane
#[cfg(feature = "tmux_3_0")]
pub fn pane_marked(&mut self, v: &'a mut Option<bool>) -> &mut Self {
self.push(VariableOutput::PaneMarked(v));
self
}
/// `pane_marked_set` - 1 if a marked pane is set
#[cfg(feature = "tmux_3_0")]
pub fn pane_marked_set(&mut self, v: &'a mut Option<bool>) -> &mut Self {
self.push(VariableOutput::PaneMarkedSet(v));
self
}
/// `pane_mode` - Name of pane mode, if any
#[cfg(feature = "tmux_2_5")]
pub fn pane_mode(&mut self, v: &'a mut Option<usize>) -> &mut Self {
self.push(VariableOutput::PaneMode(v));
self
}
/// `pane_path` - #T Path of pane (can be set by application)
#[cfg(feature = "tmux_3_1")]
pub fn pane_path(&mut self, v: &'a mut Option<String>) -> &mut Self {
self.push(VariableOutput::PanePath(v));
self
}
/// `pane_pid` - PID of first process in pane
#[cfg(feature = "tmux_1_6")]
pub fn pane_pid(&mut self, v: &'a mut Option<usize>) -> &mut Self {
self.push(VariableOutput::PanePid(v));
self
}
/// `pane_pipe` - 1 if pane is being piped
#[cfg(feature = "tmux_2_6")]
pub fn pane_pipe(&mut self, v: &'a mut Option<bool>) -> &mut Self {
self.push(VariableOutput::PanePipe(v));
self
}
/// `pane_right` - Right of pane
#[cfg(feature = "tmux_2_0")]
pub fn pane_right(&mut self, v: &'a mut Option<usize>) -> &mut Self {
self.push(VariableOutput::PaneRight(v));
self
}
/// `pane_search_string` - Last search `Option<String>` in copy mode
#[cfg(feature = "tmux_2_5")]
pub fn pane_search_string(&mut self, v: &'a mut Option<usize>) -> &mut Self {
self.push(VariableOutput::PaneSearchString(v));
self
}
/// `pane_start_command` - Command pane started with
#[cfg(feature = "tmux_1_6")]
pub fn pane_start_command(&mut self, v: &'a mut Option<usize>) -> &mut Self {
self.push(VariableOutput::PaneStartCommand(v));
self
}
/// `pane_start_path` - Path pane started with
#[cfg(all(feature = "tmux_1_6", not(feature = "tmux_2_0")))]
pub fn pane_start_path(&mut self, v: &'a mut Option<usize>) -> &mut Self {
self.push(VariableOutput::PaneStartPath(v));
self
}
/// `pane_synchronized` - 1 if pane is synchronized
#[cfg(feature = "tmux_1_9")]
pub fn pane_synchronized(&mut self, v: &'a mut Option<bool>) -> &mut Self {
self.push(VariableOutput::PaneSynchronized(v));
self
}
/// `pane_tabs` - Pane tab positions
#[cfg(feature = "tmux_1_8")]
pub fn pane_tabs(&mut self, v: &'a mut Option<PaneTabs>) -> &mut Self {
self.push(VariableOutput::PaneTabs(v));
self
}
/// `pane_title` - #T Title of pane (can be set by application)
#[cfg(feature = "tmux_1_6")]
pub fn pane_title(&mut self, v: &'a mut Option<String>) -> &mut Self {
self.push(VariableOutput::PaneTitle(v));
self
}
/// `pane_top` - Top of pane
#[cfg(feature = "tmux_2_0")]
pub fn pane_top(&mut self, v: &'a mut Option<usize>) -> &mut Self {
self.push(VariableOutput::PaneTop(v));
self
}
/// `pane_tty` - Pseudo terminal of pane
#[cfg(feature = "tmux_1_6")]
pub fn pane_tty(&mut self, v: &'a mut Option<String>) -> &mut Self {
self.push(VariableOutput::PaneTty(v));
self
}
/// `pane_width` - Width of pane
#[cfg(feature = "tmux_1_6")]
pub fn pane_width(&mut self, v: &'a mut Option<usize>) -> &mut Self {
self.push(VariableOutput::PaneWidth(v));
self
}
/// `saved_cursor_x` - Saved cursor X in pane
#[cfg(any(feature = "tmux_1_8", not(feature = "tmux_2_1")))]
pub fn saved_cursor_x(&mut self, v: &'a mut Option<usize>) -> &mut Self {
self.push(VariableOutput::SavedCursorX(v));
self
}
/// `saved_cursor_y` - Saved cursor Y in pane
#[cfg(any(feature = "tmux_1_8", not(feature = "tmux_2_1")))]
pub fn saved_cursor_y(&mut self, v: &'a mut Option<usize>) -> &mut Self {
self.push(VariableOutput::SavedCursorY(v));
self
}
/// `pid` - Server PID
#[cfg(feature = "tmux_2_1")]
pub fn pid(&mut self, v: &'a mut Option<usize>) -> &mut Self {
self.push(VariableOutput::Pid(v));
self
}
/// `rectangle_toggle` - 1 if rectangle selection is activated
#[cfg(feature = "tmux_2_7")]
pub fn rectangle_toggle(&mut self, v: &'a mut Option<bool>) -> &mut Self {
self.push(VariableOutput::RectangleToggle(v));
self
}
/// `scroll_position` - Scroll position in copy mode
#[cfg(feature = "tmux_2_2")]
pub fn scroll_position(&mut self, v: &'a mut Option<usize>) -> &mut Self {
self.push(VariableOutput::ScrollPosition(v));
self
}
/// `scroll_region_lower` - Bottom of scroll region in pane
#[cfg(feature = "tmux_1_8")]
pub fn scroll_region_lower(&mut self, v: &'a mut Option<usize>) -> &mut Self {
self.push(VariableOutput::ScrollRegionLower(v));
self
}
/// `scroll_region_upper` - Top of scroll region in pane
#[cfg(feature = "tmux_1_8")]
pub fn scroll_region_upper(&mut self, v: &'a mut Option<usize>) -> &mut Self {
self.push(VariableOutput::ScrollRegionUpper(v));
self
}
/// `selection_active` - 1 if selection started and changes with the curso
#[cfg(feature = "tmux_3_1")]
pub fn selection_active(&mut self, v: &'a mut Option<bool>) -> &mut Self {
self.push(VariableOutput::SelectionActive(v));
self
}
/// `selection_end_x` - X position of the end of the selection
#[cfg(feature = "tmux_3_1")]
pub fn selection_end_x(&mut self, v: &'a mut Option<usize>) -> &mut Self {
self.push(VariableOutput::SelectionEndX(v));
self
}
/// `selection_end_y` - Y position of the end of the selection
#[cfg(feature = "tmux_3_1")]
pub fn selection_end_y(&mut self, v: &'a mut Option<usize>) -> &mut Self {
self.push(VariableOutput::SelectionEndY(v));
self
}
/// `selection_present` - 1 if selection started in copy mode
#[cfg(feature = "tmux_2_6")]
pub fn selection_present(&mut self, v: &'a mut Option<bool>) -> &mut Self {
self.push(VariableOutput::SelectionPresent(v));
self
}
/// `selection_start_x` - X position of the start of the selection
#[cfg(feature = "tmux_3_1")]
pub fn selection_start_x(&mut self, v: &'a mut Option<usize>) -> &mut Self {
self.push(VariableOutput::SelectionStartX(v));
self
}
/// `selection_start_y` - Y position of the start of the selection
#[cfg(feature = "tmux_3_1")]
pub fn selection_start_y(&mut self, v: &'a mut Option<usize>) -> &mut Self {
self.push(VariableOutput::SelectionStartY(v));
self
}
// Session
/// `session_activity` - Time of session last activity
#[cfg(feature = "tmux_2_1")]
pub fn session_activity(&mut self, v: &'a mut Option<usize>) -> &mut Self {
self.push(VariableOutput::SessionActivity(v));
self
}
/// `session_activity_string` - Option<String> time of session last activity
#[cfg(all(feature = "tmux_2_1", not(feature = "tmux_2_2")))]
pub fn session_activity_string(&mut self, v: &'a mut Option<String>) -> &mut Self {
self.push(VariableOutput::SessionActivityString(v));
self
}
/// `session_alerts` - List of window indexes with alerts
#[cfg(feature = "tmux_2_1")]
pub fn session_alerts(&mut self, v: &'a mut Option<String>) -> &mut Self {
self.push(VariableOutput::SessionAlerts(v));
self
}
/// `session_attached` - Number of clients session is attached to
#[cfg(feature = "tmux_1_6")]
pub fn session_attached(&mut self, v: &'a mut Option<usize>) -> &mut Self {
self.push(VariableOutput::SessionAttached(v));
self
}
/// `session_attached_list` - List of clients session is attached to
#[cfg(feature = "tmux_3_1")]
pub fn session_attached_list(&mut self, v: &'a mut Option<usize>) -> &mut Self {
self.push(VariableOutput::SessionAttachedList(v));
self
}
/// `session_created` - Time session created
#[cfg(feature = "tmux_1_6")]
pub fn session_created(&mut self, v: &'a mut Option<usize>) -> &mut Self {
self.push(VariableOutput::SessionCreated(v));
self
}
/// `session_created_string` - Option<String> time session created
#[cfg(all(feature = "tmux_1_6", not(feature = "tmux_2_2")))]
pub fn session_created_string(&mut self, v: &'a mut Option<String>) -> &mut Self {
self.push(VariableOutput::SessionCreatedString(v));
self
}
/// `session_format` - 1 if format is for a session (not assuming the current)
#[cfg(feature = "tmux_2_6")]
pub fn session_format(&mut self, v: &'a mut Option<bool>) -> &mut Self {
self.push(VariableOutput::SessionFormat(v));
self
}
/// `session_group` - Name of session group
#[cfg(feature = "tmux_1_6")]
pub fn session_group(&mut self, v: &'a mut Option<String>) -> &mut Self {
self.push(VariableOutput::SessionGroup(v));
self
}
/// `session_group_attached` - Number of clients sessions in group are attached >
#[cfg(feature = "tmux_3_1")]
pub fn session_group_attached(&mut self, v: &'a mut Option<usize>) -> &mut Self {
self.push(VariableOutput::SessionGroupAttached(v));
self
}
/// `session_group_attached_list` - List of clients sessions in group are attached to
#[cfg(feature = "tmux_3_1")]
pub fn session_group_attached_list(&mut self, v: &'a mut Option<String>) -> &mut Self {
self.push(VariableOutput::SessionGroupAttachedList(v));
self
}
/// `session_group_list` - List of sessions in group
#[cfg(feature = "tmux_2_7")]
pub fn session_group_list(&mut self, v: &'a mut Option<String>) -> &mut Self {
self.push(VariableOutput::SessionGroupList(v));
self
}
/// `session_group_many_attached` - 1 if multiple clients attached to sessions in gro
#[cfg(feature = "tmux_3_1")]
pub fn session_group_many_attached(&mut self, v: &'a mut Option<bool>) -> &mut Self {
self.push(VariableOutput::SessionGroupManyAttached(v));
self
}
/// `session_group_size` - Size of session group
#[cfg(feature = "tmux_2_7")]
pub fn session_group_size(&mut self, v: &'a mut Option<String>) -> &mut Self {
self.push(VariableOutput::SessionGroupSize(v));
self
}
/// `session_grouped` - 1 if session in a group
#[cfg(feature = "tmux_1_6")]
pub fn session_grouped(&mut self, v: &'a mut Option<bool>) -> &mut Self {
self.push(VariableOutput::SessionGrouped(v));
self
}
/// `session_height` - Height of session
#[cfg(all(feature = "tmux_1_6", not(feature = "tmux_2_9")))]
pub fn session_height(&mut self, v: &'a mut Option<usize>) -> &mut Self {
self.push(VariableOutput::SessionHeight(v));
self
}
/// `session_width` - Width of session
#[cfg(all(feature = "tmux_1_6", not(feature = "tmux_2_9")))]
pub fn session_width(&mut self, v: &'a mut Option<usize>) -> &mut Self {
self.push(VariableOutput::SessionWidth(v));
self
}
/// `session_id` - Unique session ID
#[cfg(feature = "tmux_1_8")]
pub fn session_id(&mut self, v: &'a mut Option<usize>) -> &mut Self {
self.push(VariableOutput::SessionId(v));
self
}
/// `session_last_attached` - Time session last attached
#[cfg(feature = "tmux_2_1")]
pub fn session_last_attached(&mut self, v: &'a mut Option<usize>) -> &mut Self {
self.push(VariableOutput::SessionLastAttached(v));
self
}
/// `session_last_attached_string` - Option<String> time session last attached
#[cfg(all(feature = "tmux_2_1", not(feature = "tmux_2_2")))]
pub fn session_last_attached_string(&mut self, v: &'a mut Option<String>) -> &mut Self {
self.push(VariableOutput::SessionLastAttachedString(v));
self
}
/// `session_many_attached` - 1 if multiple clients attached
#[cfg(feature = "tmux_2_0")]
pub fn session_many_attached(&mut self, v: &'a mut Option<bool>) -> &mut Self {
self.push(VariableOutput::SessionManyAttached(v));
self
}
/// `session_name` - #S Name of session
#[cfg(feature = "tmux_1_6")]
pub fn session_name(&mut self, v: &'a mut Option<String>) -> &mut Self {
self.push(VariableOutput::SessionName(v));
self
}
/// `session_stack` - Window indexes in most recent order
#[cfg(feature = "tmux_2_5")]
pub fn session_stack(&mut self, v: &'a mut Option<SessionStack>) -> &mut Self {
self.push(VariableOutput::SessionStack(v));
self
}
/// `session_windows` - Number of windows in session
#[cfg(feature = "tmux_1_6")]
pub fn session_windows(&mut self, v: &'a mut Option<usize>) -> &mut Self {
self.push(VariableOutput::SessionWindows(v));
self
}
/// `socket_path` - Server socket path
#[cfg(feature = "tmux_2_2")]
pub fn socket_path(&mut self, v: &'a mut Option<String>) -> &mut Self {
self.push(VariableOutput::SocketPath(v));
self
}
/// `start_time` - Server start time
#[cfg(feature = "tmux_2_2")]
pub fn start_time(&mut self, v: &'a mut Option<usize>) -> &mut Self {
self.push(VariableOutput::StartTime(v));
self
}
/// `version` - Server version
#[cfg(feature = "tmux_2_4")]
pub fn version(&mut self, v: &'a mut Option<String>) -> &mut Self {
self.push(VariableOutput::Version(v));
self
}
// Window
//
/// `window_active` - 1 if window active
#[cfg(feature = "tmux_1_6")]
pub fn window_active(&mut self, v: &'a mut Option<bool>) -> &mut Self {
self.push(VariableOutput::WindowActive(v));
self
}
/// `window_active_clients` - Number of clients viewing this window
#[cfg(feature = "tmux_3_1")]
pub fn window_active_clients(&mut self, v: &'a mut Option<usize>) -> &mut Self {
self.push(VariableOutput::WindowActiveClients(v));
self
}
/// `window_active_clients_list` - List of clients viewing this window
#[cfg(feature = "tmux_3_1")]
pub fn window_active_clients_list(&mut self, v: &'a mut Option<String>) -> &mut Self {
self.push(VariableOutput::WindowActiveClientsList(v));
self
}
/// `window_active_sessions` - Number of sessions on which this window is active
#[cfg(feature = "tmux_3_1")]
pub fn window_active_sessions(&mut self, v: &'a mut Option<usize>) -> &mut Self {
self.push(VariableOutput::WindowActiveSessions(v));
self
}
/// `window_active_sessions_list` - List of sessions on which this window is active
#[cfg(feature = "tmux_3_1")]
pub fn window_active_sessions_list(&mut self, v: &'a mut Option<String>) -> &mut Self {
self.push(VariableOutput::WindowActiveSessionsList(v));
self
}
/// `window_activity` - Time of window last activity
#[cfg(feature = "tmux_2_1")]
pub fn window_activity(&mut self, v: &'a mut Option<usize>) -> &mut Self {
self.push(VariableOutput::WindowActivity(v));
self
}
/// `window_activity_string` - String time of window last activity
#[cfg(all(feature = "tmux_2_1", not(feature = "tmux_2_2")))]
pub fn window_activity_string(&mut self, v: &'a mut Option<String>) -> &mut Self {
self.push(VariableOutput::WindowActivityString(v));
self
}
/// `window_activity_flag` - 1 if window has activity
#[cfg(any(
all(feature = "tmux_1_9", not(feature = "tmux_2_2")),
feature = "tmux_2_3"
))]
pub fn window_activity_flag(&mut self, v: &'a mut Option<bool>) -> &mut Self {
self.push(VariableOutput::WindowActivityFlag(v));
self
}
/// `window_bell_flag` - 1 if window has bell
#[cfg(feature = "tmux_1_9")]
pub fn window_bell_flag(&mut self, v: &'a mut Option<bool>) -> &mut Self {
self.push(VariableOutput::WindowBellFlag(v));
self
}
/// `window_content_flag` - 1 if window has content alert
#[cfg(all(feature = "tmux_1_9", not(feature = "tmux_2_0")))]
pub fn window_content_flag(&mut self, v: &'a mut Option<bool>) -> &mut Self {
self.push(VariableOutput::WindowContentFlag(v));
self
}
/// `window_bigger` - 1 if window is larger than client
#[cfg(feature = "tmux_2_9")]
pub fn window_bigger(&mut self, v: &'a mut Option<bool>) -> &mut Self {
self.push(VariableOutput::WindowBigger(v));
self
}
/// `window_cell_height` - Height of each cell in pixels
#[cfg(feature = "tmux_3_1")]
pub fn window_cell_height(&mut self, v: &'a mut Option<usize>) -> &mut Self {
self.push(VariableOutput::WindowCellHeight(v));
self
}
/// `window_cell_width` - Width of each cell in pixels
#[cfg(feature = "tmux_3_1")]
pub fn window_cell_width(&mut self, v: &'a mut Option<usize>) -> &mut Self {
self.push(VariableOutput::WindowCellWidth(v));
self
}
/// `window_end_flag` - 1 if window has the highest index
#[cfg(feature = "tmux_2_9")]
pub fn window_end_flag(&mut self, v: &'a mut Option<bool>) -> &mut Self {
self.push(VariableOutput::WindowEndFlag(v));
self
}
/// `window_find_matches` - Matched data from the find-window command if available
#[cfg(all(feature = "tmux_1_7", not(feature = "tmux_2_6")))]
pub fn window_find_matches(&mut self, v: &'a mut Option<String>) -> &mut Self {
self.push(VariableOutput::WindowFindMatches(v));
self
}
/// `window_flags` - #F Window flags
#[cfg(feature = "tmux_1_6")]
pub fn window_flags(&mut self, v: &'a mut Option<WindowFlags>) -> &mut Self {
self.push(VariableOutput::WindowFlags(v));
self
}
// TODO: WindowRawFlags
/// `window_raw_flags` - Window flags with nothing escaped
#[cfg(feature = "tmux_3_2")]
pub fn window_raw_flags(&mut self, v: &'a mut Option<WindowFlags>) -> &mut Self {
self.push(VariableOutput::WindowRawFlags(v));
self
}
/// `window_format` - 1 if format is for a window
#[cfg(feature = "tmux_2_6")]
pub fn window_format(&mut self, v: &'a mut Option<bool>) -> &mut Self {
self.push(VariableOutput::WindowFormat(v));
self
}
/// `window_height` - Height of window
#[cfg(feature = "tmux_1_6")]
pub fn window_height(&mut self, v: &'a mut Option<usize>) -> &mut Self {
self.push(VariableOutput::WindowHeight(v));
self
}
/// `window_id` - Unique window ID
#[cfg(feature = "tmux_1_7")]
pub fn window_id(&mut self, v: &'a mut Option<usize>) -> &mut Self {
self.push(VariableOutput::WindowId(v));
self
}
/// `window_index` - #I Index of window
#[cfg(feature = "tmux_1_6")]
pub fn window_index(&mut self, v: &'a mut Option<usize>) -> &mut Self {
self.push(VariableOutput::WindowIndex(v));
self
}
/// `window_last_flag` - 1 if window is the last used
#[cfg(feature = "tmux_2_0")]
pub fn window_last_flag(&mut self, v: &'a mut Option<bool>) -> &mut Self {
self.push(VariableOutput::WindowLastFlag(v));
self
}
/// `window_layout` - Window layout description, ignoring zoomed window panes
#[cfg(feature = "tmux_1_6")]
pub fn window_layout(&mut self, v: &'a mut Option<Layout>) -> &mut Self {
self.push(VariableOutput::WindowLayout(v));
self
}
/// `window_linked` - 1 if window is linked across sessions
#[cfg(feature = "tmux_2_1")]
pub fn window_linked(&mut self, v: &'a mut Option<bool>) -> &mut Self {
self.push(VariableOutput::WindowLinked(v));
self
}
/// `window_linked_sessions` - Number of sessions this window is linked to
#[cfg(feature = "tmux_3_1")]
pub fn window_linked_sessions(&mut self, v: &'a mut Option<usize>) -> &mut Self {
self.push(VariableOutput::WindowLinkedSessions(v));
self
}
/// `window_linked_sessions_list` - List of sessions this window is linked to
#[cfg(feature = "tmux_3_1")]
pub fn window_linked_sessions_list(&mut self, v: &'a mut Option<String>) -> &mut Self {
self.push(VariableOutput::WindowLinkedSessionsList(v));
self
}
/// `window_marked_flag` - 1 if window contains the marked pane
#[cfg(feature = "tmux_3_1")]
pub fn window_marked_flag(&mut self, v: &'a mut Option<bool>) -> &mut Self {
self.push(VariableOutput::WindowMarkedFlag(v));
self
}
/// `window_name` - #W Name of window
#[cfg(feature = "tmux_1_6")]
pub fn window_name(&mut self, v: &'a mut Option<String>) -> &mut Self {
self.push(VariableOutput::WindowName(v));
self
}
/// `window_offset_x` - X offset into window if larger than client
#[cfg(feature = "tmux_2_9")]
pub fn window_offset_x(&mut self, v: &'a mut Option<usize>) -> &mut Self {
self.push(VariableOutput::WindowOffsetX(v));
self
}
/// `window_offset_y` - Y offset into window if larger than client
#[cfg(feature = "tmux_2_9")]
pub fn window_offset_y(&mut self, v: &'a mut Option<usize>) -> &mut Self {
self.push(VariableOutput::WindowOffsetY(v));
self
}
/// `window_panes` - Number of panes in window
#[cfg(feature = "tmux_1_7")]
pub fn window_panes(&mut self, v: &'a mut Option<usize>) -> &mut Self {
self.push(VariableOutput::WindowPanes(v));
self
}
/// `window_silence_flag` - 1 if window has silence alert
#[cfg(feature = "tmux_1_9")]
pub fn window_silence_flag(&mut self, v: &'a mut Option<bool>) -> &mut Self {
self.push(VariableOutput::WindowSilenceFlag(v));
self
}
/// `window_stack_index` - Index in session most recent stack
#[cfg(feature = "tmux_2_5")]
pub fn window_stack_index(&mut self, v: &'a mut Option<usize>) -> &mut Self {
self.push(VariableOutput::WindowStackIndex(v));
self
}
/// `window_start_flag` - 1 if window has the lowest index
#[cfg(feature = "tmux_2_9")]
pub fn window_start_flag(&mut self, v: &'a mut Option<bool>) -> &mut Self {
self.push(VariableOutput::WindowStartFlag(v));
self
}
/// `window_visible_layout` - Window layout description, respecting zoomed window panes
#[cfg(feature = "tmux_2_2")]
pub fn window_visible_layout(&mut self, v: &'a mut Option<Layout>) -> &mut Self {
self.push(VariableOutput::WindowVisibleLayout(v));
self
}
/// `window_width` - Width of window
#[cfg(feature = "tmux_1_6")]
pub fn window_width(&mut self, v: &'a mut Option<usize>) -> &mut Self {
self.push(VariableOutput::WindowWidth(v));
self
}
/// `window_zoomed_flag` - 1 if window is zoomed
#[cfg(feature = "tmux_2_0")]
pub fn window_zoomed_flag(&mut self, v: &'a mut Option<bool>) -> &mut Self {
self.push(VariableOutput::WindowZoomedFlag(v));
self
}
/// `wrap_flag` - Pane wrap flag
#[cfg(feature = "tmux_1_8")]
pub fn wrap_flag(&mut self, v: &'a mut Option<bool>) -> &mut Self {
self.push(VariableOutput::WrapFlag(v));
self
}
}
| true
|
a67a875f18fff072f6a98e8e3f032f1ae6188089
|
Rust
|
azriel91/autexousious
|
/crate/game_input_model/src/loaded/control_axis.rs
|
UTF-8
| 441
| 2.796875
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] |
permissive
|
use strum_macros::{Display, EnumIter, EnumString};
/// Control axis input for characters.
///
/// This is not used in `PlayerInputConfigs`, but as a logical representation
#[derive(Clone, Copy, Debug, Display, EnumIter, EnumString, Hash, PartialEq, Eq)]
#[strum(serialize_all = "snake_case")]
pub enum ControlAxis {
/// Up button.
Up,
/// Down button.
Down,
/// Left button.
Left,
/// Right button.
Right,
}
| true
|
a936a09f5d895b5afde9355857431cb9846f79b7
|
Rust
|
michaelfletchercgy/rainguage
|
/rainguage-messages/src/lib.rs
|
UTF-8
| 10,872
| 2.65625
| 3
|
[] |
no_license
|
#![no_std]
use serde::{Serialize, Deserialize};
use crc::{crc32, Hasher32};
use core::iter::Iterator;
use byteorder::ByteOrder;
use byteorder::NetworkEndian;
const MAGIC:[u8;3] = [125, 8, 141];
#[derive(Debug)]
pub enum SerializeError {
Internal(postcard::Error)
}
impl From<postcard::Error> for SerializeError {
fn from(err: postcard::Error) -> Self {
SerializeError::Internal(err)
}
}
#[derive(Debug, PartialEq)]
pub enum DeserializeError {
SerializeError(postcard::Error),
InvalidLength,
InvalidChecksum{
crc32_buf: [u8;4],
msg_buf: [u8; 64],
msg_len: u8
}
}
impl From<postcard::Error> for DeserializeError {
fn from(err: postcard::Error) -> Self {
DeserializeError::SerializeError(err)
}
}
//
// ReadingMagic -> ReadingLength -> ReadingBytes -> ReadingChecksum
//
#[derive(Debug)]
enum IteratorState {
ReadingMagic{
bytes_read:u8
},
ReadingLength,
ReadingBytes{
msg_len: u8,
num_read: usize,
msg_buf: [u8; 64]
},
ReadingChecksum {
num_read: usize,
crc32_buf: [u8;4],
msg_buf: [u8; 64],
msg_len: u8
}
}
// Wraps an iterator of bytes
pub struct PacketIterator <I:Iterator<Item=u8>> {
byte_iter:I,
state:IteratorState
}
impl <I:Iterator<Item=u8>> PacketIterator<I> {
pub fn new(byte_iter:I) -> PacketIterator<I> {
PacketIterator {
byte_iter,
state:IteratorState::ReadingMagic {
bytes_read: 0
}
}
}
}
impl <'a, I:Iterator<Item=u8>> Iterator for PacketIterator<I> {
type Item = Result<TelemetryPacket, DeserializeError>;
fn next(&mut self) -> Option<Result<TelemetryPacket, DeserializeError>> {
loop {
match self.byte_iter.next() {
Some(byte) => {
//println!("byte={}", byte);
match self.state {
IteratorState::ReadingMagic {ref mut bytes_read } => {
if *bytes_read > 3 {
*bytes_read = 0;
} else if byte == MAGIC[*bytes_read as usize] {
*bytes_read = *bytes_read + 1;
}
if *bytes_read == 3 {
self.state = IteratorState::ReadingLength;
}
},
IteratorState::ReadingLength => {
if byte > 64 {
self.state = IteratorState::ReadingMagic{ bytes_read:0 };
return Some(Result::Err(DeserializeError::InvalidLength));
}
self.state = IteratorState::ReadingBytes {
msg_len:byte,
num_read:0,
msg_buf: [0u8; 64]
};
},
IteratorState::ReadingBytes{msg_len, ref mut num_read, ref mut msg_buf} => {
msg_buf[*num_read] = byte;
*num_read += 1;
if *num_read >= msg_len.into() {
self.state = IteratorState::ReadingChecksum {
num_read:0,
msg_buf:*msg_buf,
msg_len,
crc32_buf: [0u8; 4]
};
}
},
IteratorState::ReadingChecksum{ref mut num_read, msg_buf, msg_len, ref mut crc32_buf} => {
crc32_buf[*num_read] = byte;
*num_read += 1;
if *num_read >= 4 {
let mut digest = crc32::Digest::new(crc32::IEEE);
digest.write(&msg_buf[0..msg_len as usize]);
let calculated_sum = digest.sum32();
let provided_sum = NetworkEndian::read_u32(crc32_buf);
let clone_buf = crc32_buf.clone();
self.state = IteratorState::ReadingMagic { bytes_read:0 };
if calculated_sum == provided_sum {
match postcard::from_bytes(&msg_buf[0..msg_len as usize]) {
Ok(packet) => {
return Some(Result::Ok(packet));
},
Err(err) => {
return Some(Result::Err(DeserializeError::SerializeError(err)));
}
}
} else {
return Some(Result::Err(DeserializeError::InvalidChecksum{
msg_buf,
msg_len,
crc32_buf:clone_buf
}));
}
}
}
}
},
None => {
return Option::None;
}
};
}
}
}
#[derive(Serialize, Deserialize, Debug, PartialEq)]
/// TelemetryPacket is sent from the rainguage.
pub struct TelemetryPacket {
/// The hardware identifier
pub device_id: [u8; 16],
/// The number of loops that have been run. The device has no clock so this is an approximation of time. It
/// will wrap back to 0.
pub loop_cnt: u32,
/// The number of times the rainguage has tipped over.
pub tip_cnt: u32,
/// The last voltage recorded by the battery.
pub vbat: u32,
pub temperature: f32,
pub relative_humidity: f32,
pub usb_bytes_read: u32,
pub usb_bytes_written: u32,
pub usb_error_cnt: u32,
pub lora_rx_bytes: u32,
pub lora_tx_bytes: u32,
pub lora_error_cnt: u32,
/// The number of other hardware errors that occured. This is an error outside of a more specific hardware error. Things like flashing
/// leds.
pub hardware_err_other_cnt: u32
}
impl TelemetryPacket {
pub fn new() -> TelemetryPacket {
TelemetryPacket {
device_id: [0; 16],
loop_cnt: 0,
tip_cnt: 0,
vbat: 0,
temperature: 0.0,
relative_humidity: 0.0,
usb_bytes_read: 0,
usb_bytes_written: 0,
usb_error_cnt: 0,
lora_rx_bytes: 0,
lora_tx_bytes: 0,
lora_error_cnt: 0,
hardware_err_other_cnt: 0
}
}
}
// Serialize a telemetry packet into a byte buffer returning the length of the written bytes.
//
// The packet is written including a magic value, bytes and a checksum. The format is
//
// magic 3 bytes - always 125, 8, 141
// len 1 byte - length of bytes packet)
// bytes `len` bytes - payload
// checksum 4 bytes, a crc32 checksum of `bytes` (u32 in network byte order)
pub fn serialize(telem:&TelemetryPacket, buf:&mut [u8]) -> Result<usize, SerializeError> {
// Write magic into the first three bytes
buf[0] = MAGIC[0];
buf[1] = MAGIC[1];
buf[2] = MAGIC[2];
// Serialize the telemetry packet
let result = postcard::to_slice(telem, &mut buf[4..])?;
let len = result.len();
// Calculate the crc32 checksum
let mut digest = crc32::Digest::new(crc32::IEEE);
digest.write(result);
let checksum = digest.sum32();
// Write the length into the buffer
buf[3] = result.len() as u8;
// Write the checksum into the buffer.
NetworkEndian::write_u32(&mut buf[len + 4..len+4+4+1], checksum);
// write the sum in
Ok(3 + 1 + len + 4)
}
#[cfg(test)]
#[macro_use]
extern crate std;
#[cfg(test)]
mod tests {
#[test]
fn largest_packet() {
let mut packet = super::TelemetryPacket::new();
packet.device_id = [255; 16];
packet.loop_cnt = u32::MAX;
packet.tip_cnt = u32::MAX;
packet.vbat = u32::MAX;
packet.temperature = 0.0;
packet.relative_humidity = 0.0;
packet.usb_bytes_read = u32::MAX;
packet.usb_bytes_written = u32::MAX;
packet.usb_error_cnt = u32::MAX;
packet.lora_rx_bytes = u32::MAX;
packet.lora_tx_bytes = u32::MAX;
packet.lora_error_cnt = u32::MAX;
packet.hardware_err_other_cnt = u32::MAX;
let mut buf:[u8; 127] = [0; 127];
let cnt = super::serialize(&packet, &mut buf).unwrap();
println!("{:?}", buf);
assert_eq!(72, cnt);
}
#[test]
fn test_serialize_deserialize_zero() {
let mut buf:[u8; 255] = [0; 255];
let packet = super::TelemetryPacket::new();
super::serialize(&packet, &mut buf).unwrap();
println!("{:?}", buf);
let bytes = buf.iter()
.map(|byte| *byte);
let mut iter = super::PacketIterator::new(bytes);
assert_eq!(Some(Ok(packet)), iter.next());
assert_eq!(None, iter.next());
}
#[test]
fn test_serialize_deserialize_full() {
let mut buf:[u8; 255] = [0; 255];
let mut packet = super::TelemetryPacket::new();
packet.device_id = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 120, 130, 140, 150, 160, 170];
packet.loop_cnt = 180;
packet.vbat = 190 as u32;
packet.usb_bytes_read = 200;
packet.usb_error_cnt = 210;
packet.lora_error_cnt = 220;
packet.lora_tx_bytes = 230;
super::serialize(&packet, &mut buf).unwrap();
let bytes = buf.iter()
.map(|byte| *byte);
let mut iter = super::PacketIterator::new(bytes);
let first_packet = iter.next().unwrap().unwrap();
assert_eq!(packet, first_packet);
assert_eq!(None, iter.next());
}
#[test]
fn test_bad_checksum() {
let mut buf:[u8; 128] = [0; 128];
let packet = super::TelemetryPacket::new();
super::serialize(&packet, &mut buf).unwrap();
// Random Change
buf[28] = 23;
let bytes = buf.iter()
.map(|byte| *byte);
let mut iter = super::PacketIterator::new(bytes);
if let Some(Err(_)) = iter.next() {
} else {
panic!("expected to get an error");
}
assert_eq!(None, iter.next());
}
}
| true
|
c96ffdf4ce028903abd2c5f8f8af36bd4802a0fe
|
Rust
|
lwandsyj/rust
|
/lear2/src/fn_learn.rs
|
UTF-8
| 457
| 3.640625
| 4
|
[] |
no_license
|
pub fn test(mut a: i32) -> i32 {
a = a + 1;
a
}
pub fn test_brow(a: &mut i32) -> i32 {
*a = *a + 1;
*a
}
/**
* 调用
* let mut a = 1;
let b = test_brow(&mut a);
println!("{}", a);
println!("{}", b);
*/
// 引用类型数组可以是不固定长度
fn test1(a:&[i32]){
println!("{:?}",a);
}
fn main1() {
let a:[i32;5]=[1,2,3,4,5];
test1(&a);
println!("{:?}",a);
let b:[i32;3]=[3,4,5];
test1(&b);
}
| true
|
fa48ace6d44158d05469e73fe64e130b9a9d89bf
|
Rust
|
vinhhungle/webassembly-react
|
/rust-wasm/src/condition.rs
|
UTF-8
| 345
| 3.21875
| 3
|
[] |
no_license
|
pub fn run() {
let age: u8 = 18;
let is_of_age = age >= 21; // if age >= 21 { true } else { false }
let check_id: bool = false;
if is_of_age && check_id {
println!("What would you like to drink?")
} else if !is_of_age && check_id {
println!("Sorry, you have to leave")
} else {
println!("I'll need to see your ID")
}
}
| true
|
f882a7f4a73e5e42c780f1c2ad2861aebf7630de
|
Rust
|
a-bakos/rust-playground
|
/archived-learning/hands-on-data-structures-and-algorithms-in-rust/p03-copy-clone-mut/src/main.rs
|
UTF-8
| 484
| 3.796875
| 4
|
[] |
no_license
|
// i32 implements Copy marker trait
// it means it'll automatically copy all of the memory across
#[derive(Debug, Clone)]
pub struct Person {
name: String,
age: i32,
}
fn main() {
let p = Person {
name: "Frank".to_string(),
age: 6,
};
// if the struct doesn't have a clone marker trait implemented,
// now we'd have two variables pointing to the same memory, aka p2 = p
let p2 = p.clone();
println!("p = {:?}, p2 = {:?}", p, p2);
}
| true
|
32b2d5090f408320f38da66b0cafd85473979f43
|
Rust
|
RussellChamp/advent-of-code-2016
|
/2016/day18/src/main.rs
|
UTF-8
| 3,519
| 3.328125
| 3
|
[
"MIT"
] |
permissive
|
// Trap rules
// * if 110 or 011, 100, 001
// where nonexistent sides are considered 0
#[derive(Debug, PartialEq, Clone)]
enum Tile {
Trapped = 1,
Safe = 0
}
type Row = Vec<Tile>;
type Grid = Vec<Row>;
//Part 1
fn add_row(grid: &mut Grid) {
static TRAPS: [[Tile; 3]; 4] =
[
[Tile::Trapped, Tile::Trapped, Tile::Safe],
[Tile::Safe, Tile::Trapped, Tile::Trapped],
[Tile::Trapped, Tile::Safe, Tile::Safe],
[Tile::Safe, Tile::Safe, Tile::Trapped],
];
let last_row = grid.clone().into_iter().last().unwrap();
//println!("Last row {:?}", last_row);
let mut new_row: Row = vec![];
for idx in 0..last_row.len() {
let mut pre: [Tile; 3] = [Tile::Safe, Tile::Safe, Tile::Safe];
if idx > 0 {
pre[0] = last_row[idx - 1].clone();
}
pre[1] = last_row[idx].clone();
if idx + 1 < last_row.len() {
pre[2] = last_row[idx + 1].clone();
}
if TRAPS.contains(&pre) {
new_row.push(Tile::Trapped);
} else {
new_row.push(Tile::Safe);
}
}
//println!("New row: {:?}", new_row);
grid.push(new_row);
}
fn create_grid(rows: usize) -> Grid {
let first_row: Row =
String::from(".^..^....^....^^.^^.^.^^.^.....^.^..^...^^^^^^.^^^^.^.^^^^^^^.^^^^^..^.^^^.^^..^.^^.^....^.^...^^.^.")
.chars().map(|c| {
match c {
'^' => Tile::Trapped,
_ => Tile::Safe,
}
}).collect::<Row>();
let mut grid: Grid = vec![first_row];
while grid.len() < rows {
add_row(&mut grid);
}
grid
}
// Part 2
fn step_row(last_row: &mut Row) -> i64 {
static TRAPS: [[Tile; 3]; 4] =
[
[Tile::Trapped, Tile::Trapped, Tile::Safe],
[Tile::Safe, Tile::Trapped, Tile::Trapped],
[Tile::Trapped, Tile::Safe, Tile::Safe],
[Tile::Safe, Tile::Safe, Tile::Trapped],
];
let mut new_row: Row = vec![];
let mut safe_tiles = 0;
for idx in 0..last_row.len() {
let mut pre: [Tile; 3] = [Tile::Safe, Tile::Safe, Tile::Safe];
if idx > 0 {
pre[0] = last_row[idx - 1].clone();
}
pre[1] = last_row[idx].clone();
if idx + 1 < last_row.len() {
pre[2] = last_row[idx + 1].clone();
}
if TRAPS.contains(&pre) {
new_row.push(Tile::Trapped);
} else {
new_row.push(Tile::Safe);
safe_tiles = safe_tiles + 1;
}
}
*last_row = new_row;
safe_tiles
}
fn main() {
let grid = create_grid(40);
let total_safe = grid.iter().fold(0, |sum, r| sum + r.iter().filter(|t| **t == Tile::Safe).count());
let total_trap = grid.iter().fold(0, |sum, r| sum + r.iter().filter(|t| **t == Tile::Trapped).count());
println!("Part 1: There are {} safe tiles and {} traps", total_safe, total_trap);
//Need to improve the algorithm so it finishes in a sane amount of time
let mut row: Row =
String::from(".^..^....^....^^.^^.^.^^.^.....^.^..^...^^^^^^.^^^^.^.^^^^^^^.^^^^^..^.^^^.^^..^.^^.^....^.^...^^.^.")
.chars().map(|c| {
match c {
'^' => Tile::Trapped,
_ => Tile::Safe,
}
}).collect::<Row>();
let mut safe_tiles = 48; //from row 1
for _ in 0..400000 - 1 {
safe_tiles = safe_tiles + step_row(&mut row);
}
println!("Part 2: There are {} safe tiles", safe_tiles);
}
| true
|
545012f4c355fa241565f3f8a3c323a1d4a9ff88
|
Rust
|
bokutotu/curs
|
/src/error.rs
|
UTF-8
| 4,563
| 2.765625
| 3
|
[] |
no_license
|
use cublas_sys::cublasStatus_t;
use cuda_runtime_sys::cudaError_t;
use std::ffi::CStr;
use std::fmt::{self, Debug, Display, Formatter, Result};
use std::result;
use thiserror::Error;
pub struct CublasError {
pub raw: cublasStatus_t,
}
fn cublas_error_to_string(error: cublasStatus_t) -> String {
let string = match error {
cublasStatus_t::CUBLAS_STATUS_NOT_INITIALIZED => {
"The cuBLAS library was not initialized. This is usually caused by the lack of a prior cublasCreate() call, an error in the CUDA Runtime API called by the cuBLAS routine, or an error in the hardware setup.
To correct: call cublasCreate() prior to the function call; and check that the hardware, an appropriate version of the driver, and the cuBLAS library are correctly installed."
}
cublasStatus_t::CUBLAS_STATUS_ALLOC_FAILED => {
"Resource allocation failed inside the cuBLAS library. This is usually caused by a cudaMalloc() failure.
To correct: prior to the function call, deallocate previously allocated memory as much as possible."
}
cublasStatus_t::CUBLAS_STATUS_INVALID_VALUE => {
"An unsupported value or parameter was passed to the function (a negative vector size, for example).
To correct: ensure that all the parameters being passed have valid values."
}
cublasStatus_t::CUBLAS_STATUS_ARCH_MISMATCH => {
"The function requires a feature absent from the device architecture; usually caused by compute capability lower than 5.0.
To correct: compile and run the application on a device with appropriate compute capability."
}
cublasStatus_t::CUBLAS_STATUS_MAPPING_ERROR => {
"An access to GPU memory space failed, which is usually caused by a failure to bind a texture.
To correct: prior to the function call, unbind any previously bound textures."
}
cublasStatus_t::CUBLAS_STATUS_EXECUTION_FAILED => {
"The GPU program failed to execute. This is often caused by a launch failure of the kernel on the GPU, which can be caused by multiple reasons.
To correct: check that the hardware, an appropriate version of the driver, and the cuBLAS library are correctly installed."
}
cublasStatus_t::CUBLAS_STATUS_INTERNAL_ERROR => {
"An internal cuBLAS operation failed. This error is usually caused by a cudaMemcpyAsync() failure.
To correct: check that the hardware, an appropriate version of the driver, and the cuBLAS library are correctly installed. Also, check that the memory passed as a parameter to the routine is not being deallocated prior to the routine’s completion."
}
cublasStatus_t::CUBLAS_STATUS_NOT_SUPPORTED => {
"The functionality requested is not supported"
}
cublasStatus_t::CUBLAS_STATUS_LICENSE_ERROR => {
"The functionality requested requires some license and an error was detected when trying to check the current licensing. This error can happen if the license is not present or is expired or if the environment variable NVIDIA_LICENSE_FILE is not set properly."
}
_ => unreachable!(),
};
string.to_string()
}
impl Debug for CublasError {
fn fmt(&self, f: &mut Formatter) -> Result {
let string = cublas_error_to_string(self.raw);
f.debug_struct("cublasError")
.field("error status", &self.raw)
.field("content", &string)
.finish()
}
}
impl Display for CublasError {
fn fmt(&self, f: &mut Formatter) -> Result {
let string = cublas_error_to_string(self.raw);
write!(f, "({})", string)
}
}
pub struct CudaError {
pub raw: cudaError_t,
}
impl Debug for CudaError {
fn fmt(&self, f: &mut Formatter) -> result::Result<(), fmt::Error> {
write!(
f,
"{}",
unsafe { CStr::from_ptr(cuda_runtime_sys::cudaGetErrorString(self.raw)) }
.to_string_lossy()
)
}
}
impl Display for CudaError {
fn fmt(&self, f: &mut Formatter) -> result::Result<(), fmt::Error> {
write!(
f,
"{}",
unsafe { CStr::from_ptr(cuda_runtime_sys::cudaGetErrorString(self.raw)) }
.to_string_lossy()
)
}
}
#[derive(Error, Debug)]
pub enum Error {
#[error("Cuda Error {0}")]
Cuda(CudaError),
#[error("cublas Error {0}")]
Cublas(CublasError),
}
| true
|
ba5f9e5f0e0e9f5dfc7aae99bdb8e3f4bff64182
|
Rust
|
gkbrk/rust-gophermap
|
/src/lib.rs
|
UTF-8
| 7,404
| 3.484375
| 3
|
[
"MIT"
] |
permissive
|
//! gophermap is a Rust crate that can parse and generate Gopher responses.
//! It can be used to implement Gopher clients and servers. It doesn't handle
//! any I/O on purpose. This library is meant to be used by other servers and
//! clients in order to avoid re-implementing the gophermap logic.
//!
#![forbid(unsafe_code)]
use std::io::Write;
/// A single entry in a Gopher map. This struct can be filled in order to
/// generate Gopher responses. It can also be the result of parsing one.
pub struct GopherEntry<'a> {
/// The type of the link
pub item_type: ItemType,
/// The human-readable description of the link. Displayed on the UI.
pub display_string: &'a str,
/// The target page (selector) of the link
pub selector: &'a str,
/// The host for the target of the link
pub host: &'a str,
/// The port for the target of the link
pub port: u16,
}
impl<'a> GopherEntry<'a> {
/// Parse a line into a Gopher directory entry.
/// ```rust
/// use gophermap::GopherEntry;
/// let entry = GopherEntry::from("1Floodgap Home /home gopher.floodgap.com 70\r\n")
/// .unwrap();
/// assert_eq!(entry.selector, "/home");
/// ```
pub fn from(line: &'a str) -> Option<Self> {
let line = {
let mut chars = line.chars();
if !(chars.next_back()? == '\n' && chars.next_back()? == '\r') {
return None;
}
chars.as_str()
};
let mut parts = line.split('\t');
Some(GopherEntry {
item_type: ItemType::from(line.chars().next()?),
display_string: {
let part = parts.next()?;
let (index, _) = part.char_indices().skip(1).next()?;
&part[index..]
},
selector: parts.next()?,
host: parts.next()?,
port: parts.next()?.parse().ok()?,
})
}
/// Serializes a Gopher entry into bytes. This function can be used to
/// generate Gopher responses.
pub fn write<W>(&self, mut buf: W) -> std::io::Result<()>
where
W: Write,
{
write!(
buf,
"{}{}\t{}\t{}\t{}\r\n",
self.item_type.to_char(),
self.display_string,
self.selector,
self.host,
self.port
)?;
Ok(())
}
}
pub struct GopherMenu<W>
where
W: Write,
{
target: W,
}
impl<'a, W> GopherMenu<&'a W>
where
&'a W: Write,
{
pub fn with_write(target: &'a W) -> Self {
GopherMenu { target: &target }
}
pub fn info(&self, text: &str) -> std::io::Result<()> {
self.write_entry(ItemType::Info, text, "FAKE", "fake.host", 1)
}
pub fn error(&self, text: &str) -> std::io::Result<()> {
self.write_entry(ItemType::Error, text, "FAKE", "fake.host", 1)
}
pub fn write_entry(
&self,
item_type: ItemType,
text: &str,
selector: &str,
host: &str,
port: u16,
) -> std::io::Result<()> {
GopherEntry {
item_type,
display_string: text,
selector,
host,
port,
}
.write(self.target)
}
pub fn end(&mut self) -> std::io::Result<()> {
write!(self.target, ".\r\n")
}
}
/// Item type for a Gopher directory entry
#[derive(Debug, PartialEq)]
pub enum ItemType {
/// Item is a file
File,
/// Item is a directory
Directory,
/// Item is a CSO phone-book server
CsoServer,
/// Error
Error,
/// Item is a BinHexed Macintosh file.
BinHex,
/// Item is a DOS binary archive of some sort.
/// Client must read until the TCP connection closes. Beware.
DosBinary,
/// Item is a UNIX uuencoded file.
Uuencoded,
/// Item is an Index-Search server.
Search,
/// Item points to a text-based telnet session.
Telnet,
/// Item is a binary file!
/// Client must read until the TCP connection closes. Beware.
Binary,
/// Item is a redundant server
RedundantServer,
/// Item points to a text-based tn3270 session.
Tn3270,
/// Item is a GIF format graphics file.
Gif,
/// Item is some sort of image file. Client decides how to display.
Image,
/// Informational message
Info,
/// Other types
Other(char),
}
impl ItemType {
/// Parses a char into an Item Type
pub fn from(c: char) -> Self {
match c {
'0' => ItemType::File,
'1' => ItemType::Directory,
'2' => ItemType::CsoServer,
'3' => ItemType::Error,
'4' => ItemType::BinHex,
'5' => ItemType::DosBinary,
'6' => ItemType::Uuencoded,
'7' => ItemType::Search,
'8' => ItemType::Telnet,
'9' => ItemType::Binary,
'+' => ItemType::RedundantServer,
'T' => ItemType::Tn3270,
'g' => ItemType::Gif,
'I' => ItemType::Image,
'i' => ItemType::Info,
c => ItemType::Other(c),
}
}
/// Turns an Item Type into a char
pub fn to_char(&self) -> char {
match self {
ItemType::File => '0',
ItemType::Directory => '1',
ItemType::CsoServer => '2',
ItemType::Error => '3',
ItemType::BinHex => '4',
ItemType::DosBinary => '5',
ItemType::Uuencoded => '6',
ItemType::Search => '7',
ItemType::Telnet => '8',
ItemType::Binary => '9',
ItemType::RedundantServer => '+',
ItemType::Tn3270 => 'T',
ItemType::Gif => 'g',
ItemType::Image => 'I',
ItemType::Info => 'i',
ItemType::Other(c) => *c,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn get_test_pairs() -> Vec<(String, GopherEntry<'static>)> {
let mut pairs = Vec::new();
pairs.push((
"1Floodgap Home /home gopher.floodgap.com 70\r\n".to_owned(),
GopherEntry {
item_type: ItemType::Directory,
display_string: "Floodgap Home",
selector: "/home",
host: "gopher.floodgap.com",
port: 70,
},
));
pairs.push((
"iWelcome to my page FAKE (NULL) 0\r\n".to_owned(),
GopherEntry {
item_type: ItemType::Info,
display_string: "Welcome to my page",
selector: "FAKE",
host: "(NULL)",
port: 0,
},
));
return pairs;
}
#[test]
fn test_parse() {
for (raw, parsed) in get_test_pairs() {
let entry = GopherEntry::from(&raw).unwrap();
assert_eq!(entry.item_type, parsed.item_type);
assert_eq!(entry.display_string, parsed.display_string);
assert_eq!(entry.selector, parsed.selector);
assert_eq!(entry.host, parsed.host);
assert_eq!(entry.port, parsed.port);
}
}
#[test]
fn test_write() {
for (raw, parsed) in get_test_pairs() {
let mut output = Vec::new();
parsed.write(&mut output).unwrap();
let line = String::from_utf8(output).unwrap();
assert_eq!(raw, line);
}
}
}
| true
|
2b767f69ea875614b833ec9e1a0a3fd6e55c467f
|
Rust
|
lRiaXl/public
|
/rust/tests/handling_test/src/main.rs
|
UTF-8
| 1,518
| 3.03125
| 3
|
[] |
no_license
|
use std::fs::{File, OpenOptions};
use std::io::prelude::*;
use std::io::{ErrorKind, Write};
use handling::*;
fn main() {
let path = "a.txt";
File::create(path).unwrap();
open_or_create(path, "content to be written");
let mut file = File::open(path).unwrap();
let mut s = String::new();
file.read_to_string(&mut s).unwrap();
println!("{}", s);
// output: content to be written
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
use std::panic;
fn get_file_content(filename: &str) -> String {
let mut file = File::open(filename).unwrap();
let mut s = String::new();
file.read_to_string(&mut s).unwrap();
fs::remove_file(filename).unwrap();
return s;
}
#[test]
fn test_if_file_exists() {
let filename = "test_existing_file.txt";
let content = "hello world!";
File::create(filename).unwrap();
open_or_create(filename, content);
assert_eq!(content, get_file_content(filename));
}
#[test]
fn test_create_file() {
let file = "no_existing_file.txt";
let content = "hello world!";
open_or_create(file, content);
assert_eq!(content, get_file_content(file));
}
#[test]
fn test_error_case() {
let filename = "hello.txt";
File::create(filename).unwrap();
let mut perms = fs::metadata(filename).unwrap().permissions();
perms.set_readonly(true);
fs::set_permissions(filename, perms).unwrap();
let result = panic::catch_unwind(|| open_or_create(filename, "test"));
fs::remove_file(filename).unwrap();
assert!(result.is_err());
}
}
| true
|
853818ae4a5022d99e5f1716821e20633639d1d7
|
Rust
|
loganyu/leetcode
|
/problems/039_combination_sum.rs
|
UTF-8
| 1,751
| 3.375
| 3
|
[] |
no_license
|
/*
Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order.
The same number may be chosen from candidates an unlimited number of times. Two combinations are unique if the frequency of at least one of the chosen numbers is different.
It is guaranteed that the number of unique combinations that sum up to target is less than 150 combinations for the given input.
Example 1:
Input: candidates = [2,3,6,7], target = 7
Output: [[2,2,3],[7]]
Explanation:
2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times.
7 is a candidate, and 7 = 7.
These are the only two combinations.
Example 2:
Input: candidates = [2,3,5], target = 8
Output: [[2,2,2,2],[2,3,3],[3,5]]
Example 3:
Input: candidates = [2], target = 1
Output: []
Constraints:
1 <= candidates.length <= 30
1 <= candidates[i] <= 200
All elements of candidates are distinct.
1 <= target <= 500
*/
impl Solution {
pub fn combination_sum(candidates: Vec<i32>, target: i32) -> Vec<Vec<i32>> {
let mut combos = vec![];
Self::find_combos(&candidates, &mut vec![], &mut combos, target, 0);
combos
}
fn find_combos(candidates: &Vec<i32>, cans: &mut Vec<i32>, combos: &mut Vec<Vec<i32>>, target: i32, idx: usize) {
if target < 0 {
return;
} else if target == 0 {
combos.push(cans.clone());
return;
}
for i in idx..candidates.len() {
cans.push(candidates[i]);
Self::find_combos(candidates, cans, combos, target - candidates[i], i);
cans.pop();
}
}
}
| true
|
9764428f58e3b7115da7f14af1e85b665bf17c63
|
Rust
|
rennis250/processing-rs
|
/src/transform.rs
|
UTF-8
| 5,690
| 3.109375
| 3
|
[] |
no_license
|
use Screen;
use {Matrix4, Vector3, Unit};
impl<'a> Screen<'a> {
/// Pre-multiply the current MVP transformation matrix with a matrix formed
/// from the given values.
pub fn apply_matrix(
&mut self,
n00: f32,
n01: f32,
n02: f32,
n03: f32,
n10: f32,
n11: f32,
n12: f32,
n13: f32,
n20: f32,
n21: f32,
n22: f32,
n23: f32,
n30: f32,
n31: f32,
n32: f32,
n33: f32,
) {
let m = Matrix4::new(
n00,
n01,
n02,
n03,
n10,
n11,
n12,
n13,
n20,
n21,
n22,
n23,
n30,
n31,
n32,
n33,
);
self.matrices.curr_matrix = m * self.matrices.curr_matrix;
}
/// Remove the current MVP transformation matrix from the stack and use the most
/// recently used one instead.
pub fn pop_matrix(&mut self) {
match self.matrices.matrix_stack.pop() {
Some(m) => self.matrices.curr_matrix = m,
None => {
self.matrices.curr_matrix = Matrix4::identity();
}
};
}
/// Push the current MVP transformation matrix onto the stack, so that it can be
/// saved for later. Useful for when you want to temporarily apply some rotation
/// or translation to a single object and don't want to disturb the rest of the
/// scene.
pub fn push_matrix(&mut self) {
self.matrices.matrix_stack.push(self.matrices.curr_matrix);
}
/// Remove the current MVP transfomation matrix and set it to the standard 4x4
/// identity matrix.
pub fn reset_matrix(&mut self) {
self.matrices.curr_matrix = Matrix4::identity();
}
/// Pre-multiply the current MVP transformation matrix by a rotation matrix which
/// is derived from a rotation angle about a vector in the direction (x, y, z).
pub fn rotate(&mut self, angle: f32, x: f32, y: f32, z: f32) {
// let m = Matrix4::new(
// angle.cos(),
// -angle.sin(),
// 0.,
// 0.,
// angle.sin(),
// angle.cos(),
// 0.,
// 0.,
// 0.,
// 0.,
// 1.,
// 0.,
// 0.,
// 0.,
// 0.,
// 1.,
// );
let m = Matrix4::from_axis_angle(&Unit::new_unchecked(Vector3::new(x, y, z)), angle);
self.matrices.curr_matrix = m * self.matrices.curr_matrix;
}
/// Apply a rotation matrix for a given angle around the x-axis to the current MVP
/// transformation matrix.
pub fn rotate_x(&mut self, angle: f32) {
let m = Matrix4::from_axis_angle(&Unit::new_unchecked(Vector3::new(1., 0., 0.)), angle);
self.matrices.curr_matrix = m * self.matrices.curr_matrix;
}
/// Apply a rotation matrix for a given angle around the y-axis to the current MVP
/// transformation matrix.
pub fn rotate_y(&mut self, angle: f32) {
let m = Matrix4::from_axis_angle(&Unit::new_unchecked(Vector3::new(0., 1., 0.)), angle);
self.matrices.curr_matrix = m * self.matrices.curr_matrix;
}
/// Apply a rotation matrix for a given angle around the z-axis to the current MVP
/// transformation matrix.
pub fn rotate_z(&mut self, angle: f32) {
let m = Matrix4::from_axis_angle(&Unit::new_unchecked(Vector3::new(0., 0., 1.)), angle);
self.matrices.curr_matrix = m * self.matrices.curr_matrix;
}
/// Scale the scene along the x-, y-, and z-axes by applying a matrix derived from
/// these values to the current MVP transformation matrix.
pub fn scale(&mut self, x: f32, y: f32, z: f32) {
// let m = Matrix4::new(x, 0., 0., 0., 0., y, 0., 0., 0., 0., z, 0., 0., 0., 0., 1.);
self.matrices.curr_matrix.append_nonuniform_scaling(
&Vector3::new(x, y, z),
); //* self.matrices.curr_matrix;
}
/// Derive a matrix that applies shear for a given angle the scene about the x-axis
/// and apply it to the current MVP transformation matrix.
pub fn shear_x(&mut self, angle: f32) {
let m = Matrix4::new(
1.,
angle.tan(),
0.,
0.,
0.,
1.,
0.,
0.,
0.,
0.,
1.,
0.,
0.,
0.,
0.,
1.,
);
self.matrices.curr_matrix = m * self.matrices.curr_matrix;
}
/// Derive a matrix that applies shear for a given angle the scene about the y-axis
/// and apply it to the current MVP transformation matrix.
pub fn shear_y(&mut self, angle: f32) {
let m = Matrix4::new(
1.,
0.,
0.,
0.,
angle.tan(),
1.,
0.,
0.,
0.,
0.,
1.,
0.,
0.,
0.,
0.,
1.,
);
self.matrices.curr_matrix = m * self.matrices.curr_matrix;
}
/// Derive a translation matrix from the given (x, y, z) vector and apply it to the
/// current MVP transformation matrix.
pub fn translate(&mut self, x: f32, y: f32, z: f32) {
let m = Matrix4::new(1., 0., 0., x, 0., 1., 0., y, 0., 0., 1., z, 0., 0., 0., 1.);
self.matrices.curr_matrix = m * self.matrices.curr_matrix;
}
/// Print out the current MVP transformation matrix.
pub fn print_matrix(&self) {
println!("{:?}", self.matrices.curr_matrix);
}
}
| true
|
12d236367ef244f322b7b6bd11d856b60a1b6374
|
Rust
|
fplust/rlox
|
/src/main.rs
|
UTF-8
| 1,939
| 2.578125
| 3
|
[] |
no_license
|
mod error;
mod expr;
mod parser;
mod scanner;
mod token;
mod tokentype;
// mod ast_printer;
mod environment;
mod interpreter;
mod lox_class;
mod lox_function;
mod lox_instance;
mod object;
mod resolver;
mod stmt;
// use crate::ast_printer::AstPrinter;
use crate::interpreter::Interpreter;
use crate::parser::Parser;
use crate::resolver::Resolver;
use crate::scanner::Scanner;
use std::env;
use std::fs::File;
use std::io::prelude::*;
use std::io::{self, BufReader};
fn main() {
let args: Vec<String> = env::args().collect();
println!("{:?}", args);
let args_len: usize = args.len();
if args_len > 2 {
println!("Usage: lox [script]");
} else if args_len == 2 {
run_file(&args[1]);
} else {
run_prompt();
}
}
fn run_file(path: &str) {
match File::open(path) {
Err(e) => println!("{:?}", e),
Ok(file) => {
let mut buf_reader = BufReader::new(file);
let mut s: String = String::from("");
buf_reader.read_to_string(&mut s).unwrap();
run(&s);
}
}
}
fn run_prompt() {
let stdin = io::stdin();
let mut stdout = io::stdout();
let mut buf_reader = BufReader::new(stdin);
loop {
print!("> ");
stdout.flush().unwrap();
let mut line: String = String::from("");
buf_reader.read_line(&mut line).unwrap();
run(&line);
}
}
fn run(source: &String) {
let mut scanner = Scanner::new(source);
let tokens = scanner.scan_tokens();
// for token in tokens {
// println!("{}", token);
// }
let mut parser = Parser::new(tokens);
let statements = parser.parse().expect("Error");
// let printer = AstPrinter {};
// println!("{}", printer.print(&expr));
let mut interpreter = Interpreter::new();
let mut resolver = Resolver::new(&mut interpreter);
resolver.resolves(&statements);
interpreter.interpret(statements);
}
| true
|
b5af8f9041f17ae6b77bc3f6bf4ef7176e48d52d
|
Rust
|
tramulns/benchmark-memory
|
/benchmark_cpu_cache_levels/src/lib.rs
|
UTF-8
| 1,057
| 2.65625
| 3
|
[] |
no_license
|
#![feature(test)]
#[allow(dead_code)]
const KB: usize = 1024;
#[allow(dead_code)]
const MB: usize = KB * KB;
#[allow(dead_code)]
const N: usize = 16 * MB;
#[cfg(test)]
mod tests {
use super::*;
extern crate test;
use test::Bencher;
#[bench]
fn bench_calc_2048kb_array(b: &mut Bencher) {
let mut data = vec![0_u8; KB * 2048];
let mask = data.len() - 1;
b.iter(|| {
for i in 0..N {
data[(i * 64) & mask] += 1;
}
});
}
#[bench]
fn bench_calc_4096kb_array(b: &mut Bencher) {
let mut data = vec![0_u8; KB * 4096];
let mask = data.len() - 1;
b.iter(|| {
for i in 0..N {
data[(i * 64) & mask] += 1;
}
});
}
#[bench]
fn bench_calc_6144kb_array(b: &mut Bencher) {
let mut data = vec![0_u8; KB * 6144];
let mask = data.len() - 1;
b.iter(|| {
for i in 0..N {
data[(i * 64) & mask] += 1;
}
});
}
}
| true
|
be21e70db1ad07f2956d7930c5810a9072dc93d3
|
Rust
|
sb89/fixerio
|
/src/exchange.rs
|
UTF-8
| 5,318
| 3.125
| 3
|
[
"MIT"
] |
permissive
|
/// The response from fixerio.
#[derive(Debug, Deserialize)]
pub struct Exchange {
/// The base currency requested.
pub base: String,
/// The date for which the exchange rates are for.
pub date: String,
/// The exhcange rates for the base currency.
pub rates: Rates,
}
/// The exchange rates for the base currency within the response.
#[derive(Debug, Deserialize)]
pub struct Rates {
/// Australian dollar
#[serde(rename = "AUD", default)]
pub aud: f32,
/// Bulgarian lev
#[serde(rename = "BGN", default)]
pub bgn: f32,
/// Brazilian real
#[serde(rename = "BRL", default)]
pub brl: f32,
#[serde(rename = "CAD", default)]
/// Canadian dollar
pub cad: f32,
#[serde(rename = "CHF", default)]
/// Swiss franc
pub chf: f32,
/// Chinese yuan
#[serde(rename = "CNY", default)]
pub cny: f32,
/// Czech koruna
#[serde(rename = "CZK", default)]
pub czk: f32,
/// Danish krone
#[serde(rename = "DKK", default)]
pub dkk: f32,
/// Euro
#[serde(rename = "EUR", default)]
pub eur: f32,
/// Pound sterling
#[serde(rename = "GBP", default)]
pub gbp: f32,
/// Hong Kong dollar
#[serde(rename = "HKD", default)]
pub hkd: f32,
/// Croatian kuna
#[serde(rename = "HRK", default)]
pub hrk: f32,
/// Hungarian forint
#[serde(rename = "HUF", default)]
pub huf: f32,
/// Indonesian rupiah
#[serde(rename = "IDR", default)]
pub idr: f32,
/// Israeli new shekel
#[serde(rename = "ILS", default)]
pub ils: f32,
/// Indian rupee
#[serde(rename = "INR", default)]
pub inr: f32,
/// Japanese yen
#[serde(rename = "JPY", default)]
pub jpy: f32,
/// South Korean won
#[serde(rename = "KRW", default)]
pub krw: f32,
/// Mexican peso
#[serde(rename = "MXN", default)]
pub mxn: f32,
/// Malasyian ringgit
#[serde(rename = "MYR", default)]
pub myr: f32,
/// Norwegian krone
#[serde(rename = "NOK", default)]
pub nok: f32,
/// New Zealand dollar
#[serde(rename = "NZD", default)]
pub nzd: f32,
/// Philippine peso
#[serde(rename = "PHP", default)]
pub php: f32,
/// Polish złoty
#[serde(rename = "PLN", default)]
pub pln: f32,
/// Romanian leu
#[serde(rename = "RON", default)]
pub ron: f32,
/// Russian ruble
#[serde(rename = "RUB", default)]
pub rub: f32,
/// Swedish krona
#[serde(rename = "SEK", default)]
pub sek: f32,
/// Singapore dollar
#[serde(rename = "SGD", default)]
pub sgd: f32,
/// Thai baht
#[serde(rename = "THB", default)]
pub thb: f32,
/// Turkish lira
#[serde(rename = "TRY", default)]
pub try: f32,
/// United States dollar
#[serde(rename = "USD", default)]
pub usd: f32,
/// South African rand
#[serde(rename = "ZAR", default)]
pub zar: f32
}
/// Fixerio currency.
#[derive(Debug, PartialEq)]
pub enum Currency {
/// Australian dollar
AUD,
/// Bulgarian lev
BGN,
/// Brazilian real
BRL,
/// Canadian dollar
CAD,
/// Swiss franc
CHF,
/// Chinese yuan
CNY,
/// Czech koruna
CZK,
/// Danish krone
DKK,
/// Euro
EUR,
/// Pound sterling
GBP,
/// Hong Kong dollar
HKD,
/// Croatian kuna
HRK,
/// Hungarian forint
HUF,
/// Indonesian rupiah
IDR,
/// Israeli new shekel
ILS,
/// Indian rupee
INR,
/// Japanese yen
JPY,
/// South Korean won
KRW,
/// Mexican peso
MXN,
/// Malasyian ringgit
MYR,
/// Norwegian krone
NOK,
/// New Zealand dollar
NZD,
/// Philippine peso
PHP,
/// Polish złoty
PLN,
/// Romanian leu
RON,
/// Russian ruble
RUB,
/// Swedish krona
SEK,
/// Singapore dollar
SGD,
/// Thai baht
THB,
/// Turkish lira
TRY,
/// United States dollar
USD,
/// South African rand
ZAR,
}
impl Currency {
/// Return the string representation.
pub fn string(&self) -> &str {
match *self {
Currency::AUD => "AUD",
Currency::BGN => "BGN",
Currency::BRL => "BRL",
Currency::CAD => "CAD",
Currency::CHF => "CHF",
Currency::CNY => "CNY",
Currency::CZK => "CZK",
Currency::DKK => "DKK",
Currency::EUR => "EUR",
Currency::GBP => "GBP",
Currency::HKD => "HKD",
Currency::HRK => "HRK",
Currency::HUF => "HUF",
Currency::IDR => "IDR",
Currency::ILS => "ILS",
Currency::INR => "INR",
Currency::JPY => "JPY",
Currency::KRW => "KRW",
Currency::MXN => "MXN",
Currency::MYR => "MYR",
Currency::NOK => "NOK",
Currency::NZD => "NZD",
Currency::PHP => "PHP",
Currency::PLN => "PLN",
Currency::RON => "RON",
Currency::RUB => "RUB",
Currency::SEK => "SEK",
Currency::SGD => "SGD",
Currency::THB => "THB",
Currency::TRY => "TRY",
Currency::USD => "USD",
Currency::ZAR => "ZAR"
}
}
}
| true
|
d6bce0e50164ea12f0582d985617da83d365deac
|
Rust
|
hhawkens/advent_2018
|
/src/day_3/types.rs
|
UTF-8
| 307
| 3.125
| 3
|
[] |
no_license
|
#[derive(Debug)]
pub struct Rect {
pub location: Point,
pub size: Size,
}
#[derive(Debug, PartialEq, Eq, Hash)]
pub struct Point {
/// To the right
pub x: i32,
/// Down
pub y: i32,
}
#[derive(Debug)]
pub struct Size {
/// Width
pub w: i32,
/// Height
pub h: i32,
}
| true
|
19fe4a2a4dc0b8b479741fd7b037a5f5a86ff35f
|
Rust
|
popovegor/codeforces
|
/828B/rust/src/main.rs
|
UTF-8
| 1,572
| 2.9375
| 3
|
[] |
no_license
|
fn main() {
use std::io;
use std::io::prelude::*;
use std::cmp;
let stdin = io::stdin();
let mut counter = 0;
let mut w = 0;
let mut h = 0;
let (mut left, mut right, mut bottom, mut top) = (100,1,1,100);
let mut black_counter = 0;
let mut white_counter = 0;
for line in stdin.lock().lines() {
if counter == 0 {
let l = line.unwrap();
let mut l1 = l.split(" ");
h = l1.next().unwrap().parse::<i32>().unwrap();
w = l1.next().unwrap().parse::<i32>().unwrap();
// println!("w{:?} - h{:?}", w, h);
} else {
let l = line.unwrap_or(String::default());
let mut chars = l.chars();
let mut i = 0;
while let Some(ch) = chars.next() {
i += 1;
if ch == 'B' {
black_counter += 1;
left = cmp::min(left, i);
top = cmp::min(counter, top);
right = cmp::max(right, i);
bottom = cmp::max(bottom, counter);
} else {
white_counter += 1;
}
// println!("c{:?} i{:?} {:?}", counter, i, ch);
}
// println!("{:?}", l);
}
counter += 1;
}
if black_counter == 0 && white_counter > 0 {
println!("{:?}", 1);
} else {
let square_side_len = cmp::max((right - left + 1), (bottom - top + 1));
let black_needed = square_side_len * square_side_len - black_counter;
if black_needed < 0 || (black_needed + black_counter) > w*h || square_side_len > w || square_side_len > h {
println!("{:?}", -1);
} else {
println!("{:?}", black_needed);
}
}
// println!("{:?} {:?} {:?} {:?}", right, left, bottom, top);
}
| true
|
deaa1dd2e72f9a3791c19761bbbeab576028b47b
|
Rust
|
TheButlah/mujoco-rs
|
/mujoco/src/lib.rs
|
UTF-8
| 3,918
| 2.5625
| 3
|
[
"MIT"
] |
permissive
|
//! Provides safe bindings to [MuJoCo](http://www.mujoco.org/index.html), a physics
//! simulator commonly used for robotics and machine learning.
pub mod model;
mod re_exports;
pub mod state;
mod vfs;
pub use model::Model;
pub use state::State;
use lazy_static::lazy_static;
use std::cell::RefCell;
use std::ffi::{CStr, CString};
pub(crate) mod helpers;
lazy_static! {
/// The location of the MuJoCo key
///
/// By default this is ~/.mujoco/mjkey.txt, but can be overriden via the
/// `MUJOCO_RS_KEY_LOC` environment variable
pub static ref KEY_LOC: String = match std::env::var("MUJOCO_RS_KEY_LOC") {
Ok(loc) => loc,
Err(std::env::VarError::NotPresent) => dirs::home_dir()
.expect(
"Could not find home directory when attempting to use default mujoco key \
location. Consider setting `MUJOCO_RS_KEY_LOC`."
)
.join(".mujoco").join("mjkey.txt").to_str().unwrap().to_owned(),
Err(std::env::VarError::NotUnicode(_)) => panic!("`MUJOCO_RS_KEY_LOC` must be unicode!")
};
}
// Using a thread-local VFS is how we enable the use of temporary VFS objects in
// a global storage without accidentally getting filename collisions or thread
// safety issues. The RefCell is there to allow us to mutate safely (it could
// probably be mutated via unsafe code everywhere but that is a minor speed
// improvement for many unsafe LOC)
thread_local! {
static VFS: RefCell<vfs::Vfs> = RefCell::new(vfs::Vfs::new());
}
/// Activates MuJoCo using the default key [`KEY_LOC`]
///
/// [`KEY_LOC`]: struct.KEY_LOC.html
pub fn activate() {
let s: &str = &KEY_LOC;
activate_from_str(s)
}
/// Deactivates MuJoCo
///
/// Note that this globally deactivates MuJoCo, so make sure sure that other
/// code doesn't expect it to be activated when this is called
pub fn deactivate() {
unsafe { mujoco_sys::mj_deactivate() }
}
/// Activates MuJoCo from a the key's filepath
///
/// # Panics
/// Panics if there is an error getting the mujoco key
pub fn activate_from_str(key_loc: impl AsRef<str>) {
let key_loc = CString::new(key_loc.as_ref()).unwrap();
activate_from_cstr(key_loc)
}
/// Activates MuJoCo from a the key's filepath as a c-style string
///
/// # Panics
/// Panics if there is an error getting the mujoco key
pub fn activate_from_cstr(key_loc: impl AsRef<CStr>) {
let key_loc = key_loc.as_ref();
let activate_result;
unsafe {
activate_result = mujoco_sys::mj_activate(key_loc.as_ptr());
}
if activate_result != 1 {
unreachable!("If activation fails, mujoco calls error handler and terminates.")
}
}
#[cfg(test)]
mod tests {
use lazy_static::lazy_static;
use std::ffi::CString;
lazy_static! {
pub(crate) static ref PKG_ROOT: std::path::PathBuf =
std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.canonicalize()
.expect("Could not resolve absolute path for package root!");
pub(crate) static ref SIMPLE_XML_PATH: std::path::PathBuf =
PKG_ROOT.join("tests").join("res").join("simple.xml");
pub(crate) static ref SIMPLE_XML: &'static str = r#"
<mujoco>
<worldbody>
<light name="light0" diffuse=".5 .5 .5" pos="0 0 3" dir="0 0 -1"/>
<geom name="geom0" type="plane" size="1 1 0.1" rgba=".9 0 0 1"/>
<body name="body1" pos="0 0 1">
<joint name="joint0" type="free"/>
<geom name="geom1" type="box" size=".1 .2 .3" rgba="0 .9 0 1"/>
</body>
</worldbody>
</mujoco>"#;
}
#[test]
fn activate() {
let s: &str = &super::KEY_LOC;
super::activate();
super::activate_from_str(s);
super::activate_from_cstr(CString::new(s).unwrap());
}
}
| true
|
5eb7cb64fc6ada724c5cb5ad419eb06d0161abad
|
Rust
|
chinatsu/oo-workshop
|
/src/chance/chance_test.rs
|
UTF-8
| 2,401
| 3.09375
| 3
|
[] |
no_license
|
use super::{Chance, ChanceError};
lazy_static! {
static ref CERTAIN: Chance = Chance::new(super::CERTAIN).unwrap();
static ref LIKELY: Chance = Chance::new(0.75).unwrap();
static ref FIFTY_NINE: Chance = Chance::new(0.59).unwrap();
static ref EQUALLY_LIKELY: Chance = Chance::new(0.5).unwrap();
static ref FORTY_ONE: Chance = Chance::new(0.41).unwrap();
static ref UNLIKELY: Chance = Chance::new(0.25).unwrap();
static ref IMPOSSIBLE: Chance = Chance::new(0.0).unwrap();
}
#[test]
fn the_chance_of_25_should_be_ok() {
assert!(Chance::new(0.25).is_ok());
}
#[test]
fn the_chance_of_130_should_be_out_of_bounds() {
assert_eq!(Err(ChanceError::OutOfBounds), Chance::new(1.30));
}
#[test]
fn the_chance_of_minus_10_should_be_out_of_bounds() {
assert_eq!(Err(ChanceError::OutOfBounds), Chance::new(-0.1));
}
#[test]
fn the_chance_of_75_should_equal_likely() -> Result<(), ChanceError> {
assert_eq!(*LIKELY, Chance::new(0.75)?);
Ok(())
}
#[test]
fn the_chance_of_75_should_not_equal_the_chance_of_25() {
assert_ne!(*UNLIKELY, *LIKELY);
}
#[test]
fn the_opposite_of_100_should_be_0() {
assert_eq!(*IMPOSSIBLE, !*CERTAIN);
}
#[test]
fn the_opposite_of_75_should_be_25() {
assert_eq!(*UNLIKELY, !*LIKELY);
}
#[test]
fn the_opposite_of_the_opposite_of_41_should_be_41() {
assert_eq!(*FORTY_ONE, !!*FORTY_ONE);
}
#[test]
fn the_opposite_of_the_opposite_of_the_opposite_of_41_should_be_59() {
assert_eq!(*FIFTY_NINE, !!!*FORTY_ONE);
}
#[test]
fn chances_with_values_41_and_50_together_should_be_20_5() {
assert_eq!(Chance::new(0.205).unwrap(), *FORTY_ONE & *EQUALLY_LIKELY);
}
#[test]
fn chances_with_values_13_and_0_together_should_be_0() {
assert_eq!(*IMPOSSIBLE, *FIFTY_NINE & *IMPOSSIBLE);
}
#[test]
fn chances_with_values_100_and_75_and_50_together_should_be_3_75() -> Result<(), ChanceError> {
assert_eq!(Chance::new(0.375)?, *CERTAIN & *LIKELY & *EQUALLY_LIKELY);
Ok(())
}
#[test]
fn chances_of_75_or_75_should_be_93_75() -> Result<(), ChanceError> {
assert_eq!(Chance::new(0.9375)?, *LIKELY | *LIKELY);
Ok(())
}
#[test]
fn sequence_of_4_chances_of_75_should_be_99_609375() -> Result<(), ChanceError> {
assert_eq!(Chance::new(0.99609375)?, *LIKELY | *LIKELY | *LIKELY | *LIKELY);
Ok(())
}
#[test]
fn chances_of_100_or_75_should_be_100() {
assert_eq!(*CERTAIN, *CERTAIN | *UNLIKELY);
}
| true
|
c39148bf9a189c3f29f336de12cf1d4b50c29ccc
|
Rust
|
rk9109/sandbox-api
|
/src/main.rs
|
UTF-8
| 494
| 2.546875
| 3
|
[] |
no_license
|
// TODO convert to REST API
mod command;
mod sandbox;
use command::Language;
use sandbox::Sandbox;
const TEST_C_CODE: &'static str = r#"
#include <stdio.h>
int main() {
for (int i = 0; i < 10; i++) {
printf("%d\n", i);
}
return 0;
}
"#;
fn main() {
let output = Sandbox::new(TEST_C_CODE, Language::C)
.expect("Failed to construct sandbox")
.output()
.expect("Failed to execute");
println!("STDOUT:\n{}", output.execute_output.stdout);
}
| true
|
ac35012aa407d9854482267fa63f9b93b3688bba
|
Rust
|
akovaski/AdventOfCode
|
/2018/src/year2018/d10p1.rs
|
UTF-8
| 3,215
| 3.03125
| 3
|
[] |
no_license
|
use regex::Regex;
use std::cmp;
use std::collections::{HashSet, VecDeque};
use std::fs::File;
use std::io;
use std::io::prelude::*;
use std::io::BufReader;
pub struct Light {
pub pos: Vector,
pub vel: Vector,
}
#[derive(Clone, Copy, Eq, PartialEq, Hash)]
pub struct Vector {
pub x: i32,
pub y: i32,
}
pub fn main() -> io::Result<()> {
let f = File::open("./input/day10.txt")?;
let mut reader = BufReader::new(f);
let re =
Regex::new(r"^position=< ?(-?\d+), ?(-?\d+)> velocity=< ?(-?\d+), ?(-?\d+)>$").unwrap();
let lights: Vec<_> = reader
.by_ref()
.lines()
.map(|l| {
let line = l.unwrap();
let line_ref = line.trim().as_ref();
let cap = re.captures(line_ref).unwrap();
let x_pos: i32 = cap[1].parse().unwrap();
let y_pos: i32 = cap[2].parse().unwrap();
let x_vel: i32 = cap[3].parse().unwrap();
let y_vel: i32 = cap[4].parse().unwrap();
Light {
pos: Vector { x: x_pos, y: y_pos },
vel: Vector { x: x_vel, y: y_vel },
}
})
.collect();
let mut prev_dev = VecDeque::new();
for t in 0.. {
let sim = simulate_movement(&lights, t);
let y_avg: i32 = sim.iter().map(|l| l.pos.y).sum::<i32>() / sim.len() as i32;
let y_dev = sim
.iter()
.map(|l| {
let dev = y_avg - l.pos.y;
dev.abs()
})
.sum::<i32>();
if prev_dev.len() > 6 {
prev_dev.pop_front();
let rolling_dev =
prev_dev.iter().map(|av: &(i32, i32)| av.1).sum::<i32>() / prev_dev.len() as i32;
if y_dev > rolling_dev {
break;
}
}
prev_dev.push_back((t, y_dev));
}
let min_dev = prev_dev.iter().min_by_key(|(_, dev)| dev).unwrap();
let sim = simulate_movement(&lights, min_dev.0);
print_lights(&sim);
Ok(())
}
fn print_lights(lights: &Vec<Light>) {
let (min, max) = lights
.iter()
.fold((lights[0].pos, lights[0].pos), |(mut min, mut max), l| {
//let (min, max) = (min, max);
min.x = cmp::min(min.x, l.pos.x);
min.y = cmp::min(min.y, l.pos.y);
max.x = cmp::max(max.x, l.pos.x);
max.y = cmp::max(max.y, l.pos.y);
(min, max)
});
let mut light_set = HashSet::new();
for l in lights {
light_set.insert(l.pos);
}
for y in min.y..=max.y {
for x in min.x..=max.x {
let disp_char = match light_set.get(&Vector { x, y }) {
Some(_) => '#',
None => '.',
};
print!("{}", disp_char);
}
println!();
}
}
pub fn simulate_movement(lights: &Vec<Light>, time: i32) -> Vec<Light> {
lights
.iter()
.map(|l| Light {
pos: Vector {
x: l.pos.x + l.vel.x * time,
y: l.pos.y + l.vel.y * time,
},
vel: Vector {
x: l.vel.x,
y: l.vel.y,
},
})
.collect()
}
| true
|
97da531d9ce4814033a7e71857f6c08bc0d22b83
|
Rust
|
Indy2222/introns
|
/preprocess/src/samples/io.rs
|
UTF-8
| 6,475
| 2.75
| 3
|
[] |
no_license
|
use crate::features::FeatureId;
use anyhow::{Context, Error, Result};
use ncrs::data::Symbol;
use ndarray::{arr0, Array, Array2};
use ndarray_npy::NpzWriter;
use std::convert::TryFrom;
use std::fs::{self, File, OpenOptions};
use std::path::{Path, PathBuf};
pub struct OrganismWriter {
target_dir: PathBuf,
counter: u64,
path_writer: csv::Writer<File>,
}
impl OrganismWriter {
pub fn with_target_dir<P: AsRef<Path>>(target_dir: P, organism_id: &str) -> Result<Self> {
let mut target_dir = target_dir.as_ref().to_path_buf();
target_dir.push(organism_id);
if !target_dir.exists() {
fs::create_dir(&target_dir).context(format!(
"Failed to create directory for samples of organism {}",
organism_id
))?;
}
let path_writer = {
let mut csv_path = target_dir.clone();
csv_path.push("samples.csv");
let create_file = !csv_path.exists();
let file = OpenOptions::new()
.create(create_file)
.append(true)
.open(&csv_path)
.with_context(|| {
format!("Failed to create samples CSV file {}", csv_path.display())
})?;
let mut path_writer = csv::WriterBuilder::new().from_writer(file);
if create_file {
path_writer.serialize((
"path",
"is_positive",
"sample_type_name",
"feature_id",
"absolute_position",
"scaffold_name",
))?;
}
path_writer
};
Ok(Self {
target_dir,
path_writer,
counter: 0,
})
}
/// Store a new sample to disk.
///
/// # Arguments
///
/// * `sequence` - input sequence to be stored in the sample.
///
/// * `relative_position` - 0-based position of splice-site within the sequence.
pub fn write(
&mut self,
sequence: &[Symbol],
is_positive: bool,
sample_type_name: &str,
relative_position: usize,
absolute_position: usize,
feature_id: Option<FeatureId>,
scaffold_name: &str,
) -> Result<()> {
let relative_sample_path = self.relative_sample_path(is_positive, sample_type_name);
let mut target_file_path = self.target_dir.clone();
target_file_path.push(&relative_sample_path);
{
let target_sub_dir = target_file_path.parent().unwrap();
fs::create_dir_all(&target_sub_dir).with_context(|| {
format!(
"Failed to create samples directory {}",
target_sub_dir.display()
)
})?;
}
let input = sequence_to_one_hot(&sequence);
let output = arr0(if is_positive { 1.0 } else { 0.0 });
{
let file = File::create(&target_file_path).context("Failed to store a sample")?;
let mut npz_writer = NpzWriter::new_compressed(file);
let error_context = || {
format!(
"Error while writing to target file {}",
target_file_path.display()
)
};
if relative_position > sequence.len() {
panic!("Relative splice-site position out of sequence bounds.");
}
let relative_position = arr0(
u64::try_from(relative_position)
.context("Splice-site position cannot be serialized")?,
);
npz_writer
.add_array("position", &relative_position)
.with_context(error_context)?;
npz_writer
.add_array("input", &input)
.with_context(error_context)?;
npz_writer
.add_array("output", &output)
.with_context(error_context)?;
}
self.write_path(
&relative_sample_path,
is_positive,
sample_type_name,
feature_id,
absolute_position,
scaffold_name,
)?;
self.counter += 1;
Ok(())
}
fn write_path(
&mut self,
relative_path: &Path,
is_positive: bool,
sample_type_name: &str,
feature_id: Option<FeatureId>,
absolute_position: usize,
scaffold_name: &str,
) -> Result<()> {
if relative_path.is_absolute() {
panic!(
"Relative sample path expected, got absolute path: {}",
relative_path.display()
);
}
let feature_id = match feature_id {
Some(feature_id) => feature_id.to_hex(),
None => String::new(),
};
let absolute_position = format!("{}", absolute_position);
self.path_writer
.serialize((
relative_path
.to_str()
.expect("Failed to serialize sample path as a UTF-8 string."),
format!("{}", is_positive),
sample_type_name,
feature_id,
absolute_position,
scaffold_name,
))
.map_err(Error::new)
}
fn relative_sample_path(&self, is_positive: bool, sample_type_name: &str) -> PathBuf {
let mut relative_path = PathBuf::new();
relative_path.push(format!("{:04}", self.counter >> 16));
relative_path.push(format!("{:03}", (self.counter >> 8) & 0xff));
let mut file_name = String::new();
if is_positive {
file_name.push_str("positive_");
} else {
file_name.push_str("negative_");
}
file_name.push_str(sample_type_name);
file_name.push_str(&format!("_{:03}.npz", self.counter & 0xff));
relative_path.push(file_name);
relative_path
}
}
/// Create a one-hot-encoded 2D array of a sequence. First dimension
/// represents individual sequence positions and second dimension represents
/// one-hot-encoding.
fn sequence_to_one_hot(sequence: &[Symbol]) -> Array2<f32> {
let mut input = Array::zeros((sequence.len(), 5));
for (i, symbol) in sequence.iter().enumerate() {
let pos: usize = (*symbol).into();
input[(i, pos)] = 1.;
}
input
}
| true
|
bd343b0c2338bee0b60f4e0baa7c43e2e41e35db
|
Rust
|
NyxTo/Advent-of-Code
|
/2019/Code/day_10_asteroid.rs
|
UTF-8
| 1,473
| 2.921875
| 3
|
[] |
no_license
|
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::cmp::{min, max};
fn gcd(mut a: usize, mut b: usize) -> usize {
while b > 0 {
let rem = a % b;
a = b;
b = rem;
}
a
}
fn main() {
let grid = BufReader::new(File::open("in_10.txt").unwrap()).lines().map(|row| row.unwrap().chars().collect::<Vec<_>>()).collect::<Vec<_>>();
let (hgt, wid, mut max_det, mut vapour) = (grid.len(), grid[0].len(), 0, (0, 0));
for sy in 0..hgt {
for sx in 0..wid {
if grid[sy][sx] == '#' {
let (mut detect, mut btwn, mut aster, mut ang) = (0, vec![vec![0; wid]; hgt], vec![], vec![vec![0.; wid]; hgt]);
for ey in 0..hgt {
for ex in 0..wid {
if grid[ey][ex] == '#' {
if ex == sx && ey == sy { continue; }
let num = gcd(max(sx, ex) - min(sx, ex), max(sy, ey) - min(sy, ey));
btwn[ey][ex] = (1..num).filter(|i| {
let (bx, by) = ((sx * (num - i) + ex * i) / num, (sy * (num - i) + ey * i) / num);
grid[by][bx] == '#'
}).count();
if btwn[ey][ex] == 0 { detect += 1; }
aster.push((ex, ey));
ang[ey][ex] = (ex as f64 - sx as f64).atan2(ey as f64 - sy as f64);
}
}
}
if detect >= max_det {
max_det = detect;
aster.sort_by(|(x1, y1), (x2, y2)| ang[*y2][*x2].partial_cmp(&ang[*y1][*x1]).unwrap());
aster.sort_by_key(|(x, y)| btwn[*y][*x]);
vapour = aster[199];
}
}
}
}
println!("Part A: {}", max_det); // 221
println!("Part B: {}", vapour.0 * 100 + vapour.1); // 806
}
| true
|
fb77b7aa24d2d3bd97c7f147c149665782414c1d
|
Rust
|
algon-320/mandarin
|
/kernel/src/global.rs
|
UTF-8
| 1,247
| 2.546875
| 3
|
[] |
no_license
|
use crate::console::{Attribute, Console};
use crate::graphics::{font, FrameBuffer, Scaled};
use crate::sync::spin::SpinMutex;
use core::mem::MaybeUninit;
pub static FRAME_BUF: SpinMutex<MaybeUninit<Scaled<FrameBuffer, 1>>> =
SpinMutex::new("frame_buffer", MaybeUninit::uninit());
pub fn init_frame_buffer(frame_buffer: FrameBuffer) {
let mut fb = FRAME_BUF.lock();
unsafe { fb.as_mut_ptr().write(Scaled(frame_buffer)) };
}
pub fn lock_frame_buffer<F: FnMut(&mut Scaled<FrameBuffer, 1>)>(mut f: F) {
let mut fb = FRAME_BUF.lock();
let fb = unsafe { &mut *fb.as_mut_ptr() };
f(fb)
}
pub static CONSOLE: SpinMutex<Console> = SpinMutex::new("console", Console::new(80, 27));
pub fn init_console(columns: usize, lines: usize) {
let mut console = CONSOLE.lock();
console.resize(columns, lines);
}
pub fn console_write(attr: Attribute, args: core::fmt::Arguments) {
let mut console = CONSOLE.lock();
use core::fmt::Write;
let old_attr = console.attr;
console.attr = attr;
console.write_fmt(args).unwrap();
console.attr = old_attr;
}
pub fn console_flush() {
let mut console = CONSOLE.lock();
lock_frame_buffer(|fb| {
console.render(fb, &mut font::ShinonomeFont);
});
}
| true
|
ca3b5872214906c728258dca015c36f1abc89c86
|
Rust
|
rob-clarke/arusti
|
/arusti/tests/olan_tests.rs
|
UTF-8
| 4,264
| 3.0625
| 3
|
[] |
no_license
|
use arusti;
use arusti::{ElementType,Element};
fn compare_elements(result: &Vec<Element>, expectation: &Vec<Element>) {
assert_eq!(result.len(), expectation.len(), "Figure has wrong number of elements");
for (index,(result,expected)) in result.iter().zip( expectation.iter() ).enumerate() {
assert_eq!(result, expected, "Element {} does not match expectation", index);
}
}
#[test]
fn loop_plain() {
let sequence_str = "o".to_string();
let sequence = arusti::olan::parse_sequence(sequence_str);
let expected_elements = vec![
Element::line(0.0),
Element::radius(180.0),
Element::radius(180.0),
Element::line(0.0),
];
compare_elements(&sequence.figures[0].elements, &expected_elements);
}
#[test]
fn loop_with_leading_roll() {
let sequence_str = "1o".to_string();
let sequence = arusti::olan::parse_sequence(sequence_str);
let expected_elements = vec![
Element::line(0.0),
Element { angle: 360.0, argument: 1.0, .. Element::new(ElementType::Roll) },
Element::radius(180.0),
Element::radius(180.0),
Element::line(0.0),
];
compare_elements(&sequence.figures[0].elements, &expected_elements);
}
#[test]
fn loop_with_combining_roll() {
let sequence_str = "o1".to_string();
let sequence = arusti::olan::parse_sequence(sequence_str);
let expected_elements = vec![
Element::line(0.0),
Element::radius(180.0),
Element { angle: 360.0, argument: 1.0, .. Element::new(ElementType::Roll) },
Element::radius(180.0),
Element::line(0.0),
];
compare_elements(&sequence.figures[0].elements, &expected_elements);
}
#[test]
fn loop_with_all_rolls() {
let sequence_str = "1o1".to_string();
let sequence = arusti::olan::parse_sequence(sequence_str);
let expected_elements = vec![
Element::line(0.0),
Element { angle: 360.0, argument: 1.0, .. Element::new(ElementType::Roll) },
Element::radius(180.0),
Element { angle: 360.0, argument: 1.0, .. Element::new(ElementType::Roll) },
Element::radius(180.0),
Element::line(0.0),
];
compare_elements(&sequence.figures[0].elements, &expected_elements);
}
#[test]
fn loop_with_inverted_flight() {
let sequence_str = "-o-".to_string();
let sequence = arusti::olan::parse_sequence(sequence_str);
let expected_elements = vec![
Element::invline(0.0),
Element::radius(-180.0),
Element::radius(-180.0),
Element::invline(0.0),
];
compare_elements(&sequence.figures[0].elements, &expected_elements);
}
#[test]
fn loop_with_inverted_entry_and_inverting_leading_roll() {
let sequence_str = "-2o".to_string();
let sequence = arusti::olan::parse_sequence(sequence_str);
let expected_elements = vec![
Element::invline(0.0),
Element { angle: 180.0, argument: 1.0, .. Element::new(ElementType::Roll) },
Element::radius(180.0),
Element::radius(180.0),
Element::line(0.0),
];
compare_elements(&sequence.figures[0].elements, &expected_elements);
}
#[test]
fn loop_with_inverted_entry_and_inverting_combining_roll() {
let sequence_str = "-o2".to_string();
let sequence = arusti::olan::parse_sequence(sequence_str);
let expected_elements = vec![
Element::invline(0.0),
Element::radius(-180.0),
Element { angle: 180.0, argument: 1.0, .. Element::new(ElementType::Roll) },
Element::radius(180.0),
Element::line(0.0),
];
compare_elements(&sequence.figures[0].elements, &expected_elements);
}
#[test]
fn hammerhead_turn() {
let sequence_str = "h".to_string();
let sequence = arusti::olan::parse_sequence(sequence_str);
let expected_elements = vec![
Element::line(0.0),
Element::radius(90.0),
Element::line(90.0),
Element { angle: 180.0, argument: 0.0, .. Element::new(ElementType::Stall) },
Element::line(-90.0),
Element::radius(90.0),
Element::line(0.0),
];
compare_elements(&sequence.figures[0].elements, &expected_elements);
}
| true
|
04b6bedbfb90e194343d2fd56500d851e2843422
|
Rust
|
m-lima/advent-of-code-2020
|
/src/bin/112/build.rs
|
UTF-8
| 814
| 2.625
| 3
|
[] |
no_license
|
pub fn prepare() {
use std::io::Write;
const OUTPUT: &str = "src/bin/112/input.rs";
const INPUT: &str = include_str!("input.txt");
println!("cargo:rerun-if-changed=src/bin/112/{}", INPUT);
let input: Vec<_> = INPUT
.split('\n')
.filter(|line| !line.is_empty())
.map(|line| line.chars().collect::<Vec<_>>())
.collect();
let mut output = std::fs::File::create(OUTPUT).unwrap();
output
.write_all(
format!(
"pub const INPUT: [[char; {}]; {}] = [",
input[0].len(),
input.len()
)
.as_bytes(),
)
.unwrap();
for line in input {
output.write_all(format!("{:?},", line).as_bytes()).unwrap();
}
output.write_all(b"];").unwrap();
}
| true
|
1f1bd79e8d27d676bd719d96aaa3a92ee51c7b2e
|
Rust
|
longlb/exercism
|
/rust/triangle/src/lib.rs
|
UTF-8
| 987
| 3.578125
| 4
|
[] |
no_license
|
pub struct Triangle {
side1: u64,
side2: u64,
side3: u64,
}
impl Triangle {
pub fn build(sides: [u64; 3]) -> Option<Triangle> {
let new_tri = Triangle {
side1: sides[0],
side2: sides[1],
side3: sides[2],
};
if new_tri.is_valid() {
Some(new_tri)
} else {
None
}
}
pub fn is_equilateral(&self) -> bool {
self.side1 == self.side2 && self.side2 == self.side3 && self.side3 == self.side1
}
pub fn is_scalene(&self) -> bool {
self.side1 != self.side2 && self.side2 != self.side3 && self.side3 != self.side1
}
pub fn is_isosceles(&self) -> bool {
self.side1 == self.side2 || self.side2 == self.side3 || self.side3 == self.side1
}
fn is_valid(&self) -> bool {
self.side1 < self.side2 + self.side3
&& self.side2 < self.side1 + self.side3
&& self.side3 < self.side1 + self.side2
}
}
| true
|
e393954bde0ff61b876070ee5572e15717893ce3
|
Rust
|
acohen4/steelmate
|
/src/lib/engine.rs
|
UTF-8
| 13,224
| 3.15625
| 3
|
[] |
no_license
|
use super::board::{Board, Color, Piece, PieceKind, Position};
use std::collections::HashMap;
struct MovePattern {
is_repeatable: bool,
move_enumerations: Vec<Position>,
}
impl MovePattern {
fn new(is_repeatable: bool, move_enumerations: Vec<Position>) -> MovePattern {
MovePattern {
is_repeatable,
move_enumerations,
}
}
}
pub enum BoardSetup {
Basic,
}
pub struct ChessEngine {
pub board: Board,
}
impl ChessEngine {
pub fn create_board(setup: BoardSetup) -> Result<Board, String> {
match setup {
BoardSetup::Basic => ChessEngine::setup_basic_board()
}
}
pub fn possible_moves(board: &Board, p: &Position) -> Result<Vec<Position>, String> {
match board.get_space(p)? {
Option::None => Ok(vec![]),
Option::Some(Piece { kind: PieceKind::Pawn, color: c, has_moved: hm }) => {
Ok(ChessEngine::generate_pawn_moves(board, p, *c, *hm))
},
Option::Some(Piece { kind: PieceKind::King, color: c, has_moved: hm }) => {
Ok(ChessEngine::generate_king_moves(board, p, *c, *hm))
},
Option::Some(piece) => {
let mut solutions = vec![];
let pattern = ChessEngine::get_move_pattern(piece.kind)?;
for diff in pattern.move_enumerations.iter() {
ChessEngine::apply_move(board, &mut solutions, p, diff, &piece.color,
pattern.is_repeatable)
}
Ok(solutions)
}
}
}
fn generate_king_moves(board: &Board, p: &Position, color: Color, has_moved: bool)
-> Vec<Position> {
let mut solutions = vec![];
if !has_moved {
if ChessEngine::can_side_castle(board, p, true) {
solutions.push(Position::new(p.row, p.col - 3));
}
if ChessEngine::can_side_castle(board, p, false) {
solutions.push(Position::new(p.row, p.col + 2));
}
}
// do the basic case
let surroundings: Vec<Position> = ChessEngine::expand_with_inverses(vec![
Position::new(0, 1),
Position::new(1, 0),
Position::new(1, 1),
])
.iter()
.map(|pos| Position::add(p, pos))
.collect();
for pos in surroundings {
if let Ok(_) = board.get_space(&pos) {
if ChessEngine::is_enemy_space(board, &pos, color)
|| board.is_empty_space(&pos) {
if !ChessEngine::is_threatened(board, &pos, color) {
solutions.push(pos.clone());
}
}
}
}
solutions
}
fn can_side_castle(board: &Board, king_pos: &Position, is_left: bool) -> bool {
let direction = if is_left { -1 } else { 1 };
let rook_col = if is_left { 0 } else { (board.get_size() as i32) - 1 };
let mut can_castle =
match board.get_space(&Position::new(king_pos.row, rook_col)){
Ok(Option::Some(Piece {kind: _, color: _, has_moved: false})) => true,
_ => false,
};
let mut i = king_pos.col;
while i > 0 && can_castle {
i = i + direction;
match board.get_space(&Position::new(king_pos.row, i)) {
Ok(Option::Some(_)) => can_castle = false,
_ => ()
}
}
can_castle
}
fn generate_pawn_moves(board: &Board, p: &Position, c: Color, has_moved: bool) -> Vec<Position>{
// convert color to direction
let mut solutions = vec![];
let direction = if c == Color::White { 1 } else { -1 };
let forward_space = Position::new(direction + p.row, p.col);
if let Ok(Option::None) = board.get_space(&forward_space) {
solutions.push(forward_space);
if has_moved == false {
let double_forward_space = Position::new(2 * direction + p.row
, p.col);
if let Ok(Option::None) = board.get_space(&double_forward_space) {
solutions.push(double_forward_space);
}
}
}
let positive_diagonal_space = Position::new(p.row + direction
, p.col + 1);
if ChessEngine::is_enemy_space(board, &positive_diagonal_space, c) {
solutions.push(positive_diagonal_space);
}
let negative_diagonal_space = Position::new(p.row + direction
, p.col - 1);
if ChessEngine::is_enemy_space(board, &negative_diagonal_space, c) {
solutions.push(negative_diagonal_space);
}
solutions
}
fn is_enemy_space(board: &Board, p: &Position, c: Color) -> bool {
if let Ok(
Option::Some(Piece { kind: _, color: move_color, has_moved: _ })
) = board.get_space(p) {
*move_color != c
} else {
false
}
}
pub fn execute_move(board: &mut Board, from: &Position, to: &Position)
-> Result<Option<Piece>, String> {
let possibilities = ChessEngine::possible_moves(board, from)?;
if possibilities.contains(to) {
// if castle, also move Rook
if ChessEngine::is_castle(board, from, to) {
ChessEngine::castle_rook(board, from, to)?;
}
Ok(board.move_piece(from, to)?)
} else {
Err(String::from("You cannot move to this space"))
}
}
fn apply_move(
board: &Board,
sink: &mut Vec<Position>,
pos: &Position,
diff: &Position,
color: &Color,
repeat: bool,
) {
let check_pos = Position::add(pos, diff);
println!("Checking Position");
println!("{:?}", check_pos);
if let Err(_) = board.validate_position(&check_pos) {
return;
}
if let Ok(space) = board.get_space(&check_pos) {
match space {
Option::None => {
sink.push(check_pos);
if repeat {
ChessEngine::apply_move(board, sink, &check_pos, diff, color, repeat);
}
}
Option::Some(piece) => {
if piece.color != *color {
sink.push(check_pos);
}
}
}
}
}
fn get_move_pattern(kind: PieceKind) -> Result<MovePattern, String> {
match kind {
PieceKind::King | PieceKind::Pawn => Err(String::from("not supported")),
PieceKind::Queen => {
let moves = ChessEngine::expand_with_inverses(vec![
Position::new(0, 1),
Position::new(1, 0),
Position::new(1, 1),
]);
Ok(MovePattern::new(true, moves))
}
PieceKind::Rook => {
let moves = ChessEngine::expand_with_inverses(vec![
Position::new(0, 1),
Position::new(1, 0),
]);
Ok(MovePattern::new(true, moves))
}
PieceKind::Bishop => {
Ok(MovePattern::new(true, Position::new(1, 1)
.yield_all_inverse_positions()))
}
PieceKind::Knight => {
let moves = ChessEngine::expand_with_inverses(vec![
Position::new(1, 2),
Position::new(2, 1),
]);
Ok(MovePattern::new(false, moves))
}
}
}
fn expand_with_inverses(positions: Vec<Position>) -> Vec<Position> {
//positions.iter().map(|pos| pos.yield_all_inverse_positions()).collect()
let mut expanded = Vec::new();
for pos in positions.iter() {
expanded.append(&mut pos.yield_all_inverse_positions());
}
expanded
}
fn is_castle(board: &Board, from: &Position, to: &Position) -> bool {
board.get_space(from).unwrap().unwrap().kind == PieceKind::King
&& (from.col - to.col).abs() == 2
}
fn castle_rook(board: &mut Board, king_start: &Position, king_dest: &Position) -> Result<(), String> {
let is_right = king_start.col > king_dest.col;
let rook_from_col = if is_right {0} else {board.get_size() as i32};
let rook_to_col = if is_right {king_dest.col - 1} else {king_dest.col + 1};
ChessEngine::execute_move(board, &Position::new(king_start.row, rook_from_col),
&Position::new(king_start.row, rook_to_col))?;
Ok(())
}
fn is_threatened(board: &Board, pos: &Position, color: Color) -> bool {
let threatened = board.get_piece_positions().iter()
.filter(|(_, piece)| piece.color != color)
.flat_map(|(position, _)| ChessEngine::possible_moves(board, position).unwrap())
.any(|possible_move| possible_move == *pos);
threatened
}
fn setup_basic_board() -> Result<Board, String>{
let mut b = Board::new(8)?;
//setup pawns
b.fill(Some(6), None, Piece::new(PieceKind::Pawn, Color::Black))?;
b.fill(Some(1), None, Piece::new(PieceKind::Pawn, Color::White))?;
// populate accepts map of Spot => Piece
let mut map = HashMap::new();
// handle rooks
map.insert(
Position::new(0, 0),
Piece::new(PieceKind::Rook, Color::White),
);
map.insert(
Position::new(0, 7),
Piece::new(PieceKind::Rook, Color::White),
);
map.insert(
Position::new(7, 0),
Piece::new(PieceKind::Rook, Color::Black),
);
map.insert(
Position::new(7, 7),
Piece::new(PieceKind::Rook, Color::Black),
);
// handle knights
map.insert(
Position::new(0, 1),
Piece::new(PieceKind::Knight, Color::White),
);
map.insert(
Position::new(0, 6),
Piece::new(PieceKind::Knight, Color::White),
);
map.insert(
Position::new(7, 1),
Piece::new(PieceKind::Knight, Color::Black),
);
map.insert(
Position::new(7, 6),
Piece::new(PieceKind::Knight, Color::Black),
);
// handle bishops
map.insert(
Position::new(0, 2),
Piece::new(PieceKind::Bishop, Color::White),
);
map.insert(
Position::new(0, 5),
Piece::new(PieceKind::Bishop, Color::White),
);
map.insert(
Position::new(7, 2),
Piece::new(PieceKind::Bishop, Color::Black),
);
map.insert(
Position::new(7, 5),
Piece::new(PieceKind::Bishop, Color::Black),
);
// handle queens
map.insert(
Position::new(0, 3),
Piece::new(PieceKind::Queen, Color::White),
);
map.insert(
Position::new(7, 3),
Piece::new(PieceKind::Queen, Color::Black),
);
// handle kings
map.insert(
Position::new(0, 4),
Piece::new(PieceKind::King, Color::White),
);
map.insert(
Position::new(7, 4),
Piece::new(PieceKind::King, Color::Black),
);
b.populate(map)?;
Ok(b)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_basic_board() -> Result<(), String> {
let board = ChessEngine::setup_basic_board()?;
let pos = Position::new(0, 1);
let res = board.get_space(&pos);
let op = res?;
assert_eq!(
Some(&Piece {
kind: PieceKind::Knight,
color: Color::White,
has_moved: false
}),
op
);
Ok(())
}
#[test]
fn test_move_piece() -> Result<(), String> {
let mut board = ChessEngine::setup_basic_board()?;
let from = Position::new(1, 1);
let to = Position::new(2, 1);
ChessEngine::execute_move(&mut board, &from, &to)?;
let op_to = board.get_space(&to)?;
let op_from = board.get_space(&from)?;
assert_eq!(
Some(&Piece {
kind: PieceKind::Pawn,
color: Color::White,
has_moved: true
}),
op_to
);
assert_eq!(None, op_from);
Ok(())
}
#[test]
fn test_possible_moves() -> Result<(), String> {
let board = ChessEngine::setup_basic_board()?;
let pos = Position::new(0, 1);
let possibilities = ChessEngine::possible_moves(&board, &pos)?;
board.pretty_print();
println!("{:?}", possibilities);
assert_eq!(possibilities.len(), 2);
Ok(())
}
}
| true
|
b36f1451cae914f0eea9f2760d6377ec041aed44
|
Rust
|
yaozijian/RustProgramming
|
/chap15/src/section1.rs
|
UTF-8
| 667
| 3.71875
| 4
|
[
"MIT"
] |
permissive
|
pub fn demo(){
let x = 5;
let y = &x;
let z = Box::new(x);
assert_eq!(x,5);
assert_eq!(*y,5);
assert_eq!(*z,5);
}
pub fn demo2(){
struct MyBox<T>(T);
impl<T> MyBox<T>{
fn new(x: T) -> MyBox<T>{
MyBox(x)
}
}
use std::ops::Deref;
impl<T> Deref for MyBox<T>{
type Target = T;
fn deref(&self) -> &T{
&self.0
}
}
let x = 5;
let y = &x;
let z = MyBox::new(x);
let a = MyBox::new(String::from("ABC"));
fn hello(x : &str){ println!("{}",x); };
assert_eq!(x,5);
assert_eq!(*y,5);
assert_eq!(*z,5);
assert_eq!(*a,String::from("ABC"));
hello(a.deref().deref());
hello(&a);
hello(&*a);
}
| true
|
0aed52d6d235a63d94a9e35e41fca828a0307f8a
|
Rust
|
zhengrenzhe/nand2tetris
|
/compiler/vm-compiler/src/lexical.rs
|
UTF-8
| 1,670
| 3.4375
| 3
|
[] |
no_license
|
#[derive(Debug)]
pub struct Token {
pub command: String,
pub target: String,
pub arg: String,
}
pub fn lexical(code: &str) -> Option<Token> {
let parts: Vec<&str> = code.split(' ').filter(|code| !code.is_empty()).collect();
if parts.is_empty() {
return None;
}
Some(Token {
command: String::from(parts[0]),
target: String::from(*parts.get(1).unwrap_or(&"")),
arg: String::from(*parts.get(2).unwrap_or(&"")),
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_lexical_analysis() {
if let Some(val) = lexical("") {
panic!(format!("val: {:?} should be None", val));
}
match lexical("add") {
Some(token) => {
assert_eq!(token.command, String::from("add"));
assert_eq!(token.target, String::from(""));
assert_eq!(token.arg, String::from(""));
}
None => panic!("should not be None"),
}
match lexical("push 12") {
Some(token) => {
assert_eq!(token.command, String::from("push"));
assert_eq!(token.target, String::from("12"));
assert_eq!(token.arg, String::from(""));
}
None => panic!("should not be None"),
}
match lexical("push constant 12") {
Some(token) => {
assert_eq!(token.command, String::from("push"));
assert_eq!(token.target, String::from("constant"));
assert_eq!(token.arg, String::from("12"));
}
None => panic!("should not be None"),
}
}
}
| true
|
68d2c48e7b995f9cf69a985eb6292ef8c6ee5112
|
Rust
|
chyvonomys/serpanok
|
/src/format.rs
|
UTF-8
| 5,990
| 2.765625
| 3
|
[] |
no_license
|
use chrono::{Datelike, Timelike};
pub fn format_lat_lon(lat: f32, lon: f32) -> String {
format!("{:.03}°{} {:.03}°{}",
lat.abs(), if lat > 0.0 {"N"} else {"S"},
lon.abs(), if lat > 0.0 {"E"} else {"W"},
)
}
const MONTH_ABBREVS: [&str; 12] = [
"Січ", "Лют", "Бер", "Кві", "Тра", "Чер", "Лип", "Сер", "Вер", "Жов", "Лис", "Гру"
];
fn format_time(t: chrono::DateTime<chrono_tz::Tz>) -> String {
format!("{} {} {:02}:{:02}",
t.day(),
MONTH_ABBREVS.get(t.month0() as usize).unwrap_or(&"?"),
t.hour(), t.minute()
)
}
fn format_rain_rate(mmhr: f32) -> String {
if mmhr < 0.01 {
None
} else if mmhr < 2.5 {
Some("\u{1F4A7}")
} else if mmhr < 7.6 {
Some("\u{1F4A7}\u{1F4A7}")
} else {
Some("\u{1F4A7}\u{1F4A7}\u{1F4A7}")
}.map(|g| format!("{}{:.2}мм/год", g, mmhr)).unwrap_or_else(|| "--".to_owned())
}
fn format_snow_rate(mmhr: f32) -> String {
if mmhr < 0.01 {
None
} else if mmhr < 1.3 {
Some("\u{2744}")
} else if mmhr < 3.0 {
Some("\u{2744}\u{2744}")
} else if mmhr < 7.6 {
Some("\u{2744}\u{2744}\u{2744}")
} else {
Some("\u{2744}\u{26A0}")
}.map(|g| format!("{}{:.2}мм/год", g, mmhr)).unwrap_or_else(|| "--".to_owned())
}
fn format_wind_dir(u: f32, v: f32) -> &'static str {
let ws_az = (-v).atan2(-u) / std::f32::consts::PI * 180.0;
if ws_az > 135.0 + 22.5 {
"\u{2192}"
} else if ws_az > 90.0 + 22.5 {
"\u{2198}"
} else if ws_az > 45.0 + 22.5 {
"\u{2193}"
} else if ws_az > 22.5 {
"\u{2199}"
} else if ws_az > -22.5 {
"\u{2190}"
} else if ws_az > -45.0 - 22.5 {
"\u{2196}"
} else if ws_az > -90.0 - 22.5 {
"\u{2191}"
} else if ws_az > -135.0 - 22.5 {
"\u{2197}"
} else {
"\u{2192}"
}
}
use crate::data;
pub struct ForecastText(pub String);
pub fn format_place_link(name: &Option<String>, lat: f32, lon: f32) -> String {
let text = name.clone().unwrap_or_else(|| format_lat_lon(lat, lon));
format!("[{}](http://www.openstreetmap.org/?mlat={}&mlon={})", text, lat, lon)
}
pub fn format_forecast(name: &Option<String>, lat: f32, lon: f32, f: &data::Forecast, tz: chrono_tz::Tz) -> ForecastText {
let interval = (f.time.1 - f.time.0).num_minutes() as f32;
let mut result = String::new();
result.push_str(&format_place_link(name, lat, lon));
result.push('\n');
result.push_str(&format!("_{}_\n", format_time(f.time.0.with_timezone(&tz))));
if let Some(tmpk) = f.temperature {
let tmpc = (10.0 * (tmpk - 273.15)).round() / 10.0;
result.push_str(&format!("t повітря: *{:.1}°C*\n", tmpc));
}
if let Some(rain) = f.rain_accum {
let rain_rate = ((rain.1 - rain.0) * 60.0 / interval).max(0.0);
result.push_str(&format!("дощ: *{}*\n", format_rain_rate(rain_rate)));
}
if let Some(snow) = f.snow_accum {
let snow_rate = ((snow.1 - snow.0) * 60.0 / interval).max(0.0);
result.push_str(&format!("сніг: *{}*\n", format_snow_rate(snow_rate)));
}
if let Some(snow_depth) = f.snow_depth {
result.push_str(&format!("шар снігу: *{:.01}см*\n", snow_depth * 100.0));
}
if let Some(clouds) = f.total_cloud_cover {
result.push_str(&format!("хмарність: *{:.0}%*\n", clouds.round()));
}
if let Some(wind) = f.wind_speed {
let wind_speed = (wind.0 * wind.0 + wind.1 * wind.1).sqrt();
result.push_str(&format!("вітер: *{} {:.1}м/с*\n", format_wind_dir(wind.0, wind.1), (10.0 * wind_speed).round() / 10.0));
}
if let Some(relhum) = f.rel_humidity {
result.push_str(&format!("відн. вологість: *{:.0}%*\n", relhum));
}
if let Some(pmsl) = f.pressure_msl {
result.push_str(&format!("атм. тиск: *{:.0}ммHg*\n", pmsl / 133.322))
}
ForecastText(result)
}
use plotters::prelude::*;
pub fn format_exchange_graph(
rs: &[(chrono::DateTime::<chrono::Utc>, u32, u32)],
from: &chrono::DateTime::<chrono::Utc>,
to: &chrono::DateTime::<chrono::Utc>,
) -> Result<String, String> {
let min_buy = rs.iter().map(|x| x.1).min().unwrap_or(0);
let min_sell = rs.iter().map(|x| x.2).min().unwrap_or(0);
let max_buy = rs.iter().map(|x| x.1).max().unwrap_or(3000);
let max_sell = rs.iter().map(|x| x.2).max().unwrap_or(3000);
let min = std::cmp::min(min_buy, min_sell) as f32 / 100.0;
let max = std::cmp::max(max_buy, max_sell) as f32 / 100.0;
let max_pad = max + 0.1 * (max - min);
let min_pad = min - 0.1 * (max - min);
let filename = format!("plot-{}.png", chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, false));
{
let root = BitMapBackend::new(&filename, (200, 100)).into_drawing_area();
root.fill(&RGBColor(255, 255, 240));
let mut chart = ChartBuilder::on(&root)
.x_label_area_size(20)
.y_label_area_size(30)
.build_cartesian_2d(*from..*to, min_pad..max_pad)
.map_err(|e| e.to_string())?;
chart
.configure_mesh()
.light_line_style(BLACK.mix(0.0).filled())
.x_labels(5)
.y_labels(5)
.x_label_formatter(&|dt: &chrono::DateTime::<chrono::Utc>| format!("{}:{}", dt.hour(), dt.minute()))
.draw()
.map_err(|e| e.to_string())?;
chart
.draw_series(LineSeries::new(
rs.iter().map(|x| (x.0, x.1 as f32 * 0.01)),
&RGBColor(20, 20, 200),
))
.map_err(|e| e.to_string())?;
chart
.draw_series(LineSeries::new(
rs.iter().map(|x| (x.0, x.2 as f32 * 0.01)),
&RGBColor(20, 200, 20),
))
.map_err(|e| e.to_string())?;
}
Ok(filename)
}
| true
|
b16142cf5144097229d0a02f2e7942b78db3a226
|
Rust
|
mcmcgrath13/delf-rs
|
/src/graph/mod.rs
|
UTF-8
| 10,170
| 3
| 3
|
[
"MIT"
] |
permissive
|
use std::collections::{HashMap, HashSet};
use std::process::exit;
use ansi_term::Colour::{Red, Green, Cyan};
use petgraph::{
graph::{EdgeIndex, NodeIndex},
Directed, Graph, Incoming, Outgoing,
};
/// The edge of a DelfGraph is a DelfEdge
pub mod edge;
/// The node of a DelfGraph is a DelfObject
pub mod object;
use crate::storage::{get_connection, DelfStorageConnection};
use crate::DelfYamls;
/// The DelfGraph is the core structure for delf's functionality. It contains the algorithm to traverse the graph, as well as metadata to perform the deletions.
#[derive(Debug)]
pub struct DelfGraph {
pub(crate) nodes: HashMap<String, NodeIndex>,
pub(crate) edges: HashMap<String, EdgeIndex>,
graph: Graph<object::DelfObject, edge::DelfEdge, Directed>,
storages: HashMap<String, Box<dyn DelfStorageConnection>>,
}
impl DelfGraph {
/// Create a new DelfGraph from a schema and a config. See [yaml_rust](../../yaml_rust/index.html) for information on creating the Yaml structs, or alternately use the helper functions: [read_files](../fn.read_files.html), [read_yamls](../fn.read_yamls.html) for constructing a DelfGraph from either paths or `&str` of yaml.
pub fn new(yamls: &DelfYamls) -> DelfGraph {
let schema = &yamls.schema;
let config = &yamls.config;
let mut edges_to_insert = Vec::new();
let mut nodes = HashMap::<String, NodeIndex>::new();
let mut edges = HashMap::<String, EdgeIndex>::new();
let mut graph = Graph::<object::DelfObject, edge::DelfEdge>::new();
// each yaml is an object
for yaml in schema.iter() {
let obj_name = String::from(yaml["object_type"]["name"].as_str().unwrap());
let obj_node = object::DelfObject::from(&yaml["object_type"]);
let node_id = graph.add_node(obj_node);
nodes.insert(obj_name.clone(), node_id);
// need to make sure all the nodes exist before edges can be added to the graph
for e in yaml["object_type"]["edge_types"].as_vec().unwrap().iter() {
let delf_edge = edge::DelfEdge::from(e);
edges_to_insert.push((obj_name.clone(), delf_edge));
}
}
// add all the edges to the graph
for (from, e) in edges_to_insert.iter_mut() {
if !nodes.contains_key(&e.to.object_type) {
eprintln!("Error creating edge {:#?}: No object with name {:#?}", e.name, e.to.object_type);
exit(1);
}
let edge_id = graph.add_edge(nodes[from], nodes[&e.to.object_type], e.clone());
edges.insert(String::from(&e.name), edge_id);
}
// create the storage map
let mut storages = HashMap::<String, Box<dyn DelfStorageConnection>>::new();
for yaml in config.iter() {
for storage in yaml["storages"].as_vec().unwrap().iter() {
let storage_name = String::from(storage["name"].as_str().unwrap());
storages.insert(
storage_name,
get_connection(
storage["plugin"].as_str().unwrap(),
storage["url"].as_str().unwrap(),
),
);
}
}
return DelfGraph {
nodes,
edges,
graph,
storages,
};
}
/// Pretty print the graph's contents.
pub fn print(&self) {
println!("{:#?}", self.graph);
}
/// Given an edge name, get the corresponding DelfEdge
pub fn get_edge(&self, edge_name: &String) -> &edge::DelfEdge {
let edge_id = self.edges.get(edge_name).unwrap();
return self.graph.edge_weight(*edge_id).unwrap();
}
/// Given an edge name and the ids of the to/from object instances, delete the edge
pub fn delete_edge(&self, edge_name: &String, from_id: &String, to_id: &String) {
let e = self.get_edge(edge_name);
e.delete_one(from_id, to_id, self);
}
/// Given an object name, get the corresponding DelfObject
pub fn get_object(&self, object_name: &String) -> &object::DelfObject {
let object_id = self.nodes.get(object_name).unwrap();
return self.graph.node_weight(*object_id).unwrap();
}
/// Given the object name and the id of the instance, delete the object
pub fn delete_object(&self, object_name: &String, id: &String) {
self._delete_object(object_name, id, None);
}
fn _delete_object(
&self,
object_name: &String,
id: &String,
from_edge: Option<&edge::DelfEdge>,
) {
let obj = self.get_object(object_name);
let deleted = obj.delete(id, from_edge, &self.storages);
if deleted {
let edges = self.graph.edges_directed(self.nodes[&obj.name], Outgoing);
for e in edges {
e.weight().delete_all(id, &obj.id_type, self);
}
}
}
/// Validate that the objects and edges described in the schema exist in the corresponding storage as expected. Additionally, ensure that all objects in the graph are reachable by traversal via `deep` or `refcount` edges starting at an object with deletion type of `directly`, `directly_only`, `short_ttl`, or `not_deleted`. This ensures that all objects are deletable and accounted for.
pub fn validate(&self) {
println!("\u{1f50d} {}", Cyan.bold().paint("Validating DelF graph..."));
let mut errs = Vec::new();
let mut passed = true;
for (_, node_id) in self.nodes.iter() {
match self.graph
.node_weight(*node_id)
.unwrap()
.validate(&self.storages) {
Err(e) => errs.push(e),
_ => ()
}
}
if errs.len() > 0 {
passed = false;
println!("\u{274c} {}", Red.paint("Not all objects found in storage"));
for err in errs.drain(..) {
println!(" {}", err);
}
} else {
println!("\u{2705} {}", Green.paint("Objects exist in storage"));
}
for (_, edge_id) in self.edges.iter() {
match self.graph.edge_weight(*edge_id).unwrap().validate(self) {
Err(e) => errs.push(e),
_ => ()
}
}
if errs.len() > 0 {
passed = false;
println!("\u{274c} {}", Red.paint("Not all edges found in storage"));
for err in errs.drain(..) {
println!(" {}", err);
}
} else {
println!("\u{2705} {}", Green.paint("Edges exist in storage"));
}
match self.reachability_analysis() {
Err(e) => errs.push(e),
_ => ()
}
if errs.len() > 0 {
passed = false;
println!("\u{274c} {}", Red.paint("Not all objects deletable"));
for err in errs.drain(..) {
println!(" {}", err);
}
} else {
println!("\u{2705} {}", Green.paint("All objects deletable"));
}
if passed {
println!("\u{1F680} {} \u{1F680}", Green.bold().paint("Validation successful!"));
} else {
println!("\u{26a0} {} \u{26a0}", Red.bold().paint("Validation errors found"));
}
}
// Starting from a directly deletable (or excepted) node, ensure all ndoes are reached.
fn reachability_analysis(&self) -> Result<(), String> {
let mut visited_nodes = HashSet::new();
for (_, node_id) in self.nodes.iter() {
let obj = self.graph.node_weight(*node_id).unwrap();
match obj.deletion {
object::DeleteType::ShortTTL
| object::DeleteType::Directly
| object::DeleteType::DirectlyOnly
| object::DeleteType::NotDeleted => {
// this object is a starting point in traversal, start traversal
self.visit_node(&obj.name, &mut visited_nodes);
}
_ => (),
}
}
if visited_nodes.len() != self.nodes.len() {
let node_set: HashSet<String> = self.nodes.keys().cloned().collect();
return Err(format!(
"Not all objects are deletable: {:?}",
node_set.difference(&visited_nodes)
));
} else {
return Ok(());
}
}
// Recursively visit all un-visited nodes that are connected via depp or refcounte edges from the starting node with the passed in name
fn visit_node(&self, name: &String, visited_nodes: &mut HashSet<String>) {
visited_nodes.insert(name.clone());
let edges = self.graph.edges_directed(self.nodes[name], Outgoing);
for e in edges {
let ew = e.weight();
match ew.deletion {
edge::DeleteType::Deep | edge::DeleteType::RefCount => {
if !visited_nodes.contains(&ew.to.object_type) {
self.visit_node(&ew.to.object_type, visited_nodes);
}
}
_ => (),
}
}
}
// find all the inbound edges for a given object
fn get_inbound_edges(&self, obj: &object::DelfObject) -> Vec<&edge::DelfEdge> {
let object_id = self.nodes.get(&obj.name).unwrap();
let edges = self.graph.edges_directed(*object_id, Incoming);
let mut res = Vec::new();
for edge in edges {
res.push(edge.weight());
}
return res;
}
/// Check all objects in the DelfGraph with the deletion type of `short_ttl` if there are instances of the object which are past their expiration time. If so, delete the objects.
pub fn check_short_ttl(&self) {
for (_, node_id) in self.nodes.iter() {
let obj = self.graph.node_weight(*node_id).unwrap();
for obj_id in obj.check_short_ttl(&self.storages).iter() {
self.delete_object(&obj.name, obj_id);
}
}
}
}
| true
|
6c0e8e36b308ca708bae70153efefedd172f86a1
|
Rust
|
DesmondWillowbrook/cargo-optional-features-for-testing-and-examples
|
/src/main.rs
|
UTF-8
| 316
| 2.96875
| 3
|
[] |
no_license
|
use test_features::one::add_one;
#[cfg(feature = "add_two")]
use test_features::two::add_two;
fn main () -> std::io::Result<()> {
let num: usize = 5;
println!("Add 1 to num: {}", add_one(num));
#[cfg(feature = "add_two")]
{
println!("Add 2 to num: {}", add_two(num));
}
Ok(())
}
| true
|
c844b05ad06a8c4daa911b893ebd4d3d01a64450
|
Rust
|
schungx/rhai
|
/tests/debugging.rs
|
UTF-8
| 2,320
| 2.96875
| 3
|
[
"Apache-2.0",
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
#![cfg(feature = "debugging")]
use rhai::{Engine, INT};
#[cfg(not(feature = "no_index"))]
use rhai::Array;
#[cfg(not(feature = "no_object"))]
use rhai::Map;
#[test]
fn test_debugging() {
let mut engine = Engine::new();
engine.register_debugger(
|_, dbg| dbg,
|_, _, _, _, _| Ok(rhai::debugger::DebuggerCommand::Continue),
);
#[cfg(not(feature = "no_function"))]
#[cfg(not(feature = "no_index"))]
{
let r = engine
.eval::<Array>(
"
fn foo(x) {
if x >= 5 {
back_trace()
} else {
foo(x+1)
}
}
foo(0)
",
)
.unwrap();
assert_eq!(r.len(), 6);
assert_eq!(engine.eval::<INT>("len(back_trace())").unwrap(), 0);
}
}
#[test]
#[cfg(not(feature = "no_object"))]
fn test_debugger_state() {
let mut engine = Engine::new();
engine.register_debugger(
|_, mut debugger| {
// Say, use an object map for the debugger state
let mut state = Map::new();
// Initialize properties
state.insert("hello".into(), (42 as INT).into());
state.insert("foo".into(), false.into());
debugger.set_state(state);
debugger
},
|mut context, _, _, _, _| {
// Print debugger state - which is an object map
println!(
"Current state = {}",
context.global_runtime_state().debugger().state()
);
// Modify state
let mut state = context
.global_runtime_state_mut()
.debugger_mut()
.state_mut()
.write_lock::<Map>()
.unwrap();
let hello = state.get("hello").unwrap().as_int().unwrap();
state.insert("hello".into(), (hello + 1).into());
state.insert("foo".into(), true.into());
state.insert("something_new".into(), "hello, world!".into());
// Continue with debugging
Ok(rhai::debugger::DebuggerCommand::StepInto)
},
);
engine.run("let x = 42;").unwrap();
}
| true
|
1921912b6e8472305a883f1d2b93b569d281c1c7
|
Rust
|
ssolaric/cses.fi
|
/2. Sorting and Searching/7-sum-of-two-values.rs
|
UTF-8
| 1,696
| 3.3125
| 3
|
[
"MIT"
] |
permissive
|
// This is the 2sum problem.
use std::collections::HashMap;
use std::io;
use std::str;
pub struct Scanner<R> {
reader: R,
buffer: Vec<String>,
}
impl<R: io::BufRead> Scanner<R> {
pub fn new(reader: R) -> Self {
Self {
reader,
buffer: vec![],
}
}
pub fn token<T: str::FromStr>(&mut self) -> T {
loop {
if let Some(token) = self.buffer.pop() {
return token.parse().ok().expect("Failed parse");
}
let mut input = String::new();
self.reader.read_line(&mut input).expect("Failed read");
self.buffer = input.split_whitespace().rev().map(String::from).collect();
}
}
}
fn two_sum(values: &[i32], target: i32) -> Option<(usize, usize)> {
let mut to_index = HashMap::new();
let n = values.len();
for i in 0..n {
let to_find = target - values[i];
if let Some(ind) = to_index.get(&to_find) {
return Some((*ind, i));
}
to_index.insert(values[i], i);
}
None
}
fn solve<R: io::BufRead, W: io::Write>(scan: &mut Scanner<R>, out: &mut W) {
let n: usize = scan.token();
let target: i32 = scan.token();
let mut values = Vec::new();
for _ in 0..n {
values.push(scan.token::<i32>());
}
match two_sum(&values, target) {
Some((pos1, pos2)) => writeln!(out, "{} {}", pos1 + 1, pos2 + 1).ok(),
None => writeln!(out, "IMPOSSIBLE").ok(),
};
}
fn main() {
let (stdin, stdout) = (io::stdin(), io::stdout());
let mut scan = Scanner::new(stdin.lock());
let mut out = io::BufWriter::new(stdout.lock());
solve(&mut scan, &mut out);
}
| true
|
0231e78af7a2c964807b586b2b572d0e445cdd36
|
Rust
|
UnicodeSnowman/matasano-crypto-challenges
|
/rust/src/main.rs
|
UTF-8
| 1,502
| 2.90625
| 3
|
[] |
no_license
|
extern crate matasano;
use matasano::one;
use matasano::two;
fn main() {
println!("{}", "Section One");
println!("{}", "================");
//one::convert_hex_to_base64("49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d");
//one::fixed_xor();
//let hex_string: &str = "1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736";
//let bytes: Vec<u8> = hex_string.from_hex().unwrap();
//one::single_bit_xor_cypher(&bytes);
//one::single_bit_xor_cypher(&hex_string);
// let winner = one::detect_single_character_xor();
// match winner {
// Ok(w) => println!("WINNAR {:?} {:?}", w.key, w.secret),
// Err(err) => println!("oh noes, you lose {:?}", err)
// }
//let key: Vec<u8> = vec!(b'I', b'C', b'E');
//let string_bytes: Vec<u8> = "Burning 'em, if you ain't quick and nimble I go crazy when I hear a cymbal".bytes().collect();
//let xored_string = one::repeating_key_xor(&string_bytes, &key);
//let res = one::break_repeating_key_xor();
println!("{}", "Section Two");
println!("{}", "================");
// let mut bytes = "YELLOW SUBMARINE".bytes().collect();
// two::pad_pkcs_7(&mut bytes, 20);
// println!("{:?}", String::from_utf8(bytes).unwrap());
//two::an_ecb_cbc_detection_oracle::run();
//two::byte_at_a_time_ecb_decryption_simple::run();
//two::ecb_cut_and_paste::run();
two::byte_at_a_time_ecb_decryption_harder::run();
}
| true
|
e4c3abce32634160b79e30513b200d65573cb2d5
|
Rust
|
Palmr/lameboy
|
/src/lameboy/cpu/instructions/stack.rs
|
UTF-8
| 1,350
| 3.25
| 3
|
[
"MIT"
] |
permissive
|
use crate::lameboy::cpu::Cpu;
/// Push an 8-bit value to the stack.
/// Decrements the stack pointer and then writes the 8-bit value using the new stack pointer value.
pub fn push_stack_d8(cpu: &mut Cpu, d8: u8) {
// Decrement stack pointer
cpu.registers.sp = cpu.registers.sp.wrapping_sub(1);
// Write byte to stack
cpu.mmu.write8(cpu.registers.sp, d8);
}
/// Push a 16-bit value to the stack.
/// Pushing the high byte of the value first, then the low byte.
pub fn push_stack_d16(cpu: &mut Cpu, d16: u16) {
// Write high byte
push_stack_d8(cpu, ((d16 >> 8) & 0xFF) as u8);
// Write low byte
push_stack_d8(cpu, (d16 & 0xFF) as u8);
}
/// Pop an 8-bit value off the stack.
/// Decrements the stack pointer and then writes the 8-bit value using the new stack pointer value.
pub fn pop_stack_d8(cpu: &mut Cpu) -> u8 {
// Read byte from stack
let value = cpu.mmu.read8(cpu.registers.sp);
// Increment stack pointer
cpu.registers.sp = cpu.registers.sp.wrapping_add(1);
value
}
/// Pop a 16-bit value off the stack.
/// Pushing the high byte of the value first, then the low byte.
pub fn pop_stack_d16(cpu: &mut Cpu) -> u16 {
let mut value: u16;
// Pop low byte
value = u16::from(pop_stack_d8(cpu));
// Pop high byte
value |= (u16::from(pop_stack_d8(cpu))) << 8;
value
}
| true
|
d8c93dcd1e1c57d800375b0cc53edfdc80aafdc8
|
Rust
|
feds01/lang
|
/compiler/hash-reporting/src/errors.rs
|
UTF-8
| 1,408
| 2.953125
| 3
|
[
"MIT"
] |
permissive
|
//! Hash Compiler error and warning reporting module
//!
//! All rights reserved 2021 (c) The Hash Language authors
use std::{io, process::exit};
use thiserror::Error;
use hash_ast::error::ParseError;
/// Enum representing the variants of error that can occur when running an interactive session
#[derive(Error, Debug)]
pub enum InteractiveCommandError {
#[error("Unkown command `{0}`.")]
UnrecognisedCommand(String),
#[error("Command `{0}` does not take any arguments.")]
ZeroArguments(String),
// @Future: Maybe provide a second paramater to support multiple argument command
#[error("Command `{0}` requires one argument.")]
ArgumentMismatchError(String),
#[error("Unexpected error: `{0}`")]
InternalError(String),
}
/// Error message prefix
const ERR: &str = "\x1b[31m\x1b[1merror\x1b[0m";
/// Errors that might occur when attempting to compile and or interpret a
/// program.
#[derive(Debug, Error)]
pub enum CompilerError {
#[error("{0}")]
IoError(#[from] io::Error),
#[error("{message}")]
ArgumentError { message: String },
#[error("{0}")]
ParseError(#[from] ParseError),
#[error("{0}")]
InterpreterError(#[from] InteractiveCommandError),
}
impl CompilerError {
pub fn report_and_exit(&self) -> ! {
self.report();
exit(-1);
}
pub fn report(&self) {
println!("{}: {}", ERR, self);
}
}
| true
|
a7b9e243d738716f575b35969fd85aa122dd714c
|
Rust
|
immunant/c2rust
|
/c2rust-bitfields-derive/src/lib.rs
|
UTF-8
| 8,743
| 2.65625
| 3
|
[
"BSD-3-Clause",
"Apache-2.0"
] |
permissive
|
#![recursion_limit = "512"]
use proc_macro::{Span, TokenStream};
use quote::quote;
use syn::parse::Error;
use syn::punctuated::Punctuated;
use syn::spanned::Spanned;
use syn::{
parse_macro_input, Attribute, Field, Fields, Ident, ItemStruct, Lit, Meta, NestedMeta, Path,
PathArguments, PathSegment, Token,
};
#[cfg(target_endian = "big")]
compile_error!("Big endian architectures are not currently supported");
/// This struct keeps track of a single bitfield attr's params
/// as well as the bitfield's field name.
#[derive(Debug)]
struct BFFieldAttr {
field_name: Ident,
name: String,
ty: String,
bits: (String, proc_macro2::Span),
}
fn parse_bitfield_attr(
attr: &Attribute,
field_ident: &Ident,
) -> Result<Option<BFFieldAttr>, Error> {
let mut name = None;
let mut ty = None;
let mut bits = None;
let mut bits_span = None;
if let Meta::List(meta_list) = attr.parse_meta()? {
for nested_meta in meta_list.nested {
if let NestedMeta::Meta(Meta::NameValue(meta_name_value)) = nested_meta {
let rhs_string = match meta_name_value.lit {
Lit::Str(lit_str) => lit_str.value(),
_ => {
let err_str = "Found bitfield attribute with non str literal assignment";
let span = meta_name_value.path.span();
return Err(Error::new(span, err_str));
}
};
if let Some(lhs_ident) = meta_name_value.path.get_ident() {
match lhs_ident.to_string().as_str() {
"name" => name = Some(rhs_string),
"ty" => ty = Some(rhs_string),
"bits" => {
bits = Some(rhs_string);
bits_span = Some(meta_name_value.path.span());
}
// This one shouldn't ever occur here,
// but we're handling it just to be safe
"padding" => {
return Ok(None);
}
_ => {}
}
}
} else if let NestedMeta::Meta(Meta::Path(ref path)) = nested_meta {
if let Some(ident) = path.get_ident() {
if ident == "padding" {
return Ok(None);
}
}
}
}
}
if name.is_none() || ty.is_none() || bits.is_none() {
let mut missing_fields = Vec::new();
if name.is_none() {
missing_fields.push("name");
}
if ty.is_none() {
missing_fields.push("ty");
}
if bits.is_none() {
missing_fields.push("bits");
}
let err_str = format!("Missing bitfield params: {:?}", missing_fields);
let span = attr.path.segments.span();
return Err(Error::new(span, err_str));
}
Ok(Some(BFFieldAttr {
field_name: field_ident.clone(),
name: name.unwrap(),
ty: ty.unwrap(),
bits: (bits.unwrap(), bits_span.unwrap()),
}))
}
fn filter_and_parse_fields(field: &Field) -> Vec<Result<BFFieldAttr, Error>> {
let attrs: Vec<_> = field
.attrs
.iter()
.filter(|attr| attr.path.segments.last().unwrap().ident == "bitfield")
.collect();
if attrs.is_empty() {
return Vec::new();
}
attrs
.into_iter()
.map(|attr| parse_bitfield_attr(attr, field.ident.as_ref().unwrap()))
.flat_map(Result::transpose) // Remove the Ok(None) values
.collect()
}
fn parse_bitfield_ty_path(field: &BFFieldAttr) -> Path {
let leading_colon = if field.ty.starts_with("::") {
Some(Token.into(),
Span::call_site().into(),
]))
} else {
None
};
let mut segments = Punctuated::new();
let mut segment_strings = field.ty.split("::").peekable();
while let Some(segment_string) = segment_strings.next() {
segments.push_value(PathSegment {
ident: Ident::new(segment_string, Span::call_site().into()),
arguments: PathArguments::None,
});
if segment_strings.peek().is_some() {
segments.push_punct(Token.into(),
Span::call_site().into(),
]));
}
}
Path {
leading_colon,
segments,
}
}
#[proc_macro_derive(BitfieldStruct, attributes(bitfield))]
pub fn bitfield_struct(input: TokenStream) -> TokenStream {
let struct_item = parse_macro_input!(input as ItemStruct);
match bitfield_struct_impl(struct_item) {
Ok(ts) => ts,
Err(error) => error.to_compile_error().into(),
}
}
fn bitfield_struct_impl(struct_item: ItemStruct) -> Result<TokenStream, Error> {
// REVIEW: Should we throw a compile error if bit ranges on a single field overlap?
let struct_ident = struct_item.ident;
let fields = match struct_item.fields {
Fields::Named(named_fields) => named_fields.named,
Fields::Unnamed(_) => {
let err_str =
"Unnamed struct fields are not currently supported but may be in the future.";
let span = struct_ident.span();
return Err(Error::new(span, err_str));
}
Fields::Unit => {
let err_str = "Cannot create bitfield struct out of struct with no fields";
let span = struct_ident.span();
return Err(Error::new(span, err_str));
}
};
let bitfields: Result<Vec<BFFieldAttr>, Error> =
fields.iter().flat_map(filter_and_parse_fields).collect();
let bitfields = bitfields?;
let field_types: Vec<_> = bitfields.iter().map(parse_bitfield_ty_path).collect();
let field_types_return = &field_types;
let field_types_typedef = &field_types;
let field_types_setter_arg = &field_types;
let method_names: Vec<_> = bitfields
.iter()
.map(|field| Ident::new(&field.name, Span::call_site().into()))
.collect();
let field_names: Vec<_> = bitfields.iter().map(|field| &field.field_name).collect();
let field_names_setters = &field_names;
let field_names_getters = &field_names;
let method_name_setters: Vec<_> = method_names
.iter()
.map(|field_ident| {
let span = Span::call_site().into();
let setter_name = &format!("set_{}", field_ident);
Ident::new(setter_name, span)
})
.collect();
let field_bit_info: Result<Vec<_>, Error> = bitfields
.iter()
.map(|field| {
let bit_string = &field.bits.0;
let nums: Vec<_> = bit_string.split("..=").collect();
let err_str = "bits param must be in the format \"1..=4\"";
if nums.len() != 2 {
return Err(Error::new(field.bits.1, err_str));
}
let lhs = nums[0].parse::<usize>();
let rhs = nums[1].parse::<usize>();
let (lhs, rhs) = match (lhs, rhs) {
(Err(_), _) | (_, Err(_)) => return Err(Error::new(field.bits.1, err_str)),
(Ok(lhs), Ok(rhs)) => (lhs, rhs),
};
Ok(quote! { (#lhs, #rhs) })
})
.collect();
let field_bit_info = field_bit_info?;
let field_bit_info_setters = &field_bit_info;
let field_bit_info_getters = &field_bit_info;
// TODO: Method visibility determined by struct field visibility?
let q = quote! {
#[automatically_derived]
impl #struct_ident {
#(
/// This method allows you to write to a bitfield with a value
pub fn #method_name_setters(&mut self, int: #field_types_setter_arg) {
use c2rust_bitfields::FieldType;
let field = &mut self.#field_names_setters;
let (lhs_bit, rhs_bit) = #field_bit_info_setters;
int.set_field(field, (lhs_bit, rhs_bit));
}
/// This method allows you to read from a bitfield to a value
pub fn #method_names(&self) -> #field_types_return {
use c2rust_bitfields::FieldType;
type IntType = #field_types_typedef;
let field = &self.#field_names_getters;
let (lhs_bit, rhs_bit) = #field_bit_info_getters;
<IntType as FieldType>::get_field(field, (lhs_bit, rhs_bit))
}
)*
}
};
Ok(q.into())
}
| true
|
b8df6ae8e4de33703de889d4f76f010bd7c789e5
|
Rust
|
stkfd/rd-histogram
|
/src/simple_vec_histogram.rs
|
UTF-8
| 6,022
| 3.125
| 3
|
[] |
no_license
|
use num::traits::NumAssign;
use ord_subset::{OrdSubset, OrdSubsetIterExt, OrdSubsetSliceExt};
use std::cmp::Ordering;
use traits::{DynamicHistogram, EmptyClone, Merge, MergeRef};
#[derive(Clone, Debug, PartialEq)]
pub struct SimpleVecHistogram<V, C> {
bins: Vec<Bin<V, C>>,
bins_cap: usize,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Bin<V, C> {
left: V,
right: V,
count: C,
sum: V,
}
impl<V: PartialOrd + OrdSubset + NumAssign + Copy, C: Clone + NumAssign + Copy>
SimpleVecHistogram<V, C>
{
fn search_bins(&self, value: V) -> Result<usize, usize> {
self.bins.binary_search_by(|probe| {
if probe.left <= value && probe.right > value {
Ordering::Equal
} else if probe.left > value {
Ordering::Greater
} else {
Ordering::Less
}
})
}
fn shrink_to_fit(&mut self) {
while self.bins.len() > self.bins_cap {
let merge_result = self
.bins
.iter()
.zip(self.bins.iter().skip(1))
.enumerate()
.map(|(i, (bin, next_bin))| {
// calculate distances between bins
(i, bin, next_bin, next_bin.left - bin.right)
})
.ord_subset_min_by_key(|(_i, _bin, _next_bin, distance)| *distance)
.map(|(i, bin, next_bin, _)| {
let merged_bin = Bin {
left: bin.left,
right: next_bin.right,
sum: bin.sum + next_bin.sum,
count: bin.count + next_bin.count,
};
(i, merged_bin)
});
if let Some((i, merged_bin)) = merge_result {
self.bins[i] = merged_bin;
self.bins.remove(i + 1);
}
}
}
fn bins(&self) -> &[Bin<V, C>] {
self.bins.as_slice()
}
}
impl<V: PartialOrd + OrdSubset + Copy + NumAssign, C: Copy + NumAssign + Into<V>>
DynamicHistogram<V, C> for SimpleVecHistogram<V, C>
{
/// Type of a bin in this histogram
type Bin = Bin<V, C>;
/// Instantiate a histogram with the given number of maximum bins
fn new(n_bins: usize) -> Self {
SimpleVecHistogram {
bins: Vec::with_capacity(n_bins),
bins_cap: n_bins,
}
}
/// Insert a new data point into this histogram
fn insert(&mut self, value: V, count: C) {
let search_result = self.search_bins(value);
match search_result {
Ok(found) => {
self.bins[found].count += count;
self.bins[found].sum += value * count.into();
}
Err(insert_at) => self.bins.insert(
insert_at,
Bin {
left: value,
right: value,
count,
sum: value * count.into(),
},
),
}
self.shrink_to_fit();
}
/// Count the total number of data points in this histogram (over all bins)
fn count(&self) -> C {
unimplemented!()
}
}
impl<V: PartialOrd + OrdSubset + Copy + NumAssign, C: Copy + NumAssign + Into<V>> EmptyClone
for SimpleVecHistogram<V, C>
{
fn empty_clone(&self) -> Self {
SimpleVecHistogram::new(self.bins_cap)
}
}
impl<V: PartialOrd + OrdSubset + Copy + NumAssign, C: Copy + NumAssign + Into<V>> MergeRef
for SimpleVecHistogram<V, C>
{
fn merge_ref(&mut self, other: &Self) {
self.bins.extend_from_slice(other.bins());
self.bins.ord_subset_sort_by_key(|b| b.left);
self.shrink_to_fit();
}
}
impl<V: PartialOrd + OrdSubset + Copy + NumAssign, C: Copy + NumAssign + Into<V>> Merge
for SimpleVecHistogram<V, C>
{
fn merge(&mut self, other: Self) {
self.bins.extend(other.bins.into_iter());
self.bins.ord_subset_sort_by_key(|b| b.left);
self.shrink_to_fit();
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn insert() {
// fill with the maximum bin number
let mut h = SimpleVecHistogram::new(5);
let samples: &[(f64, u32)] = &[(1., 1), (2., 1), (3., 1), (4., 1), (5., 1)];
h.insert_iter(samples);
for (bin, s) in h.bins().iter().zip(samples.iter()) {
assert_eq!(s.0, bin.left);
assert_eq!(s.0, bin.right);
}
// checks merging the closest two bins
h.insert(5.5, 2);
assert_eq!(
h.bins()[4],
Bin {
left: 5.,
right: 5.5,
count: 3,
sum: 16.
}
);
// checks inserting into an existing bin
h.insert(5.2, 1);
assert_eq!(
h.bins()[4],
Bin {
left: 5.,
right: 5.5,
count: 4,
sum: 21.2
}
);
}
#[test]
fn merge() {
// fill with the maximum bin number
let samples1: &[(f64, u32)] = &[(1., 1), (2., 1), (3., 1), (4., 1), (5., 1)];
let samples2: &[(f64, u32)] = &[(1.1, 1), (2.1, 1), (3.1, 1), (4.1, 1), (5.1, 1)];
let mut h = SimpleVecHistogram::new(5);
h.insert_iter(samples1);
println!("{:?}", h);
let mut h2 = SimpleVecHistogram::new(5);
h2.insert_iter(samples2);
println!("{:?}", h2);
h.merge(h2);
println!("{:?}", h);
assert_eq!(h.bins().len(), 5);
assert_eq!(
h.bins()[2],
Bin {
left: 3.,
right: 3.1,
count: 2,
sum: 6.1
}
);
assert_eq!(
h.bins()[4],
Bin {
left: 5.,
right: 5.1,
count: 2,
sum: 10.1
}
);
}
}
| true
|
c0563791dd9ae4d6ca09b42b63a69f0273affb6d
|
Rust
|
emakryo/cmpro
|
/src/abc221/src/bin/c.rs
|
UTF-8
| 885
| 2.59375
| 3
|
[] |
no_license
|
#![allow(unused_macros, unused_imports)]
use proconio::marker::Bytes;
macro_rules! dbg {
($($xs:expr),+) => {
if cfg!(debug_assertions) {
std::dbg!($($xs),+)
} else {
($($xs),+)
}
}
}
fn main() {
proconio::input!{
n: Bytes,
}
let m = n.len();
let mut cs = n.into_iter().map(|c| (c - b'0') as u64).collect::<Vec<_>>();
cs.sort();
cs.reverse();
let mut a = 0;
let mut b = 0;
for i in 0..m/2 {
let c = cs[2*i];
let d = cs[2*i+1];
// d <= c
if a <= b {
a = 10*a + c;
b = 10*b + d;
} else {
a = 10*a + d;
b = 10*b + c;
}
}
if m%2==1 {
if a <= b {
a = 10*a + cs[m-1];
} else {
b = 10*b + cs[m-1];
}
}
println!("{}", a*b);
}
| true
|
134d79f3059cc8fda9706ba4154a79fba04014db
|
Rust
|
b-ramsey/cargo-generate
|
/src/git.rs
|
UTF-8
| 886
| 2.5625
| 3
|
[
"Apache-2.0",
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
use git2::{
build::CheckoutBuilder, build::RepoBuilder, Repository as GitRepository, RepositoryInitOptions,
};
use quicli::prelude::*;
use remove_dir_all::remove_dir_all;
use std::path::PathBuf;
use Args;
pub fn create(project_dir: &PathBuf, args: Args) -> Result<GitRepository> {
let mut rb = RepoBuilder::new();
rb.bare(false).with_checkout(CheckoutBuilder::new());
if let Some(ref branch) = args.branch {
rb.branch(branch);
}
Ok(rb.clone(&args.git, &project_dir)?)
}
pub fn remove_history(project_dir: &PathBuf) -> Result<()> {
Ok(remove_dir_all(project_dir.join(".git")).context("Error cleaning up cloned template")?)
}
pub fn init(project_dir: &PathBuf) -> Result<GitRepository> {
Ok(
GitRepository::init_opts(project_dir, RepositoryInitOptions::new().bare(false))
.context("Couldn't init new repository")?,
)
}
| true
|
d63faa075580a490542c4c763c335b56e8df9877
|
Rust
|
racer-rust/racer
|
/src/racer/codecleaner.rs
|
UTF-8
| 14,591
| 3.5
| 4
|
[
"MIT"
] |
permissive
|
use crate::core::{BytePos, ByteRange};
/// Type of the string
#[derive(Clone, Copy, Debug)]
enum StrStyle {
/// normal string starts with "
Cooked,
/// Raw(n) => raw string started with n #s
Raw(usize),
}
#[derive(Clone, Copy)]
enum State {
Code,
Comment,
CommentBlock,
String(StrStyle),
Char,
Finished,
}
#[derive(Clone, Copy)]
pub struct CodeIndicesIter<'a> {
src: &'a str,
pos: BytePos,
state: State,
}
impl<'a> Iterator for CodeIndicesIter<'a> {
type Item = ByteRange;
fn next(&mut self) -> Option<ByteRange> {
match self.state {
State::Code => Some(self.code()),
State::Comment => Some(self.comment()),
State::CommentBlock => Some(self.comment_block()),
State::String(style) => Some(self.string(style)),
State::Char => Some(self.char()),
State::Finished => None,
}
}
}
impl<'a> CodeIndicesIter<'a> {
fn code(&mut self) -> ByteRange {
let mut pos = self.pos;
let start = match self.state {
State::String(_) | State::Char => pos.decrement(), // include quote
_ => pos,
};
let src_bytes = self.src.as_bytes();
for &b in &src_bytes[pos.0..] {
pos = pos.increment();
match b {
b'/' if src_bytes.len() > pos.0 => match src_bytes[pos.0] {
b'/' => {
self.state = State::Comment;
self.pos = pos.increment();
return ByteRange::new(start, pos.decrement());
}
b'*' => {
self.state = State::CommentBlock;
self.pos = pos.increment();
return ByteRange::new(start, pos.decrement());
}
_ => {}
},
b'"' => {
// "
let str_type = self.detect_str_type(pos);
self.state = State::String(str_type);
self.pos = pos;
return ByteRange::new(start, pos); // include dblquotes
}
b'\'' => {
// single quotes are also used for lifetimes, so we need to
// be confident that this is not a lifetime.
// Look for backslash starting the escape, or a closing quote:
if src_bytes.len() > pos.increment().0
&& (src_bytes[pos.0] == b'\\' || src_bytes[pos.increment().0] == b'\'')
{
self.state = State::Char;
self.pos = pos;
return ByteRange::new(start, pos); // include single quote
}
}
_ => {}
}
}
self.state = State::Finished;
ByteRange::new(start, self.src.len().into())
}
fn comment(&mut self) -> ByteRange {
let mut pos = self.pos;
let src_bytes = self.src.as_bytes();
for &b in &src_bytes[pos.0..] {
pos = pos.increment();
if b == b'\n' {
if pos.0 + 2 <= src_bytes.len() && src_bytes[pos.0..pos.0 + 2] == [b'/', b'/'] {
continue;
}
break;
}
}
self.pos = pos;
self.code()
}
fn comment_block(&mut self) -> ByteRange {
let mut nesting_level = 0usize;
let mut prev = b' ';
let mut pos = self.pos;
for &b in &self.src.as_bytes()[pos.0..] {
pos = pos.increment();
match b {
b'/' if prev == b'*' => {
prev = b' ';
if nesting_level == 0 {
break;
} else {
nesting_level -= 1;
}
}
b'*' if prev == b'/' => {
prev = b' ';
nesting_level += 1;
}
_ => {
prev = b;
}
}
}
self.pos = pos;
self.code()
}
fn string(&mut self, str_type: StrStyle) -> ByteRange {
let src_bytes = self.src.as_bytes();
let mut pos = self.pos;
match str_type {
StrStyle::Raw(level) => {
// raw string (e.g. br#"\"#)
#[derive(Debug)]
enum SharpState {
Sharp {
// number of preceding #s
num_sharps: usize,
// Position of last "
quote_pos: BytePos,
},
None, // No preceding "##...
}
let mut cur_state = SharpState::None;
let mut end_was_found = false;
// detect corresponding end(if start is r##", "##) greedily
for (i, &b) in src_bytes[self.pos.0..].iter().enumerate() {
match cur_state {
SharpState::Sharp {
num_sharps,
quote_pos,
} => {
cur_state = match b {
b'#' => SharpState::Sharp {
num_sharps: num_sharps + 1,
quote_pos,
},
b'"' => SharpState::Sharp {
num_sharps: 0,
quote_pos: BytePos(i),
},
_ => SharpState::None,
}
}
SharpState::None => {
if b == b'"' {
cur_state = SharpState::Sharp {
num_sharps: 0,
quote_pos: BytePos(i),
};
}
}
}
if let SharpState::Sharp {
num_sharps,
quote_pos,
} = cur_state
{
if num_sharps == level {
end_was_found = true;
pos += quote_pos.increment();
break;
}
}
}
if !end_was_found {
pos = src_bytes.len().into();
}
}
StrStyle::Cooked => {
let mut is_not_escaped = true;
for &b in &src_bytes[pos.0..] {
pos = pos.increment();
match b {
b'"' if is_not_escaped => {
break;
} // "
b'\\' => {
is_not_escaped = !is_not_escaped;
}
_ => {
is_not_escaped = true;
}
}
}
}
};
self.pos = pos;
self.code()
}
fn char(&mut self) -> ByteRange {
let mut is_not_escaped = true;
let mut pos = self.pos;
for &b in &self.src.as_bytes()[pos.0..] {
pos = pos.increment();
match b {
b'\'' if is_not_escaped => {
break;
}
b'\\' => {
is_not_escaped = !is_not_escaped;
}
_ => {
is_not_escaped = true;
}
}
}
self.pos = pos;
self.code()
}
fn detect_str_type(&self, pos: BytePos) -> StrStyle {
let src_bytes = self.src.as_bytes();
let mut sharp = 0;
if pos == BytePos::ZERO {
return StrStyle::Cooked;
}
// now pos is at one byte after ", so we have to start at pos - 2
for &b in src_bytes[..pos.decrement().0].iter().rev() {
match b {
b'#' => sharp += 1,
b'r' => return StrStyle::Raw(sharp),
_ => return StrStyle::Cooked,
}
}
StrStyle::Cooked
}
}
/// Returns indices of chunks of code (minus comments and string contents)
pub fn code_chunks(src: &str) -> CodeIndicesIter<'_> {
CodeIndicesIter {
src,
state: State::Code,
pos: BytePos::ZERO,
}
}
#[cfg(test)]
mod code_indices_iter_test {
use super::*;
use crate::testutils::{rejustify, slice};
#[test]
fn removes_a_comment() {
let src = &rejustify(
"
this is some code // this is a comment
some more code
",
);
let mut it = code_chunks(src);
assert_eq!("this is some code ", slice(src, it.next().unwrap()));
assert_eq!("some more code", slice(src, it.next().unwrap()));
}
#[test]
fn removes_consecutive_comments() {
let src = &rejustify(
"
this is some code // this is a comment
// this is more comment
// another comment
some more code
",
);
let mut it = code_chunks(src);
assert_eq!("this is some code ", slice(src, it.next().unwrap()));
assert_eq!("some more code", slice(src, it.next().unwrap()));
}
#[test]
fn removes_string_contents() {
let src = &rejustify(
"
this is some code \"this is a string\" more code
",
);
let mut it = code_chunks(src);
assert_eq!("this is some code \"", slice(src, it.next().unwrap()));
assert_eq!("\" more code", slice(src, it.next().unwrap()));
}
#[test]
fn removes_char_contents() {
let src = &rejustify(
"
this is some code \'\"\' more code \'\\x00\' and \'\\\'\' that\'s it
",
);
let mut it = code_chunks(src);
assert_eq!("this is some code \'", slice(src, it.next().unwrap()));
assert_eq!("\' more code \'", slice(src, it.next().unwrap()));
assert_eq!("\' and \'", slice(src, it.next().unwrap()));
assert_eq!("\' that\'s it", slice(src, it.next().unwrap()));
}
#[test]
fn removes_string_contents_with_a_comment_in_it() {
let src = &rejustify(
"
this is some code \"string with a // fake comment \" more code
",
);
let mut it = code_chunks(src);
assert_eq!("this is some code \"", slice(src, it.next().unwrap()));
assert_eq!("\" more code", slice(src, it.next().unwrap()));
}
#[test]
fn removes_a_comment_with_a_dbl_quote_in_it() {
let src = &rejustify(
"
this is some code // comment with \" double quote
some more code
",
);
let mut it = code_chunks(src);
assert_eq!("this is some code ", slice(src, it.next().unwrap()));
assert_eq!("some more code", slice(src, it.next().unwrap()));
}
#[test]
fn removes_multiline_comment() {
let src = &rejustify(
"
this is some code /* this is a
\"multiline\" comment */some more code
",
);
let mut it = code_chunks(src);
assert_eq!("this is some code ", slice(src, it.next().unwrap()));
assert_eq!("some more code", slice(src, it.next().unwrap()));
}
#[test]
fn handles_nesting_of_block_comments() {
let src = &rejustify(
"
this is some code /* nested /* block */ comment */ some more code
",
);
let mut it = code_chunks(src);
assert_eq!("this is some code ", slice(src, it.next().unwrap()));
assert_eq!(" some more code", slice(src, it.next().unwrap()));
}
#[test]
fn handles_documentation_block_comments_nested_into_block_comments() {
let src = &rejustify(
"
this is some code /* nested /** documentation block */ comment */ some more code
",
);
let mut it = code_chunks(src);
assert_eq!("this is some code ", slice(src, it.next().unwrap()));
assert_eq!(" some more code", slice(src, it.next().unwrap()));
}
#[test]
fn removes_string_with_escaped_dblquote_in_it() {
let src = &rejustify(
"
this is some code \"string with a \\\" escaped dblquote fake comment \" more code
",
);
let mut it = code_chunks(src);
assert_eq!("this is some code \"", slice(src, it.next().unwrap()));
assert_eq!("\" more code", slice(src, it.next().unwrap()));
}
#[test]
fn removes_raw_string_with_dangling_escape_in_it() {
let src = &rejustify(
"
this is some code br\" escaped dblquote raw string \\\" more code
",
);
let mut it = code_chunks(src);
assert_eq!("this is some code br\"", slice(src, it.next().unwrap()));
assert_eq!("\" more code", slice(src, it.next().unwrap()));
}
#[test]
fn removes_string_with_escaped_slash_before_dblquote_in_it() {
let src = &rejustify("
this is some code \"string with an escaped slash, so dbl quote does end the string after all \\\\\" more code
");
let mut it = code_chunks(src);
assert_eq!("this is some code \"", slice(src, it.next().unwrap()));
assert_eq!("\" more code", slice(src, it.next().unwrap()));
}
#[test]
fn handles_tricky_bit_from_str_rs() {
let src = &rejustify(
"
before(\"\\\\\'\\\\\\\"\\\\\\\\\");
more_code(\" skip me \")
",
);
for range in code_chunks(src) {
let range = || range.to_range();
println!("BLOB |{}|", &src[range()]);
if src[range()].contains("skip me") {
panic!("{}", &src[range()]);
}
}
}
#[test]
fn removes_nested_rawstr() {
let src = &rejustify(
r####"
this is some code br###""" r##""##"### more code
"####,
);
let mut it = code_chunks(src);
assert_eq!("this is some code br###\"", slice(src, it.next().unwrap()));
assert_eq!("\"### more code", slice(src, it.next().unwrap()));
}
}
| true
|
3f25a94579101de7158a4a0e2f469e40937aa5cd
|
Rust
|
Aloso/parkour
|
/src/error.rs
|
UTF-8
| 9,015
| 3.71875
| 4
|
[
"MIT",
"Apache-2.0"
] |
permissive
|
use std::fmt;
use std::num::{ParseFloatError, ParseIntError};
use crate::help::PossibleValues;
use crate::util::Flag;
/// The error type when parsing command-line arguments. You can create an
/// `Error` by creating an `ErrorInner` and converting it with `.into()`.
///
/// This error type supports an error source for attaching context to the error.
#[derive(Debug)]
pub struct Error {
inner: ErrorInner,
source: Option<Box<dyn std::error::Error + Sync + Send + 'static>>,
}
impl Error {
/// Attach context to the error. Note that this overwrites the current
/// source, if there is one.
///
/// ### Usage
///
/// ```
/// use parkour::{Error, util::Flag};
///
/// Error::missing_value()
/// .with_source(Error::in_subcommand("test"))
/// # ;
/// ```
///
/// This could produce the following output:
/// ```text
/// missing value
/// source: in subcommand `test`
/// ```
pub fn with_source(
self,
source: impl std::error::Error + Sync + Send + 'static,
) -> Self {
Error { source: Some(Box::new(source)), ..self }
}
/// Attach context to the error. This function ensures that an already
/// attached source isn't discarded, but appended to the the new source. The
/// sources therefore form a singly linked list.
///
/// ### Usage
///
/// ```
/// use parkour::{Error, ErrorInner, util::Flag};
///
/// Error::missing_value()
/// .chain(ErrorInner::IncompleteValue(1))
/// # ;
/// ```
pub fn chain(mut self, source: ErrorInner) -> Self {
let mut new = Self::from(source);
new.source = self.source.take();
Error { source: Some(Box::new(new)), ..self }
}
/// Create a `NoValue` error
pub fn no_value() -> Self {
ErrorInner::NoValue.into()
}
/// Returns `true` if this is a `NoValue` error
pub fn is_no_value(&self) -> bool {
matches!(self.inner, ErrorInner::NoValue)
}
/// Create a `MissingValue` error
pub fn missing_value() -> Self {
ErrorInner::MissingValue.into()
}
/// Returns the [`ErrorInner`] of this error
pub fn inner(&self) -> &ErrorInner {
&self.inner
}
/// Create a `EarlyExit` error
pub fn early_exit() -> Self {
ErrorInner::EarlyExit.into()
}
/// Returns `true` if this is a `EarlyExit` error
pub fn is_early_exit(&self) -> bool {
matches!(self.inner, ErrorInner::EarlyExit)
}
/// Create a `UnexpectedValue` error
pub fn unexpected_value(
got: impl ToString,
expected: Option<PossibleValues>,
) -> Self {
ErrorInner::InvalidValue { got: got.to_string(), expected }.into()
}
/// Create a `MissingArgument` error
pub fn missing_argument(arg: impl ToString) -> Self {
ErrorInner::MissingArgument { arg: arg.to_string() }.into()
}
/// Create a `InArgument` error
pub fn in_argument(flag: &Flag) -> Self {
ErrorInner::InArgument(flag.first_to_string()).into()
}
/// Create a `InSubcommand` error
pub fn in_subcommand(cmd: impl ToString) -> Self {
ErrorInner::InSubcommand(cmd.to_string()).into()
}
/// Create a `TooManyArgOccurrences` error
pub fn too_many_arg_occurrences(arg: impl ToString, max: Option<u32>) -> Self {
ErrorInner::TooManyArgOccurrences { arg: arg.to_string(), max }.into()
}
}
impl From<ErrorInner> for Error {
fn from(inner: ErrorInner) -> Self {
Error { inner, source: None }
}
}
/// The error type when parsing command-line arguments
#[derive(Debug, PartialEq)]
pub enum ErrorInner {
/// The argument you tried to parse wasn't present at the current position.
/// Has a similar purpose as `Option::None`
NoValue,
/// The argument you tried to parse wasn't present at the current position,
/// but was required
MissingValue,
/// The argument you tried to parse was only partly present
IncompleteValue(usize),
/// Used when an argument should abort argument parsing, like --help
EarlyExit,
/// Indicates that the error originated in the specified argument. This
/// should be used as the source for another error
InArgument(String),
/// Indicates that the error originated in the specified subcommand. This
/// should be used as the source for another error
InSubcommand(String),
/// The parsed value doesn't meet our expectations
InvalidValue {
/// The value we tried to parse
got: String,
/// The expectation that was violated. For example, this string can
/// contain a list of accepted values.
expected: Option<PossibleValues>,
},
/// The parsed list contains more items than allowed
TooManyValues {
/// The maximum number of items
max: usize,
/// The number of items that was parsed
count: usize,
},
/// The parsed array has the wrong length
WrongNumberOfValues {
/// The length of the array
expected: usize,
/// The number of items that was parsed
got: usize,
},
/// A required argument was not provided
MissingArgument {
/// The name of the argument that is missing
arg: String,
},
/// An unknown argument was provided
UnexpectedArgument {
/// The (full) argument that wasn't expected
arg: String,
},
/// The argument has a value, but no value was expected
UnexpectedValue {
/// The value of the argument
value: String,
},
/// An argument was provided more often than allowed
TooManyArgOccurrences {
/// The name of the argument that was provided too many times
arg: String,
/// The maximum number of times the argument may be provided
max: Option<u32>,
},
/// Parsing an integer failed
ParseIntError(ParseIntError),
/// Parsing a floating-point number failed
ParseFloatError(ParseFloatError),
}
impl From<ParseIntError> for Error {
fn from(e: ParseIntError) -> Self {
ErrorInner::ParseIntError(e).into()
}
}
impl From<ParseFloatError> for Error {
fn from(e: ParseFloatError) -> Self {
ErrorInner::ParseFloatError(e).into()
}
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.source {
Some(source) => Some(&**source as &(dyn std::error::Error + 'static)),
None => None,
}
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self.inner {
ErrorInner::NoValue => write!(f, "no value"),
ErrorInner::MissingValue => write!(f, "missing value"),
ErrorInner::IncompleteValue(part) => {
write!(f, "missing part {} of value", part)
}
ErrorInner::EarlyExit => write!(f, "early exit"),
ErrorInner::InArgument(opt) => write!(f, "in `{}`", opt.escape_debug()),
ErrorInner::InSubcommand(cmd) => {
write!(f, "in subcommand {}", cmd.escape_debug())
}
ErrorInner::InvalidValue { expected, got } => {
if let Some(expected) = expected {
write!(
f,
"unexpected value `{}`, expected {}",
got.escape_debug(),
expected,
)
} else {
write!(f, "unexpected value `{}`", got.escape_debug())
}
}
ErrorInner::UnexpectedArgument { arg } => {
write!(f, "unexpected argument `{}`", arg.escape_debug())
}
ErrorInner::UnexpectedValue { value } => {
write!(f, "unexpected value `{}`", value.escape_debug())
}
ErrorInner::TooManyValues { max, count } => {
write!(f, "too many values, expected at most {}, got {}", max, count)
}
ErrorInner::WrongNumberOfValues { expected, got } => {
write!(f, "wrong number of values, expected {}, got {}", expected, got)
}
ErrorInner::MissingArgument { arg } => {
write!(f, "required {} was not provided", arg)
}
ErrorInner::TooManyArgOccurrences { arg, max } => {
if let Some(max) = max {
write!(
f,
"{} was used too often, it can be used at most {} times",
arg, max
)
} else {
write!(f, "{} was used too often", arg)
}
}
ErrorInner::ParseIntError(e) => write!(f, "{}", e),
ErrorInner::ParseFloatError(e) => write!(f, "{}", e),
}
}
}
| true
|
3abb46cea2b60c54f13e04b08078c306026a654a
|
Rust
|
philipcraig/mylang
|
/src/frame.rs
|
UTF-8
| 8,295
| 3.5625
| 4
|
[
"MIT"
] |
permissive
|
use crate::ast::{BinaryOp, Expression, Function, OpName, Statement, UnaryOp};
use std::{collections::HashMap, fmt, rc::Rc};
use thiserror::Error;
#[derive(Debug, PartialEq)]
pub enum Value {
Boolean(bool),
Float(f64),
Function(Rc<Function>),
Integer(i32),
String(Rc<String>),
}
impl fmt::Display for Value {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Value::Boolean(b) => write!(f, "Boolean({})", b),
Value::Float(float) => write!(f, "Float({})", float),
Value::Function(_) => write!(f, "Function()"),
Value::Integer(i) => write!(f, "Integer({})", i),
Value::String(s) => write!(f, "String({})", s),
}
}
}
#[derive(Error, Debug, PartialEq)]
pub enum EvaluationError {
#[error("Evaluation requested on unknown identifier `{0}`")]
UnknownIdentifier(String),
#[error("Called on {0}, which is not a callable type")]
NonCallableType(String),
#[error("Mismatch in argument count for Function {name:?}. Expected {expected:?} arguments but got {got:?}")]
ArgumentCountMismatch {
name: String,
expected: usize,
got: usize,
},
#[error("Function {0} didn't return a value")]
NoReturnValue(String),
#[error("Can't apply a unary operation {opname:?} to {value:?}")]
IllegalUnaryOperation { opname: String, value: String },
#[error("Can't apply binary operation {opname:?} to {left:?} {right:?}")]
IllegalBinaryOperation {
opname: String,
left: String,
right: String,
},
}
pub struct Frame {
values: HashMap<String, Rc<Value>>,
}
impl Frame {
pub(crate) fn new() -> Self {
Self {
values: HashMap::new(),
}
}
pub(crate) fn evaluate_body(
&mut self,
body: &[Statement],
) -> Result<Option<Rc<Value>>, EvaluationError> {
for statement in body {
if let Some(v) = self.evaluate_statement(statement)? {
return Ok(Some(v));
}
}
Ok(None)
}
fn evaluate_expression(&self, expression: &Expression) -> Result<Rc<Value>, EvaluationError> {
match expression {
Expression::Boolean(b) => Ok(Rc::new(Value::Boolean(*b))),
Expression::Float(f) => Ok(Rc::new(Value::Float(*f))),
Expression::Function(function) => Ok(Rc::new(Value::Function(function.clone()))),
Expression::Integer(i) => Ok(Rc::new(Value::Integer(*i))),
Expression::StringLiteral(s) => Ok(Rc::new(Value::String(s.clone()))),
Expression::Identifier(identifier) => self.values.get(identifier).map_or_else(
|| Err(EvaluationError::UnknownIdentifier(identifier.to_string())),
|value| Ok(Rc::clone(value)),
),
Expression::Call(call) => {
if let Some(value) = self.values.get(&call.name) {
match &**value {
Value::Boolean(_)
| Value::Float(_)
| Value::Integer(_)
| Value::String(_) => {
Err(EvaluationError::NonCallableType((**value).to_string()))
}
Value::Function(function) => {
if function.arguments.len() == call.arguments.len() {
let mut function_frame = Self::new();
for (arg_name, arg_expression) in
function.arguments.iter().zip(call.arguments.iter())
{
let argument_value =
self.evaluate_expression(arg_expression)?;
function_frame
.values
.insert(arg_name.clone(), argument_value);
}
(function_frame.evaluate_body(&function.body)?).map_or_else(
|| Err(EvaluationError::NoReturnValue(call.name.clone())),
|return_value| Ok(Rc::clone(&return_value)),
)
} else {
Err(EvaluationError::ArgumentCountMismatch {
name: call.name.clone(),
expected: function.arguments.len(),
got: call.arguments.len(),
})
}
}
}
} else {
Err(EvaluationError::UnknownIdentifier(call.name.clone()))
}
}
Expression::UnaryOp(op) => self.evaluate_unary_op(op),
Expression::BinaryOp(op) => self.evaluate_binary_op(op),
}
}
fn evaluate_statement(
&mut self,
statement: &Statement,
) -> Result<Option<Rc<Value>>, EvaluationError> {
match &statement {
Statement::Let(let_statement) => {
let value = self.evaluate_expression(&let_statement.expression)?;
self.values.insert(let_statement.identifier.clone(), value);
Ok(None)
}
Statement::Return(return_statement) => {
Ok(Some(self.evaluate_expression(return_statement)?))
}
Statement::Expression(expression) => {
let _value = self.evaluate_expression(expression);
// TODO: Print _value to the console if we're in a REPL.
Ok(None)
}
}
}
fn evaluate_unary_op(&self, op: &UnaryOp) -> Result<Rc<Value>, EvaluationError> {
let target = self.evaluate_expression(&op.target)?;
match (&*target, &op.operation) {
(Value::Float(_) | Value::Integer(_), OpName::Plus) => Ok(target.clone()),
(Value::Float(f), OpName::Minus) => Ok(Rc::new(Value::Float(-f))),
(Value::Integer(i), OpName::Minus) => Ok(Rc::new(Value::Integer(-i))),
(
Value::Boolean(_)
| Value::Function(_)
| Value::String(_)
| Value::Float(_)
| Value::Integer(_),
_,
) => Err(EvaluationError::IllegalUnaryOperation {
opname: op.operation.to_string(),
value: (*target).to_string(),
}),
}
}
fn evaluate_binary_op(&self, op: &BinaryOp) -> Result<Rc<Value>, EvaluationError> {
let left = self.evaluate_expression(&op.left)?;
let right = self.evaluate_expression(&op.right)?;
match (&op.operation, &*left, &*right) {
(OpName::Plus, &Value::Integer(lhs), &Value::Integer(rhs)) => {
Ok(Rc::new(Value::Integer(lhs + rhs)))
}
(OpName::Minus, &Value::Integer(lhs), &Value::Integer(rhs)) => {
Ok(Rc::new(Value::Integer(lhs - rhs)))
}
(OpName::Divide, &Value::Integer(lhs), &Value::Integer(rhs)) => {
Ok(Rc::new(Value::Integer(lhs / rhs)))
}
(OpName::Multiply, &Value::Integer(lhs), &Value::Integer(rhs)) => {
Ok(Rc::new(Value::Integer(lhs * rhs)))
}
(OpName::Plus, &Value::Float(lhs), &Value::Float(rhs)) => {
Ok(Rc::new(Value::Float(lhs + rhs)))
}
(OpName::Minus, &Value::Float(lhs), &Value::Float(rhs)) => {
Ok(Rc::new(Value::Float(lhs - rhs)))
}
(OpName::Divide, &Value::Float(lhs), &Value::Float(rhs)) => {
Ok(Rc::new(Value::Float(lhs / rhs)))
}
(OpName::Multiply, &Value::Float(lhs), &Value::Float(rhs)) => {
Ok(Rc::new(Value::Float(lhs * rhs)))
}
_ => Err(EvaluationError::IllegalBinaryOperation {
opname: op.operation.to_string(),
left: left.to_string(),
right: right.to_string(),
}),
}
}
}
| true
|
9f6d6cab3295d329c4a4e91d8b2012c420e076ed
|
Rust
|
tatetian/ngo2
|
/src/libos/src/entry/context_switch/gp_regs.rs
|
UTF-8
| 1,147
| 2.5625
| 3
|
[
"BSD-3-Clause"
] |
permissive
|
use crate::prelude::*;
/// The general-purpose registers of CPU.
///
/// Note. The Rust definition of this struct must be kept in sync with assembly code.
#[derive(Clone, Copy, Debug, Default)]
#[repr(C)]
pub struct GpRegs {
pub r8: u64,
pub r9: u64,
pub r10: u64,
pub r11: u64,
pub r12: u64,
pub r13: u64,
pub r14: u64,
pub r15: u64,
pub rdi: u64,
pub rsi: u64,
pub rbp: u64,
pub rbx: u64,
pub rdx: u64,
pub rax: u64,
pub rcx: u64,
pub rsp: u64,
pub rip: u64,
pub rflags: u64,
}
impl From<&sgx_cpu_context_t> for GpRegs {
fn from(src: &sgx_cpu_context_t) -> Self {
Self {
r8: src.r8,
r9: src.r9,
r10: src.r10,
r11: src.r11,
r12: src.r12,
r13: src.r13,
r14: src.r14,
r15: src.r15,
rdi: src.rdi,
rsi: src.rsi,
rbp: src.rbp,
rbx: src.rbx,
rdx: src.rdx,
rax: src.rax,
rcx: src.rcx,
rsp: src.rsp,
rip: src.rip,
rflags: src.rflags,
}
}
}
| true
|
d9272fe0ee2e4eb06d3f65f8aa5b66cd7332d701
|
Rust
|
Cazadorro/sfal
|
/src/erfc.rs
|
UTF-8
| 4,869
| 3.234375
| 3
|
[
"MIT"
] |
permissive
|
/// Functions that approximate the erfc(x), the "Complementary Error Function".
use super::erf;
use super::consts;
use std::f64;
///https://en.wikipedia.org/wiki/Error_function#Asymptotic_expansion
pub fn divergent_series(x: f64, max_n: u64) -> f64 {
let mut prod = 1.0;
let mut sum = 1.0;
for n in 1..max_n {
if n & 1 == 1 {
prod *= n as f64;
}
prod /= (2.0 * x * x);
}
(f64::exp(-(x * x)) / (x * f64::consts::PI.sqrt())) * sum
}
///https://en.wikipedia.org/wiki/Error_function#Continued_fraction_expansion
pub fn continued_fraction(x: f64, max_n: u64) -> f64 {
let mut fraction = 1.0;
for i in (1..=max_n).rev() {
let ai = i as f64 / 2.0;
if i & 1 == 1 {
fraction = (x * x) + (ai as f64 / fraction);
} else {
fraction = 1.0 + (ai as f64 / fraction);
}
}
(x / f64::consts::PI.sqrt()) * f64::exp(-(x * x)) / fraction
}
///https://en.wikipedia.org/wiki/Error_function#Numerical_approximations
pub fn abramowitz_0(x: f64) -> f64 {
let x_negative = x < 0.0;
let x = if x_negative { -x } else { x };
let ai_array = [0.278393, 0.230389, 0.000972, 0.078108];
let mut denominator_sum = 1.0_f64;
let mut x_prod = 1.0;
for i in 0..ai_array.len() {
x_prod *= x;
denominator_sum += ai_array[i] * x_prod;
}
let result = (1.0 / denominator_sum.powi(4));
if x_negative {
-result
} else {
result
}
}
///https://en.wikipedia.org/wiki/Error_function#Numerical_approximations
pub fn abramowitz_1(x: f64) -> f64 {
let x_negative = x < 0.0;
let x = if x_negative { -x } else { x };
let p = 0.47047;
let t = 1.0/(1.0 + p*x);
let ai_array = [0.3480242,-0.0958798,0.7478556];
let mut sum = 1.0;
let mut t_prod = 1.0;
for i in 0..ai_array.len() {
t_prod *= t;
sum += ai_array[i] * t_prod;
}
let result = (sum*f64::exp(-(x*x)));
if x_negative {
-result
} else {
result
}
}
///https://en.wikipedia.org/wiki/Error_function#Numerical_approximations
pub fn abramowitz_2(x: f64) -> f64 {
let x_negative = x < 0.0;
let x = if x_negative { -x } else { x };
let ai_array = [0.0705230784, 0.0422820123, 0.0092705272, 0.0001520143, 0.0002765672, 0.0000430638];
let mut denominator_sum = 1.0_f64;
let mut x_prod = 1.0;
for i in 0..ai_array.len() {
x_prod *= x;
denominator_sum += ai_array[i] * x_prod;
}
let result = (1.0 / denominator_sum.powi(16));
if x_negative {
-result
} else {
result
}
}
///https://en.wikipedia.org/wiki/Error_function#Numerical_approximations
pub fn abramowitz_3(x: f64) -> f64 {
let x_negative = x < 0.0;
let x = if x_negative { -x } else { x };
let p = 0.3275911;
let t = 1.0/(1.0 + p*x);
let ai_array = [0.254829592,-0.284496736,1.421413741,-1.453152027,1.061405429];
let mut sum = 1.0;
let mut t_prod = 1.0;
for i in 0..ai_array.len() {
t_prod *= t;
sum += ai_array[i] * t_prod;
}
let result = (sum*f64::exp(-(x*x)));
if x_negative {
-result
} else {
result
}
}
///https://en.wikipedia.org/wiki/Error_function#Numerical_approximations
pub fn karagiannidis(x: f64) -> f64{
let x_negative = x < 0.0;
let x = if x_negative { -x } else { x };
let a = 1.98;
let b = 1.135;
let result = ((1.0 - f64::exp(-a*x))*f64::exp(-(x*x)))/(b * f64::consts::PI.sqrt() * x);
if x_negative {
-result
} else {
result
}
}
///https://en.wikipedia.org/wiki/Error_function#Numerical_approximations
pub fn sergei_pade(x:f64)-> f64{
1.0 - erf::sergei_pade(x)
}
pub fn polynomial_9th(x:f64) -> f64{
1.0 - erf::polynomial_9th(x)
}
///Numerical Recipes third edition page 265.
pub fn recipes_cheb(x : f64) -> f64{
let cheb_coef_array = [-1.3026537197817094, 6.4196979235649026e-1,
1.9476473204185836e-2,-9.561514786808631e-3,-9.46595344482036e-4,
3.66839497852761e-4,4.2523324806907e-5,-2.0278578112534e-5,
-1.624290004647e-6,1.303655835580e-6,1.5626441722e-8,-8.5238095915e-8,
6.529054439e-9,5.059343495e-9,-9.91364156e-10,-2.27365122e-10,
9.6467911e-11, 2.394038e-12,-6.886027e-12,8.94487e-13, 3.13092e-13,
-1.12708e-13,3.81e-16,7.106e-15,-1.523e-15,-9.4e-17,1.21e-16,-2.8e-17];
let mut d=0.0;
let mut dd=0.0;
let x_negative = x < 0.0;
let x = if x_negative{ -x }else{ x };
let t = 2.0/(2.0+x);
let ty = 4.0*t - 2.0;
for j in (0..cheb_coef_array.len()).rev() {
let tmp = d;
d = ty*d - dd + cheb_coef_array[j as usize];
dd = tmp;
}
let result = t*f64::exp(-x*x + 0.5*(cheb_coef_array[0] + ty*d) - dd);
if x_negative{
-result
}else{
result
}
}
| true
|
e95967df9ce5dd18e8ee73c489ce9ef120d27977
|
Rust
|
fuerstenau/gorrosion-gtp
|
/src/data/color.rs
|
UTF-8
| 778
| 2.859375
| 3
|
[] |
no_license
|
use super::super::messages::WriteGTP;
use super::*;
use std::io;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Value {
Black,
White,
}
impl WriteGTP for Value {
fn write_gtp(&self, f: &mut impl io::Write) -> io::Result<()> {
match self {
Value::Black => write!(f, "Black"),
Value::White => write!(f, "White"),
}
}
}
singleton_type!(Color);
impl HasType<Type> for Value {
fn has_type(&self, _t: &Type) -> bool {
true
}
}
impl Data for Value {
type Type = Type;
fn parse<'a, I: Input<'a>>(i: I, _t: &Self::Type) -> IResult<I, Self> {
#[rustfmt::skip]
alt!(i,
value!(
Value::White,
alt!(tag_no_case!("W") | tag_no_case!("white"))
) |
value!(
Value::Black,
alt!(tag_no_case!("B") | tag_no_case!("black"))
)
)
}
}
| true
|
f75ec2b2f15bd84d20f2a363894ec906bd7cecb0
|
Rust
|
skanev/playground
|
/advent-of-code/2021/day09/src/main.rs
|
UTF-8
| 1,989
| 3.328125
| 3
|
[] |
no_license
|
use std::{collections::VecDeque, fs};
fn parse_input() -> Vec<Vec<u8>> {
let text = fs::read_to_string("../inputs/09").unwrap();
let height = text.lines().count();
let width = text.lines().next().unwrap().len();
let mut result = vec![vec![9; width + 2]; height + 2];
for (i, line) in text.lines().enumerate() {
for (j, byte) in line.bytes().enumerate() {
result[i + 1][j + 1] = byte - b'0';
}
}
result
}
fn low_points(map: &Vec<Vec<u8>>) -> Vec<(usize, usize)> {
let height = map.len();
let width = map[0].len();
let mut result = vec![];
for i in 1..(height - 2) {
for j in 1..(width - 2) {
if map[i][j] < map[i - 1][j]
&& map[i][j] < map[i + 1][j]
&& map[i][j] < map[i][j - 1]
&& map[i][j] < map[i][j + 1]
{
result.push((i, j));
}
}
}
result
}
fn fill(map: &mut Vec<Vec<u8>>, point: (usize, usize)) -> usize {
let mut left: VecDeque<(usize, usize)> = VecDeque::new();
let mut count = 0;
left.push_back(point);
while left.len() > 0 {
let point = left.pop_front().unwrap();
if map[point.0][point.1] == 9 {
continue;
}
map[point.0][point.1] = 9;
count += 1;
left.push_back((point.0 - 1, point.1));
left.push_back((point.0 + 1, point.1));
left.push_back((point.0, point.1 - 1));
left.push_back((point.0, point.1 + 1));
}
count
}
fn main() {
let mut map = parse_input();
let lows = low_points(&map);
let first: usize = lows.iter().map(|&(x, y)| (map[x][y] as usize) + 1).sum();
let mut basins: Vec<usize> = vec![];
for point in lows {
basins.push(fill(&mut map, point));
}
basins.sort();
let second: usize = basins[basins.len() - 3..].iter().product();
println!("first = {}", first);
println!("second = {}", second);
}
| true
|
9170d885608392e23cee3e89a0170fb7bf621d19
|
Rust
|
ArthurMatthys/Gomoku
|
/src/model/score_board.rs
|
UTF-8
| 2,434
| 2.875
| 3
|
[] |
no_license
|
use super::super::render::board::SIZE_BOARD;
#[derive(Clone, Copy)]
pub struct ScoreBoard([[[(u8, Option<bool>, Option<bool>); 4]; SIZE_BOARD]; SIZE_BOARD]);
impl ScoreBoard {
/// Retrieve score_board[x][y][dir]
pub fn get(&self, x: usize, y: usize, dir: usize) -> (u8, Option<bool>, Option<bool>) {
self.0[x][y][dir]
}
/// Check and Retrieve score_board[x][y][dir] if possible
pub fn get_check(
&self,
x: usize,
y: usize,
dir: usize,
) -> Option<(u8, Option<bool>, Option<bool>)> {
self.0
.get(x)
.map(|b| b.get(y).map(|c| c.get(dir)))
.flatten()
.flatten()
.cloned()
}
/// Change value of score_board[x][y][dir]
pub fn set(
&mut self,
x: usize,
y: usize,
dir: usize,
score: (u8, Option<bool>, Option<bool>),
) -> () {
self.0[x][y][dir] = score;
}
/// Retrieve score_board[x][y]
pub fn get_arr(&self, x: usize, y: usize) -> [(u8, Option<bool>, Option<bool>); 4] {
self.0[x][y]
}
pub fn reset(&mut self, x: usize, y: usize, dir: usize) -> () {
self.0[x][y][dir] = (0, Some(false), Some(false));
}
// Print score_board
pub fn print(&self) -> () {
self.0.iter().for_each(|x| {
x.iter().for_each(|y| {
y.iter().for_each(|el| print!("{:2}", el.0));
print!("||");
});
println!();
})
}
}
impl From<[[[(u8, Option<bool>, Option<bool>); 4]; SIZE_BOARD]; SIZE_BOARD]> for ScoreBoard {
fn from(item: [[[(u8, Option<bool>, Option<bool>); 4]; SIZE_BOARD]; SIZE_BOARD]) -> Self {
ScoreBoard(item)
}
}
impl From<ScoreBoard> for [[[(u8, Option<bool>, Option<bool>); 4]; SIZE_BOARD]; SIZE_BOARD] {
fn from(item: ScoreBoard) -> Self {
item.0
}
}
impl PartialEq for ScoreBoard {
fn eq(&self, other: &Self) -> bool {
for x in 0..SIZE_BOARD {
for y in 0..SIZE_BOARD {
for dir in 0..4 {
if self.0[x][y][dir].0 != other.0[x][y][dir].0
|| self.0[x][y][dir].1 != other.0[x][y][dir].1
|| self.0[x][y][dir].2 != other.0[x][y][dir].2
{
return false;
}
}
}
}
true
}
}
| true
|
78e668f8d152738b18f2c4770faed77a5edf2d21
|
Rust
|
kerinin/email-rs
|
/src/rfc2822/quoted.rs
|
UTF-8
| 6,883
| 2.734375
| 3
|
[] |
no_license
|
use bytes::{Bytes, ByteStr};
use chomp::*;
use rfc2822::folding::*;
use rfc2822::obsolete::*;
use rfc2822::primitive::*;
// quoted-pair = ("\" text) / obs-qp
// Consumes & returns matches
pub fn quoted_pair(i: Input<u8>) -> U8Result<u8> {
parse!{i;
or(
|i| parse!{i; token(b'\\') >> text() },
obs_qp,
)}
}
/*
#[test]
pub fn test_quoted_pair() {
assert_eq!(parse_only(quoted_pair, "\\\n".as_bytes()), Ok("\n".as_bytes()));
}
*/
// qtext = NO-WS-CTL / ; Non white space controls
//
// %d33 / ; The rest of the US-ASCII
// %d35-91 / ; characters not including "\"
// %d93-126 ; or the quote character
const QTEXT: [bool; 256] = [
// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
false, true, true, true, true, true, true, true, true, false, false, true, true, false, true, true, true, true, true, true, // 0 - 19
true, true, true, true, true, true, true, true, true, true, true, true, false, true, false, true, true, true, true, true, // 20 - 39
true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, // 40 - 59
true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, // 60 - 79
true, true, true, true, true, true, true, true, true, true, true, true, false, true, true, true, true, true, true, true, // 80 - 99
true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, // 100 - 119
true, true, true, true, true, true, true, true, false, false, false, false, false, false, false, false, false, false, false, false, // 120 - 139
false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, // 140 - 159
false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, // 160 - 179
false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, // 180 - 199
false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, // 200 - 219
false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, // 220 - 239
false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false // 240 - 256
];
pub fn qtext(i: Input<u8>) -> U8Result<u8> {
satisfy(i, |c| QTEXT[c as usize])
}
// qcontent = qtext / quoted-pair
pub fn qcontent(i: Input<u8>) -> U8Result<u8> {
parse!{i;
qtext() <|> quoted_pair()
}
}
#[test]
fn test_qcontent() {
let i = b"G";
let msg = parse_only(qcontent, i);
assert!(msg.is_ok());
assert_eq!(msg.unwrap(), b'G');
let i = b"\\\"";
let msg = parse_only(qcontent, i);
assert!(msg.is_ok());
assert_eq!(msg.unwrap(), b'\"');
}
// quoted-string = [CFWS]
// DQUOTE *([FWS] qcontent) [FWS] DQUOTE
// [CFWS]
// NOTE: in order to reduce allocations, this checks for runs of qtext
// explicitly, so expanding things out:
// quoted-string = [CFWS] DQUOTE *([FWS] qcontent) [FWS] DQUOTE [CFWS]
//
// substitute qcontent:
// = [CFWS] DQUOTE *([FWS] (qtext / quoted-pair)) [FWS] DQUOTE [CFWS]
//
// associate many
// = [CFWS] DQUOTE *([FWS] (1*qtext / quoted-pair)) [FWS] DQUOTE [CFWS]
//
pub fn quoted_string(i: Input<u8>) -> U8Result<Bytes> {
option(i, cfws, Bytes::empty()).bind(|i, ws1| {
dquote(i).then(|i| {
let a = |i| {
option(i, fws, Bytes::empty()).bind(|i, ws2| {
or(i,
|i| matched_by(i, |i| skip_many1(i, qtext)).map(|(v, _)| Bytes::from_slice(v)),
|i| quoted_pair(i).map(|c| Bytes::from_slice(&[c][..])),
).bind(|i, cs| {
i.ret(ws2.concat(&cs))
})
})
};
many(i, a).bind(|i, rs: Vec<Bytes>| {
option(i, fws, Bytes::empty()).bind(|i, ws3| {
dquote(i).then(|i| {
option(i, cfws, Bytes::empty()).bind(|i, ws4| {
let bs = rs.into_iter().fold(ws1, |acc, r| acc.concat(&r));
i.ret(bs.concat(&ws3).concat(&ws4))
})
})
})
})
})
})
}
#[test]
fn test_quoted_string() {
let i = b"\"Giant; \\\"Big\\\" Box\"";
let msg = parse_only(quoted_string, i);
assert!(msg.is_ok());
assert_eq!(msg.unwrap(), Bytes::from_slice(b"Giant; \"Big\" Box"));
}
pub fn quoted_string_not<P>(i: Input<u8>, mut p: P) -> U8Result<Bytes> where
P: FnMut(u8) -> bool,
{
option(i, cfws, Bytes::empty()).bind(|i, ws1| {
dquote(i).then(|i| {
many1(i, |i| {
option(i, fws, Bytes::empty()).bind(|i, ws2| {
matched_by(i, |i| {
peek_next(i).bind(|i, next| {
if p(next) {
i.err(Error::Unexpected)
} else {
qcontent(i)
}
})
}).bind(|i, (v, _)| {
i.ret(ws2.concat(&Bytes::from_slice(v)))
})
})
}).bind(|i, rs: Vec<Bytes>| {
option(i, fws, Bytes::empty()).bind(|i, ws3| {
dquote(i).then(|i| {
option(i, cfws, Bytes::empty()).bind(|i, ws4| {
let bs = rs.into_iter().fold(ws1, |acc, r| acc.concat(&r));
i.ret(bs.concat(&ws3).concat(&ws4))
})
})
})
})
})
})
}
#[test]
fn test_quoted_string_not() {
let i = b"\"jdoe\"";
let msg = parse_only(|i| quoted_string_not(i, |c| c == b'@'), i);
assert_eq!(msg, Ok(Bytes::from_slice(b"jdoe")));
let i = b"\"jdoe\"@example.com";
let msg = parse_only(|i| quoted_string_not(i, |c| c == b'@'), i);
assert_eq!(msg, Ok(Bytes::from_slice(b"jdoe")));
}
| true
|
50a892d11aded402f16b56046793a5e33e989d75
|
Rust
|
iCodeIN/rust-advent
|
/y2020/ex04/src/validators.rs
|
UTF-8
| 2,842
| 3.34375
| 3
|
[
"MIT"
] |
permissive
|
use regex::Regex;
use std::ops::RangeInclusive;
pub trait Validator {
fn validate(&self, value: &str) -> bool;
}
pub struct U16RangeValidator {
range: RangeInclusive<u16>,
}
impl U16RangeValidator {
pub fn new(range: RangeInclusive<u16>) -> Self {
U16RangeValidator { range }
}
}
impl Validator for U16RangeValidator {
fn validate(&self, value: &str) -> bool {
if let Ok(year) = value.parse::<u16>() {
return self.range.contains(&year);
}
false
}
}
pub struct RegexValidator {
regex: Regex,
}
impl RegexValidator {
pub fn new(regex: Regex) -> Self {
RegexValidator { regex }
}
}
impl Validator for RegexValidator {
fn validate(&self, value: &str) -> bool {
self.regex.is_match(value)
}
}
// byr (Birth Year) - four digits; at least 1920 and at most 2002.
pub fn create_byr_validator() -> U16RangeValidator {
U16RangeValidator::new(1920..=2002)
}
// iyr (Issue Year) - four digits; at least 2010 and at most 2020.
pub fn create_iyr_validator() -> U16RangeValidator {
U16RangeValidator::new(2010..=2020)
}
// eyr (Expiration Year) - four digits; at least 2020 and at most 2030.
pub fn create_eyr_validator() -> U16RangeValidator {
U16RangeValidator::new(2020..=2030)
}
// hgt (Height) - a number followed by either cm or in.
// If cm, the number must be at least 150 and at most 193.
// If in, the number must be at least 59 and at most 76.
pub struct HgtValidator {
regex: Regex,
}
impl HgtValidator {
pub fn new() -> Self {
let regex = Regex::new(r"^(\d+)(in|cm)$").unwrap();
HgtValidator { regex }
}
}
impl Validator for HgtValidator {
fn validate(&self, value: &str) -> bool {
if let Some(captures) = self.regex.captures(value) {
let unit = captures.get(2).unwrap().as_str();
if let Ok(num) = captures.get(1).unwrap().as_str().parse::<u16>() {
return (unit == "in" && (59..=76).contains(&num))
|| (unit == "cm" && (150..=193).contains(&num));
}
}
false
}
}
pub fn create_hgt_validator() -> HgtValidator {
HgtValidator::new()
}
// hcl (Hair Color) - a # followed by exactly six characters 0-9 or a-f.
pub fn create_hcl_validator() -> RegexValidator {
let regex = Regex::new(r"^#[0-9a-fA-F]{6}$").unwrap();
RegexValidator::new(regex)
}
// ecl (Eye Color) - exactly one of: amb blu brn gry grn hzl oth.
pub fn create_ecl_validator() -> RegexValidator {
let regex = Regex::new(r"^(amb|blu|brn|gry|grn|hzl|oth)$").unwrap();
RegexValidator::new(regex)
}
// pid (Passport ID) - a nine-digit number, including leading zeroes.
pub fn create_pid_validator() -> RegexValidator {
let regex = Regex::new(r"^\d{9}$").unwrap();
RegexValidator::new(regex)
}
| true
|
158bc4f31dcdf8670799376e3b8855835b601485
|
Rust
|
open-telemetry/opentelemetry-rust
|
/opentelemetry-sdk/src/testing/trace/in_memory_exporter.rs
|
UTF-8
| 4,403
| 2.734375
| 3
|
[
"Apache-2.0"
] |
permissive
|
use crate::export::trace::{ExportResult, SpanData, SpanExporter};
use futures_util::future::BoxFuture;
use opentelemetry::trace::{TraceError, TraceResult};
use std::sync::{Arc, Mutex};
/// An in-memory span exporter that stores span data in memory.
///
/// This exporter is useful for testing and debugging purposes. It stores
/// metric data in a `Vec<SpanData>`. Metrics can be retrieved
/// using the `get_finished_spans` method.
/// # Example
/// ```
///# use opentelemetry::trace::{SpanKind, TraceContextExt};
///# use opentelemetry::{global, trace::Tracer, Context};
///# use opentelemetry_sdk::propagation::TraceContextPropagator;
///# use opentelemetry_sdk::runtime;
///# use opentelemetry_sdk::testing::trace::InMemorySpanExporterBuilder;
///# use opentelemetry_sdk::trace::{BatchSpanProcessor, TracerProvider};
///
///# #[tokio::main]
///# async fn main() {
/// let exporter = InMemorySpanExporterBuilder::new().build();
/// let provider = TracerProvider::builder()
/// .with_span_processor(BatchSpanProcessor::builder(exporter.clone(), runtime::Tokio).build())
/// .build();
///
/// global::set_tracer_provider(provider.clone());
///
/// let tracer = global::tracer("example/in_memory_exporter");
/// let span = tracer
/// .span_builder("say hello")
/// .with_kind(SpanKind::Server)
/// .start(&tracer);
///
/// let cx = Context::current_with_span(span);
/// cx.span().add_event("handling this...", Vec::new());
/// cx.span().end();
///
/// let results = provider.force_flush();
/// for result in results {
/// if let Err(e) = result {
/// println!("{:?}", e)
/// }
/// }
/// let spans = exporter.get_finished_spans().unwrap();
/// for span in spans {
/// println!("{:?}", span)
/// }
///# }
/// ```
#[derive(Clone, Debug)]
pub struct InMemorySpanExporter {
spans: Arc<Mutex<Vec<SpanData>>>,
}
impl Default for InMemorySpanExporter {
fn default() -> Self {
InMemorySpanExporterBuilder::new().build()
}
}
/// Builder for [`InMemorySpanExporter`].
/// # Example
/// ```
///# use opentelemetry_sdk::testing::trace::InMemorySpanExporterBuilder;
///
/// let exporter = InMemorySpanExporterBuilder::new().build();
/// ```
#[derive(Clone, Debug)]
pub struct InMemorySpanExporterBuilder {}
impl Default for InMemorySpanExporterBuilder {
fn default() -> Self {
Self::new()
}
}
impl InMemorySpanExporterBuilder {
/// Creates a new instance of the `InMemorySpanExporterBuilder`.
pub fn new() -> Self {
Self {}
}
/// Creates a new instance of the `InMemorySpanExporter`.
pub fn build(&self) -> InMemorySpanExporter {
InMemorySpanExporter {
spans: Arc::new(Mutex::new(Vec::new())),
}
}
}
impl InMemorySpanExporter {
/// Returns the finished span as a vector of `SpanData`.
///
/// # Errors
///
/// Returns a `TraceError` if the internal lock cannot be acquired.
///
/// # Example
///
/// ```
/// # use opentelemetry_sdk::testing::trace::InMemorySpanExporter;
///
/// let exporter = InMemorySpanExporter::default();
/// let finished_spans = exporter.get_finished_spans().unwrap();
/// ```
pub fn get_finished_spans(&self) -> TraceResult<Vec<SpanData>> {
self.spans
.lock()
.map(|spans_guard| spans_guard.iter().cloned().collect())
.map_err(TraceError::from)
}
/// Clears the internal storage of finished spans.
///
/// # Example
///
/// ```
/// # use opentelemetry_sdk::testing::trace::InMemorySpanExporter;
///
/// let exporter = InMemorySpanExporter::default();
/// exporter.reset();
/// ```
pub fn reset(&self) {
let _ = self.spans.lock().map(|mut spans_guard| spans_guard.clear());
}
}
impl SpanExporter for InMemorySpanExporter {
fn export(&mut self, batch: Vec<SpanData>) -> BoxFuture<'static, ExportResult> {
if let Err(err) = self
.spans
.lock()
.map(|mut spans_guard| spans_guard.append(&mut batch.clone()))
.map_err(TraceError::from)
{
return Box::pin(std::future::ready(Err(Into::into(err))));
}
Box::pin(std::future::ready(Ok(())))
}
fn shutdown(&mut self) {
self.reset()
}
}
| true
|
2006d078ad47d36d15c36ed32964ca4e48ba983a
|
Rust
|
Jackywathy/mipsy
|
/crates/mipsy_web/src/components/pagebackground.rs
|
UTF-8
| 800
| 2.640625
| 3
|
[] |
no_license
|
use yew::prelude::*;
use yew::{Children, Properties};
#[derive(Properties, Clone)]
pub struct Props {
#[prop_or_default]
pub children: Children,
}
pub struct PageBackground {
pub props: Props,
}
impl Component for PageBackground {
type Message = ();
type Properties = Props;
fn create(props: Self::Properties, _: ComponentLink<Self>) -> Self {
PageBackground { props }
}
fn change(&mut self, props: Self::Properties) -> ShouldRender {
self.props = props;
true
}
fn update(&mut self, _: Self::Message) -> ShouldRender {
true
}
fn view(&self) -> Html {
html! {
<div class="min-h-screen py-2 bg-th-primary">
{ for self.props.children.iter() }
</div>
}
}
}
| true
|
6f26f1b91aa0aa6fbc61955934f49b2b711a4f1e
|
Rust
|
cjoh88/Zombie
|
/src/editor/input.rs
|
UTF-8
| 2,246
| 2.921875
| 3
|
[] |
no_license
|
use sfml::window::{Key};
use sfml::window::{event};
use sfml::window::MouseButton;
use sfml::graphics::{RenderWindow};
use sfml::system::{Vector2i, Vector2f};
use sfml::graphics::RenderTarget;
use editor::world::World;
pub struct EditorInputHandler {
dummy: i32
}
impl EditorInputHandler {
pub fn new() -> Self {
EditorInputHandler {
dummy: 0,
}
}
pub fn handle_input(&mut self, world: &mut World, window: &mut RenderWindow) {
for event in window.events() {
match event {
event::Closed => window.close(),
event::KeyPressed{code, ..} => self.handle_key_pressed(world, window, code), //world, window, code
event::KeyReleased{code, ..} => self.handle_key_released(world, window, code), //world, window, code
event::MouseButtonPressed{button, x, y} => self.handle_mouse_pressed(world, window, button, x, y), //world, window, button, x, y
_ => (),
}
}
}
fn handle_key_pressed(&mut self, world: &mut World, window: &mut RenderWindow, code: Key) {
match code {
Key::Escape => window.close(),
Key::Right | Key::D => world.get_mut_camera().move_right(),
Key::Left | Key::A => world.get_mut_camera().move_left(),
Key::Up | Key::W => world.get_mut_camera().move_up(),
Key::Down | Key::S => world.get_mut_camera().move_down(),
_ => ()
}
}
fn handle_key_released(&mut self, world: &mut World, window: &mut RenderWindow, code: Key) {
match code {
Key::Right | Key::Left | Key::D | Key::A => world.get_mut_camera().stop_horizontal(),
Key::Up | Key::Down | Key::W | Key::S => world.get_mut_camera().stop_vertical(),
Key::Add => world.get_mut_camera().zoom(0.5),
Key::Subtract => world.get_mut_camera().zoom(2.0),
_ => ()
}
}
fn handle_mouse_pressed(&mut self, editor: &mut World, window: &mut RenderWindow, code: MouseButton, x: i32, y: i32) {
/*let v = Vector2i::new(x,y);
let v2: Vector2f = window.map_pixel_to_coords(&v, &editor.get_view());
let v3 = screen_to_map(v2);
println!("Mouse({}, {})", v3.x, v3.y);*/
}
}
| true
|
9cfe05532aedfe26141eba73dd1bd0d2ee01e656
|
Rust
|
rust-lang/rust-analyzer
|
/crates/ide-diagnostics/src/handlers/unresolved_macro_call.rs
|
UTF-8
| 1,607
| 2.796875
| 3
|
[
"Apache-2.0",
"MIT"
] |
permissive
|
use crate::{Diagnostic, DiagnosticCode, DiagnosticsContext};
// Diagnostic: unresolved-macro-call
//
// This diagnostic is triggered if rust-analyzer is unable to resolve the path
// to a macro in a macro invocation.
pub(crate) fn unresolved_macro_call(
ctx: &DiagnosticsContext<'_>,
d: &hir::UnresolvedMacroCall,
) -> Diagnostic {
// Use more accurate position if available.
let display_range = ctx.resolve_precise_location(&d.macro_call, d.precise_location);
let bang = if d.is_bang { "!" } else { "" };
Diagnostic::new(
DiagnosticCode::RustcHardError("unresolved-macro-call"),
format!("unresolved macro `{}{bang}`", d.path.display(ctx.sema.db)),
display_range,
)
.experimental()
}
#[cfg(test)]
mod tests {
use crate::tests::check_diagnostics;
#[test]
fn unresolved_macro_diag() {
check_diagnostics(
r#"
fn f() {
m!();
} //^ error: unresolved macro `m!`
"#,
);
}
#[test]
fn test_unresolved_macro_range() {
check_diagnostics(
r#"
foo::bar!(92);
//^^^ error: unresolved macro `foo::bar!`
"#,
);
}
#[test]
fn unresolved_legacy_scope_macro() {
check_diagnostics(
r#"
macro_rules! m { () => {} }
m!(); m2!();
//^^ error: unresolved macro `m2!`
"#,
);
}
#[test]
fn unresolved_module_scope_macro() {
check_diagnostics(
r#"
mod mac {
#[macro_export]
macro_rules! m { () => {} } }
self::m!(); self::m2!();
//^^ error: unresolved macro `self::m2!`
"#,
);
}
}
| true
|
2d3c47f93338cb47dfcdef8c16ab9c8fa0fea7bf
|
Rust
|
zmbush/cargo
|
/src/cargo/core/resolver/mod.rs
|
UTF-8
| 22,960
| 2.546875
| 3
|
[
"GCC-exception-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"OpenSSL",
"Zlib",
"MIT",
"curl",
"GPL-2.0-only",
"LicenseRef-scancode-openssl",
"LicenseRef-scancode-ssleay-windows",
"Unlicense",
"LGPL-2.1-only",
"Apache-2.0"
] |
permissive
|
use std::cell::RefCell;
use std::collections::HashSet;
use std::collections::hash_map::HashMap;
use std::fmt;
use std::rc::Rc;
use semver;
use core::{PackageId, Registry, SourceId, Summary, Dependency};
use core::PackageIdSpec;
use util::{CargoResult, Graph, human, ChainError, CargoError};
use util::profile;
use util::graph::{Nodes, Edges};
pub use self::encode::{EncodableResolve, EncodableDependency, EncodablePackageId};
pub use self::encode::Metadata;
mod encode;
/// Represents a fully resolved package dependency graph. Each node in the graph
/// is a package and edges represent dependencies between packages.
///
/// Each instance of `Resolve` also understands the full set of features used
/// for each package as well as what the root package is.
#[derive(PartialEq, Eq, Clone)]
pub struct Resolve {
graph: Graph<PackageId>,
features: HashMap<PackageId, HashSet<String>>,
root: PackageId,
metadata: Option<Metadata>,
}
#[derive(Clone, Copy)]
pub enum Method<'a> {
Everything,
Required{ dev_deps: bool,
features: &'a [String],
uses_default_features: bool,
target_platform: Option<&'a str>},
}
impl Resolve {
fn new(root: PackageId) -> Resolve {
let mut g = Graph::new();
g.add(root.clone(), &[]);
Resolve { graph: g, root: root, features: HashMap::new(), metadata: None }
}
pub fn copy_metadata(&mut self, other: &Resolve) {
self.metadata = other.metadata.clone();
}
pub fn iter(&self) -> Nodes<PackageId> {
self.graph.iter()
}
pub fn root(&self) -> &PackageId { &self.root }
pub fn deps(&self, pkg: &PackageId) -> Option<Edges<PackageId>> {
self.graph.edges(pkg)
}
pub fn query(&self, spec: &str) -> CargoResult<&PackageId> {
let spec = try!(PackageIdSpec::parse(spec).chain_error(|| {
human(format!("invalid package id specification: `{}`", spec))
}));
let mut ids = self.iter().filter(|p| spec.matches(*p));
let ret = match ids.next() {
Some(id) => id,
None => return Err(human(format!("package id specification `{}` \
matched no packages", spec))),
};
return match ids.next() {
Some(other) => {
let mut msg = format!("There are multiple `{}` packages in \
your project, and the specification \
`{}` is ambiguous.\n\
Please re-run this command \
with `-p <spec>` where `<spec>` is one \
of the following:",
spec.name(), spec);
let mut vec = vec![ret, other];
vec.extend(ids);
minimize(&mut msg, vec, &spec);
Err(human(msg))
}
None => Ok(ret)
};
fn minimize(msg: &mut String,
ids: Vec<&PackageId>,
spec: &PackageIdSpec) {
let mut version_cnt = HashMap::new();
for id in ids.iter() {
*version_cnt.entry(id.version()).or_insert(0) += 1;
}
for id in ids.iter() {
if version_cnt[id.version()] == 1 {
msg.push_str(&format!("\n {}:{}", spec.name(),
id.version()));
} else {
msg.push_str(&format!("\n {}",
PackageIdSpec::from_package_id(*id)));
}
}
}
}
pub fn features(&self, pkg: &PackageId) -> Option<&HashSet<String>> {
self.features.get(pkg)
}
}
impl fmt::Debug for Resolve {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
try!(write!(fmt, "graph: {:?}\n", self.graph));
try!(write!(fmt, "\nfeatures: {{\n"));
for (pkg, features) in &self.features {
try!(write!(fmt, " {}: {:?}\n", pkg, features));
}
write!(fmt, "}}")
}
}
#[derive(Clone)]
struct Context {
activations: HashMap<(String, SourceId), Vec<Rc<Summary>>>,
resolve: Resolve,
visited: Rc<RefCell<HashSet<PackageId>>>,
}
/// Builds the list of all packages required to build the first argument.
pub fn resolve(summary: &Summary, method: Method,
registry: &mut Registry) -> CargoResult<Resolve> {
trace!("resolve; summary={}", summary.package_id());
let summary = Rc::new(summary.clone());
let cx = Box::new(Context {
resolve: Resolve::new(summary.package_id().clone()),
activations: HashMap::new(),
visited: Rc::new(RefCell::new(HashSet::new())),
});
let _p = profile::start(format!("resolving: {}", summary.package_id()));
match try!(activate(cx, registry, &summary, method)) {
Ok(cx) => {
debug!("resolved: {:?}", cx.resolve);
Ok(cx.resolve)
}
Err(e) => Err(e),
}
}
fn activate(mut cx: Box<Context>,
registry: &mut Registry,
parent: &Rc<Summary>,
method: Method)
-> CargoResult<CargoResult<Box<Context>>> {
// Dependency graphs are required to be a DAG, so we keep a set of
// packages we're visiting and bail if we hit a dupe.
let id = parent.package_id();
if !cx.visited.borrow_mut().insert(id.clone()) {
return Err(human(format!("cyclic package dependency: package `{}` \
depends on itself", id)))
}
// If we're already activated, then that was easy!
if flag_activated(&mut *cx, parent, &method) {
cx.visited.borrow_mut().remove(id);
return Ok(Ok(cx))
}
debug!("activating {}", parent.package_id());
// Extracting the platform request.
let platform = match method {
Method::Required{target_platform: platform, ..} => platform,
Method::Everything => None,
};
// First, figure out our set of dependencies based on the requsted set of
// features. This also calculates what features we're going to enable for
// our own dependencies.
let deps = try!(resolve_features(&mut cx, parent, method));
// Next, transform all dependencies into a list of possible candidates which
// can satisfy that dependency.
let mut deps = try!(deps.into_iter().map(|(_dep_name, (dep, features))| {
let mut candidates = try!(registry.query(dep));
// When we attempt versions for a package, we'll want to start at the
// maximum version and work our way down.
candidates.sort_by(|a, b| {
b.version().cmp(a.version())
});
let candidates = candidates.into_iter().map(Rc::new).collect::<Vec<_>>();
Ok((dep, candidates, features))
}).collect::<CargoResult<Vec<_>>>());
// When we recurse, attempt to resolve dependencies with fewer candidates
// before recursing on dependencies with more candidates. This way if the
// dependency with only one candidate can't be resolved we don't have to do
// a bunch of work before we figure that out.
deps.sort_by(|&(_, ref a, _), &(_, ref b, _)| {
a.len().cmp(&b.len())
});
// Workaround compilation error: `deps` does not live long enough
let platform = platform.map(|s| &*s);
Ok(match try!(activate_deps(cx, registry, parent, platform, &deps, 0)) {
Ok(cx) => {
cx.visited.borrow_mut().remove(parent.package_id());
Ok(cx)
}
Err(e) => Err(e),
})
}
// Activate this summary by inserting it into our list of known activations.
//
// Returns if this summary with the given method is already activated.
fn flag_activated(cx: &mut Context,
summary: &Rc<Summary>,
method: &Method) -> bool {
let id = summary.package_id();
let key = (id.name().to_string(), id.source_id().clone());
let prev = cx.activations.entry(key).or_insert(Vec::new());
if !prev.iter().any(|c| c == summary) {
cx.resolve.graph.add(id.clone(), &[]);
prev.push(summary.clone());
return false
}
debug!("checking if {} is already activated", summary.package_id());
let (features, use_default) = match *method {
Method::Required { features, uses_default_features, .. } => {
(features, uses_default_features)
}
Method::Everything => return false,
};
let has_default_feature = summary.features().contains_key("default");
match cx.resolve.features(id) {
Some(prev) => {
features.iter().all(|f| prev.contains(f)) &&
(!use_default || prev.contains("default") || !has_default_feature)
}
None => features.len() == 0 && (!use_default || !has_default_feature)
}
}
fn activate_deps<'a>(cx: Box<Context>,
registry: &mut Registry,
parent: &Summary,
platform: Option<&'a str>,
deps: &'a [(&Dependency, Vec<Rc<Summary>>, Vec<String>)],
cur: usize) -> CargoResult<CargoResult<Box<Context>>> {
if cur == deps.len() { return Ok(Ok(cx)) }
let (dep, ref candidates, ref features) = deps[cur];
let method = Method::Required{
dev_deps: false,
features: &features,
uses_default_features: dep.uses_default_features(),
target_platform: platform};
let key = (dep.name().to_string(), dep.source_id().clone());
let prev_active = cx.activations.get(&key)
.map(|v| &v[..]).unwrap_or(&[]);
trace!("{}[{}]>{} {} candidates", parent.name(), cur, dep.name(),
candidates.len());
trace!("{}[{}]>{} {} prev activations", parent.name(), cur,
dep.name(), prev_active.len());
// Filter the set of candidates based on the previously activated
// versions for this dependency. We can actually use a version if it
// precisely matches an activated version or if it is otherwise
// incompatible with all other activated versions. Note that we define
// "compatible" here in terms of the semver sense where if the left-most
// nonzero digit is the same they're considered compatible.
let my_candidates = candidates.iter().filter(|&b| {
prev_active.iter().any(|a| a == b) ||
prev_active.iter().all(|a| {
!compatible(a.version(), b.version())
})
});
// Alright, for each candidate that's gotten this far, it meets the
// following requirements:
//
// 1. The version matches the dependency requirement listed for this
// package
// 2. There are no activated versions for this package which are
// semver-compatible, or there's an activated version which is
// precisely equal to `candidate`.
//
// This means that we're going to attempt to activate each candidate in
// turn. We could possibly fail to activate each candidate, so we try
// each one in turn.
let mut last_err = None;
for candidate in my_candidates {
trace!("{}[{}]>{} trying {}", parent.name(), cur, dep.name(),
candidate.version());
let mut my_cx = cx.clone();
my_cx.resolve.graph.link(parent.package_id().clone(),
candidate.package_id().clone());
// If we hit an intransitive dependency then clear out the visitation
// list as we can't induce a cycle through transitive dependencies.
if !dep.is_transitive() {
my_cx.visited.borrow_mut().clear();
}
let my_cx = match try!(activate(my_cx, registry, candidate, method)) {
Ok(cx) => cx,
Err(e) => { last_err = Some(e); continue }
};
match try!(activate_deps(my_cx, registry, parent, platform, deps,
cur + 1)) {
Ok(cx) => return Ok(Ok(cx)),
Err(e) => { last_err = Some(e); }
}
}
trace!("{}[{}]>{} -- {:?}", parent.name(), cur, dep.name(),
last_err);
// Oh well, we couldn't activate any of the candidates, so we just can't
// activate this dependency at all
Ok(activation_error(&cx, registry, last_err, parent, dep, prev_active,
&candidates))
}
fn activation_error(cx: &Context,
registry: &mut Registry,
err: Option<Box<CargoError>>,
parent: &Summary,
dep: &Dependency,
prev_active: &[Rc<Summary>],
candidates: &[Rc<Summary>]) -> CargoResult<Box<Context>> {
match err {
Some(e) => return Err(e),
None => {}
}
if candidates.len() > 0 {
let mut msg = format!("failed to select a version for `{}` \
(required by `{}`):\n\
all possible versions conflict with \
previously selected versions of `{}`",
dep.name(), parent.name(),
dep.name());
'outer: for v in prev_active.iter() {
for node in cx.resolve.graph.iter() {
let edges = match cx.resolve.graph.edges(node) {
Some(edges) => edges,
None => continue,
};
for edge in edges {
if edge != v.package_id() { continue }
msg.push_str(&format!("\n version {} in use by {}",
v.version(), edge));
continue 'outer;
}
}
msg.push_str(&format!("\n version {} in use by ??",
v.version()));
}
msg.push_str(&format!("\n possible versions to select: {}",
candidates.iter()
.map(|v| v.version())
.map(|v| v.to_string())
.collect::<Vec<_>>()
.connect(", ")));
return Err(human(msg))
}
// Once we're all the way down here, we're definitely lost in the
// weeds! We didn't actually use any candidates above, so we need to
// give an error message that nothing was found.
//
// Note that we re-query the registry with a new dependency that
// allows any version so we can give some nicer error reporting
// which indicates a few versions that were actually found.
let msg = format!("no matching package named `{}` found \
(required by `{}`)\n\
location searched: {}\n\
version required: {}",
dep.name(), parent.name(),
dep.source_id(),
dep.version_req());
let mut msg = msg;
let all_req = semver::VersionReq::parse("*").unwrap();
let new_dep = dep.clone().set_version_req(all_req);
let mut candidates = try!(registry.query(&new_dep));
candidates.sort_by(|a, b| {
b.version().cmp(a.version())
});
if candidates.len() > 0 {
msg.push_str("\nversions found: ");
for (i, c) in candidates.iter().take(3).enumerate() {
if i != 0 { msg.push_str(", "); }
msg.push_str(&c.version().to_string());
}
if candidates.len() > 3 {
msg.push_str(", ...");
}
}
// If we have a path dependency with a locked version, then this may
// indicate that we updated a sub-package and forgot to run `cargo
// update`. In this case try to print a helpful error!
if dep.source_id().is_path() &&
dep.version_req().to_string().starts_with("=") &&
candidates.len() > 0 {
msg.push_str("\nconsider running `cargo update` to update \
a path dependency's locked version");
}
Err(human(msg))
}
// Returns if `a` and `b` are compatible in the semver sense. This is a
// commutative operation.
//
// Versions `a` and `b` are compatible if their left-most nonzero digit is the
// same.
fn compatible(a: &semver::Version, b: &semver::Version) -> bool {
if a.major != b.major { return false }
if a.major != 0 { return true }
if a.minor != b.minor { return false }
if a.minor != 0 { return true }
a.patch == b.patch
}
fn resolve_features<'a>(cx: &mut Context, parent: &'a Summary,
method: Method)
-> CargoResult<HashMap<&'a str,
(&'a Dependency, Vec<String>)>> {
let dev_deps = match method {
Method::Everything => true,
Method::Required { dev_deps, .. } => dev_deps,
};
// First, filter by dev-dependencies
let deps = parent.dependencies();
let deps = deps.iter().filter(|d| d.is_transitive() || dev_deps);
// Second, ignoring dependencies that should not be compiled for this platform
let deps = deps.filter(|d| {
match method {
Method::Required{target_platform: Some(ref platform), ..} => {
d.is_active_for_platform(platform)
},
_ => true
}
});
let (mut feature_deps, used_features) = try!(build_features(parent, method));
let mut ret = HashMap::new();
// Next, sanitize all requested features by whitelisting all the requested
// features that correspond to optional dependencies
for dep in deps {
// weed out optional dependencies, but not those required
if dep.is_optional() && !feature_deps.contains_key(dep.name()) {
continue
}
let mut base = feature_deps.remove(dep.name()).unwrap_or(vec![]);
for feature in dep.features().iter() {
base.push(feature.clone());
if feature.contains("/") {
return Err(human(format!("features in dependencies \
cannot enable features in \
other dependencies: `{}`",
feature)));
}
}
ret.insert(dep.name(), (dep, base));
}
// All features can only point to optional dependencies, in which case they
// should have all been weeded out by the above iteration. Any remaining
// features are bugs in that the package does not actually have those
// features.
if feature_deps.len() > 0 {
let unknown = feature_deps.keys().map(|s| &s[..])
.collect::<Vec<&str>>();
if unknown.len() > 0 {
let features = unknown.connect(", ");
return Err(human(format!("Package `{}` does not have these features: \
`{}`", parent.package_id(), features)))
}
}
// Record what list of features is active for this package.
if used_features.len() > 0 {
let pkgid = parent.package_id();
cx.resolve.features.entry(pkgid.clone())
.or_insert(HashSet::new())
.extend(used_features);
}
Ok(ret)
}
// Returns a pair of (feature dependencies, all used features)
//
// The feature dependencies map is a mapping of package name to list of features
// enabled. Each package should be enabled, and each package should have the
// specified set of features enabled.
//
// The all used features set is the set of features which this local package had
// enabled, which is later used when compiling to instruct the code what
// features were enabled.
fn build_features(s: &Summary, method: Method)
-> CargoResult<(HashMap<String, Vec<String>>, HashSet<String>)> {
let mut deps = HashMap::new();
let mut used = HashSet::new();
let mut visited = HashSet::new();
match method {
Method::Everything => {
for key in s.features().keys() {
try!(add_feature(s, key, &mut deps, &mut used, &mut visited));
}
for dep in s.dependencies().iter().filter(|d| d.is_optional()) {
try!(add_feature(s, dep.name(), &mut deps, &mut used,
&mut visited));
}
}
Method::Required{features: requested_features, ..} => {
for feat in requested_features.iter() {
try!(add_feature(s, feat, &mut deps, &mut used, &mut visited));
}
}
}
match method {
Method::Everything |
Method::Required { uses_default_features: true, .. } => {
if s.features().get("default").is_some() {
try!(add_feature(s, "default", &mut deps, &mut used,
&mut visited));
}
}
Method::Required { uses_default_features: false, .. } => {}
}
return Ok((deps, used));
fn add_feature(s: &Summary, feat: &str,
deps: &mut HashMap<String, Vec<String>>,
used: &mut HashSet<String>,
visited: &mut HashSet<String>) -> CargoResult<()> {
if feat.is_empty() { return Ok(()) }
// If this feature is of the form `foo/bar`, then we just lookup package
// `foo` and enable its feature `bar`. Otherwise this feature is of the
// form `foo` and we need to recurse to enable the feature `foo` for our
// own package, which may end up enabling more features or just enabling
// a dependency.
let mut parts = feat.splitn(2, '/');
let feat_or_package = parts.next().unwrap();
match parts.next() {
Some(feat) => {
let package = feat_or_package;
deps.entry(package.to_string())
.or_insert(Vec::new())
.push(feat.to_string());
}
None => {
let feat = feat_or_package;
if !visited.insert(feat.to_string()) {
return Err(human(format!("Cyclic feature dependency: \
feature `{}` depends on itself",
feat)))
}
used.insert(feat.to_string());
match s.features().get(feat) {
Some(recursive) => {
for f in recursive {
try!(add_feature(s, f, deps, used, visited));
}
}
None => {
deps.entry(feat.to_string()).or_insert(Vec::new());
}
}
visited.remove(&feat.to_string());
}
}
Ok(())
}
}
| true
|
1b4b1f4dd67bdc635d7c5d9cf5b1e7eb4b3d0c49
|
Rust
|
superhawk610/too-many-lists
|
/src/first_improved.rs
|
UTF-8
| 1,590
| 3.984375
| 4
|
[] |
no_license
|
/// some easy improvements over `first`
///
/// 1) change `Link` to simply alias `Option<Box<Node>>`
/// 2) substitute `std::mem::replace(x, None)` with `x.take()` (yay, options!)
/// 3) substitute `match option { None => None, Some(x) => Some(y) }` with `option.map(|x| y)`
pub struct List {
head: Link,
}
struct Node {
elem: i32,
next: Link,
}
type Link = Option<Box<Node>>;
impl List {
pub fn new() -> Self {
List { head: None }
}
pub fn push(&mut self, elem: i32) {
let new_node = Box::new(Node {
elem: elem,
next: self.head.take(),
});
self.head = Some(new_node);
}
pub fn pop(&mut self) -> Option<i32> {
self.pop_node().map(|node| node.elem)
}
fn pop_node(&mut self) -> Link {
self.head.take().map(|mut node| {
self.head = node.next.take();
node
})
}
}
impl Drop for List {
fn drop(&mut self) {
while let Some(_) = self.pop_node() {}
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn basics() {
let mut list = List::new();
list.push(1);
list.push(2);
list.push(3);
// normal removal...
assert_eq!(list.pop(), Some(3));
assert_eq!(list.pop(), Some(2));
list.push(4);
list.push(5);
// some more normal removal...
assert_eq!(list.pop(), Some(5));
assert_eq!(list.pop(), Some(4));
// and exhaustion...
assert_eq!(list.pop(), Some(1));
assert_eq!(list.pop(), None);
}
}
| true
|
c5dcb378d3f65c5222879e2c91b862b6baf218aa
|
Rust
|
steveklabnik/clog
|
/src/main.rs
|
UTF-8
| 2,413
| 2.59375
| 3
|
[
"MIT"
] |
permissive
|
#![crate_name = "clog"]
#![comment = "A conventional changelog generator"]
#![license = "MIT"]
#![feature(macro_rules, phase)]
extern crate regex;
#[phase(plugin)]
extern crate regex_macros;
extern crate serialize;
#[phase(plugin)] extern crate docopt_macros;
extern crate docopt;
extern crate time;
use git::{ LogReaderConfig };
use log_writer::{ LogWriter, LogWriterOptions };
use std::io::{File, Open, Write};
use docopt::FlagParser;
mod common;
mod git;
mod log_writer;
mod section_builder;
docopt!(Args, "clog
Usage:
clog [--repository=<link> --setversion=<version> --subtitle=<subtitle>
--from=<from> --to=<to> --from-latest-tag]
Options:
-h --help Show this screen.
--version Show version
-r --repository=<link> e.g https://github.com/thoughtram/clog
--setversion=<version> e.g. 0.1.0
--subtitle=<subtitle> e.g. crazy-release-name
--from=<from> e.g. 12a8546
--to=<to> e.g. 8057684
--from-latest-tag uses the latest tag as starting point. Ignores other --from parameter")
fn main () {
let start_nsec = ::time::get_time().nsec;
let args: Args = FlagParser::parse().unwrap_or_else(|e| e.exit());
let log_reader_config = LogReaderConfig {
grep: "^feat|^fix|BREAKING'".to_string(),
format: "%H%n%s%n%b%n==END==".to_string(),
from: if args.flag_from_latest_tag { ::git::get_latest_tag() } else { args.flag_from },
to: args.flag_to
};
let commits = ::git::get_log_entries(log_reader_config);
let sections = ::section_builder::build_sections(commits.clone());
let contents = match File::open(&Path::new("changelog.md")).read_to_string() {
Ok(content) => content,
Err(_) => "".to_string()
};
let mut file = File::open_mode(&Path::new("changelog.md"), Open, Write).ok().unwrap();
let mut writer = LogWriter::new(&mut file, LogWriterOptions {
repository_link: args.flag_repository,
version: args.flag_setversion,
subtitle: args.flag_subtitle
});
writer.write_header();
writer.write_section("Bug Fixes", §ions.fixes);
writer.write_section("Features", §ions.features);
writer.write(contents.as_slice());
let end_nsec = ::time::get_time().nsec;
let elapsed_mssec = (end_nsec - start_nsec) / 1000000;
println!("changelog updated. (took {} ms)", elapsed_mssec);
}
| true
|
62aae4363ffd1c7035a96dc556dd050825538727
|
Rust
|
geoffjay/codility-rs
|
/src/binary-gap/lib.rs
|
UTF-8
| 1,401
| 3.375
| 3
|
[] |
no_license
|
#![feature(test)]
extern crate test;
pub fn solution(n: i32) -> i32 {
let mut gap = 0;
let mut largest = 0;
let mut num = n;
let mut init = false;
loop {
// increase gap size when number is zero, and count has been initialized
if num & 1 == 0 {
if init {
gap += 1;
}
} else {
if gap > largest {
largest = gap;
}
gap = 0;
// start the count once a 1 has been seen
init = true;
}
num >>= 1;
if num == 0 {
break;
}
}
largest
}
#[cfg(test)]
mod tests {
use super::*;
use test::Bencher;
#[test]
fn it_works() {
assert_eq!(solution(9), 2);
assert_eq!(solution(529), 4);
assert_eq!(solution(20), 1);
assert_eq!(solution(15), 0);
assert_eq!(solution(1041), 5);
assert_eq!(solution(32), 0);
assert_eq!(solution(0b0000), 0);
assert_eq!(solution(0b10000), 0);
assert_eq!(solution(0b10000000), 0);
assert_eq!(solution(0b10000001), 6);
}
#[bench]
#[ignore]
fn bench_solution(b: &mut Bencher) {
b.iter(|| solution(204913));
}
#[bench]
#[ignore]
fn bench_solution_many(b: &mut Bencher) {
b.iter(|| (0..10000).map(solution).collect::<Vec<i32>>())
}
}
| true
|
7ead7a9fcd57b7a557255d3c2f5a347291de7637
|
Rust
|
rust-embedded/embedded-hal
|
/embedded-hal-nb/src/serial.rs
|
UTF-8
| 3,970
| 3.421875
| 3
|
[
"MIT",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
//! Serial interface.
/// Serial error.
pub trait Error: core::fmt::Debug {
/// Convert error to a generic serial error kind
///
/// By using this method, serial errors freely defined by HAL implementations
/// can be converted to a set of generic serial errors upon which generic
/// code can act.
fn kind(&self) -> ErrorKind;
}
impl Error for core::convert::Infallible {
#[inline]
fn kind(&self) -> ErrorKind {
match *self {}
}
}
/// Serial error kind.
///
/// This represents a common set of serial operation errors. HAL implementations are
/// free to define more specific or additional error types. However, by providing
/// a mapping to these common serial errors, generic code can still react to them.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
#[non_exhaustive]
pub enum ErrorKind {
/// The peripheral receive buffer was overrun.
Overrun,
/// Received data does not conform to the peripheral configuration.
/// Can be caused by a misconfigured device on either end of the serial line.
FrameFormat,
/// Parity check failed.
Parity,
/// Serial line is too noisy to read valid data.
Noise,
/// A different error occurred. The original error may contain more information.
Other,
}
impl Error for ErrorKind {
#[inline]
fn kind(&self) -> ErrorKind {
*self
}
}
impl core::fmt::Display for ErrorKind {
#[inline]
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::Overrun => write!(f, "The peripheral receive buffer was overrun"),
Self::Parity => write!(f, "Parity check failed"),
Self::Noise => write!(f, "Serial line is too noisy to read valid data"),
Self::FrameFormat => write!(
f,
"Received data does not conform to the peripheral configuration"
),
Self::Other => write!(
f,
"A different error occurred. The original error may contain more information"
),
}
}
}
/// Serial error type trait.
///
/// This just defines the error type, to be used by the other traits.
pub trait ErrorType {
/// Error type
type Error: Error;
}
impl<T: ErrorType + ?Sized> ErrorType for &mut T {
type Error = T::Error;
}
/// Read half of a serial interface.
///
/// Some serial interfaces support different data sizes (8 bits, 9 bits, etc.);
/// This can be encoded in this trait via the `Word` type parameter.
pub trait Read<Word: Copy = u8>: ErrorType {
/// Reads a single word from the serial interface
fn read(&mut self) -> nb::Result<Word, Self::Error>;
}
impl<T: Read<Word> + ?Sized, Word: Copy> Read<Word> for &mut T {
#[inline]
fn read(&mut self) -> nb::Result<Word, Self::Error> {
T::read(self)
}
}
/// Write half of a serial interface.
pub trait Write<Word: Copy = u8>: ErrorType {
/// Writes a single word to the serial interface.
fn write(&mut self, word: Word) -> nb::Result<(), Self::Error>;
/// Ensures that none of the previously written words are still buffered.
fn flush(&mut self) -> nb::Result<(), Self::Error>;
}
impl<T: Write<Word> + ?Sized, Word: Copy> Write<Word> for &mut T {
#[inline]
fn write(&mut self, word: Word) -> nb::Result<(), Self::Error> {
T::write(self, word)
}
#[inline]
fn flush(&mut self) -> nb::Result<(), Self::Error> {
T::flush(self)
}
}
/// Implementation of `core::fmt::Write` for the HAL's `serial::Write`.
///
/// TODO write example of usage
impl<Word, Error: self::Error> core::fmt::Write for dyn Write<Word, Error = Error> + '_
where
Word: Copy + From<u8>,
{
#[inline]
fn write_str(&mut self, s: &str) -> core::fmt::Result {
let _ = s
.bytes()
.map(|c| nb::block!(self.write(Word::from(c))))
.last();
Ok(())
}
}
| true
|
963697e7187c6fc18e4ed1c62c6b6aff79afb9cb
|
Rust
|
MiyamonY/atcoder
|
/abc/036/d/01/src/main.rs
|
UTF-8
| 2,655
| 2.859375
| 3
|
[] |
no_license
|
#[allow(unused_macros)]
macro_rules! scan {
() => {
{
let mut line: String = String::new();
std::io::stdin().read_line(&mut line).unwrap();
line.trim().to_string()
}
};
(;;) => {
{
let mut line: String = String::new();
std::io::stdin().read_line(&mut line).unwrap();
line.trim().split_whitespace().map(|s| s.to_string()).collect::<Vec<String>>()
}
};
(;;$n:expr) => {
{
(0..$n).map(|_| scan!()).collect::<Vec<_>>()
}
};
($t:ty) => {
{
let mut line: String = String::new();
std::io::stdin().read_line(&mut line).unwrap();
line.trim().parse::<$t>().unwrap()
}
};
($($t:ty),*) => {
{
let mut line: String = String::new();
std::io::stdin().read_line(&mut line).unwrap();
let mut iter = line.split_whitespace();
(
$(iter.next().unwrap().parse::<$t>().unwrap(),)*
)
}
};
($t:ty;;) => {
{
let mut line: String = String::new();
std::io::stdin().read_line(&mut line).unwrap();
line.split_whitespace()
.map(|t| t.parse::<$t>().unwrap())
.collect::<Vec<_>>()
}
};
($t:ty;;$n:expr) => {
(0..$n).map(|_| scan!($t;;)).collect::<Vec<_>>()
};
($t:ty; $n:expr) => {
(0..$n).map(|_|
scan!($t)
).collect::<Vec<_>>()
};
($($t:ty),*; $n:expr) => {
(0..$n).map(|_|
scan!($($t),*)
).collect::<Vec<_>>()
};
}
const MOD: i64 = 1_000_000_007;
fn dfs_w(graph: &[Vec<usize>], p: usize, n: usize, dp: &mut [Option<i64>]) -> i64 {
let mut whites = 1;
for &g in &graph[n] {
if g != p {
whites *= dfs(graph, n, g, dp);
whites %= MOD;
}
}
whites
}
fn dfs(graph: &[Vec<usize>], p: usize, n: usize, dp: &mut [Option<i64>]) -> i64 {
if let Some(v) = dp[n] {
return v;
}
let mut whites = 1;
for &g in &graph[n] {
if g != p {
whites *= dfs_w(graph, n, g, dp);
whites %= MOD;
}
}
let v = (dfs_w(graph, p, n, dp) + whites) % MOD;
dp[n] = Some(v);
v
}
fn main() {
let n = scan!(usize);
let mut graph = vec![vec![]; n + 1];
for _ in 0..n - 1 {
let (a, b) = scan!(usize, usize);
graph[a].push(b);
graph[b].push(a);
}
let mut dp = vec![None; n + 1];
println!("{}", dfs(&graph, 0, 1, &mut dp));
}
| true
|
c476bad1aefaa05cf003fa16b01a4248b0e75bc9
|
Rust
|
liu-hz18/rCore-v2
|
/src/process/kernel_stack.rs
|
UTF-8
| 3,748
| 3.5
| 4
|
[] |
no_license
|
//! 内核栈 [`KernelStack`]
//!
//! 用户态的线程出现中断时,因为用户栈无法保证可用性,中断处理流程必须在内核栈上进行。
//! 所以我们创建一个公用的内核栈,即当发生中断时,会将 Context 写到内核栈顶。
//!
//! ### 线程 [`Context`] 的存放
//! > 1. 线程初始化时,一个 `Context` 放置在内核栈顶,`sp` 指向 `Context` 的位置
//! > (即 栈顶 - `size_of::<Context>()`)
//! > 2. 切换到线程,执行 `__restore` 时,将 `Context` 的数据恢复到寄存器中后,
//! > 会将 `Context` 出栈(即 `sp += size_of::<Context>()`),
//! > 然后保存 `sp` 至 `sscratch`(此时 `sscratch` 即为内核栈顶)
//! > 3. 发生中断时,将 `sscratch` 和 `sp` 互换,入栈一个 `Context` 并保存数据
//!
//! 容易发现,线程的 `Context` 一定保存在内核栈顶。因此,当线程需要运行(切换到)时,
//! 从 [`Thread`] 中取出 `Context` 然后置于内核栈顶即可
// 做法:
// 1. 预留一段空间作为内核栈
// 2. 运行线程时,在 sscratch 寄存器中保存内核栈顶指针
// 3. 如果线程遇到中断,则将 Context 压入 sscratch 指向的栈中(Context 的地址为 sscratch - size_of::<Context>()),同时用新的栈地址来替换 sp(此时 sp 也会被复制到 a0 作为 handle_interrupt 的参数)
// 4. 从中断中返回时(__restore 时),a0 应指向被压在内核栈中的 Context。此时出栈 Context 并且将栈顶保存到 sscratch 中
use super::*;
use core::mem::size_of;
/// 内核栈
#[repr(align(16))]
#[repr(C)]
pub struct KernelStack([u8; KERNEL_STACK_SIZE]);
/// 公用的内核栈
pub static mut KERNEL_STACK: KernelStack = KernelStack([0; KERNEL_STACK_SIZE]);
// 创建线程时,需要使用的操作就是在内核栈顶压入一个初始状态 Context
impl KernelStack {
/// 在栈顶加入 Context 并且返回新的栈顶指针
pub fn push_context(&mut self, context: Context) -> *mut Context {
// 栈顶sp
let stack_top = &self.0 as *const _ as usize + size_of::<Self>();
// Context 的位置
let push_address = (stack_top - size_of::<Context>()) as *mut Context; // 编译器负责解析这个指针
// Context 压入栈顶
unsafe {
*push_address = context; // 编译器负责对内存对应位置依次赋值
}
push_address
}
}
// 关于内核栈(和sscratch)的作用的探讨:
/*
如果不使用 sscratch 提供内核栈,而是像原来一样,遇到中断就直接将上下文压栈, 会有什么问题?
1. 一种情况不会出现问题: 只运行一个非常善意的线程,比如 loop {}
2. 一种情况导致异常无法处理(指无法进入 handle_interrupt):
线程把自己的 sp 搞丢了,比如 mv sp, x0。此时无法保存寄存器,也没有能够支持操作系统正常运行的栈
3. 一种情况导致产生嵌套异常(指第二个异常能够进行到调用 handle_interrupt 时,不考虑后续执行情况)
运行两个线程。在两个线程切换的时候,会需要切换页表。但是此时操作系统运行在前一个线程的栈上,一旦切换,再访问栈就会导致缺页,因为每个线程的栈只在自己的页表中
4. 一种情况导致一个用户进程(先不考虑是怎么来的)可以将自己变为内核进程,或以内核态执行自己的代码
用户进程巧妙地设计 sp,使得它恰好落在内核的某些变量附近,于是在保存寄存器时就修改了变量的值。这相当于任意修改操作系统的控制信息
*/
| true
|
c35f2531daf6327618f829e4d7e15ea4dc61309f
|
Rust
|
gdoct/rustvm
|
/src/instructions/asl.rs
|
UTF-8
| 2,522
| 3.140625
| 3
|
[
"BSD-3-Clause"
] |
permissive
|
use crate::traits::{ Instruction, VirtualCpu };
use crate::types::{ Byte };
use crate::instructions::generic::*;
fn asl(cpu: &mut dyn VirtualCpu, num: Byte, with: Byte) {
let asl = num << with;
cpu.set_a(asl);
}
/// AslZp: ASL zeropage
/// Arithmetic Shift Left (ASL) operation between
/// the content of Accumulator and the content of
/// the zero page address
pub struct AslZp { }
impl Instruction for AslZp {
fn opcode (&self) -> &'static str { "ASL"}
fn hexcode(&self) -> Byte { 0x06 }
fn execute(&self, cpu: &mut dyn VirtualCpu) -> std::io::Result<()> {
let zp = fetch_zp_val(cpu)?;
let a = cpu.get_a();
asl(cpu, a, zp);
Ok(())
}
}
/// Asl: ASL
/// Arithmetic Shift Left (ASL) operation between immediate val
/// and the content of the Accumulator
pub struct Asl { }
impl Instruction for Asl {
fn opcode (&self) -> &'static str { "ASL"}
fn hexcode(&self) -> Byte { 0x0A }
fn execute(&self, cpu: &mut dyn VirtualCpu) -> std::io::Result<()> {
let imm = fetch_imm_val(cpu)?;
let a = cpu.get_a();
asl(cpu, imm, a);
Ok(())
}
}
/// AslAbs: ASL absolute
/// Arithmetic Shift Left (ASL) operation between the content of
/// Accumulator and the content located at address $1234
pub struct AslAbs { }
impl Instruction for AslAbs {
fn opcode (&self) -> &'static str { "ASL"}
fn hexcode(&self) -> Byte { 0x0E }
fn execute(&self, cpu: &mut dyn VirtualCpu) -> std::io::Result<()> {
let val = fetch_abs_val(cpu)?;
let a = cpu.get_a();
asl(cpu, a, val);
Ok(())
}
}
/// AslZpX: ASL absolute, indexed by X
pub struct AslZpX { }
impl Instruction for AslZpX {
fn opcode (&self) -> &'static str { "ASL"}
fn hexcode(&self) -> Byte { 0x16 }
fn execute(&self, cpu: &mut dyn VirtualCpu) -> std::io::Result<()> {
let val = fetch_absx_val(cpu)?;
let a = cpu.get_a();
asl(cpu, a, val);
Ok(())
}
}
/// AslAbsX: ASL absolute, indexed by X
/// Arithmetic Shift Left (ASL) operation between the content of Accumulator and the content
/// located at address calculated from $1234 adding content of X
pub struct AslAbsX { }
impl Instruction for AslAbsX {
fn opcode (&self) -> &'static str { "ASL"}
fn hexcode(&self) -> Byte { 0x1E }
fn execute(&self, cpu: &mut dyn VirtualCpu) -> std::io::Result<()> {
let val = fetch_absx_val(cpu)?;
let a = cpu.get_a();
asl(cpu, a, val);
Ok(())
}
}
| true
|
f7d335dc73bf00f15287442fb8a40d2d3abe1ccc
|
Rust
|
jamestthompson3/subtxt-rs
|
/src/lib.rs
|
UTF-8
| 2,535
| 3.75
| 4
|
[] |
no_license
|
pub struct Parser<'a> {
input: std::str::Lines<'a>,
}
impl<'a> Parser<'a> {
pub fn new(text: &'a str) -> Self {
Self {
input: text.lines(),
}
}
}
impl<'a> Iterator for Parser<'a> {
type Item = Event<'a>;
fn next(&mut self) -> Option<Self::Item> {
match self.input.next() {
Some(line) => {
if line.is_empty() {
return Some(Event::Empty);
}
let mut chars = line.chars();
match (chars.next().unwrap(), chars.next().unwrap()) {
('#', ' ') => Some(Event::Heading(line.split_at(2).1)),
('-', ' ') => Some(Event::List(line.split_at(2).1)),
('&', ' ') => Some(Event::Link(line.split_at(2).1)),
('>', ' ') => Some(Event::Quote(line.split_at(2).1)),
_ => Some(Event::Text(line)),
}
}
None => None,
}
}
}
#[derive(Debug, PartialEq)]
pub enum Event<'a> {
Heading(&'a str),
Text(&'a str),
List(&'a str),
Quote(&'a str),
Link(&'a str),
Empty,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_normal_input() {
let test_string = "# Heading\n- List1";
let parser = Parser::new(test_string);
let events = parser.collect::<Vec<Event>>();
assert_eq!(events[0], Event::Heading("Heading"));
assert_eq!(events[1], Event::List("List1"));
}
#[test]
fn parse_malformed_input() {
let test_string = "# ";
let parser = Parser::new(test_string);
let events = parser.collect::<Vec<Event>>();
assert_eq!(events[0], Event::Heading(""));
}
#[test]
fn parse_malformed_and_normal_input() {
let test_string = "# \n- List1";
let parser = Parser::new(test_string);
let events = parser.collect::<Vec<Event>>();
assert_eq!(events[0], Event::Heading(""));
assert_eq!(events[1], Event::List("List1"));
}
#[test]
fn parse_typo_input() {
let test_string = "-List1";
let parser = Parser::new(test_string);
let events = parser.collect::<Vec<Event>>();
assert_eq!(events[0], Event::Text("-List1"));
}
#[test]
fn parse_empty_lines() {
let test_string = "asdf\n\nasdf";
let parser = Parser::new(test_string);
let events = parser.collect::<Vec<Event>>();
assert_eq!(events[1], Event::Empty);
}
}
| true
|
31e738f9fca604d1584626d02ea022781ef862b6
|
Rust
|
SymmetricChaos/project_euler_rust
|
/src/worked_problems/euler_76.rs
|
UTF-8
| 2,993
| 3.5625
| 4
|
[] |
no_license
|
// Problem: How many different ways can one hundred be written as a sum of at least two positive integers?
/*
*/
struct AllIntegers {
ctr: i64,
parity: u8,
}
impl Iterator for AllIntegers {
type Item = i64;
fn next(&mut self) -> Option<i64> {
if self.parity == 0 {
self.parity = 1;
return Some(self.ctr)
} else {
self.parity = 0;
self.ctr += 1;
return Some(-(self.ctr-1))
}
}
}
fn gen_pentagonal(n: i64) -> i64 {
(3*n*n-n)/2
}
pub fn euler76() -> u64 {
let mut known_partitions = [0i64;101];
known_partitions[0] = 1;
known_partitions[1] = 1;
for n in 2..=100 {
let mut ctr = AllIntegers{ctr: 1, parity: 0};
let mut p = gen_pentagonal(ctr.next().unwrap());
let mut sum = 0;
let mut sign = [1,1,-1,-1].iter().cycle();
while p <= n {
sum += known_partitions[(n-p) as usize]*sign.next().unwrap();
p = gen_pentagonal(ctr.next().unwrap());
}
known_partitions[n as usize] = sum
}
// We need to subtract 1 because the partitions we calculated include the number itself as a partition
(known_partitions[100]-1) as u64
}
pub fn euler76_example() {
println!("\nProblem: How many different ways can one hundred be written as a sum of at least two positive integers?");
println!("\n\nThis could possibly be done using brute force to calculate partitions of each integer and then memoizing the results. However Euler's Pentagonal Number Theorem gives us a much more efficient option where we don't need to brute force calculate any partitions except for 0 and 1, which both have a single partition.");
let s = "
struct AllIntegers {
ctr: i64,
parity: u8,
}
impl Iterator for AllIntegers {
type Item = i64;
fn next(&mut self) -> Option<i64> {
if self.parity == 0 {
self.parity = 1;
return Some(self.ctr)
} else {
self.parity = 0;
self.ctr += 1;
return Some(-(self.ctr-1))
}
}
}
fn gen_pentagonal(n: i64) -> i64 {
(3*n*n-n)/2
}
pub fn euler76() -> u64 {
let mut known_partitions = [0i64;101];
known_partitions[0] = 1;
known_partitions[1] = 1;
for n in 2..=100 {
let mut ctr = AllIntegers{ctr: 1, parity: 0};
let mut p = gen_pentagonal(ctr.next().unwrap());
let mut sum = 0;
let mut sign = [1,1,-1,-1].iter().cycle();
while p <= n {
sum += known_partitions[(n-p) as usize]*sign.next().unwrap();
p = gen_pentagonal(ctr.next().unwrap());
}
known_partitions[n as usize] = sum
}
// We need to subtract 1 because the partitions we calculated include the number itself as a partition
(known_partitions[100]-1) as u64
}";
println!("\n{}\n",s);
println!("The answer is: {}",euler76());
}
#[test]
fn test76() {
assert_eq!(euler76(),190569291)
}
| true
|
6d6eb9ccc92b1b7c0c047bbda5e8f96466302ad9
|
Rust
|
mandx/harplay
|
/src/har/mod.rs
|
UTF-8
| 1,559
| 2.9375
| 3
|
[
"MIT"
] |
permissive
|
pub mod errors;
pub mod generic;
use std::fs::File;
use std::io::{BufReader, Read};
use std::path::Path;
use serde::{Deserialize, Serialize};
pub use errors::HarError;
use errors::*;
pub use generic::*;
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
pub struct Har {
pub log: Log,
}
/// Deserialize a HAR from a path
#[cfg_attr(tarpaulin, skip)]
pub fn from_path<P: AsRef<Path>>(path: P) -> Result<Har, HarError> {
from_reader(BufReader::new(File::open(path).context(Opening)?))
}
/// Deserialize a HAR from type which implements Read
pub fn from_reader<R: Read>(read: R) -> Result<Har, HarError> {
Ok(serde_json::from_reader::<R, Har>(read).context(Reading)?)
}
#[cfg(test)]
mod tests {
use super::*;
use assert_matches::assert_matches;
#[test]
fn load_from_not_json_or_har() {
let json = br#"{"some": "json"}"#;
assert_matches!(from_reader(&json[..]), Err(_));
let json = br#"{"log": {}}"#;
assert_matches!(from_reader(&json[..]), Err(_));
let json = br#"{"log":{"version":"1.2","pages":[],"entries":[]}}"#;
assert_matches!(from_reader(&json[..]), Err(_));
}
#[test]
fn load_from_har() {
let json =
br#"{"log":{"creator":{"name":"Creator?","version":"0.1"},"pages":[],"entries":[]}}"#;
assert_matches!(from_reader(&json[..]), Ok(_));
let json = br#"{"log":{"version":"1.2","creator":{"name":"Creator?","version":"0.1"},"pages":[],"entries":[]}}"#;
assert_matches!(from_reader(&json[..]), Ok(_));
}
}
| true
|
4f1f7675a2b1b60a4e4a2ee34b4bc0918db7bf77
|
Rust
|
arielb1/rustc-perf-collector
|
/src/execute.rs
|
UTF-8
| 3,855
| 2.609375
| 3
|
[
"MIT"
] |
permissive
|
//! Execute benchmarks in a sysroot.
use std::str;
use std::path::{Path, PathBuf};
use std::process::Command;
use tempdir::TempDir;
use rustc_perf_collector::{Patch, Run};
use errors::{Result, ResultExt};
use rust_sysroot::sysroot::Sysroot;
use time_passes::{PassAverager, process_output};
pub struct Benchmark {
pub name: String,
pub path: PathBuf
}
impl Benchmark {
pub fn command<P: AsRef<Path>>(&self, sysroot: &Sysroot, path: P) -> Command {
let mut command = sysroot.command(path);
command.current_dir(&self.path);
command
}
/// Run a specific benchmark on a specific commit
pub fn run(&self, sysroot: &Sysroot) -> Result<Vec<Patch>> {
info!("processing {}", self.name);
let mut patch_runs: Vec<Patch> = Vec::new();
for _ in 0..3 {
let tmp_dir = TempDir::new(&format!("rustc-benchmark-{}", self.name))?;
info!("temporary directory is {}", tmp_dir.path().display());
info!("copying files to temporary directory");
let output = self.command(sysroot, "cp").arg("-r").arg("-T").arg("--")
.arg(".").arg(tmp_dir.path()).output()?;
if !output.status.success() {
bail!("copy failed: {}", String::from_utf8_lossy(&output.stderr));
}
let make = || {
let mut command = sysroot.command("make");
command.current_dir(tmp_dir.path());
command
};
let output = make().arg("patches").output()?;
let mut patches = str::from_utf8(&output.stdout)
.chain_err(|| format!("make patches in {} returned non UTF-8 output", self.path.display()))?
.split_whitespace()
.collect::<Vec<_>>();
if patches.is_empty() {
patches.push("");
}
for patch in &patches {
info!("running `make all{}`", patch);
let output = make().arg(&format!("all{}", patch))
.env("CARGO_OPTS", "")
.env("CARGO_RUSTC_OPTS", "-Z time-passes")
.output()?;
if !output.status.success() {
bail!("stderr non empty: {},\n\n stdout={}",
String::from_utf8_lossy(&output.stderr),
String::from_utf8_lossy(&output.stdout)
);
}
let patch_index = if let Some(p) = patch_runs.iter().position(|p_run| p_run.patch == *patch) {
p
} else {
patch_runs.push(Patch {
patch: patch.to_string(),
name: self.name.clone(),
runs: Vec::new(),
});
patch_runs.len() - 1
};
let combined_name = format!("{}{}", self.name, patch);
patch_runs[patch_index].runs.push(Run {
passes: process_output(&combined_name, output.stdout)?,
name: combined_name,
});
}
}
let mut patches = Vec::new();
for patch_run in patch_runs {
let mut runs = patch_run.runs.into_iter();
let mut pa = PassAverager::new(runs.next().unwrap().passes);
for run in runs {
pa.average_with(run.passes)?;
}
patches.push(Patch {
name: patch_run.name.clone(),
patch: patch_run.patch.clone(),
runs: vec![
Run {
name: patch_run.name + &patch_run.patch,
passes: pa.state,
}
],
});
}
Ok(patches)
}
}
| true
|
9dbba9ca63b7899339ef99ae88d923535b42df89
|
Rust
|
matthew86707/PDESimulator
|
/PDESimulator/src/simulation.rs
|
UTF-8
| 3,612
| 2.890625
| 3
|
[] |
no_license
|
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use std::{thread, time};
pub fn simulation_loop(display_values_mutex : Arc<Mutex<[f32; 15000]>>, GRID_SIZE_X : usize, GRID_SIZE_Y : usize){
let TIME_SAMPLES_PER_PRINTOUT : u32 = 100;
let mut time_samples : u32 = 0;
let mut time_acc : u32 = 0;
let mut tick_number : u32 = 0;
loop {
let start = Instant::now();
{
let mut old_values = display_values_mutex.lock().unwrap();
let new_values = heat_simulation_loop(block_array(*old_values), tick_number);
tick_number += 1;
*old_values = serialize_array(new_values);
}
time_acc += Instant::now().duration_since(start).subsec_millis();
if (time_samples == TIME_SAMPLES_PER_PRINTOUT){
println!("Delay : {}ms", time_acc as f32 / TIME_SAMPLES_PER_PRINTOUT as f32);
time_samples = 0;
time_acc = 0;
}
time_samples += 1;
let ten_millis = time::Duration::from_millis(5);
thread::sleep(ten_millis);
}
}
fn heat_simulation_loop(data : [[f32; 100];150], tick_number : u32) -> [[f32; 100];150] {
let mut next_data : [[f32; 100];150] = data;
//Actual simulation code
{
/*
Heat equation : du/dt - (du/dx)^2, where u = temperature, t = time, and x = our spacial domain
which, solved for du/dt : du/dt = (du/dx)^2
expanding spacial domain and therefor it's derivitive into two dimensions : du/dt = (du/dx)^2 + (du/dy)^2
From this PDE we can use the central difference method to approximate the 2nd spacial derivitives...
From the difference quotient of the first derivitive...
f(x - h) - f(x + h) / 2h
We then derive the difference quotient of the 2nd derivitive...
f(x - h) - 2 * f(x) + f(x + h) / h^2
In code, this recurrence equation implies...
next_data[i][j] += ((data[i + 1][j] - (2.0 * data[i][j]) + data[i - 1][j]) + (data[i][j + 1] - (2.0 * data[i][j]) + data[i][j - 1])) / h ^ 2;
Which is seen implemented below.
A note on boundry conditions :
First derivitive boundry conditions set du/dx on all walls to be 0.5
*/
for i in 0..150 - 1{
for j in 0..100 - 1{
if i == 0 || i == 150 || j == 0 || j == 100{
//next_data[i][j] = 0.5;
}else{
next_data[i][j] += ((data[i + 1][j] - (2.0 * data[i][j]) + data[i - 1][j]) + (data[i][j + 1] - (2.0 * data[i][j]) + data[i][j - 1])) / 4.00;
}
}
}
if(tick_number < 200){
next_data[75][20] = 1.0;
next_data[75][40] = 1.0;
next_data[75][60] = 1.0;
next_data[75][80] = 1.0;
next_data[95][20] = 1.0;
next_data[95][40] = 1.0;
next_data[95][60] = 1.0;
next_data[95][80] = 1.0;
}
}
return next_data;
}
fn serialize_array(array : [[f32; 100];150]) -> [f32; 15000]{
let mut to_return : [f32; 15000] = [0.0; 15000];
for i in 0..to_return.len() {
to_return[i] = array[i % 150][i / 150];
}
return to_return;
}
fn block_array(array : [f32; 15000]) -> [[f32; 100];150]{
let mut to_return : [[f32; 100];150] = [[0.0; 100]; 150];
for i in 0..150{
for j in 0..100{
to_return[i][j] = array[j * 150 + i];
}
}
return to_return;
}
| true
|
1f4d83c360620fae73a2f35780e132c22c51605e
|
Rust
|
kroeckx/ruma
|
/crates/ruma-events/src/room/redaction.rs
|
UTF-8
| 2,461
| 2.796875
| 3
|
[
"MIT"
] |
permissive
|
//! Types for the *m.room.redaction* event.
use ruma_common::MilliSecondsSinceUnixEpoch;
use ruma_events_macros::{Event, EventContent};
use ruma_identifiers::{EventId, RoomId, UserId};
use serde::{Deserialize, Serialize};
use crate::Unsigned;
/// Redaction event.
#[derive(Clone, Debug, Event)]
#[allow(clippy::exhaustive_structs)]
pub struct RedactionEvent {
/// Data specific to the event type.
pub content: RedactionEventContent,
/// The ID of the event that was redacted.
pub redacts: EventId,
/// The globally unique event identifier for the user who sent the event.
pub event_id: EventId,
/// The fully-qualified ID of the user who sent this event.
pub sender: UserId,
/// Timestamp in milliseconds on originating homeserver when this event was sent.
pub origin_server_ts: MilliSecondsSinceUnixEpoch,
/// The ID of the room associated with this event.
pub room_id: RoomId,
/// Additional key-value pairs not signed by the homeserver.
pub unsigned: Unsigned,
}
/// Redaction event without a `room_id`.
#[derive(Clone, Debug, Event)]
#[allow(clippy::exhaustive_structs)]
pub struct SyncRedactionEvent {
/// Data specific to the event type.
pub content: RedactionEventContent,
/// The ID of the event that was redacted.
pub redacts: EventId,
/// The globally unique event identifier for the user who sent the event.
pub event_id: EventId,
/// The fully-qualified ID of the user who sent this event.
pub sender: UserId,
/// Timestamp in milliseconds on originating homeserver when this event was sent.
pub origin_server_ts: MilliSecondsSinceUnixEpoch,
/// Additional key-value pairs not signed by the homeserver.
pub unsigned: Unsigned,
}
/// A redaction of an event.
#[derive(Clone, Debug, Default, Deserialize, Serialize, EventContent)]
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
#[ruma_event(type = "m.room.redaction", kind = Message)]
pub struct RedactionEventContent {
/// The reason for the redaction, if any.
#[serde(skip_serializing_if = "Option::is_none")]
pub reason: Option<String>,
}
impl RedactionEventContent {
/// Creates an empty `RedactionEventContent`.
pub fn new() -> Self {
Self::default()
}
/// Creates a new `RedactionEventContent` with the given reason.
pub fn with_reason(reason: String) -> Self {
Self { reason: Some(reason) }
}
}
| true
|
072a8fb46341d51bd070b776ebd1071a560ab6dc
|
Rust
|
KrutNA/huffman-coding
|
/src/queue.rs
|
UTF-8
| 462
| 2.640625
| 3
|
[] |
no_license
|
use crate::types::node::*;
use std::collections::BinaryHeap;
pub fn update_with_data(heap_buffer: &mut [u32], data: &[u8]) {
for &byte in data.iter() {
heap_buffer[byte as usize] += 1;
}
}
pub fn convert_to_heap(
heap_buffer: &mut [u32]
)
-> BinaryHeap<Element>
{
heap_buffer.iter().enumerate().filter_map(|(data, &priority)| {
if priority > 0 { Some(Element::new_with_priority(data as u8, priority)) }
else { None }
}).collect()
}
| true
|
2706201ef1c85ac4eb4e84369f6783e76f71263d
|
Rust
|
KadoBOT/exercism-rust
|
/diamond/src/lib.rs
|
UTF-8
| 705
| 3.203125
| 3
|
[] |
no_license
|
pub fn get_diamond(c: char) -> Vec<String> {
let distance = ((c as u8) - b'A') as usize;
let mut result = vec![" ".repeat(distance + distance + 1); distance + distance + 1];
let size = result.len();
let mut replace_char = |idx: usize, pos: usize, ch: char| {
result[idx].replace_range(pos..=pos, &ch.to_string());
};
let mut replace_row = |idx: usize, n: usize| {
replace_char(idx, distance - n, (b'A' + n as u8) as char);
replace_char(idx, distance + n, (b'A' + n as u8) as char);
};
(0..=distance).for_each(|n| {
let tail = (size - n) - 1;
replace_row(n as usize, n);
replace_row(tail as usize, n);
});
result
}
| true
|
a988a03a0c59f16e3b29b0bf32f34af8acf6ac10
|
Rust
|
andrew-johnson-4/rdxl_internals
|
/src/xtext_crumb.rs
|
UTF-8
| 2,887
| 2.5625
| 3
|
[
"MIT",
"Apache-2.0"
] |
permissive
|
// Copyright 2020, The rdxl Project Developers.
// Dual Licensed under the MIT license and the Apache 2.0 license,
// see the LICENSE file or <http://opensource.org/licenses/MIT>
// also see LICENSE2 file or <https://www.apache.org/licenses/LICENSE-2.0>
use quote::{quote_spanned, ToTokens};
use proc_macro2::{Span, Literal};
use syn::parse::{Parse, ParseStream, Result};
use syn::{Token};
use syn::token::{Bracket,Brace};
use crate::core::{TokenAsLiteral};
use crate::xtext::{XtextTag,XtextExpr,BracketedExpr,XtextClass};
pub enum XtextCrumb {
S(String, Span),
T(XtextTag),
E(XtextExpr),
F(BracketedExpr),
C(XtextClass)
}
impl XtextCrumb {
pub fn span(&self) -> Span {
match self {
XtextCrumb::S(_,sp) => { sp.clone() }
XtextCrumb::T(t) => { t.outer_span.clone() }
XtextCrumb::E(e) => { e.brace_token1.span.clone() }
XtextCrumb::F(f) => { f.span() }
XtextCrumb::C(c) => { c.open.span.join(c.close.span).unwrap_or(c.open.span) }
}
}
pub fn parse_outer(input: ParseStream) -> Result<Vec<Self>> {
let mut cs = vec!();
while !input.is_empty() &&
!(input.peek(Token![<]) && input.peek2(Token![/])) {
let c: XtextCrumb = input.parse()?;
cs.push(c);
}
Ok(cs)
}
}
impl Parse for XtextCrumb {
fn parse(input: ParseStream) -> Result<Self> {
if input.peek(Token![<]) && input.peek2(Token![!]) {
let c: XtextClass = input.parse()?;
Ok(XtextCrumb::C(c))
} else if input.peek(Token![<]) {
let t: XtextTag = input.parse()?;
Ok(XtextCrumb::T(t))
} else if input.peek(Bracket) {
let f: BracketedExpr = BracketedExpr::parse("markup".to_string(),input)?;
Ok(XtextCrumb::F(f))
} else if input.peek(Brace) {
let e: XtextExpr = input.parse()?;
Ok(XtextCrumb::E(e))
} else {
let t: TokenAsLiteral = input.parse()?;
Ok(XtextCrumb::S(t.token_literal, t.span))
}
}
}
impl ToTokens for XtextCrumb {
fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
match self {
XtextCrumb::S(s,span) => {
let l = Literal::string(&s);
(quote_spanned!{span.clone()=>
stream.push_str(#l);
}).to_tokens(tokens);
},
XtextCrumb::T(t) => {
t.to_tokens(tokens);
}
XtextCrumb::E(e) => {
e.to_tokens(tokens);
}
XtextCrumb::F(e) => {
e.to_tokens(tokens);
}
XtextCrumb::C(c) => {
let span = c.span();
(quote_spanned!{span=>
stream.push_str(&#c.to_string());
}).to_tokens(tokens);
}
}
}
}
| true
|
35e07ed8d1c382e5e625ba0beb0438033033b0fe
|
Rust
|
doytsujin/yew
|
/packages/yew/src/functional/hooks/use_transitive_state/feat_ssr.rs
|
UTF-8
| 2,278
| 2.6875
| 3
|
[
"Apache-2.0",
"MIT"
] |
permissive
|
//! The server-side rendering variant.
use std::cell::RefCell;
use std::rc::Rc;
use base64ct::{Base64, Encoding};
use serde::de::DeserializeOwned;
use serde::Serialize;
use crate::functional::{Hook, HookContext, PreparedState};
use crate::suspense::SuspensionResult;
pub(super) struct TransitiveStateBase<T, D, F>
where
D: Serialize + DeserializeOwned + PartialEq + 'static,
T: Serialize + DeserializeOwned + 'static,
F: 'static + FnOnce(Rc<D>) -> T,
{
pub state_fn: RefCell<Option<F>>,
pub deps: Rc<D>,
}
impl<T, D, F> PreparedState for TransitiveStateBase<T, D, F>
where
D: Serialize + DeserializeOwned + PartialEq + 'static,
T: Serialize + DeserializeOwned + 'static,
F: 'static + FnOnce(Rc<D>) -> T,
{
fn prepare(&self) -> String {
let f = self.state_fn.borrow_mut().take().unwrap();
let state = f(self.deps.clone());
let state = bincode::serialize(&(Some(&state), Some(&*self.deps)))
.expect("failed to prepare state");
Base64::encode_string(&state)
}
}
#[doc(hidden)]
pub fn use_transitive_state<T, D, F>(
f: F,
deps: D,
) -> impl Hook<Output = SuspensionResult<Option<Rc<T>>>>
where
D: Serialize + DeserializeOwned + PartialEq + 'static,
T: Serialize + DeserializeOwned + 'static,
F: 'static + FnOnce(Rc<D>) -> T,
{
struct HookProvider<T, D, F>
where
D: Serialize + DeserializeOwned + PartialEq + 'static,
T: Serialize + DeserializeOwned + 'static,
F: 'static + FnOnce(Rc<D>) -> T,
{
deps: D,
f: F,
}
impl<T, D, F> Hook for HookProvider<T, D, F>
where
D: Serialize + DeserializeOwned + PartialEq + 'static,
T: Serialize + DeserializeOwned + 'static,
F: 'static + FnOnce(Rc<D>) -> T,
{
type Output = SuspensionResult<Option<Rc<T>>>;
fn run(self, ctx: &mut HookContext) -> Self::Output {
let f = self.f;
ctx.next_prepared_state(move |_re_render, _| -> TransitiveStateBase<T, D, F> {
TransitiveStateBase {
state_fn: Some(f).into(),
deps: self.deps.into(),
}
});
Ok(None)
}
}
HookProvider::<T, D, F> { deps, f }
}
| true
|
802004b243938e1da6cda1e4bfff6b4a6aab2d05
|
Rust
|
dollarkillerx/Learn-RUST-again
|
/day2_4/src/main.rs
|
UTF-8
| 695
| 3.453125
| 3
|
[
"MIT"
] |
permissive
|
fn main() {
hello1();
hello2();
}
struct User;
trait Hel {
fn hello(&self) -> String;
}
trait Hum {
fn hello(&self);
fn hello_world<T: Hel>(&self, you: T);
}
struct DK;
impl Hel for DK {
fn hello(&self) -> String {
"hello DK".to_string()
}
}
impl Hum for User {
fn hello(&self) {
println!("Hello Hum");
}
fn hello_world<T: Hel>(&self, you: T) {
println!("{}",you.hello());
}
}
fn hello1() {
let a = User;
status_test(a);
}
fn hello2() {
let a = User;
dyn_test(&a);
}
fn status_test<T: Hum>(u: T) {
let b = DK;
u.hello_world(b);
}
fn dyn_test(c: &dyn Hum) {
let b = DK;
c.hello_world(b);
}
| true
|
1bc54ef27643c5b481231dd66aa5edd12898efb6
|
Rust
|
ScarboroughCoral/Notes
|
/剑指Offer/面试题56 - I. 数组中数字出现的次数.rs
|
UTF-8
| 421
| 3.265625
| 3
|
[] |
no_license
|
impl Solution {
pub fn single_numbers(nums: Vec<i32>) -> Vec<i32> {
let mut r=0;
for x in &nums{
r^=x;
}
let mut d=1;
while (d&r)==0{
d<<=1;
}
let mut a=0;
let mut b=0;
for x in &nums{
if x&d==0{
a^=x;
}
else{
b^=x;
}
}
return vec![a,b];
}
}
| true
|
e81986963f4f3f3a4fd322b1288ef3f58d4e9e99
|
Rust
|
ens-ds23/ensembl-client
|
/src/assets/browser/app/src/controller/output/report.rs
|
UTF-8
| 7,288
| 2.703125
| 3
|
[] |
no_license
|
use std::collections::HashMap;
use std::sync::{ Arc, Mutex };
use controller::global::{ App, AppRunner };
use controller::output::OutputAction;
use serde_json::Map as JSONMap;
use serde_json::Value as JSONValue;
use serde_json::Number as JSONNumber;
#[derive(Clone)]
#[allow(unused)]
pub enum StatusJigsawType {
Number,
String,
Boolean
}
#[derive(Clone)]
#[allow(unused)]
pub enum StatusJigsaw {
Atom(String,StatusJigsawType),
Array(Vec<StatusJigsaw>),
Object(HashMap<String,StatusJigsaw>)
}
struct StatusOutput {
last_value: Option<JSONValue>,
jigsaw: StatusJigsaw,
last_sent: Option<f64>,
send_every: Option<f64>
}
impl StatusOutput {
fn new(jigsaw: StatusJigsaw) -> StatusOutput {
StatusOutput {
jigsaw,
last_sent: None,
send_every: Some(0.),
last_value: None,
}
}
fn is_send_now(&self, t: f64) -> bool {
if let Some(interval) = self.send_every {
if interval == 0. { return true; }
if let Some(last_sent) = self.last_sent {
if t - last_sent > interval { return true; }
} else {
return true;
}
}
return false;
}
}
lazy_static! {
static ref REPORT_CONFIG:
Vec<(&'static str,StatusJigsaw,Option<f64>)> = vec!{
("location",StatusJigsaw::Array(vec!{
StatusJigsaw::Atom("stick".to_string(),StatusJigsawType::String),
StatusJigsaw::Atom("start".to_string(),StatusJigsawType::Number),
StatusJigsaw::Atom("end".to_string(),StatusJigsawType::Number),
}),Some(500.)),
("bumper",StatusJigsaw::Array(vec!{
StatusJigsaw::Atom("bumper-top".to_string(),StatusJigsawType::Boolean),
StatusJigsaw::Atom("bumper-bottom".to_string(),StatusJigsawType::Boolean),
StatusJigsaw::Atom("bumper-out".to_string(),StatusJigsawType::Boolean),
StatusJigsaw::Atom("bumper-in".to_string(),StatusJigsawType::Boolean),
StatusJigsaw::Atom("bumper-left".to_string(),StatusJigsawType::Boolean),
StatusJigsaw::Atom("bumper-right".to_string(),StatusJigsawType::Boolean),
}),Some(500.))
};
}
pub struct ReportImpl {
pieces: HashMap<String,String>,
outputs: HashMap<String,StatusOutput>
}
impl ReportImpl {
pub fn new() -> ReportImpl {
let out = ReportImpl {
pieces: HashMap::<String,String>::new(),
outputs: HashMap::<String,StatusOutput>::new()
};
out
}
fn get_piece(&mut self, key: &str) -> Option<String> {
self.pieces.get(key).map(|s| s.clone())
}
fn get_output(&mut self, key: &str) -> Option<&mut StatusOutput> {
self.outputs.get_mut(key)
}
fn add_output(&mut self, key: &str, jigsaw: StatusJigsaw) {
self.outputs.insert(key.to_string(),StatusOutput::new(jigsaw));
}
pub fn set_status(&mut self, key: &str, value: &str) {
self.pieces.insert(key.to_string(),value.to_string());
}
pub fn set_interval(&mut self, key: &str, interval: Option<f64>) {
if let Some(ref mut p) = self.get_output(key) {
p.send_every = interval;
}
}
fn make_number(&self, data: &str) -> JSONValue {
data.parse::<f64>().ok()
.and_then(|v| JSONNumber::from_f64(v) )
.map(|v| JSONValue::Number(v) )
.unwrap_or(JSONValue::Null)
}
fn make_bool(&self, data: &str) -> JSONValue {
data.parse::<bool>().ok()
.map(|v| JSONValue::Bool(v))
.unwrap_or(JSONValue::Null)
}
fn make_atom(&self, key: &str, type_: &StatusJigsawType) -> Option<JSONValue> {
let v = self.pieces.get(key);
if let Some(ref v) = v {
Some(match type_ {
StatusJigsawType::Number => self.make_number(v),
StatusJigsawType::String => JSONValue::String(v.to_string()),
StatusJigsawType::Boolean => self.make_bool(v)
})
} else {
None
}
}
fn make_array(&self, values: &Vec<StatusJigsaw>) -> Option<JSONValue> {
let mut out = Vec::<JSONValue>::new();
for v in values {
if let Some(value) = self.make_value(v) {
out.push(value);
} else {
return None;
}
}
Some(JSONValue::Array(out))
}
fn make_object(&self, values: &HashMap<String,StatusJigsaw>) -> Option<JSONValue> {
let mut out = JSONMap::<String,JSONValue>::new();
for (k,v) in values {
if let Some(value) = self.make_value(v) {
out.insert(k.to_string(),value);
} else {
return None;
}
}
Some(JSONValue::Object(out))
}
fn make_value(&self, j: &StatusJigsaw) -> Option<JSONValue> {
match j {
StatusJigsaw::Atom(key,type_) => self.make_atom(key,type_),
StatusJigsaw::Array(values) => self.make_array(values),
StatusJigsaw::Object(values) => self.make_object(values)
}
}
fn new_report(&mut self, t: f64) -> Option<JSONValue> {
let mut out = JSONMap::<String,JSONValue>::new();
for (k,s) in &self.outputs {
if let Some(value) = self.make_value(&s.jigsaw) {
if let Some(ref last_value) = s.last_value {
if last_value == &value { continue; }
}
if s.is_send_now(t) {
out.insert(k.to_string(),value.clone());
}
}
}
for (k,v) in &out {
if let Some(ref mut p) = self.outputs.get_mut(k) {
p.last_value = Some(v.clone());
p.last_sent = Some(t);
}
}
if out.len() > 0 {
Some(JSONValue::Object(out))
} else {
None
}
}
}
#[derive(Clone)]
pub struct Report(Arc<Mutex<ReportImpl>>);
impl Report {
pub fn new(ar: &mut AppRunner) -> Report {
let mut out = Report(Arc::new(Mutex::new(ReportImpl::new())));
for (k,j,v) in REPORT_CONFIG.iter() {
{
let mut imp = out.0.lock().unwrap();
imp.add_output(k,j.clone());
}
out.set_interval(k,*v);
}
ar.add_timer(enclose! { (out) move |app,t| {
if let Some(report) = out.new_report(t) {
vec!{
OutputAction::SendCustomEvent("bpane-out".to_string(),report)
}
} else { vec!{} }
}},None);
out
}
pub fn set_status(&self, key: &str, value: &str) {
let mut imp = self.0.lock().unwrap();
imp.set_status(key,value);
}
pub fn set_status_bool(&self, key: &str, value: bool) {
self.set_status(key,&value.to_string());
}
pub fn set_interval(&mut self, key: &str, interval: Option<f64>) {
let mut imp = self.0.lock().unwrap();
imp.set_interval(key,interval);
}
pub fn new_report(&self, t: f64) -> Option<JSONValue> {
self.0.lock().unwrap().new_report(t)
}
}
| true
|
7cbe3f3c5c78b20de4c23dc0199e9d3f80a2c69e
|
Rust
|
pormeu/openbrush-contracts
|
/examples/reentrancy-guard/flip_on_me/lib.rs
|
UTF-8
| 708
| 2.65625
| 3
|
[
"MIT"
] |
permissive
|
#![cfg_attr(not(feature = "std"), no_std)]
#[ink_lang::contract]
pub mod flip_on_me {
use ink_env::call::FromAccountId;
use my_flipper_guard::my_flipper_guard::MyFlipper;
#[ink(storage)]
#[derive(Default)]
pub struct FlipOnMe {}
impl FlipOnMe {
#[ink(constructor)]
pub fn new() -> Self {
Self::default()
}
#[ink(message)]
pub fn flip_on_me(&mut self) {
let caller = self.env().caller();
// This method does a cross-contract call to caller contract and calls the `flip` method.
let mut flipper: MyFlipper = FromAccountId::from_account_id(caller);
flipper.flip();
}
}
}
| true
|
7fd1fbd2faf430e8d8dfed2219562371e2ef46d0
|
Rust
|
RaymondK99/advent_of_code_2020_rs
|
/src/util/day_02.rs
|
UTF-8
| 2,057
| 3.421875
| 3
|
[] |
no_license
|
use super::Part;
pub fn solve(input : String, part: Part) -> String {
let list = input.lines()
.map(|line| parse_line(line))
.collect();
let result = match part {
Part::Part1 => part1(list),
Part::Part2 => part2(list)
};
format!("{}",result)
}
fn parse_line(input:&str) -> (usize,usize,char,&str) {
let cols:Vec<&str> = input.split(|c| c == ' ' || c == ':' || c == '-' ).collect();
let min = cols[0].parse().unwrap();
let max = cols[1].parse().unwrap();
let pattern = cols[2].as_bytes()[0] as char;
let password = cols[4];
(min,max,pattern,password)
}
fn part1(list:Vec<(usize,usize,char,&str)>) -> usize {
list.iter().filter( |&(min,max,ch,input)| {
let cnt = input.chars().filter(|c| *c == *ch).count();
cnt >= *min && cnt <= *max
}).count()
}
fn part2(list:Vec<(usize,usize,char,&str)>) -> usize {
list.iter().filter( |&(index1,index2,ch,input)| {
let ch1 = input.as_bytes()[index1-1] as char;
let ch2 = input.as_bytes()[index2-1] as char;
(*ch == ch1) ^ (*ch == ch2)
}).count()}
#[cfg(test)]
mod tests {
// Note this useful idiom: importing names from outer (for mod tests) scope.
use super::*;
use util::Part::{Part1, Part2};
#[test]
fn test_parse() {
let input = "1-3 a: abcde";
assert_eq!((1,3,'a',"abcde"), parse_line(input));
}
#[test]
fn test1() {
let input = "1-3 a: abcde
1-3 b: cdefg
2-9 c: ccccccccc";
assert_eq!("2", solve(input.to_string(),Part1));
}
#[test]
fn test_part1() {
let input = include_str!("../../input_02.txt");
assert_eq!("548", solve(input.to_string(), Part1));
}
#[test]
fn test2() {
let input = "1-3 a: abcde
1-3 b: cdefg
2-9 c: ccccccccc";
assert_eq!("1", solve(input.to_string(),Part2));
}
#[test]
fn test_part2() {
let input = include_str!("../../input_02.txt");
assert_eq!("502", solve(input.to_string(), Part2));
}
}
| true
|
974f376bbe0dfc6d2fe87d7bde6b2462456dd29a
|
Rust
|
YoshikawaMasashi/toid
|
/src/high_layer_trial/phrase_operation/split_by_condition.rs
|
UTF-8
| 680
| 2.71875
| 3
|
[] |
no_license
|
use super::super::super::data::music_info::{Note, Phrase};
pub fn split_by_condition<N: Note + Eq + Ord + Clone>(
phrase: Phrase<N>,
condition: Vec<bool>,
) -> (Phrase<N>, Phrase<N>) {
let mut true_phrase = Phrase::new();
let mut false_phrase = Phrase::new();
true_phrase = true_phrase.set_length(phrase.length);
false_phrase = false_phrase.set_length(phrase.length);
for (note, &cond) in phrase.note_vec().iter().zip(condition.iter()) {
if cond {
true_phrase = true_phrase.add_note(note.clone());
} else {
false_phrase = false_phrase.add_note(note.clone());
}
}
(true_phrase, false_phrase)
}
| true
|
e221920e5dca5c1739194e031e0a40581847066d
|
Rust
|
RevelationOfTuring/Rust-exercise
|
/src/error_handling_result_early_returns.rs
|
UTF-8
| 1,265
| 4.09375
| 4
|
[
"Apache-2.0"
] |
permissive
|
/*
我们可以显式地使用组合算子处理了错误。
另一种处理错误的方式是使用 `match 语句` 和 `提前返回`(early return)的结合。
也就是说:
如果发生错误,我们可以`停止`函数的执行然后返回错误。
这样的代码更好写,更易读。
*/
#[cfg(test)]
mod tests {
use std::num::ParseIntError;
// 如果遇到
fn multiply(first_num_str: &str, second_num_str: &str) -> Result<i32, ParseIntError> {
let n1 = match first_num_str.parse::<i32>() {
Ok(i) => i,
// 提前返回,如果出了错误
Err(e) => return Err(e),
};
let n2 = match second_num_str.parse::<i32>() {
Ok(i) => i,
Err(e) => return Err(e),
};
// 正确的返回
Ok(n1 * n2)
}
fn print_result(result: Result<i32, ParseIntError>) {
match result {
Ok(i) => println!("{}", i),
Err(e) => println!("Error: {}", e),
}
}
#[test]
fn test_error_handling_result_early_returns() {
// 正常现象
print_result(multiply("10", "11"));
// 返回错误(提前返回)
print_result(multiply("michael.w", "11"));
}
}
| true
|
a6f6c1b0a2a2212631a11f9881158a39ee17b1a3
|
Rust
|
villor/rustia
|
/crates/proxy/src/game.rs
|
UTF-8
| 1,857
| 2.859375
| 3
|
[] |
no_license
|
use bytes::BytesMut;
use protocol::{FrameType, packet::ClientPacket};
use crate::{Origin, ProxyConnection, ProxyEventHandler};
/// Event handler that will detect a game protocol handshake and enable XTEA with the correct key
#[derive(Default)]
pub struct GameHandshaker;
impl GameHandshaker {
pub fn new() -> Self { Self::default() }
pub fn new_boxed() -> Box<Self> {
Box::new(Self::new())
}
}
impl ProxyEventHandler for GameHandshaker {
fn on_new_connection(&self, connection: &mut ProxyConnection) -> anyhow::Result<()> {
// Because nonce is weird
connection.set_frame_type(FrameType::LengthPrefixed);
Ok(())
}
fn on_frame(&self, connection: &mut ProxyConnection, from: Origin, frame: BytesMut) -> anyhow::Result<BytesMut> {
if connection.first_frame() { // Nonce from server
connection.set_frame_type(FrameType::Raw);
} else if connection.current_frame_id() == 1 { // First frame from client
match from {
Origin::Client => {
let mut frame = frame.clone(); // clone really needed? BytesMut is very non-intuitive, Frame-abstraction?
match ClientPacket::read_from(&mut frame)? {
ClientPacket::GameLogin(login_packet) => {
connection.set_frame_type(FrameType::XTEA(login_packet.xtea_key));
},
packet => {
anyhow::bail!(format!("Wrong first packet from client, expected GameLogin, got {:?}", packet));
},
};
},
Origin::Server => {
anyhow::bail!("Unexpected frame order, client should send the second frame.");
}
}
}
Ok(frame)
}
}
| true
|
7f5f0a9ae08b396e66daa292f60f500d7d3265cb
|
Rust
|
FreskyZ/fff-lang
|
/src/vm/builtin_impl.rs
|
UTF-8
| 48,766
| 2.671875
| 3
|
[
"Apache-2.0"
] |
permissive
|
// Builtin methods implementation
use std::str::FromStr;
use std::fmt;
use lexical::SeperatorKind;
use codegen::FnName;
use codegen::ItemID;
use codegen::Type;
use codegen::Operand;
use codegen::TypeCollection;
use super::runtime::Runtime;
use super::runtime::RuntimeValue;
// Based on the assumption that runtime will not meet invalid, return ItemID::Invalid for index out of bound
fn prep_param_type(typeids: &Vec<ItemID>, index: usize) -> Option<usize> {
if index >= typeids.len() {
None
} else {
Some(typeids[index].as_option().unwrap()) // assume unwrap able
}
}
fn prep_param(params: &Vec<Operand>, index: usize) -> Option<&Operand> {
if index >= params.len() {
None
} else {
Some(¶ms[index])
}
}
fn read_int_from_stdin<T>() -> T where T: FromStr, <T as FromStr>::Err: fmt::Debug {
use std::io;
let mut line = String::new();
io::stdin().read_line(&mut line).expect("Failed to read line");
line.trim().parse().expect("Wanted a number")
}
fn str_begin_with(source: &str, pattern: &str) -> bool {
let mut source_chars = source.chars();
let mut pattern_chars = pattern.chars();
loop {
match (source_chars.next(), pattern_chars.next()) {
(Some(ch1), Some(ch2)) => if ch1 != ch2 { return false; }, // else continue
(_, _) => return true,
}
}
}
pub fn dispatch_builtin(fn_sign: (FnName, Vec<ItemID>), params: &Vec<Operand>, types: &TypeCollection, rt: &mut Runtime) -> RuntimeValue {
use super::runtime::RuntimeValue::*;
let fn_name = fn_sign.0;
let param_types = fn_sign.1;
macro_rules! native_forward_2 {
($param0: expr, $param1: expr, $pat: pat => $stmt: block) => (match (rt.index($param0), rt.index($param1)) {
$pat => $stmt,
_ => unreachable!()
})
}
macro_rules! native_forward_1 {
($param0: expr, $pat: pat => $stmt: block) => (match rt.index($param0) {
$pat => $stmt
_ => unreachable!()
})
}
macro_rules! native_forward_mut_1 {
($param0: expr, $pat: pat => $stmt: block) => (match rt.index_mut($param0) {
$pat => $stmt
_ => unreachable!()
})
}
// Global
match (&fn_name, prep_param_type(¶m_types, 0), prep_param_type(¶m_types, 1), prep_param(¶ms, 0), prep_param(¶ms, 1)) {
(&FnName::Ident(ref ident_name), param_type0, param_type1, param0, param1) => match (ident_name.as_ref(), param_type0, param_type1, param0, param1) {
("write", Some(13), None, Some(ref operand), None) => { print!("{}", rt.index(operand).get_str_lit()); return RuntimeValue::Unit; }
("writeln", Some(13), None, Some(ref operand), None) => { println!("{}", rt.index(operand).get_str_lit()); return RuntimeValue::Unit; }
("read_i32", None, None, None, None) => return RuntimeValue::Int(read_int_from_stdin::<i32>() as u64),
("read_u64", None, None, None, None) => return RuntimeValue::Int(read_int_from_stdin::<u64>()),
_ => (),
},
_ => (),
}
// Builtin type
match (&fn_name, prep_param_type(¶m_types, 0), prep_param_type(¶m_types, 1), prep_param(¶ms, 0), prep_param(¶ms, 1)) {
// Integral Add
(&FnName::Operator(SeperatorKind::Add), Some(1), Some(1), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::Add), Some(2), Some(2), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::Add), Some(3), Some(3), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::Add), Some(4), Some(4), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::Add), Some(5), Some(5), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::Add), Some(6), Some(6), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::Add), Some(7), Some(7), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::Add), Some(8), Some(8), Some(ref param0), Some(ref param1))
=> native_forward_2!{ param0, param1, (Int(value0), Int(value1)) => { return Int(value0 + value1); } },
// Integral Sub
(&FnName::Operator(SeperatorKind::Sub), Some(1), Some(1), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::Sub), Some(2), Some(2), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::Sub), Some(3), Some(3), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::Sub), Some(4), Some(4), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::Sub), Some(5), Some(5), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::Sub), Some(6), Some(6), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::Sub), Some(7), Some(7), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::Sub), Some(8), Some(8), Some(ref param0), Some(ref param1))
=> native_forward_2!{ param0, param1, (Int(value0), Int(value1)) => { return Int(value0 - value1); } },
// Integral Mul
(&FnName::Operator(SeperatorKind::Mul), Some(1), Some(1), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::Mul), Some(2), Some(2), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::Mul), Some(3), Some(3), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::Mul), Some(4), Some(4), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::Mul), Some(5), Some(5), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::Mul), Some(6), Some(6), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::Mul), Some(7), Some(7), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::Mul), Some(8), Some(8), Some(ref param0), Some(ref param1))
=> native_forward_2!{ param0, param1, (Int(value0), Int(value1)) => { return Int(value0 * value1); } },
// Integral Div
(&FnName::Operator(SeperatorKind::Div), Some(1), Some(1), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::Div), Some(2), Some(2), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::Div), Some(3), Some(3), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::Div), Some(4), Some(4), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::Div), Some(5), Some(5), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::Div), Some(6), Some(6), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::Div), Some(7), Some(7), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::Div), Some(8), Some(8), Some(ref param0), Some(ref param1))
=> native_forward_2!{ param0, param1, (Int(value0), Int(value1)) => { return Int(value0 / value1); } },
// Integral Rem
(&FnName::Operator(SeperatorKind::Rem), Some(1), Some(1), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::Rem), Some(2), Some(2), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::Rem), Some(3), Some(3), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::Rem), Some(4), Some(4), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::Rem), Some(5), Some(5), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::Rem), Some(6), Some(6), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::Rem), Some(7), Some(7), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::Rem), Some(8), Some(8), Some(ref param0), Some(ref param1))
=> native_forward_2!{ param0, param1, (Int(value0), Int(value1)) => { return Int(value0 % value1); } },
// Integral ShiftLeft
(&FnName::Operator(SeperatorKind::ShiftLeft), Some(1), Some(5), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::ShiftLeft), Some(2), Some(5), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::ShiftLeft), Some(3), Some(5), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::ShiftLeft), Some(4), Some(5), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::ShiftLeft), Some(5), Some(5), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::ShiftLeft), Some(6), Some(5), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::ShiftLeft), Some(7), Some(5), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::ShiftLeft), Some(8), Some(5), Some(ref param0), Some(ref param1))
=> native_forward_2!{ param0, param1, (Int(value0), Int(value1)) => { return Int(value0 << value1); } },
// Integral ShiftRight
(&FnName::Operator(SeperatorKind::ShiftRight), Some(1), Some(5), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::ShiftRight), Some(2), Some(5), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::ShiftRight), Some(3), Some(5), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::ShiftRight), Some(4), Some(5), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::ShiftRight), Some(5), Some(5), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::ShiftRight), Some(6), Some(5), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::ShiftRight), Some(7), Some(5), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::ShiftRight), Some(8), Some(5), Some(ref param0), Some(ref param1))
=> native_forward_2!{ param0, param1, (Int(value0), Int(value1)) => { return Int(value0 >> value1); } },
// Integral BitAnd
(&FnName::Operator(SeperatorKind::BitAnd), Some(1), Some(1), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::BitAnd), Some(2), Some(2), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::BitAnd), Some(3), Some(3), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::BitAnd), Some(4), Some(4), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::BitAnd), Some(5), Some(5), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::BitAnd), Some(6), Some(6), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::BitAnd), Some(7), Some(7), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::BitAnd), Some(8), Some(8), Some(ref param0), Some(ref param1))
=> native_forward_2!{ param0, param1, (Int(value0), Int(value1)) => { return Int(value0 & value1); } },
// Integral BitOr
(&FnName::Operator(SeperatorKind::BitOr), Some(1), Some(1), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::BitOr), Some(2), Some(2), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::BitOr), Some(3), Some(3), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::BitOr), Some(4), Some(4), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::BitOr), Some(5), Some(5), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::BitOr), Some(6), Some(6), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::BitOr), Some(7), Some(7), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::BitOr), Some(8), Some(8), Some(ref param0), Some(ref param1))
=> native_forward_2!{ param0, param1, (Int(value0), Int(value1)) => { return Int(value0 | value1); } },
// Integral BitXor
(&FnName::Operator(SeperatorKind::BitXor), Some(1), Some(1), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::BitXor), Some(2), Some(2), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::BitXor), Some(3), Some(3), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::BitXor), Some(4), Some(4), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::BitXor), Some(5), Some(5), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::BitXor), Some(6), Some(6), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::BitXor), Some(7), Some(7), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::BitXor), Some(8), Some(8), Some(ref param0), Some(ref param1))
=> native_forward_2!{ param0, param1, (Int(value0), Int(value1)) => { return Int(value0 ^ value1); } },
// Integral Equal
(&FnName::Operator(SeperatorKind::Equal), Some(1), Some(1), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::Equal), Some(2), Some(2), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::Equal), Some(3), Some(3), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::Equal), Some(4), Some(4), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::Equal), Some(5), Some(5), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::Equal), Some(6), Some(6), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::Equal), Some(7), Some(7), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::Equal), Some(8), Some(8), Some(ref param0), Some(ref param1))
=> native_forward_2!{ param0, param1, (Int(value0), Int(value1)) => { return Bool(value0 == value1); } },
// Integral NotEqual
(&FnName::Operator(SeperatorKind::NotEqual), Some(1), Some(1), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::NotEqual), Some(2), Some(2), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::NotEqual), Some(3), Some(3), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::NotEqual), Some(4), Some(4), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::NotEqual), Some(5), Some(5), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::NotEqual), Some(6), Some(6), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::NotEqual), Some(7), Some(7), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::NotEqual), Some(8), Some(8), Some(ref param0), Some(ref param1))
=> native_forward_2!{ param0, param1, (Int(value0), Int(value1)) => { return Bool(value0 != value1); } },
// Integral GreatEqual
(&FnName::Operator(SeperatorKind::GreatEqual), Some(1), Some(1), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::GreatEqual), Some(2), Some(2), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::GreatEqual), Some(3), Some(3), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::GreatEqual), Some(4), Some(4), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::GreatEqual), Some(5), Some(5), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::GreatEqual), Some(6), Some(6), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::GreatEqual), Some(7), Some(7), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::GreatEqual), Some(8), Some(8), Some(ref param0), Some(ref param1))
=> native_forward_2!{ param0, param1, (Int(value0), Int(value1)) => { return Bool(value0 >= value1); } },
// Integral LessEqual
(&FnName::Operator(SeperatorKind::LessEqual), Some(1), Some(1), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::LessEqual), Some(2), Some(2), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::LessEqual), Some(3), Some(3), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::LessEqual), Some(4), Some(4), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::LessEqual), Some(5), Some(5), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::LessEqual), Some(6), Some(6), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::LessEqual), Some(7), Some(7), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::LessEqual), Some(8), Some(8), Some(ref param0), Some(ref param1))
=> native_forward_2!{ param0, param1, (Int(value0), Int(value1)) => { return Bool(value0 <= value1); } },
// Integral Great
(&FnName::Operator(SeperatorKind::Great), Some(1), Some(1), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::Great), Some(2), Some(2), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::Great), Some(3), Some(3), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::Great), Some(4), Some(4), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::Great), Some(5), Some(5), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::Great), Some(6), Some(6), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::Great), Some(7), Some(7), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::Great), Some(8), Some(8), Some(ref param0), Some(ref param1))
=> native_forward_2!{ param0, param1, (Int(value0), Int(value1)) => { return Bool(value0 > value1); } },
// Integral Less
(&FnName::Operator(SeperatorKind::Less), Some(1), Some(1), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::Less), Some(2), Some(2), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::Less), Some(3), Some(3), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::Less), Some(4), Some(4), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::Less), Some(5), Some(5), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::Less), Some(6), Some(6), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::Less), Some(7), Some(7), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::Less), Some(8), Some(8), Some(ref param0), Some(ref param1))
=> native_forward_2!{ param0, param1, (Int(value0), Int(value1)) => { return Bool(value0 < value1); } },
// Integral BitNot
(&FnName::Operator(SeperatorKind::BitNot), Some(1), None, Some(ref param0), None)
| (&FnName::Operator(SeperatorKind::BitNot), Some(2), None, Some(ref param0), None)
| (&FnName::Operator(SeperatorKind::BitNot), Some(3), None, Some(ref param0), None)
| (&FnName::Operator(SeperatorKind::BitNot), Some(4), None, Some(ref param0), None)
| (&FnName::Operator(SeperatorKind::BitNot), Some(5), None, Some(ref param0), None)
| (&FnName::Operator(SeperatorKind::BitNot), Some(6), None, Some(ref param0), None)
| (&FnName::Operator(SeperatorKind::BitNot), Some(7), None, Some(ref param0), None)
| (&FnName::Operator(SeperatorKind::BitNot), Some(8), None, Some(ref param0), None)
=> native_forward_1!{ param0, Int(value) => { return Int(!value); } },
// // Integral Increase
// (&FnName::Operator(SeperatorKind::Increase), Some(1), None, Some(ref param0), None)
// | (&FnName::Operator(SeperatorKind::Increase), Some(2), None, Some(ref param0), None)
// | (&FnName::Operator(SeperatorKind::Increase), Some(3), None, Some(ref param0), None)
// | (&FnName::Operator(SeperatorKind::Increase), Some(4), None, Some(ref param0), None)
// | (&FnName::Operator(SeperatorKind::Increase), Some(5), None, Some(ref param0), None)
// | (&FnName::Operator(SeperatorKind::Increase), Some(6), None, Some(ref param0), None)
// | (&FnName::Operator(SeperatorKind::Increase), Some(7), None, Some(ref param0), None)
// | (&FnName::Operator(SeperatorKind::Increase), Some(8), None, Some(ref param0), None)
// => native_forward_mut_1!{ param0, &mut Int(ref mut value) => { *value += 1; return Unit; } },
// // Integral Decrease
// (&FnName::Operator(SeperatorKind::Decrease), Some(1), None, Some(ref param0), None)
// | (&FnName::Operator(SeperatorKind::Decrease), Some(2), None, Some(ref param0), None)
// | (&FnName::Operator(SeperatorKind::Decrease), Some(3), None, Some(ref param0), None)
// | (&FnName::Operator(SeperatorKind::Decrease), Some(4), None, Some(ref param0), None)
// | (&FnName::Operator(SeperatorKind::Decrease), Some(5), None, Some(ref param0), None)
// | (&FnName::Operator(SeperatorKind::Decrease), Some(6), None, Some(ref param0), None)
// | (&FnName::Operator(SeperatorKind::Decrease), Some(7), None, Some(ref param0), None)
// | (&FnName::Operator(SeperatorKind::Decrease), Some(8), None, Some(ref param0), None)
// => native_forward_mut_1!{ param0, &mut Int(ref mut value) => { *value -= 1; return Unit; } },
// Integral Cast to integral
(&FnName::Cast(1), Some(1), None, Some(ref param0), None)
| (&FnName::Cast(2), Some(1), None, Some(ref param0), None)
| (&FnName::Cast(3), Some(1), None, Some(ref param0), None)
| (&FnName::Cast(4), Some(1), None, Some(ref param0), None)
| (&FnName::Cast(5), Some(1), None, Some(ref param0), None)
| (&FnName::Cast(6), Some(1), None, Some(ref param0), None)
| (&FnName::Cast(7), Some(1), None, Some(ref param0), None)
| (&FnName::Cast(8), Some(1), None, Some(ref param0), None)
| (&FnName::Cast(1), Some(2), None, Some(ref param0), None)
| (&FnName::Cast(2), Some(2), None, Some(ref param0), None)
| (&FnName::Cast(3), Some(2), None, Some(ref param0), None)
| (&FnName::Cast(4), Some(2), None, Some(ref param0), None)
| (&FnName::Cast(5), Some(2), None, Some(ref param0), None)
| (&FnName::Cast(6), Some(2), None, Some(ref param0), None)
| (&FnName::Cast(7), Some(2), None, Some(ref param0), None)
| (&FnName::Cast(8), Some(2), None, Some(ref param0), None)
| (&FnName::Cast(1), Some(3), None, Some(ref param0), None)
| (&FnName::Cast(2), Some(3), None, Some(ref param0), None)
| (&FnName::Cast(3), Some(3), None, Some(ref param0), None)
| (&FnName::Cast(4), Some(3), None, Some(ref param0), None)
| (&FnName::Cast(5), Some(3), None, Some(ref param0), None)
| (&FnName::Cast(6), Some(3), None, Some(ref param0), None)
| (&FnName::Cast(7), Some(3), None, Some(ref param0), None)
| (&FnName::Cast(8), Some(3), None, Some(ref param0), None)
| (&FnName::Cast(1), Some(4), None, Some(ref param0), None)
| (&FnName::Cast(2), Some(4), None, Some(ref param0), None)
| (&FnName::Cast(3), Some(4), None, Some(ref param0), None)
| (&FnName::Cast(4), Some(4), None, Some(ref param0), None)
| (&FnName::Cast(5), Some(4), None, Some(ref param0), None)
| (&FnName::Cast(6), Some(4), None, Some(ref param0), None)
| (&FnName::Cast(7), Some(4), None, Some(ref param0), None)
| (&FnName::Cast(8), Some(4), None, Some(ref param0), None)
| (&FnName::Cast(1), Some(5), None, Some(ref param0), None)
| (&FnName::Cast(2), Some(5), None, Some(ref param0), None)
| (&FnName::Cast(3), Some(5), None, Some(ref param0), None)
| (&FnName::Cast(4), Some(5), None, Some(ref param0), None)
| (&FnName::Cast(5), Some(5), None, Some(ref param0), None)
| (&FnName::Cast(6), Some(5), None, Some(ref param0), None)
| (&FnName::Cast(7), Some(5), None, Some(ref param0), None)
| (&FnName::Cast(8), Some(5), None, Some(ref param0), None)
| (&FnName::Cast(1), Some(6), None, Some(ref param0), None)
| (&FnName::Cast(2), Some(6), None, Some(ref param0), None)
| (&FnName::Cast(3), Some(6), None, Some(ref param0), None)
| (&FnName::Cast(4), Some(6), None, Some(ref param0), None)
| (&FnName::Cast(5), Some(6), None, Some(ref param0), None)
| (&FnName::Cast(6), Some(6), None, Some(ref param0), None)
| (&FnName::Cast(7), Some(6), None, Some(ref param0), None)
| (&FnName::Cast(8), Some(6), None, Some(ref param0), None)
| (&FnName::Cast(1), Some(7), None, Some(ref param0), None)
| (&FnName::Cast(2), Some(7), None, Some(ref param0), None)
| (&FnName::Cast(3), Some(7), None, Some(ref param0), None)
| (&FnName::Cast(4), Some(7), None, Some(ref param0), None)
| (&FnName::Cast(5), Some(7), None, Some(ref param0), None)
| (&FnName::Cast(6), Some(7), None, Some(ref param0), None)
| (&FnName::Cast(7), Some(7), None, Some(ref param0), None)
| (&FnName::Cast(8), Some(7), None, Some(ref param0), None)
| (&FnName::Cast(1), Some(8), None, Some(ref param0), None)
| (&FnName::Cast(2), Some(8), None, Some(ref param0), None)
| (&FnName::Cast(3), Some(8), None, Some(ref param0), None)
| (&FnName::Cast(4), Some(8), None, Some(ref param0), None)
| (&FnName::Cast(5), Some(8), None, Some(ref param0), None)
| (&FnName::Cast(6), Some(8), None, Some(ref param0), None)
| (&FnName::Cast(7), Some(8), None, Some(ref param0), None)
| (&FnName::Cast(8), Some(8), None, Some(ref param0), None)
=> native_forward_1!{ param0, Int(value) => { return Int(value); } },
// Integral cast to float
(&FnName::Cast(10), Some(1), None, Some(ref param0), None)
| (&FnName::Cast(10), Some(2), None, Some(ref param0), None)
| (&FnName::Cast(10), Some(3), None, Some(ref param0), None)
| (&FnName::Cast(10), Some(4), None, Some(ref param0), None)
| (&FnName::Cast(10), Some(5), None, Some(ref param0), None)
| (&FnName::Cast(10), Some(6), None, Some(ref param0), None)
| (&FnName::Cast(10), Some(7), None, Some(ref param0), None)
| (&FnName::Cast(10), Some(8), None, Some(ref param0), None)
=> native_forward_1!{ param0, Int(value) => { return Float(value as f64); } },
// Float Add
(&FnName::Operator(SeperatorKind::Add), Some(9), Some(9), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::Add), Some(10), Some(10), Some(ref param0), Some(ref param1))
=> native_forward_2!{ param0, param1, (Float(value0), Float(value1)) => { return Float(value0 + value1); } },
(&FnName::Operator(SeperatorKind::Sub), Some(9), Some(9), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::Sub), Some(10), Some(10), Some(ref param0), Some(ref param1))
=> native_forward_2!{ param0, param1, (Float(value0), Float(value1)) => { return Float(value0 - value1); } },
(&FnName::Operator(SeperatorKind::Mul), Some(9), Some(9), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::Mul), Some(10), Some(10), Some(ref param0), Some(ref param1))
=> native_forward_2!{ param0, param1, (Float(value0), Float(value1)) => { return Float(value0 * value1); } },
(&FnName::Operator(SeperatorKind::Div), Some(9), Some(9), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::Div), Some(10), Some(10), Some(ref param0), Some(ref param1))
=> native_forward_2!{ param0, param1, (Float(value0), Float(value1)) => { return Float(value0 / value1); } },
// Float Compare
(&FnName::Operator(SeperatorKind::Equal), Some(9), Some(9), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::Equal), Some(10), Some(10), Some(ref param0), Some(ref param1))
=> native_forward_2!{ param0, param1, (Float(value0), Float(value1)) => { return Bool(value0 == value1); } },
(&FnName::Operator(SeperatorKind::NotEqual), Some(9), Some(9), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::NotEqual), Some(10), Some(10), Some(ref param0), Some(ref param1))
=> native_forward_2!{ param0, param1, (Float(value0), Float(value1)) => { return Bool(value0 != value1); } },
(&FnName::Operator(SeperatorKind::GreatEqual), Some(9), Some(9), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::GreatEqual), Some(10), Some(10), Some(ref param0), Some(ref param1))
=> native_forward_2!{ param0, param1, (Float(value0), Float(value1)) => { return Bool(value0 >= value1); } },
(&FnName::Operator(SeperatorKind::LessEqual), Some(9), Some(9), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::LessEqual), Some(10), Some(10), Some(ref param0), Some(ref param1))
=> native_forward_2!{ param0, param1, (Float(value0), Float(value1)) => { return Bool(value0 <= value1); } },
(&FnName::Operator(SeperatorKind::Great), Some(9), Some(9), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::Great), Some(10), Some(10), Some(ref param0), Some(ref param1))
=> native_forward_2!{ param0, param1, (Float(value0), Float(value1)) => { return Bool(value0 > value1); } },
(&FnName::Operator(SeperatorKind::Less), Some(9), Some(9), Some(ref param0), Some(ref param1))
| (&FnName::Operator(SeperatorKind::Less), Some(10), Some(10), Some(ref param0), Some(ref param1))
=> native_forward_2!{ param0, param1, (Float(value0), Float(value1)) => { return Bool(value0 < value1); } },
// Float cast to float
(&FnName::Cast(9), Some(9), None, Some(ref param0), None)
| (&FnName::Cast(10), Some(9), None, Some(ref param0), None)
| (&FnName::Cast(9), Some(10), None, Some(ref param0), None)
| (&FnName::Cast(10), Some(10), None, Some(ref param0), None)
=> native_forward_1!{ param0, Float(value) => { return Float(value); } },
// Float cast to integral
(&FnName::Cast(8), Some(9), None, Some(ref param0), None)
| (&FnName::Cast(8), Some(10), None, Some(ref param0), None)
=> native_forward_1!{ param0, Float(value) => { return Int(value as u64); } },
// Char Compare
(&FnName::Operator(SeperatorKind::Equal), Some(11), Some(11), Some(ref param0), Some(ref param1))
=> native_forward_2!{ param0, param1, (Char(value0), Char(value1)) => { return Bool(value0 == value1); } },
(&FnName::Operator(SeperatorKind::NotEqual), Some(11), Some(11), Some(ref param0), Some(ref param1))
=> native_forward_2!{ param0, param1, (Char(value0), Char(value1)) => { return Bool(value0 != value1); } },
(&FnName::Operator(SeperatorKind::GreatEqual), Some(11), Some(11), Some(ref param0), Some(ref param1))
=> native_forward_2!{ param0, param1, (Char(value0), Char(value1)) => { return Bool(value0 >= value1); } },
(&FnName::Operator(SeperatorKind::LessEqual), Some(11), Some(11), Some(ref param0), Some(ref param1))
=> native_forward_2!{ param0, param1, (Char(value0), Char(value1)) => { return Bool(value0 <= value1); } },
(&FnName::Operator(SeperatorKind::Great), Some(11), Some(11), Some(ref param0), Some(ref param1))
=> native_forward_2!{ param0, param1, (Char(value0), Char(value1)) => { return Bool(value0 > value1); } },
(&FnName::Operator(SeperatorKind::Less), Some(11), Some(11), Some(ref param0), Some(ref param1))
=> native_forward_2!{ param0, param1, (Char(value0), Char(value1)) => { return Bool(value0 < value1); } },
// Char cast
(&FnName::Cast(6), Some(11), None, Some(ref param0), None)
=> native_forward_1!{ param0, Char(value) => { return RuntimeValue::Int(value as u64); } },
// Bool
(&FnName::Operator(SeperatorKind::Equal), Some(12), Some(12), Some(ref param0), Some(ref param1))
=> native_forward_2!{ param0, param1, (Bool(value0), Bool(value1)) => { return Bool(value0 == value1); } },
(&FnName::Operator(SeperatorKind::NotEqual), Some(12), Some(12), Some(ref param0), Some(ref param1))
=> native_forward_2!{ param0, param1, (Bool(value0), Bool(value1)) => { return Bool(value0 != value1); } },
(&FnName::Operator(SeperatorKind::LogicalAnd), Some(12), Some(12), Some(ref param0), Some(ref param1))
=> native_forward_2!{ param0, param1, (Bool(value0), Bool(value1)) => { return Bool(value0 && value1); } },
(&FnName::Operator(SeperatorKind::LogicalOr), Some(12), Some(12), Some(ref param0), Some(ref param1))
=> native_forward_2!{ param0, param1, (Bool(value0), Bool(value1)) => { return Bool(value0 || value1); } },
(&FnName::Operator(SeperatorKind::LogicalNot), Some(12), None, Some(ref param0), None)
=> native_forward_1!{ param0, Bool(value) => { return Bool(!value); } },
// Str
(&FnName::Operator(SeperatorKind::Add), Some(13), Some(13), Some(ref param0), Some(ref param1))
=> native_forward_2!{ param0, param1, (Str(value0), Str(value1)) => { return Str(value0 + &value1); } },
(&FnName::Operator(SeperatorKind::Equal), Some(13), Some(13), Some(ref param0), Some(ref param1))
=> native_forward_2!{ param0, param1, (Str(value0), Str(value1)) => { return Bool(value0 == value1); } },
(&FnName::Operator(SeperatorKind::NotEqual), Some(13), Some(13), Some(ref param0), Some(ref param1))
=> native_forward_2!{ param0, param1, (Str(value0), Str(value1)) => { return Bool(value0 != value1); } },
// Special ident dispatcher
(&FnName::Ident(ref ident_name), param_type0, param_type1, param0, param1) => match (ident_name.as_ref(), param_type0, param_type1, param0, param1) {
// Integral is_odd
("is_odd", Some(1), None, Some(ref param0), None)
| ("is_odd", Some(2), None, Some(ref param0), None)
| ("is_odd", Some(3), None, Some(ref param0), None)
| ("is_odd", Some(4), None, Some(ref param0), None)
| ("is_odd", Some(5), None, Some(ref param0), None)
| ("is_odd", Some(6), None, Some(ref param0), None)
| ("is_odd", Some(7), None, Some(ref param0), None)
| ("is_odd", Some(8), None, Some(ref param0), None)
=> native_forward_1!{ param0, Int(value) => { return Bool((value & 1) == 0); } },
// Integral to_string
("to_string", Some(1), None, Some(ref param0), None)
| ("to_string", Some(2), None, Some(ref param0), None)
| ("to_string", Some(3), None, Some(ref param0), None)
| ("to_string", Some(4), None, Some(ref param0), None)
| ("to_string", Some(5), None, Some(ref param0), None)
| ("to_string", Some(6), None, Some(ref param0), None)
| ("to_string", Some(7), None, Some(ref param0), None)
| ("to_string", Some(8), None, Some(ref param0), None)
=> native_forward_1!{ param0, Int(value) => { return Str(format!("{}", value)); } },
// Float to_string
("to_string", Some(9), None, Some(ref param0), None)
| ("to_string", Some(10), None, Some(ref param0), None)
=> native_forward_1!{ param0, Float(value) => { return Str(format!("{}", value)); } },
// Char to_string
("to_string", Some(11), None, Some(ref param0), None)
=> native_forward_1!{ param0, Char(value) => { return Str(format!("{}", value)); } },
// String
("length", Some(13), None, Some(ref param0), None)
=> native_forward_1!{ param0, Str(value) => { return Int(value.len() as u64); } },
("get_index", Some(13), Some(5), Some(ref param0), Some(ref param1))
=> native_forward_2!{ param0, param1, (Str(value0), Int(value1)) => { return Char(value0.chars().nth(value1 as usize).unwrap()); } },
("get_index", Some(13), Some(8), Some(ref param0), Some(ref param1))
=> native_forward_2!{ param0, param1, (Str(value0), Int(value1)) => { return Char(value0.chars().nth(value1 as usize).unwrap()); } },
(_, _, _, _, _) => (),
},
(_, _, _, _, _) => (),
}
// Builtin template type global
if let &FnName::Ident(ref fn_name) = &fn_name {
if fn_name == "?new_tuple" { // ?new_tuple(aaa, bbb, ccc) -> (aaa, bbb, ccc)
let mut rt_values = Vec::new();
for param in params {
rt_values.push(rt.index(param));
}
return RuntimeValue::Tuple(rt_values);
} else if fn_name == "?new_array" { // ?new_array(value, size) -> [value]
// Currently 5 and 8 are all 8 at runtime, no more need to check
if let RuntimeValue::Int(item_init_size) = rt.index(¶ms[1]) {
let item_init_value = rt.index(¶ms[0]);
let mut array_items = Vec::new();
for _ in 0..item_init_size {
array_items.push(item_init_value.clone());
}
return RuntimeValue::ArrayRef(rt.allocate_heap(RuntimeValue::Array(array_items)));
}
} else if str_begin_with(fn_name, "?new_array_") { // ?new_array_xxx() -> [xxx]
return RuntimeValue::ArrayRef(rt.allocate_heap(RuntimeValue::Array(Vec::new())));
} else if str_begin_with(fn_name, "set_item") {
let mut temp_id_str = String::new();
for i in 8..fn_name.len() {
temp_id_str.push(fn_name.chars().nth(i).unwrap());
}
let item_id = usize::from_str(&temp_id_str).unwrap();
if params.len() == 2 {
let new_value = rt.index(¶ms[1]);
match rt.index_mut(¶ms[0]) {
&mut RuntimeValue::Tuple(ref mut items) => { items[item_id] = new_value; return RuntimeValue::Unit; }
_ => unreachable!()
}
} else {
unreachable!()
}
}
}
// Builtin template type instance
if let Some(real_typeid) = prep_param_type(¶m_types, 0) {
match types.get_by_idx(real_typeid) {
&Type::Base(_) => unreachable!(),
&Type::Array(_item_real_typeid) => {
match (&fn_name,
prep_param_type(¶m_types, 0), prep_param_type(¶m_types, 1), prep_param_type(¶m_types, 2),
prep_param(¶ms, 0), prep_param(¶ms, 1), prep_param(¶ms, 2)) {
(&FnName::Operator(SeperatorKind::Equal), _, _, _, Some(ref param0), Some(ref param1), None) => {
match (rt.index(param0), rt.index(param1)) {
(RuntimeValue::ArrayRef(heap_index1), RuntimeValue::ArrayRef(heap_index2)) => {
let (array1_clone, array2_clone) = match (&rt.heap[heap_index1], &rt.heap[heap_index2]) {
(&RuntimeValue::Array(ref array1), &RuntimeValue::Array(ref array2)) => (array1.clone(), array2.clone()),
_ => unreachable!(),
};
if array1_clone.len() != array2_clone.len() {
return RuntimeValue::Bool(false);
} else {
let mut ret_val = true;
for i in 0..array1_clone.len() {
ret_val = ret_val && (array1_clone[i] == array2_clone[i]); // because cannot decide part of heap's operand, that's all
}
return RuntimeValue::Bool(ret_val);
}
}
_ => unreachable!()
}
}
(&FnName::Operator(SeperatorKind::NotEqual), _, _, _, Some(ref param0), Some(ref param1), None) => {
match (rt.index(param0), rt.index(param1)) {
(RuntimeValue::ArrayRef(heap_index1), RuntimeValue::ArrayRef(heap_index2)) => {
let (array1_clone, array2_clone) = match (&rt.heap[heap_index1], &rt.heap[heap_index2]) {
(&RuntimeValue::Array(ref array1), &RuntimeValue::Array(ref array2)) => (array1.clone(), array2.clone()),
_ => unreachable!(),
};
if array1_clone.len() != array2_clone.len() {
return RuntimeValue::Bool(true);
} else {
let mut ret_val = false;
for i in 0..array1_clone.len() {
ret_val = ret_val || (array1_clone[i] != array2_clone[i]);
}
return RuntimeValue::Bool(ret_val);
}
}
_ => unreachable!()
}
}
(&FnName::Ident(ref ident_name), param_type0, param_type1, param_type2, param0, param1, param2) => match (ident_name.as_ref(), param_type0, param_type1, param_type2, param0, param1, param2) {
("set_index", _, Some(5), _, Some(ref param0), Some(ref param1), Some(ref param2))
| ("set_index", _, Some(8), _, Some(ref param0), Some(ref param1), Some(ref param2)) => {
match (rt.index(param0), rt.index(param1), rt.index(param2)) {
(RuntimeValue::ArrayRef(heap_index), RuntimeValue::Int(array_index), new_value) => {
match &mut rt.heap[heap_index as usize] {
&mut RuntimeValue::Array(ref mut array) => { array[array_index as usize] = new_value.clone(); return RuntimeValue::Unit; }
_ => unreachable!()
}
}
_ => unreachable!()
}
}
("get_index", _, Some(5), None, Some(ref param0), Some(ref param1), None)
| ("get_index", _, Some(8), None, Some(ref param0), Some(ref param1), None) => {
match (rt.index(param0), rt.index(param1)) {
(RuntimeValue::ArrayRef(heap_index), RuntimeValue::Int(array_index)) => {
match &mut rt.heap[heap_index as usize] {
&mut RuntimeValue::Array(ref mut array) => return array[array_index as usize].clone(),
_ => unreachable!()
}
}
_ => unreachable!()
}
}
("push", _, _, None, Some(ref param0), Some(ref param1), None) => {
match (rt.index(param0), rt.index(param1)) {
(RuntimeValue::ArrayRef(heap_index), new_value) => {
match &mut rt.heap[heap_index as usize] {
&mut RuntimeValue::Array(ref mut array) => { array.push(new_value.clone()); return RuntimeValue::Unit; }
_ => unreachable!()
}
}
_ => unreachable!()
}
}
("pop", _, None, None, Some(ref param0), None, None) => {
match rt.index(param0) {
RuntimeValue::ArrayRef(heap_index) => {
match &mut rt.heap[heap_index as usize] {
&mut RuntimeValue::Array(ref mut array) => return array.pop().unwrap(),
_ => unreachable!()
}
}
_ => unreachable!()
}
}
("length", _, None, None, Some(ref param0), None, None) => {
match rt.index(param0) {
RuntimeValue::ArrayRef(heap_index) => {
match &mut rt.heap[heap_index as usize] {
&mut RuntimeValue::Array(ref mut array) => return RuntimeValue::Int(array.len() as u64),
_ => unreachable!()
}
}
_ => unreachable!()
}
}
_ => unreachable!(),
},
_ => unreachable!(),
}
}
&Type::Tuple(ref _item_real_typeids) => {
match (&fn_name, prep_param_type(¶m_types, 0), prep_param_type(¶m_types, 1), prep_param(¶ms, 0), prep_param(¶ms, 1)) {
(&FnName::Operator(SeperatorKind::Equal), _, _, Some(ref param0), Some(ref param1)) => {
match (rt.index(param0), rt.index(param1)) {
(RuntimeValue::Tuple(values1), RuntimeValue::Tuple(values2)) => {
let mut ret_val = true;
for i in 0..values1.len() {
ret_val = ret_val && values1[i] == values2[i];
}
return RuntimeValue::Bool(ret_val);
}
_ => unreachable!()
}
}
(&FnName::Operator(SeperatorKind::NotEqual), _, _, Some(ref param0), Some(ref param1)) => {
match (rt.index(param0), rt.index(param1)) {
(RuntimeValue::Tuple(values1), RuntimeValue::Tuple(values2)) => {
let mut ret_val = false;
for i in 0..values1.len() {
ret_val = ret_val || values1[i] != values2[i];
}
return RuntimeValue::Bool(ret_val);
}
_ => unreachable!()
}
}
_ => unreachable!()
}
}
}
}
unreachable!()
}
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.