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 |
---|---|---|---|---|---|---|---|---|---|---|---|
df374bac81098ea1ba4c7f25dbc3432e0e70c67c
|
Rust
|
burzek/katas
|
/AdventOfCode2021/src/day3.rs
|
UTF-8
| 1,797 | 3.15625 | 3 |
[] |
no_license
|
use std::collections::HashSet;
pub fn day3_task1(mut input: String) {
input.retain(|c| c != '\n');
const PACKET_LEN: usize = 12;
let packets = input.len() / PACKET_LEN;
let mut gamma = String::new();
for i in 0..PACKET_LEN {
let mut zero_count = 0;
for j in 0..packets {
match input.as_str().bytes().nth(i + j * PACKET_LEN).unwrap() {
48 => zero_count = zero_count + 1, //bytes ~100x faster than chars()
49 => zero_count = zero_count - 1,
_ => panic!("invalid input")
}
}
gamma.push(if zero_count > 0 { '0' } else { '1' });
}
let gamma_i = u32::from_str_radix(gamma.as_str(), 2).unwrap();
println!("day 3 task 1: {}", gamma_i * (((1 << PACKET_LEN) - 1) - gamma_i));
}
pub fn day3_task2(mut input: String) {
let mut set = HashSet::new();
input.lines().for_each(|l| { set.insert(l); });
let mut iter = 0;
while (set.len() != 1) {
let zero_count = set.iter().fold(0, |acc, &x| { acc + if x.as_bytes()[iter] == 48 {1} else {-1} });
set.retain(|&e| { e.bytes().nth(iter).unwrap() == if zero_count > 0 { 48 } else { 49 } });
iter = iter + 1;
}
let co2 = u32::from_str_radix(set.iter().next().unwrap(), 2).unwrap();
set.clear();
input.lines().for_each(|l| { set.insert(l); });
let mut iter = 0;
while (set.len() != 1) {
let zero_count = set.iter().fold(0, |acc, &x| { acc + if x.as_bytes()[iter] == 48 {1} else {-1} });
set.retain(|&e| { e.bytes().nth(iter).unwrap() != if zero_count > 0 { 48 } else { 49 } });
iter = iter + 1;
}
let co2_scrub = u32::from_str_radix(set.iter().next().unwrap(), 2).unwrap();
println!("day 3 task 2: {}", co2 * co2_scrub);
}
| true |
58959d18efda71793737875d1074e75c6ecd071a
|
Rust
|
Tetrergeru/opengl-rust-0
|
/src/drawing/shaders.rs
|
UTF-8
| 1,659 | 2.796875 | 3 |
[] |
no_license
|
use gl::types::{GLenum, GLuint};
use gl::Gl;
use std::ffi::CStr;
use super::create_whitespace_cstring;
pub struct Shader {
gl: Gl,
id: GLuint,
}
impl Shader {
pub(super) fn id(&self) -> GLuint {
self.id
}
pub fn from_source(gl: Gl, source: &CStr, kind: GLenum) -> Result<Shader, String> {
let id = unsafe { gl.CreateShader(kind) };
unsafe {
gl.ShaderSource(id, 1, &source.as_ptr(), std::ptr::null());
gl.CompileShader(id);
}
let mut success: gl::types::GLint = 1;
unsafe {
gl.GetShaderiv(id, gl::COMPILE_STATUS, &mut success);
}
if success == 0 {
let mut len: gl::types::GLint = 0;
unsafe {
gl.GetShaderiv(id, gl::INFO_LOG_LENGTH, &mut len);
}
let error = create_whitespace_cstring(len as usize);
unsafe {
gl.GetShaderInfoLog(
id,
len,
std::ptr::null_mut(),
error.as_ptr() as *mut gl::types::GLchar,
);
}
return Err(error.to_string_lossy().into_owned());
}
Ok(Self { gl, id })
}
pub fn from_vert_source(gl: Gl, source: &CStr) -> Result<Shader, String> {
Self::from_source(gl, source, gl::VERTEX_SHADER)
}
pub fn from_frag_source(gl: Gl, source: &CStr) -> Result<Shader, String> {
Self::from_source(gl, source, gl::FRAGMENT_SHADER)
}
}
impl Drop for Shader {
fn drop(&mut self) {
unsafe {
self.gl.DeleteShader(self.id);
}
}
}
| true |
d0b43dd6c7682a36ac529acb46e1c1d0509afe78
|
Rust
|
ferrous-systems/imxrt1052
|
/src/ccm_analog/misc2_clr/mod.rs
|
UTF-8
| 44,590 | 2.78125 | 3 |
[] |
no_license
|
#[doc = r" Value read from the register"]
pub struct R {
bits: u32,
}
#[doc = r" Value to write to the register"]
pub struct W {
bits: u32,
}
impl super::MISC2_CLR {
#[doc = r" Modifies the contents of the register"]
#[inline]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,
{
let bits = self.register.get();
let r = R { bits: bits };
let mut w = W { bits: bits };
f(&r, &mut w);
self.register.set(w.bits);
}
#[doc = r" Reads the contents of the register"]
#[inline]
pub fn read(&self) -> R {
R {
bits: self.register.get(),
}
}
#[doc = r" Writes to the register"]
#[inline]
pub fn write<F>(&self, f: F)
where
F: FnOnce(&mut W) -> &mut W,
{
let mut w = W::reset_value();
f(&mut w);
self.register.set(w.bits);
}
#[doc = r" Writes the reset value to the register"]
#[inline]
pub fn reset(&self) {
self.write(|w| w)
}
}
#[doc = "Possible values of the field `REG0_BO_OFFSET`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum REG0_BO_OFFSETR {
#[doc = "Brownout offset = 0.100V"]
REG0_BO_OFFSET_4,
#[doc = "Brownout offset = 0.175V"]
REG0_BO_OFFSET_7,
#[doc = r" Reserved"]
_Reserved(u8),
}
impl REG0_BO_OFFSETR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
match *self {
REG0_BO_OFFSETR::REG0_BO_OFFSET_4 => 4,
REG0_BO_OFFSETR::REG0_BO_OFFSET_7 => 7,
REG0_BO_OFFSETR::_Reserved(bits) => bits,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: u8) -> REG0_BO_OFFSETR {
match value {
4 => REG0_BO_OFFSETR::REG0_BO_OFFSET_4,
7 => REG0_BO_OFFSETR::REG0_BO_OFFSET_7,
i => REG0_BO_OFFSETR::_Reserved(i),
}
}
#[doc = "Checks if the value of the field is `REG0_BO_OFFSET_4`"]
#[inline]
pub fn is_reg0_bo_offset_4(&self) -> bool {
*self == REG0_BO_OFFSETR::REG0_BO_OFFSET_4
}
#[doc = "Checks if the value of the field is `REG0_BO_OFFSET_7`"]
#[inline]
pub fn is_reg0_bo_offset_7(&self) -> bool {
*self == REG0_BO_OFFSETR::REG0_BO_OFFSET_7
}
}
#[doc = "Possible values of the field `REG0_BO_STATUS`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum REG0_BO_STATUSR {
#[doc = "Brownout, supply is below target minus brownout offset."]
REG0_BO_STATUS_1,
#[doc = r" Reserved"]
_Reserved(bool),
}
impl REG0_BO_STATUSR {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
REG0_BO_STATUSR::REG0_BO_STATUS_1 => true,
REG0_BO_STATUSR::_Reserved(bits) => bits,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> REG0_BO_STATUSR {
match value {
true => REG0_BO_STATUSR::REG0_BO_STATUS_1,
i => REG0_BO_STATUSR::_Reserved(i),
}
}
#[doc = "Checks if the value of the field is `REG0_BO_STATUS_1`"]
#[inline]
pub fn is_reg0_bo_status_1(&self) -> bool {
*self == REG0_BO_STATUSR::REG0_BO_STATUS_1
}
}
#[doc = r" Value of the field"]
pub struct REG0_ENABLE_BOR {
bits: bool,
}
impl REG0_ENABLE_BOR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct REG0_OKR {
bits: bool,
}
impl REG0_OKR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = "Possible values of the field `PLL3_disable`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum PLL3_DISABLER {
#[doc = "PLL3 is being used by peripherals and is enabled when SoC is not in any low power mode"]
PLL3_DISABLE_0,
#[doc = "PLL3 can be disabled when the SoC is not in any low power mode"]
PLL3_DISABLE_1,
}
impl PLL3_DISABLER {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
PLL3_DISABLER::PLL3_DISABLE_0 => false,
PLL3_DISABLER::PLL3_DISABLE_1 => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> PLL3_DISABLER {
match value {
false => PLL3_DISABLER::PLL3_DISABLE_0,
true => PLL3_DISABLER::PLL3_DISABLE_1,
}
}
#[doc = "Checks if the value of the field is `PLL3_DISABLE_0`"]
#[inline]
pub fn is_pll3_disable_0(&self) -> bool {
*self == PLL3_DISABLER::PLL3_DISABLE_0
}
#[doc = "Checks if the value of the field is `PLL3_DISABLE_1`"]
#[inline]
pub fn is_pll3_disable_1(&self) -> bool {
*self == PLL3_DISABLER::PLL3_DISABLE_1
}
}
#[doc = "Possible values of the field `REG1_BO_OFFSET`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum REG1_BO_OFFSETR {
#[doc = "Brownout offset = 0.100V"]
REG1_BO_OFFSET_4,
#[doc = "Brownout offset = 0.175V"]
REG1_BO_OFFSET_7,
#[doc = r" Reserved"]
_Reserved(u8),
}
impl REG1_BO_OFFSETR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
match *self {
REG1_BO_OFFSETR::REG1_BO_OFFSET_4 => 4,
REG1_BO_OFFSETR::REG1_BO_OFFSET_7 => 7,
REG1_BO_OFFSETR::_Reserved(bits) => bits,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: u8) -> REG1_BO_OFFSETR {
match value {
4 => REG1_BO_OFFSETR::REG1_BO_OFFSET_4,
7 => REG1_BO_OFFSETR::REG1_BO_OFFSET_7,
i => REG1_BO_OFFSETR::_Reserved(i),
}
}
#[doc = "Checks if the value of the field is `REG1_BO_OFFSET_4`"]
#[inline]
pub fn is_reg1_bo_offset_4(&self) -> bool {
*self == REG1_BO_OFFSETR::REG1_BO_OFFSET_4
}
#[doc = "Checks if the value of the field is `REG1_BO_OFFSET_7`"]
#[inline]
pub fn is_reg1_bo_offset_7(&self) -> bool {
*self == REG1_BO_OFFSETR::REG1_BO_OFFSET_7
}
}
#[doc = "Possible values of the field `REG1_BO_STATUS`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum REG1_BO_STATUSR {
#[doc = "Brownout, supply is below target minus brownout offset."]
REG1_BO_STATUS_1,
#[doc = r" Reserved"]
_Reserved(bool),
}
impl REG1_BO_STATUSR {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
REG1_BO_STATUSR::REG1_BO_STATUS_1 => true,
REG1_BO_STATUSR::_Reserved(bits) => bits,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> REG1_BO_STATUSR {
match value {
true => REG1_BO_STATUSR::REG1_BO_STATUS_1,
i => REG1_BO_STATUSR::_Reserved(i),
}
}
#[doc = "Checks if the value of the field is `REG1_BO_STATUS_1`"]
#[inline]
pub fn is_reg1_bo_status_1(&self) -> bool {
*self == REG1_BO_STATUSR::REG1_BO_STATUS_1
}
}
#[doc = r" Value of the field"]
pub struct REG1_ENABLE_BOR {
bits: bool,
}
impl REG1_ENABLE_BOR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct REG1_OKR {
bits: bool,
}
impl REG1_OKR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = "Possible values of the field `AUDIO_DIV_LSB`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum AUDIO_DIV_LSBR {
#[doc = "divide by 1 (Default)"]
AUDIO_DIV_LSB_0,
#[doc = "divide by 2"]
AUDIO_DIV_LSB_1,
}
impl AUDIO_DIV_LSBR {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
AUDIO_DIV_LSBR::AUDIO_DIV_LSB_0 => false,
AUDIO_DIV_LSBR::AUDIO_DIV_LSB_1 => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> AUDIO_DIV_LSBR {
match value {
false => AUDIO_DIV_LSBR::AUDIO_DIV_LSB_0,
true => AUDIO_DIV_LSBR::AUDIO_DIV_LSB_1,
}
}
#[doc = "Checks if the value of the field is `AUDIO_DIV_LSB_0`"]
#[inline]
pub fn is_audio_div_lsb_0(&self) -> bool {
*self == AUDIO_DIV_LSBR::AUDIO_DIV_LSB_0
}
#[doc = "Checks if the value of the field is `AUDIO_DIV_LSB_1`"]
#[inline]
pub fn is_audio_div_lsb_1(&self) -> bool {
*self == AUDIO_DIV_LSBR::AUDIO_DIV_LSB_1
}
}
#[doc = "Possible values of the field `REG2_BO_OFFSET`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum REG2_BO_OFFSETR {
#[doc = "Brownout offset = 0.100V"]
REG2_BO_OFFSET_4,
#[doc = "Brownout offset = 0.175V"]
REG2_BO_OFFSET_7,
#[doc = r" Reserved"]
_Reserved(u8),
}
impl REG2_BO_OFFSETR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
match *self {
REG2_BO_OFFSETR::REG2_BO_OFFSET_4 => 4,
REG2_BO_OFFSETR::REG2_BO_OFFSET_7 => 7,
REG2_BO_OFFSETR::_Reserved(bits) => bits,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: u8) -> REG2_BO_OFFSETR {
match value {
4 => REG2_BO_OFFSETR::REG2_BO_OFFSET_4,
7 => REG2_BO_OFFSETR::REG2_BO_OFFSET_7,
i => REG2_BO_OFFSETR::_Reserved(i),
}
}
#[doc = "Checks if the value of the field is `REG2_BO_OFFSET_4`"]
#[inline]
pub fn is_reg2_bo_offset_4(&self) -> bool {
*self == REG2_BO_OFFSETR::REG2_BO_OFFSET_4
}
#[doc = "Checks if the value of the field is `REG2_BO_OFFSET_7`"]
#[inline]
pub fn is_reg2_bo_offset_7(&self) -> bool {
*self == REG2_BO_OFFSETR::REG2_BO_OFFSET_7
}
}
#[doc = r" Value of the field"]
pub struct REG2_BO_STATUSR {
bits: bool,
}
impl REG2_BO_STATUSR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct REG2_ENABLE_BOR {
bits: bool,
}
impl REG2_ENABLE_BOR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct REG2_OKR {
bits: bool,
}
impl REG2_OKR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = "Possible values of the field `AUDIO_DIV_MSB`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum AUDIO_DIV_MSBR {
#[doc = "divide by 1 (Default)"]
AUDIO_DIV_MSB_0,
#[doc = "divide by 2"]
AUDIO_DIV_MSB_1,
}
impl AUDIO_DIV_MSBR {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
AUDIO_DIV_MSBR::AUDIO_DIV_MSB_0 => false,
AUDIO_DIV_MSBR::AUDIO_DIV_MSB_1 => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> AUDIO_DIV_MSBR {
match value {
false => AUDIO_DIV_MSBR::AUDIO_DIV_MSB_0,
true => AUDIO_DIV_MSBR::AUDIO_DIV_MSB_1,
}
}
#[doc = "Checks if the value of the field is `AUDIO_DIV_MSB_0`"]
#[inline]
pub fn is_audio_div_msb_0(&self) -> bool {
*self == AUDIO_DIV_MSBR::AUDIO_DIV_MSB_0
}
#[doc = "Checks if the value of the field is `AUDIO_DIV_MSB_1`"]
#[inline]
pub fn is_audio_div_msb_1(&self) -> bool {
*self == AUDIO_DIV_MSBR::AUDIO_DIV_MSB_1
}
}
#[doc = "Possible values of the field `REG0_STEP_TIME`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum REG0_STEP_TIMER {
#[doc = "64"]
_64_CLOCKS,
#[doc = "128"]
_128_CLOCKS,
#[doc = "256"]
_256_CLOCKS,
#[doc = "512"]
_512_CLOCKS,
}
impl REG0_STEP_TIMER {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
match *self {
REG0_STEP_TIMER::_64_CLOCKS => 0,
REG0_STEP_TIMER::_128_CLOCKS => 1,
REG0_STEP_TIMER::_256_CLOCKS => 2,
REG0_STEP_TIMER::_512_CLOCKS => 3,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: u8) -> REG0_STEP_TIMER {
match value {
0 => REG0_STEP_TIMER::_64_CLOCKS,
1 => REG0_STEP_TIMER::_128_CLOCKS,
2 => REG0_STEP_TIMER::_256_CLOCKS,
3 => REG0_STEP_TIMER::_512_CLOCKS,
_ => unreachable!(),
}
}
#[doc = "Checks if the value of the field is `_64_CLOCKS`"]
#[inline]
pub fn is_64_clocks(&self) -> bool {
*self == REG0_STEP_TIMER::_64_CLOCKS
}
#[doc = "Checks if the value of the field is `_128_CLOCKS`"]
#[inline]
pub fn is_128_clocks(&self) -> bool {
*self == REG0_STEP_TIMER::_128_CLOCKS
}
#[doc = "Checks if the value of the field is `_256_CLOCKS`"]
#[inline]
pub fn is_256_clocks(&self) -> bool {
*self == REG0_STEP_TIMER::_256_CLOCKS
}
#[doc = "Checks if the value of the field is `_512_CLOCKS`"]
#[inline]
pub fn is_512_clocks(&self) -> bool {
*self == REG0_STEP_TIMER::_512_CLOCKS
}
}
#[doc = "Possible values of the field `REG1_STEP_TIME`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum REG1_STEP_TIMER {
#[doc = "64"]
_64_CLOCKS,
#[doc = "128"]
_128_CLOCKS,
#[doc = "256"]
_256_CLOCKS,
#[doc = "512"]
_512_CLOCKS,
}
impl REG1_STEP_TIMER {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
match *self {
REG1_STEP_TIMER::_64_CLOCKS => 0,
REG1_STEP_TIMER::_128_CLOCKS => 1,
REG1_STEP_TIMER::_256_CLOCKS => 2,
REG1_STEP_TIMER::_512_CLOCKS => 3,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: u8) -> REG1_STEP_TIMER {
match value {
0 => REG1_STEP_TIMER::_64_CLOCKS,
1 => REG1_STEP_TIMER::_128_CLOCKS,
2 => REG1_STEP_TIMER::_256_CLOCKS,
3 => REG1_STEP_TIMER::_512_CLOCKS,
_ => unreachable!(),
}
}
#[doc = "Checks if the value of the field is `_64_CLOCKS`"]
#[inline]
pub fn is_64_clocks(&self) -> bool {
*self == REG1_STEP_TIMER::_64_CLOCKS
}
#[doc = "Checks if the value of the field is `_128_CLOCKS`"]
#[inline]
pub fn is_128_clocks(&self) -> bool {
*self == REG1_STEP_TIMER::_128_CLOCKS
}
#[doc = "Checks if the value of the field is `_256_CLOCKS`"]
#[inline]
pub fn is_256_clocks(&self) -> bool {
*self == REG1_STEP_TIMER::_256_CLOCKS
}
#[doc = "Checks if the value of the field is `_512_CLOCKS`"]
#[inline]
pub fn is_512_clocks(&self) -> bool {
*self == REG1_STEP_TIMER::_512_CLOCKS
}
}
#[doc = "Possible values of the field `REG2_STEP_TIME`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum REG2_STEP_TIMER {
#[doc = "64"]
_64_CLOCKS,
#[doc = "128"]
_128_CLOCKS,
#[doc = "256"]
_256_CLOCKS,
#[doc = "512"]
_512_CLOCKS,
}
impl REG2_STEP_TIMER {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
match *self {
REG2_STEP_TIMER::_64_CLOCKS => 0,
REG2_STEP_TIMER::_128_CLOCKS => 1,
REG2_STEP_TIMER::_256_CLOCKS => 2,
REG2_STEP_TIMER::_512_CLOCKS => 3,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: u8) -> REG2_STEP_TIMER {
match value {
0 => REG2_STEP_TIMER::_64_CLOCKS,
1 => REG2_STEP_TIMER::_128_CLOCKS,
2 => REG2_STEP_TIMER::_256_CLOCKS,
3 => REG2_STEP_TIMER::_512_CLOCKS,
_ => unreachable!(),
}
}
#[doc = "Checks if the value of the field is `_64_CLOCKS`"]
#[inline]
pub fn is_64_clocks(&self) -> bool {
*self == REG2_STEP_TIMER::_64_CLOCKS
}
#[doc = "Checks if the value of the field is `_128_CLOCKS`"]
#[inline]
pub fn is_128_clocks(&self) -> bool {
*self == REG2_STEP_TIMER::_128_CLOCKS
}
#[doc = "Checks if the value of the field is `_256_CLOCKS`"]
#[inline]
pub fn is_256_clocks(&self) -> bool {
*self == REG2_STEP_TIMER::_256_CLOCKS
}
#[doc = "Checks if the value of the field is `_512_CLOCKS`"]
#[inline]
pub fn is_512_clocks(&self) -> bool {
*self == REG2_STEP_TIMER::_512_CLOCKS
}
}
#[doc = "Possible values of the field `VIDEO_DIV`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum VIDEO_DIVR {
#[doc = "divide by 1 (Default)"]
VIDEO_DIV_0,
#[doc = "divide by 2"]
VIDEO_DIV_1,
#[doc = "divide by 1"]
VIDEO_DIV_2,
#[doc = "divide by 4"]
VIDEO_DIV_3,
}
impl VIDEO_DIVR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
match *self {
VIDEO_DIVR::VIDEO_DIV_0 => 0,
VIDEO_DIVR::VIDEO_DIV_1 => 1,
VIDEO_DIVR::VIDEO_DIV_2 => 2,
VIDEO_DIVR::VIDEO_DIV_3 => 3,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: u8) -> VIDEO_DIVR {
match value {
0 => VIDEO_DIVR::VIDEO_DIV_0,
1 => VIDEO_DIVR::VIDEO_DIV_1,
2 => VIDEO_DIVR::VIDEO_DIV_2,
3 => VIDEO_DIVR::VIDEO_DIV_3,
_ => unreachable!(),
}
}
#[doc = "Checks if the value of the field is `VIDEO_DIV_0`"]
#[inline]
pub fn is_video_div_0(&self) -> bool {
*self == VIDEO_DIVR::VIDEO_DIV_0
}
#[doc = "Checks if the value of the field is `VIDEO_DIV_1`"]
#[inline]
pub fn is_video_div_1(&self) -> bool {
*self == VIDEO_DIVR::VIDEO_DIV_1
}
#[doc = "Checks if the value of the field is `VIDEO_DIV_2`"]
#[inline]
pub fn is_video_div_2(&self) -> bool {
*self == VIDEO_DIVR::VIDEO_DIV_2
}
#[doc = "Checks if the value of the field is `VIDEO_DIV_3`"]
#[inline]
pub fn is_video_div_3(&self) -> bool {
*self == VIDEO_DIVR::VIDEO_DIV_3
}
}
#[doc = r" Proxy"]
pub struct _REG0_ENABLE_BOW<'a> {
w: &'a mut W,
}
impl<'a> _REG0_ENABLE_BOW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 5;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `PLL3_disable`"]
pub enum PLL3_DISABLEW {
#[doc = "PLL3 is being used by peripherals and is enabled when SoC is not in any low power mode"]
PLL3_DISABLE_0,
#[doc = "PLL3 can be disabled when the SoC is not in any low power mode"]
PLL3_DISABLE_1,
}
impl PLL3_DISABLEW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
PLL3_DISABLEW::PLL3_DISABLE_0 => false,
PLL3_DISABLEW::PLL3_DISABLE_1 => true,
}
}
}
#[doc = r" Proxy"]
pub struct _PLL3_DISABLEW<'a> {
w: &'a mut W,
}
impl<'a> _PLL3_DISABLEW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: PLL3_DISABLEW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "PLL3 is being used by peripherals and is enabled when SoC is not in any low power mode"]
#[inline]
pub fn pll3_disable_0(self) -> &'a mut W {
self.variant(PLL3_DISABLEW::PLL3_DISABLE_0)
}
#[doc = "PLL3 can be disabled when the SoC is not in any low power mode"]
#[inline]
pub fn pll3_disable_1(self) -> &'a mut W {
self.variant(PLL3_DISABLEW::PLL3_DISABLE_1)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 7;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _REG1_ENABLE_BOW<'a> {
w: &'a mut W,
}
impl<'a> _REG1_ENABLE_BOW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 13;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `AUDIO_DIV_LSB`"]
pub enum AUDIO_DIV_LSBW {
#[doc = "divide by 1 (Default)"]
AUDIO_DIV_LSB_0,
#[doc = "divide by 2"]
AUDIO_DIV_LSB_1,
}
impl AUDIO_DIV_LSBW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
AUDIO_DIV_LSBW::AUDIO_DIV_LSB_0 => false,
AUDIO_DIV_LSBW::AUDIO_DIV_LSB_1 => true,
}
}
}
#[doc = r" Proxy"]
pub struct _AUDIO_DIV_LSBW<'a> {
w: &'a mut W,
}
impl<'a> _AUDIO_DIV_LSBW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: AUDIO_DIV_LSBW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "divide by 1 (Default)"]
#[inline]
pub fn audio_div_lsb_0(self) -> &'a mut W {
self.variant(AUDIO_DIV_LSBW::AUDIO_DIV_LSB_0)
}
#[doc = "divide by 2"]
#[inline]
pub fn audio_div_lsb_1(self) -> &'a mut W {
self.variant(AUDIO_DIV_LSBW::AUDIO_DIV_LSB_1)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 15;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _REG2_ENABLE_BOW<'a> {
w: &'a mut W,
}
impl<'a> _REG2_ENABLE_BOW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 21;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `AUDIO_DIV_MSB`"]
pub enum AUDIO_DIV_MSBW {
#[doc = "divide by 1 (Default)"]
AUDIO_DIV_MSB_0,
#[doc = "divide by 2"]
AUDIO_DIV_MSB_1,
}
impl AUDIO_DIV_MSBW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
AUDIO_DIV_MSBW::AUDIO_DIV_MSB_0 => false,
AUDIO_DIV_MSBW::AUDIO_DIV_MSB_1 => true,
}
}
}
#[doc = r" Proxy"]
pub struct _AUDIO_DIV_MSBW<'a> {
w: &'a mut W,
}
impl<'a> _AUDIO_DIV_MSBW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: AUDIO_DIV_MSBW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "divide by 1 (Default)"]
#[inline]
pub fn audio_div_msb_0(self) -> &'a mut W {
self.variant(AUDIO_DIV_MSBW::AUDIO_DIV_MSB_0)
}
#[doc = "divide by 2"]
#[inline]
pub fn audio_div_msb_1(self) -> &'a mut W {
self.variant(AUDIO_DIV_MSBW::AUDIO_DIV_MSB_1)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 23;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `REG0_STEP_TIME`"]
pub enum REG0_STEP_TIMEW {
#[doc = "64"]
_64_CLOCKS,
#[doc = "128"]
_128_CLOCKS,
#[doc = "256"]
_256_CLOCKS,
#[doc = "512"]
_512_CLOCKS,
}
impl REG0_STEP_TIMEW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> u8 {
match *self {
REG0_STEP_TIMEW::_64_CLOCKS => 0,
REG0_STEP_TIMEW::_128_CLOCKS => 1,
REG0_STEP_TIMEW::_256_CLOCKS => 2,
REG0_STEP_TIMEW::_512_CLOCKS => 3,
}
}
}
#[doc = r" Proxy"]
pub struct _REG0_STEP_TIMEW<'a> {
w: &'a mut W,
}
impl<'a> _REG0_STEP_TIMEW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: REG0_STEP_TIMEW) -> &'a mut W {
{
self.bits(variant._bits())
}
}
#[doc = "64"]
#[inline]
pub fn _64_clocks(self) -> &'a mut W {
self.variant(REG0_STEP_TIMEW::_64_CLOCKS)
}
#[doc = "128"]
#[inline]
pub fn _128_clocks(self) -> &'a mut W {
self.variant(REG0_STEP_TIMEW::_128_CLOCKS)
}
#[doc = "256"]
#[inline]
pub fn _256_clocks(self) -> &'a mut W {
self.variant(REG0_STEP_TIMEW::_256_CLOCKS)
}
#[doc = "512"]
#[inline]
pub fn _512_clocks(self) -> &'a mut W {
self.variant(REG0_STEP_TIMEW::_512_CLOCKS)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bits(self, value: u8) -> &'a mut W {
const MASK: u8 = 3;
const OFFSET: u8 = 24;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `REG1_STEP_TIME`"]
pub enum REG1_STEP_TIMEW {
#[doc = "64"]
_64_CLOCKS,
#[doc = "128"]
_128_CLOCKS,
#[doc = "256"]
_256_CLOCKS,
#[doc = "512"]
_512_CLOCKS,
}
impl REG1_STEP_TIMEW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> u8 {
match *self {
REG1_STEP_TIMEW::_64_CLOCKS => 0,
REG1_STEP_TIMEW::_128_CLOCKS => 1,
REG1_STEP_TIMEW::_256_CLOCKS => 2,
REG1_STEP_TIMEW::_512_CLOCKS => 3,
}
}
}
#[doc = r" Proxy"]
pub struct _REG1_STEP_TIMEW<'a> {
w: &'a mut W,
}
impl<'a> _REG1_STEP_TIMEW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: REG1_STEP_TIMEW) -> &'a mut W {
{
self.bits(variant._bits())
}
}
#[doc = "64"]
#[inline]
pub fn _64_clocks(self) -> &'a mut W {
self.variant(REG1_STEP_TIMEW::_64_CLOCKS)
}
#[doc = "128"]
#[inline]
pub fn _128_clocks(self) -> &'a mut W {
self.variant(REG1_STEP_TIMEW::_128_CLOCKS)
}
#[doc = "256"]
#[inline]
pub fn _256_clocks(self) -> &'a mut W {
self.variant(REG1_STEP_TIMEW::_256_CLOCKS)
}
#[doc = "512"]
#[inline]
pub fn _512_clocks(self) -> &'a mut W {
self.variant(REG1_STEP_TIMEW::_512_CLOCKS)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bits(self, value: u8) -> &'a mut W {
const MASK: u8 = 3;
const OFFSET: u8 = 26;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `REG2_STEP_TIME`"]
pub enum REG2_STEP_TIMEW {
#[doc = "64"]
_64_CLOCKS,
#[doc = "128"]
_128_CLOCKS,
#[doc = "256"]
_256_CLOCKS,
#[doc = "512"]
_512_CLOCKS,
}
impl REG2_STEP_TIMEW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> u8 {
match *self {
REG2_STEP_TIMEW::_64_CLOCKS => 0,
REG2_STEP_TIMEW::_128_CLOCKS => 1,
REG2_STEP_TIMEW::_256_CLOCKS => 2,
REG2_STEP_TIMEW::_512_CLOCKS => 3,
}
}
}
#[doc = r" Proxy"]
pub struct _REG2_STEP_TIMEW<'a> {
w: &'a mut W,
}
impl<'a> _REG2_STEP_TIMEW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: REG2_STEP_TIMEW) -> &'a mut W {
{
self.bits(variant._bits())
}
}
#[doc = "64"]
#[inline]
pub fn _64_clocks(self) -> &'a mut W {
self.variant(REG2_STEP_TIMEW::_64_CLOCKS)
}
#[doc = "128"]
#[inline]
pub fn _128_clocks(self) -> &'a mut W {
self.variant(REG2_STEP_TIMEW::_128_CLOCKS)
}
#[doc = "256"]
#[inline]
pub fn _256_clocks(self) -> &'a mut W {
self.variant(REG2_STEP_TIMEW::_256_CLOCKS)
}
#[doc = "512"]
#[inline]
pub fn _512_clocks(self) -> &'a mut W {
self.variant(REG2_STEP_TIMEW::_512_CLOCKS)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bits(self, value: u8) -> &'a mut W {
const MASK: u8 = 3;
const OFFSET: u8 = 28;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `VIDEO_DIV`"]
pub enum VIDEO_DIVW {
#[doc = "divide by 1 (Default)"]
VIDEO_DIV_0,
#[doc = "divide by 2"]
VIDEO_DIV_1,
#[doc = "divide by 1"]
VIDEO_DIV_2,
#[doc = "divide by 4"]
VIDEO_DIV_3,
}
impl VIDEO_DIVW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> u8 {
match *self {
VIDEO_DIVW::VIDEO_DIV_0 => 0,
VIDEO_DIVW::VIDEO_DIV_1 => 1,
VIDEO_DIVW::VIDEO_DIV_2 => 2,
VIDEO_DIVW::VIDEO_DIV_3 => 3,
}
}
}
#[doc = r" Proxy"]
pub struct _VIDEO_DIVW<'a> {
w: &'a mut W,
}
impl<'a> _VIDEO_DIVW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: VIDEO_DIVW) -> &'a mut W {
{
self.bits(variant._bits())
}
}
#[doc = "divide by 1 (Default)"]
#[inline]
pub fn video_div_0(self) -> &'a mut W {
self.variant(VIDEO_DIVW::VIDEO_DIV_0)
}
#[doc = "divide by 2"]
#[inline]
pub fn video_div_1(self) -> &'a mut W {
self.variant(VIDEO_DIVW::VIDEO_DIV_1)
}
#[doc = "divide by 1"]
#[inline]
pub fn video_div_2(self) -> &'a mut W {
self.variant(VIDEO_DIVW::VIDEO_DIV_2)
}
#[doc = "divide by 4"]
#[inline]
pub fn video_div_3(self) -> &'a mut W {
self.variant(VIDEO_DIVW::VIDEO_DIV_3)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bits(self, value: u8) -> &'a mut W {
const MASK: u8 = 3;
const OFFSET: u8 = 30;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
impl R {
#[doc = r" Value of the register as raw bits"]
#[inline]
pub fn bits(&self) -> u32 {
self.bits
}
#[doc = "Bits 0:2 - This field defines the brown out voltage offset for the CORE power domain"]
#[inline]
pub fn reg0_bo_offset(&self) -> REG0_BO_OFFSETR {
REG0_BO_OFFSETR::_from({
const MASK: u8 = 7;
const OFFSET: u8 = 0;
((self.bits >> OFFSET) & MASK as u32) as u8
})
}
#[doc = "Bit 3 - Reg0 brownout status bit.Not related to CCM. See Power Management Unit (PMU)"]
#[inline]
pub fn reg0_bo_status(&self) -> REG0_BO_STATUSR {
REG0_BO_STATUSR::_from({
const MASK: bool = true;
const OFFSET: u8 = 3;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 5 - Enables the brownout detection.Not related to CCM. See Power Management Unit (PMU)"]
#[inline]
pub fn reg0_enable_bo(&self) -> REG0_ENABLE_BOR {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 5;
((self.bits >> OFFSET) & MASK as u32) != 0
};
REG0_ENABLE_BOR { bits }
}
#[doc = "Bit 6 - ARM supply Not related to CCM. See Power Management Unit (PMU)"]
#[inline]
pub fn reg0_ok(&self) -> REG0_OKR {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 6;
((self.bits >> OFFSET) & MASK as u32) != 0
};
REG0_OKR { bits }
}
#[doc = "Bit 7 - When USB is in low power suspend mode this Control bit is used to indicate if other system peripherals require the USB PLL3 clock when the SoC is not in low power mode"]
#[inline]
pub fn pll3_disable(&self) -> PLL3_DISABLER {
PLL3_DISABLER::_from({
const MASK: bool = true;
const OFFSET: u8 = 7;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bits 8:10 - This field defines the brown out voltage offset for the xPU power domain"]
#[inline]
pub fn reg1_bo_offset(&self) -> REG1_BO_OFFSETR {
REG1_BO_OFFSETR::_from({
const MASK: u8 = 7;
const OFFSET: u8 = 8;
((self.bits >> OFFSET) & MASK as u32) as u8
})
}
#[doc = "Bit 11 - Reg1 brownout status bit. Not related to CCM. See Power Management Unit (PMU)"]
#[inline]
pub fn reg1_bo_status(&self) -> REG1_BO_STATUSR {
REG1_BO_STATUSR::_from({
const MASK: bool = true;
const OFFSET: u8 = 11;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 13 - Enables the brownout detection.Not related to CCM. See Power Management Unit (PMU)"]
#[inline]
pub fn reg1_enable_bo(&self) -> REG1_ENABLE_BOR {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 13;
((self.bits >> OFFSET) & MASK as u32) != 0
};
REG1_ENABLE_BOR { bits }
}
#[doc = "Bit 14 - GPU/VPU supply Not related to CCM. See Power Management Unit (PMU)"]
#[inline]
pub fn reg1_ok(&self) -> REG1_OKR {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 14;
((self.bits >> OFFSET) & MASK as u32) != 0
};
REG1_OKR { bits }
}
#[doc = "Bit 15 - LSB of Post-divider for Audio PLL"]
#[inline]
pub fn audio_div_lsb(&self) -> AUDIO_DIV_LSBR {
AUDIO_DIV_LSBR::_from({
const MASK: bool = true;
const OFFSET: u8 = 15;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bits 16:18 - This field defines the brown out voltage offset for the xPU power domain"]
#[inline]
pub fn reg2_bo_offset(&self) -> REG2_BO_OFFSETR {
REG2_BO_OFFSETR::_from({
const MASK: u8 = 7;
const OFFSET: u8 = 16;
((self.bits >> OFFSET) & MASK as u32) as u8
})
}
#[doc = "Bit 19 - Reg2 brownout status bit.Not related to CCM. See Power Management Unit (PMU)"]
#[inline]
pub fn reg2_bo_status(&self) -> REG2_BO_STATUSR {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 19;
((self.bits >> OFFSET) & MASK as u32) != 0
};
REG2_BO_STATUSR { bits }
}
#[doc = "Bit 21 - Enables the brownout detection.Not related to CCM. See Power Management Unit (PMU)"]
#[inline]
pub fn reg2_enable_bo(&self) -> REG2_ENABLE_BOR {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 21;
((self.bits >> OFFSET) & MASK as u32) != 0
};
REG2_ENABLE_BOR { bits }
}
#[doc = "Bit 22 - Signals that the voltage is above the brownout level for the SOC supply"]
#[inline]
pub fn reg2_ok(&self) -> REG2_OKR {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 22;
((self.bits >> OFFSET) & MASK as u32) != 0
};
REG2_OKR { bits }
}
#[doc = "Bit 23 - MSB of Post-divider for Audio PLL"]
#[inline]
pub fn audio_div_msb(&self) -> AUDIO_DIV_MSBR {
AUDIO_DIV_MSBR::_from({
const MASK: bool = true;
const OFFSET: u8 = 23;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bits 24:25 - Number of clock periods (24MHz clock).Not related to CCM. See Power Management Unit (PMU)"]
#[inline]
pub fn reg0_step_time(&self) -> REG0_STEP_TIMER {
REG0_STEP_TIMER::_from({
const MASK: u8 = 3;
const OFFSET: u8 = 24;
((self.bits >> OFFSET) & MASK as u32) as u8
})
}
#[doc = "Bits 26:27 - Number of clock periods (24MHz clock).Not related to CCM. See Power Management Unit (PMU)"]
#[inline]
pub fn reg1_step_time(&self) -> REG1_STEP_TIMER {
REG1_STEP_TIMER::_from({
const MASK: u8 = 3;
const OFFSET: u8 = 26;
((self.bits >> OFFSET) & MASK as u32) as u8
})
}
#[doc = "Bits 28:29 - Number of clock periods (24MHz clock).Not related to CCM. See Power Management Unit (PMU)"]
#[inline]
pub fn reg2_step_time(&self) -> REG2_STEP_TIMER {
REG2_STEP_TIMER::_from({
const MASK: u8 = 3;
const OFFSET: u8 = 28;
((self.bits >> OFFSET) & MASK as u32) as u8
})
}
#[doc = "Bits 30:31 - Post-divider for video"]
#[inline]
pub fn video_div(&self) -> VIDEO_DIVR {
VIDEO_DIVR::_from({
const MASK: u8 = 3;
const OFFSET: u8 = 30;
((self.bits >> OFFSET) & MASK as u32) as u8
})
}
}
impl W {
#[doc = r" Reset value of the register"]
#[inline]
pub fn reset_value() -> W {
W { bits: 2565927 }
}
#[doc = r" Writes raw bits to the register"]
#[inline]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
#[doc = "Bit 5 - Enables the brownout detection.Not related to CCM. See Power Management Unit (PMU)"]
#[inline]
pub fn reg0_enable_bo(&mut self) -> _REG0_ENABLE_BOW {
_REG0_ENABLE_BOW { w: self }
}
#[doc = "Bit 7 - When USB is in low power suspend mode this Control bit is used to indicate if other system peripherals require the USB PLL3 clock when the SoC is not in low power mode"]
#[inline]
pub fn pll3_disable(&mut self) -> _PLL3_DISABLEW {
_PLL3_DISABLEW { w: self }
}
#[doc = "Bit 13 - Enables the brownout detection.Not related to CCM. See Power Management Unit (PMU)"]
#[inline]
pub fn reg1_enable_bo(&mut self) -> _REG1_ENABLE_BOW {
_REG1_ENABLE_BOW { w: self }
}
#[doc = "Bit 15 - LSB of Post-divider for Audio PLL"]
#[inline]
pub fn audio_div_lsb(&mut self) -> _AUDIO_DIV_LSBW {
_AUDIO_DIV_LSBW { w: self }
}
#[doc = "Bit 21 - Enables the brownout detection.Not related to CCM. See Power Management Unit (PMU)"]
#[inline]
pub fn reg2_enable_bo(&mut self) -> _REG2_ENABLE_BOW {
_REG2_ENABLE_BOW { w: self }
}
#[doc = "Bit 23 - MSB of Post-divider for Audio PLL"]
#[inline]
pub fn audio_div_msb(&mut self) -> _AUDIO_DIV_MSBW {
_AUDIO_DIV_MSBW { w: self }
}
#[doc = "Bits 24:25 - Number of clock periods (24MHz clock).Not related to CCM. See Power Management Unit (PMU)"]
#[inline]
pub fn reg0_step_time(&mut self) -> _REG0_STEP_TIMEW {
_REG0_STEP_TIMEW { w: self }
}
#[doc = "Bits 26:27 - Number of clock periods (24MHz clock).Not related to CCM. See Power Management Unit (PMU)"]
#[inline]
pub fn reg1_step_time(&mut self) -> _REG1_STEP_TIMEW {
_REG1_STEP_TIMEW { w: self }
}
#[doc = "Bits 28:29 - Number of clock periods (24MHz clock).Not related to CCM. See Power Management Unit (PMU)"]
#[inline]
pub fn reg2_step_time(&mut self) -> _REG2_STEP_TIMEW {
_REG2_STEP_TIMEW { w: self }
}
#[doc = "Bits 30:31 - Post-divider for video"]
#[inline]
pub fn video_div(&mut self) -> _VIDEO_DIVW {
_VIDEO_DIVW { w: self }
}
}
| true |
91b37e6accee5c17ed3daf4316b5c52d46a0de4e
|
Rust
|
nhatvu148/rustlang
|
/src/print.rs
|
UTF-8
| 638 | 3.703125 | 4 |
[] |
no_license
|
pub fn run() {
// Print to console
println!("Hello! from the print.rs file");
// Basic formatting
println!("Number {} is number of {}", 1, "Vu");
// Positional arguments
println!("{0} is from {1} and {0} is {2}!", "Vu", "Vietnam", "cool");
// Named arguments
println!(
"{name} likes to play {activity}",
name = "Vu",
activity = "soccer"
);
// Placeholder traits
println!("Binary: {:b} Hex: {:x} Octal: {:o}.", 10, 10, 10);
// Placeholder for debug trait
println!("{:?}", (12, true, "hi there!"));
// Basic math
println!("10 + 10 = {}", 10 + 10);
}
| true |
71b0ef00686353ff8619143e6f90d16d7f90bb0c
|
Rust
|
jallen02/deuterium
|
/src/predicate/and.rs
|
UTF-8
| 516 | 2.640625 | 3 |
[
"MIT"
] |
permissive
|
use super::ToSharedPredicate;
#[derive(Clone, Debug)]
pub struct AndPredicate {
pub left: super::SharedPredicate,
pub right: super::SharedPredicate
}
pub trait ToAndPredicate {
fn and(&self, val: super::SharedPredicate) -> super::SharedPredicate;
}
impl ToAndPredicate for super::SharedPredicate {
fn and(&self, predicate: super::SharedPredicate) -> super::SharedPredicate {
AndPredicate{ left: self.clone(), right: predicate }.upcast()
}
}
impl super::Predicate for AndPredicate { }
| true |
bb73c75dee766758b09dcfe33ba6d49c233161b2
|
Rust
|
hidva/waitforgraph
|
/src/bin/subgraph/main.rs
|
UTF-8
| 1,778 | 2.671875 | 3 |
[
"Apache-2.0"
] |
permissive
|
use anyhow::anyhow;
use std::collections::{HashMap, HashSet};
use std::io::{self, BufRead};
use waitforgraph::graph::dot;
use waitforgraph::lock::SessionId;
fn add_graph(graph: &mut HashMap<SessionId, Vec<SessionId>>, line: &str) -> anyhow::Result<()> {
let mut spliter = line.split("->");
let left = spliter.next().ok_or(anyhow!(""))?.trim();
let right = spliter.next().ok_or(anyhow!(""))?.trim();
if spliter.next().is_some() {
return Err(anyhow!(""));
}
let left: SessionId = left.parse()?;
let right: SessionId = right.parse()?;
if let Some(vexs) = graph.get_mut(&left) {
vexs.push(right);
} else {
graph.insert(left, vec![right]);
}
return Ok(());
}
fn main() {
let argv: Vec<String> = std::env::args().collect();
let from: SessionId = argv[1].parse().expect("invalid from session id");
let mut graph: HashMap<SessionId, Vec<SessionId>> = HashMap::new();
for line in io::stdin().lock().lines() {
match line {
Ok(line) => {
if add_graph(&mut graph, &line).is_err() {
eprintln!("add_graph: invalid line: {}", line);
}
}
Err(e) => {
eprintln!("error: {}", e);
}
}
}
let mut meet = HashSet::new();
let mut queue = Vec::new();
queue.push(from);
meet.insert(from);
while let Some(sessid) = queue.pop() {
if let Some(deps) = graph.get(&sessid) {
for &dep in deps {
if !meet.contains(&dep) {
queue.push(dep);
meet.insert(dep);
}
}
}
}
println!("{}", dot::render_tiny(&graph, meet.iter().map(|v| *v)));
return;
}
| true |
ab32cbc128e8cf14b9a252ae9b116f6a496c76ad
|
Rust
|
kebab-mai-haddi/substrate-api-client
|
/src/examples/example_contract.rs
|
UTF-8
| 7,372 | 2.53125 | 3 |
[
"Apache-2.0"
] |
permissive
|
/*
Copyright 2019 Supercomputing Systems AG
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
//! This example shows how to use the predefined contract extrinsics found in the extrinsic module.
//! General (slightly outdated) background on how to deploy ink! contract is found here:
//! `https://substrate.dev/docs/en/contracts/deploying-a-contract`
//!
//!
//! *Note*: The runtime module here is not in the generic substrate node. Hence, this example
//! must run against the customized node found in `https://github.com/scs/substrate-test-nodes`.
use std::sync::mpsc::channel;
use clap::{load_yaml, App};
use codec::Decode;
use keyring::AccountKeyring;
use node_primitives::AccountId;
use sp_core::H256 as Hash;
use sp_std::prelude::*;
use substrate_api_client::Api;
// Lookup the details on the event from the metadata
#[derive(Decode)]
struct ContractInstantiatedEventArgs {
_from: AccountId,
deployed_at: AccountId,
}
fn main() {
env_logger::init();
let url = get_node_url_from_cli();
// initialize api and set the signer (sender) that is used to sign the extrinsics
let from = AccountKeyring::Alice.pair();
let api = Api::new(format!("ws://{}", url)).set_signer(from);
println!("[+] Alice's Account Nonce is {}", api.get_nonce().unwrap());
// contract to be deployed on the chain
const CONTRACT: &str = r#"
(module
(func (export "call"))
(func (export "deploy"))
)
"#;
let wasm = wabt::wat2wasm(CONTRACT).expect("invalid wabt");
// 1. Put the contract code as a wasm blob on the chain
let xt = api.contract_put_code(500_000, wasm);
println!(
"[+] Putting contract code on chain with extrinsic:\n\n{:?}\n",
xt
);
let tx_hash = api.send_extrinsic(xt.hex_encode()).unwrap();
println!("[+] Transaction got finalized. Hash: {:?}\n", tx_hash);
// setup the events listener for our chain.
let (events_in, events_out) = channel();
api.subscribe_events(events_in.clone());
// wait for the `contract.CodeStored(code_hash)` event, which returns code hash that is needed
// to define what contract shall be instantiated afterwards.
println!("[+] Waiting for the contract.CodeStored event");
let code_hash: Hash = api
.wait_for_event("Contract", "CodeStored", &events_out)
.unwrap()
.unwrap();
println!("[+] Event was received. Got code hash: {:?}\n", code_hash);
// 2. Create an actual instance of the contract
let xt = api.contract_instantiate(1_000, 500_000, code_hash, vec![1u8]);
println!(
"[+] Creating a contract instance with extrinsic:\n\n{:?}\n",
xt
);
let tx_hash = api.send_extrinsic(xt.hex_encode()).unwrap();
println!("[+] Transaction got finalized. Hash: {:?}\n", tx_hash);
// Now if the contract has been instantiated successfully, the following events are fired:
// - indices.NewAccountIndex, balances.NewAccount -> generic events when an account is created
// - balances.Transfer(from, to, balance) -> Transfer from caller of contract.create/call to the contract account
// - contract.Instantiated(from, deployedAt) -> successful deployment at address. We Want this one.
// Note: Trying to instantiate the same contract with the same data twice does not work. No event is
// fired correspondingly.
println!("[+] Waiting for the contract.Instantiated event");
// Fixme: Somehow no events are thrown from this point. The example hangs here...
let args: ContractInstantiatedEventArgs = api
.wait_for_event("Contract", "Instantiated", &events_out)
.unwrap()
.unwrap();
println!(
"[+] Event was received. Contract deployed at: {:?}\n",
args.deployed_at
);
// 3. Call the contract instance
let xt = api.contract_call(args.deployed_at.into(), 500_000, 500_000, vec![1u8]);
// Currently, a contract call does not fire any events nor interact in any other fashion with
// the outside world. Only node logs can supply information on the consequences of a contract
// call. Still, it can be checked if the transaction was successful.
println!(
"[+] Calling the contract with extrinsic Extrinsic:\n{:?}\n\n",
xt
);
let tx_hash = api.send_extrinsic(xt.hex_encode()).unwrap();
println!("[+] Transaction got finalized. Hash: {:?}", tx_hash);
}
pub fn get_node_url_from_cli() -> String {
let yml = load_yaml!("../../src/examples/cli.yml");
let matches = App::from_yaml(yml).get_matches();
let node_ip = matches.value_of("node-server").unwrap_or("127.0.0.1");
let node_port = matches.value_of("node-port").unwrap_or("9944");
let url = format!("{}:{}", node_ip, node_port);
println!("Interacting with node on {}", url);
url
}
// Alternatively you could subscribe to the contracts events using the Event enum from the
// node_runtime.
//
// use node_runtime::Event
//
//fn subcribe_to_code_stored_event(events_out: &Receiver<String>) -> Hash {
// loop {
// let event_str = events_out.recv().unwrap();
//
// let _unhex = hexstr_to_vec(event_str).unwrap();
// let mut _er_enc = _unhex.as_slice();
// let _events = Vec::<system::EventRecord<Event, Hash>>::decode(&mut _er_enc);
// if let Ok(evts) = _events {
// for evr in &evts {
// debug!("decoded: phase {:?} event {:?}", evr.phase, evr.event);
// if let Event::contracts(ce) = &evr.event {
// if let contracts::RawEvent::CodeStored(code_hash) = &ce {
// info!("Received Contract.CodeStored event");
// info!("Codehash: {:?}", code_hash);
// return code_hash.to_owned();
// }
// }
// }
// }
// }
//}
//
//fn subscribe_to_code_instantiated_event(events_out: &Receiver<String>) -> GenericAddress {
// loop {
// let event_str = events_out.recv().unwrap();
//
// let _unhex = hexstr_to_vec(event_str).unwrap();
// let mut _er_enc = _unhex.as_slice();
// let _events = Vec::<system::EventRecord<Event, Hash>>::decode(&mut _er_enc);
// if let Ok(evts) = _events {
// for evr in &evts {
// debug!("decoded: phase {:?} event {:?}", evr.phase, evr.event);
// if let Event::contracts(ce) = &evr.event {
// if let contracts::RawEvent::Instantiated(from, deployed_at) = &ce {
// info!("Received Contract.Instantiated Event");
// info!("From: {:?}", from);
// info!("Deployed at: {:?}", deployed_at);
// return GenericAddress::from(deployed_at.to_owned());
// }
// }
// }
// }
// }
//}
| true |
0641bda0ff7a60a0e8c9be185864570afe61afa5
|
Rust
|
serbe/rsp
|
/src/sites/freeproxylistcom.rs
|
UTF-8
| 1,154 | 2.546875 | 3 |
[
"MIT"
] |
permissive
|
use super::netutils::crawl;
use crate::error::RspError;
use regex::Regex;
pub async fn get() -> Result<Vec<String>, RspError> {
let urls = vec![
"https://free-proxy-list.com/?page=1",
"https://free-proxy-list.com/?page=2",
"https://free-proxy-list.com/?page=3",
"https://free-proxy-list.com/?page=4",
"https://free-proxy-list.com/?page=5",
"https://free-proxy-list.com/?search=1&page=&port=&type%5B%5D=http&type%5B%5D=https&level%5B%5D=high-anonymous&speed%5B%5D=2&speed%5B%5D=3&connect_time%5B%5D=3&up_time=60&search=Search",
];
let re = Regex::new(r"(\d{2,3}\.\d{2,3}\.\d{2,3}\.\d{2,3}:\d{2,5})")?;
let mut list = Vec::new();
for url in urls {
let body = crawl(url).await?;
list.append(
&mut re
.captures_iter(&body)
.map(|cap| cap[1].to_string())
.collect(),
);
}
Ok(list)
}
#[cfg(test)]
mod tests {
use super::get;
#[tokio::test]
async fn test_freeproxylistcom() {
let r = get().await;
assert!(r.is_ok());
assert!(dbg!(r.unwrap().len()) > 0);
}
}
| true |
101c6bda42621589194ce89a80fa3f2df1e70af3
|
Rust
|
sile/dotgraph
|
/src/graph.rs
|
UTF-8
| 3,490 | 3.421875 | 3 |
[] |
no_license
|
use std::io::{self, Write};
use node;
#[derive(Debug)]
pub struct Graph {
name: String,
properties: GraphProperties,
nodes: Vec<Node>,
edges: Vec<Edge>,
}
impl Graph {
pub fn new<T: Into<String>>(name: T) -> Self {
Graph {
name: name.into(),
properties: GraphProperties::default(),
nodes: Vec::new(),
edges: Vec::new(),
}
}
pub fn add_node(&mut self, node: Node) {
self.nodes.push(node);
}
pub fn add_edge(&mut self, edge: Edge) {
self.edges.push(edge);
}
pub fn properties_mut(&mut self) -> &mut GraphProperties {
&mut self.properties
}
pub fn write_as_dot<W: Write>(&self, mut writer: W) -> io::Result<()> {
let graph_type = if self.properties.is_directed {
"digraph"
} else {
"graph"
};
writeln!(writer, "{} {:?} {{", graph_type, self.name)?;
for node in self.nodes.iter() {
node.write(&mut writer)?;
}
for edge in self.edges.iter() {
edge.write(&mut writer, self.properties.is_directed)?;
}
writeln!(writer, "}}")?;
Ok(())
}
}
#[derive(Debug)]
pub struct GraphProperties {
pub is_directed: bool,
}
impl Default for GraphProperties {
fn default() -> Self {
GraphProperties { is_directed: false }
}
}
#[derive(Debug)]
pub struct Node {
id: String,
label: Option<String>,
shape: node::NodeShape,
}
impl Node {
pub fn new<T: Into<String>>(id: T) -> Self {
Node {
id: id.into(),
label: None,
shape: node::NodeShape::default(),
}
}
pub fn with_label(mut self, label: String) -> Self {
self.label = Some(label);
self
}
pub fn shape(mut self, shape: node::NodeShape) -> Self {
self.shape = shape;
self
}
pub fn set_lable<T: Into<String>>(&mut self, label: T) -> &mut Self {
self.label = Some(label.into());
self
}
fn write<W: Write>(&self, writer: &mut W) -> io::Result<()> {
write!(writer, " {:?}[", self.id)?;
let mut delim = "";
if let Some(ref label) = self.label {
write!(writer, "{}label={:?}", delim, label)?;
delim = ", ";
}
if node::NodeShape::default() != self.shape {
write!(writer, "{}shape={}", delim, self.shape)?;
// delim = ", ";
}
writeln!(writer, "];")?;
Ok(())
}
}
#[derive(Debug)]
pub struct Edge {
from_node_id: String,
to_node_id: String,
}
impl Edge {
pub fn new<T: Into<String>, U: Into<String>>(from: T, to: U) -> Self {
Edge {
from_node_id: from.into(),
to_node_id: to.into(),
}
}
fn write<W: Write>(&self, writer: &mut W, is_directed: bool) -> io::Result<()> {
let edge_type = if is_directed { "->" } else { "--" };
writeln!(writer,
" {:?} {} {:?};",
self.from_node_id,
edge_type,
self.to_node_id)?;
Ok(())
}
}
#[cfg(test)]
mod test {
use std::str;
use super::*;
#[test]
fn empty_graph() {
let graph = Graph::new("foo");
let mut buf = Vec::new();
graph.write_as_dot(&mut buf).unwrap();
let expected = r#"graph "foo" {
}
"#;
assert_eq!(str::from_utf8(&buf[..]).unwrap(), expected);
}
}
| true |
93b09f6b115caee24e3b4dee41efc70719a89962
|
Rust
|
BogdanFloris/leetcode-rust
|
/src/fizz_buzz.rs
|
UTF-8
| 795 | 3.734375 | 4 |
[] |
no_license
|
#[allow(dead_code)]
pub fn fizz_buzz(n: i32) -> Vec<String> {
let mut sol: Vec<String> = vec![];
for i in 1..=n {
if i % 3 == 0 && i % 5 == 0 {
sol.push(String::from("FizzBuzz"));
} else if i % 3 == 0 {
sol.push(String::from("Fizz"));
} else if i % 5 == 0 {
sol.push(String::from("Buzz"));
} else {
sol.push(i.to_string())
}
}
sol
}
#[cfg(test)]
mod tests {
use super::fizz_buzz;
#[test]
fn basic() {
let n = 15;
let sol = fizz_buzz(n);
assert_eq!(
sol,
vec![
"1", "2", "Fizz", "4", "Buzz", "Fizz", "7", "8", "Fizz", "Buzz", "11", "Fizz",
"13", "14", "FizzBuzz"
]
);
}
}
| true |
0bdffbff67c98dcb464bada62981877395db0f80
|
Rust
|
kb10uy/uv-remapper
|
/src/main.rs
|
UTF-8
| 2,501 | 2.875 | 3 |
[
"Apache-2.0"
] |
permissive
|
mod remapper;
mod scripting;
use crate::remapper::Remapper;
use std::{error::Error, fs::File, io::BufReader};
use clap::Clap;
use log::{error, info};
use rlua::prelude::*;
#[derive(Clap)]
#[clap(name = "UV Remapper", version, author, about)]
struct Arguments {
/// 実行する Lua スクリプトのパス
script: String,
/// 出力先画像ファイルのパス
output: String,
/// 出力画像のサイズ (デフォルト: 1024)
#[clap(short = "s", long = "size")]
size: Option<usize>,
/// ベース画像のパス。 --size は無視される
#[clap(short = "b", long = "base")]
base_image: Option<String>,
}
fn main() {
pretty_env_logger::init();
// Termination trait 安定化までのワークアラウンド
let termination = run();
match termination {
Ok(()) => (),
Err(e) => {
error!("{}", e);
let mut source = e.source();
while let Some(e) = source {
error!("-> {}", e);
source = e.source();
}
}
}
}
fn run() -> Result<(), Box<dyn Error>> {
let arguments = Arguments::parse();
let mut remapper = match arguments.base_image {
Some(path) => {
let image = image::open(&path)?;
info!("Loaded '{}' as base image", path);
Remapper::from_image(image)
}
None => {
let texture_size = arguments.size.unwrap_or(1024);
info!(
"Set empty image ({}x{}) as base image",
texture_size, texture_size
);
Remapper::new(texture_size, texture_size)
}
};
let lua = Lua::new();
let script_reader = BufReader::new(File::open(&arguments.script)?);
scripting::prepare(&lua, &arguments.script, script_reader)?;
info!("Loaded '{}' as manipulation script", arguments.script);
info!("Loading source images");
let loader = scripting::call_initialize(&lua)?;
for (key, filename) in loader.entries() {
let source = image::open(&filename)?;
remapper.insert_source(&key, source);
info!("Loaded '{}' as '{}'", filename, key);
}
info!("Executing remapper script");
let queue = scripting::call_run(&lua)?;
info!("Remapping image");
for command in queue.commands() {
remapper.patch(command)?;
}
info!("Saving as '{}'", arguments.output);
remapper.base_image().save(arguments.output)?;
Ok(())
}
| true |
3093a1b1502179417c7fd03d47e87652bbda1f33
|
Rust
|
christian-blades-cb/aoc-2018
|
/day9/src/main.rs
|
UTF-8
| 3,938 | 3.15625 | 3 |
[] |
no_license
|
#[macro_use]
extern crate nom;
use nom::digit;
use std::io::prelude::*;
fn main() -> Result<(), std::io::Error> {
use std::fs::File;
let mut file = File::open("input-day9")?;
let mut buf = String::new();
file.read_to_string(&mut buf)?;
let (n_players, last_marble) = parse_input(&buf).unwrap().1;
println!("day9.1 {}", part2(n_players, last_marble));
println!("day9.2 {}", part2(n_players, last_marble * 100));
Ok(())
}
fn part2(n_players: usize, final_marble: usize) -> usize {
use std::collections::VecDeque;
let mut board = VecDeque::with_capacity(final_marble);
board.push_back(0);
let mut players: Vec<usize> = vec![0_usize; n_players];
let mut current_player = (0..players.len()).into_iter().cycle().skip(1);
let draw = (1..=final_marble).into_iter();
for marble in draw {
let player_i = current_player.next().unwrap();
if marble % 23 == 0 {
players[player_i] += marble;
for _n in 0..7 {
let back = board.pop_back().unwrap();
board.push_front(back);
}
players[player_i] += board.pop_front().unwrap();
} else {
for _n in 0..2 {
let front = board.pop_front().unwrap();
board.push_back(front);
}
board.push_front(marble);
}
}
*(players.iter().max().unwrap())
}
named!(parse_input<&str, (usize, usize)>,
do_parse!(
n_players: digit >>
tag!(" players; last marble is worth ") >>
last_marble: digit >>
((n_players.parse::<usize>().unwrap(),
last_marble.parse::<usize>().unwrap()))));
#[derive(Debug, Clone)]
struct Player(usize);
// so very inefficient, I assume it's spending a bunch of time
// shifting the elements in the `remove` function
#[allow(dead_code)]
fn part1(n_players: usize, final_marble: usize) -> usize {
let mut board: Vec<usize> = Vec::with_capacity(final_marble);
board.push(0);
board.push(1);
let mut players: Vec<Player> = vec![Player(0); n_players];
let draw = (2..=final_marble).into_iter();
let mut current_index: usize = 1;
let mut current_player = (0..n_players).into_iter().cycle().skip(1);
for marble in draw {
let player_i = current_player.next().unwrap();
if marble % 23 == 0 {
players[player_i].0 += marble;
let mut next_board_index: isize = current_index as isize - 7;
if next_board_index < 0 {
next_board_index =
board.len() as isize - (next_board_index.abs() % board.len() as isize);
}
players[player_i].0 += board.remove(next_board_index as usize);
current_index = next_board_index as usize;
} else {
// non-23
let next_board_index = (current_index + 2) % board.len();
board.insert(next_board_index, marble);
current_index = next_board_index;
}
}
players.iter().map(|x| x.0).max().unwrap()
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_part1() {
assert_eq!(32, part1(9, 25));
assert_eq!(8317, part1(10, 1618));
assert_eq!(146373, part1(13, 7999));
assert_eq!(2764, part1(17, 1104));
assert_eq!(54718, part1(21, 6111));
assert_eq!(37305, part1(30, 5807));
}
#[test]
fn test_part2() {
assert_eq!(32, part2(9, 25));
assert_eq!(8317, part2(10, 1618));
assert_eq!(146373, part2(13, 7999));
assert_eq!(2764, part2(17, 1104));
assert_eq!(54718, part2(21, 6111));
assert_eq!(37305, part2(30, 5807));
}
#[test]
fn test_part1_real() {
assert_eq!(367802, part2(493, 71863));
}
#[test]
fn test_part2_real() {
assert_eq!(2996043280, part2(493, 71863 * 100));
}
}
| true |
6a5dc5ba615206f1abd7a57550314bf61e0bf66c
|
Rust
|
royaltm/rust-ym-file-parser
|
/src/ym.rs
|
UTF-8
| 12,329 | 2.703125 | 3 |
[] |
no_license
|
use core::time::Duration;
use core::num::NonZeroU32;
use core::fmt;
use core::ops::Range;
use chrono::NaiveDateTime;
pub mod flags;
pub mod effects;
mod parse;
mod player;
use flags::*;
use effects::*;
pub const MAX_DD_SAMPLES: usize = 32;
pub const MFP_TIMER_FREQUENCY: u32 = 2_457_600;
const DEFAULT_CHIPSET_FREQUENCY: u32 = 2_000_000;
const DEFAULT_FRAME_FREQUENCY: u16 = 50;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum YmVersion {
Ym2,
Ym3,
Ym4,
Ym5,
Ym6,
}
impl YmVersion {
/// The YM version identifier tag as a string (4 ascii characters).
pub fn tag(self) -> &'static str {
match self {
YmVersion::Ym2 => "YM2!",
YmVersion::Ym3 => "YM3!",
YmVersion::Ym4 => "YM4!",
YmVersion::Ym5 => "YM5!",
YmVersion::Ym6 => "YM6!",
}
}
}
impl fmt::Display for YmVersion {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.tag().fmt(f)
}
}
/// The **YM** music file.
///
/// The YM-file consist of [YmFrame]s that represent the state of the AY/YM chipset registers and
/// contain additional information about special effects.
///
/// Depending on the [YmSong::version] special effects are being encoded differently.
#[derive(Debug, Clone)]
pub struct YmSong {
/// YM-file version.
pub version: YmVersion,
/// The last modification timestamp of the YM-file from the LHA envelope.
pub created: Option<NaiveDateTime>,
/// The song attributes.
pub song_attrs: SongAttributes,
/// The song title or a file name.
pub title: String,
/// The song author.
pub author: String,
/// The comment.
pub comments: String,
/// The number of cycles per second of the AY/YM chipset clock.
pub chipset_frequency: u32,
/// The number of frames played each second.
pub frame_frequency: u16,
/// The loop frame index.
pub loop_frame: u32,
/// The AY/YM state frames.
pub frames: Box<[YmFrame]>,
/// `DIGI-DRUM` samples.
pub dd_samples: Box<[u8]>,
/// `DIGI-DRUM` sample end indexes in [YmSong::dd_samples].
pub dd_samples_ends: [usize;MAX_DD_SAMPLES],
cursor: usize,
voice_effects: [(SidVoice, SinusSid, DigiDrum); 3],
buzzer: SyncBuzzer,
}
/// This type represent the state of the AY/YM chipset registers and contain additional information
/// about special effects.
///
/// ```text
/// X - AY/YM register data.
/// S - Controls special effects.
/// P - Frequency pre-divisor.
/// F - Frequency divisor.
/// - - Unused.
/// ----------------------------------------------------------
/// b7 b6 b5 b4 b3 b2 b1 b0 Register description
/// 0: X X X X X X X X Fine period voice A
/// 1: S S S S X X X X Coarse period voice A
/// 2: X X X X X X X X Fine period voice B
/// 3: S S S S X X X X Coarse period voice B
/// 4: X X X X X X X X Fine period voice C
/// 5: - - - - X X X X Coarse period voice C
/// 6: P P P X X X X X Noise period
/// 7: X X X X X X X X Mixer control
/// 8: P P P X X X X X Volume voice A
/// 9: - - - X X X X X Volume voice B
/// 10: - - - X X X X X Volume voice C
/// 11: X X X X X X X X Envelope fine period
/// 12: X X X X X X X X Envelope coarse period
/// 13: x x x x X X X X Envelope shape
/// ----------------------------------------------------------
/// virtual registers to store extra data for special effects:
/// ----------------------------------------------------------
/// 14: F F F F F F F F Frequency divisor for S in 1
/// 15: F F F F F F F F Frequency divisor for S in 3
/// ```
///
/// The AY/YM `Envelope shape` register is modified only if the value of the 13 frame
/// register is not equal to `0xff`.
///
/// # Special effects
///
/// The frequency of a special effect is encoded as `(2457600 / P) / F`.
///
/// The divisor `F` is an unsigned 8-bit integer.
///
/// The pre-divisor `P` is encoded as:
///
/// |PPP| pre-divisor value|
/// |-----------------------|
/// |000| Timer off |
/// |001| 4 |
/// |010| 10 |
/// |011| 16 |
/// |100| 50 |
/// |101| 64 |
/// |110| 100 |
/// |111| 200 |
///
/// * The pre-divisor `P` in register 6 matches effect controlled by register 1.
/// * The divisor `F` in register 14 matches effect controlled by register 1.
/// * The pre-divisor `P` in register 8 matches effect controlled by register 3.
/// * The divisor `F` in register 15 matches effect controlled by register 3.
///
/// If an effect is active, the additional data resides in `X` bits in the `Volume` register of
/// the relevant voice:
///
/// * For the [`SID voice`][SidVoice] and [`Sinus SID`][SinusSid] effects the 4 lowest `X` bits
/// determine the effect's volume.
/// * For the [`Sync Buzzer`][SyncBuzzer] the 4 lowest `X` bits determine the effect's `Envelope shape`.
/// * For the [`DIGI-DRUM`][DigiDrum] effect the 5 `X` bits determine the played sample number.
/// * The `DIGI-DRUM` sample plays until its end or if it's overridden by another effect.
/// * All other effects are active only for the duration of a single frame.
/// * When the `DIGI-DRUM` is active the volume register from the frame for the relevant voice is being
/// ignored and the relevant voice mixer tone and noise bits are forced to be set.
///
/// The control bits of special effects are interpreted differently depending on the YM-file verion.
///
/// ## YM6!
///
/// The `S` bits in registers 1 and 3 controls any two of the selectable effects:
/// ```text
/// b7 b6 b5 b4
/// - - 0 0 effect disabled
/// - - 0 1 effect active on voice A
/// - - 1 0 effect active on voice B
/// - - 1 1 effect active on voice C
/// 0 0 - - select SID voice effect
/// 0 1 - - select DIGI-DRUM effect
/// 1 0 - - select Sinus SID effect
/// 1 1 - - select Sync Buzzer effect
/// ```
///
/// ## YM4!/YM5!
///
/// The `S` bits in register 1 controls the `SID voice` effect.
/// The `S` bits in register 3 controls the `DIGI-DRUM` effect.
/// ```text
/// b7 b6 b5 b4
/// - - 0 0 effect disabled
/// - - 0 1 effect active on voice A
/// - - 1 0 effect active on voice B
/// - - 1 1 effect active on voice C
/// - 0 - - SID voice timer continues, ignored for DIGI-DRUM
/// - 1 - - SID voice timer restarts, ignored for DIGI-DRUM
///```
///
/// ## YM3!
///
/// There are no special effects in this version.
///
/// ## YM2!
///
/// Only the `DIGI-DRUM` effect is recognized in this format. It is being played on voice C, and
/// uses one of the 40 predefined samples.
///
/// * The effect starts when the highest bit (7) of the `Volume voice C` register (10) is 1.
/// * The sample number is taken from the lowest 7 bits of the `Volume voice C` register (10).
/// * The effect frequency is calculated by `(2457600 / 4) / X`, where `X` is the unsigned 8-bit
/// value stored in the register 12 of the frame.
/// * The value of AY/YM chipset registers 11, 12 and 13 is only written if the value of the
/// frame register 13 is not equal to `0xFF`.
/// * The register 12 of the AY/YM chipset is always being set to `0` in this format.
/// * The register 13 of the AY/YM chipset is always being set to `0x10` in this format.
#[derive(Default, Debug, Clone, Copy)]
pub struct YmFrame {
/// Frame data.
pub data: [u8;16]
}
impl YmSong {
/// Creates a new instance of `YmSong` from the given `frames` and other meta data.
pub fn new(
version: YmVersion,
frames: Box<[YmFrame]>,
loop_frame: u32,
title: String,
created: Option<NaiveDateTime>
) -> YmSong
{
YmSong {
version,
created,
song_attrs: SongAttributes::default(),
title,
author: String::new(),
comments: String::new(),
chipset_frequency: DEFAULT_CHIPSET_FREQUENCY,
frame_frequency: DEFAULT_FRAME_FREQUENCY,
loop_frame,
frames,
dd_samples: Box::new([]),
dd_samples_ends: [0usize;MAX_DD_SAMPLES],
cursor: 0,
voice_effects: Default::default(),
buzzer: Default::default()
}
}
/// Returns `YmSong` with the `author` and `comments` set from the given arguments.
pub fn with_meta(mut self, author: String, comments: String) -> YmSong {
self.author = author;
self.comments = comments;
self
}
/// Returns `YmSong` with the `song_attrs`, `dd_samples` and `dd_samples_ends` set from the given arguments.
pub fn with_samples(
mut self,
song_attrs: SongAttributes,
dd_samples: Box<[u8]>,
dd_samples_ends: [usize;MAX_DD_SAMPLES]
) -> YmSong
{
self.song_attrs = song_attrs;
self.dd_samples = dd_samples;
self.dd_samples_ends = dd_samples_ends;
self
}
/// Returns `YmSong` with the `chipset_frequency` and `frame_frequency` set from the given arguments.
pub fn with_frequency(mut self, chipset_frequency: u32, frame_frequency: u16) -> YmSong {
self.chipset_frequency = chipset_frequency;
self.frame_frequency = frame_frequency;
self
}
/// Returns the song duration.
pub fn song_duration(&self) -> Duration {
let seconds = self.frames.len() as f64 / self.frame_frequency as f64;
Duration::from_secs_f64(seconds)
}
/// Returns the AY/YM chipset clock frequency.
#[inline]
pub fn clock_frequency(&self) -> f32 {
self.chipset_frequency as f32
}
/// Returns the number of AY/YM chipset clock cycles of a single music frame.
pub fn frame_cycles(&self) -> f32 {
self.clock_frequency() / self.frame_frequency as f32
}
/// Calculates the timer interval in clock cycles, from the given `divisor`.
pub fn timer_interval(&self, divisor: NonZeroU32) -> f32 {
let divisor = divisor.get() as f32;
self.clock_frequency() as f32 * divisor / MFP_TIMER_FREQUENCY as f32
}
/// Returns the indicated sample data range in the [YmSong::dd_samples] for the given `sample`.
///
/// # Panics
/// Panics if `sample` value is not below [MAX_DD_SAMPLES].
pub fn sample_data_range(&self, sample: usize) -> Range<usize> {
let end = self.dd_samples_ends[sample];
let start = match sample {
0 => 0,
index => self.dd_samples_ends[index - 1]
};
start..end
}
}
impl YmFrame {
/// Returns special effect control flags from the register 1.
pub fn fx0(&self) -> FxCtrlFlags {
FxCtrlFlags::from_bits_retain(self.data[1])
}
/// Returns special effect control flags from the register 3.
pub fn fx1(&self) -> FxCtrlFlags {
FxCtrlFlags::from_bits_retain(self.data[3])
}
/// Returns the value of the volume register for the indicated `chan`.
///
/// The 2 lowest bits of `chan` indicate the voice channel:
/// ```text
/// b1 b0 voice channel
/// 0 0 A
/// 0 1 B
/// 1 0 C
/// 1 1 invalid (panics in debug mode)
/// ```
pub fn vol(&self, chan: u8) -> u8 {
let chan = chan & 3;
debug_assert_ne!(chan, 3);
self.data[(VOL_A_REG + chan) as usize] & 0x1f
}
/// Calculates the timer divsor for the special effect `fx0`.
pub fn timer_divisor0(&self) -> Option<NonZeroU32> {
calculate_timer_divisor(self.data[6], self.data[14])
}
/// Calculates the timer divsor for the special effect `fx1`.
pub fn timer_divisor1(&self) -> Option<NonZeroU32> {
calculate_timer_divisor(self.data[8], self.data[15])
}
}
fn calculate_timer_divisor(prediv3: u8, div8: u8) -> Option<NonZeroU32> {
let prediv = match prediv3 & 0b11100000 {
0b00000000 => 0,
0b00100000 => 4,
0b01000000 => 10,
0b01100000 => 16,
0b10000000 => 50,
0b10100000 => 64,
0b11000000 => 100,
0b11100000 => 200,
_ => unreachable!()
};
NonZeroU32::new(prediv * div8 as u32)
}
| true |
86bbd839be256d61ba32ce65b3c3af12966b6d65
|
Rust
|
brianloveswords/learn-rust
|
/002: Even Fibonacci numbers/1-first-attempt.rs
|
UTF-8
| 1,053 | 3.953125 | 4 |
[] |
no_license
|
/// For my first attempt, I went at it without really looking up too
/// much. I knew I wanted my `fib` function to be generic, with the
/// logic around figuring out the the sum separate. I also wanted to use
/// a generator, but very quickly figured out that though "yield" is a
/// reserved keyword, it doesn't actually do anything. For some reason,
/// this was the first solution that popped into my head. It's probably
/// strange, and very non-idiomatic, but it worked.
fn fib(pred: |x: int| -> bool) {
let mut previous = 1;
let mut current = 1;
loop {
if !pred(previous) { break }
let tmp = current;
current += previous;
previous = tmp;
}
}
fn main() {
let mut sum = 0;
fib(|i| -> bool {
if i > 4000000 {
// more or less a `break`
return false
}
if i % 2 != 0 {
// more or less `next`
return true
}
println!("adding {}", i);
sum += i;
true
});
println!("sum = {}", sum)
}
| true |
23cf4349123df1836865f41bd82e2af3a4aa8272
|
Rust
|
hzkazmi/Batch6_34_Quarter1
|
/may_03_2020_imran/variable/src/main.rs
|
UTF-8
| 1,350 | 3.890625 | 4 |
[] |
no_license
|
fn main() {
let age = 33; //declare and initialize a variable
println!("welcome in Live Review Class");
//printing value of a variable
println!("The data in age variable is : {}",age);
println!("Hello, world!");
//declare and initialize a tuple
let data = (137816,"Inayat",1500,80.88);
//index 0 1 2 3
//printing one element value of an index on an tuple
println!("Element # 1 {}",data.1);
//printing complete tuple
println!("Complete Tuple {:#?}",data);
//printing complete tuple
println!("Complete Tuple {:?}",data);
//let data = ();
//declare and initialize a array
let age = [22,33,44,55];
// 0 1 2 3
//declare and initialize a array
let names = ["Areeb","Saif","Imran","Zia Khan"];
// 0 1 2 3
//printing one element value of an index on an array
println!("age 1 {}",age[1]);
//printing one element value of an index on an array
println!("Name 1 {}",names[1]);
//printing complete array
println!("{:?}",age);
//printing complete array
println!("{:#?}",names);
//declare and initialize boolean variable
let rain = false;
let summer = true;
//printing boolean variable
println!("Is it raining? {}",rain);
println!("is Today hot? {}",summer);
}
| true |
5129466ed5a539f20ddd39f08dfb726c2b3be23b
|
Rust
|
rschristian/rust-rocket-template
|
/src/db/auth_repository.rs
|
UTF-8
| 988 | 2.796875 | 3 |
[
"MIT"
] |
permissive
|
use crate::db::Conn;
use crate::models::user::{InsertableUser, User};
use crate::schema::users;
use diesel::prelude::*;
use diesel::result::{DatabaseErrorKind, Error};
pub enum UserCreationError {
DuplicatedEmail,
}
impl From<Error> for UserCreationError {
fn from(err: Error) -> UserCreationError {
if let Error::DatabaseError(DatabaseErrorKind::UniqueViolation, info) = &err {
if let Some("unique_email") = info.constraint_name() {
return UserCreationError::DuplicatedEmail;
}
}
panic!("Error creating user: {:?}", err)
}
}
pub fn register(user: InsertableUser, conn: Conn) -> Result<User, UserCreationError> {
diesel::insert_into(users::table)
.values(user)
.get_result::<User>(&*conn)
.map_err(Into::into)
}
pub fn login(email: String, conn: Conn) -> Option<User> {
users::table
.filter(users::email.eq(email))
.get_result::<User>(&*conn)
.ok()
}
| true |
d3f3108830e405d0b74ae898b110eec226fc138c
|
Rust
|
Rodrigodd/gameroy
|
/core/src/gameboy.rs
|
UTF-8
| 16,904 | 2.796875 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"MIT",
"Apache-2.0"
] |
permissive
|
use std::cell::{Cell, RefCell};
use crate::{
disassembler::Trace,
save_state::{LoadStateError, SaveState, SaveStateContext, SaveStateHeader},
};
pub mod cartridge;
pub mod cpu;
pub mod ppu;
pub mod serial_transfer;
pub mod sound_controller;
pub mod timer;
use self::{
cartridge::Cartridge, cpu::Cpu, ppu::Ppu, serial_transfer::Serial,
sound_controller::SoundController, timer::Timer,
};
#[cfg(not(target_arch = "wasm32"))]
type VBlankCallback = Box<dyn FnMut(&mut GameBoy) + Send>;
#[cfg(target_arch = "wasm32")]
type VBlankCallback = Box<dyn FnMut(&mut GameBoy)>;
pub struct GameBoy {
pub trace: RefCell<Trace>,
pub cpu: Cpu,
pub cartridge: Cartridge,
/// C000-DFFF: Work RAM
pub wram: [u8; 0x2000],
/// FF80-FFFE: High RAM
pub hram: [u8; 0x7F],
pub boot_rom: Option<[u8; 0x100]>,
pub boot_rom_active: bool,
pub clock_count: u64,
pub timer: RefCell<Timer>,
pub sound: RefCell<SoundController>,
pub ppu: RefCell<Ppu>,
/// FF00: P1
pub joypad_io: u8,
/// JoyPad state. 0 bit means pressed.
/// From bit 7 to 0, the order is: Start, Select, B, A, Down, Up, Left, Right
pub joypad: u8,
pub serial: RefCell<Serial>,
/// FF0F: Interrupt Flag (IF)
/// - bit 0: VBlank
/// - bit 1: STAT
/// - bit 2: Timer
/// - bit 3: Serial
/// - bit 4: Joypad
pub interrupt_flag: Cell<u8>,
/// FF46: DMA register
pub dma: u8,
/// FFFF: Interrupt Enabled (IE). Same scheme as `interrupt_flag`.
pub interrupt_enabled: u8,
/// This trigger control if in the next interpret the `v_blank` callback will be called.
pub v_blank_trigger: Cell<bool>,
/// A callback that is called after a VBlank. This is called when a vblank interrupt is
/// triggered.
pub v_blank: Option<VBlankCallback>,
/// Used to toggle the next interrupt prediction, to be able to test its correctness.
pub predict_interrupt: bool,
/// Used to toggle the halt optimization, to allow interpreting with more granuallity.
pub halt_optimization: bool,
/// The clock_count when the next interrupt may happen.
pub next_interrupt: Cell<u64>,
/// trace of reads and writes. (kind | ((clock_count & !3) >> 1), address, value), kind: 0=read,1=write
#[cfg(feature = "io_trace")]
pub io_trace: RefCell<Vec<(u8, u16, u8)>>,
}
impl std::fmt::Debug for GameBoy {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
// TODO: derive Debug for fields when the time arrive.
f.debug_struct("GameBoy")
// .field("trace", &self.trace)
.field("cpu", &self.cpu)
// .field("cartridge", &self.cartridge)
.field("wram", &self.wram)
.field("hram", &self.hram)
.field("boot_rom", &self.boot_rom)
.field("boot_rom_active", &self.boot_rom_active)
.field("clock_count", &self.clock_count)
.field("timer", &self.timer)
// .field("sound", &self.sound)
// .field("ppu", &self.ppu)
.field("joypad", &self.joypad)
.field("joypad_io", &self.joypad_io)
// .field("serial_transfer", &self.serial_transfer)
// .field("v_blank", &self.v_blank)
.finish()
}
}
impl Eq for GameBoy {}
impl PartialEq for GameBoy {
fn eq(&self, other: &Self) -> bool {
// self.trace == other.trace &&
self.cpu == other.cpu
&& self.cartridge == other.cartridge
&& self.wram == other.wram
&& self.hram == other.hram
&& self.boot_rom == other.boot_rom
&& self.boot_rom_active == other.boot_rom_active
&& self.clock_count == other.clock_count
&& self.timer == other.timer
&& self.sound == other.sound
&& self.ppu == other.ppu
&& self.joypad_io == other.joypad_io
&& self.joypad == other.joypad
&& self.serial == other.serial
&& self.interrupt_flag == other.interrupt_flag
&& self.interrupt_enabled == other.interrupt_enabled
// && self.v_blank == other.v_blank
}
}
crate::save_state!(GameBoy, self, ctx, data {
SaveStateHeader;
// self.trace;
self.cpu;
self.cartridge;
self.wram;
self.hram;
// self.boot_rom;
self.clock_count;
on_load ctx.clock_count = Some(self.clock_count);
self.timer.borrow_mut();
self.sound.borrow_mut();
self.ppu.borrow_mut();
self.joypad_io;
self.joypad;
self.serial.borrow_mut();
self.interrupt_flag;
self.dma;
self.interrupt_enabled;
bitset [self.boot_rom_active, self.v_blank_trigger];
// self.v_blank;
on_load self.update_next_interrupt();
});
impl GameBoy {
pub fn new(boot_rom: Option<[u8; 0x100]>, cartridge: Cartridge) -> Self {
let mut this = Self {
trace: RefCell::new(Trace::new()),
cpu: Cpu::default(),
cartridge,
wram: [0; 0x2000],
hram: [0; 0x7F],
boot_rom,
boot_rom_active: true,
clock_count: 0,
timer: Timer::new().into(),
sound: RefCell::new(SoundController::default()),
ppu: Ppu::default().into(),
joypad: 0xFF,
joypad_io: 0x00,
serial: Serial::new().into(),
interrupt_flag: 0.into(),
dma: 0xff,
interrupt_enabled: 0,
v_blank_trigger: false.into(),
v_blank: None,
predict_interrupt: true,
halt_optimization: true,
next_interrupt: 0.into(),
#[cfg(feature = "io_trace")]
io_trace: Vec::new().into(),
};
if this.boot_rom.is_none() {
this.reset_after_boot();
}
this
}
/// call the `v_blank` callback
pub fn call_v_blank_callback(&mut self) {
if let Some(mut v_blank) = self.v_blank.take() {
v_blank(self);
self.v_blank = Some(v_blank);
}
}
/// Saves the current state of the GameBoy.
///
/// `timestamp` is the instant that this file is being saved, in number of milliseconds since
/// the UNIX_EPOCH. it may be None if the system could not provide one.
pub fn save_state<W: std::io::Write>(
&self,
timestamp: Option<u64>,
data: &mut W,
) -> Result<(), std::io::Error> {
self.update_all();
let ctx = &mut SaveStateContext::new(timestamp, self.clock_count);
SaveState::save_state(self, ctx, data)
}
pub fn load_state<R: std::io::Read>(&mut self, data: &mut R) -> Result<(), LoadStateError> {
let ctx = &mut SaveStateContext::default();
self.update_all();
SaveState::load_state(self, ctx, data)
}
/// Reset the gameboy to its stating state.
pub fn reset(&mut self) {
if self.boot_rom.is_none() {
self.reset_after_boot();
return;
}
// TODO: Maybe I should reset the cartridge
self.cpu = Cpu::default();
self.wram = [0; 0x2000];
self.hram = [0; 0x7F];
self.boot_rom_active = true;
self.clock_count = 0;
self.timer = Timer::new().into();
self.sound = RefCell::new(SoundController::default());
self.ppu = Ppu::default().into();
self.joypad = 0xFF;
self.joypad_io = 0x00;
self.next_interrupt = 0.into();
self.update_next_interrupt();
}
/// Reset the gameboy to its state after disabling the boot.
pub fn reset_after_boot(&mut self) {
let ctx = &mut SaveStateContext::default();
self.cpu = Cpu {
a: 0x01,
f: cpu::Flags(0xb0),
b: 0x00,
c: 0x13,
d: 0x00,
e: 0xd8,
h: 0x01,
l: 0x4d,
sp: 0xfffe,
pc: 0x0100,
ime: cpu::ImeState::Disabled,
halt_bug: false,
state: cpu::CpuState::Running,
};
self.wram = [0; 0x2000];
self.hram = [0; 0x7F];
self.hram[0x7a..=0x7c].copy_from_slice(&[0x39, 0x01, 0x2e]);
self.boot_rom_active = false;
self.clock_count = 23_440_324;
self.ppu.get_mut().reset_after_boot();
self.joypad = 0xFF;
self.joypad_io = 0xCF;
self.serial.get_mut().reset();
self.timer = Timer::after_boot(self.clock_count).into();
self.interrupt_flag = 1.into();
self.sound
.get_mut()
.load_state(ctx, &mut &include_bytes!("../after_boot/sound.sav")[..])
.unwrap();
self.next_interrupt = 0.into();
self.update_next_interrupt();
}
pub fn read(&self, mut address: u16) -> u8 {
if self.boot_rom_active && address < 0x100 {
let boot_rom = self
.boot_rom
.expect("the boot rom is only actived when there is one");
return boot_rom[address as usize];
}
if (0xE000..=0xFDFF).contains(&address) {
address -= 0x2000;
}
match address {
// Cartridge ROM
0x0000..=0x7FFF => self.cartridge.read(address),
// Video RAM
0x8000..=0x9FFF => Ppu::read_vram(self, address),
// Cartridge RAM
0xA000..=0xBFFF => self.cartridge.read(address),
// Work RAM
0xC000..=0xDFFF => self.wram[address as usize - 0xC000],
// ECHO RAM
0xE000..=0xFDFF => unreachable!(),
// Sprite Attribute table
0xFE00..=0xFE9F => Ppu::read_oam(self, address),
// Not Usable
0xFEA0..=0xFEFF => 0xff,
// I/O registers and Hight RAM
0xFF00..=0xFFFF => self.read_io(address as u8),
}
}
pub fn write(&mut self, mut address: u16, value: u8) {
if (0xE000..=0xFDFF).contains(&address) {
address -= 0x2000;
}
// When writing to the ppu, the ppu will already be updated, but with a special timing.
let will_write_ppu =
(0xff40..=0xff45).contains(&address) || (0xff47..=0xff4b).contains(&address);
if !will_write_ppu && self.ppu.get_mut().dma_running && self.dma as u16 == address >> 8 {
self.update_ppu();
}
match address {
// Cartridge ROM
0x0000..=0x7FFF => self.cartridge.write(address, value),
// Video RAM
0x8000..=0x9FFF => Ppu::write_vram(self, address, value),
// Cartridge RAM
0xA000..=0xBFFF => self.cartridge.write(address, value),
// Work RAM
0xC000..=0xDFFF => self.wram[address as usize - 0xC000] = value,
// ECHO RAM
0xE000..=0xFDFF => unreachable!(),
// Sprite Attribute table
0xFE00..=0xFE9F => Ppu::write_oam(self, address, value),
// Not Usable
0xFEA0..=0xFEFF => {}
// I/O registers and High RAM
0xFF00..=0xFFFF => self.write_io(address as u8, value),
}
}
/// Advance the clock by 'count' cycles
pub fn tick(&mut self, count: u64) {
self.clock_count += count;
}
pub fn update_next_interrupt(&self) {
if !self.predict_interrupt {
self.next_interrupt.set(self.clock_count);
return;
}
self.next_interrupt.set(
self.ppu
.borrow()
.next_interrupt
.min(self.timer.borrow().next_interrupt)
.min(self.serial.borrow().next_interrupt),
);
// If the interrupt_enabled was modified in the last instructions, the next interrupt may
// happen immediately.
let interrupts: u8 = self.interrupt_flag.get() & self.interrupt_enabled;
if interrupts != 0 {
self.next_interrupt
.set(self.next_interrupt.get().min(self.clock_count));
}
}
pub fn update_interrupt(&self) {
if !self.predict_interrupt {
self.update_all();
return;
}
if self.ppu.borrow().next_interrupt < self.clock_count + 4 {
self.update_ppu();
}
if self.timer.borrow().next_interrupt < self.clock_count + 4 {
self.update_timer();
}
if self.serial.borrow().next_interrupt < self.clock_count + 4 {
self.update_serial();
}
self.update_next_interrupt();
}
pub fn update_all(&self) {
self.update_ppu();
self.update_timer();
self.update_serial();
}
fn update_ppu(&self) {
let (v_blank_interrupt, stat_interrupt) = Ppu::update(self);
if stat_interrupt {
self.interrupt_flag
.set(self.interrupt_flag.get() | (1 << 1));
}
if v_blank_interrupt {
self.interrupt_flag
.set(self.interrupt_flag.get() | (1 << 0));
self.v_blank_trigger.set(true);
}
self.update_next_interrupt();
}
fn update_timer(&self) {
if self.timer.borrow_mut().update(self.clock_count) {
self.interrupt_flag
.set(self.interrupt_flag.get() | (1 << 2));
}
self.update_next_interrupt();
}
fn update_serial(&self) {
if self.serial.borrow_mut().update(self.clock_count) {
// interrupt
self.interrupt_flag
.set(self.interrupt_flag.get() | (1 << 3));
}
self.update_next_interrupt();
}
pub fn read16(&self, address: u16) -> u16 {
u16::from_le_bytes([self.read(address), self.read(address.wrapping_add(1))])
}
fn write_io(&mut self, address: u8, value: u8) {
match address {
0x00 => self.joypad_io = 0b1100_1111 | (value & 0x30), // JOYPAD
0x01..=0x02 => Serial::write(self, address, value),
0x03 => {}
0x04..=0x07 => {
self.update_timer();
self.timer.get_mut().write(address, value);
self.update_next_interrupt();
}
0x08..=0x0e => {}
0x0f => {
*self.interrupt_flag.get_mut() = value & 0x1f;
self.update_interrupt();
}
0x10..=0x14 | 0x16..=0x1e | 0x20..=0x26 | 0x30..=0x3f => {
self.sound.get_mut().write(self.clock_count, address, value)
}
0x15 => {}
0x1f => {}
0x27..=0x2f => {}
0x40..=0x45 => Ppu::write(self, address, value),
0x46 => {
// DMA Transfer
Ppu::start_dma(self, value);
}
0x47..=0x4b => Ppu::write(self, address, value),
0x4c..=0x4f => {}
0x50 => {
if self.boot_rom_active && value & 0b1 != 0 {
self.boot_rom_active = false;
self.cpu.pc = 0x100;
}
}
0x51..=0x7f => {}
0x80..=0xfe => self.hram[address as usize - 0x80] = value,
0xff => {
self.interrupt_enabled = value;
self.update_next_interrupt();
}
}
}
fn read_io(&self, address: u8) -> u8 {
match address {
0x00 => {
// JOYPAD
let v = self.joypad_io & 0x30;
let mut r = v | 0b1100_0000;
if v & 0x10 != 0 {
r |= (self.joypad >> 4) & 0x0F;
}
if v & 0x20 != 0 {
r |= self.joypad & 0x0F;
}
if v == 0 {
r |= 0x0F;
}
r
}
0x01..=0x02 => Serial::read(self, address),
0x03 => 0xff,
0x04..=0x07 => {
self.update_timer();
self.timer.borrow().read(address)
}
0x08..=0x0e => 0xff,
0x0f => {
self.update_interrupt();
self.interrupt_flag.get() | 0xE0
}
0x10..=0x14 | 0x16..=0x1e | 0x20..=0x26 | 0x30..=0x3f => {
self.sound.borrow_mut().read(self.clock_count, address)
}
0x15 => 0xff,
0x1f => 0xff,
0x27..=0x2f => 0xff,
0x40..=0x45 => Ppu::read(self, address),
0x46 => self.dma,
0x47..=0x4b => Ppu::read(self, address),
0x4c => 0xff,
0x4d => 0xff,
0x4e..=0x4f => 0xff,
0x50 => 0xff,
0x51..=0x7F => 0xff,
0x80..=0xfe => self.hram[address as usize - 0x80],
0xff => self.interrupt_enabled,
}
}
}
| true |
827c929b014d9b77789e911b5e70edeb0e52a04a
|
Rust
|
southpawgeek/perlweeklychallenge-club
|
/challenge-109/laurent-rosenfeld/rust/ch-1.rs
|
UTF-8
| 259 | 3.09375 | 3 |
[] |
no_license
|
fn chowla(n : i32) -> i32 {
let mut sum = 0;
for i in 2..=n/2 {
if n % i == 0 {
sum += i
}
}
return sum
}
fn main() {
for n in 1..20 {
print!("{}, ", chowla(n));
}
println!("{} ", chowla(20));
}
| true |
5754a13a5a68fce1bfc849da09d53211e1b5b40b
|
Rust
|
EmbarkStudios/symbolicator
|
/src/utils/futures.rs
|
UTF-8
| 3,288 | 3.171875 | 3 |
[
"MIT"
] |
permissive
|
use std::future::Future;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use futures::channel::oneshot;
use futures::{FutureExt, TryFutureExt};
use tokio::runtime::Runtime as TokioRuntime;
static IS_TEST: AtomicBool = AtomicBool::new(false);
/// Enables test mode of all thread pools and remote threads.
///
/// In this mode, futures are not spawned into threads, but instead run on the current thread. This
/// is useful to ensure deterministic test execution, and also allows to capture console output from
/// spawned tasks.
#[cfg(test)]
pub fn enable_test_mode() {
IS_TEST.store(true, Ordering::Relaxed);
}
/// Error returned from a `SpawnHandle` when the thread pool restarts.
pub use oneshot::Canceled;
/// Handle returned from `ThreadPool::spawn_handle`.
///
/// This handle is a future representing the completion of a different future spawned on to the
/// thread pool. Created through the `ThreadPool::spawn_handle` function this handle will resolve
/// when the future provided resolves on the thread pool. If the remote thread restarts due to
/// panics, `SpawnError::Canceled` is returned.
pub use oneshot::Receiver as SpawnHandle;
/// Work-stealing based thread pool for executing futures.
#[derive(Clone, Debug)]
pub struct ThreadPool {
inner: Option<Arc<TokioRuntime>>,
}
impl ThreadPool {
/// Create a new `ThreadPool`.
///
/// Since we create a CPU-heavy and an IO-heavy pool we reduce the
/// number of threads used per pool so that the pools are less
/// likely to starve each other.
pub fn new() -> Self {
let inner = if cfg!(test) && IS_TEST.load(Ordering::Relaxed) {
None
} else {
let runtime = tokio::runtime::Builder::new().build().unwrap();
Some(Arc::new(runtime))
};
ThreadPool { inner }
}
/// Spawn a future on to the thread pool, return a future representing the produced value.
///
/// The `SpawnHandle` returned is a future that is a proxy for future itself. When future
/// completes on this thread pool then the SpawnHandle will itself be resolved.
pub fn spawn_handle<F>(&self, future: F) -> SpawnHandle<F::Output>
where
F: Future + Send + 'static,
F::Output: Send + 'static,
{
let (sender, receiver) = oneshot::channel();
let spawned = async move {
sender.send(future.await).ok();
Ok(())
};
let compat = spawned.boxed().compat();
match self.inner {
Some(ref runtime) => runtime.executor().spawn(compat),
None => actix::spawn(compat),
}
receiver
}
}
/// Execute a callback on dropping of the container type.
///
/// The callback must not panic under any circumstance. Since it is called while dropping an item,
/// this might result in aborting program execution.
pub struct CallOnDrop {
f: Option<Box<dyn FnOnce() + Send + 'static>>,
}
impl CallOnDrop {
/// Creates a new `CallOnDrop`.
pub fn new<F: FnOnce() + Send + 'static>(f: F) -> CallOnDrop {
CallOnDrop {
f: Some(Box::new(f)),
}
}
}
impl Drop for CallOnDrop {
fn drop(&mut self) {
if let Some(f) = self.f.take() {
f();
}
}
}
| true |
f7bb7413f18501f2c00b4692abd2796dba73a280
|
Rust
|
awsdocs/aws-doc-sdk-examples
|
/rust_dev_preview/examples/lambda/src/bin/list-all-function-runtimes.rs
|
UTF-8
| 3,198 | 2.75 | 3 |
[
"Apache-2.0",
"MIT"
] |
permissive
|
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#![allow(clippy::result_large_err)]
use aws_sdk_lambda::Error;
use clap::Parser;
use lambda_code_examples::{make_client, make_config, Opt as BaseOpt};
#[derive(Debug, Parser)]
struct Opt {
#[structopt(flatten)]
base: BaseOpt,
/// Just show runtimes for indicated language.
/// dotnet, go, node, java, etc.
#[structopt(short, long)]
language: Option<String>,
}
/// Lists the ARNs and runtimes of all Lambda functions in all Regions.
// snippet-start:[lambda.rust.list-all-function-runtimes]
async fn show_lambdas(language: &str, region: &str, verbose: bool) -> Result<(), Error> {
let language = language.to_ascii_lowercase();
let client = make_client(BaseOpt {
region: Some(region.to_string()),
verbose: false,
})
.await;
let resp = client.list_functions().send().await?;
let resp_functions = resp.functions.unwrap_or_default();
let total_functions = resp_functions.len();
let functions = resp_functions
.iter()
.map(|func| {
(
func,
func.runtime()
.map(|rt| String::from(rt.as_ref()))
.unwrap_or_else(|| String::from("Unknown")),
)
})
.filter(|(_, runtime)| {
language.is_empty() || runtime.to_ascii_lowercase().contains(&language)
});
for (func, rt_str) in functions {
println!(" ARN: {}", func.function_arn().unwrap());
println!(" Runtime: {}", rt_str);
println!();
}
let num_functions = resp_functions.len();
if num_functions > 0 || verbose {
println!(
"Found {} function(s) (out of {}) in {} region.",
num_functions, total_functions, region,
);
println!();
}
Ok(())
}
// snippet-end:[lambda.rust.list-all-function-runtimes]
/// Lists the ARNs and runtimes of your Lambda functions in all available regions.
/// # Arguments
///
/// * `[-r REGION]` - The Region in which the client is created.
/// If not supplied, uses the value of the **AWS_REGION** environment variable.
/// If the environment variable is not set, defaults to **us-west-2**.
/// * `[-v]` - Whether to display additional information.
#[tokio::main]
async fn main() -> Result<(), Error> {
tracing_subscriber::fmt::init();
let Opt { language, base } = Opt::parse();
let language = language.as_deref().unwrap_or_default();
let verbose = base.verbose;
let sdk_config = make_config(base).await;
let ec2_client = aws_sdk_ec2::Client::new(&sdk_config);
match ec2_client.describe_regions().send().await {
Ok(resp) => {
for region in resp.regions.unwrap_or_default() {
if let Some(region) = region.region_name() {
show_lambdas(language, region, verbose)
.await
.unwrap_or_else(|err| eprintln!("{:?}", err));
}
}
}
Err(err) => eprintln!("Failed to describe ec2 regions: {}", err),
}
Ok(())
}
| true |
0151395427588566c951494d39499f2651d1b4c9
|
Rust
|
Fergus-Molloy/Advent_of_Code_2020
|
/day_5/src/main.rs
|
UTF-8
| 1,845 | 3.484375 | 3 |
[] |
no_license
|
use std::fs;
fn main() {
let contents = fs::read_to_string("input").expect("unable to read file");
let lines: Vec<&str> = contents.lines().collect();
println!("Part One: {}", part_one(&lines));
println!("Part Two: {}", part_two(&lines));
}
pub fn part_one(lines: &Vec<&str>) -> u32 {
let mut big = 0;
for line in lines.iter() {
let mut row: u8 = 127;
let mut iter = line.chars();
for x in (0..7).rev() {
if iter.next().unwrap() == 'F' {
row &= 127 - (2 as u8).pow(x);
}
}
let mut col: u8 = 7;
for x in (0..3).rev() {
if iter.next().unwrap() == 'L' {
col &= 7 - (2 as u8).pow(x);
}
}
let ID: u32 = (row as u32 * 8) + col as u32;
if ID > big {
big = ID;
}
}
big
}
pub fn part_two(lines: &Vec<&str>) -> u32 {
let mut plane: [[bool; 8]; 128] = [[false; 8]; 128];
for line in lines.iter() {
let mut row: usize = 127;
let mut iter = line.chars();
for x in (0..7).rev() {
if iter.next().unwrap() == 'F' {
row &= 127 - (2 as usize).pow(x);
}
}
let mut col: usize = 7;
for x in (0..3).rev() {
if iter.next().unwrap() == 'L' {
col &= 7 - (2 as usize).pow(x);
}
}
plane[row][col] = true;
}
//for finding out how many rows to ignore
//for x in plane.iter() {
// println!("{:?}", x)
//}
// should have a map of filled seats i know mine
// is in the middle somewhere
for x in 4..120 {
//can't be in first or last row
for y in 0..7 {
if !plane[x][y] {
return ((x * 8) + y) as u32;
}
}
}
0
}
| true |
10f714c3fd4446a0eccdf2ae448d34aaa2875894
|
Rust
|
songlinshu/winsafe
|
/src/gui/very_unsafe_cell.rs
|
UTF-8
| 792 | 3.265625 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
use std::cell::UnsafeCell;
use std::ops::Deref;
/// Syntactic sugar to `UnsafeCell`.
///
/// **Extremely** unsafe, intended only to provide less verbose internal
/// mutability within the `gui` module.
pub(crate) struct VeryUnsafeCell<T>(UnsafeCell<T>);
unsafe impl<T> Send for VeryUnsafeCell<T> {}
unsafe impl<T> Sync for VeryUnsafeCell<T> {}
impl<T> Deref for VeryUnsafeCell<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
unsafe { &*self.0.get() } // immutable reference
}
}
impl<T> VeryUnsafeCell<T> {
/// Instantiates a new object.
pub fn new(obj: T) -> VeryUnsafeCell<T> {
Self(UnsafeCell::new(obj))
}
/// Returns a mutable reference to the underlying object.
pub fn as_mut(&self) -> &mut T {
unsafe { &mut *self.0.get() }
}
}
| true |
197ab54006bdbfc061cbcb3d9dd260ff854d7b0e
|
Rust
|
wasmup/insert-per-second
|
/rust-byte1024-Uniform/src/main.rs
|
UTF-8
| 807 | 3.09375 | 3 |
[] |
no_license
|
use rand::distributions::{Distribution, Uniform};
use std::collections::HashMap;
use std::time::Instant;
fn main() {
const N: usize = 1024;
const MAX: usize = N * N;
let mut m = HashMap::with_capacity(MAX);
let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".as_bytes();
let between = Uniform::from(0..letters.len());
let mut buf = [0_u8; N];
let now = Instant::now();
for _ in 0..MAX {
let mut rng = rand::thread_rng();
for i in 0..N {
buf[i] = letters[between.sample(&mut rng)];
}
m.insert(buf.clone(), buf.clone());
}
let s = now.elapsed().as_secs();
println!("{:?}\nlen={}, ", m.values().next(), m.len());
println!("{}s, {:.0} insert/s", s, MAX as f64 / s as f64); // 9s, 116_508 insert/s
}
| true |
3057633f186b19691fa1dc4923084035d9b2b4e7
|
Rust
|
casey/RustRoguelike
|
/roguelike_core/src/messaging.rs
|
UTF-8
| 6,990 | 2.90625 | 3 |
[] |
no_license
|
use std::collections::VecDeque;
use serde::{Serialize, Deserialize};
use crate::types::*;
use crate::map::*;
use crate::movement::{Movement, MoveType, MoveMode, Action};
use crate::ai::Behavior;
pub struct MsgLog {
pub messages: VecDeque<Msg>,
pub turn_messages: VecDeque<Msg>,
}
impl MsgLog {
pub fn new() -> MsgLog {
return MsgLog {
messages: VecDeque::new(),
turn_messages: VecDeque::new(),
};
}
pub fn pop(&mut self) -> Option<Msg> {
return self.messages.pop_front();
}
pub fn log(&mut self, msg: Msg) {
self.messages.push_back(msg);
self.turn_messages.push_back(msg);
}
pub fn log_front(&mut self, msg: Msg) {
self.messages.push_front(msg);
self.turn_messages.push_front(msg);
}
pub fn clear(&mut self) {
self.messages.clear();
self.turn_messages.clear();
}
}
#[derive(Copy, Clone, PartialEq, Debug, Deserialize, Serialize)]
pub enum Msg {
Pass(),
Crushed(EntityId, Pos), // object that did the crushing, position
Sound(EntityId, Pos, usize, bool), // object causing sound, location, radius, whether animation will play
SoundTrapTriggered(EntityId, EntityId), // trap, entity
SpikeTrapTriggered(EntityId, EntityId), // trap, entity
PlayerDeath,
PickedUp(EntityId, EntityId), // entity, item id
ItemThrow(EntityId, EntityId, Pos, Pos), // thrower, stone id, start, end
Attack(EntityId, EntityId, Hp), // attacker, attacked, hp lost
Killed(EntityId, EntityId, Hp), // attacker, attacked, hp lost
Pushed(EntityId, EntityId, Pos), // attacker, attacked, change in position
Moved(EntityId, Movement, Pos),
JumpWall(EntityId, Pos, Pos), // current pos, new pos
WallKick(EntityId, Pos),
StateChange(EntityId, Behavior),
Collided(EntityId, Pos),
Yell(EntityId, Pos),
GameState(GameState),
MoveMode(MoveMode),
TriedRunWithShield,
SpawnedObject(EntityId, EntityType, Pos, EntityName),
SwordSwing(EntityId, Pos), // entity, position swung at
HammerSwing(EntityId, Pos), // entity, position swung at
HammerHitEntity(EntityId, EntityId), // entity, hit entity
HammerHitWall(EntityId, Blocked),
ChangeLevel(),
Action(EntityId, Action),
}
impl Msg {
pub fn msg_line(&self, data: &GameData) -> String {
match self {
Msg::Crushed(_obj_id, _pos) => {
return "An object has been crushed".to_string();
}
Msg::Pass() => {
return "Player passed their turn".to_string();
}
Msg::SoundTrapTriggered(_trap, _entity) => {
return "Sound trap triggered".to_string();
}
Msg::SpikeTrapTriggered(_trap, _entity) => {
return "Spike trap triggered".to_string();
}
Msg::PlayerDeath => {
return "Player died!".to_string();
}
Msg::PickedUp(entity, item) => {
return format!("{:?} picked up a {:?}",
data.entities.name[entity].clone(),
data.entities.name[item].clone());
}
Msg::ItemThrow(_thrower, _item, _start, _end) => {
return "Item throw".to_string();
}
Msg::Attack(attacker, attacked, damage) => {
return format!("{:?} attacked {:?} for {} damage",
data.entities.name[attacker],
data.entities.name[attacked],
damage);
}
Msg::Killed(attacker, attacked, _damage) => {
return format!("{:?} killed {:?}", data.entities.name[attacker], data.entities.name[attacked]);
}
Msg::Pushed(attacker, attacked, _delta_pos) => {
return format!("{:?} pushed {:?}", data.entities.name[attacker], data.entities.name[attacked]);
}
Msg::Moved(entity, movement, pos) => {
if let MoveType::Pass = movement.typ {
return format!("{:?} passed their turn", data.entities.name[entity]);
} else {
return format!("{:?} moved to {}", data.entities.name[entity], pos);
}
}
Msg::JumpWall(_entity, _start, _end) => {
return "Jumped a wall".to_string();
}
Msg::WallKick(_entity, _pos) => {
return "Did a wallkick".to_string();
}
Msg::StateChange(_entity, behavior) => {
return format!("Changed state to {:?}", *behavior);
}
Msg::Yell(entity, _pos) => {
return format!("{:?} yelled", data.entities.name[entity]);
}
Msg::Collided(_entity, _pos) => {
return "Collided".to_string();
}
Msg::GameState(game_state) => {
match game_state {
GameState::Inventory => {
return "Opened Inventory".to_string();
}
GameState::Playing => {
return "".to_string();
}
GameState::Selection => {
return "Selecting a location".to_string();
}
_ => {
panic!();
}
}
}
Msg::MoveMode(move_mode) => {
match move_mode {
MoveMode::Sneak => {
return "Sneaking".to_string();
}
MoveMode::Walk => {
return "Walking".to_string();
}
MoveMode::Run => {
return "Running".to_string();
}
}
}
Msg::TriedRunWithShield => {
return "Can't run with shield!".to_string();
}
Msg::SwordSwing(entity, _pos) => {
return format!("{:?} swung their sword", data.entities.name[entity]);
}
Msg::HammerSwing(entity, _pos) => {
return format!("{:?} swung their hammer", data.entities.name[entity]);
}
Msg::HammerHitEntity(entity, hit_entity) => {
let entity_name = &data.entities.name[entity];
let hit_entity_name = &data.entities.name[hit_entity];
return format!("{:?} hit {:?} with their hammer", entity_name, hit_entity_name);
}
Msg::HammerHitWall(entity, _blocked) => {
return format!("{:?} hit a wall with their hammer", data.entities.name[entity]);
}
_ => {
return "".to_string();
}
}
}
}
| true |
6c6b3b641a3c0e8959dc027c5e59549accb5f48d
|
Rust
|
ganmacs/playground
|
/rust/tbin/src/gen.rs
|
UTF-8
| 408 | 3.5 | 4 |
[] |
no_license
|
use std::fmt::Debug;
trait HaveArea {
fn area(&self) -> f64;
}
#[derive(Debug)]
struct Foo {
length: f64,
width: f64,
}
impl HaveArea for Foo {
fn area(&self) -> f64 { self.length * self.width }
}
fn print_debug<T: Debug>(f: &T) {
println!("{:?}", f);
}
fn main() {
let f = Foo { length: 100.0, width: 50.0 };
// let b = Bar { length: 10, width: 5 };
print_debug(&f);
}
| true |
9e49d25a920ebb7f1202bf7bc9546741e815a0cd
|
Rust
|
tempbottle/rhai
|
/src/fn_register.rs
|
UTF-8
| 4,105 | 2.640625 | 3 |
[] |
no_license
|
use std::any::TypeId;
use crate::any::{Any, Dynamic};
use crate::engine::{Engine, EvalAltResult, FnCallArgs};
pub trait RegisterFn<FN, ARGS, RET> {
fn register_fn(&mut self, name: &str, f: FN);
}
pub trait RegisterDynamicFn<FN, ARGS> {
fn register_dynamic_fn(&mut self, name: &str, f: FN);
}
pub struct Ref<A>(A);
pub struct Mut<A>(A);
macro_rules! count_args {
() => {0usize};
($head:ident $($tail:ident)*) => {1usize + count_args!($($tail)*)};
}
macro_rules! def_register {
() => {
def_register!(imp);
};
(imp $($par:ident => $mark:ty => $param:ty => $clone:expr),*) => {
impl<
$($par: Any + Clone,)*
FN: Fn($($param),*) -> RET + 'static,
RET: Any
> RegisterFn<FN, ($($mark,)*), RET> for Engine
{
fn register_fn(&mut self, name: &str, f: FN) {
let fun = move |mut args: FnCallArgs| {
// Check for length at the beginning to avoid
// per-element bound checks.
if args.len() != count_args!($($par)*) {
return Err(EvalAltResult::ErrorFunctionArgMismatch);
}
#[allow(unused_variables, unused_mut)]
let mut drain = args.drain(..);
$(
// Downcast every element, return in case of a type mismatch
let $par = ((*drain.next().unwrap()).downcast_mut() as Option<&mut $par>)
.ok_or(EvalAltResult::ErrorFunctionArgMismatch)?;
)*
// Call the user-supplied function using ($clone) to
// potentially clone the value, otherwise pass the reference.
let r = f($(($clone)($par)),*);
Ok(Box::new(r) as Dynamic)
};
self.register_fn_raw(name.to_owned(), Some(vec![$(TypeId::of::<$par>()),*]), Box::new(fun));
}
}
impl<
$($par: Any + Clone,)*
FN: Fn($($param),*) -> Dynamic + 'static,
> RegisterDynamicFn<FN, ($($mark,)*)> for Engine
{
fn register_dynamic_fn(&mut self, name: &str, f: FN) {
let fun = move |mut args: FnCallArgs| {
// Check for length at the beginning to avoid
// per-element bound checks.
if args.len() != count_args!($($par)*) {
return Err(EvalAltResult::ErrorFunctionArgMismatch);
}
#[allow(unused_variables, unused_mut)]
let mut drain = args.drain(..);
$(
// Downcast every element, return in case of a type mismatch
let $par = ((*drain.next().unwrap()).downcast_mut() as Option<&mut $par>)
.ok_or(EvalAltResult::ErrorFunctionArgMismatch)?;
)*
// Call the user-supplied function using ($clone) to
// potentially clone the value, otherwise pass the reference.
Ok(f($(($clone)($par)),*))
};
self.register_fn_raw(name.to_owned(), Some(vec![$(TypeId::of::<$par>()),*]), Box::new(fun));
}
}
//def_register!(imp_pop $($par => $mark => $param),*);
};
($p0:ident $(, $p:ident)*) => {
def_register!(imp $p0 => $p0 => $p0 => Clone::clone $(, $p => $p => $p => Clone::clone)*);
def_register!(imp $p0 => Ref<$p0> => &$p0 => |x| { x } $(, $p => $p => $p => Clone::clone)*);
def_register!(imp $p0 => Mut<$p0> => &mut $p0 => |x| { x } $(, $p => $p => $p => Clone::clone)*);
def_register!($($p),*);
};
// (imp_pop) => {};
// (imp_pop $head:ident => $head_mark:ty => $head_param:ty $(,$tail:ident => $tail_mark:ty => $tp:ty)*) => {
// def_register!(imp $($tail => $tail_mark => $tp),*);
// };
}
#[cfg_attr(rustfmt, rustfmt_skip)]
def_register!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S);
| true |
f8cd784cdefa8f6959814db86c372e4405a3e7d3
|
Rust
|
thomasantony/bobbin-sdk
|
/mcu/bobbin-kinetis/mke02z4/src/spi.rs
|
UTF-8
| 23,701 | 2.703125 | 3 |
[
"MIT",
"Apache-2.0"
] |
permissive
|
::bobbin_mcu::periph!( SPI0, Spi0, SPI0_PERIPH, SpiPeriph, SPI0_OWNED, SPI0_REF_COUNT, 0x40076000, 0x00, 0x14);
::bobbin_mcu::periph!( SPI1, Spi1, SPI1_PERIPH, SpiPeriph, SPI1_OWNED, SPI1_REF_COUNT, 0x40077000, 0x01, 0x15);
#[derive(Clone, Copy, PartialEq, Eq)]
#[doc="SPI Peripheral"]
pub struct SpiPeriph(pub usize);
impl SpiPeriph {
#[doc="Get the C1 Register."]
#[inline] pub fn c1_reg(&self) -> ::bobbin_mcu::register::Register<C1> {
::bobbin_mcu::register::Register::new(self.0 as *mut C1, 0x0)
}
#[doc="Get the *mut pointer for the C1 register."]
#[inline] pub fn c1_mut(&self) -> *mut C1 {
self.c1_reg().ptr()
}
#[doc="Get the *const pointer for the C1 register."]
#[inline] pub fn c1_ptr(&self) -> *const C1 {
self.c1_reg().ptr()
}
#[doc="Read the C1 register."]
#[inline] pub fn c1(&self) -> C1 {
self.c1_reg().read()
}
#[doc="Write the C1 register."]
#[inline] pub fn write_c1(&self, value: C1) -> &Self {
self.c1_reg().write(value);
self
}
#[doc="Set the C1 register."]
#[inline] pub fn set_c1<F: FnOnce(C1) -> C1>(&self, f: F) -> &Self {
self.c1_reg().set(f);
self
}
#[doc="Modify the C1 register."]
#[inline] pub fn with_c1<F: FnOnce(C1) -> C1>(&self, f: F) -> &Self {
self.c1_reg().with(f);
self
}
#[doc="Get the C2 Register."]
#[inline] pub fn c2_reg(&self) -> ::bobbin_mcu::register::Register<C2> {
::bobbin_mcu::register::Register::new(self.0 as *mut C2, 0x1)
}
#[doc="Get the *mut pointer for the C2 register."]
#[inline] pub fn c2_mut(&self) -> *mut C2 {
self.c2_reg().ptr()
}
#[doc="Get the *const pointer for the C2 register."]
#[inline] pub fn c2_ptr(&self) -> *const C2 {
self.c2_reg().ptr()
}
#[doc="Read the C2 register."]
#[inline] pub fn c2(&self) -> C2 {
self.c2_reg().read()
}
#[doc="Write the C2 register."]
#[inline] pub fn write_c2(&self, value: C2) -> &Self {
self.c2_reg().write(value);
self
}
#[doc="Set the C2 register."]
#[inline] pub fn set_c2<F: FnOnce(C2) -> C2>(&self, f: F) -> &Self {
self.c2_reg().set(f);
self
}
#[doc="Modify the C2 register."]
#[inline] pub fn with_c2<F: FnOnce(C2) -> C2>(&self, f: F) -> &Self {
self.c2_reg().with(f);
self
}
#[doc="Get the BR Register."]
#[inline] pub fn br_reg(&self) -> ::bobbin_mcu::register::Register<Br> {
::bobbin_mcu::register::Register::new(self.0 as *mut Br, 0x2)
}
#[doc="Get the *mut pointer for the BR register."]
#[inline] pub fn br_mut(&self) -> *mut Br {
self.br_reg().ptr()
}
#[doc="Get the *const pointer for the BR register."]
#[inline] pub fn br_ptr(&self) -> *const Br {
self.br_reg().ptr()
}
#[doc="Read the BR register."]
#[inline] pub fn br(&self) -> Br {
self.br_reg().read()
}
#[doc="Write the BR register."]
#[inline] pub fn write_br(&self, value: Br) -> &Self {
self.br_reg().write(value);
self
}
#[doc="Set the BR register."]
#[inline] pub fn set_br<F: FnOnce(Br) -> Br>(&self, f: F) -> &Self {
self.br_reg().set(f);
self
}
#[doc="Modify the BR register."]
#[inline] pub fn with_br<F: FnOnce(Br) -> Br>(&self, f: F) -> &Self {
self.br_reg().with(f);
self
}
#[doc="Get the S Register."]
#[inline] pub fn s_reg(&self) -> ::bobbin_mcu::register::Register<S> {
::bobbin_mcu::register::Register::new(self.0 as *mut S, 0x3)
}
#[doc="Get the *mut pointer for the S register."]
#[inline] pub fn s_mut(&self) -> *mut S {
self.s_reg().ptr()
}
#[doc="Get the *const pointer for the S register."]
#[inline] pub fn s_ptr(&self) -> *const S {
self.s_reg().ptr()
}
#[doc="Read the S register."]
#[inline] pub fn s(&self) -> S {
self.s_reg().read()
}
#[doc="Write the S register."]
#[inline] pub fn write_s(&self, value: S) -> &Self {
self.s_reg().write(value);
self
}
#[doc="Set the S register."]
#[inline] pub fn set_s<F: FnOnce(S) -> S>(&self, f: F) -> &Self {
self.s_reg().set(f);
self
}
#[doc="Modify the S register."]
#[inline] pub fn with_s<F: FnOnce(S) -> S>(&self, f: F) -> &Self {
self.s_reg().with(f);
self
}
#[doc="Get the D Register."]
#[inline] pub fn d_reg(&self) -> ::bobbin_mcu::register::Register<D> {
::bobbin_mcu::register::Register::new(self.0 as *mut D, 0x5)
}
#[doc="Get the *mut pointer for the D register."]
#[inline] pub fn d_mut(&self) -> *mut D {
self.d_reg().ptr()
}
#[doc="Get the *const pointer for the D register."]
#[inline] pub fn d_ptr(&self) -> *const D {
self.d_reg().ptr()
}
#[doc="Read the D register."]
#[inline] pub fn d(&self) -> D {
self.d_reg().read()
}
#[doc="Write the D register."]
#[inline] pub fn write_d(&self, value: D) -> &Self {
self.d_reg().write(value);
self
}
#[doc="Set the D register."]
#[inline] pub fn set_d<F: FnOnce(D) -> D>(&self, f: F) -> &Self {
self.d_reg().set(f);
self
}
#[doc="Modify the D register."]
#[inline] pub fn with_d<F: FnOnce(D) -> D>(&self, f: F) -> &Self {
self.d_reg().with(f);
self
}
#[doc="Get the M Register."]
#[inline] pub fn m_reg(&self) -> ::bobbin_mcu::register::Register<M> {
::bobbin_mcu::register::Register::new(self.0 as *mut M, 0x7)
}
#[doc="Get the *mut pointer for the M register."]
#[inline] pub fn m_mut(&self) -> *mut M {
self.m_reg().ptr()
}
#[doc="Get the *const pointer for the M register."]
#[inline] pub fn m_ptr(&self) -> *const M {
self.m_reg().ptr()
}
#[doc="Read the M register."]
#[inline] pub fn m(&self) -> M {
self.m_reg().read()
}
#[doc="Write the M register."]
#[inline] pub fn write_m(&self, value: M) -> &Self {
self.m_reg().write(value);
self
}
#[doc="Set the M register."]
#[inline] pub fn set_m<F: FnOnce(M) -> M>(&self, f: F) -> &Self {
self.m_reg().set(f);
self
}
#[doc="Modify the M register."]
#[inline] pub fn with_m<F: FnOnce(M) -> M>(&self, f: F) -> &Self {
self.m_reg().with(f);
self
}
}
#[doc="SPI Control Register 1"]
#[derive(Default, Clone, Copy, PartialEq, Eq)]
pub struct C1(pub u8);
impl C1 {
#[doc="LSB First (shifter direction)"]
#[inline] pub fn lsbfe(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 0) & 0x1) as u8) } // [0]
}
#[doc="Returns true if LSBFE != 0"]
#[inline] pub fn test_lsbfe(&self) -> bool {
self.lsbfe() != 0
}
#[doc="Sets the LSBFE field."]
#[inline] pub fn set_lsbfe<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u8 = value.into();
self.0 &= !(0x1 << 0);
self.0 |= value << 0;
self
}
#[doc="Slave Select Output Enable"]
#[inline] pub fn ssoe(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 1) & 0x1) as u8) } // [1]
}
#[doc="Returns true if SSOE != 0"]
#[inline] pub fn test_ssoe(&self) -> bool {
self.ssoe() != 0
}
#[doc="Sets the SSOE field."]
#[inline] pub fn set_ssoe<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u8 = value.into();
self.0 &= !(0x1 << 1);
self.0 |= value << 1;
self
}
#[doc="Clock Phase"]
#[inline] pub fn cpha(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 2) & 0x1) as u8) } // [2]
}
#[doc="Returns true if CPHA != 0"]
#[inline] pub fn test_cpha(&self) -> bool {
self.cpha() != 0
}
#[doc="Sets the CPHA field."]
#[inline] pub fn set_cpha<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u8 = value.into();
self.0 &= !(0x1 << 2);
self.0 |= value << 2;
self
}
#[doc="Clock Polarity"]
#[inline] pub fn cpol(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 3) & 0x1) as u8) } // [3]
}
#[doc="Returns true if CPOL != 0"]
#[inline] pub fn test_cpol(&self) -> bool {
self.cpol() != 0
}
#[doc="Sets the CPOL field."]
#[inline] pub fn set_cpol<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u8 = value.into();
self.0 &= !(0x1 << 3);
self.0 |= value << 3;
self
}
#[doc="Master/Slave Mode Select"]
#[inline] pub fn mstr(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 4) & 0x1) as u8) } // [4]
}
#[doc="Returns true if MSTR != 0"]
#[inline] pub fn test_mstr(&self) -> bool {
self.mstr() != 0
}
#[doc="Sets the MSTR field."]
#[inline] pub fn set_mstr<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u8 = value.into();
self.0 &= !(0x1 << 4);
self.0 |= value << 4;
self
}
#[doc="SPI Transmit Interrupt Enable"]
#[inline] pub fn sptie(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 5) & 0x1) as u8) } // [5]
}
#[doc="Returns true if SPTIE != 0"]
#[inline] pub fn test_sptie(&self) -> bool {
self.sptie() != 0
}
#[doc="Sets the SPTIE field."]
#[inline] pub fn set_sptie<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u8 = value.into();
self.0 &= !(0x1 << 5);
self.0 |= value << 5;
self
}
#[doc="SPI System Enable"]
#[inline] pub fn spe(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 6) & 0x1) as u8) } // [6]
}
#[doc="Returns true if SPE != 0"]
#[inline] pub fn test_spe(&self) -> bool {
self.spe() != 0
}
#[doc="Sets the SPE field."]
#[inline] pub fn set_spe<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u8 = value.into();
self.0 &= !(0x1 << 6);
self.0 |= value << 6;
self
}
#[doc="SPI Interrupt Enable: for SPRF and MODF"]
#[inline] pub fn spie(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 7) & 0x1) as u8) } // [7]
}
#[doc="Returns true if SPIE != 0"]
#[inline] pub fn test_spie(&self) -> bool {
self.spie() != 0
}
#[doc="Sets the SPIE field."]
#[inline] pub fn set_spie<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u8 = value.into();
self.0 &= !(0x1 << 7);
self.0 |= value << 7;
self
}
}
impl From<u8> for C1 {
#[inline]
fn from(other: u8) -> Self {
C1(other)
}
}
impl ::core::fmt::Display for C1 {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
self.0.fmt(f)
}
}
impl ::core::fmt::Debug for C1 {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
try!(write!(f, "[0x{:08x}", self.0));
if self.lsbfe() != 0 { try!(write!(f, " lsbfe"))}
if self.ssoe() != 0 { try!(write!(f, " ssoe"))}
if self.cpha() != 0 { try!(write!(f, " cpha"))}
if self.cpol() != 0 { try!(write!(f, " cpol"))}
if self.mstr() != 0 { try!(write!(f, " mstr"))}
if self.sptie() != 0 { try!(write!(f, " sptie"))}
if self.spe() != 0 { try!(write!(f, " spe"))}
if self.spie() != 0 { try!(write!(f, " spie"))}
try!(write!(f, "]"));
Ok(())
}
}
#[doc="SPI Control Register 2"]
#[derive(Default, Clone, Copy, PartialEq, Eq)]
pub struct C2(pub u8);
impl C2 {
#[doc="SPI Pin Control 0"]
#[inline] pub fn spc0(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 0) & 0x1) as u8) } // [0]
}
#[doc="Returns true if SPC0 != 0"]
#[inline] pub fn test_spc0(&self) -> bool {
self.spc0() != 0
}
#[doc="Sets the SPC0 field."]
#[inline] pub fn set_spc0<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u8 = value.into();
self.0 &= !(0x1 << 0);
self.0 |= value << 0;
self
}
#[doc="SPI Stop in Wait Mode"]
#[inline] pub fn spiswai(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 1) & 0x1) as u8) } // [1]
}
#[doc="Returns true if SPISWAI != 0"]
#[inline] pub fn test_spiswai(&self) -> bool {
self.spiswai() != 0
}
#[doc="Sets the SPISWAI field."]
#[inline] pub fn set_spiswai<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u8 = value.into();
self.0 &= !(0x1 << 1);
self.0 |= value << 1;
self
}
#[doc="Bidirectional Mode Output Enable"]
#[inline] pub fn bidiroe(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 3) & 0x1) as u8) } // [3]
}
#[doc="Returns true if BIDIROE != 0"]
#[inline] pub fn test_bidiroe(&self) -> bool {
self.bidiroe() != 0
}
#[doc="Sets the BIDIROE field."]
#[inline] pub fn set_bidiroe<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u8 = value.into();
self.0 &= !(0x1 << 3);
self.0 |= value << 3;
self
}
#[doc="Master Mode-Fault Function Enable"]
#[inline] pub fn modfen(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 4) & 0x1) as u8) } // [4]
}
#[doc="Returns true if MODFEN != 0"]
#[inline] pub fn test_modfen(&self) -> bool {
self.modfen() != 0
}
#[doc="Sets the MODFEN field."]
#[inline] pub fn set_modfen<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u8 = value.into();
self.0 &= !(0x1 << 4);
self.0 |= value << 4;
self
}
#[doc="SPI Match Interrupt Enable"]
#[inline] pub fn spmie(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 7) & 0x1) as u8) } // [7]
}
#[doc="Returns true if SPMIE != 0"]
#[inline] pub fn test_spmie(&self) -> bool {
self.spmie() != 0
}
#[doc="Sets the SPMIE field."]
#[inline] pub fn set_spmie<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u8 = value.into();
self.0 &= !(0x1 << 7);
self.0 |= value << 7;
self
}
}
impl From<u8> for C2 {
#[inline]
fn from(other: u8) -> Self {
C2(other)
}
}
impl ::core::fmt::Display for C2 {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
self.0.fmt(f)
}
}
impl ::core::fmt::Debug for C2 {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
try!(write!(f, "[0x{:08x}", self.0));
if self.spc0() != 0 { try!(write!(f, " spc0"))}
if self.spiswai() != 0 { try!(write!(f, " spiswai"))}
if self.bidiroe() != 0 { try!(write!(f, " bidiroe"))}
if self.modfen() != 0 { try!(write!(f, " modfen"))}
if self.spmie() != 0 { try!(write!(f, " spmie"))}
try!(write!(f, "]"));
Ok(())
}
}
#[doc="SPI Baud Rate Register"]
#[derive(Default, Clone, Copy, PartialEq, Eq)]
pub struct Br(pub u8);
impl Br {
#[doc="SPI Baud Rate Divisor"]
#[inline] pub fn spr(&self) -> ::bobbin_bits::U4 {
unsafe { ::core::mem::transmute(((self.0 >> 0) & 0xf) as u8) } // [3:0]
}
#[doc="Returns true if SPR != 0"]
#[inline] pub fn test_spr(&self) -> bool {
self.spr() != 0
}
#[doc="Sets the SPR field."]
#[inline] pub fn set_spr<V: Into<::bobbin_bits::U4>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U4 = value.into();
let value: u8 = value.into();
self.0 &= !(0xf << 0);
self.0 |= value << 0;
self
}
#[doc="SPI Baud Rate Prescale Divisor"]
#[inline] pub fn sppr(&self) -> ::bobbin_bits::U3 {
unsafe { ::core::mem::transmute(((self.0 >> 4) & 0x7) as u8) } // [6:4]
}
#[doc="Returns true if SPPR != 0"]
#[inline] pub fn test_sppr(&self) -> bool {
self.sppr() != 0
}
#[doc="Sets the SPPR field."]
#[inline] pub fn set_sppr<V: Into<::bobbin_bits::U3>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U3 = value.into();
let value: u8 = value.into();
self.0 &= !(0x7 << 4);
self.0 |= value << 4;
self
}
}
impl From<u8> for Br {
#[inline]
fn from(other: u8) -> Self {
Br(other)
}
}
impl ::core::fmt::Display for Br {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
self.0.fmt(f)
}
}
impl ::core::fmt::Debug for Br {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
try!(write!(f, "[0x{:08x}", self.0));
if self.spr() != 0 { try!(write!(f, " spr=0x{:x}", self.spr()))}
if self.sppr() != 0 { try!(write!(f, " sppr=0x{:x}", self.sppr()))}
try!(write!(f, "]"));
Ok(())
}
}
#[doc="SPI Status Register"]
#[derive(Default, Clone, Copy, PartialEq, Eq)]
pub struct S(pub u8);
impl S {
#[doc="Master Mode Fault Flag"]
#[inline] pub fn modf(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 4) & 0x1) as u8) } // [4]
}
#[doc="Returns true if MODF != 0"]
#[inline] pub fn test_modf(&self) -> bool {
self.modf() != 0
}
#[doc="Sets the MODF field."]
#[inline] pub fn set_modf<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u8 = value.into();
self.0 &= !(0x1 << 4);
self.0 |= value << 4;
self
}
#[doc="SPI Transmit Buffer Empty Flag"]
#[inline] pub fn sptef(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 5) & 0x1) as u8) } // [5]
}
#[doc="Returns true if SPTEF != 0"]
#[inline] pub fn test_sptef(&self) -> bool {
self.sptef() != 0
}
#[doc="Sets the SPTEF field."]
#[inline] pub fn set_sptef<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u8 = value.into();
self.0 &= !(0x1 << 5);
self.0 |= value << 5;
self
}
#[doc="SPI Match Flag"]
#[inline] pub fn spmf(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 6) & 0x1) as u8) } // [6]
}
#[doc="Returns true if SPMF != 0"]
#[inline] pub fn test_spmf(&self) -> bool {
self.spmf() != 0
}
#[doc="Sets the SPMF field."]
#[inline] pub fn set_spmf<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u8 = value.into();
self.0 &= !(0x1 << 6);
self.0 |= value << 6;
self
}
#[doc="SPI Read Buffer Full Flag"]
#[inline] pub fn sprf(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 7) & 0x1) as u8) } // [7]
}
#[doc="Returns true if SPRF != 0"]
#[inline] pub fn test_sprf(&self) -> bool {
self.sprf() != 0
}
#[doc="Sets the SPRF field."]
#[inline] pub fn set_sprf<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u8 = value.into();
self.0 &= !(0x1 << 7);
self.0 |= value << 7;
self
}
}
impl From<u8> for S {
#[inline]
fn from(other: u8) -> Self {
S(other)
}
}
impl ::core::fmt::Display for S {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
self.0.fmt(f)
}
}
impl ::core::fmt::Debug for S {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
try!(write!(f, "[0x{:08x}", self.0));
if self.modf() != 0 { try!(write!(f, " modf"))}
if self.sptef() != 0 { try!(write!(f, " sptef"))}
if self.spmf() != 0 { try!(write!(f, " spmf"))}
if self.sprf() != 0 { try!(write!(f, " sprf"))}
try!(write!(f, "]"));
Ok(())
}
}
#[doc="SPI Data Register"]
#[derive(Default, Clone, Copy, PartialEq, Eq)]
pub struct D(pub u8);
impl D {
#[doc="Data (low byte)"]
#[inline] pub fn bits(&self) -> ::bobbin_bits::U8 {
unsafe { ::core::mem::transmute(((self.0 >> 0) & 0xff) as u8) } // [7:0]
}
#[doc="Returns true if BITS != 0"]
#[inline] pub fn test_bits(&self) -> bool {
self.bits() != 0
}
#[doc="Sets the BITS field."]
#[inline] pub fn set_bits<V: Into<::bobbin_bits::U8>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U8 = value.into();
let value: u8 = value.into();
self.0 &= !(0xff << 0);
self.0 |= value << 0;
self
}
}
impl From<u8> for D {
#[inline]
fn from(other: u8) -> Self {
D(other)
}
}
impl ::core::fmt::Display for D {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
self.0.fmt(f)
}
}
impl ::core::fmt::Debug for D {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
try!(write!(f, "[0x{:08x}", self.0));
if self.bits() != 0 { try!(write!(f, " bits=0x{:x}", self.bits()))}
try!(write!(f, "]"));
Ok(())
}
}
#[doc="SPI Match Register"]
#[derive(Default, Clone, Copy, PartialEq, Eq)]
pub struct M(pub u8);
impl M {
#[doc="Hardware compare value (low byte)"]
#[inline] pub fn bits(&self) -> ::bobbin_bits::U8 {
unsafe { ::core::mem::transmute(((self.0 >> 0) & 0xff) as u8) } // [7:0]
}
#[doc="Returns true if BITS != 0"]
#[inline] pub fn test_bits(&self) -> bool {
self.bits() != 0
}
#[doc="Sets the BITS field."]
#[inline] pub fn set_bits<V: Into<::bobbin_bits::U8>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U8 = value.into();
let value: u8 = value.into();
self.0 &= !(0xff << 0);
self.0 |= value << 0;
self
}
}
impl From<u8> for M {
#[inline]
fn from(other: u8) -> Self {
M(other)
}
}
impl ::core::fmt::Display for M {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
self.0.fmt(f)
}
}
impl ::core::fmt::Debug for M {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
try!(write!(f, "[0x{:08x}", self.0));
if self.bits() != 0 { try!(write!(f, " bits=0x{:x}", self.bits()))}
try!(write!(f, "]"));
Ok(())
}
}
| true |
e7663bb700a021679e74371dcc2920093d7a8bf0
|
Rust
|
alexbensimon/advent-of-code-2020
|
/src/day_01/mod.rs
|
UTF-8
| 1,014 | 3.078125 | 3 |
[] |
no_license
|
use crate::utils::lines_from_file;
use std::time::Instant;
pub fn main() {
let start = Instant::now();
let entries: Vec<i32> = lines_from_file("src/day_01/input.txt")
.iter()
.map(|line| line.parse::<i32>().unwrap())
.collect();
// println!("{:?}", part_1(entries));
println!("{:?}", part_2(entries));
let duration = start.elapsed();
println!("Finished after {:?}", duration);
}
fn part_1(entries: Vec<i32>) -> i32 {
for entry_a in entries.iter() {
for entry_b in entries.iter() {
if entry_a + entry_b == 2020 {
return entry_a * entry_b;
}
}
}
return 0;
}
fn part_2(entries: Vec<i32>) -> i32 {
for entry_a in entries.iter() {
for entry_b in entries.iter() {
for entry_c in entries.iter() {
if entry_a + entry_b + entry_c == 2020 {
return entry_a * entry_b * entry_c;
}
}
}
}
return 0;
}
| true |
bcbfb18cbf7fd8cda2b4d38cefc51a0c764538c4
|
Rust
|
placrosse/rust-hdbconnect
|
/src/types_impl/lob/blob.rs
|
UTF-8
| 6,296 | 2.84375 | 3 |
[
"MIT"
] |
permissive
|
use crate::conn_core::AmConnCore;
use crate::protocol::server_resource_consumption_info::ServerResourceConsumptionInfo;
use crate::types_impl::lob::fetch_a_lob_chunk;
use crate::{HdbError, HdbResult};
use serde_derive::Serialize;
use std::cell::RefCell;
use std::cmp;
use std::io::{self, Write};
/// BLob implementation that is used within `HdbValue::BLOB`.
#[derive(Clone, Debug, Serialize)]
pub struct BLob(BLobEnum);
#[derive(Clone, Debug, Serialize)]
enum BLobEnum {
FromDB(RefCell<BLobHandle>),
ToDB(Vec<u8>),
}
pub(crate) fn new_blob_from_db(
am_conn_core: &AmConnCore,
is_data_complete: bool,
length_b: u64,
locator_id: u64,
data: Vec<u8>,
) -> BLob {
BLob(BLobEnum::FromDB(RefCell::new(BLobHandle::new(
am_conn_core,
is_data_complete,
length_b,
locator_id,
data,
))))
}
// Factory method for BLobs that are to be sent to the database.
pub(crate) fn new_blob_to_db(vec: Vec<u8>) -> BLob {
BLob(BLobEnum::ToDB(vec))
}
impl BLob {
/// Length of contained data.
pub fn len_alldata(&self) -> usize {
match self.0 {
BLobEnum::FromDB(ref handle) => handle.borrow_mut().len_alldata() as usize,
BLobEnum::ToDB(ref vec) => vec.len(),
}
}
/// Length of read data.
pub fn len_readdata(&self) -> usize {
match self.0 {
BLobEnum::FromDB(ref handle) => handle.borrow_mut().len_readdata() as usize,
BLobEnum::ToDB(ref vec) => vec.len(),
}
}
/// Is container empty
pub fn is_empty(&self) -> HdbResult<bool> {
Ok(self.len_alldata() == 0)
}
/// Ref to the contained Vec<u8>.
pub fn ref_to_bytes(&self) -> HdbResult<&Vec<u8>> {
trace!("BLob::ref_to_bytes()");
match self.0 {
BLobEnum::FromDB(_) => Err(HdbError::impl_("cannot serialize BLobHandle")),
BLobEnum::ToDB(ref vec) => Ok(vec),
}
}
/// Converts into the contained Vec<u8>.
pub fn into_bytes(self) -> HdbResult<Vec<u8>> {
trace!("BLob::into_bytes()");
match self.0 {
BLobEnum::FromDB(handle) => handle.into_inner().into_bytes(),
BLobEnum::ToDB(vec) => Ok(vec),
}
}
/// Returns the maximum size of the internal buffers.
///
/// Tests can verify that this value does not exceed `lob_read_size` +
/// `buf.len()`.
pub fn max_size(&self) -> usize {
match self.0 {
BLobEnum::FromDB(ref handle) => handle.borrow().max_size(),
BLobEnum::ToDB(ref v) => v.len(),
}
}
}
// Support for BLob streaming
impl io::Read for BLob {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
match self.0 {
BLobEnum::FromDB(ref blob_handle) => blob_handle.borrow_mut().read(buf),
BLobEnum::ToDB(ref v) => v.as_slice().read(buf),
}
}
}
// `BLobHandle` is used for BLobs that we receive from the database.
// The data are often not transferred completely,
// so we carry internally a database connection and the
// necessary controls to support fetching remaining data on demand.
#[derive(Clone, Debug, Serialize)]
struct BLobHandle {
#[serde(skip)]
o_am_conn_core: Option<AmConnCore>,
is_data_complete: bool,
length_b: u64,
locator_id: u64,
data: Vec<u8>,
max_size: usize,
acc_byte_length: usize,
#[serde(skip)]
server_resource_consumption_info: ServerResourceConsumptionInfo,
}
impl BLobHandle {
pub fn new(
am_conn_core: &AmConnCore,
is_data_complete: bool,
length_b: u64,
locator_id: u64,
data: Vec<u8>,
) -> BLobHandle {
trace!(
"BLobHandle::new() with length_b = {}, is_data_complete = {}, data.length() = {}",
length_b,
is_data_complete,
data.len()
);
BLobHandle {
o_am_conn_core: Some(am_conn_core.clone()),
length_b,
is_data_complete,
locator_id,
max_size: data.len(),
acc_byte_length: data.len(),
data,
server_resource_consumption_info: Default::default(),
}
}
pub fn len_alldata(&mut self) -> u64 {
self.length_b
}
pub fn len_readdata(&mut self) -> usize {
self.data.len()
}
fn fetch_next_chunk(&mut self) -> HdbResult<()> {
let (mut reply_data, reply_is_last_data) = fetch_a_lob_chunk(
&mut self.o_am_conn_core,
self.locator_id,
self.length_b,
self.acc_byte_length as u64,
&mut self.server_resource_consumption_info,
)?;
self.acc_byte_length += reply_data.len();
self.data.append(&mut reply_data);
self.is_data_complete = reply_is_last_data;
self.max_size = cmp::max(self.data.len(), self.max_size);
assert_eq!(
self.is_data_complete,
self.length_b == self.acc_byte_length as u64
);
trace!(
"fetch_next_chunk: is_data_complete = {}, data.len() = {}",
self.is_data_complete,
self.data.len()
);
Ok(())
}
/// Converts a BLob into a Vec<u8> containing its data.
fn load_complete(&mut self) -> HdbResult<()> {
trace!("load_complete()");
while !self.is_data_complete {
self.fetch_next_chunk()?;
}
Ok(())
}
pub fn max_size(&self) -> usize {
self.max_size
}
/// Converts a BLob into a Vec<u8> containing its data.
pub fn into_bytes(mut self) -> HdbResult<Vec<u8>> {
trace!("into_bytes()");
self.load_complete()?;
Ok(self.data)
}
}
// Support for streaming
impl io::Read for BLobHandle {
fn read(&mut self, mut buf: &mut [u8]) -> io::Result<usize> {
trace!("BLobHandle::read() with buf of len {}", buf.len());
while !self.is_data_complete && (buf.len() > self.data.len()) {
self.fetch_next_chunk()
.map_err(|e| io::Error::new(io::ErrorKind::UnexpectedEof, e))?;
}
let count = cmp::min(self.data.len(), buf.len());
buf.write_all(&self.data[0..count])?;
self.data.drain(0..count);
Ok(count)
}
}
| true |
9e3718681bdc3a4d4d10298ca5639346bf7b9734
|
Rust
|
marco-c/gecko-dev-wordified
|
/third_party/rust/tokio/src/runtime/task/join.rs
|
UTF-8
| 7,766 | 2.765625 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
use
crate
:
:
runtime
:
:
task
:
:
RawTask
;
use
std
:
:
fmt
;
use
std
:
:
future
:
:
Future
;
use
std
:
:
marker
:
:
PhantomData
;
use
std
:
:
panic
:
:
{
RefUnwindSafe
UnwindSafe
}
;
use
std
:
:
pin
:
:
Pin
;
use
std
:
:
task
:
:
{
Context
Poll
Waker
}
;
cfg_rt
!
{
/
/
/
An
owned
permission
to
join
on
a
task
(
await
its
termination
)
.
/
/
/
/
/
/
This
can
be
thought
of
as
the
equivalent
of
[
std
:
:
thread
:
:
JoinHandle
]
for
/
/
/
a
task
rather
than
a
thread
.
/
/
/
/
/
/
A
JoinHandle
*
detaches
*
the
associated
task
when
it
is
dropped
which
/
/
/
means
that
there
is
no
longer
any
handle
to
the
task
and
no
way
to
join
/
/
/
on
it
.
/
/
/
/
/
/
This
struct
is
created
by
the
[
task
:
:
spawn
]
and
[
task
:
:
spawn_blocking
]
/
/
/
functions
.
/
/
/
/
/
/
#
Examples
/
/
/
/
/
/
Creation
from
[
task
:
:
spawn
]
:
/
/
/
/
/
/
/
/
/
use
tokio
:
:
task
;
/
/
/
/
/
/
#
async
fn
doc
(
)
{
/
/
/
let
join_handle
:
task
:
:
JoinHandle
<
_
>
=
task
:
:
spawn
(
async
{
/
/
/
/
/
some
work
here
/
/
/
}
)
;
/
/
/
#
}
/
/
/
/
/
/
/
/
/
Creation
from
[
task
:
:
spawn_blocking
]
:
/
/
/
/
/
/
/
/
/
use
tokio
:
:
task
;
/
/
/
/
/
/
#
async
fn
doc
(
)
{
/
/
/
let
join_handle
:
task
:
:
JoinHandle
<
_
>
=
task
:
:
spawn_blocking
(
|
|
{
/
/
/
/
/
some
blocking
work
here
/
/
/
}
)
;
/
/
/
#
}
/
/
/
/
/
/
/
/
/
The
generic
parameter
T
in
JoinHandle
<
T
>
is
the
return
type
of
the
spawned
task
.
/
/
/
If
the
return
value
is
an
i32
the
join
handle
has
type
JoinHandle
<
i32
>
:
/
/
/
/
/
/
/
/
/
use
tokio
:
:
task
;
/
/
/
/
/
/
#
async
fn
doc
(
)
{
/
/
/
let
join_handle
:
task
:
:
JoinHandle
<
i32
>
=
task
:
:
spawn
(
async
{
/
/
/
5
+
3
/
/
/
}
)
;
/
/
/
#
}
/
/
/
/
/
/
/
/
/
/
/
/
If
the
task
does
not
have
a
return
value
the
join
handle
has
type
JoinHandle
<
(
)
>
:
/
/
/
/
/
/
/
/
/
use
tokio
:
:
task
;
/
/
/
/
/
/
#
async
fn
doc
(
)
{
/
/
/
let
join_handle
:
task
:
:
JoinHandle
<
(
)
>
=
task
:
:
spawn
(
async
{
/
/
/
println
!
(
"
I
return
nothing
.
"
)
;
/
/
/
}
)
;
/
/
/
#
}
/
/
/
/
/
/
/
/
/
Note
that
handle
.
await
doesn
'
t
give
you
the
return
type
directly
.
It
is
wrapped
in
a
/
/
/
Result
because
panics
in
the
spawned
task
are
caught
by
Tokio
.
The
?
operator
has
/
/
/
to
be
double
chained
to
extract
the
returned
value
:
/
/
/
/
/
/
/
/
/
use
tokio
:
:
task
;
/
/
/
use
std
:
:
io
;
/
/
/
/
/
/
#
[
tokio
:
:
main
]
/
/
/
async
fn
main
(
)
-
>
io
:
:
Result
<
(
)
>
{
/
/
/
let
join_handle
:
task
:
:
JoinHandle
<
Result
<
i32
io
:
:
Error
>
>
=
tokio
:
:
spawn
(
async
{
/
/
/
Ok
(
5
+
3
)
/
/
/
}
)
;
/
/
/
/
/
/
let
result
=
join_handle
.
await
?
?
;
/
/
/
assert_eq
!
(
result
8
)
;
/
/
/
Ok
(
(
)
)
/
/
/
}
/
/
/
/
/
/
/
/
/
If
the
task
panics
the
error
is
a
[
JoinError
]
that
contains
the
panic
:
/
/
/
/
/
/
/
/
/
use
tokio
:
:
task
;
/
/
/
use
std
:
:
io
;
/
/
/
use
std
:
:
panic
;
/
/
/
/
/
/
#
[
tokio
:
:
main
]
/
/
/
async
fn
main
(
)
-
>
io
:
:
Result
<
(
)
>
{
/
/
/
let
join_handle
:
task
:
:
JoinHandle
<
Result
<
i32
io
:
:
Error
>
>
=
tokio
:
:
spawn
(
async
{
/
/
/
panic
!
(
"
boom
"
)
;
/
/
/
}
)
;
/
/
/
/
/
/
let
err
=
join_handle
.
await
.
unwrap_err
(
)
;
/
/
/
assert
!
(
err
.
is_panic
(
)
)
;
/
/
/
Ok
(
(
)
)
/
/
/
}
/
/
/
/
/
/
/
/
/
Child
being
detached
and
outliving
its
parent
:
/
/
/
/
/
/
no_run
/
/
/
use
tokio
:
:
task
;
/
/
/
use
tokio
:
:
time
;
/
/
/
use
std
:
:
time
:
:
Duration
;
/
/
/
/
/
/
#
#
[
tokio
:
:
main
]
async
fn
main
(
)
{
/
/
/
let
original_task
=
task
:
:
spawn
(
async
{
/
/
/
let
_detached_task
=
task
:
:
spawn
(
async
{
/
/
/
/
/
Here
we
sleep
to
make
sure
that
the
first
task
returns
before
.
/
/
/
time
:
:
sleep
(
Duration
:
:
from_millis
(
10
)
)
.
await
;
/
/
/
/
/
This
will
be
called
even
though
the
JoinHandle
is
dropped
.
/
/
/
println
!
(
"
Still
alive
"
)
;
/
/
/
}
)
;
/
/
/
}
)
;
/
/
/
/
/
/
original_task
.
await
.
expect
(
"
The
task
being
joined
has
panicked
"
)
;
/
/
/
println
!
(
"
Original
task
is
joined
.
"
)
;
/
/
/
/
/
/
/
/
We
make
sure
that
the
new
task
has
time
to
run
before
the
main
/
/
/
/
/
task
returns
.
/
/
/
/
/
/
time
:
:
sleep
(
Duration
:
:
from_millis
(
1000
)
)
.
await
;
/
/
/
#
}
/
/
/
/
/
/
/
/
/
[
task
:
:
spawn
]
:
crate
:
:
task
:
:
spawn
(
)
/
/
/
[
task
:
:
spawn_blocking
]
:
crate
:
:
task
:
:
spawn_blocking
/
/
/
[
std
:
:
thread
:
:
JoinHandle
]
:
std
:
:
thread
:
:
JoinHandle
/
/
/
[
JoinError
]
:
crate
:
:
task
:
:
JoinError
pub
struct
JoinHandle
<
T
>
{
raw
:
Option
<
RawTask
>
_p
:
PhantomData
<
T
>
}
}
unsafe
impl
<
T
:
Send
>
Send
for
JoinHandle
<
T
>
{
}
unsafe
impl
<
T
:
Send
>
Sync
for
JoinHandle
<
T
>
{
}
impl
<
T
>
UnwindSafe
for
JoinHandle
<
T
>
{
}
impl
<
T
>
RefUnwindSafe
for
JoinHandle
<
T
>
{
}
impl
<
T
>
JoinHandle
<
T
>
{
pub
(
super
)
fn
new
(
raw
:
RawTask
)
-
>
JoinHandle
<
T
>
{
JoinHandle
{
raw
:
Some
(
raw
)
_p
:
PhantomData
}
}
/
/
/
Abort
the
task
associated
with
the
handle
.
/
/
/
/
/
/
Awaiting
a
cancelled
task
might
complete
as
usual
if
the
task
was
/
/
/
already
completed
at
the
time
it
was
cancelled
but
most
likely
it
/
/
/
will
fail
with
a
[
cancelled
]
JoinError
.
/
/
/
/
/
/
rust
/
/
/
use
tokio
:
:
time
;
/
/
/
/
/
/
#
[
tokio
:
:
main
]
/
/
/
async
fn
main
(
)
{
/
/
/
let
mut
handles
=
Vec
:
:
new
(
)
;
/
/
/
/
/
/
handles
.
push
(
tokio
:
:
spawn
(
async
{
/
/
/
time
:
:
sleep
(
time
:
:
Duration
:
:
from_secs
(
10
)
)
.
await
;
/
/
/
true
/
/
/
}
)
)
;
/
/
/
/
/
/
handles
.
push
(
tokio
:
:
spawn
(
async
{
/
/
/
time
:
:
sleep
(
time
:
:
Duration
:
:
from_secs
(
10
)
)
.
await
;
/
/
/
false
/
/
/
}
)
)
;
/
/
/
/
/
/
for
handle
in
&
handles
{
/
/
/
handle
.
abort
(
)
;
/
/
/
}
/
/
/
/
/
/
for
handle
in
handles
{
/
/
/
assert
!
(
handle
.
await
.
unwrap_err
(
)
.
is_cancelled
(
)
)
;
/
/
/
}
/
/
/
}
/
/
/
/
/
/
[
cancelled
]
:
method
super
:
:
error
:
:
JoinError
:
:
is_cancelled
pub
fn
abort
(
&
self
)
{
if
let
Some
(
raw
)
=
self
.
raw
{
raw
.
remote_abort
(
)
;
}
}
/
/
/
Set
the
waker
that
is
notified
when
the
task
completes
.
pub
(
crate
)
fn
set_join_waker
(
&
mut
self
waker
:
&
Waker
)
{
if
let
Some
(
raw
)
=
self
.
raw
{
if
raw
.
try_set_join_waker
(
waker
)
{
/
/
In
this
case
the
task
has
already
completed
.
We
wake
the
waker
immediately
.
waker
.
wake_by_ref
(
)
;
}
}
}
}
impl
<
T
>
Unpin
for
JoinHandle
<
T
>
{
}
impl
<
T
>
Future
for
JoinHandle
<
T
>
{
type
Output
=
super
:
:
Result
<
T
>
;
fn
poll
(
self
:
Pin
<
&
mut
Self
>
cx
:
&
mut
Context
<
'
_
>
)
-
>
Poll
<
Self
:
:
Output
>
{
let
mut
ret
=
Poll
:
:
Pending
;
/
/
Keep
track
of
task
budget
let
coop
=
ready
!
(
crate
:
:
coop
:
:
poll_proceed
(
cx
)
)
;
/
/
Raw
should
always
be
set
.
If
it
is
not
this
is
due
to
polling
after
/
/
completion
let
raw
=
self
.
raw
.
as_ref
(
)
.
expect
(
"
polling
after
JoinHandle
already
completed
"
)
;
/
/
Try
to
read
the
task
output
.
If
the
task
is
not
yet
complete
the
/
/
waker
is
stored
and
is
notified
once
the
task
does
complete
.
/
/
/
/
The
function
must
go
via
the
vtable
which
requires
erasing
generic
/
/
types
.
To
do
this
the
function
"
return
"
is
placed
on
the
stack
/
/
*
*
before
*
*
calling
the
function
and
is
passed
into
the
function
using
/
/
*
mut
(
)
.
/
/
/
/
Safety
:
/
/
/
/
The
type
of
T
must
match
the
task
'
s
output
type
.
unsafe
{
raw
.
try_read_output
(
&
mut
ret
as
*
mut
_
as
*
mut
(
)
cx
.
waker
(
)
)
;
}
if
ret
.
is_ready
(
)
{
coop
.
made_progress
(
)
;
}
ret
}
}
impl
<
T
>
Drop
for
JoinHandle
<
T
>
{
fn
drop
(
&
mut
self
)
{
if
let
Some
(
raw
)
=
self
.
raw
.
take
(
)
{
if
raw
.
header
(
)
.
state
.
drop_join_handle_fast
(
)
.
is_ok
(
)
{
return
;
}
raw
.
drop_join_handle_slow
(
)
;
}
}
}
impl
<
T
>
fmt
:
:
Debug
for
JoinHandle
<
T
>
where
T
:
fmt
:
:
Debug
{
fn
fmt
(
&
self
fmt
:
&
mut
fmt
:
:
Formatter
<
'
_
>
)
-
>
fmt
:
:
Result
{
fmt
.
debug_struct
(
"
JoinHandle
"
)
.
finish
(
)
}
}
| true |
f474802e8abaf7ca0b069de9a27120f2d2ede9aa
|
Rust
|
co42/bevy_tilemap
|
/src/chunk/render/mod.rs
|
UTF-8
| 5,374 | 2.578125 | 3 |
[
"MIT"
] |
permissive
|
use crate::lib::*;
macro_rules! build_chunk_pipeline {
($handle: ident, $id: expr, $name: ident, $file: expr) => {
/// The constant render pipeline for a chunk.
pub(crate) const $handle: HandleUntyped =
HandleUntyped::weak_from_u64(PipelineDescriptor::TYPE_UUID, $id);
/// Builds the chunk render pipeline.
fn $name(shaders: &mut Assets<Shader>) -> PipelineDescriptor {
PipelineDescriptor {
color_target_states: vec![ColorTargetState {
format: TextureFormat::default(),
color_blend: BlendState {
src_factor: BlendFactor::SrcAlpha,
dst_factor: BlendFactor::OneMinusSrcAlpha,
operation: BlendOperation::Add,
},
alpha_blend: BlendState {
src_factor: BlendFactor::One,
dst_factor: BlendFactor::One,
operation: BlendOperation::Add,
},
write_mask: ColorWrite::ALL,
}],
depth_stencil: Some(DepthStencilState {
format: TextureFormat::Depth32Float,
depth_write_enabled: true,
depth_compare: CompareFunction::LessEqual,
stencil: StencilState {
front: StencilFaceState::IGNORE,
back: StencilFaceState::IGNORE,
read_mask: 0,
write_mask: 0,
},
bias: DepthBiasState {
constant: 0,
slope_scale: 0.0,
clamp: 0.0,
},
clamp_depth: false,
}),
..PipelineDescriptor::new(ShaderStages {
vertex: shaders
.add(Shader::from_glsl(ShaderStage::Vertex, include_str!($file))),
fragment: Some(shaders.add(Shader::from_glsl(
ShaderStage::Fragment,
include_str!("tilemap.frag"),
))),
})
}
}
};
}
build_chunk_pipeline!(
CHUNK_SQUARE_PIPELINE,
2110840099625352487,
build_chunk_square_pipeline,
"tilemap-square.vert"
);
build_chunk_pipeline!(
CHUNK_HEX_X_PIPELINE,
7038597873061171051,
build_chunk_hex_x,
"tilemap-hex-x.vert"
);
build_chunk_pipeline!(
CHUNK_HEX_Y_PIPELINE,
4304966217182648108,
build_chunk_hex_y,
"tilemap-hex-y.vert"
);
build_chunk_pipeline!(
CHUNK_HEXCOLS_EVEN_PIPELINE,
7604280309043018950,
build_chunk_hexcols_even,
"tilemap-hexcols-even.vert"
);
build_chunk_pipeline!(
CHUNK_HEXCOLS_ODD_PIPELINE,
3111565682159860869,
build_chunk_hexcols_odd,
"tilemap-hexcols-odd.vert"
);
build_chunk_pipeline!(
CHUNK_HEXROWS_EVEN_PIPELINE,
1670470246078408352,
build_chunk_hexrows_even,
"tilemap-hexrows-even.vert"
);
build_chunk_pipeline!(
CHUNK_HEXROWS_ODD_PIPELINE,
8160067835497533408,
build_chunk_hexrows_odd,
"tilemap-hexrows-odd.vert"
);
/// Topology of the tilemap grid (square or hex)
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum GridTopology {
/// Square grid
Square,
/// Hex grid with rows offset (hexes with pointy top).
HexY,
/// Hex grid with columns offset (hexes with flat top).
HexX,
/// Hex grid with offset on even rows (hexes with pointy top).
HexEvenRows,
/// Hex grid with offset on odd rows (hexes with pointy top).
HexOddRows,
/// Hex grid with offset on even columns (hexes with flat top).
HexEvenCols,
/// Hex grid with offset on odd columns (hexes with flat top).
HexOddCols,
}
impl GridTopology {
/// Takes a grid topology and returns a handle.
pub(crate) fn into_pipeline_handle(self) -> HandleUntyped {
use GridTopology::*;
match self {
Square => CHUNK_SQUARE_PIPELINE,
HexY => CHUNK_HEX_Y_PIPELINE,
HexX => CHUNK_HEX_X_PIPELINE,
HexEvenRows => CHUNK_HEXROWS_EVEN_PIPELINE,
HexOddRows => CHUNK_HEXROWS_ODD_PIPELINE,
HexEvenCols => CHUNK_HEXCOLS_EVEN_PIPELINE,
HexOddCols => CHUNK_HEXCOLS_ODD_PIPELINE,
}
}
}
/// Adds the tilemap graph to the pipeline and shaders.
pub(crate) fn add_tilemap_graph(
pipelines: &mut Assets<PipelineDescriptor>,
shaders: &mut Assets<Shader>,
) {
// Might need graph.add_system_node here...?
pipelines.set_untracked(CHUNK_SQUARE_PIPELINE, build_chunk_square_pipeline(shaders));
pipelines.set_untracked(CHUNK_HEX_X_PIPELINE, build_chunk_hex_x(shaders));
pipelines.set_untracked(CHUNK_HEX_Y_PIPELINE, build_chunk_hex_y(shaders));
pipelines.set_untracked(
CHUNK_HEXCOLS_EVEN_PIPELINE,
build_chunk_hexcols_even(shaders),
);
pipelines.set_untracked(CHUNK_HEXCOLS_ODD_PIPELINE, build_chunk_hexcols_odd(shaders));
pipelines.set_untracked(
CHUNK_HEXROWS_EVEN_PIPELINE,
build_chunk_hexrows_even(shaders),
);
pipelines.set_untracked(CHUNK_HEXROWS_ODD_PIPELINE, build_chunk_hexrows_odd(shaders));
}
| true |
ebb4d64ca01f64f591f21dd2e14f464d083b525b
|
Rust
|
TechniMan/rldev-does-the-tutorial-2020-rust
|
/src/map.rs
|
UTF-8
| 6,425 | 3.03125 | 3 |
[] |
no_license
|
use std::cmp::{ max, min };
use specs::prelude::*;
use rltk::{ Rltk, RandomNumberGenerator, Point, Algorithm2D, BaseMap };
use super::{ Rect, COLOURS };
#[derive(PartialEq, Copy, Clone)]
pub enum TileType {
Wall,
Floor
}
pub struct Map {
pub tiles : Vec<TileType>,
pub explored_tiles: Vec<bool>,
pub visible_tiles: Vec<bool>,
pub blocked_tiles: Vec<bool>,
pub rooms : Vec<Rect>,
pub width: i32,
pub height: i32
}
impl Map {
fn size(&self) -> usize {
(self.width * self.height) as usize
}
/// Returns the value to index into the tiles array
pub fn xy_idx(&self, x: i32, y: i32) -> usize {
((y * self.width) + x) as usize
}
fn apply_horizontal_tunnel(&mut self, x1: i32, x2: i32, y: i32) {
for x in min(x1, x2)..=max(x1, x2) {
let idx = self.xy_idx(x, y);
if idx > 0 && idx < self.size() {
self.tiles[idx as usize] = TileType::Floor;
}
}
}
fn apply_vertical_tunnel(&mut self, y1: i32, y2: i32, x: i32) {
for y in min(y1, y2)..=max(y1, y2) {
let idx = self.xy_idx(x, y);
if idx > 0 && idx < self.size() {
self.tiles[idx as usize] = TileType::Floor;
}
}
}
fn apply_room_to_map(&mut self, room: &Rect) {
for y in room.y1+1..=room.y2 {
for x in room.x1+1..=room.x2 {
let idx = self.xy_idx(x, y) as usize;
self.tiles[idx] = TileType::Floor;
}
}
}
/// Makes an 80*50 map with random rooms and connecting corridors
pub fn new_map_rooms_and_corridors() -> Self {
let mut map = Map {
tiles: vec![TileType::Wall; 80*50],
explored_tiles: vec![false; 80*50],
visible_tiles: vec![false; 80*50],
blocked_tiles: vec![false; 80*50],
rooms: Vec::new(),
width: 80,
height: 50
};
const MAX_ROOMS: i32 = 30;
const MIN_SIZE: i32 = 5;
const MAX_SIZE: i32 = 10;
let mut rng = RandomNumberGenerator::new();
for _ in 0..MAX_ROOMS {
let w = rng.range(MIN_SIZE, MAX_SIZE);
let h = rng.range(MIN_SIZE, MAX_SIZE);
let x = rng.roll_dice(1, 80 - w - 1) - 1;
let y = rng.roll_dice(1, 50 - h - 1) - 1;
let new_room = Rect::new(x, y, w, h);
let mut ok = true;
for other_room in map.rooms.iter() {
if new_room.intersect(other_room) {
ok = false;
break;
}
}
if ok {
map.apply_room_to_map(&new_room);
if !map.rooms.is_empty() {
let (new_x, new_y) = new_room.centre();
let (prev_x, prev_y) = map.rooms[map.rooms.len() - 1].centre();
if rng.range(0, 2) == 1 {
map.apply_horizontal_tunnel(prev_x, new_x, prev_y);
map.apply_vertical_tunnel(prev_y, new_y, new_x);
} else {
map.apply_vertical_tunnel(prev_y, new_y, prev_x);
map.apply_horizontal_tunnel(prev_x, new_x, new_y);
}
}
map.rooms.push(new_room);
}
}
map
}
fn is_exit_valid(&self, x: i32, y: i32) -> bool {
// if out of bounds, return false straight away
if x < 1 || x > self.width - 1 || y < 1 || y > self.height - 1 {
return false;
}
// else, check if tile is blocked
let idx = self.xy_idx(x, y);
!self.blocked_tiles[idx]
}
/// Fill in the `map.blocked_tiles` vector
pub fn populate_blocked(&mut self) {
// for each tile, set to blocked if it is a wall
for (i, tile) in self.tiles.iter_mut().enumerate() {
self.blocked_tiles[i] = *tile == TileType::Wall;
}
}
}
impl BaseMap for Map {
/// Returns whether tile at idx blocks movement
fn is_opaque(&self, idx: usize) -> bool {
self.tiles[idx as usize] == TileType::Wall
}
fn get_available_exits(&self, idx: usize) -> rltk::SmallVec<[(usize, f32); 10]> {
// find x and y for given tiles index
let mut exits = rltk::SmallVec::new();
let x = (idx as i32) % self.width;
let y = (idx as i32) / self.width;
let w = self.width as usize;
// add each of cardinal directions which doesn't block
if self.is_exit_valid(x-1, y) { exits.push((idx - 1, 1.0)) };
if self.is_exit_valid(x+1, y) { exits.push((idx + 1, 1.0)) };
if self.is_exit_valid(x, y-1) { exits.push((idx - w, 1.0)) };
if self.is_exit_valid(x, y+1) { exits.push((idx + w, 1.0)) };
exits
}
fn get_pathing_distance(&self, idx1: usize, idx2: usize) -> f32 {
let w = self.width as usize;
let p1 = Point::new(idx1 % w, idx1 / w);
let p2 = Point::new(idx2 % w, idx2 / w);
rltk::DistanceAlg::Pythagoras.distance2d(p1, p2)
}
}
impl Algorithm2D for Map {
/// Returns a Point containing the width & height of the map
fn dimensions(&self) -> Point {
Point::new(self.width, self.height)
}
}
/// RENDERING ///
/// ///////// ///
pub fn draw_map(world: &World, context: &mut Rltk) {
let map = world.fetch::<Map>();
let mut x = 0;
let mut y = 0;
for (idx, tile) in map.tiles.iter().enumerate() {
if map.explored_tiles[idx] {
let glyph;
let fg;
match tile {
TileType::Floor => {
// glyph = rltk::to_cp437(rltk::to_char(176));
glyph = rltk::to_cp437('.');
fg = if map.visible_tiles[idx] { COLOURS[10] } else { COLOURS[12] }
}
TileType::Wall => {
// glyph = rltk::to_cp437(rltk::to_char(219));
glyph = rltk::to_cp437('#');
fg = if map.visible_tiles[idx] { COLOURS[9] } else { COLOURS[1] }
}
}
context.set(x, y, fg, COLOURS[0], glyph);
}
// advance the 'cursor' along to the next cell to draw
x += 1;
if x > (map.width - 1) {
x = 0;
y += 1;
}
}
}
| true |
add7dba7976b170b12471223ec2e8a0c09c39335
|
Rust
|
tearne/library
|
/rust/04_Ferrous/src/bin/testing.rs
|
UTF-8
| 5,326 | 3.203125 | 3 |
[] |
no_license
|
#![allow(unused)]
type Result<T> = std::result::Result<T, ()>;
// Things representing data
#[derive(Debug, PartialEq)]
struct Parameter { }
#[derive(Debug, PartialEq)]
struct Record { property: u32 }
#[derive(Debug, PartialEq, Clone)]
struct ProcessedRecord { }
// Components that work with data
struct Database {}
struct Config {}
struct Random {}
struct Processor {}
impl Database {
fn get_input(&mut self, job_id: u64) -> Result<Record> {unimplemented!()}
fn save_output(&mut self, out: &ProcessedRecord) -> Result<()> {unimplemented!()}
}
impl Config {
fn get_parameter(&self, property: u32) -> Parameter {unimplemented!()}
}
impl Random {
fn get_rnd(&mut self) -> f64 {unimplemented!()}
}
impl Processor {
fn do_lengthy_processing(record: &Record, param: Parameter, rnd: f64) -> ProcessedRecord {unimplemented!()}
}
// This brings together the components to do work.
// Assume the components are already sufficiently tested, individually.
struct Plumbing {
config: Config,
database: Database,
random: Random,
}
impl Plumbing {
fn do_work(&mut self, job_id: u64) -> Result<ProcessedRecord> {
//
// Objective is to test this code which joins everything together.
//
let record = self.database.get_input(job_id)?;
let parameter = self.config.get_parameter(record.property);
let randomness = self.random.get_rnd();
let processed = Processor::do_lengthy_processing(&record, parameter, randomness);
Ok(processed)
}
}
// In reality there wouldn't be a main here. The `do_work` call
// below would be a dependency by some other part of my program,
// which would also need testing. In other words, this isn't the
// 'top' of the application.
fn main() -> Result<()> {
let mut plumbing = Plumbing {
config: Config {},
database: Database {},
random: Random {},
};
let job_id = 1000;
let output = plumbing.do_work(job_id)?;
println!("Result of job {} is {:?}", job_id, output);
Ok(())
}
//
// This is the best solution for testing the Plumbing that I've come up with so far
//
// Separate the operations from their concrete implementations
#[cfg_attr(test, mockall::automock)]
trait Operations {
fn get_input(&mut self, job_id: u64) -> Result<Record>;
fn save_output(&mut self, out: &ProcessedRecord) -> Result<()>;
fn get_parameter(&self, property: u32) -> Parameter;
fn get_rnd(&mut self) -> f64;
fn slow_process(&mut self, record: &Record, parameter: Parameter, randomness: f64) -> ProcessedRecord;
}
struct ConcreteDependencies {
config: Config,
database: Database,
random: Random,
}
impl Operations for ConcreteDependencies {
// This is annoying to type out when there's lots of it ...
// Slight worry that unnecessary calling of functions will have performance cost?
fn get_input(&mut self, job_id: u64) -> Result<Record> {
self.database.get_input(job_id)
}
fn save_output(&mut self, out: &ProcessedRecord) -> Result<()> {
self.database.save_output(out)
}
fn get_parameter(&self, property: u32) -> Parameter {
self.config.get_parameter(property)
}
fn get_rnd(&mut self) -> f64 {
self.random.get_rnd()
}
fn slow_process(&mut self, record: &Record, parameter: Parameter, randomness: f64) -> ProcessedRecord {
Processor::do_lengthy_processing(record, parameter, randomness)
}
}
struct TestablePlumbing {}
impl TestablePlumbing {
// impl trait to use specialisation rather than dyn, may be
// faster if `do_work` is called a lot?
fn do_work(job_id: u64, deps: &mut impl Operations) -> Result<ProcessedRecord> {
let record = deps.get_input(job_id)?;
let parameter = deps.get_parameter(record.property);
let randomness = deps.get_rnd();
let processed = deps.slow_process(&record, parameter, randomness);
Ok(processed)
}
}
// The main (caller) looks same as it did before ...
fn new_main() -> Result<()> {
let mut dependencies = ConcreteDependencies {
config: Config {},
database: Database {},
random: Random {},
};
let job_id = 1000;
let output = TestablePlumbing::do_work(job_id, &mut dependencies)?;
println!("Result of job {} is {:?}", job_id, output);
Ok(())
}
// ... but now we can test 'do_work".
#[cfg(test)]
mod tests {
use super::*;
use mockall::predicate::*;
#[test]
fn test_wiring() {
let mut mock_ops = MockOperations::new();
mock_ops.expect_get_input()
.with(eq(1000))
.return_once(|_| Ok(Record { property: 42}));
mock_ops.expect_get_parameter()
.with(eq(42))
.return_once(|_| Parameter {} );
mock_ops.expect_get_rnd()
.returning(|| 0.923);
let expected_result = ProcessedRecord {};
let cloned_result = expected_result.clone();
mock_ops.expect_slow_process()
.with(
eq(Record { property: 42 }),
eq(Parameter {}),
eq(0.923 )
)
.return_once(|_,_,_| cloned_result);
assert_eq!(
expected_result,
TestablePlumbing::do_work(1000, &mut mock_ops).unwrap()
)
}
}
| true |
fe622d6dd3d8b91f4a2a34e74fe425c2e3e50967
|
Rust
|
Geal/rustmu
|
/net.rs
|
UTF-8
| 8,506 | 2.953125 | 3 |
[] |
no_license
|
use std::comm::{Port, Chan, Select};
use std::io;
use std::io::{Acceptor, Listener, IoResult};
use std::io::net::tcp::{TcpListener, TcpStream};
use std::io::net::ip::{SocketAddr, Ipv4Addr};
use std::str;
use std::task;
use std::vec;
mod telnet;
#[deriving(Eq)]
pub enum ID {
Unassigned,
Unconnected(uint),
Connected(uint)
}
impl ID {
fn get(&self) -> uint {
match *self {
Unassigned => fail!("Attempted to unwrap an unassigned ID."),
Unconnected(x) => return x,
Connected(x) => return x
}
}
}
pub enum Command {
ShutDownComplete,
TelnetCommand(ID, telnet::Command),
PlayerString(ID, ~str)
}
pub enum Response {
ShutDown,
NewConnection(Connection),
Disconnect(ID),
BroadCast(~str),
MultiCast(~[ID], ~str),
UniCast(ID, ~str),
Nothing
}
struct Connection {
id : ID,
port : Port<Option<~str>>,
chan : Chan<Option<~str>>
}
impl Drop for Connection {
fn drop(&mut self) {
self.chan.try_send(None);
}
}
impl Connection {
fn new(stream : TcpStream) -> Connection
{
let (clientPort, chan) = Chan::new();
let (port, clientChan) = Chan::new();
let writeStream = stream.clone();
let mut builder = task::task();
builder.name("<generic_client_writer>");
builder.spawn(proc(){clientWriteEntry(writeStream, clientPort)});
builder = task::task();
builder.name("<generic_client_reader>");
builder.spawn(proc(){clientReadEntry(stream, clientChan)});
Connection{id : Unassigned, port : port, chan : chan}
}
}
pub fn netEntry(mut mainPort : Port<Response>, mainChan : Chan<Command>)
{
let (mut listenPort, listenChan) = Chan::new();
let mut connections = ~[];
let mut builder = task::task();
builder.name("listener");
builder.spawn(proc(){listenEntry(listenChan)});
loop {
let maybeCommand = handleResponse(doSelect(&mut mainPort, &mut listenPort, &mainChan, connections), &mut connections);
match maybeCommand {
Some(command) => mainChan.send(command),
None => ()
}
}
}
fn clientReadEntry(mut stream : TcpStream, chan : Chan<Option<~str>>)
{
let mut read_buffer = [0, ..128];
let mut utf8_buffer = ~[];
loop{
match checkIoResult(stream.read(read_buffer), [io::EndOfFile]) {
Some(_) => utf8_buffer = vec::append(utf8_buffer, read_buffer),
None => {chan.send(None); return}
}
let telnet_commands = telnet::parse(&mut utf8_buffer);
for x in telnet_commands.iter() {
match *x {
telnet::Will(option) => {
println!("Will({})", option);
if checkIoResult(telnet::send(&mut stream, telnet::Dont(option)), [io::EndOfFile]).is_none() {
chan.send(None);
return
}
}
telnet::Wont(option) => println!("Wont({})", option),
telnet::Do(option) => {
println!("Do({})", option);
if checkIoResult(telnet::send(&mut stream, telnet::Wont(option)), [io::EndOfFile]).is_none() {
chan.send(None);
return
}
}
telnet::Dont(option) => println!("Dont({})", option),
telnet::Other(option) => println!("Other({})", option),
telnet::Malformed => {println!("Malformed telnet command."); chan.send(None); return}
}
}
let maybeStr = str::from_utf8(utf8_buffer);
if maybeStr.is_some() {
chan.send(Some(maybeStr.unwrap().to_owned()));
}
}
}
fn clientWriteEntry(mut stream : TcpStream, port : Port<Option<~str>>)
{
loop{
let message = port.recv();
match message {
Some(string) => {
let bytes = string.into_bytes();
if checkIoResult(stream.write(bytes), [io::EndOfFile]).is_none() {
return;
}
if checkIoResult(telnet::send(&mut stream, telnet::Other(telnet::GA as u8)), [io::EndOfFile]).is_none() {
return;
}
}
None => return
}
}
}
fn listenEntry(chan : Chan<TcpStream>)
{
let mut acceptor = TcpListener::bind(
SocketAddr{
ip : Ipv4Addr(0, 0, 0, 0), port : 6666
})
.ok().expect("Failed to unwrap listen Port after bind()")
.listen()
.ok().expect("Failed to unwrap listen port after listen()");
loop {
let newConnection = acceptor.accept();
match newConnection {
Ok(TcpStream) => chan.send(TcpStream),
Err(error) => fail!("Failure on accept() call: {}", error)
}
}
}
fn doSelect(mainPort : &mut Port<Response>, listenPort : &mut Port<TcpStream>,
mainChan : &Chan<Command>, connections : &mut [Option<Connection>])
-> Response
{
let sel = Select::new();
let mut mainHandle = sel.handle(mainPort);
let mut listenHandle = sel.handle(listenPort);
let mut handles = ~[];
for x in connections.mut_iter() {
match *x {
Some(ref mut connection) => handles.push((connection.id, sel.handle(&mut connection.port))),
None => ()
}
}
unsafe {
mainHandle.add();
listenHandle.add();
for &(_, ref mut x) in handles.mut_iter() {
x.add()
}
}
let ret = sel.wait();
if ret == mainHandle.id() {
return mainHandle.recv();
}
else if ret == listenHandle.id() {
let stream = listenHandle.recv();
return NewConnection(Connection::new(stream))
}
else {
for &(playerID, ref mut handle) in handles.mut_iter() {
if ret == handle.id() {
match handle.recv() {
Some(string) => {mainChan.send(PlayerString(playerID, string)); return Nothing}
None => return Disconnect(playerID)
}
}
}
}
fail!("Select returned a handles that does not exist!");
}
fn handleResponse(reponse : Response, connections : &mut ~[Option<Connection>]) -> Option<Command>
{
match reponse {
ShutDown => {
for x in connections.mut_iter() {
*x = None
}
return Some(ShutDownComplete);
}
NewConnection(mut connection) => {
let mut locationFound = false;
for (num, x) in connections.iter().enumerate() {
if !x.is_some() {
connection.id = Unconnected(num);
locationFound = true;
break;
}
}
if locationFound {
let location = connection.id.get();
connections[location] = Some(connection);
} else {
connections.push(Some(connection));
}
}
Disconnect(id) => {
for x in connections.mut_iter() {
if x.as_ref().map_or(false, |c| c.id == id) {
*x = None
}
}
}
BroadCast(string) => {
for x in connections.iter().flat_map(|o| o.iter()) {
x.chan.send(Some(string.clone()));
}
}
MultiCast(ids, string) => {
for id in ids.iter() {
for x in connections.iter().flat_map(|o| o.iter()) {
if x.id == *id {
x.chan.send(Some(string.clone()));
}
}
}
}
UniCast(id, string) => {
for x in connections.iter().flat_map(|o| o.iter()) {
if x.id == id {
x.chan.send(Some(string.clone()))
}
}
}
Nothing => ()
}
return None
}
fn checkIoResult<T>(result : IoResult<T>, kinds : &[io::IoErrorKind]) -> Option<T> {
match result {
Ok(x) => Some(x),
Err(what) => {
for x in kinds.iter() {
if what.kind == *x {
return None;
}
}
fail!("IoResult resulted in a failure with with {}", what)
}
}
}
| true |
fe68d73a2e4d7468b956bdccfbc19ca59105d47e
|
Rust
|
kernelmethod/libfixers
|
/src/wasm.rs
|
UTF-8
| 4,360 | 2.96875 | 3 |
[
"MIT",
"LicenseRef-scancode-warranty-disclaimer"
] |
permissive
|
//! WebAssembly bindings for the `libfixers` crate.
use crate::{
exif::{self, IFDDataContents, IFDDataFormat, IFDTag},
JPEGFile,
};
use base64;
use std::convert::TryFrom;
use wasm_bindgen::prelude::*;
/// Perform some preprocessing on the IFD entries extracted by the Exif parser so that they're
/// easier to display in the browser.
fn preprocess_ifd_entries(entries: &mut [exif::IFDEntry]) {
for e in entries.iter_mut() {
match (e.data_format, e.tagtype) {
// Convert XResolution and YResolution to strings of the form "X:Y"
(_, IFDTag::XResolution) | (_, IFDTag::YResolution) => {
e.content = e
.content
.iter_mut()
.map(|x| match x {
IFDDataContents::UnsignedRational(x, y) => {
IFDDataContents::AsciiString(format!("{}:{}", x, y))
}
x => x.to_owned(),
})
.collect();
}
// Convert GPS coordinates to a single floating point value
(_, IFDTag::GPSLatitude) | (_, IFDTag::GPSLongitude) => {
let coords: Result<Vec<_>, _> =
e.content.iter().map(|x| f64::try_from(x)).collect();
match coords {
Ok(coords) => {
if coords.len() != 3 {
continue;
}
let (degrees, minutes, seconds) = (coords[0], coords[1], coords[2]);
let loc = exif::gps::degrees_to_decimal(degrees, minutes, seconds);
// We round to six decimal places before returning the coordinate
let loc = (loc * 1e6).round() / 1e6;
e.content = vec![IFDDataContents::DoubleFloat(loc)];
}
_ => {}
}
}
// Convert all other rational datatypes to floating point
(IFDDataFormat::UnsignedRational, _) | (IFDDataFormat::SignedRational, _) => {
e.content = e
.content
.iter_mut()
.map(|x| match x {
IFDDataContents::UnsignedRational(x, y) => {
IFDDataContents::DoubleFloat((*x as f64) / (*y as f64))
}
IFDDataContents::SignedRational(x, y) => {
IFDDataContents::DoubleFloat((*x as f64) / (*y as f64))
}
x => x.to_owned(),
})
.collect();
}
// Do nothing for remaining unmatched tags / data types
_ => {}
}
}
}
/// Parse a JPEG file and return the Exif metadata stored in the image.
#[wasm_bindgen]
pub fn extract_exif_data(i: &[u8]) -> Result<JsValue, JsValue> {
match JPEGFile::parse(i) {
Ok((_, img)) => {
// Try to extract Exif data, if we can find any
let mut exif_entries = img.exif_metadata();
if exif_entries.len() == 0 {
Err(JsValue::from_str("No Exif data was found in the image"))
} else {
preprocess_ifd_entries(&mut exif_entries);
match JsValue::from_serde(&exif_entries) {
Ok(v) => Ok(v),
Err(_) => Err(JsValue::from_str("Unable to convert result to JSON!")),
}
}
}
Err(nom::Err::Failure(e)) | Err(nom::Err::Error(e)) => {
// Convert e into a format that makes it a little easier to read
let err = e
.errors
.iter()
.map(|err| match err {
(_, nom::error::VerboseErrorKind::Context(e)) => format!("{}", e),
(_, e) => format!("{:?}", e),
})
.rev()
.fold("JPEGFile::parse".to_string(), |acc, x| {
format!("{} => {}", acc, x)
});
let msg = format!("Unable to parse image: Error: {}", err);
Err(JsValue::from_str(&msg))
}
_ => Err(JsValue::from_str("Unkown fatal error")),
}
}
| true |
aefa4d2aad2c0a181eb68a14a7bc19e78a533ca6
|
Rust
|
SimonOsaka/my_adventures_api
|
/src/domain/tests/helpers/generate.rs
|
UTF-8
| 861 | 2.796875 | 3 |
[
"MIT"
] |
permissive
|
//! Functions for generating test data
use fake::fake;
pub enum With<T> {
Value(T),
Random,
}
pub fn article_content() -> realworld_domain::ArticleContent {
realworld_domain::ArticleContent {
title: fake!(Lorem.sentence(4, 10)).to_string(),
description: fake!(Lorem.paragraph(3, 10)),
body: fake!(Lorem.paragraph(10, 5)),
tag_list: vec![fake!(Lorem.word).to_string()],
}
}
pub fn new_user() -> (realworld_domain::SignUp, String) {
let password = fake!(Lorem.word).to_string();
let sign_up = realworld_domain::SignUp {
username: fake!(Internet.user_name).to_string(),
email: fake!(Internet.free_email).to_string(),
password: realworld_domain::Password::from_clear_text(password.clone())
.expect("Failed to hash password"),
};
(sign_up, password)
}
| true |
65cb6ff54829559728b3df4fe8114c2be9198d1b
|
Rust
|
isgasho/ligen
|
/src/ir/project/arguments.rs
|
UTF-8
| 1,420 | 2.734375 | 3 |
[
"Apache-2.0"
] |
permissive
|
//! Arguments definition module.
use crate::prelude::*;
use crate::generator::BuildType;
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
/// Arguments passed from `cargo-ligen`.
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct Arguments {
/// The name of the crate
pub crate_name: String,
/// The build type.
pub build_type: BuildType,
/// The build target directory passed with `--target-dir`.
pub target_dir: PathBuf,
/// The Cargo.toml manifest path passed with `--manifest-path`.
pub manifest_path: PathBuf,
/// The Cargo.toml workspace manifest.
pub workspace_path: Option<PathBuf>,
/// Workspace member to build passed with `--package` or `-p`.
pub workspace_member_package_id: Option<String>,
}
impl Arguments {
/// Generates a JSON representation of Arguments in CARGO_LIGEN_ARGUMENTS.
pub fn to_env(&self) -> Result<()> {
let json = serde_json::to_string(self)?;
Ok(std::env::set_var("CARGO_LIGEN_ARGUMENTS", json))
}
/// Parses the JSON representation from CARGO_LIGEN_ARGUMENTS.
pub fn from_env() -> Result<Self> {
let json_string = std::env::var("CARGO_LIGEN_ARGUMENTS")?;
let mut arguments: Self = serde_json::from_str(&json_string)?;
arguments.manifest_path = Path::new(&std::env::var("CARGO_MANIFEST_DIR")?).to_path_buf();
Ok(arguments)
}
}
| true |
9bc3de9abd4a6fa7bf739a0c9be89c630d5acbed
|
Rust
|
kofj/font2png
|
/src/main.rs
|
UTF-8
| 2,844 | 2.875 | 3 |
[] |
no_license
|
use colors_transform::{Color, Rgb};
use image::{Rgba, RgbaImage};
use imageproc::drawing::draw_text_mut;
use rusttype::{Font, Scale};
use std::path::Path;
use std::vec::Vec;
use structopt::StructOpt;
#[derive(StructOpt, Debug)]
#[structopt(
name = "font2img",
version = "v1.0.0",
about = "A tool for converting TTF icon font to images.\n\n\
example: \n\
\tfont2png --charter $(printf '\\ue957') -s 80 -f a -o src/assets/on/user.png -c \"#d43c33\"\n\
",
author = "Fanjiankong <[email protected]>"
)]
struct Options {
#[structopt(short = "f", long = "font", required = true, help = "font file path")]
fontpath: String,
#[structopt(
short = "o",
long = "output",
required = true,
help = "output filename"
)]
output: String,
#[structopt(
// short = "i",
long = "charter",
required = true,
// default_value = "\u{e966}",
help = "icon charter"
)]
charter: String,
#[structopt(short = "t", long = "transparent", help = "transparent background")]
transparent: bool,
#[structopt(short = "c", long = "color", help = "icon css style color")]
color: String,
#[structopt(
short = "s",
long = "size",
default_value = "78",
help = "output image's height and width(pixel)"
)]
size: u16,
#[structopt(
short = "S",
long = "iconsize",
default_value = "54",
help = "icon's height and width(pixel)"
)]
iconsize: f32,
}
fn main() {
let options = Options::from_args();
println!("{:?}", options);
let output_path = Path::new(&options.output);
let mut image = RgbaImage::new(options.size as u32, options.size as u32);
let fontbytes = Vec::from(include_bytes!("icon.ttf") as &[u8]);
let size = fontbytes.len();
let font = Font::try_from_vec(fontbytes).unwrap();
println!("font file size: {}, count={}", size, font.glyph_count());
let scale = Scale {
x: options.iconsize,
y: options.iconsize,
};
let offset: u32 = ((options.size - options.iconsize as u16) / 2) as u32;
let color = Rgb::from_hex_str(&options.color).unwrap();
println!(
"color: {:?}, rgb=({},{},{})",
color,
color.get_red(),
color.get_green(),
color.get_blue(),
);
draw_text_mut(
&mut image,
Rgba([
color.get_red() as u8,
color.get_green() as u8,
color.get_blue() as u8,
255u8,
// 0u8,
]),
offset,
offset,
scale,
&font,
&options.charter,
);
// let (w, h) = text_size(scale, &font, text);
// println!("Text size: {}x{}", w, h);
println!("save to {}", options.output);
let _ = image.save(output_path).unwrap();
}
| true |
a4655b6edf345b89e9265b08fecc3ee5a2cdee69
|
Rust
|
BurraAbhishek/page_replacement_algorithms_demo.rs
|
/src/page.rs
|
UTF-8
| 2,282 | 3.703125 | 4 |
[
"MIT"
] |
permissive
|
#[path = "input.rs"]
mod input;
use input as other_input;
pub struct Page {
pub page_string: Vec<String>,
}
impl Default for Page {
fn default() -> Page {
Page {
page_string: Vec::<String>::new(),
}
}
}
impl Page {
fn sequentially(mut self) -> Page {
println!("Enter the page reference string. Separation will be done character-wise");
let sequence = other_input::input();
let collected = sequence.chars();
for s in collected {
let newstr = String::from(s);
self.page_string.push(newstr);
}
return self;
}
fn commaseparated(mut self) -> Page {
println!("Enter the page reference string. Separation will be done by commas");
let sequence = other_input::input();
let cleansequence = sequence.split(",");
let collected: Vec<&str> = cleansequence.collect();
for s in collected {
let newstr = String::from(s);
let trimmed = newstr.trim();
self.page_string.push(String::from(trimmed));
}
return self;
}
fn linebyline(mut self) -> Page {
println!("Enter the page reference string line-by-line. To stop, just use Enter.");
loop {
let inserted: String = other_input::input();
if inserted.len() == 1 {
break;
}
self.page_string.push(inserted);
}
return self;
}
pub fn generate(self) -> Page {
println!("Choose any of the below options: ");
println!("0: Enter the page reference string sequentially (Example: 102341)");
println!("1: Enter the comma-separated page reference string (Example: 1, 0, 2, 3, 4, 1)");
println!("2: Enter the page reference string one after the other");
let choice = other_input::input_u8();
match choice {
0 => self.sequentially(),
1 => self.commaseparated(),
2 => self.linebyline(),
3..=255 => panic!("Invalid choice"),
}
}
pub fn get_page_string(self) -> Vec<String> {
return self.page_string;
}
pub fn _display(self) {
for i in self.page_string {
println!("{}", i);
}
}
}
| true |
f831cfacefdba95ce8bdc62b421e4b3e79bb6705
|
Rust
|
keeperofdakeys/asn1-rs
|
/asn1-utils/src/ber-json-decode.rs
|
UTF-8
| 3,405 | 2.53125 | 3 |
[
"Apache-2.0",
"MIT"
] |
permissive
|
extern crate asn1_cereal;
extern crate argparse;
extern crate serde_json;
use asn1_cereal::{tag, byte};
use asn1_cereal::ber::stream;
use std::io;
use std::io::Read;
use std::fs;
use std::path::Path;
use std::collections::BTreeMap;
use argparse::{ArgumentParser, StoreTrue, StoreOption};
use serde_json::value::Value;
use serde_json::ser::to_string_pretty;
fn main() {
let opts = parse_args();
let path = Path::new(opts.file.as_ref().unwrap());
// Create a buffered reader from the file.
let reader = io::BufReader::new(fs::File::open(path).unwrap()).bytes();
let mut dumper = StreamDumper::new();
{
let mut decoder = stream::StreamDecoder::new(reader, &mut dumper);
decoder.decode().unwrap();
}
println!("{}", to_string_pretty(&dumper.stack.last().unwrap().last().unwrap()).unwrap());
}
struct StreamDumper {
pub stack: Vec<Vec<Value>>,
elem: Option<Value>,
}
impl StreamDumper {
fn new() -> Self {
StreamDumper {
stack: vec![Vec::new()],
elem: None,
}
}
}
impl stream::StreamDecodee for StreamDumper {
fn start_element(&mut self, tag: tag::Tag, _: tag::Len) -> stream::ParseResult {
if tag.constructed {
self.stack.push(Vec::new());
}
stream::ParseResult::Ok
}
fn end_element(&mut self, tag: tag::Tag, len: tag::Len) -> stream::ParseResult {
let mut tag_map = BTreeMap::new();
let mut map = BTreeMap::new();
tag_map.insert(
"class",
match tag.class {
tag::Class::Application => "application",
tag::Class::Universal => "universal",
tag::Class::Private => "private",
tag::Class::ContextSpecific => "context",
}.to_owned(),
);
if let tag::Len::Def(ref l) = len {
tag_map.insert("length", l.to_string());
}
tag_map.insert("num", tag.tagnum.to_string());
tag_map.insert("constructed", tag.constructed.to_string());
map.insert("tag", serde_json::to_value(&tag_map));
if tag.constructed {
map.insert("elements", serde_json::to_value(&self.stack.pop().unwrap()));
} else {
if self.elem.is_some() {
map.insert("bytes", self.elem.as_ref().unwrap().clone());
self.elem = None;
} else {
panic!("No primitive element found");
}
}
self.stack.last_mut().unwrap().push(serde_json::to_value(&map));
stream::ParseResult::Ok
}
fn primitive<I: Iterator<Item=io::Result<u8>>>(&mut self, reader: &mut byte::ByteReader<I>, len: tag::LenNum) ->
stream::ParseResult {
if self.elem.is_some() {
panic!("elem should not be defined already!");
}
let mut bytes = String::new();
// Extract contents
for _ in 0..len {
let byte = match reader.read() {
Ok(b) => b,
Err(e) => return e.into(),
};
bytes.push_str(&format!("{:x}", byte));
}
self.elem = Some(serde_json::to_value(&bytes));
stream::ParseResult::Ok
}
}
struct ProgOpts {
file: Option<String>,
verbose: bool,
}
fn parse_args() -> ProgOpts {
let mut opts = ProgOpts {
file: None,
verbose: false,
};
{
let mut ap = ArgumentParser::new();
ap.set_description("Decode ASN.1 files");
ap.refer(&mut opts.verbose)
.add_option(&["-v", "--verbose"], StoreTrue, "Verbose output");
ap.refer(&mut opts.file)
.add_argument("file", StoreOption, "ASN.1 file to decode");
ap.parse_args_or_exit();
}
opts
}
| true |
40cbc492a177544b4bcb5684db89cdbeeb964008
|
Rust
|
reem/rust-http2parse
|
/src/lib.rs
|
UTF-8
| 3,599 | 2.734375 | 3 |
[
"MIT"
] |
permissive
|
#![cfg_attr(test, deny(warnings))]
#![cfg_attr(test, feature(test))]
#![allow(non_upper_case_globals)]
// #![deny(missing_docs)]
//! # http2parse
//!
//! An HTTP2 frame parser.
//!
#[macro_use]
extern crate bitflags;
extern crate byteorder;
#[cfg(test)]
extern crate test;
#[cfg(any(test, feature = "random"))]
extern crate rand;
const FRAME_HEADER_BYTES: usize = 9;
pub use kind::Kind;
pub use flag::Flag;
pub use frame::{Frame, FrameHeader};
pub use payload::{Payload, Priority, Setting, SettingIdentifier};
use byteorder::ByteOrder;
mod kind;
mod flag;
mod payload;
mod frame;
/// Errors that can occur during parsing an HTTP/2 frame.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub enum Error {
/// A full frame header was not passed.
Short,
/// An unsupported value was set for the flag value.
BadFlag(u8),
/// An unsupported value was set for the frame kind.
BadKind(u8),
/// The padding length was larger than the frame-header-specified
/// length of the payload.
TooMuchPadding(u8),
/// The payload length specified by the frame header was shorter than
/// necessary for the parser settings specified and the frame type.
///
/// This happens if, for instance, the priority flag is set and the
/// header length is shorter than a stream dependency.
///
/// `PayloadLengthTooShort` should be treated as a protocol error.
PayloadLengthTooShort,
/// The payload length specified by the frame header of a settings frame
/// was not a round multiple of the size of a single setting.
PartialSettingLength,
/// The payload length specified by the frame header was not the
/// value necessary for the specific frame type.
InvalidPayloadLength
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
struct ParserSettings {
padding: bool,
priority: bool
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub struct StreamIdentifier(pub u32);
impl StreamIdentifier {
pub fn parse(buf: &[u8]) -> StreamIdentifier {
StreamIdentifier(
byteorder::BigEndian::read_u32(buf) & ((1 << 31) - 1)
)
}
pub fn encode(&self, buf: &mut [u8]) -> usize {
encode_u32(buf, self.0)
}
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub struct ErrorCode(pub u32);
pub enum HttpError {
Protocol,
Internal,
FlowControlError,
SettingsTimeout,
}
impl ErrorCode {
pub fn parse(buf: &[u8]) -> ErrorCode {
ErrorCode(byteorder::BigEndian::read_u32(buf))
}
pub fn encode(&self, buf: &mut [u8]) -> usize {
encode_u32(buf, self.0)
}
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub struct SizeIncrement(pub u32);
impl SizeIncrement {
pub fn parse(buf: &[u8]) -> SizeIncrement {
SizeIncrement(byteorder::BigEndian::read_u32(buf))
}
pub fn encode(&self, buf: &mut [u8]) -> usize {
encode_u32(buf, self.0)
}
}
#[inline(always)]
fn encode_u24(buf: &mut [u8], val: u32) -> usize {
buf[0] = (val >> 16) as u8;
buf[1] = (val >> 8) as u8;
buf[2] = val as u8;
3
}
#[inline(always)]
fn encode_u32(buf: &mut [u8], val: u32) -> usize {
byteorder::BigEndian::write_u32(buf, val);
4
}
#[inline(always)]
fn encode_u64(buf: &mut [u8], val: u64) -> usize {
byteorder::BigEndian::write_u64(buf, val);
8
}
#[test]
fn test_stream_id_ignores_highest_bit() {
let raw1 = [0x7F, 0xFF, 0xFF, 0xFF];
let raw2 = [0xFF, 0xFF, 0xFF, 0xFF];
assert_eq!(
StreamIdentifier::parse(&raw1),
StreamIdentifier::parse(&raw2));
}
| true |
d978ce655172123479dc43664f65534929e66a62
|
Rust
|
purposed/binman
|
/src/binlib/state.rs
|
UTF-8
| 3,301 | 3.078125 | 3 |
[
"MIT"
] |
permissive
|
use std::collections::{HashMap, HashSet};
use std::fs;
use std::io::{BufWriter, Write};
use std::ops::Add;
use std::path::Path;
use anyhow::{ensure, Result};
use semver::Version;
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct StateEntry {
pub name: String,
pub artifacts: Vec<String>,
pub url: String,
pub version: Version,
}
pub struct State {
path: String,
internal_data: HashMap<String, StateEntry>,
}
impl State {
pub fn new(path: &str) -> Result<State> {
let mut s = State {
path: String::from(path),
internal_data: HashMap::new(),
};
s.acquire_lock()?;
s.refresh()?;
Ok(s)
}
fn acquire_lock(&self) -> Result<()> {
let lock_str = self.path.clone().add(".lock");
let lock_path = Path::new(&lock_str);
ensure!(!lock_path.exists(), "Lock is already acquired");
let mut file_handle = fs::File::create(lock_path)?;
file_handle.write_all(b"lock")?;
Ok(())
}
fn release_lock(&self) -> Result<()> {
let lock_str = self.path.clone().add(".lock");
let lock_path = Path::new(&lock_str);
ensure!(lock_path.exists(), "Attempted to release a free lock");
fs::remove_file(lock_path)?;
Ok(())
}
fn refresh(&mut self) -> Result<()> {
self.internal_data = HashMap::new();
if let Ok(contents) = fs::read_to_string(&self.path) {
if let Ok(internal_data) = serde_json::from_str(&contents) {
self.internal_data = internal_data;
}
}
Ok(())
}
pub fn get(&self, name: &str) -> Option<&StateEntry> {
self.internal_data.get(name)
}
pub fn get_copy(&self, name: &str) -> Option<StateEntry> {
self.internal_data.get(name).cloned()
}
pub fn list(&self) -> Vec<&StateEntry> {
self.internal_data.iter().map(|(_, v)| v).collect()
}
pub fn insert(&mut self, mut entry: StateEntry) -> Result<()> {
// Will throw if entry already exists.
ensure!(
!self.internal_data.contains_key(&entry.name),
"Target {} already in state",
&entry.name
);
// De-duplicate entry artifacts.
let mut v = Vec::new();
let mut hsh = HashSet::new();
for itm in entry.artifacts.into_iter() {
if !hsh.contains(&itm) {
hsh.insert(itm.clone());
v.push(itm);
}
}
entry.artifacts = v;
self.internal_data.insert(entry.name.clone(), entry);
self.save()
}
fn save(&self) -> Result<()> {
let file_handle = fs::File::create(&self.path)?;
serde_json::to_writer(BufWriter::new(file_handle), &self.internal_data)?;
Ok(())
}
pub fn remove(&mut self, entry_name: &str) -> Result<()> {
if self.internal_data.contains_key(entry_name) {
self.internal_data.remove(entry_name);
self.save()?
}
Ok(())
}
}
impl Drop for State {
fn drop(&mut self) {
match self.release_lock() {
Ok(_) => {}
Err(e) => {
eprintln!("{}", e);
}
}
}
}
| true |
fe63bc6733d8299730b65a210e330d1086c742ce
|
Rust
|
johnyenter-briars/gentle_intro_to_rust
|
/structs_enums_matching/enums1.rs
|
UTF-8
| 911 | 3.640625 | 4 |
[] |
no_license
|
#[derive(Debug,PartialEq)]
enum Direction {
Up,
Down,
Left,
Right
}
impl Direction {
fn as_str(&self) -> &'static str {
//normally we dont need the dereference pointer
//normally rust can asume self.first_name without (*self).first_name
match *self { //*self has type Direction
Direction::Up => "Up",
Direction::Down => "Down",
Direction::Left => "Left",
Direction::Right => "Right"
}
}
fn next(&self) -> Direction {
use Direction::*;
match *self { //*self has type Direction
Direction::Up => Direction::Right,
Direction::Down => Direction::Left,
Direction::Left => Direction::Up,
Direction::Right => Direction::Down
}
}
}
fn main() {
let start = Direction::Left;
println!("start {:?}", start.as_str()); //note as_str does not allocate
assert_eq!(start, Direction::Left);
let mut d = start;
for _ in 0..8 {
println!("d : {:?}", d);
d = d.next();
}
}
| true |
3a0ec20970670fb516dda983bd4f852eff7c79a4
|
Rust
|
vext01/yk_pv
|
/ykutil/src/addr.rs
|
UTF-8
| 7,978 | 2.703125 | 3 |
[
"MIT",
"Apache-2.0"
] |
permissive
|
//! Address utilities.
use crate::obj::{PHDR_OBJECT_CACHE, SELF_BIN_PATH};
use cached::proc_macro::cached;
use libc::{self, c_void, Dl_info};
use std::mem::MaybeUninit;
use std::{
convert::{From, TryFrom},
ffi::CStr,
path::{Path, PathBuf},
};
/// A Rust wrapper around `libc::Dl_info` using FFI types.
///
/// The strings inside are handed out by the loader and can (for now, since we don't support
/// dlclose) be considered of static lifetime. This makes the struct thread safe, and thus
/// cacheable using `#[cached]`.
#[derive(Debug, Clone)]
pub struct DLInfo {
dli_fname: Option<&'static CStr>,
dli_fbase: usize,
dli_sname: Option<&'static CStr>,
dli_saddr: usize,
}
impl From<Dl_info> for DLInfo {
fn from(dli: Dl_info) -> Self {
let dli_fname = if !dli.dli_fname.is_null() {
Some(unsafe { CStr::from_ptr(dli.dli_fname) })
} else {
None
};
let dli_sname = if !dli.dli_sname.is_null() {
Some(unsafe { CStr::from_ptr(dli.dli_sname) })
} else {
None
};
Self {
dli_fname,
dli_fbase: dli.dli_fbase as usize,
dli_sname,
dli_saddr: dli.dli_saddr as usize,
}
}
}
impl DLInfo {
pub fn dli_fname(&self) -> Option<&'static CStr> {
self.dli_fname
}
pub fn dli_fbase(&self) -> usize {
self.dli_fbase
}
pub fn dli_sname(&self) -> Option<&'static CStr> {
self.dli_sname
}
pub fn dli_saddr(&self) -> usize {
self.dli_saddr
}
}
/// Wraps `libc::dlinfo`.
///
/// Returns `Err` if the underlying call to `libc::dlddr` fails.
///
/// FIXME: This cache should be invalidated (in part, if possible) when a object is loaded or
/// unloaded from the address space.
///
/// FIXME: Consider using a LRU cache to limit memory consumption. The cached crate can do this for
/// us if we can give it a suitable cache size.
///
/// FIXME: This cache is cloning. Performance could probably be improved more.
#[cached]
pub fn dladdr(vaddr: usize) -> Result<DLInfo, ()> {
let mut info = MaybeUninit::<Dl_info>::uninit();
if unsafe { libc::dladdr(vaddr as *const c_void, info.as_mut_ptr()) } != 0 {
Ok(unsafe { info.assume_init() }.into())
} else {
Err(())
}
}
/// Given a virtual address, returns a pair indicating the object in which the address originated
/// and the byte offset.
pub fn vaddr_to_obj_and_off(vaddr: usize) -> Option<(PathBuf, u64)> {
// Find the object file from which the virtual address was loaded.
let info = dladdr(vaddr).unwrap();
let containing_obj = PathBuf::from(info.dli_fname.unwrap().to_str().unwrap());
// Find the corresponding byte offset of the virtual address in the object.
for obj in PHDR_OBJECT_CACHE.iter() {
let obj_name = obj.name();
let obj_name: &Path = if unsafe { *obj_name.as_ptr() } == 0 {
SELF_BIN_PATH.as_path()
} else {
Path::new(obj_name.to_str().unwrap())
};
if obj_name != containing_obj {
continue;
}
return Some((containing_obj, u64::try_from(vaddr).unwrap() - obj.addr()));
}
None
}
/// Find the virtual address of the offset `off` in the object `containing_obj`.
///
/// Returns `OK(virtual_address)` if a virtual address is found for the object in question,
/// otherwise returns `None`.
///
/// This is fragile and should be avoided if possible. In order for a hit, `containing_obj` must be
/// in the same form as it appears in the program header table. This function makes no attempt to
/// canonicalise equivalent, but different (in terms of string equality) object paths.
pub fn off_to_vaddr(containing_obj: &Path, off: u64) -> Option<usize> {
for obj in PHDR_OBJECT_CACHE.iter() {
if Path::new(obj.name().to_str().unwrap()) != containing_obj {
continue;
}
return Some(usize::try_from(off + obj.addr()).unwrap());
}
None // Not found.
}
/// Given a virtual address in the current address space, (if possible) determine the name of the
/// symbol this belongs to, and the path to the object from which it came.
///
/// On success returns `Ok` with a `SymbolInObject`, or on failure `Err(())`.
///
/// This function uses `dladdr()` internally, and thus inherits the same symbol visibility rules
/// used there. For example, this function will not find unexported symbols.
pub fn vaddr_to_sym_and_obj(vaddr: usize) -> Option<DLInfo> {
// `dladdr()` returns success if at least the virtual address could be mapped to an object
// file, but here it is crucial that we can also find the symbol that the address belongs to.
match dladdr(vaddr) {
Ok(x) if x.dli_sname().is_some() => Some(x),
Ok(_) | Err(()) => None,
}
}
#[cfg(test)]
mod tests {
use super::{off_to_vaddr, vaddr_to_obj_and_off, vaddr_to_sym_and_obj, MaybeUninit};
use crate::obj::PHDR_MAIN_OBJ;
use libc::{self, dlsym, Dl_info};
use std::{ffi::CString, path::PathBuf, ptr};
#[test]
fn map_libc() {
let func = CString::new("getuid").unwrap();
let vaddr = unsafe { dlsym(ptr::null_mut(), func.as_ptr() as *const i8) };
assert_ne!(vaddr, ptr::null_mut());
assert!(vaddr_to_obj_and_off(vaddr as usize).is_some());
}
#[test]
#[no_mangle]
fn map_so() {
let vaddr = vaddr_to_obj_and_off as *const u8;
assert_ne!(vaddr, ptr::null_mut());
assert!(vaddr_to_obj_and_off(vaddr as usize).is_some());
}
/// Check that converting a virtual address (from a shared object) to a file offset and back to
/// a virtual address correctly round-trips.
#[test]
fn round_trip_so() {
let func = CString::new("getuid").unwrap();
let func_vaddr = unsafe { dlsym(ptr::null_mut(), func.as_ptr() as *const i8) };
let mut dlinfo = MaybeUninit::<Dl_info>::uninit();
assert_ne!(unsafe { libc::dladdr(func_vaddr, dlinfo.as_mut_ptr()) }, 0);
let dlinfo = unsafe { dlinfo.assume_init() };
assert_eq!(func_vaddr, dlinfo.dli_saddr);
let (obj, off) = vaddr_to_obj_and_off(func_vaddr as usize).unwrap();
assert_eq!(off_to_vaddr(&obj, off).unwrap(), func_vaddr as usize);
}
/// Check that converting a virtual address (from the main object) to a file offset and back to
/// a virtual address correctly round-trips.
#[no_mangle]
#[test]
fn round_trip_main() {
let func_vaddr = round_trip_main as *const fn();
let (_obj, off) = vaddr_to_obj_and_off(func_vaddr as usize).unwrap();
assert_eq!(
off_to_vaddr(&PHDR_MAIN_OBJ, off).unwrap(),
func_vaddr as usize
);
}
#[test]
fn vaddr_to_sym_and_obj_found() {
// To test this we need an exported symbol with a predictable (i.e. unmangled) name.
use libc::fflush;
let func_vaddr = fflush as *const fn();
let sio = vaddr_to_sym_and_obj(func_vaddr as usize).unwrap();
assert!(matches!(
sio.dli_sname().unwrap().to_str().unwrap(),
"fflush" | "_IO_fflush"
));
let obj_path = PathBuf::from(sio.dli_fname().unwrap().to_str().unwrap());
assert!(obj_path
.file_name()
.unwrap()
.to_str()
.unwrap()
.starts_with("libc.so."));
}
#[test]
fn vaddr_to_sym_and_obj_cant_find_obj() {
let func_vaddr = 1; // Obscure address unlikely to be in any loaded object.
assert!(vaddr_to_sym_and_obj(func_vaddr as usize).is_none());
}
#[test]
fn vaddr_to_sym_and_obj_cant_find_sym() {
// Address valid, but symbol not exported (test bin not built with `-Wl,--export-dynamic`).
let func_vaddr = vaddr_to_sym_and_obj_cant_find_sym as *const fn();
assert!(vaddr_to_sym_and_obj(func_vaddr as usize).is_none());
}
}
| true |
6fd065c3fbc959082d47583bc52e924302841f0c
|
Rust
|
taravancil/passkeeper
|
/src/io.rs
|
UTF-8
| 4,499 | 2.984375 | 3 |
[
"LicenseRef-scancode-warranty-disclaimer"
] |
no_license
|
// std
use std::collections::HashMap;
use std::env;
use std::fs;
use std::io::{ Error, ErrorKind, stdin };
use std::io::prelude::*;
use std::path::{ PathBuf };
// passkeeper
use vault;
// external
extern crate serde;
extern crate serde_json;
/// Creates $HOME/.passkeeper/
pub fn create_passkeeper_dir() -> Result<(), Error> {
let path = env::home_dir().unwrap().join(".passkeeper");
try!(fs::create_dir(path));
Ok(())
}
/// Creates $HOME/.passkeeper/vault
pub fn create_vault() -> Result<fs::File, Error> {
let mut f = try!(fs::File::create(get_vault_path()));
let vault = vault::Vault { sites: HashMap::new() };
let serialized = serde_json::to_string(&vault).unwrap();
try!(f.write_all(&serialized.as_bytes()));
Ok((f))
}
/// Creates $HOME/.passkeeper/data
pub fn create_key_data_file() -> Result<fs::File, Error> {
let path = env::home_dir().unwrap().join(".passkeeper").join("data");
let f = try!(fs::File::create(path));
Ok((f))
}
fn get_passkeeper_directory() -> PathBuf {
env::home_dir().unwrap().join(".passkeeper")
}
pub fn get_vault_path() -> PathBuf {
get_passkeeper_directory().join("vault")
}
pub fn get_key_data_path() -> PathBuf {
get_passkeeper_directory().join("data")
}
/// Returns the key data or an Error
pub fn get_key_data() -> Result<vault::KeyData, Error> {
let path = get_key_data_path();
match fs::File::open(&path) {
Ok(f) => {
let mut f = f;
let mut serialized = String::new();
f.read_to_string(&mut serialized).unwrap();
let key_data: vault::KeyData = serde_json::from_str(&serialized).unwrap();
return Ok(key_data)
}
Err(err) => return Err(err)
}
}
/// Returns the vault or an Error
pub fn get_vault() -> Result<vault::Vault, Error> {
let path = get_vault_path();
match fs::File::open(&path) {
Ok(f) => {
let mut f = f;
let mut serialized = String::new();
f.read_to_string(&mut serialized).unwrap();
let vault: vault::Vault = serde_json::from_str(&serialized).unwrap();
return Ok(vault)
}
Err(err) => return Err(err)
}
}
/// Replaces the existing vault file `vault`
pub fn update_vault(vault: vault::Vault) -> Result<(), Error>{
let serialized = serde_json::to_string(&vault).unwrap();
try!(write(serialized.as_bytes(), get_vault_path()));
Ok(())
}
/// Prompts user to initialize passkeeper
pub fn prompt_init() {
println!("passkeeper is not initialized\nRun passkeeper init");
return
}
/// Prompts user for input and reads one line from stdin and returns the resulting
/// string or an io::Error
pub fn prompt_input(prompt: &str) -> Result<String, Error> {
let mut input = String::new();
println!("{}:", prompt);
// Only read one line
match stdin().read_line(&mut input) {
Ok(_) => {
// Trim trailing newline
let trimmed = input.trim().to_string();
if trimmed.len() == 0 {
return Err(
Error::new(ErrorKind::InvalidInput, "Empty password"))
}
return Ok(trimmed);
},
Err(err) => {
return Err(Error::new(ErrorKind::InvalidInput, err.to_string()))
}
};
}
/// Prompts user for a password; prompts twice if `verify` is true. Returns
/// a Result with either a password String or an InvalidInput Error.
pub fn prompt_password(prompt: &str, verify: bool) -> Result<String, Error> {
let password = prompt_input(&prompt);
let mut password_verify: Result<String, Error> = Ok(String::from(""));
if verify {
let verify_prompt = format!("{} again", prompt);
password_verify = prompt_input(&verify_prompt);
}
// Check that the user entered a password(s)
if password.is_err() || verify && password_verify.is_err() {
return Err(Error::new(ErrorKind::InvalidInput, "You must enter a password"))
}
// If `verify` is true, check that the passwords are the same
let final_password = password.unwrap();
if verify && final_password != password_verify.unwrap() {
return Err(Error::new(ErrorKind::InvalidInput, "Passwords do not match"))
}
Ok(final_password)
}
/// Writes `b` bytes to the file at `path`
pub fn write(b: &[u8], path: PathBuf) -> Result<(), Error> {
let mut buffer = try!(fs::File::create(path));
try!(buffer.write_all(b));
Ok(())
}
| true |
7ce7d3b7bac18b519631d30d8fb0ddf9699d5423
|
Rust
|
esovm/wast
|
/fuzz/fuzz_targets/wasm-opt-ttf.rs
|
UTF-8
| 2,762 | 2.8125 | 3 |
[
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] |
permissive
|
//! Same as `binary.rs` fuzzing, but use `wasm-opt` with the input data to
//! generate a wasm program using `-ttf` instead of interpreting `data` as a
//! wasm program.
//!
//! Additionally assert that parsing succeeds since we should be able to parse
//! everything `wasm-opt` generates.
#![no_main]
use libfuzzer_sys::*;
use std::io::{Read, Write};
use std::process::{Command, Stdio};
fuzz_target!(|data: &[u8]| {
let td = tempfile::TempDir::new().unwrap();
std::fs::write(td.path().join("input"), data).unwrap();
let mut cmd = Command::new("wasm-opt")
.arg("-ttf")
.arg("--emit-text")
.arg(td.path().join("input"))
.arg("-o")
.arg("-")
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn()
.unwrap();
cmd.stdin.take().unwrap().write_all(data).unwrap();
let mut s = String::new();
cmd.stdout.take().unwrap().read_to_string(&mut s).unwrap();
let wat = td.path().join("foo.wat");
let wasm = td.path().join("foo.wasm");
std::fs::write(&wat, &s).unwrap();
let binary = wast::parse_str(&s).unwrap();
let lexer = wast_parser::lexer::Lexer::new(&s);
for token in lexer {
let t = match token.unwrap() {
wast_parser::lexer::Source::Token(t) => t,
_ => continue,
};
match t {
wast_parser::lexer::Token::Keyword(k) => {
if k == "binary" {
return;
}
}
wast_parser::lexer::Token::Float(f) => {
if let wast_parser::lexer::FloatVal::Val { hex: true, .. } = f.val() {
return;
}
}
_ => {}
}
}
let output = Command::new("wat2wasm")
.arg(&wat)
.arg("-o")
.arg(&wasm)
.output()
.unwrap();
if output.status.success() {
let wabt_bytes = std::fs::read(&wasm).unwrap();
// see comments in the test suite for why we remove the name
// section
assert_eq!(remove_name_section(&binary), wabt_bytes);
}
});
fn remove_name_section(bytes: &[u8]) -> Vec<u8> {
use wasmparser::*;
if let Ok(mut r) = ModuleReader::new(bytes) {
loop {
let start = r.current_position();
if let Ok(s) = r.read() {
match s.code {
SectionCode::Custom { name: "name", .. } => {
let mut bytes = bytes.to_vec();
bytes.drain(start..s.range().end);
return bytes;
}
_ => {}
}
} else {
break;
}
}
}
return bytes.to_vec();
}
| true |
7a21438c7a0cafd30c85d88aa7132bc0de594017
|
Rust
|
chorddown/chordr
|
/chordr-runner/src/configuration/reader.rs
|
UTF-8
| 7,801 | 2.953125 | 3 |
[
"MIT",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
use crate::configuration::Configuration;
use crate::error::*;
use std::error::Error as StdError;
use std::fs::File;
use std::io::BufReader;
use std::path::Path;
pub struct Reader {}
impl Reader {
pub fn read_configuration_from_file(path: &Path) -> Result<Configuration, Error> {
match path.extension() {
None => Err(build_file_type_error(path)),
Some(os_str) => match os_str.to_str() {
None => Err(build_file_type_error(path)),
Some("json") => Reader::read_configuration_from_json_file(path),
#[cfg(feature = "yaml")]
Some("yaml") => Reader::read_configuration_from_yaml_file(path),
Some(t) => Err(Error::configuration_reader_error(format!(
"No deserializer for the file type '{}'",
t
))),
},
}
}
fn read_configuration_from_json_file(path: &Path) -> Result<Configuration, Error> {
let file: BufReader<File> = get_file_reader(path)?;
match serde_json::from_reader::<BufReader<File>, Configuration>(file) {
Ok(r) => Ok(r),
Err(e) => Err(build_deserialize_error(path, &e)),
}
}
#[cfg(feature = "yaml")]
fn read_configuration_from_yaml_file(path: &Path) -> Result<Configuration, Error> {
let file: BufReader<File> = get_file_reader(path)?;
match serde_yaml::from_reader::<BufReader<File>, Configuration>(file) {
Ok(r) => Ok(r),
Err(e) => Err(build_deserialize_error(path, &e)),
}
}
}
fn build_file_type_error(path: &Path) -> Error {
match path.to_str() {
None => Error::configuration_reader_error("Invalid file"),
Some(f) => {
Error::configuration_reader_error(format!("Could not detect the file type of '{}'", f))
}
}
}
fn build_deserialize_error(path: &Path, error: &dyn StdError) -> Error {
match path.to_str() {
None => Error::configuration_error(format!("Could not deserialize file: {}", error)),
Some(f) => {
Error::configuration_error(format!("Could not deserialize the file '{}': {}", f, error))
}
}
}
fn get_file_reader(path: &Path) -> Result<BufReader<File>, Error> {
let file = match File::open(path) {
Ok(f) => f,
Err(e) => {
return Err(Error::configuration_reader_error(format!(
"Could not open file {:?} for reading: {}",
path, e
)))
}
};
Ok(BufReader::new(file))
}
#[cfg(test)]
mod test {
use libsynchord::prelude::ServiceIdentifier;
use super::*;
fn assert_valid_mandatory_configuration(result: Result<Configuration, Error>) -> Configuration {
let configuration = result.unwrap();
assert_eq!(
configuration.catalog_file.to_string_lossy(),
"/tmp/path/to/catalog-file.json"
);
assert_eq!(
configuration.output_directory.to_string_lossy(),
"/tmp/path/to/download/chorddown-files"
);
configuration
}
fn assert_valid_configuration(result: Result<Configuration, Error>) {
assert!(result.is_ok(), "{}", result.unwrap_err().to_string());
let configuration = assert_valid_mandatory_configuration(result);
assert_valid_webdav_configuration_values(configuration.clone());
assert_eq!(configuration.service.identifier, ServiceIdentifier::WebDAV);
assert_eq!(configuration.service.api_token.unwrap(), "MY_API_TOKEN");
}
fn assert_valid_dropbox_configuration(result: Result<Configuration, Error>) {
assert!(result.is_ok(), "{}", result.unwrap_err().to_string());
let configuration = assert_valid_mandatory_configuration(result);
assert_eq!(configuration.service.identifier, ServiceIdentifier::Dropbox);
assert_eq!(configuration.service.api_token.unwrap(), "MY_API_TOKEN");
}
fn assert_valid_webdav_configuration(result: Result<Configuration, Error>) {
assert!(result.is_ok(), "{}", result.unwrap_err().to_string());
let configuration = assert_valid_mandatory_configuration(result);
assert_valid_webdav_configuration_values(configuration);
}
fn assert_valid_webdav_configuration_values(configuration: Configuration) {
assert_eq!(configuration.service.identifier, ServiceIdentifier::WebDAV);
assert_eq!(configuration.service.username.unwrap(), "this-is-me");
assert_eq!(configuration.service.password.unwrap(), "123-easy");
assert_eq!(
configuration.service.url.unwrap(),
"https://mycloud.example.com"
);
assert_eq!(
configuration.service.remote_directory.unwrap(),
"remote-dir"
);
assert_eq!(configuration.service.sync_interval, 34);
}
#[test]
fn read_configuration_from_file_invalid() {
let result = Reader::read_configuration_from_file(&Path::new("/tests/"));
assert!(result.is_err());
assert_eq!(
result.unwrap_err().to_string(),
"Configuration reader error: Could not detect the file type of '/tests/'"
);
let result = Reader::read_configuration_from_file(&Path::new(&format!(
"{}/tests.txt",
env!("CARGO_MANIFEST_DIR")
)));
assert!(result.is_err());
assert_eq!(
result.unwrap_err().to_string(),
"Configuration reader error: No deserializer for the file type 'txt'"
);
}
#[test]
fn read_configuration_from_file_with_not_existing_json() {
let result =
Reader::read_configuration_from_file(&Path::new("/tests/resources/not-a-file.json"));
assert!(result.is_err());
assert!(
result.unwrap_err().to_string().starts_with(
"Configuration reader error: Could not open file \"/tests/resources/not-a-file.json\" for reading: No such file or directory"
));
}
#[test]
fn read_configuration_from_file_with_json() {
let result = Reader::read_configuration_from_file(&Path::new(&format!(
"{}/tests/resources/configuration.json",
env!("CARGO_MANIFEST_DIR")
)));
assert_valid_configuration(result);
}
#[test]
fn read_dropbox_configuration_from_file() {
let result = Reader::read_configuration_from_file(&Path::new(&format!(
"{}/tests/resources/configuration-dropbox.json",
env!("CARGO_MANIFEST_DIR")
)));
assert_valid_dropbox_configuration(result);
}
#[test]
fn read_webdav_configuration_from_file() {
let result = Reader::read_configuration_from_file(&Path::new(&format!(
"{}/tests/resources/configuration-webdav.json",
env!("CARGO_MANIFEST_DIR")
)));
assert_valid_webdav_configuration(result);
}
#[test]
#[cfg(feature = "yaml")]
fn read_configuration_from_file_with_not_existing_yaml() {
let result = Reader::read_configuration_from_file(&Path::new(
"/tests/resources/not-found-configuration.yaml",
));
assert!(result.is_err());
assert!(result.unwrap_err().to_string().starts_with("Configuration reader error: Could not open file \"/tests/resources/not-found-configuration.yaml\" for reading: No such file or directory"));
}
#[test]
#[cfg(feature = "yaml")]
fn read_configuration_from_file_with_yaml() {
let result = Reader::read_configuration_from_file(&Path::new(&format!(
"{}/tests/resources/configuration.yaml",
env!("CARGO_MANIFEST_DIR")
)));
assert_valid_configuration(result);
}
}
| true |
6dbed0518752f5e42a2e2c9f8f29c3a9d601f828
|
Rust
|
lenscas/arena_keeper_quick
|
/src/structs/character.rs
|
UTF-8
| 7,409 | 2.8125 | 3 |
[] |
no_license
|
use super::{grid::Field, point::Point};
use crate::modules::structs::ModulesContainer;
use crate::{
assets::loaded::Images,
modules::structs::SpeciesType,
structs::{BuyableCharacter, CameraWork, SimpleContext},
};
use pathfinding::{directed::astar::astar, prelude::absdiff};
use rand::prelude::*;
use serde::{Deserialize, Serialize};
use std::collections::VecDeque;
pub type CharId = usize;
#[derive(Serialize, Deserialize)]
pub struct Character {
id: CharId,
_name: String,
location: Point,
point_of_interest: Point,
time_until_new: usize,
walk_speed: usize,
time_till_walk: usize,
path: Option<VecDeque<Point>>,
time_until_recalc: usize,
species: SpeciesType,
image: Images,
}
impl Character {
pub fn from_bought_char(id: CharId, bought_char: BuyableCharacter) -> Self {
Self {
id,
location: (1, 1).into(),
_name: bought_char.get_name(),
walk_speed: bought_char.get_speed(),
point_of_interest: (10, 10).into(),
time_until_new: 500,
time_till_walk: 0,
path: None,
time_until_recalc: 0,
species: bought_char.get_species(),
image: bought_char.get_image(),
}
}
/// This function updates everything that multiple characters can do at the same time.
/// Always execute update_par before update
pub fn update_par(&mut self, grid: &Field, modules: &ModulesContainer) {
if self.path.is_none() {
self.calc_path(grid, modules);
} else if self.time_until_recalc == 0 {
self.calc_path(grid, modules);
if let Some(path) = &self.path {
self.time_until_recalc = path.len() * 10;
}
} else {
self.time_until_recalc -= 1;
}
}
/// calculates the path from the current point to the point_of_interest and stores it inside self.path
fn calc_path(&mut self, grid: &Field, modules: &ModulesContainer) {
if (!self.check_walkable_tile(grid, &self.point_of_interest, modules))
|| self.location == self.point_of_interest
{
self.time_until_new = 0;
self.path = None;
return;
}
let path: Option<VecDeque<Point>> = astar(
&(self.location.x, self.location.y),
|&var| {
let point: Point = var.into();
let mut possibles = Vec::new();
if point.y > 0 {
possibles.push((point.x, point.y - 1));
}
if point.x > 0 {
possibles.push((point.x - 1, point.y));
}
if point.x < grid.len - 1 {
possibles.push((point.x + 1, point.y));
}
if point.y < grid.height - 1 {
possibles.push((point.x, point.y + 1));
}
possibles
.into_iter()
.filter(|v| self.check_walkable_tile(grid, &v.into(), modules))
.map(|p| (p, self.calculate_cost(grid, &p.into(), modules)))
},
|&(x, y)| absdiff(x, self.point_of_interest.x) + absdiff(y, self.point_of_interest.y),
|&p| self.point_of_interest == p.into(),
)
.map(|v| v.0.iter().map(|b| b.into()).collect());
self.path = path;
}
/// This is similar to update_par but updates everything that can't happen at the same time with other characters.
/// Always execute update_par before update
pub fn update(&mut self, grid: &mut Field, modules: &ModulesContainer) {
let mut rng = rand::thread_rng();
if self.time_until_new == 0 || self.location == self.point_of_interest {
self.time_until_new = rng.gen();
self.point_of_interest = if rng.gen() {
let id = self.id;
let bed = grid
.find_cell_by(|v| match &v.feature {
Some(feature) => feature.is_owned_by(id) && feature.can_sleep(id, modules),
_ => false,
})
.or_else(|| {
grid.find_cell_by(|v| match &v.feature {
Some(feature) => feature.can_sleep(id, modules),
_ => false,
})
/*
if let Some(cell) = cell {
let feature = cell.feature.as_mut().unwrap();
feature.set_owned(Some(id));
}
cell*/
});
bed.map(|v| {
let cell = v.clone();
cell.feature.unwrap().set_owned(Some(id));
v.loc
})
.unwrap_or_else(|| {
(rng.gen_range(0, grid.len), rng.gen_range(0, grid.height)).into()
})
} else {
(rng.gen_range(0, grid.len), rng.gen_range(0, grid.height)).into()
};
self.path = None;
}
self.time_until_new -= 1;
if self.time_till_walk > 0 {
self.time_till_walk -= 1;
return;
}
self.time_till_walk = self.calculate_cost(grid, &self.location, modules);
match &mut self.path {
None => {}
Some(path) => match path.pop_front() {
None => {
self.path = None;
}
Some(next) => {
if self.check_walkable_tile(grid, &next, modules) {
self.location = next;
} else {
self.path = None;
}
}
},
}
}
fn calculate_cost(&self, grid: &Field, check_on: &Point, modules: &ModulesContainer) -> usize {
self.get_walk_speed_penalty(grid, check_on, modules) * self.walk_speed
}
fn get_walk_speed_penalty(
&self,
grid: &Field,
check_on: &Point,
modules: &ModulesContainer,
) -> usize {
grid.get_cell(check_on)
.map(|cell| {
cell.feature
.as_ref()
.and_then(|feature| feature.get_speed_penalty(modules))
.unwrap_or_else(|| {
self.species.get_speed_on_tile(
&modules.all_species,
&modules.all_tiles,
&cell.cell_type,
)
})
})
.unwrap_or_else(|| panic!("{:?} is out of bounds", check_on))
}
/// Renders the character.
pub fn render(&self, context: &mut SimpleContext, cam: &CameraWork) {
cam.draw_image_on_grid(&self.location, self.image.clone(), context);
}
/// Checks wheter this character can walk on a given tile
fn check_walkable_tile(&self, grid: &Field, point: &Point, modules: &ModulesContainer) -> bool {
match grid.get_cell(point) {
None => false,
Some(cell) => cell
.feature
.as_ref()
.map(|v| v.can_walk(modules))
.unwrap_or(true),
}
}
}
| true |
a70db4a3765f774e98a0b7cd539cc2036af59af5
|
Rust
|
tocklime/aoc-rs
|
/aoc/src/solutions/y2019/day11.rs
|
UTF-8
| 2,399 | 2.90625 | 3 |
[] |
no_license
|
use utils::points::*;
use aoc_harness::aoc_main;
use std::collections::HashMap;
use std::str::FromStr;
use std::sync::mpsc;
use std::thread;
use utils::intcode::Computer;
use utils::ocr::OcrString;
aoc_main!(2019 day 11, part1 [p1] => 2160, part2 [p2] => "LRZECGFE");
const WHITE: char = '█';
const BLACK: char = ' ';
pub fn robot(
input: &mpsc::Receiver<isize>,
output: &mpsc::Sender<isize>,
c: char,
) -> HashMap<Point, char> {
let mut painted_panels = HashMap::new();
let mut p = Point(0, 0);
let mut d = Dir::U;
painted_panels.insert(p, c);
loop {
if output
.send((painted_panels.get(&p) == Some(&WHITE)).into())
.is_err()
{
break;
}
match input.recv() {
Ok(0) => painted_panels.insert(p, BLACK),
Ok(1) => painted_panels.insert(p, WHITE),
Err(_) => break,
_ => panic!("Unknown paint instruction"),
};
match input.recv() {
Ok(0) => {
d = d.rotate_left();
}
Ok(1) => d = d.rotate_left().rotate_left().rotate_left(),
Err(_) => break,
_ => panic!("Unknown turn instruction"),
}
p += d.as_point_delta();
}
painted_panels
}
pub fn my_run(input: &str, init_c: char) -> HashMap<Point, char> {
let mut c: Computer<isize> = Computer::from_str(input).unwrap();
let (tx, rx) = c.make_io_chans();
let c_thr = thread::spawn(move || {
c.run();
});
let robot_thr = thread::spawn(move || robot(&rx, &tx, init_c));
c_thr.join().unwrap();
robot_thr.join().unwrap()
}
pub fn p1(input: &str) -> usize {
my_run(input, BLACK).len()
}
pub fn p2(input: &str) -> OcrString {
utils::points::render_char_map(&my_run(input, WHITE)).into()
}
#[test]
pub fn example() {
let (txa, rxa) = mpsc::channel::<isize>();
let (txb, rxb) = mpsc::channel::<isize>();
let r = thread::spawn(move || robot(&rxb, &txa, BLACK));
let input: Vec<isize> = vec![1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0];
let correct_output = [0, 0, 0, 0, 1, 0, 0, 0];
for i in input.iter() {
txb.send(*i).unwrap()
}
drop(txb);
let mut output = vec![];
while let Ok(i) = rxa.recv() {
output.push(i);
}
assert_eq!(output, correct_output);
assert_eq!(r.join().unwrap().len(), 6);
}
| true |
78e4b74b9acd1f6633854e4300a818bc8a73821a
|
Rust
|
nbari/dbpulse
|
/src/queries.rs
|
UTF-8
| 2,823 | 2.65625 | 3 |
[
"BSD-3-Clause"
] |
permissive
|
use anyhow::{anyhow, Context, Result};
use chrono::prelude::*;
use chrono::{DateTime, Utc};
use mysql_async::prelude::*;
use rand::Rng;
use uuid::Uuid;
pub async fn test_rw(opts: mysql_async::OptsBuilder, now: DateTime<Utc>) -> Result<String> {
let mut conn = mysql_async::Conn::new(opts).await?;
// create table
r#"CREATE TABLE IF NOT EXISTS dbpulse_rw (
id INT NOT NULL,
t1 INT(11) NOT NULL ,
t2 TIMESTAMP(6) NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
uuid CHAR(36) CHARACTER SET ascii,
UNIQUE KEY(uuid),
PRIMARY KEY(id)
) ENGINE=InnoDB"#
.ignore(&mut conn)
.await?;
// write into table
let num: u32 = rand::thread_rng().gen_range(0, 100);
let uuid = Uuid::new_v4();
conn.exec_drop("INSERT INTO dbpulse_rw (id, t1, uuid) VALUES (:id, :t1, :uuid) ON DUPLICATE KEY UPDATE t1=:t1, uuid=:uuid", params! {
"id" => num,
"t1" => now.timestamp(),
"uuid" => uuid.to_string(),
}).await?;
// check if stored record matches
let row: Option<(i64, String)> = conn
.exec_first(
"SELECT t1, uuid FROM dbpulse_rw Where id=:id",
params! {
"id" => num,
},
)
.await?;
let (t1, v4) = row.context("Expected records")?;
if now.timestamp() != t1 || uuid.to_string() != v4 {
return Err(anyhow!(
"Records don't match: {}",
format!("({}, {}) != ({},{})", now, uuid, t1, v4)
));
}
// check transaction setting all records to 0
let mut tx = conn
.start_transaction(mysql_async::TxOpts::default())
.await?;
tx.exec_drop(
"UPDATE dbpulse_rw SET t1=:t1",
params! {
"t1" => "0"
},
)
.await?;
let rows = tx.exec("SELECT t1 FROM dbpulse_rw", ()).await?;
for row in rows {
let row = mysql_async::from_row::<u64>(row);
if row != 0 {
return Err(anyhow!(
"Records don't match: {}",
format!("{} != {}", row, 0)
));
}
}
tx.rollback().await?;
// update record 1 with now
let mut tx = conn
.start_transaction(mysql_async::TxOpts::default())
.await?;
tx.exec_drop(
"INSERT INTO dbpulse_rw (id, t1, uuid) VALUES (0, :t1, UUID()) ON DUPLICATE KEY UPDATE t1=:t1",
params!{
"t1" => now.timestamp()
},
).await?;
tx.commit().await?;
// drop table randomly
if now.minute() == num {
conn.query_drop("DROP TABLE dbpulse_rw").await?;
}
// get db version
let version: Option<String> = conn.query_first("SELECT VERSION()").await?;
drop(conn);
Ok(version.context("Expected version")?)
}
| true |
31ea33326c3ab29e9e2b2610c70bc01103ca62b9
|
Rust
|
dminor/walden
|
/src/lexer.rs
|
UTF-8
| 17,394 | 3.53125 | 4 |
[] |
no_license
|
use std::collections::LinkedList;
use std::error::Error;
use std::fmt;
#[derive(Debug, PartialEq)]
pub enum Token {
Bar,
Colon,
ColonEqual,
Dot,
LeftBracket,
RightBracket,
LeftParen,
RightParen,
Plus,
Minus,
Star,
Slash,
Less,
LessEqual,
Equal,
NotEqual,
Greater,
GreaterEqual,
Identifier(String),
Number(f64),
String(String),
True,
False,
Nil,
}
impl fmt::Display for Token {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Token::Bar => write!(f, "|"),
Token::Colon => write!(f, ":"),
Token::ColonEqual => write!(f, ":="),
Token::Dot => write!(f, "."),
Token::LeftBracket => write!(f, "["),
Token::RightBracket => write!(f, "]"),
Token::LeftParen => write!(f, "("),
Token::RightParen => write!(f, ")"),
Token::Plus => write!(f, "+"),
Token::Minus => write!(f, "-"),
Token::Star => write!(f, "*"),
Token::Slash => write!(f, "/"),
Token::NotEqual => write!(f, "~="),
Token::Equal => write!(f, "="),
Token::Greater => write!(f, ">"),
Token::GreaterEqual => write!(f, ">="),
Token::Less => write!(f, "<"),
Token::LessEqual => write!(f, "<="),
Token::Identifier(s) => write!(f, "{}", s),
Token::String(s) => write!(f, "{}", s),
Token::Number(n) => write!(f, "{}", n),
Token::True => write!(f, "true"),
Token::False => write!(f, "false"),
Token::Nil => write!(f, "nil"),
}
}
}
#[derive(Debug)]
pub struct LexerError {
pub err: String,
pub line: usize,
pub col: usize,
}
impl fmt::Display for LexerError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "LexerError: {}", self.err)
}
}
impl Error for LexerError {}
pub struct LexedToken {
pub token: Token,
pub line: usize,
pub col: usize,
}
macro_rules! push_token {
($T:expr, $tokens:ident, $line:ident, $col:ident) => {
$tokens.push_back({
LexedToken {
token: $T,
line: $line,
col: $col,
}
});
};
}
pub fn scan(src: &str) -> Result<LinkedList<LexedToken>, LexerError> {
let mut line = 1;
let mut col = 1;
let mut tokens = LinkedList::<LexedToken>::new();
let mut chars = src.chars().peekable();
loop {
match chars.next() {
Some(c) => match c {
'|' => {
push_token!(Token::Bar, tokens, line, col);
}
':' => match chars.peek() {
Some(c) => {
if *c == '=' {
push_token!(Token::ColonEqual, tokens, line, col);
chars.next();
} else {
push_token!(Token::Colon, tokens, line, col);
}
}
None => {
push_token!(Token::Colon, tokens, line, col);
}
},
'.' => {
push_token!(Token::Dot, tokens, line, col);
}
'[' => {
push_token!(Token::LeftBracket, tokens, line, col);
}
']' => {
push_token!(Token::RightBracket, tokens, line, col);
}
'(' => {
push_token!(Token::LeftParen, tokens, line, col);
}
')' => {
push_token!(Token::RightParen, tokens, line, col);
}
'+' => {
push_token!(Token::Plus, tokens, line, col);
}
'-' => {
push_token!(Token::Minus, tokens, line, col);
}
'*' => {
push_token!(Token::Star, tokens, line, col);
}
'/' => {
push_token!(Token::Slash, tokens, line, col);
}
'>' => match chars.peek() {
Some(c) => {
if *c == '=' {
push_token!(Token::GreaterEqual, tokens, line, col);
chars.next();
col += 1;
} else {
push_token!(Token::Greater, tokens, line, col);
}
}
None => {
push_token!(Token::Greater, tokens, line, col);
}
},
'=' => {
push_token!(Token::Equal, tokens, line, col);
}
'<' => match chars.peek() {
Some(c) => {
if *c == '=' {
push_token!(Token::LessEqual, tokens, line, col);
chars.next();
col += 1;
} else {
push_token!(Token::Less, tokens, line, col);
}
}
None => {
push_token!(Token::Less, tokens, line, col);
}
},
'~' => match chars.next() {
Some(c) => {
if c == '=' {
col += 1;
push_token!(Token::NotEqual, tokens, line, col);
} else {
return Err(LexerError {
err: "Unexpected token while scanning ~=.".to_string(),
line: line,
col: col,
});
}
}
_ => {
return Err(LexerError {
err: "Unexpected end of input while scanning ~=.".to_string(),
line: line,
col: col,
});
}
},
'\'' => {
let mut v = Vec::<char>::new();
loop {
match chars.next() {
Some(c) => match c {
'\'' => {
push_token!(
Token::String(v.into_iter().collect()),
tokens,
line,
col
);
break;
}
'\n' => {
line += 1;
col = 1;
v.push(c);
}
_ => {
v.push(c);
col += 1;
}
},
None => {
return Err(LexerError {
err: "Unexpected end of input while scanning string."
.to_string(),
line: line,
col: col,
});
}
}
}
col += 1;
}
'"' => loop {
match chars.next() {
Some(c) => match c {
'"' => {
break;
}
'\n' => {
line += 1;
col = 0; //incremented below
}
_ => {}
},
None => {
return Err(LexerError {
err: "Unexpected end of input while scanning comment.".to_string(),
line: line,
col: col,
});
}
}
col += 1;
},
'\n' => {
line += 1;
col = 1;
continue;
}
' ' => {}
_ => {
let mut valid_identifier = true;
let mut found_dot = false;
let mut push_dot = false;
if c.is_numeric() {
valid_identifier = false;
}
if !c.is_alphanumeric() && c != '@' {
valid_identifier = false;
}
let mut v = vec![c];
loop {
match chars.peek() {
Some(c) => {
if c.is_alphanumeric() {
v.push(*c);
chars.next();
col += 1;
} else if !found_dot && *c == '.' {
found_dot = true;
chars.next();
col += 1;
match chars.peek() {
Some(c) => {
if c.is_numeric() {
valid_identifier = false;
v.push('.');
} else {
push_dot = true;
break;
}
}
None => {
push_dot = true;
break;
}
}
} else {
break;
}
}
None => {
break;
}
}
}
let s: String = v.into_iter().collect();
match &s[..] {
"true" => {
push_token!(Token::True, tokens, line, col);
}
"false" => {
push_token!(Token::False, tokens, line, col);
}
"nil" => {
push_token!(Token::Nil, tokens, line, col);
}
_ => match s.parse::<f64>() {
Ok(n) => {
push_token!(Token::Number(n), tokens, line, col);
}
_ => {
if valid_identifier {
push_token!(
Token::Identifier(s.to_string()),
tokens,
line,
col
);
} else {
let mut err = "Invalid identifier: ".to_string();
err.push_str(&s);
err.push('.');
return Err(LexerError {
err: err,
line: line,
col: col,
});
}
}
},
}
if push_dot {
push_token!(Token::Dot, tokens, line, col);
}
}
},
None => {
break;
}
}
col += 1;
}
Ok(tokens)
}
#[cfg(test)]
mod tests {
use crate::lexer;
macro_rules! scan {
($input:expr, $( $value:expr),* ) => {{
match lexer::scan($input) {
Ok(mut tokens) => {
$(
match tokens.pop_front() {
Some(t) => {
assert_eq!(t.token, $value);
}
None => {}
}
)*
assert_eq!(tokens.len(), 0);
}
_ => assert!(false),
}
}};
}
macro_rules! scanfails {
($input:expr, $err:tt, $line:expr, $col:expr) => {{
match lexer::scan($input) {
Ok(_) => assert!(false),
Err(e) => {
assert_eq!(e.err, $err);
assert_eq!(e.line, $line);
assert_eq!(e.col, $col);
}
}
}};
}
#[test]
fn scanning() {
scan!(
"[:x | x + 1]",
lexer::Token::LeftBracket,
lexer::Token::Colon,
lexer::Token::Identifier("x".to_string()),
lexer::Token::Bar,
lexer::Token::Identifier("x".to_string()),
lexer::Token::Plus,
lexer::Token::Number(1.0),
lexer::Token::RightBracket
);
scan!(
"[:x :y | x - y]",
lexer::Token::LeftBracket,
lexer::Token::Colon,
lexer::Token::Identifier("x".to_string()),
lexer::Token::Colon,
lexer::Token::Identifier("y".to_string()),
lexer::Token::Bar,
lexer::Token::Identifier("x".to_string()),
lexer::Token::Minus,
lexer::Token::Identifier("y".to_string()),
lexer::Token::RightBracket
);
scan!(
"5 * 6 / 2.2",
lexer::Token::Number(5.0),
lexer::Token::Star,
lexer::Token::Number(6.0),
lexer::Token::Slash,
lexer::Token::Number(2.2)
);
scan!(
"(x <= y) or: true",
lexer::Token::LeftParen,
lexer::Token::Identifier("x".to_string()),
lexer::Token::LessEqual,
lexer::Token::Identifier("y".to_string()),
lexer::Token::RightParen,
lexer::Token::Identifier("or".to_string()),
lexer::Token::Colon,
lexer::Token::True
);
scan!(
"(x >= y) and: false",
lexer::Token::LeftParen,
lexer::Token::Identifier("x".to_string()),
lexer::Token::GreaterEqual,
lexer::Token::Identifier("y".to_string()),
lexer::Token::RightParen,
lexer::Token::Identifier("and".to_string()),
lexer::Token::Colon,
lexer::Token::False
);
scan!(
"2 ~= 3 = true",
lexer::Token::Number(2.0),
lexer::Token::NotEqual,
lexer::Token::Number(3.0),
lexer::Token::Equal,
lexer::Token::True
);
scanfails!("2 ~$", "Unexpected token while scanning ~=.", 1, 3);
scanfails!("2 ~", "Unexpected end of input while scanning ~=.", 1, 3);
scan!("<", lexer::Token::Less);
scan!(">", lexer::Token::Greater);
scan!("nil", lexer::Token::Nil);
scan!("Valid", lexer::Token::Identifier("Valid".to_string()));
scan!("@Valid", lexer::Token::Identifier("@Valid".to_string()));
scanfails!("2Valid", "Invalid identifier: 2Valid.", 1, 6);
scanfails!("In_valid", "Invalid identifier: _valid.", 1, 8);
scanfails!("$valid", "Invalid identifier: $valid.", 1, 6);
scan!(
"'hello world'",
lexer::Token::String("hello world".to_string())
);
scan!(
"'hello\nworld'",
lexer::Token::String("hello\nworld".to_string())
);
scanfails!(
"'hello world",
"Unexpected end of input while scanning string.",
1,
12
);
scanfails!(
"\"This is a comment that\nnever ends",
"Unexpected end of input while scanning comment.",
2,
11
);
}
}
| true |
4dd1440a6047bc5aa80e7bbbd427bbde7c2990e5
|
Rust
|
ExcaliburZero/quickbms-lsp
|
/src/server/server.rs
|
UTF-8
| 7,449 | 2.59375 | 3 |
[
"MIT"
] |
permissive
|
use std::fmt;
use std::io::{BufRead, Write};
use std::str::from_utf8;
use std::sync::{Arc, Mutex};
use jsonrpc_core::{IoHandler, Params};
use lsp_types::{
DidChangeTextDocumentParams, DidOpenTextDocumentParams, DocumentSymbolParams,
GotoDefinitionParams, GotoDefinitionResponse, HoverParams, HoverProviderCapability,
InitializeParams, InitializeResult, ReferenceParams, ServerCapabilities,
TextDocumentSyncCapability, TextDocumentSyncKind,
};
use regex::Regex;
use serde_json::{self, from_value, to_value, Value};
use crate::server::state::ServerState;
pub fn run<R, W>(mut input: R, mut output: W)
where
R: BufRead,
W: Write,
{
let io = setup_handler();
eprintln!("Started server");
loop {
let message = Message::read_from_buffered_reader(&mut input);
let response = io.handle_request_sync(&message.content);
if let Some(response) = response {
let response_message = Message::from_content(&response);
write!(output, "{}", response_message).unwrap();
output.flush().unwrap();
}
}
}
fn setup_handler() -> IoHandler {
let mut io = IoHandler::new();
let state = Arc::new(Mutex::new(ServerState::new()));
io.add_sync_method("initialize", |params| {
let value = params_to_value(params);
let _request = from_value::<InitializeParams>(value).unwrap();
let mut response = InitializeResult::default();
response.capabilities.hover_provider = Some(HoverProviderCapability::Simple(true));
let response = InitializeResult {
capabilities: ServerCapabilities {
text_document_sync: Some(TextDocumentSyncCapability::Kind(
TextDocumentSyncKind::Full,
)),
hover_provider: Some(true.into()),
definition_provider: Some(lsp_types::OneOf::Left(true)),
references_provider: Some(lsp_types::OneOf::Left(true)),
document_symbol_provider: Some(lsp_types::OneOf::Left(true)),
..ServerCapabilities::default()
},
..InitializeResult::default()
};
Ok(to_value(response).unwrap())
});
let state_c = state.clone();
io.add_notification("textDocument/didOpen", move |params| {
let value = params_to_value(params);
let notification = from_value::<DidOpenTextDocumentParams>(value).unwrap();
state_c.lock().unwrap().did_open(¬ification);
});
let state_c = state.clone();
io.add_notification("textDocument/didChange", move |params| {
let value = params_to_value(params);
let notification = from_value::<DidChangeTextDocumentParams>(value).unwrap();
state_c.lock().unwrap().did_change(¬ification);
});
let state_c = state.clone();
io.add_sync_method("textDocument/documentSymbol", move |params| {
let value = params_to_value(params);
let request = from_value::<DocumentSymbolParams>(value).unwrap();
let response = state_c.lock().unwrap().document_symbol(&request);
match response {
None => Ok(Value::Null),
Some(response) => Ok(to_value(response).unwrap()),
}
});
let state_c = state.clone();
io.add_sync_method("textDocument/hover", move |params| {
let value = params_to_value(params);
let request = from_value::<HoverParams>(value).unwrap();
let response = state_c.lock().unwrap().hover(&request);
match response {
None => Ok(Value::Null),
Some(response) => Ok(to_value(response).unwrap()),
}
});
let state_c = state.clone();
io.add_sync_method("textDocument/definition", move |params| {
let value = params_to_value(params);
let request = from_value::<GotoDefinitionParams>(value).unwrap();
let response = match state_c.lock().unwrap().goto_definition(&request) {
Some(resp) => resp,
None => GotoDefinitionResponse::Array(vec![]),
};
Ok(to_value(response).unwrap())
});
let state_c = state.clone();
io.add_sync_method("textDocument/references", move |params| {
let value = params_to_value(params);
let request = from_value::<ReferenceParams>(value).unwrap();
let response = state_c.lock().unwrap().goto_references(&request);
Ok(to_value(response).unwrap())
});
io
}
fn params_to_value(params: Params) -> Value {
match params {
Params::Map(map) => Value::Object(map),
Params::Array(arr) => Value::Array(arr),
Params::None => Value::Null,
}
}
#[derive(Debug, Eq, PartialEq)]
struct Header {
content_length: u64,
content_type: Option<String>,
}
impl Header {
fn read_from_buffered_reader<R: BufRead>(input: &mut R) -> Header {
let mut content_length_line = String::new();
input.read_line(&mut content_length_line).unwrap();
let mut content_type_line = String::new();
input.read_line(&mut content_type_line).unwrap();
let content_length = Header::parse_content_length(&content_length_line);
let content_type = Header::parse_content_type(&content_type_line);
Header {
content_length,
content_type,
}
}
fn parse_content_length(line: &str) -> u64 {
let re = Regex::new(r"^Content-Length: (\d+)\r\n").unwrap();
let length_string = re.captures(line).unwrap()[1].to_string();
length_string.parse::<u64>().unwrap()
}
fn parse_content_type(line: &str) -> Option<String> {
if line == "\r\n" {
None
} else {
Some(line.to_string())
}
}
}
impl fmt::Display for Header {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Content-Length: {}\r\n\r\n", self.content_length)
}
}
#[derive(Debug, Eq, PartialEq)]
struct Message {
header: Header,
content: String,
}
impl Message {
fn read_from_buffered_reader<R: BufRead>(input: &mut R) -> Message {
let header = Header::read_from_buffered_reader(input);
let mut content_buf: Vec<u8> = vec![0; header.content_length as usize];
input.read_exact(&mut content_buf).unwrap();
let content = from_utf8(&content_buf).unwrap().to_string();
Message { header, content }
}
fn from_content(content: &str) -> Message {
let content_length = content.as_bytes().len() as u64;
Message {
header: Header {
content_length,
content_type: None,
},
content: content.to_string(),
}
}
}
impl fmt::Display for Message {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}{}", self.header, self.content)
}
}
#[test]
fn test_message_from_buffered_reader() {
use std::io::BufReader;
let text =
"Content-Length: 52\r\n\r\n{\"jsonrpc\":\"2.0\",\"method\":\"initialized\",\"params\":{}}";
let mut reader = BufReader::new(text.as_bytes());
let actual = Message::read_from_buffered_reader(&mut reader);
let expected = Message {
header: Header {
content_length: 52,
content_type: None,
},
content: r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#.to_string(),
};
assert_eq!(expected, actual);
}
| true |
2d9dfc5fb4d96faf7ae1fd44567316ff32a886dd
|
Rust
|
maxastyler/square_sandpile
|
/src/main.rs
|
UTF-8
| 5,363 | 2.765625 | 3 |
[] |
no_license
|
#[macro_use]
extern crate ndarray;
extern crate image;
extern crate rayon;
use ndarray::{Array, Array2, ArrayView2, ArrayViewMut2};
use rayon::prelude::*;
fn topple(mut pile: ArrayViewMut2<i64>) {
// Topples a sandpile, using the edges as sinks.
let dim = (pile.shape()[0], pile.shape()[1]);
let mut collapse_queue: Vec<(usize, usize)> = vec!();
while let Some(next_pos) = get_first_untoppled(&pile.view()) {
pile[next_pos]-=4;
for i in get_surrounding(next_pos).iter() {
pile[*i]+=1;
if !on_rect_edge(*i, dim) && pile[*i]>=4 {collapse_queue.push(*i)}
}
while let Some(i) = collapse_queue.pop() {
if pile[i] >= 4 {
pile[i] -= 4;
for j in get_surrounding(i).iter() {
pile[*j]+=1;
if !on_rect_edge(*j, dim) && pile[*j]>=4 {collapse_queue.push(*j)}
}
}
}
}
}
fn topple_threaded(mut pile: &mut Array2<i64>, n: usize) {
// Break in to n parts which are threaded
let x = pile.shape()[0];
let y = pile.shape()[1];
let mut sizes = vec!{};
for _ in 0..n {sizes.push(x/n)}
for i in 0..(x%n) {sizes[i]+=1}
let mut pos = vec!{};
pos.push(0);
for i in 0..n {
let a = pos[i];
pos.push(a+sizes[i]);
}
let positions: Vec<(usize, usize)> = pos.iter().zip(pos.iter().skip(1)).map(|(&x, &y)| (x, y)).collect();
let mut inside_bounds = vec!{};
for i in 0..n {
if i!=0 { inside_bounds.push(positions[i].0-1)}
if i!=(n-1) {inside_bounds.push(positions[i].1)};
}
let mut boundary_pairs: Vec<(usize, usize)> = vec!{};
for i in 0..inside_bounds.len()/2 {
boundary_pairs.push((inside_bounds.pop().unwrap(), inside_bounds.pop().unwrap()));
}
while let Some(_) = get_first_untoppled(&pile.view()) {
// for bounds in positions.par_iter() {
// topple(pile.slice_mut(s!((bounds.0)..(bounds.1), 0..y)));
// }
positions.iter().for_each(|bounds| {
topple(pile.slice_mut(s!((bounds.0)..(bounds.1), 0..y)))
});
for pair in boundary_pairs.iter() {
topple(pile.slice_mut(s!((pair.0-1)..(pair.1+1), 0..y)));
}
}
}
fn on_rect_edge(pos: (usize, usize), rect_dim: (usize, usize)) -> bool {
if pos.0 > 0 && pos.0 < rect_dim.0-1 && pos.1 > 0 && pos.1 < rect_dim.0-1 {
false } else { true }
}
fn get_first_untoppled(pile: &ArrayView2<i64>) -> Option<(usize, usize)> {
let s = pile.shape();
for x in 0..s[0] {
for y in 0..s[1] {
if pile[(x, y)]>=4 && !on_rect_edge((x, y), (s[0], s[1])) { return Some((x, y)) }
}
}
None
}
fn get_surrounding(pos: (usize, usize)) -> [(usize, usize); 4]{
[(pos.0-1, pos.1), (pos.0+1, pos.1), (pos.0, pos.1-1), (pos.0, pos.1+1)]
}
fn single_point() {
// let colours = vec![
// [255,255,255],
// [229,208,255],
// [204,163,255],
// [191,139,255]];
let colours = vec![
[26, 83, 92],
[78, 205, 196],
[247, 255, 247],
[255, 107, 107],
[255, 230, 109]
];
let mut n = 0;
loop {
println!("On {} now", n);
let res = 205;
let mut a: Array2<i64> = Array::zeros((res, res));
a[[102, 102]] = n*1050;
topple(a.view_mut());
//topple_threaded(&mut a, 1);
let mut imgbuf: image::ImageBuffer<image::Rgb<u8>, _>= image::ImageBuffer::new(res as u32, res as u32);
for (i, &n) in a.iter().enumerate() {
let x = i as u32 % res as u32;
let y = i as u32 / res as u32;
let pix = imgbuf.get_pixel_mut(x, y);
if n > 0 && n < 4 {
*pix = image::Rgb(colours[n as usize])
} else if n >= 4 { *pix = image::Rgb(colours[4])}
else { *pix = image::Rgb(colours[0])}
}
imgbuf.save(format!("sand_gif/sandpile_gif_{:04}.bmp", n)).unwrap();
n += 1;
if n>284 {break}
}
}
fn four_points() {
// let colours = vec![
// [255,255,255],
// [229,208,255],
// [204,163,255],
// [191,139,255]];
let colours = vec![
[26, 83, 92],
[78, 205, 196],
[247, 255, 247],
[255, 107, 107],
[255, 230, 109]
];
let mut n = 0;
loop {
println!("On {} now", n);
let res = 182;
let mut a: Array2<i64> = Array::zeros((res, res));
a[[60, 60]] = n*250;
a[[60, 121]] = n*250;
a[[121, 60]] = n*250;
a[[121, 121]] = n*250;
topple(a.view_mut());
//topple_threaded(&mut a, 1);
let mut imgbuf: image::ImageBuffer<image::Rgb<u8>, _>= image::ImageBuffer::new(res as u32, res as u32);
for (i, &n) in a.iter().enumerate() {
let x = i as u32 % res as u32;
let y = i as u32 / res as u32;
let pix = imgbuf.get_pixel_mut(x, y);
if n > 0 && n < 4 {
*pix = image::Rgb(colours[n as usize])
} else if n >= 4 { *pix = image::Rgb(colours[4])}
else { *pix = image::Rgb(colours[0])}
}
imgbuf.save(format!("four_points/sandpile_gif_{:04}.bmp", n)).unwrap();
n += 1;
if n>200 {break}
}
}
fn main() {
four_points();
}
| true |
994e7224eff195d3e3f41778a0c82b0e66eca312
|
Rust
|
kino00/Rust-zipper
|
/src/lib.rs
|
UTF-8
| 25,800 | 3.140625 | 3 |
[] |
no_license
|
use std::fs::File;
use std::io::prelude::*;
use std::io::{Error};
use std::fs::metadata;
use chrono::prelude::*;
/*
デバッグ用に出力を制御するためのもの
*/
const PRINT_DEBUG: bool = false;
const MAX_BUFFER_SIZE: usize = 1024; // 1回の入力で受けつける最大のバイト
const MAX_MATCH_LEN: usize = 258; // 最大でどれだけ一致するかのサイズ
const MIN_MATCH_LEN: usize = 3; // 少なくとも3は一致しないと圧縮処理が行われない
const MAX_WINDOW_SIZE: usize = 1024; // スライドウインドウの最大サイズ 小さめにとっている
/*
bit単位で出力を行うためのもの
bit_count: bufferに何ビット突っ込んだかを保持する
buffer: 出力用のbuffer
output_vector: 出力データをこのvectorに溜めて最後に一気に出力する
output: 出力ファイルデータ
*/
struct BitWriter<'a, T: Write> {
bit_count: u8,
buffer: u8,
output_vector: Vec<u8>,
output: &'a mut T,
}
impl<'a, T: Write> BitWriter<'a, T> {
pub fn new(output: &'a mut T) -> Self {
BitWriter {
bit_count: 0,
buffer: 0,
output_vector: Vec::new(),
output,
}
}
/*
deflate圧縮では出力方向が変わるため、ハフマン符号化したものや、距離符号のためのもの
*/
pub fn code_bits(&mut self, bits: u16, bit_count: u8) -> Result<(), Error> {
for i in 0..bit_count {
if self.bit_count == 8 {
self.flush_to_output()?;
}
let offset = bit_count - 1 - i;
let bit = (bits & (1 << offset)) >> offset;
self.buffer <<= 1;
self.buffer |= bit as u8;
self.bit_count += 1;
}
Ok(())
}
/*
上以外のもの(拡張ビットや、ブロックの種類)
*/
pub fn extra_bits(&mut self, bits: u16, bit_count: u8) -> Result<(), Error> {
for i in 0..bit_count {
if self.bit_count == 8 {
self.flush_to_output()?;
}
let bit = (bits >> i) & 1;
self.buffer <<= 1;
self.buffer |= bit as u8;
self.bit_count += 1;
}
Ok(())
}
/*
最後にvecterに入っているものをまとめて出力する
また、出力がバイト単位になるようにパディングを行う
*/
pub fn flush(&mut self) -> Result<(), Error> {
if self.bit_count > 0 {
self.buffer <<= 8 - self.bit_count;
let mut buffer = 0;
for i in 0..8 {
buffer <<= 1;
buffer |= (self.buffer >> i) & 1;
}
self.output_vector.push(buffer.clone());
if PRINT_DEBUG == true {
println!("push data: {:08b}", self.buffer);
for i in 0..(self.output_vector.len()){
print!("{:08b}", self.output_vector[i]);
}
println!();
println!("{:02x?}", self.output_vector);
}
}
Ok(())
}
/*
bufferが8ビット(1バイト)溜まった時に実行される
*/
fn flush_to_output(&mut self) -> Result<(), Error> {
let mut buffer = 0;
for i in 0..8 {
buffer <<= 1;
buffer |= (self.buffer >> i) & 1;
}
self.output_vector.push(buffer.clone());
if PRINT_DEBUG == true {
println!("push data: {:08b}", buffer);
for i in 0..(self.output_vector.len()){
print!("{:08b}", self.output_vector[i]);
}
println!();
}
self.buffer = 0;
self.bit_count = 0;
Ok(())
}
}
/*
読み込みをbyteで保持するもの
buffer: データをMAX_BUFFER_SIZE分取り込むための配列。
buf_count: 現在bufferが何個目まで読まれているかを保持する。
buf_size: bufferの何番目までデータがあるかを保持する
flag: 読み込むデータがもうない時に使用する。
file_size: 入力ファイルのサイズを記録する。
input: 入力ファイルの情報を記録する。
*/
struct ByteReader<'a, T: Read> {
buffer: [u8; MAX_BUFFER_SIZE],
buf_count: usize,
buf_size: usize,
flag: bool,
file_size: u32,
input: &'a mut T,
}
impl<'a, T: Read> ByteReader<'a, T> {
pub fn new(input: &'a mut T) -> Self {
let mut reader = ByteReader {
buffer: [0; MAX_BUFFER_SIZE],
buf_count: 0,
buf_size: 0,
flag: true,
file_size: 0,
input,
};
let _ = reader.load_next_byte();
reader
}
/*
bufferが最後まで読まれたり、最初の読み込みの際に実行される。
*/
fn load_next_byte(&mut self) -> Result<(), std::io::Error>{
match self.input.read(&mut self.buffer)? {
0 => {
self.flag = false;
self.buf_size = 0;
},
n => {
self.file_size += n as u32;
self.buf_size = n;
self.flag = true;
}
};
Ok(())
}
/*
buf_countの位置にあるバイトを返す。
*/
pub fn seek_byte(&mut self) -> u8{
self.buffer[self.buf_count]
}
/*
bit_countを進める。bufferの最後まできていた場合には
load_next_byteで次のブロックを読み込む。
*/
pub fn next_byte(&mut self) {
if self.buf_count + 1 < self.buf_size {
self.buf_count += 1;
} else {
let _ = self.load_next_byte();
self.buf_count = 0;
}
}
/*
bit_countの位置にあるバイトを返して、next_byteを読みこむ
*/
pub fn get_byte(&mut self) -> u8 {
let buffer = self.buffer[self.buf_count];
self.next_byte();
buffer
}
}
/*
Crc32を計算するための構造体
crc32の実装については下のurlを参考に行なった。
https://www.slideshare.net/7shi/crc32
divisor: 除算を行う際に使用するbit列を保持する
non_divisor: 除算される側のデータを保持する
buffer: とりあえずのデータを保持する
buf_count: bufferが何bit処理されたかを保持する
first_count: 最初の4バイトは反転する必要があるためカウントする
*/
struct Crc32 {
divisor: u32,
non_divisor: u32,
buffer: u8,
buf_count: u8,
first_count: u8,
}
impl Crc32 {
pub fn new() -> Self {
Crc32{
divisor: 0b100110000010001110110110111,
non_divisor: 0,
buffer: 0,
buf_count: 0,
first_count: 0,
}
}
/*
non_divisorやbufferにデータを保持させるもの
*/
pub fn push_buf(&mut self, buf: u8){
let mut buffer: u8 = 0;
for i in 0..8 {
buffer <<= 1;
buffer |= (buf >> i) & 1;
}
if self.first_count < 4 {
self.non_divisor <<= 8;
self.non_divisor += !buffer as u32;
self.first_count += 1;
} else {
self.buffer = buffer.clone();
self.buf_count = 8;
self.bit_shift();
}
}
/*
先頭bitが立っている場合には除算を行い、それ以外の場合にはbufferのbitを先頭から突っ込む
*/
fn bit_shift(&mut self){
for i in 0..self.buf_count{
if self.non_divisor >= 2147483648{
self.non_divisor <<= 1;
self.non_divisor |= (((self.buffer as u16) >> (self.buf_count - i - 1)) & 1) as u32;
self.xor();
} else {
self.non_divisor <<= 1;
self.non_divisor |= (((self.buffer as u16) >> (self.buf_count - i - 1)) & 1) as u32;
}
}
self.buf_count = 0
}
/*
除算を行う。実際にはxor
*/
fn xor(&mut self){
let buffer = self.non_divisor ^ self.divisor;
self.non_divisor = buffer;
}
/*
現在のnon_divisorからcrc32を計算してそれを返す
*/
fn get_crc32(&mut self) -> u32 {
self.push_buf(0);
self.push_buf(0);
self.push_buf(0);
self.push_buf(0);
let mut buffer: u32 = 0;
for i in 0..32 {
buffer <<= 1;
buffer |= (self.non_divisor >> i) & 1;
}
if PRINT_DEBUG == true {
println!("crc32: {:08x?}", !buffer);
}
!buffer
}
}
/*
zipのローカルヘッダーやセントラルヘッダー、エンドセントラルヘッダなどを
保持するための構造体
buffer: ヘッダー情報を保持する
before_size: 圧縮前のサイズを保持する
after_size: 圧縮後のサイズを保持する
filename: ファイルの名前を保持する
crc32: crc32の情報を保持する
hms: 時間, 分, 秒のデータを保持する
ymd: 年, 月, 日のデータを保持する
*/
struct Header{
buffer: Vec<u8>,
before_size: u32,
after_size: u32,
filename: String,
crc32: u32,
hms: u16,
ymd: u16,
}
impl Header {
pub fn new(before_size: u32, after_size: u32, filename: impl Into<String>, crc32: u32, hms: u16, ymd: u16) -> Self {
Header{
buffer: Vec::new(),
before_size,
after_size,
filename: filename.into(),
crc32,
hms,
ymd,
}
}
/*
32bitの情報をbufferに追加する
*/
fn push32(&mut self, num: u32) {
let a = num & 0b11111111;
let b = (num >> 8) & (0b11111111);
let c = (num >> 16) & (0b11111111);
let d = (num >> 24) & (0b11111111);
self.buffer.push(a as u8);
self.buffer.push(b as u8);
self.buffer.push(c as u8);
self.buffer.push(d as u8);
}
/*
16bitの情報をbufferに追加する
*/
fn push16(&mut self, num: u16) {
let a = num & 0b11111111;
let b = (num >> 8) & (0b11111111);
self.buffer.push(a as u8);
self.buffer.push(b as u8);
}
/*
PK0506ヘッダであることを示す情報を追加する
*/
fn push_pk0506(&mut self){
self.buffer.push(0x50);
self.buffer.push(0x4b);
self.buffer.push(0x05);
self.buffer.push(0x06);
}
/*
PK0304ヘッダであることを示す情報を追加する
*/
fn push_pk0304(&mut self){
self.buffer.push(0x50);
self.buffer.push(0x4b);
self.buffer.push(0x03);
self.buffer.push(0x04);
}
/*
PK0102ヘッダであることを示す情報を追加する
*/
fn push_pk0102(&mut self){
self.buffer.push(0x50);
self.buffer.push(0x4b);
self.buffer.push(0x01);
self.buffer.push(0x02);
}
/*
ファイルの名前の情報を追加する
*/
fn push_filename(&mut self){
let bytes: &[u8] = self.filename.as_bytes();
for i in 0..bytes.len() {
self.buffer.push(bytes[i]);
}
}
/*
ローカルヘッダーに必要な情報をもらって、ローカルヘッダーを作成する
構造
8byte: PK0304ヘッダを示す情報
4byte: 展開に必要なバージョン(2.0)
4byte: オプション(今回は設定していない)
4byte: 使用圧縮アルゴリズム(deflate圧縮: 0008)
4byte: 時刻
4byte: 日付
8byte: crc32情報
8byte: 圧縮後のサイズ(mとする)
8byte: 圧縮前のサイズ
4byte: ファイル名の長さ(nとする)
4byte: コメントがあればその長さ(今回はないものとしている)
nbyte: ファイル名
mbyte: 圧縮したデータ(ここではpushしておらず、ファイルに書き込む際に追加している)
*/
pub fn local_header(mut self) -> Vec<u8> {
self.push_pk0304();
self.push16(0x0014);
self.push16(0x0000);
self.push16(0x0008);
self.push16(self.hms);
self.push16(self.ymd);
self.push32(self.crc32);
self.push32(self.after_size);
self.push32(self.before_size);
self.push16((self.filename.len()) as u16);
self.push16(0x0000);
self.push_filename();
self.buffer
}
/*
セントラルヘッダーに必要な情報をもらって、セントラルヘッダーを作成する
8byte: PK0102ヘッダを示す情報
4byte: 作成したバージョン(ここでは2.0としている)
4byte: 展開に必要なバージョン(2.0)
4byte: オプション(今回は設定していない)
4byte: 使用圧縮アルゴリズム(deflate圧縮)
4byte: 時刻
4byte: 日付
8byte: crc32情報
8byte: 圧縮後のサイズ
8byte: 圧縮前のサイズ
4byte: ファイル名の長さ(nとする)
4byte: 拡張フィールドの長さ。(使用していないため0)
4byte: コメントがあればその長さ(今回はないものとしている)
4byte: 分割されている場合、対応するPK0304ヘッダが格納されたパートの番号
(分割していないため0)
4byte: 対応するPK0304に格納したファイルの属性情報(0としている)
8byte: OSで保持していた対象ファイルの属性情報(0としている)
8byte: 対応するPK0304ヘッダの位置
(今回はファイル一つのみの設定であるため0としている)
nbyte: ファイル名
*/
pub fn central_header(mut self) -> Vec<u8> {
self.push_pk0102();
self.push16(0x0314);
self.push16(0x0014);
self.push16(0x0000);
self.push16(0x0008);
self.push16(self.hms);
self.push16(self.ymd);
self.push32(self.crc32);
self.push32(self.after_size);
self.push32(self.before_size);
self.push16((self.filename.len()) as u16);
self.push16(0x0000);
self.push16(0x0000);
self.push16(0x0000);
self.push16(0x0000);
self.push32(0x00000000);
self.push32(0x00000000);
self.push_filename();
self.buffer
}
/*
エンドセントラルヘッダーに必要な情報をもらって、エンドセントラルヘッダーを作成する
8byte: PK0506ヘッダを示す情報
4byte: 分割している場合にはこのパートの番号(分割していないため0)
4byte: 分割している場合には最初のPK0304が格納されたパートの番号(分割していないため0)
4byte: 分割時にこのパートに格納されているファイル数(分割していないため下と同じ)
4byte: 圧縮したファイルの数(1としている)
8byte: PK0102ヘッダの合計サイズ
8byte: PK0102ヘッダの開始位置
4byte: コメントの長さ(今回は無し)
*/
pub fn end_header(mut self, header_size: u32, header_start: u32) -> Vec<u8>{
self.push_pk0506();
self.push16(0x0000);
self.push16(0x0000);
self.push16(0x0001);
self.push16(0x0001);
self.push32(header_size);
self.push32(header_start);
self.push16(0x00);
self.buffer
}
/*
cloneの実装を行なっている
*/
pub fn clone(&self) -> Self {
Header::new(self.before_size, self.after_size, self.filename.clone(), self.crc32, self.hms, self.ymd)
}
}
/*
ファイルの最終更新日時を取得してそれぞれをzipに必要な形式にして返す。
下のurlのヘッダ構造の部分から形式を知った。
https://hgotoh.jp/wiki/doku.php/documents/other/other-017
*/
fn time_data(filename: &str) -> (u16, u16) {
let times;
if let Ok(metadata) = metadata(filename) {
if let Ok(time) = metadata.modified() {
if let Ok(epoch) = time.duration_since(std::time::SystemTime::UNIX_EPOCH) {
times = epoch.as_secs();
} else {
times = 0;
}
} else {
let now = std::time::SystemTime::now();
if let Ok(epoch) = now.duration_since(std::time::SystemTime::UNIX_EPOCH) {
times = epoch.as_secs();
} else {
times = 0;
}
}
} else {
times = 0;
}
let data = Local.timestamp(times as i64, 0);
let mut hms = 0;
hms += (data.hour() as u32)<< 11;
hms += (data.minute() as u32) << 5;
hms += (data.second() as u32) / 2;
let mut ymd = 0;
ymd += ((data.year() - 1980) as u32) << 9;
ymd += (data.month() as u32) << 5;
ymd += data.day() as u32;
(hms as u16, ymd as u16)
}
/*
windowの中にcheckと同じ並びのものがあるかを調べる。
あった際には距離を返す。
*/
fn match_check<T: Eq>(window: &[T], check: &[T]) -> isize {
if window.len() < check.len(){
return -1;
}
'outer: for i in 0..(window.len() - check.len() + 1) {
for j in 0..(check.len()){
if window[i + j] != check[j]{
continue 'outer;
}
}
if PRINT_DEBUG == true {
println!("{} {} {}", window.len(), check.len(), i);
}
return (window.len() - check.len() - i + 1) as isize;
}
-1
}
/*
固定ハフマンに変換する
*/
fn changer(num: usize) -> (u8, u16) {
let (len, re) = match num {
0 ..= 143 => (8, num + 0x30 ),
144 ..= 255 => (9, num + 0x91 ),
256 ..= 279 => (7, num - 0x100),
280 ..= 287 => (8, num - 0x58 ),
_ => (0, 512),
};
(len, re as u16)
}
/*
長さから長さ符号と拡張ビットを調べる
*/
fn length_extra(data: u16) -> (u16, u8, u16){
let (num, len, extra) = match data {
3 ..= 10 => (data + 254, 0, 0),
11 ..= 12 => (265, 1, ((data - 3)) & 0b1),
13 ..= 14 => (266, 1, ((data - 3)) & 0b1),
15 ..= 16 => (267, 1, ((data - 3)) & 0b1),
17 ..= 18 => (268, 1, ((data - 3)) & 0b1),
19 ..= 22 => (269, 2, ((data - 3)) & 0b11),
23 ..= 26 => (270, 2, ((data - 3)) & 0b11),
27 ..= 30 => (271, 2, ((data - 3)) & 0b11),
31 ..= 34 => (272, 2, ((data - 3)) & 0b11),
35 ..= 42 => (273, 3, ((data - 3)) & 0b111),
43 ..= 50 => (274, 3, ((data - 3)) & 0b111),
51 ..= 58 => (275, 3, ((data - 3)) & 0b111),
59 ..= 66 => (276, 3, ((data - 3)) & 0b111),
67 ..= 82 => (277, 4, ((data - 3)) & 0b1111),
83 ..= 98 => (278, 4, ((data - 3)) & 0b1111),
99 ..= 114 => (279, 4, ((data - 3)) & 0b1111),
115 ..= 130 => (280, 4, ((data - 3)) & 0b1111),
131 ..= 162 => (281, 5, ((data - 3)) & 0b11111),
163 ..= 194 => (282, 5, ((data - 3)) & 0b11111),
195 ..= 226 => (283, 5, ((data - 3)) & 0b11111),
227 ..= 257 => (284, 5, ((data - 3)) & 0b11111),
_ => (286, 6, 0)
};
(num as u16 ,len as u8 ,extra as u16)
}
/*
距離から距離符号と拡張ビットを調べる
*/
fn distance_extra(data: u32) -> (u8, u8, u16){
let (num, dis, extra) = match data {
1 ..= 4 => (data - 1,0, 0),
5 ..= 6 => (4 ,1 , (data - 1) & 0b1),
7 ..= 8 => (5 ,1 , (data - 1) & 0b1),
9 ..= 12 => (6 ,2 , (data - 1) & 0b11),
13 ..= 16 => (7 ,2 , (data - 1) & 0b11),
17 ..= 24 => (8 ,3 , (data - 1) & 0b111),
25 ..= 32 => (9 ,3 , (data - 1) & 0b111),
33 ..= 48 => (10,4 , (data - 1) & 0b1111),
49 ..= 64 => (11,4 , (data - 1) & 0b1111),
65 ..= 96 => (12,5 , (data - 1) & 0b11111),
97 ..= 128 => (13,5 , (data - 1) & 0b11111),
129 ..= 192 => (14,6 , (data - 1) & 0b111111),
193 ..= 256 => (15,6 , (data - 1) & 0b111111),
257 ..= 384 => (16,7 , (data - 1) & 0b1111111),
385 ..= 512 => (17,7 , (data - 1) & 0b1111111),
513 ..= 768 => (18,8 , (data - 1) & 0b11111111),
769 ..= 1024 => (19,8 , (data - 1) & 0b11111111),
1025 ..= 1536 => (20,9 , (data - 1) & 0b111111111),
1537 ..= 2048 => (21,9 , (data - 1) & 0b111111111),
2049 ..= 3072 => (22,10, (data - 1) & 0b1111111111),
3073 ..= 4096 => (23,10, (data - 1) & 0b1111111111),
4097 ..= 6144 => (24,11, (data - 1) & 0b11111111111),
6145 ..= 8192 => (25,11, (data - 1) & 0b11111111111),
8193 ..= 12288 => (26,12, (data - 1) & 0b111111111111),
12289 ..= 16384 => (27,12, (data - 1) & 0b111111111111),
16385 ..= 24576 => (28,13, (data - 1) & 0b1111111111111),
24577 ..= 32768 => (29,13, (data - 1) & 0b1111111111111),
_ => (31, 14, 0)
};
(num as u8 ,dis as u8, extra as u16)
}
/*
エンコード処理を行い、zip形式で出力を行う。
deflate圧縮の固定ハフマン方式を使用してそれをzip形式にしている。
固定ハフマンについては下のurlを参考にして作成を行なった。
https://darkcrowcorvus.hatenablog.jp/?page=1483525541
https://wiki.suikawiki.org/n/DEFLATE#anchor-106
https://www.slideshare.net/7shi/deflate
zipのフォーマットについては下のurlを参考にして作成を行なった。
https://hgotoh.jp/wiki/doku.php/documents/other/other-017
http://menyukko.ifdef.jp/cauldron/dtzipformat.html
デバッグは出力を手で解析して行なった。
*/
pub fn encode(input_file: &str, output_file: &str) -> Result<(), std::io::Error> {
let mut input = File::open(input_file)?;
let mut output = File::create(output_file)?;
let mut input_reader = ByteReader::new(&mut input);
let mut output_writer = BitWriter::new(&mut output);
let mut crcs = Crc32::new();
let mut window = Vec::new();
output_writer.extra_bits(0b1, 1)?;
output_writer.extra_bits(0b01, 2)?;
let first = input_reader.get_byte();
crcs.push_buf(first.clone());
let (bit, first_data)= changer(first as usize);
output_writer.code_bits(first_data, bit)?;
loop{
if input_reader.flag == false { break;}
let byte = input_reader.get_byte();
if PRINT_DEBUG == true {
println!("{:02x?}", byte);
}
crcs.push_buf(byte.clone());
let mut res = vec![byte.clone()];
let mut offset: isize = -1;
window.push(res[0]);
while res.len() < MAX_MATCH_LEN {
let v = input_reader.seek_byte().clone();
res.push(v);
let new_offset = match_check(&mut window, &mut res);
window.push(v);
if new_offset == -1 {
res.pop();
window.pop();
break;
}
offset = new_offset;
crcs.push_buf(v.clone());
input_reader.next_byte();
if input_reader.flag == false { break };
}
if res.len() < MIN_MATCH_LEN {
for byte in &res {
let (bits, buf) = changer(*byte as usize);
output_writer.code_bits(buf, bits)?;
if PRINT_DEBUG == true {
println!("{:09b} :{}", buf, bits);
}
}
} else {
let (num , data, extra) = length_extra(res.len() as u16);
let (bits, buf) = changer(num as usize);
output_writer.code_bits(buf, bits)?;
if PRINT_DEBUG == true {
println!("{:09b} :{}", buf, bits);
}
output_writer.extra_bits(extra, data)?;
if PRINT_DEBUG == true {
println!("{:05b} :{}", extra, data);
}
let (num , data, extra) = distance_extra(offset as u32);
output_writer.code_bits(num as u16, 5)?;
if PRINT_DEBUG == true {
println!("{:05b} :{}", num, 5);
}
output_writer.extra_bits(extra , data)?;
if PRINT_DEBUG == true {
println!("{:09b} :{}", extra, data);
}
}
if window.len() > MAX_WINDOW_SIZE{
window.drain(0..(window.len() - MAX_WINDOW_SIZE));
}
}
output_writer.code_bits(0b0000000, 7)?;
output_writer.flush()?;
let crc32 = crcs.get_crc32();
let (hms, ymd) = time_data(&input_file);
let header = Header::new(input_reader.file_size, (output_writer.output_vector.len()) as u32, input_file, crc32, hms, ymd);
let local_header = header.clone().local_header();
let central_header = header.clone().central_header();
let end_header = header.clone().end_header((central_header.len()) as u32, (local_header.len() + output_writer.output_vector.len()) as u32);
if PRINT_DEBUG == true {
for i in 0..(output_writer.output_vector.len()){
print!("{:08b}", output_writer.output_vector[i]);
}
println!();
}
/*
ここでzipファイルを出力している。
*/
output_writer.output.write_all(&local_header)?;
output_writer.output.write_all(&output_writer.output_vector)?;
output_writer.output.write_all(¢ral_header)?;
output_writer.output.write_all(&end_header)?;
Ok(())
}
| true |
ce1c25467dabbb70b581c2d354c4837dcbde20bb
|
Rust
|
scottnm/snm_rand_utils
|
/src/test_utils.rs
|
UTF-8
| 341 | 2.671875 | 3 |
[
"MIT"
] |
permissive
|
#[cfg(test)]
use crate::range_rng::RangeRng;
/// sample_gen_range_caller is used to exercise different implementations of the RangeRng
/// trait being passed to a function via trait reference.
#[cfg(test)]
pub fn sample_gen_range_caller<T: PartialOrd>(rng: &mut dyn RangeRng<T>, lower: T, upper: T) -> T {
rng.gen_range(lower, upper)
}
| true |
89e6c21e9b0c3df251b71d91543b00a0c6300e80
|
Rust
|
addam128/cextractor
|
/src/analyzers/title_finder.rs
|
UTF-8
| 2,123 | 2.84375 | 3 |
[
"MIT"
] |
permissive
|
use regex::Regex;
use json::JsonValue;
use crate::utils;
use super::traits::Analyzer;
pub(crate) struct TitleFinder {
_title_regexes: [Regex; 7],
_title: String
}
impl TitleFinder {
pub(crate) fn new() -> Result<Self, utils::Error> {
Ok(
Self{
_title: String::new(),
_title_regexes: [
Regex::new(r"(?i)Security (?i)Target[ Lite]*\s*(.*(\s*.*)*)(Common Criteria|Reference)")?,
Regex::new(r"EAL\d\+(.+)Document version")?,
Regex::new(r"(\S+(\s*.*)*)\s*Security Target Lite")?,
Regex::new(r"(\S+(\s*.*)*)\s*CC Document")?,
Regex::new(r"for\s*(.*(\s*.*)*)from")?,
Regex::new(r"EAL6\+\s+(.*(\s*.*)+)\s+H13")?,
Regex::new(r"Version \d{4}-\d\s+(.*(\s*.*)*)\s+Sponsor")?]
}
)
}
}
impl Analyzer for TitleFinder {
fn process(&mut self, chunk: &str) -> Result<(), utils::Error> {
if !self._title.is_empty() {
return Ok(());
}
let mut text = "".to_owned();
for line in chunk.lines(){
text.push_str(line);
for title_regex in &self._title_regexes{
match title_regex.captures(&text) {
None => {continue}
Some(_) => {
let caps = title_regex.captures(&text).unwrap();
let mut i = 1;
while caps.get(i) == None {
i += 1;
}
self._title = caps.get(i).map_or("", |m| m.as_str()).replace("\n", "");
return Ok(())
}
}
}
}
Ok(())
}
fn finalize(&mut self) -> Result<JsonValue, utils::Error> {
let re = Regex::new(r"\s+").unwrap();
let result_title = re.replace_all(&self._title, " ");
Ok(
JsonValue::from(result_title.trim())
)
}
fn clear(&mut self){
self._title.clear();
}
}
| true |
28e8fde20ee1acc254e304d6b371761f4270a388
|
Rust
|
ytakasugi/workspace
|
/Rust_workspace/introduction/section15/intro_1504/intro_1504_06/src/main.rs
|
UTF-8
| 1,698 | 3.78125 | 4 |
[] |
no_license
|
// ジェネリック型に境界(bound)を与え、特定のトレイトを実装していることを保証できるのと同様、
// ライフタイム(それ自身ジェネリック型)にも境界を与えることができます。
// ここでは多少異なる意味を持ちますが`+`は同じです。以下の構文の意味をチェックしてください。
//
// 1.T: 'a: T内の 全ての 参照は'aよりも長生きでなくてはならない
// 2.T: Trait + 'a: 上に加えてTはTraitという名のトレイトを実装してなくてはならない。
//
// 上記の構文を実際に動く例で見ていきましょう。whereキーワードの後に注目してください。
// ライフタイムを紐付けるトレイト
use std::fmt::Debug;
// `Ref`は`'a`というライフタイムを持つジェネリック型`T`に対する参照を持ち、
// `T`の値に対する参照は必ず`'a`よりも長生きでなくてはならない。
// さらに、`Ref`のライフタイムは`'a`を超えてはならない。
#[derive(Debug)]
struct Ref<'a, T: 'a>(&'a T);
// `Debug`トレイトを利用してプリントを行うジェネリック関数
fn print<T>(t: T)
where
T: Debug
{
println!("`print`: t is {:?}", t);
}
// `Debug`を実装している`T`への参照を取る。
// `T`への参照は必ず`'a`よりも長生きでなくてはならない。
// さらに、`'a`は関数自体よりも長生きでなくてはならない。
fn print_ref<'a, T>(t: &'a T)
where
T: Debug + 'a
{
println!("`print_ref`: t is {:?}", t);
}
fn main() {
let x = 7;
let ref_x = Ref(&x);
print_ref(&ref_x);
print(ref_x);
}
| true |
46307c652529734828950d7abe5ff2354cdad6f9
|
Rust
|
JayThomason/rays
|
/src/material.rs
|
UTF-8
| 2,831 | 3.109375 | 3 |
[] |
no_license
|
use crate::hittable::HitRecord;
use crate::ray::Ray;
use crate::vec3::{Color, Vec3, reflect, refract};
use rand::Rng;
pub trait Material {
fn scatter(&self, r_in: &Ray, rec: &HitRecord) -> Option<(Ray, Color)>;
}
#[derive(Debug, Copy, Clone)]
pub struct Lambertian {
pub albedo: Color,
}
unsafe impl Send for Lambertian {}
unsafe impl Sync for Lambertian {}
impl Lambertian {
pub fn new(albedo: Color) -> Lambertian {
Lambertian{albedo}
}
}
impl Material for Lambertian {
fn scatter(&self, _r_in: &Ray, rec: &HitRecord) -> Option<(Ray, Color)> {
let mut scatter_direction = rec.normal + Vec3::random_unit_vector();
if scatter_direction.near_zero() {
scatter_direction = rec.normal;
}
let scattered = Ray::new(rec.p, scatter_direction);
let attenuation = self.albedo;
Some((scattered, attenuation))
}
}
#[derive(Debug, Copy, Clone)]
pub struct Metal {
pub albedo: Color,
pub fuzz: f64
}
unsafe impl Send for Metal {}
unsafe impl Sync for Metal {}
impl Metal {
pub fn new(albedo: Color, fuzz: f64) -> Metal {
Metal{albedo, fuzz}
}
}
impl Material for Metal {
fn scatter(&self, r_in: &Ray, rec: &HitRecord) -> Option<(Ray, Color)> {
let reflected: Vec3 = reflect(&r_in.dir.unit_vec(), &rec.normal);
let scattered = Ray::new(rec.p, reflected + self.fuzz*Vec3::random_in_unit_sphere());
let attenuation = self.albedo;
if scattered.dir.dot(&rec.normal) > 0. {
Some((scattered, attenuation))
} else {
None
}
}
}
pub struct Dielectric {
pub ir: f64,
}
unsafe impl Send for Dielectric {}
unsafe impl Sync for Dielectric {}
fn reflectance(cosine: f64, ref_idx: f64) -> f64 {
// Use Schlick's approximation for reflectance.
let mut r0 = (1. - ref_idx) / (1. + ref_idx);
r0 = r0 * r0;
r0 + (1. - r0) * (1. - cosine).powf(5.)
}
impl Material for Dielectric {
fn scatter(&self, r_in: &Ray, rec: &HitRecord) -> Option<(Ray, Color)> {
let attenuation = Color::new(1., 1., 1.);
let refraction_ratio = if rec.front_face { 1./self.ir } else { self.ir };
let unit_direction = r_in.dir.unit_vec();
let cos_theta = (-unit_direction).dot(&rec.normal).min(1.);
let sin_theta = (1. - cos_theta*cos_theta).sqrt();
let cannot_refract = refraction_ratio * sin_theta > 1.0;
let mut rng = rand::thread_rng();
let direction = if cannot_refract || reflectance(cos_theta, refraction_ratio) > rng.gen_range(0.0, 1.0) {
reflect(&unit_direction, &rec.normal)
} else {
refract(&unit_direction, &rec.normal, refraction_ratio)
};
let scattered = Ray::new(rec.p, direction);
Some((scattered, attenuation))
}
}
| true |
537ea4b5c4f60a885ebf1c7679ed61fa24896abb
|
Rust
|
s4i/cargo-rls-install
|
/examples/rustup.rs
|
UTF-8
| 1,182 | 2.765625 | 3 |
[
"MIT"
] |
permissive
|
use regex::Regex;
use std::process::Command;
fn main() {
let output = if cfg!(target_os = "windows") {
String::from_utf8(
Command::new("cmd")
.args(&["/C", "rustup show"])
.output()
.expect("failed to execute process")
.stdout,
)
.unwrap()
} else {
String::from_utf8(
Command::new("rustup")
.arg("show")
.output()
.expect("rustup show failed")
.stdout,
)
.unwrap()
};
println!("{:?}", output);
let lines: Vec<&str> = output.split('\n').collect();
let re_nightly = Regex::new(r"^nightly-\d{4}-\d{2}-\d{2}-").unwrap();
let re_date = Regex::new(r"\d{4}-\d{2}-\d{2}").unwrap();
let mut installed_toolchain = vec![];
for line in &lines {
// End loop: Find "active toolchain" line
if line.starts_with("active") {
break;
}
if re_nightly.is_match(line) {
installed_toolchain.push(re_date.find(line).unwrap().as_str().to_owned());
}
}
println!("{:?}", installed_toolchain);
}
| true |
8d35769ec91919bd4274e5a81fb7783477963b1e
|
Rust
|
simmons/cbm
|
/src/disk/chain.rs
|
UTF-8
| 12,572 | 3.140625 | 3 |
[
"Apache-2.0",
"MIT"
] |
permissive
|
use std::collections::HashSet;
use std::io::{self, Write};
use crate::disk::bam::BamRef;
use crate::disk::block::{BlockDeviceRef, Location, BLOCK_SIZE};
use crate::disk::directory::DirectoryEntry;
use crate::disk::error::DiskError;
/// A "zero" chain link is a link that indicates that this is a tail block, and
/// it has zero data bytes used. (Which means it has a total of two bytes
/// used, counting the link itself.)
pub static CHAIN_LINK_ZERO: ChainLink = ChainLink::Tail(2);
#[derive(Debug)]
pub enum ChainLink {
Next(Location),
Tail(usize), // used bytes
}
impl ChainLink {
#[inline]
pub fn new(block: &[u8]) -> io::Result<ChainLink> {
if block[0] == 0x00 {
// This is the last sector of the chain, so the next byte indicates how much of
// this sector is actually used.
if block[1] < 1 {
// It's not valid for a chain sector to not include the first two bytes
// as allocated.
return Err(DiskError::InvalidChainLink.into());
}
Ok(ChainLink::Tail(block[1] as usize + 1)) // 2..=256
} else {
Ok(ChainLink::Next(Location::new(block[0], block[1])))
}
}
#[inline]
pub fn to_bytes(&self, bytes: &mut [u8]) {
assert!(bytes.len() >= 2);
match &self {
ChainLink::Next(location) => location.write_bytes(bytes),
ChainLink::Tail(size) => {
assert!(*size >= 2 && *size <= 256);
bytes[0] = 0x00;
bytes[1] = (*size - 1) as u8;
}
}
}
}
/// A ChainSector is the result of a chain iteration, and provides the block contents and the
/// location from which it was read.
pub struct ChainSector {
/// The 256-byte block contents, which includes the two-byte NTS (next track and sector) link.
pub data: Vec<u8>,
pub location: Location,
}
/// Returns a ChainSector which includes the NTS (next track and sector) link.
pub struct ChainIterator {
blocks: BlockDeviceRef,
next_sector: Option<Location>,
visited_sectors: HashSet<Location>,
block: [u8; BLOCK_SIZE],
}
impl ChainIterator {
/// Create a new chain iterator starting at the specified location.
pub fn new(blocks: BlockDeviceRef, starting_sector: Location) -> ChainIterator {
ChainIterator {
blocks,
next_sector: Some(starting_sector),
visited_sectors: HashSet::new(),
block: [0u8; BLOCK_SIZE],
}
}
/// Read the entire chain and return a list of locations.
pub fn locations(self) -> io::Result<Vec<Location>> {
self.map(|r| r.map(|cs| cs.location)).collect()
}
}
impl Iterator for ChainIterator {
type Item = io::Result<ChainSector>;
fn next(&mut self) -> Option<io::Result<ChainSector>> {
let location = match self.next_sector.take() {
Some(next) => next,
None => return None,
};
// Loop detection.
if !self.visited_sectors.insert(location) {
return Some(Err(DiskError::ChainLoop.into()));
}
// Read the next sector.
{
let blocks = self.blocks.borrow();
let block = match blocks.sector(location) {
Ok(b) => b,
Err(e) => return Some(Err(e)),
};
self.block.copy_from_slice(block);
}
// Trim the block if needed.
let size = match ChainLink::new(&self.block[..]) {
Ok(ChainLink::Next(location)) => {
self.next_sector = Some(location);
BLOCK_SIZE // The entire sector is used.
}
Ok(ChainLink::Tail(size)) => size,
Err(e) => return Some(Err(e)),
};
let block = &self.block[..size];
Some(Ok(ChainSector {
data: block.to_vec(),
location,
}))
}
}
/// ChainReader objects implement the Read trait are used to read a byte stream
/// represented as a series of chained sectors on the disk image. Simple files
/// (e.g. CBM PRG and SEQ files) store data in a single chain where the
/// beginning track and sector is provided in the directory entry. More exotic
/// file types (GEOS, REL, etc.) use more complex structures, possibly with
/// multiple ChainReader objects (e.g. a GEOS VLIR file may provide a
/// ChainReader for each record).
pub struct ChainReader {
chain: ChainIterator,
block: Option<Vec<u8>>,
eof: bool,
}
impl ChainReader {
pub fn new(blocks: BlockDeviceRef, start: Location) -> ChainReader {
let chain = ChainIterator::new(blocks, start);
ChainReader {
chain,
block: None,
eof: false,
}
}
}
impl io::Read for ChainReader {
fn read(&mut self, mut buf: &mut [u8]) -> io::Result<usize> {
let mut total_nbytes = 0;
while !buf.is_empty() && !self.eof {
match self.block.take() {
Some(mut block) => {
// Copy as much of this block as possible into the caller-provided buffer.
let nbytes = block.len().min(buf.len());
let _ = &buf[0..nbytes].copy_from_slice(&block[0..nbytes]);
total_nbytes += nbytes;
// Reduce the block slice to the unread portion (which may be zero bytes).
if block.len() == nbytes {
} else {
// Reduce
let mut tail = block.split_off(nbytes);
::std::mem::swap(&mut block, &mut tail);
// Return the unread portion
self.block = Some(block);
}
// Reduce the provided buffer slice to the unwritten portion.
let buf_ref = &mut buf;
let value: &mut [u8] = std::mem::take(buf_ref);
*buf_ref = &mut value[nbytes..];
}
None => {
// Read the next block.
match self.chain.next() {
Some(Ok(mut block)) => {
// discard the next-track/sector bytes
self.block = Some(block.data.split_off(2));
// Loop back to the Some(_) case to process the block.
}
Some(Err(e)) => {
self.eof = true;
return Err(e);
}
None => self.eof = true,
}
}
}
}
Ok(total_nbytes)
}
}
/// A writer for writing data to a chain. The chain is extended as needed according to the
/// allocation algorithm for the disk format.
pub struct ChainWriter {
blocks: BlockDeviceRef,
bam: BamRef,
entry: DirectoryEntry,
location: Location,
block: Vec<u8>,
dirty: bool,
}
impl ChainWriter {
pub fn new(
blocks: BlockDeviceRef,
bam: BamRef,
entry: DirectoryEntry,
start: Location,
) -> io::Result<ChainWriter> {
// Advance to the last block in the chain.
let tail_block;
let mut tail_location;
{
let blocks = blocks.borrow();
let mut block = blocks.sector(start)?;
tail_location = start;
while let ChainLink::Next(location) = ChainLink::new(block)? {
block = blocks.sector(location)?;
tail_location = location;
}
tail_block = block.to_vec();
}
Ok(ChainWriter {
blocks,
bam,
entry,
location: tail_location,
block: tail_block,
dirty: true,
})
}
fn increment_entry_blocks(&mut self) -> io::Result<()> {
let mut blocks = self.blocks.borrow_mut();
blocks.positioned_read(&mut self.entry)?;
self.entry.file_size += 1;
blocks.positioned_write(&self.entry)?;
Ok(())
}
fn allocate_next_block(&mut self) -> io::Result<usize> {
// NOTE: The ordering of these steps is important for consistency. We don't
// want a block to be allocated in BAM, then not used because an error
// was thrown later.
// Write the current block without the updated link.
self.write_current_block()?;
// Find a new block.
let next_location = self.bam.borrow_mut().next_free_block(None)?;
// Initialize a fresh block in memory with a link indicating a tail block with
// zero bytes used. (Really, two bytes used for the link, but zero data
// bytes used.)
for i in 2..BLOCK_SIZE {
self.block[i] = 0;
}
ChainLink::Tail(2).to_bytes(&mut self.block[..]);
// Write the fresh block to the new location
self.blocks
.borrow_mut()
.sector_mut(next_location)?
.copy_from_slice(&self.block);
// Allocate the next block.
self.bam.borrow_mut().allocate(next_location)?;
// Increment the directory entry's file size (measured in blocks)
self.increment_entry_blocks()?;
// If allocation succeeds, only then do we link the current block to the next
// block.
let mut blocks = self.blocks.borrow_mut();
let block = match blocks.sector_mut(self.location) {
Ok(block) => block,
Err(e) => {
// Roll back the allocation.
self.bam.borrow_mut().free(next_location)?;
return Err(e);
}
};
next_location.write_bytes(block);
// Update state
self.location = next_location;
// Return the available bytes in the newly loaded block, which is always two
// less than the block size.
Ok(BLOCK_SIZE - 2)
}
fn write_current_block(&mut self) -> io::Result<()> {
// Write the current block
let mut blocks = self.blocks.borrow_mut();
blocks
.sector_mut(self.location)?
.copy_from_slice(&self.block);
Ok(())
}
}
impl Drop for ChainWriter {
fn drop(&mut self) {
let _result = self.flush();
}
}
// NOTE: allocating and updating entry block size should be atomic.
impl io::Write for ChainWriter {
fn write(&mut self, mut buf: &[u8]) -> io::Result<usize> {
self.dirty = true;
let mut total_nbytes = 0;
while !buf.is_empty() {
let (offset, remaining) = match ChainLink::new(&self.block)? {
ChainLink::Next(_) => unreachable!(), // The stored buffer is always a tail block.
ChainLink::Tail(nbytes) if nbytes == BLOCK_SIZE => {
// Allocate a new block
let remaining = self.allocate_next_block()?;
(BLOCK_SIZE - remaining, remaining)
}
ChainLink::Tail(nbytes) => (nbytes, BLOCK_SIZE - nbytes),
};
// Copy as much of the caller-provided buffer as possible into the block.
let nbytes = remaining.min(buf.len());
let _ = &self.block[offset..offset + nbytes].copy_from_slice(&buf[0..nbytes]);
total_nbytes += nbytes;
// Update the block link's indication of used bytes.
ChainLink::Tail(offset + nbytes).to_bytes(&mut self.block);
// Reduce the provided buffer slice to the unwritten portion.
buf = &buf[nbytes..];
}
Ok(total_nbytes)
}
fn flush(&mut self) -> io::Result<()> {
if self.dirty {
// Write the current block
self.write_current_block()?;
// Flush the BAM
self.bam.borrow_mut().flush()?;
// Flush the underlying medium.
let mut blocks = self.blocks.borrow_mut();
blocks.flush()?;
self.dirty = false;
}
Ok(())
}
}
pub fn remove_chain(blocks: BlockDeviceRef, bam: BamRef, start: Location) -> io::Result<()> {
// Read the whole chain first to be sure we can visit every block with no
// errors.
let locations = ChainIterator::new(blocks, start).locations()?;
// Deallocate
let mut bam = bam.borrow_mut();
for location in locations {
bam.free(location)?;
}
bam.flush()?;
Ok(())
}
| true |
4952e57a0f1cb9dd9d6d55b3482e243f74d43a96
|
Rust
|
rustwasm/wasm-bindgen
|
/tests/wasm/option.rs
|
UTF-8
| 1,437 | 2.84375 | 3 |
[
"Apache-2.0",
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
use wasm_bindgen::prelude::*;
use wasm_bindgen_test::*;
#[wasm_bindgen(module = "tests/wasm/option.js")]
extern "C" {
pub type MyType;
#[wasm_bindgen(constructor)]
fn new() -> MyType;
fn take_none_byval(t: Option<MyType>);
fn take_some_byval(t: Option<MyType>);
fn return_undef_byval() -> Option<MyType>;
fn return_null_byval() -> Option<MyType>;
fn return_some_byval() -> Option<MyType>;
fn test_option_values();
#[wasm_bindgen(js_name = take_none_byval)]
fn take_none_byref(t: Option<&MyType>);
#[wasm_bindgen(js_name = take_some_byval)]
fn take_some_byref(t: Option<&MyType>);
}
#[wasm_bindgen_test]
fn import_by_value() {
take_none_byval(None);
take_some_byval(Some(MyType::new()));
assert!(return_null_byval().is_none());
assert!(return_undef_byval().is_none());
assert!(return_some_byval().is_some());
}
#[wasm_bindgen_test]
fn export_by_value() {
test_option_values();
}
#[wasm_bindgen]
pub fn rust_take_none_byval(t: Option<MyType>) {
assert!(t.is_none());
}
#[wasm_bindgen]
pub fn rust_take_some_byval(t: Option<MyType>) {
assert!(t.is_some());
}
#[wasm_bindgen]
pub fn rust_return_none_byval() -> Option<MyType> {
None
}
#[wasm_bindgen]
pub fn rust_return_some_byval() -> Option<MyType> {
Some(MyType::new())
}
#[wasm_bindgen_test]
fn import_by_ref() {
take_none_byref(None);
take_some_byref(Some(&MyType::new()));
}
| true |
0c9c74fb15d344aa23a7a395e7ab8ec945300032
|
Rust
|
aandrews-amu/American-Road-Trip-Path-Finding-Project
|
/final-project/src/sat.rs
|
UTF-8
| 1,493 | 3.125 | 3 |
[] |
no_license
|
use super::{Constraint, PartialValuation, ValueType, Var};
/// A SAT literal: a `Var` appears either positively or negatively.
pub enum Lit {
Pos(Var),
Neg(Var),
}
impl ValueType for bool {}
/// A SAT clause constraint, comprising a vec of literals; the clause
/// is satisfied if any literal is satisfied.
pub struct SAT(pub Vec<Lit>);
impl Constraint<bool> for SAT {
fn vars(&self) -> Vec<Var> {
self.0
.iter()
.map(|l| match l {
Lit::Pos(v) => *v,
Lit::Neg(v) => *v,
})
.collect()
}
fn is_satisfied(&self, vals: &PartialValuation<bool>) -> bool {
self.0.iter().any(|l| match *l {
Lit::Pos(v) => vals.get(v),
Lit::Neg(v) => !vals.get(v),
})
}
}
#[cfg(test)]
mod pub_tests {
use super::*;
use crate::{csp::CSP, Domain, Valuation};
#[test]
fn test_sat() {
let mut csp = CSP::new();
let v1 = csp.add_variable(Domain::new(vec![false, true]));
let v2 = csp.add_variable(Domain::new(vec![false, true]));
let v3 = csp.add_variable(Domain::new(vec![false, true]));
csp.add_constraint(SAT(vec![Lit::Pos(v1), Lit::Pos(v2)]));
csp.add_constraint(SAT(vec![Lit::Neg(v2), Lit::Neg(v3)]));
csp.add_constraint(SAT(vec![Lit::Pos(v3)]));
let soln = csp.solve();
assert!(soln.is_some());
assert_eq!(soln, Some(Valuation::new(vec![true, false, true])));
}
}
| true |
862995d5b425620240bbb1bbda32e3e23b599787
|
Rust
|
you-win/bevy
|
/crates/bevy_text/src/pipeline.rs
|
UTF-8
| 3,830 | 2.65625 | 3 |
[
"Apache-2.0",
"MIT",
"LicenseRef-scancode-other-permissive",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-unknown-license-reference",
"Zlib"
] |
permissive
|
use ab_glyph::{PxScale, ScaleFont};
use bevy_asset::{Assets, Handle, HandleId};
use bevy_ecs::component::Component;
use bevy_ecs::system::Resource;
use bevy_math::Vec2;
use bevy_render::texture::Image;
use bevy_sprite::TextureAtlas;
use bevy_utils::HashMap;
use glyph_brush_layout::{FontId, SectionText};
use crate::{
error::TextError, glyph_brush::GlyphBrush, scale_value, Font, FontAtlasSet, FontAtlasWarning,
PositionedGlyph, TextAlignment, TextSection, TextSettings, YAxisOrientation,
};
#[derive(Default, Resource)]
pub struct TextPipeline {
brush: GlyphBrush,
map_font_id: HashMap<HandleId, FontId>,
}
/// Render information for a corresponding [`Text`](crate::Text) component.
///
/// Contains scaled glyphs and their size. Generated via [`TextPipeline::queue_text`].
#[derive(Component, Clone, Default, Debug)]
pub struct TextLayoutInfo {
pub glyphs: Vec<PositionedGlyph>,
pub size: Vec2,
}
impl TextPipeline {
pub fn get_or_insert_font_id(&mut self, handle: &Handle<Font>, font: &Font) -> FontId {
let brush = &mut self.brush;
*self
.map_font_id
.entry(handle.id())
.or_insert_with(|| brush.add_font(handle.clone(), font.font.clone()))
}
#[allow(clippy::too_many_arguments)]
pub fn queue_text(
&mut self,
fonts: &Assets<Font>,
sections: &[TextSection],
scale_factor: f64,
text_alignment: TextAlignment,
bounds: Vec2,
font_atlas_set_storage: &mut Assets<FontAtlasSet>,
texture_atlases: &mut Assets<TextureAtlas>,
textures: &mut Assets<Image>,
text_settings: &TextSettings,
font_atlas_warning: &mut FontAtlasWarning,
y_axis_orientation: YAxisOrientation,
) -> Result<TextLayoutInfo, TextError> {
let mut scaled_fonts = Vec::new();
let sections = sections
.iter()
.map(|section| {
let font = fonts
.get(§ion.style.font)
.ok_or(TextError::NoSuchFont)?;
let font_id = self.get_or_insert_font_id(§ion.style.font, font);
let font_size = scale_value(section.style.font_size, scale_factor);
scaled_fonts.push(ab_glyph::Font::as_scaled(&font.font, font_size));
let section = SectionText {
font_id,
scale: PxScale::from(font_size),
text: §ion.value,
};
Ok(section)
})
.collect::<Result<Vec<_>, _>>()?;
let section_glyphs = self
.brush
.compute_glyphs(§ions, bounds, text_alignment)?;
if section_glyphs.is_empty() {
return Ok(TextLayoutInfo::default());
}
let mut min_x: f32 = std::f32::MAX;
let mut min_y: f32 = std::f32::MAX;
let mut max_x: f32 = std::f32::MIN;
let mut max_y: f32 = std::f32::MIN;
for sg in §ion_glyphs {
let scaled_font = scaled_fonts[sg.section_index];
let glyph = &sg.glyph;
min_x = min_x.min(glyph.position.x);
min_y = min_y.min(glyph.position.y - scaled_font.ascent());
max_x = max_x.max(glyph.position.x + scaled_font.h_advance(glyph.id));
max_y = max_y.max(glyph.position.y - scaled_font.descent());
}
let size = Vec2::new(max_x - min_x, max_y - min_y);
let glyphs = self.brush.process_glyphs(
section_glyphs,
§ions,
font_atlas_set_storage,
fonts,
texture_atlases,
textures,
text_settings,
font_atlas_warning,
y_axis_orientation,
)?;
Ok(TextLayoutInfo { glyphs, size })
}
}
| true |
b92b700ce38b8f243a922a7cc4a927d4557efd51
|
Rust
|
wibbe/organizer
|
/src/app.rs
|
UTF-8
| 544 | 2.78125 | 3 |
[] |
no_license
|
use ::ui::*;
use ::doc::*;
use ::glutin;
pub struct App<'a> {
ui: UI,
window: &'a glutin::Window,
doc: Box<Document>,
}
impl<'a> App<'a> {
pub fn new(mut ui: UI, window: &'a glutin::Window) -> App {
ui.print(10, 10, "Hello World", Color::new(230, 230, 230), Color::new(30, 40, 50));
App {
ui: ui,
window: window,
doc: Box::new(Document::default()),
}
}
pub fn paint(&self) {
let (w, h) = self.window.get_inner_size_pixels().unwrap();
self.ui.paint(w, h);
}
}
| true |
a055019bc2028f0c322951290486ab5777dcd155
|
Rust
|
bouzuya/rust-atcoder
|
/cargo-atcoder/contests/past202104-open/src/bin/l.rs
|
UTF-8
| 2,068 | 2.6875 | 3 |
[] |
no_license
|
use ordered_float::NotNan;
use proconio::input;
fn prim(e: &[Vec<(usize, NotNan<f64>)>], s: usize) -> NotNan<f64> {
let n = e.len();
let mut used = vec![false; n];
let mut d = NotNan::new(0_f64).unwrap();
let mut pq = std::collections::BinaryHeap::new();
pq.push(std::cmp::Reverse((NotNan::new(0_f64).unwrap(), s)));
while let Some(std::cmp::Reverse((c_u, u))) = pq.pop() {
if used[u] {
continue;
}
used[u] = true;
d += c_u;
for &(v, c_v) in e[u].iter() {
if !used[v] {
pq.push(std::cmp::Reverse((c_v, v)));
}
}
}
d
}
fn distance((x_i, y_i, r_i): (f64, f64, f64), (x_j, y_j, r_j): (f64, f64, f64)) -> f64 {
let d = ((x_i - x_j).powf(2_f64) + (y_i - y_j).powf(2_f64)).sqrt();
if d > (r_i + r_j) {
d - (r_i + r_j)
} else if d <= (r_i + r_j) && (r_i - r_j).abs() > d {
(r_i - r_j).abs() - d
} else {
0_f64
}
}
fn main() {
input! {
n: usize,
m: usize,
p: [(i64, i64); n],
c: [(i64, i64, i64); m],
};
let inf = NotNan::new(1_000_000_000_000_f64).unwrap();
let mut res = inf;
for bits in 0..1 << m {
let s = p
.iter()
.copied()
.map(|(px_i, py_i)| (px_i as f64, py_i as f64, 0_f64))
.chain(
c.iter()
.enumerate()
.filter(|&(j, _)| (bits >> j) & 1 == 1)
.map(|(_, &(cx_i, cy_i, r_i))| (cx_i as f64, cy_i as f64, r_i as f64)),
)
.collect::<Vec<(f64, f64, f64)>>();
let mut edges = vec![vec![]; s.len()];
for i in 0..s.len() {
for j in i + 1..s.len() {
let w = distance(s[i], s[j]);
edges[i].push((j, NotNan::new(w).unwrap()));
edges[j].push((i, NotNan::new(w).unwrap()));
}
}
let sum = prim(&edges, 0);
res = res.min(sum);
}
let ans = res;
println!("{}", ans);
}
| true |
73e850162115b6767ee7aa14204fde96d287a018
|
Rust
|
panoptesDev/tari-crypto
|
/src/signatures/schnorr.rs
|
UTF-8
| 4,669 | 3.21875 | 3 |
[] |
no_license
|
//! Schnorr Signature module
//! This module defines generic traits for handling the digital signature operations, agnostic
//! of the underlying elliptic curve implementation
use crate::keys::{PublicKey, SecretKey};
use serde::{Deserialize, Serialize};
use std::{
cmp::Ordering,
ops::{Add, Mul},
};
use tari_utilities::ByteArray;
use thiserror::Error;
#[derive(Clone, Debug, Error, PartialEq, Eq, Deserialize, Serialize)]
pub enum SchnorrSignatureError {
#[error("An invalid challenge was provided")]
InvalidChallenge,
}
#[allow(non_snake_case)]
#[derive(PartialEq, Eq, Copy, Debug, Clone, Serialize, Deserialize, Hash)]
pub struct SchnorrSignature<P, K> {
public_nonce: P,
signature: K,
}
impl<P, K> SchnorrSignature<P, K>
where
P: PublicKey<K = K>,
K: SecretKey,
{
pub fn new(public_nonce: P, signature: K) -> Self {
SchnorrSignature {
public_nonce,
signature,
}
}
pub fn calc_signature_verifier(&self) -> P {
P::from_secret_key(&self.signature)
}
pub fn sign(secret: K, nonce: K, challenge: &[u8]) -> Result<Self, SchnorrSignatureError>
where K: Add<Output = K> + Mul<P, Output = P> + Mul<Output = K> {
// s = r + e.k
let e = match K::from_bytes(challenge) {
Ok(e) => e,
Err(_) => return Err(SchnorrSignatureError::InvalidChallenge),
};
let public_nonce = P::from_secret_key(&nonce);
let ek = e * secret;
let s = ek + nonce;
Ok(Self::new(public_nonce, s))
}
pub fn verify_challenge<'a>(&self, public_key: &'a P, challenge: &[u8]) -> bool
where
for<'b> &'b K: Mul<&'a P, Output = P>,
for<'b> &'b P: Add<P, Output = P>,
{
let e = match K::from_bytes(&challenge) {
Ok(e) => e,
Err(_) => return false,
};
self.verify(public_key, &e)
}
pub fn verify<'a>(&self, public_key: &'a P, challenge: &K) -> bool
where
for<'b> &'b K: Mul<&'a P, Output = P>,
for<'b> &'b P: Add<P, Output = P>,
{
let lhs = self.calc_signature_verifier();
let rhs = &self.public_nonce + challenge * public_key;
// Implementors should make this a constant time comparison
lhs == rhs
}
#[inline]
pub fn get_signature(&self) -> &K {
&self.signature
}
#[inline]
pub fn get_public_nonce(&self) -> &P {
&self.public_nonce
}
}
impl<'a, 'b, P, K> Add<&'b SchnorrSignature<P, K>> for &'a SchnorrSignature<P, K>
where
P: PublicKey<K = K>,
&'a P: Add<&'b P, Output = P>,
K: SecretKey,
&'a K: Add<&'b K, Output = K>,
{
type Output = SchnorrSignature<P, K>;
fn add(self, rhs: &'b SchnorrSignature<P, K>) -> SchnorrSignature<P, K> {
let r_sum = self.get_public_nonce() + rhs.get_public_nonce();
let s_sum = self.get_signature() + rhs.get_signature();
SchnorrSignature::new(r_sum, s_sum)
}
}
impl<'a, P, K> Add<SchnorrSignature<P, K>> for &'a SchnorrSignature<P, K>
where
P: PublicKey<K = K>,
for<'b> &'a P: Add<&'b P, Output = P>,
K: SecretKey,
for<'b> &'a K: Add<&'b K, Output = K>,
{
type Output = SchnorrSignature<P, K>;
fn add(self, rhs: SchnorrSignature<P, K>) -> SchnorrSignature<P, K> {
let r_sum = self.get_public_nonce() + rhs.get_public_nonce();
let s_sum = self.get_signature() + rhs.get_signature();
SchnorrSignature::new(r_sum, s_sum)
}
}
impl<P, K> Default for SchnorrSignature<P, K>
where
P: PublicKey<K = K>,
K: SecretKey,
{
fn default() -> Self {
SchnorrSignature::new(P::default(), K::default())
}
}
/// Provide an efficient ordering algorithm for Schnorr signatures. It's probably not a good idea to implement `Ord`
/// for secret keys, but in this instance, the signature is publicly known and is simply a scalar, so we use the byte
/// representation of the scalar as the canonical ordering metric. This conversion is done if and only if the public
/// nonces are already equal, otherwise the public nonce ordering determines the SchnorrSignature order.
impl<P, K> Ord for SchnorrSignature<P, K>
where
P: Eq + Ord,
K: Eq + ByteArray,
{
fn cmp(&self, other: &Self) -> Ordering {
match self.public_nonce.cmp(&other.public_nonce) {
Ordering::Equal => self.signature.as_bytes().cmp(&other.signature.as_bytes()),
v => v,
}
}
}
impl<P, K> PartialOrd for SchnorrSignature<P, K>
where
P: Eq + Ord,
K: Eq + ByteArray,
{
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
| true |
40b6c5e6605f3f2fa61f05ad5066a8e3e2321f4d
|
Rust
|
makepad/makepad
|
/libs/toml_parser/src/toml.rs
|
UTF-8
| 13,801 | 3.125 | 3 |
[
"MIT"
] |
permissive
|
use std::collections::{HashMap};
use std::str::Chars;
#[derive(Default)]
pub struct TomlParser {
pub cur: char,
pub pos: usize,
}
#[derive(PartialEq, Debug, Clone)]
pub struct TomlSpan{
pub start:usize,
pub len:usize
}
#[derive(PartialEq, Debug)]
pub struct TomlTokWithSpan{
pub span: TomlSpan,
pub tok: TomlTok
}
#[derive(PartialEq, Debug)]
pub enum TomlTok {
Ident(String),
Str(String),
U64(u64),
I64(i64),
F64(f64),
Bool(bool),
Nan(bool),
Inf(bool),
Date(String),
Equals,
BlockOpen,
BlockClose,
ObjectOpen,
ObjectClose,
Comma,
Bof,
Eof
}
#[derive(PartialEq, Debug, Clone)]
pub enum Toml{
Str(String, TomlSpan),
Bool(bool, TomlSpan),
Num(f64, TomlSpan),
Date(String, TomlSpan),
Array(Vec<Toml>),
}
impl Toml{
pub fn into_str(self)->Option<String>{
match self{
Self::Str(v,_)=>Some(v),
_=>None
}
}
}
pub struct TomlErr{
pub msg:String,
pub span:TomlSpan,
}
impl std::fmt::Debug for TomlErr {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Toml error: {}, start:{} len:{}", self.msg, self.span.start, self.span.len)
}
}
pub fn parse_toml(data:&str)->Result<HashMap<String, Toml>, TomlErr>{
let i = &mut data.chars();
let mut t = TomlParser::default();
t.next(i);
let mut out = HashMap::new();
let mut local_scope = String::new();
loop{
let tok = t.next_tok(i)?;
match tok.tok{
TomlTok::Eof=>{ // at eof.
return Ok(out);
},
TomlTok::BlockOpen=>{ // its a scope
// we should expect an ident or a string
let tok = t.next_tok(i)?;
let (tok, double_block) = if let TomlTok::BlockOpen = tok.tok{
(t.next_tok(i)?, true)
}
else{(tok, false)};
match tok.tok{
TomlTok::Str(key)=>{ // a key
local_scope = key;
},
TomlTok::Ident(key)=>{ // also a key
local_scope = key;
},
_=>return Err(t.err_token(tok))
}
let tok = t.next_tok(i)?;
if tok.tok != TomlTok::BlockClose{
return Err(t.err_token(tok))
}
if double_block{
let tok = t.next_tok(i)?;
if tok.tok != TomlTok::BlockClose{
return Err(t.err_token(tok))
}
}
},
TomlTok::Str(key)=>{ // a key
t.parse_key_value(&local_scope, key, i, &mut out)?;
},
TomlTok::Ident(key)=>{ // also a key
t.parse_key_value(&local_scope, key, i, &mut out)?;
},
_=>return Err(t.err_token(tok))
}
}
}
impl TomlParser {
pub fn to_val(&mut self, tok:TomlTokWithSpan, i: &mut Chars)->Result<Toml, TomlErr>{
match tok.tok{
TomlTok::BlockOpen=>{
let mut vals = Vec::new();
loop{
let tok = self.next_tok(i)?;
match tok.tok{
TomlTok::BlockClose | TomlTok::Eof=>{
break;
}
TomlTok::Comma=>{}
_=>{
vals.push(self.to_val(tok, i)?);
}
}
}
Ok(Toml::Array(vals))
},
TomlTok::Str(v)=>Ok(Toml::Str(v, tok.span)),
TomlTok::U64(v)=>Ok(Toml::Num(v as f64, tok.span)),
TomlTok::I64(v)=>Ok(Toml::Num(v as f64, tok.span)),
TomlTok::F64(v)=>Ok(Toml::Num(v, tok.span)),
TomlTok::Bool(v)=>Ok(Toml::Bool(v, tok.span)),
TomlTok::Nan(v)=>Ok(Toml::Num(if v{-std::f64::NAN}else{std::f64::NAN}, tok.span)),
TomlTok::Inf(v)=>Ok(Toml::Num(if v{-std::f64::INFINITY}else{std::f64::INFINITY}, tok.span)),
TomlTok::Date(v)=>Ok(Toml::Date(v, tok.span)),
_=>Err(self.err_token(tok))
}
}
pub fn parse_key_value(&mut self, local_scope:&str, key:String, i: &mut Chars, out:&mut HashMap<String, Toml>)->Result<(), TomlErr>{
let tok = self.next_tok(i)?;
if tok.tok != TomlTok::Equals{
return Err(self.err_token(tok));
}
let tok = self.next_tok(i)?;
// if we are an ObjectOpen we do a subscope
if let TomlTok::ObjectOpen = tok.tok{
let local_scope = if !local_scope.is_empty(){
format!("{}.{}", local_scope, key)
}
else{
key
};
loop{
let tok = self.next_tok(i)?;
match tok.tok{
TomlTok::ObjectClose | TomlTok::Eof=>{
break;
}
TomlTok::Comma=>{}
TomlTok::Str(key)=>{ // a key
self.parse_key_value(&local_scope, key, i, out)?;
},
TomlTok::Ident(key)=>{ // also a key
self.parse_key_value(&local_scope, key, i, out)?;
},
_=>return Err(self.err_token(tok))
}
}
}
else{
let val = self.to_val(tok, i)?;
let key = if !local_scope.is_empty(){
format!("{}.{}", local_scope, key)
}
else{
key
};
out.insert(key, val);
}
Ok(())
}
pub fn next(&mut self, i: &mut Chars) {
if let Some(c) = i.next() {
self.cur = c;
self.pos += 1;
}
else {
self.cur = '\0';
}
}
pub fn err_token(&self, tok:TomlTokWithSpan) -> TomlErr {
TomlErr{msg:format!("Unexpected token {:?} ", tok), span:tok.span}
}
pub fn err_parse(&self, what:&str) -> TomlErr {
TomlErr{msg:format!("Cannot parse toml {} ", what), span:TomlSpan{start:self.pos, len:0}}
}
pub fn next_tok(&mut self, i: &mut Chars) -> Result<TomlTokWithSpan, TomlErr> {
while self.cur == '\n' || self.cur == '\r' || self.cur == '\t' || self.cur == ' ' || self.cur == '#'{
if self.cur == '#'{
while self.cur !='\n' && self.cur != '\0'{
self.next(i);
}
continue
}
self.next(i);
}
let start = self.pos;
match self.cur {
'\0'=>{
Ok(TomlTokWithSpan{tok:TomlTok::Eof, span:TomlSpan{start, len:0}})
}
',' => {
self.next(i);
Ok(TomlTokWithSpan{tok:TomlTok::Comma, span:TomlSpan{start, len:1}})
}
'[' => {
self.next(i);
Ok(TomlTokWithSpan{tok:TomlTok::BlockOpen, span:TomlSpan{start, len:1}})
}
']' => {
self.next(i);
Ok(TomlTokWithSpan{tok:TomlTok::BlockClose, span:TomlSpan{start, len:1}})
}
'{' => {
self.next(i);
Ok(TomlTokWithSpan{tok:TomlTok::ObjectOpen, span:TomlSpan{start, len:1}})
}
'}' => {
self.next(i);
Ok(TomlTokWithSpan{tok:TomlTok::ObjectClose, span:TomlSpan{start, len:1}})
}
'=' => {
self.next(i);
Ok(TomlTokWithSpan{tok:TomlTok::Equals, span:TomlSpan{start, len:1}})
}
'+' | '-' | '0'..='9' => {
let mut num = String::new();
let is_neg = if self.cur == '-' {
num.push(self.cur);
self.next(i);
true
}
else {
if self.cur == '+' {
self.next(i);
}
false
};
if self.cur == 'n' {
self.next(i);
if self.cur == 'a' {
self.next(i);
if self.cur == 'n' {
self.next(i);
return Ok(TomlTokWithSpan{tok:TomlTok::Nan(is_neg), span:TomlSpan{start, len:self.pos - start}})
}
else {
return Err(self.err_parse("nan"))
}
}
else {
return Err(self.err_parse("nan"))
}
}
if self.cur == 'i' {
self.next(i);
if self.cur == 'n' {
self.next(i);
if self.cur == 'f' {
self.next(i);
return Ok(TomlTokWithSpan{tok:TomlTok::Inf(is_neg), span:TomlSpan{start, len:self.pos - start}})
}
else {
return Err(self.err_parse("inf"))
}
}
else {
return Err(self.err_parse("nan"))
}
}
while self.cur >= '0' && self.cur <= '9' || self.cur == '_' {
if self.cur != '_' {
num.push(self.cur);
}
self.next(i);
}
if self.cur == '.' {
num.push(self.cur);
self.next(i);
while self.cur >= '0' && self.cur <= '9' || self.cur == '_' {
if self.cur != '_' {
num.push(self.cur);
}
self.next(i);
}
if let Ok(num) = num.parse() {
Ok(TomlTokWithSpan{tok:TomlTok::F64(num), span:TomlSpan{start, len:self.pos - start}})
}
else {
Err(self.err_parse("number"))
}
}
else if self.cur == '-' { // lets assume its a date. whatever. i don't feel like more parsing today
num.push(self.cur);
self.next(i);
while self.cur >= '0' && self.cur <= '9' || self.cur == ':' || self.cur == '-' || self.cur == 'T' {
num.push(self.cur);
self.next(i);
}
return Ok(TomlTokWithSpan{tok:TomlTok::Date(num), span:TomlSpan{start, len:self.pos - start}})
}
else {
if is_neg {
if let Ok(num) = num.parse() {
return Ok(TomlTokWithSpan{tok:TomlTok::I64(num), span:TomlSpan{start, len:self.pos - start}})
}
else {
return Err(self.err_parse("number"));
}
}
if let Ok(num) = num.parse() {
return Ok(TomlTokWithSpan{tok:TomlTok::U64(num), span:TomlSpan{start, len:self.pos - start}})
}
else {
return Err(self.err_parse("number"));
}
}
},
'a'..='z' | 'A'..='Z' | '_' => {
let mut ident = String::new();
while self.cur >= 'a' && self.cur <= 'z'
|| self.cur >= 'A' && self.cur <= 'Z'
|| self.cur >= '0' && self.cur <= '9'
|| self.cur == '_' || self.cur == '-' || self.cur == '.'{
ident.push(self.cur);
self.next(i);
}
if ident == "true" {
return Ok(TomlTokWithSpan{tok:TomlTok::Bool(true), span:TomlSpan{start, len:self.pos - start}})
}
if ident == "false" {
return Ok(TomlTokWithSpan{tok:TomlTok::Bool(false), span:TomlSpan{start, len:self.pos - start}})
}
if ident == "inf" {
return Ok(TomlTokWithSpan{tok:TomlTok::Inf(false), span:TomlSpan{start, len:self.pos - start}})
}
if ident == "nan" {
return Ok(TomlTokWithSpan{tok:TomlTok::Nan(false), span:TomlSpan{start, len:self.pos - start}})
}
Ok(TomlTokWithSpan{tok:TomlTok::Ident(ident), span:TomlSpan{start, len:self.pos - start}})
},
'"' => {
let mut val = String::new();
self.next(i);
while self.cur != '"' {
if self.cur == '\\' {
self.next(i);
}
if self.cur == '\0' {
return Err(self.err_parse("string"));
}
val.push(self.cur);
self.next(i);
}
self.next(i);
Ok(TomlTokWithSpan{tok:TomlTok::Str(val), span:TomlSpan{start, len:self.pos - start}})
},
_ => {
Err(self.err_parse("tokenizer"))
}
}
}
}
| true |
11f264fdd64a0e7dc1297fef7397aedb3dd71b3b
|
Rust
|
fits/try_samples
|
/rust/wasm-bindgen/graphql_sample/src/lib.rs
|
UTF-8
| 2,163 | 2.625 | 3 |
[] |
no_license
|
use juniper::{execute_sync, EmptySubscription, FieldError, FieldResult, Variables};
use wasm_bindgen::prelude::*;
use std::collections::HashMap;
use std::sync::RwLock;
#[derive(Default, Debug)]
struct Store {
store: RwLock<HashMap<String, Item>>,
}
impl juniper::Context for Store {}
#[derive(Debug, Clone, juniper::GraphQLObject)]
struct Item {
id: String,
value: i32,
}
#[derive(Debug, Clone, juniper::GraphQLInputObject)]
struct CreateItem {
id: String,
value: i32,
}
fn error(msg: &str) -> FieldError {
FieldError::new(msg, juniper::Value::Null)
}
#[derive(Debug)]
struct Query;
#[juniper::graphql_object(context = Store)]
impl Query {
fn find(ctx: &Store, id: String) -> FieldResult<Item> {
let s = ctx
.store
.read()
.map_err(|e| error(format!("read lock: {:?}", e).as_str()))?;
s.get(&id).cloned().ok_or(error("not found"))
}
}
#[derive(Debug)]
struct Mutation;
#[juniper::graphql_object(context = Store)]
impl Mutation {
fn create(ctx: &Store, input: CreateItem) -> FieldResult<Item> {
let data = Item {
id: input.id,
value: input.value,
};
let mut s = ctx
.store
.write()
.map_err(|e| error(format!("write lock: {:?}", e).as_str()))?;
if s.insert(data.id.clone(), data.clone()).is_none() {
Ok(data)
} else {
Err(error("duplicated id"))
}
}
}
type Schema = juniper::RootNode<'static, Query, Mutation, EmptySubscription<Store>>;
#[wasm_bindgen]
pub struct Context {
context: Store,
schema: Schema,
}
#[wasm_bindgen]
impl Context {
#[wasm_bindgen(constructor)]
pub fn new() -> Self {
let context = Store::default();
let schema = Schema::new(Query, Mutation, EmptySubscription::new());
Self{ context, schema }
}
pub fn query(&self, q: String) -> String {
let r = execute_sync(&q, None, &self.schema, &Variables::new(), &self.context);
match r {
Ok((v, _)) => format!("{}", v),
Err(e) => format!("{}", e),
}
}
}
| true |
d1c2f19d1f7c260b06c6424ec038e0eca3db4448
|
Rust
|
aeshirey/h3rs
|
/src/vec3d.rs
|
UTF-8
| 2,145 | 3.765625 | 4 |
[
"Apache-2.0"
] |
permissive
|
pub struct Vec3d {
/// x component
pub x: f64,
/// y component
pub y: f64,
/// z component
pub z: f64,
}
/// Square of a number
fn _square(x: f64) -> f64 {
x * x
}
impl Vec3d {
pub const fn new(x: f64, y: f64, z: f64) -> Self {
Vec3d { x, y, z }
}
/// Calculate the square of the distance between two 3D coordinates.
pub fn _pointSquareDist(&self, other: &Self) -> f64 {
_square(self.x - other.x) + _square(self.y - other.y) + _square(self.z - other.z)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_pointSquareDist() {
let v1 = Vec3d::new(0., 0., 0.);
let v2 = Vec3d::new(1., 0., 0.);
let v3 = Vec3d::new(0., 1., 1.);
let v4 = Vec3d::new(1., 1., 1.);
let v5 = Vec3d::new(1., 1., 2.);
assert!(
(v1._pointSquareDist(&v1)).abs() < f64::EPSILON,
"distance to self is 0"
);
assert!(
(v1._pointSquareDist(&v2) - 1.).abs() < f64::EPSILON,
"distance to <1,0,0> is 1"
);
assert!(
(v1._pointSquareDist(&v3) - 2.).abs() < f64::EPSILON,
"distance to <0,1,1> is 2"
);
assert!(
(v1._pointSquareDist(&v4) - 3.).abs() < f64::EPSILON,
"distance to <1,1,1> is 3"
);
assert!(
(v1._pointSquareDist(&v5) - 6.).abs() < f64::EPSILON,
"distance to <1,1,2> is 6"
);
}
/*
#[test]
fn test_geoToVec3d() {
Vec3d origin = {0};
GeoCoord c1 = {0, 0};
Vec3d p1;
_geoToVec3d(&c1, &p1);
assert!(fabs(_pointSquareDist(&origin, &p1) - 1) < EPSILON_RAD, "Geo point is on the unit sphere");
GeoCoord c2 = {M_PI_2, 0};
Vec3d p2;
_geoToVec3d(&c2, &p2);
assert!(fabs(_pointSquareDist(&p1, &p2) - 2) < EPSILON_RAD, "Geo point is on another axis");
GeoCoord c3 = {M_PI, 0};
Vec3d p3;
_geoToVec3d(&c3, &p3);
assert!(fabs(_pointSquareDist(&p1, &p3) - 4) < EPSILON_RAD, "Geo point is the other side of the sphere");
}
*/
}
| true |
1ca6b994a201028efc60106004eec1c8de4ee38d
|
Rust
|
input-output-hk/jorup
|
/src/commands/setup.rs
|
UTF-8
| 7,952 | 2.515625 | 3 |
[
"Apache-2.0",
"MIT"
] |
permissive
|
use super::Cmd;
use crate::{common::JorupConfig, utils::download};
use std::{
env::{self, consts::EXE_SUFFIX},
fs, io,
path::{Path, PathBuf},
};
use structopt::StructOpt;
use thiserror::Error;
/// Operations for 'jorup'
#[derive(Debug, StructOpt)]
pub enum Command {
Install(Install),
Update,
Uninstall,
}
/// Install jorup
#[derive(Debug, StructOpt)]
pub struct Install {
/// Don't change the local PATH variables
#[structopt(long)]
no_modify_path: bool,
/// Even if a previous installed jorup is already installed, install
/// this new version.
#[structopt(short, long)]
force: bool,
}
#[derive(Debug, Error)]
pub enum Error {
#[error(transparent)]
Common(#[from] crate::common::Error),
#[error("jorup already installed")]
AlreadyInstalled,
#[error("Cannot get the current executable for the installer")]
NoInstallerExecutable(#[source] io::Error),
#[error("Cannot install jorup in {1}")]
Install(#[source] io::Error, PathBuf),
#[cfg(unix)]
#[error("Cannot set permissions for {1}")]
Permissions(#[source] io::Error, PathBuf),
#[cfg(unix)]
#[error("Cannot read file {1}")]
Read(#[source] io::Error, PathBuf),
#[cfg(unix)]
#[error("Cannot write to file {1}")]
Write(#[source] io::Error, PathBuf),
#[cfg(windows)]
#[error("Cannot update PATH in Windows registry")]
WinregError(#[source] io::Error),
#[error("Failed to check for update")]
UpdateCheck(#[from] crate::utils::jorup_update::Error),
#[error("Failed to download an update")]
UpdateDownload(#[from] download::Error),
#[error("Could not find the latest jorup binary for the current platform")]
UpdateAssetNotFound,
}
impl Command {
pub fn run(self, cfg: JorupConfig) -> Result<(), Error> {
match self {
Command::Install(cmd) => cmd.run(cfg),
Command::Update => update(cfg),
Command::Uninstall => uninstall(cfg),
}
}
}
impl Install {
pub fn run(self, cfg: JorupConfig) -> Result<(), Error> {
let bin_dir = cfg.bin_dir();
let jorup_file = bin_dir.join(format!("jorup{}", EXE_SUFFIX));
if jorup_file.is_file() {
let force = self.force
|| dialoguer::Confirmation::new()
.with_text("jorup is already installed, overwrite?")
.interact()
.unwrap();
if !force {
return Err(Error::AlreadyInstalled);
}
}
let jorup_current = env::current_exe().map_err(Error::NoInstallerExecutable)?;
fs::copy(&jorup_current, &jorup_file).map_err(|e| Error::Install(e, jorup_file.clone()))?;
make_executable(&jorup_file)?;
if !self.no_modify_path {
do_add_to_path(&cfg)?;
}
Ok(())
}
}
impl Cmd for Install {
type Err = Error;
fn run(self) -> Result<(), Self::Err> {
let cfg = crate::common::JorupConfig::new(None, None, false)?;
self.run(cfg)
}
}
pub fn uninstall(_cfg: JorupConfig) -> Result<(), Error> {
unimplemented!()
}
pub fn update(cfg: JorupConfig) -> Result<(), Error> {
let bin_dir = cfg.bin_dir();
let jorup_file = bin_dir.join(format!("jorup{}", EXE_SUFFIX));
match crate::utils::check_jorup_update()? {
Some(release) => {
let perform_update = dialoguer::Confirmation::new()
.with_text(&format!(
"An update to version {} is available. Continue?",
release.version()
))
.interact()
.unwrap();
if !perform_update {
return Ok(());
}
let mut client = download::Client::new()?;
let url = release
.get_asset_url(env!("TARGET"))
.ok_or(Error::UpdateAssetNotFound)?;
client.download_file("jorup", url, jorup_file)?;
eprintln!("Jorup was successfully updated!");
}
None => {
eprintln!("No updates available");
}
}
Ok(())
}
#[cfg(unix)]
fn make_executable(path: &Path) -> Result<(), Error> {
use std::os::unix::fs::PermissionsExt;
let metadata = fs::metadata(path).map_err(|e| Error::Permissions(e, path.to_path_buf()))?;
let mut perms = metadata.permissions();
let mode = perms.mode();
let new_mode = (mode & !0o777) | 0o755;
if mode == new_mode {
return Ok(());
}
perms.set_mode(new_mode);
fs::set_permissions(path, perms).map_err(|e| Error::Permissions(e, path.to_path_buf()))
}
#[cfg(windows)]
fn make_executable(_: &Path) -> Result<(), Error> {
Ok(())
}
#[cfg(unix)]
fn do_add_to_path(cfg: &JorupConfig) -> Result<(), Error> {
let methods = get_add_path_methods();
for rcpath in methods {
let file = if rcpath.exists() {
fs::read_to_string(&rcpath).map_err(|e| Error::Read(e, rcpath.clone()))?
} else {
String::new()
};
let addition = format!("\n{}", shell_export_string(cfg));
if !file.contains(&addition) {
use std::io::Write as _;
let mut writer = fs::OpenOptions::new()
.create(true)
.append(true)
.open(&rcpath)
.map_err(|e| Error::Write(e, rcpath.clone()))?;
writer
.write_all(addition.as_bytes())
.map_err(|e| Error::Write(e, rcpath.clone()))?;
}
}
Ok(())
}
#[cfg(windows)]
fn do_add_to_path(cfg: &JorupConfig) -> Result<(), Error> {
use std::ptr;
use winapi::shared::minwindef::*;
use winapi::um::winuser::{
SendMessageTimeoutA, HWND_BROADCAST, SMTO_ABORTIFHUNG, WM_SETTINGCHANGE,
};
use winreg::enums::*;
use winreg::RegKey;
let hkcu = RegKey::predef(HKEY_CURRENT_USER);
let environment = hkcu
.open_subkey_with_flags("Environment", KEY_READ | KEY_WRITE)
.map_err(Error::WinregError)?;
let current_path: String = environment.get_value("Path").map_err(Error::WinregError)?;
let jorup_path = cfg.bin_dir().display().to_string();
if current_path.contains(&jorup_path) {
return Ok(());
}
let new_path = format!("{};{}", jorup_path, current_path);
environment
.set_value("Path", &new_path)
.map_err(Error::WinregError)?;
unsafe {
SendMessageTimeoutA(
HWND_BROADCAST,
WM_SETTINGCHANGE,
0 as WPARAM,
"Environment\0".as_ptr() as LPARAM,
SMTO_ABORTIFHUNG,
5000,
ptr::null_mut(),
);
}
Ok(())
}
/// Decide which rcfiles we're going to update, so we can tell the user before
/// they confirm.
#[cfg(unix)]
fn get_add_path_methods() -> Vec<PathBuf> {
let profile = dirs::home_dir().map(|p| p.join(".profile"));
let mut profiles = vec![profile];
if let Ok(shell) = env::var("SHELL") {
if shell.contains("zsh") {
let zdotdir = env::var("ZDOTDIR")
.ok()
.map(PathBuf::from)
.or_else(dirs::home_dir);
let zprofile = zdotdir.map(|p| p.join(".zprofile"));
profiles.push(zprofile);
}
}
if let Some(bash_profile) = dirs::home_dir().map(|p| p.join(".bash_profile")) {
// Only update .bash_profile if it exists because creating .bash_profile
// will cause .profile to not be read
if bash_profile.exists() {
profiles.push(Some(bash_profile));
}
}
let rcfiles = profiles.into_iter().filter_map(|f| f);
rcfiles.collect()
}
#[cfg(unix)]
fn shell_export_string(cfg: &JorupConfig) -> String {
let path = cfg.bin_dir().display().to_string();
// The path is *pre-pended* in case there are system-installed
format!(r#"export PATH="{}:$PATH""#, path)
}
| true |
80f5dd0fcfa69e905b5b6a1b1c8d98c9dea95793
|
Rust
|
ajscholl/mqs
|
/mqs-common/src/router/handler.rs
|
UTF-8
| 7,255 | 2.890625 | 3 |
[
"BSD-3-Clause"
] |
permissive
|
use http::version::Version;
use hyper::{
header::{HeaderValue, CONNECTION, CONTENT_TYPE, SERVER},
Body,
Request,
Response,
};
use crate::{read_body, router::Router, Status};
/// Handle a single request using the given router.
///
/// If the given connection is `None`, an error response is returned.
/// If more than `max_message_size` bytes are send by the client, an
/// error response is returned.
///
/// ```
/// use async_trait::async_trait;
/// use hyper::{Body, Method, Request, Response};
/// use mqs_common::{
/// read_body,
/// router::{handle, Handler, Router},
/// test::make_runtime,
/// };
///
/// struct IntSource {
/// int: i32,
/// }
///
/// struct ExampleHandler {}
///
/// #[async_trait]
/// impl Handler<(i32, IntSource)> for ExampleHandler {
/// async fn handle(
/// &self,
/// args: (i32, IntSource),
/// req: Request<Body>,
/// body: Vec<u8>,
/// ) -> Response<Body> {
/// Response::new(Body::from(format!("{} -> {}", args.0, args.1.int)))
/// }
/// }
///
/// make_runtime().block_on(async {
/// let router = Router::new_simple(Method::GET, ExampleHandler {});
/// let mut response = handle(
/// None,
/// IntSource { int: 5 },
/// &router,
/// 100,
/// Request::new(Body::default()),
/// )
/// .await;
/// assert_eq!(response.status(), 503);
/// assert_eq!(
/// read_body(response.body_mut(), None).await.unwrap().unwrap(),
/// b"{\"error\":\"Service unavailable, try again later\"}".as_ref()
/// );
/// let mut response = handle(
/// Some(42),
/// IntSource { int: 5 },
/// &router,
/// 100,
/// Request::new(Body::default()),
/// )
/// .await;
/// assert_eq!(response.status(), 200);
/// assert_eq!(
/// read_body(response.body_mut(), None).await.unwrap().unwrap(),
/// b"42 -> 5"
/// );
/// });
/// ```
pub async fn handle<T: Send, S: Send>(
conn: Option<T>,
source: S,
router: &Router<(T, S)>,
max_message_size: usize,
mut req: Request<Body>,
) -> Response<Body> {
let version = req.version();
let mut response = if let Some(conn) = conn {
let segments = req.uri().path().split('/');
{
if let Some(handler) = router.route(req.method(), segments) {
let body = if handler.needs_body() {
read_body(req.body_mut(), Some(max_message_size)).await
} else {
Ok(Some(Vec::new()))
};
match body {
Err(err) => {
error!("Failed to read message body: {}", err);
let mut response = Response::new(Body::from("{\"error\":\"Internal server error\"}"));
response
.headers_mut()
.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
*response.status_mut() = Status::InternalServerError.into();
response
},
Ok(None) => {
warn!("Body was larger than max allowed size ({})", max_message_size);
let mut response = Response::new(Body::from("{\"error\":\"Payload too large\"}"));
response
.headers_mut()
.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
*response.status_mut() = Status::PayloadTooLarge.into();
response
},
Ok(Some(body)) => {
info!("Found handler for request {} {}", req.method(), req.uri().path());
handler.handle((conn, source), req, body).await
},
}
} else {
error!("No handler found for request {} {}", req.method(), req.uri().path());
let mut response = Response::new(Body::from("{\"error\":\"No handler found for request\"}"));
response
.headers_mut()
.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
*response.status_mut() = Status::NotFound.into();
response
}
}
} else {
error!(
"No database connection available for request {} {}",
req.method(),
req.uri().path()
);
let mut response = Response::new(Body::from("{\"error\":\"Service unavailable, try again later\"}"));
response
.headers_mut()
.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
*response.status_mut() = Status::ServiceUnavailable.into();
response
};
response.headers_mut().insert(SERVER, HeaderValue::from_static("mqs"));
if version <= Version::HTTP_11 {
response
.headers_mut()
.insert(CONNECTION, HeaderValue::from_static("keep-alive"));
}
response
}
#[cfg(test)]
mod test {
use super::*;
use crate::{
read_body,
router::{Handler, Router},
};
use async_trait::async_trait;
use hyper::{Body, Method, Request, Response};
struct EchoHandler {}
#[async_trait]
impl Handler<(i32, ())> for EchoHandler {
fn needs_body(&self) -> bool {
true
}
async fn handle(&self, args: (i32, ()), _: Request<Body>, body: Vec<u8>) -> Response<Body> {
Response::new(Body::from(format!(
"{} -> {}",
args.0,
String::from_utf8(body).unwrap()
)))
}
}
#[test]
async fn test_handler() {
let router = Router::new_simple(Method::GET, EchoHandler {});
let mut response = handle(None, (), &router, 100, Request::new(Body::default())).await;
assert_eq!(response.status(), 503);
assert_eq!(
read_body(response.body_mut(), None).await.unwrap().unwrap(),
b"{\"error\":\"Service unavailable, try again later\"}".as_ref()
);
let mut response = handle(Some(42), (), &router, 100, Request::new(Body::default())).await;
assert_eq!(response.status(), 200);
assert_eq!(read_body(response.body_mut(), None).await.unwrap().unwrap(), b"42 -> ");
let mut response = handle(Some(42), (), &router, 3, Request::new(Body::from("hello".to_string()))).await;
assert_eq!(response.status(), 413);
assert_eq!(
read_body(response.body_mut(), None).await.unwrap().unwrap(),
b"{\"error\":\"Payload too large\"}".as_ref()
);
let mut response = handle(
Some(42),
(),
&Router::default(),
3,
Request::new(Body::from("hello".to_string())),
)
.await;
assert_eq!(response.status(), 404);
assert_eq!(
read_body(response.body_mut(), None).await.unwrap().unwrap(),
b"{\"error\":\"No handler found for request\"}".as_ref()
);
}
}
| true |
f3e8935e2936b2ebfc7f0c0834e7851d76358b82
|
Rust
|
lighter/Leetcode-Rust
|
/n0168. Excel Sheet Column Title/main.rs
|
UTF-8
| 387 | 2.703125 | 3 |
[
"MIT"
] |
permissive
|
// Author: Netcan @ https://github.com/netcan/Leetcode-Rust
// Zhihu: https://www.zhihu.com/people/netcan
impl Solution {
pub fn convert_to_title(mut n: i32) -> String {
let mut title = String::new();
while n != 0 {
title = ((((n - 1) % 26) as u8 + 'A' as u8) as char).to_string() + &title;
n = (n - 1) / 26;
}
title
}
}
| true |
d55ad682d27ec30e0b1a52951cf3f1c4adf32a7f
|
Rust
|
sifyfy/iris-rs
|
/src/log.rs
|
UTF-8
| 15,068 | 2.921875 | 3 |
[] |
no_license
|
//! # iris::log
//!
//! ## Usage
//!
//! In app:
//! ```
//! iris::log::Tracer::builder()
//! .format_for_app_simple()
//! .init()
//! .unwrap();
//!
//! iris::log::error!("Error");
//! ```
//!
//! In server:
//! ```
//! iris::log::Tracer::builder()
//! .format_for_server()
//! .init()
//! .unwrap();
//!
//! iris::log::error!("");
//! ```
//!
mod format_time {
use tracing_subscriber::fmt::time::{ChronoLocal, ChronoUtc};
pub type Local = ChronoLocal;
pub type Utc = ChronoUtc;
}
mod format_fields {}
mod format_event {
use super::format_time::{Local, Utc};
use serde::ser::{SerializeMap, Serializer};
use std::fmt::Write;
use std::marker::PhantomData;
use thiserror::private::DisplayAsDisplay;
use tracing::{Event, Subscriber};
use tracing_log::NormalizeEvent;
use tracing_subscriber::fmt::time::FormatTime;
use tracing_subscriber::fmt::{FmtContext, FormatEvent, FormatFields, FormattedFields};
use tracing_subscriber::registry::{LookupSpan, SpanRef};
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash, Default)]
pub struct Simple;
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash, Default)]
pub struct Debug;
#[derive(Debug, Clone)]
pub struct FormatForApp<M, T> {
log_mode: M,
format_time: T,
}
impl<M: Default, T: FormatTime> FormatForApp<M, T> {
pub fn new(format_time: T) -> Self {
FormatForApp {
log_mode: M::default(),
format_time,
}
}
}
impl FormatForApp<Simple, Local> {
pub fn simple() -> Self {
Default::default()
}
}
impl FormatForApp<Simple, Utc> {
pub fn simple_utc() -> Self {
Default::default()
}
}
impl FormatForApp<Debug, Local> {
pub fn debug() -> Self {
Default::default()
}
}
impl FormatForApp<Debug, Utc> {
pub fn debug_utc() -> Self {
Default::default()
}
}
impl<M, T> Default for FormatForApp<M, T>
where
M: Default,
T: Default + FormatTime,
{
fn default() -> Self {
Self::new(T::default())
}
}
impl<S, N, T> FormatEvent<S, N> for FormatForApp<Simple, T>
where
S: Subscriber + for<'a> LookupSpan<'a>,
N: for<'a> FormatFields<'a> + 'static,
T: FormatTime,
{
fn format_event(
&self,
ctx: &FmtContext<'_, S, N>,
writer: &mut dyn Write,
event: &Event<'_>,
) -> std::fmt::Result {
{
write!(writer, "[")?;
self.format_time.format_time(writer)?;
write!(writer, "]")?;
}
{
let normalized_metadata = event.normalized_metadata();
let metadata = normalized_metadata
.as_ref()
.unwrap_or_else(|| event.metadata());
write!(writer, "[{level}]", level = metadata.level().as_display())?;
}
{
write!(writer, " ")?;
}
{
ctx.format_fields(writer, event)?;
}
writeln!(writer)
}
}
impl<S, N, T> FormatEvent<S, N> for FormatForApp<Debug, T>
where
S: Subscriber + for<'a> LookupSpan<'a>,
N: for<'a> FormatFields<'a> + 'static,
T: FormatTime,
{
fn format_event(
&self,
ctx: &FmtContext<'_, S, N>,
writer: &mut dyn Write,
event: &Event<'_>,
) -> std::fmt::Result {
let normalized_metadata = event.normalized_metadata();
let metadata = normalized_metadata
.as_ref()
.unwrap_or_else(|| event.metadata());
{
write!(writer, "[")?;
self.format_time.format_time(writer)?;
write!(writer, "]")?;
}
{
write!(writer, "[{level}]", level = metadata.level().as_display())?;
}
{
write!(writer, "[")?;
let mut is_first = true;
ctx.visit_spans(|span| {
if is_first {
is_first = false;
} else {
write!(writer, " -> ")?;
}
write!(writer, "{}", span.name())?;
WriteSpan::<N, S>::write(writer, span)?;
Ok(())
})?;
write!(writer, "]")?;
}
{
write!(writer, " ")?;
}
{
ctx.format_fields(writer, event)?;
}
{
let file = metadata.file().unwrap_or("unknown");
let line = metadata.line().unwrap_or(0);
write!(writer, " at {file}:{line}", file = file, line = line)?;
}
writeln!(writer)
}
}
#[derive(Debug, Clone)]
pub struct FormatForServer<T> {
format_time: T,
}
impl<T: FormatTime + Default> FormatForServer<T> {
pub fn new(format_time: T) -> Self {
FormatForServer { format_time }
}
}
impl FormatForServer<Local> {
pub fn local() -> Self {
Default::default()
}
}
impl FormatForServer<Utc> {
pub fn utc() -> Self {
Default::default()
}
}
impl<T: FormatTime + Default> Default for FormatForServer<T> {
fn default() -> Self {
FormatForServer::new(T::default())
}
}
impl<S, N, T> FormatEvent<S, N> for FormatForServer<T>
where
S: Subscriber + for<'a> LookupSpan<'a>,
N: for<'a> FormatFields<'a> + 'static,
T: FormatTime,
{
fn format_event(
&self,
ctx: &FmtContext<'_, S, N>,
writer: &mut dyn Write,
event: &Event<'_>,
) -> std::fmt::Result {
(|| -> Result<(), JsonLogError> {
let mut serializer = serde_json::Serializer::new(WriteAdapter::new(writer));
let mut serializer = serializer.serialize_map(None)?;
let normalized_metadata = event.normalized_metadata();
let metadata = normalized_metadata
.as_ref()
.unwrap_or_else(|| event.metadata());
let mut timestamp_buf = String::new();
self.format_time.format_time(&mut timestamp_buf)?;
serializer.serialize_entry("timestamp", timestamp_buf.as_str())?;
serializer.serialize_entry("level", metadata.level().as_str())?;
serializer.serialize_entry("target", metadata.target())?;
let mut span_buf = String::new();
let mut is_first = true;
ctx.visit_spans(|span| -> std::fmt::Result {
if is_first {
is_first = false;
} else {
write!(&mut span_buf, " -> ")?;
}
write!(&mut span_buf, "{}", span.name())?;
WriteSpan::<N, S>::write(&mut span_buf, span)?;
Ok(())
})?;
serializer.serialize_entry(
"span",
&if !span_buf.is_empty() {
Some(span_buf.as_str())
} else {
None
},
)?;
let mut visitor = tracing_serde::SerdeMapVisitor::new(serializer);
event.record(&mut visitor);
serializer = visitor.take_serializer()?;
serializer.serialize_entry("file", &metadata.file())?;
serializer.serialize_entry("line", &metadata.line())?;
serializer.end()?;
Ok(())
})()
.map_err(|_| std::fmt::Error)?;
writeln!(writer)
}
}
#[derive(Debug, thiserror::Error)]
enum JsonLogError {
#[error("FmtError: {0}")]
FmtError(#[from] std::fmt::Error),
#[error("SerdeJsonError: {0}")]
SerdeJsonError(#[from] serde_json::Error),
}
#[derive(Debug)]
struct WriteSpan<N, S> {
format_fields: PhantomData<N>,
subscriber: PhantomData<S>,
}
impl<N, S> WriteSpan<N, S> {
fn write(writer: &mut dyn Write, span: &SpanRef<S>) -> std::fmt::Result
where
N: 'static,
S: Subscriber + for<'a> LookupSpan<'a>,
{
if let Some(fields) = span.extensions().get::<FormattedFields<N>>() {
if !fields.is_empty() {
write!(writer, "{{{}}}", fields)?;
}
}
Ok(())
}
}
struct WriteAdapter<'a> {
fmt_writer: &'a mut dyn Write,
}
impl<'a> WriteAdapter<'a> {
fn new(fmt_writer: &'a mut dyn Write) -> Self {
WriteAdapter { fmt_writer }
}
}
impl<'a> std::io::Write for WriteAdapter<'a> {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
let s = String::from_utf8_lossy(buf);
self.fmt_writer
.write_str(&s)
.map_err(|err| std::io::Error::new(std::io::ErrorKind::Other, err))?;
Ok(buf.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
}
pub use self::format_event::{Debug, FormatForApp, FormatForServer, Simple};
pub use self::format_time::{Local, Utc};
pub use tracing::{self, debug, error, info, level_filters::LevelFilter, trace, warn, Level};
pub use tracing_subscriber;
use crate::log::tracing_subscriber::fmt::MakeWriter;
use tracing::subscriber::SetGlobalDefaultError;
use tracing_log::{AsLog, LogTracer};
use tracing_subscriber::{fmt::format::DefaultFields, fmt::FormatEvent, Registry};
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash, Default)]
pub struct Tracer;
impl Tracer {
pub fn builder() -> Builder {
Builder::default()
}
}
#[derive(Debug, thiserror::Error)]
pub enum TracingInitError {
#[error("TracingLogError: {0}")]
TracingLogError(#[from] log::SetLoggerError),
#[error("TracingError: {0}")]
TracingError(#[from] SetGlobalDefaultError),
}
enum FormatEventKind {
AppSimple,
AppDebug,
Server,
}
enum TimeLocale {
Utc,
Local,
}
pub struct Builder<W = fn() -> std::io::Stderr> {
format_event_kind: FormatEventKind,
time_locale: TimeLocale,
max_level: LevelFilter,
make_writer: W,
}
impl Default for Builder {
fn default() -> Self {
Builder {
format_event_kind: FormatEventKind::AppSimple,
time_locale: TimeLocale::Local,
max_level: LevelFilter::ERROR,
make_writer: std::io::stderr,
}
}
}
impl<W> Builder<W>
where W: MakeWriter + Send + Sync + 'static,
{
pub fn new(make_writer: W) -> Self {
let default = Builder::default();
Builder {
format_event_kind: default.format_event_kind,
time_locale: default.time_locale,
max_level: default.max_level,
make_writer,
}
}
pub fn format_for_app_simple(mut self) -> Self {
self.format_event_kind = FormatEventKind::AppSimple;
self
}
pub fn format_for_app_debug(mut self) -> Self {
self.format_event_kind = FormatEventKind::AppDebug;
self
}
pub fn format_for_server(mut self) -> Self {
self.format_event_kind = FormatEventKind::Server;
self
}
pub fn local_timestamp(mut self) -> Self {
self.time_locale = TimeLocale::Local;
self
}
pub fn utc_timestamp(mut self) -> Self {
self.time_locale = TimeLocale::Utc;
self
}
pub fn max_level(mut self, max_level: impl Into<LevelFilter>) -> Self {
self.max_level = max_level.into();
self
}
pub fn make_writer<W2: MakeWriter>(self, make_writer: W2) -> Builder<W2> {
let Builder {
format_event_kind,
time_locale,
max_level,
..
} = self;
Builder {
format_event_kind,
time_locale,
max_level,
make_writer,
}
}
pub fn init(self) -> Result<(), TracingInitError> {
let Builder {
format_event_kind,
time_locale,
max_level,
make_writer,
} = self;
LogTracer::builder()
.with_max_level(max_level.as_log())
.init()?;
match (format_event_kind, time_locale) {
(FormatEventKind::AppSimple, TimeLocale::Local) => tracing_init(
FormatForApp::<Simple, Local>::default(),
max_level,
make_writer,
)?,
(FormatEventKind::AppSimple, TimeLocale::Utc) => tracing_init(
FormatForApp::<Simple, Utc>::default(),
max_level,
make_writer,
)?,
(FormatEventKind::AppDebug, TimeLocale::Local) => tracing_init(
FormatForApp::<Debug, Local>::default(),
max_level,
make_writer,
)?,
(FormatEventKind::AppDebug, TimeLocale::Utc) => tracing_init(
FormatForApp::<Debug, Utc>::default(),
max_level,
make_writer,
)?,
(FormatEventKind::Server, TimeLocale::Local) => tracing_init(
FormatForServer::<Local>::default(),
max_level,
make_writer,
)?,
(FormatEventKind::Server, TimeLocale::Utc) => tracing_init(
FormatForServer::<Local>::default(),
max_level,
make_writer,
)?,
};
Ok(())
}
}
fn tracing_init<E, W>(
format_event: E,
max_level: impl Into<LevelFilter>,
make_writer: W,
) -> Result<(), SetGlobalDefaultError>
where
E: FormatEvent<Registry, DefaultFields> + Send + Sync + 'static,
W: MakeWriter + Send + Sync + 'static,
{
let subscriber = tracing_subscriber::fmt()
.with_max_level(max_level)
.event_format(format_event)
.with_writer(make_writer)
.finish();
tracing::subscriber::set_global_default(subscriber)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn construct_format_events() {
let _: FormatForApp<Simple, Local> = FormatForApp::simple();
let _: FormatForApp<Debug, Local> = FormatForApp::debug();
let _: FormatForApp<Simple, Utc> = FormatForApp::simple_utc();
let _: FormatForApp<Debug, Utc> = FormatForApp::debug_utc();
let _: FormatForServer<Utc> = FormatForServer::default();
}
}
| true |
41d73b40c2039afdccb87b32c3acac889530ed07
|
Rust
|
ranon-rat/nysh
|
/src/tools/sql_for_autocompletition.rs
|
UTF-8
| 1,196 | 2.765625 | 3 |
[] |
no_license
|
use rusqlite::{params, Connection};
// select the last command use it with a resemblance
pub fn update_commands(val: String) {
let conn = Connection::open("src/database/database.db").unwrap();
let sql = "UPDATE commands SET last_time_used=strftime('%f', 'now')+ strftime('%s', 'now') WHERE command=?1;";
conn.execute(sql, params![val]).unwrap();
}
pub fn insert_command(val: String) {
let sql = "INSERT INTO commands(command,last_time_used) SELECT ?1,strftime('%f', 'now')+ strftime('%s', 'now') WHERE NOT EXISTS(SELECT 1 FROM commands WHERE command = ?1);";
let conn = Connection::open("src/database/database.db").unwrap();
conn.execute(sql, params![val]).unwrap();
}
pub fn select_commands(val: String) -> String {
let conn = Connection::open("src/database/database.db").unwrap();
let sql = "SELECT command FROM commands WHERE command like ?1 ORDER BY last_time_used DESC LIMIT 1;";
let mut stm = conn.prepare(sql).unwrap();
let mut rows = stm.query(params![val + "%"]).unwrap();
let mut command_output = String::new();
while let Some(row) = rows.next().unwrap() {
command_output=row.get(0).unwrap();
}
return command_output;
}
| true |
95a88648c97fb567ab2fcb56da30593106b2dc49
|
Rust
|
collinpeters/rust-clippy
|
/tests/ui/string_lit_as_bytes.rs
|
UTF-8
| 470 | 2.515625 | 3 |
[
"Apache-2.0",
"MIT"
] |
permissive
|
// run-rustfix
#![allow(dead_code, unused_variables)]
#![warn(clippy::string_lit_as_bytes)]
fn str_lit_as_bytes() {
let bs = "hello there".as_bytes();
let bs = r###"raw string with three ### in it and some " ""###.as_bytes();
// no warning, because this cannot be written as a byte string literal:
let ubs = "☃".as_bytes();
let strify = stringify!(foobar).as_bytes();
let includestr = include_str!("entry.rs").as_bytes();
}
fn main() {}
| true |
d4a66090a04693aa62f95aa369caaa6967aa3479
|
Rust
|
optozorax/simple_rustc_tokenizer
|
/src/lib.rs
|
UTF-8
| 12,436 | 2.90625 | 3 |
[] |
no_license
|
use std::ops::Range;
pub mod peg;
#[derive(Debug, Clone, PartialEq, PartialOrd)]
pub enum Token<'a> {
// Idents
Ident(&'a str),
RawIdent(&'a str),
Lifetime(&'a str),
// Comments
LineComment(&'a str),
BlockComment(&'a str),
// String and char
UnescapedString(String),
Char(char),
Bytes(Vec<u8>),
Byte(u8),
// Numbers
Int(i64),
Float(f64),
// Symbols
Whitespace,
Semi,
Comma,
Dot,
OpenParen,
CloseParen,
OpenBrace,
CloseBrace,
OpenBracket,
CloseBracket,
At,
Pound,
Tilde,
Question,
Colon,
Dollar,
Eq,
Not,
Lt,
Gt,
Minus,
And,
Or,
Plus,
Star,
Slash,
Caret,
Percent,
}
#[derive(Debug, Eq, PartialEq)]
pub struct Error {
pub range: Range<usize>,
pub kind: ErrorKind,
}
#[derive(Debug, Eq, PartialEq)]
pub struct EscapeError {
pub range: Range<usize>,
pub kind: rustc_lexer::unescape::EscapeError,
}
#[derive(Debug, Eq, PartialEq)]
pub enum ErrorKind {
UnknownToken,
StringNotTerminated,
StringNotStarted,
SuffixNotSupported,
NumParseError,
CharEscapeError(EscapeError),
StringEscapeErrors(Vec<EscapeError>),
}
#[derive(Debug, Clone, PartialEq)]
pub struct TokenWithPos<'a> {
pub token: Token<'a>,
pub range: Range<usize>,
}
pub fn tokenize(string: &str) -> Result<Vec<TokenWithPos>, Error> {
use rustc_lexer::unescape;
use rustc_lexer::TokenKind::*;
use rustc_lexer::LiteralKind::*;
use ErrorKind::*;
rustc_lexer::tokenize(string)
.map(|x| (x.kind, x.len))
.scan((0, Gt, 0), |(pos, _, _), (kind, len)| {
*pos += len;
Some((*pos - len, kind, len))
})
.map(|(pos, token_kind, len)| {
let range = pos..pos+len;
let current_text = &string[range.clone()];
macro_rules! terminated_or {
($terminated:ident, $($x:tt)*) => {
if !$terminated {
Err(Error { range, kind: ErrorKind::StringNotTerminated })
} else {
$($x)*
}
};
}
macro_rules! ok {
($result:expr) => {
Ok(TokenWithPos { token: $result, range: pos..pos+len })
};
}
match token_kind {
Ident => ok!(Token::Ident(current_text)),
RawIdent => ok!(Token::RawIdent(¤t_text[2..])),
Lifetime { .. } => ok!(Token::Lifetime(¤t_text[1..])),
LineComment => ok!(Token::LineComment(&string[pos+2..pos+len])),
BlockComment { terminated } => {
terminated_or! {
terminated,
ok!(Token::BlockComment(&string[pos+2..pos+len-2]))
}
},
Literal { kind, suffix_start } => {
let text_before_suffix = &string[pos..pos+suffix_start];
let text_after_suffix = &string[pos+suffix_start..pos+len];
macro_rules! process_str {
($range:expr, $container:ident, $method:ident, $constructor:ident) => {
let mut result = $container::new();
let mut errors = Vec::new();
let range = $range;
rustc_lexer::unescape::$method(&string[range.clone()], &mut |range1, c| {
match c.map_err(|kind| EscapeError { kind, range: range.start+range1.start..range.start+range1.end }) {
Ok(c) => result.push(c),
Err(e) => errors.push(e),
}
});
if errors.is_empty() {
ok!(Token::$constructor(result))
} else {
Err(Error { range, kind: ErrorKind::StringEscapeErrors(errors) })
}
};
}
macro_rules! process_raw_str {
($started:ident, $range:expr, $container:ident, $method:ident, $constructor:ident) => {
if !$started {
Err(Error { range, kind: ErrorKind::StringNotStarted })
} else {
let mut result = $container::new();
let mut errors = Vec::new();
let range = $range;
rustc_lexer::unescape::$method(&string[range.clone()], &mut |range1, c| {
match c.map_err(|kind| EscapeError { kind, range: range.start+range1.start..range.start+range1.end }) {
Ok(c) => result.push(c),
Err(e) => errors.push(e),
}
});
if errors.is_empty() {
ok!(Token::$constructor(result))
} else {
Err(Error { range, kind: ErrorKind::StringEscapeErrors(errors) })
}
}
};
}
macro_rules! process_number {
($constructor:ident) => {
if !text_after_suffix.is_empty() {
Err(Error { range, kind: ErrorKind::SuffixNotSupported })
} else {
match text_before_suffix.parse() {
Ok(val) => ok!(Token::$constructor(val)),
Err(_) => Err(Error { range, kind: ErrorKind::NumParseError }),
}
}
};
}
macro_rules! process_char {
($range:expr, $constructor:ident, $method:ident) => {
if !text_after_suffix.is_empty() {
Err(Error { range, kind: ErrorKind::SuffixNotSupported })
} else {
let range = $range;
match unescape::$method(&string[range.clone()]) {
Ok(val) => ok!(Token::$constructor(val)),
Err((_, kind)) => Err(Error {
range: range.clone(),
kind: ErrorKind::CharEscapeError(EscapeError { range, kind } )
}),
}
}
};
}
match kind {
Str { terminated } => {
terminated_or! {
terminated,
process_str!{
range.start+1..range.end-1,
String,
unescape_str,
UnescapedString
}
}
},
ByteStr { terminated } => {
terminated_or! {
terminated,
process_str! {
range.start+1+1..range.end-1,
Vec,
unescape_byte_str,
Bytes
}
}
},
RawStr { n_hashes, started, terminated } => {
terminated_or! {
terminated,
process_raw_str! {
started,
range.start+2+n_hashes..range.end-1-n_hashes,
String,
unescape_raw_str,
UnescapedString
}
}
},
RawByteStr { n_hashes, started, terminated } => {
terminated_or! {
terminated,
process_raw_str! {
started,
range.start+2+n_hashes+1..range.end-1-n_hashes,
Vec,
unescape_raw_byte_str,
Bytes
}
}
},
Int { .. } => process_number!(Int),
Float { .. } => process_number!(Float),
Char { terminated } => {
terminated_or! {
terminated,
process_char!{
range.start+1..range.end-1,
Char,
unescape_char
}
}
},
Byte { terminated } => {
terminated_or! {
terminated,
process_char!{
range.start+1+1..range.end-1,
Byte,
unescape_byte
}
}
},
}
},
Whitespace => ok!(Token::Whitespace),
Semi => ok!(Token::Semi),
Comma => ok!(Token::Comma),
Dot => ok!(Token::Dot),
OpenParen => ok!(Token::OpenParen),
CloseParen => ok!(Token::CloseParen),
OpenBrace => ok!(Token::OpenBrace),
CloseBrace => ok!(Token::CloseBrace),
OpenBracket => ok!(Token::OpenBracket),
CloseBracket => ok!(Token::CloseBracket),
At => ok!(Token::At),
Pound => ok!(Token::Pound),
Tilde => ok!(Token::Tilde),
Question => ok!(Token::Question),
Colon => ok!(Token::Colon),
Dollar => ok!(Token::Dollar),
Eq => ok!(Token::Eq),
Not => ok!(Token::Not),
Lt => ok!(Token::Lt),
Gt => ok!(Token::Gt),
Minus => ok!(Token::Minus),
And => ok!(Token::And),
Or => ok!(Token::Or),
Plus => ok!(Token::Plus),
Star => ok!(Token::Star),
Slash => ok!(Token::Slash),
Caret => ok!(Token::Caret),
Percent => ok!(Token::Percent),
Unknown => Err(Error { range, kind: UnknownToken }),
}
})
.collect()
}
#[derive(Debug, Clone, PartialEq, PartialOrd)]
pub enum ClonedToken {
// Idents
Ident(String),
RawIdent(String),
Lifetime(String),
// Comments
LineComment(String),
BlockComment(String),
// String and char
UnescapedString(String),
Char(char),
Bytes(Vec<u8>),
Byte(u8),
// Numbers
Int(i64),
Float(f64),
// Symbols
Whitespace,
Semi,
Comma,
Dot,
OpenParen,
CloseParen,
OpenBrace,
CloseBrace,
OpenBracket,
CloseBracket,
At,
Pound,
Tilde,
Question,
Colon,
Dollar,
Eq,
Not,
Lt,
Gt,
Minus,
And,
Or,
Plus,
Star,
Slash,
Caret,
Percent,
}
impl From<Token<'_>> for ClonedToken {
fn from(item: Token<'_>) -> Self {
use Token::*;
match item {
Ident(inner) => ClonedToken::Ident(inner.to_string()),
RawIdent(inner) => ClonedToken::RawIdent(inner.to_string()),
Lifetime(inner) => ClonedToken::Lifetime(inner.to_string()),
LineComment(inner) => ClonedToken::LineComment(inner.to_string()),
BlockComment(inner) => ClonedToken::BlockComment(inner.to_string()),
UnescapedString(inner) => ClonedToken::UnescapedString(inner),
Char(inner) => ClonedToken::Char(inner),
Bytes(inner) => ClonedToken::Bytes(inner),
Byte(inner) => ClonedToken::Byte(inner),
Int(inner) => ClonedToken::Int(inner),
Float(inner) => ClonedToken::Float(inner),
Whitespace => ClonedToken::Whitespace,
Semi => ClonedToken::Semi,
Comma => ClonedToken::Comma,
Dot => ClonedToken::Dot,
OpenParen => ClonedToken::OpenParen,
CloseParen => ClonedToken::CloseParen,
OpenBrace => ClonedToken::OpenBrace,
CloseBrace => ClonedToken::CloseBrace,
OpenBracket => ClonedToken::OpenBracket,
CloseBracket => ClonedToken::CloseBracket,
At => ClonedToken::At,
Pound => ClonedToken::Pound,
Tilde => ClonedToken::Tilde,
Question => ClonedToken::Question,
Colon => ClonedToken::Colon,
Dollar => ClonedToken::Dollar,
Eq => ClonedToken::Eq,
Not => ClonedToken::Not,
Lt => ClonedToken::Lt,
Gt => ClonedToken::Gt,
Minus => ClonedToken::Minus,
And => ClonedToken::And,
Or => ClonedToken::Or,
Plus => ClonedToken::Plus,
Star => ClonedToken::Star,
Slash => ClonedToken::Slash,
Caret => ClonedToken::Caret,
Percent => ClonedToken::Percent,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn all_tokens() {
let string = r###"
ident идент
r#rawident
'1 'лайфтайм
// comment
/// doc-comment
/* multi-line comment */
/*! multi-line doc comment */
"string\u{55}\n"
r#".""."#
r##"."#"."##
'ё'
b"hello"
br#".""."#
br##"."#"."##
b'h'
13
2.55
;
,
.
(
)
{
}
[
]
@
~
?
:
$
=
!
<
>
-
&
|
+
*
/
^
%
_
"###;
use Token::*;
let tokens_with_pos = tokenize(string).unwrap();
let tokens = tokens_with_pos.into_iter().map(|x| x.token).collect::<Vec<_>>();
assert_eq!(tokens, vec![
Whitespace, Ident("ident"),
Whitespace, Ident("идент"),
Whitespace, RawIdent("rawident"),
Whitespace, Lifetime("1"),
Whitespace, Lifetime("лайфтайм"),
Whitespace, LineComment(" comment"),
Whitespace, LineComment("/ doc-comment"),
Whitespace, BlockComment(" multi-line comment "),
Whitespace, BlockComment("! multi-line doc comment "),
Whitespace, UnescapedString("string\u{55}\n".to_string()),
Whitespace, UnescapedString(".\"\".".to_string()),
Whitespace, UnescapedString(".\"#\".".to_string()),
Whitespace, Char('ё'),
Whitespace, Bytes(br#"hello"#.to_vec()),
Whitespace, Bytes(br#".""."#.to_vec()),
Whitespace, Bytes(br##"."#"."##.to_vec()),
Whitespace, Byte(b'h'),
Whitespace, Int(13),
Whitespace, Float(2.55),
Whitespace, Semi,
Whitespace, Comma,
Whitespace, Dot,
Whitespace, OpenParen,
Whitespace, CloseParen,
Whitespace, OpenBrace,
Whitespace, CloseBrace,
Whitespace, OpenBracket,
Whitespace, CloseBracket,
Whitespace, At,
// Whitespace, Pound, // What is this?
Whitespace, Tilde,
Whitespace, Question,
Whitespace, Colon,
Whitespace, Dollar,
Whitespace, Eq,
Whitespace, Not,
Whitespace, Lt,
Whitespace, Gt,
Whitespace, Minus,
Whitespace, And,
Whitespace, Or,
Whitespace, Plus,
Whitespace, Star,
Whitespace, Slash,
Whitespace, Caret,
Whitespace, Percent,
Whitespace, Ident("_"),
Whitespace,
]);
}
#[test]
fn simple() {
use Token::*;
let string = r#"ident = "string\n\u{55}";"#;
assert_eq!(tokenize(string), Ok(vec![
TokenWithPos { range: 0..5, token: Ident("ident") },
TokenWithPos { range: 5..7, token: Whitespace },
TokenWithPos { range: 7..8, token: Eq },
TokenWithPos { range: 8..9, token: Whitespace },
TokenWithPos { range: 9..25, token: UnescapedString("string\n\u{55}".to_string()) },
TokenWithPos { range: 25..26, token: Semi },
]));
}
}
| true |
de9d3a7d988bb572ee596a636a8331a9a623a4ec
|
Rust
|
tokio-rs/axum
|
/examples/rest-grpc-multiplex/src/main.rs
|
UTF-8
| 2,282 | 2.609375 | 3 |
[] |
no_license
|
//! Run with
//!
//! ```not_rust
//! cargo run -p example-rest-grpc-multiplex
//! ```
use self::multiplex_service::MultiplexService;
use axum::{routing::get, Router};
use proto::{
greeter_server::{Greeter, GreeterServer},
HelloReply, HelloRequest,
};
use std::net::SocketAddr;
use tonic::{Response as TonicResponse, Status};
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
mod multiplex_service;
mod proto {
tonic::include_proto!("helloworld");
pub(crate) const FILE_DESCRIPTOR_SET: &[u8] =
tonic::include_file_descriptor_set!("helloworld_descriptor");
}
#[derive(Default)]
struct GrpcServiceImpl {}
#[tonic::async_trait]
impl Greeter for GrpcServiceImpl {
async fn say_hello(
&self,
request: tonic::Request<HelloRequest>,
) -> Result<TonicResponse<HelloReply>, Status> {
tracing::info!("Got a request from {:?}", request.remote_addr());
let reply = HelloReply {
message: format!("Hello {}!", request.into_inner().name),
};
Ok(TonicResponse::new(reply))
}
}
async fn web_root() -> &'static str {
"Hello, World!"
}
#[tokio::main]
async fn main() {
// initialize tracing
tracing_subscriber::registry()
.with(
tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| "example_rest_grpc_multiplex=debug".into()),
)
.with(tracing_subscriber::fmt::layer())
.init();
// build the rest service
let rest = Router::new().route("/", get(web_root));
// build the grpc service
let reflection_service = tonic_reflection::server::Builder::configure()
.register_encoded_file_descriptor_set(proto::FILE_DESCRIPTOR_SET)
.build()
.unwrap();
let grpc = tonic::transport::Server::builder()
.add_service(reflection_service)
.add_service(GreeterServer::new(GrpcServiceImpl::default()))
.into_service();
// combine them into one service
let service = MultiplexService::new(rest, grpc);
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
tracing::debug!("listening on {}", addr);
hyper::Server::bind(&addr)
.serve(tower::make::Shared::new(service))
.await
.unwrap();
}
| true |
cd7c576c11bb50906c123a7f237def0e4eb4dcfd
|
Rust
|
nouvadam/pathtracer
|
/src/material/metalic.rs
|
UTF-8
| 1,231 | 3 | 3 |
[
"MIT"
] |
permissive
|
use crate::hit::Hit;
use crate::material::*;
use crate::misc::ZeroPdf;
use crate::ray::Ray;
use crate::V3;
/// Metalic material.
#[derive(Clone)]
pub struct Metalic {
/// Color of metalic surface.
pub albedo: V3<f32>,
/// Irregularity of surface.
pub fuzz: f32,
}
impl MaterialTrait for Metalic {
fn scatter<'a>(&self, ray_in: &'a Ray, hit: &Hit) -> Option<ScatterRecord<'a>> {
let norm = ray_in.end.norm();
let reflected = reflect(norm, hit.normal);
let end = reflected + V3::get_point_on_sphere() * self.fuzz;
let specular_ray = Ray {
origin: hit.point,
end,
..*ray_in
};
Some(ScatterRecord {
specular_ray: Some(specular_ray),
attenuation: self.albedo,
pdf: Box::new(ZeroPdf),
})
}
fn scattering_pdf<'a>(&self, _ray_in: &'a Ray, _hit: &Hit, _ray_scattered: &Ray) -> f32 {
todo!()
}
fn color_emitted<'a>(&self, _ray_in: &'a Ray, _hit: &Hit) -> V3<f32> {
todo!()
}
}
impl Metalic {
/// Returns new Dielectric material.
pub fn new(albedo: V3<f32>, fuzz: f32) -> Material {
Material::Metalic(Metalic { albedo, fuzz })
}
}
| true |
69105b192688a60bc46e8ffb48b749c8c83cf280
|
Rust
|
OIdiotLin/LeetCode-Solutions
|
/354/solution.rs
|
UTF-8
| 815 | 2.859375 | 3 |
[] |
no_license
|
struct Solution {}
impl Solution {
pub fn max_envelopes(envelopes: Vec<Vec<i32>>) -> i32 {
if envelopes.len() == 0 {
return 0;
}
let mut pairs = envelopes.clone();
pairs.sort();
let mut f = vec![1; pairs.len()];
let mut res = 1;
for i in 1..f.len() {
for j in (0..i).rev() {
if pairs[j][0] < pairs[i][0] && pairs[j][1] < pairs[i][1] {
f[i] = std::cmp::max(f[j] + 1, f[i]);
}
}
res = std::cmp::max(res, f[i])
}
res
}
}
fn main() {
let vec = vec![vec![4,5],
vec![4,6],
vec![6,7],
vec![2,3],
vec![1,1]];
println!("{}", Solution::max_envelopes(vec));
}
| true |
94e33533766c3189222b1b0ab2c3937c5f1e37a4
|
Rust
|
graphql-rust/graphql-client
|
/graphql_client/tests/operation_selection.rs
|
UTF-8
| 1,916 | 2.828125 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"MIT",
"Apache-2.0"
] |
permissive
|
use graphql_client::GraphQLQuery;
#[derive(GraphQLQuery)]
#[graphql(
query_path = "tests/operation_selection/queries.graphql",
schema_path = "tests/operation_selection/schema.graphql",
response_derives = "Debug, PartialEq, Eq"
)]
pub struct Heights;
#[derive(GraphQLQuery)]
#[graphql(
query_path = "tests/operation_selection/queries.graphql",
schema_path = "tests/operation_selection/schema.graphql",
response_derives = "Debug, PartialEq, Eq"
)]
pub struct Echo;
const HEIGHTS_RESPONSE: &str = r##"{"mountainHeight": 224, "buildingHeight": 12}"##;
const ECHO_RESPONSE: &str = r##"{"echo": "tiramisù"}"##;
#[test]
fn operation_selection_works() {
let heights_response_data: heights::ResponseData =
serde_json::from_str(HEIGHTS_RESPONSE).unwrap();
let echo_response_data: echo::ResponseData = serde_json::from_str(ECHO_RESPONSE).unwrap();
let _echo_variables = echo::Variables {
msg: Some("hi".to_string()),
};
let _height_variables = heights::Variables {
building_id: "12".to_string(),
mountain_name: Some("canigou".to_string()),
};
let expected_echo = echo::ResponseData {
echo: Some("tiramisù".to_string()),
};
let expected_heights = heights::ResponseData {
mountain_height: Some(224),
building_height: Some(12),
};
assert_eq!(expected_echo, echo_response_data);
assert_eq!(expected_heights, heights_response_data);
}
#[test]
fn operation_name_is_correct() {
let echo_variables = echo::Variables {
msg: Some("hi".to_string()),
};
let height_variables = heights::Variables {
building_id: "12".to_string(),
mountain_name: Some("canigou".to_string()),
};
assert_eq!(Echo::build_query(echo_variables).operation_name, "Echo");
assert_eq!(
Heights::build_query(height_variables).operation_name,
"Heights"
);
}
| true |
8cf63bfe1dafbfbfa2798af33aefee1f63dde0bc
|
Rust
|
Peter229/SEngine
|
/src/network_game.rs
|
UTF-8
| 9,881 | 2.625 | 3 |
[] |
no_license
|
use crate::mario;
use crate::online_mario;
use crate::level;
use crate::shader;
use crate::camera;
use crate::sound;
use crate::network;
use std::net::{UdpSocket, SocketAddr, IpAddr, Ipv4Addr};
use std::io::{self, Read, Error, stdin, stdout, Write, ErrorKind};
use std::collections::HashMap;
use cgmath;
use std::ffi;
pub struct Game {
player: mario::Player,
players: HashMap<std::net::SocketAddr, online_mario::Player>,
level: level::Level,
camera: camera::Camera,
network: network::Network,
}
impl Game {
pub fn new() -> Game {
let mut player = mario::Player::new();
let mut players: HashMap<std::net::SocketAddr, online_mario::Player> = HashMap::new();
let mut level = level::Level::new();
let mut camera = camera::Camera::new();
let mut network = network::Network::quick_new();
Game { player, players, level, camera, network, }
}
pub fn start(&mut self) {
//self.sound_manager.play_sound("track0", 0);
//self.sound_manager.set_volume(0.5, 0);
}
pub fn init_peer(&mut self) {
self.network = network::Network::new();
}
pub fn add_player(&mut self) {
let mut s=String::new();
print!("Please enter the ip of the person you want to connect to: ");
let _=stdout().flush();
stdin().read_line(&mut s).expect("Did not enter a correct string");
let socket: SocketAddr = (s.trim_right()).parse().unwrap();
self.players.insert(socket, online_mario::Player::new());
}
pub fn add_player_fast(&mut self, socket_addr: SocketAddr) {
self.players.insert(socket_addr, online_mario::Player::new());
}
pub fn request_sync(&mut self, socket_addr: SocketAddr) {
let mut buffer: [u8; 16] = [0; 16];
buffer[0] = 245;
self.network.send_inputs(&buffer, socket_addr.clone());
println!("Request to sync sent");
}
pub fn check_updates(&mut self, sound_manager: &sound::Sound_Manager) {
let mut come_through = self.network.recieve();
if come_through.recieve {
//Update world
if come_through.buffer[0] == 244 {
self.online_mouse_update(&come_through.buffer);
}
else if come_through.buffer[0] == 245 {
println!("HOST: Recieved sync request");
//Send sync info
let mut buffer: [u8; 16] = come_through.buffer;
buffer[0] = 246;
let mut new_socket = come_through.from_socket.ip().to_string();
let new_socket_parts: Vec<&str> = new_socket.split(".").collect();
//let new_socket_length = b.len();
//buffer[1] = new_socket_length as u8;
let mut pos = 1;
for part in new_socket_parts {
buffer[pos] = part.parse::<u8>().unwrap();
pos += 1;
}
println!("{:?}", buffer);
for socket in self.players.keys() {
//Dont send it init sync back to person who wants sync
if socket.ip() != come_through.from_socket.ip() {
self.network.send_inputs(&buffer, socket.clone());
}
}
let mut buffer_two: [u8; 16] = [0; 16];
buffer_two[0] = 247;
buffer_two[1] = (((self.player.get_position_x().floor() as usize) & 0xfff0) / 16) as u8;
buffer_two[2] = ((self.player.get_position_x().floor() as usize) % 16) as u8;
buffer_two[3] = (((self.player.get_position_y().floor() as usize) & 0xfff0) / 16) as u8;
buffer_two[4] = ((self.player.get_position_y().floor() as usize) % 16) as u8;
self.network.send_inputs(&buffer_two, come_through.from_socket.clone());
if !self.players.contains_key(&come_through.from_socket) {
self.players.insert(come_through.from_socket, online_mario::Player::new());
}
}
else if come_through.buffer[0] == 246 {
println!("Resyncing with other players");
let socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(come_through.buffer[1], come_through.buffer[2], come_through.buffer[3], come_through.buffer[4])), 3456);
println!("Socket that needs syncing with {}", socket_addr);
let mut buffer_two: [u8; 16] = [0; 16];
buffer_two[0] = 247;
buffer_two[1] = (((self.player.get_position_x().floor() as usize) & 0xfff0) / 16) as u8;
buffer_two[2] = ((self.player.get_position_x().floor() as usize) % 16) as u8;
buffer_two[3] = (((self.player.get_position_y().floor() as usize) & 0xfff0) / 16) as u8;
buffer_two[4] = ((self.player.get_position_y().floor() as usize) % 16) as u8;
self.network.send_inputs(&buffer_two, socket_addr.clone());
if !self.players.contains_key(&socket_addr) {
self.players.insert(socket_addr, online_mario::Player::new());
}
}
else if come_through.buffer[0] == 247 {
println!("Sync confirmed");
let mut pos_x: u32 = (((come_through.buffer[1] as u32) * 16_u32) + (come_through.buffer[2] as u32));
let mut pos_y: u32 = (((come_through.buffer[3] as u32) * 16_u32) + (come_through.buffer[4] as u32));
if self.players.contains_key(&come_through.from_socket) {
self.players.get_mut(&come_through.from_socket).unwrap().update_pos(pos_x, pos_y);
}
else {
self.players.insert(come_through.from_socket, online_mario::Player::new_pos(pos_x, pos_y));
}
}
else {
//Game Update
if self.players.contains_key(&come_through.from_socket) {
self.players.get_mut(&come_through.from_socket).unwrap().set_key_state(&come_through.buffer);
self.players.get_mut(&come_through.from_socket).unwrap().update(&self.level.get_tiles(), sound_manager);
}
else {
self.players.insert(come_through.from_socket, online_mario::Player::new());
}
}
}
}
pub fn update(&mut self, keys: &Vec<HashMap<usize, bool>>, sound_manager: &sound::Sound_Manager) {
self.player.inputs(keys);
self.player.update(&self.level.get_tiles(), sound_manager);
for socket in self.players.keys() {
self.network.send_inputs(&self.player.online_state_buffer(), socket.clone());
}
self.camera.pos_x = self.player.get_position_x() - (256.0 / 2.0);
self.camera.pos_y = self.player.get_position_y() - (192.0 / 3.0);
self.camera.update();
}
pub fn render(&mut self, quad_shader: &shader::Program, level_shader: &shader::Program, ortho: cgmath::Matrix4<f32>) {
let eye = cgmath::Point3::new(self.camera.pos_x, self.camera.pos_y, 1.0);
let dir = cgmath::Vector3::new(0.0, 0.0, -1.0);
let up = cgmath::Vector3::new(0.0, 1.0, 0.0);
let view = cgmath::Matrix4::look_at_dir(eye, dir, up);
let view_projection = ortho * view;
quad_shader.set_used();
quad_shader.set_mat4_cg(&view_projection, ffi::CStr::from_bytes_with_nul(b"view_projection\0").expect("CStr::from_bytes_with_nul failed"));
level_shader.set_used();
level_shader.set_mat4_cg(&view_projection, ffi::CStr::from_bytes_with_nul(b"view_projection\0").expect("CStr::from_bytes_with_nul failed"));
self.player.render(quad_shader);
for player in self.players.values_mut() {
player.render(quad_shader);
}
self.level.render(level_shader);
}
pub fn online_mouse_update(&mut self, keys: &[u8; 16]) {
let left_mouse = keys[1] == 1;
let right_mouse = keys[2] == 1;
let tile_pos_x = keys[3] as usize;
let tile_pos_y = keys[4] as usize;
let current_tile = keys[5] as u32;
self.level.mouse_edit(tile_pos_x, tile_pos_y, left_mouse, right_mouse, current_tile);
}
pub fn mouse_update(&mut self, mouse_x: i32, mouse_y: i32, left_mouse: bool, right_mouse: bool, current_tile: u32) {
let tile_pos_x = (((mouse_x as usize) + (self.camera.pos_x as usize)) & 0xfff0) / 16;
let tile_pos_y = (((mouse_y as usize) + (self.camera.pos_y as usize)) & 0xfff0) / 16;
//Stop the squad from destroying the floor :(
if tile_pos_x != 0 && tile_pos_x != 63 && tile_pos_y != 0 && tile_pos_y != 63 {
self.level.mouse_edit(tile_pos_x, tile_pos_y, left_mouse, right_mouse, current_tile);
if left_mouse || right_mouse {
let mut buffer: [u8; 16] = [0; 16];
buffer[0] = 244;
if left_mouse {
buffer[1] = 1;
}else {
buffer[1] = 0;
}
if right_mouse {
buffer[2] = 1;
}else {
buffer[2] = 0;
}
buffer[3] = tile_pos_x as u8;
buffer[4] = tile_pos_y as u8;
buffer[5] = current_tile as u8;
for socket in self.players.keys() {
self.network.send_inputs(&buffer, socket.clone());
}
}
}
}
}
| true |
236646db2d0876cb02bb3f4d531fb68679b1255e
|
Rust
|
mchesser/gdbstub
|
/src/target/ext/catch_syscalls.rs
|
UTF-8
| 1,917 | 3.015625 | 3 |
[
"MIT"
] |
permissive
|
//! Enable or disable catching syscalls from the inferior process.
use crate::arch::Arch;
use crate::target::{Target, TargetResult};
/// Target Extension - Enable and disable catching syscalls from the inferior
/// process.
///
/// Implementing this extension allows the target to support the `catch syscall`
/// GDB client command. See [GDB documentation](https://sourceware.org/gdb/onlinedocs/gdb/Set-Catchpoints.html)
/// for further details.
///
/// Corresponds to GDB's [`QCatchSyscalls`](https://sourceware.org/gdb/current/onlinedocs/gdb/General-Query-Packets.html#QCatchSyscalls) command.
pub trait CatchSyscalls: Target {
/// Enables catching syscalls from the inferior process.
///
/// If `filter` is `None`, then all syscalls should be reported to GDB. If a
/// filter is provided, only the syscalls listed in the filter should be
/// reported to GDB.
///
/// Note: filters are not combined, subsequent calls this method should
/// replace any existing syscall filtering.
fn enable_catch_syscalls(
&mut self,
filter: Option<SyscallNumbers<<Self::Arch as Arch>::Usize>>,
) -> TargetResult<(), Self>;
/// Disables catching syscalls from the inferior process.
fn disable_catch_syscalls(&mut self) -> TargetResult<(), Self>;
}
define_ext!(CatchSyscallsOps, CatchSyscalls);
/// Describes where the syscall catchpoint was triggered at.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CatchSyscallPosition {
/// Reached the entry location of the syscall.
Entry,
/// Reached the return location of the syscall.
Return,
}
/// Iterator of syscall numbers that should be reported to GDB.
pub struct SyscallNumbers<'a, U> {
pub(crate) inner: &'a mut dyn Iterator<Item = U>,
}
impl<U> Iterator for SyscallNumbers<'_, U> {
type Item = U;
fn next(&mut self) -> Option<Self::Item> {
self.inner.next()
}
}
| true |
140016a49bbbd19c0c945a4ce7a5c955ef56a9bf
|
Rust
|
bolipus/rustcodewars
|
/src/main.rs
|
UTF-8
| 21,520 | 3.359375 | 3 |
[] |
no_license
|
use std::collections::HashMap;
use std::fmt;
use std::mem;
use std::str::FromStr;
mod codewars;
fn literals_operator() {
println!("1 + 2 = {}", 1i32 + 2);
println!("0011 ^ 0110 = {:04b}", 0b0011u32 ^ 0b0110u32);
println!("0011 << 2 = {:04b}", 0b0011u32 << 2);
println!("0011 >> 2 = {:04b}", 0b0011u32 >> 2);
println!("0o7 << 1 = {:04o}", 0o7u32 << 1);
println!("0x7 << 1 = {:04x}", 0x7u32 << 1);
}
fn reverse(pair: (i32, bool)) -> (bool, i32) {
let (x, y) = pair;
(y, x)
}
#[derive(Debug)]
struct Matrix(f32, f32, f32, f32);
fn transpose(matrix: Matrix) -> Matrix {
Matrix(matrix.0, matrix.2, matrix.1, matrix.3)
}
impl fmt::Display for Matrix {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "( {}, {} )\n( {}, {} )", self.0, self.1, self.2, self.3)
}
}
fn tuple_activity() {
println!("{:?}", reverse((20i32, false)));
println!("one element tuple: {:?}", (5u32,));
println!("just an integer: {:?}", (5u32));
let tuple = (1, "hello", 4.5, true);
let (a, b, c, d) = tuple;
println!("{:?}, {:?}, {:?}, {:?}", a, b, c, d);
let matrix = Matrix(1.1, 1.2, 2.1, 2.2);
println!("Matrix:\n{}", matrix);
println!("Transpose:\n{}", transpose(matrix));
}
fn analyze_slice(slice: &[Matrix]) {
println!("first element of the slice: \n{}", slice[0]);
println!("the slice has {} elements.", slice.len());
}
fn arrays_slices() {
let x: [Matrix; 2] = [
Matrix(10.2f32, 2.1f32, 3.1f32, 4.5f32),
Matrix(5.2f32, 6.1f32, 2.1f32, 8.5f32),
];
println!("Array occupies: {:?} bytes", mem::size_of_val(&x));
analyze_slice(&x[1..2]);
}
#[derive(Debug, Copy, Clone)]
struct Person<'a> {
name: &'a str,
age: u8,
}
impl<'a> Person<'a> {
fn changeName(&mut self, new_name: &'a str) -> &'a Person {
self.name = new_name;
self
}
}
#[derive(Debug)]
struct Point {
x: f32,
y: f32,
}
#[derive(Debug)]
struct Triangle {
top_left: Point,
bottom_right: Point,
}
struct Unit;
struct Pair(i32, i32);
fn square(point: Point, val: f32) -> Triangle {
Triangle {
bottom_right: Point {
x: point.x + val,
y: point.y - val,
},
top_left: point,
}
}
fn struct_test() {
let mut person = Person {
name: "Peter",
age: 30u8,
};
let new_name = "Janez";
let changedPerson = person.changeName(new_name);
println!("Person: {:?}", changedPerson);
let point = Point { x: 20.2, y: 30.3 };
println!("Point: {:?}", point);
let bottom_right = Point { x: 10.2, ..point };
println!("bottom_right: {:?}", bottom_right);
let top_left = Point { x: 2.2, y: 5.3 };
let triangle = Triangle {
bottom_right: bottom_right,
top_left: top_left,
};
println!("{:?}", triangle);
let Triangle {
bottom_right: Point { x: x1, y: y1 },
top_left: Point { x: x2, y: y2 },
} = triangle;
println!("x1: {}, y1: {}, x2: {}, y2:{}", x1, y1, x2, y2);
println!("Area:{}", (x2 - x1) * (y2 - y1));
let unit = Unit;
let pair = Pair(20, 30);
println!("pair contains {:?} and {:?}", pair.0, pair.1);
let Pair(x, y) = pair;
println!("pair contains {:?} and {:?}", x, y);
println!("{:?}", square(point, 20.2));
}
enum WebEvent {
PageLoad,
PageUnload,
KeyPress(char),
Paste(String),
Click { x: i64, y: i64 },
}
use crate::WebEvent::*;
impl WebEvent {
fn run(&self, m: i32) -> String {
match self {
PageLoad => return format!("Page loaded in {} seconds.", m),
PageUnload => format!("PageUnloaded"),
KeyPress(c) => format!("KeyPressed: {}", c),
Paste(s) => format!("Pasted: {}", s),
Click { x, y } => format!("Clicked on position: {}, {}", x, y),
}
}
}
fn inspect(event: WebEvent) {
match event {
PageLoad => println!("PageLoaded"),
PageUnload => println!("PageUnloaded"),
KeyPress(c) => println!("KeyPressed: {}", c),
Paste(s) => println!("Pasted: {}", s),
Click { x, y } => println!("Clicked on position: {}, {}", x, y),
}
}
enum Number_enum {
Zero,
One,
Two,
}
// enum with explicit discriminator
enum Color {
Red = 0xff0000,
Green = 0x00ff00,
Blue = 0x0000ff,
}
fn test_enum() {
let pressed = KeyPress('x');
// `to_owned()` creates an owned `String` from a string slice.
let pasted = Paste("my text".to_owned());
let click = Click { x: 20, y: 80 };
let load = PageLoad;
let unload = PageUnload;
inspect(pressed);
inspect(pasted);
inspect(click);
inspect(load);
inspect(unload);
let loadSec = WebEvent::PageLoad;
println!("{}", &loadSec.run(20));
println!("zero is {}", Number_enum::Zero as i32);
println!("one is {}", Number_enum::One as i32);
println!("roses are #{:06x}", Color::Red as i32);
println!("violets are #{:06x}", Color::Blue as i32);
}
fn test_var_bind() {
let mut x = 2;
{
let x = "4";
}
x = 4;
}
fn casting() {
let decimal = 22.8832_f32;
let integer = decimal as u8;
println!("Integer: {}", integer);
let character = integer as char;
println!("character: {}", character);
println!("1000 as a u16 is: {:b}", 1000 as u16);
let num = 1000;
println!("1000 as a u8 is : {:b}", num as u8);
println!(" -1 as a u8 is : {:b}", (-1i8) as u8);
println!("1000 mod 256 is : {:b}", 1000 % 256);
// Unless it already fits, of course.
println!(" 128 as a i16 is: {:b} ({})", 128 as i16, 128 as i16);
// 128 as u8 -> 128, whose two's complement in eight bits is:
let num: i16 = 128;
println!(" 128 as a i8 is : {:b} ({})", num as i8, num as i8);
println!("127={:b}", 127_i8);
println!("-128={:b}", -128_i8);
println!("255={:b}", 255_u8);
println!("0={:b}", 0_u8);
println!("255= {}", 127_u8 as i8);
println!("0={:b}", 0_u8 as i8);
let x = 1u8;
let y = 2u32;
let z = 3f32;
// Unsuffixed literal, their types depend on how they are used
let i = 1;
let f = 1.0;
// `size_of_val` returns the size of a variable in bytes
println!("size of `x` in bytes: {}", std::mem::size_of_val(&x));
println!("size of `y` in bytes: {}", std::mem::size_of_val(&y));
println!("size of `z` in bytes: {}", std::mem::size_of_val(&z));
println!("size of `i` in bytes: {}", std::mem::size_of_val(&i));
println!("size of `f` in bytes: {}", std::mem::size_of_val(&f));
let elem = 5u8;
// Create an empty vector (a growable array).
let mut vec = Vec::new();
// At this point the compiler doesn't know the exact type of `vec`, it
// just knows that it's a vector of something (`Vec<_>`).
// Insert `elem` in the vector.
vec.push(elem);
// Aha! Now the compiler knows that `vec` is a vector of `u8`s (`Vec<u8>`)
// TODO ^ Try commenting out the `vec.push(elem)` line
println!("{:?}", vec);
}
use std::convert::From;
use std::convert::Into;
use std::convert::TryFrom;
use std::convert::TryInto;
#[derive(Debug)]
struct Number {
value: i32,
}
impl From<i32> for Number {
fn from(item: i32) -> Self {
Number { value: item }
}
}
impl fmt::Display for Number {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Number is: {}", self.value)
}
}
#[derive(Debug, PartialEq)]
struct EvenNumber(i32);
impl TryFrom<i32> for EvenNumber {
type Error = ();
fn try_from(value: i32) -> Result<Self, Self::Error> {
if value % 2 == 0 {
Ok(EvenNumber(value))
} else {
Err(())
}
}
}
fn conversion() {
let s = "Test";
let myString = String::from(s);
let b = myString.into_boxed_str();
let ptr = b.as_ptr();
println!("b:{:?}", ptr);
let ref_b = b.as_ref();
println!("s:{:?}", ref_b);
let number = Number::from(34_i32);
println!("{}", number);
let n = 5;
let num: i32 = n.into();
println!("My number is {:?}", num);
assert_eq!(EvenNumber::try_from(8), Ok(EvenNumber(8)));
assert_eq!(EvenNumber::try_from(5), Err(()));
println!("{:?}", EvenNumber::try_from(5));
let result: Result<EvenNumber, ()> = 8i32.try_into();
assert_eq!(result, Ok(EvenNumber(8)));
let result: Result<EvenNumber, ()> = 5i32.try_into();
assert_eq!(result, Err(()));
let parsed: i32 = "5".parse().unwrap();
let turbo_parsed = "10".parse::<i32>().unwrap();
let sum = parsed + turbo_parsed;
println!("Sum: {:?}", sum);
}
fn expression() {
let x0 = 2;
let sum = {
let x = 20_i8;
let y = 12;
x + y + x0
};
println!("Sum: {:?}", sum)
}
fn flowControl() {
let mut count = 0;
loop {
count += 1;
if count % 2 == 0 {
continue;
}
println!("Count: {}", count);
if count > 6 {
break;
}
}
let mut optional = Some(20);
match optional {
Some(i) => {
println!("Number: {:?}", i);
}
_ => {
println!("Not present");
}
}
if let Some(i) = Some(20) {
println!("Number is indeed: {}", i);
}
while let Some(i) = optional {
if i == 25 {
println!("Number is: {}", i);
optional = None;
} else {
println!("`i` is `{:?}`. Try again.", i);
optional = Some(i + 1);
}
}
}
fn isDivisibleBy(lhs: u32, rhs: u32) -> bool {
if (rhs == 0) {
return false;
}
lhs % rhs == 0
}
impl Point {
fn origin() -> Point {
Point { x: 0.0, y: 0.0 }
}
fn new(x: f32, y: f32) -> Point {
Point { x: x, y: y }
}
fn distance(&self, p: &Point) -> f32 {
let dx = self.x - p.x;
let dy: f32 = self.y - p.y;
(dx * dy + dy + dy).sqrt()
}
fn translate(&mut self, dx: f32, dy: f32) {
self.x += dx;
self.y += dy;
}
}
fn functions() {
println!("isD: {:?}", isDivisibleBy(20, 4));
println!("isD: {:?}", isDivisibleBy(20, 3));
let mut point = Point::new(22.2, 32.3);
let mut origin = Point::origin();
println!("Distance: {:?}", point.distance(&origin));
point.translate(3.0, -2.0);
println!("Point: {:?}", point);
println!("Distance: {:?}", point.distance(&origin));
let x = 20;
let fun1 = |i: i32| -> i32 { i + 1 + x };
let fun2 = |i| i + 1 + x;
let i = 1;
println!("Inc1: {:?}", fun1(i));
println!("Inc2: {:?}", fun2(i));
let one = || 1;
println!("One: {:?}", one());
let color = "Green";
let print = || println!("Color: {:?}", color);
print();
let _reborow = &color;
print();
let mut count = 0;
let mut inc = || {
count += 1;
println!("Count: {:?}", count);
};
inc();
inc();
let reborrow = &mut count;
let movable = Box::new(3);
let consume = || {
println!("Movable: {:?}", movable);
mem::drop(movable);
};
consume();
let haystack = vec![1, 2, 3];
let contains = move |needle| haystack.contains(needle);
println!("{}", contains(&1));
println!("{}", contains(&2));
}
fn apply<F>(f: F)
where
F: FnOnce(),
{
f();
}
fn apply_to_3<F>(f: F) -> i32
where
F: Fn(i32) -> i32,
{
f(3)
}
fn call_me<F: Fn()>(f: F) {
f();
}
fn function() {
println!("I am function");
}
fn functions2() {
let x = 30;
println!("x: {:?}", x);
let y = apply_to_3(|x| x + 20);
println!("y: {:?}", y);
let greeting = "Hello";
let mut farewel = "Goodby".to_owned();
let diary = || {
println!("I said {}", greeting);
farewel.push_str("!!!!!");
println!("Than I screemed {}", farewel);
println!("Than I sleep");
mem::drop(farewel);
};
apply(diary);
let double = |x| 2 * x;
println!("3 doubled: {}", apply_to_3(double));
let closure = || println!("I am closure");
call_me(function);
call_me(closure);
}
fn create_fn() -> impl Fn() {
let text = "Fn".to_owned();
move || println!("This is a text: {}", text)
}
fn create_fn_mut() -> impl FnMut() {
let text = "FnMut".to_owned();
move || println!("This is a text: {}", text)
}
fn create_fn_once() -> impl FnOnce() {
let text = "FnOnce".to_owned();
move || println!("This is a: {}", text)
}
fn functions3() {
let x = create_fn();
x();
let mut y = create_fn_mut();
y();
let z = create_fn_once();
z();
let v1 = vec![1, 2, 3];
let v2 = vec![4, 5, 6];
println!("2 in v1: {}", v1.iter().any(|&x| x == 2));
println!("2 in v2: {}", v2.iter().any(|&x| x == 2));
let a1 = [1, 2, 3];
let a2 = [4, 5, 6];
println!("2 in v1: {}", a1.iter().any(|&x| x == 2));
println!("2 in v2: {}", a2.iter().any(|&x| x == 2));
let mut iter1 = v1.iter();
let mut into_iter = v2.into_iter();
println!("Find 2 in v1: {:?}", iter1.find(|&&x| x == 2));
println!("Find 2 in v1: {:?}", into_iter.find(|&x| x == 2));
let array1 = [1, 2, 3];
let array2 = [4, 5, 6];
println!("Find 2 in v1: {:?}", array1.iter().find(|&&x| x == 2));
println!("Find 2 in v1: {:?}", array2.into_iter().find(|&&x| x == 2));
let index_of_first_even_number = array1.iter().position(|x| x % 2 == 0);
println!(
"index_of_first_even_number: {}",
index_of_first_even_number.unwrap()
);
}
fn is_odd(n: u32) -> bool {
n % 2 == 1
}
fn foo() -> () {
()
}
fn higherOrder() {
let upper = 1000;
let mut acc = 0;
for n in 0.. {
let n_squared = n * n;
if n_squared > upper {
break;
} else if is_odd(n_squared) {
acc += n_squared;
}
}
println!("Sum1: {:?}", acc);
let sum2 = (0..)
.map(|n| n * n)
.take_while(|&n_squared| n_squared < upper)
.filter(|&n_squared| n_squared % 2 == 1)
.fold(0, |acc, n_squared| acc + n_squared);
println!("Sum2: {:?}", sum2);
fn sum_odd_numbers(up_to: u32) -> u32 {
let mut acc = 0;
for i in 0..up_to {
// Notice that the return type of this match expression must be u32
// because of the type of the "addition" variable.
let addition: u32 = match i % 2 == 1 {
// The "i" variable is of type u32, which is perfectly fine.
true => i,
// On the other hand, the "continue" expression does not return
// u32, but it is still fine, because it never returns and therefore
// does not violate the type requirements of the match expression.
false => continue,
};
acc += addition;
}
acc
}
println!(
"Sum of odd numbers up to 9 (excluding): {}",
sum_odd_numbers(9)
);
}
struct S;
struct GenericVal<T>(T);
impl GenericVal<i32> {}
impl GenericVal<S> {}
impl<T> GenericVal<T> {}
struct Val {
val: f64,
}
struct GenVal<T> {
gen_val: T,
}
// impl of Val
impl Val {
fn value(&self) -> &f64 {
&self.val
}
}
// impl of GenVal for a generic type `T`
impl<T> GenVal<T> {
fn value(&self) -> &T {
&self.gen_val
}
}
fn generics() {
let x = Val { val: 3.0 };
let y = GenVal { gen_val: 3i32 };
println!("{}, {}", x.value(), y.value());
}
fn create_box() {
let _box = Box::new(3i32);
}
struct ToDrop;
impl Drop for ToDrop {
fn drop(&mut self) {
println!("ToDrop is being dropped");
}
}
fn destroy_box(c: Box<i32>) {
println!("Destroying a box that contains {}", c);
// `c` is destroyed and the memory freed
}
fn scoping() {
/* create_box();
let _box2 = Box::new(5i32);
{
let _box3 = Box::new(4i32);
}
let x = ToDrop;
{
let y = ToDrop;
}*/
let x = 5u32;
let y = x;
println!("x is {}, and y is {}", x, y);
let a = Box::new(5i32);
let mut b = a;
*b = 30i32;
//destroy_box(b);
println!("{}", b);
}
fn ownership() {
let a = Box::new(5i32);
let mut b = a;
*b = 4;
println!("{}", b);
}
fn eat_box(boxed: Box<i32>) {
println!("{}", boxed);
}
fn borrow(borrowed: &i32) {
println!("{}", borrowed);
}
fn borrowing() {
let boxed = Box::new(5_i32);
let stacked = 6_i32;
borrow(&boxed);
borrow(&stacked);
{
let refTo: &i32 = &boxed;
borrow(refTo);
}
eat_box(boxed);
}
#[derive(Clone, Copy)]
struct Book {
author: &'static str,
title: &'static str,
year: u32,
}
fn borrow_book(book: &Book) {
println!("I immutably borrowed {} - {}", book.author, book.title);
}
fn new_edition(book: &mut Book) {
book.year = 2014;
println!("I mutably borrowed {} - {} edition", book.title, book.year);
}
fn mutability() {
let immutable_book = Book {
author: "Ivan Cankar",
title: "Hlapci",
year: 1910,
};
let mut mutable_book = immutable_book;
borrow_book(&immutable_book);
borrow_book(&mutable_book);
new_edition(&mut mutable_book);
}
struct Location {
x: i32,
y: i32,
z: i32,
}
fn aliasing() {
let mut location = Location { x: 0, y: 0, z: 0 };
let borrow1 = &location;
let borrow2 = &location;
println!("{} {}", location.x, borrow1.x);
//let mut_borow = &mut location;
println!(
"Location has coordinates: ({}, {}, {})",
borrow1.x, borrow2.y, location.z
);
let mut_borow = &mut location;
mut_borow.x = 10;
mut_borow.y = 23;
mut_borow.z = 29;
let borrow3 = &location;
}
#[derive(PartialEq, PartialOrd)]
struct Centimeters(f64);
#[derive(Debug)]
struct Inches(i32);
impl Inches {
fn to_centimeters(&self) -> Centimeters {
let &Inches(inches) = self;
Centimeters(inches as f64 * 2.54)
}
}
struct Seconds(i32);
fn deriveTest() {
let one_second = Seconds(1);
let foot = Inches(12);
println!("One foot equals: {:?}", foot);
let meter = Centimeters(100.0);
let cmp = if foot.to_centimeters() < meter {
"smaller"
} else {
"bigger"
};
println!("One foot is {} than one meter.", cmp);
}
struct Sheep {}
struct Cow {}
trait Animal {
fn noise(&self) -> &'static str;
}
impl Animal for Sheep {
fn noise(&self) -> &'static str {
"baaah"
}
}
impl Animal for Cow {
fn noise(&self) -> &'static str {
"moooooo"
}
}
fn random_animal(random_number: f64) -> Box<dyn Animal> {
if random_number < 0.5 {
Box::new(Sheep {})
} else {
Box::new(Cow {})
}
}
fn dyReturn() {
let random_number = 0.3444;
let animal = random_animal(random_number);
println!(
"You've randomly chosen an animal, and it says {}",
animal.noise()
);
}
use std::ops;
struct Foo;
struct Bar;
#[derive(Debug)]
struct FooBar;
#[derive(Debug)]
struct BarFoo;
impl ops::Add<Bar> for Foo {
type Output = FooBar;
fn add(self, _rhs: Bar) -> FooBar {
println!("> Foo.add(Bar) was called");
FooBar
}
}
impl ops::Add<Foo> for Bar {
type Output = BarFoo;
fn add(self, rhs: Foo) -> BarFoo {
println!("> Bar.add(Foo) was called");
BarFoo
}
}
fn operatorOverloading() {
println!("Foo + Bar = {:?}", Foo + Bar);
println!("Bar + Foo = {:?}", Bar + Foo);
}
struct Droppable {
name: &'static str,
}
impl Drop for Droppable {
fn drop(&mut self) {
println!("> Dropping {}", self.name);
}
}
fn dropping() {
let a = Droppable { name: "a" };
{
let b = Droppable { name: "b" };
{
let c = Droppable { name: "c" };
let d = Droppable { name: "d" };
println!("Exiting block B");
}
println!("Just exited block B");
println!("Exiting block A");
}
}
struct Fibonacci {
curr: u32,
next: u32,
}
impl Iterator for Fibonacci {
type Item = u32;
fn next(&mut self) -> Option<u32> {
let new_next = self.curr + self.next;
self.curr = self.next;
self.next = new_next;
Some(self.curr)
}
}
fn fibonacci() -> Fibonacci {
Fibonacci { curr: 0, next: 1 }
}
fn iterTest() {
let mut sequence = 0..3;
println!("Four consecutive `next` calls on 0..3");
println!("> {:?}", sequence.next());
println!("> {:?}", sequence.next());
println!("> {:?}", sequence.next());
println!("> {:?}", sequence.next());
for i in fibonacci().take(4) {
println!("> {}", i);
}
for i in fibonacci().skip(4).take(4) {
println!("> {}", i);
}
let array = [1u32, 3, 3, 7];
for i in array.iter() {
println!("> {}", i);
}
}
fn main() {
codewars::cw01::run();
// literals_operator();
//tuple_activity();
//arrays_slices();
// struct_test();
//test_enum();
//test_var_bind();
//casting();
//conversion();
//expression();
//flowControl();
// functions();
//functions2();
//functions3();
//higherOrder();
//generics();
//scoping();
//ownership();
//borrowing();
//mutability();
// aliasing();
//deriveTest();
//dyReturn();
// operatorOverloading();
// dropping();
iterTest();
}
| true |
aa0b76ef332a75c346c8ed6f3e857795f72241c0
|
Rust
|
niofis/raybench
|
/bench.rs
|
UTF-8
| 9,305 | 2.65625 | 3 |
[] |
no_license
|
#!/usr/bin/env run-cargo-script
//! Install cargo-script first:
//! cargo install cargo-script
//! cargo script bench.rs -- run c -m
//!
//! ```cargo
//! [dependencies]
//! time = "0.1"
//! clap = "2"
//! ```
extern crate clap;
extern crate time;
use clap::{App, AppSettings, Arg, SubCommand};
use std::fs::File;
use std::io::{BufWriter, Write};
use std::process::Command;
fn platform_details() -> (String, String) {
let output = Command::new("sh")
.arg("./os.sh")
.output()
.expect("failed to run");
let os = String::from_utf8_lossy(&output.stdout)
.to_string()
.replace("\n", "");
let output = Command::new("sh")
.arg("./cpu.sh")
.output()
.expect("failed to run");
let cpu = String::from_utf8_lossy(&output.stdout)
.to_string()
.replace("\n", "");
(os, cpu)
}
fn compile_run(name: &str, path: &str, ppm: &str) -> (String, String, f64, String) {
let output = Command::new("sh")
.arg(format!("{}/version.sh", path))
.output()
.expect("failed to run");
let version = String::from_utf8_lossy(&output.stdout)
.to_string()
.replace("\n", "");
println!("{} ({})\nCompiling...", &name, &version);
Command::new("sh")
.arg(format!("{}/compile.sh", path))
.spawn()
.expect("compilation did not succeed")
.wait()
.expect("wait");
println!("Running...");
let start = time::precise_time_s();
let output = Command::new("sh")
.arg(format!("{}/run.sh", path))
.output()
.expect("failed to run");
let end = time::precise_time_s();
let elapsed = end - start;
println!("Running time: {:.4}s", elapsed);
let ppm_string = String::from_utf8_lossy(&output.stdout);
let mut ppm_file = BufWriter::new(File::create(ppm).expect("error creating file"));
write!(ppm_file, "{}", &ppm_string).expect("write ppm");
(name.to_string(), version, elapsed, ppm_string.to_string())
}
fn simply_run(name: &str, path: &str, ppm: &str) -> (String, String, f64, String) {
let output = Command::new("sh")
.arg(format!("{}/version.sh", path))
.output()
.expect("failed to run");
let version = String::from_utf8_lossy(&output.stdout)
.to_string()
.replace("\n", "");
println!("{} ({})\nRunning...", &name, &version);
let start = time::precise_time_s();
let output = Command::new("sh")
.arg(format!("{}/run.sh", path))
.output()
.expect("failed to run");
let end = time::precise_time_s();
let elapsed = end - start;
println!("Running time: {:.4}s", elapsed);
let ppm_string = String::from_utf8_lossy(&output.stdout);
let mut ppm_file = BufWriter::new(File::create(ppm).expect("error creating file"));
write!(ppm_file, "{}", &ppm_string).expect("write ppm");
(name.to_string(), version, elapsed, ppm_string.to_string())
}
fn c_lang() -> (String, String, f64, String) {
compile_run("C", "./c", "./tmp/crb.ppm")
}
fn rust_lang() -> (String, String, f64, String) {
compile_run("Rust Alt", "./rust", "./tmp/rsrb_alt.ppm")
}
fn go_lang() -> (String, String, f64, String) {
compile_run("Go", "./go", "./tmp/gorb.ppm")
}
fn java_lang() -> (String, String, f64, String) {
compile_run("Java", "./java", "./tmp/javarb.ppm")
}
fn scala_lang() -> (String, String, f64, String) {
compile_run("Scala", "./scala", "./tmp/scalarb.ppm")
}
fn haxe_lang() -> (String, String, f64, String) {
simply_run("Haxe", "./haxe", "./tmp/haxerb.ppm")
}
fn factor_lang() -> (String, String, f64, String) {
simply_run("Factor", "./factor", "./tmp/factor.ppm")
}
fn js_lang() -> (String, String, f64, String) {
simply_run("Javascript", "./javascript", "./tmp/jsrb.ppm")
}
fn cs_lang() -> (String, String, f64, String) {
compile_run("C#", "./csharp", "./tmp/csrb.ppm")
}
fn nim_lang() -> (String, String, f64, String) {
compile_run("Nim", "./nim", "./tmp/nimrb.ppm")
}
fn wren_lang() -> (String, String, f64, String) {
simply_run("Wren", "./wren", "./tmp/wrenrb.ppm")
}
fn lisp_lang() -> (String, String, f64, String) {
compile_run("Lisp", "./lisp", "./tmp/lisprb.ppm")
}
fn lua_lang() -> (String, String, f64, String) {
simply_run("Lua", "./lua", "./tmp/luarb.ppm")
}
fn luajit_lang() -> (String, String, f64, String) {
simply_run("LuaJIT", "./luajit", "./tmp/luarbjit.ppm")
}
fn swift_lang() -> (String, String, f64, String) {
compile_run("Swift", "./swift", "./tmp/swrb.ppm")
}
fn zig_lang() -> (String, String, f64, String) {
compile_run("Zig", "./zig", "./tmp/zigrb.ppm")
}
fn wat_lang() -> (String, String, f64, String) {
compile_run("Webassembly", "./webassembly", "./tmp/wasmrt.ppm")
}
fn odin_lang() -> (String, String, f64, String) {
compile_run("Odin", "./odin", "./tmp/odinrb.ppm")
}
fn rescript_lang() -> (String, String, f64, String) {
compile_run("ReScript", "./rescript", "./tmp/rescript.ppm")
}
fn plain_results(results: Vec<(String, String, f64, String)>) {
let (os, cpu) = platform_details();
println!("{} ({})", os, cpu);
results.iter().for_each(|(name, version, elapsed, _)| {
println!("{:7} \t {:.4}s ({})", name, elapsed, version)
});
}
fn markdown_results(results: Vec<(String, String, f64, String)>) {
let (os, cpu) = platform_details();
println!("#### {} ({})", os, cpu);
println!("|Language|Running Time|Version|");
println!("|--------|----------------|-------|");
results.iter().for_each(|(name, version, elapsed, _)| {
println!("|{:7}|{:.4} (s)|{}|", name, elapsed, version)
});
}
fn main() {
let matches = App::new("raybench runner")
.version("0.1")
.author("Enrique <[email protected]>")
.about("Compiles runs and compares different raybench tests.\nAvailable implementations: c,rust,js,go,cs,nim,wren,lua,luajit,swift,haxe,java,scala,lisp,wasm,factor")
.subcommand(
SubCommand::with_name("run")
.about("runs and compares the implementations specified")
.arg(
Arg::with_name("implementations")
.required(true)
.help("one or multiple benchmarks separated by commas")
.takes_value(true),
)
.arg(
Arg::with_name("markdown")
.long("markdown")
.short("m")
.required(false)
.help("prints results in markdown format")
.takes_value(false),
),
)
.setting(AppSettings::ArgRequiredElseHelp)
.get_matches();
if let Some(matches) = matches.subcommand_matches("run") {
if let Some(langs) = matches.value_of("implementations") {
let mut results: Vec<(String, String, f64, String)> = langs
.split(",")
.filter_map(|lang_str| {
let lang = lang_str.trim();
if lang == "c" {
return Some(c_lang());
} else if lang == "rust" {
return Some(rust_lang());
} else if lang == "go" {
return Some(go_lang());
} else if lang == "haxe" {
return Some(haxe_lang());
} else if lang == "js" {
return Some(js_lang());
} else if lang == "java" {
return Some(java_lang());
} else if lang == "cs" {
return Some(cs_lang());
} else if lang == "nim" {
return Some(nim_lang());
} else if lang == "wren" {
return Some(wren_lang());
} else if lang == "lisp" {
return Some(lisp_lang());
} else if lang == "lua" {
return Some(lua_lang());
} else if lang == "luajit" {
return Some(luajit_lang());
} else if lang == "swift" {
return Some(swift_lang());
} else if lang == "scala" {
return Some(scala_lang());
} else if lang == "wasm" {
return Some(wat_lang());
} else if lang == "zig" {
return Some(zig_lang());
} else if lang == "odin" {
return Some(odin_lang());
} else if lang == "factor" {
return Some(factor_lang());
} else if lang == "rescript" {
return Some(rescript_lang());
} else {
return None;
}
})
.collect();
results.sort_by(|a, b| a.2.partial_cmp(&b.2).unwrap());
if matches.is_present("markdown") {
markdown_results(results);
} else {
plain_results(results);
}
}
}
}
| true |
f580fcaba6976d9fff1a9b74c84dfe076aae429f
|
Rust
|
tuxmark5/north
|
/north_core/src/util/dyn_traits.rs
|
UTF-8
| 2,104 | 3.109375 | 3 |
[] |
no_license
|
use {
std::{
any::Any,
cmp::PartialEq,
hash::{Hash, Hasher},
}
};
////////////////////////////////////////////////////////////////////////////////////////////////
pub struct Dyn<T: ?Sized>(pub T);
pub struct DynBox<T: ?Sized>(pub Box<T>);
/*impl<T: ?Sized> Borrow<Dyn<T>> for Box<Dyn<T>> {
fn borrow(&self) -> &Dyn<T> {
self.0
}
}*/
////////////////////////////////////////////////////////////////////////////////////////////////
pub trait EqDyn: PartialEqDyn { }
impl<T: Any + Eq> EqDyn for T { }
impl<T> Eq for Dyn<T> where
T: AsRef<dyn Any> + EqDyn + ?Sized { }
impl<T> Eq for DynBox<T> where
T: AsRef<dyn Any> + EqDyn + ?Sized { }
////////////////////////////////////////////////////////////////////////////////////////////////
pub trait HashDyn {
fn hash_dyn(&self, state: &mut dyn Hasher);
}
impl<T: Any + Hash> HashDyn for T {
fn hash_dyn(&self, mut state: &mut dyn Hasher) {
Hash::hash(self, &mut state);
}
}
impl<T> Hash for Dyn<T> where
T: HashDyn + ?Sized
{
fn hash<H: Hasher>(&self, state: &mut H) {
HashDyn::hash_dyn(&self.0, state);
}
}
impl<T> Hash for DynBox<T> where
T: HashDyn + ?Sized
{
fn hash<H: Hasher>(&self, state: &mut H) {
HashDyn::hash_dyn(&*self.0, state);
}
}
////////////////////////////////////////////////////////////////////////////////////////////////
pub trait PartialEqDyn {
fn eq_dyn(&self, other: &dyn Any) -> bool;
}
impl<T: Any + PartialEq> PartialEqDyn for T {
fn eq_dyn(&self, other: &dyn Any) -> bool {
match other.downcast_ref::<T>() {
Some(other) => self.eq(other),
None => false,
}
}
}
impl<T> PartialEq for Dyn<T> where
T: AsRef<dyn Any> + PartialEqDyn + ?Sized
{
fn eq(&self, other: &Dyn<T>) -> bool {
PartialEqDyn::eq_dyn(&self.0, (other.0).as_ref())
}
}
impl<T> PartialEq for DynBox<T> where
T: AsRef<dyn Any> + PartialEqDyn + ?Sized
{
fn eq(&self, other: &DynBox<T>) -> bool {
PartialEqDyn::eq_dyn(&*self.0, (*other.0).as_ref())
}
}
////////////////////////////////////////////////////////////////////////////////////////////////
| true |
b661504f70faba19eb5a7900cd14ae8d857cf190
|
Rust
|
littleroys/leetcode-rs
|
/src/algebra/k_closest_point.rs
|
UTF-8
| 610 | 3.234375 | 3 |
[] |
no_license
|
// 973 find k-th close points
struct Solution;
impl Solution {
pub fn k_closest(points: Vec<Vec<i32>>, k: i32) -> Vec<Vec<i32>> {
let mut points: Vec<Vec<i32>> = points;
points.sort_by(|a, b| (a[0].pow(2) + a[1].pow(2)).cmp(&(b[0].pow(2) + b[1].pow(2))));
points.drain(..k as usize).collect()
}
}
#[cfg(test)]
mod test {
use crate::algebra::k_closest_point::Solution;
#[test]
pub fn test_k_closest() {
assert_eq!(
Solution::k_closest(vec![vec![3, 3], vec![5, -1], vec![-2, 4]], 2),
vec![vec![3, 3], vec![-2, 4]]
)
}
}
| true |
bbec31ad78e4ccddba1899a36f10eba12860d89b
|
Rust
|
foleyj2/rust-examples
|
/rust-book/09-error_handling/src/main.rs
|
UTF-8
| 3,466 | 3.234375 | 3 |
[
"MIT"
] |
permissive
|
// Example code from Rust Book Chapter 9
// https://doc.rust-lang.org/book/ch09-00-error-handling.html
use std::error::Error;
use std::fs;
use std::fs::File;
use std::io;
use std::io::ErrorKind;
use std::io::Read;
fn main() {
//println!("Hello, world!");
println!("Error handling examples");
//panic_basic()
//panic_backtrace();
//result_file();
//result_file_match();
//result_file_unwrap();
result_file_unwrap_shortcut();
}
fn panic_basic() {
//panic!("crash and burn");
}
fn panic_backtrace() {
let v = vec![1, 2, 3];
v[99]; // invalid index! Oh no!
// export RUST_BACKTRACE=1 to get a full stack trace
// or just simply "RUST_BACKTRACE=1 cargo run"
}
fn result_file() {
let f = File::open("hello.txt");
// Standard library docs
// to discover it returns a Result
// https://doc.rust-lang.org/std/index.html
//let f: u32 = File::open("hello.txt"); //Wrong type, but guessing
// // look at the compiler error for hints
}
fn result_file_match() {
let f = File::open("hello.txt");
let f = match f {
Ok(file) => file,
Err(error) => panic!("Problem opening the file: {:?}", error),
};
}
fn result_file_match2() {
fn main() {
let f = File::open("hello.txt");
let f = match f {
Ok(file) => file,
Err(error) => match error.kind() {
ErrorKind::NotFound => match File::create("hello.txt") {
Ok(fc) => fc,
Err(e) => panic!("Problem creating the file: {:?}", e),
},
other_error => panic!("Problem opening the file: {:?}", other_error),
},
};
}
}
fn result_file_unwrap() {
let f = File::open("hello.txt").unwrap_or_else(|error| {
if error.kind() == ErrorKind::NotFound {
File::create("hello.txt").unwrap_or_else(|error| {
panic!("Problem creating the file: {:?}", error);
})
} else {
panic!("Problem opening the file: {:?}", error);
}
});
}
fn result_file_unwrap_shortcut() {
//let f = File::open("hello.txt").unwrap();
// get value or panic generically!
let f = File::open("hello.txt").expect("Failed to open hello.txt");
// get value or panic with helpful message. Better!
}
fn result_propogate_error() {}
fn read_username_from_file() -> Result<String, io::Error> {
let f = File::open("hello.txt");
let mut f = match f {
Ok(file) => file,
Err(e) => return Err(e),
};
let mut s = String::new();
match f.read_to_string(&mut s) {
Ok(_) => Ok(s),
Err(e) => Err(e),
}
}
fn read_username_from_file_shorter() -> Result<String, io::Error> {
let mut f = File::open("hello.txt")?;
let mut s = String::new();
f.read_to_string(&mut s)?;
Ok(s)
}
fn read_username_from_file_even_shorter() -> Result<String, io::Error> {
let mut s = String::new();
File::open("hello.txt")?.read_to_string(&mut s)?;
Ok(s)
}
fn read_username_from_file_shortest() -> Result<String, io::Error> {
fs::read_to_string("hello.txt")
}
//fn result_return_questionmark_() {
// let f = File::open("hello.txt")?; //oops! only allowed to use ? if we handle the Result or Option
//}
fn result_return_questionmark() -> Result<(), Box<dyn Error>> {
// Uhhh, what is a Box?
let f = File::open("hello.txt")?;
Ok(())
}
| true |
7d71d08a4e8c04b0208c0b4a463da3855d26f0ea
|
Rust
|
ergoplatform/sigma-rust
|
/ergotree-interpreter/src/eval/coll_by_index.rs
|
UTF-8
| 2,659 | 2.765625 | 3 |
[
"CC0-1.0"
] |
permissive
|
use ergotree_ir::mir::coll_by_index::ByIndex;
use ergotree_ir::mir::constant::TryExtractInto;
use ergotree_ir::mir::value::Value;
use crate::eval::env::Env;
use crate::eval::EvalContext;
use crate::eval::EvalError;
use crate::eval::Evaluable;
impl Evaluable for ByIndex {
fn eval(&self, env: &Env, ctx: &mut EvalContext) -> Result<Value, EvalError> {
let input_v = self.input.eval(env, ctx)?;
let index_v = self.index.eval(env, ctx)?;
let normalized_input_vals: Vec<Value> = match input_v {
Value::Coll(coll) => Ok(coll.as_vec()),
_ => Err(EvalError::UnexpectedValue(format!(
"ByIndex: expected input to be Value::Coll, got: {0:?}",
input_v
))),
}?;
match self.default.clone() {
Some(default) => {
let default_v = default.eval(env, ctx)?;
Ok(normalized_input_vals
.get(index_v.try_extract_into::<i32>()? as usize)
.cloned()
.unwrap_or(default_v))
}
None => normalized_input_vals
.get(index_v.clone().try_extract_into::<i32>()? as usize)
.cloned()
.ok_or_else(|| {
EvalError::Misc(format!(
"ByIndex: index {0:?} out of bounds for collection size {1:?}",
index_v,
normalized_input_vals.len()
))
}),
}
}
}
#[allow(clippy::unwrap_used)]
#[cfg(test)]
mod tests {
use ergotree_ir::chain::ergo_box::ErgoBox;
use ergotree_ir::mir::expr::Expr;
use ergotree_ir::mir::global_vars::GlobalVars;
use sigma_test_util::force_any_val;
use super::*;
use crate::eval::context::Context;
use crate::eval::tests::eval_out;
use crate::eval::tests::eval_out_wo_ctx;
use std::rc::Rc;
use std::sync::Arc;
#[test]
fn eval() {
let expr: Expr = ByIndex::new(GlobalVars::Outputs.into(), Expr::Const(0i32.into()), None)
.unwrap()
.into();
let ctx = Rc::new(force_any_val::<Context>());
assert_eq!(
eval_out::<Arc<ErgoBox>>(&expr, ctx.clone()).box_id(),
ctx.outputs.get(0).unwrap().box_id()
);
}
#[test]
fn eval_with_default() {
let expr: Expr = ByIndex::new(
Expr::Const(vec![1i64, 2i64].into()),
Expr::Const(3i32.into()),
Some(Box::new(Expr::Const(5i64.into()))),
)
.unwrap()
.into();
assert_eq!(eval_out_wo_ctx::<i64>(&expr), 5);
}
}
| true |
0bec9b5a17a6d086813910bf7c112c7b09796698
|
Rust
|
maniflames/insync
|
/src/system/input.rs
|
UTF-8
| 1,543 | 2.765625 | 3 |
[] |
no_license
|
use recs::{EntityId, component_filter};
use crate::*;
pub fn run(mut window: &mut three::Window, mut store: &mut Ecs) {
let component_filter = component_filter!(Position, GameObject);
let mut entities: Vec<EntityId> = Vec::new();
store.collect_with(&component_filter, &mut entities);
for entity in entities {
let gameobject = store.get::<GameObject>(entity).unwrap();
if gameobject.object_type == GameObjectType::Player {
let position = store.get::<Position>(entity).unwrap();
let space_button = three::Button::from(three::controls::Button::Key(three::controls::Key::Space));
if window.input.hit(three::Key::Space) && window.input.hit_count(space_button) == 1 {
factory::create_bullet(&mut window, &mut store, position);
};
let mut new_position = position.clone();
if window.input.hit(three::Key::W) {
new_position.y = new_position.y + gameobject.velocity;
}
if window.input.hit(three::Key::S) {
new_position.y = new_position.y - gameobject.velocity;
}
if window.input.hit(three::Key::A) {
new_position.x = new_position.x - gameobject.velocity;
}
if window.input.hit(three::Key::D) {
new_position.x = new_position.x + gameobject.velocity;
}
let _ = store.set::<Position>(entity, new_position).unwrap();
}
}
}
| true |
a860f5df10ef528689f2b5ab1ad92d97fbeed390
|
Rust
|
Voxelot/transaction-processor
|
/src/domain/engine/tests/deposit.rs
|
UTF-8
| 2,639 | 2.65625 | 3 |
[] |
no_license
|
use crate::domain::engine::tests::test_helpers::{
TestContext, TEST_CLIENT_ID, TEST_TRANSACTION_ID_1,
};
use crate::domain::model::{AmountInMinorUnits, Deposit, Transaction};
use crate::domain::ports::Engine;
#[tokio::test]
async fn deposit_increases_client_available_funds_by_deposit_amount() {
// test setup
let mut ctx = TestContext::new();
// test subject
ctx.engine
.process_transaction(Transaction::Deposit(Deposit {
client: TEST_CLIENT_ID,
tx: TEST_TRANSACTION_ID_1,
amount: AmountInMinorUnits::from(5),
}))
.await
.unwrap();
// check results
let clients = ctx.get_clients().await;
assert_eq!(clients[0].available, AmountInMinorUnits::from(5));
}
#[tokio::test]
async fn deposit_increases_client_total_funds_by_deposit_amount() {
// test setup
let mut ctx = TestContext::new();
// test subject
ctx.engine
.process_transaction(Transaction::Deposit(Deposit {
client: TEST_CLIENT_ID,
tx: TEST_TRANSACTION_ID_1,
amount: AmountInMinorUnits::from(5),
}))
.await
.unwrap();
// check results
let clients = ctx.get_clients().await;
assert_eq!(clients[0].total, AmountInMinorUnits::from(5));
}
#[tokio::test]
async fn deposit_does_not_increase_available_funds_if_already_processed() {
// test setup
let deposit_amount = AmountInMinorUnits::from(100);
let mut ctx = TestContext::new();
ctx.with_deposit(deposit_amount.clone(), AmountInMinorUnits::from(0))
.await;
// test subject
ctx.engine
.process_transaction(Transaction::Deposit(Deposit {
client: TEST_CLIENT_ID,
tx: TEST_TRANSACTION_ID_1,
amount: deposit_amount.clone(),
}))
.await
.unwrap();
// check results
let clients = ctx.get_clients().await;
assert_eq!(clients[0].available, deposit_amount);
}
#[tokio::test]
async fn deposit_does_not_increase_total_funds_if_already_processed() {
// test setup
let deposit_amount = AmountInMinorUnits::from(100);
let mut ctx = TestContext::new();
ctx.with_deposit(deposit_amount.clone(), AmountInMinorUnits::from(0))
.await;
// test subject
ctx.engine
.process_transaction(Transaction::Deposit(Deposit {
client: TEST_CLIENT_ID,
tx: TEST_TRANSACTION_ID_1,
amount: deposit_amount.clone(),
}))
.await
.unwrap();
// check results
let clients = ctx.get_clients().await;
assert_eq!(clients[0].total, deposit_amount);
}
| true |
20b7e38db6761b3e788d12a60c15a18009bc1e97
|
Rust
|
szabo137/ptarmigan
|
/src/input/types.rs
|
UTF-8
| 3,730 | 3.328125 | 3 |
[
"Apache-2.0"
] |
permissive
|
//! YAML-readable types
use std::convert::TryFrom;
use yaml_rust::yaml::Yaml;
use meval::Context;
/// Types that can be parsed from a YML-formatted file
pub trait FromYaml: Sized {
type Error;
/// Attempt to parse the YML field as the specified type, using the supplied Context for named variables and constants.
fn from_yaml(arg: Yaml, ctx: &Context) -> Result<Self, Self::Error>;
}
// Atomic
impl FromYaml for bool {
type Error = ();
fn from_yaml(arg: Yaml, _ctx: &Context) -> Result<Self, Self::Error> {
match arg {
Yaml::Boolean(b) => Ok(b),
_ => Err(())
}
}
}
impl FromYaml for String {
type Error = ();
fn from_yaml(arg: Yaml, _ctx: &Context) -> Result<Self, Self::Error> {
match arg {
Yaml::String(s) => Ok(s.clone()),
Yaml::Integer(i) => Ok(i.to_string()),
Yaml::Real(s) => Ok(s.clone()),
Yaml::Boolean(b) => Ok(b.to_string()),
_ => Err(())
}
}
}
// Numbers: f64, i64, usize
impl FromYaml for f64 {
type Error = ();
fn from_yaml(arg: Yaml, ctx: &Context) -> Result<Self, Self::Error> {
match arg {
Yaml::Real(s) => {
s.parse::<f64>().or(Err(()))
},
Yaml::Integer(i) => {
Ok(i as f64)
},
Yaml::String(s) => {
s.parse::<meval::Expr>()
.and_then(|expr| expr.eval_with_context(ctx))
.or(Err(()))
}
_ => Err(())
}
}
}
impl FromYaml for i64 {
type Error = ();
fn from_yaml(arg: Yaml, _ctx: &Context) -> Result<Self, Self::Error> {
match arg {
Yaml::Integer(i) => Ok(i),
_ => Err(())
}
}
}
impl FromYaml for usize {
type Error = ();
fn from_yaml(arg: Yaml, ctx: &Context) -> Result<Self, Self::Error> {
let i: i64 = FromYaml::from_yaml(arg, ctx)?;
usize::try_from(i).map_err(|_| ())
}
}
// Vecs
impl FromYaml for Vec<String> {
type Error = ();
fn from_yaml(arg: Yaml, _ctx: &Context) -> Result<Self, Self::Error> {
match arg {
// turn a single String into a vec of length 1.
Yaml::String(s) | Yaml::Real(s) => {
Ok(vec![s.clone()])
},
Yaml::Integer(i) => {
Ok(vec![i.to_string()])
},
Yaml::Boolean(b) => {
Ok(vec![b.to_string()])
},
Yaml::Array(array) => {
// a is a vec of Vec<Yaml>
let take_yaml_string = |y: &Yaml| -> Option<String> {
match y {
Yaml::String(s) | Yaml::Real(s) => Some(s.clone()),
Yaml::Integer(i) => Some(i.to_string()),
Yaml::Boolean(b) => Some(b.to_string()),
_ => None
}
};
let got: Vec<String> = array.iter().filter_map(take_yaml_string).collect();
if got.is_empty() {
Err(())
} else {
Ok(got)
}
},
_ => Err(())
}
}
}
impl FromYaml for Vec<f64> {
type Error = ();
fn from_yaml(arg: Yaml, ctx: &Context) -> Result<Self, Self::Error> {
let strs: Vec<String> = FromYaml::from_yaml(arg, ctx)?;
let v: Result<Vec<f64>, _> = strs.iter()
.map(|s| {
s.parse::<meval::Expr>()
.and_then(|expr| expr.eval_with_context(ctx))
.or(Err(()))
})
.collect();
v
}
}
| true |
2b07db33421424d36cd37d9a97ba2bc4d4ca0015
|
Rust
|
MatusT/master-thesis
|
/lod_creator/src/main.rs
|
UTF-8
| 4,843 | 2.609375 | 3 |
[
"MIT"
] |
permissive
|
use kmeans;
use nalgebra_glm::*;
use rpdb::{molecule::Molecule, molecule::MoleculeLod, FromRon, ToRon};
fn sphere_sreen_space_area(projection: Mat4, dimensions: Vec2, center: Vec3, radius: f32) -> f32 {
let d2 = dot(¢er, ¢er);
let a = (d2 - radius * radius).sqrt();
// view-aligned "right" vector (right angle to the view plane from the center of the sphere. Since "up" is always (0,n,0), replaced cross product with vec3(-c.z, 0, c.x)
let right = (radius / a) * vec3(-center.z, 0.0, center.x);
let up = vec3(0.0, radius, 0.0);
let projected_right = projection * vec4(right.x, right.y, right.z, 0.0);
let projected_up = projection * vec4(up.x, up.y, up.z, 0.0);
let projected_center = projection * vec4(center.x, center.y, center.z, 1.0);
let mut north = projected_center + projected_up;
let mut east = projected_center + projected_right;
let mut south = projected_center - projected_up;
let mut west = projected_center - projected_right;
north /= north.w;
east /= east.w;
west /= west.w;
south /= south.w;
let north = vec2(north.x, north.y);
let east = vec2(east.x, east.y);
let west = vec2(west.x, west.y);
let south = vec2(south.x, south.y);
let box_min = min2(&min2(&min2(&east, &west), &north), &south);
let box_max = max2(&max2(&max2(&east, &west), &north), &south);
let box_min = box_min * 0.5 + vec2(0.5, 0.5);
let box_max = box_max * 0.5 + vec2(0.5, 0.5);
let area = box_max - box_min;
let area = area.component_mul(&dimensions);
let area = area.x * area.y;
area
}
fn main() {
// Load existing molecule
let args: Vec<String> = std::env::args().collect();
let mut molecule = Molecule::from_ron(&args[1]);
// Create new LODs
let mut lods = Vec::new();
lods.push(molecule.lods()[0].clone());
// Constants
let width = 1920.0;
let height = 1080.0;
let aspect = width / height;
let projection = infinite_perspective_rh_no(aspect, 0.785398163, 0.1);
let ratios = [0.9, 0.75, 0.5, 0.25, 0.1,
0.075, 0.05, 0.025, 0.01,
0.005, 0.001, 0.0005, 0.0001
];
let area_threshold = 32.0;
// Current largest radius that is being projected
let mut radius = lods.last().unwrap().max_radius();
let mut z = radius * 2.0;
// Iteratively zoom out
let mut current_ratio_index = 0;
'main: loop {
z += 1.0;
if current_ratio_index >= ratios.len() - 1 {
break 'main;
}
let view = look_at(
&vec3(0.0, 0.0, z as f32),
&vec3(0.0, 0.0, 0.0),
&vec3(0.0, 1.0, 0.0),
);
let position = view * vec4(0.0, 0.0, 0.0, 1.0);
let area = sphere_sreen_space_area(projection, vec2(width, height), position.xyz(), radius);
if !area.is_finite() {
continue;
}
// Breakpoint at area limit
// Currently 64 = 8x8 pixel area
if area < area_threshold {
// println!("{:?}", area);
println!("Distance: {}", z);
// Continue along the reduction ratios
for reduction_ratio in current_ratio_index..ratios.len() {
let mut new_centroids_num = (lods[0].atoms().len() as f32 * ratios[reduction_ratio]) as usize;
// End if It is not possible to reduce further
if lods.last().unwrap().atoms().len() == 1 {
break 'main;
}
if new_centroids_num < 1 {
new_centroids_num = 1;
}
let new_means = kmeans::reduce(
lods[0].atoms(),
new_centroids_num,
);
if new_means.len() == 0 {
continue;
}
let mut new_lod = MoleculeLod::new(new_means, 0.0);
let new_area = sphere_sreen_space_area(projection, vec2(width, height), position.xyz(), new_lod.max_radius());
println!("Current ratio: {}. New centroids: {}. New means real len: {}. New area: {}", ratios[reduction_ratio], new_centroids_num, new_lod.atoms().len(), new_area);
// If the new are is now above the area limit, save It and continue
if new_area > area_threshold || reduction_ratio == ratios.len() - 1{
radius = new_lod.max_radius();
new_lod.set_breakpoint(z);
lods.push(new_lod);
current_ratio_index = reduction_ratio + 1;
break;
}
}
}
}
molecule.lods = lods;
molecule.to_ron(&args[1]);
}
| true |
9f937835b35be26abab8b9e28ff2825af1d39dc8
|
Rust
|
john-terrell/mantle
|
/src/scenegraph/geometry/vector.rs
|
UTF-8
| 1,747 | 3.8125 | 4 |
[] |
no_license
|
#[derive(Copy, Clone)]
pub struct Vector {
pub x: f64,
pub y: f64,
pub z: f64,
}
impl Vector {
pub fn add(lhs: Vector, rhs: Vector) -> Vector {
return Vector{
x: lhs.x + rhs.x,
y: lhs.y + rhs.y,
z: lhs.z + rhs.z,
}
}
pub fn subtract(lhs: Vector, rhs: Vector) -> Vector {
return Vector{
x: lhs.x - rhs.x,
y: lhs.y - rhs.y,
z: lhs.z - rhs.z,
}
}
pub fn dot_product(lhs: Vector, rhs: Vector) -> f64 {
return (lhs.x * rhs.x) + (lhs.y * rhs.y) + (lhs.z * rhs.z);
}
pub fn squared_magnitude(&self) -> f64 {
return (self.x * self.x) + (self.y * self.y) + (self.z * self.z);
}
pub fn magnitude(&self) -> f64 {
return self.squared_magnitude().sqrt();
}
pub fn inverse(&self) -> Vector {
return Vector{x: -self.x, y: -self.y, z: -self.z};
}
pub fn normalized(&self) -> Vector {
let scale = 1.0 / self.magnitude();
return Vector{
x: self.x * scale,
y: self.y * scale,
z: self.z * scale,
}
}
pub fn of_magnitude(&self, magnitude: f64) -> Vector {
let scale = magnitude / self.magnitude();
return Vector{
x: self.x * scale,
y: self.y * scale,
z: self.z * scale,
}
}
pub fn set_length(&mut self, length: f64) {
let mag = self.magnitude();
let scaler = length / mag;
self.x /= scaler;
self.y /= scaler;
self.z /= scaler;
}
pub fn normalize(&mut self) {
let mag = self.magnitude();
self.x /= mag;
self.y /= mag;
self.z /= mag;
}
}
| true |
19e94d93bff2fa263843f1ca2828617fe75a8ea8
|
Rust
|
Orange-OpenSource/hurl
|
/packages/hurl/src/report/tap/testcase.rs
|
UTF-8
| 2,924 | 3.015625 | 3 |
[
"Apache-2.0"
] |
permissive
|
/*
* Hurl (https://hurl.dev)
* Copyright (C) 2023 Orange
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
use crate::report::Error;
use crate::runner::HurlResult;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Testcase {
pub(crate) description: String,
pub(crate) success: bool,
}
impl Testcase {
/// Creates an Tap <testcase> from an [`HurlResult`].
pub fn from(hurl_result: &HurlResult, filename: &str) -> Testcase {
let description = filename.to_string();
let success = hurl_result.errors().is_empty();
Testcase {
description,
success,
}
}
/// Creates an Tap <testcase> from a TAP line
/// ok 1 - this is the first test
/// nok 2 - this is the second test
pub(crate) fn parse(line: &str) -> Result<Testcase, Error> {
let mut line = line;
let success = if line.starts_with("ok") {
line = &line[2..];
true
} else if line.starts_with("nok") {
line = &line[3..];
false
} else {
return Err(Error {
message: format!("Invalid TAP line <{line}> - must start with ok or nok"),
});
};
let description = match line.find('-') {
None => {
return Err(Error {
message: format!("Invalid TAP line <{line}> - missing '-' separator"),
})
}
Some(index) => {
if line.split_at(index).0.trim().parse::<usize>().is_err() {
return Err(Error {
message: format!("Invalid TAP line <{line}> - missing test number"),
});
}
line.split_at(index).1[1..].trim().to_string()
}
};
Ok(Testcase {
description,
success,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_tap_test_line() {
assert_eq!(
Testcase::parse("toto").err().unwrap().message,
"Invalid TAP line <toto> - must start with ok or nok".to_string()
);
assert_eq!(
Testcase::parse("ok 1 - tests_ok/test.1.hurl").unwrap(),
Testcase {
description: "tests_ok/test.1.hurl".to_string(),
success: true
}
);
}
}
| true |
7d7e4578d0262954e55e3e26b6b12dee809be981
|
Rust
|
andygrove/hmc5883l-rs
|
/src/lib.rs
|
UTF-8
| 1,516 | 2.953125 | 3 |
[] |
no_license
|
use std::f32;
use std::thread;
use std::time::Duration;
extern crate i2cdev;
use self::i2cdev::core::*;
use self::i2cdev::linux::{LinuxI2CDevice, LinuxI2CError};
pub struct HMC5883L {
dev: Box<LinuxI2CDevice>
}
impl HMC5883L {
pub fn new(filename: &'static str, address: u16) -> Result<Self, Box<LinuxI2CError>> {
let mut dev = try!(LinuxI2CDevice::new(filename, address));
// set gain to +/1 1.3 Gauss
try!(dev.smbus_write_byte_data(0x01, 0x20));
// set in continuous-measurement mode
try!(dev.smbus_write_byte_data(0x02, 0x00));
// delay before taking first reading
thread::sleep(Duration::from_millis(100));
Ok(HMC5883L { dev: Box::new(dev) })
}
pub fn read(&mut self) -> Result<(f32, f32, f32), Box<LinuxI2CError>> {
// read two bytes each from registers 03 through 05 (x, z, y)
let mut buf: [u8; 6] = [0; 6];
try!(self.dev.read(&mut buf));
// start reading from register 03 (x value)
try!(self.dev.smbus_write_byte(0x03));
thread::sleep(Duration::from_millis(100));
// parse the data in the correct order - x, z, y (NOT x, y, z as you would expect)
let x : i16 = ((buf[0] as i16) << 8) as i16 | buf[1] as i16;
let z : i16 = ((buf[2] as i16) << 8) as i16 | buf[3] as i16;
let y : i16 = ((buf[4] as i16) << 8) as i16 | buf[5] as i16;
// return tuple containing x, y, z values
Ok((x as f32, y as f32, z as f32))
}
}
| true |
81ca867a8b731d222254db6158028680ffa0d4f7
|
Rust
|
rodya-mirov/palladium
|
/main/src/systems/update/breathe.rs
|
UTF-8
| 3,623 | 2.859375 | 3 |
[
"Apache-2.0"
] |
permissive
|
use super::*;
use std::collections::HashMap;
use components::{Breathes, CanSuffocate, HasPosition, OxygenContainer};
use resources::{Callbacks, NpcMoves};
fn safe_subtract(start: usize, subtraction: usize) -> usize {
if start > subtraction {
start - subtraction
} else {
0
}
}
fn add_and_cap(start: usize, add: usize, cap: usize) -> usize {
std::cmp::min(cap, start + add)
}
#[derive(SystemData)]
pub struct BreathSystemData<'a> {
has_pos: ReadStorage<'a, HasPosition>,
oxygen_cont: WriteStorage<'a, OxygenContainer>,
breathes: WriteStorage<'a, Breathes>,
can_suffocate: ReadStorage<'a, CanSuffocate>,
entities: Entities<'a>,
npc_moves: Read<'a, NpcMoves>,
callbacks: Write<'a, Callbacks>,
}
pub struct BreatheSystem;
impl<'a> System<'a> for BreatheSystem {
type SystemData = BreathSystemData<'a>;
fn run(&mut self, mut data: Self::SystemData) {
if !data.npc_moves.move_was_made {
return;
}
// first build the amount of oxygen available at all places
let mut oxygen_map: HashMap<TilePos, usize> = HashMap::new();
for (hp, oc) in (&data.has_pos, &data.oxygen_cont).join() {
*oxygen_map.entry(hp.position).or_insert(0) += oc.contents;
}
// then look through all the breathers and see what happens to them
for (breathe, hp, entity) in (&mut data.breathes, &data.has_pos, &data.entities).join() {
let oxygen_here = oxygen_map.get(&hp.position).copied().unwrap_or(0);
if oxygen_here >= breathe.fast_gain_threshold {
add_oxygen(breathe, constants::oxygen::FAST_GAIN_SPEED);
} else if oxygen_here >= breathe.slow_gain_threshold {
add_oxygen(breathe, constants::oxygen::SLOW_GAIN_SPEED);
} else if oxygen_here >= breathe.slow_drop_threshold {
lose_oxygen(breathe, constants::oxygen::SLOW_DROP_SPEED);
if breathe.contents == 0 {
if let Some(cs) = data.can_suffocate.get(entity) {
process_suffocate(entity, cs, &mut data.callbacks, &data.entities);
}
}
} else {
lose_oxygen(breathe, constants::oxygen::FAST_DROP_SPEED);
if breathe.contents == 0 {
if let Some(cs) = data.can_suffocate.get(entity) {
process_suffocate(entity, cs, &mut data.callbacks, &data.entities);
}
}
}
}
}
}
fn add_oxygen(breathe: &mut Breathes, addition: usize) {
breathe.contents = add_and_cap(breathe.contents, addition, breathe.capacity);
}
fn lose_oxygen(breathe: &mut Breathes, loss: usize) {
breathe.contents = safe_subtract(breathe.contents, loss);
}
fn process_suffocate(entity: Entity, cs: &CanSuffocate, callbacks: &mut Callbacks, entities: &Entities) {
use resources::Callback;
match cs {
CanSuffocate::Player => {
let builder = dialogue_helpers::DialogueBuilder::new(
"You have been without air for too long.\n\nThis life is over, but the tether pulls you back.",
)
.with_option("[Continue]", vec![Callback::EndDialogue, Callback::LoadGame]);
dialogue_helpers::launch_dialogue(builder, callbacks);
}
CanSuffocate::Death => {
// thing dies, uh, delete it
// TODO: do something more interesting here?
entities.delete(entity).expect("Entity should be live, since it just came up");
}
}
}
| true |
7fe0ac8efd60a45b1692c2aa421ff350433286bc
|
Rust
|
standard-ai/hedwig-rust
|
/src/topic.rs
|
UTF-8
| 509 | 3 | 3 |
[
"Apache-2.0"
] |
permissive
|
/// A message queue topic name to which messages can be published
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub struct Topic(&'static str);
impl std::fmt::Display for Topic {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
std::fmt::Display::fmt(self.0, f)
}
}
impl From<&'static str> for Topic {
fn from(s: &'static str) -> Topic {
Topic(s)
}
}
impl AsRef<str> for Topic {
fn as_ref(&self) -> &str {
self.0
}
}
| true |
878f5a400b280ca03072fe1fee4f8c30acac14dc
|
Rust
|
Rodrigodd/gameroy
|
/src/rom_loading/wasm.rs
|
UTF-8
| 3,410 | 2.515625 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"MIT",
"Apache-2.0"
] |
permissive
|
use std::borrow::Cow;
use gameroy::gameboy::cartridge::CartridgeHeader;
use wasm_bindgen::{closure::Closure, JsCast, JsValue};
pub fn load_roms(_roms_path: &str) -> Result<Vec<RomFile>, String> {
Ok(Vec::new())
}
pub fn load_boot_rom() -> Option<[u8; 256]> {
None
}
pub fn load_file(file_name: &str) -> Result<Vec<u8>, String> {
let window = web_sys::window().ok_or_else(|| "window object is null".to_string())?;
let local_storage = window
.local_storage()
.map_err(|_| "error getting local storage".to_string())?
.ok_or_else(|| "local storage is null".to_string())?;
let save = local_storage
.get_item(file_name)
.map_err(|_| "error getting item from local storage".to_string())?
.ok_or_else(|| "save not found".to_string())?;
base64::decode(save).map_err(|err| format!("failed decoding save: {}", err.to_string()))
}
pub fn save_file(file_name: &str, data: &[u8]) -> Result<(), String> {
let window = web_sys::window().ok_or_else(|| "window object is null".to_string())?;
let local_storage = window
.local_storage()
.map_err(|_| "error getting local storage".to_string())?
.ok_or_else(|| "local storage is null".to_string())?;
let save = base64::encode(data);
local_storage
.set_item(file_name, &save)
.map_err(|_| "error setting item in local storage".to_string())?;
Ok(())
}
#[derive(Clone, Debug)]
pub struct RomFile {
web_file: web_sys::File,
}
impl RomFile {
pub fn file_name(&self) -> Cow<str> {
self.web_file.name().into()
}
pub async fn read(&self) -> Result<Vec<u8>, String> {
let promise = js_sys::Promise::new(&mut move |res, _rej| {
let file_reader = web_sys::FileReader::new().unwrap();
let fr = file_reader.clone();
let closure = Closure::wrap(Box::new(move || {
res.call1(&JsValue::undefined(), &fr.result().unwrap())
.unwrap();
}) as Box<dyn FnMut()>);
file_reader.set_onload(Some(closure.as_ref().unchecked_ref()));
closure.forget();
file_reader.read_as_array_buffer(&self.web_file).unwrap();
});
let future = wasm_bindgen_futures::JsFuture::from(promise);
let res = future.await.unwrap();
let buffer: js_sys::Uint8Array = js_sys::Uint8Array::new(&res);
let mut vec = vec![0; buffer.length() as usize];
buffer.copy_to(&mut vec[..]);
Ok(vec)
}
pub fn save_ram_data(&self, data: &[u8]) -> Result<(), String> {
let file_name = self.file_name().to_string() + ".sav";
save_file(&file_name, data)
}
pub async fn load_ram_data(&self) -> Result<Vec<u8>, String> {
let file_name = self.file_name().to_string() + ".sav";
load_file(&file_name)
}
pub fn save_state(&self, state: &[u8]) -> Result<(), String> {
let file_name = self.file_name().to_string() + ".save_state";
save_file(&file_name, state)
}
pub fn load_state(&self) -> Result<Vec<u8>, String> {
let file_name = self.file_name().to_string() + ".save_state";
load_file(&file_name)
}
}
#[cfg(feature = "rfd")]
impl From<rfd::FileHandle> for RomFile {
fn from(handle: rfd::FileHandle) -> Self {
Self {
web_file: handle.inner().clone(),
}
}
}
| true |
6da1383d69284fb5246bae246f003487c127b4eb
|
Rust
|
marco-c/gecko-dev-wordified-and-comments-removed
|
/third_party/rust/nom/src/internal.rs
|
UTF-8
| 10,226 | 2.828125 | 3 |
[
"CC0-1.0",
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
use
self
:
:
Needed
:
:
*
;
use
crate
:
:
error
:
:
{
self
ErrorKind
}
;
use
crate
:
:
lib
:
:
std
:
:
fmt
;
use
core
:
:
num
:
:
NonZeroUsize
;
pub
type
IResult
<
I
O
E
=
error
:
:
Error
<
I
>
>
=
Result
<
(
I
O
)
Err
<
E
>
>
;
pub
trait
Finish
<
I
O
E
>
{
fn
finish
(
self
)
-
>
Result
<
(
I
O
)
E
>
;
}
impl
<
I
O
E
>
Finish
<
I
O
E
>
for
IResult
<
I
O
E
>
{
fn
finish
(
self
)
-
>
Result
<
(
I
O
)
E
>
{
match
self
{
Ok
(
res
)
=
>
Ok
(
res
)
Err
(
Err
:
:
Error
(
e
)
)
|
Err
(
Err
:
:
Failure
(
e
)
)
=
>
Err
(
e
)
Err
(
Err
:
:
Incomplete
(
_
)
)
=
>
{
panic
!
(
"
Cannot
call
finish
(
)
on
Err
(
Err
:
:
Incomplete
(
_
)
)
:
this
result
means
that
the
parser
does
not
have
enough
data
to
decide
you
should
gather
more
data
and
try
to
reapply
the
parser
instead
"
)
}
}
}
}
#
[
derive
(
Debug
PartialEq
Eq
Clone
Copy
)
]
#
[
cfg_attr
(
nightly
warn
(
rustdoc
:
:
missing_doc_code_examples
)
)
]
pub
enum
Needed
{
Unknown
Size
(
NonZeroUsize
)
}
impl
Needed
{
pub
fn
new
(
s
:
usize
)
-
>
Self
{
match
NonZeroUsize
:
:
new
(
s
)
{
Some
(
sz
)
=
>
Needed
:
:
Size
(
sz
)
None
=
>
Needed
:
:
Unknown
}
}
pub
fn
is_known
(
&
self
)
-
>
bool
{
*
self
!
=
Unknown
}
#
[
inline
]
pub
fn
map
<
F
:
Fn
(
NonZeroUsize
)
-
>
usize
>
(
self
f
:
F
)
-
>
Needed
{
match
self
{
Unknown
=
>
Unknown
Size
(
n
)
=
>
Needed
:
:
new
(
f
(
n
)
)
}
}
}
#
[
derive
(
Debug
Clone
PartialEq
)
]
#
[
cfg_attr
(
nightly
warn
(
rustdoc
:
:
missing_doc_code_examples
)
)
]
pub
enum
Err
<
E
>
{
Incomplete
(
Needed
)
Error
(
E
)
Failure
(
E
)
}
impl
<
E
>
Err
<
E
>
{
pub
fn
is_incomplete
(
&
self
)
-
>
bool
{
if
let
Err
:
:
Incomplete
(
_
)
=
self
{
true
}
else
{
false
}
}
pub
fn
map
<
E2
F
>
(
self
f
:
F
)
-
>
Err
<
E2
>
where
F
:
FnOnce
(
E
)
-
>
E2
{
match
self
{
Err
:
:
Incomplete
(
n
)
=
>
Err
:
:
Incomplete
(
n
)
Err
:
:
Failure
(
t
)
=
>
Err
:
:
Failure
(
f
(
t
)
)
Err
:
:
Error
(
t
)
=
>
Err
:
:
Error
(
f
(
t
)
)
}
}
pub
fn
convert
<
F
>
(
e
:
Err
<
F
>
)
-
>
Self
where
E
:
From
<
F
>
{
e
.
map
(
crate
:
:
lib
:
:
std
:
:
convert
:
:
Into
:
:
into
)
}
}
impl
<
T
>
Err
<
(
T
ErrorKind
)
>
{
pub
fn
map_input
<
U
F
>
(
self
f
:
F
)
-
>
Err
<
(
U
ErrorKind
)
>
where
F
:
FnOnce
(
T
)
-
>
U
{
match
self
{
Err
:
:
Incomplete
(
n
)
=
>
Err
:
:
Incomplete
(
n
)
Err
:
:
Failure
(
(
input
k
)
)
=
>
Err
:
:
Failure
(
(
f
(
input
)
k
)
)
Err
:
:
Error
(
(
input
k
)
)
=
>
Err
:
:
Error
(
(
f
(
input
)
k
)
)
}
}
}
impl
<
T
>
Err
<
error
:
:
Error
<
T
>
>
{
pub
fn
map_input
<
U
F
>
(
self
f
:
F
)
-
>
Err
<
error
:
:
Error
<
U
>
>
where
F
:
FnOnce
(
T
)
-
>
U
{
match
self
{
Err
:
:
Incomplete
(
n
)
=
>
Err
:
:
Incomplete
(
n
)
Err
:
:
Failure
(
error
:
:
Error
{
input
code
}
)
=
>
Err
:
:
Failure
(
error
:
:
Error
{
input
:
f
(
input
)
code
}
)
Err
:
:
Error
(
error
:
:
Error
{
input
code
}
)
=
>
Err
:
:
Error
(
error
:
:
Error
{
input
:
f
(
input
)
code
}
)
}
}
}
#
[
cfg
(
feature
=
"
alloc
"
)
]
use
crate
:
:
lib
:
:
std
:
:
{
borrow
:
:
ToOwned
string
:
:
String
vec
:
:
Vec
}
;
#
[
cfg
(
feature
=
"
alloc
"
)
]
impl
Err
<
(
&
[
u8
]
ErrorKind
)
>
{
#
[
cfg_attr
(
feature
=
"
docsrs
"
doc
(
cfg
(
feature
=
"
alloc
"
)
)
)
]
pub
fn
to_owned
(
self
)
-
>
Err
<
(
Vec
<
u8
>
ErrorKind
)
>
{
self
.
map_input
(
ToOwned
:
:
to_owned
)
}
}
#
[
cfg
(
feature
=
"
alloc
"
)
]
impl
Err
<
(
&
str
ErrorKind
)
>
{
#
[
cfg_attr
(
feature
=
"
docsrs
"
doc
(
cfg
(
feature
=
"
alloc
"
)
)
)
]
pub
fn
to_owned
(
self
)
-
>
Err
<
(
String
ErrorKind
)
>
{
self
.
map_input
(
ToOwned
:
:
to_owned
)
}
}
#
[
cfg
(
feature
=
"
alloc
"
)
]
impl
Err
<
error
:
:
Error
<
&
[
u8
]
>
>
{
#
[
cfg_attr
(
feature
=
"
docsrs
"
doc
(
cfg
(
feature
=
"
alloc
"
)
)
)
]
pub
fn
to_owned
(
self
)
-
>
Err
<
error
:
:
Error
<
Vec
<
u8
>
>
>
{
self
.
map_input
(
ToOwned
:
:
to_owned
)
}
}
#
[
cfg
(
feature
=
"
alloc
"
)
]
impl
Err
<
error
:
:
Error
<
&
str
>
>
{
#
[
cfg_attr
(
feature
=
"
docsrs
"
doc
(
cfg
(
feature
=
"
alloc
"
)
)
)
]
pub
fn
to_owned
(
self
)
-
>
Err
<
error
:
:
Error
<
String
>
>
{
self
.
map_input
(
ToOwned
:
:
to_owned
)
}
}
impl
<
E
:
Eq
>
Eq
for
Err
<
E
>
{
}
impl
<
E
>
fmt
:
:
Display
for
Err
<
E
>
where
E
:
fmt
:
:
Debug
{
fn
fmt
(
&
self
f
:
&
mut
fmt
:
:
Formatter
<
'
_
>
)
-
>
fmt
:
:
Result
{
match
self
{
Err
:
:
Incomplete
(
Needed
:
:
Size
(
u
)
)
=
>
write
!
(
f
"
Parsing
requires
{
}
bytes
/
chars
"
u
)
Err
:
:
Incomplete
(
Needed
:
:
Unknown
)
=
>
write
!
(
f
"
Parsing
requires
more
data
"
)
Err
:
:
Failure
(
c
)
=
>
write
!
(
f
"
Parsing
Failure
:
{
:
?
}
"
c
)
Err
:
:
Error
(
c
)
=
>
write
!
(
f
"
Parsing
Error
:
{
:
?
}
"
c
)
}
}
}
#
[
cfg
(
feature
=
"
std
"
)
]
use
std
:
:
error
:
:
Error
;
#
[
cfg
(
feature
=
"
std
"
)
]
impl
<
E
>
Error
for
Err
<
E
>
where
E
:
fmt
:
:
Debug
{
fn
source
(
&
self
)
-
>
Option
<
&
(
dyn
Error
+
'
static
)
>
{
None
}
}
pub
trait
Parser
<
I
O
E
>
{
fn
parse
(
&
mut
self
input
:
I
)
-
>
IResult
<
I
O
E
>
;
fn
map
<
G
O2
>
(
self
g
:
G
)
-
>
Map
<
Self
G
O
>
where
G
:
Fn
(
O
)
-
>
O2
Self
:
core
:
:
marker
:
:
Sized
{
Map
{
f
:
self
g
phantom
:
core
:
:
marker
:
:
PhantomData
}
}
fn
flat_map
<
G
H
O2
>
(
self
g
:
G
)
-
>
FlatMap
<
Self
G
O
>
where
G
:
FnMut
(
O
)
-
>
H
H
:
Parser
<
I
O2
E
>
Self
:
core
:
:
marker
:
:
Sized
{
FlatMap
{
f
:
self
g
phantom
:
core
:
:
marker
:
:
PhantomData
}
}
fn
and_then
<
G
O2
>
(
self
g
:
G
)
-
>
AndThen
<
Self
G
O
>
where
G
:
Parser
<
O
O2
E
>
Self
:
core
:
:
marker
:
:
Sized
{
AndThen
{
f
:
self
g
phantom
:
core
:
:
marker
:
:
PhantomData
}
}
fn
and
<
G
O2
>
(
self
g
:
G
)
-
>
And
<
Self
G
>
where
G
:
Parser
<
I
O2
E
>
Self
:
core
:
:
marker
:
:
Sized
{
And
{
f
:
self
g
}
}
fn
or
<
G
>
(
self
g
:
G
)
-
>
Or
<
Self
G
>
where
G
:
Parser
<
I
O
E
>
Self
:
core
:
:
marker
:
:
Sized
{
Or
{
f
:
self
g
}
}
fn
into
<
O2
:
From
<
O
>
E2
:
From
<
E
>
>
(
self
)
-
>
Into
<
Self
O
O2
E
E2
>
where
Self
:
core
:
:
marker
:
:
Sized
{
Into
{
f
:
self
phantom_out1
:
core
:
:
marker
:
:
PhantomData
phantom_err1
:
core
:
:
marker
:
:
PhantomData
phantom_out2
:
core
:
:
marker
:
:
PhantomData
phantom_err2
:
core
:
:
marker
:
:
PhantomData
}
}
}
impl
<
'
a
I
O
E
F
>
Parser
<
I
O
E
>
for
F
where
F
:
FnMut
(
I
)
-
>
IResult
<
I
O
E
>
+
'
a
{
fn
parse
(
&
mut
self
i
:
I
)
-
>
IResult
<
I
O
E
>
{
self
(
i
)
}
}
#
[
cfg
(
feature
=
"
alloc
"
)
]
use
alloc
:
:
boxed
:
:
Box
;
#
[
cfg
(
feature
=
"
alloc
"
)
]
impl
<
'
a
I
O
E
>
Parser
<
I
O
E
>
for
Box
<
dyn
Parser
<
I
O
E
>
+
'
a
>
{
fn
parse
(
&
mut
self
input
:
I
)
-
>
IResult
<
I
O
E
>
{
(
*
*
self
)
.
parse
(
input
)
}
}
#
[
cfg_attr
(
nightly
warn
(
rustdoc
:
:
missing_doc_code_examples
)
)
]
pub
struct
Map
<
F
G
O1
>
{
f
:
F
g
:
G
phantom
:
core
:
:
marker
:
:
PhantomData
<
O1
>
}
impl
<
'
a
I
O1
O2
E
F
:
Parser
<
I
O1
E
>
G
:
Fn
(
O1
)
-
>
O2
>
Parser
<
I
O2
E
>
for
Map
<
F
G
O1
>
{
fn
parse
(
&
mut
self
i
:
I
)
-
>
IResult
<
I
O2
E
>
{
match
self
.
f
.
parse
(
i
)
{
Err
(
e
)
=
>
Err
(
e
)
Ok
(
(
i
o
)
)
=
>
Ok
(
(
i
(
self
.
g
)
(
o
)
)
)
}
}
}
#
[
cfg_attr
(
nightly
warn
(
rustdoc
:
:
missing_doc_code_examples
)
)
]
pub
struct
FlatMap
<
F
G
O1
>
{
f
:
F
g
:
G
phantom
:
core
:
:
marker
:
:
PhantomData
<
O1
>
}
impl
<
'
a
I
O1
O2
E
F
:
Parser
<
I
O1
E
>
G
:
Fn
(
O1
)
-
>
H
H
:
Parser
<
I
O2
E
>
>
Parser
<
I
O2
E
>
for
FlatMap
<
F
G
O1
>
{
fn
parse
(
&
mut
self
i
:
I
)
-
>
IResult
<
I
O2
E
>
{
let
(
i
o1
)
=
self
.
f
.
parse
(
i
)
?
;
(
self
.
g
)
(
o1
)
.
parse
(
i
)
}
}
#
[
cfg_attr
(
nightly
warn
(
rustdoc
:
:
missing_doc_code_examples
)
)
]
pub
struct
AndThen
<
F
G
O1
>
{
f
:
F
g
:
G
phantom
:
core
:
:
marker
:
:
PhantomData
<
O1
>
}
impl
<
'
a
I
O1
O2
E
F
:
Parser
<
I
O1
E
>
G
:
Parser
<
O1
O2
E
>
>
Parser
<
I
O2
E
>
for
AndThen
<
F
G
O1
>
{
fn
parse
(
&
mut
self
i
:
I
)
-
>
IResult
<
I
O2
E
>
{
let
(
i
o1
)
=
self
.
f
.
parse
(
i
)
?
;
let
(
_
o2
)
=
self
.
g
.
parse
(
o1
)
?
;
Ok
(
(
i
o2
)
)
}
}
#
[
cfg_attr
(
nightly
warn
(
rustdoc
:
:
missing_doc_code_examples
)
)
]
pub
struct
And
<
F
G
>
{
f
:
F
g
:
G
}
impl
<
'
a
I
O1
O2
E
F
:
Parser
<
I
O1
E
>
G
:
Parser
<
I
O2
E
>
>
Parser
<
I
(
O1
O2
)
E
>
for
And
<
F
G
>
{
fn
parse
(
&
mut
self
i
:
I
)
-
>
IResult
<
I
(
O1
O2
)
E
>
{
let
(
i
o1
)
=
self
.
f
.
parse
(
i
)
?
;
let
(
i
o2
)
=
self
.
g
.
parse
(
i
)
?
;
Ok
(
(
i
(
o1
o2
)
)
)
}
}
#
[
cfg_attr
(
nightly
warn
(
rustdoc
:
:
missing_doc_code_examples
)
)
]
pub
struct
Or
<
F
G
>
{
f
:
F
g
:
G
}
impl
<
'
a
I
:
Clone
O
E
:
crate
:
:
error
:
:
ParseError
<
I
>
F
:
Parser
<
I
O
E
>
G
:
Parser
<
I
O
E
>
>
Parser
<
I
O
E
>
for
Or
<
F
G
>
{
fn
parse
(
&
mut
self
i
:
I
)
-
>
IResult
<
I
O
E
>
{
match
self
.
f
.
parse
(
i
.
clone
(
)
)
{
Err
(
Err
:
:
Error
(
e1
)
)
=
>
match
self
.
g
.
parse
(
i
)
{
Err
(
Err
:
:
Error
(
e2
)
)
=
>
Err
(
Err
:
:
Error
(
e1
.
or
(
e2
)
)
)
res
=
>
res
}
res
=
>
res
}
}
}
#
[
cfg_attr
(
nightly
warn
(
rustdoc
:
:
missing_doc_code_examples
)
)
]
pub
struct
Into
<
F
O1
O2
:
From
<
O1
>
E1
E2
:
From
<
E1
>
>
{
f
:
F
phantom_out1
:
core
:
:
marker
:
:
PhantomData
<
O1
>
phantom_err1
:
core
:
:
marker
:
:
PhantomData
<
E1
>
phantom_out2
:
core
:
:
marker
:
:
PhantomData
<
O2
>
phantom_err2
:
core
:
:
marker
:
:
PhantomData
<
E2
>
}
impl
<
'
a
I
:
Clone
O1
O2
:
From
<
O1
>
E1
E2
:
crate
:
:
error
:
:
ParseError
<
I
>
+
From
<
E1
>
F
:
Parser
<
I
O1
E1
>
>
Parser
<
I
O2
E2
>
for
Into
<
F
O1
O2
E1
E2
>
{
fn
parse
(
&
mut
self
i
:
I
)
-
>
IResult
<
I
O2
E2
>
{
match
self
.
f
.
parse
(
i
)
{
Ok
(
(
i
o
)
)
=
>
Ok
(
(
i
o
.
into
(
)
)
)
Err
(
Err
:
:
Error
(
e
)
)
=
>
Err
(
Err
:
:
Error
(
e
.
into
(
)
)
)
Err
(
Err
:
:
Failure
(
e
)
)
=
>
Err
(
Err
:
:
Failure
(
e
.
into
(
)
)
)
Err
(
Err
:
:
Incomplete
(
e
)
)
=
>
Err
(
Err
:
:
Incomplete
(
e
)
)
}
}
}
#
[
cfg
(
test
)
]
mod
tests
{
use
super
:
:
*
;
use
crate
:
:
error
:
:
ErrorKind
;
#
[
doc
(
hidden
)
]
#
[
macro_export
]
macro_rules
!
assert_size
(
(
t
:
ty
sz
:
expr
)
=
>
(
assert_eq
!
(
crate
:
:
lib
:
:
std
:
:
mem
:
:
size_of
:
:
<
t
>
(
)
sz
)
;
)
;
)
;
#
[
test
]
#
[
cfg
(
target_pointer_width
=
"
64
"
)
]
fn
size_test
(
)
{
assert_size
!
(
IResult
<
&
[
u8
]
&
[
u8
]
(
&
[
u8
]
u32
)
>
40
)
;
assert_size
!
(
Needed
8
)
;
assert_size
!
(
Err
<
u32
>
16
)
;
assert_size
!
(
ErrorKind
1
)
;
}
#
[
test
]
fn
err_map_test
(
)
{
let
e
=
Err
:
:
Error
(
1
)
;
assert_eq
!
(
e
.
map
(
|
v
|
v
+
1
)
Err
:
:
Error
(
2
)
)
;
}
}
| true |
974a9d95546e8ea4c1feeb24bb6a8fb91d17a2ae
|
Rust
|
smokku/emerald
|
/src/world/emerald_world.rs
|
UTF-8
| 4,200 | 2.75 | 3 |
[
"MIT"
] |
permissive
|
use crate::rendering::components::Camera;
use crate::EmeraldError;
use hecs::*;
#[cfg(feature = "physics")]
use crate::world::physics::*;
#[cfg(feature = "physics")]
use rapier2d::dynamics::*;
pub struct EmeraldWorld {
#[cfg(feature = "physics")]
pub(crate) physics_engine: PhysicsEngine,
pub(crate) inner: World,
}
impl EmeraldWorld {
pub fn new() -> Self {
EmeraldWorld {
#[cfg(feature = "physics")]
physics_engine: PhysicsEngine::new(),
inner: World::default(),
}
}
/// Disable all cameras then set the camera on the given entity as active.
/// Fails if the given entity does not exist, or does not have a camera.
#[inline]
pub fn make_active_camera(&mut self, entity: Entity) -> Result<(), EmeraldError> {
let mut set_camera = false;
if let Ok(mut camera) = self.get_mut::<Camera>(entity) {
camera.is_active = true;
set_camera = true;
}
if set_camera {
for (id, mut camera_to_disable) in self.query::<&mut Camera>().iter() {
if id != entity {
camera_to_disable.is_active = false;
}
}
return Ok(());
}
Err(EmeraldError::new(format!(
"Entity {:?} either does not exist or does not hold a camera",
entity
)))
}
#[inline]
pub fn get_active_camera(&self) -> Option<Entity> {
let mut cam = None;
for (id, camera) in self.query::<&Camera>().iter() {
if camera.is_active {
cam = Some(id);
break;
}
}
cam
}
// TODO(bombfuse): Load an ecs world and physics world into this one.
pub fn merge(&mut self, _world: EmeraldWorld) -> Result<(), EmeraldError> {
Ok(())
}
pub fn spawn(&mut self, components: impl DynamicBundle) -> Entity {
self.inner.spawn(components)
}
#[cfg(feature = "physics")]
pub fn spawn_with_body(
&mut self,
components: impl DynamicBundle,
body_builder: RigidBodyBuilder,
) -> Result<(Entity, RigidBodyHandle), EmeraldError> {
let entity = self.spawn(components);
let rbh = self.physics().build_body(entity, body_builder)?;
Ok((entity, rbh))
}
pub fn spawn_batch<I>(&mut self, iter: I) -> SpawnBatchIter<'_, I::IntoIter>
where
I: IntoIterator,
I::Item: Bundle + 'static,
{
self.inner.spawn_batch::<I>(iter)
}
pub fn despawn(&mut self, entity: Entity) -> Result<(), NoSuchEntity> {
#[cfg(feature = "physics")]
self.physics_engine.remove_body(entity);
self.inner.despawn(entity)
}
pub fn clear(&mut self) {
self.inner.clear();
#[cfg(feature = "physics")]
{
self.physics_engine = PhysicsEngine::new();
}
}
pub fn query<Q: Query>(&self) -> QueryBorrow<'_, Q> {
self.inner.query::<Q>()
}
pub fn get_mut<T: Component>(&self, entity: Entity) -> Result<RefMut<'_, T>, ComponentError> {
self.inner.get_mut::<T>(entity)
}
pub fn get<T: Component>(&self, entity: Entity) -> Result<Ref<'_, T>, ComponentError> {
self.inner.get::<T>(entity)
}
pub fn reserve_entity(&self) -> Entity {
self.inner.reserve_entity()
}
pub fn insert(
&mut self,
entity: Entity,
components: impl DynamicBundle,
) -> Result<(), NoSuchEntity> {
self.inner.insert(entity, components)
}
pub fn remove<T: Bundle + 'static>(&mut self, entity: Entity) -> Result<T, ComponentError> {
self.inner.remove::<T>(entity)
}
pub fn remove_one<T: Component>(&mut self, entity: Entity) -> Result<T, ComponentError> {
self.inner.remove_one::<T>(entity)
}
#[cfg(feature = "physics")]
pub fn physics(&mut self) -> PhysicsHandler<'_> {
PhysicsHandler::new(&mut self.physics_engine, &mut self.inner)
}
#[cfg(feature = "physics")]
pub fn physics_ref(&self) -> PhysicsRefHandler<'_> {
PhysicsRefHandler::new(&self.physics_engine)
}
}
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.