text stringlengths 8 4.13M |
|---|
extern crate proconio;
use proconio::input;
fn main() {
input! {
n: i64,
a: i64,
b: i64,
}
let tak = "Takahashi";
let aok = "Aoki";
if a >= n {
println!("{}", tak);
return;
}
if a == b {
println!("{}", if n % (a + 1) != 0 { tak } else { aok });
return;
}
println!("{}", if a > b { tak } else { aok });
}
|
#[doc = "Reader of register BMTRGR"]
pub type R = crate::R<u32, super::BMTRGR>;
#[doc = "Writer for register BMTRGR"]
pub type W = crate::W<u32, super::BMTRGR>;
#[doc = "Register BMTRGR `reset()`'s with value 0"]
impl crate::ResetValue for super::BMTRGR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "OCHPEV\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum OCHPEV_A {
#[doc = "0: Rising edge on an on-chip event has no effect"]
NOEFFECT = 0,
#[doc = "1: Rising edge on an on-chip event triggers a burst mode entry"]
TRIGGER = 1,
}
impl From<OCHPEV_A> for bool {
#[inline(always)]
fn from(variant: OCHPEV_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `OCHPEV`"]
pub type OCHPEV_R = crate::R<bool, OCHPEV_A>;
impl OCHPEV_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> OCHPEV_A {
match self.bits {
false => OCHPEV_A::NOEFFECT,
true => OCHPEV_A::TRIGGER,
}
}
#[doc = "Checks if the value of the field is `NOEFFECT`"]
#[inline(always)]
pub fn is_no_effect(&self) -> bool {
*self == OCHPEV_A::NOEFFECT
}
#[doc = "Checks if the value of the field is `TRIGGER`"]
#[inline(always)]
pub fn is_trigger(&self) -> bool {
*self == OCHPEV_A::TRIGGER
}
}
#[doc = "Write proxy for field `OCHPEV`"]
pub struct OCHPEV_W<'a> {
w: &'a mut W,
}
impl<'a> OCHPEV_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: OCHPEV_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Rising edge on an on-chip event has no effect"]
#[inline(always)]
pub fn no_effect(self) -> &'a mut W {
self.variant(OCHPEV_A::NOEFFECT)
}
#[doc = "Rising edge on an on-chip event triggers a burst mode entry"]
#[inline(always)]
pub fn trigger(self) -> &'a mut W {
self.variant(OCHPEV_A::TRIGGER)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 31)) | (((value as u32) & 0x01) << 31);
self.w
}
}
#[doc = "EEV8\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum EEV8_A {
#[doc = "0: External event X has no effect"]
NOEFFECT = 0,
#[doc = "1: External event X triggers a burst mode entry"]
TRIGGER = 1,
}
impl From<EEV8_A> for bool {
#[inline(always)]
fn from(variant: EEV8_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `EEV8`"]
pub type EEV8_R = crate::R<bool, EEV8_A>;
impl EEV8_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> EEV8_A {
match self.bits {
false => EEV8_A::NOEFFECT,
true => EEV8_A::TRIGGER,
}
}
#[doc = "Checks if the value of the field is `NOEFFECT`"]
#[inline(always)]
pub fn is_no_effect(&self) -> bool {
*self == EEV8_A::NOEFFECT
}
#[doc = "Checks if the value of the field is `TRIGGER`"]
#[inline(always)]
pub fn is_trigger(&self) -> bool {
*self == EEV8_A::TRIGGER
}
}
#[doc = "Write proxy for field `EEV8`"]
pub struct EEV8_W<'a> {
w: &'a mut W,
}
impl<'a> EEV8_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: EEV8_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "External event X has no effect"]
#[inline(always)]
pub fn no_effect(self) -> &'a mut W {
self.variant(EEV8_A::NOEFFECT)
}
#[doc = "External event X triggers a burst mode entry"]
#[inline(always)]
pub fn trigger(self) -> &'a mut W {
self.variant(EEV8_A::TRIGGER)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 30)) | (((value as u32) & 0x01) << 30);
self.w
}
}
#[doc = "EEV7"]
pub type EEV7_A = EEV8_A;
#[doc = "Reader of field `EEV7`"]
pub type EEV7_R = crate::R<bool, EEV8_A>;
#[doc = "Write proxy for field `EEV7`"]
pub struct EEV7_W<'a> {
w: &'a mut W,
}
impl<'a> EEV7_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: EEV7_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "External event X has no effect"]
#[inline(always)]
pub fn no_effect(self) -> &'a mut W {
self.variant(EEV8_A::NOEFFECT)
}
#[doc = "External event X triggers a burst mode entry"]
#[inline(always)]
pub fn trigger(self) -> &'a mut W {
self.variant(EEV8_A::TRIGGER)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 29)) | (((value as u32) & 0x01) << 29);
self.w
}
}
#[doc = "TDEEV8\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TDEEV8_A {
#[doc = "0: has no effect"]
NOEFFECT = 0,
#[doc = "1: triggers a burst mode entry"]
TRIGGER = 1,
}
impl From<TDEEV8_A> for bool {
#[inline(always)]
fn from(variant: TDEEV8_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `TDEEV8`"]
pub type TDEEV8_R = crate::R<bool, TDEEV8_A>;
impl TDEEV8_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> TDEEV8_A {
match self.bits {
false => TDEEV8_A::NOEFFECT,
true => TDEEV8_A::TRIGGER,
}
}
#[doc = "Checks if the value of the field is `NOEFFECT`"]
#[inline(always)]
pub fn is_no_effect(&self) -> bool {
*self == TDEEV8_A::NOEFFECT
}
#[doc = "Checks if the value of the field is `TRIGGER`"]
#[inline(always)]
pub fn is_trigger(&self) -> bool {
*self == TDEEV8_A::TRIGGER
}
}
#[doc = "Write proxy for field `TDEEV8`"]
pub struct TDEEV8_W<'a> {
w: &'a mut W,
}
impl<'a> TDEEV8_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: TDEEV8_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "has no effect"]
#[inline(always)]
pub fn no_effect(self) -> &'a mut W {
self.variant(TDEEV8_A::NOEFFECT)
}
#[doc = "triggers a burst mode entry"]
#[inline(always)]
pub fn trigger(self) -> &'a mut W {
self.variant(TDEEV8_A::TRIGGER)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 28)) | (((value as u32) & 0x01) << 28);
self.w
}
}
#[doc = "TAEEV7"]
pub type TAEEV7_A = TDEEV8_A;
#[doc = "Reader of field `TAEEV7`"]
pub type TAEEV7_R = crate::R<bool, TDEEV8_A>;
#[doc = "Write proxy for field `TAEEV7`"]
pub struct TAEEV7_W<'a> {
w: &'a mut W,
}
impl<'a> TAEEV7_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: TAEEV7_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "has no effect"]
#[inline(always)]
pub fn no_effect(self) -> &'a mut W {
self.variant(TDEEV8_A::NOEFFECT)
}
#[doc = "triggers a burst mode entry"]
#[inline(always)]
pub fn trigger(self) -> &'a mut W {
self.variant(TDEEV8_A::TRIGGER)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 27)) | (((value as u32) & 0x01) << 27);
self.w
}
}
#[doc = "TECMP2\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TECMP2_A {
#[doc = "0: Timer X compare Y event has no effect"]
NOEFFECT = 0,
#[doc = "1: Timer X compare Y event triggers a burst mode entry"]
TRIGGER = 1,
}
impl From<TECMP2_A> for bool {
#[inline(always)]
fn from(variant: TECMP2_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `TECMP2`"]
pub type TECMP2_R = crate::R<bool, TECMP2_A>;
impl TECMP2_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> TECMP2_A {
match self.bits {
false => TECMP2_A::NOEFFECT,
true => TECMP2_A::TRIGGER,
}
}
#[doc = "Checks if the value of the field is `NOEFFECT`"]
#[inline(always)]
pub fn is_no_effect(&self) -> bool {
*self == TECMP2_A::NOEFFECT
}
#[doc = "Checks if the value of the field is `TRIGGER`"]
#[inline(always)]
pub fn is_trigger(&self) -> bool {
*self == TECMP2_A::TRIGGER
}
}
#[doc = "Write proxy for field `TECMP2`"]
pub struct TECMP2_W<'a> {
w: &'a mut W,
}
impl<'a> TECMP2_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: TECMP2_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Timer X compare Y event has no effect"]
#[inline(always)]
pub fn no_effect(self) -> &'a mut W {
self.variant(TECMP2_A::NOEFFECT)
}
#[doc = "Timer X compare Y event triggers a burst mode entry"]
#[inline(always)]
pub fn trigger(self) -> &'a mut W {
self.variant(TECMP2_A::TRIGGER)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 26)) | (((value as u32) & 0x01) << 26);
self.w
}
}
#[doc = "TECMP1"]
pub type TECMP1_A = TECMP2_A;
#[doc = "Reader of field `TECMP1`"]
pub type TECMP1_R = crate::R<bool, TECMP2_A>;
#[doc = "Write proxy for field `TECMP1`"]
pub struct TECMP1_W<'a> {
w: &'a mut W,
}
impl<'a> TECMP1_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: TECMP1_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Timer X compare Y event has no effect"]
#[inline(always)]
pub fn no_effect(self) -> &'a mut W {
self.variant(TECMP2_A::NOEFFECT)
}
#[doc = "Timer X compare Y event triggers a burst mode entry"]
#[inline(always)]
pub fn trigger(self) -> &'a mut W {
self.variant(TECMP2_A::TRIGGER)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 25)) | (((value as u32) & 0x01) << 25);
self.w
}
}
#[doc = "TEREP\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TEREP_A {
#[doc = "0: Timer X repetition event has no effect"]
NOEFFECT = 0,
#[doc = "1: Timer X repetition event triggers a burst mode entry"]
TRIGGER = 1,
}
impl From<TEREP_A> for bool {
#[inline(always)]
fn from(variant: TEREP_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `TEREP`"]
pub type TEREP_R = crate::R<bool, TEREP_A>;
impl TEREP_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> TEREP_A {
match self.bits {
false => TEREP_A::NOEFFECT,
true => TEREP_A::TRIGGER,
}
}
#[doc = "Checks if the value of the field is `NOEFFECT`"]
#[inline(always)]
pub fn is_no_effect(&self) -> bool {
*self == TEREP_A::NOEFFECT
}
#[doc = "Checks if the value of the field is `TRIGGER`"]
#[inline(always)]
pub fn is_trigger(&self) -> bool {
*self == TEREP_A::TRIGGER
}
}
#[doc = "Write proxy for field `TEREP`"]
pub struct TEREP_W<'a> {
w: &'a mut W,
}
impl<'a> TEREP_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: TEREP_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Timer X repetition event has no effect"]
#[inline(always)]
pub fn no_effect(self) -> &'a mut W {
self.variant(TEREP_A::NOEFFECT)
}
#[doc = "Timer X repetition event triggers a burst mode entry"]
#[inline(always)]
pub fn trigger(self) -> &'a mut W {
self.variant(TEREP_A::TRIGGER)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 24)) | (((value as u32) & 0x01) << 24);
self.w
}
}
#[doc = "TERST\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TERST_A {
#[doc = "0: Timer X reset/roll-over event has no effect"]
NOEFFECT = 0,
#[doc = "1: Timer X reset/roll-over event triggers a burst mode entry"]
TRIGGER = 1,
}
impl From<TERST_A> for bool {
#[inline(always)]
fn from(variant: TERST_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `TERST`"]
pub type TERST_R = crate::R<bool, TERST_A>;
impl TERST_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> TERST_A {
match self.bits {
false => TERST_A::NOEFFECT,
true => TERST_A::TRIGGER,
}
}
#[doc = "Checks if the value of the field is `NOEFFECT`"]
#[inline(always)]
pub fn is_no_effect(&self) -> bool {
*self == TERST_A::NOEFFECT
}
#[doc = "Checks if the value of the field is `TRIGGER`"]
#[inline(always)]
pub fn is_trigger(&self) -> bool {
*self == TERST_A::TRIGGER
}
}
#[doc = "Write proxy for field `TERST`"]
pub struct TERST_W<'a> {
w: &'a mut W,
}
impl<'a> TERST_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: TERST_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Timer X reset/roll-over event has no effect"]
#[inline(always)]
pub fn no_effect(self) -> &'a mut W {
self.variant(TERST_A::NOEFFECT)
}
#[doc = "Timer X reset/roll-over event triggers a burst mode entry"]
#[inline(always)]
pub fn trigger(self) -> &'a mut W {
self.variant(TERST_A::TRIGGER)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 23)) | (((value as u32) & 0x01) << 23);
self.w
}
}
#[doc = "TDCMP2"]
pub type TDCMP2_A = TECMP2_A;
#[doc = "Reader of field `TDCMP2`"]
pub type TDCMP2_R = crate::R<bool, TECMP2_A>;
#[doc = "Write proxy for field `TDCMP2`"]
pub struct TDCMP2_W<'a> {
w: &'a mut W,
}
impl<'a> TDCMP2_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: TDCMP2_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Timer X compare Y event has no effect"]
#[inline(always)]
pub fn no_effect(self) -> &'a mut W {
self.variant(TECMP2_A::NOEFFECT)
}
#[doc = "Timer X compare Y event triggers a burst mode entry"]
#[inline(always)]
pub fn trigger(self) -> &'a mut W {
self.variant(TECMP2_A::TRIGGER)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 22)) | (((value as u32) & 0x01) << 22);
self.w
}
}
#[doc = "TDCMP1"]
pub type TDCMP1_A = TECMP2_A;
#[doc = "Reader of field `TDCMP1`"]
pub type TDCMP1_R = crate::R<bool, TECMP2_A>;
#[doc = "Write proxy for field `TDCMP1`"]
pub struct TDCMP1_W<'a> {
w: &'a mut W,
}
impl<'a> TDCMP1_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: TDCMP1_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Timer X compare Y event has no effect"]
#[inline(always)]
pub fn no_effect(self) -> &'a mut W {
self.variant(TECMP2_A::NOEFFECT)
}
#[doc = "Timer X compare Y event triggers a burst mode entry"]
#[inline(always)]
pub fn trigger(self) -> &'a mut W {
self.variant(TECMP2_A::TRIGGER)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 21)) | (((value as u32) & 0x01) << 21);
self.w
}
}
#[doc = "TDREP"]
pub type TDREP_A = TEREP_A;
#[doc = "Reader of field `TDREP`"]
pub type TDREP_R = crate::R<bool, TEREP_A>;
#[doc = "Write proxy for field `TDREP`"]
pub struct TDREP_W<'a> {
w: &'a mut W,
}
impl<'a> TDREP_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: TDREP_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Timer X repetition event has no effect"]
#[inline(always)]
pub fn no_effect(self) -> &'a mut W {
self.variant(TEREP_A::NOEFFECT)
}
#[doc = "Timer X repetition event triggers a burst mode entry"]
#[inline(always)]
pub fn trigger(self) -> &'a mut W {
self.variant(TEREP_A::TRIGGER)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 20)) | (((value as u32) & 0x01) << 20);
self.w
}
}
#[doc = "TDRST"]
pub type TDRST_A = TERST_A;
#[doc = "Reader of field `TDRST`"]
pub type TDRST_R = crate::R<bool, TERST_A>;
#[doc = "Write proxy for field `TDRST`"]
pub struct TDRST_W<'a> {
w: &'a mut W,
}
impl<'a> TDRST_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: TDRST_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Timer X reset/roll-over event has no effect"]
#[inline(always)]
pub fn no_effect(self) -> &'a mut W {
self.variant(TERST_A::NOEFFECT)
}
#[doc = "Timer X reset/roll-over event triggers a burst mode entry"]
#[inline(always)]
pub fn trigger(self) -> &'a mut W {
self.variant(TERST_A::TRIGGER)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 19)) | (((value as u32) & 0x01) << 19);
self.w
}
}
#[doc = "TCCMP2"]
pub type TCCMP2_A = TECMP2_A;
#[doc = "Reader of field `TCCMP2`"]
pub type TCCMP2_R = crate::R<bool, TECMP2_A>;
#[doc = "Write proxy for field `TCCMP2`"]
pub struct TCCMP2_W<'a> {
w: &'a mut W,
}
impl<'a> TCCMP2_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: TCCMP2_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Timer X compare Y event has no effect"]
#[inline(always)]
pub fn no_effect(self) -> &'a mut W {
self.variant(TECMP2_A::NOEFFECT)
}
#[doc = "Timer X compare Y event triggers a burst mode entry"]
#[inline(always)]
pub fn trigger(self) -> &'a mut W {
self.variant(TECMP2_A::TRIGGER)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 18)) | (((value as u32) & 0x01) << 18);
self.w
}
}
#[doc = "TCCMP1"]
pub type TCCMP1_A = TECMP2_A;
#[doc = "Reader of field `TCCMP1`"]
pub type TCCMP1_R = crate::R<bool, TECMP2_A>;
#[doc = "Write proxy for field `TCCMP1`"]
pub struct TCCMP1_W<'a> {
w: &'a mut W,
}
impl<'a> TCCMP1_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: TCCMP1_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Timer X compare Y event has no effect"]
#[inline(always)]
pub fn no_effect(self) -> &'a mut W {
self.variant(TECMP2_A::NOEFFECT)
}
#[doc = "Timer X compare Y event triggers a burst mode entry"]
#[inline(always)]
pub fn trigger(self) -> &'a mut W {
self.variant(TECMP2_A::TRIGGER)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 17)) | (((value as u32) & 0x01) << 17);
self.w
}
}
#[doc = "TCREP"]
pub type TCREP_A = TEREP_A;
#[doc = "Reader of field `TCREP`"]
pub type TCREP_R = crate::R<bool, TEREP_A>;
#[doc = "Write proxy for field `TCREP`"]
pub struct TCREP_W<'a> {
w: &'a mut W,
}
impl<'a> TCREP_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: TCREP_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Timer X repetition event has no effect"]
#[inline(always)]
pub fn no_effect(self) -> &'a mut W {
self.variant(TEREP_A::NOEFFECT)
}
#[doc = "Timer X repetition event triggers a burst mode entry"]
#[inline(always)]
pub fn trigger(self) -> &'a mut W {
self.variant(TEREP_A::TRIGGER)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 16)) | (((value as u32) & 0x01) << 16);
self.w
}
}
#[doc = "TCRST"]
pub type TCRST_A = TERST_A;
#[doc = "Reader of field `TCRST`"]
pub type TCRST_R = crate::R<bool, TERST_A>;
#[doc = "Write proxy for field `TCRST`"]
pub struct TCRST_W<'a> {
w: &'a mut W,
}
impl<'a> TCRST_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: TCRST_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Timer X reset/roll-over event has no effect"]
#[inline(always)]
pub fn no_effect(self) -> &'a mut W {
self.variant(TERST_A::NOEFFECT)
}
#[doc = "Timer X reset/roll-over event triggers a burst mode entry"]
#[inline(always)]
pub fn trigger(self) -> &'a mut W {
self.variant(TERST_A::TRIGGER)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 15)) | (((value as u32) & 0x01) << 15);
self.w
}
}
#[doc = "TBCMP2"]
pub type TBCMP2_A = TECMP2_A;
#[doc = "Reader of field `TBCMP2`"]
pub type TBCMP2_R = crate::R<bool, TECMP2_A>;
#[doc = "Write proxy for field `TBCMP2`"]
pub struct TBCMP2_W<'a> {
w: &'a mut W,
}
impl<'a> TBCMP2_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: TBCMP2_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Timer X compare Y event has no effect"]
#[inline(always)]
pub fn no_effect(self) -> &'a mut W {
self.variant(TECMP2_A::NOEFFECT)
}
#[doc = "Timer X compare Y event triggers a burst mode entry"]
#[inline(always)]
pub fn trigger(self) -> &'a mut W {
self.variant(TECMP2_A::TRIGGER)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 14)) | (((value as u32) & 0x01) << 14);
self.w
}
}
#[doc = "TBCMP1"]
pub type TBCMP1_A = TECMP2_A;
#[doc = "Reader of field `TBCMP1`"]
pub type TBCMP1_R = crate::R<bool, TECMP2_A>;
#[doc = "Write proxy for field `TBCMP1`"]
pub struct TBCMP1_W<'a> {
w: &'a mut W,
}
impl<'a> TBCMP1_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: TBCMP1_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Timer X compare Y event has no effect"]
#[inline(always)]
pub fn no_effect(self) -> &'a mut W {
self.variant(TECMP2_A::NOEFFECT)
}
#[doc = "Timer X compare Y event triggers a burst mode entry"]
#[inline(always)]
pub fn trigger(self) -> &'a mut W {
self.variant(TECMP2_A::TRIGGER)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 13)) | (((value as u32) & 0x01) << 13);
self.w
}
}
#[doc = "TBREP"]
pub type TBREP_A = TEREP_A;
#[doc = "Reader of field `TBREP`"]
pub type TBREP_R = crate::R<bool, TEREP_A>;
#[doc = "Write proxy for field `TBREP`"]
pub struct TBREP_W<'a> {
w: &'a mut W,
}
impl<'a> TBREP_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: TBREP_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Timer X repetition event has no effect"]
#[inline(always)]
pub fn no_effect(self) -> &'a mut W {
self.variant(TEREP_A::NOEFFECT)
}
#[doc = "Timer X repetition event triggers a burst mode entry"]
#[inline(always)]
pub fn trigger(self) -> &'a mut W {
self.variant(TEREP_A::TRIGGER)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 12)) | (((value as u32) & 0x01) << 12);
self.w
}
}
#[doc = "TBRST"]
pub type TBRST_A = TERST_A;
#[doc = "Reader of field `TBRST`"]
pub type TBRST_R = crate::R<bool, TERST_A>;
#[doc = "Write proxy for field `TBRST`"]
pub struct TBRST_W<'a> {
w: &'a mut W,
}
impl<'a> TBRST_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: TBRST_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Timer X reset/roll-over event has no effect"]
#[inline(always)]
pub fn no_effect(self) -> &'a mut W {
self.variant(TERST_A::NOEFFECT)
}
#[doc = "Timer X reset/roll-over event triggers a burst mode entry"]
#[inline(always)]
pub fn trigger(self) -> &'a mut W {
self.variant(TERST_A::TRIGGER)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 11)) | (((value as u32) & 0x01) << 11);
self.w
}
}
#[doc = "TACMP2"]
pub type TACMP2_A = TECMP2_A;
#[doc = "Reader of field `TACMP2`"]
pub type TACMP2_R = crate::R<bool, TECMP2_A>;
#[doc = "Write proxy for field `TACMP2`"]
pub struct TACMP2_W<'a> {
w: &'a mut W,
}
impl<'a> TACMP2_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: TACMP2_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Timer X compare Y event has no effect"]
#[inline(always)]
pub fn no_effect(self) -> &'a mut W {
self.variant(TECMP2_A::NOEFFECT)
}
#[doc = "Timer X compare Y event triggers a burst mode entry"]
#[inline(always)]
pub fn trigger(self) -> &'a mut W {
self.variant(TECMP2_A::TRIGGER)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 10)) | (((value as u32) & 0x01) << 10);
self.w
}
}
#[doc = "TACMP1"]
pub type TACMP1_A = TECMP2_A;
#[doc = "Reader of field `TACMP1`"]
pub type TACMP1_R = crate::R<bool, TECMP2_A>;
#[doc = "Write proxy for field `TACMP1`"]
pub struct TACMP1_W<'a> {
w: &'a mut W,
}
impl<'a> TACMP1_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: TACMP1_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Timer X compare Y event has no effect"]
#[inline(always)]
pub fn no_effect(self) -> &'a mut W {
self.variant(TECMP2_A::NOEFFECT)
}
#[doc = "Timer X compare Y event triggers a burst mode entry"]
#[inline(always)]
pub fn trigger(self) -> &'a mut W {
self.variant(TECMP2_A::TRIGGER)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 9)) | (((value as u32) & 0x01) << 9);
self.w
}
}
#[doc = "TAREP"]
pub type TAREP_A = TEREP_A;
#[doc = "Reader of field `TAREP`"]
pub type TAREP_R = crate::R<bool, TEREP_A>;
#[doc = "Write proxy for field `TAREP`"]
pub struct TAREP_W<'a> {
w: &'a mut W,
}
impl<'a> TAREP_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: TAREP_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Timer X repetition event has no effect"]
#[inline(always)]
pub fn no_effect(self) -> &'a mut W {
self.variant(TEREP_A::NOEFFECT)
}
#[doc = "Timer X repetition event triggers a burst mode entry"]
#[inline(always)]
pub fn trigger(self) -> &'a mut W {
self.variant(TEREP_A::TRIGGER)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 8)) | (((value as u32) & 0x01) << 8);
self.w
}
}
#[doc = "TARST"]
pub type TARST_A = TERST_A;
#[doc = "Reader of field `TARST`"]
pub type TARST_R = crate::R<bool, TERST_A>;
#[doc = "Write proxy for field `TARST`"]
pub struct TARST_W<'a> {
w: &'a mut W,
}
impl<'a> TARST_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: TARST_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Timer X reset/roll-over event has no effect"]
#[inline(always)]
pub fn no_effect(self) -> &'a mut W {
self.variant(TERST_A::NOEFFECT)
}
#[doc = "Timer X reset/roll-over event triggers a burst mode entry"]
#[inline(always)]
pub fn trigger(self) -> &'a mut W {
self.variant(TERST_A::TRIGGER)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 7)) | (((value as u32) & 0x01) << 7);
self.w
}
}
#[doc = "MSTCMP4\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum MSTCMP4_A {
#[doc = "0: Master timer compare X event has no effect"]
NOEFFECT = 0,
#[doc = "1: Master timer compare X event triggers a burst mode entry"]
TRIGGER = 1,
}
impl From<MSTCMP4_A> for bool {
#[inline(always)]
fn from(variant: MSTCMP4_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `MSTCMP4`"]
pub type MSTCMP4_R = crate::R<bool, MSTCMP4_A>;
impl MSTCMP4_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> MSTCMP4_A {
match self.bits {
false => MSTCMP4_A::NOEFFECT,
true => MSTCMP4_A::TRIGGER,
}
}
#[doc = "Checks if the value of the field is `NOEFFECT`"]
#[inline(always)]
pub fn is_no_effect(&self) -> bool {
*self == MSTCMP4_A::NOEFFECT
}
#[doc = "Checks if the value of the field is `TRIGGER`"]
#[inline(always)]
pub fn is_trigger(&self) -> bool {
*self == MSTCMP4_A::TRIGGER
}
}
#[doc = "Write proxy for field `MSTCMP4`"]
pub struct MSTCMP4_W<'a> {
w: &'a mut W,
}
impl<'a> MSTCMP4_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: MSTCMP4_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Master timer compare X event has no effect"]
#[inline(always)]
pub fn no_effect(self) -> &'a mut W {
self.variant(MSTCMP4_A::NOEFFECT)
}
#[doc = "Master timer compare X event triggers a burst mode entry"]
#[inline(always)]
pub fn trigger(self) -> &'a mut W {
self.variant(MSTCMP4_A::TRIGGER)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 6)) | (((value as u32) & 0x01) << 6);
self.w
}
}
#[doc = "MSTCMP3"]
pub type MSTCMP3_A = MSTCMP4_A;
#[doc = "Reader of field `MSTCMP3`"]
pub type MSTCMP3_R = crate::R<bool, MSTCMP4_A>;
#[doc = "Write proxy for field `MSTCMP3`"]
pub struct MSTCMP3_W<'a> {
w: &'a mut W,
}
impl<'a> MSTCMP3_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: MSTCMP3_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Master timer compare X event has no effect"]
#[inline(always)]
pub fn no_effect(self) -> &'a mut W {
self.variant(MSTCMP4_A::NOEFFECT)
}
#[doc = "Master timer compare X event triggers a burst mode entry"]
#[inline(always)]
pub fn trigger(self) -> &'a mut W {
self.variant(MSTCMP4_A::TRIGGER)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 5)) | (((value as u32) & 0x01) << 5);
self.w
}
}
#[doc = "MSTCMP2"]
pub type MSTCMP2_A = MSTCMP4_A;
#[doc = "Reader of field `MSTCMP2`"]
pub type MSTCMP2_R = crate::R<bool, MSTCMP4_A>;
#[doc = "Write proxy for field `MSTCMP2`"]
pub struct MSTCMP2_W<'a> {
w: &'a mut W,
}
impl<'a> MSTCMP2_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: MSTCMP2_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Master timer compare X event has no effect"]
#[inline(always)]
pub fn no_effect(self) -> &'a mut W {
self.variant(MSTCMP4_A::NOEFFECT)
}
#[doc = "Master timer compare X event triggers a burst mode entry"]
#[inline(always)]
pub fn trigger(self) -> &'a mut W {
self.variant(MSTCMP4_A::TRIGGER)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 4)) | (((value as u32) & 0x01) << 4);
self.w
}
}
#[doc = "MSTCMP1"]
pub type MSTCMP1_A = MSTCMP4_A;
#[doc = "Reader of field `MSTCMP1`"]
pub type MSTCMP1_R = crate::R<bool, MSTCMP4_A>;
#[doc = "Write proxy for field `MSTCMP1`"]
pub struct MSTCMP1_W<'a> {
w: &'a mut W,
}
impl<'a> MSTCMP1_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: MSTCMP1_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Master timer compare X event has no effect"]
#[inline(always)]
pub fn no_effect(self) -> &'a mut W {
self.variant(MSTCMP4_A::NOEFFECT)
}
#[doc = "Master timer compare X event triggers a burst mode entry"]
#[inline(always)]
pub fn trigger(self) -> &'a mut W {
self.variant(MSTCMP4_A::TRIGGER)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 3)) | (((value as u32) & 0x01) << 3);
self.w
}
}
#[doc = "MSTREP\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum MSTREP_A {
#[doc = "0: Master timer repetition event has no effect"]
NOEFFECT = 0,
#[doc = "1: Master timer repetition event triggers a burst mode entry"]
TRIGGER = 1,
}
impl From<MSTREP_A> for bool {
#[inline(always)]
fn from(variant: MSTREP_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `MSTREP`"]
pub type MSTREP_R = crate::R<bool, MSTREP_A>;
impl MSTREP_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> MSTREP_A {
match self.bits {
false => MSTREP_A::NOEFFECT,
true => MSTREP_A::TRIGGER,
}
}
#[doc = "Checks if the value of the field is `NOEFFECT`"]
#[inline(always)]
pub fn is_no_effect(&self) -> bool {
*self == MSTREP_A::NOEFFECT
}
#[doc = "Checks if the value of the field is `TRIGGER`"]
#[inline(always)]
pub fn is_trigger(&self) -> bool {
*self == MSTREP_A::TRIGGER
}
}
#[doc = "Write proxy for field `MSTREP`"]
pub struct MSTREP_W<'a> {
w: &'a mut W,
}
impl<'a> MSTREP_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: MSTREP_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Master timer repetition event has no effect"]
#[inline(always)]
pub fn no_effect(self) -> &'a mut W {
self.variant(MSTREP_A::NOEFFECT)
}
#[doc = "Master timer repetition event triggers a burst mode entry"]
#[inline(always)]
pub fn trigger(self) -> &'a mut W {
self.variant(MSTREP_A::TRIGGER)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2);
self.w
}
}
#[doc = "MSTRST\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum MSTRST_A {
#[doc = "0: Master timer reset/roll-over event has no effect"]
NOEFFECT = 0,
#[doc = "1: Master timer reset/roll-over event triggers a burst mode entry"]
TRIGGER = 1,
}
impl From<MSTRST_A> for bool {
#[inline(always)]
fn from(variant: MSTRST_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `MSTRST`"]
pub type MSTRST_R = crate::R<bool, MSTRST_A>;
impl MSTRST_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> MSTRST_A {
match self.bits {
false => MSTRST_A::NOEFFECT,
true => MSTRST_A::TRIGGER,
}
}
#[doc = "Checks if the value of the field is `NOEFFECT`"]
#[inline(always)]
pub fn is_no_effect(&self) -> bool {
*self == MSTRST_A::NOEFFECT
}
#[doc = "Checks if the value of the field is `TRIGGER`"]
#[inline(always)]
pub fn is_trigger(&self) -> bool {
*self == MSTRST_A::TRIGGER
}
}
#[doc = "Write proxy for field `MSTRST`"]
pub struct MSTRST_W<'a> {
w: &'a mut W,
}
impl<'a> MSTRST_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: MSTRST_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Master timer reset/roll-over event has no effect"]
#[inline(always)]
pub fn no_effect(self) -> &'a mut W {
self.variant(MSTRST_A::NOEFFECT)
}
#[doc = "Master timer reset/roll-over event triggers a burst mode entry"]
#[inline(always)]
pub fn trigger(self) -> &'a mut W {
self.variant(MSTRST_A::TRIGGER)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1);
self.w
}
}
#[doc = "SW\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum SW_A {
#[doc = "0: No effect"]
NOEFFECT = 0,
#[doc = "1: Trigger immediate burst mode operation"]
TRIGGER = 1,
}
impl From<SW_A> for bool {
#[inline(always)]
fn from(variant: SW_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `SW`"]
pub type SW_R = crate::R<bool, SW_A>;
impl SW_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> SW_A {
match self.bits {
false => SW_A::NOEFFECT,
true => SW_A::TRIGGER,
}
}
#[doc = "Checks if the value of the field is `NOEFFECT`"]
#[inline(always)]
pub fn is_no_effect(&self) -> bool {
*self == SW_A::NOEFFECT
}
#[doc = "Checks if the value of the field is `TRIGGER`"]
#[inline(always)]
pub fn is_trigger(&self) -> bool {
*self == SW_A::TRIGGER
}
}
#[doc = "Write proxy for field `SW`"]
pub struct SW_W<'a> {
w: &'a mut W,
}
impl<'a> SW_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: SW_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "No effect"]
#[inline(always)]
pub fn no_effect(self) -> &'a mut W {
self.variant(SW_A::NOEFFECT)
}
#[doc = "Trigger immediate burst mode operation"]
#[inline(always)]
pub fn trigger(self) -> &'a mut W {
self.variant(SW_A::TRIGGER)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01);
self.w
}
}
impl R {
#[doc = "Bit 31 - OCHPEV"]
#[inline(always)]
pub fn ochpev(&self) -> OCHPEV_R {
OCHPEV_R::new(((self.bits >> 31) & 0x01) != 0)
}
#[doc = "Bit 30 - EEV8"]
#[inline(always)]
pub fn eev8(&self) -> EEV8_R {
EEV8_R::new(((self.bits >> 30) & 0x01) != 0)
}
#[doc = "Bit 29 - EEV7"]
#[inline(always)]
pub fn eev7(&self) -> EEV7_R {
EEV7_R::new(((self.bits >> 29) & 0x01) != 0)
}
#[doc = "Bit 28 - TDEEV8"]
#[inline(always)]
pub fn tdeev8(&self) -> TDEEV8_R {
TDEEV8_R::new(((self.bits >> 28) & 0x01) != 0)
}
#[doc = "Bit 27 - TAEEV7"]
#[inline(always)]
pub fn taeev7(&self) -> TAEEV7_R {
TAEEV7_R::new(((self.bits >> 27) & 0x01) != 0)
}
#[doc = "Bit 26 - TECMP2"]
#[inline(always)]
pub fn tecmp2(&self) -> TECMP2_R {
TECMP2_R::new(((self.bits >> 26) & 0x01) != 0)
}
#[doc = "Bit 25 - TECMP1"]
#[inline(always)]
pub fn tecmp1(&self) -> TECMP1_R {
TECMP1_R::new(((self.bits >> 25) & 0x01) != 0)
}
#[doc = "Bit 24 - TEREP"]
#[inline(always)]
pub fn terep(&self) -> TEREP_R {
TEREP_R::new(((self.bits >> 24) & 0x01) != 0)
}
#[doc = "Bit 23 - TERST"]
#[inline(always)]
pub fn terst(&self) -> TERST_R {
TERST_R::new(((self.bits >> 23) & 0x01) != 0)
}
#[doc = "Bit 22 - TDCMP2"]
#[inline(always)]
pub fn tdcmp2(&self) -> TDCMP2_R {
TDCMP2_R::new(((self.bits >> 22) & 0x01) != 0)
}
#[doc = "Bit 21 - TDCMP1"]
#[inline(always)]
pub fn tdcmp1(&self) -> TDCMP1_R {
TDCMP1_R::new(((self.bits >> 21) & 0x01) != 0)
}
#[doc = "Bit 20 - TDREP"]
#[inline(always)]
pub fn tdrep(&self) -> TDREP_R {
TDREP_R::new(((self.bits >> 20) & 0x01) != 0)
}
#[doc = "Bit 19 - TDRST"]
#[inline(always)]
pub fn tdrst(&self) -> TDRST_R {
TDRST_R::new(((self.bits >> 19) & 0x01) != 0)
}
#[doc = "Bit 18 - TCCMP2"]
#[inline(always)]
pub fn tccmp2(&self) -> TCCMP2_R {
TCCMP2_R::new(((self.bits >> 18) & 0x01) != 0)
}
#[doc = "Bit 17 - TCCMP1"]
#[inline(always)]
pub fn tccmp1(&self) -> TCCMP1_R {
TCCMP1_R::new(((self.bits >> 17) & 0x01) != 0)
}
#[doc = "Bit 16 - TCREP"]
#[inline(always)]
pub fn tcrep(&self) -> TCREP_R {
TCREP_R::new(((self.bits >> 16) & 0x01) != 0)
}
#[doc = "Bit 15 - TCRST"]
#[inline(always)]
pub fn tcrst(&self) -> TCRST_R {
TCRST_R::new(((self.bits >> 15) & 0x01) != 0)
}
#[doc = "Bit 14 - TBCMP2"]
#[inline(always)]
pub fn tbcmp2(&self) -> TBCMP2_R {
TBCMP2_R::new(((self.bits >> 14) & 0x01) != 0)
}
#[doc = "Bit 13 - TBCMP1"]
#[inline(always)]
pub fn tbcmp1(&self) -> TBCMP1_R {
TBCMP1_R::new(((self.bits >> 13) & 0x01) != 0)
}
#[doc = "Bit 12 - TBREP"]
#[inline(always)]
pub fn tbrep(&self) -> TBREP_R {
TBREP_R::new(((self.bits >> 12) & 0x01) != 0)
}
#[doc = "Bit 11 - TBRST"]
#[inline(always)]
pub fn tbrst(&self) -> TBRST_R {
TBRST_R::new(((self.bits >> 11) & 0x01) != 0)
}
#[doc = "Bit 10 - TACMP2"]
#[inline(always)]
pub fn tacmp2(&self) -> TACMP2_R {
TACMP2_R::new(((self.bits >> 10) & 0x01) != 0)
}
#[doc = "Bit 9 - TACMP1"]
#[inline(always)]
pub fn tacmp1(&self) -> TACMP1_R {
TACMP1_R::new(((self.bits >> 9) & 0x01) != 0)
}
#[doc = "Bit 8 - TAREP"]
#[inline(always)]
pub fn tarep(&self) -> TAREP_R {
TAREP_R::new(((self.bits >> 8) & 0x01) != 0)
}
#[doc = "Bit 7 - TARST"]
#[inline(always)]
pub fn tarst(&self) -> TARST_R {
TARST_R::new(((self.bits >> 7) & 0x01) != 0)
}
#[doc = "Bit 6 - MSTCMP4"]
#[inline(always)]
pub fn mstcmp4(&self) -> MSTCMP4_R {
MSTCMP4_R::new(((self.bits >> 6) & 0x01) != 0)
}
#[doc = "Bit 5 - MSTCMP3"]
#[inline(always)]
pub fn mstcmp3(&self) -> MSTCMP3_R {
MSTCMP3_R::new(((self.bits >> 5) & 0x01) != 0)
}
#[doc = "Bit 4 - MSTCMP2"]
#[inline(always)]
pub fn mstcmp2(&self) -> MSTCMP2_R {
MSTCMP2_R::new(((self.bits >> 4) & 0x01) != 0)
}
#[doc = "Bit 3 - MSTCMP1"]
#[inline(always)]
pub fn mstcmp1(&self) -> MSTCMP1_R {
MSTCMP1_R::new(((self.bits >> 3) & 0x01) != 0)
}
#[doc = "Bit 2 - MSTREP"]
#[inline(always)]
pub fn mstrep(&self) -> MSTREP_R {
MSTREP_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bit 1 - MSTRST"]
#[inline(always)]
pub fn mstrst(&self) -> MSTRST_R {
MSTRST_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 0 - SW"]
#[inline(always)]
pub fn sw(&self) -> SW_R {
SW_R::new((self.bits & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 31 - OCHPEV"]
#[inline(always)]
pub fn ochpev(&mut self) -> OCHPEV_W {
OCHPEV_W { w: self }
}
#[doc = "Bit 30 - EEV8"]
#[inline(always)]
pub fn eev8(&mut self) -> EEV8_W {
EEV8_W { w: self }
}
#[doc = "Bit 29 - EEV7"]
#[inline(always)]
pub fn eev7(&mut self) -> EEV7_W {
EEV7_W { w: self }
}
#[doc = "Bit 28 - TDEEV8"]
#[inline(always)]
pub fn tdeev8(&mut self) -> TDEEV8_W {
TDEEV8_W { w: self }
}
#[doc = "Bit 27 - TAEEV7"]
#[inline(always)]
pub fn taeev7(&mut self) -> TAEEV7_W {
TAEEV7_W { w: self }
}
#[doc = "Bit 26 - TECMP2"]
#[inline(always)]
pub fn tecmp2(&mut self) -> TECMP2_W {
TECMP2_W { w: self }
}
#[doc = "Bit 25 - TECMP1"]
#[inline(always)]
pub fn tecmp1(&mut self) -> TECMP1_W {
TECMP1_W { w: self }
}
#[doc = "Bit 24 - TEREP"]
#[inline(always)]
pub fn terep(&mut self) -> TEREP_W {
TEREP_W { w: self }
}
#[doc = "Bit 23 - TERST"]
#[inline(always)]
pub fn terst(&mut self) -> TERST_W {
TERST_W { w: self }
}
#[doc = "Bit 22 - TDCMP2"]
#[inline(always)]
pub fn tdcmp2(&mut self) -> TDCMP2_W {
TDCMP2_W { w: self }
}
#[doc = "Bit 21 - TDCMP1"]
#[inline(always)]
pub fn tdcmp1(&mut self) -> TDCMP1_W {
TDCMP1_W { w: self }
}
#[doc = "Bit 20 - TDREP"]
#[inline(always)]
pub fn tdrep(&mut self) -> TDREP_W {
TDREP_W { w: self }
}
#[doc = "Bit 19 - TDRST"]
#[inline(always)]
pub fn tdrst(&mut self) -> TDRST_W {
TDRST_W { w: self }
}
#[doc = "Bit 18 - TCCMP2"]
#[inline(always)]
pub fn tccmp2(&mut self) -> TCCMP2_W {
TCCMP2_W { w: self }
}
#[doc = "Bit 17 - TCCMP1"]
#[inline(always)]
pub fn tccmp1(&mut self) -> TCCMP1_W {
TCCMP1_W { w: self }
}
#[doc = "Bit 16 - TCREP"]
#[inline(always)]
pub fn tcrep(&mut self) -> TCREP_W {
TCREP_W { w: self }
}
#[doc = "Bit 15 - TCRST"]
#[inline(always)]
pub fn tcrst(&mut self) -> TCRST_W {
TCRST_W { w: self }
}
#[doc = "Bit 14 - TBCMP2"]
#[inline(always)]
pub fn tbcmp2(&mut self) -> TBCMP2_W {
TBCMP2_W { w: self }
}
#[doc = "Bit 13 - TBCMP1"]
#[inline(always)]
pub fn tbcmp1(&mut self) -> TBCMP1_W {
TBCMP1_W { w: self }
}
#[doc = "Bit 12 - TBREP"]
#[inline(always)]
pub fn tbrep(&mut self) -> TBREP_W {
TBREP_W { w: self }
}
#[doc = "Bit 11 - TBRST"]
#[inline(always)]
pub fn tbrst(&mut self) -> TBRST_W {
TBRST_W { w: self }
}
#[doc = "Bit 10 - TACMP2"]
#[inline(always)]
pub fn tacmp2(&mut self) -> TACMP2_W {
TACMP2_W { w: self }
}
#[doc = "Bit 9 - TACMP1"]
#[inline(always)]
pub fn tacmp1(&mut self) -> TACMP1_W {
TACMP1_W { w: self }
}
#[doc = "Bit 8 - TAREP"]
#[inline(always)]
pub fn tarep(&mut self) -> TAREP_W {
TAREP_W { w: self }
}
#[doc = "Bit 7 - TARST"]
#[inline(always)]
pub fn tarst(&mut self) -> TARST_W {
TARST_W { w: self }
}
#[doc = "Bit 6 - MSTCMP4"]
#[inline(always)]
pub fn mstcmp4(&mut self) -> MSTCMP4_W {
MSTCMP4_W { w: self }
}
#[doc = "Bit 5 - MSTCMP3"]
#[inline(always)]
pub fn mstcmp3(&mut self) -> MSTCMP3_W {
MSTCMP3_W { w: self }
}
#[doc = "Bit 4 - MSTCMP2"]
#[inline(always)]
pub fn mstcmp2(&mut self) -> MSTCMP2_W {
MSTCMP2_W { w: self }
}
#[doc = "Bit 3 - MSTCMP1"]
#[inline(always)]
pub fn mstcmp1(&mut self) -> MSTCMP1_W {
MSTCMP1_W { w: self }
}
#[doc = "Bit 2 - MSTREP"]
#[inline(always)]
pub fn mstrep(&mut self) -> MSTREP_W {
MSTREP_W { w: self }
}
#[doc = "Bit 1 - MSTRST"]
#[inline(always)]
pub fn mstrst(&mut self) -> MSTRST_W {
MSTRST_W { w: self }
}
#[doc = "Bit 0 - SW"]
#[inline(always)]
pub fn sw(&mut self) -> SW_W {
SW_W { w: self }
}
}
|
use super::*;
pub struct RootedSlotIterator<'a> {
next_slots: Vec<u64>,
blocktree: &'a super::Blocktree,
}
impl<'a> RootedSlotIterator<'a> {
pub fn new(start_slot: u64, blocktree: &'a super::Blocktree) -> Result<Self> {
if blocktree.is_root(start_slot) {
Ok(Self {
next_slots: vec![start_slot],
blocktree,
})
} else {
Err(Error::BlocktreeError(BlocktreeError::SlotNotRooted))
}
}
}
impl<'a> Iterator for RootedSlotIterator<'a> {
type Item = (u64, super::SlotMeta);
fn next(&mut self) -> Option<Self::Item> {
// Clone b/c passing the closure to the map below requires exclusive access to
// `self`, which is borrowed here if we don't clone.
let rooted_slot = self
.next_slots
.iter()
.find(|x| self.blocktree.is_root(**x))
.cloned();
rooted_slot.map(|rooted_slot| {
let slot_meta = self
.blocktree
.meta(rooted_slot)
.expect("Database failure, couldnt fetch SlotMeta")
.expect("SlotMeta in iterator didn't exist");
self.next_slots = slot_meta.next_slots.clone();
(rooted_slot, slot_meta)
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::blockBufferPoolProcessor::tests::fill_blocktree_slot_with_ticks;
#[test]
fn test_rooted_slot_iterator() {
let blocktree_path = get_tmp_ledger_path("test_rooted_slot_iterator");
let blocktree = Blocktree::open(&blocktree_path).unwrap();
blocktree.set_root(0, 0).unwrap();
let ticks_per_slot = 5;
/*
Build a blocktree in the ledger with the following fork structure:
slot 0
|
slot 1 <-- set_root(true)
/ \
slot 2 |
/ |
slot 3 |
|
slot 4
*/
// Fork 1, ending at slot 3
let last_entry_hash = Hash::default();
let fork_point = 1;
let mut fork_hash = Hash::default();
for slot in 0..=3 {
let parent = {
if slot == 0 {
0
} else {
slot - 1
}
};
let last_entry_hash = fill_blocktree_slot_with_ticks(
&blocktree,
ticks_per_slot,
slot,
parent,
last_entry_hash,
);
if slot == fork_point {
fork_hash = last_entry_hash;
}
}
// Fork 2, ending at slot 4
let _ =
fill_blocktree_slot_with_ticks(&blocktree, ticks_per_slot, 4, fork_point, fork_hash);
// Set a root
blocktree.set_root(3, 0).unwrap();
// Trying to get an iterator on a different fork will error
assert!(RootedSlotIterator::new(4, &blocktree).is_err());
// Trying to get an iterator on any slot on the root fork should succeed
let result: Vec<_> = RootedSlotIterator::new(3, &blocktree)
.unwrap()
.into_iter()
.map(|(slot, _)| slot)
.collect();
let expected = vec![3];
assert_eq!(result, expected);
let result: Vec<_> = RootedSlotIterator::new(0, &blocktree)
.unwrap()
.into_iter()
.map(|(slot, _)| slot)
.collect();
let expected = vec![0, 1, 2, 3];
assert_eq!(result, expected);
drop(blocktree);
Blocktree::destroy(&blocktree_path).expect("Expected successful database destruction");
}
}
|
use std::io::Write;
use crate::tftp::shared::{
Deserializable, Serializable, TFTPPacket, TFTPParseError, OP_DATA, OP_LEN,
};
use super::byteorder::{ByteOrder, NetworkEndian, WriteBytesExt};
const BLK_NUM_LEN: usize = 2;
const DATA_MAX_LEN: usize = 512;
#[derive(Debug, Eq, PartialEq)]
pub struct DataPacket {
op: u16,
blk: u16,
data: Vec<u8>,
}
impl DataPacket {
pub fn new(blk: u16, data: Vec<u8>) -> Self {
DataPacket {
op: OP_DATA,
blk,
data,
}
}
pub fn blk(&self) -> u16 {
self.blk
}
pub fn data(self) -> Vec<u8> {
self.data
}
}
impl DataPacket {
fn data_length(&self) -> usize {
self.data.len()
}
}
impl Serializable for DataPacket {
fn box_serialize(self: Box<Self>) -> Vec<u8> {
self.serialize()
}
fn serialize(self) -> Vec<u8> {
let buf_len = OP_LEN + BLK_NUM_LEN + self.data_length();
let mut buf: Vec<u8> = Vec::with_capacity(buf_len);
// self.serialize_op(&mut buf);
buf.write_u16::<NetworkEndian>(self.op).unwrap();
buf.write_u16::<NetworkEndian>(self.blk).unwrap();
buf.write_all(self.data.as_slice()).unwrap();
buf
}
}
impl Deserializable for DataPacket {
fn deserialize(buf: &[u8]) -> Result<TFTPPacket, TFTPParseError> {
let op: u16 = NetworkEndian::read_u16(&buf[0..2]);
if OP_DATA != op {
return Err(TFTPParseError::new("Bad OP code!"));
}
let blk = NetworkEndian::read_u16(&buf[2..4]);
let data = &buf[4..];
if data.len() > DATA_MAX_LEN {
return Err(TFTPParseError::new("Invalid data length"));
}
let p = DataPacket::new(blk, data.to_vec());
Ok(TFTPPacket::DATA(p))
}
}
#[cfg(test)]
mod tests {
#[test]
fn serialize_data_packet() {}
#[test]
fn deserialize_data_packet() {}
#[test]
fn deserialize_error() {}
}
|
#[macro_use]
extern crate error_chain;
extern crate glib_sys as glib_ffi;
extern crate gtk_sys as ffi;
extern crate glib;
extern crate gtk;
extern crate sourceview;
extern crate syntex_syntax;
extern crate syntex_pos;
mod echain;
mod gui;
mod visitor;
mod tree_column_set_data_func_ext;
mod ast_model_extensions;
fn main() {
gui::gui_main().unwrap();
}
|
//! The `block_tree` module provides functions for parallel verification of the
//! Proof of History ledger as well as iterative read, append write, and random
//! access read to a persistent file-based ledger.
use crate::entryInfo::Entry;
use crate::expunge::{self, Session};
use crate::packet::{Blob, SharedBlob, BLOB_HEADER_SIZE};
use crate::result::{Error, Result};
#[cfg(feature = "kvstore")]
use morgan_kvstore as kvstore;
use bincode::deserialize;
use hashbrown::HashMap;
#[cfg(not(feature = "kvstore"))]
use rocksdb;
use morgan_metricbot::{datapoint_error, datapoint_info};
use morgan_interface::genesis_block::GenesisBlock;
use morgan_interface::hash::Hash;
use morgan_interface::signature::{Keypair, KeypairUtil};
use morgan_helper::logHelper::*;
use std::borrow::{Borrow, Cow};
use std::cell::RefCell;
use std::cmp;
use std::fs;
use std::io;
use std::rc::Rc;
use std::sync::mpsc::{sync_channel, Receiver, SyncSender, TrySendError};
use std::sync::{Arc, RwLock};
pub use self::meta::*;
pub use self::rooted_slot_iterator::*;
mod db;
mod meta;
mod rooted_slot_iterator;
macro_rules! db_imports {
{ $mod:ident, $db:ident, $db_path:expr } => {
mod $mod;
use $mod::$db;
use db::columns as cf;
pub use db::columns;
pub type Database = db::Database<$db>;
pub type Cursor<C> = db::Cursor<$db, C>;
pub type LedgerColumn<C> = db::LedgerColumn<$db, C>;
pub type WriteBatch = db::WriteBatch<$db>;
type BatchProcessor = db::BatchProcessor<$db>;
pub trait Column: db::Column<$db> {}
impl<C: db::Column<$db>> Column for C {}
pub const BLOCKTREE_DIRECTORY: &str = $db_path;
};
}
#[cfg(not(feature = "kvstore"))]
db_imports! {rocks, Rocks, "rocksdb"}
#[cfg(feature = "kvstore")]
db_imports! {kvs, Kvs, "kvstore"}
pub const MAX_COMPLETED_SLOTS_IN_CHANNEL: usize = 100_000;
pub type CompletedSlotsReceiver = Receiver<Vec<u64>>;
#[derive(Debug)]
pub enum BlocktreeError {
BlobForIndexExists,
InvalidBlobData,
RocksDb(rocksdb::Error),
#[cfg(feature = "kvstore")]
KvsDb(kvstore::Error),
SlotNotRooted,
}
// ledger window
pub struct Blocktree {
db: Arc<Database>,
meta_cf: LedgerColumn<cf::SlotMeta>,
data_cf: LedgerColumn<cf::Data>,
erasure_cf: LedgerColumn<cf::Coding>,
erasure_meta_cf: LedgerColumn<cf::ErasureMeta>,
orphans_cf: LedgerColumn<cf::Orphans>,
batch_processor: Arc<RwLock<BatchProcessor>>,
session: Arc<expunge::Session>,
pub new_blobs_signals: Vec<SyncSender<bool>>,
pub completed_slots_senders: Vec<SyncSender<Vec<u64>>>,
}
// Column family for metadata about a leader slot
pub const META_CF: &str = "meta";
// Column family for the data in a leader slot
pub const DATA_CF: &str = "data";
// Column family for erasure data
pub const ERASURE_CF: &str = "erasure";
pub const ERASURE_META_CF: &str = "erasure_meta";
// Column family for orphans data
pub const ORPHANS_CF: &str = "orphans";
// Column family for root data
pub const ROOT_CF: &str = "root";
impl Blocktree {
/// Opens a Ledger in directory, provides "infinite" window of blobs
pub fn open(ledger_path: &str) -> Result<Blocktree> {
use std::path::Path;
fs::create_dir_all(&ledger_path)?;
let ledger_path = Path::new(&ledger_path).join(BLOCKTREE_DIRECTORY);
// Open the database
let db = Database::open(&ledger_path)?;
let batch_processor = unsafe { Arc::new(RwLock::new(db.batch_processor())) };
// Create the metadata column family
let meta_cf = db.column();
// Create the data column family
let data_cf = db.column();
// Create the erasure column family
let erasure_cf = db.column();
let erasure_meta_cf = db.column();
// Create the orphans column family. An "orphan" is defined as
// the head of a detached chain of slots, i.e. a slot with no
// known parent
let orphans_cf = db.column();
// setup erasure
let session = Arc::new(expunge::Session::default());
let db = Arc::new(db);
Ok(Blocktree {
db,
meta_cf,
data_cf,
erasure_cf,
erasure_meta_cf,
orphans_cf,
session,
new_blobs_signals: vec![],
batch_processor,
completed_slots_senders: vec![],
})
}
pub fn open_with_signal(
ledger_path: &str,
) -> Result<(Self, Receiver<bool>, CompletedSlotsReceiver)> {
let mut blocktree = Self::open(ledger_path)?;
let (signal_sender, signal_receiver) = sync_channel(1);
let (completed_slots_sender, completed_slots_receiver) =
sync_channel(MAX_COMPLETED_SLOTS_IN_CHANNEL);
blocktree.new_blobs_signals = vec![signal_sender];
blocktree.completed_slots_senders = vec![completed_slots_sender];
Ok((blocktree, signal_receiver, completed_slots_receiver))
}
pub fn destroy(ledger_path: &str) -> Result<()> {
// Database::destroy() fails is the path doesn't exist
fs::create_dir_all(ledger_path)?;
let path = std::path::Path::new(ledger_path).join(BLOCKTREE_DIRECTORY);
Database::destroy(&path)
}
pub fn meta(&self, slot: u64) -> Result<Option<SlotMeta>> {
self.meta_cf.get(slot)
}
pub fn erasure_meta(&self, slot: u64, set_index: u64) -> Result<Option<ErasureMeta>> {
self.erasure_meta_cf.get((slot, set_index))
}
pub fn orphan(&self, slot: u64) -> Result<Option<bool>> {
self.orphans_cf.get(slot)
}
pub fn rooted_slot_iterator<'a>(&'a self, slot: u64) -> Result<RootedSlotIterator<'a>> {
RootedSlotIterator::new(slot, self)
}
pub fn slot_meta_iterator(&self, slot: u64) -> Result<impl Iterator<Item = (u64, SlotMeta)>> {
let meta_iter = self.db.iter::<cf::SlotMeta>(Some(slot))?;
Ok(meta_iter.map(|(slot, slot_meta_bytes)| {
(
slot,
deserialize(&slot_meta_bytes)
.unwrap_or_else(|_| panic!("Could not deserialize SlotMeta for slot {}", slot)),
)
}))
}
pub fn slot_data_iterator(
&self,
slot: u64,
) -> Result<impl Iterator<Item = ((u64, u64), Box<[u8]>)>> {
let slot_iterator = self.db.iter::<cf::Data>(Some((slot, 0)))?;
Ok(slot_iterator.take_while(move |((blob_slot, _), _)| *blob_slot == slot))
}
pub fn write_shared_blobs<I>(&self, shared_blobs: I) -> Result<()>
where
I: IntoIterator,
I::Item: Borrow<SharedBlob>,
{
let c_blobs: Vec<_> = shared_blobs
.into_iter()
.map(move |s| s.borrow().clone())
.collect();
let r_blobs: Vec<_> = c_blobs.iter().map(move |b| b.read().unwrap()).collect();
let blobs = r_blobs.iter().map(|s| &**s);
self.insert_data_blobs(blobs)
}
pub fn write_blobs<I>(&self, blobs: I) -> Result<()>
where
I: IntoIterator,
I::Item: Borrow<Blob>,
{
self.insert_data_blobs(blobs)
}
pub fn write_entries<I>(
&self,
start_slot: u64,
num_ticks_in_start_slot: u64,
start_index: u64,
ticks_per_slot: u64,
entries: I,
) -> Result<()>
where
I: IntoIterator,
I::Item: Borrow<Entry>,
{
assert!(num_ticks_in_start_slot < ticks_per_slot);
let mut remaining_ticks_in_slot = ticks_per_slot - num_ticks_in_start_slot;
let mut blobs = vec![];
let mut current_index = start_index;
let mut current_slot = start_slot;
let mut parent_slot = {
if current_slot == 0 {
current_slot
} else {
current_slot - 1
}
};
// Find all the entries for start_slot
for entry in entries {
if remaining_ticks_in_slot == 0 {
current_slot += 1;
current_index = 0;
parent_slot = current_slot - 1;
remaining_ticks_in_slot = ticks_per_slot;
}
let mut b = entry.borrow().to_blob();
if entry.borrow().is_tick() {
remaining_ticks_in_slot -= 1;
if remaining_ticks_in_slot == 0 {
b.set_is_last_in_slot();
}
}
b.set_index(current_index);
b.set_slot(current_slot);
b.set_parent(parent_slot);
blobs.push(b);
current_index += 1;
}
self.write_blobs(&blobs)
}
pub fn insert_data_blobs<I>(&self, new_blobs: I) -> Result<()>
where
I: IntoIterator,
I::Item: Borrow<Blob>,
{
let db = &*self.db;
let mut batch_processor = self.batch_processor.write().unwrap();
let mut write_batch = batch_processor.batch()?;
let new_blobs: Vec<_> = new_blobs.into_iter().collect();
let mut recovered_data = vec![];
let mut prev_inserted_blob_datas = HashMap::new();
// A map from slot to a 2-tuple of metadata: (working copy, backup copy),
// so we can detect changes to the slot metadata later
let mut slot_meta_working_set = HashMap::new();
let mut erasure_meta_working_set = HashMap::new();
for blob in new_blobs.iter() {
let blob = blob.borrow();
let blob_slot = blob.slot();
let set_index = ErasureMeta::set_index_for(blob.index());
erasure_meta_working_set
.entry((blob_slot, set_index))
.or_insert_with(|| {
self.erasure_meta_cf
.get((blob_slot, set_index))
.expect("Expect database get to succeed")
.unwrap_or_else(|| ErasureMeta::new(set_index))
});
}
insert_data_blob_batch(
new_blobs.iter().map(Borrow::borrow),
&db,
&mut slot_meta_working_set,
&mut erasure_meta_working_set,
&mut prev_inserted_blob_datas,
&mut write_batch,
)?;
for (&(slot, _), erasure_meta) in erasure_meta_working_set.iter_mut() {
if let Some((data, coding)) = try_erasure_recover(
&db,
&self.session,
&erasure_meta,
slot,
&prev_inserted_blob_datas,
None,
)? {
for data_blob in data {
recovered_data.push(data_blob);
}
for coding_blob in coding {
erasure_meta.set_coding_present(coding_blob.index(), true);
write_batch.put_bytes::<cf::Coding>(
(coding_blob.slot(), coding_blob.index()),
&coding_blob.data[..BLOB_HEADER_SIZE + coding_blob.size()],
)?;
}
}
}
insert_data_blob_batch(
recovered_data.iter(),
&db,
&mut slot_meta_working_set,
&mut erasure_meta_working_set,
&mut prev_inserted_blob_datas,
&mut write_batch,
)?;
// Handle chaining for the working set
handle_chaining(&db, &mut write_batch, &slot_meta_working_set)?;
let mut should_signal = false;
let mut newly_completed_slots = vec![];
// Check if any metadata was changed, if so, insert the new version of the
// metadata into the write batch
for (slot, (meta, meta_backup)) in slot_meta_working_set.iter() {
let meta: &SlotMeta = &RefCell::borrow(&*meta);
if !self.completed_slots_senders.is_empty()
&& is_newly_completed_slot(meta, meta_backup)
{
newly_completed_slots.push(*slot);
}
// Check if the working copy of the metadata has changed
if Some(meta) != meta_backup.as_ref() {
should_signal = should_signal || slot_has_updates(meta, &meta_backup);
write_batch.put::<cf::SlotMeta>(*slot, &meta)?;
}
}
for ((slot, set_index), erasure_meta) in erasure_meta_working_set {
write_batch.put::<cf::ErasureMeta>((slot, set_index), &erasure_meta)?;
}
batch_processor.write(write_batch)?;
if should_signal {
for signal in &self.new_blobs_signals {
let _ = signal.try_send(true);
}
}
if !self.completed_slots_senders.is_empty() && !newly_completed_slots.is_empty() {
let mut slots: Vec<_> = (0..self.completed_slots_senders.len() - 1)
.map(|_| newly_completed_slots.clone())
.collect();
slots.push(newly_completed_slots);
for (signal, slots) in self.completed_slots_senders.iter().zip(slots.into_iter()) {
let res = signal.try_send(slots);
if let Err(TrySendError::Full(_)) = res {
datapoint_error!(
"blocktree_error",
(
"error",
"Unable to send newly completed slot because channel is full"
.to_string(),
String
),
);
}
}
}
Ok(())
}
// Fill 'buf' with num_blobs or most number of consecutive
// whole blobs that fit into buf.len()
//
// Return tuple of (number of blob read, total size of blobs read)
pub fn read_blobs_bytes(
&self,
start_index: u64,
num_blobs: u64,
buf: &mut [u8],
slot: u64,
) -> Result<(u64, u64)> {
let mut db_iterator = self.db.cursor::<cf::Data>()?;
db_iterator.seek((slot, start_index));
let mut total_blobs = 0;
let mut total_current_size = 0;
for expected_index in start_index..start_index + num_blobs {
if !db_iterator.valid() {
if expected_index == start_index {
return Err(Error::IO(io::Error::new(
io::ErrorKind::NotFound,
"Blob at start_index not found",
)));
} else {
break;
}
}
// Check key is the next sequential key based on
// blob index
let (_, index) = db_iterator.key().expect("Expected valid key");
if index != expected_index {
break;
}
// Get the blob data
let value = &db_iterator.value_bytes();
if value.is_none() {
break;
}
let value = value.as_ref().unwrap();
let blob_data_len = value.len();
if total_current_size + blob_data_len > buf.len() {
break;
}
buf[total_current_size..total_current_size + value.len()].copy_from_slice(value);
total_current_size += blob_data_len;
total_blobs += 1;
// TODO: Change this logic to support looking for data
// that spans multiple leader slots, once we support
// a window that knows about different leader slots
db_iterator.next();
}
Ok((total_blobs, total_current_size as u64))
}
pub fn get_coding_blob_bytes(&self, slot: u64, index: u64) -> Result<Option<Vec<u8>>> {
self.erasure_cf.get_bytes((slot, index))
}
pub fn delete_coding_blob(&self, slot: u64, index: u64) -> Result<()> {
let set_index = ErasureMeta::set_index_for(index);
let mut batch_processor = self.batch_processor.write().unwrap();
let mut erasure_meta = self
.erasure_meta_cf
.get((slot, set_index))?
.unwrap_or_else(|| ErasureMeta::new(set_index));
erasure_meta.set_coding_present(index, false);
let mut batch = batch_processor.batch()?;
batch.delete::<cf::Coding>((slot, index))?;
batch.put::<cf::ErasureMeta>((slot, set_index), &erasure_meta)?;
batch_processor.write(batch)?;
Ok(())
}
pub fn get_data_blob_bytes(&self, slot: u64, index: u64) -> Result<Option<Vec<u8>>> {
self.data_cf.get_bytes((slot, index))
}
/// For benchmarks, testing, and setup.
/// Does no metadata tracking. Use with care.
pub fn put_data_blob_bytes(&self, slot: u64, index: u64, bytes: &[u8]) -> Result<()> {
self.data_cf.put_bytes((slot, index), bytes)
}
/// For benchmarks, testing, and setup.
/// Does no metadata tracking. Use with care.
pub fn put_coding_blob_bytes_raw(&self, slot: u64, index: u64, bytes: &[u8]) -> Result<()> {
self.erasure_cf.put_bytes((slot, index), bytes)
}
/// this function will insert coding blobs and also automatically track erasure-related
/// metadata. If recovery is available it will be done
pub fn put_coding_blob_bytes(&self, slot: u64, index: u64, bytes: &[u8]) -> Result<()> {
let set_index = ErasureMeta::set_index_for(index);
let mut batch_processor = self.batch_processor.write().unwrap();
let mut erasure_meta = self
.erasure_meta_cf
.get((slot, set_index))?
.unwrap_or_else(|| ErasureMeta::new(set_index));
erasure_meta.set_coding_present(index, true);
erasure_meta.set_size(bytes.len() - BLOB_HEADER_SIZE);
let mut writebatch = batch_processor.batch()?;
writebatch.put_bytes::<cf::Coding>((slot, index), bytes)?;
let recovered_data = {
if let Some((data, coding)) = try_erasure_recover(
&self.db,
&self.session,
&erasure_meta,
slot,
&HashMap::new(),
Some((index, bytes)),
)? {
let mut erasure_meta_working_set = HashMap::new();
erasure_meta_working_set.insert((slot, set_index), erasure_meta);
erasure_meta = *erasure_meta_working_set.values().next().unwrap();
for coding_blob in coding {
erasure_meta.set_coding_present(coding_blob.index(), true);
writebatch.put_bytes::<cf::Coding>(
(coding_blob.slot(), coding_blob.index()),
&coding_blob.data[..BLOB_HEADER_SIZE + coding_blob.size()],
)?;
}
Some(data)
} else {
None
}
};
writebatch.put::<cf::ErasureMeta>((slot, set_index), &erasure_meta)?;
batch_processor.write(writebatch)?;
drop(batch_processor);
if let Some(data) = recovered_data {
if !data.is_empty() {
self.insert_data_blobs(&data)?;
}
}
Ok(())
}
pub fn put_many_coding_blob_bytes(&self, coding_blobs: &[SharedBlob]) -> Result<()> {
for shared_coding_blob in coding_blobs {
let blob = shared_coding_blob.read().unwrap();
assert!(blob.is_coding());
let size = blob.size() + BLOB_HEADER_SIZE;
self.put_coding_blob_bytes(blob.slot(), blob.index(), &blob.data[..size])?
}
Ok(())
}
pub fn get_data_blob(&self, slot: u64, blob_index: u64) -> Result<Option<Blob>> {
let bytes = self.get_data_blob_bytes(slot, blob_index)?;
Ok(bytes.map(|bytes| {
let blob = Blob::new(&bytes);
assert!(blob.slot() == slot);
assert!(blob.index() == blob_index);
blob
}))
}
pub fn get_entries_bytes(
&self,
_start_index: u64,
_num_entries: u64,
_buf: &mut [u8],
) -> io::Result<(u64, u64)> {
Err(io::Error::new(io::ErrorKind::Other, "TODO"))
}
// Given a start and end entry index, find all the missing
// indexes in the ledger in the range [start_index, end_index)
// for the slot with the specified slot
fn find_missing_indexes<C>(
db_iterator: &mut Cursor<C>,
slot: u64,
start_index: u64,
end_index: u64,
max_missing: usize,
) -> Vec<u64>
where
C: Column<Index = (u64, u64)>,
{
if start_index >= end_index || max_missing == 0 {
return vec![];
}
let mut missing_indexes = vec![];
// Seek to the first blob with index >= start_index
db_iterator.seek((slot, start_index));
// The index of the first missing blob in the slot
let mut prev_index = start_index;
'outer: loop {
if !db_iterator.valid() {
for i in prev_index..end_index {
missing_indexes.push(i);
if missing_indexes.len() == max_missing {
break;
}
}
break;
}
let (current_slot, index) = db_iterator.key().expect("Expect a valid key");
let current_index = {
if current_slot > slot {
end_index
} else {
index
}
};
let upper_index = cmp::min(current_index, end_index);
for i in prev_index..upper_index {
missing_indexes.push(i);
if missing_indexes.len() == max_missing {
break 'outer;
}
}
if current_slot > slot {
break;
}
if current_index >= end_index {
break;
}
prev_index = current_index + 1;
db_iterator.next();
}
missing_indexes
}
pub fn find_missing_data_indexes(
&self,
slot: u64,
start_index: u64,
end_index: u64,
max_missing: usize,
) -> Vec<u64> {
if let Ok(mut db_iterator) = self.db.cursor::<cf::Data>() {
Self::find_missing_indexes(&mut db_iterator, slot, start_index, end_index, max_missing)
} else {
vec![]
}
}
/// Returns the entry vector for the slot starting with `blob_start_index`
pub fn get_slot_entries(
&self,
slot: u64,
blob_start_index: u64,
max_entries: Option<u64>,
) -> Result<Vec<Entry>> {
self.get_slot_entries_with_blob_count(slot, blob_start_index, max_entries)
.map(|x| x.0)
}
pub fn read_ledger_blobs(&self) -> impl Iterator<Item = Blob> + '_ {
let iter = self.db.iter::<cf::Data>(None).unwrap();
iter.map(|(_, blob_data)| Blob::new(&blob_data))
}
/// Return an iterator for all the entries in the given file.
pub fn read_ledger(&self) -> Result<impl Iterator<Item = Entry>> {
use crate::entryInfo::EntrySlice;
use std::collections::VecDeque;
struct EntryIterator {
db_iterator: Cursor<cf::Data>,
// TODO: remove me when replay_stage is iterating by block (Blocktree)
// this verification is duplicating that of replay_stage, which
// can do this in parallel
blockhash: Option<Hash>,
// https://github.com/rust-rocksdb/rust-rocksdb/issues/234
// rocksdb issue: the _blocktree member must be lower in the struct to prevent a crash
// when the db_iterator member above is dropped.
// _blocktree is unused, but dropping _blocktree results in a broken db_iterator
// you have to hold the database open in order to iterate over it, and in order
// for db_iterator to be able to run Drop
// _blocktree: Blocktree,
entries: VecDeque<Entry>,
}
impl Iterator for EntryIterator {
type Item = Entry;
fn next(&mut self) -> Option<Entry> {
if !self.entries.is_empty() {
return Some(self.entries.pop_front().unwrap());
}
if self.db_iterator.valid() {
if let Some(value) = self.db_iterator.value_bytes() {
if let Ok(next_entries) =
deserialize::<Vec<Entry>>(&value[BLOB_HEADER_SIZE..])
{
if let Some(blockhash) = self.blockhash {
if !next_entries.verify(&blockhash) {
return None;
}
}
self.db_iterator.next();
if next_entries.is_empty() {
return None;
}
self.entries = VecDeque::from(next_entries);
let entry = self.entries.pop_front().unwrap();
self.blockhash = Some(entry.hash);
return Some(entry);
}
}
}
None
}
}
let mut db_iterator = self.db.cursor::<cf::Data>()?;
db_iterator.seek_to_first();
Ok(EntryIterator {
entries: VecDeque::new(),
db_iterator,
blockhash: None,
})
}
pub fn get_slot_entries_with_blob_count(
&self,
slot: u64,
blob_start_index: u64,
max_entries: Option<u64>,
) -> Result<(Vec<Entry>, usize)> {
// Find the next consecutive block of blobs.
let consecutive_blobs = get_slot_consecutive_blobs(
slot,
&self.db,
&HashMap::new(),
blob_start_index,
max_entries,
)?;
let num = consecutive_blobs.len();
Ok((deserialize_blobs(&consecutive_blobs), num))
}
// Returns slots connecting to any element of the list `slots`.
pub fn get_slots_since(&self, slots: &[u64]) -> Result<HashMap<u64, Vec<u64>>> {
// Return error if there was a database error during lookup of any of the
// slot indexes
let slot_metas: Result<Vec<Option<SlotMeta>>> =
slots.iter().map(|slot| self.meta(*slot)).collect();
let slot_metas = slot_metas?;
let result: HashMap<u64, Vec<u64>> = slots
.iter()
.zip(slot_metas)
.filter_map(|(height, meta)| meta.map(|meta| (*height, meta.next_slots)))
.collect();
Ok(result)
}
pub fn deserialize_blob_data(data: &[u8]) -> Result<Vec<Entry>> {
let entries = deserialize(data)?;
Ok(entries)
}
pub fn is_root(&self, slot: u64) -> bool {
if let Ok(Some(true)) = self.db.get::<cf::Root>(slot) {
true
} else {
false
}
}
pub fn set_root(&self, new_root: u64, prev_root: u64) -> Result<()> {
let mut current_slot = new_root;
unsafe {
let mut batch_processor = self.db.batch_processor();
let mut write_batch = batch_processor.batch()?;
if new_root == 0 {
write_batch.put::<cf::Root>(0, &true)?;
} else {
while current_slot != prev_root {
write_batch.put::<cf::Root>(current_slot, &true)?;
current_slot = self.meta(current_slot).unwrap().unwrap().parent_slot;
}
}
batch_processor.write(write_batch)?;
}
Ok(())
}
pub fn get_orphans(&self, max: Option<usize>) -> Vec<u64> {
let mut results = vec![];
let mut iter = self.db.cursor::<cf::Orphans>().unwrap();
iter.seek_to_first();
while iter.valid() {
if let Some(max) = max {
if results.len() > max {
break;
}
}
results.push(iter.key().unwrap());
iter.next();
}
results
}
// Handle special case of writing genesis blobs. For instance, the first two entries
// don't count as ticks, even if they're empty entries
fn write_genesis_blobs(&self, blobs: &[Blob]) -> Result<()> {
// TODO: change bootstrap height to number of slots
let mut bootstrap_meta = SlotMeta::new(0, 1);
let last = blobs.last().unwrap();
let mut batch_processor = self.batch_processor.write().unwrap();
bootstrap_meta.consumed = last.index() + 1;
bootstrap_meta.received = last.index() + 1;
bootstrap_meta.is_connected = true;
let mut batch = batch_processor.batch()?;
batch.put::<cf::SlotMeta>(0, &bootstrap_meta)?;
for blob in blobs {
let serialized_blob_datas = &blob.data[..BLOB_HEADER_SIZE + blob.size()];
batch.put_bytes::<cf::Data>((blob.slot(), blob.index()), serialized_blob_datas)?;
}
batch_processor.write(batch)?;
Ok(())
}
}
fn insert_data_blob_batch<'a, I>(
new_blobs: I,
db: &Database,
slot_meta_working_set: &mut HashMap<u64, (Rc<RefCell<SlotMeta>>, Option<SlotMeta>)>,
erasure_meta_working_set: &mut HashMap<(u64, u64), ErasureMeta>,
prev_inserted_blob_datas: &mut HashMap<(u64, u64), &'a [u8]>,
write_batch: &mut WriteBatch,
) -> Result<()>
where
I: IntoIterator<Item = &'a Blob>,
{
for blob in new_blobs.into_iter() {
let inserted = check_insert_data_blob(
blob,
db,
slot_meta_working_set,
prev_inserted_blob_datas,
write_batch,
);
if inserted {
erasure_meta_working_set
.get_mut(&(blob.slot(), ErasureMeta::set_index_for(blob.index())))
.unwrap()
.set_data_present(blob.index(), true);
}
}
Ok(())
}
/// Insert a blob into ledger, updating the slot_meta if necessary
fn insert_data_blob<'a>(
blob_to_insert: &'a Blob,
db: &Database,
prev_inserted_blob_datas: &mut HashMap<(u64, u64), &'a [u8]>,
slot_meta: &mut SlotMeta,
write_batch: &mut WriteBatch,
) -> Result<()> {
let blob_index = blob_to_insert.index();
let blob_slot = blob_to_insert.slot();
let blob_size = blob_to_insert.size();
let new_consumed = {
if slot_meta.consumed == blob_index {
let blob_datas = get_slot_consecutive_blobs(
blob_slot,
db,
prev_inserted_blob_datas,
// Don't start looking for consecutive blobs at blob_index,
// because we haven't inserted/committed the new blob_to_insert
// into the database or prev_inserted_blob_datas hashmap yet.
blob_index + 1,
None,
)?;
// Add one because we skipped this current blob when calling
// get_slot_consecutive_blobs() earlier
slot_meta.consumed + blob_datas.len() as u64 + 1
} else {
slot_meta.consumed
}
};
let serialized_blob_data = &blob_to_insert.data[..BLOB_HEADER_SIZE + blob_size];
// Commit step: commit all changes to the mutable structures at once, or none at all.
// We don't want only some of these changes going through.
write_batch.put_bytes::<cf::Data>((blob_slot, blob_index), serialized_blob_data)?;
prev_inserted_blob_datas.insert((blob_slot, blob_index), serialized_blob_data);
// Index is zero-indexed, while the "received" height starts from 1,
// so received = index + 1 for the same blob.
slot_meta.received = cmp::max(blob_index + 1, slot_meta.received);
slot_meta.consumed = new_consumed;
slot_meta.last_index = {
// If the last index in the slot hasn't been set before, then
// set it to this blob index
if slot_meta.last_index == std::u64::MAX {
if blob_to_insert.is_last_in_slot() {
blob_index
} else {
std::u64::MAX
}
} else {
slot_meta.last_index
}
};
Ok(())
}
/// Checks to see if the data blob passes integrity checks for insertion. Proceeds with
/// insertion if it does.
fn check_insert_data_blob<'a>(
blob: &'a Blob,
db: &Database,
slot_meta_working_set: &mut HashMap<u64, (Rc<RefCell<SlotMeta>>, Option<SlotMeta>)>,
prev_inserted_blob_datas: &mut HashMap<(u64, u64), &'a [u8]>,
write_batch: &mut WriteBatch,
) -> bool {
let blob_slot = blob.slot();
let parent_slot = blob.parent();
let meta_cf = db.column::<cf::SlotMeta>();
// Check if we've already inserted the slot metadata for this blob's slot
let entry = slot_meta_working_set.entry(blob_slot).or_insert_with(|| {
// Store a 2-tuple of the metadata (working copy, backup copy)
if let Some(mut meta) = meta_cf
.get(blob_slot)
.expect("Expect database get to succeed")
{
let backup = Some(meta.clone());
// If parent_slot == std::u64::MAX, then this is one of the orphans inserted
// during the chaining process, see the function find_slot_meta_in_cached_state()
// for details. Slots that are orphans are missing a parent_slot, so we should
// fill in the parent now that we know it.
if is_orphan(&meta) {
meta.parent_slot = parent_slot;
}
(Rc::new(RefCell::new(meta)), backup)
} else {
(
Rc::new(RefCell::new(SlotMeta::new(blob_slot, parent_slot))),
None,
)
}
});
let slot_meta = &mut entry.0.borrow_mut();
// This slot is full, skip the bogus blob
// Check if this blob should be inserted
if !should_insert_blob(&slot_meta, db, &prev_inserted_blob_datas, blob) {
false
} else {
let _ = insert_data_blob(blob, db, prev_inserted_blob_datas, slot_meta, write_batch);
true
}
}
fn should_insert_blob(
slot: &SlotMeta,
db: &Database,
prev_inserted_blob_datas: &HashMap<(u64, u64), &[u8]>,
blob: &Blob,
) -> bool {
let blob_index = blob.index();
let blob_slot = blob.slot();
let data_cf = db.column::<cf::Data>();
// Check that the blob doesn't already exist
if blob_index < slot.consumed
|| prev_inserted_blob_datas.contains_key(&(blob_slot, blob_index))
|| data_cf
.get_bytes((blob_slot, blob_index))
.map(|opt| opt.is_some())
.unwrap_or(false)
{
return false;
}
// Check that we do not receive blobs >= than the last_index
// for the slot
let last_index = slot.last_index;
if blob_index >= last_index {
datapoint_error!(
"blocktree_error",
(
"error",
format!(
"Received last blob with index {} >= slot.last_index {}",
blob_index, last_index
),
String
)
);
return false;
}
// Check that we do not receive a blob with "last_index" true, but index
// less than our current received
if blob.is_last_in_slot() && blob_index < slot.received {
datapoint_error!(
"blocktree_error",
(
"error",
format!(
"Received last blob with index {} < slot.received {}",
blob_index, slot.received
),
String
)
);
return false;
}
true
}
// 1) Find the slot metadata in the cache of dirty slot metadata we've previously touched,
// else:
// 2) Search the database for that slot metadata. If still no luck, then:
// 3) Create a dummy orphan slot in the database
fn find_slot_meta_else_create<'a>(
db: &Database,
working_set: &'a HashMap<u64, (Rc<RefCell<SlotMeta>>, Option<SlotMeta>)>,
chained_slots: &'a mut HashMap<u64, Rc<RefCell<SlotMeta>>>,
slot_index: u64,
) -> Result<Rc<RefCell<SlotMeta>>> {
let result = find_slot_meta_in_cached_state(working_set, chained_slots, slot_index)?;
if let Some(slot) = result {
Ok(slot)
} else {
find_slot_meta_in_db_else_create(db, slot_index, chained_slots)
}
}
// Search the database for that slot metadata. If still no luck, then
// create a dummy orphan slot in the database
fn find_slot_meta_in_db_else_create<'a>(
db: &Database,
slot: u64,
insert_map: &'a mut HashMap<u64, Rc<RefCell<SlotMeta>>>,
) -> Result<Rc<RefCell<SlotMeta>>> {
if let Some(slot_meta) = db.column::<cf::SlotMeta>().get(slot)? {
insert_map.insert(slot, Rc::new(RefCell::new(slot_meta)));
Ok(insert_map.get(&slot).unwrap().clone())
} else {
// If this slot doesn't exist, make a orphan slot. This way we
// remember which slots chained to this one when we eventually get a real blob
// for this slot
insert_map.insert(
slot,
Rc::new(RefCell::new(SlotMeta::new(slot, std::u64::MAX))),
);
Ok(insert_map.get(&slot).unwrap().clone())
}
}
// Find the slot metadata in the cache of dirty slot metadata we've previously touched
fn find_slot_meta_in_cached_state<'a>(
working_set: &'a HashMap<u64, (Rc<RefCell<SlotMeta>>, Option<SlotMeta>)>,
chained_slots: &'a HashMap<u64, Rc<RefCell<SlotMeta>>>,
slot: u64,
) -> Result<Option<Rc<RefCell<SlotMeta>>>> {
if let Some((entry, _)) = working_set.get(&slot) {
Ok(Some(entry.clone()))
} else if let Some(entry) = chained_slots.get(&slot) {
Ok(Some(entry.clone()))
} else {
Ok(None)
}
}
/// Returns the next consumed index and the number of ticks in the new consumed
/// range
fn get_slot_consecutive_blobs<'a>(
slot: u64,
db: &Database,
prev_inserted_blob_datas: &HashMap<(u64, u64), &'a [u8]>,
mut current_index: u64,
max_blobs: Option<u64>,
) -> Result<Vec<Cow<'a, [u8]>>> {
let mut blobs: Vec<Cow<[u8]>> = vec![];
let data_cf = db.column::<cf::Data>();
loop {
if Some(blobs.len() as u64) == max_blobs {
break;
}
// Try to find the next blob we're looking for in the prev_inserted_blob_datas
if let Some(prev_blob_data) = prev_inserted_blob_datas.get(&(slot, current_index)) {
blobs.push(Cow::Borrowed(*prev_blob_data));
} else if let Some(blob_data) = data_cf.get_bytes((slot, current_index))? {
// Try to find the next blob we're looking for in the database
blobs.push(Cow::Owned(blob_data));
} else {
break;
}
current_index += 1;
}
Ok(blobs)
}
// Chaining based on latest discussion here: https://github.com/morgan-labs/morgan/pull/2253
fn handle_chaining(
db: &Database,
write_batch: &mut WriteBatch,
working_set: &HashMap<u64, (Rc<RefCell<SlotMeta>>, Option<SlotMeta>)>,
) -> Result<()> {
let mut new_chained_slots = HashMap::new();
let working_set_slots: Vec<_> = working_set.iter().map(|s| *s.0).collect();
for slot in working_set_slots {
handle_chaining_for_slot(db, write_batch, working_set, &mut new_chained_slots, slot)?;
}
// Write all the newly changed slots in new_chained_slots to the write_batch
for (slot, meta) in new_chained_slots.iter() {
let meta: &SlotMeta = &RefCell::borrow(&*meta);
write_batch.put::<cf::SlotMeta>(*slot, meta)?;
}
Ok(())
}
fn handle_chaining_for_slot(
db: &Database,
write_batch: &mut WriteBatch,
working_set: &HashMap<u64, (Rc<RefCell<SlotMeta>>, Option<SlotMeta>)>,
new_chained_slots: &mut HashMap<u64, Rc<RefCell<SlotMeta>>>,
slot: u64,
) -> Result<()> {
let (meta, meta_backup) = working_set
.get(&slot)
.expect("Slot must exist in the working_set hashmap");
{
let mut meta_mut = meta.borrow_mut();
let was_orphan_slot = meta_backup.is_some() && is_orphan(meta_backup.as_ref().unwrap());
// If:
// 1) This is a new slot
// 2) slot != 0
// then try to chain this slot to a previous slot
if slot != 0 {
let prev_slot = meta_mut.parent_slot;
// Check if the slot represented by meta_mut is either a new slot or a orphan.
// In both cases we need to run the chaining logic b/c the parent on the slot was
// previously unknown.
if meta_backup.is_none() || was_orphan_slot {
let prev_slot_meta =
find_slot_meta_else_create(db, working_set, new_chained_slots, prev_slot)?;
// This is a newly inserted slot/orphan so run the chaining logic to link it to a
// newly discovered parent
chain_new_slot_to_prev_slot(&mut prev_slot_meta.borrow_mut(), slot, &mut meta_mut);
// If the parent of `slot` is a newly inserted orphan, insert it into the orphans
// column family
if is_orphan(&RefCell::borrow(&*prev_slot_meta)) {
write_batch.put::<cf::Orphans>(prev_slot, &true)?;
}
}
}
// At this point this slot has received a parent, so it's no longer an orphan
if was_orphan_slot {
write_batch.delete::<cf::Orphans>(slot)?;
}
}
// If this is a newly inserted slot, then we know the children of this slot were not previously
// connected to the trunk of the ledger. Thus if slot.is_connected is now true, we need to
// update all child slots with `is_connected` = true because these children are also now newly
// connected to to trunk of the the ledger
let should_propagate_is_connected =
is_newly_completed_slot(&RefCell::borrow(&*meta), meta_backup)
&& RefCell::borrow(&*meta).is_connected;
if should_propagate_is_connected {
// slot_function returns a boolean indicating whether to explore the children
// of the input slot
let slot_function = |slot: &mut SlotMeta| {
slot.is_connected = true;
// We don't want to set the is_connected flag on the children of non-full
// slots
slot.is_full()
};
traverse_children_mut(
db,
slot,
&meta,
working_set,
new_chained_slots,
slot_function,
)?;
}
Ok(())
}
fn traverse_children_mut<F>(
db: &Database,
slot: u64,
slot_meta: &Rc<RefCell<(SlotMeta)>>,
working_set: &HashMap<u64, (Rc<RefCell<SlotMeta>>, Option<SlotMeta>)>,
new_chained_slots: &mut HashMap<u64, Rc<RefCell<SlotMeta>>>,
slot_function: F,
) -> Result<()>
where
F: Fn(&mut SlotMeta) -> bool,
{
let mut next_slots: Vec<(u64, Rc<RefCell<(SlotMeta)>>)> = vec![(slot, slot_meta.clone())];
while !next_slots.is_empty() {
let (_, current_slot) = next_slots.pop().unwrap();
// Check whether we should explore the children of this slot
if slot_function(&mut current_slot.borrow_mut()) {
let current_slot = &RefCell::borrow(&*current_slot);
for next_slot_index in current_slot.next_slots.iter() {
let next_slot = find_slot_meta_else_create(
db,
working_set,
new_chained_slots,
*next_slot_index,
)?;
next_slots.push((*next_slot_index, next_slot));
}
}
}
Ok(())
}
fn is_orphan(meta: &SlotMeta) -> bool {
// If we have no parent, then this is the head of a detached chain of
// slots
!meta.is_parent_set()
}
// 1) Chain current_slot to the previous slot defined by prev_slot_meta
// 2) Determine whether to set the is_connected flag
fn chain_new_slot_to_prev_slot(
prev_slot_meta: &mut SlotMeta,
current_slot: u64,
current_slot_meta: &mut SlotMeta,
) {
prev_slot_meta.next_slots.push(current_slot);
current_slot_meta.is_connected = prev_slot_meta.is_connected && prev_slot_meta.is_full();
}
fn is_newly_completed_slot(slot_meta: &SlotMeta, backup_slot_meta: &Option<SlotMeta>) -> bool {
slot_meta.is_full()
&& (backup_slot_meta.is_none()
|| slot_meta.consumed != backup_slot_meta.as_ref().unwrap().consumed)
}
/// Attempts recovery using erasure coding
fn try_erasure_recover(
db: &Database,
session: &Session,
erasure_meta: &ErasureMeta,
slot: u64,
prev_inserted_blob_datas: &HashMap<(u64, u64), &[u8]>,
new_coding_blob: Option<(u64, &[u8])>,
) -> Result<Option<(Vec<Blob>, Vec<Blob>)>> {
use crate::expunge::ERASURE_SET_SIZE;
let set_index = erasure_meta.set_index;
let start_index = erasure_meta.start_index();
let (data_end_index, _) = erasure_meta.end_indexes();
let submit_metrics = |attempted: bool, status: String| {
datapoint_info!(
"blocktree-erasure",
("slot", slot as i64, i64),
("start_index", start_index as i64, i64),
("end_index", data_end_index as i64, i64),
("recovery_attempted", attempted, bool),
("recovery_status", status, String),
);
};
let blobs = match erasure_meta.status() {
ErasureMetaStatus::CanRecover => {
let erasure_result = recover(
db,
session,
slot,
erasure_meta,
prev_inserted_blob_datas,
new_coding_blob,
);
match erasure_result {
Ok((data, coding)) => {
let recovered = data.len() + coding.len();
assert_eq!(
ERASURE_SET_SIZE,
recovered + (erasure_meta.num_coding() + erasure_meta.num_data()) as usize,
"Recovery should always complete a set"
);
submit_metrics(true, "complete".into());
debug!(
"[try_erasure] slot: {}, set_index: {}, recovered {} blobs",
slot, set_index, recovered
);
Some((data, coding))
}
Err(Error::ErasureError(e)) => {
submit_metrics(true, format!("error: {}", e));
// error!(
// "{}",
// Error(format!("[try_erasure] slot: {}, set_index: {}, recovery failed: cause: {}",
// slot, erasure_meta.set_index, e).to_string())
// );
println!(
"{}",
Error(
format!("[try_erasure] slot: {}, set_index: {}, recovery failed: cause: {}",
slot, erasure_meta.set_index, e).to_string(),
module_path!().to_string()
)
);
None
}
Err(e) => return Err(e),
}
}
ErasureMetaStatus::StillNeed(needed) => {
submit_metrics(false, format!("still need: {}", needed));
debug!(
"[try_erasure] slot: {}, set_index: {}, still need {} blobs",
slot, set_index, needed
);
None
}
ErasureMetaStatus::DataFull => {
submit_metrics(false, "complete".into());
debug!(
"[try_erasure] slot: {}, set_index: {}, set full",
slot, set_index,
);
None
}
};
Ok(blobs)
}
fn recover(
db: &Database,
session: &Session,
slot: u64,
erasure_meta: &ErasureMeta,
prev_inserted_blob_datas: &HashMap<(u64, u64), &[u8]>,
new_coding: Option<(u64, &[u8])>,
) -> Result<(Vec<Blob>, Vec<Blob>)> {
use crate::expunge::ERASURE_SET_SIZE;
let start_idx = erasure_meta.start_index();
let size = erasure_meta.size();
let data_cf = db.column::<cf::Data>();
let erasure_cf = db.column::<cf::Coding>();
let (data_end_idx, coding_end_idx) = erasure_meta.end_indexes();
let present = &mut [true; ERASURE_SET_SIZE];
let mut blobs = Vec::with_capacity(ERASURE_SET_SIZE);
for i in start_idx..coding_end_idx {
if erasure_meta.is_coding_present(i) {
let mut blob_bytes = match new_coding {
Some((new_coding_index, bytes)) if new_coding_index == i => bytes.to_vec(),
_ => erasure_cf
.get_bytes((slot, i))?
.expect("ErasureMeta must have no false positives"),
};
blob_bytes.drain(..BLOB_HEADER_SIZE);
blobs.push(blob_bytes);
} else {
let set_relative_idx = erasure_meta.coding_index_in_set(i).unwrap() as usize;
blobs.push(vec![0; size]);
present[set_relative_idx] = false;
}
}
assert_ne!(size, 0);
for i in start_idx..data_end_idx {
let set_relative_idx = erasure_meta.data_index_in_set(i).unwrap() as usize;
if erasure_meta.is_data_present(i) {
let mut blob_bytes = match prev_inserted_blob_datas.get(&(slot, i)) {
Some(bytes) => bytes.to_vec(),
None => data_cf
.get_bytes((slot, i))?
.expect("erasure_meta must have no false positives"),
};
// If data is too short, extend it with zeroes
blob_bytes.resize(size, 0u8);
blobs.insert(set_relative_idx, blob_bytes);
} else {
blobs.insert(set_relative_idx, vec![0u8; size]);
// data erasures must come before any coding erasures if present
present[set_relative_idx] = false;
}
}
let (recovered_data, recovered_coding) =
session.reconstruct_blobs(&mut blobs, present, size, start_idx, slot)?;
trace!(
"[recover] reconstruction OK slot: {}, indexes: [{},{})",
slot,
start_idx,
data_end_idx
);
Ok((recovered_data, recovered_coding))
}
fn deserialize_blobs<I>(blob_datas: &[I]) -> Vec<Entry>
where
I: Borrow<[u8]>,
{
blob_datas
.iter()
.flat_map(|blob_data| {
let serialized_entries_data = &blob_data.borrow()[BLOB_HEADER_SIZE..];
Blocktree::deserialize_blob_data(serialized_entries_data)
.expect("Ledger should only contain well formed data")
})
.collect()
}
fn slot_has_updates(slot_meta: &SlotMeta, slot_meta_backup: &Option<SlotMeta>) -> bool {
// We should signal that there are updates if we extended the chain of consecutive blocks starting
// from block 0, which is true iff:
// 1) The block with index prev_block_index is itself part of the trunk of consecutive blocks
// starting from block 0,
slot_meta.is_connected &&
// AND either:
// 1) The slot didn't exist in the database before, and now we have a consecutive
// block for that slot
((slot_meta_backup.is_none() && slot_meta.consumed != 0) ||
// OR
// 2) The slot did exist, but now we have a new consecutive block for that slot
(slot_meta_backup.is_some() && slot_meta_backup.as_ref().unwrap().consumed != slot_meta.consumed))
}
// Creates a new ledger with slot 0 full of ticks (and only ticks).
//
// Returns the blockhash that can be used to append entries with.
pub fn create_new_ledger(ledger_path: &str, genesis_block: &GenesisBlock) -> Result<Hash> {
let ticks_per_slot = genesis_block.ticks_per_slot;
Blocktree::destroy(ledger_path)?;
genesis_block.write(&ledger_path)?;
// Fill slot 0 with ticks that link back to the genesis_block to bootstrap the ledger.
let blocktree = Blocktree::open(ledger_path)?;
let entries = crate::entryInfo::create_ticks(ticks_per_slot, genesis_block.hash());
blocktree.write_entries(0, 0, 0, ticks_per_slot, &entries)?;
Ok(entries.last().unwrap().hash)
}
pub fn genesis<'a, I>(ledger_path: &str, keypair: &Keypair, entries: I) -> Result<()>
where
I: IntoIterator<Item = &'a Entry>,
{
let blocktree = Blocktree::open(ledger_path)?;
// TODO sign these blobs with keypair
let blobs: Vec<_> = entries
.into_iter()
.enumerate()
.map(|(idx, entry)| {
let mut b = entry.borrow().to_blob();
b.set_index(idx as u64);
b.set_id(&keypair.pubkey());
b.set_slot(0);
b
})
.collect();
blocktree.write_genesis_blobs(&blobs[..])?;
Ok(())
}
#[macro_export]
macro_rules! tmp_ledger_name {
() => {
&format!("{}-{}", file!(), line!())
};
}
#[macro_export]
macro_rules! get_tmp_ledger_path {
() => {
get_tmp_ledger_path(tmp_ledger_name!())
};
}
pub fn get_tmp_ledger_path(name: &str) -> String {
use std::env;
let out_dir = env::var("OUT_DIR").unwrap_or_else(|_| "target".to_string());
let keypair = Keypair::new();
let path = format!("{}/tmp/ledger/{}-{}", out_dir, name, keypair.pubkey());
// whack any possible collision
let _ignored = fs::remove_dir_all(&path);
path
}
#[macro_export]
macro_rules! create_new_tmp_ledger {
($genesis_block:expr) => {
create_new_tmp_ledger(tmp_ledger_name!(), $genesis_block)
};
}
// Same as `create_new_ledger()` but use a temporary ledger name based on the provided `name`
//
// Note: like `create_new_ledger` the returned ledger will have slot 0 full of ticks (and only
// ticks)
pub fn create_new_tmp_ledger(name: &str, genesis_block: &GenesisBlock) -> (String, Hash) {
let ledger_path = get_tmp_ledger_path(name);
let blockhash = create_new_ledger(&ledger_path, genesis_block).unwrap();
(ledger_path, blockhash)
}
#[macro_export]
macro_rules! tmp_copy_blocktree {
($from:expr) => {
tmp_copy_blocktree($from, tmp_ledger_name!())
};
}
pub fn tmp_copy_blocktree(from: &str, name: &str) -> String {
let path = get_tmp_ledger_path(name);
let blocktree = Blocktree::open(from).unwrap();
let blobs = blocktree.read_ledger_blobs();
let genesis_block = GenesisBlock::load(from).unwrap();
Blocktree::destroy(&path).expect("Expected successful database destruction");
let blocktree = Blocktree::open(&path).unwrap();
blocktree.write_blobs(blobs).unwrap();
genesis_block.write(&path).unwrap();
path
}
#[cfg(test)]
pub mod tests {
use super::*;
use crate::entryInfo::{
create_ticks, make_tiny_test_entries, make_tiny_test_entries_from_hash, Entry, EntrySlice,
};
use crate::expunge::{CodingGenerator, NUM_CODING, NUM_DATA};
use crate::packet;
use rand::seq::SliceRandom;
use rand::thread_rng;
use rand::Rng;
use morgan_interface::hash::Hash;
use morgan_interface::pubkey::Pubkey;
use std::cmp::min;
use std::collections::HashSet;
use std::iter::once;
use std::iter::FromIterator;
use std::time::Duration;
#[test]
fn test_write_entries() {
morgan_logger::setup();
let ledger_path = get_tmp_ledger_path!();
{
let ticks_per_slot = 10;
let num_slots = 10;
let num_ticks = ticks_per_slot * num_slots;
let ledger = Blocktree::open(&ledger_path).unwrap();
let ticks = create_ticks(num_ticks, Hash::default());
ledger
.write_entries(0, 0, 0, ticks_per_slot, ticks.clone())
.unwrap();
for i in 0..num_slots {
let meta = ledger.meta(i).unwrap().unwrap();
assert_eq!(meta.consumed, ticks_per_slot);
assert_eq!(meta.received, ticks_per_slot);
assert_eq!(meta.last_index, ticks_per_slot - 1);
if i == num_slots - 1 {
assert!(meta.next_slots.is_empty());
} else {
assert_eq!(meta.next_slots, vec![i + 1]);
}
if i == 0 {
assert_eq!(meta.parent_slot, 0);
} else {
assert_eq!(meta.parent_slot, i - 1);
}
assert_eq!(
&ticks[(i * ticks_per_slot) as usize..((i + 1) * ticks_per_slot) as usize],
&ledger.get_slot_entries(i, 0, None).unwrap()[..]
);
}
// Simulate writing to the end of a slot with existing ticks
ledger
.write_entries(
num_slots,
ticks_per_slot - 1,
ticks_per_slot - 2,
ticks_per_slot,
&ticks[0..2],
)
.unwrap();
let meta = ledger.meta(num_slots).unwrap().unwrap();
assert_eq!(meta.consumed, 0);
// received blob was ticks_per_slot - 2, so received should be ticks_per_slot - 2 + 1
assert_eq!(meta.received, ticks_per_slot - 1);
// last blob index ticks_per_slot - 2 because that's the blob that made tick_height == ticks_per_slot
// for the slot
assert_eq!(meta.last_index, ticks_per_slot - 2);
assert_eq!(meta.parent_slot, num_slots - 1);
assert_eq!(meta.next_slots, vec![num_slots + 1]);
assert_eq!(
&ticks[0..1],
&ledger
.get_slot_entries(num_slots, ticks_per_slot - 2, None)
.unwrap()[..]
);
// We wrote two entries, the second should spill into slot num_slots + 1
let meta = ledger.meta(num_slots + 1).unwrap().unwrap();
assert_eq!(meta.consumed, 1);
assert_eq!(meta.received, 1);
assert_eq!(meta.last_index, std::u64::MAX);
assert_eq!(meta.parent_slot, num_slots);
assert!(meta.next_slots.is_empty());
assert_eq!(
&ticks[1..2],
&ledger.get_slot_entries(num_slots + 1, 0, None).unwrap()[..]
);
}
Blocktree::destroy(&ledger_path).expect("Expected successful database destruction");
}
#[test]
fn test_put_get_simple() {
let ledger_path = get_tmp_ledger_path("test_put_get_simple");
let ledger = Blocktree::open(&ledger_path).unwrap();
// Test meta column family
let meta = SlotMeta::new(0, 1);
ledger.meta_cf.put(0, &meta).unwrap();
let result = ledger
.meta_cf
.get(0)
.unwrap()
.expect("Expected meta object to exist");
assert_eq!(result, meta);
// Test erasure column family
let erasure = vec![1u8; 16];
let erasure_key = (0, 0);
ledger.erasure_cf.put_bytes(erasure_key, &erasure).unwrap();
let result = ledger
.erasure_cf
.get_bytes(erasure_key)
.unwrap()
.expect("Expected erasure object to exist");
assert_eq!(result, erasure);
// Test data column family
let data = vec![2u8; 16];
let data_key = (0, 0);
ledger.data_cf.put_bytes(data_key, &data).unwrap();
let result = ledger
.data_cf
.get_bytes(data_key)
.unwrap()
.expect("Expected data object to exist");
assert_eq!(result, data);
// Destroying database without closing it first is undefined behavior
drop(ledger);
Blocktree::destroy(&ledger_path).expect("Expected successful database destruction");
}
#[test]
fn test_read_blobs_bytes() {
let shared_blobs = make_tiny_test_entries(10).to_single_entry_shared_blobs();
let slot = 0;
packet::index_blobs(&shared_blobs, &Pubkey::new_rand(), 0, slot, 0);
let blob_locks: Vec<_> = shared_blobs.iter().map(|b| b.read().unwrap()).collect();
let blobs: Vec<&Blob> = blob_locks.iter().map(|b| &**b).collect();
let ledger_path = get_tmp_ledger_path("test_read_blobs_bytes");
let ledger = Blocktree::open(&ledger_path).unwrap();
ledger.write_blobs(blobs.clone()).unwrap();
let mut buf = [0; 1024];
let (num_blobs, bytes) = ledger.read_blobs_bytes(0, 1, &mut buf, slot).unwrap();
let bytes = bytes as usize;
assert_eq!(num_blobs, 1);
{
let blob_data = &buf[..bytes];
assert_eq!(blob_data, &blobs[0].data[..bytes]);
}
let (num_blobs, bytes2) = ledger.read_blobs_bytes(0, 2, &mut buf, slot).unwrap();
let bytes2 = bytes2 as usize;
assert_eq!(num_blobs, 2);
assert!(bytes2 > bytes);
{
let blob_data_1 = &buf[..bytes];
assert_eq!(blob_data_1, &blobs[0].data[..bytes]);
let blob_data_2 = &buf[bytes..bytes2];
assert_eq!(blob_data_2, &blobs[1].data[..bytes2 - bytes]);
}
// buf size part-way into blob[1], should just return blob[0]
let mut buf = vec![0; bytes + 1];
let (num_blobs, bytes3) = ledger.read_blobs_bytes(0, 2, &mut buf, slot).unwrap();
assert_eq!(num_blobs, 1);
let bytes3 = bytes3 as usize;
assert_eq!(bytes3, bytes);
let mut buf = vec![0; bytes2 - 1];
let (num_blobs, bytes4) = ledger.read_blobs_bytes(0, 2, &mut buf, slot).unwrap();
assert_eq!(num_blobs, 1);
let bytes4 = bytes4 as usize;
assert_eq!(bytes4, bytes);
let mut buf = vec![0; bytes * 2];
let (num_blobs, bytes6) = ledger.read_blobs_bytes(9, 1, &mut buf, slot).unwrap();
assert_eq!(num_blobs, 1);
let bytes6 = bytes6 as usize;
{
let blob_data = &buf[..bytes6];
assert_eq!(blob_data, &blobs[9].data[..bytes6]);
}
// Read out of range
assert!(ledger.read_blobs_bytes(20, 2, &mut buf, slot).is_err());
// Destroying database without closing it first is undefined behavior
drop(ledger);
Blocktree::destroy(&ledger_path).expect("Expected successful database destruction");
}
#[test]
fn test_insert_data_blobs_basic() {
let num_entries = 5;
assert!(num_entries > 1);
let (blobs, entries) = make_slot_entries(0, 0, num_entries);
let ledger_path = get_tmp_ledger_path("test_insert_data_blobs_basic");
let ledger = Blocktree::open(&ledger_path).unwrap();
// Insert last blob, we're missing the other blobs, so no consecutive
// blobs starting from slot 0, index 0 should exist.
ledger
.insert_data_blobs(once(&blobs[num_entries as usize - 1]))
.unwrap();
assert!(ledger.get_slot_entries(0, 0, None).unwrap().is_empty());
let meta = ledger
.meta(0)
.unwrap()
.expect("Expected new metadata object to be created");
assert!(meta.consumed == 0 && meta.received == num_entries);
// Insert the other blobs, check for consecutive returned entries
ledger
.insert_data_blobs(&blobs[0..(num_entries - 1) as usize])
.unwrap();
let result = ledger.get_slot_entries(0, 0, None).unwrap();
assert_eq!(result, entries);
let meta = ledger
.meta(0)
.unwrap()
.expect("Expected new metadata object to exist");
assert_eq!(meta.consumed, num_entries);
assert_eq!(meta.received, num_entries);
assert_eq!(meta.parent_slot, 0);
assert_eq!(meta.last_index, num_entries - 1);
assert!(meta.next_slots.is_empty());
assert!(meta.is_connected);
// Destroying database without closing it first is undefined behavior
drop(ledger);
Blocktree::destroy(&ledger_path).expect("Expected successful database destruction");
}
#[test]
fn test_insert_data_blobs_reverse() {
let num_entries = 10;
let (blobs, entries) = make_slot_entries(0, 0, num_entries);
let ledger_path = get_tmp_ledger_path("test_insert_data_blobs_reverse");
let ledger = Blocktree::open(&ledger_path).unwrap();
// Insert blobs in reverse, check for consecutive returned blobs
for i in (0..num_entries).rev() {
ledger.insert_data_blobs(once(&blobs[i as usize])).unwrap();
let result = ledger.get_slot_entries(0, 0, None).unwrap();
let meta = ledger
.meta(0)
.unwrap()
.expect("Expected metadata object to exist");
assert_eq!(meta.parent_slot, 0);
assert_eq!(meta.last_index, num_entries - 1);
if i != 0 {
assert_eq!(result.len(), 0);
assert!(meta.consumed == 0 && meta.received == num_entries as u64);
} else {
assert_eq!(result, entries);
assert!(meta.consumed == num_entries as u64 && meta.received == num_entries as u64);
}
}
// Destroying database without closing it first is undefined behavior
drop(ledger);
Blocktree::destroy(&ledger_path).expect("Expected successful database destruction");
}
#[test]
fn test_insert_slots() {
test_insert_data_blobs_slots("test_insert_data_blobs_slots_single", false);
test_insert_data_blobs_slots("test_insert_data_blobs_slots_bulk", true);
}
#[test]
pub fn test_iteration_order() {
let slot = 0;
let blocktree_path = get_tmp_ledger_path("test_iteration_order");
{
let blocktree = Blocktree::open(&blocktree_path).unwrap();
// Write entries
let num_entries = 8;
let entries = make_tiny_test_entries(num_entries);
let mut blobs = entries.to_single_entry_blobs();
for (i, b) in blobs.iter_mut().enumerate() {
b.set_index(1 << (i * 8));
b.set_slot(0);
}
blocktree
.write_blobs(&blobs)
.expect("Expected successful write of blobs");
let mut db_iterator = blocktree
.db
.cursor::<cf::Data>()
.expect("Expected to be able to open database iterator");
db_iterator.seek((slot, 1));
// Iterate through ledger
for i in 0..num_entries {
assert!(db_iterator.valid());
let (_, current_index) = db_iterator.key().expect("Expected a valid key");
assert_eq!(current_index, (1 as u64) << (i * 8));
db_iterator.next();
}
}
Blocktree::destroy(&blocktree_path).expect("Expected successful database destruction");
}
#[test]
pub fn test_get_slot_entries1() {
let blocktree_path = get_tmp_ledger_path("test_get_slot_entries1");
{
let blocktree = Blocktree::open(&blocktree_path).unwrap();
let entries = make_tiny_test_entries(8);
let mut blobs = entries.clone().to_single_entry_blobs();
for (i, b) in blobs.iter_mut().enumerate() {
b.set_slot(1);
if i < 4 {
b.set_index(i as u64);
} else {
b.set_index(8 + i as u64);
}
}
blocktree
.write_blobs(&blobs)
.expect("Expected successful write of blobs");
assert_eq!(
blocktree.get_slot_entries(1, 2, None).unwrap()[..],
entries[2..4],
);
assert_eq!(
blocktree.get_slot_entries(1, 12, None).unwrap()[..],
entries[4..],
);
}
Blocktree::destroy(&blocktree_path).expect("Expected successful database destruction");
}
#[test]
pub fn test_get_slot_entries2() {
let blocktree_path = get_tmp_ledger_path("test_get_slot_entries2");
{
let blocktree = Blocktree::open(&blocktree_path).unwrap();
// Write entries
let num_slots = 5 as u64;
let mut index = 0;
for slot in 0..num_slots {
let entries = make_tiny_test_entries(slot as usize + 1);
let last_entry = entries.last().unwrap().clone();
let mut blobs = entries.clone().to_single_entry_blobs();
for b in blobs.iter_mut() {
b.set_index(index);
b.set_slot(slot as u64);
index += 1;
}
blocktree
.write_blobs(&blobs)
.expect("Expected successful write of blobs");
assert_eq!(
blocktree.get_slot_entries(slot, index - 1, None).unwrap(),
vec![last_entry],
);
}
}
Blocktree::destroy(&blocktree_path).expect("Expected successful database destruction");
}
#[test]
pub fn test_get_slot_entries3() {
// Test inserting/fetching blobs which contain multiple entries per blob
let blocktree_path = get_tmp_ledger_path("test_get_slot_entries3");
{
let blocktree = Blocktree::open(&blocktree_path).unwrap();
let num_slots = 5 as u64;
let blobs_per_slot = 5 as u64;
let entry_serialized_size =
bincode::serialized_size(&make_tiny_test_entries(1)).unwrap();
let entries_per_slot =
(blobs_per_slot * packet::BLOB_DATA_SIZE as u64) / entry_serialized_size;
// Write entries
for slot in 0..num_slots {
let mut index = 0;
let entries = make_tiny_test_entries(entries_per_slot as usize);
let mut blobs = entries.clone().to_blobs();
assert_eq!(blobs.len() as u64, blobs_per_slot);
for b in blobs.iter_mut() {
b.set_index(index);
b.set_slot(slot as u64);
index += 1;
}
blocktree
.write_blobs(&blobs)
.expect("Expected successful write of blobs");
assert_eq!(blocktree.get_slot_entries(slot, 0, None).unwrap(), entries,);
}
}
Blocktree::destroy(&blocktree_path).expect("Expected successful database destruction");
}
#[test]
pub fn test_insert_data_blobs_consecutive() {
let blocktree_path = get_tmp_ledger_path("test_insert_data_blobs_consecutive");
{
let blocktree = Blocktree::open(&blocktree_path).unwrap();
for i in 0..4 {
let slot = i;
let parent_slot = if i == 0 { 0 } else { i - 1 };
// Write entries
let num_entries = 21 as u64 * (i + 1);
let (blobs, original_entries) = make_slot_entries(slot, parent_slot, num_entries);
blocktree
.write_blobs(blobs.iter().skip(1).step_by(2))
.unwrap();
assert_eq!(blocktree.get_slot_entries(slot, 0, None).unwrap(), vec![]);
let meta = blocktree.meta(slot).unwrap().unwrap();
if num_entries % 2 == 0 {
assert_eq!(meta.received, num_entries);
} else {
debug!("got here");
assert_eq!(meta.received, num_entries - 1);
}
assert_eq!(meta.consumed, 0);
assert_eq!(meta.parent_slot, parent_slot);
if num_entries % 2 == 0 {
assert_eq!(meta.last_index, num_entries - 1);
} else {
assert_eq!(meta.last_index, std::u64::MAX);
}
blocktree.write_blobs(blobs.iter().step_by(2)).unwrap();
assert_eq!(
blocktree.get_slot_entries(slot, 0, None).unwrap(),
original_entries,
);
let meta = blocktree.meta(slot).unwrap().unwrap();
assert_eq!(meta.received, num_entries);
assert_eq!(meta.consumed, num_entries);
assert_eq!(meta.parent_slot, parent_slot);
assert_eq!(meta.last_index, num_entries - 1);
}
}
Blocktree::destroy(&blocktree_path).expect("Expected successful database destruction");
}
#[test]
pub fn test_insert_data_blobs_duplicate() {
// Create RocksDb ledger
let blocktree_path = get_tmp_ledger_path("test_insert_data_blobs_duplicate");
{
let blocktree = Blocktree::open(&blocktree_path).unwrap();
// Make duplicate entries and blobs
let num_duplicates = 2;
let num_unique_entries = 10;
let (original_entries, blobs) = {
let (blobs, entries) = make_slot_entries(0, 0, num_unique_entries);
let entries: Vec<_> = entries
.into_iter()
.flat_map(|e| vec![e.clone(), e])
.collect();
let blobs: Vec<_> = blobs.into_iter().flat_map(|b| vec![b.clone(), b]).collect();
(entries, blobs)
};
blocktree
.write_blobs(
blobs
.iter()
.skip(num_duplicates as usize)
.step_by(num_duplicates as usize * 2),
)
.unwrap();
assert_eq!(blocktree.get_slot_entries(0, 0, None).unwrap(), vec![]);
blocktree
.write_blobs(blobs.iter().step_by(num_duplicates as usize * 2))
.unwrap();
let expected: Vec<_> = original_entries
.into_iter()
.step_by(num_duplicates as usize)
.collect();
assert_eq!(blocktree.get_slot_entries(0, 0, None).unwrap(), expected,);
let meta = blocktree.meta(0).unwrap().unwrap();
assert_eq!(meta.consumed, num_unique_entries);
assert_eq!(meta.received, num_unique_entries);
assert_eq!(meta.parent_slot, 0);
assert_eq!(meta.last_index, num_unique_entries - 1);
}
Blocktree::destroy(&blocktree_path).expect("Expected successful database destruction");
}
#[test]
pub fn test_genesis_and_entry_iterator() {
let entries = make_tiny_test_entries_from_hash(&Hash::default(), 10);
let ledger_path = get_tmp_ledger_path("test_genesis_and_entry_iterator");
{
genesis(&ledger_path, &Keypair::new(), &entries).unwrap();
let ledger = Blocktree::open(&ledger_path).expect("open failed");
let read_entries: Vec<Entry> =
ledger.read_ledger().expect("read_ledger failed").collect();
assert!(read_entries.verify(&Hash::default()));
assert_eq!(entries, read_entries);
}
Blocktree::destroy(&ledger_path).expect("Expected successful database destruction");
}
#[test]
pub fn test_entry_iterator_up_to_consumed() {
let entries = make_tiny_test_entries_from_hash(&Hash::default(), 3);
let ledger_path = get_tmp_ledger_path("test_genesis_and_entry_iterator");
{
// put entries except last 2 into ledger
genesis(&ledger_path, &Keypair::new(), &entries[..entries.len() - 2]).unwrap();
let ledger = Blocktree::open(&ledger_path).expect("open failed");
// now write the last entry, ledger has a hole in it one before the end
// +-+-+-+-+-+-+-+ +-+
// | | | | | | | | | |
// +-+-+-+-+-+-+-+ +-+
ledger
.write_entries(
0u64,
0,
(entries.len() - 1) as u64,
16,
&entries[entries.len() - 1..],
)
.unwrap();
let read_entries: Vec<Entry> =
ledger.read_ledger().expect("read_ledger failed").collect();
assert!(read_entries.verify(&Hash::default()));
// enumeration should stop at the hole
assert_eq!(entries[..entries.len() - 2].to_vec(), read_entries);
}
Blocktree::destroy(&ledger_path).expect("Expected successful database destruction");
}
#[test]
pub fn test_new_blobs_signal() {
// Initialize ledger
let ledger_path = get_tmp_ledger_path("test_new_blobs_signal");
let (ledger, recvr, _) = Blocktree::open_with_signal(&ledger_path).unwrap();
let ledger = Arc::new(ledger);
let entries_per_slot = 10;
// Create entries for slot 0
let (blobs, _) = make_slot_entries(0, 0, entries_per_slot);
// Insert second blob, but we're missing the first blob, so no consecutive
// blobs starting from slot 0, index 0 should exist.
ledger.insert_data_blobs(once(&blobs[1])).unwrap();
let timer = Duration::new(1, 0);
assert!(recvr.recv_timeout(timer).is_err());
// Insert first blob, now we've made a consecutive block
ledger.insert_data_blobs(once(&blobs[0])).unwrap();
// Wait to get notified of update, should only be one update
assert!(recvr.recv_timeout(timer).is_ok());
assert!(recvr.try_recv().is_err());
// Insert the rest of the ticks
ledger
.insert_data_blobs(&blobs[1..entries_per_slot as usize])
.unwrap();
// Wait to get notified of update, should only be one update
assert!(recvr.recv_timeout(timer).is_ok());
assert!(recvr.try_recv().is_err());
// Create some other slots, and send batches of ticks for each slot such that each slot
// is missing the tick at blob index == slot index - 1. Thus, no consecutive blocks
// will be formed
let num_slots = entries_per_slot;
let mut blobs: Vec<Blob> = vec![];
let mut missing_blobs = vec![];
for slot in 1..num_slots + 1 {
let (mut slot_blobs, _) = make_slot_entries(slot, slot - 1, entries_per_slot);
let missing_blob = slot_blobs.remove(slot as usize - 1);
blobs.extend(slot_blobs);
missing_blobs.push(missing_blob);
}
// Should be no updates, since no new chains from block 0 were formed
ledger.insert_data_blobs(blobs.iter()).unwrap();
assert!(recvr.recv_timeout(timer).is_err());
// Insert a blob for each slot that doesn't make a consecutive block, we
// should get no updates
let blobs: Vec<_> = (1..num_slots + 1)
.flat_map(|slot| {
let (mut blob, _) = make_slot_entries(slot, slot - 1, 1);
blob[0].set_index(2 * num_slots as u64);
blob
})
.collect();
ledger.insert_data_blobs(blobs.iter()).unwrap();
assert!(recvr.recv_timeout(timer).is_err());
// For slots 1..num_slots/2, fill in the holes in one batch insertion,
// so we should only get one signal
ledger
.insert_data_blobs(&missing_blobs[..(num_slots / 2) as usize])
.unwrap();
assert!(recvr.recv_timeout(timer).is_ok());
assert!(recvr.try_recv().is_err());
// Fill in the holes for each of the remaining slots, we should get a single update
// for each
for missing_blob in &missing_blobs[(num_slots / 2) as usize..] {
ledger
.insert_data_blobs(vec![missing_blob.clone()])
.unwrap();
}
// Destroying database without closing it first is undefined behavior
drop(ledger);
Blocktree::destroy(&ledger_path).expect("Expected successful database destruction");
}
#[test]
pub fn test_completed_blobs_signal() {
// Initialize ledger
let ledger_path = get_tmp_ledger_path("test_completed_blobs_signal");
let (ledger, _, recvr) = Blocktree::open_with_signal(&ledger_path).unwrap();
let ledger = Arc::new(ledger);
let entries_per_slot = 10;
// Create blobs for slot 0
let (blobs, _) = make_slot_entries(0, 0, entries_per_slot);
// Insert all but the first blob in the slot, should not be considered complete
ledger
.insert_data_blobs(&blobs[1..entries_per_slot as usize])
.unwrap();
assert!(recvr.try_recv().is_err());
// Insert first blob, slot should now be considered complete
ledger.insert_data_blobs(once(&blobs[0])).unwrap();
assert_eq!(recvr.try_recv().unwrap(), vec![0]);
}
#[test]
pub fn test_completed_blobs_signal_orphans() {
// Initialize ledger
let ledger_path = get_tmp_ledger_path("test_completed_blobs_signal_orphans");
let (ledger, _, recvr) = Blocktree::open_with_signal(&ledger_path).unwrap();
let ledger = Arc::new(ledger);
let entries_per_slot = 10;
let slots = vec![2, 5, 10];
let all_blobs = make_chaining_slot_entries(&slots[..], entries_per_slot);
// Get the blobs for slot 5 chaining to slot 2
let (ref orphan_blobs, _) = all_blobs[1];
// Get the blobs for slot 10, chaining to slot 5
let (ref orphan_child, _) = all_blobs[2];
// Insert all but the first blob in the slot, should not be considered complete
ledger
.insert_data_blobs(&orphan_child[1..entries_per_slot as usize])
.unwrap();
assert!(recvr.try_recv().is_err());
// Insert first blob, slot should now be considered complete
ledger.insert_data_blobs(once(&orphan_child[0])).unwrap();
assert_eq!(recvr.try_recv().unwrap(), vec![slots[2]]);
// Insert the blobs for the orphan_slot
ledger
.insert_data_blobs(&orphan_blobs[1..entries_per_slot as usize])
.unwrap();
assert!(recvr.try_recv().is_err());
// Insert first blob, slot should now be considered complete
ledger.insert_data_blobs(once(&orphan_blobs[0])).unwrap();
assert_eq!(recvr.try_recv().unwrap(), vec![slots[1]]);
}
#[test]
pub fn test_completed_blobs_signal_many() {
// Initialize ledger
let ledger_path = get_tmp_ledger_path("test_completed_blobs_signal_many");
let (ledger, _, recvr) = Blocktree::open_with_signal(&ledger_path).unwrap();
let ledger = Arc::new(ledger);
let entries_per_slot = 10;
let mut slots = vec![2, 5, 10];
let all_blobs = make_chaining_slot_entries(&slots[..], entries_per_slot);
let disconnected_slot = 4;
let (ref blobs0, _) = all_blobs[0];
let (ref blobs1, _) = all_blobs[1];
let (ref blobs2, _) = all_blobs[2];
let (ref blobs3, _) = make_slot_entries(disconnected_slot, 1, entries_per_slot);
let mut all_blobs: Vec<_> = vec![blobs0, blobs1, blobs2, blobs3]
.into_iter()
.flatten()
.collect();
all_blobs.shuffle(&mut thread_rng());
ledger.insert_data_blobs(all_blobs).unwrap();
let mut result = recvr.try_recv().unwrap();
result.sort();
slots.push(disconnected_slot);
slots.sort();
assert_eq!(result, slots);
}
#[test]
pub fn test_handle_chaining_basic() {
let blocktree_path = get_tmp_ledger_path("test_handle_chaining_basic");
{
let entries_per_slot = 2;
let num_slots = 3;
let blocktree = Blocktree::open(&blocktree_path).unwrap();
// Construct the blobs
let (blobs, _) = make_many_slot_entries(0, num_slots, entries_per_slot);
// 1) Write to the first slot
blocktree
.write_blobs(&blobs[entries_per_slot as usize..2 * entries_per_slot as usize])
.unwrap();
let s1 = blocktree.meta(1).unwrap().unwrap();
assert!(s1.next_slots.is_empty());
// Slot 1 is not trunk because slot 0 hasn't been inserted yet
assert!(!s1.is_connected);
assert_eq!(s1.parent_slot, 0);
assert_eq!(s1.last_index, entries_per_slot - 1);
// 2) Write to the second slot
blocktree
.write_blobs(&blobs[2 * entries_per_slot as usize..3 * entries_per_slot as usize])
.unwrap();
let s2 = blocktree.meta(2).unwrap().unwrap();
assert!(s2.next_slots.is_empty());
// Slot 2 is not trunk because slot 0 hasn't been inserted yet
assert!(!s2.is_connected);
assert_eq!(s2.parent_slot, 1);
assert_eq!(s2.last_index, entries_per_slot - 1);
// Check the first slot again, it should chain to the second slot,
// but still isn't part of the trunk
let s1 = blocktree.meta(1).unwrap().unwrap();
assert_eq!(s1.next_slots, vec![2]);
assert!(!s1.is_connected);
assert_eq!(s1.parent_slot, 0);
assert_eq!(s1.last_index, entries_per_slot - 1);
// 3) Write to the zeroth slot, check that every slot
// is now part of the trunk
blocktree
.write_blobs(&blobs[0..entries_per_slot as usize])
.unwrap();
for i in 0..3 {
let s = blocktree.meta(i).unwrap().unwrap();
// The last slot will not chain to any other slots
if i != 2 {
assert_eq!(s.next_slots, vec![i + 1]);
}
if i == 0 {
assert_eq!(s.parent_slot, 0);
} else {
assert_eq!(s.parent_slot, i - 1);
}
assert_eq!(s.last_index, entries_per_slot - 1);
assert!(s.is_connected);
}
}
Blocktree::destroy(&blocktree_path).expect("Expected successful database destruction");
}
#[test]
pub fn test_handle_chaining_missing_slots() {
let blocktree_path = get_tmp_ledger_path("test_handle_chaining_missing_slots");
{
let blocktree = Blocktree::open(&blocktree_path).unwrap();
let num_slots = 30;
let entries_per_slot = 2;
// Separate every other slot into two separate vectors
let mut slots = vec![];
let mut missing_slots = vec![];
for slot in 0..num_slots {
let parent_slot = {
if slot == 0 {
0
} else {
slot - 1
}
};
let (slot_blobs, _) = make_slot_entries(slot, parent_slot, entries_per_slot);
if slot % 2 == 1 {
slots.extend(slot_blobs);
} else {
missing_slots.extend(slot_blobs);
}
}
// Write the blobs for every other slot
blocktree.write_blobs(&slots).unwrap();
// Check metadata
for i in 0..num_slots {
// If "i" is the index of a slot we just inserted, then next_slots should be empty
// for slot "i" because no slots chain to that slot, because slot i + 1 is missing.
// However, if it's a slot we haven't inserted, aka one of the gaps, then one of the
// slots we just inserted will chain to that gap, so next_slots for that orphan slot
// won't be empty, but the parent slot is unknown so should equal std::u64::MAX.
let s = blocktree.meta(i as u64).unwrap().unwrap();
if i % 2 == 0 {
assert_eq!(s.next_slots, vec![i as u64 + 1]);
assert_eq!(s.parent_slot, std::u64::MAX);
} else {
assert!(s.next_slots.is_empty());
assert_eq!(s.parent_slot, i - 1);
}
if i == 0 {
assert!(s.is_connected);
} else {
assert!(!s.is_connected);
}
}
// Write the blobs for the other half of the slots that we didn't insert earlier
blocktree.write_blobs(&missing_slots[..]).unwrap();
for i in 0..num_slots {
// Check that all the slots chain correctly once the missing slots
// have been filled
let s = blocktree.meta(i as u64).unwrap().unwrap();
if i != num_slots - 1 {
assert_eq!(s.next_slots, vec![i as u64 + 1]);
} else {
assert!(s.next_slots.is_empty());
}
if i == 0 {
assert_eq!(s.parent_slot, 0);
} else {
assert_eq!(s.parent_slot, i - 1);
}
assert_eq!(s.last_index, entries_per_slot - 1);
assert!(s.is_connected);
}
}
Blocktree::destroy(&blocktree_path).expect("Expected successful database destruction");
}
#[test]
pub fn test_forward_chaining_is_connected() {
let blocktree_path = get_tmp_ledger_path("test_forward_chaining_is_connected");
{
let blocktree = Blocktree::open(&blocktree_path).unwrap();
let num_slots = 15;
let entries_per_slot = 2;
assert!(entries_per_slot > 1);
let (blobs, _) = make_many_slot_entries(0, num_slots, entries_per_slot);
// Write the blobs such that every 3rd slot has a gap in the beginning
for (slot, slot_ticks) in blobs.chunks(entries_per_slot as usize).enumerate() {
if slot % 3 == 0 {
blocktree
.write_blobs(&slot_ticks[1..entries_per_slot as usize])
.unwrap();
} else {
blocktree
.write_blobs(&slot_ticks[..entries_per_slot as usize])
.unwrap();
}
}
// Check metadata
for i in 0..num_slots {
let s = blocktree.meta(i as u64).unwrap().unwrap();
// The last slot will not chain to any other slots
if i as u64 != num_slots - 1 {
assert_eq!(s.next_slots, vec![i as u64 + 1]);
} else {
assert!(s.next_slots.is_empty());
}
if i == 0 {
assert_eq!(s.parent_slot, 0);
} else {
assert_eq!(s.parent_slot, i - 1);
}
assert_eq!(s.last_index, entries_per_slot - 1);
// Other than slot 0, no slots should be part of the trunk
if i != 0 {
assert!(!s.is_connected);
} else {
assert!(s.is_connected);
}
}
// Iteratively finish every 3rd slot, and check that all slots up to and including
// slot_index + 3 become part of the trunk
for (slot_index, slot_ticks) in blobs.chunks(entries_per_slot as usize).enumerate() {
if slot_index % 3 == 0 {
blocktree.write_blobs(&slot_ticks[0..1]).unwrap();
for i in 0..num_slots {
let s = blocktree.meta(i as u64).unwrap().unwrap();
if i != num_slots - 1 {
assert_eq!(s.next_slots, vec![i as u64 + 1]);
} else {
assert!(s.next_slots.is_empty());
}
if i <= slot_index as u64 + 3 {
assert!(s.is_connected);
} else {
assert!(!s.is_connected);
}
if i == 0 {
assert_eq!(s.parent_slot, 0);
} else {
assert_eq!(s.parent_slot, i - 1);
}
assert_eq!(s.last_index, entries_per_slot - 1);
}
}
}
}
Blocktree::destroy(&blocktree_path).expect("Expected successful database destruction");
}
#[test]
pub fn test_chaining_tree() {
let blocktree_path = get_tmp_ledger_path("test_chaining_tree");
{
let blocktree = Blocktree::open(&blocktree_path).unwrap();
let num_tree_levels = 6;
assert!(num_tree_levels > 1);
let branching_factor: u64 = 4;
// Number of slots that will be in the tree
let num_slots = (branching_factor.pow(num_tree_levels) - 1) / (branching_factor - 1);
let entries_per_slot = NUM_DATA as u64;
assert!(entries_per_slot > 1);
let (mut blobs, _) = make_many_slot_entries(0, num_slots, entries_per_slot);
// Insert tree one slot at a time in a random order
let mut slots: Vec<_> = (0..num_slots).collect();
// Get blobs for the slot
slots.shuffle(&mut thread_rng());
for slot in slots {
// Get blobs for the slot "slot"
let slot_blobs = &mut blobs
[(slot * entries_per_slot) as usize..((slot + 1) * entries_per_slot) as usize];
for blob in slot_blobs.iter_mut() {
// Get the parent slot of the slot in the tree
let slot_parent = {
if slot == 0 {
0
} else {
(slot - 1) / branching_factor
}
};
blob.set_parent(slot_parent);
}
let shared_blobs: Vec<_> = slot_blobs
.iter()
.cloned()
.map(|blob| Arc::new(RwLock::new(blob)))
.collect();
let mut coding_generator = CodingGenerator::new(Arc::clone(&blocktree.session));
let coding_blobs = coding_generator.next(&shared_blobs);
assert_eq!(coding_blobs.len(), NUM_CODING);
let mut rng = thread_rng();
// Randomly pick whether to insert erasure or coding blobs first
if rng.gen_bool(0.5) {
blocktree.write_blobs(slot_blobs).unwrap();
blocktree.put_many_coding_blob_bytes(&coding_blobs).unwrap();
} else {
blocktree.put_many_coding_blob_bytes(&coding_blobs).unwrap();
blocktree.write_blobs(slot_blobs).unwrap();
}
}
// Make sure everything chains correctly
let last_level =
(branching_factor.pow(num_tree_levels - 1) - 1) / (branching_factor - 1);
for slot in 0..num_slots {
let slot_meta = blocktree.meta(slot).unwrap().unwrap();
assert_eq!(slot_meta.consumed, entries_per_slot);
assert_eq!(slot_meta.received, entries_per_slot);
assert!(slot_meta.is_connected);
let slot_parent = {
if slot == 0 {
0
} else {
(slot - 1) / branching_factor
}
};
assert_eq!(slot_meta.parent_slot, slot_parent);
let expected_children: HashSet<_> = {
if slot >= last_level {
HashSet::new()
} else {
let first_child_slot = min(num_slots - 1, slot * branching_factor + 1);
let last_child_slot = min(num_slots - 1, (slot + 1) * branching_factor);
(first_child_slot..last_child_slot + 1).collect()
}
};
let result: HashSet<_> = slot_meta.next_slots.iter().cloned().collect();
if expected_children.len() != 0 {
assert_eq!(slot_meta.next_slots.len(), branching_factor as usize);
} else {
assert_eq!(slot_meta.next_slots.len(), 0);
}
assert_eq!(expected_children, result);
}
// No orphan slots should exist
assert!(blocktree.orphans_cf.is_empty().unwrap())
}
Blocktree::destroy(&blocktree_path).expect("Expected successful database destruction");
}
#[test]
pub fn test_get_slots_since() {
let blocktree_path = get_tmp_ledger_path("test_get_slots_since");
{
let blocktree = Blocktree::open(&blocktree_path).unwrap();
// Slot doesn't exist
assert!(blocktree.get_slots_since(&vec![0]).unwrap().is_empty());
let mut meta0 = SlotMeta::new(0, 0);
blocktree.meta_cf.put(0, &meta0).unwrap();
// Slot exists, chains to nothing
let expected: HashMap<u64, Vec<u64>> =
HashMap::from_iter(vec![(0, vec![])].into_iter());
assert_eq!(blocktree.get_slots_since(&vec![0]).unwrap(), expected);
meta0.next_slots = vec![1, 2];
blocktree.meta_cf.put(0, &meta0).unwrap();
// Slot exists, chains to some other slots
let expected: HashMap<u64, Vec<u64>> =
HashMap::from_iter(vec![(0, vec![1, 2])].into_iter());
assert_eq!(blocktree.get_slots_since(&vec![0]).unwrap(), expected);
assert_eq!(blocktree.get_slots_since(&vec![0, 1]).unwrap(), expected);
let mut meta3 = SlotMeta::new(3, 1);
meta3.next_slots = vec![10, 5];
blocktree.meta_cf.put(3, &meta3).unwrap();
let expected: HashMap<u64, Vec<u64>> =
HashMap::from_iter(vec![(0, vec![1, 2]), (3, vec![10, 5])].into_iter());
assert_eq!(blocktree.get_slots_since(&vec![0, 1, 3]).unwrap(), expected);
}
Blocktree::destroy(&blocktree_path).expect("Expected successful database destruction");
}
#[test]
fn test_orphans() {
let blocktree_path = get_tmp_ledger_path("test_orphans");
{
let blocktree = Blocktree::open(&blocktree_path).unwrap();
// Create blobs and entries
let entries_per_slot = 1;
let (blobs, _) = make_many_slot_entries(0, 3, entries_per_slot);
// Write slot 2, which chains to slot 1. We're missing slot 0,
// so slot 1 is the orphan
blocktree.write_blobs(once(&blobs[2])).unwrap();
let meta = blocktree
.meta(1)
.expect("Expect database get to succeed")
.unwrap();
assert!(is_orphan(&meta));
assert_eq!(blocktree.get_orphans(None), vec![1]);
// Write slot 1 which chains to slot 0, so now slot 0 is the
// orphan, and slot 1 is no longer the orphan.
blocktree.write_blobs(once(&blobs[1])).unwrap();
let meta = blocktree
.meta(1)
.expect("Expect database get to succeed")
.unwrap();
assert!(!is_orphan(&meta));
let meta = blocktree
.meta(0)
.expect("Expect database get to succeed")
.unwrap();
assert!(is_orphan(&meta));
assert_eq!(blocktree.get_orphans(None), vec![0]);
// Write some slot that also chains to existing slots and orphan,
// nothing should change
let blob4 = &make_slot_entries(4, 0, 1).0[0];
let blob5 = &make_slot_entries(5, 1, 1).0[0];
blocktree.write_blobs(vec![blob4, blob5]).unwrap();
assert_eq!(blocktree.get_orphans(None), vec![0]);
// Write zeroth slot, no more orphans
blocktree.write_blobs(once(&blobs[0])).unwrap();
for i in 0..3 {
let meta = blocktree
.meta(i)
.expect("Expect database get to succeed")
.unwrap();
assert!(!is_orphan(&meta));
}
// Orphans cf is empty
assert!(blocktree.orphans_cf.is_empty().unwrap())
}
Blocktree::destroy(&blocktree_path).expect("Expected successful database destruction");
}
fn test_insert_data_blobs_slots(name: &str, should_bulk_write: bool) {
let blocktree_path = get_tmp_ledger_path(name);
{
let blocktree = Blocktree::open(&blocktree_path).unwrap();
// Create blobs and entries
let num_entries = 20 as u64;
let mut entries = vec![];
let mut blobs = vec![];
for slot in 0..num_entries {
let parent_slot = {
if slot == 0 {
0
} else {
slot - 1
}
};
let (mut blob, entry) = make_slot_entries(slot, parent_slot, 1);
blob[0].set_index(slot);
blobs.extend(blob);
entries.extend(entry);
}
// Write blobs to the database
if should_bulk_write {
blocktree.write_blobs(blobs.iter()).unwrap();
} else {
for i in 0..num_entries {
let i = i as usize;
blocktree.write_blobs(&blobs[i..i + 1]).unwrap();
}
}
for i in 0..num_entries - 1 {
assert_eq!(
blocktree.get_slot_entries(i, i, None).unwrap()[0],
entries[i as usize]
);
let meta = blocktree.meta(i).unwrap().unwrap();
assert_eq!(meta.received, i + 1);
assert_eq!(meta.last_index, i);
if i != 0 {
assert_eq!(meta.parent_slot, i - 1);
assert!(meta.consumed == 0);
} else {
assert_eq!(meta.parent_slot, 0);
assert!(meta.consumed == 1);
}
}
}
Blocktree::destroy(&blocktree_path).expect("Expected successful database destruction");
}
#[test]
fn test_find_missing_data_indexes() {
let slot = 0;
let blocktree_path = get_tmp_ledger_path!();
let blocktree = Blocktree::open(&blocktree_path).unwrap();
// Write entries
let gap = 10;
assert!(gap > 3);
let num_entries = 10;
let mut blobs = make_tiny_test_entries(num_entries).to_single_entry_blobs();
for (i, b) in blobs.iter_mut().enumerate() {
b.set_index(i as u64 * gap);
b.set_slot(slot);
}
blocktree.write_blobs(&blobs).unwrap();
// Index of the first blob is 0
// Index of the second blob is "gap"
// Thus, the missing indexes should then be [1, gap - 1] for the input index
// range of [0, gap)
let expected: Vec<u64> = (1..gap).collect();
assert_eq!(
blocktree.find_missing_data_indexes(slot, 0, gap, gap as usize),
expected
);
assert_eq!(
blocktree.find_missing_data_indexes(slot, 1, gap, (gap - 1) as usize),
expected,
);
assert_eq!(
blocktree.find_missing_data_indexes(slot, 0, gap - 1, (gap - 1) as usize),
&expected[..expected.len() - 1],
);
assert_eq!(
blocktree.find_missing_data_indexes(slot, gap - 2, gap, gap as usize),
vec![gap - 2, gap - 1],
);
assert_eq!(
blocktree.find_missing_data_indexes(slot, gap - 2, gap, 1),
vec![gap - 2],
);
assert_eq!(
blocktree.find_missing_data_indexes(slot, 0, gap, 1),
vec![1],
);
// Test with end indexes that are greater than the last item in the ledger
let mut expected: Vec<u64> = (1..gap).collect();
expected.push(gap + 1);
assert_eq!(
blocktree.find_missing_data_indexes(slot, 0, gap + 2, (gap + 2) as usize),
expected,
);
assert_eq!(
blocktree.find_missing_data_indexes(slot, 0, gap + 2, (gap - 1) as usize),
&expected[..expected.len() - 1],
);
for i in 0..num_entries as u64 {
for j in 0..i {
let expected: Vec<u64> = (j..i)
.flat_map(|k| {
let begin = k * gap + 1;
let end = (k + 1) * gap;
(begin..end)
})
.collect();
assert_eq!(
blocktree.find_missing_data_indexes(
slot,
j * gap,
i * gap,
((i - j) * gap) as usize
),
expected,
);
}
}
drop(blocktree);
Blocktree::destroy(&blocktree_path).expect("Expected successful database destruction");
}
#[test]
fn test_find_missing_data_indexes_sanity() {
let slot = 0;
let blocktree_path = get_tmp_ledger_path!();
let blocktree = Blocktree::open(&blocktree_path).unwrap();
// Early exit conditions
let empty: Vec<u64> = vec![];
assert_eq!(blocktree.find_missing_data_indexes(slot, 0, 0, 1), empty);
assert_eq!(blocktree.find_missing_data_indexes(slot, 5, 5, 1), empty);
assert_eq!(blocktree.find_missing_data_indexes(slot, 4, 3, 1), empty);
assert_eq!(blocktree.find_missing_data_indexes(slot, 1, 2, 0), empty);
let mut blobs = make_tiny_test_entries(2).to_single_entry_blobs();
const ONE: u64 = 1;
const OTHER: u64 = 4;
blobs[0].set_index(ONE);
blobs[1].set_index(OTHER);
// Insert one blob at index = first_index
blocktree.write_blobs(&blobs).unwrap();
const STARTS: u64 = OTHER * 2;
const END: u64 = OTHER * 3;
const MAX: usize = 10;
// The first blob has index = first_index. Thus, for i < first_index,
// given the input range of [i, first_index], the missing indexes should be
// [i, first_index - 1]
for start in 0..STARTS {
let result = blocktree.find_missing_data_indexes(
slot, start, // start
END, //end
MAX, //max
);
let expected: Vec<u64> = (start..END).filter(|i| *i != ONE && *i != OTHER).collect();
assert_eq!(result, expected);
}
drop(blocktree);
Blocktree::destroy(&blocktree_path).expect("Expected successful database destruction");
}
#[test]
pub fn test_no_missing_blob_indexes() {
let slot = 0;
let blocktree_path = get_tmp_ledger_path!();
let blocktree = Blocktree::open(&blocktree_path).unwrap();
// Write entries
let num_entries = 10;
let shared_blobs = make_tiny_test_entries(num_entries).to_single_entry_shared_blobs();
crate::packet::index_blobs(&shared_blobs, &Pubkey::new_rand(), 0, slot, 0);
let blob_locks: Vec<_> = shared_blobs.iter().map(|b| b.read().unwrap()).collect();
let blobs: Vec<&Blob> = blob_locks.iter().map(|b| &**b).collect();
blocktree.write_blobs(blobs).unwrap();
let empty: Vec<u64> = vec![];
for i in 0..num_entries as u64 {
for j in 0..i {
assert_eq!(
blocktree.find_missing_data_indexes(slot, j, i, (i - j) as usize),
empty
);
}
}
drop(blocktree);
Blocktree::destroy(&blocktree_path).expect("Expected successful database destruction");
}
#[test]
pub fn test_should_insert_blob() {
let (mut blobs, _) = make_slot_entries(0, 0, 20);
let blocktree_path = get_tmp_ledger_path!();
let blocktree = Blocktree::open(&blocktree_path).unwrap();
// Insert the first 5 blobs, we don't have a "is_last" blob yet
blocktree.insert_data_blobs(&blobs[0..5]).unwrap();
// Trying to insert a blob less than consumed should fail
let slot_meta = blocktree.meta(0).unwrap().unwrap();
assert_eq!(slot_meta.consumed, 5);
assert!(!should_insert_blob(
&slot_meta,
&blocktree.db,
&HashMap::new(),
&blobs[4].clone()
));
// Trying to insert the same blob again should fail
blocktree.insert_data_blobs(&blobs[7..8]).unwrap();
let slot_meta = blocktree.meta(0).unwrap().unwrap();
assert!(!should_insert_blob(
&slot_meta,
&blocktree.db,
&HashMap::new(),
&blobs[7].clone()
));
// Trying to insert another "is_last" blob with index < the received index
// should fail
blocktree.insert_data_blobs(&blobs[8..9]).unwrap();
let slot_meta = blocktree.meta(0).unwrap().unwrap();
assert_eq!(slot_meta.received, 9);
blobs[8].set_is_last_in_slot();
assert!(!should_insert_blob(
&slot_meta,
&blocktree.db,
&HashMap::new(),
&blobs[8].clone()
));
// Insert the 10th blob, which is marked as "is_last"
blobs[9].set_is_last_in_slot();
blocktree.insert_data_blobs(&blobs[9..10]).unwrap();
let slot_meta = blocktree.meta(0).unwrap().unwrap();
// Trying to insert a blob with index > the "is_last" blob should fail
assert!(!should_insert_blob(
&slot_meta,
&blocktree.db,
&HashMap::new(),
&blobs[10].clone()
));
drop(blocktree);
Blocktree::destroy(&blocktree_path).expect("Expected successful database destruction");
}
#[test]
pub fn test_insert_multiple_is_last() {
let (mut blobs, _) = make_slot_entries(0, 0, 20);
let blocktree_path = get_tmp_ledger_path!();
let blocktree = Blocktree::open(&blocktree_path).unwrap();
// Inserting multiple blobs with the is_last flag set should only insert
// the first blob with the "is_last" flag, and drop the rest
for i in 6..20 {
blobs[i].set_is_last_in_slot();
}
blocktree.insert_data_blobs(&blobs[..]).unwrap();
let slot_meta = blocktree.meta(0).unwrap().unwrap();
assert_eq!(slot_meta.consumed, 7);
assert_eq!(slot_meta.received, 7);
assert_eq!(slot_meta.last_index, 6);
assert!(slot_meta.is_full());
drop(blocktree);
Blocktree::destroy(&blocktree_path).expect("Expected successful database destruction");
}
#[test]
fn test_slot_data_iterator() {
// Construct the blobs
let blocktree_path = get_tmp_ledger_path!();
let blocktree = Blocktree::open(&blocktree_path).unwrap();
let blobs_per_slot = 10;
let slots = vec![2, 4, 8, 12];
let all_blobs = make_chaining_slot_entries(&slots, blobs_per_slot);
let slot_8_blobs = all_blobs[2].0.clone();
for (slot_blobs, _) in all_blobs {
blocktree.insert_data_blobs(&slot_blobs[..]).unwrap();
}
// Slot doesnt exist, iterator should be empty
let blob_iter = blocktree.slot_data_iterator(5).unwrap();
let result: Vec<_> = blob_iter.collect();
assert_eq!(result, vec![]);
// Test that the iterator for slot 8 contains what was inserted earlier
let blob_iter = blocktree.slot_data_iterator(8).unwrap();
let result: Vec<_> = blob_iter.map(|(_, bytes)| Blob::new(&bytes)).collect();
assert_eq!(result.len() as u64, blobs_per_slot);
assert_eq!(result, slot_8_blobs);
drop(blocktree);
Blocktree::destroy(&blocktree_path).expect("Expected successful database destruction");
}
#[test]
fn test_set_root() {
let blocktree_path = get_tmp_ledger_path!();
let blocktree = Blocktree::open(&blocktree_path).unwrap();
blocktree.set_root(0, 0).unwrap();
let chained_slots = vec![0, 2, 4, 7, 12, 15];
// Make a chain of slots
let all_blobs = make_chaining_slot_entries(&chained_slots, 10);
// Insert the chain of slots into the ledger
for (slot_blobs, _) in all_blobs {
blocktree.insert_data_blobs(&slot_blobs[..]).unwrap();
}
blocktree.set_root(4, 0).unwrap();
for i in &chained_slots[0..3] {
assert!(blocktree.is_root(*i));
}
for i in &chained_slots[3..] {
assert!(!blocktree.is_root(*i));
}
blocktree.set_root(15, 4).unwrap();
for i in chained_slots {
assert!(blocktree.is_root(i));
}
drop(blocktree);
Blocktree::destroy(&blocktree_path).expect("Expected successful database destruction");
}
mod erasure {
use super::*;
use crate::blockBufferPool::meta::ErasureMetaStatus;
use crate::expunge::test::{generate_ledger_model, ErasureSpec, SlotSpec};
use crate::expunge::{CodingGenerator, NUM_CODING, NUM_DATA};
use rand::{thread_rng, Rng};
use std::sync::RwLock;
impl Into<SharedBlob> for Blob {
fn into(self) -> SharedBlob {
Arc::new(RwLock::new(self))
}
}
#[test]
fn test_erasure_meta_accuracy() {
use crate::expunge::ERASURE_SET_SIZE;
use ErasureMetaStatus::{DataFull, StillNeed};
let path = get_tmp_ledger_path!();
let blocktree = Blocktree::open(&path).unwrap();
// two erasure sets
let num_blobs = NUM_DATA as u64 * 2;
let slot = 0;
let (blobs, _) = make_slot_entries(slot, 0, num_blobs);
let shared_blobs: Vec<_> = blobs
.iter()
.cloned()
.map(|blob| Arc::new(RwLock::new(blob)))
.collect();
blocktree.write_blobs(&blobs[..2]).unwrap();
let erasure_meta_opt = blocktree
.erasure_meta(slot, 0)
.expect("DB get must succeed");
assert!(erasure_meta_opt.is_some());
let erasure_meta = erasure_meta_opt.unwrap();
let should_need = ERASURE_SET_SIZE - NUM_CODING - 2;
match erasure_meta.status() {
StillNeed(n) => assert_eq!(n, should_need),
_ => panic!("Should still need more blobs"),
};
blocktree.write_blobs(&blobs[2..NUM_DATA]).unwrap();
let erasure_meta = blocktree
.erasure_meta(slot, 0)
.expect("DB get must succeed")
.unwrap();
assert_eq!(erasure_meta.status(), DataFull);
// insert all coding blobs in first set
let mut coding_generator = CodingGenerator::new(Arc::clone(&blocktree.session));
let coding_blobs = coding_generator.next(&shared_blobs[..NUM_DATA]);
for shared_coding_blob in coding_blobs {
let blob = shared_coding_blob.read().unwrap();
let size = blob.size() + BLOB_HEADER_SIZE;
blocktree
.put_coding_blob_bytes(blob.slot(), blob.index(), &blob.data[..size])
.unwrap();
}
let erasure_meta = blocktree
.erasure_meta(slot, 0)
.expect("DB get must succeed")
.unwrap();
assert_eq!(erasure_meta.status(), DataFull);
// insert blobs in the 2nd set until recovery should be possible given all coding blobs
let set2 = &blobs[NUM_DATA..];
let mut end = 1;
let blobs_needed = ERASURE_SET_SIZE - NUM_CODING;
while end < blobs_needed {
blocktree.write_blobs(&set2[end - 1..end]).unwrap();
let erasure_meta = blocktree
.erasure_meta(slot, 1)
.expect("DB get must succeed")
.unwrap();
match erasure_meta.status() {
StillNeed(n) => assert_eq!(n, blobs_needed - end),
_ => panic!("Should still need more blobs"),
};
end += 1;
}
// insert all coding blobs in 2nd set. Should trigger recovery
let mut coding_generator = CodingGenerator::new(Arc::clone(&blocktree.session));
let coding_blobs = coding_generator.next(&shared_blobs[NUM_DATA..]);
for shared_coding_blob in coding_blobs {
let blob = shared_coding_blob.read().unwrap();
let size = blob.size() + BLOB_HEADER_SIZE;
blocktree
.put_coding_blob_bytes(blob.slot(), blob.index(), &blob.data[..size])
.unwrap();
}
let erasure_meta = blocktree
.erasure_meta(slot, 1)
.expect("DB get must succeed")
.unwrap();
assert_eq!(erasure_meta.status(), DataFull);
// remove coding blobs, erasure meta should still report being full
let (start_idx, coding_end_idx) =
(erasure_meta.start_index(), erasure_meta.end_indexes().1);
for idx in start_idx..coding_end_idx {
blocktree.delete_coding_blob(slot, idx).unwrap();
}
let erasure_meta = blocktree
.erasure_meta(slot, 1)
.expect("DB get must succeed")
.unwrap();
assert_eq!(erasure_meta.status(), ErasureMetaStatus::DataFull);
}
#[test]
pub fn test_recovery_basic() {
morgan_logger::setup();
let slot = 0;
let ledger_path = get_tmp_ledger_path!();
let blocktree = Blocktree::open(&ledger_path).unwrap();
let num_sets = 3;
let data_blobs = make_slot_entries(slot, 0, num_sets * NUM_DATA as u64)
.0
.into_iter()
.map(Blob::into)
.collect::<Vec<_>>();
let mut coding_generator = CodingGenerator::new(Arc::clone(&blocktree.session));
for (set_index, data_blobs) in data_blobs.chunks_exact(NUM_DATA).enumerate() {
let focused_index = (set_index + 1) * NUM_DATA - 1;
let coding_blobs = coding_generator.next(&data_blobs);
assert_eq!(coding_blobs.len(), NUM_CODING);
let deleted_data = data_blobs[NUM_DATA - 1].clone();
blocktree
.write_shared_blobs(&data_blobs[..NUM_DATA - 1])
.unwrap();
// This should trigger recovery of the missing data blob
for shared_coding_blob in coding_blobs {
let blob = shared_coding_blob.read().unwrap();
let size = blob.size() + BLOB_HEADER_SIZE;
blocktree
.put_coding_blob_bytes(slot, blob.index(), &blob.data[..size])
.expect("Inserting coding blobs must succeed");
(slot, blob.index());
}
// Verify the slot meta
let slot_meta = blocktree.meta(slot).unwrap().unwrap();
assert_eq!(slot_meta.consumed, (NUM_DATA * (set_index + 1)) as u64);
assert_eq!(slot_meta.received, (NUM_DATA * (set_index + 1)) as u64);
assert_eq!(slot_meta.parent_slot, 0);
assert!(slot_meta.next_slots.is_empty());
assert_eq!(slot_meta.is_connected, true);
if set_index as u64 == num_sets - 1 {
assert_eq!(
slot_meta.last_index,
(NUM_DATA * (set_index + 1) - 1) as u64
);
}
let erasure_meta = blocktree
.erasure_meta_cf
.get((slot, set_index as u64))
.expect("Erasure Meta should be present")
.unwrap();
assert_eq!(erasure_meta.status(), ErasureMetaStatus::DataFull);
let retrieved_data = blocktree
.data_cf
.get_bytes((slot, focused_index as u64))
.unwrap();
assert!(retrieved_data.is_some());
let data_blob = Blob::new(&retrieved_data.unwrap());
assert_eq!(&data_blob, &*deleted_data.read().unwrap());
}
drop(blocktree);
Blocktree::destroy(&ledger_path).expect("Expect successful Blocktree destruction");
}
#[test]
fn test_recovery_fails_safely() {
const SLOT: u64 = 0;
const SET_INDEX: u64 = 0;
morgan_logger::setup();
let ledger_path = get_tmp_ledger_path!();
let blocktree = Blocktree::open(&ledger_path).unwrap();
let data_blobs = make_slot_entries(SLOT, 0, NUM_DATA as u64)
.0
.into_iter()
.map(Blob::into)
.collect::<Vec<_>>();
let mut coding_generator = CodingGenerator::new(Arc::clone(&blocktree.session));
let shared_coding_blobs = coding_generator.next(&data_blobs);
assert_eq!(shared_coding_blobs.len(), NUM_CODING);
// Insert coding blobs except 1 and no data. Not enough to do recovery
for shared_blob in shared_coding_blobs.iter().skip(1) {
let blob = shared_blob.read().unwrap();
let size = blob.size() + BLOB_HEADER_SIZE;
blocktree
.put_coding_blob_bytes(SLOT, blob.index(), &blob.data[..size])
.expect("Inserting coding blobs must succeed");
}
// try recovery even though there aren't enough blobs
let erasure_meta = blocktree
.erasure_meta_cf
.get((SLOT, SET_INDEX))
.unwrap()
.unwrap();
assert_eq!(erasure_meta.status(), ErasureMetaStatus::StillNeed(1));
let prev_inserted_blob_datas = HashMap::new();
let attempt_result = try_erasure_recover(
&blocktree.db,
&blocktree.session,
&erasure_meta,
SLOT,
&prev_inserted_blob_datas,
None,
);
assert!(attempt_result.is_ok());
let recovered_blobs_opt = attempt_result.unwrap();
assert!(recovered_blobs_opt.is_none());
}
#[test]
fn test_recovery_multi_slot_multi_thread() {
use rand::{rngs::SmallRng, seq::SliceRandom, SeedableRng};
use std::thread;
const N_THREADS: usize = 3;
let slots = vec![0, 3, 5, 50, 100];
let max_erasure_sets = 16;
morgan_logger::setup();
let path = get_tmp_ledger_path!();
let mut rng = thread_rng();
// Specification should generate a ledger where each slot has an random number of
// erasure sets. Odd erasure sets will have all coding blobs and between 1-4 data blobs
// missing, and even ones will have between 1-2 data blobs missing and 1-2 coding blobs
// missing
let specs = slots
.iter()
.map(|&slot| {
let num_erasure_sets = rng.gen_range(0, max_erasure_sets);
let set_specs = (0..num_erasure_sets)
.map(|set_index| {
let (num_data, num_coding) = if set_index % 2 == 0 {
(
NUM_DATA - rng.gen_range(1, 3),
NUM_CODING - rng.gen_range(1, 3),
)
} else {
(NUM_DATA - rng.gen_range(1, 5), NUM_CODING)
};
ErasureSpec {
set_index,
num_data,
num_coding,
}
})
.collect();
SlotSpec { slot, set_specs }
})
.collect::<Vec<_>>();
let model = generate_ledger_model(specs);
let blocktree = Arc::new(Blocktree::open(&path).unwrap());
// Write to each slot in a different thread simultaneously.
// These writes should trigger the recovery. Every erasure set should have all of its
// data blobs and coding_blobs at the end
let mut handles = vec![];
// Each thread will attempt to write to each slot in order. Within a slot, each thread
// will try to write each erasure set in a random order. Within each erasure set, there
// is a 50/50 chance of attempting to write the coding blobs first or the data blobs
// first.
// The goal is to be as racey as possible and cover a wide range of situations
for thread_id in 0..N_THREADS {
let blocktree = Arc::clone(&blocktree);
let mut rng = SmallRng::from_rng(&mut rng).unwrap();
let model = model.clone();
let handle = thread::spawn(move || {
for slot_model in model {
let slot = slot_model.slot;
let num_erasure_sets = slot_model.chunks.len();
let unordered_sets = slot_model
.chunks
.choose_multiple(&mut rng, num_erasure_sets);
for erasure_set in unordered_sets {
let mut attempt = 0;
loop {
if rng.gen() {
blocktree
.write_shared_blobs(&erasure_set.data)
.expect("Writing data blobs must succeed");
debug!(
"multislot: wrote data: slot: {}, erasure_set: {}",
slot, erasure_set.set_index
);
for shared_coding_blob in &erasure_set.coding {
let blob = shared_coding_blob.read().unwrap();
let size = blob.size() + BLOB_HEADER_SIZE;
blocktree
.put_coding_blob_bytes(
slot,
blob.index(),
&blob.data[..size],
)
.expect("Writing coding blobs must succeed");
}
debug!(
"multislot: wrote coding: slot: {}, erasure_set: {}",
slot, erasure_set.set_index
);
} else {
// write coding blobs first, then write the data blobs.
for shared_coding_blob in &erasure_set.coding {
let blob = shared_coding_blob.read().unwrap();
let size = blob.size() + BLOB_HEADER_SIZE;
blocktree
.put_coding_blob_bytes(
slot,
blob.index(),
&blob.data[..size],
)
.expect("Writing coding blobs must succeed");
}
debug!(
"multislot: wrote coding: slot: {}, erasure_set: {}",
slot, erasure_set.set_index
);
blocktree
.write_shared_blobs(&erasure_set.data)
.expect("Writing data blobs must succeed");
debug!(
"multislot: wrote data: slot: {}, erasure_set: {}",
slot, erasure_set.set_index
);
}
// due to racing, some blobs might not be inserted. don't stop
// trying until *some* thread succeeds in writing everything and
// triggering recovery.
let erasure_meta = blocktree
.erasure_meta_cf
.get((slot, erasure_set.set_index))
.unwrap()
.unwrap();
let status = erasure_meta.status();
attempt += 1;
debug!(
"[multi_slot] thread_id: {}, attempt: {}, slot: {}, set_index: {}, status: {:?}",
thread_id, attempt, slot, erasure_set.set_index, status
);
if status == ErasureMetaStatus::DataFull {
break;
}
}
}
}
});
handles.push(handle);
}
handles
.into_iter()
.for_each(|handle| handle.join().unwrap());
for slot_model in model {
let slot = slot_model.slot;
for erasure_set_model in slot_model.chunks {
let set_index = erasure_set_model.set_index as u64;
let erasure_meta = blocktree
.erasure_meta_cf
.get((slot, set_index))
.expect("DB get must succeed")
.expect("ErasureMeta must be present for each erasure set");
debug!(
"multislot: got erasure_meta: slot: {}, set_index: {}, erasure_meta: {:?}",
slot, set_index, erasure_meta
);
// all possibility for recovery should be exhausted
assert_eq!(erasure_meta.status(), ErasureMetaStatus::DataFull);
// Should have all data
assert_eq!(erasure_meta.num_data(), NUM_DATA);
// Should have all coding
assert_eq!(erasure_meta.num_coding(), NUM_CODING);
}
}
drop(blocktree);
Blocktree::destroy(&path).expect("Blocktree destruction must succeed");
}
}
pub fn entries_to_blobs(
entries: &Vec<Entry>,
slot: u64,
parent_slot: u64,
is_full_slot: bool,
) -> Vec<Blob> {
let mut blobs = entries.clone().to_single_entry_blobs();
for (i, b) in blobs.iter_mut().enumerate() {
b.set_index(i as u64);
b.set_slot(slot);
b.set_parent(parent_slot);
}
if is_full_slot {
blobs.last_mut().unwrap().set_is_last_in_slot();
}
blobs
}
pub fn make_slot_entries(
slot: u64,
parent_slot: u64,
num_entries: u64,
) -> (Vec<Blob>, Vec<Entry>) {
let entries = make_tiny_test_entries(num_entries as usize);
let blobs = entries_to_blobs(&entries, slot, parent_slot, true);
(blobs, entries)
}
pub fn make_many_slot_entries(
start_slot: u64,
num_slots: u64,
entries_per_slot: u64,
) -> (Vec<Blob>, Vec<Entry>) {
let mut blobs = vec![];
let mut entries = vec![];
for slot in start_slot..start_slot + num_slots {
let parent_slot = if slot == 0 { 0 } else { slot - 1 };
let (slot_blobs, slot_entries) = make_slot_entries(slot, parent_slot, entries_per_slot);
blobs.extend(slot_blobs);
entries.extend(slot_entries);
}
(blobs, entries)
}
// Create blobs for slots that have a parent-child relationship defined by the input `chain`
pub fn make_chaining_slot_entries(
chain: &[u64],
entries_per_slot: u64,
) -> Vec<(Vec<Blob>, Vec<Entry>)> {
let mut slots_blobs_and_entries = vec![];
for (i, slot) in chain.iter().enumerate() {
let parent_slot = {
if *slot == 0 {
0
} else if i == 0 {
std::u64::MAX
} else {
chain[i - 1]
}
};
let result = make_slot_entries(*slot, parent_slot, entries_per_slot);
slots_blobs_and_entries.push(result);
}
slots_blobs_and_entries
}
}
|
use projecteuler::binomial;
fn main() {
dbg!(solve(2));
dbg!(solve(20));
}
fn solve(n: usize) -> usize {
binomial::binomial_coefficient(2 * n, n)
}
|
use std::fs::read_to_string;
fn read_param(prog: &Vec<i32>, base: i32, pos: usize, i: usize) -> i32 {
match prog[pos] / 10_i32.pow(i as u32 + 1) % 10 {
0 => prog[prog[pos + i] as usize],
1 => prog[pos + i],
2 => prog[(base + prog[pos + i]) as usize],
_ => panic!("invalid parameter mode"),
}
}
fn write_param(prog: &Vec<i32>, base: i32, pos: usize, i: usize) -> usize {
match prog[pos] / 10_i32.pow(i as u32 + 1) % 10 {
0 => prog[pos + i] as usize,
2 => (base + prog[pos + i]) as usize,
_ => panic!("invalid parameter mode"),
}
}
fn run(mut prog: Vec<i32>, quart: bool) -> (i32, i32) {
let (mut pos, mut base, mut grid, mut coords, mut wait, mut blocks, mut padl, mut ball, mut score) = (0, 0, [[5; 42]; 24], (0, 0), 0, 0, 0, 0, 0);
if quart { prog[0] = 2; }
loop {
let op = prog[pos];
if op == 99 { break; }
match op % 100 {
1 => {
let store = write_param(&prog, base, pos, 3);
prog[store] = read_param(&prog, base, pos, 1) + read_param(&prog, base, pos, 2);
pos += 4;
},
2 => {
let store = write_param(&prog, base, pos, 3);
prog[store] = read_param(&prog, base, pos, 1) * read_param(&prog, base, pos, 2);
pos += 4;
},
3 => {
if !quart { panic!("no input given"); }
let store = write_param(&prog, base, pos, 1);
prog[store] = if ball < padl { -1 } else if ball > padl { 1 } else { 0 };
pos += 2;
},
4 => {
let output = read_param(&prog, base, pos, 1);
if wait == 0 { coords.0 = output; }
else if wait == 1 { coords.1 = output; }
else if wait == 2 {
if coords.0 == -1 && coords.1 == 0 { score = output; }
else {
grid[coords.1 as usize][coords.0 as usize] = output;
if !quart && output == 2 { blocks += 1; }
if output == 3 { padl = coords.0 };
if output == 4 { ball = coords.0 };
}
}
wait = (wait + 1) % 3;
pos += 2;
},
5 => pos = if read_param(&prog, base, pos, 1) != 0 { read_param(&prog, base, pos, 2) as usize } else { pos + 3 },
6 => pos = if read_param(&prog, base, pos, 1) == 0 { read_param(&prog, base, pos, 2) as usize } else { pos + 3 },
7 => {
let store = write_param(&prog, base, pos, 3);
prog[store] = if read_param(&prog, base, pos, 1) < read_param(&prog, base, pos, 2) { 1 } else { 0 };
pos += 4;
},
8 => {
let store = write_param(&prog, base, pos, 3);
prog[store] = if read_param(&prog, base, pos, 1) == read_param(&prog, base, pos, 2) { 1 } else { 0 };
pos += 4;
},
9 => {
base += read_param(&prog, base, pos, 1);
pos += 2;
}
_ => panic!("invalid opcode"),
}
}
(blocks, score)
}
fn main() {
let mut prog = read_to_string("in_13.txt").unwrap().trim_end().split(',').map(|int| int.parse::<i32>().unwrap()).collect::<Vec<_>>();
prog.resize(2700, 0);
println!("Part A: {}", run(prog.clone(), false).0); // 258
println!("Part B: {}", run(prog.clone(), true).1); // 12765
}
|
// auto generated, do not modify.
// created: Mon Feb 22 23:57:02 2016
// src-file: /QtGui/qpen.h
// dst-file: /src/gui/qpen.rs
//
// header block begin =>
#![feature(libc)]
#![feature(core)]
#![feature(collections)]
extern crate libc;
use self::libc::*;
// <= header block end
// main block begin =>
// <= main block end
// use block begin =>
use std::ops::Deref;
use super::qcolor::*; // 773
use super::qbrush::*; // 773
// use super::qvector::*; // 775
// <= use block end
// ext block begin =>
// #[link(name = "Qt5Core")]
// #[link(name = "Qt5Gui")]
// #[link(name = "Qt5Widgets")]
// #[link(name = "QtInline")]
extern {
fn QPen_Class_Size() -> c_int;
// proto: void QPen::~QPen();
fn C_ZN4QPenD2Ev(qthis: u64 /* *mut c_void*/);
// proto: qreal QPen::dashOffset();
fn C_ZNK4QPen10dashOffsetEv(qthis: u64 /* *mut c_void*/) -> c_double;
// proto: void QPen::QPen(const QColor & color);
fn C_ZN4QPenC2ERK6QColor(arg0: *mut c_void) -> u64;
// proto: qreal QPen::miterLimit();
fn C_ZNK4QPen10miterLimitEv(qthis: u64 /* *mut c_void*/) -> c_double;
// proto: void QPen::setWidthF(qreal width);
fn C_ZN4QPen9setWidthFEd(qthis: u64 /* *mut c_void*/, arg0: c_double);
// proto: void QPen::setBrush(const QBrush & brush);
fn C_ZN4QPen8setBrushERK6QBrush(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: QColor QPen::color();
fn C_ZNK4QPen5colorEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QPen::setWidth(int width);
fn C_ZN4QPen8setWidthEi(qthis: u64 /* *mut c_void*/, arg0: c_int);
// proto: qreal QPen::widthF();
fn C_ZNK4QPen6widthFEv(qthis: u64 /* *mut c_void*/) -> c_double;
// proto: void QPen::setCosmetic(bool cosmetic);
fn C_ZN4QPen11setCosmeticEb(qthis: u64 /* *mut c_void*/, arg0: c_char);
// proto: bool QPen::isSolid();
fn C_ZNK4QPen7isSolidEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: void QPen::setColor(const QColor & color);
fn C_ZN4QPen8setColorERK6QColor(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: QVector<qreal> QPen::dashPattern();
fn C_ZNK4QPen11dashPatternEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: bool QPen::isDetached();
fn C_ZN4QPen10isDetachedEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: void QPen::QPen(const QPen & pen);
fn C_ZN4QPenC2ERKS_(arg0: *mut c_void) -> u64;
// proto: void QPen::setMiterLimit(qreal limit);
fn C_ZN4QPen13setMiterLimitEd(qthis: u64 /* *mut c_void*/, arg0: c_double);
// proto: void QPen::QPen();
fn C_ZN4QPenC2Ev() -> u64;
// proto: int QPen::width();
fn C_ZNK4QPen5widthEv(qthis: u64 /* *mut c_void*/) -> c_int;
// proto: void QPen::swap(QPen & other);
fn C_ZN4QPen4swapERS_(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: QBrush QPen::brush();
fn C_ZNK4QPen5brushEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: bool QPen::isCosmetic();
fn C_ZNK4QPen10isCosmeticEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: void QPen::setDashOffset(qreal doffset);
fn C_ZN4QPen13setDashOffsetEd(qthis: u64 /* *mut c_void*/, arg0: c_double);
} // <= ext block end
// body block begin =>
// class sizeof(QPen)=8
#[derive(Default)]
pub struct QPen {
// qbase: None,
pub qclsinst: u64 /* *mut c_void*/,
}
impl /*struct*/ QPen {
pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QPen {
return QPen{qclsinst: qthis, ..Default::default()};
}
}
// proto: void QPen::~QPen();
impl /*struct*/ QPen {
pub fn free<RetType, T: QPen_free<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.free(self);
// return 1;
}
}
pub trait QPen_free<RetType> {
fn free(self , rsthis: & QPen) -> RetType;
}
// proto: void QPen::~QPen();
impl<'a> /*trait*/ QPen_free<()> for () {
fn free(self , rsthis: & QPen) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN4QPenD2Ev()};
unsafe {C_ZN4QPenD2Ev(rsthis.qclsinst)};
// return 1;
}
}
// proto: qreal QPen::dashOffset();
impl /*struct*/ QPen {
pub fn dashOffset<RetType, T: QPen_dashOffset<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.dashOffset(self);
// return 1;
}
}
pub trait QPen_dashOffset<RetType> {
fn dashOffset(self , rsthis: & QPen) -> RetType;
}
// proto: qreal QPen::dashOffset();
impl<'a> /*trait*/ QPen_dashOffset<f64> for () {
fn dashOffset(self , rsthis: & QPen) -> f64 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK4QPen10dashOffsetEv()};
let mut ret = unsafe {C_ZNK4QPen10dashOffsetEv(rsthis.qclsinst)};
return ret as f64; // 1
// return 1;
}
}
// proto: void QPen::QPen(const QColor & color);
impl /*struct*/ QPen {
pub fn new<T: QPen_new>(value: T) -> QPen {
let rsthis = value.new();
return rsthis;
// return 1;
}
}
pub trait QPen_new {
fn new(self) -> QPen;
}
// proto: void QPen::QPen(const QColor & color);
impl<'a> /*trait*/ QPen_new for (&'a QColor) {
fn new(self) -> QPen {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN4QPenC2ERK6QColor()};
let ctysz: c_int = unsafe{QPen_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let arg0 = self.qclsinst as *mut c_void;
let qthis: u64 = unsafe {C_ZN4QPenC2ERK6QColor(arg0)};
let rsthis = QPen{qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: qreal QPen::miterLimit();
impl /*struct*/ QPen {
pub fn miterLimit<RetType, T: QPen_miterLimit<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.miterLimit(self);
// return 1;
}
}
pub trait QPen_miterLimit<RetType> {
fn miterLimit(self , rsthis: & QPen) -> RetType;
}
// proto: qreal QPen::miterLimit();
impl<'a> /*trait*/ QPen_miterLimit<f64> for () {
fn miterLimit(self , rsthis: & QPen) -> f64 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK4QPen10miterLimitEv()};
let mut ret = unsafe {C_ZNK4QPen10miterLimitEv(rsthis.qclsinst)};
return ret as f64; // 1
// return 1;
}
}
// proto: void QPen::setWidthF(qreal width);
impl /*struct*/ QPen {
pub fn setWidthF<RetType, T: QPen_setWidthF<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setWidthF(self);
// return 1;
}
}
pub trait QPen_setWidthF<RetType> {
fn setWidthF(self , rsthis: & QPen) -> RetType;
}
// proto: void QPen::setWidthF(qreal width);
impl<'a> /*trait*/ QPen_setWidthF<()> for (f64) {
fn setWidthF(self , rsthis: & QPen) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN4QPen9setWidthFEd()};
let arg0 = self as c_double;
unsafe {C_ZN4QPen9setWidthFEd(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QPen::setBrush(const QBrush & brush);
impl /*struct*/ QPen {
pub fn setBrush<RetType, T: QPen_setBrush<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setBrush(self);
// return 1;
}
}
pub trait QPen_setBrush<RetType> {
fn setBrush(self , rsthis: & QPen) -> RetType;
}
// proto: void QPen::setBrush(const QBrush & brush);
impl<'a> /*trait*/ QPen_setBrush<()> for (&'a QBrush) {
fn setBrush(self , rsthis: & QPen) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN4QPen8setBrushERK6QBrush()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN4QPen8setBrushERK6QBrush(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: QColor QPen::color();
impl /*struct*/ QPen {
pub fn color<RetType, T: QPen_color<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.color(self);
// return 1;
}
}
pub trait QPen_color<RetType> {
fn color(self , rsthis: & QPen) -> RetType;
}
// proto: QColor QPen::color();
impl<'a> /*trait*/ QPen_color<QColor> for () {
fn color(self , rsthis: & QPen) -> QColor {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK4QPen5colorEv()};
let mut ret = unsafe {C_ZNK4QPen5colorEv(rsthis.qclsinst)};
let mut ret1 = QColor::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QPen::setWidth(int width);
impl /*struct*/ QPen {
pub fn setWidth<RetType, T: QPen_setWidth<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setWidth(self);
// return 1;
}
}
pub trait QPen_setWidth<RetType> {
fn setWidth(self , rsthis: & QPen) -> RetType;
}
// proto: void QPen::setWidth(int width);
impl<'a> /*trait*/ QPen_setWidth<()> for (i32) {
fn setWidth(self , rsthis: & QPen) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN4QPen8setWidthEi()};
let arg0 = self as c_int;
unsafe {C_ZN4QPen8setWidthEi(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: qreal QPen::widthF();
impl /*struct*/ QPen {
pub fn widthF<RetType, T: QPen_widthF<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.widthF(self);
// return 1;
}
}
pub trait QPen_widthF<RetType> {
fn widthF(self , rsthis: & QPen) -> RetType;
}
// proto: qreal QPen::widthF();
impl<'a> /*trait*/ QPen_widthF<f64> for () {
fn widthF(self , rsthis: & QPen) -> f64 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK4QPen6widthFEv()};
let mut ret = unsafe {C_ZNK4QPen6widthFEv(rsthis.qclsinst)};
return ret as f64; // 1
// return 1;
}
}
// proto: void QPen::setCosmetic(bool cosmetic);
impl /*struct*/ QPen {
pub fn setCosmetic<RetType, T: QPen_setCosmetic<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setCosmetic(self);
// return 1;
}
}
pub trait QPen_setCosmetic<RetType> {
fn setCosmetic(self , rsthis: & QPen) -> RetType;
}
// proto: void QPen::setCosmetic(bool cosmetic);
impl<'a> /*trait*/ QPen_setCosmetic<()> for (i8) {
fn setCosmetic(self , rsthis: & QPen) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN4QPen11setCosmeticEb()};
let arg0 = self as c_char;
unsafe {C_ZN4QPen11setCosmeticEb(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: bool QPen::isSolid();
impl /*struct*/ QPen {
pub fn isSolid<RetType, T: QPen_isSolid<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isSolid(self);
// return 1;
}
}
pub trait QPen_isSolid<RetType> {
fn isSolid(self , rsthis: & QPen) -> RetType;
}
// proto: bool QPen::isSolid();
impl<'a> /*trait*/ QPen_isSolid<i8> for () {
fn isSolid(self , rsthis: & QPen) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK4QPen7isSolidEv()};
let mut ret = unsafe {C_ZNK4QPen7isSolidEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: void QPen::setColor(const QColor & color);
impl /*struct*/ QPen {
pub fn setColor<RetType, T: QPen_setColor<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setColor(self);
// return 1;
}
}
pub trait QPen_setColor<RetType> {
fn setColor(self , rsthis: & QPen) -> RetType;
}
// proto: void QPen::setColor(const QColor & color);
impl<'a> /*trait*/ QPen_setColor<()> for (&'a QColor) {
fn setColor(self , rsthis: & QPen) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN4QPen8setColorERK6QColor()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN4QPen8setColorERK6QColor(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: QVector<qreal> QPen::dashPattern();
impl /*struct*/ QPen {
pub fn dashPattern<RetType, T: QPen_dashPattern<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.dashPattern(self);
// return 1;
}
}
pub trait QPen_dashPattern<RetType> {
fn dashPattern(self , rsthis: & QPen) -> RetType;
}
// proto: QVector<qreal> QPen::dashPattern();
impl<'a> /*trait*/ QPen_dashPattern<u64> for () {
fn dashPattern(self , rsthis: & QPen) -> u64 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK4QPen11dashPatternEv()};
let mut ret = unsafe {C_ZNK4QPen11dashPatternEv(rsthis.qclsinst)};
return ret as u64; // 5
// return 1;
}
}
// proto: bool QPen::isDetached();
impl /*struct*/ QPen {
pub fn isDetached<RetType, T: QPen_isDetached<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isDetached(self);
// return 1;
}
}
pub trait QPen_isDetached<RetType> {
fn isDetached(self , rsthis: & QPen) -> RetType;
}
// proto: bool QPen::isDetached();
impl<'a> /*trait*/ QPen_isDetached<i8> for () {
fn isDetached(self , rsthis: & QPen) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN4QPen10isDetachedEv()};
let mut ret = unsafe {C_ZN4QPen10isDetachedEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: void QPen::QPen(const QPen & pen);
impl<'a> /*trait*/ QPen_new for (&'a QPen) {
fn new(self) -> QPen {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN4QPenC2ERKS_()};
let ctysz: c_int = unsafe{QPen_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let arg0 = self.qclsinst as *mut c_void;
let qthis: u64 = unsafe {C_ZN4QPenC2ERKS_(arg0)};
let rsthis = QPen{qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: void QPen::setMiterLimit(qreal limit);
impl /*struct*/ QPen {
pub fn setMiterLimit<RetType, T: QPen_setMiterLimit<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setMiterLimit(self);
// return 1;
}
}
pub trait QPen_setMiterLimit<RetType> {
fn setMiterLimit(self , rsthis: & QPen) -> RetType;
}
// proto: void QPen::setMiterLimit(qreal limit);
impl<'a> /*trait*/ QPen_setMiterLimit<()> for (f64) {
fn setMiterLimit(self , rsthis: & QPen) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN4QPen13setMiterLimitEd()};
let arg0 = self as c_double;
unsafe {C_ZN4QPen13setMiterLimitEd(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QPen::QPen();
impl<'a> /*trait*/ QPen_new for () {
fn new(self) -> QPen {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN4QPenC2Ev()};
let ctysz: c_int = unsafe{QPen_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let qthis: u64 = unsafe {C_ZN4QPenC2Ev()};
let rsthis = QPen{qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: int QPen::width();
impl /*struct*/ QPen {
pub fn width<RetType, T: QPen_width<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.width(self);
// return 1;
}
}
pub trait QPen_width<RetType> {
fn width(self , rsthis: & QPen) -> RetType;
}
// proto: int QPen::width();
impl<'a> /*trait*/ QPen_width<i32> for () {
fn width(self , rsthis: & QPen) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK4QPen5widthEv()};
let mut ret = unsafe {C_ZNK4QPen5widthEv(rsthis.qclsinst)};
return ret as i32; // 1
// return 1;
}
}
// proto: void QPen::swap(QPen & other);
impl /*struct*/ QPen {
pub fn swap<RetType, T: QPen_swap<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.swap(self);
// return 1;
}
}
pub trait QPen_swap<RetType> {
fn swap(self , rsthis: & QPen) -> RetType;
}
// proto: void QPen::swap(QPen & other);
impl<'a> /*trait*/ QPen_swap<()> for (&'a QPen) {
fn swap(self , rsthis: & QPen) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN4QPen4swapERS_()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN4QPen4swapERS_(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: QBrush QPen::brush();
impl /*struct*/ QPen {
pub fn brush<RetType, T: QPen_brush<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.brush(self);
// return 1;
}
}
pub trait QPen_brush<RetType> {
fn brush(self , rsthis: & QPen) -> RetType;
}
// proto: QBrush QPen::brush();
impl<'a> /*trait*/ QPen_brush<QBrush> for () {
fn brush(self , rsthis: & QPen) -> QBrush {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK4QPen5brushEv()};
let mut ret = unsafe {C_ZNK4QPen5brushEv(rsthis.qclsinst)};
let mut ret1 = QBrush::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: bool QPen::isCosmetic();
impl /*struct*/ QPen {
pub fn isCosmetic<RetType, T: QPen_isCosmetic<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isCosmetic(self);
// return 1;
}
}
pub trait QPen_isCosmetic<RetType> {
fn isCosmetic(self , rsthis: & QPen) -> RetType;
}
// proto: bool QPen::isCosmetic();
impl<'a> /*trait*/ QPen_isCosmetic<i8> for () {
fn isCosmetic(self , rsthis: & QPen) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK4QPen10isCosmeticEv()};
let mut ret = unsafe {C_ZNK4QPen10isCosmeticEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: void QPen::setDashOffset(qreal doffset);
impl /*struct*/ QPen {
pub fn setDashOffset<RetType, T: QPen_setDashOffset<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setDashOffset(self);
// return 1;
}
}
pub trait QPen_setDashOffset<RetType> {
fn setDashOffset(self , rsthis: & QPen) -> RetType;
}
// proto: void QPen::setDashOffset(qreal doffset);
impl<'a> /*trait*/ QPen_setDashOffset<()> for (f64) {
fn setDashOffset(self , rsthis: & QPen) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN4QPen13setDashOffsetEd()};
let arg0 = self as c_double;
unsafe {C_ZN4QPen13setDashOffsetEd(rsthis.qclsinst, arg0)};
// return 1;
}
}
// <= body block end
|
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#[cfg(target_arch = "aarch64")]
mod hos {
use cell::UnsafeCell;
use mem;
pub struct Mutex {
inner: UnsafeCell<libnx::Mutex>,
}
#[inline]
pub unsafe fn raw(m: &Mutex) -> *mut libnx::Mutex {
m.inner.get()
}
unsafe impl Send for Mutex {}
unsafe impl Sync for Mutex {}
#[cfg(target_arch = "aarch64")]
impl Mutex {
pub const fn new() -> Mutex {
Mutex { inner: UnsafeCell::new(0) }
}
#[inline]
pub unsafe fn init(&mut self) {
self.inner = UnsafeCell::new(0);
}
#[inline]
pub unsafe fn lock(&self) {
libnx::mutexLock(self.inner.get());
}
#[inline]
pub unsafe fn unlock(&self) {
libnx::mutexUnlock(self.inner.get());
}
#[inline]
pub unsafe fn try_lock(&self) -> bool {
libnx::mutexTryLock(self.inner.get())
}
#[inline]
pub unsafe fn destroy(&self) {
}
}
pub struct ReentrantMutex { inner: UnsafeCell<libnx::RMutex> }
unsafe impl Send for ReentrantMutex {}
unsafe impl Sync for ReentrantMutex {}
impl ReentrantMutex {
pub unsafe fn uninitialized() -> ReentrantMutex {
ReentrantMutex {
inner: UnsafeCell::new(libnx::RMutex {
lock : 0,
thread_tag : 0,
counter : 0,
})
}
}
pub unsafe fn init(&mut self) {
let mtx = libnx::RMutex {
lock : 0,
thread_tag : 0,
counter : 0
};
self.inner = UnsafeCell::new(mtx);
}
pub unsafe fn lock(&self) {
libnx::rmutexLock(self.inner.get());
}
#[inline]
pub unsafe fn try_lock(&self) -> bool {
libnx::rmutexTryLock(self.inner.get())
}
pub unsafe fn unlock(&self) {
libnx::rmutexUnlock(self.inner.get());
}
pub unsafe fn destroy(&self) {}
}
}
#[cfg(target_arch = "aarch64")]
pub use self::hos::*;
|
import std.map.hashmap;
import std.option;
import std._vec;
import util.common.span;
import util.common.spanned;
import util.common.ty_mach;
import util.common.filename;
import util.typestate_ann.ts_ann;
type ident = str;
type path_ = rec(vec[ident] idents, vec[@ty] types);
type path = spanned[path_];
type crate_num = int;
type def_num = int;
type def_id = tup(crate_num, def_num);
type ty_param = ident;
// Annotations added during successive passes.
tag ann {
ann_none;
ann_type(@middle.ty.t,
option.t[vec[@middle.ty.t]], /* ty param substs */
option.t[@ts_ann]); /* pre- and postcondition for typestate */
}
tag def {
def_fn(def_id);
def_obj(def_id);
def_obj_field(def_id);
def_mod(def_id);
def_native_mod(def_id);
def_const(def_id);
def_arg(def_id);
def_local(def_id);
def_upvar(def_id);
def_variant(def_id /* tag */, def_id /* variant */);
def_ty(def_id);
def_ty_arg(uint);
def_binding(def_id);
def_use(def_id);
def_native_ty(def_id);
def_native_fn(def_id);
}
fn def_id_of_def(def d) -> def_id {
alt (d) {
case (def_fn(?id)) { ret id; }
case (def_obj(?id)) { ret id; }
case (def_obj_field(?id)) { ret id; }
case (def_mod(?id)) { ret id; }
case (def_native_mod(?id)) { ret id; }
case (def_const(?id)) { ret id; }
case (def_arg(?id)) { ret id; }
case (def_local(?id)) { ret id; }
case (def_upvar(?id)) { ret id; }
case (def_variant(_, ?id)) { ret id; }
case (def_ty(?id)) { ret id; }
case (def_ty_arg(_)) { fail; }
case (def_binding(?id)) { ret id; }
case (def_use(?id)) { ret id; }
case (def_native_ty(?id)) { ret id; }
case (def_native_fn(?id)) { ret id; }
}
fail;
}
type crate = spanned[crate_];
type crate_ = rec(vec[@crate_directive] directives,
_mod module);
tag crate_directive_ {
cdir_expr(@expr);
// FIXME: cdir_let should be eliminated
// and redirected to the use of const stmt_decls inside
// crate directive blocks.
cdir_let(ident, @expr, vec[@crate_directive]);
cdir_src_mod(ident, option.t[filename]);
cdir_dir_mod(ident, option.t[filename], vec[@crate_directive]);
cdir_view_item(@view_item);
cdir_meta(vec[@meta_item]);
cdir_syntax(path);
cdir_auth(path, _auth);
}
type crate_directive = spanned[crate_directive_];
type meta_item = spanned[meta_item_];
type meta_item_ = rec(ident name, str value);
type block = spanned[block_];
type block_index = hashmap[ident, block_index_entry];
tag block_index_entry {
bie_item(@item);
bie_local(@local);
bie_tag_variant(@item /* tag item */, uint /* variant index */);
}
type block_ = rec(vec[@stmt] stmts,
option.t[@expr] expr,
hashmap[ident,block_index_entry] index,
ann a); /* ann is only meaningful for the ts_ann field */
type variant_def = tup(def_id /* tag */, def_id /* variant */);
type pat = spanned[pat_];
tag pat_ {
pat_wild(ann);
pat_bind(ident, def_id, ann);
pat_lit(@lit, ann);
pat_tag(path, vec[@pat], option.t[variant_def], ann);
}
tag mutability {
mut;
imm;
maybe_mut;
}
tag layer {
layer_value;
layer_state;
layer_gc;
}
tag _auth {
auth_unsafe;
}
tag proto {
proto_iter;
proto_fn;
}
tag binop {
add;
sub;
mul;
div;
rem;
and;
or;
bitxor;
bitand;
bitor;
lsl;
lsr;
asr;
eq;
lt;
le;
ne;
ge;
gt;
}
fn binop_to_str(binop op) -> str {
alt (op) {
case (add) {ret "+";}
case (sub) {ret "-";}
case (mul) {ret "*";}
case (div) {ret "/";}
case (rem) {ret "%";}
case (and) {ret "&&";}
case (or) {ret "||";}
case (bitxor) {ret "^";}
case (bitand) {ret "&";}
case (bitor) {ret "|";}
case (lsl) {ret "<<";}
case (lsr) {ret ">>";}
case (asr) {ret ">>>";}
case (eq) {ret "==";}
case (lt) {ret "<";}
case (le) {ret "<=";}
case (ne) {ret "!=";}
case (ge) {ret ">=";}
case (gt) {ret ">";}
}
}
tag unop {
box(mutability);
deref;
bitnot;
not;
neg;
}
fn unop_to_str(unop op) -> str {
alt (op) {
case (box(?mt)) {
if (mt == mut) { ret "@mutable"; }
ret "@";
}
case (deref) {ret "*";}
case (bitnot) {ret "~";}
case (not) {ret "!";}
case (neg) {ret "-";}
}
}
tag mode {
val;
alias;
}
type stmt = spanned[stmt_];
tag stmt_ {
/* Only the ts_ann field is meaningful for statements,
but we make it an ann to make traversals simpler */
stmt_decl(@decl, ann);
stmt_expr(@expr, ann);
// These only exist in crate-level blocks.
stmt_crate_directive(@crate_directive);
}
tag init_op {
init_assign;
init_recv;
}
type initializer = rec(init_op op,
@expr expr);
type local = rec(option.t[@ty] ty,
bool infer,
ident ident,
option.t[initializer] init,
def_id id,
ann ann);
type decl = spanned[decl_];
tag decl_ {
decl_local(@local);
decl_item(@item);
}
type arm = rec(@pat pat, block block, hashmap[ident,def_id] index);
type elt = rec(mutability mut, @expr expr);
type field = rec(mutability mut, ident ident, @expr expr);
tag spawn_dom {
dom_implicit;
dom_thread;
}
type expr = spanned[expr_];
tag expr_ {
expr_vec(vec[@expr], mutability, ann);
expr_tup(vec[elt], ann);
expr_rec(vec[field], option.t[@expr], ann);
expr_call(@expr, vec[@expr], ann);
expr_self_method(ident, ann);
expr_bind(@expr, vec[option.t[@expr]], ann);
expr_spawn(spawn_dom, option.t[str], @expr, vec[@expr], ann);
expr_binary(binop, @expr, @expr, ann);
expr_unary(unop, @expr, ann);
expr_lit(@lit, ann);
expr_cast(@expr, @ty, ann);
expr_if(@expr, block, option.t[@expr], ann);
expr_while(@expr, block, ann);
expr_for(@decl, @expr, block, ann);
expr_for_each(@decl, @expr, block, ann);
expr_do_while(block, @expr, ann);
expr_alt(@expr, vec[arm], ann);
expr_block(block, ann);
expr_assign(@expr /* TODO: @expr|is_lval */, @expr, ann);
expr_assign_op(binop, @expr /* TODO: @expr|is_lval */, @expr, ann);
expr_send(@expr /* TODO: @expr|is_lval */, @expr, ann);
expr_recv(@expr /* TODO: @expr|is_lval */, @expr, ann);
expr_field(@expr, ident, ann);
expr_index(@expr, @expr, ann);
expr_path(path, option.t[def], ann);
expr_ext(path, vec[@expr], option.t[@expr], @expr, ann);
expr_fail(ann);
expr_break(ann);
expr_cont(ann);
expr_ret(option.t[@expr], ann);
expr_put(option.t[@expr], ann);
expr_be(@expr, ann);
expr_log(int, @expr, ann);
expr_check_expr(@expr, ann);
expr_port(ann);
expr_chan(@expr, ann);
}
type lit = spanned[lit_];
tag lit_ {
lit_str(str);
lit_char(char);
lit_int(int);
lit_uint(uint);
lit_mach_int(ty_mach, int);
lit_float(str);
lit_mach_float(ty_mach, str);
lit_nil;
lit_bool(bool);
}
// NB: If you change this, you'll probably want to change the corresponding
// type structure in middle/ty.rs as well.
type mt = rec(@ty ty, mutability mut);
type ty_field = rec(ident ident, mt mt);
type ty_arg = rec(mode mode, @ty ty);
type ty_method = rec(proto proto, ident ident,
vec[ty_arg] inputs, @ty output);
type ty = spanned[ty_];
tag ty_ {
ty_nil;
ty_bool;
ty_int;
ty_uint;
ty_float;
ty_machine(util.common.ty_mach);
ty_char;
ty_str;
ty_box(mt);
ty_vec(mt);
ty_port(@ty);
ty_chan(@ty);
ty_tup(vec[mt]);
ty_rec(vec[ty_field]);
ty_fn(proto, vec[ty_arg], @ty);
ty_obj(vec[ty_method]);
ty_path(path, option.t[def]);
ty_type;
ty_constr(@ty, vec[@constr]);
}
tag constr_arg_ {
carg_base;
carg_ident(ident);
}
type constr_arg = spanned[constr_arg_];
type constr_ = rec(path path, vec[@constr_arg] args);
type constr = spanned[constr_];
type arg = rec(mode mode, @ty ty, ident ident, def_id id);
type fn_decl = rec(vec[arg] inputs,
@ty output);
type _fn = rec(fn_decl decl,
proto proto,
block body);
type method_ = rec(ident ident, _fn meth, def_id id, ann ann);
type method = spanned[method_];
type obj_field = rec(@ty ty, ident ident, def_id id, ann ann);
type _obj = rec(vec[obj_field] fields,
vec[@method] methods,
option.t[@method] dtor);
tag mod_index_entry {
mie_view_item(@view_item);
mie_item(@item);
mie_tag_variant(@item /* tag item */, uint /* variant index */);
}
tag native_mod_index_entry {
nmie_view_item(@view_item);
nmie_item(@native_item);
}
type mod_index = hashmap[ident,mod_index_entry];
type _mod = rec(vec[@view_item] view_items,
vec[@item] items,
mod_index index);
tag native_abi {
native_abi_rust;
native_abi_cdecl;
native_abi_llvm;
}
type native_mod = rec(str native_name,
native_abi abi,
vec[@view_item] view_items,
vec[@native_item] items,
native_mod_index index);
type native_mod_index = hashmap[ident,native_mod_index_entry];
type variant_arg = rec(@ty ty, def_id id);
type variant_ = rec(str name, vec[variant_arg] args, def_id id, ann ann);
type variant = spanned[variant_];
type view_item = spanned[view_item_];
tag view_item_ {
view_item_use(ident, vec[@meta_item], def_id, option.t[int]);
view_item_import(ident, vec[ident], def_id, option.t[def]);
view_item_export(ident);
}
type obj_def_ids = rec(def_id ty, def_id ctor);
type item = spanned[item_];
tag item_ {
item_const(ident, @ty, @expr, def_id, ann);
item_fn(ident, _fn, vec[ty_param], def_id, ann);
item_mod(ident, _mod, def_id);
item_native_mod(ident, native_mod, def_id);
item_ty(ident, @ty, vec[ty_param], def_id, ann);
item_tag(ident, vec[variant], vec[ty_param], def_id, ann);
item_obj(ident, _obj, vec[ty_param], obj_def_ids, ann);
}
type native_item = spanned[native_item_];
tag native_item_ {
native_item_ty(ident, def_id);
native_item_fn(ident, option.t[str],
fn_decl, vec[ty_param], def_id, ann);
}
fn index_view_item(mod_index index, @view_item it) {
alt (it.node) {
case(ast.view_item_use(?id, _, _, _)) {
index.insert(id, ast.mie_view_item(it));
}
case(ast.view_item_import(?def_ident,_,_,_)) {
index.insert(def_ident, ast.mie_view_item(it));
}
case(ast.view_item_export(_)) {
// NB: don't index these, they might collide with
// the import or use that they're exporting. Have
// to do linear search for exports.
}
}
}
fn index_item(mod_index index, @item it) {
alt (it.node) {
case (ast.item_const(?id, _, _, _, _)) {
index.insert(id, ast.mie_item(it));
}
case (ast.item_fn(?id, _, _, _, _)) {
index.insert(id, ast.mie_item(it));
}
case (ast.item_mod(?id, _, _)) {
index.insert(id, ast.mie_item(it));
}
case (ast.item_native_mod(?id, _, _)) {
index.insert(id, ast.mie_item(it));
}
case (ast.item_ty(?id, _, _, _, _)) {
index.insert(id, ast.mie_item(it));
}
case (ast.item_tag(?id, ?variants, _, _, _)) {
index.insert(id, ast.mie_item(it));
let uint variant_idx = 0u;
for (ast.variant v in variants) {
index.insert(v.node.name,
ast.mie_tag_variant(it, variant_idx));
variant_idx += 1u;
}
}
case (ast.item_obj(?id, _, _, _, _)) {
index.insert(id, ast.mie_item(it));
}
}
}
fn index_native_item(native_mod_index index, @native_item it) {
alt (it.node) {
case (ast.native_item_ty(?id, _)) {
index.insert(id, ast.nmie_item(it));
}
case (ast.native_item_fn(?id, _, _, _, _, _)) {
index.insert(id, ast.nmie_item(it));
}
}
}
fn index_native_view_item(native_mod_index index, @view_item it) {
alt (it.node) {
case(ast.view_item_import(?def_ident,_,_,_)) {
index.insert(def_ident, ast.nmie_view_item(it));
}
case(ast.view_item_export(_)) {
// NB: don't index these, they might collide with
// the import or use that they're exporting. Have
// to do linear search for exports.
}
}
}
fn index_stmt(block_index index, @stmt s) {
alt (s.node) {
case (ast.stmt_decl(?d,_)) {
alt (d.node) {
case (ast.decl_local(?loc)) {
index.insert(loc.ident, ast.bie_local(loc));
}
case (ast.decl_item(?it)) {
alt (it.node) {
case (ast.item_fn(?i, _, _, _, _)) {
index.insert(i, ast.bie_item(it));
}
case (ast.item_mod(?i, _, _)) {
index.insert(i, ast.bie_item(it));
}
case (ast.item_ty(?i, _, _, _, _)) {
index.insert(i, ast.bie_item(it));
}
case (ast.item_tag(?i, ?variants, _, _, _)) {
index.insert(i, ast.bie_item(it));
let uint vid = 0u;
for (ast.variant v in variants) {
auto t = ast.bie_tag_variant(it, vid);
index.insert(v.node.name, t);
vid += 1u;
}
}
case (ast.item_obj(?i, _, _, _, _)) {
index.insert(i, ast.bie_item(it));
}
}
}
}
}
case (_) { /* fall through */ }
}
}
fn is_call_expr(@expr e) -> bool {
alt (e.node) {
case (expr_call(_, _, _)) {
ret true;
}
case (_) {
ret false;
}
}
}
//
// Local Variables:
// mode: rust
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// compile-command: "make -k -C $RBUILD 2>&1 | sed -e 's/\\/x\\//x:\\//g'";
// End:
//
|
use super::request_handler::RequestHandler;
use bytesize::ByteSize;
use std::time::Duration;
/// Configuration for the server.
pub struct Config<R: RequestHandler> {
/// Handler for push and request.
pub request_handler: R,
/// Maximum size of the payload part of a loqui frame.
pub max_payload_size: ByteSize,
/// The duration between ping frames being sent.
pub ping_interval: Duration,
/// The duration before we give up handshaking.
pub handshake_timeout: Duration,
/// Supported encodings.
pub supported_encodings: &'static [&'static str],
}
|
fn main() {
println!("--output--");
for (i, arg) in std::env::args().enumerate() {
println!("{:>4}: {:?}", format!("[{}]", i), arg);
}
}
|
use rotor_http;
|
fn main(){
proconio::input!{n:u64,k:u64};
let m = n % k;
println!("{}",m.min(k-m))
} |
use crate::{RAMCORE_SYMBOL, RAMMARKET, SELF};
use eosio::*;
use eosio_cdt::*;
use lazy_static::lazy_static;
/// Defines new global state parameters.
/// <https://github.com/EOSIO/eosio.contracts/blob/v1.9.0-rc3/contracts/eosio.system/include/eosio.system/eosio.system.hpp#L120-L145>
#[derive(Table, Read, Write, NumBytes)]
#[eosio(table_name = "global", singleton)]
pub struct EosioGlobalState {
pub blockchain_parameters: BlockchainParameters,
pub max_ram_size: u64,
pub total_ram_bytes_reserved: u64,
pub total_ram_stake: i64,
pub last_producer_schedule_update: BlockTimestamp,
pub last_pervote_bucket_fill: TimePoint,
pub pervote_bucket: i64,
pub perblock_bucket: i64,
/// all blocks which have been produced but not paid
pub total_unpaid_blocks: u32,
pub total_activated_stake: i64,
pub thresh_activated_stake_time: TimePoint,
pub last_producer_schedule_size: u16,
/// the sum of all producer votes
pub total_producer_vote_weight: f64,
pub last_name_close: BlockTimestamp,
}
impl Default for EosioGlobalState {
fn default() -> Self {
Self {
blockchain_parameters: get_blockchain_parameters().expect("read"),
max_ram_size: 64 * 1024 * 1024 * 1024,
total_ram_bytes_reserved: 0,
total_ram_stake: 0,
last_producer_schedule_update: 0.into(),
last_pervote_bucket_fill: 0.into(),
pervote_bucket: 0,
perblock_bucket: 0,
total_unpaid_blocks: 0,
total_activated_stake: 0,
thresh_activated_stake_time: 0.into(),
last_producer_schedule_size: 0,
total_producer_vote_weight: 0.0,
last_name_close: 0.into(),
}
}
}
/// Defines new global state parameters added after version 1.0
/// <https://github.com/EOSIO/eosio.contracts/blob/v1.9.0-rc3/contracts/eosio.system/include/eosio.system/eosio.system.hpp#L147-L159>
#[derive(Table, Read, Write, NumBytes, Default)]
#[eosio(table_name = "global2", singleton)]
pub struct EosioGlobalState2 {
pub new_ram_per_block: u16,
pub last_ram_increase: BlockTimestamp,
pub last_block_num: BlockTimestamp,
pub total_producer_votepay_share: f64,
pub revision: u8,
}
/// Defines new global state parameters added after version 1.3.0
/// <https://github.com/EOSIO/eosio.contracts/blob/v1.9.0-rc3/contracts/eosio.system/include/eosio.system/eosio.system.hpp#L161-L168>
#[derive(Table, Read, Write, NumBytes)]
#[eosio(table_name = "global3", singleton)]
pub struct EosioGlobalState3 {
pub last_vpay_state_update: TimePoint,
pub total_vpay_share_change_rate: f64,
}
#[derive(Table, Read, Write, NumBytes)]
#[eosio(table_name = "global4", singleton)]
pub struct EosioGlobalState4 {
pub continuous_rate: f64,
pub inflation_pay_factor: i64,
pub votepay_factor: i64,
}
lazy_static! {
pub static ref GLOBAL: SingletonIndex<EosioGlobalState> =
EosioGlobalState::singleton(*SELF, *SELF);
pub static ref GLOBAL2: SingletonIndex<EosioGlobalState2> =
EosioGlobalState2::singleton(*SELF, *SELF);
pub static ref GLOBAL3: SingletonIndex<EosioGlobalState3> =
EosioGlobalState3::singleton(*SELF, *SELF);
pub static ref GLOBAL4: SingletonIndex<EosioGlobalState4> =
EosioGlobalState4::singleton(*SELF, *SELF);
}
/// <https://github.com/EOSIO/eosio.contracts/blob/v1.9.0-rc3/contracts/eosio.system/src/eosio.system.cpp#L66-L84>
#[eosio::action]
pub fn setram(max_ram_size: u64) {
require_auth(*SELF);
let mut gstate = GLOBAL.get_or_default().expect("read");
// decreasing ram might result market maker issues
assert!(
gstate.max_ram_size < max_ram_size,
"ram may only be increased"
);
assert!(
max_ram_size < 1024 * 1024 * 1024 * 1024 * 1024,
"ram size is unrealistic"
);
assert!(
max_ram_size > gstate.total_ram_bytes_reserved,
"attempt to set max below reserved"
);
// Increase the amount of ram for sale based upon the change in max ram size.
let cursor = RAMMARKET
.find(RAMCORE_SYMBOL)
.expect("failed to find RAMCORE market");
let mut market = cursor.get().expect("read");
market.base.balance.amount +=
max_ram_size.saturating_sub(gstate.max_ram_size) as i64;
cursor.modify(Payer::Same, market).expect("write");
gstate.max_ram_size = max_ram_size;
GLOBAL.set(&gstate, *SELF).expect("write");
}
/// <https://github.com/EOSIO/eosio.contracts/blob/v1.9.0-rc3/contracts/eosio.system/src/eosio.system.cpp#L104-L109>
#[eosio::action]
pub fn setramrate(bytes_per_block: u16) {
require_auth(*SELF);
let mut gstate = GLOBAL.get_or_default().expect("read");
let mut gstate2 = GLOBAL2.get_or_default().expect("read");
let cbt = current_block_time();
if cbt <= gstate2.last_ram_increase {
return;
}
let cursor = RAMMARKET
.find(RAMCORE_SYMBOL)
.expect("failed to find RAMCORE market");
let mut market = cursor.get().expect("read");
}
/// <https://github.com/EOSIO/eosio.contracts/blob/v1.9.0-rc3/contracts/eosio.system/src/eosio.system.cpp#L111-L116>
#[eosio::action]
pub fn setparams(params: BlockchainParameters) {}
/// <https://github.com/EOSIO/eosio.contracts/blob/v1.9.0-rc3/contracts/eosio.system/src/eosio.system.cpp#L118-L121>
#[eosio::action]
pub fn setpriv(account: AccountName, is_priv: u8) {}
/// Set account limits action sets the resource limits of an account
///
/// @param account - name of the account whose resource limit to be set,
/// @param ram_bytes - ram limit in absolute bytes,
/// @param net_weight - fractionally proportionate net limit of available resources based on (weight / total_weight_of_all_accounts),
/// @param cpu_weight - fractionally proportionate cpu limit of available resources based on (weight / total_weight_of_all_accounts).
///
/// <https://github.com/EOSIO/eosio.contracts/blob/v1.9.0-rc3/contracts/eosio.system/src/eosio.system.cpp#L123-L139>
#[eosio::action]
pub fn setalimits(
account: AccountName,
ram_bytes: i64,
net_weight: i64,
cpu_weight: i64,
) {
}
/// <https://github.com/EOSIO/eosio.contracts/blob/v1.9.0-rc3/contracts/eosio.system/src/eosio.system.cpp#L141-L184>
#[eosio::action]
pub fn setacctram(account: AccountName, ram_bytes: Option<i64>) {}
/// <https://github.com/EOSIO/eosio.contracts/blob/v1.9.0-rc3/contracts/eosio.system/src/eosio.system.cpp#L186-L228>
#[eosio::action]
pub fn setacctnet(account: AccountName, net_weight: Option<i64>) {}
/// <https://github.com/EOSIO/eosio.contracts/blob/v1.9.0-rc3/contracts/eosio.system/src/eosio.system.cpp#L230-L272>
#[eosio::action]
pub fn setacctcpu(account: AccountName, cpu_weight: Option<i64>) {}
/// <https://github.com/EOSIO/eosio.contracts/blob/v1.9.0-rc3/contracts/eosio.system/src/eosio.system.cpp#L274-L277>
#[eosio::action]
pub fn activate(feature_digest: Checksum256) {}
/// <https://github.com/EOSIO/eosio.contracts/blob/v1.9.0-rc3/contracts/eosio.system/src/eosio.system.cpp#L279-L286>
#[eosio::action]
pub fn rmvproducer(producer: AccountName) {}
/// <https://github.com/EOSIO/eosio.contracts/blob/v1.9.0-rc3/contracts/eosio.system/src/eosio.system.cpp#L288-L295>
#[eosio::action]
pub fn updtrevision(revision: u8) {}
/// <https://github.com/EOSIO/eosio.contracts/blob/v1.9.0-rc3/contracts/eosio.system/src/eosio.system.cpp#L297-L310>
#[eosio::action]
pub fn setinflation(
annual_rate: i64,
inflation_pay_factor: i64,
votepay_factor: i64,
) {
}
/// The Init action initializes the system contract for a version and a symbol.
/// Only succeeds when:
/// - version is 0 and
/// - symbol is found and
/// - system token supply is greater than 0,
/// - and system contract wasn’t already been initialized.
///
/// @param version - the version, has to be 0,
/// @param core - the system symbol.
/// <https://github.com/EOSIO/eosio.contracts/blob/v1.9.0-rc3/contracts/eosio.system/src/eosio.system.cpp#L375-L397>
#[eosio::action]
pub fn init(version: UnsignedInt, core: Symbol) {}
|
use std::{cell::RefCell, rc::Rc};
pub struct LinkedList<T: Clone + Default> {
head: Option<Rc<RefCell<Node<T>>>>,
tail: Option<Rc<RefCell<Node<T>>>>,
}
#[derive(Clone)]
pub struct Node<T: Clone + Default> {
pub value: T,
next_node: Option<Rc<RefCell<Node<T>>>>,
prev_node: Option<Rc<RefCell<Node<T>>>>,
}
pub struct LinkedListIter<T: Clone + Default> {
head: Option<Rc<RefCell<Node<T>>>>,
cur_node: Option<Rc<RefCell<Node<T>>>>,
}
impl<T: Clone + Default> Node<T> {
fn new() -> Node<T> {
Node {
value: T::default(),
next_node: None,
prev_node: None,
}
}
pub fn next(&self) -> Node<T> {
if self.next_node.is_some() {
let next_ref = self.next_node.as_ref();
let next_unwrap = next_ref.unwrap();
let next_borrow = next_unwrap.borrow();
next_borrow.clone()
} else {
panic!("No `next` available!");
}
}
pub fn prev(&self) -> Node<T> {
if self.prev_node.is_some() {
let prev_ref = self.prev_node.as_ref();
let prev_unwrap = prev_ref.unwrap();
let prev_borrow = prev_unwrap.borrow();
prev_borrow.clone()
} else {
panic!("No `prev` available!");
}
}
pub fn mutate(&self, value: T) {
let next_node = self.next_node.clone();
let this_node = next_node.unwrap().borrow().prev_node.clone().unwrap();
this_node.borrow_mut().value = value;
}
}
impl<T: Clone + Default> LinkedList<T> {
pub fn new() -> LinkedList<T> {
LinkedList {
head: None,
tail: None,
}
}
pub fn add(&mut self, value: T) {
let mut new_node = Node::<T>::new();
new_node.value = value;
let link = Rc::new(RefCell::new(new_node));
let mut node_ref = link.borrow_mut();
if self.head.is_none() {
node_ref.next_node = Some(link.clone());
node_ref.prev_node = Some(link.clone());
self.head = Some(link.clone());
self.tail = Some(link.clone());
} else {
let head = self.head.take().unwrap();
let tail = self.tail.take().unwrap();
node_ref.prev_node = Some(tail.clone());
node_ref.next_node = Some(head.clone());
head.borrow_mut().prev_node = Some(link.clone());
tail.borrow_mut().next_node = Some(link.clone());
self.head = Some(head);
self.tail = Some(link.clone());
}
}
pub fn head(&self) -> Node<T> {
if self.head.is_none() {
panic!("`LinkedList` is not built!");
}
let head_link = self.head.clone();
let head_unwrap = head_link.unwrap();
let head_ref = head_unwrap.borrow();
head_ref.clone()
}
pub fn tail(&self) -> Node<T> {
if self.tail.is_none() {
panic!("`LinkedList` is not built!");
}
let tail_link = self.tail.clone();
let tail_unwrap = tail_link.unwrap();
let tail_ref = tail_unwrap.borrow();
tail_ref.clone()
}
pub fn is_tail(&self, node: &Node<T>) -> bool {
let next_node = node.next_node.clone();
let next_unwrap = next_node.unwrap();
let cur_node = next_unwrap.borrow().prev_node.clone().unwrap();
if Rc::ptr_eq(&self.tail.clone().unwrap(), &cur_node) {
true
} else {
false
}
}
pub fn is_head(&self, node: &Node<T>) -> bool {
let next_node = node.next_node.clone();
let next_unwrap = next_node.unwrap();
let cur_node = next_unwrap.borrow().prev_node.clone().unwrap();
if Rc::ptr_eq(&self.head.clone().unwrap(), &cur_node) {
true
} else {
false
}
}
pub fn iter(&self) -> LinkedListIter<T> {
LinkedListIter {
head: self.head.clone(),
cur_node: self.head.clone(),
}
}
}
impl<T: Clone + Default> Iterator for LinkedListIter<T> {
type Item = Node<T>;
fn next(&mut self) -> Option<Self::Item> {
if self.cur_node.is_none() {
None
} else {
let cur_t = self.cur_node.clone().unwrap().borrow().clone();
let next = self.cur_node.clone().unwrap().borrow().clone().next_node;
if Rc::ptr_eq(&self.head.clone().unwrap(), &next.clone().unwrap()) {
self.cur_node = None;
} else {
self.cur_node = next;
}
Some(cur_t)
}
}
}
impl<T: Clone + Default> DoubleEndedIterator for LinkedListIter<T> {
fn next_back(&mut self) -> Option<Node<T>> {
if self.cur_node.is_none() {
None
} else {
let next_back = self.cur_node.clone().unwrap().borrow().prev_node.clone();
if Rc::ptr_eq(&self.head.clone().unwrap(), &next_back.clone().unwrap()) {
self.cur_node = None;
} else {
self.cur_node = next_back.clone();
}
Some(next_back.clone().unwrap().borrow().clone())
}
}
}
|
use std::str::FromStr;
use std::string::ToString;
use std::sync::Arc;
mod original;
pub use original::*;
mod mobility;
pub use mobility::*;
mod flood;
pub use flood::*;
mod random;
pub use random::*;
pub mod maxn;
mod solo;
pub use solo::*;
use crate::game::Game;
use super::env::{GameRequest, MoveResponse};
const MAX_BOARD_SIZE: usize = 19;
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(deny_unknown_fields)]
pub enum Agent {
Mobility(MobilityAgent),
Tree(TreeHeuristic),
Flood(FloodHeuristic),
Solo(SoloHeuristic),
Random(RandomAgent),
}
impl Default for Agent {
fn default() -> Self {
Self::Mobility(MobilityAgent::default())
}
}
impl Agent {
pub async fn step(&self, request: &GameRequest, latency: u64) -> MoveResponse {
let game = Game::from_request(request);
let timeout = request.game.timeout.saturating_sub(latency);
self.step_internal(timeout, &game).await
}
pub async fn step_internal(&self, timeout: u64, game: &Game) -> MoveResponse {
if game.grid.width > MAX_BOARD_SIZE || game.grid.height > MAX_BOARD_SIZE {
return RandomAgent.step(game).await;
}
match self {
Agent::Mobility(agent) => agent.step(game).await,
Agent::Tree(agent) => maxn::step(Arc::new(agent.clone()), timeout, game).await,
Agent::Flood(agent) => maxn::step(Arc::new(agent.clone()), timeout, game).await,
Agent::Solo(agent) => maxn::step(Arc::new(agent.clone()), timeout, game).await,
Agent::Random(agent) => agent.step(game).await,
}
}
}
impl FromStr for Agent {
type Err = serde_json::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
serde_json::from_str(s)
}
}
impl ToString for Agent {
fn to_string(&self) -> String {
serde_json::to_string(self).unwrap_or_default()
}
}
|
#![deny(unreachable_code)]
// ^^^^^^^^^^^^^^^^NOTE lint level defined here
pub mod remote_note_1_mod;
|
#![feature(box_raw)]
#![feature(associated_consts)]
use std::ops::Deref;
use std::vec::Vec;
use std::collections::HashMap;
struct Heap {
ptrs: HashMap<usize, bool>
}
struct GcBox<T> {
value: *mut T
}
impl <T> GcBox<T> {
fn new(value: T) -> GcBox<T> {
GcBox{value: Box::into_raw(Box::new(value))}
}
fn ptr(&self) -> usize {
self.value as usize
}
fn value(&self) -> &T {
unsafe { &*self.value as &T }
}
}
impl <T> Deref for GcBox<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
self.value()
}
}
trait Collectible {
fn mark(&self, _heap: &mut Heap) {}
}
impl Collectible for GcBox<String> {
fn mark(&self, heap: &mut Heap) {
heap.ptrs.insert(self.ptr(), true);
}
}
impl <T: Collectible> Collectible for GcBox<Vec<T>> {
fn mark(&self, heap: &mut Heap) {
heap.ptrs.insert(self.ptr(), true);
for value in self.value().iter() {
value.mark(heap);
}
}
}
fn main() {
let mut h = Heap{ptrs: HashMap::new()};
let mut v: Vec<GcBox<String>> = Vec::new();
let s: GcBox<String> = GcBox::new("foo".to_string());
v.push(s);
let b = GcBox::new(v);
b.mark(&mut h);
println!("{:#?}", &h.ptrs);
}
|
#[macro_use] extern crate lazy_static;
extern crate regex;
use regex::Regex;
use std::collections::HashMap;
use BalanceResult::*;
#[derive(Eq, PartialEq, Debug)]
pub enum BalanceResult<'a> {
Balanced(usize),
Unbalanced(&'a str, usize),
}
pub struct ProgramAnalyzer {
programs: HashMap<String, (usize, Vec<String>)>,
parents: HashMap<String, String>,
}
impl ProgramAnalyzer {
pub fn new() -> ProgramAnalyzer {
ProgramAnalyzer {
programs: HashMap::new(),
parents: HashMap::new(),
}
}
pub fn add_line(&mut self, line: &str) -> Result<(), String> {
lazy_static! {
static ref RE: Regex = Regex::new(r"^(\w+) \((\d+)\)(?: -> (\w+(?:, \w+)*))?").unwrap();
}
match RE.captures(line) {
Some(capture) => {
let name = capture[1].to_string();
let weight = usize::from_str_radix(&capture[2], 10).unwrap();
let others = capture.get(3)
.map_or_else(
|| vec![],
|other_cpt| {
other_cpt.as_str()
.split(",")
.map(|s| s.trim())
.map(|s| s.to_string())
.map(|s| {
self.parents.insert(s.to_owned(), name.to_owned());
s
})
.collect()
});
self.programs.insert(name, (weight, others));
Ok(())
},
None => Err(format!("invalid input line: {}", line))
}
}
pub fn find_bottom(&self) -> Option<&str> {
self.parents.keys().next()
.map(|elem| self.find_parent_rec(elem))
}
fn find_parent_rec<'a>(&'a self, elem: &'a str) -> &'a str {
match self.parents.get(elem) {
Some(parent) => self.find_parent_rec(parent),
None => elem,
}
}
pub fn balance<'a>(&'a self) -> Option<BalanceResult<'a>> {
self.find_bottom()
.map(|bottom| self.balance_rec(bottom))
}
fn balance_rec<'a>(&'a self, elem: &'a str) -> BalanceResult<'a> {
let (weight, ref others) = self.programs[elem];
if others.is_empty() {
return Balanced(weight);
}
let mut sum_weight: usize = 0;
let mut weights: Vec<(&'a str, usize)> = vec![];
let mut weight_freq: HashMap<usize, usize> = HashMap::new();
for other in others {
match self.balance_rec(other) {
Balanced(w) => {
sum_weight += w;
weights.push((other, w));
let count = match weight_freq.get(&w) {
Some(f) => f + 1,
None => 1,
};
weight_freq.insert(w, count);
},
Unbalanced(n, c) => return Unbalanced(n, c),
}
}
if 1 >= weight_freq.len() {
return Balanced(weight + sum_weight);
}
let odd_weight = *weight_freq.iter()
.min_by_key(|&(_, f)| f)
.map(|(w, _)| w)
.unwrap();
let normal_weight = *weight_freq.iter()
.max_by_key(|&(_, f)| f)
.map(|(w, _)| w)
.unwrap();
let unbal_name = weights.iter()
.find(|&&(_, w)| w == odd_weight)
.map(|&(name, _)| name)
.unwrap();
let unbal_weight = self.programs[unbal_name].0;
let corr_weight = if odd_weight > normal_weight {
unbal_weight - (odd_weight - normal_weight)
} else {
unbal_weight + (normal_weight - odd_weight)
};
Unbalanced(unbal_name, corr_weight)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_works() {
let lines = [
"pbga (66)",
"xhth (57)",
"ebii (61)",
"havc (66)",
"ktlj (57)",
"fwft (72) -> ktlj, cntj, xhth",
"qoyq (66)",
"padx (45) -> pbga, havc, qoyq",
"tknk (41) -> ugml, padx, fwft",
"jptl (61)",
"ugml (68) -> gyxo, ebii, jptl",
"gyxo (61)",
"cntj (57)",
];
let mut analyzer = ProgramAnalyzer::new();
lines.iter()
.for_each(|line| analyzer.add_line(&line).unwrap());
assert_eq!(Some(Unbalanced("ugml", 60)), analyzer.balance());
}
}
|
#![warn(clippy::all)]
#![warn(missing_docs)]
//! [](https://travis-ci.org/danieleades/harbourmaster)
//! [](https://docs.rs/harbourmaster/)
//!
//! Harbourmaster is a library of high-level abstractions of Docker objects.
//!
//! Harbourmaster is built on top of the excellent '[shiplift](https://github.com/softprops/shiplift)', but provides an object-oriented interface that
//! is a little easier to work with for some use cases. It's also using
//! async/await-ready futures-0.3 for the interface.
//!
//! Particularly useful for unit testing that involves spinning up and then
//! removing Docker containers.
//!
//! ## Usage
//! ```no_run
//! use harbourmaster::Container;
//!
//! #[tokio::main]
//! async fn main() {
//! let image = "alpine";
//!
//! println!("creating container!");
//! let container = Container::new(image).await.unwrap();
//! println!("container created!");
//!
//! println!("removing container!");
//! container.delete().await.unwrap();
//! println!("container removed!");
//! }
//! ```
mod client;
pub use client::Client;
mod container;
mod network;
pub use crate::network::Network;
mod port;
pub use crate::port::Protocol;
pub use container::{Container, ContainerBuilder};
pub use shiplift::Error;
|
// Copyright (c) 2020, KTH Royal Institute of Technology.
// SPDX-License-Identifier: AGPL-3.0-only
//! Example Arc-Script code which should be translated into
//! something which resembles this file. NB: `--` are Arc-Script comments.
//!
//! ```txt
//! type MyData = { i:i32, f:f32 };
//!
//! task MyOperator() (In(MyData)) -> (Out(MyData))
//!
//! -- State types supported by Arcon.
//! state state1: Value<MyData>;
//! state state2: Appender<MyData>;
//! state state3: Map<u64, MyData>;
//!
//! on In(data) => {
//! if let Some(_) = state1.get() {
//! let foo = { i=0, f=1.1 };
//! emit Out(foo);
//! state1.set(foo);
//! state2.clear();
//! } else {
//! state2.append(data);
//! state3.put(5, data);
//! emit Out(data);
//! }
//! }
//! end
//! ```
use arcon::prelude::state;
use arcon::prelude::*;
use arcon_macros::Arcon;
use arcon_state::{index::IndexOps, Backend};
use kompact::prelude::ComponentDefinition;
#[derive(ArconState)]
pub(crate) struct MyOperator {
state1: state::Value<MyData, Sled>,
state2: state::Appender<MyData, Sled>,
state3: state::Map<u64, MyData, Sled>,
}
type MyInputData = MyData;
type MyOutputData = MyData;
#[cfg_attr(feature = "arcon_serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Arcon, prost::Message, Copy, Clone, abomonation_derive::Abomonation)]
#[arcon(unsafe_ser_id = 12, reliable_ser_id = 13, version = 1)]
pub(crate) struct MyData {
#[prost(int32, tag = "1")]
pub i: i32,
#[prost(float, tag = "2")]
pub f: f32,
}
impl Operator for MyOperator {
type IN = MyInputData;
type OUT = MyOutputData;
type TimerState = ArconNever;
type OperatorState = Self;
fn handle_element(
&mut self,
element: ArconElement<Self::IN>,
ctx: OperatorContext<Self, impl Backend, impl ComponentDefinition>,
) -> ArconResult<()> {
// Setup code
let ArconElement { timestamp, data } = element;
// Handler generated by arc-mlir, could maybe be inlined if we want.
my_handler(data, timestamp, self, ctx)?;
Ok(())
}
arcon::ignore_timeout!();
fn persist(&mut self) -> Result<(), arcon_state::error::ArconStateError> {
<Self as IndexOps>::persist(self)
}
}
fn my_handler(
input_data: MyData,
input_timestamp: Option<u64>,
op: &mut MyOperator,
mut ctx: OperatorContext<MyOperator, impl Backend, impl ComponentDefinition>,
) -> ArconResult<()> {
let x0 = op.state1.get();
let x1 = x0.is_some();
let _x11 = if x1 {
let x2 = 0;
let x3 = 1.1;
let foo = MyData { i: x2, f: x3 };
let _x4 = ctx.output(ArconElement {
data: foo,
timestamp: input_timestamp,
});
let _x5 = op.state1.put(foo);
let x6 = op.state2.clear()?;
x6
} else {
let x7 = 5;
let _x8 = op.state2.append(input_data)?;
let _x9 = op.state3.put(x7, input_data)?;
let x10 = ctx.output(ArconElement {
data: input_data,
timestamp: input_timestamp,
});
x10
};
Ok(())
}
|
extern crate dtlib;
extern crate clap;
use clap::*;
use dtlib::*;
fn main() {
let yaml = load_yaml!("opts.yml");
let matches = App::from_yaml(yaml)
.author(crate_authors!())
.version(crate_version!())
.get_matches();
if let Some(matches) = matches.subcommand_matches("uid") {
user::generate(matches.value_of("INPUT").unwrap())
} else {
panic!("No arguments or subcommands provided")
}
}
|
pub mod simulator;
pub mod surface;
pub mod common;
mod tracer;
|
#[derive(Debug)]
enum IpAddrKind {
V4,
V6,
}
#[derive(Debug)]
struct IpAddr {
kind: IpAddrKind,
address: String,
}
fn main() {
let four = IpAddrKind::V4;
println!("{:?}", four);
let loopback = IpAddr {
kind: IpAddrKind::V6,
address: String::from("::1"),
};
println!("{:?}", loopback);
} |
use crate::{HdbError, HdbResult};
// Read n bytes, return as Vec<u8>
pub(crate) async fn parse_bytes<R: std::marker::Unpin + tokio::io::AsyncReadExt>(
len: usize,
rdr: &mut R,
) -> HdbResult<Vec<u8>> {
let mut vec: Vec<u8> = std::iter::repeat(255_u8).take(len).collect();
{
let rf: &mut [u8] = &mut vec;
rdr.read_exact(rf).await?;
}
Ok(vec)
}
pub(crate) async fn skip_bytes<R: std::marker::Unpin + tokio::io::AsyncReadExt>(
n: usize,
rdr: &mut R,
) -> HdbResult<()> {
const MAXBUFLEN: usize = 16;
if n > MAXBUFLEN {
Err(HdbError::Impl("impl: n > MAXBUFLEN (16)"))
} else {
let mut buffer = [0_u8; MAXBUFLEN];
let _tmp: usize = rdr.read_exact(&mut buffer[0..n]).await?;
Ok(())
}
}
|
#[macro_use]
mod common;
use common::util::*;
static UTIL_NAME: &'static str = "head";
static INPUT: &'static str = "lorem_ipsum.txt";
#[test]
fn test_stdin_default() {
let (at, mut ucmd) = testing(UTIL_NAME);
let result = ucmd.run_piped_stdin(at.read(INPUT));
assert_eq!(result.stdout, at.read("lorem_ipsum_default.expected"));
}
#[test]
fn test_stdin_1_line_obsolete() {
let (at, mut ucmd) = testing(UTIL_NAME);
let result = ucmd.args(&["-1"])
.run_piped_stdin(at.read(INPUT));
assert_eq!(result.stdout, at.read("lorem_ipsum_1_line.expected"));
}
#[test]
fn test_stdin_1_line() {
let (at, mut ucmd) = testing(UTIL_NAME);
let result = ucmd.args(&["-n", "1"])
.run_piped_stdin(at.read(INPUT));
assert_eq!(result.stdout, at.read("lorem_ipsum_1_line.expected"));
}
#[test]
fn test_stdin_5_chars() {
let (at, mut ucmd) = testing(UTIL_NAME);
let result = ucmd.args(&["-c", "5"])
.run_piped_stdin(at.read(INPUT));
assert_eq!(result.stdout, at.read("lorem_ipsum_5_chars.expected"));
}
#[test]
fn test_single_default() {
let (at, mut ucmd) = testing(UTIL_NAME);
let result = ucmd.arg(INPUT).run();
assert_eq!(result.stdout, at.read("lorem_ipsum_default.expected"));
}
#[test]
fn test_single_1_line_obsolete() {
let (at, mut ucmd) = testing(UTIL_NAME);
let result = ucmd.args(&["-1", INPUT]).run();
assert_eq!(result.stdout, at.read("lorem_ipsum_1_line.expected"));
}
#[test]
fn test_single_1_line() {
let (at, mut ucmd) = testing(UTIL_NAME);
let result = ucmd.args(&["-n", "1", INPUT]).run();
assert_eq!(result.stdout, at.read("lorem_ipsum_1_line.expected"));
}
#[test]
fn test_single_5_chars() {
let (at, mut ucmd) = testing(UTIL_NAME);
let result = ucmd.args(&["-c", "5", INPUT]).run();
assert_eq!(result.stdout, at.read("lorem_ipsum_5_chars.expected"));
}
#[test]
fn test_verbose() {
let (at, mut ucmd) = testing(UTIL_NAME);
let result = ucmd.args(&["-v", INPUT]).run();
assert_eq!(result.stdout, at.read("lorem_ipsum_verbose.expected"));
}
|
// This file is part of linux-epoll. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/linux-epoll/master/COPYRIGHT. No part of linux-epoll, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file.
// Copyright © 2019 The developers of linux-epoll. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/linux-epoll/master/COPYRIGHT.
/// A 31 bit unsigned integer that specifies the time interval (in seconds) that a resource record (RR) may be cached before it should be discarded.
///
/// See <https://tools.ietf.org/html/rfc2181#section-8>.
///
/// Zero values are interpreted to mean that the resource record can only be used for the transaction in progress, and should not be cached.
#[derive(Default, Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(C, packed)]
pub struct TimeToLiveInSeconds([u8; 4]);
impl From<[u8; 4]> for TimeToLiveInSeconds
{
#[inline(always)]
fn from(seconds: [u8; 4]) -> Self
{
Self(seconds)
}
}
impl Into<u32> for TimeToLiveInSeconds
{
#[inline(always)]
fn into(self) -> u32
{
let value = self.0.from_network_endian_to_native_endian();
// RFC 2181, Section 8; if the top bit is set, the value is zero.
if unlikely!(value & 0x80000000 != 0)
{
0
}
else
{
value
}
}
}
|
// auto generated, do not modify.
// created: Mon Feb 22 23:57:02 2016
// src-file: /QtGui/qguiapplication.h
// dst-file: /src/gui/qguiapplication.rs
//
// header block begin =>
#![feature(libc)]
#![feature(core)]
#![feature(collections)]
extern crate libc;
use self::libc::*;
// <= header block end
// main block begin =>
// <= main block end
// use block begin =>
use super::super::core::qcoreapplication::*; // 771
use std::ops::Deref;
use super::qfont::*; // 773
use super::super::core::qstring::*; // 771
// use super::qlist::*; // 775
use super::qpalette::*; // 773
use super::qinputmethod::*; // 773
use super::qscreen::*; // 773
use super::qcursor::*; // 773
use super::qicon::*; // 773
use super::qstylehints::*; // 773
use super::qclipboard::*; // 773
use super::super::core::qobject::*; // 771
use super::super::core::qcoreevent::*; // 771
use super::super::core::qpoint::*; // 771
use super::qwindow::*; // 773
// use super::qplatformnativeinterface::*; // 775
use super::super::core::qobjectdefs::*; // 771
use super::super::core::qbytearray::*; // 771
// use super::qfunctionpointer::*; // 775
use super::qsessionmanager::*; // 773
// <= use block end
// ext block begin =>
// #[link(name = "Qt5Core")]
// #[link(name = "Qt5Gui")]
// #[link(name = "Qt5Widgets")]
// #[link(name = "QtInline")]
extern {
fn QGuiApplication_Class_Size() -> c_int;
// proto: void QGuiApplication::~QGuiApplication();
fn C_ZN15QGuiApplicationD2Ev(qthis: u64 /* *mut c_void*/);
// proto: static void QGuiApplication::setFont(const QFont & );
fn C_ZN15QGuiApplication7setFontERK5QFont(arg0: *mut c_void);
// proto: static QString QGuiApplication::platformName();
fn C_ZN15QGuiApplication12platformNameEv() -> *mut c_void;
// proto: static QList<QScreen *> QGuiApplication::screens();
fn C_ZN15QGuiApplication7screensEv() -> *mut c_void;
// proto: static void QGuiApplication::setPalette(const QPalette & pal);
fn C_ZN15QGuiApplication10setPaletteERK8QPalette(arg0: *mut c_void);
// proto: static QInputMethod * QGuiApplication::inputMethod();
fn C_ZN15QGuiApplication11inputMethodEv() -> *mut c_void;
// proto: bool QGuiApplication::isSavingSession();
fn C_ZNK15QGuiApplication15isSavingSessionEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: static QFont QGuiApplication::font();
fn C_ZN15QGuiApplication4fontEv() -> *mut c_void;
// proto: bool QGuiApplication::isSessionRestored();
fn C_ZNK15QGuiApplication17isSessionRestoredEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: QString QGuiApplication::sessionKey();
fn C_ZNK15QGuiApplication10sessionKeyEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: static bool QGuiApplication::desktopSettingsAware();
fn C_ZN15QGuiApplication20desktopSettingsAwareEv() -> c_char;
// proto: static void QGuiApplication::sync();
fn C_ZN15QGuiApplication4syncEv();
// proto: static void QGuiApplication::setQuitOnLastWindowClosed(bool quit);
fn C_ZN15QGuiApplication25setQuitOnLastWindowClosedEb(arg0: c_char);
// proto: static QScreen * QGuiApplication::primaryScreen();
fn C_ZN15QGuiApplication13primaryScreenEv() -> *mut c_void;
// proto: static QCursor * QGuiApplication::overrideCursor();
fn C_ZN15QGuiApplication14overrideCursorEv() -> *mut c_void;
// proto: static QIcon QGuiApplication::windowIcon();
fn C_ZN15QGuiApplication10windowIconEv() -> *mut c_void;
// proto: static QStyleHints * QGuiApplication::styleHints();
fn C_ZN15QGuiApplication10styleHintsEv() -> *mut c_void;
// proto: static QClipboard * QGuiApplication::clipboard();
fn C_ZN15QGuiApplication9clipboardEv() -> *mut c_void;
// proto: static QPalette QGuiApplication::palette();
fn C_ZN15QGuiApplication7paletteEv() -> *mut c_void;
// proto: bool QGuiApplication::notify(QObject * , QEvent * );
fn C_ZN15QGuiApplication6notifyEP7QObjectP6QEvent(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void) -> c_char;
// proto: static QWindowList QGuiApplication::topLevelWindows();
fn C_ZN15QGuiApplication15topLevelWindowsEv() -> *mut c_void;
// proto: static bool QGuiApplication::isRightToLeft();
fn C_ZN15QGuiApplication13isRightToLeftEv() -> c_char;
// proto: static void QGuiApplication::changeOverrideCursor(const QCursor & );
fn C_ZN15QGuiApplication20changeOverrideCursorERK7QCursor(arg0: *mut c_void);
// proto: static QWindowList QGuiApplication::allWindows();
fn C_ZN15QGuiApplication10allWindowsEv() -> *mut c_void;
// proto: static void QGuiApplication::setOverrideCursor(const QCursor & );
fn C_ZN15QGuiApplication17setOverrideCursorERK7QCursor(arg0: *mut c_void);
// proto: static void QGuiApplication::setWindowIcon(const QIcon & icon);
fn C_ZN15QGuiApplication13setWindowIconERK5QIcon(arg0: *mut c_void);
// proto: QString QGuiApplication::sessionId();
fn C_ZNK15QGuiApplication9sessionIdEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: static void QGuiApplication::setApplicationDisplayName(const QString & name);
fn C_ZN15QGuiApplication25setApplicationDisplayNameERK7QString(arg0: *mut c_void);
// proto: static bool QGuiApplication::isLeftToRight();
fn C_ZN15QGuiApplication13isLeftToRightEv() -> c_char;
// proto: static QWindow * QGuiApplication::topLevelAt(const QPoint & pos);
fn C_ZN15QGuiApplication10topLevelAtERK6QPoint(arg0: *mut c_void) -> *mut c_void;
// proto: void QGuiApplication::QGuiApplication(int & argc, char ** argv, int );
fn C_ZN15QGuiApplicationC2ERiPPci(arg0: *mut c_int, arg1: *mut c_char, arg2: c_int) -> u64;
// proto: static void QGuiApplication::setDesktopSettingsAware(bool on);
fn C_ZN15QGuiApplication23setDesktopSettingsAwareEb(arg0: c_char);
// proto: static QWindow * QGuiApplication::modalWindow();
fn C_ZN15QGuiApplication11modalWindowEv() -> *mut c_void;
// proto: static QString QGuiApplication::applicationDisplayName();
fn C_ZN15QGuiApplication22applicationDisplayNameEv() -> *mut c_void;
// proto: static int QGuiApplication::exec();
fn C_ZN15QGuiApplication4execEv() -> c_int;
// proto: static bool QGuiApplication::quitOnLastWindowClosed();
fn C_ZN15QGuiApplication22quitOnLastWindowClosedEv() -> c_char;
// proto: static void QGuiApplication::restoreOverrideCursor();
fn C_ZN15QGuiApplication21restoreOverrideCursorEv();
// proto: static QPlatformNativeInterface * QGuiApplication::platformNativeInterface();
fn C_ZN15QGuiApplication23platformNativeInterfaceEv() -> *mut c_void;
// proto: const QMetaObject * QGuiApplication::metaObject();
fn C_ZNK15QGuiApplication10metaObjectEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: static QObject * QGuiApplication::focusObject();
fn C_ZN15QGuiApplication11focusObjectEv() -> *mut c_void;
// proto: static QWindow * QGuiApplication::focusWindow();
fn C_ZN15QGuiApplication11focusWindowEv() -> *mut c_void;
// proto: qreal QGuiApplication::devicePixelRatio();
fn C_ZNK15QGuiApplication16devicePixelRatioEv(qthis: u64 /* *mut c_void*/) -> c_double;
// proto: static QFunctionPointer QGuiApplication::platformFunction(const QByteArray & function);
fn C_ZN15QGuiApplication16platformFunctionERK10QByteArray(arg0: *mut c_void) -> *mut c_void;
fn QGuiApplication_SlotProxy_connect__ZN15QGuiApplication18focusObjectChangedEP7QObject(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
fn QGuiApplication_SlotProxy_connect__ZN15QGuiApplication19fontDatabaseChangedEv(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
fn QGuiApplication_SlotProxy_connect__ZN15QGuiApplication17commitDataRequestER15QSessionManager(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
fn QGuiApplication_SlotProxy_connect__ZN15QGuiApplication14paletteChangedERK8QPalette(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
fn QGuiApplication_SlotProxy_connect__ZN15QGuiApplication13screenRemovedEP7QScreen(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
fn QGuiApplication_SlotProxy_connect__ZN15QGuiApplication18focusWindowChangedEP7QWindow(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
fn QGuiApplication_SlotProxy_connect__ZN15QGuiApplication16lastWindowClosedEv(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
fn QGuiApplication_SlotProxy_connect__ZN15QGuiApplication11screenAddedEP7QScreen(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
fn QGuiApplication_SlotProxy_connect__ZN15QGuiApplication16saveStateRequestER15QSessionManager(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
} // <= ext block end
// body block begin =>
// class sizeof(QGuiApplication)=1
#[derive(Default)]
pub struct QGuiApplication {
qbase: QCoreApplication,
pub qclsinst: u64 /* *mut c_void*/,
pub _saveStateRequest: QGuiApplication_saveStateRequest_signal,
pub _applicationStateChanged: QGuiApplication_applicationStateChanged_signal,
pub _screenAdded: QGuiApplication_screenAdded_signal,
pub _screenRemoved: QGuiApplication_screenRemoved_signal,
pub _focusObjectChanged: QGuiApplication_focusObjectChanged_signal,
pub _paletteChanged: QGuiApplication_paletteChanged_signal,
pub _focusWindowChanged: QGuiApplication_focusWindowChanged_signal,
pub _lastWindowClosed: QGuiApplication_lastWindowClosed_signal,
pub _fontDatabaseChanged: QGuiApplication_fontDatabaseChanged_signal,
pub _layoutDirectionChanged: QGuiApplication_layoutDirectionChanged_signal,
pub _commitDataRequest: QGuiApplication_commitDataRequest_signal,
}
impl /*struct*/ QGuiApplication {
pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QGuiApplication {
return QGuiApplication{qbase: QCoreApplication::inheritFrom(qthis), qclsinst: qthis, ..Default::default()};
}
}
impl Deref for QGuiApplication {
type Target = QCoreApplication;
fn deref(&self) -> &QCoreApplication {
return & self.qbase;
}
}
impl AsRef<QCoreApplication> for QGuiApplication {
fn as_ref(& self) -> & QCoreApplication {
return & self.qbase;
}
}
// proto: void QGuiApplication::~QGuiApplication();
impl /*struct*/ QGuiApplication {
pub fn free<RetType, T: QGuiApplication_free<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.free(self);
// return 1;
}
}
pub trait QGuiApplication_free<RetType> {
fn free(self , rsthis: & QGuiApplication) -> RetType;
}
// proto: void QGuiApplication::~QGuiApplication();
impl<'a> /*trait*/ QGuiApplication_free<()> for () {
fn free(self , rsthis: & QGuiApplication) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN15QGuiApplicationD2Ev()};
unsafe {C_ZN15QGuiApplicationD2Ev(rsthis.qclsinst)};
// return 1;
}
}
// proto: static void QGuiApplication::setFont(const QFont & );
impl /*struct*/ QGuiApplication {
pub fn setFont_s<RetType, T: QGuiApplication_setFont_s<RetType>>( overload_args: T) -> RetType {
return overload_args.setFont_s();
// return 1;
}
}
pub trait QGuiApplication_setFont_s<RetType> {
fn setFont_s(self ) -> RetType;
}
// proto: static void QGuiApplication::setFont(const QFont & );
impl<'a> /*trait*/ QGuiApplication_setFont_s<()> for (&'a QFont) {
fn setFont_s(self ) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN15QGuiApplication7setFontERK5QFont()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN15QGuiApplication7setFontERK5QFont(arg0)};
// return 1;
}
}
// proto: static QString QGuiApplication::platformName();
impl /*struct*/ QGuiApplication {
pub fn platformName_s<RetType, T: QGuiApplication_platformName_s<RetType>>( overload_args: T) -> RetType {
return overload_args.platformName_s();
// return 1;
}
}
pub trait QGuiApplication_platformName_s<RetType> {
fn platformName_s(self ) -> RetType;
}
// proto: static QString QGuiApplication::platformName();
impl<'a> /*trait*/ QGuiApplication_platformName_s<QString> for () {
fn platformName_s(self ) -> QString {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN15QGuiApplication12platformNameEv()};
let mut ret = unsafe {C_ZN15QGuiApplication12platformNameEv()};
let mut ret1 = QString::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: static QList<QScreen *> QGuiApplication::screens();
impl /*struct*/ QGuiApplication {
pub fn screens_s<RetType, T: QGuiApplication_screens_s<RetType>>( overload_args: T) -> RetType {
return overload_args.screens_s();
// return 1;
}
}
pub trait QGuiApplication_screens_s<RetType> {
fn screens_s(self ) -> RetType;
}
// proto: static QList<QScreen *> QGuiApplication::screens();
impl<'a> /*trait*/ QGuiApplication_screens_s<u64> for () {
fn screens_s(self ) -> u64 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN15QGuiApplication7screensEv()};
let mut ret = unsafe {C_ZN15QGuiApplication7screensEv()};
return ret as u64; // 5
// return 1;
}
}
// proto: static void QGuiApplication::setPalette(const QPalette & pal);
impl /*struct*/ QGuiApplication {
pub fn setPalette_s<RetType, T: QGuiApplication_setPalette_s<RetType>>( overload_args: T) -> RetType {
return overload_args.setPalette_s();
// return 1;
}
}
pub trait QGuiApplication_setPalette_s<RetType> {
fn setPalette_s(self ) -> RetType;
}
// proto: static void QGuiApplication::setPalette(const QPalette & pal);
impl<'a> /*trait*/ QGuiApplication_setPalette_s<()> for (&'a QPalette) {
fn setPalette_s(self ) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN15QGuiApplication10setPaletteERK8QPalette()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN15QGuiApplication10setPaletteERK8QPalette(arg0)};
// return 1;
}
}
// proto: static QInputMethod * QGuiApplication::inputMethod();
impl /*struct*/ QGuiApplication {
pub fn inputMethod_s<RetType, T: QGuiApplication_inputMethod_s<RetType>>( overload_args: T) -> RetType {
return overload_args.inputMethod_s();
// return 1;
}
}
pub trait QGuiApplication_inputMethod_s<RetType> {
fn inputMethod_s(self ) -> RetType;
}
// proto: static QInputMethod * QGuiApplication::inputMethod();
impl<'a> /*trait*/ QGuiApplication_inputMethod_s<QInputMethod> for () {
fn inputMethod_s(self ) -> QInputMethod {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN15QGuiApplication11inputMethodEv()};
let mut ret = unsafe {C_ZN15QGuiApplication11inputMethodEv()};
let mut ret1 = QInputMethod::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: bool QGuiApplication::isSavingSession();
impl /*struct*/ QGuiApplication {
pub fn isSavingSession<RetType, T: QGuiApplication_isSavingSession<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isSavingSession(self);
// return 1;
}
}
pub trait QGuiApplication_isSavingSession<RetType> {
fn isSavingSession(self , rsthis: & QGuiApplication) -> RetType;
}
// proto: bool QGuiApplication::isSavingSession();
impl<'a> /*trait*/ QGuiApplication_isSavingSession<i8> for () {
fn isSavingSession(self , rsthis: & QGuiApplication) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK15QGuiApplication15isSavingSessionEv()};
let mut ret = unsafe {C_ZNK15QGuiApplication15isSavingSessionEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: static QFont QGuiApplication::font();
impl /*struct*/ QGuiApplication {
pub fn font_s<RetType, T: QGuiApplication_font_s<RetType>>( overload_args: T) -> RetType {
return overload_args.font_s();
// return 1;
}
}
pub trait QGuiApplication_font_s<RetType> {
fn font_s(self ) -> RetType;
}
// proto: static QFont QGuiApplication::font();
impl<'a> /*trait*/ QGuiApplication_font_s<QFont> for () {
fn font_s(self ) -> QFont {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN15QGuiApplication4fontEv()};
let mut ret = unsafe {C_ZN15QGuiApplication4fontEv()};
let mut ret1 = QFont::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: bool QGuiApplication::isSessionRestored();
impl /*struct*/ QGuiApplication {
pub fn isSessionRestored<RetType, T: QGuiApplication_isSessionRestored<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isSessionRestored(self);
// return 1;
}
}
pub trait QGuiApplication_isSessionRestored<RetType> {
fn isSessionRestored(self , rsthis: & QGuiApplication) -> RetType;
}
// proto: bool QGuiApplication::isSessionRestored();
impl<'a> /*trait*/ QGuiApplication_isSessionRestored<i8> for () {
fn isSessionRestored(self , rsthis: & QGuiApplication) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK15QGuiApplication17isSessionRestoredEv()};
let mut ret = unsafe {C_ZNK15QGuiApplication17isSessionRestoredEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: QString QGuiApplication::sessionKey();
impl /*struct*/ QGuiApplication {
pub fn sessionKey<RetType, T: QGuiApplication_sessionKey<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.sessionKey(self);
// return 1;
}
}
pub trait QGuiApplication_sessionKey<RetType> {
fn sessionKey(self , rsthis: & QGuiApplication) -> RetType;
}
// proto: QString QGuiApplication::sessionKey();
impl<'a> /*trait*/ QGuiApplication_sessionKey<QString> for () {
fn sessionKey(self , rsthis: & QGuiApplication) -> QString {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK15QGuiApplication10sessionKeyEv()};
let mut ret = unsafe {C_ZNK15QGuiApplication10sessionKeyEv(rsthis.qclsinst)};
let mut ret1 = QString::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: static bool QGuiApplication::desktopSettingsAware();
impl /*struct*/ QGuiApplication {
pub fn desktopSettingsAware_s<RetType, T: QGuiApplication_desktopSettingsAware_s<RetType>>( overload_args: T) -> RetType {
return overload_args.desktopSettingsAware_s();
// return 1;
}
}
pub trait QGuiApplication_desktopSettingsAware_s<RetType> {
fn desktopSettingsAware_s(self ) -> RetType;
}
// proto: static bool QGuiApplication::desktopSettingsAware();
impl<'a> /*trait*/ QGuiApplication_desktopSettingsAware_s<i8> for () {
fn desktopSettingsAware_s(self ) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN15QGuiApplication20desktopSettingsAwareEv()};
let mut ret = unsafe {C_ZN15QGuiApplication20desktopSettingsAwareEv()};
return ret as i8; // 1
// return 1;
}
}
// proto: static void QGuiApplication::sync();
impl /*struct*/ QGuiApplication {
pub fn sync_s<RetType, T: QGuiApplication_sync_s<RetType>>( overload_args: T) -> RetType {
return overload_args.sync_s();
// return 1;
}
}
pub trait QGuiApplication_sync_s<RetType> {
fn sync_s(self ) -> RetType;
}
// proto: static void QGuiApplication::sync();
impl<'a> /*trait*/ QGuiApplication_sync_s<()> for () {
fn sync_s(self ) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN15QGuiApplication4syncEv()};
unsafe {C_ZN15QGuiApplication4syncEv()};
// return 1;
}
}
// proto: static void QGuiApplication::setQuitOnLastWindowClosed(bool quit);
impl /*struct*/ QGuiApplication {
pub fn setQuitOnLastWindowClosed_s<RetType, T: QGuiApplication_setQuitOnLastWindowClosed_s<RetType>>( overload_args: T) -> RetType {
return overload_args.setQuitOnLastWindowClosed_s();
// return 1;
}
}
pub trait QGuiApplication_setQuitOnLastWindowClosed_s<RetType> {
fn setQuitOnLastWindowClosed_s(self ) -> RetType;
}
// proto: static void QGuiApplication::setQuitOnLastWindowClosed(bool quit);
impl<'a> /*trait*/ QGuiApplication_setQuitOnLastWindowClosed_s<()> for (i8) {
fn setQuitOnLastWindowClosed_s(self ) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN15QGuiApplication25setQuitOnLastWindowClosedEb()};
let arg0 = self as c_char;
unsafe {C_ZN15QGuiApplication25setQuitOnLastWindowClosedEb(arg0)};
// return 1;
}
}
// proto: static QScreen * QGuiApplication::primaryScreen();
impl /*struct*/ QGuiApplication {
pub fn primaryScreen_s<RetType, T: QGuiApplication_primaryScreen_s<RetType>>( overload_args: T) -> RetType {
return overload_args.primaryScreen_s();
// return 1;
}
}
pub trait QGuiApplication_primaryScreen_s<RetType> {
fn primaryScreen_s(self ) -> RetType;
}
// proto: static QScreen * QGuiApplication::primaryScreen();
impl<'a> /*trait*/ QGuiApplication_primaryScreen_s<QScreen> for () {
fn primaryScreen_s(self ) -> QScreen {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN15QGuiApplication13primaryScreenEv()};
let mut ret = unsafe {C_ZN15QGuiApplication13primaryScreenEv()};
let mut ret1 = QScreen::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: static QCursor * QGuiApplication::overrideCursor();
impl /*struct*/ QGuiApplication {
pub fn overrideCursor_s<RetType, T: QGuiApplication_overrideCursor_s<RetType>>( overload_args: T) -> RetType {
return overload_args.overrideCursor_s();
// return 1;
}
}
pub trait QGuiApplication_overrideCursor_s<RetType> {
fn overrideCursor_s(self ) -> RetType;
}
// proto: static QCursor * QGuiApplication::overrideCursor();
impl<'a> /*trait*/ QGuiApplication_overrideCursor_s<QCursor> for () {
fn overrideCursor_s(self ) -> QCursor {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN15QGuiApplication14overrideCursorEv()};
let mut ret = unsafe {C_ZN15QGuiApplication14overrideCursorEv()};
let mut ret1 = QCursor::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: static QIcon QGuiApplication::windowIcon();
impl /*struct*/ QGuiApplication {
pub fn windowIcon_s<RetType, T: QGuiApplication_windowIcon_s<RetType>>( overload_args: T) -> RetType {
return overload_args.windowIcon_s();
// return 1;
}
}
pub trait QGuiApplication_windowIcon_s<RetType> {
fn windowIcon_s(self ) -> RetType;
}
// proto: static QIcon QGuiApplication::windowIcon();
impl<'a> /*trait*/ QGuiApplication_windowIcon_s<QIcon> for () {
fn windowIcon_s(self ) -> QIcon {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN15QGuiApplication10windowIconEv()};
let mut ret = unsafe {C_ZN15QGuiApplication10windowIconEv()};
let mut ret1 = QIcon::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: static QStyleHints * QGuiApplication::styleHints();
impl /*struct*/ QGuiApplication {
pub fn styleHints_s<RetType, T: QGuiApplication_styleHints_s<RetType>>( overload_args: T) -> RetType {
return overload_args.styleHints_s();
// return 1;
}
}
pub trait QGuiApplication_styleHints_s<RetType> {
fn styleHints_s(self ) -> RetType;
}
// proto: static QStyleHints * QGuiApplication::styleHints();
impl<'a> /*trait*/ QGuiApplication_styleHints_s<QStyleHints> for () {
fn styleHints_s(self ) -> QStyleHints {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN15QGuiApplication10styleHintsEv()};
let mut ret = unsafe {C_ZN15QGuiApplication10styleHintsEv()};
let mut ret1 = QStyleHints::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: static QClipboard * QGuiApplication::clipboard();
impl /*struct*/ QGuiApplication {
pub fn clipboard_s<RetType, T: QGuiApplication_clipboard_s<RetType>>( overload_args: T) -> RetType {
return overload_args.clipboard_s();
// return 1;
}
}
pub trait QGuiApplication_clipboard_s<RetType> {
fn clipboard_s(self ) -> RetType;
}
// proto: static QClipboard * QGuiApplication::clipboard();
impl<'a> /*trait*/ QGuiApplication_clipboard_s<QClipboard> for () {
fn clipboard_s(self ) -> QClipboard {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN15QGuiApplication9clipboardEv()};
let mut ret = unsafe {C_ZN15QGuiApplication9clipboardEv()};
let mut ret1 = QClipboard::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: static QPalette QGuiApplication::palette();
impl /*struct*/ QGuiApplication {
pub fn palette_s<RetType, T: QGuiApplication_palette_s<RetType>>( overload_args: T) -> RetType {
return overload_args.palette_s();
// return 1;
}
}
pub trait QGuiApplication_palette_s<RetType> {
fn palette_s(self ) -> RetType;
}
// proto: static QPalette QGuiApplication::palette();
impl<'a> /*trait*/ QGuiApplication_palette_s<QPalette> for () {
fn palette_s(self ) -> QPalette {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN15QGuiApplication7paletteEv()};
let mut ret = unsafe {C_ZN15QGuiApplication7paletteEv()};
let mut ret1 = QPalette::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: bool QGuiApplication::notify(QObject * , QEvent * );
impl /*struct*/ QGuiApplication {
pub fn notify<RetType, T: QGuiApplication_notify<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.notify(self);
// return 1;
}
}
pub trait QGuiApplication_notify<RetType> {
fn notify(self , rsthis: & QGuiApplication) -> RetType;
}
// proto: bool QGuiApplication::notify(QObject * , QEvent * );
impl<'a> /*trait*/ QGuiApplication_notify<i8> for (&'a QObject, &'a QEvent) {
fn notify(self , rsthis: & QGuiApplication) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN15QGuiApplication6notifyEP7QObjectP6QEvent()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.qclsinst as *mut c_void;
let mut ret = unsafe {C_ZN15QGuiApplication6notifyEP7QObjectP6QEvent(rsthis.qclsinst, arg0, arg1)};
return ret as i8; // 1
// return 1;
}
}
// proto: static QWindowList QGuiApplication::topLevelWindows();
impl /*struct*/ QGuiApplication {
pub fn topLevelWindows_s<RetType, T: QGuiApplication_topLevelWindows_s<RetType>>( overload_args: T) -> RetType {
return overload_args.topLevelWindows_s();
// return 1;
}
}
pub trait QGuiApplication_topLevelWindows_s<RetType> {
fn topLevelWindows_s(self ) -> RetType;
}
// proto: static QWindowList QGuiApplication::topLevelWindows();
impl<'a> /*trait*/ QGuiApplication_topLevelWindows_s<u64> for () {
fn topLevelWindows_s(self ) -> u64 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN15QGuiApplication15topLevelWindowsEv()};
let mut ret = unsafe {C_ZN15QGuiApplication15topLevelWindowsEv()};
return ret as u64; // 5
// return 1;
}
}
// proto: static bool QGuiApplication::isRightToLeft();
impl /*struct*/ QGuiApplication {
pub fn isRightToLeft_s<RetType, T: QGuiApplication_isRightToLeft_s<RetType>>( overload_args: T) -> RetType {
return overload_args.isRightToLeft_s();
// return 1;
}
}
pub trait QGuiApplication_isRightToLeft_s<RetType> {
fn isRightToLeft_s(self ) -> RetType;
}
// proto: static bool QGuiApplication::isRightToLeft();
impl<'a> /*trait*/ QGuiApplication_isRightToLeft_s<i8> for () {
fn isRightToLeft_s(self ) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN15QGuiApplication13isRightToLeftEv()};
let mut ret = unsafe {C_ZN15QGuiApplication13isRightToLeftEv()};
return ret as i8; // 1
// return 1;
}
}
// proto: static void QGuiApplication::changeOverrideCursor(const QCursor & );
impl /*struct*/ QGuiApplication {
pub fn changeOverrideCursor_s<RetType, T: QGuiApplication_changeOverrideCursor_s<RetType>>( overload_args: T) -> RetType {
return overload_args.changeOverrideCursor_s();
// return 1;
}
}
pub trait QGuiApplication_changeOverrideCursor_s<RetType> {
fn changeOverrideCursor_s(self ) -> RetType;
}
// proto: static void QGuiApplication::changeOverrideCursor(const QCursor & );
impl<'a> /*trait*/ QGuiApplication_changeOverrideCursor_s<()> for (&'a QCursor) {
fn changeOverrideCursor_s(self ) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN15QGuiApplication20changeOverrideCursorERK7QCursor()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN15QGuiApplication20changeOverrideCursorERK7QCursor(arg0)};
// return 1;
}
}
// proto: static QWindowList QGuiApplication::allWindows();
impl /*struct*/ QGuiApplication {
pub fn allWindows_s<RetType, T: QGuiApplication_allWindows_s<RetType>>( overload_args: T) -> RetType {
return overload_args.allWindows_s();
// return 1;
}
}
pub trait QGuiApplication_allWindows_s<RetType> {
fn allWindows_s(self ) -> RetType;
}
// proto: static QWindowList QGuiApplication::allWindows();
impl<'a> /*trait*/ QGuiApplication_allWindows_s<u64> for () {
fn allWindows_s(self ) -> u64 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN15QGuiApplication10allWindowsEv()};
let mut ret = unsafe {C_ZN15QGuiApplication10allWindowsEv()};
return ret as u64; // 5
// return 1;
}
}
// proto: static void QGuiApplication::setOverrideCursor(const QCursor & );
impl /*struct*/ QGuiApplication {
pub fn setOverrideCursor_s<RetType, T: QGuiApplication_setOverrideCursor_s<RetType>>( overload_args: T) -> RetType {
return overload_args.setOverrideCursor_s();
// return 1;
}
}
pub trait QGuiApplication_setOverrideCursor_s<RetType> {
fn setOverrideCursor_s(self ) -> RetType;
}
// proto: static void QGuiApplication::setOverrideCursor(const QCursor & );
impl<'a> /*trait*/ QGuiApplication_setOverrideCursor_s<()> for (&'a QCursor) {
fn setOverrideCursor_s(self ) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN15QGuiApplication17setOverrideCursorERK7QCursor()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN15QGuiApplication17setOverrideCursorERK7QCursor(arg0)};
// return 1;
}
}
// proto: static void QGuiApplication::setWindowIcon(const QIcon & icon);
impl /*struct*/ QGuiApplication {
pub fn setWindowIcon_s<RetType, T: QGuiApplication_setWindowIcon_s<RetType>>( overload_args: T) -> RetType {
return overload_args.setWindowIcon_s();
// return 1;
}
}
pub trait QGuiApplication_setWindowIcon_s<RetType> {
fn setWindowIcon_s(self ) -> RetType;
}
// proto: static void QGuiApplication::setWindowIcon(const QIcon & icon);
impl<'a> /*trait*/ QGuiApplication_setWindowIcon_s<()> for (&'a QIcon) {
fn setWindowIcon_s(self ) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN15QGuiApplication13setWindowIconERK5QIcon()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN15QGuiApplication13setWindowIconERK5QIcon(arg0)};
// return 1;
}
}
// proto: QString QGuiApplication::sessionId();
impl /*struct*/ QGuiApplication {
pub fn sessionId<RetType, T: QGuiApplication_sessionId<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.sessionId(self);
// return 1;
}
}
pub trait QGuiApplication_sessionId<RetType> {
fn sessionId(self , rsthis: & QGuiApplication) -> RetType;
}
// proto: QString QGuiApplication::sessionId();
impl<'a> /*trait*/ QGuiApplication_sessionId<QString> for () {
fn sessionId(self , rsthis: & QGuiApplication) -> QString {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK15QGuiApplication9sessionIdEv()};
let mut ret = unsafe {C_ZNK15QGuiApplication9sessionIdEv(rsthis.qclsinst)};
let mut ret1 = QString::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: static void QGuiApplication::setApplicationDisplayName(const QString & name);
impl /*struct*/ QGuiApplication {
pub fn setApplicationDisplayName_s<RetType, T: QGuiApplication_setApplicationDisplayName_s<RetType>>( overload_args: T) -> RetType {
return overload_args.setApplicationDisplayName_s();
// return 1;
}
}
pub trait QGuiApplication_setApplicationDisplayName_s<RetType> {
fn setApplicationDisplayName_s(self ) -> RetType;
}
// proto: static void QGuiApplication::setApplicationDisplayName(const QString & name);
impl<'a> /*trait*/ QGuiApplication_setApplicationDisplayName_s<()> for (&'a QString) {
fn setApplicationDisplayName_s(self ) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN15QGuiApplication25setApplicationDisplayNameERK7QString()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN15QGuiApplication25setApplicationDisplayNameERK7QString(arg0)};
// return 1;
}
}
// proto: static bool QGuiApplication::isLeftToRight();
impl /*struct*/ QGuiApplication {
pub fn isLeftToRight_s<RetType, T: QGuiApplication_isLeftToRight_s<RetType>>( overload_args: T) -> RetType {
return overload_args.isLeftToRight_s();
// return 1;
}
}
pub trait QGuiApplication_isLeftToRight_s<RetType> {
fn isLeftToRight_s(self ) -> RetType;
}
// proto: static bool QGuiApplication::isLeftToRight();
impl<'a> /*trait*/ QGuiApplication_isLeftToRight_s<i8> for () {
fn isLeftToRight_s(self ) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN15QGuiApplication13isLeftToRightEv()};
let mut ret = unsafe {C_ZN15QGuiApplication13isLeftToRightEv()};
return ret as i8; // 1
// return 1;
}
}
// proto: static QWindow * QGuiApplication::topLevelAt(const QPoint & pos);
impl /*struct*/ QGuiApplication {
pub fn topLevelAt_s<RetType, T: QGuiApplication_topLevelAt_s<RetType>>( overload_args: T) -> RetType {
return overload_args.topLevelAt_s();
// return 1;
}
}
pub trait QGuiApplication_topLevelAt_s<RetType> {
fn topLevelAt_s(self ) -> RetType;
}
// proto: static QWindow * QGuiApplication::topLevelAt(const QPoint & pos);
impl<'a> /*trait*/ QGuiApplication_topLevelAt_s<QWindow> for (&'a QPoint) {
fn topLevelAt_s(self ) -> QWindow {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN15QGuiApplication10topLevelAtERK6QPoint()};
let arg0 = self.qclsinst as *mut c_void;
let mut ret = unsafe {C_ZN15QGuiApplication10topLevelAtERK6QPoint(arg0)};
let mut ret1 = QWindow::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QGuiApplication::QGuiApplication(int & argc, char ** argv, int );
impl /*struct*/ QGuiApplication {
pub fn new<T: QGuiApplication_new>(value: T) -> QGuiApplication {
let rsthis = value.new();
return rsthis;
// return 1;
}
}
pub trait QGuiApplication_new {
fn new(self) -> QGuiApplication;
}
// proto: void QGuiApplication::QGuiApplication(int & argc, char ** argv, int );
impl<'a> /*trait*/ QGuiApplication_new for (&'a mut i32, &'a mut String, Option<i32>) {
fn new(self) -> QGuiApplication {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN15QGuiApplicationC2ERiPPci()};
let ctysz: c_int = unsafe{QGuiApplication_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let arg0 = self.0 as *mut c_int;
let arg1 = self.1.as_ptr() as *mut c_char;
let arg2 = (if self.2.is_none() {0 as i32} else {self.2.unwrap()}) as c_int;
let qthis: u64 = unsafe {C_ZN15QGuiApplicationC2ERiPPci(arg0, arg1, arg2)};
let rsthis = QGuiApplication{qbase: QCoreApplication::inheritFrom(qthis), qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: static void QGuiApplication::setDesktopSettingsAware(bool on);
impl /*struct*/ QGuiApplication {
pub fn setDesktopSettingsAware_s<RetType, T: QGuiApplication_setDesktopSettingsAware_s<RetType>>( overload_args: T) -> RetType {
return overload_args.setDesktopSettingsAware_s();
// return 1;
}
}
pub trait QGuiApplication_setDesktopSettingsAware_s<RetType> {
fn setDesktopSettingsAware_s(self ) -> RetType;
}
// proto: static void QGuiApplication::setDesktopSettingsAware(bool on);
impl<'a> /*trait*/ QGuiApplication_setDesktopSettingsAware_s<()> for (i8) {
fn setDesktopSettingsAware_s(self ) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN15QGuiApplication23setDesktopSettingsAwareEb()};
let arg0 = self as c_char;
unsafe {C_ZN15QGuiApplication23setDesktopSettingsAwareEb(arg0)};
// return 1;
}
}
// proto: static QWindow * QGuiApplication::modalWindow();
impl /*struct*/ QGuiApplication {
pub fn modalWindow_s<RetType, T: QGuiApplication_modalWindow_s<RetType>>( overload_args: T) -> RetType {
return overload_args.modalWindow_s();
// return 1;
}
}
pub trait QGuiApplication_modalWindow_s<RetType> {
fn modalWindow_s(self ) -> RetType;
}
// proto: static QWindow * QGuiApplication::modalWindow();
impl<'a> /*trait*/ QGuiApplication_modalWindow_s<QWindow> for () {
fn modalWindow_s(self ) -> QWindow {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN15QGuiApplication11modalWindowEv()};
let mut ret = unsafe {C_ZN15QGuiApplication11modalWindowEv()};
let mut ret1 = QWindow::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: static QString QGuiApplication::applicationDisplayName();
impl /*struct*/ QGuiApplication {
pub fn applicationDisplayName_s<RetType, T: QGuiApplication_applicationDisplayName_s<RetType>>( overload_args: T) -> RetType {
return overload_args.applicationDisplayName_s();
// return 1;
}
}
pub trait QGuiApplication_applicationDisplayName_s<RetType> {
fn applicationDisplayName_s(self ) -> RetType;
}
// proto: static QString QGuiApplication::applicationDisplayName();
impl<'a> /*trait*/ QGuiApplication_applicationDisplayName_s<QString> for () {
fn applicationDisplayName_s(self ) -> QString {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN15QGuiApplication22applicationDisplayNameEv()};
let mut ret = unsafe {C_ZN15QGuiApplication22applicationDisplayNameEv()};
let mut ret1 = QString::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: static int QGuiApplication::exec();
impl /*struct*/ QGuiApplication {
pub fn exec_s<RetType, T: QGuiApplication_exec_s<RetType>>( overload_args: T) -> RetType {
return overload_args.exec_s();
// return 1;
}
}
pub trait QGuiApplication_exec_s<RetType> {
fn exec_s(self ) -> RetType;
}
// proto: static int QGuiApplication::exec();
impl<'a> /*trait*/ QGuiApplication_exec_s<i32> for () {
fn exec_s(self ) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN15QGuiApplication4execEv()};
let mut ret = unsafe {C_ZN15QGuiApplication4execEv()};
return ret as i32; // 1
// return 1;
}
}
// proto: static bool QGuiApplication::quitOnLastWindowClosed();
impl /*struct*/ QGuiApplication {
pub fn quitOnLastWindowClosed_s<RetType, T: QGuiApplication_quitOnLastWindowClosed_s<RetType>>( overload_args: T) -> RetType {
return overload_args.quitOnLastWindowClosed_s();
// return 1;
}
}
pub trait QGuiApplication_quitOnLastWindowClosed_s<RetType> {
fn quitOnLastWindowClosed_s(self ) -> RetType;
}
// proto: static bool QGuiApplication::quitOnLastWindowClosed();
impl<'a> /*trait*/ QGuiApplication_quitOnLastWindowClosed_s<i8> for () {
fn quitOnLastWindowClosed_s(self ) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN15QGuiApplication22quitOnLastWindowClosedEv()};
let mut ret = unsafe {C_ZN15QGuiApplication22quitOnLastWindowClosedEv()};
return ret as i8; // 1
// return 1;
}
}
// proto: static void QGuiApplication::restoreOverrideCursor();
impl /*struct*/ QGuiApplication {
pub fn restoreOverrideCursor_s<RetType, T: QGuiApplication_restoreOverrideCursor_s<RetType>>( overload_args: T) -> RetType {
return overload_args.restoreOverrideCursor_s();
// return 1;
}
}
pub trait QGuiApplication_restoreOverrideCursor_s<RetType> {
fn restoreOverrideCursor_s(self ) -> RetType;
}
// proto: static void QGuiApplication::restoreOverrideCursor();
impl<'a> /*trait*/ QGuiApplication_restoreOverrideCursor_s<()> for () {
fn restoreOverrideCursor_s(self ) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN15QGuiApplication21restoreOverrideCursorEv()};
unsafe {C_ZN15QGuiApplication21restoreOverrideCursorEv()};
// return 1;
}
}
// proto: static QPlatformNativeInterface * QGuiApplication::platformNativeInterface();
impl /*struct*/ QGuiApplication {
pub fn platformNativeInterface_s<RetType, T: QGuiApplication_platformNativeInterface_s<RetType>>( overload_args: T) -> RetType {
return overload_args.platformNativeInterface_s();
// return 1;
}
}
pub trait QGuiApplication_platformNativeInterface_s<RetType> {
fn platformNativeInterface_s(self ) -> RetType;
}
// proto: static QPlatformNativeInterface * QGuiApplication::platformNativeInterface();
impl<'a> /*trait*/ QGuiApplication_platformNativeInterface_s<u64> for () {
fn platformNativeInterface_s(self ) -> u64 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN15QGuiApplication23platformNativeInterfaceEv()};
let mut ret = unsafe {C_ZN15QGuiApplication23platformNativeInterfaceEv()};
return ret as u64; // 4
// return 1;
}
}
// proto: const QMetaObject * QGuiApplication::metaObject();
impl /*struct*/ QGuiApplication {
pub fn metaObject<RetType, T: QGuiApplication_metaObject<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.metaObject(self);
// return 1;
}
}
pub trait QGuiApplication_metaObject<RetType> {
fn metaObject(self , rsthis: & QGuiApplication) -> RetType;
}
// proto: const QMetaObject * QGuiApplication::metaObject();
impl<'a> /*trait*/ QGuiApplication_metaObject<QMetaObject> for () {
fn metaObject(self , rsthis: & QGuiApplication) -> QMetaObject {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK15QGuiApplication10metaObjectEv()};
let mut ret = unsafe {C_ZNK15QGuiApplication10metaObjectEv(rsthis.qclsinst)};
let mut ret1 = QMetaObject::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: static QObject * QGuiApplication::focusObject();
impl /*struct*/ QGuiApplication {
pub fn focusObject_s<RetType, T: QGuiApplication_focusObject_s<RetType>>( overload_args: T) -> RetType {
return overload_args.focusObject_s();
// return 1;
}
}
pub trait QGuiApplication_focusObject_s<RetType> {
fn focusObject_s(self ) -> RetType;
}
// proto: static QObject * QGuiApplication::focusObject();
impl<'a> /*trait*/ QGuiApplication_focusObject_s<QObject> for () {
fn focusObject_s(self ) -> QObject {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN15QGuiApplication11focusObjectEv()};
let mut ret = unsafe {C_ZN15QGuiApplication11focusObjectEv()};
let mut ret1 = QObject::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: static QWindow * QGuiApplication::focusWindow();
impl /*struct*/ QGuiApplication {
pub fn focusWindow_s<RetType, T: QGuiApplication_focusWindow_s<RetType>>( overload_args: T) -> RetType {
return overload_args.focusWindow_s();
// return 1;
}
}
pub trait QGuiApplication_focusWindow_s<RetType> {
fn focusWindow_s(self ) -> RetType;
}
// proto: static QWindow * QGuiApplication::focusWindow();
impl<'a> /*trait*/ QGuiApplication_focusWindow_s<QWindow> for () {
fn focusWindow_s(self ) -> QWindow {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN15QGuiApplication11focusWindowEv()};
let mut ret = unsafe {C_ZN15QGuiApplication11focusWindowEv()};
let mut ret1 = QWindow::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: qreal QGuiApplication::devicePixelRatio();
impl /*struct*/ QGuiApplication {
pub fn devicePixelRatio<RetType, T: QGuiApplication_devicePixelRatio<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.devicePixelRatio(self);
// return 1;
}
}
pub trait QGuiApplication_devicePixelRatio<RetType> {
fn devicePixelRatio(self , rsthis: & QGuiApplication) -> RetType;
}
// proto: qreal QGuiApplication::devicePixelRatio();
impl<'a> /*trait*/ QGuiApplication_devicePixelRatio<f64> for () {
fn devicePixelRatio(self , rsthis: & QGuiApplication) -> f64 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK15QGuiApplication16devicePixelRatioEv()};
let mut ret = unsafe {C_ZNK15QGuiApplication16devicePixelRatioEv(rsthis.qclsinst)};
return ret as f64; // 1
// return 1;
}
}
// proto: static QFunctionPointer QGuiApplication::platformFunction(const QByteArray & function);
impl /*struct*/ QGuiApplication {
pub fn platformFunction_s<RetType, T: QGuiApplication_platformFunction_s<RetType>>( overload_args: T) -> RetType {
return overload_args.platformFunction_s();
// return 1;
}
}
pub trait QGuiApplication_platformFunction_s<RetType> {
fn platformFunction_s(self ) -> RetType;
}
// proto: static QFunctionPointer QGuiApplication::platformFunction(const QByteArray & function);
impl<'a> /*trait*/ QGuiApplication_platformFunction_s<u64> for (&'a QByteArray) {
fn platformFunction_s(self ) -> u64 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN15QGuiApplication16platformFunctionERK10QByteArray()};
let arg0 = self.qclsinst as *mut c_void;
let mut ret = unsafe {C_ZN15QGuiApplication16platformFunctionERK10QByteArray(arg0)};
return ret as u64; // 3
// return 1;
}
}
#[derive(Default)] // for QGuiApplication_saveStateRequest
pub struct QGuiApplication_saveStateRequest_signal{poi:u64}
impl /* struct */ QGuiApplication {
pub fn saveStateRequest(&self) -> QGuiApplication_saveStateRequest_signal {
return QGuiApplication_saveStateRequest_signal{poi:self.qclsinst};
}
}
impl /* struct */ QGuiApplication_saveStateRequest_signal {
pub fn connect<T: QGuiApplication_saveStateRequest_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QGuiApplication_saveStateRequest_signal_connect {
fn connect(self, sigthis: QGuiApplication_saveStateRequest_signal);
}
#[derive(Default)] // for QGuiApplication_applicationStateChanged
pub struct QGuiApplication_applicationStateChanged_signal{poi:u64}
impl /* struct */ QGuiApplication {
pub fn applicationStateChanged(&self) -> QGuiApplication_applicationStateChanged_signal {
return QGuiApplication_applicationStateChanged_signal{poi:self.qclsinst};
}
}
impl /* struct */ QGuiApplication_applicationStateChanged_signal {
pub fn connect<T: QGuiApplication_applicationStateChanged_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QGuiApplication_applicationStateChanged_signal_connect {
fn connect(self, sigthis: QGuiApplication_applicationStateChanged_signal);
}
#[derive(Default)] // for QGuiApplication_screenAdded
pub struct QGuiApplication_screenAdded_signal{poi:u64}
impl /* struct */ QGuiApplication {
pub fn screenAdded(&self) -> QGuiApplication_screenAdded_signal {
return QGuiApplication_screenAdded_signal{poi:self.qclsinst};
}
}
impl /* struct */ QGuiApplication_screenAdded_signal {
pub fn connect<T: QGuiApplication_screenAdded_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QGuiApplication_screenAdded_signal_connect {
fn connect(self, sigthis: QGuiApplication_screenAdded_signal);
}
#[derive(Default)] // for QGuiApplication_screenRemoved
pub struct QGuiApplication_screenRemoved_signal{poi:u64}
impl /* struct */ QGuiApplication {
pub fn screenRemoved(&self) -> QGuiApplication_screenRemoved_signal {
return QGuiApplication_screenRemoved_signal{poi:self.qclsinst};
}
}
impl /* struct */ QGuiApplication_screenRemoved_signal {
pub fn connect<T: QGuiApplication_screenRemoved_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QGuiApplication_screenRemoved_signal_connect {
fn connect(self, sigthis: QGuiApplication_screenRemoved_signal);
}
#[derive(Default)] // for QGuiApplication_focusObjectChanged
pub struct QGuiApplication_focusObjectChanged_signal{poi:u64}
impl /* struct */ QGuiApplication {
pub fn focusObjectChanged(&self) -> QGuiApplication_focusObjectChanged_signal {
return QGuiApplication_focusObjectChanged_signal{poi:self.qclsinst};
}
}
impl /* struct */ QGuiApplication_focusObjectChanged_signal {
pub fn connect<T: QGuiApplication_focusObjectChanged_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QGuiApplication_focusObjectChanged_signal_connect {
fn connect(self, sigthis: QGuiApplication_focusObjectChanged_signal);
}
#[derive(Default)] // for QGuiApplication_paletteChanged
pub struct QGuiApplication_paletteChanged_signal{poi:u64}
impl /* struct */ QGuiApplication {
pub fn paletteChanged(&self) -> QGuiApplication_paletteChanged_signal {
return QGuiApplication_paletteChanged_signal{poi:self.qclsinst};
}
}
impl /* struct */ QGuiApplication_paletteChanged_signal {
pub fn connect<T: QGuiApplication_paletteChanged_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QGuiApplication_paletteChanged_signal_connect {
fn connect(self, sigthis: QGuiApplication_paletteChanged_signal);
}
#[derive(Default)] // for QGuiApplication_focusWindowChanged
pub struct QGuiApplication_focusWindowChanged_signal{poi:u64}
impl /* struct */ QGuiApplication {
pub fn focusWindowChanged(&self) -> QGuiApplication_focusWindowChanged_signal {
return QGuiApplication_focusWindowChanged_signal{poi:self.qclsinst};
}
}
impl /* struct */ QGuiApplication_focusWindowChanged_signal {
pub fn connect<T: QGuiApplication_focusWindowChanged_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QGuiApplication_focusWindowChanged_signal_connect {
fn connect(self, sigthis: QGuiApplication_focusWindowChanged_signal);
}
#[derive(Default)] // for QGuiApplication_lastWindowClosed
pub struct QGuiApplication_lastWindowClosed_signal{poi:u64}
impl /* struct */ QGuiApplication {
pub fn lastWindowClosed(&self) -> QGuiApplication_lastWindowClosed_signal {
return QGuiApplication_lastWindowClosed_signal{poi:self.qclsinst};
}
}
impl /* struct */ QGuiApplication_lastWindowClosed_signal {
pub fn connect<T: QGuiApplication_lastWindowClosed_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QGuiApplication_lastWindowClosed_signal_connect {
fn connect(self, sigthis: QGuiApplication_lastWindowClosed_signal);
}
#[derive(Default)] // for QGuiApplication_fontDatabaseChanged
pub struct QGuiApplication_fontDatabaseChanged_signal{poi:u64}
impl /* struct */ QGuiApplication {
pub fn fontDatabaseChanged(&self) -> QGuiApplication_fontDatabaseChanged_signal {
return QGuiApplication_fontDatabaseChanged_signal{poi:self.qclsinst};
}
}
impl /* struct */ QGuiApplication_fontDatabaseChanged_signal {
pub fn connect<T: QGuiApplication_fontDatabaseChanged_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QGuiApplication_fontDatabaseChanged_signal_connect {
fn connect(self, sigthis: QGuiApplication_fontDatabaseChanged_signal);
}
#[derive(Default)] // for QGuiApplication_layoutDirectionChanged
pub struct QGuiApplication_layoutDirectionChanged_signal{poi:u64}
impl /* struct */ QGuiApplication {
pub fn layoutDirectionChanged(&self) -> QGuiApplication_layoutDirectionChanged_signal {
return QGuiApplication_layoutDirectionChanged_signal{poi:self.qclsinst};
}
}
impl /* struct */ QGuiApplication_layoutDirectionChanged_signal {
pub fn connect<T: QGuiApplication_layoutDirectionChanged_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QGuiApplication_layoutDirectionChanged_signal_connect {
fn connect(self, sigthis: QGuiApplication_layoutDirectionChanged_signal);
}
#[derive(Default)] // for QGuiApplication_commitDataRequest
pub struct QGuiApplication_commitDataRequest_signal{poi:u64}
impl /* struct */ QGuiApplication {
pub fn commitDataRequest(&self) -> QGuiApplication_commitDataRequest_signal {
return QGuiApplication_commitDataRequest_signal{poi:self.qclsinst};
}
}
impl /* struct */ QGuiApplication_commitDataRequest_signal {
pub fn connect<T: QGuiApplication_commitDataRequest_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QGuiApplication_commitDataRequest_signal_connect {
fn connect(self, sigthis: QGuiApplication_commitDataRequest_signal);
}
// focusObjectChanged(class QObject *)
extern fn QGuiApplication_focusObjectChanged_signal_connect_cb_0(rsfptr:fn(QObject), arg0: *mut c_void) {
println!("{}:{}", file!(), line!());
let rsarg0 = QObject::inheritFrom(arg0 as u64);
rsfptr(rsarg0);
}
extern fn QGuiApplication_focusObjectChanged_signal_connect_cb_box_0(rsfptr_raw:*mut Box<Fn(QObject)>, arg0: *mut c_void) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
let rsarg0 = QObject::inheritFrom(arg0 as u64);
// rsfptr(rsarg0);
unsafe{(*rsfptr_raw)(rsarg0)};
}
impl /* trait */ QGuiApplication_focusObjectChanged_signal_connect for fn(QObject) {
fn connect(self, sigthis: QGuiApplication_focusObjectChanged_signal) {
// do smth...
// self as u64; // error for Fn, Ok for fn
self as *mut c_void as u64;
self as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QGuiApplication_focusObjectChanged_signal_connect_cb_0 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QGuiApplication_SlotProxy_connect__ZN15QGuiApplication18focusObjectChangedEP7QObject(arg0, arg1, arg2)};
}
}
impl /* trait */ QGuiApplication_focusObjectChanged_signal_connect for Box<Fn(QObject)> {
fn connect(self, sigthis: QGuiApplication_focusObjectChanged_signal) {
// do smth...
// Box::into_raw(self) as u64;
// Box::into_raw(self) as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QGuiApplication_focusObjectChanged_signal_connect_cb_box_0 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QGuiApplication_SlotProxy_connect__ZN15QGuiApplication18focusObjectChangedEP7QObject(arg0, arg1, arg2)};
}
}
// fontDatabaseChanged()
extern fn QGuiApplication_fontDatabaseChanged_signal_connect_cb_1(rsfptr:fn(), ) {
println!("{}:{}", file!(), line!());
rsfptr();
}
extern fn QGuiApplication_fontDatabaseChanged_signal_connect_cb_box_1(rsfptr_raw:*mut Box<Fn()>, ) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
// rsfptr();
unsafe{(*rsfptr_raw)()};
}
impl /* trait */ QGuiApplication_fontDatabaseChanged_signal_connect for fn() {
fn connect(self, sigthis: QGuiApplication_fontDatabaseChanged_signal) {
// do smth...
// self as u64; // error for Fn, Ok for fn
self as *mut c_void as u64;
self as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QGuiApplication_fontDatabaseChanged_signal_connect_cb_1 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QGuiApplication_SlotProxy_connect__ZN15QGuiApplication19fontDatabaseChangedEv(arg0, arg1, arg2)};
}
}
impl /* trait */ QGuiApplication_fontDatabaseChanged_signal_connect for Box<Fn()> {
fn connect(self, sigthis: QGuiApplication_fontDatabaseChanged_signal) {
// do smth...
// Box::into_raw(self) as u64;
// Box::into_raw(self) as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QGuiApplication_fontDatabaseChanged_signal_connect_cb_box_1 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QGuiApplication_SlotProxy_connect__ZN15QGuiApplication19fontDatabaseChangedEv(arg0, arg1, arg2)};
}
}
// commitDataRequest(class QSessionManager &)
extern fn QGuiApplication_commitDataRequest_signal_connect_cb_2(rsfptr:fn(QSessionManager), arg0: *mut c_void) {
println!("{}:{}", file!(), line!());
let rsarg0 = QSessionManager::inheritFrom(arg0 as u64);
rsfptr(rsarg0);
}
extern fn QGuiApplication_commitDataRequest_signal_connect_cb_box_2(rsfptr_raw:*mut Box<Fn(QSessionManager)>, arg0: *mut c_void) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
let rsarg0 = QSessionManager::inheritFrom(arg0 as u64);
// rsfptr(rsarg0);
unsafe{(*rsfptr_raw)(rsarg0)};
}
impl /* trait */ QGuiApplication_commitDataRequest_signal_connect for fn(QSessionManager) {
fn connect(self, sigthis: QGuiApplication_commitDataRequest_signal) {
// do smth...
// self as u64; // error for Fn, Ok for fn
self as *mut c_void as u64;
self as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QGuiApplication_commitDataRequest_signal_connect_cb_2 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QGuiApplication_SlotProxy_connect__ZN15QGuiApplication17commitDataRequestER15QSessionManager(arg0, arg1, arg2)};
}
}
impl /* trait */ QGuiApplication_commitDataRequest_signal_connect for Box<Fn(QSessionManager)> {
fn connect(self, sigthis: QGuiApplication_commitDataRequest_signal) {
// do smth...
// Box::into_raw(self) as u64;
// Box::into_raw(self) as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QGuiApplication_commitDataRequest_signal_connect_cb_box_2 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QGuiApplication_SlotProxy_connect__ZN15QGuiApplication17commitDataRequestER15QSessionManager(arg0, arg1, arg2)};
}
}
// paletteChanged(const class QPalette &)
extern fn QGuiApplication_paletteChanged_signal_connect_cb_3(rsfptr:fn(QPalette), arg0: *mut c_void) {
println!("{}:{}", file!(), line!());
let rsarg0 = QPalette::inheritFrom(arg0 as u64);
rsfptr(rsarg0);
}
extern fn QGuiApplication_paletteChanged_signal_connect_cb_box_3(rsfptr_raw:*mut Box<Fn(QPalette)>, arg0: *mut c_void) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
let rsarg0 = QPalette::inheritFrom(arg0 as u64);
// rsfptr(rsarg0);
unsafe{(*rsfptr_raw)(rsarg0)};
}
impl /* trait */ QGuiApplication_paletteChanged_signal_connect for fn(QPalette) {
fn connect(self, sigthis: QGuiApplication_paletteChanged_signal) {
// do smth...
// self as u64; // error for Fn, Ok for fn
self as *mut c_void as u64;
self as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QGuiApplication_paletteChanged_signal_connect_cb_3 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QGuiApplication_SlotProxy_connect__ZN15QGuiApplication14paletteChangedERK8QPalette(arg0, arg1, arg2)};
}
}
impl /* trait */ QGuiApplication_paletteChanged_signal_connect for Box<Fn(QPalette)> {
fn connect(self, sigthis: QGuiApplication_paletteChanged_signal) {
// do smth...
// Box::into_raw(self) as u64;
// Box::into_raw(self) as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QGuiApplication_paletteChanged_signal_connect_cb_box_3 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QGuiApplication_SlotProxy_connect__ZN15QGuiApplication14paletteChangedERK8QPalette(arg0, arg1, arg2)};
}
}
// screenRemoved(class QScreen *)
extern fn QGuiApplication_screenRemoved_signal_connect_cb_4(rsfptr:fn(QScreen), arg0: *mut c_void) {
println!("{}:{}", file!(), line!());
let rsarg0 = QScreen::inheritFrom(arg0 as u64);
rsfptr(rsarg0);
}
extern fn QGuiApplication_screenRemoved_signal_connect_cb_box_4(rsfptr_raw:*mut Box<Fn(QScreen)>, arg0: *mut c_void) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
let rsarg0 = QScreen::inheritFrom(arg0 as u64);
// rsfptr(rsarg0);
unsafe{(*rsfptr_raw)(rsarg0)};
}
impl /* trait */ QGuiApplication_screenRemoved_signal_connect for fn(QScreen) {
fn connect(self, sigthis: QGuiApplication_screenRemoved_signal) {
// do smth...
// self as u64; // error for Fn, Ok for fn
self as *mut c_void as u64;
self as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QGuiApplication_screenRemoved_signal_connect_cb_4 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QGuiApplication_SlotProxy_connect__ZN15QGuiApplication13screenRemovedEP7QScreen(arg0, arg1, arg2)};
}
}
impl /* trait */ QGuiApplication_screenRemoved_signal_connect for Box<Fn(QScreen)> {
fn connect(self, sigthis: QGuiApplication_screenRemoved_signal) {
// do smth...
// Box::into_raw(self) as u64;
// Box::into_raw(self) as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QGuiApplication_screenRemoved_signal_connect_cb_box_4 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QGuiApplication_SlotProxy_connect__ZN15QGuiApplication13screenRemovedEP7QScreen(arg0, arg1, arg2)};
}
}
// focusWindowChanged(class QWindow *)
extern fn QGuiApplication_focusWindowChanged_signal_connect_cb_5(rsfptr:fn(QWindow), arg0: *mut c_void) {
println!("{}:{}", file!(), line!());
let rsarg0 = QWindow::inheritFrom(arg0 as u64);
rsfptr(rsarg0);
}
extern fn QGuiApplication_focusWindowChanged_signal_connect_cb_box_5(rsfptr_raw:*mut Box<Fn(QWindow)>, arg0: *mut c_void) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
let rsarg0 = QWindow::inheritFrom(arg0 as u64);
// rsfptr(rsarg0);
unsafe{(*rsfptr_raw)(rsarg0)};
}
impl /* trait */ QGuiApplication_focusWindowChanged_signal_connect for fn(QWindow) {
fn connect(self, sigthis: QGuiApplication_focusWindowChanged_signal) {
// do smth...
// self as u64; // error for Fn, Ok for fn
self as *mut c_void as u64;
self as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QGuiApplication_focusWindowChanged_signal_connect_cb_5 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QGuiApplication_SlotProxy_connect__ZN15QGuiApplication18focusWindowChangedEP7QWindow(arg0, arg1, arg2)};
}
}
impl /* trait */ QGuiApplication_focusWindowChanged_signal_connect for Box<Fn(QWindow)> {
fn connect(self, sigthis: QGuiApplication_focusWindowChanged_signal) {
// do smth...
// Box::into_raw(self) as u64;
// Box::into_raw(self) as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QGuiApplication_focusWindowChanged_signal_connect_cb_box_5 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QGuiApplication_SlotProxy_connect__ZN15QGuiApplication18focusWindowChangedEP7QWindow(arg0, arg1, arg2)};
}
}
// lastWindowClosed()
extern fn QGuiApplication_lastWindowClosed_signal_connect_cb_6(rsfptr:fn(), ) {
println!("{}:{}", file!(), line!());
rsfptr();
}
extern fn QGuiApplication_lastWindowClosed_signal_connect_cb_box_6(rsfptr_raw:*mut Box<Fn()>, ) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
// rsfptr();
unsafe{(*rsfptr_raw)()};
}
impl /* trait */ QGuiApplication_lastWindowClosed_signal_connect for fn() {
fn connect(self, sigthis: QGuiApplication_lastWindowClosed_signal) {
// do smth...
// self as u64; // error for Fn, Ok for fn
self as *mut c_void as u64;
self as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QGuiApplication_lastWindowClosed_signal_connect_cb_6 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QGuiApplication_SlotProxy_connect__ZN15QGuiApplication16lastWindowClosedEv(arg0, arg1, arg2)};
}
}
impl /* trait */ QGuiApplication_lastWindowClosed_signal_connect for Box<Fn()> {
fn connect(self, sigthis: QGuiApplication_lastWindowClosed_signal) {
// do smth...
// Box::into_raw(self) as u64;
// Box::into_raw(self) as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QGuiApplication_lastWindowClosed_signal_connect_cb_box_6 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QGuiApplication_SlotProxy_connect__ZN15QGuiApplication16lastWindowClosedEv(arg0, arg1, arg2)};
}
}
// screenAdded(class QScreen *)
extern fn QGuiApplication_screenAdded_signal_connect_cb_7(rsfptr:fn(QScreen), arg0: *mut c_void) {
println!("{}:{}", file!(), line!());
let rsarg0 = QScreen::inheritFrom(arg0 as u64);
rsfptr(rsarg0);
}
extern fn QGuiApplication_screenAdded_signal_connect_cb_box_7(rsfptr_raw:*mut Box<Fn(QScreen)>, arg0: *mut c_void) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
let rsarg0 = QScreen::inheritFrom(arg0 as u64);
// rsfptr(rsarg0);
unsafe{(*rsfptr_raw)(rsarg0)};
}
impl /* trait */ QGuiApplication_screenAdded_signal_connect for fn(QScreen) {
fn connect(self, sigthis: QGuiApplication_screenAdded_signal) {
// do smth...
// self as u64; // error for Fn, Ok for fn
self as *mut c_void as u64;
self as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QGuiApplication_screenAdded_signal_connect_cb_7 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QGuiApplication_SlotProxy_connect__ZN15QGuiApplication11screenAddedEP7QScreen(arg0, arg1, arg2)};
}
}
impl /* trait */ QGuiApplication_screenAdded_signal_connect for Box<Fn(QScreen)> {
fn connect(self, sigthis: QGuiApplication_screenAdded_signal) {
// do smth...
// Box::into_raw(self) as u64;
// Box::into_raw(self) as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QGuiApplication_screenAdded_signal_connect_cb_box_7 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QGuiApplication_SlotProxy_connect__ZN15QGuiApplication11screenAddedEP7QScreen(arg0, arg1, arg2)};
}
}
// saveStateRequest(class QSessionManager &)
extern fn QGuiApplication_saveStateRequest_signal_connect_cb_8(rsfptr:fn(QSessionManager), arg0: *mut c_void) {
println!("{}:{}", file!(), line!());
let rsarg0 = QSessionManager::inheritFrom(arg0 as u64);
rsfptr(rsarg0);
}
extern fn QGuiApplication_saveStateRequest_signal_connect_cb_box_8(rsfptr_raw:*mut Box<Fn(QSessionManager)>, arg0: *mut c_void) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
let rsarg0 = QSessionManager::inheritFrom(arg0 as u64);
// rsfptr(rsarg0);
unsafe{(*rsfptr_raw)(rsarg0)};
}
impl /* trait */ QGuiApplication_saveStateRequest_signal_connect for fn(QSessionManager) {
fn connect(self, sigthis: QGuiApplication_saveStateRequest_signal) {
// do smth...
// self as u64; // error for Fn, Ok for fn
self as *mut c_void as u64;
self as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QGuiApplication_saveStateRequest_signal_connect_cb_8 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QGuiApplication_SlotProxy_connect__ZN15QGuiApplication16saveStateRequestER15QSessionManager(arg0, arg1, arg2)};
}
}
impl /* trait */ QGuiApplication_saveStateRequest_signal_connect for Box<Fn(QSessionManager)> {
fn connect(self, sigthis: QGuiApplication_saveStateRequest_signal) {
// do smth...
// Box::into_raw(self) as u64;
// Box::into_raw(self) as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QGuiApplication_saveStateRequest_signal_connect_cb_box_8 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QGuiApplication_SlotProxy_connect__ZN15QGuiApplication16saveStateRequestER15QSessionManager(arg0, arg1, arg2)};
}
}
// <= body block end
|
/*************************************************************************
* ph0llux:24efd740f491bae39a06ceb74c1f642f8d93b8e4aebdf03f95e32031b4f7ceea
*************************************************************************/
// - external
use base64::{encode};
use hex::ToHex as HexToHex;
pub trait ToBase64 {
/// method converts the input to a base64 encoded [String].
/// # Example
/// ```
///
/// extern crate phollaits;
/// use phollaits::{ToBase64};
/// fn main() {
/// let a = "Teststring".to_string();
/// assert_eq!(a.base64(), "VGVzdHN0cmluZw==".to_string());
/// }
fn base64(self) -> String;
}
impl ToBase64 for String {
fn base64(self) -> String {
encode(self.as_bytes())
}
}
impl ToBase64 for &str {
fn base64(self) -> String {
encode(self.as_bytes())
}
}
impl ToBase64 for Vec<u8> {
fn base64(self) -> String {
encode(self)
}
}
pub trait ToHex {
fn hexify(self) -> String;
fn hexify_upper(self) -> String;
}
impl<T: AsRef<[u8]>> ToHex for T {
/// converts a value (implementing AsRef<[u8]>; this includes String, str, Vec<u8> and [u8]) to hex.
/// # Example
/// ```
/// use phollaits::{ToHex};
///
/// fn main() {
/// let value = "myValue!";
/// assert_eq!(value.hexify(), "6d7956616c756521".to_string())
/// }
/// ```
fn hexify(self) -> String {
self.encode_hex::<String>()
}
/// converts a value (implementing AsRef<[u8]>; this includes String, str, Vec<u8> and [u8]) to hex (UPPER_CASE).
/// # Example
/// ```
/// use phollaits::{ToHex};
///
/// fn main() {
/// let value = "myValue!";
/// assert_eq!(value.hexify_upper(), "6D7956616C756521".to_string())
/// }
/// ```
fn hexify_upper(self) -> String {
self.encode_hex_upper::<String>()
}
} |
use std::ops::{Add, Div, Range};
use std::cmp::max;
use num::{Integer, NumCast};
trait Midpoint<T> {
fn midpoint(&self) -> T;
}
impl<T> Midpoint<T> for Range<T>
where T: Add<Output = T> + Div<Output = T> + Copy + Integer + NumCast {
fn midpoint(&self) -> T {
return (self.start + self.end) / NumCast::from(2).unwrap();
}
}
fn main() {
let mut max_id = 0;
let mut seats = Vec::<bool>::new();
seats.resize(1000, false);
for line in aoc::read_lines_as_vec("./day5.txt") {
let mut row = 0..128;
let mut col = 0..8;
for c in line.chars() {
match c {
'F' => row = row.start..row.midpoint(),
'B' => row = row.midpoint()..row.end,
'L' => col = col.start..col.midpoint(),
'R' => col = col.midpoint()..col.end,
_ => panic!("That's not allowed stahp"),
};
}
let id = row.start * 8 + col.start;
seats[id] = true;
max_id = max(max_id, id);
}
println!("Max ID: {}", max_id);
for (i, seat) in seats.iter().enumerate() {
if i == 0 { continue; }
if i == max_id { break; }
if seats[i-1] && !seat && seats[i+1] {
println!("My Seat: {}", i);
break;
}
}
}
|
use winnow::combinator::alt;
use winnow::combinator::fail;
use winnow::combinator::peek;
use winnow::token::any;
use crate::parser::array::array;
use crate::parser::datetime::date_time;
use crate::parser::inline_table::inline_table;
use crate::parser::numbers::{float, integer};
use crate::parser::prelude::*;
use crate::parser::strings::string;
use crate::repr::{Formatted, Repr};
use crate::value as v;
use crate::RawString;
use crate::Value;
// val = string / boolean / array / inline-table / date-time / float / integer
pub(crate) fn value<'i>(check: RecursionCheck) -> impl Parser<Input<'i>, v::Value, ContextError> {
move |input: &mut Input<'i>| {
dispatch!{peek(any);
crate::parser::strings::QUOTATION_MARK |
crate::parser::strings::APOSTROPHE => string.map(|s| {
v::Value::String(Formatted::new(
s.into_owned()
))
}),
crate::parser::array::ARRAY_OPEN => array(check).map(v::Value::Array),
crate::parser::inline_table::INLINE_TABLE_OPEN => inline_table(check).map(v::Value::InlineTable),
// Date/number starts
b'+' | b'-' | b'0'..=b'9' => {
// Uncommon enough not to be worth optimizing at this time
alt((
date_time
.map(v::Value::from),
float
.map(v::Value::from),
integer
.map(v::Value::from),
))
},
// Report as if they were numbers because its most likely a typo
b'_' => {
integer
.map(v::Value::from)
.context(StrContext::Expected(StrContextValue::Description("leading digit")))
},
// Report as if they were numbers because its most likely a typo
b'.' => {
float
.map(v::Value::from)
.context(StrContext::Expected(StrContextValue::Description("leading digit")))
},
b't' => {
crate::parser::numbers::true_.map(v::Value::from)
.context(StrContext::Label("string"))
.context(StrContext::Expected(StrContextValue::CharLiteral('"')))
.context(StrContext::Expected(StrContextValue::CharLiteral('\'')))
},
b'f' => {
crate::parser::numbers::false_.map(v::Value::from)
.context(StrContext::Label("string"))
.context(StrContext::Expected(StrContextValue::CharLiteral('"')))
.context(StrContext::Expected(StrContextValue::CharLiteral('\'')))
},
b'i' => {
crate::parser::numbers::inf.map(v::Value::from)
.context(StrContext::Label("string"))
.context(StrContext::Expected(StrContextValue::CharLiteral('"')))
.context(StrContext::Expected(StrContextValue::CharLiteral('\'')))
},
b'n' => {
crate::parser::numbers::nan.map(v::Value::from)
.context(StrContext::Label("string"))
.context(StrContext::Expected(StrContextValue::CharLiteral('"')))
.context(StrContext::Expected(StrContextValue::CharLiteral('\'')))
},
_ => {
fail
.context(StrContext::Label("string"))
.context(StrContext::Expected(StrContextValue::CharLiteral('"')))
.context(StrContext::Expected(StrContextValue::CharLiteral('\'')))
},
}
.with_span()
.try_map(|(value, span)| apply_raw(value, span))
.parse_next(input)
}
}
fn apply_raw(mut val: Value, span: std::ops::Range<usize>) -> Result<Value, std::str::Utf8Error> {
match val {
Value::String(ref mut f) => {
let raw = RawString::with_span(span);
f.set_repr_unchecked(Repr::new_unchecked(raw));
}
Value::Integer(ref mut f) => {
let raw = RawString::with_span(span);
f.set_repr_unchecked(Repr::new_unchecked(raw));
}
Value::Float(ref mut f) => {
let raw = RawString::with_span(span);
f.set_repr_unchecked(Repr::new_unchecked(raw));
}
Value::Boolean(ref mut f) => {
let raw = RawString::with_span(span);
f.set_repr_unchecked(Repr::new_unchecked(raw));
}
Value::Datetime(ref mut f) => {
let raw = RawString::with_span(span);
f.set_repr_unchecked(Repr::new_unchecked(raw));
}
Value::Array(ref mut arr) => {
arr.span = Some(span);
}
Value::InlineTable(ref mut table) => {
table.span = Some(span);
}
};
val.decorate("", "");
Ok(val)
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn values() {
let inputs = [
"1979-05-27T00:32:00.999999",
"-239",
"1e200",
"9_224_617.445_991_228_313",
r#"'''I [dw]on't need \d{2} apples'''"#,
r#"'''
The first newline is
trimmed in raw strings.
All other whitespace
is preserved.
'''"#,
r#""Jos\u00E9\n""#,
r#""\\\"\b/\f\n\r\t\u00E9\U000A0000""#,
r#"{ hello = "world", a = 1}"#,
r#"[ { x = 1, a = "2" }, {a = "a",b = "b", c = "c"} ]"#,
];
for input in inputs {
dbg!(input);
let mut parsed = value(Default::default()).parse(new_input(input));
if let Ok(parsed) = &mut parsed {
parsed.despan(input);
}
assert_eq!(parsed.map(|a| a.to_string()), Ok(input.to_owned()));
}
}
}
|
use std::path::PathBuf;
#[ derive (Debug, Deserialize, Serialize) ]
pub struct FileDataRecord {
pub path: PathBuf,
pub size: u64,
#[ serde (skip_serializing_if = "Option::is_none") ]
pub content_hash: Option <String>,
#[ serde (skip_serializing_if = "Option::is_none") ]
pub content_hash_time: Option <i64>,
#[ serde (skip_serializing_if = "Option::is_none") ]
pub extent_hash: Option <String>,
#[ serde (skip_serializing_if = "Option::is_none") ]
pub extent_hash_time: Option <i64>,
#[ serde (skip_serializing_if = "Option::is_none") ]
pub defragment_time: Option <i64>,
#[ serde (skip_serializing_if = "Option::is_none") ]
pub deduplicate_time: Option <i64>,
pub mtime: i64,
pub ctime: i64,
pub mode: u32,
pub uid: u32,
pub gid: u32,
}
// ex: noet ts=4 filetype=rust
|
#![ allow( non_snake_case ) ]
use std::fs;
use serial_test::*;
use lt_blockchain::blockchain::{ digest, system };
//
#[ test ]
#[ ignore ]
fn new()
{
/*
issue : https://github.com/Learn-Together-Pro/Blockchain/issues/33
To run test enter :
cargo test system_test::new -- --ignored
When test will pass, comment out directive `#[ ignore ]`.
*/
println!( "empty initial transactions" );
let system = system::System::new();
assert_eq!( system.chain.blocks.len(), 1 );
assert_eq!( system.chain.blocks[ 0 ].body.transactions.len(), 1 );
assert_eq!( system.store_path.clone(), system::System::StorePathDefault() );
assert_eq!( system.wallets.len(), 1 );
let wallet = system.wallets.get( &String::from( "root" ) );
assert_eq!( wallet.is_some(), true );
assert_eq!( system.chain.balance_get( &wallet.unwrap().public_key.clone() ), system::START_AMOUNT );
}
//
#[ test ]
#[ ignore ]
fn valid_is()
{
let system_original = system::System::new();
/* */
println!( "valid system" );
let system = system_original.clone();
let got = system.valid_is();
assert_eq!( got, true );
println!( "system has no root wallet" );
let mut system = system_original.clone();
system.wallets.remove( &String::from( "root" ) ).unwrap();
let got = system.valid_is();
assert_eq!( got, false );
println!( "system has invalid public key of root wallet" );
let mut system = system_original.clone();
let key = digest::Digest::from( Vec::from([ 0u8 ; 270 ]) );
let mut root_wallet = system.wallets.get_mut( &String::from( "root" ) ).unwrap();
root_wallet.public_key = key;
let got = system.valid_is();
assert_eq!( got, false );
}
//
#[ test ]
#[ ignore ]
fn Make()
{
/*
issue : https://github.com/Learn-Together-Pro/Blockchain/issues/21
To run test enter :
cargo test system_test::Make -- --ignored
When test will pass, comment out directive `#[ ignore ]`.
*/
println!( "empty initial transactions" );
let system = system::System::Make();
assert_eq!( system.chain.blocks.len(), 1 );
assert_eq!( system.chain.blocks[ 0 ].body.transactions.len(), 1 );
assert_eq!( system.store_path.clone(), system::System::StorePathDefault() );
assert_eq!( system.wallets.len(), 1 );
let wallet = system.wallets.get( &String::from( "root" ) );
assert_eq!( wallet.is_some(), true );
assert_eq!( system.chain.balance_get( &wallet.unwrap().public_key.clone() ), system::START_AMOUNT );
assert_eq!( fs::read_to_string( &system.store_path ).is_err(), true );
}
//
#[ test ]
#[ ignore ]
fn MakePersistant()
{
/*
issue : https://github.com/Learn-Together-Pro/Blockchain/issues/12
To run test enter :
cargo test system_test::MakePersistant -- --ignored
When test will pass, comment out directive `#[ ignore ]`.
*/
println!( "empty initial transactions" );
let system = system::System::MakePersistant();
assert_eq!( system.chain.blocks.len(), 1 );
assert_eq!( system.chain.blocks[ 0 ].body.transactions.len(), 1 );
assert_eq!( system.store_path.clone(), system::System::StorePathDefault() );
assert_eq!( system.wallets.len(), 1 );
let wallet = system.wallets.get( &String::from( "root" ) );
assert_eq!( wallet.is_some(), true );
assert_eq!( system.chain.balance_get( &wallet.unwrap().public_key.clone() ), system::START_AMOUNT );
assert_eq!( fs::read_to_string( &system.store_path ).is_ok(), true );
fs::remove_file( &system.store_path ).unwrap();
}
//
#[ test ]
#[ ignore ]
fn StorePathDefault()
{
/*
issue : https://github.com/Learn-Together-Pro/Blockchain/issues/16
To run test enter :
cargo test system_test::StorePathDefault -- --ignored
When test will pass, comment out directive `#[ ignore ]`.
*/
fs::remove_file( system::System::StorePathDefault() ).unwrap_or_default();
/* */
println!( "no system with persistent" );
let path = system::System::StorePathDefault();
assert_eq!( path.exists(), false );
assert_eq!( path.is_file(), false );
assert_eq!( path.is_absolute(), true );
assert_eq!( path.file_name().unwrap().to_str().unwrap(), "chain.json" );
println!( "system with persistent" );
let system = system::System::MakePersistant();
let path = system::System::StorePathDefault();
assert_eq!( path.exists(), true );
assert_eq!( path.is_file(), true );
assert_eq!( path.is_absolute(), true );
assert_eq!( path.file_name().unwrap().to_str().unwrap(), "chain.json" );
fs::remove_file( &system.store_path ).unwrap();
}
//
#[ test ]
#[ ignore ]
#[ serial ]
fn Load()
{
fs::remove_file( system::System::StorePathDefault() ).unwrap_or_default();
/* */
println!( "no file" );
let got = system::System::Load();
assert_eq!( got.is_err(), true );
println!( "wrong schema of json file" );
let path = system::System::StorePathDefault();
fs::write( &path, "{}" ).unwrap();
let got = system::System::Load();
assert_eq!( got.is_err(), true );
fs::remove_file( &path ).unwrap();
println!( "load from file" );
let system = system::System::MakePersistant();
let got = system::System::Load();
assert_eq!( got.is_ok(), true );
assert_eq!( got.unwrap(), system );
fs::remove_file( &system.store_path ).unwrap();
}
//
#[ test ]
#[ ignore ]
#[ serial ]
fn LoadFromFile()
{
/*
issue : https://github.com/Learn-Together-Pro/Blockchain/issues/13
To run test enter :
cargo test system_test::LoadFromFile -- --ignored
When test will pass, comment out directive `#[ ignore ]`.
*/
fs::remove_file( system::System::StorePathDefault() ).unwrap_or_default();
/* */
println!( "no file" );
let path = system::System::StorePathDefault();
let got = system::System::LoadFromFile( &path );
assert_eq!( got.is_err(), true );
println!( "wrong schema of json file" );
let path = system::System::StorePathDefault();
fs::write( &path, "{}" ).unwrap();
let got = system::System::LoadFromFile( &path );
assert_eq!( got.is_err(), true );
fs::remove_file( &path ).unwrap();
println!( "load from file" );
let system = system::System::MakePersistant();
let path = system::System::StorePathDefault();
let got = system::System::LoadFromFile( &path );
assert_eq!( got.is_ok(), true );
assert_eq!( got.unwrap(), system );
fs::remove_file( &system.store_path ).unwrap();
}
//
#[ test ]
#[ ignore ]
#[ serial ]
fn store()
{
let store_path = system::System::StorePathDefault();
fs::remove_file( &store_path ).unwrap_or_default();
/* */
println!( "store system to user path" );
let system = system::System::new();
assert_eq!( system.store_path.exists(), false );
assert_eq!( system.store_path.is_file(), false );
system.store();
assert_eq!( system.store_path.exists(), true );
assert_eq!( system.store_path.is_file(), true );
let got = system::System::LoadFromFile( &system.store_path );
assert_eq!( got.is_ok(), true );
assert_eq!( got.unwrap(), system );
fs::remove_file( &store_path ).unwrap();
}
//
#[ test ]
#[ ignore ]
fn store_to()
{
/*
issue : https://github.com/Learn-Together-Pro/Blockchain/issues/11
To run test enter :
cargo test system_test::store_to -- --ignored
When test will pass, comment out directive `#[ ignore ]`.
*/
let store_path = system::System::StorePathDefault().with_file_name( "store.json" );
fs::remove_file( &store_path ).unwrap_or_default();
/* */
println!( "store system to user path" );
let path = store_path.clone();
let system = system::System::new();
system.store_to( &path );
assert_eq!( path.exists(), true );
assert_eq!( path.is_file(), true );
let got = system::System::LoadFromFile( &path );
assert_eq!( got.is_ok(), true );
assert_eq!( got.unwrap(), system );
fs::remove_file( &path ).unwrap();
}
|
#[doc = "Writer for register ICR"]
pub type W = crate::W<u32, super::ICR>;
#[doc = "Register ICR `reset()`'s with value 0"]
impl crate::ResetValue for super::ICR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Write proxy for field `CRXBFF`"]
pub struct CRXBFF_W<'a> {
w: &'a mut W,
}
impl<'a> CRXBFF_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01);
self.w
}
}
#[doc = "Write proxy for field `CTXBEF`"]
pub struct CTXBEF_W<'a> {
w: &'a mut W,
}
impl<'a> CTXBEF_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1);
self.w
}
}
#[doc = "Write proxy for field `CRXBERF`"]
pub struct CRXBERF_W<'a> {
w: &'a mut W,
}
impl<'a> CRXBERF_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2);
self.w
}
}
#[doc = "Write proxy for field `CRXOVRF`"]
pub struct CRXOVRF_W<'a> {
w: &'a mut W,
}
impl<'a> CRXOVRF_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 3)) | (((value as u32) & 0x01) << 3);
self.w
}
}
#[doc = "Write proxy for field `CTXUNRF`"]
pub struct CTXUNRF_W<'a> {
w: &'a mut W,
}
impl<'a> CTXUNRF_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 4)) | (((value as u32) & 0x01) << 4);
self.w
}
}
#[doc = "Write proxy for field `CTCF`"]
pub struct CTCF_W<'a> {
w: &'a mut W,
}
impl<'a> CTCF_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 7)) | (((value as u32) & 0x01) << 7);
self.w
}
}
#[doc = "Write proxy for field `CSRF`"]
pub struct CSRF_W<'a> {
w: &'a mut W,
}
impl<'a> CSRF_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 8)) | (((value as u32) & 0x01) << 8);
self.w
}
}
#[doc = "Write proxy for field `CRDYF`"]
pub struct CRDYF_W<'a> {
w: &'a mut W,
}
impl<'a> CRDYF_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 11)) | (((value as u32) & 0x01) << 11);
self.w
}
}
impl W {
#[doc = "Bit 0 - Clear receive buffer full flag"]
#[inline(always)]
pub fn crxbff(&mut self) -> CRXBFF_W {
CRXBFF_W { w: self }
}
#[doc = "Bit 1 - Clear transmit buffer empty flag"]
#[inline(always)]
pub fn ctxbef(&mut self) -> CTXBEF_W {
CTXBEF_W { w: self }
}
#[doc = "Bit 2 - Clear receive CRC error flag"]
#[inline(always)]
pub fn crxberf(&mut self) -> CRXBERF_W {
CRXBERF_W { w: self }
}
#[doc = "Bit 3 - Clear receive overrun error flag"]
#[inline(always)]
pub fn crxovrf(&mut self) -> CRXOVRF_W {
CRXOVRF_W { w: self }
}
#[doc = "Bit 4 - Clear transmit underrun error flag"]
#[inline(always)]
pub fn ctxunrf(&mut self) -> CTXUNRF_W {
CTXUNRF_W { w: self }
}
#[doc = "Bit 7 - Clear transfer complete flag"]
#[inline(always)]
pub fn ctcf(&mut self) -> CTCF_W {
CTCF_W { w: self }
}
#[doc = "Bit 8 - Clear slave resume flag"]
#[inline(always)]
pub fn csrf(&mut self) -> CSRF_W {
CSRF_W { w: self }
}
#[doc = "Bit 11 - Clear transceiver ready flag"]
#[inline(always)]
pub fn crdyf(&mut self) -> CRDYF_W {
CRDYF_W { w: self }
}
}
|
use std::{thread, time::Duration};
use opencv::{
core,
highgui,
imgproc,
prelude::*,
types,
videoio,
};
fn make_veci32(i: i32) -> types::VectorOfi32 {
let mut result = types::VectorOfi32::with_capacity(1);
result.push(i);
return result;
}
fn make_vecf32(v0: f32, v1: f32) -> types::VectorOff32 {
let mut result = types::VectorOff32::with_capacity(2);
result.push(v0);
result.push(v1);
return result;
}
fn compute_pt(x: i32, val: f32, num_buckets: i32, max_count: f32,
image_width: i32, image_height: i32,
bounds: &core::Rect) -> core::Point {
let tx = x as f32 / num_buckets as f32;
let ty = 1. - val / max_count;
let ix = bounds.x + (tx * bounds.width as f32) as i32;
let iy = bounds.y + (ty * bounds.height as f32) as i32;
return core::Point { x: ix, y: iy};
}
fn compute_histogram(images: &types::VectorOfMat, channel: i32, num_buckets: i32) -> Result<Mat, opencv::Error> {
let mut hist = Mat::default()?;
let channels = make_veci32(channel);
let mask = Mat::default()?;
let hist_size = make_veci32(num_buckets);
let ranges = make_vecf32(0., 255.);
let accumulate = false;
match imgproc::calc_hist(&images, &channels, &mask,
&mut hist,
&hist_size, &ranges, accumulate) {
Result::Ok(_) => {
// println!("hist = {:?}", r_hist);
},
Result::Err(err) => println!("error in calc_hist {:?}", err)
}
return Ok(hist);
}
fn draw_histogram(mut frame: &mut Mat, r_hist: Mat, g_hist: Mat, b_hist: Mat, bounds: core::Rect) {
let hist_size = r_hist.rows();
let mut frame_width = 0;
let mut frame_height = 0;
match frame.size() {
Result::Ok(s) => {
frame_width = s.width;
frame_height = s.height;
}
Err(_) => { }
}
let red = core::Scalar::new( 0., 0.,255., 0.);
let green = core::Scalar::new( 0.,255., 0., 0.);
let blue = core::Scalar::new(255., 0., 0., 0.);
let black = core::Scalar::new( 0., 0., 0., 0.);
let _white = core::Scalar::new(255.,255.,255., 0.);
let line_width = 1;
let _fill_type = imgproc::LineTypes::FILLED as i32;
let line_type = imgproc::LineTypes::LINE_8 as i32;
let shift = 0;
let mut max_count = 0. as f32;
for i in 0..r_hist.rows() {
match r_hist.at(i) {
Result::Ok(v) => {
max_count = max_count.max(*v);
}
Err(_) => { }
}
match g_hist.at(i) {
Result::Ok(v) => {
max_count = max_count.max(*v);
}
Err(_) => { }
}
match b_hist.at(i) {
Result::Ok(v) => {
max_count = max_count.max(*v);
}
Err(_) => { }
}
}
let ll = compute_pt(0,0.,hist_size, max_count,frame_width, frame_height, &bounds);
let ur = compute_pt(hist_size,max_count, hist_size,max_count,frame_width,frame_height, &bounds);
let outline = core::Rect { x: ll.x, y: ur.y, width: ur.x-ll.x, height: ll.y-ur.y };
// background
// let r = imgproc::rectangle(&mut frame, outline,
// _white, _fill_type, line_type, shift);
let mut r_prev = 0 as f32;
match r_hist.at(0) {
Result::Ok(prev) => {
r_prev = *prev;
}
Err(_) => { }
}
let mut g_prev = 0 as f32;
match g_hist.at(0) {
Result::Ok(prev) => {
g_prev = *prev;
}
Err(_) => { }
}
let mut b_prev = 0 as f32;
match b_hist.at(0) {
Result::Ok(prev) => {
b_prev = *prev;
}
Err(_) => { }
}
for i in 1..hist_size {
match r_hist.at(i) {
Result::Ok(next) => {
let r_next = *next;
let _ = imgproc::line(&mut frame,
compute_pt(i-1, r_prev, hist_size, max_count, frame_width, frame_height, &bounds),
compute_pt(i, r_next, hist_size, max_count, frame_width, frame_height, &bounds),
red,
line_width, line_type, shift);
r_prev = r_next;
}
Err(_) => { }
}
match g_hist.at(i) {
Result::Ok(next) => {
let g_next = *next;
let _ = imgproc::line(&mut frame,
compute_pt(i-1, g_prev, hist_size, max_count, frame_width, frame_height, &bounds),
compute_pt(i, g_next, hist_size, max_count, frame_width, frame_height, &bounds),
green,
line_width, line_type, shift);
g_prev = g_next;
}
Err(_) => { }
}
match b_hist.at(i) {
Result::Ok(next) => {
let b_next = *next;
let _ = imgproc::line(&mut frame,
compute_pt(i-1, b_prev, hist_size, max_count, frame_width, frame_height, &bounds),
compute_pt(i, b_next, hist_size, max_count, frame_width, frame_height, &bounds),
blue,
line_width, line_type, shift);
b_prev = b_next;
}
Err(_) => { }
}
}
let _ = imgproc::rectangle(&mut frame, outline,
black, line_width, line_type,shift);
}
fn run() -> opencv::Result<()> {
let num_buckets = 256;
let hist_width = 600;
let hist_height = 150;
let hist_pad = 32;
// Create a window
let window = "video capture";
highgui::named_window(window, 1)?;
// Open the video camera
let mut cam = videoio::VideoCapture::new(0, videoio::CAP_ANY)?; // 0 is the default camera
if !videoio::VideoCapture::is_opened(&cam)? {
panic!("Unable to open default camera!");
}
loop {
let mut frame = Mat::default()?;
cam.read(&mut frame)?;
if frame.size()?.width == 0 {
thread::sleep(Duration::from_secs(50));
continue;
}
// compute histograms
let mut images = types::VectorOfMat::with_capacity(1);
images.push(frame.clone()?); // wassup with clone?
let r_hist = compute_histogram(&images, 2, num_buckets)?;
let g_hist = compute_histogram(&images, 1, num_buckets)?;
let b_hist = compute_histogram(&images, 0, num_buckets)?;
// draw the histogram
let hist_bounds = core::Rect {
x: (frame.size()?.width - hist_width) / 2,
y: frame.size()?.height - (hist_height + hist_pad),
width: hist_width,
height: hist_height
};
draw_histogram(&mut frame, r_hist, g_hist, b_hist, hist_bounds);
// Display the image
highgui::imshow(window, &frame)?;
// Wait 10 milliseconds and quit if a key was pressed
if highgui::wait_key(10)? > 0 {
break;
}
}
Ok(())
}
fn main() {
run().unwrap()
}
|
///! This module defines an error type which distinguishes between runtime and system exceptions.
///!
///! Errors which are part of the normal execution of an Erlang program are represented by the
///! `RuntimeException` type, while errors which are not recoverable from Erlang code are
/// represented ! by the `SystemException` type.
// Allocation errors
mod alloc;
pub use self::alloc::Alloc;
// A wrapper around anyhow::Error that can be cloned and shared across threads
mod arc;
pub use self::arc::ArcError;
// The concrete implementations of the runtime exception classes
mod classes;
pub use self::classes::{Class, Error, Exit, Throw};
mod erlang;
pub use self::erlang::ErlangException;
// A location represents file/line/column info about an error
mod location;
pub use self::location::Location;
// These helpers provide convenience constructors for common error types
mod helpers;
pub use self::helpers::*;
mod internal;
pub use self::internal::*;
mod runtime;
pub use self::runtime::RuntimeException;
mod system;
pub use self::system::SystemException;
use core::any::type_name;
use core::convert::Into;
use core::marker::PhantomData;
use thiserror::Error;
use super::term::prelude::*;
use crate::erts::process::trace::Trace;
use crate::erts::string::InvalidEncodingNameError;
/// A convenience type alias for results which fail with `Exception`
pub type Result<T> = core::result::Result<T, Exception>;
/// A convenience type alias for results from allocating functions
pub type AllocResult<T> = core::result::Result<T, Alloc>;
/// An error type which distinguishes between runtime and system exceptions
#[derive(Error, Debug, Clone, PartialEq)]
pub enum Exception {
#[error("system error")]
System(#[from] SystemException),
#[error("runtime error")]
Runtime(#[from] RuntimeException),
}
// Allows use with ?
impl From<core::convert::Infallible> for Exception {
fn from(_: core::convert::Infallible) -> Self {
unreachable!()
}
}
// System exception type conversions
impl From<Alloc> for Exception {
fn from(alloc: Alloc) -> Self {
Self::System(alloc.into())
}
}
impl From<TermDecodingError> for Exception {
fn from(err: TermDecodingError) -> Self {
Self::System(err.into())
}
}
impl From<TermEncodingError> for Exception {
fn from(err: TermEncodingError) -> Self {
Self::System(err.into())
}
}
// Runtime exception type conversions
impl From<anyhow::Error> for Exception {
fn from(err: anyhow::Error) -> Self {
InternalException::from(ArcError::new(err)).into()
}
}
impl From<InvalidEncodingNameError> for Exception {
fn from(err: InvalidEncodingNameError) -> Self {
InternalException::from(ArcError::from_err(err)).into()
}
}
impl From<InternalException> for Exception {
fn from(err: InternalException) -> Self {
match err {
InternalException::System(err) => Self::System(err),
InternalException::Internal(source) => Self::Runtime(badarg!(Trace::capture(), source)),
}
}
}
/// Used to represent errors which occur when expecting a
/// particular exception when converting from a more abstract type
#[derive(Error, Debug, Clone, Copy, PartialEq, Eq)]
#[error("unexpected exception occured; expected error of type {}, got {}", type_name::<T>(), type_name::<U>())]
pub struct UnexpectedExceptionError<T, U>(PhantomData<T>, PhantomData<U>)
where
T: std::error::Error,
U: std::error::Error;
impl<T, U> Default for UnexpectedExceptionError<T, U>
where
T: std::error::Error,
U: std::error::Error,
{
fn default() -> Self {
Self(PhantomData, PhantomData)
}
}
|
use std::marker::PhantomData;
use std::ops::Deref;
use super::body::Skeleton;
use super::error::{k4a_result, Error};
#[derive(Debug)]
pub struct Frame<'d> {
frame_handle: libk4a_sys::k4abt_frame_t,
_phantom: PhantomData<&'d ()>,
}
impl<'d> Frame<'d> {
/// # Safety
///
/// Ensure `frame_handle` is unique, and not a null or not dangling
pub unsafe fn from_handle(frame_handle: libk4a_sys::k4abt_frame_t) -> Self {
Self {
frame_handle,
_phantom: PhantomData,
}
}
pub fn get_num_bodies(&self) -> u32 {
unsafe { libk4a_sys::k4abt_frame_get_num_bodies(self.frame_handle) }
}
pub fn get_body_id(&self, index: u32) -> u32 {
unsafe { libk4a_sys::k4abt_frame_get_body_id(self.frame_handle, index) }
}
pub fn get_body_skeleton(&self, index: u32) -> Result<Skeleton, Error> {
let mut skelton = std::mem::MaybeUninit::<Skeleton>::uninit();
let result = unsafe {
libk4a_sys::k4abt_frame_get_body_skeleton(
self.frame_handle,
index,
skelton.as_mut_ptr(),
)
};
k4a_result(result)?;
Ok(unsafe { skelton.assume_init() })
}
}
impl<'d> Clone for Frame<'d> {
fn clone(&self) -> Self {
unsafe {
libk4a_sys::k4abt_frame_reference(self.frame_handle);
Self::from_handle(self.frame_handle)
}
}
}
impl<'d> Drop for Frame<'d> {
fn drop(&mut self) {
let frame_handle = self.frame_handle;
if frame_handle.is_null() {
return;
}
unsafe {
libk4a_sys::k4abt_frame_release(frame_handle);
}
self.frame_handle = std::ptr::null_mut();
}
}
impl<'d> Deref for Frame<'d> {
type Target = libk4a_sys::k4abt_frame_t;
fn deref(&self) -> &Self::Target {
&self.frame_handle
}
}
|
use logging::data_types::TypeInfo;
use logging::{ self, LogStream };
use variable::Variable;
use std::io;
use serde::Serialize;
use std::fmt::Display;
pub fn create_log_for<'a, T>(var: &mut Variable<'a, T>, name: &str) -> io::Result<()>
where T: PartialEq + TypeInfo + Serialize + Display + Copy + 'a {
let path = logging::get_timestamped_path()?;
let mut log_stream: LogStream<T> = LogStream::new(
&path.join(format!("{}.ebl", name)),
&format!("drive-core_{}", name))?;
// Log the variable's initial value
log_stream.log(*var.value())?;
var.add_listener(move |val| {
match log_stream.log(*val) {
Ok(()) => {},
Err(e) => println!("Failed to log value {}: {:?}", val, e)
}
});
Ok(())
} |
#[macro_use]
mod card;
mod actor;
use actor::{Actor, JawWorm};
use card::{CardTemplate, CardType, Effect, Target, CARDS};
use mcts::tree_policy::*;
use mcts::*;
use rand::rngs::SmallRng;
use rand::Rng;
use rand::{FromEntropy, SeedableRng, XorShiftRng};
use std::mem;
#[derive(Clone, PartialEq)]
pub struct Card {
id: usize,
cost: i32,
}
impl Card {
fn new(id: usize, cost: i32) -> Card {
Card { id, cost }
}
}
impl std::fmt::Debug for Card {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{}, Cost: {}", CARDS[self.id].name, self.cost)
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum Action {
Play(usize), // Play card in given slot
TargetPlay(usize, usize), // Play card in given slot directed at entity x
Discard(usize),
EndTurn,
}
#[derive(Clone, Debug)]
pub struct Battle {
pub hand: Vec<Card>,
pub draw: Vec<Card>,
pub discard: Vec<Card>,
pub exhaust: Vec<Card>,
pub enemy: JawWorm,
pub slayer: actor::Player,
pub queue: Vec<Action>,
}
impl Battle {
fn new(mut deck: Vec<Card>) -> Battle {
use rand::seq::index::sample;
let mut rng = SmallRng::from_entropy();
let mut hand = Vec::new();
let mut sample = sample(&mut rng, deck.len(), 5).into_vec();
sample.sort_unstable();
for index in sample.into_iter().rev() {
hand.push(deck.swap_remove(index));
}
let mut enemy = JawWorm {
health: 44,
block: 0,
strength: 0,
intent: 0,
weak: 0,
last_actions: Vec::new(),
queue: Vec::new(),
};
enemy.set_intent();
let slayer = actor::Player {
health: 100,
block: 0,
energy: 3,
};
Battle {
hand,
draw: deck,
discard: Vec::new(),
exhaust: Vec::new(),
enemy,
slayer,
queue: Vec::new(),
}
}
fn draw_cards(&mut self, mut number: usize) {
use rand::seq::index::sample;
if self.draw.len() > number {
let mut counter = 0;
let mut rng = SmallRng::from_entropy();
let mut sample = sample(&mut rng, self.draw.len(), number).into_vec();
sample.sort_unstable();
for index in sample.into_iter().rev() {
self.hand.push(self.draw.swap_remove(index - counter));
counter += 1;
}
} else {
number -= self.draw.len();
self.hand.append(&mut self.draw);
if self.discard.len() > 0 {
mem::swap(&mut self.discard, &mut self.draw);
return self.draw_cards(number);
}
}
}
fn end_discard(&mut self) {
self.discard.append(&mut self.hand);
}
pub fn apply_effect(&mut self, eff: &Effect, source_id: usize, target_id: usize) {
let scaled = match eff {
Effect::Attack(damage) => {
if source_id == 0 {
self.slayer.scale_attack(*damage)
} else {
self.enemy.scale_attack(*damage)
}
}
_ => 0,
};
let target: &mut Actor = {
if target_id == 0 {
&mut self.slayer
} else {
&mut self.enemy
}
};
match eff {
Effect::Attack(_) => target.take_damage(scaled),
Effect::Block(block) => target.add_block(*block),
Effect::Weak(weak) => target.add_weak(*weak),
Effect::Strength(strength) => target.add_strength(*strength),
Effect::Discard(discard) => self.queue.push(Action::Discard(*discard)),
Effect::Draw(card_count) => self.draw_cards(*card_count),
}
}
pub fn is_terminal(&self) -> bool {
if self.enemy.health <= 0 || self.slayer.health <= 0 {
true
} else {
false
}
}
}
impl GameState for Battle {
type Move = Action;
type Player = ();
type MoveList = Vec<Action>;
fn current_player(&self) -> <Self as GameState>::Player {
()
}
fn available_moves(&self) -> <Self as GameState>::MoveList {
if self.is_terminal() {
return vec![]; //Terminal condition
}
let mut actions = Vec::new();
if self.queue.is_empty() {
let mut actions = Vec::new();
let max_cost = self.slayer.energy;
for (index, _c) in self.hand.iter().filter(|c| c.cost <= max_cost).enumerate() {
actions.push(Action::Play(index));
}
actions.push(Action::EndTurn);
actions
} else {
let head = &self.queue[0];
match head {
Action::Discard(_) => {
for (index, _c) in self.hand.iter().enumerate() {
actions.push(Action::Discard(index));
}
}
_ => {
unimplemented!();
}
}
actions
}
}
fn make_move(&mut self, mov: &<Self as GameState>::Move) {
match mov {
Action::Play(card_slot) => {
let card = self.hand.swap_remove(*card_slot);
let template: &CardTemplate = &CARDS[card.id];
let source_id = 0;
for pair in template.effects.iter() {
let target_id = match pair.target {
Target::Player => source_id,
Target::Single => 1,
Target::Multi => unimplemented!(),
};
self.apply_effect(&pair.effect, source_id, target_id)
}
self.slayer.energy -= card.cost;
self.discard.push(card);
}
Action::EndTurn => {
let opp_actions = self.enemy.act();
for pair in opp_actions {
let source_id = 1; // Todo variable
let target_id = match pair.target {
Target::Player => source_id,
Target::Single => 0,
Target::Multi => unimplemented!(),
};
self.apply_effect(&pair.effect, source_id, target_id);
}
self.end_discard();
self.draw_cards(5);
self.slayer.energy = 3;
self.slayer.block = 0;
self.enemy.block = 0;
self.enemy.set_intent();
}
Action::Discard(slot) => {
let out = self.hand.swap_remove(*slot);
self.discard.push(out);
if let Some(Action::Discard(num)) = self.queue.first() {
let res = num - 1;
if res > 0 {
// Continue discarding
self.queue[0] = Action::Discard(res);
} else {
// Queue should always be small so overhead is okay
self.queue.remove(0);
}
} else {
panic!("Unknown path into discard action"); // Todo more graceful
}
}
_ => unimplemented!(),
}
}
}
struct GameEvaluator;
impl Evaluator<SpireMCTS> for GameEvaluator {
type StateEvaluation = i64;
fn evaluate_new_state(
&self,
state: &Battle,
moves: &Vec<Action>,
_: Option<SearchHandle<SpireMCTS>>,
) -> (Vec<()>, i64) {
(vec![(); moves.len()], state.slayer.health as i64)
}
fn evaluate_existing_state(
&self,
state: &<SpireMCTS as MCTS>::State,
existing_evaln: &Self::StateEvaluation,
handle: SearchHandle<SpireMCTS>,
) -> Self::StateEvaluation {
state.slayer.health as i64
}
fn interpret_evaluation_for_player(
&self,
evaluation: &Self::StateEvaluation,
player: &<<SpireMCTS as MCTS>::State as GameState>::Player,
) -> i64 {
*evaluation
}
}
#[derive(Default)]
struct SpireMCTS;
impl MCTS for SpireMCTS {
type State = Battle;
type Eval = GameEvaluator;
type TreePolicy = MyUCT;
type NodeData = ();
type ExtraThreadData = ();
}
pub struct MyUCT {
pub exploration_constant: f64,
}
impl MyUCT {
pub fn new(exploration_constant: f64) -> Self {
Self {
exploration_constant,
}
}
}
impl<Spec: MCTS<TreePolicy = Self>> TreePolicy<Spec> for MyUCT {
type ThreadLocalData = PolicyRng;
type MoveEvaluation = ();
fn choose_child<'a, MoveIter>(
&self,
moves: MoveIter,
mut handle: SearchHandle<Spec>,
) -> &'a MoveInfo<Spec>
where
MoveIter: Iterator<Item = &'a MoveInfo<Spec>> + Clone,
{
let total_visits = moves.clone().map(|x| x.visits()).sum::<u64>();
let adjusted_total = (total_visits + 1) as f64;
let ln_adjusted_total = adjusted_total.ln();
handle
.thread_local_data()
.policy_data
.select_by_key(moves, |mov| {
let sum_rewards = mov.sum_rewards();
let child_visits = mov.visits();
// http://mcts.ai/pubs/mcts-survey-master.pdf
if child_visits == 0 {
std::f64::INFINITY
} else {
let explore_term = 2.0 * (ln_adjusted_total / child_visits as f64).sqrt();
let mean_action_value = sum_rewards as f64 / child_visits as f64;
self.exploration_constant * explore_term + mean_action_value
}
})
.unwrap()
}
}
#[derive(Clone)]
pub struct PolicyRng {
rng: XorShiftRng,
}
impl PolicyRng {
pub fn new() -> Self {
let rng = SeedableRng::from_seed([1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]);
Self { rng }
}
pub fn select_by_key<T, Iter, KeyFn>(&mut self, elts: Iter, mut key_fn: KeyFn) -> Option<T>
where
Iter: Iterator<Item = T>,
KeyFn: FnMut(&T) -> f64,
{
let mut choice = None;
let mut num_optimal: u32 = 0;
let mut best_so_far: f64 = std::f64::NEG_INFINITY;
for elt in elts {
let score = key_fn(&elt);
if score > best_so_far {
choice = Some(elt);
num_optimal = 1;
best_so_far = score;
} else if score == best_so_far {
num_optimal += 1;
if self.rng.gen_bool(1.0 / num_optimal as f64) {
choice = Some(elt);
}
}
}
choice
}
}
impl Default for PolicyRng {
fn default() -> Self {
Self::new()
}
}
fn simulate_battle(mut battle: Battle) {
while !battle.is_terminal() {
let mut mcts = MCTSManager::new(battle.clone(), SpireMCTS, GameEvaluator, MyUCT::new(50.0));
mcts.playout_n_parallel(10000, 4);
let best_move = mcts.best_move().expect("Error computing best move");
dbg!(&best_move);
battle.make_move(&best_move);
}
println!(
"Slayer: {}, JawWorm: {}",
battle.slayer.health, battle.enemy.health
);
}
fn main() {
let battle = Battle::new(vec![
Card::new(1, 1),
Card::new(1, 1),
Card::new(0, 1),
Card::new(0, 1),
Card::new(0, 1),
]);
simulate_battle(battle);
println!("Battle concluded!");
}
|
pub mod block_source;
pub mod broadcaster;
pub mod fee_estimator;
|
// digit_index * 2 > input_length so the only Patterns for digit_index are 0 for input[0..digit_index] and 1 for input[digit_index..input_length]
// So the sum for digit_index is the sum of input[digit_index..input_length]
// The sum for digit_index+1 is just the (sum for digit_index) - input[digit_index] (starting from the end probably makes more sense than what I did)
fn process_signal(cur_phase: &Vec<i64>) -> Vec<i64> {
let mut new_phase: Vec<i64> = vec![0; cur_phase.len()];
let mut result: i64 = 0;
for i in 0..cur_phase.len() {
if i == 0 {
result = cur_phase[i..cur_phase.len()].iter().sum();
} else {
result = result - cur_phase[i-1];
}
new_phase[i] = (result % 10).abs();
}
new_phase
}
fn print_phase(phase: &Vec<i64>) {
let mut res_str = String::new();
for i in &phase[0..8] {
res_str += &i.to_string();
}
println!("Current phase: {}", res_str);
}
pub fn run_puzzle() {
let input = "59776034095811644545367793179989602140948714406234694972894485066523525742503986771912019032922788494900655855458086979764617375580802558963587025784918882219610831940992399201782385674223284411499237619800193879768668210162176394607502218602633153772062973149533650562554942574593878073238232563649673858167635378695190356159796342204759393156294658366279922734213385144895116649768185966866202413314939692174223210484933678866478944104978890019728562001417746656699281992028356004888860103805472866615243544781377748654471750560830099048747570925902575765054898899512303917159138097375338444610809891667094051108359134017128028174230720398965960712";
let start_digit = 5977603;
let input_length = input.len();
let mut phase: Vec<i64> = Vec::new();
for i in start_digit..input_length*10000 {
phase.push(input.chars().nth((i % input_length) as usize).unwrap().to_digit(10).unwrap() as i64);
}
for _ in 0..100 {
phase = process_signal(&phase);
}
print_phase(&phase);
}
|
//! Make a block out of parsed RLE code.
use std::ops::Range;
use crate::{Block, Hashlife};
use crate::leaf::{Leaf, LEAF_SIZE, LEAF_Y_SHIFT, LEAF_X_SHIFT};
use crate::util::make_2x2;
use super::parse::{RLE, RLEEncode, RLEToken, State};
fn expand_rle<A:Clone>(rle: &RLEEncode<A>) -> Vec<A> {
use std::iter;
rle.iter().flat_map(|&(n, ref t)| iter::repeat(t.clone()).take(n)).collect()
}
// matrix[y][x]
fn tokens_to_matrix(tokens: &[RLEToken]) -> Result<Vec<Vec<State>>, ()> {
let mut matrix = Vec::new();
let mut cur_line = Vec::new();
for token in tokens {
match *token {
RLEToken::State(state) => {
cur_line.push(state);
}
RLEToken::EndLine => {
matrix.push(cur_line);
cur_line = Vec::new();
}
RLEToken::EndBlock => {
matrix.push(cur_line);
return Ok(matrix);
}
}
}
Err(())
}
pub fn block_from_rle<'a>(hl: &Hashlife<'a>, rle: &RLE) -> Result<Block<'a>,
()> {
use std::cmp::max;
let mut matrix = tokens_to_matrix(&expand_rle(rle))?;
let max_row_len = matrix.iter().map(|row| row.len()).max().unwrap_or(0);
let max_side = max(max_row_len, matrix.len());
let res_side: usize = max(max_side, LEAF_SIZE).next_power_of_two();
let res_depth = (res_side / LEAF_SIZE).trailing_zeros();
for row in &mut matrix {
row.resize(res_side, State::Dead);
}
let empty_row = vec![State::Dead; res_side];
matrix.resize(res_side, empty_row);
let matrix = matrix.iter().map(|row| &**row).collect();
Ok(block_from_matrix(hl, res_depth, matrix))
}
pub fn block_from_matrix<'a>(hl: &Hashlife<'a>, depth: u32, matrix:
Vec<&[State]>) -> Block<'a> {
assert_eq!(matrix.len(), LEAF_SIZE << depth);
for row in &matrix {assert_eq!(row.len(), LEAF_SIZE << depth);}
if depth == 0 {
hl.leaf(states_to_leaf(&matrix))
} else {
// Side-length of subblock.
let slen = LEAF_SIZE << (depth - 1);
let subblocks = make_2x2(|i, j| {
let submatrix = submatrix(&matrix,
i*slen..(i+1)*slen,
j*slen..(j+1)*slen);
block_from_matrix(hl, depth-1, submatrix)
});
hl.node_block(subblocks)
}
}
fn submatrix<'a, T>(matrix: &[&'a [T]], outer: Range<usize>, inner:
Range<usize>) -> Vec<&'a [T]> {
matrix[outer].iter().map(|row| &row[inner.clone()]).collect()
}
fn states_to_leaf(states: &[&[State]]) -> Leaf {
fn state_to_bit(state: State) -> u8 {
match state {
State::Dead => 0,
State::Alive => 1,
}
}
assert!(states.len() == LEAF_SIZE && states.iter().all(|row| row.len() ==
LEAF_SIZE));
/*
state_to_bit(states[0][0])
| state_to_bit(states[0][1]) << 1
| state_to_bit(states[1][0]) << 4
| state_to_bit(states[1][1]) << 5
*/
let mut res: Leaf = 0;
for y in 0..LEAF_SIZE {
for x in 0..LEAF_SIZE {
res |= (state_to_bit(states[y][x]) as Leaf) << (y * LEAF_Y_SHIFT
+ x * LEAF_X_SHIFT);
}
}
res
}
#[test]
fn test_expand_rle() {
// Test with the look-and-say sequence
assert_eq!(expand_rle(&[(1, 1)]), [1]);
assert_eq!(expand_rle(&[(2, 1)]), [1, 1]);
assert_eq!(expand_rle(&[(1, 2), (1, 1)]), [2, 1]);
assert_eq!(expand_rle(&[(1, 1), (1, 2), (2, 1)]), [1, 2, 1, 1]);
assert_eq!(expand_rle(&[(3, 1), (2, 2), (1, 1)]), [1, 1, 1, 2, 2, 1]);
}
#[cfg(test)]
mod test {
//use super::block_from_rle;
/*
#[test]
#[cfg(not(feature = "4x4_leaf"))]
fn test_build_examples() {
use format::parse::RLEToken::*;
use format::parse::State::*;
use block::Block;
use ::Hashlife;
//let tokens0 = vec![Run(1, Dead), Run(1, Alive), EndLine, Run(1, Alive),
// EndBlock];
let tokens0 = [(1, State(Dead)), (1, State(Alive)), (1, EndLine),
(1, State(Alive)), (1, EndBlock)];
//let tokens1 = vec![Run(3, Alive), EndLine, EndLine, Run(1, Alive),
// EndBlock];
let tokens1 = [(3, State(Alive)), (1, EndLine), (1, EndLine), (1,
State(Alive)), (1, EndBlock)];
let tokens2 = [(1, EndBlock)];
// From failed format::write test
let tokens3 = [(1, State(Dead)), (1, State(Dead)), (1, EndLine),
(1, State(Dead)), (1, State(Dead)), (1, EndBlock)];
Hashlife::with_new(|hl| {
assert_eq!(block_from_rle(&hl, &tokens0).to_raw(),
Ok(Block::Leaf(0x12)));
let node = hl.raw_node([[Block::Leaf(0x03), Block::Leaf(0x01)],
[Block::Leaf(0x01), Block::Leaf(0x00)]]);
assert_eq!(block_from_rle(&hl, &tokens1).to_raw(),
Ok(Block::Node(node)));
assert_eq!(block_from_rle(&hl, &tokens2).to_raw(),
Ok(Block::Leaf(0x00)));
assert_eq!(block_from_rle(&hl, &[(1, EndLine), (1, EndBlock)])
.to_raw(), Ok(Block::Leaf(0x00)));
assert_eq!(block_from_rle(&hl, &tokens3).to_raw(),
Ok(Block::Leaf(0x00)));
});
}
*/
}
|
use crate::ast;
use crate::{Parse, Spanned, ToTokens};
/// A `yield [expr]` expression to return a value from a generator.
///
/// # Examples
///
/// ```rust
/// use rune::{testing, ast};
///
/// testing::roundtrip::<ast::ExprYield>("yield");
/// testing::roundtrip::<ast::ExprYield>("yield 42");
/// testing::roundtrip::<ast::ExprYield>("#[attr] yield 42");
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Parse, ToTokens, Spanned)]
#[rune(parse = "meta_only")]
pub struct ExprYield {
/// The attributes of the `yield`
#[rune(iter, meta)]
pub attributes: Vec<ast::Attribute>,
/// The return token.
pub yield_token: T![yield],
/// An optional expression to yield.
#[rune(iter)]
pub expr: Option<ast::Expr>,
}
expr_parse!(Yield, ExprYield, "yield expression");
|
//! System Configuration service.
//!
//! This module contains basic methods to retrieve the console's system configuration.
#![doc(alias = "configuration")]
use crate::error::ResultCode;
/// Console region.
#[doc(alias = "CFG_Region")]
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
#[repr(u32)]
pub enum Region {
/// Japan.
Japan = ctru_sys::CFG_REGION_JPN,
/// USA.
USA = ctru_sys::CFG_REGION_USA,
/// Europe.
Europe = ctru_sys::CFG_REGION_EUR,
/// Australia.
Australia = ctru_sys::CFG_REGION_AUS,
/// China.
China = ctru_sys::CFG_REGION_CHN,
/// Korea.
Korea = ctru_sys::CFG_REGION_KOR,
/// Taiwan.
Taiwan = ctru_sys::CFG_REGION_TWN,
}
/// Language set for the console's OS.
#[doc(alias = "CFG_Language")]
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
#[repr(u32)]
pub enum Language {
/// Japanese.
Japanese = ctru_sys::CFG_LANGUAGE_JP,
/// English.
English = ctru_sys::CFG_LANGUAGE_EN,
/// French.
French = ctru_sys::CFG_LANGUAGE_FR,
/// German.
German = ctru_sys::CFG_LANGUAGE_DE,
/// Italian.
Italian = ctru_sys::CFG_LANGUAGE_IT,
/// Spanish.
Spanish = ctru_sys::CFG_LANGUAGE_ES,
/// Korean.
Korean = ctru_sys::CFG_LANGUAGE_KO,
/// Dutch.
Dutch = ctru_sys::CFG_LANGUAGE_NL,
/// Portuguese.
Portuguese = ctru_sys::CFG_LANGUAGE_PT,
/// Russian.
Russian = ctru_sys::CFG_LANGUAGE_RU,
/// Simplified Chinese.
SimplifiedChinese = ctru_sys::CFG_LANGUAGE_ZH,
/// Traditional Chinese.
TraditionalChinese = ctru_sys::CFG_LANGUAGE_TW,
}
/// Specific model of the console.
#[doc(alias = "CFG_SystemModel")]
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
#[repr(u32)]
pub enum SystemModel {
/// Old Nintendo 3DS.
Old3DS = ctru_sys::CFG_MODEL_3DS,
/// Old Nintendo 3DS XL.
Old3DSXL = ctru_sys::CFG_MODEL_3DSXL,
/// New Nintendo 3DS.
New3DS = ctru_sys::CFG_MODEL_N3DS,
/// Old Nintendo 2DS.
Old2DS = ctru_sys::CFG_MODEL_2DS,
/// New Nintendo 3DS XL.
New3DSXL = ctru_sys::CFG_MODEL_N3DSXL,
/// New Nintendo 2DS XL.
New2DSXL = ctru_sys::CFG_MODEL_N2DSXL,
}
/// Handle to the System Configuration service.
pub struct Cfgu(());
impl Cfgu {
/// Initialize a new service handle.
///
/// # Example
///
/// ```no_run
/// # use std::error::Error;
/// # fn main() -> Result<(), Box<dyn Error>> {
/// #
/// use ctru::services::cfgu::Cfgu;
///
/// let cfgu = Cfgu::new()?;
/// #
/// # Ok(())
/// # }
/// ```
#[doc(alias = "cfguInit")]
pub fn new() -> crate::Result<Cfgu> {
ResultCode(unsafe { ctru_sys::cfguInit() })?;
Ok(Cfgu(()))
}
/// Returns the console's region from the system's secure info.
///
/// # Example
///
/// ```no_run
/// # use std::error::Error;
/// # fn main() -> Result<(), Box<dyn Error>> {
/// #
/// use ctru::services::cfgu::Cfgu;
/// let cfgu = Cfgu::new()?;
///
/// let region = cfgu.region()?;
/// #
/// # Ok(())
/// # }
/// ```
#[doc(alias = "CFGU_SecureInfoGetRegion")]
pub fn region(&self) -> crate::Result<Region> {
let mut region: u8 = 0;
ResultCode(unsafe { ctru_sys::CFGU_SecureInfoGetRegion(&mut region) })?;
Ok(Region::try_from(region).unwrap())
}
/// Returns the console's model.
///
/// # Example
///
/// ```no_run
/// # use std::error::Error;
/// # fn main() -> Result<(), Box<dyn Error>> {
/// #
/// use ctru::services::cfgu::Cfgu;
/// let cfgu = Cfgu::new()?;
///
/// let model = cfgu.model()?;
/// #
/// # Ok(())
/// # }
/// ```
#[doc(alias = "CFGU_GetSystemModel")]
pub fn model(&self) -> crate::Result<SystemModel> {
let mut model: u8 = 0;
ResultCode(unsafe { ctru_sys::CFGU_GetSystemModel(&mut model) })?;
Ok(SystemModel::try_from(model).unwrap())
}
/// Returns the system language set for the console.
///
/// # Example
///
/// ```no_run
/// # use std::error::Error;
/// # fn main() -> Result<(), Box<dyn Error>> {
/// #
/// use ctru::services::cfgu::Cfgu;
/// let cfgu = Cfgu::new()?;
///
/// let language = cfgu.language()?;
/// #
/// # Ok(())
/// # }
/// ```
#[doc(alias = "CFGU_GetSystemLanguage")]
pub fn language(&self) -> crate::Result<Language> {
let mut language: u8 = 0;
ResultCode(unsafe { ctru_sys::CFGU_GetSystemLanguage(&mut language) })?;
Ok(Language::try_from(language).unwrap())
}
/// Check if NFC is supported by the console.
///
/// # Example
///
/// ```no_run
/// # use std::error::Error;
/// # fn main() -> Result<(), Box<dyn Error>> {
/// #
/// use ctru::services::cfgu::Cfgu;
/// let cfgu = Cfgu::new()?;
///
/// if cfgu.is_nfc_supported()? {
/// println!("NFC is available!");
/// }
/// #
/// # Ok(())
/// # }
/// ```
#[doc(alias = "CFGU_IsNFCSupported")]
pub fn is_nfc_supported(&self) -> crate::Result<bool> {
let mut supported: bool = false;
ResultCode(unsafe { ctru_sys::CFGU_IsNFCSupported(&mut supported) })?;
Ok(supported)
}
/// Check if the console is from the 2DS family ([`Old2DS`](SystemModel::Old2DS), [`New2DSXL`](SystemModel::New2DSXL)).
///
/// Useful to avoid stereoscopic 3D rendering when working with 2DS consoles.
///
/// # Example
///
/// ```no_run
/// # use std::error::Error;
/// # fn main() -> Result<(), Box<dyn Error>> {
/// #
/// use ctru::services::cfgu::Cfgu;
/// let cfgu = Cfgu::new()?;
///
/// if cfgu.is_2ds_family()? {
/// println!("Stereoscopic 3D is not supported.");
/// }
/// #
/// # Ok(())
/// # }
/// ```
#[doc(alias = "CFGU_GetModelNintendo2DS")]
pub fn is_2ds_family(&self) -> crate::Result<bool> {
let mut is_2ds_family: u8 = 0;
ResultCode(unsafe { ctru_sys::CFGU_GetModelNintendo2DS(&mut is_2ds_family) })?;
Ok(is_2ds_family == 0)
}
}
impl Drop for Cfgu {
#[doc(alias = "cfguExit")]
fn drop(&mut self) {
unsafe {
ctru_sys::cfguExit();
}
}
}
from_impl!(Region, u8);
from_impl!(Language, u8);
from_impl!(SystemModel, u8);
impl TryFrom<u8> for Region {
type Error = ();
fn try_from(value: u8) -> Result<Self, Self::Error> {
match value as u32 {
ctru_sys::CFG_REGION_JPN => Ok(Region::Japan),
ctru_sys::CFG_REGION_USA => Ok(Region::USA),
ctru_sys::CFG_REGION_EUR => Ok(Region::Europe),
ctru_sys::CFG_REGION_AUS => Ok(Region::Australia),
ctru_sys::CFG_REGION_CHN => Ok(Region::China),
ctru_sys::CFG_REGION_KOR => Ok(Region::Korea),
ctru_sys::CFG_REGION_TWN => Ok(Region::Taiwan),
_ => Err(()),
}
}
}
impl TryFrom<u8> for Language {
type Error = ();
fn try_from(value: u8) -> Result<Self, Self::Error> {
match value as u32 {
ctru_sys::CFG_LANGUAGE_JP => Ok(Language::Japanese),
ctru_sys::CFG_LANGUAGE_EN => Ok(Language::English),
ctru_sys::CFG_LANGUAGE_FR => Ok(Language::French),
ctru_sys::CFG_LANGUAGE_DE => Ok(Language::German),
ctru_sys::CFG_LANGUAGE_IT => Ok(Language::Italian),
ctru_sys::CFG_LANGUAGE_ES => Ok(Language::Spanish),
ctru_sys::CFG_LANGUAGE_ZH => Ok(Language::SimplifiedChinese),
ctru_sys::CFG_LANGUAGE_KO => Ok(Language::Korean),
ctru_sys::CFG_LANGUAGE_NL => Ok(Language::Dutch),
ctru_sys::CFG_LANGUAGE_PT => Ok(Language::Portuguese),
ctru_sys::CFG_LANGUAGE_RU => Ok(Language::Russian),
ctru_sys::CFG_LANGUAGE_TW => Ok(Language::TraditionalChinese),
_ => Err(()),
}
}
}
impl TryFrom<u8> for SystemModel {
type Error = ();
fn try_from(value: u8) -> Result<Self, Self::Error> {
match value as u32 {
ctru_sys::CFG_MODEL_3DS => Ok(SystemModel::Old3DS),
ctru_sys::CFG_MODEL_3DSXL => Ok(SystemModel::Old3DSXL),
ctru_sys::CFG_MODEL_N3DS => Ok(SystemModel::New3DS),
ctru_sys::CFG_MODEL_2DS => Ok(SystemModel::Old2DS),
ctru_sys::CFG_MODEL_N3DSXL => Ok(SystemModel::New3DSXL),
ctru_sys::CFG_MODEL_N2DSXL => Ok(SystemModel::New2DSXL),
_ => Err(()),
}
}
}
|
// Copyright 2021 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::sync::Arc;
use std::sync::Mutex;
use async_trait::async_trait;
use common_base::base::tokio;
use common_meta_api::SchemaApiTestSuite;
use common_meta_api::ShareApiTestSuite;
use common_meta_kvapi::kvapi;
use common_meta_raft_store::state_machine::StateMachine;
use crate::testing::new_raft_test_context;
use crate::testing::RaftTestContext;
#[derive(Clone)]
struct StateMachineBuilder {
test_context: Arc<Mutex<Option<RaftTestContext>>>,
}
#[async_trait]
impl kvapi::ApiBuilder<StateMachine> for StateMachineBuilder {
async fn build(&self) -> StateMachine {
let tc = new_raft_test_context();
let sm = StateMachine::open(&tc.raft_config, 1).await.unwrap();
{
let mut x = self.test_context.lock().unwrap();
*x = Some(tc);
}
sm
}
async fn build_cluster(&self) -> Vec<StateMachine> {
unimplemented!("StateMachine does not support cluster mode")
}
}
#[async_entry::test(
worker_threads = 3,
init = "init_raft_store_ut!()",
tracing_span = "debug"
)]
async fn test_meta_embedded_single() -> anyhow::Result<()> {
let builder = StateMachineBuilder {
test_context: Default::default(),
};
SchemaApiTestSuite::test_single_node(builder.clone()).await?;
ShareApiTestSuite::test_single_node_share(builder).await
}
|
// TODO: module docs
pub extern crate rendy_command as command;
pub extern crate rendy_memory as memory;
pub extern crate rendy_resource as resource;
extern crate winit;
#[macro_use]
extern crate derivative;
#[cfg(feature = "hal")]
pub extern crate gfx_hal as hal;
#[cfg(feature = "ash")]
pub extern crate ash;
mod impls;
mod config;
mod device;
mod factory;
mod init;
mod queue;
mod render;
pub use config::{Config, MemoryConfig, RenderBuilder, RenderConfig};
pub use device::Device;
pub use factory::Factory;
pub use init::init;
pub use queue::QueuesPicker;
|
use crate::*;
use ark_crypto_primitives::{Error, CRH as CRHTrait};
use ark_ff::{BigInteger, PrimeField};
use arkworks_gadgets::poseidon::{circom::CircomCRH, sbox::PoseidonSbox, PoseidonParameters, Rounds, CRH};
use sp_std::{marker::PhantomData, vec::Vec};
#[derive(Default, Clone, Copy)]
pub struct PoseidonRounds3x5;
#[derive(Default, Clone, Copy)]
pub struct PoseidonRounds5x5;
impl Rounds for PoseidonRounds3x5 {
const FULL_ROUNDS: usize = 8;
const PARTIAL_ROUNDS: usize = 57;
const SBOX: PoseidonSbox = PoseidonSbox::Exponentiation(5);
const WIDTH: usize = 3;
}
impl Rounds for PoseidonRounds5x5 {
const FULL_ROUNDS: usize = 8;
const PARTIAL_ROUNDS: usize = 60;
const SBOX: PoseidonSbox = PoseidonSbox::Exponentiation(5);
const WIDTH: usize = 5;
}
pub struct ArkworksPoseidonHasher<F: PrimeField, P: Rounds>(PhantomData<F>, PhantomData<P>);
impl<F: PrimeField, P: Rounds> InstanceHasher for ArkworksPoseidonHasher<F, P> {
fn hash(input: &[u8], param_bytes: &[u8]) -> Result<Vec<u8>, Error> {
let params = PoseidonParameters::<F>::from_bytes(param_bytes)?;
let output: F = <CRH<F, P> as CRHTrait>::evaluate(¶ms, input)?;
let value = output.into_repr().to_bytes_le();
Ok(value)
}
}
pub struct CircomPoseidonHasher<F: PrimeField, P: Rounds>(PhantomData<F>, PhantomData<P>);
impl<F: PrimeField, P: Rounds> InstanceHasher for CircomPoseidonHasher<F, P> {
fn hash(input: &[u8], param_bytes: &[u8]) -> Result<Vec<u8>, Error> {
let params = PoseidonParameters::<F>::from_bytes(param_bytes)?;
let output: F = <CircomCRH<F, P> as CRHTrait>::evaluate(¶ms, input)?;
let value = output.into_repr().to_bytes_le();
Ok(value)
}
}
use ark_bls12_381::Fr as Bls381;
pub type BLS381Poseidon3x5Hasher = ArkworksPoseidonHasher<Bls381, PoseidonRounds3x5>;
pub type BLS381Poseidon5x5Hasher = ArkworksPoseidonHasher<Bls381, PoseidonRounds5x5>;
pub type BLS381CircomPoseidon3x5Hasher = CircomPoseidonHasher<Bls381, PoseidonRounds3x5>;
pub type BLS381CircomPoseidon5x5Hasher = CircomPoseidonHasher<Bls381, PoseidonRounds5x5>;
use ark_bn254::Fr as Bn254;
pub type BN254Poseidon3x5Hasher = ArkworksPoseidonHasher<Bn254, PoseidonRounds3x5>;
pub type BN254Poseidon5x5Hasher = ArkworksPoseidonHasher<Bn254, PoseidonRounds5x5>;
pub type BN254CircomPoseidon3x5Hasher = CircomPoseidonHasher<Bn254, PoseidonRounds3x5>;
pub type BN254CircomPoseidon5x5Hasher = CircomPoseidonHasher<Bn254, PoseidonRounds5x5>;
|
use crate::lttp::{
AppState,
GameState,
};
use anyhow::{
anyhow,
Context,
Result,
};
use std::{
convert::TryFrom,
sync::Arc,
};
use tracing::{
debug,
info,
};
#[tracing::instrument(skip(app_state), err)]
pub async fn poll_status(app_state: Arc<AppState>, device: &str) -> Result<()> {
if device.is_empty() {
return Ok(());
}
let mut client = qusb2snes_client::Client::new().await?;
debug!("Attaching to {}", device);
client.attach(device).await?;
let region_start = qusb2snes_client::offsets::WRAM + 0x0000_F340;
let region_length = 0x0200;
let snes_state = client.get_address(region_start, region_length).await?;
let prev_game_state = match app_state.game_state.read() {
Ok(pgs) => pgs.clone(),
Err(e) => return Err(anyhow!("Unable to get current game state: {}", e)),
};
let new_game_state =
GameState::try_from(snes_state).context("Unable to parse game state from WRAM")?;
let should_broadcast_update = new_game_state != prev_game_state;
match app_state.game_state.write() {
Ok(mut gs) => *gs = new_game_state,
Err(e) => return Err(anyhow!("Unable to lock game state for update: {}", e)),
}
if should_broadcast_update {
info!("Updating location & dungeon availabilities");
app_state.update_availabilities()?;
};
Ok(())
}
|
use super::*;
pub async fn do_write(fd: FileDesc, buf: &[u8]) -> Result<usize> {
debug!("write: fd: {}", fd);
let file_ref = current!().file(fd)?;
file_ref.write(buf).await
}
pub async fn do_writev(fd: FileDesc, bufs: &[&[u8]]) -> Result<usize> {
debug!("writev: fd: {}", fd);
let file_ref = current!().file(fd)?;
file_ref.writev(bufs).await
}
pub async fn do_pwrite(fd: FileDesc, buf: &[u8], offset: off_t) -> Result<usize> {
debug!("pwrite: fd: {}, offset: {}", fd, offset);
if offset < 0 {
return_errno!(EINVAL, "the offset is negative");
}
let file_ref = current!().file(fd)?;
if let Some(inode_file) = file_ref.as_inode_file() {
inode_file.write_at(offset as usize, buf)
} else {
// For non-inode files, we simply ignore the offset
file_ref.write(buf).await
}
}
|
#[doc = "Reader of register APB_FZ1"]
pub type R = crate::R<u32, super::APB_FZ1>;
#[doc = "Writer for register APB_FZ1"]
pub type W = crate::W<u32, super::APB_FZ1>;
#[doc = "Register APB_FZ1 `reset()`'s with value 0"]
impl crate::ResetValue for super::APB_FZ1 {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `DBG_TIMER2_STOP`"]
pub type DBG_TIMER2_STOP_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `DBG_TIMER2_STOP`"]
pub struct DBG_TIMER2_STOP_W<'a> {
w: &'a mut W,
}
impl<'a> DBG_TIMER2_STOP_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01);
self.w
}
}
#[doc = "Reader of field `DBG_TIM3_STOP`"]
pub type DBG_TIM3_STOP_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `DBG_TIM3_STOP`"]
pub struct DBG_TIM3_STOP_W<'a> {
w: &'a mut W,
}
impl<'a> DBG_TIM3_STOP_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1);
self.w
}
}
#[doc = "Reader of field `DBG_TIMER6_STOP`"]
pub type DBG_TIMER6_STOP_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `DBG_TIMER6_STOP`"]
pub struct DBG_TIMER6_STOP_W<'a> {
w: &'a mut W,
}
impl<'a> DBG_TIMER6_STOP_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 4)) | (((value as u32) & 0x01) << 4);
self.w
}
}
#[doc = "Reader of field `DBG_TIM7_STOP`"]
pub type DBG_TIM7_STOP_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `DBG_TIM7_STOP`"]
pub struct DBG_TIM7_STOP_W<'a> {
w: &'a mut W,
}
impl<'a> DBG_TIM7_STOP_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 5)) | (((value as u32) & 0x01) << 5);
self.w
}
}
#[doc = "Reader of field `DBG_RTC_STOP`"]
pub type DBG_RTC_STOP_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `DBG_RTC_STOP`"]
pub struct DBG_RTC_STOP_W<'a> {
w: &'a mut W,
}
impl<'a> DBG_RTC_STOP_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 10)) | (((value as u32) & 0x01) << 10);
self.w
}
}
#[doc = "Reader of field `DBG_WWDG_STOP`"]
pub type DBG_WWDG_STOP_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `DBG_WWDG_STOP`"]
pub struct DBG_WWDG_STOP_W<'a> {
w: &'a mut W,
}
impl<'a> DBG_WWDG_STOP_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 11)) | (((value as u32) & 0x01) << 11);
self.w
}
}
#[doc = "Reader of field `DBG_IWDG_STOP`"]
pub type DBG_IWDG_STOP_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `DBG_IWDG_STOP`"]
pub struct DBG_IWDG_STOP_W<'a> {
w: &'a mut W,
}
impl<'a> DBG_IWDG_STOP_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 12)) | (((value as u32) & 0x01) << 12);
self.w
}
}
#[doc = "Reader of field `DBG_I2C1_STOP`"]
pub type DBG_I2C1_STOP_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `DBG_I2C1_STOP`"]
pub struct DBG_I2C1_STOP_W<'a> {
w: &'a mut W,
}
impl<'a> DBG_I2C1_STOP_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 21)) | (((value as u32) & 0x01) << 21);
self.w
}
}
#[doc = "Reader of field `DBG_LPTIM2_STOP`"]
pub type DBG_LPTIM2_STOP_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `DBG_LPTIM2_STOP`"]
pub struct DBG_LPTIM2_STOP_W<'a> {
w: &'a mut W,
}
impl<'a> DBG_LPTIM2_STOP_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 30)) | (((value as u32) & 0x01) << 30);
self.w
}
}
#[doc = "Reader of field `DBG_LPTIM1_STOP`"]
pub type DBG_LPTIM1_STOP_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `DBG_LPTIM1_STOP`"]
pub struct DBG_LPTIM1_STOP_W<'a> {
w: &'a mut W,
}
impl<'a> DBG_LPTIM1_STOP_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 31)) | (((value as u32) & 0x01) << 31);
self.w
}
}
impl R {
#[doc = "Bit 0 - Debug Timer 2 stopped when Core is halted"]
#[inline(always)]
pub fn dbg_timer2_stop(&self) -> DBG_TIMER2_STOP_R {
DBG_TIMER2_STOP_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - TIM3 counter stopped when core is halted"]
#[inline(always)]
pub fn dbg_tim3_stop(&self) -> DBG_TIM3_STOP_R {
DBG_TIM3_STOP_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 4 - Debug Timer 6 stopped when Core is halted"]
#[inline(always)]
pub fn dbg_timer6_stop(&self) -> DBG_TIMER6_STOP_R {
DBG_TIMER6_STOP_R::new(((self.bits >> 4) & 0x01) != 0)
}
#[doc = "Bit 5 - TIM7 counter stopped when core is halted"]
#[inline(always)]
pub fn dbg_tim7_stop(&self) -> DBG_TIM7_STOP_R {
DBG_TIM7_STOP_R::new(((self.bits >> 5) & 0x01) != 0)
}
#[doc = "Bit 10 - Debug RTC stopped when Core is halted"]
#[inline(always)]
pub fn dbg_rtc_stop(&self) -> DBG_RTC_STOP_R {
DBG_RTC_STOP_R::new(((self.bits >> 10) & 0x01) != 0)
}
#[doc = "Bit 11 - Debug Window Wachdog stopped when Core is halted"]
#[inline(always)]
pub fn dbg_wwdg_stop(&self) -> DBG_WWDG_STOP_R {
DBG_WWDG_STOP_R::new(((self.bits >> 11) & 0x01) != 0)
}
#[doc = "Bit 12 - Debug Independent Wachdog stopped when Core is halted"]
#[inline(always)]
pub fn dbg_iwdg_stop(&self) -> DBG_IWDG_STOP_R {
DBG_IWDG_STOP_R::new(((self.bits >> 12) & 0x01) != 0)
}
#[doc = "Bit 21 - I2C1 SMBUS timeout mode stopped when core is halted"]
#[inline(always)]
pub fn dbg_i2c1_stop(&self) -> DBG_I2C1_STOP_R {
DBG_I2C1_STOP_R::new(((self.bits >> 21) & 0x01) != 0)
}
#[doc = "Bit 30 - Clocking of LPTIMER2 counter when the core is halted"]
#[inline(always)]
pub fn dbg_lptim2_stop(&self) -> DBG_LPTIM2_STOP_R {
DBG_LPTIM2_STOP_R::new(((self.bits >> 30) & 0x01) != 0)
}
#[doc = "Bit 31 - Clocking of LPTIMER1 counter when the core is halted"]
#[inline(always)]
pub fn dbg_lptim1_stop(&self) -> DBG_LPTIM1_STOP_R {
DBG_LPTIM1_STOP_R::new(((self.bits >> 31) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 0 - Debug Timer 2 stopped when Core is halted"]
#[inline(always)]
pub fn dbg_timer2_stop(&mut self) -> DBG_TIMER2_STOP_W {
DBG_TIMER2_STOP_W { w: self }
}
#[doc = "Bit 1 - TIM3 counter stopped when core is halted"]
#[inline(always)]
pub fn dbg_tim3_stop(&mut self) -> DBG_TIM3_STOP_W {
DBG_TIM3_STOP_W { w: self }
}
#[doc = "Bit 4 - Debug Timer 6 stopped when Core is halted"]
#[inline(always)]
pub fn dbg_timer6_stop(&mut self) -> DBG_TIMER6_STOP_W {
DBG_TIMER6_STOP_W { w: self }
}
#[doc = "Bit 5 - TIM7 counter stopped when core is halted"]
#[inline(always)]
pub fn dbg_tim7_stop(&mut self) -> DBG_TIM7_STOP_W {
DBG_TIM7_STOP_W { w: self }
}
#[doc = "Bit 10 - Debug RTC stopped when Core is halted"]
#[inline(always)]
pub fn dbg_rtc_stop(&mut self) -> DBG_RTC_STOP_W {
DBG_RTC_STOP_W { w: self }
}
#[doc = "Bit 11 - Debug Window Wachdog stopped when Core is halted"]
#[inline(always)]
pub fn dbg_wwdg_stop(&mut self) -> DBG_WWDG_STOP_W {
DBG_WWDG_STOP_W { w: self }
}
#[doc = "Bit 12 - Debug Independent Wachdog stopped when Core is halted"]
#[inline(always)]
pub fn dbg_iwdg_stop(&mut self) -> DBG_IWDG_STOP_W {
DBG_IWDG_STOP_W { w: self }
}
#[doc = "Bit 21 - I2C1 SMBUS timeout mode stopped when core is halted"]
#[inline(always)]
pub fn dbg_i2c1_stop(&mut self) -> DBG_I2C1_STOP_W {
DBG_I2C1_STOP_W { w: self }
}
#[doc = "Bit 30 - Clocking of LPTIMER2 counter when the core is halted"]
#[inline(always)]
pub fn dbg_lptim2_stop(&mut self) -> DBG_LPTIM2_STOP_W {
DBG_LPTIM2_STOP_W { w: self }
}
#[doc = "Bit 31 - Clocking of LPTIMER1 counter when the core is halted"]
#[inline(always)]
pub fn dbg_lptim1_stop(&mut self) -> DBG_LPTIM1_STOP_W {
DBG_LPTIM1_STOP_W { w: self }
}
}
|
mod adventofcode;
use adventofcode::load_file;
#[cfg(test)]
mod tests {
use spreadsheet_sum;
#[test]
fn test1() {
let input = r#"5 9 2 8
9 4 7 3
3 8 6 5"#;
assert_eq!(spreadsheet_sum(&input), 9);
}
}
fn spreadsheet_sum(input: &str) -> i32 {
let mut sum = 0;
for line in input.lines() {
let values: Vec<_> = line.split_whitespace()
.map(|s| s.parse::<i32>().unwrap())
.collect();
for a in values.iter() {
for b in values.iter() {
if b != a && a % b == 0 {
sum += a / b;
}
}
}
}
sum
}
fn main() {
let input = load_file("inputs/02-1.txt").unwrap();
let sum = spreadsheet_sum(&input);
println!("{}", sum);
}
|
pub mod dir;
pub mod error;
|
use bytes::Buf;
use iovec::IoVec;
/// A `Buf` wrapping a static byte slice.
#[derive(Debug)]
pub(crate) struct StaticBuf(pub(crate) &'static [u8]);
impl Buf for StaticBuf {
#[inline]
fn remaining(&self) -> usize {
self.0.len()
}
#[inline]
fn bytes(&self) -> &[u8] {
self.0
}
#[inline]
fn advance(&mut self, cnt: usize) {
self.0 = &self.0[cnt..];
}
#[inline]
fn bytes_vec<'t>(&'t self, dst: &mut [&'t IoVec]) -> usize {
if dst.is_empty() || self.0.is_empty() {
0
} else {
dst[0] = self.0.into();
1
}
}
}
|
extern crate json;
use std::io;
fn main() {
// Explicit type declaration
let s_ref: &str = "ba";
// Type inference
let mut s = String::from("hi there");
// Print to stdout
println!("Hello, world! {} {}", s_ref, s);
// Format to string
let x: &str = format!("This is me {}", "really");
println!("{}", x);
// Read from stdin
io::stdin().read_line(&mut s).expect("Failed to read");
println!("{}", s);
// Let's parse some json
let js: json::JsonValue = json::parse(r#"{"key": "value"}"#).expect("Failed to parse json");
println!("{}", js["key"]);
}
|
#[doc = "Reader of register EV_PENDING"]
pub type R = crate::R<u8, super::EV_PENDING>;
#[doc = "Writer for register EV_PENDING"]
pub type W = crate::W<u8, super::EV_PENDING>;
#[doc = "Register EV_PENDING `reset()`'s with value 0"]
impl crate::ResetValue for super::EV_PENDING {
type Type = u8;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `pending`"]
pub type PENDING_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `pending`"]
pub struct PENDING_W<'a> {
w: &'a mut W,
}
impl<'a> PENDING_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !0x01) | ((value as u8) & 0x01);
self.w
}
}
impl R {
#[doc = "Bit 0"]
#[inline(always)]
pub fn pending(&self) -> PENDING_R {
PENDING_R::new((self.bits & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 0"]
#[inline(always)]
pub fn pending(&mut self) -> PENDING_W {
PENDING_W { w: self }
}
}
|
use crate::error::SymbolError;
/// # symbol - Interned, Unicode symbolic atoms (aka identifiers)
///
/// symbol - Interned, Unicode symbolic atoms (aka identifiers)
/// A subset of symbols called identifiers can be denoted in text without single-quotes.
/// An identifier is a sequence of ASCII letters, digits, or the
/// characters $ (dollar sign) or _ (underscore), not starting with a digit.
///
/// Ion symbols may have text that is unknown. That is, there is no binding to a (potentially empty) sequence of text.
/// This can happen as a result of not having access to a shared symbol table being imported,
/// or having a symbol table (shared or local) that contains a null slot.
///
/// A processor encountering a symbol with unknown text and a valid SID other than $0 MAY produce an error
/// because this means that the context of the data is missing.
/// Note: serde_ion does not support symbols other than $0 with unknown text.
/// # Structures
///
/// Where Int may be any integer and String may be any string.
/// ## SymbolToken
///
/// <text:String, importLocation:ImportLocation>
///
/// ### SymbolToken equivalence
///
/// In order to fully support the equivalence semantics defined by the specification,
/// SymbolToken equivalence must be implemented as follows.
///
/// When text is
///
/// #### Defined
///
/// SymbolTokens with the same text are equivalent; importLocation is ignored.
///
/// #### Undefined
///
/// ```text
/// if importLocation is
///
/// * Defined: SymbolTokens are equivalent if and only if their importLocations’ importName and importSID are equivalent.
///
/// * Undefined: The SymbolToken represents the special symbol zero,
/// which is used to denote that a SymbolToken has unknown text in any symbol table.
/// SymbolTokens representing symbol zero are equivalent only to other SymbolTokens
/// representing symbol zero.
/// ```
///
/// ### Reading SymbolTokens
///
/// ```text
/// Ion readers must support being provided with an optional catalog to use for resolving shared
/// symbol table imports declared within local symbol tables encountered in the stream.
/// If a declared import is not found in the catalog,
/// all of the symbol IDs in its max_id range will have unknown text.
///
/// Generally, Ion readers provide two kinds of SymbolToken reading APIs, those that return:
///
/// * Raw text (for convenience), and
/// * Complete SymbolTokens (for full fidelity).
///
/// For a Binary reader, if the local symbol ID is
///
/// * Within the current local symbol table’s max_id range, if the local symbol ID maps to text which is
///
/// ** Known, for
///
/// *** Raw text APIs, return that text.
///
/// *** SymbolToken APIs, return a SymbolToken with that text and with an undefined importLocation.
///
/// ** Unknown, if the local symbol ID is
///
/// *** Less than the current local symbol table’s min_local_id (as defined by the specification), for
///
/// **** Raw text APIs, the implementation should raise an error.
///
/// **** SymbolToken APIs, return a SymbolToken with undefined text and with importLocation set.
///
/// *** At least min_local_id, then this symbol ID maps to a null (or non-string) slot in the local symbol table, and is treated as symbol zero. For
///
/// **** Raw text APIs, return undefined text.
///
/// **** SymbolToken APIs, return a SymbolToken with undefined text and an undefined importLocation.
///
/// * Greater than the current local symbol table’s max_id, or less than zero, an error must be raised.
/// ```
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum SymbolToken {
// All SymbolTokens with identical known text are equivalent, import_location is ignored
Known { text: String },
// The SymbolToken's text is undefined if the import_location cannot not be resolved
Unknown { import_location: ImportDescriptor },
// Special symbol zero denotes unknown text in any symbol table
Zero,
}
impl SymbolToken {
pub fn to_text(&self) -> String {
match self {
SymbolToken::Known { text } => text.to_string(),
SymbolToken::Unknown { .. } => todo!(), // should error, but how?
SymbolToken::Zero => "$0".to_string(),
}
}
}
/// ## ImportDescriptor
///
/// <importName:String, version:Int, max_id:Int>
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct ImportDescriptor {
import_name: String,
version: u32,
max_id: u32,
}
/// ## ImportLocation
///
/// <importName:String, importSID:Int>
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct ImportLocation {
import_name: String,
import_sid: u32,
}
/// ## SymbolTable
///
/// Stores a symbol mapping used to convert encountered Symbols back into text.
///
/// ### Semantics
/// When mapping from symbol ID to string, there is no ambiguity.
/// However, due to unavailable imports, certain IDs may appear to be undefined when binary data
/// is decoded. Any symbol ID outside of the range of the local symbol table (or system symbol
/// table if no local symbol table is defined) for which it is encoded under MUST raise an error.
///
/// When mapping from string to symbol ID, there may be multiple assigned IDs;
/// implementations MUST select the lowest known ID. If an imported table is unavailable,
/// this may cause selection of a greater ID than would be the case otherwise.
/// This restriction ensures that symbols defined by system symbol tables can
/// never be mapped to other IDs.
///
/// Put another way, string-to-SID mappings have the following precedence:
///
/// The system table is always consulted first.
/// Each imported table is consulted in the order of import.
/// Local symbols are last.
#[derive(Clone, Debug, PartialEq)]
pub enum SymbolTable {
Local(LocalSymbolTable),
Shared(SharedSymbolTable),
SystemV1,
}
impl SymbolTable {
pub fn lookup_text(&self, text: &str) -> Result<SymbolToken, SymbolError> {
match self {
SymbolTable::Local(table) => todo!(),
SymbolTable::Shared(table) => todo!(),
SymbolTable::SystemV1 => todo!(),
}
}
pub fn lookup_sid(&self, sid: usize) -> Result<SymbolToken, SymbolError> {
if sid == 0 {
return Ok(SymbolToken::Zero);
}
match self {
SymbolTable::Local(table) => todo!(),
SymbolTable::Shared(table) => todo!(),
SymbolTable::SystemV1 => match SYSTEM_SYMBOL_TABLE_V1.symbols.get(sid) {
Some(token) => Ok(token.clone()),
None => Err(SymbolError::AboveMaxId {
symbol_id: sid,
max_id: 9,
}),
},
}
}
}
/// ## LocalSymbolTable
///
/// Stores an in-stream symbol table definition.
/// A local symbol table imports either the symbols from a list of shared symbol tables,
/// or may import the current symbol table.
#[derive(Clone, Debug, PartialEq)]
pub struct LocalSymbolTable {
imports: LocalImport,
symbols: Vec<String>,
}
// Specifies the import of a SharedSymbolTable into a LocalSymbolTable
#[derive(Clone, Debug, PartialEq)]
pub struct LocalImport {
name: String,
version: u32,
max_id: u32,
}
/// ## SharedSymbolTable
///
/// Stores an in-stream symbol table definition.
/// A local symbol table imports either the symbols from a list of shared symbol tables,
/// or may import the current symbol table.
#[derive(Clone, Debug, PartialEq)]
pub struct SharedSymbolTable {
name: String,
version: u32,
// The imports field is for informational purposes only in shared tables.
// They assert that this table contains a superset of the strings in each of these named tables.
// It makes no assertion about any relationship between symbol IDs in this table and the imports,
// only that the symbols’ text occurs here.
imports: Vec<SharedImport>,
symbols: Vec<String>,
}
// Specifies the import of a SharedSymbolTable into a SharedSymbolTable.
// This differs from LocalSymbolTableImport in that the import is informational only, so the max_id is unnecessary.
#[derive(Clone, Debug, PartialEq)]
pub struct SharedImport {
name: String,
version: u32,
}
#[derive(Clone, Debug, PartialEq)]
pub struct SystemSymbolTable {
pub name: &'static str,
pub version: u32,
// Hopefully there will be const generics by the time the $ion symbol table has more than 1 version
pub symbols: [SymbolToken; 10],
}
lazy_static! {
pub static ref SYSTEM_SYMBOL_TABLE_V1: SystemSymbolTable = {
SystemSymbolTable {
name: "$ion",
version: 1,
symbols: [
SymbolToken::Zero,
SymbolToken::Known {
text: "$ion".to_string(),
},
SymbolToken::Known {
text: "$ion_1_0".to_string(),
},
SymbolToken::Known {
text: "$ion_symbol_table".to_string(),
},
SymbolToken::Known {
text: "name".to_string(),
},
SymbolToken::Known {
text: "version".to_string(),
},
SymbolToken::Known {
text: "imports".to_string(),
},
SymbolToken::Known {
text: "symbols".to_string(),
},
SymbolToken::Known {
text: "max_id".to_string(),
},
SymbolToken::Known {
text: "$ion_shared_symbol_table".to_string(),
},
],
}
};
}
|
use crate::auth;
use crate::diesel::QueryDsl;
use crate::diesel::RunQueryDsl;
use crate::handlers::types::*;
use crate::helpers::aws;
use crate::model::{Space, SpaceUser, User};
use crate::schema::spaces::dsl::*;
#[allow(unused_imports)]
use crate::schema::spaces_channel::dsl::space_id as channel_space_id;
use crate::schema::spaces_users::dsl::space_id;
use crate::schema::spaces_users::dsl::*;
use crate::schema::users::dsl::*;
use crate::Pool;
use crate::controllers::space_controller::*;
use actix_files::NamedFile;
use actix_multipart::Multipart;
use actix_web::{web, Error, HttpResponse};
use actix_web_httpauth::extractors::bearer::BearerAuth;
use diesel::prelude::*;
use futures::{StreamExt, TryStreamExt};
use std::fs;
use std::fs::remove_file;
use std::io::Write;
use std::time::{SystemTime, UNIX_EPOCH};
//http responses
pub async fn add_space(
db: web::Data<Pool>,
item: web::Json<CreateSpace>,
auth: BearerAuth,
) -> Result<HttpResponse, Error> {
match auth::validate_token(&auth.token().to_string()) {
Ok(res) => {
if res == true {
Ok(
web::block(move || add_space_db(db, item, auth.token().to_string()))
.await
.map(|response| HttpResponse::Ok().json(response))
.map_err(|_| {
HttpResponse::Ok()
.json(Response::new(false, "some error ocuured".to_string()))
})?,
)
} else {
Ok(HttpResponse::Ok().json(ResponseError::new(false, "jwt error".to_string())))
}
}
Err(_) => Ok(HttpResponse::Ok().json(ResponseError::new(false, "jwt error".to_string()))),
}
}
pub async fn update_space_logo(
db: web::Data<Pool>,
mut payload: Multipart,
token: BearerAuth,
space_name: web::Path<PathInfo>,
) -> Result<HttpResponse, Error> {
match auth::validate_token(&token.token().to_string()) {
Ok(res) => {
if res == true {
//check if user is an admin
let decoded_token = auth::decode_token(&token.token().to_string());
let conn = db.get().unwrap();
let user: User = users
.find(decoded_token.parse::<i32>().unwrap())
.first(&conn)
.unwrap();
let space = spaces
.filter(spaces_name.ilike(&space_name.info))
.first::<Space>(&conn);
match space {
Ok(space) => {
let spaces_user: SpaceUser = spaces_users
.filter(space_id.eq(space.id))
.filter(user_id.eq(user.id))
.first::<SpaceUser>(&conn)
.unwrap();
if !spaces_user.admin_status {
return Ok(HttpResponse::Ok().json(Response::new(
false,
"Only admin is permitted to update this space logo".to_string(),
)));
};
while let Ok(Some(mut field)) = payload.try_next().await {
//get file content
let content_type = field.content_disposition().unwrap();
let filename = format!(
"{}-{}",
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_micros(),
content_type.get_filename().unwrap(),
);
let filepath =
format!("./tmp/{}", sanitize_filename::sanitize(&filename));
// File::create is blocking operation, use threadpool
let mut f = web::block(|| std::fs::File::create(filepath))
.await
.unwrap();
// Field in turn is stream of *Bytes* object
while let Some(chunk) = field.next().await {
let data = chunk.unwrap();
// filesystem operations are blocking, we have to use threadpool
f = web::block(move || f.write_all(&data).map(|_| f))
.await
.unwrap();
}
//extract file vector
let file: Vec<u8> = fs::read(format!("./tmp/{}", &filename)).unwrap();
let metadata = fs::metadata(format!("./tmp/{}", &filename)).unwrap();
//validate if file is over 5 MB
if metadata.len() > 5000000 {
remove_file(format!("./tmp/{}", &filename)).unwrap();
return Ok(HttpResponse::Ok().json(Response::new(
false,
"file should not be larger than 5 MB".to_string(),
)));
} else {
remove_file(format!("./tmp/{}", &filename)).unwrap();
//upload to aws
let uploaded = web::block(|| aws::aws_func(filename, file)).await;
match uploaded {
Ok(file_link) => {
let _space_details = diesel::update(spaces.find(space.id))
.set(spaces_img.eq(&file_link))
.execute(&conn);
return Ok(
HttpResponse::Ok().json(Response::new(true, file_link))
);
}
_ => {
return Ok(HttpResponse::Ok().json(Response::new(
false,
"error uploading file".to_string(),
)))
}
}
}
}
}
_ => {
return Ok(HttpResponse::Ok()
.json(Response::new(false, "Space not found".to_string())))
}
}
} else {
return Ok(
HttpResponse::Ok().json(ResponseError::new(false, "jwt error".to_string()))
);
}
}
Err(_) => {
return Ok(HttpResponse::Ok().json(ResponseError::new(false, "jwt error".to_string())))
}
}
Ok(HttpResponse::Ok().json(Response::new(true, "file upload successful".to_string())))
}
pub async fn update_space(
db: web::Data<Pool>,
item: web::Json<CreateSpace>,
auth: BearerAuth,
space_name: web::Path<PathInfo>,
) -> Result<HttpResponse, Error> {
match auth::validate_token(&auth.token().to_string()) {
Ok(res) => {
if res == true {
Ok(web::block(move || {
update_space_db(db, item, auth.token().to_string(), space_name)
})
.await
.map(|response| HttpResponse::Ok().json(response))
.map_err(|_| {
HttpResponse::Ok()
.json(Response::new(false, "Space name already exist".to_string()))
})?)
} else {
Ok(HttpResponse::Ok().json(ResponseError::new(false, "jwt error".to_string())))
}
}
Err(_) => Ok(HttpResponse::Ok().json(ResponseError::new(false, "jwt error".to_string()))),
}
}
pub async fn get_space(
db: web::Data<Pool>,
auth: BearerAuth,
space_name: web::Path<PathInfo>,
) -> Result<HttpResponse, Error> {
match auth::validate_token(&auth.token().to_string()) {
Ok(res) => {
if res == true {
Ok(
web::block(move || get_space_db(db, auth.token().to_string(), space_name))
.await
.map(|response| HttpResponse::Ok().json(response))
.map_err(|_| {
HttpResponse::Ok().json(Response::new(
false,
"Unauthorized to view space".to_string(),
))
})?,
)
} else {
Ok(HttpResponse::Ok().json(ResponseError::new(false, "jwt error".to_string())))
}
}
Err(_) => Ok(HttpResponse::Ok().json(ResponseError::new(false, "jwt error".to_string()))),
}
}
pub async fn get_user_space(db: web::Data<Pool>, auth: BearerAuth) -> Result<HttpResponse, Error> {
match auth::validate_token(&auth.token().to_string()) {
Ok(res) => {
if res == true {
Ok(
web::block(move || get_user_space_db(db, auth.token().to_string()))
.await
.map(|user| HttpResponse::Ok().json(user))
.map_err(|_| HttpResponse::InternalServerError())?,
)
} else {
Ok(HttpResponse::Ok().json(ResponseError::new(false, "jwt error".to_string())))
}
}
Err(_) => Ok(HttpResponse::Ok().json(ResponseError::new(false, "jwt error".to_string()))),
}
}
pub async fn add_invited_user(
db: web::Data<Pool>,
item: web::Json<CreateUser>,
query: web::Query<QueryInfo>,
) -> Result<HttpResponse, Error> {
match auth::validate_token(&query.token.to_string()) {
Ok(res) => {
if res == true {
Ok(web::block(move || add_invited_user_db(db, item, query))
.await
.map(|response| HttpResponse::Ok().json(response))
.map_err(|_| HttpResponse::InternalServerError())?)
} else {
Ok(HttpResponse::Ok().json(ResponseError::new(false, "jwt error".to_string())))
}
}
Err(_) => Ok(HttpResponse::Ok().json(ResponseError::new(false, "jwt error".to_string()))),
}
}
pub async fn invite_user(
db: web::Data<Pool>,
item: web::Json<InviteToSpace>,
auth: BearerAuth,
space_name: web::Path<PathInfo>,
) -> Result<HttpResponse, Error> {
match auth::validate_token(&auth.token().to_string()) {
Ok(res) => {
if res == true {
Ok(web::block(move || {
invite_user_db(db, item, auth.token().to_string(), space_name)
})
.await
.map(|response| HttpResponse::Ok().json(response))
.map_err(|_| {
HttpResponse::Ok().json(Response::new(false, "Space not found".to_string()))
})?)
} else {
Ok(HttpResponse::Ok().json(ResponseError::new(false, "jwt error".to_string())))
}
}
Err(_) => Ok(HttpResponse::Ok().json(ResponseError::new(false, "jwt error".to_string()))),
}
}
pub async fn invite_page(_item: web::Query<QueryInfo>) -> Result<NamedFile, ()> {
let success_file = format!("./pages/invite.html");
Ok(NamedFile::open(success_file).unwrap())
}
pub async fn get_user_space_status(
db: web::Data<Pool>,
auth: BearerAuth,
space_name: web::Path<PathInfo>,
) -> Result<HttpResponse, Error> {
match auth::validate_token(&auth.token().to_string()) {
Ok(res) => {
if res == true {
Ok(web::block(move || {
get_user_space_status_db(db, auth.token().to_string(), space_name)
})
.await
.map(|response| HttpResponse::Ok().json(response))
.map_err(|_| {
HttpResponse::Ok()
.json(Response::new(false, "Error getting status".to_string()))
})?)
} else {
Ok(HttpResponse::Ok().json(ResponseError::new(false, "jwt error".to_string())))
}
}
Err(_) => Ok(HttpResponse::Ok().json(ResponseError::new(false, "jwt error".to_string()))),
}
}
pub async fn remove_user_from_space(
db: web::Data<Pool>,
auth: BearerAuth,
space_name: web::Path<PathInfo>,
item: web::Json<UserIdStruct>,
) -> Result<HttpResponse, Error> {
match auth::validate_token(&auth.token().to_string()) {
Ok(res) => {
if res == true {
Ok(web::block(move || {
remove_user_from_space_db(db, auth.token().to_string(), space_name, item)
})
.await
.map(|response| HttpResponse::Ok().json(response))
.map_err(|_| {
HttpResponse::Ok().json(Response::new(
false,
"Error getting space details".to_string(),
))
})?)
} else {
Ok(HttpResponse::Ok().json(ResponseError::new(false, "jwt error".to_string())))
}
}
Err(_) => Ok(HttpResponse::Ok().json(ResponseError::new(false, "jwt error".to_string()))),
}
}
pub async fn leave_space(
db: web::Data<Pool>,
auth: BearerAuth,
space_name: web::Path<PathInfo>,
) -> Result<HttpResponse, Error> {
match auth::validate_token(&auth.token().to_string()) {
Ok(res) => {
if res == true {
Ok(
web::block(move || leave_space_db(db, auth.token().to_string(), space_name))
.await
.map(|response| HttpResponse::Ok().json(response))
.map_err(|_| {
HttpResponse::Ok().json(Response::new(
false,
"Error getting space details".to_string(),
))
})?,
)
} else {
Ok(HttpResponse::Ok().json(ResponseError::new(false, "jwt error".to_string())))
}
}
Err(_) => Ok(HttpResponse::Ok().json(ResponseError::new(false, "jwt error".to_string()))),
}
}
pub async fn change_user_priviledge_status(
db: web::Data<Pool>,
auth: BearerAuth,
space_name: web::Path<PathInfo>,
item: web::Json<PriviledgeStruct>,
) -> Result<HttpResponse, Error> {
match auth::validate_token(&auth.token().to_string()) {
Ok(res) => {
if res == true {
Ok(web::block(move || {
change_user_priviledge_status_db(db, auth.token().to_string(), space_name, item)
})
.await
.map(|response| HttpResponse::Ok().json(response))
.map_err(|_| {
HttpResponse::Ok().json(Response::new(
false,
"Error getting space details".to_string(),
))
})?)
} else {
Ok(HttpResponse::Ok().json(ResponseError::new(false, "jwt error".to_string())))
}
}
Err(_) => Ok(HttpResponse::Ok().json(ResponseError::new(false, "jwt error".to_string()))),
}
}
pub async fn get_users_in_space(
db: web::Data<Pool>,
space_name: web::Path<PathInfo>,
) -> Result<HttpResponse, Error> {
Ok(web::block(move || get_users_in_space_db(db, space_name))
.await
.map(|response| HttpResponse::Ok().json(response))
.map_err(|_| {
HttpResponse::Ok().json(Response::new(
false,
"Error getting space details".to_string(),
))
})?)
}
|
//! The ecs module defines the Ecs struct which is the main entry point of tuber-ecs
use std::any::{Any, TypeId};
use std::cell::{Ref, RefCell, RefMut};
use std::collections::{HashMap, HashSet};
use crate::bitset::BitSet;
use crate::query::{ComponentTypeId, Query, QueryIterator, QueryIteratorByIds};
use crate::EntityIndex;
pub type Components = HashMap<TypeId, ComponentStore>;
pub type Resources = HashMap<TypeId, RefCell<Box<dyn Any>>>;
type EntitiesBitsetType = [u64; 1024];
pub struct ComponentStore {
pub(crate) component_data: Vec<Option<RefCell<Box<dyn Any>>>>,
pub(crate) entities_bitset: EntitiesBitsetType,
}
impl ComponentStore {
#[must_use]
pub fn with_size(size: usize) -> Self {
let mut component_data = vec![None];
for _ in 0..size {
component_data.push(None);
}
Self {
component_data,
entities_bitset: [0u64; 1024],
}
}
pub fn remove_from_entity(&mut self, entity_index: EntityIndex) {
self.entities_bitset.unset_bit(entity_index);
self.component_data[entity_index] = None;
}
pub fn add_to_entity<C: 'static>(&mut self, component: C, entity_index: EntityIndex) {
self.entities_bitset.set_bit(entity_index);
self.component_data[entity_index] = Some(RefCell::new(Box::new(component)));
}
}
impl Default for ComponentStore {
fn default() -> Self {
Self {
component_data: vec![None],
entities_bitset: [0u64; 1024],
}
}
}
/// The Ecs itself, stores entities and runs systems
#[derive(Default)]
pub struct Ecs {
components: Components,
shared_resources: Resources,
next_index: EntityIndex,
}
impl Ecs {
pub fn insert_shared_resource<T: 'static>(&mut self, resource: T) {
self.shared_resources
.insert(TypeId::of::<T>(), RefCell::new(Box::new(resource)));
}
#[must_use]
pub fn shared_resource<T: 'static>(&self) -> Option<Ref<T>> {
Some(Ref::map(
self.shared_resources.get(&TypeId::of::<T>())?.borrow(),
|r| r.downcast_ref().unwrap(),
))
}
#[must_use]
pub fn shared_resource_mut<T: 'static>(&self) -> Option<RefMut<T>> {
Some(RefMut::map(
self.shared_resources
.get(&TypeId::of::<T>())
.as_ref()?
.borrow_mut(),
|r| r.downcast_mut().unwrap(),
))
}
/// Inserts an entity into the Ecs.
///
/// This method takes an [`EntityDefinition`] describing the entity.
///
/// It returns the [`EntityIndex`] of the inserted entity.
pub fn insert<ED: EntityDefinition>(&mut self, entity_definition: ED) -> EntityIndex {
let index = self.next_index;
entity_definition.store_components(&mut self.components, index);
self.next_index += 1;
index
}
pub fn delete_by_query<Q: for<'a> Query<'a>>(&mut self) {
let to_delete = Q::matching_ids(self.entity_count(), &self.components);
self.delete_by_ids(to_delete.iter().copied().collect::<Vec<_>>().as_slice());
}
pub fn delete_by_ids(&mut self, to_delete: &[usize]) {
for &entity_index in to_delete {
for component in self.components.values_mut() {
component.entities_bitset.unset_bit(entity_index);
component.component_data[entity_index] = None;
}
}
}
pub fn remove_component<C: 'static>(&mut self, entity_index: EntityIndex) {
if let Some(components) = self.components.get_mut(&TypeId::of::<C>()) {
components.remove_from_entity(entity_index);
}
}
pub fn add_component<C: 'static>(&mut self, component: C, entity_index: EntityIndex) {
if let Some(components) = self.components.get_mut(&TypeId::of::<C>()) {
components.add_to_entity(component, entity_index);
}
}
#[must_use]
pub fn query<'a, Q: Query<'a>>(&self) -> QueryIterator<Q> {
QueryIterator::new(self.entity_count(), &self.components)
}
#[must_use]
pub fn query_by_ids<'a, Q: Query<'a>>(&self, ids: &HashSet<usize>) -> QueryIteratorByIds<Q> {
QueryIteratorByIds::new(self.entity_count(), &self.components, ids)
}
#[must_use]
pub fn query_one<'a, Q: Query<'a>>(&'a self) -> Option<Q::ResultType> {
let index = {
let type_ids = Q::type_ids();
let type_ids: Vec<_> = type_ids
.iter()
.filter_map(|type_id| {
if let ComponentTypeId::RequiredComponentTypeId(type_id) = type_id {
Some(type_id)
} else {
None
}
})
.collect();
let bitsets: Vec<&EntitiesBitsetType> = type_ids
.iter()
.filter_map(|type_id| Some(&self.components.get(type_id)?.entities_bitset))
.collect();
if bitsets.len() != type_ids.len() {
return None;
}
let mut index = None;
for i in 0..self.entity_count() {
if bitsets.iter().all(|bitset| bitset.bit(i)) {
index = Some(i);
break;
}
}
index?
};
Q::fetch(index, &self.components)
}
#[must_use]
pub fn query_one_by_id<'a, Q: Query<'a>>(&'a self, id: EntityIndex) -> Option<Q::ResultType> {
Q::fetch(id, &self.components)
}
/// Returns the entity count of the Ecs.
#[must_use]
pub fn entity_count(&self) -> usize {
self.next_index
}
}
/// A type that can be used to define an entity
pub trait EntityDefinition {
fn store_components(self, components: &mut Components, index: usize);
}
macro_rules! impl_entity_definition_tuples {
($($t:tt => $i:tt,)*) => {
impl<$($t: 'static,)*> EntityDefinition for ($($t,)*) {
fn store_components(self, components: &mut Components, index: usize) {
use crate::bitset::BitSet;
for component_storage in components.values_mut() {
component_storage.component_data.push(None);
}
$(
let component_storage = components.entry(TypeId::of::<$t>()).or_insert(ComponentStore::with_size(index));
*component_storage.component_data.last_mut().unwrap() = (Some(RefCell::new(Box::new(self.$i))));
component_storage.entities_bitset.set_bit(index);
)*
}
}
}
}
impl_entity_definition_tuples!(A => 0,);
impl_entity_definition_tuples!(A => 0, B => 1,);
impl_entity_definition_tuples!(A => 0, B => 1, C => 2,);
impl_entity_definition_tuples!(A => 0, B => 1, C => 2, D => 3,);
impl_entity_definition_tuples!(A => 0, B => 1, C => 2, D => 3, E => 4,);
impl_entity_definition_tuples!(A => 0, B => 1, C => 2, D => 3, E => 4, F => 5,);
impl_entity_definition_tuples!(A => 0, B => 1, C => 2, D => 3, E => 4, F => 5, G => 6,);
impl_entity_definition_tuples!(A => 0, B => 1, C => 2, D => 3, E => 4, F => 5, G => 6, H => 7,);
#[cfg(test)]
mod tests {
use crate::query::accessors::Opt;
use super::*;
#[derive(Debug, PartialEq)]
struct Position {
x: f32,
y: f32,
}
#[derive(Debug)]
struct Velocity {
x: f32,
y: f32,
}
#[test]
pub fn ecs_new() {
let ecs = Ecs::default();
assert_eq!(ecs.entity_count(), 0usize);
}
#[test]
pub fn ecs_insert() {
let mut ecs = Ecs::default();
ecs.insert((Position { x: 0.0, y: 1.0 }, Velocity { x: 2.0, y: 3.0 }));
assert_eq!(ecs.entity_count(), 1usize);
ecs.insert((Position { x: 4.0, y: 5.0 }, Velocity { x: 6.0, y: 7.0 }));
assert_eq!(ecs.entity_count(), 2usize);
}
#[test]
pub fn ecs_query() {
let mut ecs = Ecs::default();
ecs.insert((Position { x: 12.0, y: 1.0 }, Velocity { x: 2.0, y: 3.0 }));
ecs.insert((Position { x: 4.0, y: 5.0 }, Velocity { x: 6.0, y: 7.0 }));
ecs.insert((Position { x: 4.0, y: 5.0 },));
for (_, (mut velocity,)) in ecs.query::<(&mut Velocity,)>() {
velocity.x = 0.0;
}
for (_, (velocity,)) in ecs.query::<(&Velocity,)>() {
assert_float_absolute_eq!(velocity.x, 0.0, 0.01);
}
assert_eq!(ecs.query::<(&Position,)>().count(), 3);
assert_eq!(ecs.query::<(&Velocity,)>().count(), 2);
}
#[test]
pub fn ecs_query_one() {
let mut ecs = Ecs::default();
ecs.insert((Position { x: 12.0, y: 1.0 }, Velocity { x: 2.0, y: 3.0 }));
assert_eq!(ecs.query_one::<(&Position,)>().unwrap().0, 0);
assert_eq!(
(*(ecs.query_one::<(&Position,)>().unwrap().1).0),
Position { x: 12.0, y: 1.0 }
);
}
#[test]
pub fn ecs_query_optional() {
let mut ecs = Ecs::default();
ecs.insert((Position { x: 12.0, y: 1.0 }, Velocity { x: 2.0, y: 3.0 }));
ecs.insert((Position { x: 15.0, y: 8.0 },));
assert_eq!(ecs.query::<(&Position, Opt<&Velocity>)>().count(), 2);
}
#[test]
pub fn ecs_query_one_optional() {
let mut ecs = Ecs::default();
ecs.insert((Position { x: 12.0, y: 1.0 },));
let (_, (position, velocity)) = ecs.query_one::<(&Position, Opt<&Velocity>)>().unwrap();
assert_eq!(*position, Position { x: 12.0, y: 1.0 });
assert!(velocity.is_none());
}
#[test]
pub fn ecs_query_one_implicit_read_accessor() {
let mut ecs = Ecs::default();
ecs.insert((Position { x: 12.0, y: 1.0 },));
let (_, (position,)) = ecs.query_one::<(&Position,)>().unwrap();
assert_eq!(*position, Position { x: 12.0, y: 1.0 });
}
}
|
//! Miscellaneous system related functionality.
//!
//! Other than the extern portion of this module, this is basically a really poorly done
//! https://github.com/nix-rust/nix clone. Use that instead :)
#![allow(unsafe_code)]
use libc;
use std::fs;
use std::ffi::{CString, CStr};
use std::ptr;
use std::env;
// XXX: I'm mixing two different UnixDatagram types by not being async everywhere , but it doesn't
// matter because I don't even deal with the server code properly here :/
use std::os::unix::io::AsRawFd;
use std::os::unix::net::UnixDatagram;
mod ffi {
extern {
pub fn sandbox() -> i32;
pub fn open_recvmsg(socket: i32, fd: &i32) -> i32;
pub fn open_sendmsg(socket: i32, fd: i32) -> i32;
pub fn open_sendmsg_err(socket: i32) -> i32;
}
}
// TODO: Should probably make a macro out of the "call and check errno" pattern
// FIXME: The way I'm calling all them is different; some I set errno some I don't, etc.
pub enum ProcessType {
Parent,
Child,
}
// FIXME: Use Result not Option
pub fn fork() -> Option<ProcessType> {
// XXX: I'm not actually 100% sure whether this is safe to call at all in a Rust program.
let ret;
unsafe {
let errno = libc::__errno_location();
*errno = 0;
ret = libc::fork();
if ret < 0 || *errno != 0 {
let err = CStr::from_ptr(libc::strerror(*errno));
println!("fork(): {:?}", err);
return None;
}
}
// XXX: Wait isn't this backwards? The PIDs seem right in `ps` but I don't know what the child
// is :/
if ret == 0 {
Some(ProcessType::Child)
} else {
Some(ProcessType::Parent)
}
}
// FIXME: Handle errors
pub fn readlink(path: &str) -> String {
// XXX: This is _terrible_! I told you not to look in this file :)
unsafe {
let len: usize = 256;
let path_c = CString::new(path).unwrap();
let mut buf: Vec<u8> = Vec::with_capacity(len);
let p = buf.as_mut_ptr() as *mut libc::c_char;
let errno = libc::__errno_location();
*errno = 0;
let ret = libc::readlink(path_c.as_ptr(), p, len);
// On error just return the original argument
if ret < 0 || *errno != 0 {
let err = CStr::from_ptr(libc::strerror(*errno));
println!("Error readlink(): {:?}", err);
return path.to_string();
} else if ret == len as isize {
println!("Error readlink(): Buffer was too small. Path truncated");
}
// Null terminate at ret
buf.set_len(len);
buf[ret as usize] = 0;
// Shorten buf to first null
let s = CStr::from_ptr(p);
buf.set_len(s.to_bytes().len());
// Create a string and return it
let ret = CString::new(buf).unwrap();
ret.into_string().unwrap()
}
}
// FIXME: Handle errors
pub fn set_hostname(hostname: &str) {
unsafe {
let hostname_c = CString::new(hostname).unwrap();
let errno = libc::__errno_location();
*errno = 0;
let ret = libc::sethostname(hostname_c.as_ptr(), hostname.len());
if ret != 0 || *errno != 0 {
let err = CStr::from_ptr(libc::strerror(*errno));
println!("[foo] Error setting hostname: {:?}", err); // FIXME: lol
}
}
}
// FIXME: Use Result not Option
// FIXME: Does libc give better types than this? i32 seems wrong for an fd regardless.
pub fn open_recvmsg(socket: &UnixDatagram) -> Option<i32> {
unsafe {
let socketfd = socket.as_raw_fd();
let mut fd = -1;
let ret = ffi::open_recvmsg(socketfd, &mut fd);
let errno = *libc::__errno_location();
if ret == -127 {
println!("[ipc client] Request failed policy");
None
} else if ret < 0 || errno != 0 || fd < 0 {
let err = CStr::from_ptr(libc::strerror(errno));
println!("[ipc client] Error calling recvmsg(): ({:?}) {:?}", errno, err);
None
} else {
Some(fd)
}
}
}
// FIXME: Use Result not Option
pub fn open_sendmsg(socket: i32, fd: i32) -> Option<()> {
unsafe {
let ret = ffi::open_sendmsg(socket, fd);
let errno = *libc::__errno_location();
if ret < 0 || errno != 0 {
let err = CStr::from_ptr(libc::strerror(errno));
println!("[ipc server] Error calling sendmsg(): ({:?}) {:?}", errno, err);
None
} else {
Some(())
}
}
}
// FIXME: Use Result not Option
pub fn open_sendmsg_err(socket: i32) -> Option<()> {
unsafe {
let ret = ffi::open_sendmsg_err(socket);
let errno = *libc::__errno_location();
if ret < 0 || errno != 0 {
let err = CStr::from_ptr(libc::strerror(errno));
println!("[ipc server] Error calling sendmsg(): ({:?}) {:?}", errno, err);
None
} else {
Some(())
}
}
}
// FIXME: Handle errors
// FIXME: This name is misleading and doesn't actually discribe behaviour
pub fn prctl() {
unsafe {
let errno = libc::__errno_location();
*errno = 0;
let ret = libc::prctl(libc::PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
if ret != 0 || *errno != 0 {
let err = CStr::from_ptr(libc::strerror(*errno));
println!("[broker] Error enabling prctl: {:?}", err);
}
}
}
// FIXME: Handle errors
pub fn dropcap() {
unsafe {
// NOTE: This just blindly calls prctl() assuming there are 38 incrementing values, which
// at the time of writing is true against modern kernel versions
for cap in 0..37 {
let errno = libc::__errno_location();
*errno = 0;
let ret = libc::prctl(libc::PR_CAPBSET_DROP, cap, 0, 0, 0);
if ret != 0 || *errno != 0 {
let err = CStr::from_ptr(libc::strerror(*errno));
println!("[broker] Error dropping capability: ({}) {:?}", cap, err);
}
}
}
}
// FIXME: Shared code
// FIXME: Handle errors
pub fn unshare(flag: i32) {
unsafe {
let errno = libc::__errno_location();
*errno = 0;
let ret = libc::syscall(libc::SYS_unshare, flag);
if ret != 0 || *errno != 0 {
let err = CStr::from_ptr(libc::strerror(*errno));
println!("[broker] Error enabling namespaces: {:?}", err);
}
}
}
pub fn get_uid() -> libc::uid_t {
unsafe {
libc::getuid()
}
}
pub fn get_euid() -> libc::uid_t {
unsafe {
libc::geteuid()
}
}
pub fn get_gid() -> libc::uid_t {
unsafe {
libc::getgid()
}
}
pub fn get_egid() -> libc::uid_t {
unsafe {
libc::getegid()
}
}
// TODO: mount()
// FIXME: Should return an option
//fn mount(source, target, fstype, flags: u64) { }
// TODO: umount()
// FIXME: Should return an option
//fn umount(source, target, fstype, flags: u64) { }
// TODO: pivot_root()
// FIXME: Should return an option
//fn pivot_root(source, target, fstype, flags: u64) { }
// TODO: Handle errors
pub fn pivot() {
unsafe {
let source = ptr::null();
let target = CString::new("/").unwrap();
let fstype = ptr::null();
let flags = libc::MS_REC | libc::MS_PRIVATE;
let data = ptr::null();
let errno = libc::__errno_location();
*errno = 0;
let ret = libc::mount(source, target.as_ptr(), fstype, flags, data);
if ret != 0 || *errno != 0 {
let err = CStr::from_ptr(libc::strerror(*errno));
println!("[sandbox] private root mount(): ({:?}) {:?}", *errno, err);
}
}
unsafe {
let source = CString::new(".").unwrap();
let target = CString::new(".").unwrap();
let fstype = ptr::null();
let flags = libc::MS_REC | libc::MS_BIND;
let data = ptr::null();
let errno = libc::__errno_location();
*errno = 0;
let ret = libc::mount(source.as_ptr(), target.as_ptr(), fstype, flags, data);
if ret != 0 || *errno != 0 {
let err = CStr::from_ptr(libc::strerror(*errno));
println!("[sandbox] bind self mount(): ({:?}) {:?}", *errno, err);
}
}
// FIXME: Hardcoded dir
env::set_current_dir("/tmp/sandpit.sandbox").unwrap();
fs::create_dir("proc").unwrap();
unsafe {
let source = CString::new("none").unwrap();
let target = CString::new("proc").unwrap();
let fstype = CString::new("proc").unwrap();
let flags = libc::MS_NOEXEC | libc::MS_NOSUID | libc::MS_NODEV;
let data = ptr::null();
let errno = libc::__errno_location();
*errno = 0;
let ret = libc::mount(source.as_ptr(), target.as_ptr(), fstype.as_ptr(), flags, data);
if ret != 0 || *errno != 0 {
let err = CStr::from_ptr(libc::strerror(*errno));
println!("[sandbox] proc mount(): ({:?}) {:?}", *errno, err);
}
}
fs::create_dir("sys").unwrap();
unsafe {
let source = CString::new("none").unwrap();
let target = CString::new("sys").unwrap();
let fstype = CString::new("sysfs").unwrap();
let flags = libc::MS_NOEXEC | libc::MS_NOSUID | libc::MS_NODEV | libc::MS_RDONLY;
let data = ptr::null();
let errno = libc::__errno_location();
*errno = 0;
let ret = libc::mount(source.as_ptr(), target.as_ptr(), fstype.as_ptr(), flags, data);
if ret != 0 || *errno != 0 {
let err = CStr::from_ptr(libc::strerror(*errno));
println!("[sandbox] sys mount(): ({:?}) {:?}", *errno, err);
}
}
unsafe {
let new_root = CString::new(".").unwrap();
let put_old = CString::new(".").unwrap();
let errno = libc::__errno_location();
*errno = 0;
let ret = libc::syscall(libc::SYS_pivot_root, new_root.as_ptr(), put_old.as_ptr());
if ret != 0 || *errno != 0 {
let err = CStr::from_ptr(libc::strerror(*errno));
println!("[sandbox] pivot_root(): ({:?}) {:?}", *errno, err);
}
}
unsafe {
let target = CString::new(".").unwrap();
let errno = libc::__errno_location();
*errno = 0;
let ret = libc::umount2(target.as_ptr(), libc::MNT_DETACH);
if ret != 0 || *errno != 0 {
let err = CStr::from_ptr(libc::strerror(*errno));
println!("[sandbox] umount2(): ({:?}) {:?}", *errno, err);
}
}
env::set_current_dir("/").unwrap();
}
// FIXME: Handle errors
pub fn seccomp() {
unsafe {
let ret = ffi::sandbox();
let errno = *libc::__errno_location();
if ret != 0 || errno != 0 {
let err = CStr::from_ptr(libc::strerror(errno));
println!("[sandbox] Error enabling seccomp: {:?}", err);
}
}
}
|
use std::fs::File;
use std::process;
use gif::SetParameter;
use png::ColorType::{Grayscale, GrayscaleAlpha, RGB, RGBA};
use crate::cmd_options::CmdOptions;
pub struct OutputInfo {
pub width: u32,
pub height: u32,
}
pub fn create_canvas(file: &File, options: &CmdOptions) -> Vec<Vec<(u8, u8, u8)>> {
let (bytes, info) = parse_file(file, options);
let pixels = group_pixels(bytes);
let canvas = reduce_to_codels_and_group_into_rows(pixels, options.codel_size, info.width);
if options.verbose {
eprintln!(
"Creating canvas with {} codels per row and {} rows",
canvas[0].len(),
canvas.len()
);
}
canvas
}
fn parse_file(file: &File, options: &CmdOptions) -> (Vec<u8>, OutputInfo) {
if options.file_path.ends_with(".png") {
return parse_png_file(file, options);
} else if options.file_path.ends_with(".gif") {
return parse_gif_file(file, options);
} else {
eprintln!("Unknown filetype: {}", options.file_path);
process::exit(1);
}
}
fn parse_gif_file(file: &File, options: &CmdOptions) -> (Vec<u8>, OutputInfo) {
let mut decoder = gif::Decoder::new(file);
decoder.set(gif::ColorOutput::RGBA);
let mut reader = match decoder.read_info() {
Ok(reader) => reader,
Err(e) => {
eprintln!("Application error: {}", e);
process::exit(1);
}
};
match reader.next_frame_info() {
Ok(Some(_)) => (),
Ok(None) => {
eprintln!("Application error: No frame data while reading gif");
process::exit(1);
}
Err(e) => {
eprintln!("Application error: {}", e);
process::exit(1);
}
};
let mut data = vec![0; reader.buffer_size()];
match reader.read_into_buffer(&mut data) {
Ok(_) => (),
Err(e) => {
eprintln!("Application error: {}", e);
process::exit(1);
}
};
if options.verbose {
eprintln!(
"Parsed the file as valid GIF (width={}, height={})",
reader.width(),
reader.height()
);
}
let output_info = OutputInfo {
width: reader.width() as u32,
height: reader.height() as u32,
};
(convert_to_rgb(data, png::ColorType::RGBA), output_info)
}
fn parse_png_file(file: &File, options: &CmdOptions) -> (Vec<u8>, OutputInfo) {
let decoder = png::Decoder::new(file);
let (info, mut reader) = match decoder.read_info() {
Ok(decoded) => decoded,
Err(e) => {
eprintln!("Application error: {}", e);
process::exit(1);
}
};
if info.width % options.codel_size != 0 || info.height % options.codel_size != 0 {
eprintln!(
"Application error: codel_size {} does not fit into image dimensions ({}, {})",
options.codel_size, info.width, info.height
);
process::exit(1);
}
let mut data = vec![0; info.buffer_size()];
reader.next_frame(&mut data).unwrap_or_else(|e| {
eprintln!("Application error: {}", e);
process::exit(1);
});
if options.verbose {
eprintln!(
"Parsed the file as valid PNG (width={}, height={})",
info.width, info.height
);
}
let output_info = OutputInfo {
width: info.width,
height: info.height,
};
(convert_to_rgb(data, info.color_type), output_info)
}
fn convert_to_rgb(img_data: Vec<u8>, color_type: png::ColorType) -> Vec<u8> {
match color_type {
RGB => img_data,
RGBA => {
let mut vec = Vec::with_capacity(img_data.len() / 4 * 3);
for rgba in img_data.chunks(4) {
let r = rgba[0];
let g = rgba[1];
let b = rgba[2];
vec.extend([r, g, b].iter().cloned())
}
vec
}
Grayscale => {
let mut vec = Vec::with_capacity(img_data.len() * 3);
for g in img_data {
vec.extend([g, g, g].iter().cloned())
}
vec
}
GrayscaleAlpha => {
let mut vec = Vec::with_capacity(img_data.len() * 3);
for ga in img_data.chunks(2) {
let g = ga[0];
let a = ga[1];
vec.extend([g, g, g, a].iter().cloned())
}
vec
}
_ => unreachable!("uncovered color type"),
}
}
fn group_pixels(bytes: Vec<u8>) -> Vec<(u8, u8, u8)> {
bytes
.chunks_exact(3)
.map(|rgb| (rgb[0], rgb[1], rgb[2]))
.collect::<Vec<_>>()
}
fn reduce_to_codels_and_group_into_rows(
pixels: Vec<(u8, u8, u8)>,
codel_size: u32,
width: u32,
) -> Vec<Vec<(u8, u8, u8)>> {
let codels = pixels
.into_iter()
.step_by(codel_size as usize)
.collect::<Vec<_>>();
codels
.chunks_exact((width / codel_size) as usize)
.step_by(codel_size as usize)
.map(|row| Vec::from(row))
.collect::<Vec<_>>()
}
|
pub struct Solution;
#[derive(Debug, PartialEq, Eq)]
pub struct TreeNode {
pub val: i32,
pub left: Tree,
pub right: Tree,
}
use std::cell::RefCell;
use std::rc::Rc;
type Tree = Option<Rc<RefCell<TreeNode>>>;
impl Solution {
pub fn zigzag_level_order(root: Tree) -> Vec<Vec<i32>> {
let mut res = Vec::new();
let mut trees = vec![root];
let mut reverse = false;
loop {
let mut values = Vec::new();
for tree in &trees {
if tree.is_some() {
values.push(tree.as_ref().unwrap().borrow().val);
}
}
if values.is_empty() {
break;
}
if reverse {
values.reverse();
reverse = false;
} else {
reverse = true;
}
res.push(values);
let mut new_trees = Vec::new();
for tree in trees {
if tree.is_some() {
let node = tree.as_ref().unwrap().borrow();
new_trees.push(node.left.clone());
new_trees.push(node.right.clone());
}
}
trees = new_trees;
}
res
}
}
#[test]
fn test0103() {
fn tree(left: Tree, val: i32, right: Tree) -> Tree {
Some(Rc::new(RefCell::new(TreeNode { val, left, right })))
}
assert_eq!(
Solution::zigzag_level_order(tree(
tree(None, 9, None),
3,
tree(tree(None, 15, None), 20, tree(None, 7, None))
)),
vec![vec![3], vec![20, 9], vec![15, 7],]
);
}
|
use huffman::*;
use binary_writer::*;
use std::io::{Read, Write, Bytes, BufReader};
use std::fs::File;
pub fn read_freq_table<R: Read>(input: &mut Bytes<R>) -> [u64; 256] {
let mut freq_table = [0; 256];
while let Some(Ok(x)) = input.next() {
freq_table[x as usize] += 1;
}
freq_table
}
fn dfs<W: Write>(
node: &Node,
bit_sequence: &mut Vec<bool>,
table: &mut [Vec<bool>],
output: &mut BinaryWriter<W>,
) {
match *node {
Node::Leaf(x) => {
output.write_bit(1);
output.write_u8(x);
table[x as usize] = bit_sequence.clone();
}
Node::Parent {
ref left,
ref right,
} => {
output.write_bit(0);
bit_sequence.push(false);
dfs(left, bit_sequence, table, output);
let index = bit_sequence.len() - 1;
bit_sequence[index] = true;
dfs(right, bit_sequence, table, output);
bit_sequence.pop();
}
}
}
pub fn compress<R: Read, W: Write>(
freq_table: [u64; 256],
input: &mut R,
output: &mut BinaryWriter<W>,
) {
let mut num_bytes = 0;
// -1 if no symbol
// -2 if more than one symbol
// non-negative if only one symbol, = the symbol
let mut single_symbol = -1;
for (symbol, &freq) in freq_table.iter().enumerate() {
if freq > 0 {
num_bytes += freq;
if single_symbol >= 0 {
single_symbol = -2;
} else if single_symbol == -1 {
single_symbol = symbol as i32;
}
}
}
output.write_u64(num_bytes);
if num_bytes == 0 {
return;
}
// whole file consists of the same byte
if single_symbol >= 0 {
output.write_bit(1);
output.write_u8(single_symbol as u8);
return;
}
if let Some(root) = build_tree(freq_table) {
let mut table = vec![vec![]; 256];
let mut bit_sequence = vec![];
dfs(&root, &mut bit_sequence, &mut table, output);
let mut input_bytes = input.bytes();
while let Some(Ok(x)) = input_bytes.next() {
for &bit in &table[x as usize] {
output.write_bit(if bit { 1 } else { 0 });
}
}
}
}
pub fn compress_file<W: Write>(input_file: &str, output: &mut W) -> ::std::io::Result<()> {
let freq_table = {
let f = File::open(input_file)?;
let mut input = BufReader::new(f).bytes();
read_freq_table(&mut input)
};
let f = File::open(input_file)?;
let mut input = BufReader::new(f);
let mut output = BinaryWriter::new(output);
compress(freq_table, &mut input, &mut output);
Ok(())
}
pub fn show_freq_and_dict(input_file: &str) -> ::std::io::Result<()> {
let freq_table = {
let f = File::open(input_file)?;
let mut input = BufReader::new(f).bytes();
read_freq_table(&mut input)
};
if let Some(root) = build_tree(freq_table) {
let mut table = vec![vec![]; 256];
let mut dummy = [0u8; 8 * 1024];
let mut dummy = BinaryWriter::new(&mut dummy[..]);
let mut bit_sequence = vec![];
dfs(&root, &mut bit_sequence, &mut table, &mut dummy);
println!("字母\t\t词频\t赫夫曼编码");
for (symbol, &freq) in freq_table.iter().enumerate() {
if freq > 0 {
println!(
"{:?}\t\t{}\t{}",
String::from_utf8_lossy(&[symbol as u8]),
freq,
code_to_str(&table[symbol])
);
}
}
}
Ok(())
}
fn code_to_str(v: &Vec<bool>) -> String {
let mut r = String::with_capacity(v.len());
for (i, &x) in v.iter().enumerate() {
r.insert(i, if x { '0' } else { '1' });
}
r.to_owned()
}
|
// =========
use std::cmp::{max, min};
use std::collections::{HashMap, HashSet};
use std::process::exit;
const MOD: usize = 1000000007;
pub struct IO<R, W: std::io::Write>(R, std::io::BufWriter<W>);
impl<R: std::io::Read, W: std::io::Write> IO<R, W> {
pub fn new(r: R, w: W) -> IO<R, W> {
IO(r, std::io::BufWriter::new(w))
}
pub fn write<S: std::ops::Deref<Target = str>>(&mut self, s: S) {
use std::io::Write;
self.1.write(s.as_bytes()).unwrap();
}
pub fn read<T: std::str::FromStr>(&mut self) -> T {
use std::io::Read;
let buf = self
.0
.by_ref()
.bytes()
.map(|b| b.unwrap())
.skip_while(|&b| b == b' ' || b == b'\n' || b == b'\r' || b == b'\t')
.take_while(|&b| b != b' ' && b != b'\n' && b != b'\r' && b != b'\t')
.collect::<Vec<_>>();
unsafe { std::str::from_utf8_unchecked(&buf) }
.parse()
.ok()
.expect("Parse error.")
}
pub fn vec<T: std::str::FromStr>(&mut self, n: u8) -> Vec<T> {
(0..n).map(|_| self.read()).collect()
}
pub fn chars(&mut self) -> Vec<char> {
self.read::<String>().chars().collect()
}
}
// =========
fn directed_hierholder(
adjl: &mut HashMap<(u8, u8), Vec<(u8, u8)>>,
start: (u8, u8),
) -> Option<Vec<(u8, u8)>> {
let mut res_circuit: Vec<(u8, u8)> = vec![];
let mut trail_stack: Vec<(u8, u8)> = vec![start];
let mut cur_v: (u8, u8) = start;
while trail_stack.len() > 0 {
if adjl.get_mut(&cur_v).unwrap().len() > 0 {
trail_stack.push(cur_v);
match adjl.get_mut(&cur_v) {
Some(n_list) => match n_list.pop() {
Some(n) => cur_v = n,
None => (),
},
None => (),
}
} else {
res_circuit.push(cur_v);
match trail_stack.pop() {
Some(p) => cur_v = p,
None => return None,
}
}
}
// 有向なのでひっくりかえす
res_circuit.reverse();
Some(res_circuit)
}
fn main() {
let (r, w) = (std::io::stdin(), std::io::stdout());
let mut sc = IO::new(r.lock(), w.lock());
let n: usize = sc.read();
let mut deg = HashMap::<(u8, u8), isize>::new();
// tuple のMapを初期化
let mut adjl = {
let mut adtmp = HashMap::<(u8, u8), Vec<(u8, u8)>>::new();
for i in 0..255 {
for j in 0..255 {
adtmp.insert((i, j), vec![]);
}
}
adtmp
};
// input を受け取る
for _ in 0..n {
let s: String = sc.read();
let s = s.as_bytes();
let start = (s[0], s[1]);
let end = (s[s.len() - 2], s[s.len() - 1]);
match adjl.get_mut(&start) {
Some(l) => l.push(end),
None => {
adjl.insert(start, vec![end]);
}
}
match deg.get_mut(&start) {
Some(d) => *d += 1,
None => {
deg.insert(start, 1);
}
}
match deg.get_mut(&end) {
Some(d) => *d += -1,
None => {
deg.insert(end, -1);
}
}
}
// 始点を決める
let start: (u8, u8) = {
let mut s: (u8, u8) = (std::u8::MAX, std::u8::MAX);
for (n, d) in ° {
if *d == 1 {
if s != (std::u8::MAX, std::u8::MAX) {
println!("NO");
exit(0);
}
s = *n;
} else if d.abs() > 1 {
println!("NO");
exit(0);
}
}
if deg.get(&s) == None {
*deg.iter().next().unwrap().0
} else {
s
}
};
match directed_hierholder(&mut adjl, start) {
Some(w) => {
if w.len() != n + 1 {
println!("NO");
exit(0);
}
println!("YES");
let mut pass = String::new();
for s in w.iter() {
pass.push(s.0 as char);
}
pass.push(w[w.len() - 1].1 as char);
println!("{}", pass);
}
None => {
println!("NO");
}
}
}
|
use std::io::prelude::*;
fn main() {
println!("Starting server...");
let server = std::net::TcpListener::bind("127.0.0.1:8080").unwrap();
println!("Server is up {:?}", server);
loop {
match server.accept() {
Ok((mut stream, origin)) => {
let mut buffer = [0; 1024];
let n = stream.read(&mut buffer).unwrap();
let str = std::str::from_utf8(&buffer[0..(n - 1)]).unwrap();
println!("{}, {}\n{}\n===================\n", n, origin, str);
if str == "exit" {
break;
}
}
Err(e) => {
println!("{:?}", e);
break;
}
}
}
println!("Tearing down server");
}
|
macro_rules! syntax_error {
($($arg:tt)*) => (
return Err(BadSyntax(format!("{}: {}", $($arg)*)))
)
}
pub mod interpreter;
pub mod value;
pub mod error;
mod data;
mod base;
mod reader;
mod env;
mod machine;
use scheme::error::LispError;
pub const UNDERSCORE: &str = "_";
pub const ELLIPSIS: &str = "...";
pub type LispResult<T> = Result<T, LispError>;
|
#![warn(clippy::all)]
#![warn(clippy::pedantic)]
use factorial::Factorial;
fn main() {
run();
}
#[allow(clippy::cast_possible_truncation)]
#[allow(clippy::similar_names)]
fn run() {
let start = std::time::Instant::now();
// code goes here
let digits = nth_lexicographic_permutation(999_999, &mut vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
// convert digits to integer
let mut res = 0;
for digit in digits {
res *= 10;
res += digit;
}
let span = start.elapsed().as_nanos();
println!("{} {}", res, span);
}
#[allow(clippy::similar_names)]
#[allow(clippy::cast_possible_truncation)]
fn nth_lexicographic_permutation(n: u64, set: &mut Vec<u64>) -> Vec<u64> {
let mut res = vec![];
let mut idx = n;
while !set.is_empty() {
let perms = (set.len() - 1).factorial() as u64;
let ridx = idx / perms;
idx %= perms;
res.push(set.remove(ridx as usize));
}
res
}
#[cfg(test)]
mod tests {
use super::nth_lexicographic_permutation;
#[test]
fn it_works() {
assert_eq!(
vec![0, 1, 2],
nth_lexicographic_permutation(0, &mut vec![0, 1, 2])
);
assert_eq!(
vec![0, 2, 1],
nth_lexicographic_permutation(1, &mut vec![0, 1, 2])
);
assert_eq!(
vec![1, 0, 2],
nth_lexicographic_permutation(2, &mut vec![0, 1, 2])
);
assert_eq!(
vec![1, 2, 0],
nth_lexicographic_permutation(3, &mut vec![0, 1, 2])
);
assert_eq!(
vec![2, 0, 1],
nth_lexicographic_permutation(4, &mut vec![0, 1, 2])
);
assert_eq!(
vec![2, 1, 0],
nth_lexicographic_permutation(5, &mut vec![0, 1, 2])
);
}
}
|
use std::cmp;
use petgraph::{Graph, Directed};
use petgraph::visit::GetAdjacencyMatrix;
use super::graph::{Node, Edge};
use super::cycle_removal::remove_cycle;
use super::ranking::{RankingModule, LongetPathRanking};
use super::crossing_reduction::crossing_reduction;
use super::position_assignment::brandes::brandes;
use super::normalize::normalize;
pub trait Setting {
fn node_width<N>(&self, node: N) -> usize;
fn node_height<N>(&self, node: N) -> usize;
}
pub struct SugiyamaLayout<R = LongetPathRanking>
where
R: RankingModule,
{
ranking_module: R,
}
impl SugiyamaLayout {
pub fn new() -> SugiyamaLayout<LongetPathRanking> {
SugiyamaLayout { ranking_module: LongetPathRanking::new() }
}
}
impl<R: RankingModule> SugiyamaLayout<R> {
pub fn call<N, E>(&self, input: &Graph<N, E, Directed>) -> Graph<Node, Edge> {
let mut graph = input.map(|_, _| Node::new(), |_, _| Edge::new());
remove_cycle(&mut graph);
let mut layers_map = self.ranking_module.call(&graph);
normalize(&mut graph, &mut layers_map);
let height = 1 +
graph.node_indices().fold(0, |max, u| {
cmp::max(max, *layers_map.get(&u).unwrap())
});
let mut layers: Vec<_> = (0..height).map(|_| vec![]).collect();
for u in graph.node_indices() {
let layer = layers_map.get(&u).unwrap();
layers[*layer].push(u);
}
let matrix = graph.adjacency_matrix();
for i in 1..height {
let h1 = layers.get_mut(i - 1).unwrap().clone();
let mut h2 = layers.get_mut(i).unwrap();
crossing_reduction(&graph, &matrix, &h1, &mut h2);
}
for (i, layer) in layers.iter().enumerate() {
for (j, &u) in layer.iter().enumerate() {
graph[u].width = 100;
graph[u].height = 100;
graph[u].orig_width = 100;
graph[u].orig_height = 100;
graph[u].layer = i;
graph[u].order = j;
}
}
brandes(&mut graph, &layers);
graph
}
}
#[cfg(test)]
mod tests {
use petgraph::Graph;
use super::*;
struct MySetting;
impl Setting for MySetting {
fn node_width<N>(&self, node: N) -> usize {
10
}
fn node_height<N>(&self, node: N) -> usize {
10
}
}
#[test]
fn test_sugiyama_layout() {
let mut graph = Graph::new();
let a1 = graph.add_node("a1");
let a2 = graph.add_node("a2");
let a3 = graph.add_node("a3");
let b1 = graph.add_node("b1");
let b2 = graph.add_node("b2");
let b3 = graph.add_node("b3");
let c1 = graph.add_node("c1");
let c2 = graph.add_node("c2");
let c3 = graph.add_node("c3");
let d1 = graph.add_node("d1");
let d2 = graph.add_node("d2");
let d3 = graph.add_node("d3");
graph.add_edge(a1, b2, "");
graph.add_edge(a2, b1, "");
graph.add_edge(a3, b1, "");
graph.add_edge(b1, c1, "");
graph.add_edge(b2, c1, "");
graph.add_edge(b2, c2, "");
graph.add_edge(b2, c3, "");
graph.add_edge(b3, c2, "");
graph.add_edge(c1, d3, "");
graph.add_edge(c2, d1, "");
graph.add_edge(c2, d2, "");
let sugiyama_layout = SugiyamaLayout::new();
let result = sugiyama_layout.call(&graph);
for u in result.node_indices() {
println!("{} {}", result[u].x, result[u].y);
}
}
}
|
use core::{Model, Material, RayIntersection, Ray, RayIntersectionError};
use defs::{Point3, Vector3, FloatType};
use tools::{CompareWithTolerance};
use na;
use na::{Unit};
use std;
use uuid::{Uuid};
pub struct SolidSphere {
material: Material,
origo: Point3,
radius: FloatType,
identifier: Uuid
}
impl SolidSphere {
pub fn new(material: Material) -> Self {
Self { material: material,
origo: Point3::new(0.0, 0.0, 0.0),
radius: 1.0,
identifier: Uuid::new_v4()}
}
pub fn new_positioned(material: Material, origo: Point3, radius: FloatType) -> Self {
Self { material: material,
origo: origo,
radius: radius,
identifier: Uuid::new_v4()}
}
pub fn set_custom_identifier(&mut self, identifier: Uuid) {
self.identifier = identifier;
}
}
impl Model for SolidSphere {
fn get_intersection(&self, ray: &Ray) -> Option<RayIntersection> {
let dir = ray.get_direction();
let origin = ray.get_origin();
let ray_origo = origin - self.origo;
let a = dir.x.powi(2) + dir.y.powi(2) + dir.z.powi(2);
let b = 2.0 * (ray_origo.x * dir.x + ray_origo.y * dir.y + ray_origo.z * dir.z);
let c = ray_origo.x.powi(2) + ray_origo.y.powi(2) + ray_origo.z.powi(2) - self.radius.powi(2);
let determinant = b.powi(2) - 4.0 * a * c;
if determinant.less_eps(&0.0) {
None
} else {
let t1 = (-b + determinant.sqrt()) / (2.0 * a);
let t2 = (-b - determinant.sqrt()) / (2.0 * a);
let result_calc = |t, inside: bool| {
let intersection_point = origin + dir * t;
let normal = if !inside { intersection_point - self.origo } else { self.origo - intersection_point };
match RayIntersection::new_model_identifier(normal, intersection_point, ray, self.material, inside, self.identifier) {
Ok(intersection) => Some(intersection),
Err(RayIntersectionError::NoRayTravelDistance) => None,
_ => panic!("Unrecoverable RayIntersectin:new_model_identifier error")
}
};
if t1.is_sign_negative() && t2.is_sign_negative() {
None
} else if t1.is_sign_positive() && t2.is_sign_negative() {
result_calc(t1, true)
} else {
match result_calc(t2, false) {
Some(result) => Some(result),
None => result_calc(t1, true),
}
}
}
}
}
pub struct SolidPlane {
material: Material,
base: Point3,
normal: Vector3,
identifier: Uuid,
}
impl SolidPlane {
pub fn new(material: Material) -> Self {
Self { material: material,
base: Point3::origin(),
normal: Vector3::new(0.0, 0.0, 1.0),
identifier: Uuid::new_v4()
}
}
pub fn new_positioned(material: Material, base: Point3, normal: Unit<Vector3>) -> Self {
Self { material: material,
base: base,
normal: normal.unwrap(),
identifier: Uuid::new_v4()
}
}
pub fn set_custom_identifier(&mut self, identifier: Uuid) {
self.identifier = identifier;
}
}
impl Model for SolidPlane {
fn get_intersection(&self, ray: &Ray) -> Option<RayIntersection> {
let origin = ray.get_origin();
let dir = ray.get_direction();
let u = self.normal.dot(dir);
if !u.near_zero_eps() {
let k = self.normal.x * self.base.x + self.normal.y * self.base.y + self.normal.z * self.base.z;
let s = self.normal.x * origin.x + self.normal.y * origin.y + self.normal.z * origin.z;
let t = (k-s) / u;
if t.greater_eq_eps(&0.0) {
let is_inside = na::angle(&self.normal, dir).less_eq_eps(&std::f64::consts::FRAC_PI_2);
let point = origin + dir * t;
if !is_inside {
match RayIntersection::new_model_identifier(self.normal, point, ray, self.material, is_inside, self.identifier) {
Ok(intersection) => Some(intersection),
Err(RayIntersectionError::NoRayTravelDistance) => None,
_ => panic!("Unrecoverable RayIntersectin:new_model_identifier error")
}
} else {
match RayIntersection::new_model_identifier(-self.normal, point, ray, self.material, is_inside, self.identifier) {
Ok(intersection) => Some(intersection),
Err(RayIntersectionError::NoRayTravelDistance) => None,
_ => panic!("Unrecoverable RayIntersectin:new_model_identifier error")
}
}
} else {
None
}
} else {
None
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use core::Color;
fn test_solid_unit_sphere(test_ray: &Ray, expected_result: Option<&Point3>) {
let test_material = Material::new_shiny(Color::new(1.0, 1.0, 1.0), (Color::new(1.0, 1.0, 1.0), 1.5), None);
let test_sphere = SolidSphere::new(test_material);
let intersection_result = test_sphere.get_intersection(test_ray);
match expected_result {
Some(expected_point) => {
let intersection = intersection_result.expect("Was expected intersection but none intersected");
assert_relative_eq!(expected_point, intersection.get_intersection_point());
},
None => {
assert!(intersection_result.is_none());
}
}
}
#[test]
fn test_solid_unit_sphere_head_on() {
let test_ray = Ray::new_single_shot(Point3::new(2.0, 0.0, 0.0), Vector3::new(-1.0, 0.0, 0.0));
test_solid_unit_sphere(&test_ray, Some(&Point3::new(1.0, 0.0, 0.0)));
}
#[test]
fn test_solid_unit_sphere_tangential_hit() {
let test_ray = Ray::new_single_shot(Point3::new(2.0, 0.0, 1.0), Vector3::new(-1.0, 0.0, 0.0));
test_solid_unit_sphere(&test_ray, Some(&Point3::new(0.0, 0.0, 1.0)));
}
#[test]
fn test_solid_unit_sphere_tangential_miss() {
let test_ray = Ray::new_single_shot(Point3::new(2.0, 0.0, 1.01), Vector3::new(-1.0, 0.0, 0.0));
test_solid_unit_sphere(&test_ray, None);
}
} |
extern crate nom;
use std::collections::HashSet;
pub mod abssyn;
use self::abssyn::*;
pub mod substitution;
use self::substitution::*;
pub mod parser;
use self::parser::*;
#[derive(Clone, Debug, PartialEq, Eq)]
enum FContextElem {
HasType(String, FType),
TyVar(String),
}
fn typeinfer(ctx: &[FContextElem], term: FTermChurch) -> Option<FType> {
use self::FTermChurch::*;
match term {
Var(x) => {
ctx.iter().filter_map(|e| if let FContextElem::HasType(y, ty) = e { Some((y, ty)) } else { None }).find(|(y, _)| x == **y).map(|(_, ty)| ty.clone())
},
Lam(x, y, z) => {
let mut ctx = ctx.to_vec();
ctx.push(FContextElem::HasType(x, *y.clone()));
typeinfer(&ctx, *z).map(|w| arr(*y, w))
},
App(x, y) => {
typeinfer(ctx, *x).and_then(|t| typeinfer(ctx, *y).and_then(|b| {
if let FType::Arr(_, b2) = &t { if b == **b2 { return Some(b); } }
None
}))
},
TLam(x, y) => {
let mut ctx = ctx.to_vec();
ctx.push(FContextElem::TyVar(x.clone()));
typeinfer(&ctx, *y).map(|b| forall(x, b))
},
TApp(x, y) => {
if let Some(FType::Forall(a, b)) = typeinfer(ctx, *x) {
Some(substtyvar_ty(&a, *y, *b))
} else {
None
}
},
}
}
fn smallstep(term: FTermChurch) -> Option<FTermChurch> {
use self::FTermChurch::*;
match term {
Var(_) => None,
Lam(_, _, _) => None,
App(e1, e2) => {
if !e1.is_value() { let r = smallstep(*e1.clone()).map(|x| app(x, *e2.clone())); if r.is_some() { return r; } }
if !e2.is_value() { let r = smallstep(*e2.clone()).map(|x| app(*e1.clone(), x)); if r.is_some() { return r; } }
match *e1 {
Lam(x, _, z) => return Some(substvar_term(&x, *e2, *z)),
_ => (),
}
None
}
TLam(x, y) => smallstep(*y).map(|t| tlam(x, t)),
TApp(x, y) => match *x {
TLam(a, b) => Some(substtyvar_term(&a, *y, *b)),
_ => None
}
}
}
#[test]
fn test_evaluation() {
let succ = var("succ");
let nat = tvar("nat");
let double = { let x = tvar("X"); tlam("X", lam("f", arr(x.clone(), x.clone()), lam("a", x.clone(), app(var("f"), app(var("f"), var("a")))))) };
let example = { app(tapp(double.clone(), nat.clone()), lam("x", nat, app(succ.clone(), app(succ.clone(), var("x"))))) };
println!("double = {}", double);
let x_arr_x = arr(tvar("X"), tvar("X"));
let tdouble = forall("X", arr(x_arr_x.clone(), x_arr_x.clone()));
let inferred = typeinfer(&[], double.clone());
println!("typeinfer result for double: {:?}", inferred.clone().map(|x| format!("{}", x)));
println!("expected type of double = {}, equivalent to inferred: {}", tdouble.clone(), inferred == Some(tdouble));
println!("example = {}", example);
let natctx = [FContextElem::TyVar("nat".into()), FContextElem::HasType("succ".into(), arr(tvar("nat"), tvar("nat")))];
println!("natctx = {:?}", natctx);
println!("typeinfer result for example: {:?}", typeinfer(&natctx, example.clone()).map(|x| format!("{}", x)));
let idnat = lam("x", tvar("nat"), var("x"));
let mut tmp = Some(app(idnat, app(example, var("0"))));
while let Some(old) = tmp {
let new = smallstep(old.clone());
println!("{} --> {:?}", old, new.clone().map(|x| format!("{}", x)));
tmp = new;
}
}
fn main() {
use std::io;
let mut ctx = vec![];
ctx.push(FContextElem::TyVar("nat".into()));
ctx.push(FContextElem::HasType("0".into(), tvar("nat")));
ctx.push(FContextElem::HasType("succ".into(), arr(tvar("nat"), tvar("nat"))));
loop {
let mut line = String::new();
let len = io::stdin().read_line(&mut line).unwrap();
if len == 0 { break; }
println!("Got {:?}", line);
if let Ok((_, term)) = parse_term(line.as_bytes()) {
println!("Parsed as {:?}", term);
if let Some(ty) = typeinfer(&ctx, term.clone()) {
println!("It typechecks as {}", ty);
let mut tmp = Some(term);
while let Some(old) = tmp {
let new = smallstep(old.clone());
println!("{} --> {:?}", old, new.clone().map(|x| format!("{}", x)));
tmp = new;
}
}
}
}
}
|
use crate::models::apod::Apod;
use crate::services::DB;
use chrono::NaiveDate;
use sqlx::postgres::PgQueryResult;
#[derive(Debug, sqlx::FromRow)]
pub struct DBApod {
pub id: i32,
pub publish_date: NaiveDate,
pub explanation: String,
pub title: String,
pub hdurl: String,
pub copyright: Option<String>,
pub dispatched: bool,
}
impl Default for DBApod {
fn default() -> Self {
DBApod {
id: 0,
publish_date: NaiveDate::from_ymd(2003, 12, 31),
explanation: "".to_string(),
title: "".to_string(),
hdurl: "".to_string(),
copyright: None,
dispatched: false,
}
}
}
impl From<&Apod> for DBApod {
fn from(a: &Apod) -> Self {
DBApod {
id: 0,
publish_date: NaiveDate::parse_from_str(a.date.as_str(), "%Y-%m-%d").unwrap(),
explanation: a.explanation.clone(),
title: a.title.clone(),
hdurl: a.hdurl.clone(),
copyright: a.copyright.clone(),
dispatched: false,
}
}
}
impl DB {
pub async fn get_most_recent_apod(&self) -> DBApod {
sqlx::query_as("SELECT * FROM astra.apod ORDER BY publish_date DESC LIMIT 1")
.fetch_one(&self.pool)
.await
.unwrap()
}
pub async fn get_apod_dispatched(&self, a: &mut DBApod) {
let res: DBApod = sqlx::query_as("SELECT * FROM astra.apod WHERE publish_date = $1;")
.bind(a.publish_date)
.fetch_optional(&self.pool)
.await
.unwrap()
.unwrap_or_default();
a.dispatched = res.dispatched;
}
pub async fn set_apod(&self, a: &DBApod) -> Result<PgQueryResult, sqlx::Error> {
sqlx::query(
"INSERT INTO astra.apod (publish_date, explanation, \
title, hdurl, copyright, dispatched) \
VALUES ($1, $2, $3, $4, $5, $6);",
)
.bind(&a.publish_date)
.bind(&a.explanation)
.bind(&a.title)
.bind(&a.hdurl)
.bind(&a.copyright)
.bind(&a.dispatched)
.execute(&self.pool)
.await
}
}
|
//! Osu skin directory parser module
// TODO add support for hd textures (scaling shouldn't be an issue, just finding them and loading
// them which shouldn't be hard but I'm just lazy
use graphics::{
draw_state::{self, DrawState},
image::Image,
math, Graphics,
};
use texture::{CreateTexture, Format, ImageSize, TextureSettings, TextureOp};
use std::{
collections::HashMap, error, fmt, fs::File, io::BufRead, io::BufReader, path, rc::Rc, str, time,
};
use crate::judgement::Judgement;
use super::{ParseError, GameSkin};
#[derive(Copy, Clone, Debug)]
enum NoteBodyStyle {
Stretch,
CascadeFromTop,
CascadeFromBottom,
}
impl str::FromStr for NoteBodyStyle {
type Err = NoteBodyStyleParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"0" => Ok(NoteBodyStyle::Stretch),
"1" => Ok(NoteBodyStyle::CascadeFromTop),
"2" => Ok(NoteBodyStyle::CascadeFromBottom),
_ => Err(NoteBodyStyleParseError),
}
}
}
#[derive(Copy, Clone, Debug)]
struct NoteBodyStyleParseError;
impl fmt::Display for NoteBodyStyleParseError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Invalid NoteBodyStyle variant")
}
}
#[derive(Copy, Clone, Debug)]
enum HitAnimState {
SingleNote(time::Instant),
LongNote(time::Instant),
/// Time when the animation started, and time when the animation was told to
/// finish whatever is left.
LongNoteFinal(time::Instant, time::Instant),
None,
}
/// Holds skin data, such as note images and what not.
struct OsuSkinTextures<T> {
miss: Rc<[Rc<T>]>,
hit50: Rc<[Rc<T>]>,
hit100: Rc<[Rc<T>]>,
hit200: Rc<[Rc<T>]>,
hit300: Rc<[Rc<T>]>,
hit300g: Rc<[Rc<T>]>,
/// The animation played when a single note is pressed
lighting_n: Rc<[Rc<T>]>,
/// The animation played when a long note is pressed
lighting_l: Rc<[Rc<T>]>,
/// The images virtual keys under the judgement line.
keys: [Rc<T>; 7],
/// The images of the virtual keys under the judgement line when the
/// corresponding key on the keyboard is pressed.
keys_d: [Rc<T>; 7],
/// The notes' images.
notes: [Rc<[Rc<T>]>; 7],
/// The long notes' ends' images.
long_notes_head: [Rc<[Rc<T>]>; 7],
/// The long notes' bodies' images.
long_notes_body: [Rc<[Rc<T>]>; 7],
/// The long notes' tails' images.
long_notes_tail: [Option<Rc<[Rc<T>]>>; 7],
/// The stage light animation images
stage_light: Rc<[Rc<T>]>,
/// The stage components.
stage_hint: Rc<[Rc<T>]>,
stage_left: Rc<T>,
stage_right: Rc<T>,
stage_bottom: Option<Rc<[Rc<T>]>>,
}
/// Various information related to how to draw components. All the numbers are
/// taken unmodified from the skin.ini file. Scaling happens in the drawing
/// functions.
struct OsuSkinConfig {
column_start: u16,
column_width: [u16; 7],
column_spacing: [u16; 6],
column_line_width: [u16; 8],
colour_column_line: [u8; 4],
hit_position: u16,
score_position: u16,
light_position: u16,
width_for_note_height_scale: f64,
note_body_style: [NoteBodyStyle; 7],
colour_light: [[u8; 3]; 7],
// TODO
// lighting_n_width: [u16; 7],
// lighting_l_width: [u16; 7],
// combo_position: u16,
// judgement_line: bool,
// low priority
// special_style: SpecialStyle,
// keys_under_notes: bool,
}
struct OsuAnimStates {
keys_last_down_time: [Option<time::Instant>; 7],
hit_anim: [HitAnimState; 7],
}
struct OsuSkin<G: Graphics> {
textures: OsuSkinTextures<G::Texture>,
config: OsuSkinConfig,
anim_states: OsuAnimStates,
/// judgement, time of first frame
judgement: Option<(Judgement, time::Instant)>,
}
impl<G: Graphics> GameSkin<G> for OsuSkin<G> {
fn draw_play_scene(
&mut self,
transform: math::Matrix2d,
g: &mut G,
stage_height: f64,
keys_down: &[bool; 7],
// column index, start pos, end pos
notes: &[(usize, f64, Option<f64>)],
) {
let draw_state = &DrawState::default();
self.draw_track(draw_state, transform, g, stage_height);
self.draw_keys(draw_state, transform, g, stage_height, keys_down);
for &(column, pos, end_pos) in notes {
if let Some(end_p) = end_pos {
self.draw_long_note(draw_state, transform, g, stage_height, pos, end_p, column);
} else {
self.draw_note(draw_state, transform, g, stage_height, pos, column);
}
}
self.draw_hit_anims(
&DrawState::default().blend(draw_state::Blend::Add),
transform,
g,
stage_height,
);
// Draw judgement
if let Some((judgement, time)) = self.judgement {
let elapsed = time.elapsed();
if elapsed <= time::Duration::from_millis(200) {
// the "burst" animation
let scale = if elapsed <= time::Duration::from_millis(50) {
1.5 - elapsed.subsec_nanos() as f64 / 50_000_000.0 / 2.0
} else if elapsed <= time::Duration::from_millis(160) {
1.0
} else {
1.0 - (elapsed.subsec_nanos() - 160_000_000) as f64 / 150_000_000.0
};
match judgement {
Judgement::Miss => self.draw_miss(draw_state, transform, g, stage_height),
Judgement::Bad => remani_warn!("draw Bad judgement is not implemented for osu skin"), // TODO
Judgement::Good => remani_warn!("draw Bad judgement is not implemented for osu skin"),
Judgement::Perfect => {
self.draw_perfect(draw_state, transform, scale, g, stage_height, elapsed)
}
};
} else {
self.judgement = None;
}
}
}
fn draw_judgement(&mut self, _column: usize, judgement: Judgement) {
self.judgement = Some((judgement, time::Instant::now()));
}
fn key_down(&mut self, column: usize) {
self.anim_states.keys_last_down_time[column] = None;
}
fn key_up(&mut self, column: usize) {
self.anim_states.keys_last_down_time[column] = Some(time::Instant::now());
}
fn single_note_hit_anim(&mut self, column: usize) {
self.anim_states.hit_anim[column] = HitAnimState::SingleNote(time::Instant::now());
}
fn long_note_hit_anim_start(&mut self, column: usize) {
self.anim_states.hit_anim[column] = HitAnimState::LongNote(time::Instant::now());
}
fn long_note_hit_anim_stop(&mut self, column: usize) {
match self.anim_states.hit_anim[column] {
HitAnimState::LongNote(time) => self.anim_states.hit_anim[column] = HitAnimState::LongNoteFinal(time, time::Instant::now()),
_ => (),
}
}
}
impl<G: Graphics> OsuSkin<G> {
fn draw_note(
&self,
draw_state: &DrawState,
transform: math::Matrix2d,
g: &mut G,
stage_h: f64,
pos: f64,
column_index: usize,
) {
// TODO mania-note is animatable
let scale = stage_h / 480.0;
let hit_p = self.config.hit_position as f64 * scale;
let note_w = self.config.column_width[column_index] as f64 * scale;
let note_h = self.config.width_for_note_height_scale * scale;
// Calculate X position from column start, column width sum, and column spacing sum up to
// column_index
let note_x = scale
* (self.config.column_start as f64
+ self.config.column_width[0..column_index]
.iter()
.sum::<u16>() as f64
+ self.config.column_spacing[0..column_index]
.iter()
.sum::<u16>() as f64);
let note_y = hit_p * (1.0 - pos) - note_h;
let note = &*self.textures.notes[column_index][0];
let note_img = Image::new().rect([note_x, note_y, note_w, note_h]);
note_img.draw(note, draw_state, transform, g);
}
fn draw_long_note(
&self,
draw_state: &DrawState,
transform: math::Matrix2d,
g: &mut G,
stage_h: f64,
pos: f64,
end_pos: f64,
column_index: usize,
) {
// TODO mania-note#L is animatable
let scale = stage_h / 480.0;
let scale2 = stage_h / 768.0; // long note body height when cascading is scaled with this
let hit_p = self.config.hit_position as f64 * scale;
let note_w = self.config.column_width[column_index] as f64 * scale;
// Calculate X position from column start, column width sum, and column spacing sum up to
// column_index
let note_x = scale
* (self.config.column_start as f64
+ self.config.column_width[0..column_index]
.iter()
.sum::<u16>() as f64
+ self.config.column_spacing[0..column_index]
.iter()
.sum::<u16>() as f64);
// Theoretical long note bottom
let real_bottom_y = hit_p * (1.0 - pos);
// Long note bottom but clamped at the hit position/judgement line
// TODO Don't clamp if the long note isn't being held
let bottom_y = if pos < 0.0 { hit_p } else { real_bottom_y };
let top_y = hit_p * (1.0 - end_pos);
let note_head = &*self.textures.long_notes_head[column_index][0];
let note_tail = self.textures.long_notes_tail[column_index].as_ref().map(|v| &*v[0]);
let note_body = &*self.textures.long_notes_body[column_index][0];
let note_body_h = note_body.get_height() as f64 * scale2;
let note_end_h = self.config.width_for_note_height_scale * scale;
let note_head_y = bottom_y - note_end_h;
let note_tail_y = top_y - note_end_h;
let note_head_img = Image::new().rect([note_x, note_head_y, note_w, note_end_h]);
let note_tail_img = Image::new().rect([note_x, note_tail_y, note_w, note_end_h]);
match self.config.note_body_style[column_index] {
// Note body image is stretched to the height of the note
NoteBodyStyle::Stretch => {
let note_body_img = Image::new()
.src_rect([
0.0,
0.0,
note_body.get_width() as f64,
((bottom_y - top_y) / (real_bottom_y - top_y)
* (note_body.get_height() as f64)),
]).rect([
note_x,
top_y - note_end_h / 2.0,
note_w,
bottom_y - top_y,
]);
note_body_img.draw(note_body, draw_state, transform, g);
}
// Note body image is repeated, starting from the top
NoteBodyStyle::CascadeFromTop => {
let mut rect = [note_x, top_y - note_end_h / 2.0, note_w, note_body_h];
let mut i = 0.0;
let mut note_body_img = Image::new();
while i < bottom_y - top_y - note_body_h {
note_body_img = note_body_img.rect(rect);
note_body_img.draw(note_body, draw_state, transform, g);
rect[1] += note_body_h;
i += note_body_h;
}
let mut mod_rect = rect;
mod_rect[3] = bottom_y - top_y - i;
let src_rect = [0.0, 0.0, note_body.get_width() as f64, mod_rect[3]];
note_body_img = note_body_img.src_rect(src_rect).rect(mod_rect);
note_body_img.draw(note_body, draw_state, transform, g);
}
// Note body image is repeated, starting from the bottom
NoteBodyStyle::CascadeFromBottom => {
let mut rect = [note_x, top_y - note_end_h / 2.0, note_w, note_body_h];
let mut note_body_img = Image::new();
let offset = (real_bottom_y - top_y) % note_body_h;
let mut mod_rect = rect;
mod_rect[3] = offset;
let src_rect = [
0.0,
offset / scale2,
note_body.get_width() as f64,
-(mod_rect[3] / scale2),
];
note_body_img = note_body_img.src_rect(src_rect).rect(mod_rect);
note_body_img.draw(note_body, draw_state, transform, g);
note_body_img = Image::new();
rect[1] += offset;
let mut i = offset;
// The rectangle is upside down to simplify the thinking, and the image source
// rectangle is also upside down so it's fine
let upside_down_rect = [
0.0,
note_body.get_height() as f64,
note_body.get_width() as f64,
-(note_body.get_height() as f64),
];
while i < bottom_y - top_y - note_body_h {
note_body_img = note_body_img.src_rect(upside_down_rect).rect(rect);
note_body_img.draw(note_body, draw_state, transform, g);
rect[1] += note_body_h;
i += note_body_h;
}
mod_rect = rect;
mod_rect[3] = bottom_y - top_y - i;
let src_rect = [
0.0,
note_body.get_height() as f64,
note_body.get_width() as f64,
-mod_rect[3],
];
note_body_img = note_body_img.src_rect(src_rect).rect(mod_rect);
note_body_img.draw(note_body, draw_state, transform, g);
let note_body_img =
Image::new().rect([note_x, top_y - note_end_h / 2.0, note_w, bottom_y - top_y]);
note_body_img.draw(note_body, draw_state, transform, g);
}
}
note_head_img.draw(note_head, draw_state, transform, g);
// If there's a separate note tail image, use it, otherwise, flip the note head image and
// use it
if let Some(note_tail) = note_tail {
note_tail_img.draw(note_tail, draw_state, transform, g);
} else {
note_tail_img
.src_rect([
0.0,
note_head.get_height() as f64,
note_head.get_width() as f64,
-(note_head.get_height() as f64),
]).draw(note_head, draw_state, transform, g);
}
}
fn draw_track(
&self,
draw_state: &DrawState,
transform: math::Matrix2d,
g: &mut G,
stage_h: f64,
) {
// TODO mania-stage-bottom, mania-stage-light, and mania-stage-hint are all animatable
let scale = stage_h / 480.0;
// Apparently some things are based on a height of 480, and other things are based on a
// height of 768. .-.
let scale2 = stage_h / 768.0;
let column_width_sum = (self.config.column_width.iter().sum::<u16>() as f64
+ self.config.column_spacing.iter().sum::<u16>() as f64)
* scale;
let column_start = self.config.column_start as f64 * scale;
let stage_hint_height = self.textures.stage_hint[0].get_height() as f64 * scale;
let stage_l_width = self.textures.stage_left.get_width() as f64 * scale2;
let stage_r_width = self.textures.stage_right.get_width() as f64 * scale2;
let stage_l_img =
Image::new().rect([column_start - stage_l_width, 0.0, stage_l_width, stage_h]);
let stage_r_img =
Image::new().rect([column_start + column_width_sum, 0.0, stage_r_width, stage_h]);
let stage_hint_img = Image::new().rect([
column_start,
self.config.hit_position as f64 * scale - stage_hint_height / 2.0,
column_width_sum,
stage_hint_height,
]);
stage_hint_img.draw(
&*self.textures.stage_hint[0],
draw_state,
transform,
g,
);
stage_l_img.draw(&*self.textures.stage_left, draw_state, transform, g);
stage_r_img.draw(&*self.textures.stage_right, draw_state, transform, g);
if let Some(ref v) = self.textures.stage_bottom {
let stage_bottom = &*v[0];
let stage_b_width = stage_bottom.get_width() as f64 * scale;
let stage_b_height = stage_bottom.get_height() as f64 * scale;
let stage_b_img = Image::new().rect([
column_start + column_width_sum / 2.0 - stage_b_width / 2.0,
stage_h - stage_b_height,
stage_b_width,
stage_b_height,
]);
stage_b_img.draw(stage_bottom, draw_state, transform, g);
}
}
fn draw_keys(
&self,
draw_state: &DrawState,
transform: math::Matrix2d,
g: &mut G,
stage_h: f64,
pressed: &[bool; 7],
) {
let scale = stage_h / 480.0;
let scale2 = stage_h / 768.0;
let hit_position = self.config.hit_position as f64 * scale;
for (i, key_pressed) in pressed.iter().enumerate() {
let key_texture = if *key_pressed {
self.textures.keys_d[i].as_ref()
} else {
self.textures.keys[i].as_ref()
};
let key_width = self.config.column_width[i] as f64 * scale;
let key_height = key_texture.get_height() as f64 * scale2;
let key_x = scale
* (self.config.column_start as f64
+ self.config.column_width[0..i].iter().sum::<u16>() as f64
+ self.config.column_spacing[0..i].iter().sum::<u16>() as f64);
let key_y = stage_h - key_height;
let key_img = Image::new().rect([key_x, key_y, key_width, key_height]);
let mut color = [
self.config.colour_light[i][0] as f32 / 255.0,
self.config.colour_light[i][1] as f32 / 255.0,
self.config.colour_light[i][2] as f32 / 255.0,
1.0,
];
let column_line_width1 = self.config.column_line_width[i] as f64 * stage_h / 1024.0; // wtaf theres a 3rd scale???
let column_line_width2 = self.config.column_line_width[i+1] as f64 * stage_h / 1024.0;
let alpha = (self.config.colour_column_line[3] as f32 / 255.0).powf(2.0); // wtf???
let column_line_color = [
self.config.colour_column_line[0] as f32 / 255.0 * alpha,
self.config.colour_column_line[1] as f32 / 255.0 * alpha,
self.config.colour_column_line[2] as f32 / 255.0 * alpha,
self.config.colour_column_line[3] as f32 / 255.0,
];
let column_line_rect1 = [
key_x,
0.0,
column_line_width1,
hit_position,
];
let column_line_rect2 = [
key_x + key_width,
0.0,
column_line_width2,
hit_position,
];
let column_line_rect = graphics::Rectangle::new(column_line_color);
let ds = draw_state.blend(draw_state::Blend::Add);
column_line_rect.draw(column_line_rect1, &ds, transform, g);
column_line_rect.draw(column_line_rect2, &ds, transform, g);
let sl_size = self.textures.stage_light.len();
let stage_light_height =
self.textures.stage_light[sl_size - 1].get_height() as f64 * scale2;
let stage_light_y = self.config.light_position as f64 * scale - stage_light_height;
let stage_light_img = Image::new()
.rect([
key_x,
stage_light_y,
key_width,
stage_light_height,
]);
if let Some(last_down_time) = self.anim_states.keys_last_down_time[i] {
let current_time = time::Instant::now();
let elapsed_time = current_time - last_down_time;
let elapsed_time_secs = elapsed_time.as_secs() as f64
+ elapsed_time.subsec_nanos() as f64 / 1e9;
let fframe: f32 = elapsed_time_secs as f32 * 30.0;
let frame = fframe as usize;
if frame < 3 {
color[3] -= fframe / 3.0;
stage_light_img.color(color).draw(
self.textures.stage_light[sl_size - 1].as_ref(),
draw_state,
transform,
g,
);
}
} else if *key_pressed {
stage_light_img.color(color).draw(
self.textures.stage_light[0].as_ref(),
draw_state,
transform,
g,
);
}
key_img.draw(key_texture, draw_state, transform, g);
}
}
fn draw_perfect(
&self,
draw_state: &DrawState,
transform: math::Matrix2d,
size_scale: f64,
g: &mut G,
stage_h: f64,
elapsed_time: time::Duration,
) {
let elapsed =
elapsed_time.as_secs() as f64 + elapsed_time.subsec_nanos() as f64 / 1e9;
let frame = (elapsed * 30.0) as usize % self.textures.hit300g.len();
let tx = &*self.textures.hit300g[frame];
let scale = stage_h / 480.0;
let scale2 = stage_h / 768.0;
let stage_width = (self.config.column_width.iter().sum::<u16>() as f64
+ self.config.column_spacing.iter().sum::<u16>() as f64)
* scale;
let column_start = self.config.column_start as f64 * scale;
let tx_w = tx.get_width() as f64 * scale2 / 1.5 * size_scale;
let tx_h = tx.get_height() as f64 * scale2 / 1.5 * size_scale;
let tx_x = stage_width / 2.0 - tx_w / 2.0 + column_start;
let tx_y = self.config.score_position as f64 * scale - tx_h / 2.0;
let img = Image::new().rect([tx_x, tx_y, tx_w, tx_h]);
img.draw(tx, draw_state, transform, g);
}
fn draw_miss(
&self,
draw_state: &DrawState,
transform: math::Matrix2d,
g: &mut G,
stage_h: f64,
) {
let tx = &*self.textures.miss[0];
let scale = stage_h / 480.0;
let scale2 = stage_h / 768.0;
let stage_width = (self.config.column_width.iter().sum::<u16>() as f64
+ self.config.column_spacing.iter().sum::<u16>() as f64)
* scale;
let column_start = self.config.column_start as f64 * scale;
let tx_w = tx.get_width() as f64 * scale2;
let tx_h = tx.get_height() as f64 * scale2;
let tx_x = stage_width / 2.0 - tx_w / 2.0 + column_start;
let tx_y = self.config.score_position as f64 * scale - tx_h / 2.0;
let img = Image::new().rect([tx_x, tx_y, tx_w, tx_h]);
img.draw(tx, draw_state, transform, g);
}
fn draw_hit_anims(
&mut self,
draw_state: &DrawState,
transform: math::Matrix2d,
g: &mut G,
stage_height: f64,
) {
let scale = stage_height / 480.0;
let scale2 = stage_height / 768.0;
let hit_p = self.config.hit_position as f64 * scale;
for (i, hit_anim) in self.anim_states.hit_anim.iter_mut().enumerate() {
let key_width = self.config.column_width[i] as f64 * scale;
let hit_x = scale
* (self.config.column_start as f64
+ self.config.column_width[0..i].iter().sum::<u16>() as f64
+ self.config.column_spacing[0..i].iter().sum::<u16>() as f64);
match *hit_anim {
HitAnimState::SingleNote(time) => {
let frame = (time.elapsed() * 60).as_secs() as usize;
if frame > self.textures.lighting_n.len() - 1 {
*hit_anim = HitAnimState::None;
} else {
let hit_w = self.textures.lighting_n[frame].get_width() as f64 * scale2;
let hit_h = self.textures.lighting_n[frame].get_height() as f64 * scale2;
let hit_img = Image::new().rect([
hit_x - hit_w / 2.0 + key_width / 2.0,
hit_p - hit_h / 2.0,
hit_w,
hit_h,
]);
hit_img.draw(
&*self.textures.lighting_n[frame],
draw_state,
transform,
g,
);
}
}
HitAnimState::LongNote(time) => {
let frame = (time.elapsed() * 60).as_secs() as usize % self.textures.lighting_l.len();
let hit_w = self.textures.lighting_l[frame].get_width() as f64 * scale2;
let hit_h = self.textures.lighting_l[frame].get_height() as f64 * scale2;
let hit_img = Image::new().rect([
hit_x - hit_w / 2.0 + key_width / 2.0,
hit_p - hit_h / 2.0,
hit_w,
hit_h,
]);
hit_img.draw(
&*self.textures.lighting_l[frame],
draw_state,
transform,
g,
);
}
HitAnimState::LongNoteFinal(start, end) => {
let diff = end - start;
let elapsed = start.elapsed();
let anim_count1 = (diff * 60 / self.textures.lighting_l.len() as u32).as_secs();
let anim_count2 = (elapsed * 60 / self.textures.lighting_l.len() as u32).as_secs();
if anim_count2 > anim_count1 {
*hit_anim = HitAnimState::None;
} else {
let frame = (elapsed * 60).as_secs() as usize % self.textures.lighting_l.len();
let hit_w = self.textures.lighting_l[frame].get_width() as f64 * scale2;
let hit_h = self.textures.lighting_l[frame].get_height() as f64 * scale2;
let hit_img = Image::new().rect([
hit_x - hit_w / 2.0 + key_width / 2.0,
hit_p - hit_h / 2.0,
hit_w,
hit_h,
]);
hit_img.draw(
&*self.textures.lighting_l[frame],
draw_state,
transform,
g,
);
}
}
HitAnimState::None => (),
}
}
}
}
#[derive(Debug)]
enum OsuSkinParseError {
NoDefaultTexture(String),
}
impl fmt::Display for OsuSkinParseError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
OsuSkinParseError::NoDefaultTexture(ref s) => {
write!(f, "No default texture found for {}", s)
}
}
}
}
impl From<OsuSkinParseError> for ParseError {
fn from(e: OsuSkinParseError) -> ParseError {
ParseError::Parse(String::from("Error reading osu skin"), Some(Box::new(e)))
}
}
impl error::Error for OsuSkinParseError {
fn description(&self) -> &str {
match *self {
OsuSkinParseError::NoDefaultTexture(_) => "No default texture found",
}
}
}
// Apparently I need to do this?
fn fix_alpha(img: &mut image::RgbaImage) {
use std::u8;
// linearize the alpha channel (wtf)
for pixel in img.pixels_mut() {
const U8_MAX: f32 = u8::MAX as f32;
let mut v = pixel.0[3] as f32 / U8_MAX;
if v <= 0.04045 {
v /= 12.92
} else {
v = ((v + 0.055) / 1.055).powf(2.4)
}
pixel.0[3] = (v * U8_MAX).round() as u8;
}
}
fn texture_from_path<F, T, P>(
factory: &mut F,
path: P,
texture_settings: &TextureSettings,
) -> Result<T, ParseError>
where
T: CreateTexture<F>,
P: AsRef<path::Path>,
T::Error: ToString,
{
let path_string = path.as_ref().to_string_lossy().into_owned();
let mut image = match image::open(&path) {
Ok(t) => t.to_rgba8(),
Err(e) => return Err(ParseError::ImageError(path_string, e)),
};
fix_alpha(&mut image); // ???
let dimensions = image.dimensions();
CreateTexture::create(
factory,
Format::Rgba8,
&*image.into_raw(),
[dimensions.0, dimensions.1],
texture_settings,
).map_err(|e: T::Error| {
ParseError::TextureError {
path: path.as_ref().to_owned(),
error: e.to_string(),
}
})
}
/// Load an animatable skin element's textures
///
/// This function takes the basename and tries different paths until it finds one that exists
fn load_texture_anim<F, T>(
factory: &mut F,
cache: &mut HashMap<String, Rc<[Rc<T>]>>,
dir: &path::Path,
default_dir: &path::Path,
names: &(&'static str, String),
texture_settings: &TextureSettings,
) -> Result<Rc<[Rc<T>]>, ParseError>
where
T: CreateTexture<F>,
T::Error: ToString,
{
let mut textures = Vec::new();
let mut path;
macro_rules! repetitive_code {
// $dir should be a path::Path
($(($dir:ident, $name:expr)),*) => {$(
// Check the cache
if let Some(texture) = cache.get(&$name) {
return Ok(Rc::clone(texture));
}
// TODO can these join's be optimized? how much time does it take to allocate the pathbuf?
// Check for an animation sequence
path = $dir.join($name + "-0.png");
if path.exists() {
textures.push(Rc::new(texture_from_path(factory, &path, texture_settings)?));
let mut n = 1;
loop {
path = $dir.join(format!("{}-{}.png", $name, n));
if !path.exists() { break; }
textures.push(Rc::new(texture_from_path(factory, &path, texture_settings)?));
n += 1;
}
let anim = Rc::from(textures);
cache.insert($name, Rc::clone(&anim));
return Ok(anim);
}
// Check for static image
path = $dir.join($name + ".png");
if path.exists() {
// help
let texture = Rc::new(texture_from_path(factory, &path, texture_settings)?);
let anim = Rc::from(&[texture][..]);
cache.insert($name, Rc::clone(&anim));
return Ok(anim);
}
)*}
}
// Check the skin directory, then the default skin directory
repetitive_code!((dir, names.1.clone()), (default_dir, names.0.to_owned()));
Err(OsuSkinParseError::NoDefaultTexture(String::from(names.0)).into())
}
/// Load a skin element's texture
///
/// This function takes the basename and tries different paths until it finds one that exists
fn load_texture<F, T>(
factory: &mut F,
cache: &mut HashMap<String, Rc<[Rc<T>]>>,
dir: &path::Path,
default_dir: &path::Path,
names: &(&'static str, String),
texture_settings: &TextureSettings,
) -> Result<Rc<T>, ParseError>
where
T: CreateTexture<F>,
T::Error: ToString,
{
macro_rules! repetitive_code {
// $dir should be a path::Path
($(($dir:ident, $name:expr)),*) => {$(
// Check the cache
if let Some(texture) = cache.get(&$name) {
return Ok(Rc::clone(&texture[0]));
}
// TODO can these join's be optimized? how much time does it take to allocate the pathbuf?
let path = $dir.join($name + ".png");
if path.exists() {
let texture = texture_from_path(factory, path, texture_settings)?;
let rc = Rc::new(texture);
cache.insert($name, Rc::from(&[Rc::clone(&rc)][..]));
return Ok(rc);
}
)*}
}
// Check the skin directory, then the default skin directory
repetitive_code!((dir, names.1.clone()), (default_dir, names.0.to_owned()));
Err(OsuSkinParseError::NoDefaultTexture(String::from(names.0)).into())
}
pub fn from_path<F, G>(
factory: &mut F,
dir: &path::Path,
default_dir: &path::Path,
) -> Result<Box<dyn GameSkin<G>>, ParseError>
where
G: Graphics + 'static,
G::Texture: CreateTexture<F>,
<G::Texture as TextureOp<F>>::Error: ToString,
{
let config_path = dir.join(path::Path::new("skin.ini"));
let texture_settings = TextureSettings::new();
macro_rules! double {
($e:expr) => {
($e, String::from($e))
};
}
// put things into the 1213121 pattern
macro_rules! pat {
($a:expr, $b:expr, $c:expr) => {
[$a, $b, $a, $c, $a, $b, $a]
};
}
// (default image name, skin image name)
// the skin filename might get changed by the skin.ini, which is parsed later
let mut miss_name = double!("mania-hit0");
let mut hit50_name = double!("mania-hit50");
let mut hit100_name = double!("mania-hit100");
let mut hit200_name = double!("mania-hit200");
let mut hit300_name = double!("mania-hit300");
let mut hit300g_name = double!("mania-hit300g");
let mut stage_light_name = double!("mania-stage-light");
let mut lighting_n_name = double!("lightingN");
let mut lighting_l_name = double!("lightingL");
let mut keys_name = pat![
double!("mania-key1"),
double!("mania-key2"),
double!("mania-keyS")
];
let mut keys_d_name = pat![
double!("mania-key1D"),
double!("mania-key2D"),
double!("mania-keySD")
];
let mut notes_name = pat![
double!("mania-note1"),
double!("mania-note2"),
double!("mania-noteS")
];
// lns is plural of ln (long note)
let mut lns_head_name = pat![
double!("mania-note1H"),
double!("mania-note2H"),
double!("mania-noteSH")
];
let mut lns_body_name = pat![
double!("mania-note1L"),
double!("mania-note2L"),
double!("mania-noteSL")
];
let mut lns_tail_name = pat![
double!("mania-note1T"),
double!("mania-note2T"),
double!("mania-noteST")
];
let mut stage_hint_name = double!("mania-stage-hint");
let mut stage_left_name = double!("mania-stage-left");
let mut stage_right_name = double!("mania-stage-right");
let mut stage_bottom_name = double!("mania-stage-bottom");
// default values
let mut column_start = 136;
let mut column_width = [30; 7];
let mut column_line_width = [2; 8];
let mut colour_column_line = [255; 4];
let mut column_spacing = [0; 6];
let mut colour_light = [[255, 255, 255]; 7];
let mut hit_position = 402;
let mut score_position = 240; // idk TODO
let mut light_position = 413;
let mut note_body_style = [NoteBodyStyle::CascadeFromTop; 7];
// parse skin.ini
if config_path.exists() {
let config_file = File::open(config_path)
.map_err(|e| ParseError::Io(String::from("Error opening config file"), e))?;
let config_reader = BufReader::new(&config_file);
let mut section = String::from("General");
let mut keys: u8 = 0;
for (line_number, l) in config_reader.lines().enumerate().map(|(n, l)| (n + 1, l)) {
let line =
l.map_err(|e| ParseError::Io(String::from("Error reading config file"), e))?;
let line = line.trim();
// section declarations look like [section name]
if line.starts_with('[') && line.ends_with(']') {
section = line[1..line.len() - 1].to_string();
continue;
}
// comment line or empty line
if line.starts_with("//") || line == "" {
continue;
}
// key: value
let mut line_parts = line.splitn(2, ':');
// parse but with some error handling
macro_rules! parse {
($value:ident) => {
match $value.parse() {
Ok(o) => o,
Err(e) => {
remani_warn!(
"Malformed value in line {} of skin.ini ({}), ignoring",
line_number,
e
);
continue;
}
}
};
}
let key = if let Some(k) = line_parts.next() {
k.trim()
} else {
continue;
};
let value = if let Some(v) = line_parts.next() {
v.trim()
} else {
continue;
};
match key {
"Keys" => keys = parse!(value),
_ => {
if keys == 7 && section == "Mania" {
macro_rules! prop_name {
({$prefix:ident#$suffix:ident}, $n:expr) => {
concat!(
concat!(stringify!($prefix), stringify!($n)),
stringify!($suffix)
)
};
({$prefix:ident#}, $n:expr) => {
concat!(stringify!($prefix), stringify!($n))
};
}
// fancy macros
// used to match stuff like KeyImage{0..6}H more easily
macro_rules! enumerate_match {
($key:ident,
$(.$name1:tt => $varname1:ident = $value1:expr, [ $baseidx1:literal $($idx1:literal)* ],)*
==
$(.$name2:tt => $varname2:ident = $value2:expr, [ $baseidx2:literal $($idx2:literal)* ],)*) => {
match $key {
$(
prop_name!($name1, $baseidx1) => $varname1[0].1 = $value1,
$(prop_name!($name1, $idx1) => $varname1[$idx1 - $baseidx1].1 = $value1,)*
)*
$(
prop_name!($name2, $baseidx2) => $varname2[0] = $value2,
$(prop_name!($name2, $idx2) => $varname2[$idx2 - $baseidx2] = $value2,)*
)*
_ => (),
}
};
}
// for values that look like
// 42,10,5,1337,4,8,2
macro_rules! csv {
($default:expr; $count:expr) => {{
let mut a = $default;
let mut n = 0;
for (i, v) in value.split(",").enumerate().take($count) {
a[i] = parse!(v);
n = i;
}
if n < $count - 1 {
remani_warn!(
"Malformed value in line {} of skin.ini (not enough fields), ignoring",
line_number
);
continue;
} else {
a
}
}};
}
match key {
"ColumnStart" => column_start = parse!(value),
"HitPosition" => hit_position = parse!(value),
"ScorePosition" => score_position = parse!(value),
"LightPosition" => light_position = parse!(value),
"ColumnWidth" => column_width = csv![column_width; 7],
"ColumnLineWidth" => column_line_width = csv![column_line_width; 8],
"ColourColumnLine" => colour_column_line = csv![colour_column_line; 4],
"ColumnSpacing" => column_spacing = csv![column_spacing; 6],
"NoteBodyStyle" => note_body_style = [parse!(value); 7],
"Hit0" => miss_name.1 = value.to_owned(),
"Hit50" => hit50_name.1 = value.to_owned(),
"Hit100" => hit100_name.1 = value.to_owned(),
"Hit200" => hit200_name.1 = value.to_owned(),
"Hit300" => hit300_name.1 = value.to_owned(),
"Hit300g" => hit300g_name.1 = value.to_owned(),
"StageHint" => stage_hint_name.1 = value.to_owned(),
"StageLeft" => stage_left_name.1 = value.to_owned(),
"StageRight" => stage_right_name.1 = value.to_owned(),
"StageBottom" => stage_bottom_name.1 = value.to_owned(),
"StageLight" => stage_light_name.1 = value.to_owned(),
"LightingN" => lighting_n_name.1 = value.to_owned(),
"LightingL" => lighting_l_name.1 = value.to_owned(),
k => enumerate_match! { k,
.{KeyImage#} => keys_name = value.to_owned(), [0 1 2 3 4 5 6],
.{KeyImage#D} => keys_d_name = value.to_owned(), [0 1 2 3 4 5 6],
.{NoteImage#} => notes_name = value.to_owned(), [0 1 2 3 4 5 6],
.{NoteImage#H} => lns_head_name = value.to_owned(), [0 1 2 3 4 5 6],
.{NoteImage#L} => lns_body_name = value.to_owned(), [0 1 2 3 4 5 6],
.{NoteImage#T} => lns_tail_name = value.to_owned(), [0 1 2 3 4 5 6],
== // separator between the image file specifying properties above, and the other properties below
.{ColourLight#} => colour_light = csv![[0; 3]; 3], [1 2 3 4 5 6 7],
.{NoteBodyStyle#} => note_body_style = parse!(value), [0 1 2 3 4 5 6],
},
}
}
}
}
}
}
let mut cache = HashMap::new();
// load all the textures into the gpu
let miss = load_texture_anim(factory, &mut cache, dir, default_dir, &miss_name, &texture_settings)?;
let hit50 = load_texture_anim(factory, &mut cache, dir, default_dir, &hit50_name, &texture_settings)?;
let hit100 = load_texture_anim(factory, &mut cache, dir, default_dir, &hit100_name, &texture_settings)?;
let hit200 = load_texture_anim(factory, &mut cache, dir, default_dir, &hit200_name, &texture_settings)?;
let hit300 = load_texture_anim(factory, &mut cache, dir, default_dir, &hit300_name, &texture_settings)?;
let hit300g = load_texture_anim(factory, &mut cache, dir, default_dir, &hit300g_name, &texture_settings)?;
let stage_light = load_texture_anim(factory, &mut cache, dir, default_dir, &stage_light_name, &texture_settings)?;
let lighting_n = load_texture_anim(factory, &mut cache, dir, default_dir, &lighting_n_name, &texture_settings)?;
let lighting_l = load_texture_anim(factory, &mut cache, dir, default_dir, &lighting_l_name, &texture_settings)?;
let keys = [load_texture(factory, &mut cache, dir, default_dir, &keys_name[0], &texture_settings)?,
load_texture(factory, &mut cache, dir, default_dir, &keys_name[1], &texture_settings)?,
load_texture(factory, &mut cache, dir, default_dir, &keys_name[2], &texture_settings)?,
load_texture(factory, &mut cache, dir, default_dir, &keys_name[3], &texture_settings)?,
load_texture(factory, &mut cache, dir, default_dir, &keys_name[4], &texture_settings)?,
load_texture(factory, &mut cache, dir, default_dir, &keys_name[5], &texture_settings)?,
load_texture(factory, &mut cache, dir, default_dir, &keys_name[6], &texture_settings)?];
let keys_d = [load_texture(factory, &mut cache, dir, default_dir, &keys_d_name[0], &texture_settings)?,
load_texture(factory, &mut cache, dir, default_dir, &keys_d_name[1], &texture_settings)?,
load_texture(factory, &mut cache, dir, default_dir, &keys_d_name[2], &texture_settings)?,
load_texture(factory, &mut cache, dir, default_dir, &keys_d_name[3], &texture_settings)?,
load_texture(factory, &mut cache, dir, default_dir, &keys_d_name[4], &texture_settings)?,
load_texture(factory, &mut cache, dir, default_dir, &keys_d_name[5], &texture_settings)?,
load_texture(factory, &mut cache, dir, default_dir, &keys_d_name[6], &texture_settings)?];
let notes = [load_texture_anim(factory, &mut cache, dir, default_dir, ¬es_name[0], &texture_settings)?,
load_texture_anim(factory, &mut cache, dir, default_dir, ¬es_name[1], &texture_settings)?,
load_texture_anim(factory, &mut cache, dir, default_dir, ¬es_name[2], &texture_settings)?,
load_texture_anim(factory, &mut cache, dir, default_dir, ¬es_name[3], &texture_settings)?,
load_texture_anim(factory, &mut cache, dir, default_dir, ¬es_name[4], &texture_settings)?,
load_texture_anim(factory, &mut cache, dir, default_dir, ¬es_name[5], &texture_settings)?,
load_texture_anim(factory, &mut cache, dir, default_dir, ¬es_name[6], &texture_settings)?];
let long_notes_head = [load_texture_anim(factory, &mut cache, dir, default_dir, &lns_head_name[0], &texture_settings)?,
load_texture_anim(factory, &mut cache, dir, default_dir, &lns_head_name[1], &texture_settings)?,
load_texture_anim(factory, &mut cache, dir, default_dir, &lns_head_name[2], &texture_settings)?,
load_texture_anim(factory, &mut cache, dir, default_dir, &lns_head_name[3], &texture_settings)?,
load_texture_anim(factory, &mut cache, dir, default_dir, &lns_head_name[4], &texture_settings)?,
load_texture_anim(factory, &mut cache, dir, default_dir, &lns_head_name[5], &texture_settings)?,
load_texture_anim(factory, &mut cache, dir, default_dir, &lns_head_name[6], &texture_settings)?];
let long_notes_body = [load_texture_anim(factory, &mut cache, dir, default_dir, &lns_body_name[0], &texture_settings)?,
load_texture_anim(factory, &mut cache, dir, default_dir, &lns_body_name[1], &texture_settings)?,
load_texture_anim(factory, &mut cache, dir, default_dir, &lns_body_name[2], &texture_settings)?,
load_texture_anim(factory, &mut cache, dir, default_dir, &lns_body_name[3], &texture_settings)?,
load_texture_anim(factory, &mut cache, dir, default_dir, &lns_body_name[4], &texture_settings)?,
load_texture_anim(factory, &mut cache, dir, default_dir, &lns_body_name[5], &texture_settings)?,
load_texture_anim(factory, &mut cache, dir, default_dir, &lns_body_name[6], &texture_settings)?];
let long_notes_tail = [load_texture_anim(factory, &mut cache, dir, default_dir, &lns_tail_name[0], &texture_settings).ok(),
load_texture_anim(factory, &mut cache, dir, default_dir, &lns_tail_name[1], &texture_settings).ok(),
load_texture_anim(factory, &mut cache, dir, default_dir, &lns_tail_name[2], &texture_settings).ok(),
load_texture_anim(factory, &mut cache, dir, default_dir, &lns_tail_name[3], &texture_settings).ok(),
load_texture_anim(factory, &mut cache, dir, default_dir, &lns_tail_name[4], &texture_settings).ok(),
load_texture_anim(factory, &mut cache, dir, default_dir, &lns_tail_name[5], &texture_settings).ok(),
load_texture_anim(factory, &mut cache, dir, default_dir, &lns_tail_name[6], &texture_settings).ok()];
let stage_hint = load_texture_anim(factory, &mut cache, dir, default_dir, &stage_hint_name, &texture_settings)?;
let stage_left = load_texture(factory, &mut cache, dir, default_dir, &stage_left_name, &texture_settings)?;
let stage_right = load_texture(factory, &mut cache, dir, default_dir, &stage_right_name, &texture_settings)?;
let stage_bottom = load_texture_anim(factory, &mut cache, dir, default_dir, &stage_bottom_name, &texture_settings).ok();
let smallest_note_width;
let smallest_note_height;
{
let smallest_height_note = ¬es
.iter()
.min_by_key(|x: &&Rc<[Rc<G::Texture>]>| x[0].get_height())
.unwrap()[0];
smallest_note_width = smallest_height_note.get_width() as f64;
smallest_note_height = smallest_height_note.get_height() as f64;
}
let width_for_note_height_scale =
smallest_note_height / smallest_note_width * *column_width.iter().min().unwrap() as f64;
Ok(Box::new(OsuSkin {
textures: OsuSkinTextures {
miss,
hit50,
hit100,
hit200,
hit300,
hit300g,
stage_light,
lighting_n,
lighting_l,
keys,
keys_d,
notes,
long_notes_head,
long_notes_body,
long_notes_tail,
stage_hint,
stage_left,
stage_right,
stage_bottom,
},
anim_states: OsuAnimStates {
keys_last_down_time: [None; 7],
hit_anim: [HitAnimState::None; 7],
},
config: OsuSkinConfig {
column_start,
column_width,
column_spacing,
column_line_width,
colour_column_line,
hit_position,
score_position,
light_position,
width_for_note_height_scale,
note_body_style,
colour_light,
},
judgement: None,
}))
}
|
fn accept(s: &str) {
println!("{}", s);
}
fn main() {
let l_j: &str = "Linux Journal";
let magazine: &'static str = "magazine";
let my_str = format!("Hello {} {}!", l_j, magazine);
println!("my_str L:{} C:{}", my_str.len(), my_str.capacity());
for c in my_str.chars() {
print!("{} ", c);
}
println!();
for (i, c) in my_str.chars().enumerate() {
print!("{}:{} ", c, i);
}
println!();
let n: &str = "10";
match n.parse::<i32>() {
Ok(n) => println!("{} is a number!", n),
Err(e) => println!("{} is NOT a number!", e),
}
let n1: &str = "10.2";
match n1.parse::<i32>() {
Ok(n1) => println!("{} is a number!", n1),
Err(e) => println!("{}: {}", n1, e),
}
let my_str = "This is str!";
let mut my_string = String::from("This is string!");
accept(&my_str);
accept(&my_string);
println!("my_string L:{} C:{}", my_string.len(), my_string.capacity());
my_string.push_str("OK?");
println!("my_stirng L:{} C:{}", my_string.len(), my_string.capacity());
let s_str: &str = &my_string[..];
let s_string: String = s_str.to_owned();
println!("s_string: L:{} C:{}", s_string.len(), s_string.capacity());
}
|
// 1649. Create Sorted Array through Instructions
// https://leetcode.com/problems/create-sorted-array-through-instructions/
pub struct Solution;
const MODULO: i32 = 1_000_000_007;
#[cfg(disable)]
impl Solution {
pub fn create_sorted_array(instructions: Vec<i32>) -> i32 {
let mut res = Vec::with_capacity(instructions.len());
let mut cost: i32 = 0;
for inst in instructions {
let value = inst * 2;
let lower = res.binary_search(&(value - 1)).unwrap_err();
let upper = res.binary_search(&(value + 1)).unwrap_err();
cost += lower.min(res.len() - upper) as i32;
res.insert(upper, value);
if cost > MODULO {
cost %= MODULO;
}
}
cost
}
}
// Raybko (a.k.a. Fenwick) tree
struct RyabkoTree(Vec<usize>);
impl RyabkoTree {
fn new(max: usize) -> Self {
Self(vec![0; max + 1])
}
fn add(&mut self, mut num: usize) {
while num < self.0.len() {
self.0[num] += 1;
num += num - (num & (num - 1));
}
}
fn get(&self, mut num: usize) -> usize {
let mut sum = 0;
loop {
sum += self.0[num];
if num == 0 {
break sum;
}
let last_bit = num - (num & (num - 1));
if num < last_bit {
break sum;
}
num -= last_bit;
}
}
}
impl Solution {
pub fn create_sorted_array(instructions: Vec<i32>) -> i32 {
let mut tree =
RyabkoTree::new(*instructions.iter().max().unwrap_or(&0) as usize);
let mut cost = 0;
for (count, &num) in instructions.iter().enumerate() {
let lower = tree.get((num - 1) as usize);
let upper = count - tree.get(num as usize);
cost = (cost + lower.min(upper) as i32) % MODULO;
tree.add(num as usize);
}
cost as i32
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn example1() {
assert_eq!(Solution::create_sorted_array(vec![1, 5, 6, 2]), 1)
}
#[test]
fn example2() {
assert_eq!(Solution::create_sorted_array(vec![1, 2, 3, 6, 5, 4]), 3)
}
#[test]
fn example3() {
assert_eq!(
Solution::create_sorted_array(vec![1, 3, 3, 3, 2, 4, 2, 1, 2]),
4
)
}
#[test]
fn test_big() {
let instructions: Vec<i32> =
[4, 5, 6].iter().cycle().take(90_000).copied().collect();
Solution::create_sorted_array(instructions);
}
}
|
use std::cell::RefCell;
#[allow(unused_imports)]
use std::ops::DerefMut;
use winnow::combinator::cut_err;
use winnow::combinator::delimited;
use winnow::combinator::peek;
use winnow::token::take;
// https://github.com/rust-lang/rust/issues/41358
use crate::parser::key::key;
use crate::parser::prelude::*;
use crate::parser::state::ParseState;
use crate::parser::trivia::line_trailing;
// std-table-open = %x5B ws ; [ Left square bracket
pub(crate) const STD_TABLE_OPEN: u8 = b'[';
// std-table-close = ws %x5D ; ] Right square bracket
const STD_TABLE_CLOSE: u8 = b']';
// array-table-open = %x5B.5B ws ; [[ Double left square bracket
const ARRAY_TABLE_OPEN: &[u8] = b"[[";
// array-table-close = ws %x5D.5D ; ]] Double right quare bracket
const ARRAY_TABLE_CLOSE: &[u8] = b"]]";
// ;; Standard Table
// std-table = std-table-open key *( table-key-sep key) std-table-close
pub(crate) fn std_table<'s, 'i>(
state: &'s RefCell<ParseState>,
) -> impl Parser<Input<'i>, (), ContextError> + 's {
move |i: &mut Input<'i>| {
(
delimited(
STD_TABLE_OPEN,
cut_err(key),
cut_err(STD_TABLE_CLOSE)
.context(StrContext::Expected(StrContextValue::CharLiteral('.')))
.context(StrContext::Expected(StrContextValue::StringLiteral("]"))),
)
.with_span(),
cut_err(line_trailing)
.context(StrContext::Expected(StrContextValue::CharLiteral('\n')))
.context(StrContext::Expected(StrContextValue::CharLiteral('#'))),
)
.try_map(|((h, span), t)| state.borrow_mut().deref_mut().on_std_header(h, t, span))
.parse_next(i)
}
}
// ;; Array Table
// array-table = array-table-open key *( table-key-sep key) array-table-close
pub(crate) fn array_table<'s, 'i>(
state: &'s RefCell<ParseState>,
) -> impl Parser<Input<'i>, (), ContextError> + 's {
move |i: &mut Input<'i>| {
(
delimited(
ARRAY_TABLE_OPEN,
cut_err(key),
cut_err(ARRAY_TABLE_CLOSE)
.context(StrContext::Expected(StrContextValue::CharLiteral('.')))
.context(StrContext::Expected(StrContextValue::StringLiteral("]]"))),
)
.with_span(),
cut_err(line_trailing)
.context(StrContext::Expected(StrContextValue::CharLiteral('\n')))
.context(StrContext::Expected(StrContextValue::CharLiteral('#'))),
)
.try_map(|((h, span), t)| state.borrow_mut().deref_mut().on_array_header(h, t, span))
.parse_next(i)
}
}
// ;; Table
// table = std-table / array-table
pub(crate) fn table<'s, 'i>(
state: &'s RefCell<ParseState>,
) -> impl Parser<Input<'i>, (), ContextError> + 's {
move |i: &mut Input<'i>| {
dispatch!(peek::<_, &[u8],_,_>(take(2usize));
b"[[" => array_table(state),
_ => std_table(state),
)
.context(StrContext::Label("table header"))
.parse_next(i)
}
}
|
//! Operator and utilities to source data from the underlying Timely
//! logging streams.
use std::collections::HashMap;
use std::time::Duration;
use timely::communication::message::RefOrMut;
use timely::dataflow::channels::pact::Pipeline;
use timely::dataflow::operators::capture::Replay;
use timely::dataflow::operators::generic::builder_rc::OperatorBuilder;
use timely::dataflow::{Scope, Stream};
use timely::logging::{TimelyEvent, WorkerIdentifier};
use crate::sources::{Sourceable, SourcingContext};
use crate::{AsAid, Value};
use crate::{AttributeConfig, InputSemantics};
use Value::{Bool, Eid};
/// One or more taps into Timely logging.
#[derive(Hash, PartialEq, Eq, PartialOrd, Ord, Clone, Debug, Serialize, Deserialize)]
pub struct TimelyLogging<A: AsAid> {
/// The log attributes that should be materialized.
pub attributes: Vec<A>,
/// Optionally listen for events from a number of remote workers,
/// rather than introspectively.
pub remote_peers: Option<usize>,
}
impl<A, S> Sourceable<A, S> for TimelyLogging<A>
where
A: AsAid + From<&'static str>,
S: Scope<Timestamp = Duration>,
{
fn source(
&self,
scope: &mut S,
context: SourcingContext<S::Timestamp>,
) -> Vec<(
A,
AttributeConfig,
Stream<S, ((Value, Value), Duration, isize)>,
)> {
let input = match self.remote_peers {
None => {
// Read events introspectively.
Some(context.timely_events).replay_into(scope)
}
Some(source_peers) => {
// Listen for events from a remote computation.
let sockets = open_sockets(source_peers);
make_replayers(sockets, scope.index(), scope.peers()).replay_into(scope)
}
};
let mut demux = OperatorBuilder::new("Timely Logging Demux".to_string(), scope.clone());
let mut input = demux.new_input(&input, Pipeline);
let mut wrappers = HashMap::with_capacity(self.attributes.len());
let mut streams = HashMap::with_capacity(self.attributes.len());
for aid in self.attributes.iter() {
let (wrapper, stream) = demux.new_output();
wrappers.insert(aid.clone(), wrapper);
streams.insert(aid.clone(), stream);
}
let mut demux_buffer = Vec::new();
let num_interests = self.attributes.len();
let timely__scope = A::from("timely/scope");
let timely__event__operates__local_id = A::from("timely.event.operates/local-id");
let timely__event__operates__name = A::from("timely.event.operates/name");
let timely__event__operates__shutdown = A::from("timely.event.operates/shutdown?");
let timely__event__channels__src_index = A::from("timely.event.channels/src-index");
let timely__event__channels__src_port = A::from("timely.event.channels/src-port");
let timely__event__channels__target_index = A::from("timely.event.channels/target-index");
let timely__event__channels__target_port = A::from("timely.event.channels/target-port");
let schedule__started = A::from("schedule/started?");
demux.build(move |_capability| {
move |_frontiers| {
let mut handles = HashMap::with_capacity(num_interests);
for (aid, wrapper) in wrappers.iter_mut() {
handles.insert(aid.clone(), wrapper.activate());
}
input.for_each(|time, data: RefOrMut<Vec<_>>| {
data.swap(&mut demux_buffer);
let mut sessions = HashMap::with_capacity(num_interests);
for (aid, handle) in handles.iter_mut() {
sessions.insert(aid.clone(), handle.session(&time));
}
for (time, _worker, datum) in demux_buffer.drain(..) {
match datum {
TimelyEvent::Operates(mut x) => {
let eid = Eid((x.id as u64).into());
let name = Value::String(x.name);
// The id of this operator within its scope.
let local_id = Eid((x.addr.pop().unwrap() as u64).into());
if x.addr.is_empty() {
// This is a top-level subgraph and thus lives in the root.
sessions
.get_mut(&timely__scope)
.map(|s| s.give(((eid.clone(), Eid(0)), time, 1)));
} else {
// The leaf scope that this operator resides in.
let scope = Eid((x.addr.pop().unwrap() as u64).into());
sessions
.get_mut(&timely__scope)
.map(|s| s.give(((eid.clone(), scope.clone()), time, 1)));
if !x.addr.is_empty() {
// This means that there are one or more parent scopes.
// We want to make sure our scope is linked to its parent. But
// we can assume all others are doing the same, so we don't need to
// re-introduce edges for higher-level ancestors.
let parent = Eid((x.addr.pop().unwrap() as u64).into());
sessions
.get_mut(&timely__scope)
.map(|s| s.give(((scope, parent), time, 1)));
}
}
sessions
.get_mut(&timely__event__operates__local_id)
.map(|s| s.give(((eid.clone(), local_id), time, 1)));
sessions
.get_mut(&timely__event__operates__name)
.map(|s| s.give(((eid, name), time, 1)));
}
TimelyEvent::Shutdown(x) => {
let eid = Eid((x.id as u64).into());
sessions
.get_mut(&timely__event__operates__shutdown)
.map(|s| s.give(((eid, Bool(true)), time, 1)));
}
TimelyEvent::Channels(mut x) => {
let eid = Eid((x.id as u64).into());
let src_index = Eid((x.source.0 as u64).into());
let src_port = Eid((x.source.1 as u64).into());
let target_index = Eid((x.target.0 as u64).into());
let target_port = Eid((x.target.1 as u64).into());
// The leaf scope that this channel resides in.
let scope = Eid((x.scope_addr.pop().unwrap() as u64).into());
sessions
.get_mut(&timely__scope)
.map(|s| s.give(((eid.clone(), scope.clone()), time, 1)));
sessions
.get_mut(&timely__event__channels__src_index)
.map(|s| s.give(((eid.clone(), src_index), time, 1)));
sessions
.get_mut(&timely__event__channels__src_port)
.map(|s| s.give(((eid.clone(), src_port), time, 1)));
sessions
.get_mut(&timely__event__channels__target_index)
.map(|s| s.give(((eid.clone(), target_index), time, 1)));
sessions
.get_mut(&timely__event__channels__target_port)
.map(|s| s.give(((eid, target_port), time, 1)));
}
TimelyEvent::Schedule(x) => {
let eid = Eid((x.id as u64).into());
let is_started =
Bool(x.start_stop == ::timely::logging::StartStop::Start);
sessions
.get_mut(&schedule__started)
.map(|s| s.give(((eid, is_started), time, 1)));
}
TimelyEvent::Messages(_x) => {
// @TODO
// (MessagesChannel, (x.seq_noValue::Usize(x.channel), Value::Bool(x.is_send), Value::Usize(x.source), Value::Usize(x.target), Value::Usize(x.seq_no), Value::Usize(x.length)
}
_ => {}
}
}
});
}
});
self.attributes
.iter()
.map(|aid| {
(
aid.clone(),
AttributeConfig::real_time(InputSemantics::Distinct),
streams.remove(aid).unwrap(),
)
})
.collect()
}
}
use std::net::{TcpListener, TcpStream};
use std::sync::{Arc, Mutex};
use timely::dataflow::operators::capture::EventReader;
/// Listens on 127.0.0.1:8000 and opens `source_peers` sockets from
/// the computations we're examining.
fn open_sockets(source_peers: usize) -> Arc<Mutex<Vec<Option<TcpStream>>>> {
let listener = TcpListener::bind("127.0.0.1:8000").unwrap();
let sockets = (0..source_peers)
.map(|_| Some(listener.incoming().next().unwrap().unwrap()))
.collect::<Vec<_>>();
Arc::new(Mutex::new(sockets))
}
/// Construct replayers that read data from sockets and can stream it
/// into timely dataflow.
fn make_replayers(
sockets: Arc<Mutex<Vec<Option<TcpStream>>>>,
index: usize,
peers: usize,
) -> Vec<EventReader<Duration, (Duration, WorkerIdentifier, TimelyEvent), TcpStream>> {
sockets
.lock()
.unwrap()
.iter_mut()
.enumerate()
.filter(|(i, _)| *i % peers == index)
.map(move |(_, s)| s.take().unwrap())
.map(|r| EventReader::<Duration, (Duration, WorkerIdentifier, TimelyEvent), _>::new(r))
.collect::<Vec<_>>()
}
|
#![deny(warnings)]
extern crate futures;
extern crate tokio_mock_task;
extern crate tokio_sync;
use tokio_mock_task::*;
use tokio_sync::semaphore::{Permit, Semaphore};
macro_rules! assert_ready {
($e:expr) => {{
match $e {
Ok(futures::Async::Ready(v)) => v,
Ok(_) => panic!("not ready"),
Err(e) => panic!("error = {:?}", e),
}
}};
}
macro_rules! assert_not_ready {
($e:expr) => {{
match $e {
Ok(futures::Async::NotReady) => {}
Ok(futures::Async::Ready(v)) => panic!("ready; value = {:?}", v),
Err(e) => panic!("error = {:?}", e),
}
}};
}
#[test]
fn available_permits() {
let s = Semaphore::new(100);
assert_eq!(s.available_permits(), 100);
// Polling for a permit succeeds immediately
let mut permit = Permit::new();
assert!(!permit.is_acquired());
assert_ready!(permit.poll_acquire(&s));
assert_eq!(s.available_permits(), 99);
assert!(permit.is_acquired());
// Polling again on the same waiter does not claim a new permit
assert_ready!(permit.poll_acquire(&s));
assert_eq!(s.available_permits(), 99);
assert!(permit.is_acquired());
}
#[test]
fn unavailable_permits() {
let s = Semaphore::new(1);
let mut permit_1 = Permit::new();
let mut permit_2 = Permit::new();
// Acquire the first permit
assert_ready!(permit_1.poll_acquire(&s));
assert_eq!(s.available_permits(), 0);
let mut task = MockTask::new();
task.enter(|| {
// Try to acquire the second permit
assert_not_ready!(permit_2.poll_acquire(&s));
});
permit_1.release(&s);
assert_eq!(s.available_permits(), 0);
assert!(task.is_notified());
assert_ready!(permit_2.poll_acquire(&s));
permit_2.release(&s);
assert_eq!(s.available_permits(), 1);
}
#[test]
fn zero_permits() {
let s = Semaphore::new(0);
assert_eq!(s.available_permits(), 0);
let mut permit = Permit::new();
let mut task = MockTask::new();
// Try to acquire the permit
task.enter(|| {
assert_not_ready!(permit.poll_acquire(&s));
});
s.add_permits(1);
assert!(task.is_notified());
assert_ready!(permit.poll_acquire(&s));
}
#[test]
#[should_panic]
fn validates_max_permits() {
use std::usize;
Semaphore::new((usize::MAX >> 2) + 1);
}
#[test]
fn close_semaphore_prevents_acquire() {
let s = Semaphore::new(1);
s.close();
assert_eq!(1, s.available_permits());
let mut permit = Permit::new();
assert!(permit.poll_acquire(&s).is_err());
assert_eq!(1, s.available_permits());
}
#[test]
fn close_semaphore_notifies_permit1() {
let s = Semaphore::new(0);
let mut permit = Permit::new();
let mut task = MockTask::new();
task.enter(|| {
assert_not_ready!(permit.poll_acquire(&s));
});
s.close();
assert!(task.is_notified());
assert!(permit.poll_acquire(&s).is_err());
}
#[test]
fn close_semaphore_notifies_permit2() {
let s = Semaphore::new(2);
let mut permit1 = Permit::new();
let mut permit2 = Permit::new();
let mut permit3 = Permit::new();
let mut permit4 = Permit::new();
// Acquire a couple of permits
assert_ready!(permit1.poll_acquire(&s));
assert_ready!(permit2.poll_acquire(&s));
let mut task1 = MockTask::new();
let mut task2 = MockTask::new();
task1.enter(|| {
assert_not_ready!(permit3.poll_acquire(&s));
});
task2.enter(|| {
assert_not_ready!(permit4.poll_acquire(&s));
});
s.close();
assert!(task1.is_notified());
assert!(task2.is_notified());
assert!(permit3.poll_acquire(&s).is_err());
assert!(permit4.poll_acquire(&s).is_err());
assert_eq!(0, s.available_permits());
permit1.release(&s);
assert_eq!(1, s.available_permits());
assert!(permit1.poll_acquire(&s).is_err());
permit2.release(&s);
assert_eq!(2, s.available_permits());
}
|
use quote::{quote, quote_spanned};
use syn::{parse_macro_input, spanned::Spanned, Data, DeriveInput};
#[proc_macro_derive(ToProtobuf, attributes(protobuf))]
pub fn derive_to_protobuf(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
let input = parse_macro_input!(input as DeriveInput);
derive_to_protobuf_impl(input)
.unwrap_or_else(|e| e.to_compile_error())
.into()
}
fn derive_to_protobuf_impl(input: DeriveInput) -> Result<proc_macro2::TokenStream, syn::Error> {
let name = input.ident;
let protobuf_type_path = parse_attribute(&input.attrs, &name)?;
let fields = iterate_to_protobuf(&input.data)?;
Ok(quote! {
impl crate::ToProtobuf<#protobuf_type_path> for #name {
#[allow(clippy::useless_conversion)]
fn to_protobuf(self) -> #protobuf_type_path {
#protobuf_type_path {
#fields
}
}
}
})
}
/// Parse the "protobuf" attribute of our type.
///
/// Returns the type path for the protobuf-generated type we should use in the
/// implementation of the conversion.
fn parse_attribute(
attrs: &[syn::Attribute],
name: &syn::Ident,
) -> Result<syn::TypePath, syn::Error> {
let mut protobuf_type_name = format!("crate::proto::{name}");
// Find matching attribute and parse the "name" parameter as a string
for attr in attrs {
if attr.path.is_ident("protobuf") {
match attr.parse_meta() {
Ok(syn::Meta::List(meta)) => {
for meta_item in meta.nested.iter() {
match meta_item {
syn::NestedMeta::Meta(syn::Meta::NameValue(m))
if m.path.is_ident("name") =>
{
if let syn::Lit::Str(lit) = &m.lit {
protobuf_type_name = lit.value();
}
}
_ => {
return Err(syn::Error::new(
meta_item.span(),
"expected name-value pairs",
))
}
}
}
}
Ok(_) => {
return Err(syn::Error::new(
attr.span(),
"expected a list of name-value pairs",
))
}
Err(_) => {
return Err(syn::Error::new(
attr.span(),
"failed to parse content of the attribute",
))
}
}
}
}
// Parse string form of the type name into a type path
let protobuf_type_name_stream: proc_macro2::TokenStream = syn::parse_str(&protobuf_type_name)?;
let protobuf_type_path: syn::TypePath = syn::parse2(protobuf_type_name_stream)?;
Ok(protobuf_type_path)
}
/// Iterates over named fields and calls `ToProtobuf::to_protobuf()` on each.
fn iterate_to_protobuf(data: &Data) -> Result<proc_macro2::TokenStream, syn::Error> {
match *data {
Data::Struct(ref data) => match data.fields {
syn::Fields::Named(ref fields) => {
let recurse = fields.named.iter().map(|f| {
let name = &f.ident;
quote_spanned! {f.span()=>
#name: crate::ToProtobuf::to_protobuf(self.#name).into()
}
});
Ok(quote! {
#(#recurse),*
})
}
syn::Fields::Unnamed(_) | syn::Fields::Unit => {
Err(syn::Error::new(data.fields.span(), "expected named struct"))
}
},
Data::Enum(ref e) => Err(syn::Error::new(
e.enum_token.span(),
"expected named struct, got enum",
)),
Data::Union(ref u) => Err(syn::Error::new(
u.union_token.span(),
"expected named struct, got union",
)),
}
}
#[proc_macro_derive(TryFromProtobuf, attributes(optional))]
pub fn derive_try_from_protobuf(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
let input = parse_macro_input!(input as DeriveInput);
derive_try_from_protobuf_impl(input)
.unwrap_or_else(|e| e.to_compile_error())
.into()
}
fn derive_try_from_protobuf_impl(
input: DeriveInput,
) -> Result<proc_macro2::TokenStream, syn::Error> {
let name = input.ident;
let protobuf_type_path = parse_attribute(&input.attrs, &name)?;
let fields = iterate_try_from_protobuf(&input.data)?;
Ok(quote! {
impl crate::TryFromProtobuf<#protobuf_type_path> for #name {
fn try_from_protobuf(input: #protobuf_type_path, field_name: &'static str) -> Result<Self, std::io::Error> {
Ok(Self {
#fields
})
}
}
})
}
fn iterate_try_from_protobuf(data: &Data) -> Result<proc_macro2::TokenStream, syn::Error> {
match *data {
Data::Struct(ref data) => match data.fields {
syn::Fields::Named(ref fields) => {
let recurse = fields.named.iter().map(|f| {
let name = &f.ident;
let is_optional = f.attrs.iter().any(|a| a.path.is_ident("optional"));
if is_optional {
quote_spanned! {f.span()=>
#name: match input.#name {
Some(x) => Some(crate::TryFromProtobuf::try_from_protobuf(x, stringify!(#name))?),
None => None,
}
}
} else {
quote_spanned! {f.span()=>
#name: crate::TryFromProtobuf::try_from_protobuf(input.#name, stringify!(#name))?
}
}
});
Ok(quote! {
#(#recurse),*
})
}
syn::Fields::Unnamed(_) | syn::Fields::Unit => {
Err(syn::Error::new(data.fields.span(), "expected named struct"))
}
},
Data::Enum(ref e) => Err(syn::Error::new(
e.enum_token.span(),
"expected named struct, got enum",
)),
Data::Union(ref u) => Err(syn::Error::new(
u.union_token.span(),
"expected named struct, got union",
)),
}
}
|
// #[allow(dead_code)]
// #[derive(Debug)]
// enum Direction {
// Up(Point),
// Down(Point),
// Left(Point),
// Right(Point),
// }
// #[derive(Debug)]
// enum Keys {
// UpKey(String),
// DownKey(String),
// LeftKey(String),
// RightKey(String),
// }
// impl Direction {
// fn match_direction(&self) -> Keys {
// match *self {
// Direction::Up(_) => Keys::UpKey(String::from("Pressed w")),
// Direction::Down(_) => Keys::DownKey(String::from("Pressed s")),
// Direction::Left(_) => Keys::LeftKey(String::from("Pressed a")),
// Direction::Right(_) => Keys::RightKey(String::from("Pressed d")),
// }
// }
// }
// #[derive(Debug)]
// struct Point {
// x: i32,
// y: i32,
// }
// // Polymorphism
// enum Shape {
// Rectangle { width: u32, height: u32 },
// Square(u32),
// Circle(f64),
// }
// impl Shape {
// fn area(&self) -> f64 {
// match *self {
// Shape::Rectangle { width, height } => (width * height) as f64,
// Shape::Square(ref s) => (s * s) as f64,
// Shape::Circle(ref r) => 3.1415 * (r * r) as f64,
// }
// }
// }
// // options
// enum OptionX<T> {
// Some(T),
// None
// }
// fn division(x:f64, y:f64) -> OptionX<f64> {
// if y == 0.0 {
// OptionX::None
// } else {
// OptionX::Some(x/y)
// }
// }
// fn main() {
// let u = Direction::Up(Point { x: 0, y: 1 });
// let k = u.match_direction();
// println!("{:?}", k);
// // references
// let u = 10;
// let v = &u;
// let ref z = u;
// if z == v {
// println!("they are equal");
// }
// let r = Shape::Rectangle{width:10, height:70};
// let s = Shape::Square(10);
// let c = Shape::Circle(4.5);
// let ar = r.area();
// let aq = s.area();
// let ac = c.area();
// let res = division(5.0, 7.0);
// match res {
// OptionX::Some(x) => println!("{:.10}", x),
// OptionX::None => println!("cannot divide by zero")
// }
// }
|
use super::{PyBoundMethod, PyStr, PyType, PyTypeRef};
use crate::{
class::PyClassImpl,
common::lock::PyMutex,
types::{Constructor, GetDescriptor, Initializer, Representable},
AsObject, Context, Py, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine,
};
/// classmethod(function) -> method
///
/// Convert a function to be a class method.
///
/// A class method receives the class as implicit first argument,
/// just like an instance method receives the instance.
/// To declare a class method, use this idiom:
///
/// class C:
/// @classmethod
/// def f(cls, arg1, arg2, ...):
/// ...
///
/// It can be called either on the class (e.g. C.f()) or on an instance
/// (e.g. C().f()). The instance is ignored except for its class.
/// If a class method is called for a derived class, the derived class
/// object is passed as the implied first argument.
///
/// Class methods are different than C++ or Java static methods.
/// If you want those, see the staticmethod builtin.
#[pyclass(module = false, name = "classmethod")]
#[derive(Debug)]
pub struct PyClassMethod {
callable: PyMutex<PyObjectRef>,
}
impl From<PyObjectRef> for PyClassMethod {
fn from(callable: PyObjectRef) -> Self {
Self {
callable: PyMutex::new(callable),
}
}
}
impl PyPayload for PyClassMethod {
fn class(ctx: &Context) -> &'static Py<PyType> {
ctx.types.classmethod_type
}
}
impl GetDescriptor for PyClassMethod {
fn descr_get(
zelf: PyObjectRef,
obj: Option<PyObjectRef>,
cls: Option<PyObjectRef>,
vm: &VirtualMachine,
) -> PyResult {
let (zelf, _obj) = Self::_unwrap(&zelf, obj, vm)?;
let cls = cls.unwrap_or_else(|| _obj.class().to_owned().into());
let call_descr_get: PyResult<PyObjectRef> = zelf.callable.lock().get_attr("__get__", vm);
match call_descr_get {
Err(_) => Ok(PyBoundMethod::new_ref(cls, zelf.callable.lock().clone(), &vm.ctx).into()),
Ok(call_descr_get) => call_descr_get.call((cls.clone(), cls), vm),
}
}
}
impl Constructor for PyClassMethod {
type Args = PyObjectRef;
fn py_new(cls: PyTypeRef, callable: Self::Args, vm: &VirtualMachine) -> PyResult {
let doc = callable.get_attr("__doc__", vm);
let result = PyClassMethod {
callable: PyMutex::new(callable),
}
.into_ref_with_type(vm, cls)?;
let obj = PyObjectRef::from(result);
if let Ok(doc) = doc {
obj.set_attr("__doc__", doc, vm)?;
}
Ok(obj)
}
}
impl Initializer for PyClassMethod {
type Args = PyObjectRef;
fn init(zelf: PyRef<Self>, callable: Self::Args, _vm: &VirtualMachine) -> PyResult<()> {
*zelf.callable.lock() = callable;
Ok(())
}
}
impl PyClassMethod {
pub fn new_ref(callable: PyObjectRef, ctx: &Context) -> PyRef<Self> {
PyRef::new_ref(
Self {
callable: PyMutex::new(callable),
},
ctx.types.classmethod_type.to_owned(),
None,
)
}
}
#[pyclass(
with(GetDescriptor, Constructor, Representable),
flags(BASETYPE, HAS_DICT)
)]
impl PyClassMethod {
#[pygetset(magic)]
fn func(&self) -> PyObjectRef {
self.callable.lock().clone()
}
#[pygetset(magic)]
fn wrapped(&self) -> PyObjectRef {
self.callable.lock().clone()
}
#[pygetset(magic)]
fn module(&self, vm: &VirtualMachine) -> PyResult {
self.callable.lock().get_attr("__module__", vm)
}
#[pygetset(magic)]
fn qualname(&self, vm: &VirtualMachine) -> PyResult {
self.callable.lock().get_attr("__qualname__", vm)
}
#[pygetset(magic)]
fn name(&self, vm: &VirtualMachine) -> PyResult {
self.callable.lock().get_attr("__name__", vm)
}
#[pygetset(magic)]
fn annotations(&self, vm: &VirtualMachine) -> PyResult {
self.callable.lock().get_attr("__annotations__", vm)
}
#[pygetset(magic)]
fn isabstractmethod(&self, vm: &VirtualMachine) -> PyObjectRef {
match vm.get_attribute_opt(self.callable.lock().clone(), "__isabstractmethod__") {
Ok(Some(is_abstract)) => is_abstract,
_ => vm.ctx.new_bool(false).into(),
}
}
#[pygetset(magic, setter)]
fn set_isabstractmethod(&self, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
self.callable
.lock()
.set_attr("__isabstractmethod__", value, vm)?;
Ok(())
}
}
impl Representable for PyClassMethod {
#[inline]
fn repr_str(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<String> {
let callable = zelf.callable.lock().repr(vm).unwrap();
let class = Self::class(&vm.ctx);
let repr = match (
class
.qualname(vm)
.downcast_ref::<PyStr>()
.map(|n| n.as_str()),
class.module(vm).downcast_ref::<PyStr>().map(|m| m.as_str()),
) {
(None, _) => return Err(vm.new_type_error("Unknown qualified name".into())),
(Some(qualname), Some(module)) if module != "builtins" => {
format!("<{module}.{qualname}({callable})>")
}
_ => format!("<{}({})>", class.slot_name(), callable),
};
Ok(repr)
}
}
pub(crate) fn init(context: &Context) {
PyClassMethod::extend_class(context, context.types.classmethod_type);
}
|
mod encoder;
mod decoder;
mod header;
mod huffman;
mod table;
#[cfg(test)]
mod test;
pub use self::decoder::{Decoder, DecoderError, NeedMore};
pub use self::encoder::{Encode, EncodeState, Encoder, EncoderError};
pub use self::header::Header;
|
use core::JsRuntime;
use core::ModuleSpecifier;
use core::RuntimeOptions;
use futures;
use std::path::Path;
fn main() {
let mut runtime = JsRuntime::new(RuntimeOptions {
module_loader: Some(std::rc::Rc::new(core::FsModuleLoader)),
..Default::default()
});
let js_path = Path::new(env!("CARGO_MANIFEST_DIR")).join("examples/javascript/modules/index.js");
let main_module = ModuleSpecifier::resolve_url_or_path(&js_path.to_string_lossy()).expect("Module path not found");
let mod_id = futures::executor::block_on(runtime.load_module(&main_module, None)).expect("Failed to load");
futures::executor::block_on(runtime.mod_evaluate(mod_id)).unwrap();
}
|
use alloc::string::String;
use crate::numeric_traits::*;
use crate::options::FormatSizeOptions;
use crate::ISizeFormatter;
pub fn format_size_i(input: impl ToF64, options: impl AsRef<FormatSizeOptions>) -> String {
format!("{}", ISizeFormatter::new(input, options))
}
pub fn format_size(input: impl ToF64 + Unsigned, options: impl AsRef<FormatSizeOptions>) -> String {
format_size_i(input, &options)
}
pub fn make_format_i<T: ToF64>(options: impl AsRef<FormatSizeOptions>) -> impl Fn(T) -> String {
move |val| -> String { format_size_i(val, &options) }
}
pub fn make_format<T: ToF64 + Unsigned>(
options: impl AsRef<FormatSizeOptions>,
) -> impl Fn(T) -> String {
make_format_i(options)
}
|
use crate::lexer::*;
use crate::parsers::expression::argument::indexing_argument_list;
use crate::parsers::expression::method::method_invocation_without_parenthesis;
use crate::parsers::expression::operator_expression;
use crate::parsers::expression::primary_expression;
use crate::parsers::expression::variable::variable;
use crate::parsers::token::identifier::constant_identifier;
use crate::parsers::token::identifier::local_variable_identifier;
use crate::parsers::token::operator::assignment_operator;
/// *abbreviated_variable_assignment_expression* | *abbreviated_indexing_assignment_expression* | *abbreviated_method_assignment_expression*
pub(crate) fn abbreviated_assignment_expression(i: Input) -> NodeResult {
alt((
abbreviated_variable_assignment_expression,
abbreviated_indexing_assignment_expression,
abbreviated_method_assignment_expression,
))(i)
}
/// *abbreviated_variable_assignment_statement* | *abbreviated_indexing_assignment_statement* | *abbreviated_method_assignment_statement*
pub(crate) fn abbreviated_assignment_statement(i: Input) -> NodeResult {
alt((
abbreviated_variable_assignment_statement,
abbreviated_indexing_assignment_statement,
abbreviated_method_assignment_statement,
))(i)
}
/// *variable* [ no ⏎ ] *assignment_operator* *operator_expression*
pub(crate) fn abbreviated_variable_assignment_expression(i: Input) -> NodeResult {
map(
tuple((
variable,
no_lt,
assignment_operator,
ws0,
operator_expression,
)),
|_| Node::Placeholder,
)(i)
}
/// *variable* [ no ⏎ ] *assignment_operator* *method_invocation_without_parenthesis*
pub(crate) fn abbreviated_variable_assignment_statement(i: Input) -> NodeResult {
map(
tuple((
variable,
no_lt,
assignment_operator,
ws0,
method_invocation_without_parenthesis,
)),
|_| Node::Placeholder,
)(i)
}
/// *primary_expression* [ no ⏎ ] [ no ⎵ ] `[` *indexing_argument_list*? `]` [ no ⏎ ] *assignment_operator* *operator_expression*
pub(crate) fn abbreviated_indexing_assignment_expression(i: Input) -> NodeResult {
map(
tuple((
primary_expression,
char('['),
ws0,
indexing_argument_list,
ws0,
char(']'),
no_lt,
assignment_operator,
ws0,
operator_expression,
)),
|_| Node::Placeholder,
)(i)
}
/// *primary_expression* [ no ⏎ ] [ no ⎵ ] `[` *indexing_argument_list*? `]` [ no ⏎ ] *assignment_operator* *method_invocation_without_parenthesis*
pub(crate) fn abbreviated_indexing_assignment_statement(i: Input) -> NodeResult {
map(
tuple((
primary_expression,
char('['),
ws0,
indexing_argument_list,
ws0,
char(']'),
no_lt,
assignment_operator,
ws0,
method_invocation_without_parenthesis,
)),
|_| Node::Placeholder,
)(i)
}
/// *primary_expression* [ no ⏎ ] ( `.` | `::` ) *local_variable_identifier* [ no ⏎ ] *assignment_operator* *operator_expression* | *primary_expression* [ no ⏎ ] `.` *constant_identifier* [ no ⏎ ] *assignment_operator* *operator_expression*
pub(crate) fn abbreviated_method_assignment_expression(i: Input) -> NodeResult {
alt((
map(
tuple((
primary_expression,
no_lt,
alt((tag("."), tag("::"))),
local_variable_identifier,
no_lt,
assignment_operator,
ws0,
operator_expression,
)),
|_| Node::Placeholder,
),
map(
tuple((
primary_expression,
no_lt,
char('.'),
constant_identifier,
no_lt,
assignment_operator,
ws0,
operator_expression,
)),
|_| Node::Placeholder,
),
))(i)
}
/// *primary_expression* [ no ⏎ ] ( `.` | `::` ) *local_variable_identifier* [ no ⏎ ] *assignment_operator* *method_invocation_without_parenthesis* | *primary_expression* [ no ⏎ ] `.` *constant_identifier* [ no ⏎ ] *assignment_operator* *method_invocation_without_parenthesis*
pub(crate) fn abbreviated_method_assignment_statement(i: Input) -> NodeResult {
alt((
map(
tuple((
primary_expression,
no_lt,
alt((tag("."), tag("::"))),
local_variable_identifier,
no_lt,
assignment_operator,
ws0,
method_invocation_without_parenthesis,
)),
|_| Node::Placeholder,
),
map(
tuple((
primary_expression,
no_lt,
char('.'),
constant_identifier,
no_lt,
assignment_operator,
ws0,
method_invocation_without_parenthesis,
)),
|_| Node::Placeholder,
),
))(i)
}
|
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/// These modules provide access to the component storage.
pub mod stash;
mod keys;
mod serde;
|
mod nix;
mod package;
mod sources;
use color_eyre::eyre;
use eyre::{Report, Result};
use tracing::instrument;
use std::path::{Path, PathBuf};
/*
for reading json AST
https://astexplorer.net
*/
const PATH_TO_EXAMPLE_TOML: &str = "./data/example_config.toml";
#[instrument]
#[tokio::main]
async fn main() -> Result<(), Report> {
install_tracing();
color_eyre::config::HookBuilder::default()
.issue_url(concat!(env!("CARGO_PKG_HOMEPAGE"), "/issues/new"))
.add_issue_metadata("version", env!("CARGO_PKG_VERSION"))
.issue_filter(|kind| match kind {
color_eyre::ErrorKind::NonRecoverable(_) => false,
color_eyre::ErrorKind::Recoverable(_) => true,
})
.install()?;
let manifest = package::TomlManifest::from_file(Path::new(PATH_TO_EXAMPLE_TOML).to_path_buf())?;
let openvsx_packages = manifest.get_openvsx_nixpkgs().await?;
println!("{:#?}", openvsx_packages);
Ok(())
}
fn install_tracing() {
use tracing_error::ErrorLayer;
use tracing_subscriber::prelude::*;
use tracing_subscriber::{fmt, EnvFilter};
let fmt_layer = fmt::layer().with_target(false);
let filter_layer = EnvFilter::try_from_default_env()
.or_else(|_| EnvFilter::try_new("info"))
.unwrap();
tracing_subscriber::registry()
.with(filter_layer)
.with(fmt_layer)
.with(ErrorLayer::default())
.init();
}
|
use byteorder::{LittleEndian, ByteOrder};
use std::fmt;
pub struct Instr(pub Op, pub Mode, pub Cycles);
impl Instr {
pub fn from(code: &[u8]) -> Instr {
let opcode = code[0];
let oper = &code[1..];
match opcode {
0x00 => Instr(Op::Brk, Mode::Impl, Cycles::A(7)),
0x01 => Instr(Op::Ora, Mode::ind_x(oper), Cycles::A(6)),
0x05 => Instr(Op::Ora, Mode::zero(oper), Cycles::A(3)),
0x06 => Instr(Op::Asl, Mode::zero(oper), Cycles::A(5)),
0x08 => Instr(Op::Php, Mode::Impl, Cycles::A(3)),
0x09 => Instr(Op::Ora, Mode::imm(oper), Cycles::A(2)),
0x0a => Instr(Op::Asl, Mode::Acc, Cycles::A(2)),
0x0d => Instr(Op::Ora, Mode::abs(oper), Cycles::A(4)),
0x0e => Instr(Op::Asl, Mode::abs(oper), Cycles::A(6)),
0x10 => Instr(Op::Bpl, Mode::rel(oper), Cycles::C(2)),
0x11 => Instr(Op::Ora, Mode::ind_y(oper), Cycles::B(5)),
0x15 => Instr(Op::Ora, Mode::zero_x(oper), Cycles::A(4)),
0x16 => Instr(Op::Asl, Mode::zero_x(oper), Cycles::A(6)),
0x18 => Instr(Op::Clc, Mode::Impl, Cycles::A(2)),
0x19 => Instr(Op::Ora, Mode::abs_y(oper), Cycles::B(4)),
0x1d => Instr(Op::Ora, Mode::abs_x(oper), Cycles::B(4)),
0x1e => Instr(Op::Asl, Mode::abs_x(oper), Cycles::A(7)),
0x20 => Instr(Op::Jsr, Mode::abs(oper), Cycles::A(6)),
0x21 => Instr(Op::And, Mode::ind_x(oper), Cycles::A(6)),
0x24 => Instr(Op::Bit, Mode::zero(oper), Cycles::A(3)),
0x25 => Instr(Op::And, Mode::zero(oper), Cycles::A(3)),
0x26 => Instr(Op::Rol, Mode::zero(oper), Cycles::A(5)),
0x28 => Instr(Op::Plp, Mode::Impl, Cycles::A(4)),
0x29 => Instr(Op::And, Mode::imm(oper), Cycles::A(2)),
0x2a => Instr(Op::Rol, Mode::Acc, Cycles::A(2)),
0x2c => Instr(Op::Bit, Mode::abs(oper), Cycles::A(4)),
0x2d => Instr(Op::And, Mode::abs(oper), Cycles::A(4)),
0x2e => Instr(Op::Rol, Mode::abs(oper), Cycles::A(6)),
0x30 => Instr(Op::Bmi, Mode::rel(oper), Cycles::C(2)),
0x31 => Instr(Op::And, Mode::ind_y(oper), Cycles::B(5)),
0x35 => Instr(Op::And, Mode::zero_x(oper), Cycles::A(4)),
0x36 => Instr(Op::Rol, Mode::zero(oper), Cycles::A(5)),
0x38 => Instr(Op::Sec, Mode::Impl, Cycles::A(2)),
0x39 => Instr(Op::And, Mode::abs_y(oper), Cycles::B(4)),
0x3d => Instr(Op::And, Mode::abs_x(oper), Cycles::B(4)),
0x3e => Instr(Op::Rol, Mode::abs_x(oper), Cycles::A(7)),
0x40 => Instr(Op::Rti, Mode::Impl, Cycles::A(6)),
0x41 => Instr(Op::Eor, Mode::ind_x(oper), Cycles::A(6)),
0x45 => Instr(Op::Eor, Mode::zero(oper), Cycles::A(3)),
0x46 => Instr(Op::Lsr, Mode::zero(oper), Cycles::A(5)),
0x48 => Instr(Op::Pha, Mode::Impl, Cycles::A(3)),
0x49 => Instr(Op::Eor, Mode::imm(oper), Cycles::A(2)),
0x4a => Instr(Op::Lsr, Mode::Acc, Cycles::A(2)),
0x4c => Instr(Op::Jmp, Mode::abs(oper), Cycles::A(3)),
0x4d => Instr(Op::Eor, Mode::abs(oper), Cycles::A(4)),
0x4e => Instr(Op::Lsr, Mode::abs(oper), Cycles::A(6)),
0x50 => Instr(Op::Bvc, Mode::rel(oper), Cycles::C(2)),
0x51 => Instr(Op::Eor, Mode::ind_y(oper), Cycles::B(5)),
0x55 => Instr(Op::Eor, Mode::zero_x(oper), Cycles::A(4)),
0x56 => Instr(Op::Lsr, Mode::zero_x(oper), Cycles::A(6)),
0x58 => Instr(Op::Cli, Mode::Impl, Cycles::A(2)),
0x59 => Instr(Op::Eor, Mode::abs_y(oper), Cycles::B(4)),
0x5d => Instr(Op::Eor, Mode::abs_x(oper), Cycles::B(4)),
0x5e => Instr(Op::Lsr, Mode::abs_x(oper), Cycles::A(7)),
0x60 => Instr(Op::Rts, Mode::Impl, Cycles::A(6)),
0x61 => Instr(Op::Adc, Mode::ind_x(oper), Cycles::A(6)),
0x65 => Instr(Op::Adc, Mode::zero(oper), Cycles::A(3)),
0x66 => Instr(Op::Ror, Mode::zero(oper), Cycles::A(5)),
0x68 => Instr(Op::Pla, Mode::Impl, Cycles::A(4)),
0x69 => Instr(Op::Adc, Mode::imm(oper), Cycles::A(2)),
0x6a => Instr(Op::Ror, Mode::Acc, Cycles::A(2)),
0x6c => Instr(Op::Jmp, Mode::ind(oper), Cycles::A(5)),
0x6d => Instr(Op::Adc, Mode::abs(oper), Cycles::A(4)),
0x6e => Instr(Op::Ror, Mode::abs(oper), Cycles::A(6)),
0x70 => Instr(Op::Bvs, Mode::rel(oper), Cycles::C(2)),
0x71 => Instr(Op::Adc, Mode::ind_y(oper), Cycles::B(5)),
0x75 => Instr(Op::Adc, Mode::zero_x(oper), Cycles::A(4)),
0x76 => Instr(Op::Ror, Mode::zero_x(oper), Cycles::A(6)),
0x78 => Instr(Op::Sei, Mode::Impl, Cycles::A(2)),
0x79 => Instr(Op::Adc, Mode::abs_y(oper), Cycles::B(4)),
0x7d => Instr(Op::Adc, Mode::abs_x(oper), Cycles::B(4)),
0x7e => Instr(Op::Ror, Mode::abs_x(oper), Cycles::A(7)),
0x81 => Instr(Op::Sta, Mode::ind_x(oper), Cycles::A(6)),
0x84 => Instr(Op::Sty, Mode::zero(oper), Cycles::A(3)),
0x85 => Instr(Op::Sta, Mode::zero(oper), Cycles::A(3)),
0x86 => Instr(Op::Stx, Mode::zero(oper), Cycles::A(3)),
0x88 => Instr(Op::Dey, Mode::Impl, Cycles::A(2)),
0x8a => Instr(Op::Txa, Mode::Impl, Cycles::A(2)),
0x8c => Instr(Op::Sty, Mode::abs(oper), Cycles::A(4)),
0x8d => Instr(Op::Sta, Mode::abs(oper), Cycles::A(4)),
0x8e => Instr(Op::Stx, Mode::abs(oper), Cycles::A(4)),
0x90 => Instr(Op::Bcc, Mode::rel(oper), Cycles::C(2)),
0x91 => Instr(Op::Sta, Mode::ind_y(oper), Cycles::A(6)),
0x94 => Instr(Op::Sty, Mode::zero_x(oper), Cycles::A(4)),
0x95 => Instr(Op::Sta, Mode::zero_x(oper), Cycles::A(4)),
0x96 => Instr(Op::Stx, Mode::zero_y(oper), Cycles::A(4)),
0x98 => Instr(Op::Tya, Mode::Impl, Cycles::A(2)),
0x99 => Instr(Op::Sta, Mode::abs_y(oper), Cycles::A(5)),
0x9a => Instr(Op::Txs, Mode::Impl, Cycles::A(2)),
0x9d => Instr(Op::Sta, Mode::abs_x(oper), Cycles::A(5)),
0xa0 => Instr(Op::Ldy, Mode::imm(oper), Cycles::A(2)),
0xa1 => Instr(Op::Lda, Mode::ind_x(oper), Cycles::A(6)),
0xa2 => Instr(Op::Ldx, Mode::imm(oper), Cycles::A(2)),
0xa4 => Instr(Op::Ldy, Mode::zero(oper), Cycles::A(3)),
0xa5 => Instr(Op::Lda, Mode::zero(oper), Cycles::A(3)),
0xa6 => Instr(Op::Ldx, Mode::zero(oper), Cycles::A(3)),
0xa8 => Instr(Op::Tay, Mode::Impl, Cycles::A(2)),
0xa9 => Instr(Op::Lda, Mode::imm(oper), Cycles::A(2)),
0xaa => Instr(Op::Tax, Mode::Impl, Cycles::A(2)),
0xac => Instr(Op::Ldy, Mode::abs(oper), Cycles::A(4)),
0xad => Instr(Op::Lda, Mode::abs(oper), Cycles::A(4)),
0xae => Instr(Op::Ldx, Mode::abs(oper), Cycles::A(4)),
0xb0 => Instr(Op::Bcs, Mode::rel(oper), Cycles::C(2)),
0xb1 => Instr(Op::Lda, Mode::ind_y(oper), Cycles::B(5)),
0xb4 => Instr(Op::Ldy, Mode::zero_x(oper), Cycles::A(4)),
0xb5 => Instr(Op::Lda, Mode::zero_x(oper), Cycles::A(4)),
0xb6 => Instr(Op::Ldx, Mode::zero_y(oper), Cycles::A(4)),
0xb8 => Instr(Op::Clv, Mode::Impl, Cycles::A(2)),
0xb9 => Instr(Op::Lda, Mode::abs_y(oper), Cycles::B(4)),
0xba => Instr(Op::Tsx, Mode::Impl, Cycles::A(2)),
0xbc => Instr(Op::Ldy, Mode::abs_x(oper), Cycles::B(4)),
0xbd => Instr(Op::Lda, Mode::abs_x(oper), Cycles::B(4)),
0xbe => Instr(Op::Ldx, Mode::abs_y(oper), Cycles::B(4)),
0xc0 => Instr(Op::Cpy, Mode::imm(oper), Cycles::A(2)),
0xc1 => Instr(Op::Cmp, Mode::ind_x(oper), Cycles::A(6)),
0xc4 => Instr(Op::Cpy, Mode::zero(oper), Cycles::A(3)),
0xc5 => Instr(Op::Cmp, Mode::zero(oper), Cycles::A(3)),
0xc6 => Instr(Op::Dec, Mode::zero(oper), Cycles::A(5)),
0xc8 => Instr(Op::Iny, Mode::Impl, Cycles::A(2)),
0xc9 => Instr(Op::Cmp, Mode::imm(oper), Cycles::A(2)),
0xca => Instr(Op::Dex, Mode::Impl, Cycles::A(2)),
0xcc => Instr(Op::Cpy, Mode::abs(oper), Cycles::A(4)),
0xcd => Instr(Op::Cmp, Mode::abs(oper), Cycles::A(4)),
0xce => Instr(Op::Dec, Mode::abs(oper), Cycles::A(3)),
0xd0 => Instr(Op::Bne, Mode::rel(oper), Cycles::C(2)),
0xd1 => Instr(Op::Cmp, Mode::ind_y(oper), Cycles::B(5)),
0xd5 => Instr(Op::Cmp, Mode::zero_x(oper), Cycles::A(4)),
0xd6 => Instr(Op::Dec, Mode::zero_x(oper), Cycles::A(6)),
0xd8 => Instr(Op::Cld, Mode::Impl, Cycles::A(2)),
0xd9 => Instr(Op::Cmp, Mode::abs_y(oper), Cycles::B(4)),
0xdd => Instr(Op::Cmp, Mode::abs_x(oper), Cycles::B(4)),
0xde => Instr(Op::Dec, Mode::abs_x(oper), Cycles::A(7)),
0xe0 => Instr(Op::Cpx, Mode::imm(oper), Cycles::A(2)),
0xe1 => Instr(Op::Sbc, Mode::ind_x(oper), Cycles::A(6)),
0xe4 => Instr(Op::Cpx, Mode::zero(oper), Cycles::A(3)),
0xe5 => Instr(Op::Sbc, Mode::zero(oper), Cycles::A(3)),
0xe6 => Instr(Op::Inc, Mode::zero(oper), Cycles::A(5)),
0xe8 => Instr(Op::Inx, Mode::Impl, Cycles::A(2)),
0xe9 => Instr(Op::Sbc, Mode::imm(oper), Cycles::A(2)),
0xea => Instr(Op::Nop, Mode::Impl, Cycles::A(2)),
0xec => Instr(Op::Cpx, Mode::abs(oper), Cycles::A(4)),
0xed => Instr(Op::Sbc, Mode::abs(oper), Cycles::A(4)),
0xee => Instr(Op::Inc, Mode::abs(oper), Cycles::A(6)),
0xf0 => Instr(Op::Beq, Mode::rel(oper), Cycles::C(2)),
0xf1 => Instr(Op::Sbc, Mode::ind_y(oper), Cycles::B(5)),
0xf5 => Instr(Op::Sbc, Mode::zero_x(oper), Cycles::A(4)),
0xf6 => Instr(Op::Inc, Mode::zero_x(oper), Cycles::A(6)),
0xf8 => Instr(Op::Sed, Mode::Impl, Cycles::A(2)),
0xf9 => Instr(Op::Sbc, Mode::abs_y(oper), Cycles::B(4)),
0xfd => Instr(Op::Sbc, Mode::abs_x(oper), Cycles::B(4)),
0xfe => Instr(Op::Inc, Mode::abs_x(oper), Cycles::A(7)),
other => Instr(Op::Illegal(other), Mode::Impl, Cycles::A(0)),
}
}
}
impl fmt::Debug for Instr {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let op = format!("{:?}", self.0).to_lowercase();
match self.1 {
Mode::Abs(p) => write!(f, "{} ${:04x}", op, p),
Mode::AbsX(p) => write!(f, "{} ${:04x},x", op, p),
Mode::AbsY(p) => write!(f, "{} ${:04x},y", op, p),
Mode::Acc => write!(f, "{}", op),
Mode::Imm(p) => write!(f, "{} #${:02x}", op, p),
Mode::Impl => write!(f, "{}", op),
Mode::Ind(p) => write!(f, "{} (${:04x})", op, p),
Mode::IndX(p) => write!(f, "{} (${:02x},x)", op, p),
Mode::IndY(p) => write!(f, "{} (${:02x}),y", op, p),
Mode::Rel(p) => write!(f, "{} ${:02x}", op, p),
Mode::Zero(p) => write!(f, "{} ${:02x}", op, p),
Mode::ZeroX(p) => write!(f, "{} ${:02x},x", op, p),
Mode::ZeroY(p) => write!(f, "{} ${:02x},y", op, p),
}
}
}
#[derive(Debug)]
pub enum Op {
Adc,
And,
Asl,
Bcc,
Bcs,
Beq,
Bit,
Bmi,
Bne,
Bpl,
Brk,
Bvc,
Bvs,
Clc,
Cld,
Cli,
Clv,
Cmp,
Cpx,
Cpy,
Dec,
Dex,
Dey,
Eor,
Inc,
Inx,
Iny,
Jmp,
Jsr,
Lda,
Ldx,
Ldy,
Lsr,
Nop,
Ora,
Pha,
Php,
Pla,
Plp,
Rol,
Ror,
Rti,
Rts,
Sbc,
Sec,
Sed,
Sei,
Slo,
Sta,
Stx,
Sty,
Stp,
Tax,
Tay,
Tsx,
Txa,
Txs,
Tya,
Illegal(u8),
}
#[derive(Clone, Copy, Debug)]
pub enum Mode {
Abs(u16),
AbsX(u16),
AbsY(u16),
Acc,
Imm(u8),
Impl,
Ind(u16),
IndX(u8),
IndY(u8),
Rel(i8),
Zero(u8),
ZeroX(u8),
ZeroY(u8),
}
impl Mode {
pub fn payload_len(self) -> u16 {
match self {
Mode::Abs(_) => 2,
Mode::AbsX(_) => 2,
Mode::AbsY(_) => 2,
Mode::Acc => 0,
Mode::Imm(_) => 1,
Mode::Impl => 0,
Mode::Ind(_) => 2,
Mode::IndX(_) => 1,
Mode::IndY(_) => 1,
Mode::Rel(_) => 1,
Mode::Zero(_) => 1,
Mode::ZeroX(_) => 1,
Mode::ZeroY(_) => 1,
}
}
fn abs(oper: &[u8]) -> Mode {
Mode::Abs(LittleEndian::read_u16(oper))
}
fn abs_x(oper: &[u8]) -> Mode {
Mode::AbsX(LittleEndian::read_u16(oper))
}
fn abs_y(oper: &[u8]) -> Mode {
Mode::AbsY(LittleEndian::read_u16(oper))
}
fn imm(oper: &[u8]) -> Mode {
Mode::Imm(oper[0])
}
fn ind(oper: &[u8]) -> Mode {
Mode::Ind(LittleEndian::read_u16(oper))
}
fn ind_x(oper: &[u8]) -> Mode {
Mode::IndX(oper[0])
}
fn ind_y(oper: &[u8]) -> Mode {
Mode::IndY(oper[0])
}
fn rel(oper: &[u8]) -> Mode {
Mode::Rel(oper[0] as i8)
}
fn zero(oper: &[u8]) -> Mode {
Mode::Zero(oper[0])
}
fn zero_x(oper: &[u8]) -> Mode {
Mode::ZeroX(oper[0])
}
fn zero_y(oper: &[u8]) -> Mode {
Mode::ZeroY(oper[0])
}
}
#[derive(Clone, Copy, Debug)]
pub enum Cycles {
A(u8),
B(u8), // +1 if page boundary crossed
C(u8), // +1 if branch on same page; +2 if branch on different page
}
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//compile-flags: -Z borrowck=mir
#![feature(slice_patterns)]
fn mut_head_tail<'a, A>(v: &'a mut [A]) -> Option<(&'a mut A, &'a mut [A])> {
match *v {
[ref mut head, ref mut tail..] => {
Some((head, tail))
}
[] => None
}
}
fn main() {
let mut v = [1,2,3,4];
match mut_head_tail(&mut v) {
None => {},
Some((h,t)) => {
*h = 1000;
t.reverse();
}
}
}
|
extern crate rustpusher_cpu;
#[macro_use]
extern crate libretro_backend;
use rustpusher_cpu::*;
use libretro_backend::*;
pub struct RPCore {
cpu: Cpu,
palette: [(u8, u8, u8, u8); 256],
video_buffer: [u8; BANK * 4],
audio_buffer: Vec<(i16, i16)>,
game_data: Option<GameData>,
}
impl RPCore {
fn new() -> Self {
RPCore {
cpu: Cpu::new(),
palette: Self::default_palette(),
video_buffer: [0; BANK * 4],
audio_buffer: Vec::with_capacity(512),
game_data: None,
}
}
fn default_palette() -> [(u8, u8, u8, u8); 256] {
let mut palette = [(0, 0, 0, 0); 256];
for (index, out) in palette.iter_mut().enumerate() {
*out = match index {
0x00...0xd7 => {
(
(index as u32 / 36 * 0x33) as u8,
(index as u32 / 6 % 6 * 0x33) as u8,
(index as u32 % 6 * 0x33) as u8,
0,
)
}
_ => (0, 0, 0, 0),
}
}
palette
}
}
impl Default for RPCore {
fn default() -> Self {
Self::new()
}
}
impl Core for RPCore {
fn info() -> CoreInfo {
CoreInfo::new("Rustpusher", env!("CARGO_PKG_VERSION"))
.supports_roms_with_extension(".BytePusher")
}
fn on_load_game(&mut self, game_data: GameData) -> LoadGameResult {
if game_data.is_empty() {
return LoadGameResult::Failed(game_data);
}
match if let Some(data) = game_data.data() {
self.cpu.load_data(data)
} else if let Some(path) = game_data.path() {
self.cpu.load_file(path)
} else {
panic!("Unable to load game data")
} {
Ok(_) => {
self.game_data = Some(game_data);
LoadGameResult::Success(
AudioVideoInfo::new()
.video(256, 256, 60.0, PixelFormat::ARGB8888)
.audio(SAMPLE_RATE as _),
)
}
Err(_) => LoadGameResult::Failed(game_data),
}
}
fn on_unload_game(&mut self) -> GameData {
self.cpu.clear_memory();
self.game_data.take().unwrap()
}
fn on_run(&mut self, handle: &mut RuntimeHandle) {
macro_rules! update_input {
( $player:expr, $( $button:ident => $expr:expr ,)* ) => (
#[allow(unused_imports)]
use JoypadButton::*;
$( if handle.is_joypad_button_pressed($player, $button) { $expr } )*
)
}
let mut input = (0u8, 0u8);
update_input!(0,
Up => input.0 |= 0x1,
Down => input.0 |= 0x2,
Left => input.0 |= 0x4,
Right => input.0 |= 0x8,
A => input.0 |= 0x10,
B => input.0 |= 0x20,
X => input.0 |= 0x40,
Y => input.0 |= 0x80,
);
update_input!(1,
Up => input.1 |= 0x1,
Down => input.1 |= 0x2,
Left => input.1 |= 0x4,
Right => input.1 |= 0x8,
A => input.1 |= 0x10,
B => input.1 |= 0x20,
X => input.1 |= 0x40,
Y => input.1 |= 0x80,
);
self.cpu.process_input(input);
self.cpu.finish_frame();
for (index, &pixel) in self.cpu.get_video_slice().iter().enumerate() {
let (r, g, b, a) = self.palette[pixel as usize];
self.video_buffer[index * 4 + 0] = r;
self.video_buffer[index * 4 + 1] = g;
self.video_buffer[index * 4 + 2] = b;
self.video_buffer[index * 4 + 3] = a;
}
handle.upload_video_frame(&self.video_buffer);
for &x in self.cpu.get_audio_slice().iter() {
let x = (x as i16) << 8;
self.audio_buffer.push((x, x));
}
handle.upload_audio_frame(&self.audio_buffer[..]);
self.audio_buffer.clear();
}
fn on_reset(&mut self) {
if let Some(ref game_data) = self.game_data {
if let Some(data) = game_data.data() {
let _ = self.cpu.load_data(data);
} else if let Some(path) = game_data.path() {
let _ = self.cpu.load_file(path);
}
}
}
}
libretro_core!(RPCore);
|
// auto generated, do not modify.
// created: Mon Feb 22 23:57:02 2016
// src-file: /QtWidgets/qtabbar.h
// dst-file: /src/widgets/qtabbar.rs
//
// header block begin =>
#![feature(libc)]
#![feature(core)]
#![feature(collections)]
extern crate libc;
use self::libc::*;
// <= header block end
// main block begin =>
// <= main block end
// use block begin =>
use super::qwidget::*; // 773
use std::ops::Deref;
use super::super::core::qstring::*; // 771
use super::super::gui::qicon::*; // 771
use super::super::core::qsize::*; // 771
use super::super::core::qobjectdefs::*; // 771
use super::super::core::qrect::*; // 771
use super::super::core::qpoint::*; // 771
use super::super::core::qvariant::*; // 771
use super::super::gui::qcolor::*; // 771
// <= use block end
// ext block begin =>
// #[link(name = "Qt5Core")]
// #[link(name = "Qt5Gui")]
// #[link(name = "Qt5Widgets")]
// #[link(name = "QtInline")]
extern {
fn QTabBar_Class_Size() -> c_int;
// proto: bool QTabBar::usesScrollButtons();
fn C_ZNK7QTabBar17usesScrollButtonsEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: bool QTabBar::autoHide();
fn C_ZNK7QTabBar8autoHideEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: QString QTabBar::tabToolTip(int index);
fn C_ZNK7QTabBar10tabToolTipEi(qthis: u64 /* *mut c_void*/, arg0: c_int) -> *mut c_void;
// proto: bool QTabBar::expanding();
fn C_ZNK7QTabBar9expandingEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: void QTabBar::setDocumentMode(bool set);
fn C_ZN7QTabBar15setDocumentModeEb(qthis: u64 /* *mut c_void*/, arg0: c_char);
// proto: int QTabBar::count();
fn C_ZNK7QTabBar5countEv(qthis: u64 /* *mut c_void*/) -> c_int;
// proto: void QTabBar::setChangeCurrentOnDrag(bool change);
fn C_ZN7QTabBar22setChangeCurrentOnDragEb(qthis: u64 /* *mut c_void*/, arg0: c_char);
// proto: QIcon QTabBar::tabIcon(int index);
fn C_ZNK7QTabBar7tabIconEi(qthis: u64 /* *mut c_void*/, arg0: c_int) -> *mut c_void;
// proto: QSize QTabBar::minimumSizeHint();
fn C_ZNK7QTabBar15minimumSizeHintEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QTabBar::setTabsClosable(bool closable);
fn C_ZN7QTabBar15setTabsClosableEb(qthis: u64 /* *mut c_void*/, arg0: c_char);
// proto: bool QTabBar::changeCurrentOnDrag();
fn C_ZNK7QTabBar19changeCurrentOnDragEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: void QTabBar::setTabWhatsThis(int index, const QString & text);
fn C_ZN7QTabBar15setTabWhatsThisEiRK7QString(qthis: u64 /* *mut c_void*/, arg0: c_int, arg1: *mut c_void);
// proto: const QMetaObject * QTabBar::metaObject();
fn C_ZNK7QTabBar10metaObjectEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: int QTabBar::insertTab(int index, const QIcon & icon, const QString & text);
fn C_ZN7QTabBar9insertTabEiRK5QIconRK7QString(qthis: u64 /* *mut c_void*/, arg0: c_int, arg1: *mut c_void, arg2: *mut c_void) -> c_int;
// proto: void QTabBar::setTabIcon(int index, const QIcon & icon);
fn C_ZN7QTabBar10setTabIconEiRK5QIcon(qthis: u64 /* *mut c_void*/, arg0: c_int, arg1: *mut c_void);
// proto: bool QTabBar::isMovable();
fn C_ZNK7QTabBar9isMovableEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: void QTabBar::setExpanding(bool enabled);
fn C_ZN7QTabBar12setExpandingEb(qthis: u64 /* *mut c_void*/, arg0: c_char);
// proto: void QTabBar::removeTab(int index);
fn C_ZN7QTabBar9removeTabEi(qthis: u64 /* *mut c_void*/, arg0: c_int);
// proto: void QTabBar::setTabEnabled(int index, bool );
fn C_ZN7QTabBar13setTabEnabledEib(qthis: u64 /* *mut c_void*/, arg0: c_int, arg1: c_char);
// proto: bool QTabBar::isTabEnabled(int index);
fn C_ZNK7QTabBar12isTabEnabledEi(qthis: u64 /* *mut c_void*/, arg0: c_int) -> c_char;
// proto: void QTabBar::setCurrentIndex(int index);
fn C_ZN7QTabBar15setCurrentIndexEi(qthis: u64 /* *mut c_void*/, arg0: c_int);
// proto: QRect QTabBar::tabRect(int index);
fn C_ZNK7QTabBar7tabRectEi(qthis: u64 /* *mut c_void*/, arg0: c_int) -> *mut c_void;
// proto: bool QTabBar::tabsClosable();
fn C_ZNK7QTabBar12tabsClosableEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: void QTabBar::setMovable(bool movable);
fn C_ZN7QTabBar10setMovableEb(qthis: u64 /* *mut c_void*/, arg0: c_char);
// proto: void QTabBar::setAutoHide(bool hide);
fn C_ZN7QTabBar11setAutoHideEb(qthis: u64 /* *mut c_void*/, arg0: c_char);
// proto: QSize QTabBar::iconSize();
fn C_ZNK7QTabBar8iconSizeEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: QString QTabBar::tabText(int index);
fn C_ZNK7QTabBar7tabTextEi(qthis: u64 /* *mut c_void*/, arg0: c_int) -> *mut c_void;
// proto: QString QTabBar::tabWhatsThis(int index);
fn C_ZNK7QTabBar12tabWhatsThisEi(qthis: u64 /* *mut c_void*/, arg0: c_int) -> *mut c_void;
// proto: bool QTabBar::documentMode();
fn C_ZNK7QTabBar12documentModeEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: int QTabBar::tabAt(const QPoint & pos);
fn C_ZNK7QTabBar5tabAtERK6QPoint(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> c_int;
// proto: void QTabBar::setTabData(int index, const QVariant & data);
fn C_ZN7QTabBar10setTabDataEiRK8QVariant(qthis: u64 /* *mut c_void*/, arg0: c_int, arg1: *mut c_void);
// proto: void QTabBar::QTabBar(QWidget * parent);
fn C_ZN7QTabBarC2EP7QWidget(arg0: *mut c_void) -> u64;
// proto: QColor QTabBar::tabTextColor(int index);
fn C_ZNK7QTabBar12tabTextColorEi(qthis: u64 /* *mut c_void*/, arg0: c_int) -> *mut c_void;
// proto: void QTabBar::~QTabBar();
fn C_ZN7QTabBarD2Ev(qthis: u64 /* *mut c_void*/);
// proto: int QTabBar::insertTab(int index, const QString & text);
fn C_ZN7QTabBar9insertTabEiRK7QString(qthis: u64 /* *mut c_void*/, arg0: c_int, arg1: *mut c_void) -> c_int;
// proto: int QTabBar::addTab(const QString & text);
fn C_ZN7QTabBar6addTabERK7QString(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> c_int;
// proto: int QTabBar::addTab(const QIcon & icon, const QString & text);
fn C_ZN7QTabBar6addTabERK5QIconRK7QString(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void) -> c_int;
// proto: void QTabBar::setTabToolTip(int index, const QString & tip);
fn C_ZN7QTabBar13setTabToolTipEiRK7QString(qthis: u64 /* *mut c_void*/, arg0: c_int, arg1: *mut c_void);
// proto: void QTabBar::setTabTextColor(int index, const QColor & color);
fn C_ZN7QTabBar15setTabTextColorEiRK6QColor(qthis: u64 /* *mut c_void*/, arg0: c_int, arg1: *mut c_void);
// proto: void QTabBar::moveTab(int from, int to);
fn C_ZN7QTabBar7moveTabEii(qthis: u64 /* *mut c_void*/, arg0: c_int, arg1: c_int);
// proto: QVariant QTabBar::tabData(int index);
fn C_ZNK7QTabBar7tabDataEi(qthis: u64 /* *mut c_void*/, arg0: c_int) -> *mut c_void;
// proto: bool QTabBar::drawBase();
fn C_ZNK7QTabBar8drawBaseEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: int QTabBar::currentIndex();
fn C_ZNK7QTabBar12currentIndexEv(qthis: u64 /* *mut c_void*/) -> c_int;
// proto: void QTabBar::setDrawBase(bool drawTheBase);
fn C_ZN7QTabBar11setDrawBaseEb(qthis: u64 /* *mut c_void*/, arg0: c_char);
// proto: void QTabBar::setUsesScrollButtons(bool useButtons);
fn C_ZN7QTabBar20setUsesScrollButtonsEb(qthis: u64 /* *mut c_void*/, arg0: c_char);
// proto: QSize QTabBar::sizeHint();
fn C_ZNK7QTabBar8sizeHintEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QTabBar::setIconSize(const QSize & size);
fn C_ZN7QTabBar11setIconSizeERK5QSize(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: void QTabBar::setTabText(int index, const QString & text);
fn C_ZN7QTabBar10setTabTextEiRK7QString(qthis: u64 /* *mut c_void*/, arg0: c_int, arg1: *mut c_void);
fn QTabBar_SlotProxy_connect__ZN7QTabBar13tabBarClickedEi(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
fn QTabBar_SlotProxy_connect__ZN7QTabBar19tabBarDoubleClickedEi(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
fn QTabBar_SlotProxy_connect__ZN7QTabBar17tabCloseRequestedEi(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
fn QTabBar_SlotProxy_connect__ZN7QTabBar8tabMovedEii(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
fn QTabBar_SlotProxy_connect__ZN7QTabBar14currentChangedEi(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
} // <= ext block end
// body block begin =>
// class sizeof(QTabBar)=1
#[derive(Default)]
pub struct QTabBar {
qbase: QWidget,
pub qclsinst: u64 /* *mut c_void*/,
pub _tabCloseRequested: QTabBar_tabCloseRequested_signal,
pub _tabBarDoubleClicked: QTabBar_tabBarDoubleClicked_signal,
pub _tabMoved: QTabBar_tabMoved_signal,
pub _tabBarClicked: QTabBar_tabBarClicked_signal,
pub _currentChanged: QTabBar_currentChanged_signal,
}
impl /*struct*/ QTabBar {
pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QTabBar {
return QTabBar{qbase: QWidget::inheritFrom(qthis), qclsinst: qthis, ..Default::default()};
}
}
impl Deref for QTabBar {
type Target = QWidget;
fn deref(&self) -> &QWidget {
return & self.qbase;
}
}
impl AsRef<QWidget> for QTabBar {
fn as_ref(& self) -> & QWidget {
return & self.qbase;
}
}
// proto: bool QTabBar::usesScrollButtons();
impl /*struct*/ QTabBar {
pub fn usesScrollButtons<RetType, T: QTabBar_usesScrollButtons<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.usesScrollButtons(self);
// return 1;
}
}
pub trait QTabBar_usesScrollButtons<RetType> {
fn usesScrollButtons(self , rsthis: & QTabBar) -> RetType;
}
// proto: bool QTabBar::usesScrollButtons();
impl<'a> /*trait*/ QTabBar_usesScrollButtons<i8> for () {
fn usesScrollButtons(self , rsthis: & QTabBar) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK7QTabBar17usesScrollButtonsEv()};
let mut ret = unsafe {C_ZNK7QTabBar17usesScrollButtonsEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: bool QTabBar::autoHide();
impl /*struct*/ QTabBar {
pub fn autoHide<RetType, T: QTabBar_autoHide<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.autoHide(self);
// return 1;
}
}
pub trait QTabBar_autoHide<RetType> {
fn autoHide(self , rsthis: & QTabBar) -> RetType;
}
// proto: bool QTabBar::autoHide();
impl<'a> /*trait*/ QTabBar_autoHide<i8> for () {
fn autoHide(self , rsthis: & QTabBar) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK7QTabBar8autoHideEv()};
let mut ret = unsafe {C_ZNK7QTabBar8autoHideEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: QString QTabBar::tabToolTip(int index);
impl /*struct*/ QTabBar {
pub fn tabToolTip<RetType, T: QTabBar_tabToolTip<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.tabToolTip(self);
// return 1;
}
}
pub trait QTabBar_tabToolTip<RetType> {
fn tabToolTip(self , rsthis: & QTabBar) -> RetType;
}
// proto: QString QTabBar::tabToolTip(int index);
impl<'a> /*trait*/ QTabBar_tabToolTip<QString> for (i32) {
fn tabToolTip(self , rsthis: & QTabBar) -> QString {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK7QTabBar10tabToolTipEi()};
let arg0 = self as c_int;
let mut ret = unsafe {C_ZNK7QTabBar10tabToolTipEi(rsthis.qclsinst, arg0)};
let mut ret1 = QString::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: bool QTabBar::expanding();
impl /*struct*/ QTabBar {
pub fn expanding<RetType, T: QTabBar_expanding<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.expanding(self);
// return 1;
}
}
pub trait QTabBar_expanding<RetType> {
fn expanding(self , rsthis: & QTabBar) -> RetType;
}
// proto: bool QTabBar::expanding();
impl<'a> /*trait*/ QTabBar_expanding<i8> for () {
fn expanding(self , rsthis: & QTabBar) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK7QTabBar9expandingEv()};
let mut ret = unsafe {C_ZNK7QTabBar9expandingEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: void QTabBar::setDocumentMode(bool set);
impl /*struct*/ QTabBar {
pub fn setDocumentMode<RetType, T: QTabBar_setDocumentMode<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setDocumentMode(self);
// return 1;
}
}
pub trait QTabBar_setDocumentMode<RetType> {
fn setDocumentMode(self , rsthis: & QTabBar) -> RetType;
}
// proto: void QTabBar::setDocumentMode(bool set);
impl<'a> /*trait*/ QTabBar_setDocumentMode<()> for (i8) {
fn setDocumentMode(self , rsthis: & QTabBar) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN7QTabBar15setDocumentModeEb()};
let arg0 = self as c_char;
unsafe {C_ZN7QTabBar15setDocumentModeEb(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: int QTabBar::count();
impl /*struct*/ QTabBar {
pub fn count<RetType, T: QTabBar_count<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.count(self);
// return 1;
}
}
pub trait QTabBar_count<RetType> {
fn count(self , rsthis: & QTabBar) -> RetType;
}
// proto: int QTabBar::count();
impl<'a> /*trait*/ QTabBar_count<i32> for () {
fn count(self , rsthis: & QTabBar) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK7QTabBar5countEv()};
let mut ret = unsafe {C_ZNK7QTabBar5countEv(rsthis.qclsinst)};
return ret as i32; // 1
// return 1;
}
}
// proto: void QTabBar::setChangeCurrentOnDrag(bool change);
impl /*struct*/ QTabBar {
pub fn setChangeCurrentOnDrag<RetType, T: QTabBar_setChangeCurrentOnDrag<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setChangeCurrentOnDrag(self);
// return 1;
}
}
pub trait QTabBar_setChangeCurrentOnDrag<RetType> {
fn setChangeCurrentOnDrag(self , rsthis: & QTabBar) -> RetType;
}
// proto: void QTabBar::setChangeCurrentOnDrag(bool change);
impl<'a> /*trait*/ QTabBar_setChangeCurrentOnDrag<()> for (i8) {
fn setChangeCurrentOnDrag(self , rsthis: & QTabBar) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN7QTabBar22setChangeCurrentOnDragEb()};
let arg0 = self as c_char;
unsafe {C_ZN7QTabBar22setChangeCurrentOnDragEb(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: QIcon QTabBar::tabIcon(int index);
impl /*struct*/ QTabBar {
pub fn tabIcon<RetType, T: QTabBar_tabIcon<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.tabIcon(self);
// return 1;
}
}
pub trait QTabBar_tabIcon<RetType> {
fn tabIcon(self , rsthis: & QTabBar) -> RetType;
}
// proto: QIcon QTabBar::tabIcon(int index);
impl<'a> /*trait*/ QTabBar_tabIcon<QIcon> for (i32) {
fn tabIcon(self , rsthis: & QTabBar) -> QIcon {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK7QTabBar7tabIconEi()};
let arg0 = self as c_int;
let mut ret = unsafe {C_ZNK7QTabBar7tabIconEi(rsthis.qclsinst, arg0)};
let mut ret1 = QIcon::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QSize QTabBar::minimumSizeHint();
impl /*struct*/ QTabBar {
pub fn minimumSizeHint<RetType, T: QTabBar_minimumSizeHint<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.minimumSizeHint(self);
// return 1;
}
}
pub trait QTabBar_minimumSizeHint<RetType> {
fn minimumSizeHint(self , rsthis: & QTabBar) -> RetType;
}
// proto: QSize QTabBar::minimumSizeHint();
impl<'a> /*trait*/ QTabBar_minimumSizeHint<QSize> for () {
fn minimumSizeHint(self , rsthis: & QTabBar) -> QSize {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK7QTabBar15minimumSizeHintEv()};
let mut ret = unsafe {C_ZNK7QTabBar15minimumSizeHintEv(rsthis.qclsinst)};
let mut ret1 = QSize::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QTabBar::setTabsClosable(bool closable);
impl /*struct*/ QTabBar {
pub fn setTabsClosable<RetType, T: QTabBar_setTabsClosable<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setTabsClosable(self);
// return 1;
}
}
pub trait QTabBar_setTabsClosable<RetType> {
fn setTabsClosable(self , rsthis: & QTabBar) -> RetType;
}
// proto: void QTabBar::setTabsClosable(bool closable);
impl<'a> /*trait*/ QTabBar_setTabsClosable<()> for (i8) {
fn setTabsClosable(self , rsthis: & QTabBar) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN7QTabBar15setTabsClosableEb()};
let arg0 = self as c_char;
unsafe {C_ZN7QTabBar15setTabsClosableEb(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: bool QTabBar::changeCurrentOnDrag();
impl /*struct*/ QTabBar {
pub fn changeCurrentOnDrag<RetType, T: QTabBar_changeCurrentOnDrag<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.changeCurrentOnDrag(self);
// return 1;
}
}
pub trait QTabBar_changeCurrentOnDrag<RetType> {
fn changeCurrentOnDrag(self , rsthis: & QTabBar) -> RetType;
}
// proto: bool QTabBar::changeCurrentOnDrag();
impl<'a> /*trait*/ QTabBar_changeCurrentOnDrag<i8> for () {
fn changeCurrentOnDrag(self , rsthis: & QTabBar) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK7QTabBar19changeCurrentOnDragEv()};
let mut ret = unsafe {C_ZNK7QTabBar19changeCurrentOnDragEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: void QTabBar::setTabWhatsThis(int index, const QString & text);
impl /*struct*/ QTabBar {
pub fn setTabWhatsThis<RetType, T: QTabBar_setTabWhatsThis<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setTabWhatsThis(self);
// return 1;
}
}
pub trait QTabBar_setTabWhatsThis<RetType> {
fn setTabWhatsThis(self , rsthis: & QTabBar) -> RetType;
}
// proto: void QTabBar::setTabWhatsThis(int index, const QString & text);
impl<'a> /*trait*/ QTabBar_setTabWhatsThis<()> for (i32, &'a QString) {
fn setTabWhatsThis(self , rsthis: & QTabBar) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN7QTabBar15setTabWhatsThisEiRK7QString()};
let arg0 = self.0 as c_int;
let arg1 = self.1.qclsinst as *mut c_void;
unsafe {C_ZN7QTabBar15setTabWhatsThisEiRK7QString(rsthis.qclsinst, arg0, arg1)};
// return 1;
}
}
// proto: const QMetaObject * QTabBar::metaObject();
impl /*struct*/ QTabBar {
pub fn metaObject<RetType, T: QTabBar_metaObject<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.metaObject(self);
// return 1;
}
}
pub trait QTabBar_metaObject<RetType> {
fn metaObject(self , rsthis: & QTabBar) -> RetType;
}
// proto: const QMetaObject * QTabBar::metaObject();
impl<'a> /*trait*/ QTabBar_metaObject<QMetaObject> for () {
fn metaObject(self , rsthis: & QTabBar) -> QMetaObject {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK7QTabBar10metaObjectEv()};
let mut ret = unsafe {C_ZNK7QTabBar10metaObjectEv(rsthis.qclsinst)};
let mut ret1 = QMetaObject::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: int QTabBar::insertTab(int index, const QIcon & icon, const QString & text);
impl /*struct*/ QTabBar {
pub fn insertTab<RetType, T: QTabBar_insertTab<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.insertTab(self);
// return 1;
}
}
pub trait QTabBar_insertTab<RetType> {
fn insertTab(self , rsthis: & QTabBar) -> RetType;
}
// proto: int QTabBar::insertTab(int index, const QIcon & icon, const QString & text);
impl<'a> /*trait*/ QTabBar_insertTab<i32> for (i32, &'a QIcon, &'a QString) {
fn insertTab(self , rsthis: & QTabBar) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN7QTabBar9insertTabEiRK5QIconRK7QString()};
let arg0 = self.0 as c_int;
let arg1 = self.1.qclsinst as *mut c_void;
let arg2 = self.2.qclsinst as *mut c_void;
let mut ret = unsafe {C_ZN7QTabBar9insertTabEiRK5QIconRK7QString(rsthis.qclsinst, arg0, arg1, arg2)};
return ret as i32; // 1
// return 1;
}
}
// proto: void QTabBar::setTabIcon(int index, const QIcon & icon);
impl /*struct*/ QTabBar {
pub fn setTabIcon<RetType, T: QTabBar_setTabIcon<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setTabIcon(self);
// return 1;
}
}
pub trait QTabBar_setTabIcon<RetType> {
fn setTabIcon(self , rsthis: & QTabBar) -> RetType;
}
// proto: void QTabBar::setTabIcon(int index, const QIcon & icon);
impl<'a> /*trait*/ QTabBar_setTabIcon<()> for (i32, &'a QIcon) {
fn setTabIcon(self , rsthis: & QTabBar) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN7QTabBar10setTabIconEiRK5QIcon()};
let arg0 = self.0 as c_int;
let arg1 = self.1.qclsinst as *mut c_void;
unsafe {C_ZN7QTabBar10setTabIconEiRK5QIcon(rsthis.qclsinst, arg0, arg1)};
// return 1;
}
}
// proto: bool QTabBar::isMovable();
impl /*struct*/ QTabBar {
pub fn isMovable<RetType, T: QTabBar_isMovable<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isMovable(self);
// return 1;
}
}
pub trait QTabBar_isMovable<RetType> {
fn isMovable(self , rsthis: & QTabBar) -> RetType;
}
// proto: bool QTabBar::isMovable();
impl<'a> /*trait*/ QTabBar_isMovable<i8> for () {
fn isMovable(self , rsthis: & QTabBar) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK7QTabBar9isMovableEv()};
let mut ret = unsafe {C_ZNK7QTabBar9isMovableEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: void QTabBar::setExpanding(bool enabled);
impl /*struct*/ QTabBar {
pub fn setExpanding<RetType, T: QTabBar_setExpanding<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setExpanding(self);
// return 1;
}
}
pub trait QTabBar_setExpanding<RetType> {
fn setExpanding(self , rsthis: & QTabBar) -> RetType;
}
// proto: void QTabBar::setExpanding(bool enabled);
impl<'a> /*trait*/ QTabBar_setExpanding<()> for (i8) {
fn setExpanding(self , rsthis: & QTabBar) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN7QTabBar12setExpandingEb()};
let arg0 = self as c_char;
unsafe {C_ZN7QTabBar12setExpandingEb(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QTabBar::removeTab(int index);
impl /*struct*/ QTabBar {
pub fn removeTab<RetType, T: QTabBar_removeTab<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.removeTab(self);
// return 1;
}
}
pub trait QTabBar_removeTab<RetType> {
fn removeTab(self , rsthis: & QTabBar) -> RetType;
}
// proto: void QTabBar::removeTab(int index);
impl<'a> /*trait*/ QTabBar_removeTab<()> for (i32) {
fn removeTab(self , rsthis: & QTabBar) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN7QTabBar9removeTabEi()};
let arg0 = self as c_int;
unsafe {C_ZN7QTabBar9removeTabEi(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QTabBar::setTabEnabled(int index, bool );
impl /*struct*/ QTabBar {
pub fn setTabEnabled<RetType, T: QTabBar_setTabEnabled<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setTabEnabled(self);
// return 1;
}
}
pub trait QTabBar_setTabEnabled<RetType> {
fn setTabEnabled(self , rsthis: & QTabBar) -> RetType;
}
// proto: void QTabBar::setTabEnabled(int index, bool );
impl<'a> /*trait*/ QTabBar_setTabEnabled<()> for (i32, i8) {
fn setTabEnabled(self , rsthis: & QTabBar) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN7QTabBar13setTabEnabledEib()};
let arg0 = self.0 as c_int;
let arg1 = self.1 as c_char;
unsafe {C_ZN7QTabBar13setTabEnabledEib(rsthis.qclsinst, arg0, arg1)};
// return 1;
}
}
// proto: bool QTabBar::isTabEnabled(int index);
impl /*struct*/ QTabBar {
pub fn isTabEnabled<RetType, T: QTabBar_isTabEnabled<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isTabEnabled(self);
// return 1;
}
}
pub trait QTabBar_isTabEnabled<RetType> {
fn isTabEnabled(self , rsthis: & QTabBar) -> RetType;
}
// proto: bool QTabBar::isTabEnabled(int index);
impl<'a> /*trait*/ QTabBar_isTabEnabled<i8> for (i32) {
fn isTabEnabled(self , rsthis: & QTabBar) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK7QTabBar12isTabEnabledEi()};
let arg0 = self as c_int;
let mut ret = unsafe {C_ZNK7QTabBar12isTabEnabledEi(rsthis.qclsinst, arg0)};
return ret as i8; // 1
// return 1;
}
}
// proto: void QTabBar::setCurrentIndex(int index);
impl /*struct*/ QTabBar {
pub fn setCurrentIndex<RetType, T: QTabBar_setCurrentIndex<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setCurrentIndex(self);
// return 1;
}
}
pub trait QTabBar_setCurrentIndex<RetType> {
fn setCurrentIndex(self , rsthis: & QTabBar) -> RetType;
}
// proto: void QTabBar::setCurrentIndex(int index);
impl<'a> /*trait*/ QTabBar_setCurrentIndex<()> for (i32) {
fn setCurrentIndex(self , rsthis: & QTabBar) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN7QTabBar15setCurrentIndexEi()};
let arg0 = self as c_int;
unsafe {C_ZN7QTabBar15setCurrentIndexEi(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: QRect QTabBar::tabRect(int index);
impl /*struct*/ QTabBar {
pub fn tabRect<RetType, T: QTabBar_tabRect<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.tabRect(self);
// return 1;
}
}
pub trait QTabBar_tabRect<RetType> {
fn tabRect(self , rsthis: & QTabBar) -> RetType;
}
// proto: QRect QTabBar::tabRect(int index);
impl<'a> /*trait*/ QTabBar_tabRect<QRect> for (i32) {
fn tabRect(self , rsthis: & QTabBar) -> QRect {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK7QTabBar7tabRectEi()};
let arg0 = self as c_int;
let mut ret = unsafe {C_ZNK7QTabBar7tabRectEi(rsthis.qclsinst, arg0)};
let mut ret1 = QRect::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: bool QTabBar::tabsClosable();
impl /*struct*/ QTabBar {
pub fn tabsClosable<RetType, T: QTabBar_tabsClosable<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.tabsClosable(self);
// return 1;
}
}
pub trait QTabBar_tabsClosable<RetType> {
fn tabsClosable(self , rsthis: & QTabBar) -> RetType;
}
// proto: bool QTabBar::tabsClosable();
impl<'a> /*trait*/ QTabBar_tabsClosable<i8> for () {
fn tabsClosable(self , rsthis: & QTabBar) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK7QTabBar12tabsClosableEv()};
let mut ret = unsafe {C_ZNK7QTabBar12tabsClosableEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: void QTabBar::setMovable(bool movable);
impl /*struct*/ QTabBar {
pub fn setMovable<RetType, T: QTabBar_setMovable<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setMovable(self);
// return 1;
}
}
pub trait QTabBar_setMovable<RetType> {
fn setMovable(self , rsthis: & QTabBar) -> RetType;
}
// proto: void QTabBar::setMovable(bool movable);
impl<'a> /*trait*/ QTabBar_setMovable<()> for (i8) {
fn setMovable(self , rsthis: & QTabBar) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN7QTabBar10setMovableEb()};
let arg0 = self as c_char;
unsafe {C_ZN7QTabBar10setMovableEb(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QTabBar::setAutoHide(bool hide);
impl /*struct*/ QTabBar {
pub fn setAutoHide<RetType, T: QTabBar_setAutoHide<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setAutoHide(self);
// return 1;
}
}
pub trait QTabBar_setAutoHide<RetType> {
fn setAutoHide(self , rsthis: & QTabBar) -> RetType;
}
// proto: void QTabBar::setAutoHide(bool hide);
impl<'a> /*trait*/ QTabBar_setAutoHide<()> for (i8) {
fn setAutoHide(self , rsthis: & QTabBar) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN7QTabBar11setAutoHideEb()};
let arg0 = self as c_char;
unsafe {C_ZN7QTabBar11setAutoHideEb(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: QSize QTabBar::iconSize();
impl /*struct*/ QTabBar {
pub fn iconSize<RetType, T: QTabBar_iconSize<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.iconSize(self);
// return 1;
}
}
pub trait QTabBar_iconSize<RetType> {
fn iconSize(self , rsthis: & QTabBar) -> RetType;
}
// proto: QSize QTabBar::iconSize();
impl<'a> /*trait*/ QTabBar_iconSize<QSize> for () {
fn iconSize(self , rsthis: & QTabBar) -> QSize {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK7QTabBar8iconSizeEv()};
let mut ret = unsafe {C_ZNK7QTabBar8iconSizeEv(rsthis.qclsinst)};
let mut ret1 = QSize::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QString QTabBar::tabText(int index);
impl /*struct*/ QTabBar {
pub fn tabText<RetType, T: QTabBar_tabText<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.tabText(self);
// return 1;
}
}
pub trait QTabBar_tabText<RetType> {
fn tabText(self , rsthis: & QTabBar) -> RetType;
}
// proto: QString QTabBar::tabText(int index);
impl<'a> /*trait*/ QTabBar_tabText<QString> for (i32) {
fn tabText(self , rsthis: & QTabBar) -> QString {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK7QTabBar7tabTextEi()};
let arg0 = self as c_int;
let mut ret = unsafe {C_ZNK7QTabBar7tabTextEi(rsthis.qclsinst, arg0)};
let mut ret1 = QString::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QString QTabBar::tabWhatsThis(int index);
impl /*struct*/ QTabBar {
pub fn tabWhatsThis<RetType, T: QTabBar_tabWhatsThis<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.tabWhatsThis(self);
// return 1;
}
}
pub trait QTabBar_tabWhatsThis<RetType> {
fn tabWhatsThis(self , rsthis: & QTabBar) -> RetType;
}
// proto: QString QTabBar::tabWhatsThis(int index);
impl<'a> /*trait*/ QTabBar_tabWhatsThis<QString> for (i32) {
fn tabWhatsThis(self , rsthis: & QTabBar) -> QString {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK7QTabBar12tabWhatsThisEi()};
let arg0 = self as c_int;
let mut ret = unsafe {C_ZNK7QTabBar12tabWhatsThisEi(rsthis.qclsinst, arg0)};
let mut ret1 = QString::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: bool QTabBar::documentMode();
impl /*struct*/ QTabBar {
pub fn documentMode<RetType, T: QTabBar_documentMode<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.documentMode(self);
// return 1;
}
}
pub trait QTabBar_documentMode<RetType> {
fn documentMode(self , rsthis: & QTabBar) -> RetType;
}
// proto: bool QTabBar::documentMode();
impl<'a> /*trait*/ QTabBar_documentMode<i8> for () {
fn documentMode(self , rsthis: & QTabBar) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK7QTabBar12documentModeEv()};
let mut ret = unsafe {C_ZNK7QTabBar12documentModeEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: int QTabBar::tabAt(const QPoint & pos);
impl /*struct*/ QTabBar {
pub fn tabAt<RetType, T: QTabBar_tabAt<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.tabAt(self);
// return 1;
}
}
pub trait QTabBar_tabAt<RetType> {
fn tabAt(self , rsthis: & QTabBar) -> RetType;
}
// proto: int QTabBar::tabAt(const QPoint & pos);
impl<'a> /*trait*/ QTabBar_tabAt<i32> for (&'a QPoint) {
fn tabAt(self , rsthis: & QTabBar) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK7QTabBar5tabAtERK6QPoint()};
let arg0 = self.qclsinst as *mut c_void;
let mut ret = unsafe {C_ZNK7QTabBar5tabAtERK6QPoint(rsthis.qclsinst, arg0)};
return ret as i32; // 1
// return 1;
}
}
// proto: void QTabBar::setTabData(int index, const QVariant & data);
impl /*struct*/ QTabBar {
pub fn setTabData<RetType, T: QTabBar_setTabData<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setTabData(self);
// return 1;
}
}
pub trait QTabBar_setTabData<RetType> {
fn setTabData(self , rsthis: & QTabBar) -> RetType;
}
// proto: void QTabBar::setTabData(int index, const QVariant & data);
impl<'a> /*trait*/ QTabBar_setTabData<()> for (i32, &'a QVariant) {
fn setTabData(self , rsthis: & QTabBar) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN7QTabBar10setTabDataEiRK8QVariant()};
let arg0 = self.0 as c_int;
let arg1 = self.1.qclsinst as *mut c_void;
unsafe {C_ZN7QTabBar10setTabDataEiRK8QVariant(rsthis.qclsinst, arg0, arg1)};
// return 1;
}
}
// proto: void QTabBar::QTabBar(QWidget * parent);
impl /*struct*/ QTabBar {
pub fn new<T: QTabBar_new>(value: T) -> QTabBar {
let rsthis = value.new();
return rsthis;
// return 1;
}
}
pub trait QTabBar_new {
fn new(self) -> QTabBar;
}
// proto: void QTabBar::QTabBar(QWidget * parent);
impl<'a> /*trait*/ QTabBar_new for (Option<&'a QWidget>) {
fn new(self) -> QTabBar {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN7QTabBarC2EP7QWidget()};
let ctysz: c_int = unsafe{QTabBar_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let arg0 = (if self.is_none() {0} else {self.unwrap().qclsinst}) as *mut c_void;
let qthis: u64 = unsafe {C_ZN7QTabBarC2EP7QWidget(arg0)};
let rsthis = QTabBar{qbase: QWidget::inheritFrom(qthis), qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: QColor QTabBar::tabTextColor(int index);
impl /*struct*/ QTabBar {
pub fn tabTextColor<RetType, T: QTabBar_tabTextColor<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.tabTextColor(self);
// return 1;
}
}
pub trait QTabBar_tabTextColor<RetType> {
fn tabTextColor(self , rsthis: & QTabBar) -> RetType;
}
// proto: QColor QTabBar::tabTextColor(int index);
impl<'a> /*trait*/ QTabBar_tabTextColor<QColor> for (i32) {
fn tabTextColor(self , rsthis: & QTabBar) -> QColor {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK7QTabBar12tabTextColorEi()};
let arg0 = self as c_int;
let mut ret = unsafe {C_ZNK7QTabBar12tabTextColorEi(rsthis.qclsinst, arg0)};
let mut ret1 = QColor::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QTabBar::~QTabBar();
impl /*struct*/ QTabBar {
pub fn free<RetType, T: QTabBar_free<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.free(self);
// return 1;
}
}
pub trait QTabBar_free<RetType> {
fn free(self , rsthis: & QTabBar) -> RetType;
}
// proto: void QTabBar::~QTabBar();
impl<'a> /*trait*/ QTabBar_free<()> for () {
fn free(self , rsthis: & QTabBar) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN7QTabBarD2Ev()};
unsafe {C_ZN7QTabBarD2Ev(rsthis.qclsinst)};
// return 1;
}
}
// proto: int QTabBar::insertTab(int index, const QString & text);
impl<'a> /*trait*/ QTabBar_insertTab<i32> for (i32, &'a QString) {
fn insertTab(self , rsthis: & QTabBar) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN7QTabBar9insertTabEiRK7QString()};
let arg0 = self.0 as c_int;
let arg1 = self.1.qclsinst as *mut c_void;
let mut ret = unsafe {C_ZN7QTabBar9insertTabEiRK7QString(rsthis.qclsinst, arg0, arg1)};
return ret as i32; // 1
// return 1;
}
}
// proto: int QTabBar::addTab(const QString & text);
impl /*struct*/ QTabBar {
pub fn addTab<RetType, T: QTabBar_addTab<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.addTab(self);
// return 1;
}
}
pub trait QTabBar_addTab<RetType> {
fn addTab(self , rsthis: & QTabBar) -> RetType;
}
// proto: int QTabBar::addTab(const QString & text);
impl<'a> /*trait*/ QTabBar_addTab<i32> for (&'a QString) {
fn addTab(self , rsthis: & QTabBar) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN7QTabBar6addTabERK7QString()};
let arg0 = self.qclsinst as *mut c_void;
let mut ret = unsafe {C_ZN7QTabBar6addTabERK7QString(rsthis.qclsinst, arg0)};
return ret as i32; // 1
// return 1;
}
}
// proto: int QTabBar::addTab(const QIcon & icon, const QString & text);
impl<'a> /*trait*/ QTabBar_addTab<i32> for (&'a QIcon, &'a QString) {
fn addTab(self , rsthis: & QTabBar) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN7QTabBar6addTabERK5QIconRK7QString()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.qclsinst as *mut c_void;
let mut ret = unsafe {C_ZN7QTabBar6addTabERK5QIconRK7QString(rsthis.qclsinst, arg0, arg1)};
return ret as i32; // 1
// return 1;
}
}
// proto: void QTabBar::setTabToolTip(int index, const QString & tip);
impl /*struct*/ QTabBar {
pub fn setTabToolTip<RetType, T: QTabBar_setTabToolTip<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setTabToolTip(self);
// return 1;
}
}
pub trait QTabBar_setTabToolTip<RetType> {
fn setTabToolTip(self , rsthis: & QTabBar) -> RetType;
}
// proto: void QTabBar::setTabToolTip(int index, const QString & tip);
impl<'a> /*trait*/ QTabBar_setTabToolTip<()> for (i32, &'a QString) {
fn setTabToolTip(self , rsthis: & QTabBar) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN7QTabBar13setTabToolTipEiRK7QString()};
let arg0 = self.0 as c_int;
let arg1 = self.1.qclsinst as *mut c_void;
unsafe {C_ZN7QTabBar13setTabToolTipEiRK7QString(rsthis.qclsinst, arg0, arg1)};
// return 1;
}
}
// proto: void QTabBar::setTabTextColor(int index, const QColor & color);
impl /*struct*/ QTabBar {
pub fn setTabTextColor<RetType, T: QTabBar_setTabTextColor<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setTabTextColor(self);
// return 1;
}
}
pub trait QTabBar_setTabTextColor<RetType> {
fn setTabTextColor(self , rsthis: & QTabBar) -> RetType;
}
// proto: void QTabBar::setTabTextColor(int index, const QColor & color);
impl<'a> /*trait*/ QTabBar_setTabTextColor<()> for (i32, &'a QColor) {
fn setTabTextColor(self , rsthis: & QTabBar) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN7QTabBar15setTabTextColorEiRK6QColor()};
let arg0 = self.0 as c_int;
let arg1 = self.1.qclsinst as *mut c_void;
unsafe {C_ZN7QTabBar15setTabTextColorEiRK6QColor(rsthis.qclsinst, arg0, arg1)};
// return 1;
}
}
// proto: void QTabBar::moveTab(int from, int to);
impl /*struct*/ QTabBar {
pub fn moveTab<RetType, T: QTabBar_moveTab<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.moveTab(self);
// return 1;
}
}
pub trait QTabBar_moveTab<RetType> {
fn moveTab(self , rsthis: & QTabBar) -> RetType;
}
// proto: void QTabBar::moveTab(int from, int to);
impl<'a> /*trait*/ QTabBar_moveTab<()> for (i32, i32) {
fn moveTab(self , rsthis: & QTabBar) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN7QTabBar7moveTabEii()};
let arg0 = self.0 as c_int;
let arg1 = self.1 as c_int;
unsafe {C_ZN7QTabBar7moveTabEii(rsthis.qclsinst, arg0, arg1)};
// return 1;
}
}
// proto: QVariant QTabBar::tabData(int index);
impl /*struct*/ QTabBar {
pub fn tabData<RetType, T: QTabBar_tabData<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.tabData(self);
// return 1;
}
}
pub trait QTabBar_tabData<RetType> {
fn tabData(self , rsthis: & QTabBar) -> RetType;
}
// proto: QVariant QTabBar::tabData(int index);
impl<'a> /*trait*/ QTabBar_tabData<QVariant> for (i32) {
fn tabData(self , rsthis: & QTabBar) -> QVariant {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK7QTabBar7tabDataEi()};
let arg0 = self as c_int;
let mut ret = unsafe {C_ZNK7QTabBar7tabDataEi(rsthis.qclsinst, arg0)};
let mut ret1 = QVariant::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: bool QTabBar::drawBase();
impl /*struct*/ QTabBar {
pub fn drawBase<RetType, T: QTabBar_drawBase<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.drawBase(self);
// return 1;
}
}
pub trait QTabBar_drawBase<RetType> {
fn drawBase(self , rsthis: & QTabBar) -> RetType;
}
// proto: bool QTabBar::drawBase();
impl<'a> /*trait*/ QTabBar_drawBase<i8> for () {
fn drawBase(self , rsthis: & QTabBar) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK7QTabBar8drawBaseEv()};
let mut ret = unsafe {C_ZNK7QTabBar8drawBaseEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: int QTabBar::currentIndex();
impl /*struct*/ QTabBar {
pub fn currentIndex<RetType, T: QTabBar_currentIndex<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.currentIndex(self);
// return 1;
}
}
pub trait QTabBar_currentIndex<RetType> {
fn currentIndex(self , rsthis: & QTabBar) -> RetType;
}
// proto: int QTabBar::currentIndex();
impl<'a> /*trait*/ QTabBar_currentIndex<i32> for () {
fn currentIndex(self , rsthis: & QTabBar) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK7QTabBar12currentIndexEv()};
let mut ret = unsafe {C_ZNK7QTabBar12currentIndexEv(rsthis.qclsinst)};
return ret as i32; // 1
// return 1;
}
}
// proto: void QTabBar::setDrawBase(bool drawTheBase);
impl /*struct*/ QTabBar {
pub fn setDrawBase<RetType, T: QTabBar_setDrawBase<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setDrawBase(self);
// return 1;
}
}
pub trait QTabBar_setDrawBase<RetType> {
fn setDrawBase(self , rsthis: & QTabBar) -> RetType;
}
// proto: void QTabBar::setDrawBase(bool drawTheBase);
impl<'a> /*trait*/ QTabBar_setDrawBase<()> for (i8) {
fn setDrawBase(self , rsthis: & QTabBar) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN7QTabBar11setDrawBaseEb()};
let arg0 = self as c_char;
unsafe {C_ZN7QTabBar11setDrawBaseEb(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QTabBar::setUsesScrollButtons(bool useButtons);
impl /*struct*/ QTabBar {
pub fn setUsesScrollButtons<RetType, T: QTabBar_setUsesScrollButtons<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setUsesScrollButtons(self);
// return 1;
}
}
pub trait QTabBar_setUsesScrollButtons<RetType> {
fn setUsesScrollButtons(self , rsthis: & QTabBar) -> RetType;
}
// proto: void QTabBar::setUsesScrollButtons(bool useButtons);
impl<'a> /*trait*/ QTabBar_setUsesScrollButtons<()> for (i8) {
fn setUsesScrollButtons(self , rsthis: & QTabBar) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN7QTabBar20setUsesScrollButtonsEb()};
let arg0 = self as c_char;
unsafe {C_ZN7QTabBar20setUsesScrollButtonsEb(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: QSize QTabBar::sizeHint();
impl /*struct*/ QTabBar {
pub fn sizeHint<RetType, T: QTabBar_sizeHint<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.sizeHint(self);
// return 1;
}
}
pub trait QTabBar_sizeHint<RetType> {
fn sizeHint(self , rsthis: & QTabBar) -> RetType;
}
// proto: QSize QTabBar::sizeHint();
impl<'a> /*trait*/ QTabBar_sizeHint<QSize> for () {
fn sizeHint(self , rsthis: & QTabBar) -> QSize {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK7QTabBar8sizeHintEv()};
let mut ret = unsafe {C_ZNK7QTabBar8sizeHintEv(rsthis.qclsinst)};
let mut ret1 = QSize::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QTabBar::setIconSize(const QSize & size);
impl /*struct*/ QTabBar {
pub fn setIconSize<RetType, T: QTabBar_setIconSize<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setIconSize(self);
// return 1;
}
}
pub trait QTabBar_setIconSize<RetType> {
fn setIconSize(self , rsthis: & QTabBar) -> RetType;
}
// proto: void QTabBar::setIconSize(const QSize & size);
impl<'a> /*trait*/ QTabBar_setIconSize<()> for (&'a QSize) {
fn setIconSize(self , rsthis: & QTabBar) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN7QTabBar11setIconSizeERK5QSize()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN7QTabBar11setIconSizeERK5QSize(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QTabBar::setTabText(int index, const QString & text);
impl /*struct*/ QTabBar {
pub fn setTabText<RetType, T: QTabBar_setTabText<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setTabText(self);
// return 1;
}
}
pub trait QTabBar_setTabText<RetType> {
fn setTabText(self , rsthis: & QTabBar) -> RetType;
}
// proto: void QTabBar::setTabText(int index, const QString & text);
impl<'a> /*trait*/ QTabBar_setTabText<()> for (i32, &'a QString) {
fn setTabText(self , rsthis: & QTabBar) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN7QTabBar10setTabTextEiRK7QString()};
let arg0 = self.0 as c_int;
let arg1 = self.1.qclsinst as *mut c_void;
unsafe {C_ZN7QTabBar10setTabTextEiRK7QString(rsthis.qclsinst, arg0, arg1)};
// return 1;
}
}
#[derive(Default)] // for QTabBar_tabCloseRequested
pub struct QTabBar_tabCloseRequested_signal{poi:u64}
impl /* struct */ QTabBar {
pub fn tabCloseRequested(&self) -> QTabBar_tabCloseRequested_signal {
return QTabBar_tabCloseRequested_signal{poi:self.qclsinst};
}
}
impl /* struct */ QTabBar_tabCloseRequested_signal {
pub fn connect<T: QTabBar_tabCloseRequested_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QTabBar_tabCloseRequested_signal_connect {
fn connect(self, sigthis: QTabBar_tabCloseRequested_signal);
}
#[derive(Default)] // for QTabBar_tabBarDoubleClicked
pub struct QTabBar_tabBarDoubleClicked_signal{poi:u64}
impl /* struct */ QTabBar {
pub fn tabBarDoubleClicked(&self) -> QTabBar_tabBarDoubleClicked_signal {
return QTabBar_tabBarDoubleClicked_signal{poi:self.qclsinst};
}
}
impl /* struct */ QTabBar_tabBarDoubleClicked_signal {
pub fn connect<T: QTabBar_tabBarDoubleClicked_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QTabBar_tabBarDoubleClicked_signal_connect {
fn connect(self, sigthis: QTabBar_tabBarDoubleClicked_signal);
}
#[derive(Default)] // for QTabBar_tabMoved
pub struct QTabBar_tabMoved_signal{poi:u64}
impl /* struct */ QTabBar {
pub fn tabMoved(&self) -> QTabBar_tabMoved_signal {
return QTabBar_tabMoved_signal{poi:self.qclsinst};
}
}
impl /* struct */ QTabBar_tabMoved_signal {
pub fn connect<T: QTabBar_tabMoved_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QTabBar_tabMoved_signal_connect {
fn connect(self, sigthis: QTabBar_tabMoved_signal);
}
#[derive(Default)] // for QTabBar_tabBarClicked
pub struct QTabBar_tabBarClicked_signal{poi:u64}
impl /* struct */ QTabBar {
pub fn tabBarClicked(&self) -> QTabBar_tabBarClicked_signal {
return QTabBar_tabBarClicked_signal{poi:self.qclsinst};
}
}
impl /* struct */ QTabBar_tabBarClicked_signal {
pub fn connect<T: QTabBar_tabBarClicked_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QTabBar_tabBarClicked_signal_connect {
fn connect(self, sigthis: QTabBar_tabBarClicked_signal);
}
#[derive(Default)] // for QTabBar_currentChanged
pub struct QTabBar_currentChanged_signal{poi:u64}
impl /* struct */ QTabBar {
pub fn currentChanged(&self) -> QTabBar_currentChanged_signal {
return QTabBar_currentChanged_signal{poi:self.qclsinst};
}
}
impl /* struct */ QTabBar_currentChanged_signal {
pub fn connect<T: QTabBar_currentChanged_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QTabBar_currentChanged_signal_connect {
fn connect(self, sigthis: QTabBar_currentChanged_signal);
}
// tabBarClicked(int)
extern fn QTabBar_tabBarClicked_signal_connect_cb_0(rsfptr:fn(i32), arg0: c_int) {
println!("{}:{}", file!(), line!());
let rsarg0 = arg0 as i32;
rsfptr(rsarg0);
}
extern fn QTabBar_tabBarClicked_signal_connect_cb_box_0(rsfptr_raw:*mut Box<Fn(i32)>, arg0: c_int) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
let rsarg0 = arg0 as i32;
// rsfptr(rsarg0);
unsafe{(*rsfptr_raw)(rsarg0)};
}
impl /* trait */ QTabBar_tabBarClicked_signal_connect for fn(i32) {
fn connect(self, sigthis: QTabBar_tabBarClicked_signal) {
// do smth...
// self as u64; // error for Fn, Ok for fn
self as *mut c_void as u64;
self as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QTabBar_tabBarClicked_signal_connect_cb_0 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QTabBar_SlotProxy_connect__ZN7QTabBar13tabBarClickedEi(arg0, arg1, arg2)};
}
}
impl /* trait */ QTabBar_tabBarClicked_signal_connect for Box<Fn(i32)> {
fn connect(self, sigthis: QTabBar_tabBarClicked_signal) {
// do smth...
// Box::into_raw(self) as u64;
// Box::into_raw(self) as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QTabBar_tabBarClicked_signal_connect_cb_box_0 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QTabBar_SlotProxy_connect__ZN7QTabBar13tabBarClickedEi(arg0, arg1, arg2)};
}
}
// tabBarDoubleClicked(int)
extern fn QTabBar_tabBarDoubleClicked_signal_connect_cb_1(rsfptr:fn(i32), arg0: c_int) {
println!("{}:{}", file!(), line!());
let rsarg0 = arg0 as i32;
rsfptr(rsarg0);
}
extern fn QTabBar_tabBarDoubleClicked_signal_connect_cb_box_1(rsfptr_raw:*mut Box<Fn(i32)>, arg0: c_int) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
let rsarg0 = arg0 as i32;
// rsfptr(rsarg0);
unsafe{(*rsfptr_raw)(rsarg0)};
}
impl /* trait */ QTabBar_tabBarDoubleClicked_signal_connect for fn(i32) {
fn connect(self, sigthis: QTabBar_tabBarDoubleClicked_signal) {
// do smth...
// self as u64; // error for Fn, Ok for fn
self as *mut c_void as u64;
self as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QTabBar_tabBarDoubleClicked_signal_connect_cb_1 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QTabBar_SlotProxy_connect__ZN7QTabBar19tabBarDoubleClickedEi(arg0, arg1, arg2)};
}
}
impl /* trait */ QTabBar_tabBarDoubleClicked_signal_connect for Box<Fn(i32)> {
fn connect(self, sigthis: QTabBar_tabBarDoubleClicked_signal) {
// do smth...
// Box::into_raw(self) as u64;
// Box::into_raw(self) as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QTabBar_tabBarDoubleClicked_signal_connect_cb_box_1 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QTabBar_SlotProxy_connect__ZN7QTabBar19tabBarDoubleClickedEi(arg0, arg1, arg2)};
}
}
// tabCloseRequested(int)
extern fn QTabBar_tabCloseRequested_signal_connect_cb_2(rsfptr:fn(i32), arg0: c_int) {
println!("{}:{}", file!(), line!());
let rsarg0 = arg0 as i32;
rsfptr(rsarg0);
}
extern fn QTabBar_tabCloseRequested_signal_connect_cb_box_2(rsfptr_raw:*mut Box<Fn(i32)>, arg0: c_int) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
let rsarg0 = arg0 as i32;
// rsfptr(rsarg0);
unsafe{(*rsfptr_raw)(rsarg0)};
}
impl /* trait */ QTabBar_tabCloseRequested_signal_connect for fn(i32) {
fn connect(self, sigthis: QTabBar_tabCloseRequested_signal) {
// do smth...
// self as u64; // error for Fn, Ok for fn
self as *mut c_void as u64;
self as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QTabBar_tabCloseRequested_signal_connect_cb_2 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QTabBar_SlotProxy_connect__ZN7QTabBar17tabCloseRequestedEi(arg0, arg1, arg2)};
}
}
impl /* trait */ QTabBar_tabCloseRequested_signal_connect for Box<Fn(i32)> {
fn connect(self, sigthis: QTabBar_tabCloseRequested_signal) {
// do smth...
// Box::into_raw(self) as u64;
// Box::into_raw(self) as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QTabBar_tabCloseRequested_signal_connect_cb_box_2 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QTabBar_SlotProxy_connect__ZN7QTabBar17tabCloseRequestedEi(arg0, arg1, arg2)};
}
}
// tabMoved(int, int)
extern fn QTabBar_tabMoved_signal_connect_cb_3(rsfptr:fn(i32, i32), arg0: c_int, arg1: c_int) {
println!("{}:{}", file!(), line!());
let rsarg0 = arg0 as i32;
let rsarg1 = arg1 as i32;
rsfptr(rsarg0,rsarg1);
}
extern fn QTabBar_tabMoved_signal_connect_cb_box_3(rsfptr_raw:*mut Box<Fn(i32, i32)>, arg0: c_int, arg1: c_int) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
let rsarg0 = arg0 as i32;
let rsarg1 = arg1 as i32;
// rsfptr(rsarg0,rsarg1);
unsafe{(*rsfptr_raw)(rsarg0,rsarg1)};
}
impl /* trait */ QTabBar_tabMoved_signal_connect for fn(i32, i32) {
fn connect(self, sigthis: QTabBar_tabMoved_signal) {
// do smth...
// self as u64; // error for Fn, Ok for fn
self as *mut c_void as u64;
self as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QTabBar_tabMoved_signal_connect_cb_3 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QTabBar_SlotProxy_connect__ZN7QTabBar8tabMovedEii(arg0, arg1, arg2)};
}
}
impl /* trait */ QTabBar_tabMoved_signal_connect for Box<Fn(i32, i32)> {
fn connect(self, sigthis: QTabBar_tabMoved_signal) {
// do smth...
// Box::into_raw(self) as u64;
// Box::into_raw(self) as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QTabBar_tabMoved_signal_connect_cb_box_3 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QTabBar_SlotProxy_connect__ZN7QTabBar8tabMovedEii(arg0, arg1, arg2)};
}
}
// currentChanged(int)
extern fn QTabBar_currentChanged_signal_connect_cb_4(rsfptr:fn(i32), arg0: c_int) {
println!("{}:{}", file!(), line!());
let rsarg0 = arg0 as i32;
rsfptr(rsarg0);
}
extern fn QTabBar_currentChanged_signal_connect_cb_box_4(rsfptr_raw:*mut Box<Fn(i32)>, arg0: c_int) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
let rsarg0 = arg0 as i32;
// rsfptr(rsarg0);
unsafe{(*rsfptr_raw)(rsarg0)};
}
impl /* trait */ QTabBar_currentChanged_signal_connect for fn(i32) {
fn connect(self, sigthis: QTabBar_currentChanged_signal) {
// do smth...
// self as u64; // error for Fn, Ok for fn
self as *mut c_void as u64;
self as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QTabBar_currentChanged_signal_connect_cb_4 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QTabBar_SlotProxy_connect__ZN7QTabBar14currentChangedEi(arg0, arg1, arg2)};
}
}
impl /* trait */ QTabBar_currentChanged_signal_connect for Box<Fn(i32)> {
fn connect(self, sigthis: QTabBar_currentChanged_signal) {
// do smth...
// Box::into_raw(self) as u64;
// Box::into_raw(self) as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QTabBar_currentChanged_signal_connect_cb_box_4 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QTabBar_SlotProxy_connect__ZN7QTabBar14currentChangedEi(arg0, arg1, arg2)};
}
}
// <= body block end
|
pub mod cpu;
pub mod gui;
pub mod ines;
pub mod png;
pub mod ppu;
mod apu;
mod gamepad;
mod kevtris;
mod mapper;
mod record;
|
use crate::types::*;
use neo4rs_macros::BoltStruct;
#[derive(Debug, PartialEq, Clone, BoltStruct)]
#[signature(0xB1, 0x7F)]
pub struct Failure {
metadata: BoltMap,
}
impl Failure {
pub fn get<T: std::convert::TryFrom<BoltType>>(&self, key: &str) -> Option<T> {
self.metadata.get(key)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::version::Version;
use bytes::*;
use std::cell::RefCell;
use std::rc::Rc;
#[test]
fn should_deserialize_success() {
let data = Bytes::from_static(&[
0xB1, 0x7F, 0xA2, 0x84, 0x63, 0x6F, 0x64, 0x65, 0xD0, 0x25, 0x4E, 0x65, 0x6F, 0x2E,
0x43, 0x6C, 0x69, 0x65, 0x6E, 0x74, 0x45, 0x72, 0x72, 0x6F, 0x72, 0x2E, 0x53, 0x65,
0x63, 0x75, 0x72, 0x69, 0x74, 0x79, 0x2E, 0x55, 0x6E, 0x61, 0x75, 0x74, 0x68, 0x6F,
0x72, 0x69, 0x7A, 0x65, 0x64, 0x87, 0x6D, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0xD0,
0x39, 0x54, 0x68, 0x65, 0x20, 0x63, 0x6C, 0x69, 0x65, 0x6E, 0x74, 0x20, 0x69, 0x73,
0x20, 0x75, 0x6E, 0x61, 0x75, 0x74, 0x68, 0x6F, 0x72, 0x69, 0x7A, 0x65, 0x64, 0x20,
0x64, 0x75, 0x65, 0x20, 0x74, 0x6F, 0x20, 0x61, 0x75, 0x74, 0x68, 0x65, 0x6E, 0x74,
0x69, 0x63, 0x61, 0x74, 0x69, 0x6F, 0x6E, 0x20, 0x66, 0x61, 0x69, 0x6C, 0x75, 0x72,
0x65, 0x2E,
]);
let failure: Failure = Failure::parse(Version::V4_1, Rc::new(RefCell::new(data))).unwrap();
assert_eq!(
failure.get::<String>("code").unwrap(),
"Neo.ClientError.Security.Unauthorized"
);
assert_eq!(
failure.get::<String>("message").unwrap(),
"The client is unauthorized due to authentication failure."
);
}
}
|
pub fn nth(n: u32) -> u32 {
let mut primes = Vec::new();
let mut num = 2;
while primes.len() <= n as usize {
if is_prime(num, &primes) {
primes.push(num)
}
num += 1
}
primes.pop().unwrap()
}
fn is_prime(n: u32, primes: &[u32]) -> bool {
for i in primes {
if n % i == 0 {
return false;
}
}
true
}
|
/**
* Copyright © 2019
* Sami Shalayel <sami.shalayel@tutamail.com>,
* Carl Schwan <carl@carlschwan.eu>,
* Daniel Freiermuth <d_freiermu14@cs.uni-kl.de>
*
* This work is free. You can redistribute it and/or modify it under the
* terms of the Do What The Fuck You Want To Public License, Version 2,
* as published by Sam Hocevar. See the LICENSE file for more details.
*
* This program is free software. It comes without any warranty, to
* the extent permitted by applicable law. You can redistribute it
* and/or modify it under the terms of the Do What The Fuck You Want
* To Public License, Version 2, as published by Sam Hocevar. See the LICENSE
* file for more details. **/
use crate::shader::Shader;
use crate::world::World;
use image::Rgba;
use na::{Vector2, Vector3};
pub struct Intersection<'a> {
pub pos: Vector3<f64>,
pub normal_at_surface: Vector3<f64>,
pub pos_on_surface: Vector2<f64>,
pub shader: &'a Box<Shader>,
}
impl<'a> Intersection<'a> {
pub fn get_color(
&self,
ray_dir: Vector3<f64>,
world: &World,
recursion_depth: f64,
) -> Rgba<u8> {
self.shader.get_color_for(
self.pos,
ray_dir,
self.normal_at_surface,
world,
self.pos_on_surface,
recursion_depth,
)
}
pub fn get_appearance(
&self,
ray_dir: Vector3<f64>,
world: &World,
recursion_depth: f64,
) -> Vector3<f64> {
self.shader.get_appearance_for(
self.pos,
ray_dir,
self.normal_at_surface,
world,
self.pos_on_surface,
recursion_depth,
)
}
}
|
fn main() {
#macro([#trivial[], 1*2*4*2*1]);
assert(#trivial[] == 16);
}
|
//extern crate token;
#[test]
fn it_adds_two() {
assert_eq!(4, 4);
}
|
type Kilometers = i32;
fn main() {
let x: i32 = 5;
let y: Kilometers = 5;
println!("x + y = {}", x + y);
let _bs: Box<dyn std::fmt::Display> = Box::new(String::from("there"));
}
type Thunk = Box<dyn Fn() + Send + 'static>;
fn takes_long_type(f: Thunk) {
()
}
fn returns_long_type() -> Thunk {
Box::new(|| ())
}
fn x() -> ! { // the function x , returns never
loop {
println!("forecer");
}
}
fn check_guess(guess: &str) -> u32 {
match guess.trim().parse() {
Ok(num) => num,
Err(_) => panic!("Something wrong") // panic! has ! return so guess can be safely u32
}
}
fn dont_call() -> ! {
panic!("Why!?")
}
// Dynamically sized types adn Sized trait
fn dynamic_types() {
// let string: str = "Hello "; // Size of these types cannot be fixed
// let string: str = "Hello there";
// let slice: [i32] = [1, 2];
// All traits are dynamically sized types, so they similar to str and [T] can only exist as part of a pointer
let s: &dyn std::fmt::Display = &String::from("Hello");
// or
let bs: Box<dyn std::fmt::Display> = Box::new(String::from("there"));
}
fn generic_1<T>(t: T) {
}
// generic_1 and generic_2 are same, compiler adds Sized
fn generic_2<T: Sized>(t: T) {
}
// To use generics with dynamically sized types, you have to use T: ?Sized
// Special syntax only applicable to Sized trait and it reads -
// "T may or may not be Sized"
fn generic_3<T: ?Sized>(t: &T) { // But then type of t, can no longer be T, here we used a reference
} |
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
//
#![warn(missing_docs)]
//! # glTFVariantMeld
//!
//! ### Introduction
//!
//! This library exists to do one single thing: meld multiple glTF assets, each representing a
//! different *variant* of some basic model, into a single, compact format, implemented as a formal
//! glTF extension.
//!
//! For a practical canonical use case, take the common case of a retail product that's available in
//! a range of colours, and an application that lets a prospective customer switch between these
//! different variants without latency or stutters.
//!
//! We're making this internal tool publicly available with the hope of bringing the ecosystem
//! together around a common, open format, the lingua franca of variational 3D assets. One day,
//! perhaps digital content creation tools will include ways to export variational assets natively.
//! Until that day, this is how we're doing it.
//!
//! In this prerelease version, the tool produces files with the Khronos extension
//! [`KHR_materials_variants`](https://github.com/zellski/glTF/blob/ext/zell-fb-asset-variants/extensions/2.0/Khronos/KHR_materials_variants/README.md).
//! We are hopeful that the glTF community will find speedy consensus around a fully
//! ratified extension, e.g. `KHR_material_variants`.
//!
//! At present, we offer a simple command line interface. Our aspirational roadmap includes the
//! development of a web app which would leverage WebAssembly to run entirely in the browser.
//!
//! ### Technical Requirements
//!
//! For assets to be meldable, they must be logically identical, i.e. contain the same meshes – and
//! vary only in what materials are assigned to those meshes. The tool will complain if it finds
//! disrepancies between the source assets that are too confusing for it to work around.
//!
//! During the melding process, all common data is shared, whereas varying material definitions and
//! textures are copied as needed. Parts of the assets that don't vary are left untouched.
//!
//! Each source asset brought into the tool is identified by a *tag*, a short string, and it's
//! these same tags that are later used to trigger different runtime apperances.
extern crate gltf;
extern crate serde;
extern crate serde_derive;
extern crate serde_json;
extern crate sha1;
extern crate spectral;
/// Tags are short identifiers used to switch between different mesh primitive materials.
pub type Tag = String;
/// Our library-wide error type is (as yet) a simple string.
pub type Error = String;
/// Convenience type for a Result using our Error.
pub type Result<T> = ::std::result::Result<T, crate::Error>;
/// The JSON/Serde implementation of `KHR_materials_variants`.
pub mod extension;
/// The VarationalAsset struct and associated functionality.
pub mod variational_asset;
pub use variational_asset::{AssetSizes, Metadata, VariationalAsset};
/// The internal workhorse WorkAsset struct & functionality.
pub mod work_asset;
pub use work_asset::WorkAsset;
pub mod glb;
pub use glb::GlbChunk;
pub mod gltfext;
pub use gltfext::*;
/// Mapping glTF objects to unique keys for melding purposes.
pub mod meld_keys;
pub use meld_keys::{Fingerprint, MeldKey};
|
use crate::error::GenericResult;
use crate::error::GenericError;
use crate::error::ErrorKind;
use super::map;
use super::state;
use std::convert::TryFrom;
use std::io::Write;
static UPDATE_RATES: f64 = 0.05;
/// Create or load the map
pub async fn get_map(conn: std::sync::Arc<aci::Connection>, options: &crate::args::Arguments) -> GenericResult<map::Map>
{
if !options.load_map
{
let map_data = map::generate_test_map();
if options.reload_map
{
info!("Creating JSON");
let json_data = serde_json::Value::from(&map_data);
info!("Clearing the map on the server");
let setter = tokio::spawn(async move {conn.set_value("gamedata", "map", json_data).await});
info!("Done Sending");
tokio::join!(setter).0.map_err(|_| GenericError::new("Map send handler failed".to_string(), ErrorKind::ConnectionError))??;
info!("Done Writing Map Data!");
}
Ok(map_data)
}
else
{
info!("Loading data from server");
let data = conn.get_value("gamedata", "map").await?;
debug!("Parsing data from server");
super::map::Map::try_from(data)
}
}
/// Dump the map to a file
fn dump_map(map: map::Map, path: &str) -> GenericResult<()>
{
debug!("Dumping map to `{}`", path);
let json_string = serde_json::Value::from(&map).to_string();
let mut output = std::fs::File::create(path).map_err(|e| GenericError::new(format!("Unable to open file `{}` {}", path, e), ErrorKind::EnvironmentError))?;
write!(output, "{}", json_string).map_err(|e| GenericError::new(format!("Unable to write to file `{}` {}", path, e), ErrorKind::EnvironmentError))?;
debug!("Done dumping map");
Ok(())
}
/// Execute the main portion of the game server
pub async fn execute(conn: std::sync::Arc<aci::Connection>, options: crate::args::Arguments, event_listener: tokio::sync::mpsc::Receiver<aci::event::ACIEvent>) -> GenericResult<()>
{
trace!("Starting server process");
// Retrieve the password from the environment variable
let password = std::env::var("GAME_SERVER_PASSWORD").map_err(
|_| GenericError::new("Unable to read server password from environment variable `GAME_SERVER_PASSWORD`".to_string(),
ErrorKind::EnvironmentError))?;
debug!("Using password `{}`", password);
// Attempt to authenticate with the server
if !conn.a_auth("bots.woc_2021", &password).await? // bots.woc_2021
{
return Err(GenericError::new("Authentication with ACI server failed".to_string(), ErrorKind::ConnectionError));
}
else
{
trace!("Authentication Successful");
}
// If the gamedata database has not been loaded, load it from disk
if !conn.list_databases().await?.contains(&"gamedata".to_string())
{
debug!("Database `gamedata` is not loaded; loading");
conn.read_from_disk("gamedata").await?;
}
// Load the map, either from the server, or generating the map here
let map = get_map(conn.clone(), &options).await?;
// Dump the updated map to a file
// dump_map(map, "map.json")?;
let mut game_state = state::GameState::new(conn, map, event_listener, options).await?;
let mut now = std::time::SystemTime::now();
let mut time_ellapsed = 0.0;
loop
{
// Get the delta time since the last tick
let dt = now.elapsed().map_err(|e| GenericError::new(format!("Unable to calulate dt: {}", e), ErrorKind::EnvironmentError))?.as_millis() as f64 / 1000.0;
now = std::time::SystemTime::now();
time_ellapsed += dt;
// If this tick has taken too long, add a warning
if dt > 0.25
{
warn!("A tick took {} milliseconds", dt * 1000.0);
}
// Make sure the loop isn't endlessly spinning
let timer = tokio::spawn(tokio::time::sleep(tokio::time::Duration::from_millis(1)));
// Update the game state
game_state.tick(dt).await?;
// If the right amount of time has ellapsed, send the processed data to the server
if time_ellapsed > UPDATE_RATES
{
time_ellapsed -= UPDATE_RATES;
game_state.send_to_server().await?;
}
// Wait for the timer to ellapse before moving onto the next tick
if let Err(e) = tokio::join!(timer).0
{
warn!("Unable to join timer: {}", e);
}
}
// Ok(())
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.